@agentchatme/openclaw 0.7.8211111 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +193 -0
- package/README.md +174 -253
- package/RUNBOOK.md +86 -91
- package/SECURITY.md +36 -20
- package/dist/binding/agents-anchor.cjs +41 -53
- package/dist/binding/agents-anchor.cjs.map +1 -1
- package/dist/binding/agents-anchor.d.cts +61 -74
- package/dist/binding/agents-anchor.d.ts +61 -74
- package/dist/binding/agents-anchor.js +35 -53
- package/dist/binding/agents-anchor.js.map +1 -1
- package/dist/credentials/read-env.cjs +35 -1
- package/dist/credentials/read-env.cjs.map +1 -1
- package/dist/credentials/read-env.d.cts +31 -3
- package/dist/credentials/read-env.d.ts +31 -3
- package/dist/credentials/read-env.js +29 -2
- package/dist/credentials/read-env.js.map +1 -1
- package/dist/index.cjs +2116 -3607
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +543 -330
- package/dist/index.d.ts +543 -330
- package/dist/index.js +2100 -3607
- package/dist/index.js.map +1 -1
- package/dist/openclaw-layout.cjs +120 -0
- package/dist/openclaw-layout.cjs.map +1 -0
- package/dist/openclaw-layout.d.cts +64 -0
- package/dist/openclaw-layout.d.ts +64 -0
- package/dist/openclaw-layout.js +90 -0
- package/dist/openclaw-layout.js.map +1 -0
- package/dist/{setup-entry-BuDCZ44W.d.cts → setup-entry-DU51IFUF.d.cts} +58 -8
- package/dist/{setup-entry-BuDCZ44W.d.ts → setup-entry-DU51IFUF.d.ts} +58 -8
- package/dist/setup-entry.cjs +2084 -3605
- package/dist/setup-entry.cjs.map +1 -1
- package/dist/setup-entry.d.cts +1 -1
- package/dist/setup-entry.d.ts +1 -1
- package/dist/setup-entry.js +2081 -3603
- package/dist/setup-entry.js.map +1 -1
- package/openclaw.plugin.json +8 -2
- package/package.json +9 -6
- package/skills/agentchat/SKILL.md +741 -227
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AgentchatChannelConfig } from './setup-entry-
|
|
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-
|
|
1
|
+
import { A as AgentchatChannelConfig } from './setup-entry-DU51IFUF.cjs';
|
|
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.cjs';
|
|
3
3
|
export { hasAgentChatConfiguredState } from './configured-state.cjs';
|
|
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
|
|
22
|
-
*
|
|
23
|
-
*
|
|
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
|
-
/**
|
|
45
|
-
|
|
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
|
-
/**
|
|
49
|
-
|
|
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.
|
|
@@ -106,12 +98,16 @@ type UnixMillis = number;
|
|
|
106
98
|
* DEGRADED — heartbeat missed or send buffer full; still connected but impaired
|
|
107
99
|
* DRAINING — SIGTERM received; flush in-flight sends, then close
|
|
108
100
|
* CLOSED — terminal after clean shutdown
|
|
109
|
-
* AUTH_FAIL —
|
|
101
|
+
* AUTH_FAIL — the server rejected the key; the runtime retries slowly
|
|
102
|
+
* (keys get rotated back, accounts get reinstated)
|
|
110
103
|
*
|
|
111
104
|
* Invariants:
|
|
112
|
-
* -
|
|
113
|
-
*
|
|
114
|
-
*
|
|
105
|
+
* - CLOSED is the only terminal state: it is entered only by DRAIN_REQUESTED
|
|
106
|
+
* / DRAIN_COMPLETED (the caller's own stop), never by anything the
|
|
107
|
+
* network did. Every other state has a way back to CONNECTING.
|
|
108
|
+
* - From AUTH_FAIL, CONNECT is the slow retry and RECONFIGURED is the
|
|
109
|
+
* operator's "retry now"; both lead back to a fresh HELLO.
|
|
110
|
+
* - From CLOSED, every event is a no-op.
|
|
115
111
|
* - DRAINING has a deadline (ms timestamp) after which we force-close.
|
|
116
112
|
*/
|
|
117
113
|
|
|
@@ -153,8 +149,8 @@ type ConnectionState = {
|
|
|
153
149
|
* DEGRADED on `ping.timeoutMs` miss, then force-reconnect.
|
|
154
150
|
* - Schedule reconnect with exponential backoff + ±`jitterRatio` jitter
|
|
155
151
|
* per `reconnect.*` config. Thundering-herd-safe across a fleet.
|
|
156
|
-
* - Emit typed events upwards (`inboundFrame`, `stateChanged`, `error
|
|
157
|
-
* so the
|
|
152
|
+
* - Emit typed events upwards (`inboundFrame`, `stateChanged`, `error`,
|
|
153
|
+
* `authenticated`) so the runtime can turn frames into knocks.
|
|
158
154
|
*
|
|
159
155
|
* Intentional design choices:
|
|
160
156
|
* - Uses the `ws` package directly (not `globalThis.WebSocket`) because
|
|
@@ -163,9 +159,20 @@ type ConnectionState = {
|
|
|
163
159
|
* (Fly, Render, Vercel functions, Lambda) is Node.
|
|
164
160
|
* - Authenticates via HELLO frame (`{type: "hello", api_key}`), never via
|
|
165
161
|
* URL query string. Keeps the key out of access logs and Referers.
|
|
166
|
-
* - `
|
|
167
|
-
*
|
|
168
|
-
*
|
|
162
|
+
* - Advertises the `ack` capability in HELLO and NEVER acknowledges. With
|
|
163
|
+
* the capability negotiated the server keeps every envelope `stored`
|
|
164
|
+
* until an ack arrives (WS Delivery-Ack Protocol v1); none ever does
|
|
165
|
+
* from here — a verdict recorded by the gate, or a send by the agent,
|
|
166
|
+
* is what settles delivery. There is no code path in this module that
|
|
167
|
+
* can emit a frame other than HELLO: delivery is judged, never
|
|
168
|
+
* confirmed by the transport.
|
|
169
|
+
* - The client never gives up on its own. Only `stop()` ends it. A close
|
|
170
|
+
* the client itself initiated (hello-ack timeout, ping timeout, its own
|
|
171
|
+
* drain) is never read as a verdict from the server; a server-originated
|
|
172
|
+
* auth close enters `AUTH_FAIL` and retries slowly, because keys get
|
|
173
|
+
* rotated back and accounts get reinstated. A long outage widens the
|
|
174
|
+
* backoff cap to `RECONNECT_LONG_OUTAGE_BACKOFF_MS` and logs one error
|
|
175
|
+
* line so an operator sees it without a log flood.
|
|
169
176
|
* - Frame parsing is defensive: malformed JSON, unknown `type`, missing
|
|
170
177
|
* payload — all classified as `validation` errors (non-terminal for
|
|
171
178
|
* the connection, but dropped with a metric + log).
|
|
@@ -181,19 +188,13 @@ interface InboundFrame {
|
|
|
181
188
|
readonly receivedAt: UnixMillis;
|
|
182
189
|
readonly raw: unknown;
|
|
183
190
|
}
|
|
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
191
|
interface WsClientEvents {
|
|
191
192
|
stateChanged: (next: ConnectionState, prev: ConnectionState) => void;
|
|
192
193
|
inboundFrame: (frame: InboundFrame) => void;
|
|
193
194
|
error: (error: AgentChatChannelError) => void;
|
|
194
|
-
/** Fired once per `hello.ok` —
|
|
195
|
+
/** Fired once per `hello.ok` — the runtime turns it into the connect knock. */
|
|
195
196
|
authenticated: (at: UnixMillis) => void;
|
|
196
|
-
/** Fired
|
|
197
|
+
/** Fired once the client reached CLOSED — only ever after `stop()`. */
|
|
197
198
|
closed: () => void;
|
|
198
199
|
}
|
|
199
200
|
interface WsClientOptions {
|
|
@@ -242,6 +243,16 @@ declare class AgentchatWsClient {
|
|
|
242
243
|
private state;
|
|
243
244
|
private ws;
|
|
244
245
|
private attempt;
|
|
246
|
+
private _ackNegotiated;
|
|
247
|
+
/**
|
|
248
|
+
* Set by `closeSocket()` before it closes the current socket, read and
|
|
249
|
+
* cleared by `handleClose()`. A close this client asked for says nothing
|
|
250
|
+
* about the server, whatever code travelled with it.
|
|
251
|
+
*/
|
|
252
|
+
private closeInitiatedLocally;
|
|
253
|
+
/** One error line per long outage / per run of rejected keys, then debug. */
|
|
254
|
+
private longOutageAnnounced;
|
|
255
|
+
private authFailAnnounced;
|
|
245
256
|
private helloAckTimer;
|
|
246
257
|
private pingTimer;
|
|
247
258
|
private pongTimer;
|
|
@@ -252,17 +263,16 @@ declare class AgentchatWsClient {
|
|
|
252
263
|
/** Current connection state. Read-only from the caller's perspective. */
|
|
253
264
|
getState(): ConnectionState;
|
|
254
265
|
/**
|
|
255
|
-
*
|
|
256
|
-
*
|
|
257
|
-
*
|
|
266
|
+
* True when the last `hello.ok` echoed the `ack` capability: the server
|
|
267
|
+
* keeps envelopes `stored` until acknowledged — and this client never
|
|
268
|
+
* acknowledges. False against a legacy server (envelopes marked on push).
|
|
258
269
|
*/
|
|
259
|
-
|
|
270
|
+
get ackNegotiated(): boolean;
|
|
260
271
|
/**
|
|
261
|
-
*
|
|
262
|
-
*
|
|
263
|
-
* outbound adapter (P4) rather than drop here.
|
|
272
|
+
* Kick off connection. No-op if already connecting, authenticating, ready,
|
|
273
|
+
* or waiting out a backoff / auth retry. Throws only on `CLOSED`.
|
|
264
274
|
*/
|
|
265
|
-
|
|
275
|
+
start(): void;
|
|
266
276
|
/**
|
|
267
277
|
* Request a graceful drain. The caller-supplied deadline is a Unix-ms
|
|
268
278
|
* timestamp; after it passes, the socket is force-closed regardless of
|
|
@@ -270,9 +280,9 @@ declare class AgentchatWsClient {
|
|
|
270
280
|
*/
|
|
271
281
|
stop(deadline?: UnixMillis): void;
|
|
272
282
|
/**
|
|
273
|
-
* Signal that operator has rotated the API key
|
|
274
|
-
*
|
|
275
|
-
*
|
|
283
|
+
* Signal that the operator has rotated the API key: leave AUTH_FAIL and
|
|
284
|
+
* retry now instead of waiting for the slow retry timer. A no-op in every
|
|
285
|
+
* other state (the client is already connecting or connected).
|
|
276
286
|
*/
|
|
277
287
|
reconfigured(): void;
|
|
278
288
|
on<E extends keyof WsClientEvents>(event: E, handler: Listener<E>): () => void;
|
|
@@ -283,7 +293,14 @@ declare class AgentchatWsClient {
|
|
|
283
293
|
private extractReason;
|
|
284
294
|
private extractPayload;
|
|
285
295
|
private handleHelloOk;
|
|
296
|
+
/** The server answered HELLO with a rejection frame (not a close). */
|
|
286
297
|
private handleAuthRejected;
|
|
298
|
+
/**
|
|
299
|
+
* The server rejected this key. AUTH_FAIL is not the end: retry a fresh
|
|
300
|
+
* HELLO every `AUTH_RETRY_INTERVAL_MS` (jittered). The first rejection in a
|
|
301
|
+
* run logs at error so an operator sees it; the following ones at debug.
|
|
302
|
+
*/
|
|
303
|
+
private enterAuthFail;
|
|
287
304
|
private handleClose;
|
|
288
305
|
private closeSocket;
|
|
289
306
|
private startHeartbeat;
|
|
@@ -291,7 +308,16 @@ declare class AgentchatWsClient {
|
|
|
291
308
|
private sendPing;
|
|
292
309
|
private handlePong;
|
|
293
310
|
private scheduleReconnect;
|
|
311
|
+
/** AUTH_FAIL's own cadence: a fresh HELLO every AUTH_RETRY_INTERVAL_MS, jittered. */
|
|
312
|
+
private scheduleAuthRetry;
|
|
313
|
+
private clearReconnectTimer;
|
|
294
314
|
private computeReconnectDelay;
|
|
315
|
+
/**
|
|
316
|
+
* Symmetric ±`jitterRatio`. Thundering-herd-safe: a fleet that all drops
|
|
317
|
+
* at the same instant re-enters the connect queue spread across
|
|
318
|
+
* ms * [1-jitterRatio, 1+jitterRatio].
|
|
319
|
+
*/
|
|
320
|
+
private jittered;
|
|
295
321
|
private scheduleDrainDeadline;
|
|
296
322
|
/**
|
|
297
323
|
* Called by upper layers when their pending work has fully drained, to
|
|
@@ -304,275 +330,72 @@ declare class AgentchatWsClient {
|
|
|
304
330
|
}
|
|
305
331
|
|
|
306
332
|
/**
|
|
307
|
-
*
|
|
333
|
+
* What the doorbell reads from a server frame — and what it does not.
|
|
308
334
|
*
|
|
309
|
-
*
|
|
310
|
-
*
|
|
311
|
-
*
|
|
312
|
-
*
|
|
313
|
-
*
|
|
314
|
-
*
|
|
315
|
-
*
|
|
316
|
-
*
|
|
317
|
-
*
|
|
318
|
-
*
|
|
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.
|
|
335
|
+
* A `message.new` frame means *the tray changed*. The doorbell reads only
|
|
336
|
+
* the sender (to skip the echo of its own sends) and the ids (for the log
|
|
337
|
+
* line). The body is never looked at: the agent reads it through the hosted
|
|
338
|
+
* tools inside its turn. There is no schema for message content here
|
|
339
|
+
* because nothing here consumes it.
|
|
340
|
+
*
|
|
341
|
+
* A `group.invite.received` frame is the second knock kind. Invites are not
|
|
342
|
+
* on the tray and are not gated; the doorbell reads the ids and names it
|
|
343
|
+
* logs and hands the invite to the invoker, which starts one turn with a
|
|
344
|
+
* fixed prompt.
|
|
330
345
|
*/
|
|
331
346
|
|
|
332
|
-
|
|
333
|
-
interface NormalizedMessage {
|
|
347
|
+
interface MessageKnock {
|
|
334
348
|
readonly kind: 'message';
|
|
335
|
-
|
|
336
|
-
readonly conversationId: string;
|
|
337
|
-
/** Sender handle. */
|
|
349
|
+
/** Bare, lowercase sender handle (`@` stripped); `''` when the frame carried none. */
|
|
338
350
|
readonly sender: string;
|
|
339
351
|
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
352
|
readonly conversationId: string;
|
|
377
|
-
readonly reader: string;
|
|
378
|
-
readonly throughSeq: number;
|
|
379
|
-
readonly at: string | null;
|
|
380
|
-
readonly receivedAt: UnixMillis;
|
|
381
353
|
}
|
|
382
|
-
interface
|
|
383
|
-
readonly kind: 'typing';
|
|
384
|
-
readonly action: 'start' | 'stop';
|
|
385
|
-
readonly conversationKind: ConversationKind;
|
|
386
|
-
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
|
-
}
|
|
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 {
|
|
354
|
+
interface GroupInviteKnock {
|
|
408
355
|
readonly kind: 'group-invite';
|
|
409
356
|
readonly inviteId: string;
|
|
410
357
|
readonly groupId: string;
|
|
411
358
|
readonly groupName: string;
|
|
412
|
-
readonly groupDescription: string | null;
|
|
413
|
-
readonly groupAvatarUrl: string | null;
|
|
414
|
-
readonly groupMemberCount: number;
|
|
415
359
|
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
|
-
}
|
|
470
|
-
|
|
471
|
-
/**
|
|
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
360
|
}
|
|
361
|
+
type Knock = MessageKnock | GroupInviteKnock;
|
|
537
362
|
|
|
538
363
|
/**
|
|
539
|
-
* AgentChat channel runtime —
|
|
540
|
-
* transport (P2), inbound normalizer (P3), and outbound adapter (P4)
|
|
541
|
-
* together. This is the surface an OpenClaw channel binding consumes.
|
|
364
|
+
* AgentChat channel runtime — the socket as a knock.
|
|
542
365
|
*
|
|
543
|
-
*
|
|
544
|
-
*
|
|
545
|
-
*
|
|
546
|
-
*
|
|
547
|
-
* -
|
|
548
|
-
*
|
|
549
|
-
*
|
|
550
|
-
*
|
|
551
|
-
*
|
|
552
|
-
*
|
|
553
|
-
*
|
|
554
|
-
*
|
|
555
|
-
*
|
|
556
|
-
*
|
|
557
|
-
*
|
|
558
|
-
*
|
|
559
|
-
*
|
|
560
|
-
*
|
|
366
|
+
* One instance per (channelId, accountId). It owns the WebSocket transport
|
|
367
|
+
* (`AgentchatWsClient`: HELLO, state machine, heartbeat, reconnect) and turns
|
|
368
|
+
* what arrives on it into knocks for the doorbell's invoker:
|
|
369
|
+
*
|
|
370
|
+
* - `message.new` → `onKnock('message')` — after reading only
|
|
371
|
+
* the sender (to skip our own echo) and the
|
|
372
|
+
* ids for the log line. The body is never
|
|
373
|
+
* looked at; the agent reads it through the
|
|
374
|
+
* hosted tools inside its turn.
|
|
375
|
+
* - every successful HELLO → `onKnock('connect')` — whatever landed
|
|
376
|
+
* while the socket was down is on the tray.
|
|
377
|
+
* - `group.invite.received` → `onGroupInvite(invite)` — the second knock
|
|
378
|
+
* kind; not on the tray, not gated.
|
|
379
|
+
*
|
|
380
|
+
* Nothing is parsed into message shapes, nothing is acknowledged, nothing is
|
|
381
|
+
* sent: the socket advertises the `ack` capability so the server keeps every
|
|
382
|
+
* envelope `stored` until a verdict or a send settles it, and this runtime
|
|
383
|
+
* has no code path that could emit an ack frame (`ws-client.ts`). Delivery
|
|
384
|
+
* is judged by the agent, never by the transport.
|
|
561
385
|
*/
|
|
562
386
|
|
|
387
|
+
type KnockSource = 'message' | 'connect';
|
|
563
388
|
interface ChannelRuntimeHandlers {
|
|
564
|
-
/**
|
|
565
|
-
|
|
566
|
-
/**
|
|
567
|
-
|
|
568
|
-
/** Called on state transitions — surface to gateway for health/UI. */
|
|
389
|
+
/** A knock: the tray may have changed. `source` is for the log line only. */
|
|
390
|
+
onKnock?: (source: KnockSource) => void;
|
|
391
|
+
/** The second knock kind. */
|
|
392
|
+
onGroupInvite?: (invite: GroupInviteKnock) => void;
|
|
393
|
+
/** Called on state transitions — surface to the gateway for health/UI. */
|
|
569
394
|
onStateChanged?: (next: ConnectionState, prev: ConnectionState) => void;
|
|
570
|
-
/** Called once per successful
|
|
395
|
+
/** Called once per successful HELLO (initial + every reconnect), before the connect knock. */
|
|
571
396
|
onAuthenticated?: (at: UnixMillis) => void;
|
|
572
397
|
/** Called on every closed/unreachable situation worth observing. */
|
|
573
398
|
onError?: (error: AgentChatChannelError) => void;
|
|
574
|
-
/** Called when the server signals a backlog warning on an outbound send. */
|
|
575
|
-
onBacklogWarning?: (warning: OutboundBacklogWarning) => void;
|
|
576
399
|
}
|
|
577
400
|
interface ChannelRuntimeOptions {
|
|
578
401
|
readonly config: AgentchatChannelConfig;
|
|
@@ -581,67 +404,366 @@ interface ChannelRuntimeOptions {
|
|
|
581
404
|
readonly logger?: Logger;
|
|
582
405
|
/** Pre-built metrics recorder — if absent, uses no-op. */
|
|
583
406
|
readonly metrics?: MetricsRecorder;
|
|
584
|
-
readonly fetch?: typeof fetch;
|
|
585
407
|
/** Provided by tests. */
|
|
586
408
|
readonly webSocketCtor?: ConstructorParameters<typeof AgentchatWsClient>[0]['webSocketCtor'];
|
|
587
409
|
readonly now?: () => UnixMillis;
|
|
588
410
|
readonly random?: () => number;
|
|
589
|
-
readonly sleep?: (ms: number) => Promise<void>;
|
|
590
411
|
}
|
|
591
412
|
interface HealthSnapshot {
|
|
592
413
|
readonly state: ConnectionState;
|
|
593
414
|
readonly authenticated: boolean;
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
readonly
|
|
415
|
+
/** Whether the server echoed the `ack` capability on the last HELLO (envelopes stay `stored` until judged). */
|
|
416
|
+
readonly ackNegotiated: boolean;
|
|
417
|
+
readonly counters: {
|
|
418
|
+
readonly frames: number;
|
|
419
|
+
readonly selfFiltered: number;
|
|
420
|
+
readonly knocks: number;
|
|
421
|
+
readonly invites: number;
|
|
598
422
|
};
|
|
599
423
|
}
|
|
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
424
|
declare class AgentchatChannelRuntime {
|
|
607
425
|
private readonly config;
|
|
608
426
|
private readonly handlers;
|
|
609
427
|
private readonly logger;
|
|
610
|
-
private readonly metrics;
|
|
611
428
|
private readonly ws;
|
|
612
|
-
private readonly
|
|
429
|
+
private readonly selfHandle;
|
|
613
430
|
private readonly now;
|
|
614
431
|
private started;
|
|
615
432
|
private authenticated;
|
|
616
433
|
private stopPromise;
|
|
434
|
+
private frames;
|
|
435
|
+
private selfFiltered;
|
|
436
|
+
private knocks;
|
|
437
|
+
private invites;
|
|
438
|
+
private authenticatedAt;
|
|
617
439
|
constructor(opts: ChannelRuntimeOptions);
|
|
618
440
|
/** Open the transport. Idempotent — subsequent calls are no-ops. */
|
|
619
441
|
start(): void;
|
|
442
|
+
/** Graceful shutdown: close the socket (nothing is in flight — the runtime sends nothing). */
|
|
443
|
+
stop(deadlineMs?: UnixMillis): Promise<void>;
|
|
444
|
+
/** Operator rotated the API key — leave AUTH_FAIL so the next `start()` can retry. */
|
|
445
|
+
reconfigured(): void;
|
|
446
|
+
getHealth(): HealthSnapshot;
|
|
447
|
+
private bindWsEvents;
|
|
448
|
+
private dispatchFrame;
|
|
449
|
+
private knock;
|
|
450
|
+
/** A failing handler never takes the socket down; the next frame knocks again and the tray keeps the cards. */
|
|
451
|
+
private guard;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** The tray, as the server sends it. Only the fields the doorbell reads are typed; the rest passes through. */
|
|
455
|
+
interface Tray {
|
|
456
|
+
readonly you?: unknown;
|
|
457
|
+
readonly question?: unknown;
|
|
458
|
+
readonly categories?: unknown;
|
|
459
|
+
readonly conversations?: unknown;
|
|
460
|
+
readonly deferred?: unknown;
|
|
461
|
+
readonly truncated?: unknown;
|
|
462
|
+
readonly [key: string]: unknown;
|
|
463
|
+
}
|
|
464
|
+
type Decision = 'reply' | 'dismiss' | 'defer';
|
|
465
|
+
interface RecordDecisionInput {
|
|
466
|
+
readonly decision: Decision;
|
|
467
|
+
readonly category?: string | undefined;
|
|
468
|
+
readonly throughMessageId?: string | undefined;
|
|
469
|
+
readonly deferSeconds?: number | undefined;
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* A main-line call failed: transport error or a non-2xx answer.
|
|
473
|
+
* `status` is the HTTP status (`undefined` for transport failures); `code`
|
|
474
|
+
* is the server's error code when the body carried one.
|
|
475
|
+
*/
|
|
476
|
+
declare class MainLineError extends Error {
|
|
477
|
+
readonly status: number | undefined;
|
|
478
|
+
readonly code: string | undefined;
|
|
479
|
+
constructor(message: string, options?: {
|
|
480
|
+
status?: number;
|
|
481
|
+
code?: string;
|
|
482
|
+
cause?: unknown;
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
interface MainLineClientOptions {
|
|
486
|
+
readonly apiKey: string;
|
|
487
|
+
readonly apiBase: string;
|
|
488
|
+
readonly timeoutMs?: number;
|
|
489
|
+
/** Test seam. Production uses the global `fetch`. */
|
|
490
|
+
readonly fetch?: typeof fetch;
|
|
491
|
+
}
|
|
492
|
+
declare class MainLineClient {
|
|
493
|
+
private readonly apiKey;
|
|
494
|
+
private readonly apiBase;
|
|
495
|
+
private readonly timeoutMs;
|
|
496
|
+
private readonly fetchImpl;
|
|
497
|
+
constructor(options: MainLineClientOptions);
|
|
620
498
|
/**
|
|
621
|
-
*
|
|
622
|
-
*
|
|
623
|
-
*
|
|
499
|
+
* `GET /v1/inbox` — the briefing cards plus the gate question, returned as
|
|
500
|
+
* the server sent them (`you`, `question`, `categories`, `conversations`,
|
|
501
|
+
* `deferred`, `truncated`, and any field a newer server adds). Marks
|
|
502
|
+
* nothing delivered.
|
|
624
503
|
*/
|
|
625
|
-
|
|
626
|
-
|
|
504
|
+
inbox(params?: {
|
|
505
|
+
waitMs?: number;
|
|
506
|
+
limit?: number;
|
|
507
|
+
}): Promise<Tray>;
|
|
627
508
|
/**
|
|
628
|
-
*
|
|
629
|
-
*
|
|
509
|
+
* `POST /v1/conversations/{id}/decisions` — record one verdict. The server
|
|
510
|
+
* validates `decision`, `category` and `defer_seconds` against its own
|
|
511
|
+
* taxonomy; this client passes them through and raises `MainLineError`
|
|
512
|
+
* (`status` 400) when the server rejects a value, so the caller can retry
|
|
513
|
+
* with less.
|
|
630
514
|
*/
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
515
|
+
recordDecision(conversationId: string, input: RecordDecisionInput): Promise<Record<string, unknown>>;
|
|
516
|
+
private request;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/**
|
|
520
|
+
* The gate step: the agent's own model answers the server's question about the server's cards.
|
|
521
|
+
*
|
|
522
|
+
* Code we keep, brain we don't
|
|
523
|
+
* ────────────────────────────
|
|
524
|
+
* Every word the model reads here comes from the main line: the gate question
|
|
525
|
+
* (`tray.question`) and the briefing cards (`tray.conversations`) are passed
|
|
526
|
+
* through exactly as `GET /v1/inbox` returned them. This module adds a
|
|
527
|
+
* two-line wrapper asking for strict JSON, parses the answer, and records the
|
|
528
|
+
* verdicts with `POST /v1/conversations/{id}/decisions`. No wording of its
|
|
529
|
+
* own, no category list of its own (categories are offered only when the
|
|
530
|
+
* tray carries them), no pace or relationship arithmetic — the server
|
|
531
|
+
* computes, the agent's model judges, the doorbell carries.
|
|
532
|
+
*
|
|
533
|
+
* What gets recorded
|
|
534
|
+
* ──────────────────
|
|
535
|
+
* `dismiss` and `defer` are posted; a recorded verdict settles delivery for
|
|
536
|
+
* what it covers, so the sender's tick is honest and the conversation leaves
|
|
537
|
+
* the tray. `reply` is deliberately *not* posted: the send is the reply
|
|
538
|
+
* verdict, and posting it would settle the envelopes and take the card off
|
|
539
|
+
* the tray before the agent's turn has read it. Cards decided `reply` stay
|
|
540
|
+
* on the tray; the turn that follows reads exactly those with the hosted
|
|
541
|
+
* `agentchat_inbox` tool. A model that still answers the legacy spelling
|
|
542
|
+
* `no_reply` is understood and posted as `dismiss`.
|
|
543
|
+
*
|
|
544
|
+
* Failure policy
|
|
545
|
+
* ──────────────
|
|
546
|
+
* Fail closed by default: when the model cannot be reached or answers nothing
|
|
547
|
+
* usable, nothing is posted and no turn starts. The envelopes stay `stored`,
|
|
548
|
+
* the tray keeps the cards, and the invoker re-knocks on its own ladder. With
|
|
549
|
+
* `AGENTCHAT_REPLY_GATE_FAIL_OPEN=1` a failed gate starts the turn anyway and
|
|
550
|
+
* the agent judges from the tray inside the turn.
|
|
551
|
+
*/
|
|
552
|
+
|
|
553
|
+
interface Verdict {
|
|
554
|
+
readonly conversationId: string;
|
|
555
|
+
readonly decision: Decision;
|
|
556
|
+
readonly category?: string | undefined;
|
|
557
|
+
readonly deferSeconds?: number | undefined;
|
|
558
|
+
}
|
|
559
|
+
/** Returns the model's raw text. Injectable so tests never reach a provider. */
|
|
560
|
+
type GateCaller = (params: {
|
|
561
|
+
readonly systemPrompt: string;
|
|
562
|
+
readonly userContent: string;
|
|
563
|
+
readonly maxTokens: number;
|
|
564
|
+
readonly timeoutMs: number;
|
|
565
|
+
}) => Promise<string>;
|
|
566
|
+
type GateSource = 'llm' | 'empty' | 'fail_closed' | 'fail_open' | 'disabled';
|
|
567
|
+
interface GateResult {
|
|
568
|
+
/** How the cycle ended; see the module header. */
|
|
569
|
+
readonly source: GateSource;
|
|
570
|
+
readonly cards: number;
|
|
571
|
+
readonly verdicts: readonly Verdict[];
|
|
572
|
+
readonly undecided: readonly string[];
|
|
573
|
+
readonly replyConversations: readonly string[];
|
|
574
|
+
readonly posted: number;
|
|
575
|
+
readonly postFailures: number;
|
|
576
|
+
readonly truncated: boolean;
|
|
577
|
+
readonly latencyMs: number;
|
|
578
|
+
readonly failure: string | null;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/**
|
|
582
|
+
* Where the doorbell meets OpenClaw's agent runtime.
|
|
583
|
+
*
|
|
584
|
+
* Two things only, both on the `PluginRuntime` OpenClaw hands a channel entry
|
|
585
|
+
* through `defineChannelPluginEntry({ setRuntime })`:
|
|
586
|
+
*
|
|
587
|
+
* 1. **The gate call** — `runtime.llm.complete({ systemPrompt, messages,
|
|
588
|
+
* maxTokens, temperature, purpose })` runs one tool-free completion on the
|
|
589
|
+
* agent's own configured model and credentials (`LlmCompleteParams`,
|
|
590
|
+
* `plugin-sdk/types`; docs.openclaw.ai/plugins/sdk-runtime/models). Without
|
|
591
|
+
* an `agentId` OpenClaw uses the ambient default agent; passing one is an
|
|
592
|
+
* OVERRIDE that OpenClaw 2026.10.9 rejects with
|
|
593
|
+
* `LLM_COMPLETION_NOT_AUTHORIZED` unless the operator set
|
|
594
|
+
* `plugins.entries.agentchat.llm.allowAgentIdOverride: true`. The doorbell
|
|
595
|
+
* therefore passes `agentId` only when the account is genuinely routed to
|
|
596
|
+
* a non-default agent (`agentIdOverride`), and the wizard / doctor write
|
|
597
|
+
* the opt-in in that case. The judgement is the agent's; the platform
|
|
598
|
+
* computes, it never judges.
|
|
599
|
+
*
|
|
600
|
+
* 2. **The turn** — `runtime.subagent.run({ sessionKey, message, lane,
|
|
601
|
+
* deliver: false })` admits one agent run with the fixed prompt as its
|
|
602
|
+
* message and no delivery of its final text (`SubagentRunParams`;
|
|
603
|
+
* docs.openclaw.ai/plugins/sdk-runtime/background-work — the same shape
|
|
604
|
+
* OpenClaw's own background features use with `deliver: false`). The
|
|
605
|
+
* turn's output is never routed anywhere: the agent's only way to say
|
|
606
|
+
* something on AgentChat is the hosted `agentchat__agentchat_send_message`
|
|
607
|
+
* tool during the turn. `runtime.subagent.waitForRun` bounds how long the
|
|
608
|
+
* invoker waits before it may start the next cycle; it never cancels the
|
|
609
|
+
* run.
|
|
610
|
+
*
|
|
611
|
+
* The agent id is resolved the way OpenClaw routes inbound for this channel
|
|
612
|
+
* (`channelRuntime.routing.resolveAgentRoute`), so the doorbell wakes the
|
|
613
|
+
* agent the operator bound to the account; `main` when nothing is bound.
|
|
614
|
+
*/
|
|
615
|
+
|
|
616
|
+
interface TurnRequest {
|
|
617
|
+
readonly sessionKey: string;
|
|
618
|
+
readonly prompt: string;
|
|
619
|
+
readonly lane: string;
|
|
620
|
+
}
|
|
621
|
+
interface TurnOutcome {
|
|
622
|
+
readonly ran: boolean;
|
|
623
|
+
readonly runId?: string;
|
|
624
|
+
readonly status?: string;
|
|
625
|
+
readonly error?: string;
|
|
626
|
+
}
|
|
627
|
+
/** Starts one agent turn and waits for it (bounded). Injectable so the invoker is testable without OpenClaw. */
|
|
628
|
+
type TurnRunner = (request: TurnRequest) => Promise<TurnOutcome>;
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* Knock → gate → turn. The only path from the socket to the agent.
|
|
632
|
+
*
|
|
633
|
+
* What happens on a knock
|
|
634
|
+
* ───────────────────────
|
|
635
|
+
* 1. **Coalesce.** Frames inside a short window become one knock
|
|
636
|
+
* (`KnockCoalescer`). A group waking up is one cycle, not twenty.
|
|
637
|
+
* 2. **Read the tray.** `GET /v1/inbox?wait_ms=0&limit=50` — the server's
|
|
638
|
+
* briefing cards and its gate question, as it built them.
|
|
639
|
+
* 3. **Gate.** The agent's own model answers the question per card
|
|
640
|
+
* (`./gate.ts`); `dismiss` / `defer` verdicts are recorded on the server,
|
|
641
|
+
* which settles those conversations. `reply` cards stay on the tray.
|
|
642
|
+
* 4. **Turn.** If anything was decided `reply`, start ONE OpenClaw agent turn
|
|
643
|
+
* with the fixed prompt (`./turn.ts`). The agent reads and answers through
|
|
644
|
+
* the hosted MCP tools; the send is its verdict. The turn's final text is
|
|
645
|
+
* discarded — nothing is auto-routed anywhere.
|
|
646
|
+
*
|
|
647
|
+
* One cycle at a time per account: a knock that lands while a cycle runs is
|
|
648
|
+
* remembered and runs once the cycle ends (the tray is re-read, so whatever
|
|
649
|
+
* the earlier knock announced is covered). A cycle that could not complete —
|
|
650
|
+
* model unreachable, server error, verdicts rejected — re-knocks itself on a
|
|
651
|
+
* local ladder (1 m, 5 m, 30 m) because a connected socket gets no re-ring
|
|
652
|
+
* from the server; the cards wait on the tray meanwhile. One outage climbs
|
|
653
|
+
* the ladder one rung: a retry already on its way is never replaced by a
|
|
654
|
+
* later one.
|
|
655
|
+
*
|
|
656
|
+
* Group invites are a second knock kind: not on the tray, not gated, one turn
|
|
657
|
+
* each with the fixed invite prompt, serialized on the same worker.
|
|
658
|
+
*/
|
|
659
|
+
|
|
660
|
+
interface AgentInvokerOptions {
|
|
661
|
+
readonly accountId: string;
|
|
662
|
+
readonly agentId: string;
|
|
663
|
+
readonly mainLine: MainLineClient;
|
|
664
|
+
readonly gateCaller: GateCaller;
|
|
665
|
+
readonly turnRunner: TurnRunner;
|
|
666
|
+
readonly logger: Logger;
|
|
667
|
+
readonly gateEnabled?: boolean;
|
|
668
|
+
readonly gateFailOpen?: boolean;
|
|
669
|
+
readonly gateTimeoutMs?: number;
|
|
670
|
+
readonly debounceMs?: number;
|
|
671
|
+
readonly retryLadderMs?: readonly number[];
|
|
672
|
+
readonly now?: () => number;
|
|
673
|
+
readonly setTimeout?: (fn: () => void, ms: number) => NodeJS.Timeout;
|
|
674
|
+
readonly clearTimeout?: (handle: NodeJS.Timeout) => void;
|
|
675
|
+
}
|
|
676
|
+
interface InvokerCounters {
|
|
677
|
+
readonly cycles: number;
|
|
678
|
+
readonly turns: number;
|
|
679
|
+
readonly inviteTurns: number;
|
|
680
|
+
readonly knocks: number;
|
|
681
|
+
readonly absorbed: number;
|
|
682
|
+
readonly retryRung: number;
|
|
683
|
+
}
|
|
684
|
+
declare class AgentInvoker {
|
|
685
|
+
private readonly accountId;
|
|
686
|
+
private readonly agentId;
|
|
687
|
+
private readonly mainLine;
|
|
688
|
+
private readonly gateCaller;
|
|
689
|
+
private readonly turnRunner;
|
|
690
|
+
private readonly logger;
|
|
691
|
+
private readonly gateEnabled;
|
|
692
|
+
private readonly gateFailOpen;
|
|
693
|
+
private readonly gateTimeoutMs;
|
|
694
|
+
private readonly ladder;
|
|
695
|
+
private readonly now;
|
|
696
|
+
private readonly coalescer;
|
|
697
|
+
private cycleDue;
|
|
698
|
+
private running;
|
|
699
|
+
private stopped;
|
|
700
|
+
private readonly invites;
|
|
701
|
+
private readonly seenInvites;
|
|
702
|
+
private retryRung;
|
|
703
|
+
cycles: number;
|
|
704
|
+
turns: number;
|
|
705
|
+
inviteTurns: number;
|
|
706
|
+
constructor(options: AgentInvokerOptions);
|
|
707
|
+
/** A knock from the socket (a frame, a connect) or any other source. Coalesced, then cycled. */
|
|
708
|
+
knock(source: string): void;
|
|
634
709
|
/**
|
|
635
|
-
*
|
|
636
|
-
*
|
|
637
|
-
*
|
|
710
|
+
* The second knock kind. Deduplicated by invite id for the life of the
|
|
711
|
+
* process so an invite seen live and again on a connect-time catch-up is
|
|
712
|
+
* decided once. Returns true when newly queued.
|
|
638
713
|
*/
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
714
|
+
groupInvite(invite: GroupInviteKnock, source: string): boolean;
|
|
715
|
+
/** Cancel timers; a cycle in flight finishes on its own. */
|
|
716
|
+
stop(): void;
|
|
717
|
+
/** The promise of the cycle currently running, for tests and for graceful stops. */
|
|
718
|
+
settled(): Promise<void>;
|
|
719
|
+
counters(): InvokerCounters;
|
|
720
|
+
private onKnockFired;
|
|
721
|
+
/** Run the worker if idle. One cycle at a time; work that lands mid-cycle runs afterwards. */
|
|
722
|
+
private schedule;
|
|
723
|
+
private drain;
|
|
724
|
+
/** Read the tray, gate it, start a turn when warranted. Public so tests can drive one cycle. */
|
|
725
|
+
runCycle(): Promise<GateResult | null>;
|
|
726
|
+
private scheduleRetry;
|
|
727
|
+
/** Start the knock turn. Returns whether OpenClaw admitted the run. */
|
|
728
|
+
private runKnockTurn;
|
|
729
|
+
private runInviteTurn;
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
declare function hostedMcpUrl(apiBase?: string): string;
|
|
733
|
+
interface McpServerEntry {
|
|
734
|
+
readonly url: string;
|
|
735
|
+
readonly transport: 'streamable-http';
|
|
736
|
+
readonly headers: {
|
|
737
|
+
readonly Authorization: string;
|
|
738
|
+
};
|
|
644
739
|
}
|
|
740
|
+
/** The `mcp.servers.agentchat` value this plugin places. */
|
|
741
|
+
declare function hostedMcpServerEntry(apiBase?: string): McpServerEntry;
|
|
742
|
+
/** The same entry as JSON5, for the README and for operators placing it by hand. */
|
|
743
|
+
declare function hostedMcpSnippet(apiBase?: string): string;
|
|
744
|
+
interface McpProbeResult {
|
|
745
|
+
readonly ok: boolean;
|
|
746
|
+
readonly status?: number;
|
|
747
|
+
readonly serverName?: string;
|
|
748
|
+
readonly serverVersion?: string;
|
|
749
|
+
readonly protocolVersion?: string;
|
|
750
|
+
/** Whether the server published `instructions` (OpenClaw injects them into the system prompt). */
|
|
751
|
+
readonly hasInstructions?: boolean;
|
|
752
|
+
readonly error?: string;
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* Doctor check: is the hosted MCP server reachable with this key? Sends one
|
|
756
|
+
* MCP `initialize` over Streamable HTTP with the bearer key — the same
|
|
757
|
+
* request OpenClaw makes on connect — and reads the server's answer. A
|
|
758
|
+
* `401` means the key does not authenticate; a transport error means the
|
|
759
|
+
* endpoint is not reachable from here.
|
|
760
|
+
*/
|
|
761
|
+
declare function probeHostedMcp(params: {
|
|
762
|
+
apiKey: string;
|
|
763
|
+
apiBase?: string;
|
|
764
|
+
timeoutMs?: number;
|
|
765
|
+
fetch?: typeof fetch;
|
|
766
|
+
}): Promise<McpProbeResult>;
|
|
645
767
|
|
|
646
768
|
/**
|
|
647
769
|
* Account-config primitives for the AgentChat channel plugin.
|
|
@@ -666,6 +788,97 @@ declare class AgentchatChannelRuntime {
|
|
|
666
788
|
declare const AGENTCHAT_CHANNEL_ID: "agentchat";
|
|
667
789
|
declare const AGENTCHAT_DEFAULT_ACCOUNT_ID = "default";
|
|
668
790
|
|
|
791
|
+
interface KnockCoalescerOptions {
|
|
792
|
+
readonly onFire: () => void;
|
|
793
|
+
readonly debounceMs?: number;
|
|
794
|
+
readonly maxWindowMs?: number;
|
|
795
|
+
readonly now?: () => number;
|
|
796
|
+
readonly setTimeout?: (fn: () => void, ms: number) => NodeJS.Timeout;
|
|
797
|
+
readonly clearTimeout?: (handle: NodeJS.Timeout) => void;
|
|
798
|
+
}
|
|
799
|
+
declare class KnockCoalescer {
|
|
800
|
+
private readonly onFire;
|
|
801
|
+
private readonly debounceMs;
|
|
802
|
+
private readonly maxWindowMs;
|
|
803
|
+
private readonly now;
|
|
804
|
+
private readonly _setTimeout;
|
|
805
|
+
private readonly _clearTimeout;
|
|
806
|
+
private timer;
|
|
807
|
+
private burstStartedAt;
|
|
808
|
+
private delayed;
|
|
809
|
+
private delayedDeadline;
|
|
810
|
+
private stopped;
|
|
811
|
+
knocks: number;
|
|
812
|
+
absorbed: number;
|
|
813
|
+
fires: number;
|
|
814
|
+
constructor(options: KnockCoalescerOptions);
|
|
815
|
+
/** True while a debounce timer is armed. */
|
|
816
|
+
get armed(): boolean;
|
|
817
|
+
/** True while a retry knock is scheduled and has not fired. */
|
|
818
|
+
get delayedPending(): boolean;
|
|
819
|
+
/**
|
|
820
|
+
* A knock. The first one of a burst arms the window; every later one is
|
|
821
|
+
* absorbed and restarts it (trailing edge), never past the burst's cap.
|
|
822
|
+
*/
|
|
823
|
+
knock(): void;
|
|
824
|
+
/** A delayed knock (retry ladder). The sooner pending deadline is kept. */
|
|
825
|
+
knockAfter(delayMs: number): void;
|
|
826
|
+
/** Cancel everything; later knocks are ignored. */
|
|
827
|
+
stop(): void;
|
|
828
|
+
private fire;
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
/**
|
|
832
|
+
* The turn prompts and the names OpenClaw gives the hosted tools.
|
|
833
|
+
*
|
|
834
|
+
* The doorbell starts an agent turn with the main line's own wake
|
|
835
|
+
* instruction — the same three sentences the server sends every webhook
|
|
836
|
+
* doorbell — followed by the conversation ids the gate step decided to
|
|
837
|
+
* answer. What the agent then reads, decides and sends goes through the
|
|
838
|
+
* hosted MCP tools (`https://api.agentchat.me/mcp`), registered as the MCP
|
|
839
|
+
* server `agentchat` (see `./mcp.ts`).
|
|
840
|
+
*
|
|
841
|
+
* OpenClaw exposes an MCP server's tools to the model as
|
|
842
|
+
* `<server>__<tool>`: the tool-policy pipeline builds the namespace prefix
|
|
843
|
+
* as `normalizeToolName(sanitizeServerName(serverName) + "__")`
|
|
844
|
+
* (`openclaw/dist/tool-policy-*.js`, 2026.6.10) and the docs describe the
|
|
845
|
+
* same `<server>__<tool>` shape (docs.openclaw.ai/tools/mcp). Our server
|
|
846
|
+
* name is already provider-safe (`[a-z]`), so the hosted `agentchat_inbox`
|
|
847
|
+
* is `agentchat__agentchat_inbox` inside an OpenClaw turn.
|
|
848
|
+
*
|
|
849
|
+
* Nothing in this module is product text of its own: the wake instruction,
|
|
850
|
+
* the manual, the identity line, the briefing card and the gate question are
|
|
851
|
+
* all written in the main line and only placed by this plugin. The one
|
|
852
|
+
* sentence that is ours states facts (which ids the gate chose), not
|
|
853
|
+
* judgement.
|
|
854
|
+
*/
|
|
855
|
+
/** Name of the MCP server entry this plugin places. Changing it changes every tool name the model sees — keep in lockstep with `./mcp.ts`. */
|
|
856
|
+
declare const MCP_SERVER_NAME = "agentchat";
|
|
857
|
+
/** `agentchat_inbox` → `agentchat__agentchat_inbox`. */
|
|
858
|
+
declare function mcpToolName(tool: string): string;
|
|
859
|
+
/**
|
|
860
|
+
* The main line's wake instruction — the AgentChat platform's default wake
|
|
861
|
+
* instruction, the text every webhook doorbell receives — with the names
|
|
862
|
+
* OpenClaw gives the hosted tools. The server sends these three sentences to every webhook
|
|
863
|
+
* doorbell; a socket doorbell carries the same text so the agent is
|
|
864
|
+
* addressed the same way whichever doorbell rang. Update together with the
|
|
865
|
+
* server.
|
|
866
|
+
*/
|
|
867
|
+
declare const WAKE_INSTRUCTION: string;
|
|
868
|
+
declare const KNOCK_TURN_PROMPT: string;
|
|
869
|
+
declare const INVITE_TURN_PROMPT: string;
|
|
870
|
+
/**
|
|
871
|
+
* The prompt a knock turn starts with. `replyConversations` are the
|
|
872
|
+
* conversation ids the gate step decided `reply` just before this turn. The
|
|
873
|
+
* turn is a fresh session with no memory of that call, so the ids are
|
|
874
|
+
* stated; every other card on the tray was left undecided and the turn
|
|
875
|
+
* judges it with the tray's own question. Ids are metadata — a webhook wake
|
|
876
|
+
* carries the same — never content.
|
|
877
|
+
*/
|
|
878
|
+
declare function knockTurnPrompt(replyConversations?: readonly string[]): string;
|
|
879
|
+
/** The one prompt a group-invite turn starts with. */
|
|
880
|
+
declare function inviteTurnPrompt(): string;
|
|
881
|
+
|
|
669
882
|
/**
|
|
670
883
|
* Minimal HTTP client used by the setup plugin (P7) to:
|
|
671
884
|
* - verify an API key is live before finalizing setup (`validateApiKey`)
|
|
@@ -870,4 +1083,4 @@ declare function recoverAgentVerify(input: RecoverAgentVerifyInput, opts?: Regis
|
|
|
870
1083
|
*/
|
|
871
1084
|
declare function assertApiKeyValid(apiKey: string, opts?: ValidateApiKeyOptions): Promise<AgentchatAgentIdentity>;
|
|
872
1085
|
|
|
873
|
-
export { AGENTCHAT_CHANNEL_ID, AGENTCHAT_DEFAULT_ACCOUNT_ID, AgentChatChannelError, type AgentchatAgentIdentity, AgentchatChannelConfig, AgentchatChannelRuntime, type ChannelRuntimeHandlers, type ChannelRuntimeOptions, type ConnectionState, type
|
|
1086
|
+
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 };
|