@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.
@@ -1,773 +0,0 @@
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
- * Counters for the integration: the socket's state, its closes and the
75
- * notices the SDK surfaces, and the wakes handed to the invoker. 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 | retry | 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 handed to the invoker (message frames, connects, server wake frames, the ladder's retries). */
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
- * Group invites: the second wake kind, and the ledger of invites already
164
- * offered to the agent.
165
- *
166
- * An invite is not on the tray and is not gated: the agent gets one turn
167
- * with the served invite prompt and decides for itself through the hosted
168
- * tools (accept, decline, or leave it pending). Invites arrive live
169
- * (`group.invite.received` frame) and are listed again on every connect
170
- * (`GET /v1/groups/invites`), so the same invite is seen many times over
171
- * the life of an account. The ledger remembers which invites were offered —
172
- * on disk, so a gateway restart never starts one more turn for an invite
173
- * the agent chose to leave pending. An invite whose turn could not start is
174
- * NOT marked offered: it stays pending in the invoker and is retried on the
175
- * next wake.
176
- */
177
- interface GroupInvite {
178
- readonly inviteId: string;
179
- readonly groupId: string;
180
- readonly groupName: string;
181
- /** Bare handle, `@` stripped; `''` when the frame carried none. */
182
- readonly inviterHandle: string;
183
- }
184
- /** From a `group.invite.received` frame payload or a `GET /v1/groups/invites` row. `null` when the ids are missing. */
185
- declare function groupInviteFromRecord(record: unknown): GroupInvite | null;
186
- interface InviteLedgerOptions {
187
- readonly accountId: string;
188
- readonly stateDir?: string | undefined;
189
- /** Explicit file (test seam). Defaults to `<plugin state dir>/invites.json`. */
190
- readonly file?: string;
191
- readonly now?: () => number;
192
- readonly maxAgeMs?: number;
193
- /** Called when a write fails; the in-memory ledger still holds the id. */
194
- readonly onWriteError?: (err: unknown) => void;
195
- }
196
- declare class InviteLedger {
197
- private readonly file;
198
- private readonly now;
199
- private readonly maxAgeMs;
200
- private readonly onWriteError;
201
- private offered;
202
- constructor(options: InviteLedgerOptions);
203
- get path(): string;
204
- get size(): number;
205
- /** True when a turn for this invite was started before (in this process or an earlier one). */
206
- isOffered(inviteId: string): boolean;
207
- /** Record that a turn for this invite was admitted. Persists at once. */
208
- markOffered(inviteId: string): void;
209
- private read;
210
- private prune;
211
- }
212
-
213
- /**
214
- * Where the integration meets OpenClaw's agent runtime.
215
- *
216
- * Two things only, both on the `PluginRuntime` OpenClaw hands a channel entry
217
- * through `defineChannelPluginEntry({ setRuntime })`:
218
- *
219
- * 1. **The gate call** — `runtime.llm.complete({ messages, maxTokens,
220
- * temperature, purpose })` runs one tool-free completion on the agent's
221
- * own configured model and credentials (`LlmCompleteParams`,
222
- * `plugin-sdk/types`; docs.openclaw.ai/plugins/sdk-runtime/models). The
223
- * prompt is the SDK's rendering of the server's question and cards
224
- * (`gate.buildPrompt`); nothing of ours is added. No tools are passed:
225
- * the gate is a triage, and the integration records the verdicts. Without
226
- * an `agentId` OpenClaw uses the ambient default agent; passing one is an
227
- * OVERRIDE that OpenClaw 2026.10.9 rejects with
228
- * `LLM_COMPLETION_NOT_AUTHORIZED` unless the operator set
229
- * `plugins.entries.agentchat.llm.allowAgentIdOverride: true`. The
230
- * integration therefore passes `agentId` only when the account is
231
- * genuinely routed to a non-default agent (`agentIdOverride`), and the
232
- * wizard / doctor write the opt-in in that case.
233
- *
234
- * 2. **The turn** — `runtime.subagent.run({ sessionKey, message, lane,
235
- * deliver: false })` admits one agent run with the prompt as its message
236
- * and no delivery of its final text (`SubagentRunParams`;
237
- * docs.openclaw.ai/plugins/sdk-runtime/background-work — the same shape
238
- * OpenClaw's own background features use with `deliver: false`). The
239
- * turn's output is never routed anywhere: the agent's only way to say
240
- * something on AgentChat is the hosted `agentchat__agentchat_send_message`
241
- * tool during the turn. Admission and completion are reported separately
242
- * (`TurnAdmission`): the invoker records the `reply` verdict the moment
243
- * the run is admitted, and `runtime.subagent.waitForRun` bounds how long
244
- * it waits before the next cycle may start; it never cancels the run.
245
- *
246
- * The agent id is resolved the way OpenClaw routes inbound for this channel
247
- * (`channelRuntime.routing.resolveAgentRoute`), so the integration wakes the
248
- * agent the operator bound to the account; `main` when nothing is bound.
249
- */
250
-
251
- interface TurnRequest {
252
- readonly sessionKey: string;
253
- readonly prompt: string;
254
- readonly lane: string;
255
- }
256
- interface TurnOutcome {
257
- readonly ran: boolean;
258
- readonly runId?: string;
259
- readonly status?: string;
260
- readonly error?: string;
261
- }
262
- /**
263
- * What starting a turn tells the invoker: refused (OpenClaw did not admit
264
- * the run — no runtime, a thrown `subagent.run`), or admitted with a bounded
265
- * promise of the outcome.
266
- */
267
- type TurnAdmission = {
268
- readonly ran: false;
269
- readonly error: string;
270
- } | {
271
- readonly ran: true;
272
- readonly runId: string;
273
- readonly done: Promise<TurnOutcome>;
274
- };
275
- /** Starts one agent turn. Injectable so the invoker is testable without OpenClaw. */
276
- type TurnStarter = (request: TurnRequest) => Promise<TurnAdmission>;
277
- /** Whether a turn started now can look at AgentChat at all; `reason` is the operator line when it cannot. */
278
- type TurnReadiness = {
279
- readonly ready: true;
280
- } | {
281
- readonly ready: false;
282
- readonly reason: string;
283
- };
284
-
285
- /**
286
- * Wake → gate → turn. The only path from the socket to the agent.
287
- *
288
- * What happens on a wake
289
- * ──────────────────────
290
- * 1. **Coalesce.** Frames inside a short window become one wake
291
- * (`WakeCoalescer`). A group waking up is one cycle, not twenty.
292
- * 2. **Read the tray.** `client.inbox.tray()` — the server's briefing cards
293
- * and its gate question, as it built them.
294
- * 3. **Gate.** The SDK's gate helper renders the question and the cards,
295
- * asks the agent's own model (`callModel`, a tool-free completion through
296
- * `runtime.llm.complete`) and records `dismiss` / `defer` with the card's
297
- * anchor. `reply` comes back as entries the invoker records itself.
298
- * 4. **Turn.** For every conversation decided `reply`, start ONE OpenClaw
299
- * agent turn (`runtime.subagent.run`, `deliver: false`) with the served
300
- * wake instruction and the conversation id. The `reply` verdict is
301
- * recorded when the run has COMPLETED (`status: ok`) — never at its
302
- * start: recorded at admission it marked the conversation read before
303
- * the turn's own inbox call, which then waited on an empty tray, and a
304
- * turn that crashed left the peer with a read receipt and no answer. A
305
- * completed turn counts as read even if it chose not to send — unless
306
- * the turn recorded a verdict for its conversation itself (the served
307
- * texts tell the model to record `reply` after its send, or `dismiss`
308
- * when it read and chose not to answer). One tray read after the run
309
- * shows that: the card left the tray (read, or hidden by a defer) or its
310
- * `your_last_decision` moved since the gate's tray. The host then
311
- * records nothing more, so the agent's own last verdict stands and a
312
- * reply is counted once. A failed read, or a card that may sit past a
313
- * truncated tray, records `reply` as before (reading is forward-only). A turn
314
- * OpenClaw refuses, or one that ends in error or on the wait timeout,
315
- * records nothing: the conversation stays unread, the card stays on the
316
- * tray, and the ladder re-wakes so it is gated again (one more gate
317
- * call, no silent drop). The turn's final text is discarded — nothing is
318
- * auto-routed anywhere.
319
- *
320
- * One cycle at a time per account: a wake that lands while a cycle runs is
321
- * remembered and runs once the cycle ends (the tray is re-read, so whatever
322
- * the earlier wake announced is covered). A cycle ends when its turns are
323
- * ADMITTED, not when they finish: OpenClaw serializes the turns on the
324
- * account's lane (`integrationLane`), so the next cycle's turn simply queues
325
- * behind, and holding the wake loop for up to 15 minutes per turn would only
326
- * delay the next tray read. Completion is logged as it happens. A cycle
327
- * that could not complete — model unreachable, server error, turn refused —
328
- * re-wakes itself on a local ladder (1 m, 5 m, 30 m) because a connected
329
- * socket gets no re-wake from the server; the cards wait on the tray
330
- * meanwhile. One outage climbs the ladder one rung: a retry already on its
331
- * way is never replaced by a later one.
332
- *
333
- * Group invites are a second wake kind: not on the tray, not gated, one turn
334
- * each with the served invite prompt, serialized on the same worker. An
335
- * invite whose turn OpenClaw refused stays pending and is tried again on the
336
- * next wake; one that started is remembered on disk (`InviteLedger`) so a
337
- * restart never offers it twice.
338
- */
339
-
340
- /**
341
- * Where a wake came from — a closed set, because it is a metric label:
342
- * `message` (a peer wrote), `connect` (an accepted HELLO), `reminder` (the
343
- * server's wake frame for a deferred conversation), `retry` (the local
344
- * ladder), `other` (a server wake with a reason this version does not know).
345
- */
346
- type WakeSource = 'message' | 'connect' | 'reminder' | 'retry' | 'other';
347
- /** The two SDK resources a cycle uses; `AgentChatClient` satisfies it. */
348
- type InvokerClient = Pick<AgentChatClient, 'inbox' | 'decisions'>;
349
- /** The served texts as the invoker sees them: the current copy, or one attempt to get it. */
350
- interface TextsSource {
351
- readonly current: Texts | null;
352
- ensure(): Promise<Texts | null>;
353
- }
354
- /** Which invites already got their turn (persisted across restarts). */
355
- interface InviteStore {
356
- isOffered(inviteId: string): boolean;
357
- markOffered(inviteId: string): void;
358
- }
359
- interface AgentInvokerOptions {
360
- readonly accountId: string;
361
- readonly agentId: string;
362
- readonly client: InvokerClient;
363
- readonly callModel: GateModelCall;
364
- readonly startTurn: TurnStarter;
365
- readonly texts: TextsSource;
366
- readonly invites: InviteStore;
367
- readonly logger: Logger;
368
- /** Counts the ladder's re-wakes (`agentchat_channel_wake_total{source="retry"}`). The socket counts the others. */
369
- readonly metrics?: MetricsRecorder;
370
- /**
371
- * Whether a turn started now can have the hosted tools (`turnReadiness`).
372
- * Checked before the gate: while unready nothing is gated — the cards
373
- * stay on the tray, no model call is spent, no turn starts — and the
374
- * ladder re-wakes. Default: always ready.
375
- */
376
- readonly readiness?: () => TurnReadiness;
377
- /** `false`: no gate step — one turn per cycle with the served wake instruction; the agent judges in-turn. */
378
- readonly gateEnabled?: boolean;
379
- readonly debounceMs?: number;
380
- readonly retryLadderMs?: readonly number[];
381
- readonly now?: () => number;
382
- readonly setTimeout?: (fn: () => void, ms: number) => NodeJS.Timeout;
383
- readonly clearTimeout?: (handle: NodeJS.Timeout) => void;
384
- }
385
- interface InvokerCounters {
386
- readonly cycles: number;
387
- readonly turns: number;
388
- readonly inviteTurns: number;
389
- /** Turns admitted whose run has not ended yet (OpenClaw's lane serializes them). */
390
- readonly turnsInFlight: number;
391
- readonly wakes: number;
392
- readonly absorbed: number;
393
- readonly retryRung: number;
394
- readonly pendingInvites: number;
395
- }
396
- type CycleOutcome =
397
- /** The tray had no cards. */
398
- 'empty'
399
- /** The gate decided; turns were started for the replies. */
400
- | 'decided'
401
- /** The model failed or answered nothing usable; nothing recorded, no turn. */
402
- | 'fail_closed'
403
- /** The gate is off; one turn with the served wake instruction. */
404
- | 'gate_off'
405
- /** The tray could not be read. */
406
- | 'tray_failed'
407
- /** The served texts are not available yet; nothing gated, the cards wait. */
408
- | 'texts_missing'
409
- /** A turn could not have the hosted tools; nothing gated, no model call, the cards wait. */
410
- | 'tools_unavailable';
411
- interface CycleResult {
412
- readonly outcome: CycleOutcome;
413
- readonly cards: number;
414
- readonly reply: number;
415
- readonly dismiss: number;
416
- readonly defer: number;
417
- readonly undecided: number;
418
- /** `dismiss` / `defer` the server took in this cycle. `reply` verdicts are recorded as their turns complete, after the cycle. */
419
- readonly recorded: number;
420
- readonly recordFailures: number;
421
- readonly turnsStarted: number;
422
- readonly turnsRefused: number;
423
- /** Cards left out of this cycle because a reply turn for their conversation is still running. */
424
- readonly skippedInFlight: number;
425
- readonly truncated: boolean;
426
- readonly latencyMs: number;
427
- readonly failure: string | null;
428
- }
429
- declare class AgentInvoker {
430
- private readonly accountId;
431
- private readonly agentId;
432
- private readonly client;
433
- private readonly callModel;
434
- private readonly startTurn;
435
- private readonly texts;
436
- private readonly invites;
437
- private readonly logger;
438
- private readonly metrics;
439
- private readonly readiness;
440
- private readonly gateEnabled;
441
- private readonly ladder;
442
- private readonly now;
443
- private readonly coalescer;
444
- private cycleDue;
445
- private running;
446
- private stopped;
447
- private pendingInvites;
448
- private invitesDirty;
449
- private retryRung;
450
- private turnsInFlight;
451
- /**
452
- * Conversations whose reply turn is running. Their verdict is recorded
453
- * only when the turn completes, so the card stays on the tray meanwhile
454
- * and every wake in between would re-gate it and queue a second turn.
455
- * Such cards are left out of the cycle; once the turn ends the tray is
456
- * read again if any were.
457
- */
458
- private readonly replyTurnsInFlight;
459
- private skippedWhileInFlight;
460
- /** The reason the tools were last found unavailable; logged when it changes, not per wake. */
461
- private unreadyReason;
462
- cycles: number;
463
- turns: number;
464
- inviteTurns: number;
465
- constructor(options: AgentInvokerOptions);
466
- /** A wake from the socket (a frame, a connect, a reminder) or any other source. Coalesced, then cycled. */
467
- wake(source: WakeSource): void;
468
- /**
469
- * The second wake kind. An invite already offered (this process or an
470
- * earlier one, per the ledger) or already pending is ignored, so an
471
- * invite seen live and again on a connect-time catch-up is decided once.
472
- * Returns true when newly queued.
473
- */
474
- groupInvite(invite: GroupInvite, source: string): boolean;
475
- /** Cancel timers; a cycle in flight finishes on its own. */
476
- stop(): void;
477
- /** The promise of the work currently running, for tests and for graceful stops. */
478
- settled(): Promise<void>;
479
- counters(): InvokerCounters;
480
- private onWakeFired;
481
- /** Run the worker if idle. One cycle at a time; work that lands mid-cycle runs afterwards. */
482
- private schedule;
483
- private drain;
484
- /** Read the tray, gate it, start a turn per reply. Public so tests can drive one cycle. */
485
- runCycle(): Promise<CycleResult>;
486
- /** Gate off: the agent judges in-turn with the hosted tools. One turn, nothing recorded here. */
487
- private runUngated;
488
- private runGated;
489
- private result;
490
- /** Arm the next rung (or report why not). Returned as log fields so every caller writes ONE line. */
491
- private retry;
492
- /**
493
- * Book an admitted turn and log its end whenever it comes. The cycle moves
494
- * on at once; OpenClaw's lane keeps the runs of one account in order.
495
- *
496
- * For a reply turn the end is also when the `reply` verdict is recorded —
497
- * only if the run completed (`status: ok`, no error): a turn that looked
498
- * and chose not to send still counts as read. A run that ended in error,
499
- * on the wait timeout, or whose wait failed records nothing: the card stays
500
- * on the tray and the ladder re-wakes so the conversation is gated again.
501
- */
502
- private admitted;
503
- /** The reply turn for `conversationId` is over: its card may be gated again, and a tray that held skipped cards is read once more. */
504
- private replyTurnEnded;
505
- /**
506
- * Whether the completed turn recorded a verdict for its conversation
507
- * itself, seen on one fresh tray read. A card that left the tray was read
508
- * (a verdict or a mark-read) or hidden by a `defer` — by the turn, since
509
- * the host had recorded nothing for it. A card still there whose
510
- * `your_last_decision` differs from the gate's copy got a verdict in the
511
- * turn (a newer message keeps it on the tray). A card still there,
512
- * unchanged, got nothing. A failed read, or a missing card past a
513
- * truncated tray, claims nothing: `reply` is recorded as before.
514
- */
515
- private decidedInTurn;
516
- /** The `reply` verdict for a completed turn. A record the server refuses leaves the conversation unread; the ladder re-wakes. */
517
- private recordReply;
518
- /**
519
- * Every pending invite gets one attempt. An invite leaves the pending list
520
- * only once its turn was admitted (and is then remembered in the ledger);
521
- * a refused one stays there for the next wake. Invites that arrive while
522
- * this runs are appended and get their pass on the next drain.
523
- */
524
- private runInviteTurns;
525
- }
526
-
527
- /**
528
- * The socket as a wake — the SDK's `RealtimeClient` bound to one account.
529
- *
530
- * The transport is the SDK's, lifecycle included: HELLO, the reconnect
531
- * backoff that never gives up (one notice after a long outage, then a wider
532
- * cap), the handshake and idle watchdogs, the 10–15 min retry of a rejected
533
- * key, the delivery ack, per-conversation ordering, the reconnect drain. This
534
- * module holds what is runtime logic: starting and stopping it with the
535
- * account, turning what arrives into wakes for the invoker, filtering the
536
- * echo of the agent's own sends, and handing the SDK's lifecycle events to
537
- * the gateway as they are.
538
- *
539
- * - `message.new` → `onWake('message')` — after reading only
540
- * the sender (to skip our own echo) and the
541
- * ids for the log line. The body is never
542
- * looked at; the agent reads it through the
543
- * hosted tools inside its turn.
544
- * - `wake` → `onWake(reason)` — the server's content-free
545
- * wake (a deferred conversation's reminder).
546
- * - every successful HELLO → `onWake('connect')` — whatever landed while
547
- * the socket was down is on the tray.
548
- * - `group.invite.received` → `onGroupInvite(invite)` — the second wake
549
- * kind; not on the tray, not gated.
550
- *
551
- * `ackOnReceipt: true`: the SDK acknowledges every `message.new` the moment
552
- * the frame is parsed, before any handler runs — delivered means this
553
- * machine received it. Whether the agent looked is read state, recorded by
554
- * the gate's verdicts; an early ack never empties the tray. No frame is
555
- * ever acknowledged by this module; it sends nothing.
556
- *
557
- * Every frame is a wake and every wake reads the whole tray, so no ordering
558
- * assumption is made: frames the SDK parks on a sequence gap and flushes on
559
- * a close are wakes like any other.
560
- *
561
- * Nothing here classifies a close. Whether a close was a rejected key, a
562
- * slow handshake or the client's own watchdog is the SDK's call: it says
563
- * `blocked` (a typed event with the code, the reason and the delay to its
564
- * next HELLO) or it backs off, and this module reports which.
565
- */
566
-
567
- /**
568
- * The connection as the gateway reports it: the SDK's own lifecycle, read
569
- * from `realtime.state`. `idle` before the first start, `connecting` while a
570
- * socket opens or its HELLO awaits `hello.ok`, `ready` while a session is up,
571
- * `backoff` between a close and the next attempt, `blocked` after the server
572
- * rejected the key during the handshake (the SDK retries a fresh HELLO every
573
- * 10–15 min; a later `hello.ok` clears it), `stopped` after `stop()` — the
574
- * only state the client never leaves on its own.
575
- */
576
- type SocketState = RealtimeState;
577
- /** Every socket close the SDK reports: the code, the reason, and who ended it (`client` = the SDK's own watchdog). */
578
- type SocketDisconnect = DisconnectInfo;
579
- /** A rejected HELLO: the close code and reason, and the delay to the SDK's next attempt. */
580
- type SocketBlocked = BlockedInfo;
581
- interface WakeDetail {
582
- readonly conversationId?: string;
583
- readonly messageId?: string;
584
- readonly from?: string;
585
- }
586
- interface SocketHandlers {
587
- /** A wake: the tray may have changed. `source` is for the log line and the metric label only. */
588
- onWake?: (source: WakeSource, detail: WakeDetail) => void;
589
- /** The second wake kind. */
590
- onGroupInvite?: (invite: GroupInvite) => void;
591
- /** Once per accepted HELLO (initial + every reconnect), before the connect wake. */
592
- onConnected?: (at: number) => void;
593
- /** Every socket close the SDK reports (never for our own `stop()`). The state that follows says what comes next. */
594
- onDisconnected?: (info: SocketDisconnect) => void;
595
- /**
596
- * The server rejected the key during the handshake. Once per rejected
597
- * HELLO: the first of a run and every 10–15 min retry after it, until one
598
- * is accepted (`onConnected`). The state is `blocked` by the time it fires.
599
- */
600
- onBlocked?: (info: SocketBlocked) => void;
601
- /** Every notice the SDK surfaces (transport errors, watchdog trips, the long-outage and rejection notices, handler failures). */
602
- onError?: (error: Error) => void;
603
- onStateChanged?: (next: SocketState, prev: SocketState) => void;
604
- }
605
- interface IntegrationSocketOptions {
606
- readonly config: AgentchatChannelConfig;
607
- readonly logger: Logger;
608
- readonly handlers?: SocketHandlers;
609
- readonly metrics?: MetricsRecorder;
610
- /**
611
- * The SDK client for the realtime client's reconnect drain and gap fill.
612
- * Without it offline envelopes wait for the server's own re-push.
613
- */
614
- readonly client?: AgentChatClient;
615
- /** Test seam: build the realtime client. Production constructs the SDK's. */
616
- readonly createRealtime?: (options: RealtimeOptions) => RealtimeClient;
617
- /** Test seam / polyfill: the WebSocket constructor the SDK uses. */
618
- readonly webSocket?: typeof globalThis.WebSocket;
619
- readonly now?: () => number;
620
- }
621
- interface SocketHealth {
622
- readonly state: SocketState;
623
- readonly connectedAt: number | null;
624
- readonly counters: {
625
- readonly frames: number;
626
- readonly selfFiltered: number;
627
- readonly wakes: number;
628
- readonly invites: number;
629
- readonly disconnects: number;
630
- };
631
- }
632
- /** The SDK realtime options for a channel config: `wss://…` base, the account's backoff, the integration identity. */
633
- declare function realtimeOptionsFor(config: AgentchatChannelConfig, extra?: Pick<IntegrationSocketOptions, 'client' | 'webSocket'>): RealtimeOptions;
634
- declare class IntegrationSocket {
635
- private readonly config;
636
- private readonly logger;
637
- private readonly handlers;
638
- private readonly metrics;
639
- private readonly client;
640
- private readonly createRealtime;
641
- private readonly webSocket;
642
- private readonly now;
643
- private readonly selfHandle;
644
- private realtime;
645
- /** The SDK's state as last reported through its `state` event; `stopped` is set here only for a stop before any start. */
646
- private state;
647
- private connectedAt;
648
- private stopping;
649
- private frames;
650
- private selfFiltered;
651
- private wakes;
652
- private invites;
653
- private disconnects;
654
- constructor(options: IntegrationSocketOptions);
655
- /**
656
- * Open the socket. Idempotent. Resolves once the SDK has started its
657
- * connect loop; a failure to resolve a WebSocket implementation is logged
658
- * and left to the SDK's own retry. Never throws.
659
- */
660
- start(): Promise<void>;
661
- /** Close the socket for good; a stopped socket does not reconnect. Idempotent. */
662
- stop(): Promise<void>;
663
- getHealth(): SocketHealth;
664
- private bind;
665
- private onMessageNew;
666
- private onWakeFrame;
667
- private onInvite;
668
- private wake;
669
- /** The SDK's state transition, mirrored for the health probe and the gauge, then handed on. */
670
- private onState;
671
- /** A failing handler never takes the socket down; the next frame wakes again and the tray keeps the cards. */
672
- private guard;
673
- }
674
-
675
- /**
676
- * Placing the four things AgentChat authored where OpenClaw loads them.
677
- *
678
- * 1. **The key** — `AGENTCHAT_API_KEY=…` in OpenClaw's state-dir `.env`
679
- * (`~/.openclaw/.env`, or `$OPENCLAW_STATE_DIR/.env`), which OpenClaw
680
- * reads at start as its global environment fallback. The hosted MCP
681
- * server's bearer header is a template on that variable, so the key is
682
- * never written into `openclaw.json` as part of the tool declaration.
683
- * (The channel's own `channels.agentchat.apiKey` keeps holding the key
684
- * for the socket, as before.)
685
- * 2. **The identity line** — the served `identity_line` (`GET /v1/texts`,
686
- * `../integration/texts.ts`) in the workspace `AGENTS.md`, loaded into
687
- * every turn (`../binding/agents-anchor.ts`). The callers fetch the text
688
- * (server, then the cached copy) and hand it in; with neither available
689
- * the step is skipped and reported, never invented.
690
- * 3. **The manual** — `https://agentchat.me/skill.md` verbatim, bundled as
691
- * the `agentchat` skill. Nothing to write; verified present.
692
- * 4. **The tools** — `mcp.servers.agentchat` in `openclaw.json` (`./mcp.ts`),
693
- * returned as a config patch for OpenClaw to persist.
694
- *
695
- * Every placer is idempotent and reports what it did; the wizard prints the
696
- * report, the status probe and the doctor run the checks again.
697
- */
698
-
699
- interface PlacementCheck {
700
- readonly name: 'key' | 'anchor' | 'manual' | 'mcp';
701
- readonly ok: boolean;
702
- readonly detail: string;
703
- }
704
-
705
- /**
706
- * ChannelStatusAdapter — the doctor-style status for `openclaw channels status`.
707
- *
708
- * `probeAccount` reports three things an operator needs to know, with one
709
- * short timeout each:
710
- *
711
- * 1. the key authenticates (`GET /v1/agents/me`) and the account is active;
712
- * 2. the hosted MCP server is reachable with that key (one MCP
713
- * `initialize`), because that is where every AgentChat tool lives;
714
- * 3. placement: the key in the gateway environment, the identity line in
715
- * AGENTS.md (checked against the last served copy when one is cached),
716
- * the manual, the `mcp.servers.agentchat` entry.
717
- *
718
- * Plus the socket's live state when the integration is running.
719
- */
720
-
721
- type AgentchatProbeResult = {
722
- readonly ok: boolean;
723
- readonly handle?: string;
724
- readonly status?: 'active' | 'restricted' | 'suspended' | 'deleted';
725
- readonly pausedByOwner?: 'none' | 'send' | 'full';
726
- readonly error?: string;
727
- readonly mcp?: {
728
- readonly ok: boolean;
729
- readonly detail: string;
730
- };
731
- readonly placement?: readonly PlacementCheck[];
732
- readonly integration?: {
733
- readonly mode: 'on' | 'off';
734
- readonly state?: SocketState;
735
- readonly wakes?: number;
736
- readonly cycles?: number;
737
- readonly turns?: number;
738
- /** Where the served texts came from: the server, the cached copy, or nowhere yet. */
739
- readonly texts?: 'server' | 'cache' | 'missing';
740
- /** The socket's counters since the account started: wakes by source, closes by code/initiator, SDK notices by class. */
741
- readonly socket?: MetricsSnapshot;
742
- };
743
- /** Set when the integration refuses to start (more than one account configured). */
744
- readonly refusal?: string;
745
- /** 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). */
746
- readonly disabled?: string;
747
- };
748
-
749
- interface AgentchatResolvedAccount {
750
- accountId: string;
751
- enabled: boolean;
752
- configured: boolean;
753
- config: AgentchatChannelConfig | null;
754
- parseError: string | null;
755
- }
756
- declare const agentchatPlugin: ChannelPlugin<AgentchatResolvedAccount, AgentchatProbeResult>;
757
- /**
758
- * Canonical channel-entry descriptor consumed by OpenClaw's extension loader.
759
- * Exported as `default` because `openclaw.extensions` in package.json points to
760
- * this module and the loader reads the default export.
761
- *
762
- * The explicit `ReturnType<...>` annotation pins the emitted `.d.ts` to the
763
- * function signature instead of the structural shape — otherwise the inferred
764
- * type references `ChannelConfigSchema` through a non-exported path and TS
765
- * fails with TS2742 ("cannot be named without a reference to ...").
766
- */
767
- declare const agentchatChannelEntry: ReturnType<typeof defineChannelPluginEntry<typeof agentchatPlugin>>;
768
-
769
- declare const agentchatSetupEntry: {
770
- plugin: openclaw_plugin_sdk_channel_core.ChannelPlugin<AgentchatResolvedAccount, AgentchatProbeResult>;
771
- };
772
-
773
- export { AgentInvoker as A, type CreateMetricsOptions as C, type GroupInvite as G, IntegrationSocket as I, type Logger as L, type MetricsRecorder as M, type PromFactory as P, type SocketBlocked as S, type WakeSource as W, type AgentInvokerOptions as a, type AgentchatChannelConfig as b, type AgentchatResolvedAccount as c, type CycleOutcome as d, type CycleResult as e, type IntegrationSocketOptions as f, InviteLedger as g, type MetricsSnapshot as h, type PromRegistryLike as i, type SocketDisconnect as j, type SocketHandlers as k, type SocketHealth as l, type SocketState as m, agentchatChannelEntry as n, agentchatPlugin as o, agentchatSetupEntry as p, createInMemoryMetrics as q, createMetrics as r, createNoopMetrics as s, groupInviteFromRecord as t, parseChannelConfig as u, realtimeOptionsFor as v };