@agentchatme/openclaw 0.7.82111 → 0.8.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 +253 -0
  2. package/README.md +174 -244
  3. package/RUNBOOK.md +86 -91
  4. package/SECURITY.md +36 -20
  5. package/dist/binding/agents-anchor.cjs +41 -53
  6. package/dist/binding/agents-anchor.cjs.map +1 -1
  7. package/dist/binding/agents-anchor.d.cts +61 -74
  8. package/dist/binding/agents-anchor.d.ts +61 -74
  9. package/dist/binding/agents-anchor.js +35 -53
  10. package/dist/binding/agents-anchor.js.map +1 -1
  11. package/dist/credentials/read-env.cjs +35 -1
  12. package/dist/credentials/read-env.cjs.map +1 -1
  13. package/dist/credentials/read-env.d.cts +31 -3
  14. package/dist/credentials/read-env.d.ts +31 -3
  15. package/dist/credentials/read-env.js +29 -2
  16. package/dist/credentials/read-env.js.map +1 -1
  17. package/dist/index.cjs +2340 -3656
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.d.cts +607 -322
  20. package/dist/index.d.ts +607 -322
  21. package/dist/index.js +2329 -3663
  22. package/dist/index.js.map +1 -1
  23. package/dist/openclaw-layout.cjs +120 -0
  24. package/dist/openclaw-layout.cjs.map +1 -0
  25. package/dist/openclaw-layout.d.cts +64 -0
  26. package/dist/openclaw-layout.d.ts +64 -0
  27. package/dist/openclaw-layout.js +90 -0
  28. package/dist/openclaw-layout.js.map +1 -0
  29. package/dist/{setup-entry-BuDCZ44W.d.cts → setup-entry-DU51IFUF.d.cts} +58 -8
  30. package/dist/{setup-entry-BuDCZ44W.d.ts → setup-entry-DU51IFUF.d.ts} +58 -8
  31. package/dist/setup-entry.cjs +2307 -3655
  32. package/dist/setup-entry.cjs.map +1 -1
  33. package/dist/setup-entry.d.cts +1 -1
  34. package/dist/setup-entry.d.ts +1 -1
  35. package/dist/setup-entry.js +2342 -3691
  36. package/dist/setup-entry.js.map +1 -1
  37. package/openclaw.plugin.json +10 -4
  38. package/package.json +9 -6
  39. package/skills/agentchat/SKILL.md +743 -225
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as AgentchatChannelConfig } from './setup-entry-BuDCZ44W.js';
2
- export { a as AgentchatResolvedAccount, b as agentchatChannelEntry, c as agentchatPlugin, d as agentchatSetupEntry, c as agentchatSetupPlugin, b as default, p as parseChannelConfig } from './setup-entry-BuDCZ44W.js';
1
+ import { A as AgentchatChannelConfig } from './setup-entry-DU51IFUF.js';
2
+ export { a as AgentchatResolvedAccount, b as agentchatChannelEntry, c as agentchatPlugin, d as agentchatSetupEntry, c as agentchatSetupPlugin, b as default, p as parseChannelConfig } from './setup-entry-DU51IFUF.js';
3
3
  export { hasAgentChatConfiguredState } from './configured-state.js';
4
4
  import { WebSocket } from 'ws';
5
5
  import 'openclaw/plugin-sdk/channel-core';
@@ -18,38 +18,30 @@ interface Logger {
18
18
  * Optional Prometheus metrics for the channel plugin.
19
19
  *
20
20
  * Design: the gateway owns the `/metrics` endpoint. Plugins do not expose
21
- * their own port. If the user passes a `prom-client` Registry via channel
22
- * runtime context, we register our counters/gauges/histograms into it.
23
- * Otherwise, we return a no-op recorder — zero overhead, zero config.
21
+ * their own port. If the user passes a `prom-client` Registry, we register
22
+ * our counters/gauges into it. Otherwise, we return a no-op recorder — zero
23
+ * overhead, zero config.
24
24
  *
25
- * Names are prefixed with `agentchat_channel_` for easy scraping.
25
+ * Names are prefixed with `agentchat_channel_` for easy scraping. The
26
+ * doorbell sends nothing, so there are no outbound metrics: what it reports
27
+ * is the socket's state and its knocks.
26
28
  */
27
29
  interface MetricsRecorder {
28
- /** Incremented on every successfully delivered inbound message. */
29
- incInboundDelivered(labels: {
30
- kind: InboundKind;
31
- }): void;
32
- /** Incremented on every successfully sent outbound message. */
33
- incOutboundSent(labels: {
34
- kind: OutboundKind;
35
- }): void;
36
- /** Incremented on every send failure, labeled by error class. */
37
- incOutboundFailed(labels: {
38
- errorClass: string;
39
- }): void;
40
30
  /** Incremented on every reconnect attempt. */
41
31
  incReconnect(labels: {
42
32
  reason: string;
43
33
  }): void;
44
- /** Observe end-to-end send latency (ms). */
45
- observeSendLatency(ms: number): void;
34
+ /** Incremented on every transport/channel error, labeled by error class. */
35
+ incError(labels: {
36
+ errorClass: string;
37
+ }): void;
46
38
  /** Set the current connection state (cardinality bounded by state kinds). */
47
39
  setConnectionState(kind: string): void;
48
- /** Set the current in-flight send queue depth. */
49
- setInFlightDepth(n: number): void;
40
+ /** Incremented on every knock handed to the invoker. */
41
+ incKnock(labels: {
42
+ source: string;
43
+ }): void;
50
44
  }
51
- type InboundKind = 'message' | 'group-message' | 'typing' | 'read' | 'presence' | 'rate-limit-warning';
52
- type OutboundKind = 'message' | 'typing' | 'read';
53
45
 
54
46
  /**
55
47
  * Error taxonomy for the AgentChat channel plugin.
@@ -153,8 +145,8 @@ type ConnectionState = {
153
145
  * DEGRADED on `ping.timeoutMs` miss, then force-reconnect.
154
146
  * - Schedule reconnect with exponential backoff + ±`jitterRatio` jitter
155
147
  * per `reconnect.*` config. Thundering-herd-safe across a fleet.
156
- * - Emit typed events upwards (`inboundFrame`, `stateChanged`, `error`)
157
- * so the normalizer (P3) and outbound adapter (P4) can consume them.
148
+ * - Emit typed events upwards (`inboundFrame`, `stateChanged`, `error`,
149
+ * `authenticated`) so the runtime can turn frames into knocks.
158
150
  *
159
151
  * Intentional design choices:
160
152
  * - Uses the `ws` package directly (not `globalThis.WebSocket`) because
@@ -163,6 +155,13 @@ type ConnectionState = {
163
155
  * (Fly, Render, Vercel functions, Lambda) is Node.
164
156
  * - Authenticates via HELLO frame (`{type: "hello", api_key}`), never via
165
157
  * URL query string. Keeps the key out of access logs and Referers.
158
+ * - Advertises the `ack` capability in HELLO and NEVER acknowledges. With
159
+ * the capability negotiated the server keeps every envelope `stored`
160
+ * until an ack arrives (WS Delivery-Ack Protocol v1); none ever does
161
+ * from here — a verdict recorded by the gate, or a send by the agent,
162
+ * is what settles delivery. There is no code path in this module that
163
+ * can emit a frame other than HELLO: delivery is judged, never
164
+ * confirmed by the transport.
166
165
  * - `RECONNECT_HARD_CAP_ATTEMPTS` guards against runaway reconnect loops
167
166
  * after catastrophic network events; crosses into `AUTH_FAIL` so the
168
167
  * operator sees a clear signal instead of silent retry forever.
@@ -181,17 +180,11 @@ interface InboundFrame {
181
180
  readonly receivedAt: UnixMillis;
182
181
  readonly raw: unknown;
183
182
  }
184
- /** One client-action frame the caller wants to push. */
185
- interface OutboundFrame {
186
- readonly type: string;
187
- readonly payload: Record<string, unknown>;
188
- readonly id?: string;
189
- }
190
183
  interface WsClientEvents {
191
184
  stateChanged: (next: ConnectionState, prev: ConnectionState) => void;
192
185
  inboundFrame: (frame: InboundFrame) => void;
193
186
  error: (error: AgentChatChannelError) => void;
194
- /** Fired once per `hello.ok` — useful for triggering a /v1/messages/sync drain upstream. */
187
+ /** Fired once per `hello.ok` — the runtime turns it into the connect knock. */
195
188
  authenticated: (at: UnixMillis) => void;
196
189
  /** Fired after a clean close + CLOSED state (after stop() or terminal auth failure). */
197
190
  closed: () => void;
@@ -242,6 +235,7 @@ declare class AgentchatWsClient {
242
235
  private state;
243
236
  private ws;
244
237
  private attempt;
238
+ private _ackNegotiated;
245
239
  private helloAckTimer;
246
240
  private pingTimer;
247
241
  private pongTimer;
@@ -251,18 +245,18 @@ declare class AgentchatWsClient {
251
245
  constructor(options: WsClientOptions);
252
246
  /** Current connection state. Read-only from the caller's perspective. */
253
247
  getState(): ConnectionState;
248
+ /**
249
+ * True when the last `hello.ok` echoed the `ack` capability: the server
250
+ * keeps envelopes `stored` until acknowledged — and this client never
251
+ * acknowledges. False against a legacy server (envelopes marked on push).
252
+ */
253
+ get ackNegotiated(): boolean;
254
254
  /**
255
255
  * Kick off connection. No-op if already connecting, authenticating, or
256
256
  * ready. Throws on `AUTH_FAIL` — the caller must call `reconfigured()`
257
257
  * after rotating the API key before retrying.
258
258
  */
259
259
  start(): void;
260
- /**
261
- * Push a client-action frame. Requires `canSend(state)` — returns false
262
- * if the socket is not ready. Callers should queue and retry from the
263
- * outbound adapter (P4) rather than drop here.
264
- */
265
- send(frame: OutboundFrame): boolean;
266
260
  /**
267
261
  * Request a graceful drain. The caller-supplied deadline is a Unix-ms
268
262
  * timestamp; after it passes, the socket is force-closed regardless of
@@ -304,275 +298,72 @@ declare class AgentchatWsClient {
304
298
  }
305
299
 
306
300
  /**
307
- * Inbound normalizer — AgentChat server events → channel-neutral shape.
301
+ * What the doorbell reads from a server frame — and what it does not.
308
302
  *
309
- * Responsibilities:
310
- * - Validate every server frame against a Zod schema. Unknown shapes
311
- * surface as `validation` errors (the transport catches them and drops
312
- * the frame without killing the connection).
313
- * - Translate AgentChat-native payloads into a stable, plugin-internal
314
- * `NormalizedInbound` shape. The OpenClaw channel binding (P7 runtime
315
- * wiring) adapts this further to the gateway's `ChannelInboundMessage`
316
- * contract.
317
- * - Classify conversation kind (direct vs group) from the `dir_*`/`grp_*`
318
- * prefix convention so consumers don't need to grep prefixes themselves.
319
- *
320
- * Why this module exists (rather than passing raw frames up):
321
- * - The WS client is pure transport; it shouldn't know what
322
- * `message.new` means semantically.
323
- * - OpenClaw's ChannelInboundMessage has a specific shape (thread id,
324
- * content parts, attachments, sender identity). Converting from
325
- * AgentChat's wire format in one place is the only sane way to keep
326
- * the mapping auditable.
327
- * - Per-event Zod schemas make drift between plugin and server obvious
328
- * and loud — a server field rename surfaces as a validation error
329
- * caught in CI long before it goes to prod.
303
+ * A `message.new` frame means *the tray changed*. The doorbell reads only
304
+ * the sender (to skip the echo of its own sends) and the ids (for the log
305
+ * line). The body is never looked at: the agent reads it through the hosted
306
+ * tools inside its turn. There is no schema for message content here
307
+ * because nothing here consumes it.
308
+ *
309
+ * A `group.invite.received` frame is the second knock kind. Invites are not
310
+ * on the tray and are not gated; the doorbell reads the ids and names it
311
+ * logs and hands the invite to the invoker, which starts one turn with a
312
+ * fixed prompt.
330
313
  */
331
314
 
332
- type ConversationKind = 'direct' | 'group';
333
- interface NormalizedMessage {
315
+ interface MessageKnock {
334
316
  readonly kind: 'message';
335
- readonly conversationKind: ConversationKind;
336
- readonly conversationId: string;
337
- /** Sender handle. */
317
+ /** Bare, lowercase sender handle (`@` stripped); `''` when the frame carried none. */
338
318
  readonly sender: string;
339
319
  readonly messageId: string;
340
- readonly clientMsgId: string;
341
- readonly seq: number;
342
- readonly messageType: 'text' | 'structured' | 'file' | 'system';
343
- readonly content: {
344
- readonly text?: string;
345
- readonly data?: Record<string, unknown>;
346
- readonly attachmentId?: string;
347
- };
348
- readonly metadata: Record<string, unknown>;
349
- /**
350
- * Per-recipient delivery state. Since migration 011, per-recipient state
351
- * lives on `message_deliveries`, not the message row — so fresh-send
352
- * `message.new` envelopes have no status field. Drain-path (sync /
353
- * undelivered) envelopes still include `'stored'`. `null` means the
354
- * server didn't attach one; callers that need the authoritative state
355
- * should query `GET /v1/messages/sync` or `/delivery-receipts`.
356
- */
357
- readonly status: 'stored' | 'delivered' | 'read' | null;
358
- readonly createdAt: string;
359
- readonly deliveredAt: string | null;
360
- readonly readAt: string | null;
361
- readonly receivedAt: UnixMillis;
362
- /** Sender's resolved display name, or null when unset / no context block. */
363
- readonly senderDisplayName: string | null;
364
- /** 'system' = platform agent (weight its words as authoritative); 'agent' = peer. */
365
- readonly senderKind: 'agent' | 'system';
366
- /** Group's human-readable name (null for DMs / when the server omitted it). */
367
- readonly groupName: string | null;
368
- readonly memberCount: number | null;
369
- /** Handles @-mentioned, parsed server-side (word-boundary). Test your OWN
370
- * handle for membership — never substring-match the raw text. */
371
- readonly mentions: readonly string[];
372
- }
373
- interface NormalizedReadReceipt {
374
- readonly kind: 'read-receipt';
375
- readonly conversationKind: ConversationKind;
376
- readonly conversationId: string;
377
- readonly reader: string;
378
- readonly throughSeq: number;
379
- readonly at: string | null;
380
- readonly receivedAt: UnixMillis;
381
- }
382
- interface NormalizedTyping {
383
- readonly kind: 'typing';
384
- readonly action: 'start' | 'stop';
385
- readonly conversationKind: ConversationKind;
386
320
  readonly conversationId: string;
387
- readonly sender: string;
388
- readonly receivedAt: UnixMillis;
389
- }
390
- interface NormalizedPresence {
391
- readonly kind: 'presence';
392
- readonly handle: string;
393
- readonly status: 'online' | 'away' | 'offline';
394
- readonly lastActiveAt: string | null;
395
- readonly customStatus: string | null;
396
- readonly receivedAt: UnixMillis;
397
321
  }
398
- interface NormalizedRateLimitWarning {
399
- readonly kind: 'rate-limit-warning';
400
- readonly endpoint: string | null;
401
- readonly limit: number | null;
402
- readonly remaining: number | null;
403
- readonly resetAt: string | null;
404
- readonly message: string | null;
405
- readonly receivedAt: UnixMillis;
406
- }
407
- interface NormalizedGroupInvite {
322
+ interface GroupInviteKnock {
408
323
  readonly kind: 'group-invite';
409
324
  readonly inviteId: string;
410
325
  readonly groupId: string;
411
326
  readonly groupName: string;
412
- readonly groupDescription: string | null;
413
- readonly groupAvatarUrl: string | null;
414
- readonly groupMemberCount: number;
415
327
  readonly inviterHandle: string;
416
- readonly createdAt: string;
417
- readonly receivedAt: UnixMillis;
418
- }
419
- interface NormalizedGroupDeleted {
420
- readonly kind: 'group-deleted';
421
- readonly groupId: string;
422
- readonly deletedByHandle: string;
423
- readonly deletedAt: string;
424
- readonly receivedAt: UnixMillis;
425
- }
426
- /**
427
- * Unknown server event — arrived over the wire but isn't in our explicit
428
- * handler set. We still surface it (the gateway may want to log it or
429
- * forward it), but with a `type` field so downstream can discriminate.
430
- */
431
- interface NormalizedUnknown {
432
- readonly kind: 'unknown';
433
- readonly type: string;
434
- readonly payload: Record<string, unknown>;
435
- readonly receivedAt: UnixMillis;
436
- }
437
- type NormalizedInbound = NormalizedMessage | NormalizedReadReceipt | NormalizedTyping | NormalizedPresence | NormalizedRateLimitWarning | NormalizedGroupInvite | NormalizedGroupDeleted | NormalizedUnknown;
438
-
439
- /**
440
- * Shape of a message record as returned by the AgentChat REST API.
441
- *
442
- * Mirrors the `Message` interface defined in the AgentChat TypeScript SDK
443
- * (`packages/sdk-typescript/src/types/message.ts`). We keep a local copy so
444
- * this plugin has no runtime dependency on the SDK — it's type-only at the
445
- * source and the SDK isn't published to npm yet. If the server's message
446
- * contract changes, update both files together; a drift is a schema
447
- * mismatch the server will catch, but we'd rather fail type-check first.
448
- */
449
- type MessageType = 'text' | 'structured' | 'file' | 'system';
450
- type MessageStatus = 'stored' | 'delivered' | 'read';
451
- interface MessageContent {
452
- text?: string;
453
- data?: Record<string, unknown>;
454
- attachment_id?: string;
455
- }
456
- interface Message {
457
- id: string;
458
- conversation_id: string;
459
- sender: string;
460
- client_msg_id: string;
461
- seq: number;
462
- type: MessageType;
463
- content: MessageContent;
464
- metadata: Record<string, unknown>;
465
- status: MessageStatus;
466
- created_at: string;
467
- delivered_at: string | null;
468
- read_at: string | null;
469
328
  }
329
+ type Knock = MessageKnock | GroupInviteKnock;
470
330
 
471
331
  /**
472
- * Outbound adapter — OpenClaw send → AgentChat `POST /v1/messages`.
473
- *
474
- * Pipeline (left to right, each step is independently observable):
475
- * 1. Caller invokes `sendMessage(input)` with a channel-neutral shape.
476
- * 2. We derive a stable `client_msg_id` (idempotency key). If the caller
477
- * supplied one, we respect it; otherwise we mint a UUID.
478
- * 3. Circuit-breaker precheck. Open circuit → fast-fail `retry-transient`.
479
- * 4. `retryWithPolicy(...)` wraps the actual HTTP call.
480
- * 5. On success, metrics/logs + return the `Message` the server minted.
481
- * 6. On 409 (idempotent-replay), treat as success with the replay body.
482
- * 7. On 429, honor `Retry-After` (seconds or HTTP-date) via the retry
483
- * policy. Surface as `retry-rate`.
484
- * 8. On 5xx / network flap, retry with jittered exponential backoff.
485
- * 9. On 4xx other than 429/409, classify as `terminal-user` → no retry.
486
- * 10. On 401/403 → `terminal-auth`. We signal upstream so the WS client
487
- * moves to AUTH_FAIL and the operator gets paged.
488
- *
489
- * Backpressure:
490
- * - An in-flight semaphore bounds concurrent sends to `outbound.maxInFlight`.
491
- * - Over-threshold sends are enqueued and drained as capacity frees up.
492
- * - Queue has its own hard cap (`10 * maxInFlight`); over-cap sends reject
493
- * immediately with `retry-transient` so the caller can shed load rather
494
- * than OOM.
495
- */
496
-
497
- type OutboundMessageInput = OutboundDirectMessage | OutboundGroupMessage;
498
- interface OutboundMessageBase {
499
- /**
500
- * Client-generated idempotency key. Optional — we mint one if absent.
501
- * Retries of the same logical send MUST reuse the same value or you'll
502
- * get duplicates.
503
- */
504
- readonly clientMsgId?: string;
505
- readonly type?: 'text' | 'structured' | 'file';
506
- readonly content: {
507
- readonly text?: string;
508
- readonly data?: Record<string, unknown>;
509
- readonly attachmentId?: string;
510
- };
511
- readonly metadata?: Record<string, unknown>;
512
- /** Correlation id carried through logs and metrics. */
513
- readonly correlationId?: string;
514
- }
515
- interface OutboundDirectMessage extends OutboundMessageBase {
516
- readonly kind: 'direct';
517
- /** Recipient handle (e.g. "alice"). */
518
- readonly to: string;
519
- }
520
- interface OutboundGroupMessage extends OutboundMessageBase {
521
- readonly kind: 'group';
522
- /** `grp_*` conversation id. */
523
- readonly conversationId: string;
524
- }
525
- interface OutboundBacklogWarning {
526
- readonly recipientHandle: string;
527
- readonly undeliveredCount: number;
528
- }
529
- interface SendResult {
530
- readonly message: Message;
531
- readonly backlogWarning: OutboundBacklogWarning | null;
532
- readonly idempotentReplay: boolean;
533
- readonly attempts: number;
534
- readonly latencyMs: number;
535
- readonly requestId: string | null;
536
- }
537
-
538
- /**
539
- * AgentChat channel runtime — single lifecycle object that ties the WS
540
- * transport (P2), inbound normalizer (P3), and outbound adapter (P4)
541
- * together. This is the surface an OpenClaw channel binding consumes.
332
+ * AgentChat channel runtime — the socket as a knock.
542
333
  *
543
- * Responsibilities:
544
- * - Instantiate the WS client, hook its `inboundFrame` event through
545
- * `normalizeInbound` and into user-supplied handlers.
546
- * - Expose `sendMessage` that delegates to the OutboundAdapter.
547
- * - Coordinate drain: `stop(deadline)` waits for outbound in-flight to
548
- * clear (up to the deadline) before closing the WS.
549
- * - Surface a single `getHealth()` snapshot combining connection state +
550
- * outbound queue depth + circuit breaker state.
551
- *
552
- * Not in scope here:
553
- * - Per-conversation seq ordering and gap recovery — the SDK's
554
- * `RealtimeClient` owns that. For the channel plugin, we deliver
555
- * inbound frames as they arrive; upper layers can call
556
- * `GET /v1/messages/sync` for reconciliation if they require strict
557
- * ordering across reconnects.
558
- * - OpenClaw ChannelInboundMessage translation — that lives in the
559
- * bridge module (consumed by the gateway), not here. Keeping this
560
- * module decoupled means it can be smoke-tested without OpenClaw.
334
+ * One instance per (channelId, accountId). It owns the WebSocket transport
335
+ * (`AgentchatWsClient`: HELLO, state machine, heartbeat, reconnect) and turns
336
+ * what arrives on it into knocks for the doorbell's invoker:
337
+ *
338
+ * - `message.new` → `onKnock('message')` — after reading only
339
+ * the sender (to skip our own echo) and the
340
+ * ids for the log line. The body is never
341
+ * looked at; the agent reads it through the
342
+ * hosted tools inside its turn.
343
+ * - every successful HELLO → `onKnock('connect')` — whatever landed
344
+ * while the socket was down is on the tray.
345
+ * - `group.invite.received` → `onGroupInvite(invite)` — the second knock
346
+ * kind; not on the tray, not gated.
347
+ *
348
+ * Nothing is parsed into message shapes, nothing is acknowledged, nothing is
349
+ * sent: the socket advertises the `ack` capability so the server keeps every
350
+ * envelope `stored` until a verdict or a send settles it, and this runtime
351
+ * has no code path that could emit an ack frame (`ws-client.ts`). Delivery
352
+ * is judged by the agent, never by the transport.
561
353
  */
562
354
 
355
+ type KnockSource = 'message' | 'connect';
563
356
  interface ChannelRuntimeHandlers {
564
- /** Called for every successfully normalized inbound event. */
565
- onInbound?: (event: NormalizedInbound) => void | Promise<void>;
566
- /** Called whenever a frame fails validation. Default: log-and-drop. */
567
- onValidationError?: (error: AgentChatChannelError, frame: InboundFrame) => void;
568
- /** Called on state transitions — surface to gateway for health/UI. */
357
+ /** A knock: the tray may have changed. `source` is for the log line only. */
358
+ onKnock?: (source: KnockSource) => void;
359
+ /** The second knock kind. */
360
+ onGroupInvite?: (invite: GroupInviteKnock) => void;
361
+ /** Called on state transitions — surface to the gateway for health/UI. */
569
362
  onStateChanged?: (next: ConnectionState, prev: ConnectionState) => void;
570
- /** Called once per successful HELLO_OK (initial + every reconnect). */
363
+ /** Called once per successful HELLO (initial + every reconnect), before the connect knock. */
571
364
  onAuthenticated?: (at: UnixMillis) => void;
572
365
  /** Called on every closed/unreachable situation worth observing. */
573
366
  onError?: (error: AgentChatChannelError) => void;
574
- /** Called when the server signals a backlog warning on an outbound send. */
575
- onBacklogWarning?: (warning: OutboundBacklogWarning) => void;
576
367
  }
577
368
  interface ChannelRuntimeOptions {
578
369
  readonly config: AgentchatChannelConfig;
@@ -581,67 +372,366 @@ interface ChannelRuntimeOptions {
581
372
  readonly logger?: Logger;
582
373
  /** Pre-built metrics recorder — if absent, uses no-op. */
583
374
  readonly metrics?: MetricsRecorder;
584
- readonly fetch?: typeof fetch;
585
375
  /** Provided by tests. */
586
376
  readonly webSocketCtor?: ConstructorParameters<typeof AgentchatWsClient>[0]['webSocketCtor'];
587
377
  readonly now?: () => UnixMillis;
588
378
  readonly random?: () => number;
589
- readonly sleep?: (ms: number) => Promise<void>;
590
379
  }
591
380
  interface HealthSnapshot {
592
381
  readonly state: ConnectionState;
593
382
  readonly authenticated: boolean;
594
- readonly outbound: {
595
- readonly inFlight: number;
596
- readonly queued: number;
597
- readonly circuitState: 'closed' | 'open' | 'half-open';
383
+ /** Whether the server echoed the `ack` capability on the last HELLO (envelopes stay `stored` until judged). */
384
+ readonly ackNegotiated: boolean;
385
+ readonly counters: {
386
+ readonly frames: number;
387
+ readonly selfFiltered: number;
388
+ readonly knocks: number;
389
+ readonly invites: number;
598
390
  };
599
391
  }
600
- /**
601
- * Orchestrates the full channel. Construct once per (channelId, accountId)
602
- * pair at gateway startup; call `start()` to bring it up, `stop()` to
603
- * drain. Dispose is folded into `stop()` — after it resolves, the
604
- * instance is terminal.
605
- */
606
392
  declare class AgentchatChannelRuntime {
607
393
  private readonly config;
608
394
  private readonly handlers;
609
395
  private readonly logger;
610
- private readonly metrics;
611
396
  private readonly ws;
612
- private readonly outbound;
397
+ private readonly selfHandle;
613
398
  private readonly now;
614
399
  private started;
615
400
  private authenticated;
616
401
  private stopPromise;
402
+ private frames;
403
+ private selfFiltered;
404
+ private knocks;
405
+ private invites;
406
+ private authenticatedAt;
617
407
  constructor(opts: ChannelRuntimeOptions);
618
408
  /** Open the transport. Idempotent — subsequent calls are no-ops. */
619
409
  start(): void;
410
+ /** Graceful shutdown: close the socket (nothing is in flight — the runtime sends nothing). */
411
+ stop(deadlineMs?: UnixMillis): Promise<void>;
412
+ /** Operator rotated the API key — leave AUTH_FAIL so the next `start()` can retry. */
413
+ reconfigured(): void;
414
+ getHealth(): HealthSnapshot;
415
+ private bindWsEvents;
416
+ private dispatchFrame;
417
+ private knock;
418
+ /** A failing handler never takes the socket down; the next frame knocks again and the tray keeps the cards. */
419
+ private guard;
420
+ }
421
+
422
+ /** The tray, as the server sends it. Only the fields the doorbell reads are typed; the rest passes through. */
423
+ interface Tray {
424
+ readonly you?: unknown;
425
+ readonly question?: unknown;
426
+ readonly categories?: unknown;
427
+ readonly conversations?: unknown;
428
+ readonly deferred?: unknown;
429
+ readonly truncated?: unknown;
430
+ readonly [key: string]: unknown;
431
+ }
432
+ type Decision = 'reply' | 'dismiss' | 'defer';
433
+ interface RecordDecisionInput {
434
+ readonly decision: Decision;
435
+ readonly category?: string | undefined;
436
+ readonly throughMessageId?: string | undefined;
437
+ readonly deferSeconds?: number | undefined;
438
+ }
439
+ /**
440
+ * A main-line call failed: transport error or a non-2xx answer.
441
+ * `status` is the HTTP status (`undefined` for transport failures); `code`
442
+ * is the server's error code when the body carried one.
443
+ */
444
+ declare class MainLineError extends Error {
445
+ readonly status: number | undefined;
446
+ readonly code: string | undefined;
447
+ constructor(message: string, options?: {
448
+ status?: number;
449
+ code?: string;
450
+ cause?: unknown;
451
+ });
452
+ }
453
+ interface MainLineClientOptions {
454
+ readonly apiKey: string;
455
+ readonly apiBase: string;
456
+ readonly timeoutMs?: number;
457
+ /** Test seam. Production uses the global `fetch`. */
458
+ readonly fetch?: typeof fetch;
459
+ }
460
+ declare class MainLineClient {
461
+ private readonly apiKey;
462
+ private readonly apiBase;
463
+ private readonly timeoutMs;
464
+ private readonly fetchImpl;
465
+ constructor(options: MainLineClientOptions);
620
466
  /**
621
- * Graceful shutdown. Waits for outbound in-flight to drain up to the
622
- * deadline, then force-closes the WS. Returns a promise that resolves
623
- * once the WS has emitted `closed`.
467
+ * `GET /v1/inbox` — the briefing cards plus the gate question, returned as
468
+ * the server sent them (`you`, `question`, `categories`, `conversations`,
469
+ * `deferred`, `truncated`, and any field a newer server adds). Marks
470
+ * nothing delivered.
624
471
  */
625
- stop(deadlineMs?: UnixMillis): Promise<void>;
626
- private pollUntilIdle;
472
+ inbox(params?: {
473
+ waitMs?: number;
474
+ limit?: number;
475
+ }): Promise<Tray>;
627
476
  /**
628
- * Send an outbound message. Delegates to the OutboundAdapter; callers
629
- * should handle `AgentChatChannelError` with class dispatch.
477
+ * `POST /v1/conversations/{id}/decisions` — record one verdict. The server
478
+ * validates `decision`, `category` and `defer_seconds` against its own
479
+ * taxonomy; this client passes them through and raises `MainLineError`
480
+ * (`status` 400) when the server rejects a value, so the caller can retry
481
+ * with less.
630
482
  */
631
- sendMessage(input: OutboundMessageInput): Promise<SendResult>;
632
- /** Push a client-action frame over the WS (typing, read-ack, presence). */
633
- sendWsAction(type: 'typing.start' | 'typing.stop' | 'message.read_ack' | 'presence.update', payload: Record<string, unknown>): boolean;
483
+ recordDecision(conversationId: string, input: RecordDecisionInput): Promise<Record<string, unknown>>;
484
+ private request;
485
+ }
486
+
487
+ /**
488
+ * The gate step: the agent's own model answers the server's question about the server's cards.
489
+ *
490
+ * Code we keep, brain we don't
491
+ * ────────────────────────────
492
+ * Every word the model reads here comes from the main line: the gate question
493
+ * (`tray.question`) and the briefing cards (`tray.conversations`) are passed
494
+ * through exactly as `GET /v1/inbox` returned them. This module adds a
495
+ * two-line wrapper asking for strict JSON, parses the answer, and records the
496
+ * verdicts with `POST /v1/conversations/{id}/decisions`. No wording of its
497
+ * own, no category list of its own (categories are offered only when the
498
+ * tray carries them), no pace or relationship arithmetic — the server
499
+ * computes, the agent's model judges, the doorbell carries.
500
+ *
501
+ * What gets recorded
502
+ * ──────────────────
503
+ * `dismiss` and `defer` are posted; a recorded verdict settles delivery for
504
+ * what it covers, so the sender's tick is honest and the conversation leaves
505
+ * the tray. `reply` is deliberately *not* posted: the send is the reply
506
+ * verdict, and posting it would settle the envelopes and take the card off
507
+ * the tray before the agent's turn has read it. Cards decided `reply` stay
508
+ * on the tray; the turn that follows reads exactly those with the hosted
509
+ * `agentchat_inbox` tool. A model that still answers the legacy spelling
510
+ * `no_reply` is understood and posted as `dismiss`.
511
+ *
512
+ * Failure policy
513
+ * ──────────────
514
+ * Fail closed by default: when the model cannot be reached or answers nothing
515
+ * usable, nothing is posted and no turn starts. The envelopes stay `stored`,
516
+ * the tray keeps the cards, and the invoker re-knocks on its own ladder. With
517
+ * `AGENTCHAT_REPLY_GATE_FAIL_OPEN=1` a failed gate starts the turn anyway and
518
+ * the agent judges from the tray inside the turn.
519
+ */
520
+
521
+ interface Verdict {
522
+ readonly conversationId: string;
523
+ readonly decision: Decision;
524
+ readonly category?: string | undefined;
525
+ readonly deferSeconds?: number | undefined;
526
+ }
527
+ /** Returns the model's raw text. Injectable so tests never reach a provider. */
528
+ type GateCaller = (params: {
529
+ readonly systemPrompt: string;
530
+ readonly userContent: string;
531
+ readonly maxTokens: number;
532
+ readonly timeoutMs: number;
533
+ }) => Promise<string>;
534
+ type GateSource = 'llm' | 'empty' | 'fail_closed' | 'fail_open' | 'disabled';
535
+ interface GateResult {
536
+ /** How the cycle ended; see the module header. */
537
+ readonly source: GateSource;
538
+ readonly cards: number;
539
+ readonly verdicts: readonly Verdict[];
540
+ readonly undecided: readonly string[];
541
+ readonly replyConversations: readonly string[];
542
+ readonly posted: number;
543
+ readonly postFailures: number;
544
+ readonly truncated: boolean;
545
+ readonly latencyMs: number;
546
+ readonly failure: string | null;
547
+ }
548
+
549
+ /**
550
+ * Where the doorbell meets OpenClaw's agent runtime.
551
+ *
552
+ * Two things only, both on the `PluginRuntime` OpenClaw hands a channel entry
553
+ * through `defineChannelPluginEntry({ setRuntime })`:
554
+ *
555
+ * 1. **The gate call** — `runtime.llm.complete({ systemPrompt, messages,
556
+ * maxTokens, temperature, purpose })` runs one tool-free completion on the
557
+ * agent's own configured model and credentials (`LlmCompleteParams`,
558
+ * `plugin-sdk/types`; docs.openclaw.ai/plugins/sdk-runtime/models). Without
559
+ * an `agentId` OpenClaw uses the ambient default agent; passing one is an
560
+ * OVERRIDE that OpenClaw 2026.10.9 rejects with
561
+ * `LLM_COMPLETION_NOT_AUTHORIZED` unless the operator set
562
+ * `plugins.entries.agentchat.llm.allowAgentIdOverride: true`. The doorbell
563
+ * therefore passes `agentId` only when the account is genuinely routed to
564
+ * a non-default agent (`agentIdOverride`), and the wizard / doctor write
565
+ * the opt-in in that case. The judgement is the agent's; the platform
566
+ * computes, it never judges.
567
+ *
568
+ * 2. **The turn** — `runtime.subagent.run({ sessionKey, message, lane,
569
+ * deliver: false })` admits one agent run with the fixed prompt as its
570
+ * message and no delivery of its final text (`SubagentRunParams`;
571
+ * docs.openclaw.ai/plugins/sdk-runtime/background-work — the same shape
572
+ * OpenClaw's own background features use with `deliver: false`). The
573
+ * turn's output is never routed anywhere: the agent's only way to say
574
+ * something on AgentChat is the hosted `agentchat__agentchat_send_message`
575
+ * tool during the turn. `runtime.subagent.waitForRun` bounds how long the
576
+ * invoker waits before it may start the next cycle; it never cancels the
577
+ * run.
578
+ *
579
+ * The agent id is resolved the way OpenClaw routes inbound for this channel
580
+ * (`channelRuntime.routing.resolveAgentRoute`), so the doorbell wakes the
581
+ * agent the operator bound to the account; `main` when nothing is bound.
582
+ */
583
+
584
+ interface TurnRequest {
585
+ readonly sessionKey: string;
586
+ readonly prompt: string;
587
+ readonly lane: string;
588
+ }
589
+ interface TurnOutcome {
590
+ readonly ran: boolean;
591
+ readonly runId?: string;
592
+ readonly status?: string;
593
+ readonly error?: string;
594
+ }
595
+ /** Starts one agent turn and waits for it (bounded). Injectable so the invoker is testable without OpenClaw. */
596
+ type TurnRunner = (request: TurnRequest) => Promise<TurnOutcome>;
597
+
598
+ /**
599
+ * Knock → gate → turn. The only path from the socket to the agent.
600
+ *
601
+ * What happens on a knock
602
+ * ───────────────────────
603
+ * 1. **Coalesce.** Frames inside a short window become one knock
604
+ * (`KnockCoalescer`). A group waking up is one cycle, not twenty.
605
+ * 2. **Read the tray.** `GET /v1/inbox?wait_ms=0&limit=50` — the server's
606
+ * briefing cards and its gate question, as it built them.
607
+ * 3. **Gate.** The agent's own model answers the question per card
608
+ * (`./gate.ts`); `dismiss` / `defer` verdicts are recorded on the server,
609
+ * which settles those conversations. `reply` cards stay on the tray.
610
+ * 4. **Turn.** If anything was decided `reply`, start ONE OpenClaw agent turn
611
+ * with the fixed prompt (`./turn.ts`). The agent reads and answers through
612
+ * the hosted MCP tools; the send is its verdict. The turn's final text is
613
+ * discarded — nothing is auto-routed anywhere.
614
+ *
615
+ * One cycle at a time per account: a knock that lands while a cycle runs is
616
+ * remembered and runs once the cycle ends (the tray is re-read, so whatever
617
+ * the earlier knock announced is covered). A cycle that could not complete —
618
+ * model unreachable, server error, verdicts rejected — re-knocks itself on a
619
+ * local ladder (1 m, 5 m, 30 m) because a connected socket gets no re-ring
620
+ * from the server; the cards wait on the tray meanwhile. One outage climbs
621
+ * the ladder one rung: a retry already on its way is never replaced by a
622
+ * later one.
623
+ *
624
+ * Group invites are a second knock kind: not on the tray, not gated, one turn
625
+ * each with the fixed invite prompt, serialized on the same worker.
626
+ */
627
+
628
+ interface AgentInvokerOptions {
629
+ readonly accountId: string;
630
+ readonly agentId: string;
631
+ readonly mainLine: MainLineClient;
632
+ readonly gateCaller: GateCaller;
633
+ readonly turnRunner: TurnRunner;
634
+ readonly logger: Logger;
635
+ readonly gateEnabled?: boolean;
636
+ readonly gateFailOpen?: boolean;
637
+ readonly gateTimeoutMs?: number;
638
+ readonly debounceMs?: number;
639
+ readonly retryLadderMs?: readonly number[];
640
+ readonly now?: () => number;
641
+ readonly setTimeout?: (fn: () => void, ms: number) => NodeJS.Timeout;
642
+ readonly clearTimeout?: (handle: NodeJS.Timeout) => void;
643
+ }
644
+ interface InvokerCounters {
645
+ readonly cycles: number;
646
+ readonly turns: number;
647
+ readonly inviteTurns: number;
648
+ readonly knocks: number;
649
+ readonly absorbed: number;
650
+ readonly retryRung: number;
651
+ }
652
+ declare class AgentInvoker {
653
+ private readonly accountId;
654
+ private readonly agentId;
655
+ private readonly mainLine;
656
+ private readonly gateCaller;
657
+ private readonly turnRunner;
658
+ private readonly logger;
659
+ private readonly gateEnabled;
660
+ private readonly gateFailOpen;
661
+ private readonly gateTimeoutMs;
662
+ private readonly ladder;
663
+ private readonly now;
664
+ private readonly coalescer;
665
+ private cycleDue;
666
+ private running;
667
+ private stopped;
668
+ private readonly invites;
669
+ private readonly seenInvites;
670
+ private retryRung;
671
+ cycles: number;
672
+ turns: number;
673
+ inviteTurns: number;
674
+ constructor(options: AgentInvokerOptions);
675
+ /** A knock from the socket (a frame, a connect) or any other source. Coalesced, then cycled. */
676
+ knock(source: string): void;
634
677
  /**
635
- * Operator has rotated the API key — signal the WS client so it can
636
- * exit AUTH_FAIL. The caller is responsible for creating a new runtime
637
- * with the updated config OR for calling this after config hot-reload.
678
+ * The second knock kind. Deduplicated by invite id for the life of the
679
+ * process so an invite seen live and again on a connect-time catch-up is
680
+ * decided once. Returns true when newly queued.
638
681
  */
639
- reconfigured(): void;
640
- getHealth(): HealthSnapshot;
641
- private bindWsEvents;
642
- private dispatchFrame;
643
- private recordInboundMetric;
682
+ groupInvite(invite: GroupInviteKnock, source: string): boolean;
683
+ /** Cancel timers; a cycle in flight finishes on its own. */
684
+ stop(): void;
685
+ /** The promise of the cycle currently running, for tests and for graceful stops. */
686
+ settled(): Promise<void>;
687
+ counters(): InvokerCounters;
688
+ private onKnockFired;
689
+ /** Run the worker if idle. One cycle at a time; work that lands mid-cycle runs afterwards. */
690
+ private schedule;
691
+ private drain;
692
+ /** Read the tray, gate it, start a turn when warranted. Public so tests can drive one cycle. */
693
+ runCycle(): Promise<GateResult | null>;
694
+ private scheduleRetry;
695
+ /** Start the knock turn. Returns whether OpenClaw admitted the run. */
696
+ private runKnockTurn;
697
+ private runInviteTurn;
698
+ }
699
+
700
+ declare function hostedMcpUrl(apiBase?: string): string;
701
+ interface McpServerEntry {
702
+ readonly url: string;
703
+ readonly transport: 'streamable-http';
704
+ readonly headers: {
705
+ readonly Authorization: string;
706
+ };
707
+ }
708
+ /** The `mcp.servers.agentchat` value this plugin places. */
709
+ declare function hostedMcpServerEntry(apiBase?: string): McpServerEntry;
710
+ /** The same entry as JSON5, for the README and for operators placing it by hand. */
711
+ declare function hostedMcpSnippet(apiBase?: string): string;
712
+ interface McpProbeResult {
713
+ readonly ok: boolean;
714
+ readonly status?: number;
715
+ readonly serverName?: string;
716
+ readonly serverVersion?: string;
717
+ readonly protocolVersion?: string;
718
+ /** Whether the server published `instructions` (OpenClaw injects them into the system prompt). */
719
+ readonly hasInstructions?: boolean;
720
+ readonly error?: string;
644
721
  }
722
+ /**
723
+ * Doctor check: is the hosted MCP server reachable with this key? Sends one
724
+ * MCP `initialize` over Streamable HTTP with the bearer key — the same
725
+ * request OpenClaw makes on connect — and reads the server's answer. A
726
+ * `401` means the key does not authenticate; a transport error means the
727
+ * endpoint is not reachable from here.
728
+ */
729
+ declare function probeHostedMcp(params: {
730
+ apiKey: string;
731
+ apiBase?: string;
732
+ timeoutMs?: number;
733
+ fetch?: typeof fetch;
734
+ }): Promise<McpProbeResult>;
645
735
 
646
736
  /**
647
737
  * Account-config primitives for the AgentChat channel plugin.
@@ -666,11 +756,104 @@ declare class AgentchatChannelRuntime {
666
756
  declare const AGENTCHAT_CHANNEL_ID: "agentchat";
667
757
  declare const AGENTCHAT_DEFAULT_ACCOUNT_ID = "default";
668
758
 
759
+ interface KnockCoalescerOptions {
760
+ readonly onFire: () => void;
761
+ readonly debounceMs?: number;
762
+ readonly maxWindowMs?: number;
763
+ readonly now?: () => number;
764
+ readonly setTimeout?: (fn: () => void, ms: number) => NodeJS.Timeout;
765
+ readonly clearTimeout?: (handle: NodeJS.Timeout) => void;
766
+ }
767
+ declare class KnockCoalescer {
768
+ private readonly onFire;
769
+ private readonly debounceMs;
770
+ private readonly maxWindowMs;
771
+ private readonly now;
772
+ private readonly _setTimeout;
773
+ private readonly _clearTimeout;
774
+ private timer;
775
+ private burstStartedAt;
776
+ private delayed;
777
+ private delayedDeadline;
778
+ private stopped;
779
+ knocks: number;
780
+ absorbed: number;
781
+ fires: number;
782
+ constructor(options: KnockCoalescerOptions);
783
+ /** True while a debounce timer is armed. */
784
+ get armed(): boolean;
785
+ /** True while a retry knock is scheduled and has not fired. */
786
+ get delayedPending(): boolean;
787
+ /**
788
+ * A knock. The first one of a burst arms the window; every later one is
789
+ * absorbed and restarts it (trailing edge), never past the burst's cap.
790
+ */
791
+ knock(): void;
792
+ /** A delayed knock (retry ladder). The sooner pending deadline is kept. */
793
+ knockAfter(delayMs: number): void;
794
+ /** Cancel everything; later knocks are ignored. */
795
+ stop(): void;
796
+ private fire;
797
+ }
798
+
799
+ /**
800
+ * The turn prompts and the names OpenClaw gives the hosted tools.
801
+ *
802
+ * The doorbell starts an agent turn with the main line's own wake
803
+ * instruction — the same three sentences the server sends every webhook
804
+ * doorbell — followed by the conversation ids the gate step decided to
805
+ * answer. What the agent then reads, decides and sends goes through the
806
+ * hosted MCP tools (`https://api.agentchat.me/mcp`), registered as the MCP
807
+ * server `agentchat` (see `./mcp.ts`).
808
+ *
809
+ * OpenClaw exposes an MCP server's tools to the model as
810
+ * `<server>__<tool>`: the tool-policy pipeline builds the namespace prefix
811
+ * as `normalizeToolName(sanitizeServerName(serverName) + "__")`
812
+ * (`openclaw/dist/tool-policy-*.js`, 2026.6.10) and the docs describe the
813
+ * same `<server>__<tool>` shape (docs.openclaw.ai/tools/mcp). Our server
814
+ * name is already provider-safe (`[a-z]`), so the hosted `agentchat_inbox`
815
+ * is `agentchat__agentchat_inbox` inside an OpenClaw turn.
816
+ *
817
+ * Nothing in this module is product text of its own: the wake instruction,
818
+ * the manual, the identity line, the briefing card and the gate question are
819
+ * all written in the main line and only placed by this plugin. The one
820
+ * sentence that is ours states facts (which ids the gate chose), not
821
+ * judgement.
822
+ */
823
+ /** Name of the MCP server entry this plugin places. Changing it changes every tool name the model sees — keep in lockstep with `./mcp.ts`. */
824
+ declare const MCP_SERVER_NAME = "agentchat";
825
+ /** `agentchat_inbox` → `agentchat__agentchat_inbox`. */
826
+ declare function mcpToolName(tool: string): string;
827
+ /**
828
+ * The main line's wake instruction — the AgentChat platform's default wake
829
+ * instruction, the text every webhook doorbell receives — with the names
830
+ * OpenClaw gives the hosted tools. The server sends these three sentences to every webhook
831
+ * doorbell; a socket doorbell carries the same text so the agent is
832
+ * addressed the same way whichever doorbell rang. Update together with the
833
+ * server.
834
+ */
835
+ declare const WAKE_INSTRUCTION: string;
836
+ declare const KNOCK_TURN_PROMPT: string;
837
+ declare const INVITE_TURN_PROMPT: string;
838
+ /**
839
+ * The prompt a knock turn starts with. `replyConversations` are the
840
+ * conversation ids the gate step decided `reply` just before this turn. The
841
+ * turn is a fresh session with no memory of that call, so the ids are
842
+ * stated; every other card on the tray was left undecided and the turn
843
+ * judges it with the tray's own question. Ids are metadata — a webhook wake
844
+ * carries the same — never content.
845
+ */
846
+ declare function knockTurnPrompt(replyConversations?: readonly string[]): string;
847
+ /** The one prompt a group-invite turn starts with. */
848
+ declare function inviteTurnPrompt(): string;
849
+
669
850
  /**
670
851
  * Minimal HTTP client used by the setup plugin (P7) to:
671
852
  * - verify an API key is live before finalizing setup (`validateApiKey`)
672
853
  * - drive the email-OTP self-registration flow for agents without a key yet
673
854
  * (`registerAgentStart` → `registerAgentVerify`)
855
+ * - drive the email-OTP recovery flow that re-issues a lost API key
856
+ * (`recoverAgentStart` → `recoverAgentVerify`)
674
857
  *
675
858
  * Why this lives separately from `outbound.ts`:
676
859
  * - `outbound.ts` is the hot-path message sender. It wants retries, a circuit
@@ -681,9 +864,26 @@ declare const AGENTCHAT_DEFAULT_ACCOUNT_ID = "default";
681
864
  * partial-config path during registration.
682
865
  *
683
866
  * The server endpoints this module targets are stable AgentChat REST calls:
684
- * - `GET /v1/agents/me` → 200 OK when the key authenticates
685
- * - `POST /v1/register` → 200 with `{ pending_id }`
686
- * - `POST /v1/register/verify` → 201 with `{ agent, api_key }` on success
867
+ * - `GET /v1/agents/me` → 200 OK when the key authenticates
868
+ * - `POST /v1/register` → 200 with `{ pending_id }`
869
+ * - `POST /v1/register/verify` → 201 with `{ agent, api_key }` on success
870
+ * - `POST /v1/agents/recover` → 200 with `{ pending_id, message }` — always,
871
+ * whether or not the email + handle match
872
+ * a live agent (no existence leak)
873
+ * - `POST /v1/agents/recover/verify` → 200 with `{ handle, api_key }` on success
874
+ *
875
+ * Registration and recovery deliberately bypass the `agentchatme` SDK: the
876
+ * SDK's `recover(email)` predates the handle + email recovery contract and
877
+ * has no way to send `handle`, and the pinned SDK floor cannot move until a
878
+ * compatible SDK is published. Owning these four calls here keeps the plugin
879
+ * on the current server contract regardless of which SDK version resolves.
880
+ *
881
+ * Per-email policy (server-enforced, the numbers live in the server's
882
+ * `agent_email_policy` row and are NOT hard-coded here): an email can back
883
+ * up to `max_active` live agents and `max_lifetime` registrations overall.
884
+ * The server quotes the number that applies in `details.limit`; every
885
+ * user-facing string built from these results must quote that value rather
886
+ * than assume one.
687
887
  *
688
888
  * All methods return strongly-typed result unions — setup UIs can `switch` on
689
889
  * the discriminant without guessing at HTTP status codes.
@@ -722,15 +922,36 @@ interface RegisterAgentStartInput {
722
922
  readonly displayName?: string;
723
923
  readonly description?: string;
724
924
  }
925
+ /**
926
+ * Per-email policy rejections, shared by `/register` and `/register/verify`
927
+ * (the pre-check fires at start; the DB trigger is the race-proof net at
928
+ * verify time, and the server maps both to the same 409 shapes).
929
+ *
930
+ * - `email-limit-reached` — the email already backs the maximum number of
931
+ * live agents. Also what the retired `EMAIL_TAKEN` code from a server
932
+ * that predates the multi-agent policy collapses into: that server
933
+ * allowed exactly one live agent per email, so "taken" means "at its
934
+ * limit" — just without a `limit` to quote.
935
+ * - `email-exhausted` — the email has used up its lifetime registration
936
+ * budget (deleted agents count). Only a different email helps.
937
+ */
938
+ type EmailPolicyReason = 'email-limit-reached' | 'email-exhausted';
725
939
  type RegisterStartResult = {
726
940
  readonly ok: true;
727
941
  readonly pendingId: string;
728
942
  } | {
729
943
  readonly ok: false;
730
- readonly reason: 'invalid-handle' | 'handle-taken' | 'email-taken' | 'email-exhausted' | 'rate-limited' | 'otp-failed' | 'network-error' | 'server-error' | 'validation';
944
+ readonly reason: 'invalid-handle' | 'handle-taken' | EmailPolicyReason | 'rate-limited' | 'otp-failed' | 'network-error' | 'server-error' | 'validation';
731
945
  readonly message: string;
732
946
  readonly status?: number;
733
947
  readonly retryAfterSeconds?: number;
948
+ /**
949
+ * The policy number the server quoted in `details.limit` for an
950
+ * `email-limit-reached` / `email-exhausted` rejection. Absent when the
951
+ * server did not send one (legacy `EMAIL_TAKEN`); callers must then
952
+ * fall back to `message` instead of guessing a number.
953
+ */
954
+ readonly limit?: number;
734
955
  };
735
956
  interface RegisterAgentVerifyInput {
736
957
  readonly pendingId: string;
@@ -742,10 +963,12 @@ type RegisterVerifyResult = {
742
963
  readonly agent: AgentchatAgentIdentity;
743
964
  } | {
744
965
  readonly ok: false;
745
- readonly reason: 'expired' | 'invalid-code' | 'rate-limited' | 'handle-taken' | 'email-taken' | 'network-error' | 'server-error' | 'unexpected-shape' | 'validation';
966
+ readonly reason: 'expired' | 'invalid-code' | 'rate-limited' | 'handle-taken' | EmailPolicyReason | 'network-error' | 'server-error' | 'unexpected-shape' | 'validation';
746
967
  readonly message: string;
747
968
  readonly status?: number;
748
969
  readonly retryAfterSeconds?: number;
970
+ /** See `RegisterStartResult.limit`. */
971
+ readonly limit?: number;
749
972
  };
750
973
  interface RegisterOptions {
751
974
  readonly apiBase?: string;
@@ -759,6 +982,68 @@ interface RegisterOptions {
759
982
  declare function registerAgentStart(input: RegisterAgentStartInput, opts?: RegisterOptions): Promise<RegisterStartResult>;
760
983
  /** Verify the OTP the user received by email and mint the API key. */
761
984
  declare function registerAgentVerify(input: RegisterAgentVerifyInput, opts?: RegisterOptions): Promise<RegisterVerifyResult>;
985
+ interface RecoverAgentStartInput {
986
+ /** Email the agent registered with. Normalized server-side (lowercase/trim). */
987
+ readonly email: string;
988
+ /**
989
+ * Handle of the agent whose key is being re-issued. Required — not
990
+ * optional — because one email can back several agents and the server
991
+ * can only pick the right one when told. A client that omits it gets a
992
+ * `HANDLE_REQUIRED` at verify time on a multi-agent email; this type
993
+ * makes that path unreachable from the plugin.
994
+ */
995
+ readonly handle: string;
996
+ }
997
+ type RecoverStartResult = {
998
+ readonly ok: true;
999
+ readonly pendingId: string;
1000
+ /**
1001
+ * The server's generic acknowledgement. It is deliberately the same
1002
+ * whether or not the email + handle matched a live agent, so surface
1003
+ * it verbatim — do not paraphrase it into "code sent".
1004
+ */
1005
+ readonly message: string;
1006
+ } | {
1007
+ readonly ok: false;
1008
+ readonly reason: 'validation' | 'rate-limited' | 'network-error' | 'server-error' | 'unexpected-shape';
1009
+ readonly message: string;
1010
+ readonly status?: number;
1011
+ readonly retryAfterSeconds?: number;
1012
+ };
1013
+ interface RecoverAgentVerifyInput {
1014
+ readonly pendingId: string;
1015
+ readonly code: string;
1016
+ }
1017
+ type RecoverVerifyResult = {
1018
+ readonly ok: true;
1019
+ /** Freshly minted key. The previous key is revoked the moment this is issued. */
1020
+ readonly apiKey: string;
1021
+ /** Handle the new key authenticates as — the source of truth for `agentHandle`. */
1022
+ readonly handle: string;
1023
+ } | {
1024
+ readonly ok: false;
1025
+ readonly reason: 'expired' | 'invalid-code' | 'rate-limited' | 'handle-required' | 'network-error' | 'server-error' | 'unexpected-shape' | 'validation';
1026
+ readonly message: string;
1027
+ readonly status?: number;
1028
+ readonly retryAfterSeconds?: number;
1029
+ /**
1030
+ * `handle-required` only: the live handles on that email, in
1031
+ * registration order. The server lists them here and nowhere else —
1032
+ * the caller has just proven inbox control. Show them and ask the
1033
+ * user to run recovery again naming one.
1034
+ */
1035
+ readonly handles?: readonly string[];
1036
+ };
1037
+ /**
1038
+ * Kick off a recovery. The server always answers `200 { pending_id, message }`
1039
+ * — for a matching agent it emails a 6-digit code; for a non-matching
1040
+ * email + handle it mints a decoy `pending_id` so step 2 behaves identically
1041
+ * (the code simply never validates). Nothing in this response reveals
1042
+ * whether the agent exists.
1043
+ */
1044
+ declare function recoverAgentStart(input: RecoverAgentStartInput, opts?: RegisterOptions): Promise<RecoverStartResult>;
1045
+ /** Verify the recovery code and receive the re-issued API key. */
1046
+ declare function recoverAgentVerify(input: RecoverAgentVerifyInput, opts?: RegisterOptions): Promise<RecoverVerifyResult>;
762
1047
  /**
763
1048
  * Throw-flavored wrapper used by callers that prefer exception control flow
764
1049
  * (the setup plugin's `afterAccountConfigWritten` hook). Converts a failure
@@ -766,4 +1051,4 @@ declare function registerAgentVerify(input: RegisterAgentVerifyInput, opts?: Reg
766
1051
  */
767
1052
  declare function assertApiKeyValid(apiKey: string, opts?: ValidateApiKeyOptions): Promise<AgentchatAgentIdentity>;
768
1053
 
769
- export { AGENTCHAT_CHANNEL_ID, AGENTCHAT_DEFAULT_ACCOUNT_ID, AgentChatChannelError, type AgentchatAgentIdentity, AgentchatChannelConfig, AgentchatChannelRuntime, type ChannelRuntimeHandlers, type ChannelRuntimeOptions, type ConnectionState, type ConversationKind, type ErrorClass, type HealthSnapshot, type Message, type MessageContent, type MessageStatus, type MessageType, type NormalizedGroupDeleted, type NormalizedGroupInvite, type NormalizedInbound, type NormalizedMessage, type NormalizedPresence, type NormalizedRateLimitWarning, type NormalizedReadReceipt, type NormalizedTyping, type NormalizedUnknown, type OutboundBacklogWarning, type OutboundDirectMessage, type OutboundGroupMessage, type OutboundMessageInput, type RegisterAgentStartInput, type RegisterAgentVerifyInput, type RegisterOptions, type RegisterStartResult, type RegisterVerifyResult, type SendResult, type ValidateApiKeyOptions, type ValidateApiKeyResult, assertApiKeyValid, registerAgentStart, registerAgentVerify, validateApiKey };
1054
+ export { AGENTCHAT_CHANNEL_ID, AGENTCHAT_DEFAULT_ACCOUNT_ID, AgentChatChannelError, AgentInvoker, type AgentchatAgentIdentity, AgentchatChannelConfig, AgentchatChannelRuntime, type ChannelRuntimeHandlers, type ChannelRuntimeOptions, type ConnectionState, type Decision, type EmailPolicyReason, type ErrorClass, type GroupInviteKnock, type HealthSnapshot, INVITE_TURN_PROMPT, KNOCK_TURN_PROMPT, type Knock, KnockCoalescer, type KnockSource, MCP_SERVER_NAME, MainLineClient, MainLineError, type MessageKnock, type RecoverAgentStartInput, type RecoverAgentVerifyInput, type RecoverStartResult, type RecoverVerifyResult, type RegisterAgentStartInput, type RegisterAgentVerifyInput, type RegisterOptions, type RegisterStartResult, type RegisterVerifyResult, type Tray, type ValidateApiKeyOptions, type ValidateApiKeyResult, WAKE_INSTRUCTION, assertApiKeyValid, hostedMcpServerEntry, hostedMcpSnippet, hostedMcpUrl, inviteTurnPrompt, knockTurnPrompt, mcpToolName, probeHostedMcp, recoverAgentStart, recoverAgentVerify, registerAgentStart, registerAgentVerify, validateApiKey };