@agentchatme/openclaw 0.8.1 → 0.9.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 +39 -0
- package/README.md +72 -70
- package/RUNBOOK.md +65 -42
- package/SECURITY.md +9 -6
- package/dist/binding/agents-anchor.cjs +24 -20
- package/dist/binding/agents-anchor.cjs.map +1 -1
- package/dist/binding/agents-anchor.d.cts +38 -31
- package/dist/binding/agents-anchor.d.ts +38 -31
- package/dist/binding/agents-anchor.js +24 -18
- package/dist/binding/agents-anchor.js.map +1 -1
- package/dist/credentials/read-env.cjs +16 -7
- package/dist/credentials/read-env.cjs.map +1 -1
- package/dist/credentials/read-env.d.cts +26 -10
- package/dist/credentials/read-env.d.ts +26 -10
- package/dist/credentials/read-env.js +12 -6
- package/dist/credentials/read-env.js.map +1 -1
- package/dist/index.cjs +1192 -1522
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +155 -753
- package/dist/index.d.ts +155 -753
- package/dist/index.js +1178 -1514
- package/dist/index.js.map +1 -1
- package/dist/openclaw-layout.cjs.map +1 -1
- package/dist/openclaw-layout.d.cts +1 -1
- package/dist/openclaw-layout.d.ts +1 -1
- package/dist/openclaw-layout.js.map +1 -1
- package/dist/setup-entry-Dh6dRH2F.d.cts +754 -0
- package/dist/setup-entry-Dh6dRH2F.d.ts +754 -0
- package/dist/setup-entry.cjs +1144 -1527
- package/dist/setup-entry.cjs.map +1 -1
- package/dist/setup-entry.d.cts +2 -1
- package/dist/setup-entry.d.ts +2 -1
- package/dist/setup-entry.js +1145 -1528
- package/dist/setup-entry.js.map +1 -1
- package/openclaw.plugin.json +6 -12
- package/package.json +6 -6
- package/skills/agentchat/SKILL.md +132 -78
- package/dist/setup-entry-DU51IFUF.d.cts +0 -154
- package/dist/setup-entry-DU51IFUF.d.ts +0 -154
package/dist/setup-entry.cjs
CHANGED
|
@@ -7,14 +7,13 @@ var channelPluginCommon = require('openclaw/plugin-sdk/channel-plugin-common');
|
|
|
7
7
|
var setup = require('openclaw/plugin-sdk/setup');
|
|
8
8
|
var readEnv_js$1 = require('./credentials/read-env.cjs');
|
|
9
9
|
var fs = require('fs');
|
|
10
|
-
var
|
|
10
|
+
var path2 = require('path');
|
|
11
11
|
var readEnv_js = require('./credentials/read-env.cjs');
|
|
12
12
|
var openclawLayout_js = require('./openclaw-layout.cjs');
|
|
13
13
|
var agentsAnchor_js = require('./binding/agents-anchor.cjs');
|
|
14
|
+
var agentchatme = require('agentchatme');
|
|
14
15
|
var zod = require('zod');
|
|
15
16
|
var pino = require('pino');
|
|
16
|
-
var ws = require('ws');
|
|
17
|
-
var agentchatme = require('agentchatme');
|
|
18
17
|
|
|
19
18
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
20
19
|
|
|
@@ -37,7 +36,7 @@ function _interopNamespace(e) {
|
|
|
37
36
|
}
|
|
38
37
|
|
|
39
38
|
var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
|
|
40
|
-
var
|
|
39
|
+
var path2__namespace = /*#__PURE__*/_interopNamespace(path2);
|
|
41
40
|
var pino__default = /*#__PURE__*/_interopDefault(pino);
|
|
42
41
|
|
|
43
42
|
// src/channel.setup.ts
|
|
@@ -101,7 +100,7 @@ function listConfiguredAccountIds(cfg) {
|
|
|
101
100
|
function multiAccountRefusal(cfg) {
|
|
102
101
|
const ids = listConfiguredAccountIds(cfg);
|
|
103
102
|
if (ids.length <= 1) return null;
|
|
104
|
-
return `${ids.length} AgentChat accounts are configured (${ids.join(", ")}); this release runs one account per gateway \u2014 the hosted tools are one mcp.servers.agentchat entry on one AGENTCHAT_API_KEY, so a second account would act as the first. Keep one account under channels.agentchat (or run a second gateway) until per-account
|
|
103
|
+
return `${ids.length} AgentChat accounts are configured (${ids.join(", ")}); this release runs one account per gateway \u2014 the hosted tools are one mcp.servers.agentchat entry on one AGENTCHAT_API_KEY, so a second account would act as the first. Keep one account under channels.agentchat (or run a second gateway) until per-account integrations ship.`;
|
|
105
104
|
}
|
|
106
105
|
function isApiKeyPresent(value) {
|
|
107
106
|
return typeof value === "string" && value.length >= MIN_API_KEY_LENGTH;
|
|
@@ -133,52 +132,19 @@ function applyAgentchatAccountPatch(cfg, accountId, patch) {
|
|
|
133
132
|
return { ...cfg ?? {}, channels };
|
|
134
133
|
}
|
|
135
134
|
|
|
136
|
-
// src/errors.ts
|
|
137
|
-
var AgentChatChannelError = class extends Error {
|
|
138
|
-
class_;
|
|
139
|
-
retryAfterMs;
|
|
140
|
-
statusCode;
|
|
141
|
-
constructor(class_, message, options = {}) {
|
|
142
|
-
super(message, { cause: options.cause });
|
|
143
|
-
this.name = "AgentChatChannelError";
|
|
144
|
-
this.class_ = class_;
|
|
145
|
-
this.retryAfterMs = options.retryAfterMs;
|
|
146
|
-
this.statusCode = options.statusCode;
|
|
147
|
-
}
|
|
148
|
-
};
|
|
149
|
-
function classifyNetworkError(err) {
|
|
150
|
-
if (!err || typeof err !== "object") return "retry-transient";
|
|
151
|
-
const code = err.code;
|
|
152
|
-
if (typeof code === "string") {
|
|
153
|
-
if (code === "ECONNRESET" || code === "ETIMEDOUT" || code === "ECONNREFUSED") {
|
|
154
|
-
return "retry-transient";
|
|
155
|
-
}
|
|
156
|
-
if (code === "ENOTFOUND" || code === "EAI_AGAIN") return "retry-transient";
|
|
157
|
-
}
|
|
158
|
-
return "retry-transient";
|
|
159
|
-
}
|
|
160
|
-
|
|
161
135
|
// src/version.ts
|
|
162
|
-
var PACKAGE_VERSION = "0.
|
|
136
|
+
var PACKAGE_VERSION = "0.9.1";
|
|
163
137
|
|
|
164
138
|
// src/client-identity.ts
|
|
165
139
|
var AGENTCHAT_CLIENT_NAME = "openclaw";
|
|
140
|
+
var AGENTCHAT_CLIENT_IDENTITY = {
|
|
141
|
+
name: AGENTCHAT_CLIENT_NAME,
|
|
142
|
+
version: PACKAGE_VERSION
|
|
143
|
+
};
|
|
166
144
|
var AGENTCHAT_CLIENT_HEADERS = {
|
|
167
145
|
"X-AgentChat-Client": AGENTCHAT_CLIENT_NAME,
|
|
168
146
|
"X-AgentChat-Client-Version": PACKAGE_VERSION
|
|
169
147
|
};
|
|
170
|
-
function withAgentChatClientIdentity(fetchImpl) {
|
|
171
|
-
return (async (input, init) => {
|
|
172
|
-
const headers = new Headers(
|
|
173
|
-
typeof Request !== "undefined" && input instanceof Request ? input.headers : void 0
|
|
174
|
-
);
|
|
175
|
-
new Headers(init?.headers).forEach((value, key) => headers.set(key, value));
|
|
176
|
-
for (const [key, value] of Object.entries(AGENTCHAT_CLIENT_HEADERS)) {
|
|
177
|
-
headers.set(key, value);
|
|
178
|
-
}
|
|
179
|
-
return fetchImpl(input, { ...init, headers });
|
|
180
|
-
});
|
|
181
|
-
}
|
|
182
148
|
|
|
183
149
|
// src/setup-client.ts
|
|
184
150
|
var DEFAULT_API_BASE = "https://api.agentchat.me";
|
|
@@ -406,9 +372,9 @@ function readHandleList(details) {
|
|
|
406
372
|
if (!Array.isArray(handles)) return [];
|
|
407
373
|
return handles.filter((h) => typeof h === "string" && h.length > 0);
|
|
408
374
|
}
|
|
409
|
-
async function post(
|
|
375
|
+
async function post(path5, body, opts) {
|
|
410
376
|
const base = (opts.apiBase ?? DEFAULT_API_BASE).replace(/\/+$/, "");
|
|
411
|
-
const url = `${base}${
|
|
377
|
+
const url = `${base}${path5}`;
|
|
412
378
|
const controller = new AbortController();
|
|
413
379
|
const fetchImpl = opts.fetch ?? fetch;
|
|
414
380
|
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
@@ -441,53 +407,41 @@ async function post(path2, body, opts) {
|
|
|
441
407
|
}
|
|
442
408
|
}
|
|
443
409
|
|
|
444
|
-
// src/
|
|
410
|
+
// src/integration/turn.ts
|
|
445
411
|
var MCP_SERVER_NAME = "agentchat";
|
|
446
412
|
var MCP_TOOL_DELIMITER = "__";
|
|
447
|
-
var
|
|
413
|
+
var MCP_TOOL_PREFIX = `${MCP_SERVER_NAME}${MCP_TOOL_DELIMITER}`;
|
|
448
414
|
function mcpToolName(tool) {
|
|
449
|
-
return `${
|
|
415
|
+
return `${MCP_TOOL_PREFIX}${tool}`;
|
|
450
416
|
}
|
|
451
|
-
var INBOX_TOOL = mcpToolName("agentchat_inbox");
|
|
452
417
|
var DECIDE_TOOL = mcpToolName("agentchat_decide");
|
|
453
418
|
var GET_CONVERSATION_TOOL = mcpToolName("agentchat_get_conversation");
|
|
454
|
-
var
|
|
455
|
-
var
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
var MANUAL_POINTER = `(The AgentChat manual is the ${SKILL_NAME} skill bundled with this plugin; the same text is at https://agentchat.me/skill.md.)`;
|
|
464
|
-
var KNOCK_TURN_PROMPT = `${WAKE_INSTRUCTION}
|
|
465
|
-
|
|
466
|
-
${MANUAL_POINTER}`;
|
|
467
|
-
var INVITE_TURN_PROMPT = `You were woken by AgentChat: a group invitation is pending for you. Call ${LIST_GROUP_INVITES_TOOL} first, then decide for yourself: accept with ${ACCEPT_GROUP_INVITE_TOOL}, decline with ${REJECT_GROUP_INVITE_TOOL}, or leave it pending by doing nothing. Being invited is not a reason to join.
|
|
468
|
-
|
|
469
|
-
${MANUAL_POINTER}`;
|
|
470
|
-
function knockTurnPrompt(replyConversations = []) {
|
|
471
|
-
const ids = replyConversations.filter((id) => typeof id === "string" && id.length > 0);
|
|
472
|
-
if (ids.length === 0) return KNOCK_TURN_PROMPT;
|
|
473
|
-
const gateLine = `The gate step before this turn decided to answer: ${ids.join(", ")}. Any other card on the tray was left undecided; decide it with the tray's question.`;
|
|
474
|
-
return `${WAKE_INSTRUCTION}
|
|
475
|
-
|
|
476
|
-
${gateLine}
|
|
419
|
+
var OPENCLAW_TOOL_NAMER = (tool) => tool.startsWith(MCP_TOOL_PREFIX) ? tool : mcpToolName(tool);
|
|
420
|
+
var HOSTED_TOOL_TOKEN = /\bagentchat_(?!_)[a-z0-9_]+\b/g;
|
|
421
|
+
function spellToolsForOpenClaw(text) {
|
|
422
|
+
return text.replace(HOSTED_TOOL_TOKEN, (token) => OPENCLAW_TOOL_NAMER(token));
|
|
423
|
+
}
|
|
424
|
+
function wakeTurnPrompt(texts, conversationId) {
|
|
425
|
+
const instruction = texts.wake_instruction.trim();
|
|
426
|
+
if (!conversationId) return instruction;
|
|
427
|
+
return `${instruction}
|
|
477
428
|
|
|
478
|
-
${
|
|
429
|
+
${conversationLine(conversationId)}`;
|
|
479
430
|
}
|
|
480
|
-
function
|
|
481
|
-
return
|
|
431
|
+
function conversationLine(conversationId) {
|
|
432
|
+
return `Conversation to answer in this turn: ${conversationId}. The gate decided reply; its card is still on the tray while you work, and the reply verdict for it is recorded for you when this turn completes (recording it yourself with ${DECIDE_TOOL} is idempotent) \u2014 open it with ${GET_CONVERSATION_TOOL} and reply.`;
|
|
482
433
|
}
|
|
483
|
-
function
|
|
484
|
-
return
|
|
434
|
+
function inviteTurnPrompt(texts) {
|
|
435
|
+
return texts.invite_prompt.trim();
|
|
436
|
+
}
|
|
437
|
+
function wakeSessionKey(agentId, now = Date.now(), nonce = randomNonce()) {
|
|
438
|
+
return `agent:${agentId}:subagent:agentchat-wake-${utcStamp(now)}-${nonce}`;
|
|
485
439
|
}
|
|
486
440
|
function inviteSessionKey(agentId, inviteId) {
|
|
487
441
|
return `agent:${agentId}:subagent:agentchat-invite-${sanitizeKeyPart(inviteId)}`;
|
|
488
442
|
}
|
|
489
|
-
function
|
|
490
|
-
return `agentchat-
|
|
443
|
+
function integrationLane(accountId) {
|
|
444
|
+
return `agentchat-integration:${sanitizeKeyPart(accountId)}`;
|
|
491
445
|
}
|
|
492
446
|
function utcStamp(ms) {
|
|
493
447
|
return new Date(ms).toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
|
|
@@ -500,7 +454,7 @@ function sanitizeKeyPart(value) {
|
|
|
500
454
|
return clean.length > 0 ? clean : "x";
|
|
501
455
|
}
|
|
502
456
|
|
|
503
|
-
// src/
|
|
457
|
+
// src/integration/mcp.ts
|
|
504
458
|
var MCP_PATH = "/mcp";
|
|
505
459
|
var AUTH_HEADER_TEMPLATE = `Bearer \${${readEnv_js.API_KEY_ENV}}`;
|
|
506
460
|
var DEFAULT_API_BASE2 = "https://api.agentchat.me";
|
|
@@ -621,7 +575,7 @@ function readInitializeResult(text) {
|
|
|
621
575
|
return null;
|
|
622
576
|
}
|
|
623
577
|
|
|
624
|
-
// src/
|
|
578
|
+
// src/integration/runtime-holder.ts
|
|
625
579
|
var current = null;
|
|
626
580
|
function isUsablePluginRuntime(runtime) {
|
|
627
581
|
if (!runtime || typeof runtime !== "object" && typeof runtime !== "function") return false;
|
|
@@ -638,10 +592,10 @@ function setPluginRuntime(runtime) {
|
|
|
638
592
|
function getPluginRuntime() {
|
|
639
593
|
return current;
|
|
640
594
|
}
|
|
641
|
-
|
|
642
|
-
// src/doorbell/model.ts
|
|
643
595
|
var DEFAULT_AGENT_ID = "main";
|
|
644
596
|
var GATE_TEMPERATURE = 0;
|
|
597
|
+
var DEFAULT_GATE_MAX_TOKENS = 2048;
|
|
598
|
+
var DEFAULT_GATE_TIMEOUT_MS = 2e4;
|
|
645
599
|
var DEFAULT_TURN_WAIT_MS = 15 * 6e4;
|
|
646
600
|
var RuntimeUnavailableError = class extends Error {
|
|
647
601
|
constructor(what) {
|
|
@@ -649,13 +603,13 @@ var RuntimeUnavailableError = class extends Error {
|
|
|
649
603
|
this.name = "RuntimeUnavailableError";
|
|
650
604
|
}
|
|
651
605
|
};
|
|
652
|
-
function
|
|
606
|
+
function resolveIntegrationAgentId(params) {
|
|
653
607
|
try {
|
|
654
608
|
const route = params.channelRuntime?.routing?.resolveAgentRoute?.({
|
|
655
609
|
cfg: params.cfg,
|
|
656
610
|
channel: AGENTCHAT_CHANNEL_ID,
|
|
657
611
|
accountId: params.accountId,
|
|
658
|
-
peer: { kind: "direct", id: "
|
|
612
|
+
peer: { kind: "direct", id: "wake" }
|
|
659
613
|
});
|
|
660
614
|
const agentId = route?.agentId;
|
|
661
615
|
if (typeof agentId === "string" && agentId.trim().length > 0) return agentId.trim();
|
|
@@ -663,18 +617,19 @@ function resolveDoorbellAgentId(params) {
|
|
|
663
617
|
}
|
|
664
618
|
return DEFAULT_AGENT_ID;
|
|
665
619
|
}
|
|
666
|
-
function
|
|
620
|
+
function createRuntimeModelCall(params) {
|
|
667
621
|
const getRuntime = params.runtime ?? getPluginRuntime;
|
|
668
|
-
|
|
622
|
+
const maxTokens = params.maxTokens ?? DEFAULT_GATE_MAX_TOKENS;
|
|
623
|
+
const timeoutMs = params.timeoutMs ?? DEFAULT_GATE_TIMEOUT_MS;
|
|
624
|
+
return async (prompt) => {
|
|
669
625
|
const runtime = getRuntime();
|
|
670
626
|
if (!runtime) throw new RuntimeUnavailableError("the gate call");
|
|
671
627
|
const result = await runtime.llm.complete({
|
|
672
|
-
|
|
673
|
-
messages: [{ role: "user", content: userContent }],
|
|
628
|
+
messages: [{ role: "user", content: prompt }],
|
|
674
629
|
maxTokens,
|
|
675
630
|
temperature: GATE_TEMPERATURE,
|
|
676
631
|
...params.agentIdOverride ? { agentId: params.agentIdOverride } : {},
|
|
677
|
-
purpose: "AgentChat reply gate: the server's question about the server's cards",
|
|
632
|
+
purpose: "AgentChat reply gate: the server's question about the server's cards (tool-free triage)",
|
|
678
633
|
...Number.isFinite(timeoutMs) && timeoutMs > 0 ? { signal: AbortSignal.timeout(timeoutMs) } : {}
|
|
679
634
|
});
|
|
680
635
|
return typeof result?.text === "string" ? result.text : "";
|
|
@@ -704,7 +659,37 @@ function resolveGateAgent(params) {
|
|
|
704
659
|
const ambient = params.ambientAgentId?.trim().toLowerCase();
|
|
705
660
|
return { agentId: routed, agentIdOverride: routed === (ambient ?? routed) ? void 0 : routed };
|
|
706
661
|
}
|
|
707
|
-
function
|
|
662
|
+
function readLiveConfig(fallback, runtime = getPluginRuntime) {
|
|
663
|
+
try {
|
|
664
|
+
const loaded = runtime()?.config?.loadConfig?.();
|
|
665
|
+
if (loaded && typeof loaded === "object") return { cfg: loaded, live: true };
|
|
666
|
+
} catch {
|
|
667
|
+
}
|
|
668
|
+
return { cfg: fallback, live: false };
|
|
669
|
+
}
|
|
670
|
+
function turnReadiness(params) {
|
|
671
|
+
const env = params.env ?? process.env;
|
|
672
|
+
const restart = params.live === false ? ", then restart the gateway (this gateway cannot re-read its config while running)" : "";
|
|
673
|
+
switch (describeMcpEntry(params.cfg, params.apiBase, params.apiKey)) {
|
|
674
|
+
case "missing":
|
|
675
|
+
return { ready: false, reason: `mcp.servers.${MCP_SERVER_NAME} is not in the gateway config \u2014 run \`openclaw doctor --fix\`${restart}` };
|
|
676
|
+
case "disabled":
|
|
677
|
+
return { ready: false, reason: `mcp.servers.${MCP_SERVER_NAME} is disabled in the gateway config \u2014 enable it${restart}` };
|
|
678
|
+
case "user_managed":
|
|
679
|
+
return { ready: true };
|
|
680
|
+
case "ours": {
|
|
681
|
+
const value = env[readEnv_js.API_KEY_ENV];
|
|
682
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
683
|
+
return {
|
|
684
|
+
ready: false,
|
|
685
|
+
reason: `${readEnv_js.API_KEY_ENV} is not set in the gateway process, so the hosted tools' bearer template cannot resolve \u2014 restart the gateway (or reload its config) once ~/.openclaw/.env carries it`
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
return { ready: true };
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
function createRuntimeTurnStarter(params = {}) {
|
|
708
693
|
const getRuntime = params.runtime ?? getPluginRuntime;
|
|
709
694
|
const waitMs = params.waitMs ?? DEFAULT_TURN_WAIT_MS;
|
|
710
695
|
return async (request) => {
|
|
@@ -722,12 +707,12 @@ function createRuntimeTurnRunner(params = {}) {
|
|
|
722
707
|
} catch (err) {
|
|
723
708
|
return { ran: false, error: err instanceof Error ? err.message : String(err) };
|
|
724
709
|
}
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
}
|
|
710
|
+
const done = runtime.subagent.waitForRun({ runId, timeoutMs: waitMs }).then(
|
|
711
|
+
(waited) => ({ ran: true, runId, status: waited.status, ...waited.error ? { error: waited.error } : {} }),
|
|
712
|
+
// The run was admitted; only the wait failed. The turn is OpenClaw's now.
|
|
713
|
+
(err) => ({ ran: true, runId, status: "unknown", error: err instanceof Error ? err.message : String(err) })
|
|
714
|
+
);
|
|
715
|
+
return { ran: true, runId, done };
|
|
731
716
|
};
|
|
732
717
|
}
|
|
733
718
|
var HANDLE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
|
|
@@ -736,7 +721,7 @@ function isValidHandleShape(value) {
|
|
|
736
721
|
}
|
|
737
722
|
var DOTENV_NAME = ".env";
|
|
738
723
|
function dotEnvPath(stateDir = openclawLayout_js.resolveOpenClawStateDir()) {
|
|
739
|
-
return
|
|
724
|
+
return path2__namespace.join(stateDir, DOTENV_NAME);
|
|
740
725
|
}
|
|
741
726
|
function placeApiKeyInDotEnv(apiKey, stateDir = openclawLayout_js.resolveOpenClawStateDir()) {
|
|
742
727
|
const trimmed = apiKey.trim();
|
|
@@ -805,7 +790,7 @@ function stripQuotes(value) {
|
|
|
805
790
|
}
|
|
806
791
|
return value;
|
|
807
792
|
}
|
|
808
|
-
function
|
|
793
|
+
function applyIntegrationConfig(cfg, params) {
|
|
809
794
|
const changes = [];
|
|
810
795
|
let next = cfg;
|
|
811
796
|
const bareHandle = (params.handle ?? "").trim().replace(/^@/, "");
|
|
@@ -828,13 +813,13 @@ function applyDoorbellConfig(cfg, params) {
|
|
|
828
813
|
function resolvePlacementAgentId(cfg, accountId) {
|
|
829
814
|
return openclawLayout_js.resolveBoundAgentId(cfg, AGENTCHAT_CHANNEL_ID, accountId) ?? openclawLayout_js.resolveOpenClawDefaultAgentId(cfg);
|
|
830
815
|
}
|
|
831
|
-
function
|
|
816
|
+
function stripIntegrationConfig(cfg, accountId) {
|
|
832
817
|
const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? "https://api.agentchat.me";
|
|
833
818
|
const apiKey = readAgentchatConfigField(cfg, accountId, "apiKey");
|
|
834
819
|
const { cfg: next, removed } = withoutHostedMcpEntry(cfg, apiBase, apiKey);
|
|
835
820
|
return { cfg: next, changes: removed ? ["removed mcp.servers.agentchat"] : [] };
|
|
836
821
|
}
|
|
837
|
-
function
|
|
822
|
+
function removeIntegrationFiles(cfg, accountId, options) {
|
|
838
823
|
const changes = [];
|
|
839
824
|
try {
|
|
840
825
|
const removed = agentsAnchor_js.removeAgentsAnchor({ cfg, agentId: resolvePlacementAgentId(cfg, accountId) });
|
|
@@ -850,23 +835,38 @@ function removeDoorbellFiles(cfg, accountId, options) {
|
|
|
850
835
|
}
|
|
851
836
|
return changes;
|
|
852
837
|
}
|
|
853
|
-
function restoreIdentityLine(cfg, accountId, handle) {
|
|
838
|
+
function restoreIdentityLine(cfg, accountId, handle, identityLine) {
|
|
854
839
|
const agentId = resolvePlacementAgentId(cfg, accountId);
|
|
855
840
|
const bare = handle.trim().replace(/^@/, "");
|
|
856
841
|
let filePath = "";
|
|
857
842
|
try {
|
|
858
843
|
filePath = agentsAnchor_js.agentsAnchorPath(cfg, agentId);
|
|
859
844
|
if (!isValidHandleShape(bare)) return { outcome: "failed", path: filePath, detail: `agentHandle "${bare}" is not a valid AgentChat handle` };
|
|
860
|
-
|
|
845
|
+
if (identityLine === null) {
|
|
846
|
+
return { outcome: "skipped", path: filePath, detail: "the served identity line is not available (AgentChat unreachable and nothing cached) \u2014 run openclaw doctor --fix once it is" };
|
|
847
|
+
}
|
|
848
|
+
const present = agentsAnchor_js.hasAgentsAnchorFor({ cfg, handle: bare, text: identityLine, agentId });
|
|
861
849
|
filePath = present.path;
|
|
862
850
|
if (present.present) return { outcome: "present", path: present.path };
|
|
863
|
-
const written = agentsAnchor_js.writeAgentsAnchor({ cfg, handle: bare, agentId });
|
|
851
|
+
const written = agentsAnchor_js.writeAgentsAnchor({ cfg, handle: bare, text: identityLine, agentId });
|
|
864
852
|
return { outcome: "placed", path: written.path };
|
|
865
853
|
} catch (err) {
|
|
866
854
|
return { outcome: "failed", path: filePath, detail: describe(err) };
|
|
867
855
|
}
|
|
868
856
|
}
|
|
869
|
-
function
|
|
857
|
+
function refreshIdentityLine(cfg, accountId, handle, identityLine) {
|
|
858
|
+
const agentId = resolvePlacementAgentId(cfg, accountId);
|
|
859
|
+
try {
|
|
860
|
+
const found = agentsAnchor_js.readAgentsAnchor({ cfg, agentId });
|
|
861
|
+
if (!found.present) return { outcome: "absent", path: found.path };
|
|
862
|
+
if (found.text === identityLine.trim()) return { outcome: "unchanged", path: found.path };
|
|
863
|
+
const written = agentsAnchor_js.writeAgentsAnchor({ cfg, handle, text: identityLine, agentId });
|
|
864
|
+
return { outcome: "updated", path: written.path };
|
|
865
|
+
} catch (err) {
|
|
866
|
+
return { outcome: "failed", path: agentsAnchor_js.agentsAnchorPath(cfg, agentId), detail: describe(err) };
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
function placeIntegration(params) {
|
|
870
870
|
const steps = [];
|
|
871
871
|
if (params.placeKey !== false) {
|
|
872
872
|
try {
|
|
@@ -881,11 +881,20 @@ function placeDoorbell(params) {
|
|
|
881
881
|
}
|
|
882
882
|
}
|
|
883
883
|
const agentId = params.agentId ?? resolvePlacementAgentId(params.cfg, params.accountId ?? AGENTCHAT_DEFAULT_ACCOUNT_ID);
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
steps.push({
|
|
887
|
-
|
|
888
|
-
|
|
884
|
+
const handle = params.handle.replace(/^@/, "");
|
|
885
|
+
if (params.identityLine === null) {
|
|
886
|
+
steps.push({
|
|
887
|
+
name: "anchor",
|
|
888
|
+
status: "skipped",
|
|
889
|
+
detail: `identity line for @${handle} not placed \u2014 AgentChat's texts were unreachable and nothing is cached; run openclaw doctor --fix once it is reachable`
|
|
890
|
+
});
|
|
891
|
+
} else {
|
|
892
|
+
try {
|
|
893
|
+
const anchor = agentsAnchor_js.writeAgentsAnchor({ cfg: params.cfg, handle: params.handle, text: params.identityLine, agentId });
|
|
894
|
+
steps.push({ name: "anchor", status: "ok", detail: `identity line for @${handle} in ${anchor.path}` });
|
|
895
|
+
} catch (err) {
|
|
896
|
+
steps.push({ name: "anchor", status: "failed", detail: `could not write the identity line to AGENTS.md: ${describe(err)}` });
|
|
897
|
+
}
|
|
889
898
|
}
|
|
890
899
|
steps.push({ name: "manual", status: "ok", detail: "manual bundled as the agentchat skill (skills/agentchat/SKILL.md, https://agentchat.me/skill.md verbatim)" });
|
|
891
900
|
const mcp = withHostedMcpEntry(params.cfg, params.apiBase, params.apiKey);
|
|
@@ -927,7 +936,7 @@ function checkPlacement(params) {
|
|
|
927
936
|
checks.push({ name: "key", ok: false, detail: `${readEnv_js.API_KEY_ENV} is not placed \u2014 the hosted tools cannot authenticate; ${remedy("run openclaw channels add agentchat")}` });
|
|
928
937
|
}
|
|
929
938
|
if (params.handle) {
|
|
930
|
-
const anchor = agentsAnchor_js.hasAgentsAnchorFor({ cfg: params.cfg, handle: params.handle, agentId: params.agentId });
|
|
939
|
+
const anchor = agentsAnchor_js.hasAgentsAnchorFor({ cfg: params.cfg, handle: params.handle, text: params.identityLine, agentId: params.agentId });
|
|
931
940
|
checks.push({
|
|
932
941
|
name: "anchor",
|
|
933
942
|
ok: anchor.present,
|
|
@@ -948,6 +957,266 @@ function checkPlacement(params) {
|
|
|
948
957
|
function describe(err) {
|
|
949
958
|
return err instanceof Error ? err.message : String(err);
|
|
950
959
|
}
|
|
960
|
+
var PLUGIN_STATE_DIRNAME = "agentchat";
|
|
961
|
+
function safeSegment(value) {
|
|
962
|
+
const clean = value.replace(/[^A-Za-z0-9_.-]/g, "-").replace(/^\.+/, "");
|
|
963
|
+
return clean.length > 0 ? clean : "default";
|
|
964
|
+
}
|
|
965
|
+
function integrationStateDir(accountId, stateDir = openclawLayout_js.resolveOpenClawStateDir()) {
|
|
966
|
+
return path2__namespace.join(stateDir, PLUGIN_STATE_DIRNAME, safeSegment(accountId));
|
|
967
|
+
}
|
|
968
|
+
function readJsonFile(file) {
|
|
969
|
+
let raw;
|
|
970
|
+
try {
|
|
971
|
+
raw = fs__namespace.readFileSync(file, "utf8");
|
|
972
|
+
} catch {
|
|
973
|
+
return null;
|
|
974
|
+
}
|
|
975
|
+
try {
|
|
976
|
+
return JSON.parse(raw);
|
|
977
|
+
} catch {
|
|
978
|
+
return null;
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
function writeJsonFile(file, value) {
|
|
982
|
+
fs__namespace.mkdirSync(path2__namespace.dirname(file), { recursive: true });
|
|
983
|
+
const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`;
|
|
984
|
+
fs__namespace.writeFileSync(tmp, `${JSON.stringify(value, null, 2)}
|
|
985
|
+
`, "utf8");
|
|
986
|
+
try {
|
|
987
|
+
fs__namespace.renameSync(tmp, file);
|
|
988
|
+
} catch (err) {
|
|
989
|
+
try {
|
|
990
|
+
fs__namespace.unlinkSync(tmp);
|
|
991
|
+
} catch {
|
|
992
|
+
}
|
|
993
|
+
throw err;
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
// src/integration/texts.ts
|
|
998
|
+
var TEXTS_RUNTIME = "openclaw";
|
|
999
|
+
var TEXTS_REFRESH_MS = 24 * 60 * 6e4;
|
|
1000
|
+
var TEXTS_RETRY_MS = 5 * 6e4;
|
|
1001
|
+
var TEXTS_FETCH_TIMEOUT_MS = 1e4;
|
|
1002
|
+
var TEXTS_CACHE_FILE = "texts.json";
|
|
1003
|
+
function isTexts(value) {
|
|
1004
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1005
|
+
const t = value;
|
|
1006
|
+
const manual = t.manual;
|
|
1007
|
+
return typeof t.version === "string" && typeof t.wake_instruction === "string" && t.wake_instruction.length > 0 && typeof t.invite_prompt === "string" && t.invite_prompt.length > 0 && typeof t.identity_line === "string" && t.identity_line.length > 0 && typeof t.identity_line_template === "string" && !!manual && typeof manual === "object" && typeof manual.url === "string" && typeof manual.version === "string";
|
|
1008
|
+
}
|
|
1009
|
+
function textsCachePath(accountId, stateDir) {
|
|
1010
|
+
return path2__namespace.join(integrationStateDir(accountId, stateDir), TEXTS_CACHE_FILE);
|
|
1011
|
+
}
|
|
1012
|
+
function readCachedTexts(accountId, stateDir) {
|
|
1013
|
+
const raw = readJsonFile(textsCachePath(accountId, stateDir));
|
|
1014
|
+
if (!raw || typeof raw !== "object") return null;
|
|
1015
|
+
const entry = raw;
|
|
1016
|
+
if (typeof entry.fetched_at !== "string" || !isTexts(entry.texts)) return null;
|
|
1017
|
+
return { fetched_at: entry.fetched_at, texts: entry.texts };
|
|
1018
|
+
}
|
|
1019
|
+
function writeCachedTexts(accountId, texts, fetchedAt, stateDir) {
|
|
1020
|
+
const file = textsCachePath(accountId, stateDir);
|
|
1021
|
+
const entry = { fetched_at: fetchedAt.toISOString(), texts };
|
|
1022
|
+
writeJsonFile(file, entry);
|
|
1023
|
+
return file;
|
|
1024
|
+
}
|
|
1025
|
+
function spellTextsForOpenClaw(texts) {
|
|
1026
|
+
return {
|
|
1027
|
+
...texts,
|
|
1028
|
+
wake_instruction: spellToolsForOpenClaw(texts.wake_instruction),
|
|
1029
|
+
invite_prompt: spellToolsForOpenClaw(texts.invite_prompt),
|
|
1030
|
+
identity_line: spellToolsForOpenClaw(texts.identity_line),
|
|
1031
|
+
identity_line_template: spellToolsForOpenClaw(texts.identity_line_template)
|
|
1032
|
+
};
|
|
1033
|
+
}
|
|
1034
|
+
async function fetchTexts(client, timeoutMs = TEXTS_FETCH_TIMEOUT_MS) {
|
|
1035
|
+
const texts = await client.texts.get({ runtime: TEXTS_RUNTIME, timeoutMs });
|
|
1036
|
+
if (!isTexts(texts)) throw new Error("GET /v1/texts: answer is not a texts set (missing wake_instruction, invite_prompt or identity_line)");
|
|
1037
|
+
return texts;
|
|
1038
|
+
}
|
|
1039
|
+
async function loadTexts(params) {
|
|
1040
|
+
const now = params.now ?? Date.now;
|
|
1041
|
+
try {
|
|
1042
|
+
const texts = await fetchTexts(params.client, params.timeoutMs);
|
|
1043
|
+
const fetchedAt = new Date(now());
|
|
1044
|
+
try {
|
|
1045
|
+
writeCachedTexts(params.accountId, texts, fetchedAt, params.stateDir);
|
|
1046
|
+
} catch (err) {
|
|
1047
|
+
params.log?.warn({ err: describe2(err) }, "texts fetched but the cache could not be written");
|
|
1048
|
+
}
|
|
1049
|
+
return { texts: spellTextsForOpenClaw(texts), source: "server", fetchedAt: fetchedAt.toISOString() };
|
|
1050
|
+
} catch (err) {
|
|
1051
|
+
const cached = readCachedTexts(params.accountId, params.stateDir);
|
|
1052
|
+
if (cached) {
|
|
1053
|
+
params.log?.info({ err: describe2(err), fetchedAt: cached.fetched_at }, "texts: server unreachable \u2014 using the cached copy");
|
|
1054
|
+
return { texts: spellTextsForOpenClaw(cached.texts), source: "cache", fetchedAt: cached.fetched_at };
|
|
1055
|
+
}
|
|
1056
|
+
params.log?.debug({ err: describe2(err) }, "texts: server unreachable and nothing cached");
|
|
1057
|
+
return null;
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
async function loadIdentityLine(params) {
|
|
1061
|
+
const loaded = await loadTexts(params);
|
|
1062
|
+
return loaded ? loaded.texts.identity_line : null;
|
|
1063
|
+
}
|
|
1064
|
+
function cachedIdentityLine(accountId, stateDir) {
|
|
1065
|
+
const cached = readCachedTexts(accountId, stateDir);
|
|
1066
|
+
return cached ? spellToolsForOpenClaw(cached.texts.identity_line) : null;
|
|
1067
|
+
}
|
|
1068
|
+
var TextsStore = class {
|
|
1069
|
+
client;
|
|
1070
|
+
accountId;
|
|
1071
|
+
logger;
|
|
1072
|
+
stateDir;
|
|
1073
|
+
refreshMs;
|
|
1074
|
+
retryMs;
|
|
1075
|
+
fetchTimeoutMs;
|
|
1076
|
+
now;
|
|
1077
|
+
_setTimeout;
|
|
1078
|
+
_clearTimeout;
|
|
1079
|
+
loaded = null;
|
|
1080
|
+
timer = null;
|
|
1081
|
+
inFlight = null;
|
|
1082
|
+
stopped = false;
|
|
1083
|
+
missingAnnounced = false;
|
|
1084
|
+
listeners = /* @__PURE__ */ new Set();
|
|
1085
|
+
loads = 0;
|
|
1086
|
+
serverLoads = 0;
|
|
1087
|
+
constructor(options) {
|
|
1088
|
+
this.client = options.client;
|
|
1089
|
+
this.accountId = options.accountId;
|
|
1090
|
+
this.logger = options.logger.child({ component: "texts", accountId: options.accountId });
|
|
1091
|
+
this.stateDir = options.stateDir;
|
|
1092
|
+
this.refreshMs = options.refreshMs ?? TEXTS_REFRESH_MS;
|
|
1093
|
+
this.retryMs = options.retryMs ?? TEXTS_RETRY_MS;
|
|
1094
|
+
this.fetchTimeoutMs = options.fetchTimeoutMs ?? TEXTS_FETCH_TIMEOUT_MS;
|
|
1095
|
+
this.now = options.now ?? Date.now;
|
|
1096
|
+
this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
|
|
1097
|
+
this._clearTimeout = options.clearTimeout ?? ((h) => clearTimeout(h));
|
|
1098
|
+
}
|
|
1099
|
+
/** The texts spelled for OpenClaw, or null until the first copy exists. */
|
|
1100
|
+
get current() {
|
|
1101
|
+
return this.loaded?.texts ?? null;
|
|
1102
|
+
}
|
|
1103
|
+
get source() {
|
|
1104
|
+
return this.loaded?.source ?? null;
|
|
1105
|
+
}
|
|
1106
|
+
get fetchedAt() {
|
|
1107
|
+
return this.loaded?.fetchedAt ?? null;
|
|
1108
|
+
}
|
|
1109
|
+
/** Called with every copy that arrives from the server (not with a cached one). */
|
|
1110
|
+
onServerCopy(listener) {
|
|
1111
|
+
this.listeners.add(listener);
|
|
1112
|
+
return () => {
|
|
1113
|
+
this.listeners.delete(listener);
|
|
1114
|
+
};
|
|
1115
|
+
}
|
|
1116
|
+
/** First load (server, then cache), then the timer. Resolves after the first attempt; never throws. */
|
|
1117
|
+
async start() {
|
|
1118
|
+
const texts = await this.load();
|
|
1119
|
+
if (!texts && !this.missingAnnounced) {
|
|
1120
|
+
this.missingAnnounced = true;
|
|
1121
|
+
this.logger.warn(
|
|
1122
|
+
{ retryMs: this.retryMs },
|
|
1123
|
+
"AgentChat texts unreachable and nothing cached \u2014 starting anyway; turns wait for the first copy, retried until it arrives"
|
|
1124
|
+
);
|
|
1125
|
+
}
|
|
1126
|
+
this.arm();
|
|
1127
|
+
return texts;
|
|
1128
|
+
}
|
|
1129
|
+
/** The current copy, or one load attempt now (coalesced with any in flight). */
|
|
1130
|
+
async ensure() {
|
|
1131
|
+
if (this.loaded) return this.loaded.texts;
|
|
1132
|
+
if (this.stopped) return null;
|
|
1133
|
+
return this.load();
|
|
1134
|
+
}
|
|
1135
|
+
/** Force a refresh (tests, operators). Coalesced. */
|
|
1136
|
+
refresh() {
|
|
1137
|
+
return this.load();
|
|
1138
|
+
}
|
|
1139
|
+
stop() {
|
|
1140
|
+
this.stopped = true;
|
|
1141
|
+
if (this.timer !== null) {
|
|
1142
|
+
this._clearTimeout(this.timer);
|
|
1143
|
+
this.timer = null;
|
|
1144
|
+
}
|
|
1145
|
+
this.listeners.clear();
|
|
1146
|
+
}
|
|
1147
|
+
load() {
|
|
1148
|
+
if (this.inFlight) return this.inFlight;
|
|
1149
|
+
this.inFlight = (async () => {
|
|
1150
|
+
this.loads += 1;
|
|
1151
|
+
const next = await loadTexts({
|
|
1152
|
+
client: this.client,
|
|
1153
|
+
accountId: this.accountId,
|
|
1154
|
+
stateDir: this.stateDir,
|
|
1155
|
+
now: this.now,
|
|
1156
|
+
log: this.logger,
|
|
1157
|
+
timeoutMs: this.fetchTimeoutMs
|
|
1158
|
+
});
|
|
1159
|
+
if (this.stopped) return next?.texts ?? null;
|
|
1160
|
+
if (next) {
|
|
1161
|
+
const changed = this.loaded?.texts.version !== next.texts.version || this.loaded?.texts.wake_instruction !== next.texts.wake_instruction;
|
|
1162
|
+
this.loaded = next;
|
|
1163
|
+
if (next.source === "server") {
|
|
1164
|
+
this.serverLoads += 1;
|
|
1165
|
+
this.logger[changed ? "info" : "debug"](
|
|
1166
|
+
{ version: next.texts.version, manual: next.texts.manual.version },
|
|
1167
|
+
"texts fetched from the server"
|
|
1168
|
+
);
|
|
1169
|
+
for (const listener of this.listeners) {
|
|
1170
|
+
try {
|
|
1171
|
+
listener(next.texts, next.source);
|
|
1172
|
+
} catch (err) {
|
|
1173
|
+
this.logger.warn({ err: describe2(err) }, "texts listener threw \u2014 continuing");
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
return next?.texts ?? null;
|
|
1179
|
+
})().finally(() => {
|
|
1180
|
+
this.inFlight = null;
|
|
1181
|
+
});
|
|
1182
|
+
return this.inFlight;
|
|
1183
|
+
}
|
|
1184
|
+
arm() {
|
|
1185
|
+
if (this.stopped) return;
|
|
1186
|
+
if (this.timer !== null) this._clearTimeout(this.timer);
|
|
1187
|
+
const delay = this.loaded === null ? this.retryMs : this.loaded.source === "cache" ? this.retryMs : this.refreshMs;
|
|
1188
|
+
this.timer = this._setTimeout(() => {
|
|
1189
|
+
this.timer = null;
|
|
1190
|
+
void this.load().finally(() => this.arm());
|
|
1191
|
+
}, delay);
|
|
1192
|
+
this.timer.unref?.();
|
|
1193
|
+
}
|
|
1194
|
+
};
|
|
1195
|
+
function describe2(err) {
|
|
1196
|
+
return err instanceof Error ? err.message : String(err);
|
|
1197
|
+
}
|
|
1198
|
+
var cache = /* @__PURE__ */ new Map();
|
|
1199
|
+
function createSdkClient(params) {
|
|
1200
|
+
return new agentchatme.AgentChatClient({
|
|
1201
|
+
apiKey: params.apiKey,
|
|
1202
|
+
...params.apiBase ? { baseUrl: params.apiBase } : {},
|
|
1203
|
+
clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
|
|
1204
|
+
...params.options
|
|
1205
|
+
});
|
|
1206
|
+
}
|
|
1207
|
+
function getClient({ accountId, config, options }) {
|
|
1208
|
+
const existing = cache.get(accountId);
|
|
1209
|
+
if (existing && existing.apiKey === config.apiKey && existing.apiBase === config.apiBase) {
|
|
1210
|
+
return existing.client;
|
|
1211
|
+
}
|
|
1212
|
+
const client = createSdkClient({ apiKey: config.apiKey, apiBase: config.apiBase, options });
|
|
1213
|
+
cache.set(accountId, {
|
|
1214
|
+
client,
|
|
1215
|
+
apiKey: config.apiKey,
|
|
1216
|
+
apiBase: config.apiBase
|
|
1217
|
+
});
|
|
1218
|
+
return client;
|
|
1219
|
+
}
|
|
951
1220
|
|
|
952
1221
|
// src/channel.wizard.ts
|
|
953
1222
|
var JUST_REGISTERED_SENTINEL = "_agentchatJustRegistered";
|
|
@@ -1618,18 +1887,22 @@ var agentchatSetupWizard = {
|
|
|
1618
1887
|
if (result.ok) {
|
|
1619
1888
|
spinner.stop(`Authenticated as @${result.agent.handle}`);
|
|
1620
1889
|
const handle = result.agent.handle;
|
|
1621
|
-
const
|
|
1890
|
+
const resolvedBase = apiBase ?? DEFAULT_API_BASE2;
|
|
1891
|
+
const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase: resolvedBase }), accountId });
|
|
1892
|
+
const placed = placeIntegration({ cfg, handle, apiKey, apiBase: resolvedBase, identityLine, accountId });
|
|
1622
1893
|
const failed = placed.steps.filter((s) => s.status === "failed");
|
|
1894
|
+
const skipped = placed.steps.filter((s) => s.status === "skipped" && s.name === "anchor");
|
|
1623
1895
|
await prompter.note(
|
|
1624
1896
|
[
|
|
1625
1897
|
...formatPlacement(placed.steps),
|
|
1626
1898
|
"",
|
|
1627
|
-
placed.mcp === "added" || placed.steps.some((s) => s.name === "key" && s.status === "changed") ? "Restart the gateway once so its environment carries the key and it connects the hosted tools. Then `openclaw channels status` shows the
|
|
1628
|
-
...failed.length > 0 ? ["", "Some placement failed (above). Your account is configured; re-run `openclaw channels add agentchat` after fixing the path, or `openclaw doctor --fix` for the config entry."] : []
|
|
1899
|
+
placed.mcp === "added" || placed.steps.some((s) => s.name === "key" && s.status === "changed") ? "Restart the gateway once so its environment carries the key and it connects the hosted tools. Then `openclaw channels status` shows the integration and the tools." : "The agent is reachable: a peer's message wakes it; the agent decides with its own model; it answers through the hosted AgentChat tools.",
|
|
1900
|
+
...failed.length > 0 ? ["", "Some placement failed (above). Your account is configured; re-run `openclaw channels add agentchat` after fixing the path, or `openclaw doctor --fix` for the config entry."] : [],
|
|
1901
|
+
...skipped.length > 0 ? ["", "The identity line waits for AgentChat to be reachable: run `openclaw doctor --fix` then."] : []
|
|
1629
1902
|
].join("\n"),
|
|
1630
|
-
"AgentChat
|
|
1903
|
+
"AgentChat integration placed"
|
|
1631
1904
|
);
|
|
1632
|
-
const applied =
|
|
1905
|
+
const applied = applyIntegrationConfig(placed.cfg, { accountId, handle, apiKey, apiBase: resolvedBase });
|
|
1633
1906
|
return { cfg: applied.cfg };
|
|
1634
1907
|
}
|
|
1635
1908
|
spinner.stop(`API key did not pass the live check (${result.reason})`);
|
|
@@ -1678,7 +1951,7 @@ var agentchatSetupWizard = {
|
|
|
1678
1951
|
// when the user explicitly removes the channel; orphans are documented in
|
|
1679
1952
|
// RUNBOOK.md.
|
|
1680
1953
|
disable: (cfg) => {
|
|
1681
|
-
return setup.setSetupChannelEnabled(
|
|
1954
|
+
return setup.setSetupChannelEnabled(stripIntegrationConfig(cfg, "default").cfg, AGENTCHAT_CHANNEL_ID, false);
|
|
1682
1955
|
}
|
|
1683
1956
|
};
|
|
1684
1957
|
var reconnectConfigSchema = zod.z.object({
|
|
@@ -1765,809 +2038,303 @@ function wrapPino(p) {
|
|
|
1765
2038
|
}
|
|
1766
2039
|
|
|
1767
2040
|
// src/metrics.ts
|
|
2041
|
+
function createInMemoryMetrics() {
|
|
2042
|
+
let state = "idle";
|
|
2043
|
+
const wakes = /* @__PURE__ */ new Map();
|
|
2044
|
+
const disconnects = /* @__PURE__ */ new Map();
|
|
2045
|
+
const errors = /* @__PURE__ */ new Map();
|
|
2046
|
+
const bump = (map, key) => {
|
|
2047
|
+
map.set(key, (map.get(key) ?? 0) + 1);
|
|
2048
|
+
};
|
|
2049
|
+
const plain = (map) => Object.fromEntries([...map.entries()].sort(([a], [b]) => a.localeCompare(b)));
|
|
2050
|
+
return {
|
|
2051
|
+
incDisconnect: ({ code, initiator }) => bump(disconnects, `${code}/${initiator}`),
|
|
2052
|
+
incError: ({ errorClass }) => bump(errors, errorClass),
|
|
2053
|
+
setConnectionState: (kind) => {
|
|
2054
|
+
state = kind;
|
|
2055
|
+
},
|
|
2056
|
+
incWake: ({ source }) => bump(wakes, source),
|
|
2057
|
+
snapshot: () => ({ state, wakes: plain(wakes), disconnects: plain(disconnects), errors: plain(errors) })
|
|
2058
|
+
};
|
|
2059
|
+
}
|
|
1768
2060
|
function createNoopMetrics() {
|
|
1769
2061
|
return {
|
|
1770
|
-
|
|
2062
|
+
incDisconnect: () => void 0,
|
|
1771
2063
|
incError: () => void 0,
|
|
1772
2064
|
setConnectionState: () => void 0,
|
|
1773
|
-
|
|
2065
|
+
incWake: () => void 0
|
|
1774
2066
|
};
|
|
1775
2067
|
}
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
2068
|
+
function groupInviteFromRecord(record) {
|
|
2069
|
+
if (!record || typeof record !== "object" || Array.isArray(record)) return null;
|
|
2070
|
+
const row = record;
|
|
2071
|
+
const inviteId = str(row.id);
|
|
2072
|
+
const groupId = str(row.group_id);
|
|
2073
|
+
if (!inviteId || !groupId) return null;
|
|
2074
|
+
return {
|
|
2075
|
+
inviteId,
|
|
2076
|
+
groupId,
|
|
2077
|
+
groupName: str(row.group_name) ?? "",
|
|
2078
|
+
inviterHandle: (str(row.inviter_handle) ?? "").replace(/^@/, "")
|
|
2079
|
+
};
|
|
2080
|
+
}
|
|
2081
|
+
function str(value) {
|
|
2082
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
2083
|
+
}
|
|
2084
|
+
var INVITE_LEDGER_FILE = "invites.json";
|
|
2085
|
+
var INVITE_LEDGER_MAX_AGE_MS = 30 * 24 * 60 * 6e4;
|
|
2086
|
+
function inviteLedgerPath(accountId, stateDir) {
|
|
2087
|
+
return path2__namespace.join(integrationStateDir(accountId, stateDir), INVITE_LEDGER_FILE);
|
|
2088
|
+
}
|
|
2089
|
+
var InviteLedger = class {
|
|
2090
|
+
file;
|
|
2091
|
+
now;
|
|
2092
|
+
maxAgeMs;
|
|
2093
|
+
onWriteError;
|
|
2094
|
+
offered;
|
|
2095
|
+
constructor(options) {
|
|
2096
|
+
this.file = options.file ?? inviteLedgerPath(options.accountId, options.stateDir);
|
|
2097
|
+
this.now = options.now ?? Date.now;
|
|
2098
|
+
this.maxAgeMs = options.maxAgeMs ?? INVITE_LEDGER_MAX_AGE_MS;
|
|
2099
|
+
this.onWriteError = options.onWriteError;
|
|
2100
|
+
this.offered = this.read();
|
|
2101
|
+
}
|
|
2102
|
+
get path() {
|
|
2103
|
+
return this.file;
|
|
2104
|
+
}
|
|
2105
|
+
get size() {
|
|
2106
|
+
return this.offered.size;
|
|
2107
|
+
}
|
|
2108
|
+
/** True when a turn for this invite was started before (in this process or an earlier one). */
|
|
2109
|
+
isOffered(inviteId) {
|
|
2110
|
+
return this.offered.has(inviteId);
|
|
2111
|
+
}
|
|
2112
|
+
/** Record that a turn for this invite was admitted. Persists at once. */
|
|
2113
|
+
markOffered(inviteId) {
|
|
2114
|
+
this.offered.set(inviteId, new Date(this.now()).toISOString());
|
|
2115
|
+
this.prune();
|
|
2116
|
+
try {
|
|
2117
|
+
writeJsonFile(this.file, { offered: Object.fromEntries(this.offered) });
|
|
2118
|
+
} catch (err) {
|
|
2119
|
+
this.onWriteError?.(err);
|
|
1828
2120
|
}
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
2121
|
+
}
|
|
2122
|
+
read() {
|
|
2123
|
+
const raw = readJsonFile(this.file);
|
|
2124
|
+
const out = /* @__PURE__ */ new Map();
|
|
2125
|
+
if (!raw || typeof raw !== "object") return out;
|
|
2126
|
+
const offered = raw.offered;
|
|
2127
|
+
if (!offered || typeof offered !== "object" || Array.isArray(offered)) return out;
|
|
2128
|
+
for (const [id, at] of Object.entries(offered)) {
|
|
2129
|
+
if (typeof at === "string" && id.length > 0) out.set(id, at);
|
|
1836
2130
|
}
|
|
1837
|
-
|
|
1838
|
-
|
|
2131
|
+
this.offered = out;
|
|
2132
|
+
this.prune();
|
|
2133
|
+
return this.offered;
|
|
2134
|
+
}
|
|
2135
|
+
prune() {
|
|
2136
|
+
const cutoff = this.now() - this.maxAgeMs;
|
|
2137
|
+
for (const [id, at] of this.offered) {
|
|
2138
|
+
const t = Date.parse(at);
|
|
2139
|
+
if (!Number.isFinite(t) || t < cutoff) this.offered.delete(id);
|
|
1839
2140
|
}
|
|
1840
2141
|
}
|
|
2142
|
+
};
|
|
2143
|
+
|
|
2144
|
+
// src/integration/socket.ts
|
|
2145
|
+
function wakeSourceOf(reason) {
|
|
2146
|
+
return reason === "reminder" ? "reminder" : "other";
|
|
1841
2147
|
}
|
|
1842
|
-
function
|
|
1843
|
-
return
|
|
2148
|
+
function realtimeOptionsFor(config, extra = {}) {
|
|
2149
|
+
return {
|
|
2150
|
+
apiKey: config.apiKey,
|
|
2151
|
+
baseUrl: config.apiBase.replace(/^http/, "ws").replace(/\/+$/, ""),
|
|
2152
|
+
clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
|
|
2153
|
+
ackOnReceipt: true,
|
|
2154
|
+
reconnect: true,
|
|
2155
|
+
reconnectInterval: config.reconnect.initialBackoffMs,
|
|
2156
|
+
maxReconnectInterval: config.reconnect.maxBackoffMs,
|
|
2157
|
+
...extra.client ? { client: extra.client } : {},
|
|
2158
|
+
...extra.webSocket ? { webSocket: extra.webSocket } : {}
|
|
2159
|
+
};
|
|
1844
2160
|
}
|
|
1845
|
-
|
|
1846
|
-
// src/ws-client.ts
|
|
1847
|
-
var HELLO_ACK_TIMEOUT_MS = 4e3;
|
|
1848
|
-
var RECONNECT_LONG_OUTAGE_AFTER_ATTEMPTS = 60;
|
|
1849
|
-
var RECONNECT_LONG_OUTAGE_BACKOFF_MS = 5 * 6e4;
|
|
1850
|
-
var AUTH_RETRY_INTERVAL_MS = 75e4;
|
|
1851
|
-
var MAX_FRAME_BYTES = 2 * 1024 * 1024;
|
|
1852
|
-
var HELLO_CAPABILITIES = ["ack"];
|
|
1853
|
-
var UNAMBIGUOUS_AUTH_CLOSE_CODES = /* @__PURE__ */ new Set([4401, 4403]);
|
|
1854
|
-
var AMBIGUOUS_AUTH_CLOSE_CODE = 1008;
|
|
1855
|
-
var SERVER_AUTH_CLOSE_REASONS = ["invalid token"];
|
|
1856
|
-
function isHandshakeRejection(code, reason) {
|
|
1857
|
-
if (UNAMBIGUOUS_AUTH_CLOSE_CODES.has(code)) return true;
|
|
1858
|
-
if (code !== AMBIGUOUS_AUTH_CLOSE_CODE) return false;
|
|
1859
|
-
const lower = reason.toLowerCase();
|
|
1860
|
-
return SERVER_AUTH_CLOSE_REASONS.some((known) => lower.includes(known));
|
|
1861
|
-
}
|
|
1862
|
-
var AgentchatWsClient = class {
|
|
2161
|
+
var IntegrationSocket = class {
|
|
1863
2162
|
config;
|
|
1864
2163
|
logger;
|
|
2164
|
+
handlers;
|
|
1865
2165
|
metrics;
|
|
2166
|
+
client;
|
|
2167
|
+
createRealtime;
|
|
2168
|
+
webSocket;
|
|
1866
2169
|
now;
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
* Set by `closeSocket()` before it closes the current socket, read and
|
|
1879
|
-
* cleared by `handleClose()`. A close this client asked for says nothing
|
|
1880
|
-
* about the server, whatever code travelled with it.
|
|
1881
|
-
*/
|
|
1882
|
-
closeInitiatedLocally = false;
|
|
1883
|
-
/** One error line per long outage / per run of rejected keys, then debug. */
|
|
1884
|
-
longOutageAnnounced = false;
|
|
1885
|
-
authFailAnnounced = false;
|
|
1886
|
-
helloAckTimer = null;
|
|
1887
|
-
pingTimer = null;
|
|
1888
|
-
pongTimer = null;
|
|
1889
|
-
reconnectTimer = null;
|
|
1890
|
-
drainTimer = null;
|
|
1891
|
-
listeners = {
|
|
1892
|
-
stateChanged: /* @__PURE__ */ new Set(),
|
|
1893
|
-
inboundFrame: /* @__PURE__ */ new Set(),
|
|
1894
|
-
error: /* @__PURE__ */ new Set(),
|
|
1895
|
-
authenticated: /* @__PURE__ */ new Set(),
|
|
1896
|
-
closed: /* @__PURE__ */ new Set()
|
|
1897
|
-
};
|
|
2170
|
+
selfHandle;
|
|
2171
|
+
realtime = null;
|
|
2172
|
+
/** The SDK's state as last reported through its `state` event; `stopped` is set here only for a stop before any start. */
|
|
2173
|
+
state = "idle";
|
|
2174
|
+
connectedAt = null;
|
|
2175
|
+
stopping = false;
|
|
2176
|
+
frames = 0;
|
|
2177
|
+
selfFiltered = 0;
|
|
2178
|
+
wakes = 0;
|
|
2179
|
+
invites = 0;
|
|
2180
|
+
disconnects = 0;
|
|
1898
2181
|
constructor(options) {
|
|
1899
2182
|
this.config = options.config;
|
|
1900
|
-
this.logger = options.logger.child({ component: "
|
|
1901
|
-
this.
|
|
2183
|
+
this.logger = options.logger.child({ component: "socket" });
|
|
2184
|
+
this.handlers = options.handlers ?? {};
|
|
2185
|
+
this.metrics = options.metrics ?? createNoopMetrics();
|
|
2186
|
+
this.client = options.client;
|
|
2187
|
+
this.createRealtime = options.createRealtime ?? ((opts) => new agentchatme.RealtimeClient(opts));
|
|
2188
|
+
this.webSocket = options.webSocket;
|
|
1902
2189
|
this.now = options.now ?? Date.now;
|
|
1903
|
-
this.
|
|
1904
|
-
this.
|
|
1905
|
-
this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
|
|
1906
|
-
this._clearTimeout = options.clearTimeout ?? ((h) => clearTimeout(h));
|
|
1907
|
-
this._setInterval = options.setInterval ?? ((fn, ms) => setInterval(fn, ms));
|
|
1908
|
-
this._clearInterval = options.clearInterval ?? ((h) => clearInterval(h));
|
|
1909
|
-
this.metrics.setConnectionState(this.state.kind);
|
|
1910
|
-
}
|
|
1911
|
-
// ─── Public API ──────────────────────────────────────────────────────
|
|
1912
|
-
/** Current connection state. Read-only from the caller's perspective. */
|
|
1913
|
-
getState() {
|
|
1914
|
-
return this.state;
|
|
1915
|
-
}
|
|
1916
|
-
/**
|
|
1917
|
-
* True when the last `hello.ok` echoed the `ack` capability: the server
|
|
1918
|
-
* keeps envelopes `stored` until acknowledged — and this client never
|
|
1919
|
-
* acknowledges. False against a legacy server (envelopes marked on push).
|
|
1920
|
-
*/
|
|
1921
|
-
get ackNegotiated() {
|
|
1922
|
-
return this._ackNegotiated;
|
|
2190
|
+
this.selfHandle = this.config.agentHandle?.replace(/^@/, "").toLowerCase();
|
|
2191
|
+
this.metrics.setConnectionState(this.state);
|
|
1923
2192
|
}
|
|
1924
2193
|
/**
|
|
1925
|
-
*
|
|
1926
|
-
*
|
|
2194
|
+
* Open the socket. Idempotent. Resolves once the SDK has started its
|
|
2195
|
+
* connect loop; a failure to resolve a WebSocket implementation is logged
|
|
2196
|
+
* and left to the SDK's own retry. Never throws.
|
|
1927
2197
|
*/
|
|
1928
|
-
start() {
|
|
1929
|
-
if (this.
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
2198
|
+
async start() {
|
|
2199
|
+
if (this.realtime || this.stopping) return;
|
|
2200
|
+
const realtime = this.createRealtime(realtimeOptionsFor(this.config, { client: this.client, webSocket: this.webSocket }));
|
|
2201
|
+
this.realtime = realtime;
|
|
2202
|
+
this.bind(realtime);
|
|
2203
|
+
try {
|
|
2204
|
+
await realtime.connect();
|
|
2205
|
+
} catch (err) {
|
|
2206
|
+
this.logger.warn({ err: describe3(err) }, "socket connect failed \u2014 the SDK retries on its own schedule");
|
|
1934
2207
|
}
|
|
1935
|
-
this.openSocket(1);
|
|
1936
2208
|
}
|
|
1937
|
-
/**
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
this.
|
|
1948
|
-
this.scheduleDrainDeadline(computedDeadline);
|
|
2209
|
+
/** Close the socket for good; a stopped socket does not reconnect. Idempotent. */
|
|
2210
|
+
async stop() {
|
|
2211
|
+
this.stopping = true;
|
|
2212
|
+
const realtime = this.realtime;
|
|
2213
|
+
this.realtime = null;
|
|
2214
|
+
this.connectedAt = null;
|
|
2215
|
+
if (realtime) {
|
|
2216
|
+
try {
|
|
2217
|
+
realtime.disconnect();
|
|
2218
|
+
} catch (err) {
|
|
2219
|
+
this.logger.warn({ err: describe3(err) }, "socket disconnect threw \u2014 continuing");
|
|
1949
2220
|
}
|
|
1950
|
-
return;
|
|
1951
|
-
}
|
|
1952
|
-
if (isTerminal(this.state)) {
|
|
1953
|
-
return;
|
|
1954
|
-
}
|
|
1955
|
-
this.applyEvent({ type: "DRAIN_REQUESTED", now, deadline: computedDeadline });
|
|
1956
|
-
const after = this.state.kind;
|
|
1957
|
-
if (after === "DRAINING") {
|
|
1958
|
-
this.scheduleDrainDeadline(computedDeadline);
|
|
1959
|
-
} else if (after === "CLOSED") {
|
|
1960
|
-
this.closeSocket(1e3, "client drain (immediate)");
|
|
1961
|
-
this.emit("closed");
|
|
1962
2221
|
}
|
|
2222
|
+
if (this.state !== "stopped") this.onState("stopped", this.state);
|
|
1963
2223
|
}
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
reconfigured() {
|
|
1970
|
-
if (this.state.kind !== "AUTH_FAIL") return;
|
|
1971
|
-
this.clearReconnectTimer();
|
|
1972
|
-
this.applyEvent({ type: "RECONFIGURED" });
|
|
1973
|
-
this.openSocket(1);
|
|
1974
|
-
}
|
|
1975
|
-
on(event, handler) {
|
|
1976
|
-
this.listeners[event].add(handler);
|
|
1977
|
-
return () => {
|
|
1978
|
-
this.listeners[event].delete(handler);
|
|
2224
|
+
getHealth() {
|
|
2225
|
+
return {
|
|
2226
|
+
state: this.state,
|
|
2227
|
+
connectedAt: this.connectedAt,
|
|
2228
|
+
counters: { frames: this.frames, selfFiltered: this.selfFiltered, wakes: this.wakes, invites: this.invites, disconnects: this.disconnects }
|
|
1979
2229
|
};
|
|
1980
2230
|
}
|
|
1981
|
-
// ─── Internals
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
});
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
this.scheduleReconnect("ctor-failed");
|
|
2006
|
-
return;
|
|
2007
|
-
}
|
|
2008
|
-
this.ws = ws;
|
|
2009
|
-
this.bindSocket(ws);
|
|
2010
|
-
}
|
|
2011
|
-
bindSocket(ws) {
|
|
2012
|
-
ws.on("open", () => this.handleOpen());
|
|
2013
|
-
ws.on("message", (data, isBinary) => this.handleMessage(data, isBinary));
|
|
2014
|
-
ws.on("pong", () => this.handlePong());
|
|
2015
|
-
ws.on("close", (code, reason) => this.handleClose(code, reason.toString()));
|
|
2016
|
-
ws.on("error", (err) => {
|
|
2017
|
-
this.emitError(
|
|
2018
|
-
new AgentChatChannelError(
|
|
2019
|
-
classifyNetworkError(err),
|
|
2020
|
-
"ws transport error",
|
|
2021
|
-
{ cause: err }
|
|
2022
|
-
)
|
|
2231
|
+
// ─── Internals ─────────────────────────────────────────────────────
|
|
2232
|
+
bind(realtime) {
|
|
2233
|
+
realtime.on("state", (next, prev) => this.onState(next, prev));
|
|
2234
|
+
realtime.onConnect(() => {
|
|
2235
|
+
const at = this.now();
|
|
2236
|
+
this.connectedAt = at;
|
|
2237
|
+
this.logger.info({ at: new Date(at).toISOString() }, "connected (HELLO accepted)");
|
|
2238
|
+
this.guard("onConnected", () => this.handlers.onConnected?.(at));
|
|
2239
|
+
this.wake("connect", {});
|
|
2240
|
+
});
|
|
2241
|
+
realtime.onDisconnect((info) => {
|
|
2242
|
+
if (this.stopping) return;
|
|
2243
|
+
this.disconnects += 1;
|
|
2244
|
+
this.connectedAt = null;
|
|
2245
|
+
this.metrics.incDisconnect({ code: String(info.code), initiator: info.initiator });
|
|
2246
|
+
this.logger.info({ code: info.code, reason: info.reason, initiator: info.initiator }, "socket closed \u2014 the SDK decides what follows (backoff or blocked)");
|
|
2247
|
+
this.guard("onDisconnected", () => this.handlers.onDisconnected?.(info));
|
|
2248
|
+
});
|
|
2249
|
+
realtime.on("blocked", (info) => {
|
|
2250
|
+
if (this.stopping) return;
|
|
2251
|
+
this.metrics.incError({ errorClass: "auth" });
|
|
2252
|
+
this.logger.warn(
|
|
2253
|
+
{ code: info.code, reason: info.reason, retryInMs: info.retryInMs },
|
|
2254
|
+
"the server rejected the key during the handshake \u2014 the SDK retries a fresh HELLO on its own"
|
|
2023
2255
|
);
|
|
2256
|
+
this.guard("onBlocked", () => this.handlers.onBlocked?.(info));
|
|
2257
|
+
});
|
|
2258
|
+
realtime.onError((error) => {
|
|
2259
|
+
if (this.stopping) return;
|
|
2260
|
+
if (realtime.state === "blocked") {
|
|
2261
|
+
this.logger.debug({ err: error.message }, "SDK notice while blocked");
|
|
2262
|
+
return;
|
|
2263
|
+
}
|
|
2264
|
+
this.metrics.incError({ errorClass: classifyRealtimeError(error) });
|
|
2265
|
+
this.logger.debug({ err: error.message }, "socket error");
|
|
2266
|
+
this.guard("onError", () => this.handlers.onError?.(error));
|
|
2024
2267
|
});
|
|
2268
|
+
realtime.on("message.new", (message) => this.onMessageNew(message));
|
|
2269
|
+
realtime.on("wake", (frame) => this.onWakeFrame(frame));
|
|
2270
|
+
realtime.on("group.invite.received", (message) => this.onInvite(message));
|
|
2025
2271
|
}
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
const
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
);
|
|
2040
|
-
} catch (err) {
|
|
2041
|
-
this.emitError(
|
|
2042
|
-
new AgentChatChannelError(
|
|
2043
|
-
"retry-transient",
|
|
2044
|
-
"hello send failed",
|
|
2045
|
-
{ cause: err }
|
|
2046
|
-
)
|
|
2047
|
-
);
|
|
2048
|
-
this.closeSocket(1011, "hello send failed");
|
|
2272
|
+
onMessageNew(message) {
|
|
2273
|
+
this.frames += 1;
|
|
2274
|
+
const payload = message.payload ?? {};
|
|
2275
|
+
const senderRaw = payload.sender ?? payload.from ?? "";
|
|
2276
|
+
const sender = typeof senderRaw === "string" ? senderRaw.replace(/^@/, "").toLowerCase() : "";
|
|
2277
|
+
const detail = {
|
|
2278
|
+
...typeof payload.conversation_id === "string" ? { conversationId: payload.conversation_id } : {},
|
|
2279
|
+
...typeof payload.id === "string" ? { messageId: payload.id } : {},
|
|
2280
|
+
...sender ? { from: sender } : {}
|
|
2281
|
+
};
|
|
2282
|
+
if (this.selfHandle && sender === this.selfHandle) {
|
|
2283
|
+
this.selfFiltered += 1;
|
|
2284
|
+
this.logger.debug(detail, "own echo \u2014 not a wake");
|
|
2049
2285
|
return;
|
|
2050
2286
|
}
|
|
2051
|
-
this.
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
},
|
|
2287
|
+
this.logger.debug(detail, "wake \u2014 message.new");
|
|
2288
|
+
this.wake("message", detail);
|
|
2289
|
+
}
|
|
2290
|
+
onWakeFrame(frame) {
|
|
2291
|
+
this.frames += 1;
|
|
2292
|
+
const reason = frame.payload?.reason;
|
|
2293
|
+
const detail = { conversationId: frame.payload.conversation_id };
|
|
2294
|
+
this.logger.info({ ...detail, reason, step: frame.payload.step }, "wake \u2014 server wake frame");
|
|
2295
|
+
this.wake(wakeSourceOf(reason), detail);
|
|
2059
2296
|
}
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2297
|
+
onInvite(message) {
|
|
2298
|
+
this.frames += 1;
|
|
2299
|
+
const invite = groupInviteFromRecord(message.payload);
|
|
2300
|
+
if (!invite) {
|
|
2301
|
+
this.logger.warn({ keys: Object.keys(message.payload ?? {}).sort() }, "group.invite.received without ids \u2014 dropped");
|
|
2063
2302
|
return;
|
|
2064
2303
|
}
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
if (text.length > MAX_FRAME_BYTES) {
|
|
2068
|
-
this.logger.warn({ bytes: text.length }, "oversized frame \u2014 dropping");
|
|
2069
|
-
return;
|
|
2070
|
-
}
|
|
2071
|
-
let parsed;
|
|
2072
|
-
try {
|
|
2073
|
-
parsed = JSON.parse(text);
|
|
2074
|
-
} catch (err) {
|
|
2075
|
-
this.emitError(
|
|
2076
|
-
new AgentChatChannelError(
|
|
2077
|
-
"validation",
|
|
2078
|
-
"malformed json frame",
|
|
2079
|
-
{ cause: err }
|
|
2080
|
-
)
|
|
2081
|
-
);
|
|
2082
|
-
return;
|
|
2083
|
-
}
|
|
2084
|
-
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
2085
|
-
this.emitError(
|
|
2086
|
-
new AgentChatChannelError("validation", "frame not an object")
|
|
2087
|
-
);
|
|
2088
|
-
return;
|
|
2089
|
-
}
|
|
2090
|
-
const obj = parsed;
|
|
2091
|
-
const type = typeof obj.type === "string" ? obj.type : null;
|
|
2092
|
-
if (!type) {
|
|
2093
|
-
this.emitError(
|
|
2094
|
-
new AgentChatChannelError("validation", "frame missing type")
|
|
2095
|
-
);
|
|
2096
|
-
return;
|
|
2097
|
-
}
|
|
2098
|
-
if (this.state.kind === "AUTHENTICATING") {
|
|
2099
|
-
if (type === "hello.ok") {
|
|
2100
|
-
this.handleHelloOk(received, obj);
|
|
2101
|
-
return;
|
|
2102
|
-
}
|
|
2103
|
-
if (type === "hello.error" || type === "auth.rejected" || type === "error") {
|
|
2104
|
-
const reason = this.extractReason(obj) ?? "auth rejected";
|
|
2105
|
-
this.handleAuthRejected(reason);
|
|
2106
|
-
return;
|
|
2107
|
-
}
|
|
2108
|
-
this.logger.warn({ type }, "frame arrived before hello.ok \u2014 ignoring");
|
|
2109
|
-
return;
|
|
2110
|
-
}
|
|
2111
|
-
const payload = this.extractPayload(obj);
|
|
2112
|
-
this.emit("inboundFrame", {
|
|
2113
|
-
type,
|
|
2114
|
-
payload,
|
|
2115
|
-
receivedAt: received,
|
|
2116
|
-
raw: parsed
|
|
2117
|
-
});
|
|
2304
|
+
this.invites += 1;
|
|
2305
|
+
this.guard("onGroupInvite", () => this.handlers.onGroupInvite?.(invite));
|
|
2118
2306
|
}
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
if (typeof msg === "string") return msg;
|
|
2124
|
-
const reason = payload.reason;
|
|
2125
|
-
if (typeof reason === "string") return reason;
|
|
2126
|
-
}
|
|
2127
|
-
const top = obj.message ?? obj.reason;
|
|
2128
|
-
return typeof top === "string" ? top : void 0;
|
|
2129
|
-
}
|
|
2130
|
-
extractPayload(obj) {
|
|
2131
|
-
const payload = obj.payload;
|
|
2132
|
-
return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
|
|
2133
|
-
}
|
|
2134
|
-
handleHelloOk(now, frame) {
|
|
2135
|
-
if (this.helloAckTimer) {
|
|
2136
|
-
this._clearTimeout(this.helloAckTimer);
|
|
2137
|
-
this.helloAckTimer = null;
|
|
2138
|
-
}
|
|
2139
|
-
const caps = frame.capabilities ?? this.extractPayload(frame).capabilities;
|
|
2140
|
-
this._ackNegotiated = Array.isArray(caps) && caps.includes("ack");
|
|
2141
|
-
this.logger.info({ ackNegotiated: this._ackNegotiated }, "hello.ok");
|
|
2142
|
-
this.applyEvent({ type: "HELLO_OK", now });
|
|
2143
|
-
this.attempt = 0;
|
|
2144
|
-
this.longOutageAnnounced = false;
|
|
2145
|
-
this.authFailAnnounced = false;
|
|
2146
|
-
this.startHeartbeat();
|
|
2147
|
-
this.emit("authenticated", now);
|
|
2148
|
-
}
|
|
2149
|
-
/** The server answered HELLO with a rejection frame (not a close). */
|
|
2150
|
-
handleAuthRejected(reason) {
|
|
2151
|
-
if (this.helloAckTimer) {
|
|
2152
|
-
this._clearTimeout(this.helloAckTimer);
|
|
2153
|
-
this.helloAckTimer = null;
|
|
2154
|
-
}
|
|
2155
|
-
this.enterAuthFail(reason);
|
|
2156
|
-
this.closeSocket(1e3, "auth rejected");
|
|
2157
|
-
}
|
|
2158
|
-
/**
|
|
2159
|
-
* The server rejected this key. AUTH_FAIL is not the end: retry a fresh
|
|
2160
|
-
* HELLO every `AUTH_RETRY_INTERVAL_MS` (jittered). The first rejection in a
|
|
2161
|
-
* run logs at error so an operator sees it; the following ones at debug.
|
|
2162
|
-
*/
|
|
2163
|
-
enterAuthFail(reason) {
|
|
2164
|
-
this.logger[this.authFailAnnounced ? "debug" : "error"](
|
|
2165
|
-
{ reason, retryIntervalMs: AUTH_RETRY_INTERVAL_MS, attempt: this.attempt },
|
|
2166
|
-
"auth rejected \u2014 retrying slowly until the key is accepted again"
|
|
2167
|
-
);
|
|
2168
|
-
this.authFailAnnounced = true;
|
|
2169
|
-
this.applyEvent({ type: "AUTH_REJECTED", reason });
|
|
2170
|
-
this.emitError(
|
|
2171
|
-
new AgentChatChannelError("terminal-auth", `auth rejected: ${reason}`)
|
|
2172
|
-
);
|
|
2173
|
-
this.scheduleAuthRetry();
|
|
2174
|
-
}
|
|
2175
|
-
handleClose(code, reason) {
|
|
2176
|
-
const wasAuthenticating = this.state.kind === "AUTHENTICATING";
|
|
2177
|
-
const wasDraining = this.state.kind === "DRAINING";
|
|
2178
|
-
const ours = this.closeInitiatedLocally;
|
|
2179
|
-
this.closeInitiatedLocally = false;
|
|
2180
|
-
const serverAuthClose = !ours && isHandshakeRejection(code, reason);
|
|
2181
|
-
this.stopHeartbeat();
|
|
2182
|
-
if (this.helloAckTimer) {
|
|
2183
|
-
this._clearTimeout(this.helloAckTimer);
|
|
2184
|
-
this.helloAckTimer = null;
|
|
2185
|
-
}
|
|
2186
|
-
this.ws = null;
|
|
2187
|
-
this._ackNegotiated = false;
|
|
2188
|
-
const kind = this.state.kind;
|
|
2189
|
-
if (kind === "CLOSED") {
|
|
2190
|
-
this.logger.debug({ code, reason }, "socket closed after CLOSED \u2014 no-op");
|
|
2191
|
-
return;
|
|
2192
|
-
}
|
|
2193
|
-
if (kind === "AUTH_FAIL") {
|
|
2194
|
-
this.logger.debug({ code, reason }, "socket closed after AUTH_FAIL \u2014 retry already scheduled");
|
|
2195
|
-
return;
|
|
2196
|
-
}
|
|
2197
|
-
if (serverAuthClose && wasAuthenticating) {
|
|
2198
|
-
this.enterAuthFail(`close ${code}: ${reason}`);
|
|
2199
|
-
return;
|
|
2200
|
-
}
|
|
2201
|
-
this.applyEvent({ type: "SOCKET_CLOSED", code, reason });
|
|
2202
|
-
if (wasDraining || this.state.kind === "CLOSED") {
|
|
2203
|
-
this.emit("closed");
|
|
2204
|
-
return;
|
|
2205
|
-
}
|
|
2206
|
-
this.logger.info(
|
|
2207
|
-
{ code, reason, ours, attempt: this.attempt },
|
|
2208
|
-
"socket closed \u2014 scheduling reconnect"
|
|
2209
|
-
);
|
|
2210
|
-
this.scheduleReconnect(`close-${code}`);
|
|
2211
|
-
}
|
|
2212
|
-
closeSocket(code, reason) {
|
|
2213
|
-
if (!this.ws) return;
|
|
2214
|
-
this.closeInitiatedLocally = true;
|
|
2215
|
-
try {
|
|
2216
|
-
this.ws.close(code, reason);
|
|
2217
|
-
} catch {
|
|
2218
|
-
}
|
|
2219
|
-
}
|
|
2220
|
-
// ─── Internals: heartbeat ────────────────────────────────────────────
|
|
2221
|
-
startHeartbeat() {
|
|
2222
|
-
this.stopHeartbeat();
|
|
2223
|
-
const intervalMs = this.config.ping.intervalMs;
|
|
2224
|
-
this.pingTimer = this._setInterval(() => this.sendPing(), intervalMs);
|
|
2225
|
-
}
|
|
2226
|
-
stopHeartbeat() {
|
|
2227
|
-
if (this.pingTimer) {
|
|
2228
|
-
this._clearInterval(this.pingTimer);
|
|
2229
|
-
this.pingTimer = null;
|
|
2230
|
-
}
|
|
2231
|
-
if (this.pongTimer) {
|
|
2232
|
-
this._clearTimeout(this.pongTimer);
|
|
2233
|
-
this.pongTimer = null;
|
|
2234
|
-
}
|
|
2307
|
+
wake(source, detail) {
|
|
2308
|
+
this.wakes += 1;
|
|
2309
|
+
this.metrics.incWake({ source });
|
|
2310
|
+
this.guard("onWake", () => this.handlers.onWake?.(source, detail));
|
|
2235
2311
|
}
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
try {
|
|
2239
|
-
this.ws.ping();
|
|
2240
|
-
} catch (err) {
|
|
2241
|
-
this.emitError(
|
|
2242
|
-
new AgentChatChannelError(
|
|
2243
|
-
"retry-transient",
|
|
2244
|
-
"ws ping failed",
|
|
2245
|
-
{ cause: err }
|
|
2246
|
-
)
|
|
2247
|
-
);
|
|
2248
|
-
return;
|
|
2249
|
-
}
|
|
2250
|
-
const timeoutMs = this.config.ping.timeoutMs;
|
|
2251
|
-
if (this.pongTimer) this._clearTimeout(this.pongTimer);
|
|
2252
|
-
this.pongTimer = this._setTimeout(() => {
|
|
2253
|
-
this.pongTimer = null;
|
|
2254
|
-
const now = this.now();
|
|
2255
|
-
this.logger.warn({ timeoutMs }, "ping timeout \u2014 declaring degraded");
|
|
2256
|
-
this.applyEvent({ type: "PING_TIMEOUT", now });
|
|
2257
|
-
this.closeSocket(1011, "ping timeout");
|
|
2258
|
-
}, timeoutMs);
|
|
2259
|
-
}
|
|
2260
|
-
handlePong() {
|
|
2261
|
-
if (this.pongTimer) {
|
|
2262
|
-
this._clearTimeout(this.pongTimer);
|
|
2263
|
-
this.pongTimer = null;
|
|
2264
|
-
}
|
|
2265
|
-
if (this.state.kind === "DEGRADED" && this.state.reason === "ping-timeout") {
|
|
2266
|
-
this.applyEvent({ type: "RECOVERED", now: this.now() });
|
|
2267
|
-
}
|
|
2268
|
-
}
|
|
2269
|
-
// ─── Internals: reconnect ────────────────────────────────────────────
|
|
2270
|
-
scheduleReconnect(reason) {
|
|
2271
|
-
if (this.state.kind === "CLOSED" || this.state.kind === "AUTH_FAIL") return;
|
|
2272
|
-
if (this.reconnectTimer) return;
|
|
2273
|
-
const nextAttempt = this.attempt + 1;
|
|
2274
|
-
if (nextAttempt > RECONNECT_LONG_OUTAGE_AFTER_ATTEMPTS && !this.longOutageAnnounced) {
|
|
2275
|
-
this.longOutageAnnounced = true;
|
|
2276
|
-
this.logger.error(
|
|
2277
|
-
{
|
|
2278
|
-
attempt: nextAttempt,
|
|
2279
|
-
maxBackoffMs: Math.max(this.config.reconnect.maxBackoffMs, RECONNECT_LONG_OUTAGE_BACKOFF_MS)
|
|
2280
|
-
},
|
|
2281
|
-
`still reconnecting after ${RECONNECT_LONG_OUTAGE_AFTER_ATTEMPTS} attempts \u2014 backing off further, not giving up`
|
|
2282
|
-
);
|
|
2283
|
-
}
|
|
2284
|
-
const delay = this.computeReconnectDelay(nextAttempt);
|
|
2285
|
-
this.metrics.incReconnect({ reason });
|
|
2286
|
-
this.logger.info(
|
|
2287
|
-
{ attempt: nextAttempt, delayMs: delay, reason },
|
|
2288
|
-
"scheduling reconnect"
|
|
2289
|
-
);
|
|
2290
|
-
this.reconnectTimer = this._setTimeout(() => {
|
|
2291
|
-
this.reconnectTimer = null;
|
|
2292
|
-
this.openSocket(nextAttempt);
|
|
2293
|
-
}, delay);
|
|
2294
|
-
}
|
|
2295
|
-
/** AUTH_FAIL's own cadence: a fresh HELLO every AUTH_RETRY_INTERVAL_MS, jittered. */
|
|
2296
|
-
scheduleAuthRetry() {
|
|
2297
|
-
if (this.state.kind !== "AUTH_FAIL") return;
|
|
2298
|
-
this.clearReconnectTimer();
|
|
2299
|
-
const nextAttempt = this.attempt + 1;
|
|
2300
|
-
const delay = this.jittered(AUTH_RETRY_INTERVAL_MS);
|
|
2301
|
-
this.metrics.incReconnect({ reason: "auth-retry" });
|
|
2302
|
-
this.logger.debug({ attempt: nextAttempt, delayMs: delay }, "scheduling auth retry");
|
|
2303
|
-
this.reconnectTimer = this._setTimeout(() => {
|
|
2304
|
-
this.reconnectTimer = null;
|
|
2305
|
-
this.openSocket(nextAttempt);
|
|
2306
|
-
}, delay);
|
|
2307
|
-
}
|
|
2308
|
-
clearReconnectTimer() {
|
|
2309
|
-
if (this.reconnectTimer) {
|
|
2310
|
-
this._clearTimeout(this.reconnectTimer);
|
|
2311
|
-
this.reconnectTimer = null;
|
|
2312
|
-
}
|
|
2313
|
-
}
|
|
2314
|
-
computeReconnectDelay(attempt) {
|
|
2315
|
-
const { initialBackoffMs, maxBackoffMs } = this.config.reconnect;
|
|
2316
|
-
const reconnectCount = Math.max(1, attempt - 1);
|
|
2317
|
-
const exp = initialBackoffMs * Math.pow(2, Math.min(reconnectCount - 1, 20));
|
|
2318
|
-
const cap = attempt > RECONNECT_LONG_OUTAGE_AFTER_ATTEMPTS ? Math.max(maxBackoffMs, RECONNECT_LONG_OUTAGE_BACKOFF_MS) : maxBackoffMs;
|
|
2319
|
-
return this.jittered(Math.min(exp, cap));
|
|
2320
|
-
}
|
|
2321
|
-
/**
|
|
2322
|
-
* Symmetric ±`jitterRatio`. Thundering-herd-safe: a fleet that all drops
|
|
2323
|
-
* at the same instant re-enters the connect queue spread across
|
|
2324
|
-
* ms * [1-jitterRatio, 1+jitterRatio].
|
|
2325
|
-
*/
|
|
2326
|
-
jittered(ms) {
|
|
2327
|
-
const { jitterRatio } = this.config.reconnect;
|
|
2328
|
-
const jitter = 1 - jitterRatio + this.random() * 2 * jitterRatio;
|
|
2329
|
-
return Math.max(0, Math.floor(ms * jitter));
|
|
2330
|
-
}
|
|
2331
|
-
// ─── Internals: drain ────────────────────────────────────────────────
|
|
2332
|
-
scheduleDrainDeadline(deadline) {
|
|
2333
|
-
if (this.drainTimer) this._clearTimeout(this.drainTimer);
|
|
2334
|
-
const now = this.now();
|
|
2335
|
-
const delay = Math.max(0, deadline - now);
|
|
2336
|
-
this.drainTimer = this._setTimeout(() => {
|
|
2337
|
-
this.drainTimer = null;
|
|
2338
|
-
if (this.state.kind === "DRAINING") {
|
|
2339
|
-
this.logger.warn({ deadline }, "drain deadline exceeded \u2014 force-closing");
|
|
2340
|
-
this.applyEvent({ type: "DRAIN_COMPLETED" });
|
|
2341
|
-
this.closeSocket(1e3, "drain deadline");
|
|
2342
|
-
this.emit("closed");
|
|
2343
|
-
}
|
|
2344
|
-
}, delay);
|
|
2345
|
-
}
|
|
2346
|
-
/**
|
|
2347
|
-
* Called by upper layers when their pending work has fully drained, to
|
|
2348
|
-
* let the WS client transition CLOSED earlier than the deadline.
|
|
2349
|
-
*/
|
|
2350
|
-
drainCompleted() {
|
|
2351
|
-
if (this.state.kind !== "DRAINING") return;
|
|
2352
|
-
if (this.drainTimer) {
|
|
2353
|
-
this._clearTimeout(this.drainTimer);
|
|
2354
|
-
this.drainTimer = null;
|
|
2355
|
-
}
|
|
2356
|
-
this.applyEvent({ type: "DRAIN_COMPLETED" });
|
|
2357
|
-
this.closeSocket(1e3, "drain completed");
|
|
2358
|
-
this.emit("closed");
|
|
2359
|
-
}
|
|
2360
|
-
// ─── Internals: state machine + emit ─────────────────────────────────
|
|
2361
|
-
applyEvent(event) {
|
|
2362
|
-
const prev = this.state;
|
|
2363
|
-
const next = transition(prev, event);
|
|
2364
|
-
if (next === prev) {
|
|
2365
|
-
this.logger.debug(
|
|
2366
|
-
{ from: prev.kind, event: event.type },
|
|
2367
|
-
"transition.invalid"
|
|
2368
|
-
);
|
|
2369
|
-
return;
|
|
2370
|
-
}
|
|
2312
|
+
/** The SDK's state transition, mirrored for the health probe and the gauge, then handed on. */
|
|
2313
|
+
onState(next, prev) {
|
|
2371
2314
|
this.state = next;
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
this.metrics.setConnectionState(next.kind);
|
|
2376
|
-
this.logger.info(
|
|
2377
|
-
{ from: prev.kind, to: next.kind, event: event.type },
|
|
2378
|
-
"state transition"
|
|
2379
|
-
);
|
|
2380
|
-
this.emit("stateChanged", next, prev);
|
|
2315
|
+
this.metrics.setConnectionState(next);
|
|
2316
|
+
this.logger.debug({ from: prev, to: next }, "socket state");
|
|
2317
|
+
this.guard("onStateChanged", () => this.handlers.onStateChanged?.(next, prev));
|
|
2381
2318
|
}
|
|
2382
|
-
|
|
2383
|
-
for (const listener of this.listeners[event]) {
|
|
2384
|
-
try {
|
|
2385
|
-
;
|
|
2386
|
-
listener(...args);
|
|
2387
|
-
} catch (err) {
|
|
2388
|
-
this.logger.error(
|
|
2389
|
-
{ event, err: err instanceof Error ? err.message : String(err) },
|
|
2390
|
-
"listener threw \u2014 continuing"
|
|
2391
|
-
);
|
|
2392
|
-
}
|
|
2393
|
-
}
|
|
2394
|
-
}
|
|
2395
|
-
emitError(error) {
|
|
2396
|
-
this.metrics.incError({ errorClass: error.class_ });
|
|
2397
|
-
this.logger.warn(
|
|
2398
|
-
{ class: error.class_, message: error.message, statusCode: error.statusCode },
|
|
2399
|
-
"channel error"
|
|
2400
|
-
);
|
|
2401
|
-
this.emit("error", error);
|
|
2402
|
-
}
|
|
2403
|
-
};
|
|
2404
|
-
|
|
2405
|
-
// src/knock-frames.ts
|
|
2406
|
-
function readMessageKnock(frame) {
|
|
2407
|
-
if (frame.type !== "message.new") return null;
|
|
2408
|
-
const payload = frame.payload;
|
|
2409
|
-
const senderRaw = payload.sender ?? payload.from ?? "";
|
|
2410
|
-
const sender = typeof senderRaw === "string" ? senderRaw.replace(/^@/, "").toLowerCase() : "";
|
|
2411
|
-
return {
|
|
2412
|
-
kind: "message",
|
|
2413
|
-
sender,
|
|
2414
|
-
messageId: str(payload.id) ?? "<no-id>",
|
|
2415
|
-
conversationId: str(payload.conversation_id) ?? "<no-conv>"
|
|
2416
|
-
};
|
|
2417
|
-
}
|
|
2418
|
-
function readGroupInviteKnock(frame) {
|
|
2419
|
-
if (frame.type !== "group.invite.received") return null;
|
|
2420
|
-
return groupInviteFromRecord(frame.payload);
|
|
2421
|
-
}
|
|
2422
|
-
function groupInviteFromRecord(record) {
|
|
2423
|
-
if (!record || typeof record !== "object" || Array.isArray(record)) return null;
|
|
2424
|
-
const row = record;
|
|
2425
|
-
const inviteId = str(row.id);
|
|
2426
|
-
const groupId = str(row.group_id);
|
|
2427
|
-
if (!inviteId || !groupId) return null;
|
|
2428
|
-
return {
|
|
2429
|
-
kind: "group-invite",
|
|
2430
|
-
inviteId,
|
|
2431
|
-
groupId,
|
|
2432
|
-
groupName: str(row.group_name) ?? "",
|
|
2433
|
-
inviterHandle: (str(row.inviter_handle) ?? "").replace(/^@/, "")
|
|
2434
|
-
};
|
|
2435
|
-
}
|
|
2436
|
-
function str(value) {
|
|
2437
|
-
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
2438
|
-
}
|
|
2439
|
-
|
|
2440
|
-
// src/runtime.ts
|
|
2441
|
-
var BACKLOG_WINDOW_MS = 5e3;
|
|
2442
|
-
var AgentchatChannelRuntime = class {
|
|
2443
|
-
config;
|
|
2444
|
-
handlers;
|
|
2445
|
-
logger;
|
|
2446
|
-
ws;
|
|
2447
|
-
selfHandle;
|
|
2448
|
-
now;
|
|
2449
|
-
started = false;
|
|
2450
|
-
authenticated = false;
|
|
2451
|
-
stopPromise = null;
|
|
2452
|
-
frames = 0;
|
|
2453
|
-
selfFiltered = 0;
|
|
2454
|
-
knocks = 0;
|
|
2455
|
-
invites = 0;
|
|
2456
|
-
authenticatedAt = null;
|
|
2457
|
-
constructor(opts) {
|
|
2458
|
-
this.config = opts.config;
|
|
2459
|
-
this.handlers = opts.handlers ?? {};
|
|
2460
|
-
this.now = opts.now ?? Date.now;
|
|
2461
|
-
this.logger = opts.logger ?? createLogger({
|
|
2462
|
-
level: this.config.observability.logLevel,
|
|
2463
|
-
redactKeys: this.config.observability.redactKeys
|
|
2464
|
-
});
|
|
2465
|
-
this.selfHandle = this.config.agentHandle?.replace(/^@/, "").toLowerCase();
|
|
2466
|
-
this.ws = new AgentchatWsClient({
|
|
2467
|
-
config: this.config,
|
|
2468
|
-
logger: this.logger,
|
|
2469
|
-
metrics: opts.metrics ?? createNoopMetrics(),
|
|
2470
|
-
webSocketCtor: opts.webSocketCtor,
|
|
2471
|
-
now: opts.now,
|
|
2472
|
-
random: opts.random
|
|
2473
|
-
});
|
|
2474
|
-
this.bindWsEvents();
|
|
2475
|
-
}
|
|
2476
|
-
/** Open the transport. Idempotent — subsequent calls are no-ops. */
|
|
2477
|
-
start() {
|
|
2478
|
-
if (this.started) return;
|
|
2479
|
-
this.started = true;
|
|
2480
|
-
this.ws.start();
|
|
2481
|
-
}
|
|
2482
|
-
/** Graceful shutdown: close the socket (nothing is in flight — the runtime sends nothing). */
|
|
2483
|
-
stop(deadlineMs) {
|
|
2484
|
-
if (this.stopPromise) return this.stopPromise;
|
|
2485
|
-
const deadline = deadlineMs ?? this.now() + 5e3;
|
|
2486
|
-
this.stopPromise = new Promise((resolve) => {
|
|
2487
|
-
const off = this.ws.on("closed", () => {
|
|
2488
|
-
off();
|
|
2489
|
-
resolve();
|
|
2490
|
-
});
|
|
2491
|
-
this.ws.stop(deadline);
|
|
2492
|
-
this.ws.drainCompleted();
|
|
2493
|
-
});
|
|
2494
|
-
return this.stopPromise;
|
|
2495
|
-
}
|
|
2496
|
-
/** Operator rotated the API key — leave AUTH_FAIL so the next `start()` can retry. */
|
|
2497
|
-
reconfigured() {
|
|
2498
|
-
this.ws.reconfigured();
|
|
2499
|
-
}
|
|
2500
|
-
getHealth() {
|
|
2501
|
-
return {
|
|
2502
|
-
state: this.ws.getState(),
|
|
2503
|
-
authenticated: this.authenticated,
|
|
2504
|
-
ackNegotiated: this.ws.ackNegotiated,
|
|
2505
|
-
counters: { frames: this.frames, selfFiltered: this.selfFiltered, knocks: this.knocks, invites: this.invites }
|
|
2506
|
-
};
|
|
2507
|
-
}
|
|
2508
|
-
// ─── Internals ─────────────────────────────────────────────────────
|
|
2509
|
-
bindWsEvents() {
|
|
2510
|
-
this.ws.on("stateChanged", (next, prev) => {
|
|
2511
|
-
if (next.kind !== "READY" && next.kind !== "DEGRADED") this.authenticated = false;
|
|
2512
|
-
this.guard("onStateChanged", () => this.handlers.onStateChanged?.(next, prev));
|
|
2513
|
-
});
|
|
2514
|
-
this.ws.on("authenticated", (at) => {
|
|
2515
|
-
this.authenticated = true;
|
|
2516
|
-
this.authenticatedAt = at;
|
|
2517
|
-
if (!this.ws.ackNegotiated) {
|
|
2518
|
-
this.logger.warn({}, "server did not negotiate the ack capability \u2014 envelopes will be marked delivered on push, before any verdict");
|
|
2519
|
-
}
|
|
2520
|
-
this.guard("onAuthenticated", () => this.handlers.onAuthenticated?.(at));
|
|
2521
|
-
this.knock("connect");
|
|
2522
|
-
});
|
|
2523
|
-
this.ws.on("inboundFrame", (frame) => this.dispatchFrame(frame));
|
|
2524
|
-
this.ws.on("error", (error) => {
|
|
2525
|
-
this.guard("onError", () => this.handlers.onError?.(error));
|
|
2526
|
-
});
|
|
2527
|
-
}
|
|
2528
|
-
dispatchFrame(frame) {
|
|
2529
|
-
this.frames += 1;
|
|
2530
|
-
if (frame.type === "message.new") {
|
|
2531
|
-
const knock = readMessageKnock(frame);
|
|
2532
|
-
if (!knock) return;
|
|
2533
|
-
if (this.selfHandle && knock.sender === this.selfHandle) {
|
|
2534
|
-
this.selfFiltered += 1;
|
|
2535
|
-
this.logger.debug({ conversationId: knock.conversationId, messageId: knock.messageId }, "own echo \u2014 not a knock");
|
|
2536
|
-
return;
|
|
2537
|
-
}
|
|
2538
|
-
const backlog = this.authenticatedAt !== null && this.now() - this.authenticatedAt < BACKLOG_WINDOW_MS;
|
|
2539
|
-
this.logger[backlog ? "debug" : "info"](
|
|
2540
|
-
{ conversationId: knock.conversationId, messageId: knock.messageId, from: knock.sender || "?", ...backlog ? { backlog: true } : {} },
|
|
2541
|
-
"knock \u2014 message.new"
|
|
2542
|
-
);
|
|
2543
|
-
this.knock("message");
|
|
2544
|
-
return;
|
|
2545
|
-
}
|
|
2546
|
-
if (frame.type === "group.invite.received") {
|
|
2547
|
-
const invite = readGroupInviteKnock(frame);
|
|
2548
|
-
if (!invite) {
|
|
2549
|
-
this.logger.warn({ keys: Object.keys(frame.payload).sort() }, "group.invite.received without ids \u2014 dropped");
|
|
2550
|
-
return;
|
|
2551
|
-
}
|
|
2552
|
-
this.invites += 1;
|
|
2553
|
-
this.guard("onGroupInvite", () => this.handlers.onGroupInvite?.(invite));
|
|
2554
|
-
return;
|
|
2555
|
-
}
|
|
2556
|
-
this.logger.debug({ type: frame.type }, "frame \u2014 not a knock");
|
|
2557
|
-
}
|
|
2558
|
-
knock(source) {
|
|
2559
|
-
this.knocks += 1;
|
|
2560
|
-
this.guard("onKnock", () => this.handlers.onKnock?.(source));
|
|
2561
|
-
}
|
|
2562
|
-
/** A failing handler never takes the socket down; the next frame knocks again and the tray keeps the cards. */
|
|
2319
|
+
/** A failing handler never takes the socket down; the next frame wakes again and the tray keeps the cards. */
|
|
2563
2320
|
guard(name, fn) {
|
|
2564
2321
|
try {
|
|
2565
2322
|
fn();
|
|
2566
2323
|
} catch (err) {
|
|
2567
|
-
this.logger.error({ err:
|
|
2324
|
+
this.logger.error({ err: describe3(err), handler: name }, "handler threw \u2014 continuing");
|
|
2568
2325
|
}
|
|
2569
2326
|
}
|
|
2570
2327
|
};
|
|
2328
|
+
function classifyRealtimeError(error) {
|
|
2329
|
+
const message = error.message;
|
|
2330
|
+
if (/handler failed/i.test(message)) return "handler";
|
|
2331
|
+
if (/failed validation|not an object|expected a bare array/i.test(message)) return "protocol";
|
|
2332
|
+
if (error.name === "ConnectionError" || /websocket|hello|handshake|liveness|reconnecting|sync drain|sync ack/i.test(message)) return "transport";
|
|
2333
|
+
return "other";
|
|
2334
|
+
}
|
|
2335
|
+
function describe3(err) {
|
|
2336
|
+
return err instanceof Error ? err.message : String(err);
|
|
2337
|
+
}
|
|
2571
2338
|
|
|
2572
2339
|
// src/binding/runtime-registry.ts
|
|
2573
2340
|
var registry = /* @__PURE__ */ new Map();
|
|
@@ -2586,62 +2353,73 @@ function withAccountLock(accountId, op) {
|
|
|
2586
2353
|
);
|
|
2587
2354
|
return next;
|
|
2588
2355
|
}
|
|
2589
|
-
function
|
|
2356
|
+
function registerIntegration(params) {
|
|
2590
2357
|
return withAccountLock(params.accountId, async () => {
|
|
2591
2358
|
const existing = registry.get(params.accountId);
|
|
2592
2359
|
if (existing) {
|
|
2593
|
-
await stopEntry(existing
|
|
2360
|
+
await stopEntry(existing);
|
|
2594
2361
|
registry.delete(params.accountId);
|
|
2595
2362
|
}
|
|
2596
|
-
let runtimeRef = null;
|
|
2597
2363
|
let built = null;
|
|
2598
2364
|
const handlers = {
|
|
2599
|
-
|
|
2365
|
+
onWake: (source, detail) => built?.handlers.onWake?.(source, detail),
|
|
2600
2366
|
onGroupInvite: (invite) => built?.handlers.onGroupInvite?.(invite),
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
|
|
2367
|
+
onConnected: (at) => built?.handlers.onConnected?.(at),
|
|
2368
|
+
onDisconnected: (info) => built?.handlers.onDisconnected?.(info),
|
|
2369
|
+
onBlocked: (info) => built?.handlers.onBlocked?.(info),
|
|
2370
|
+
onError: (error) => built?.handlers.onError?.(error),
|
|
2371
|
+
onStateChanged: (next, prev) => built?.handlers.onStateChanged?.(next, prev)
|
|
2372
|
+
};
|
|
2373
|
+
const create = params.createSocket ?? ((options) => new IntegrationSocket(options));
|
|
2374
|
+
const socket = create({ config: params.config, logger: params.logger, handlers, ...params.socketOptions ?? {} });
|
|
2375
|
+
built = params.build(socket);
|
|
2376
|
+
const entry = {
|
|
2377
|
+
socket,
|
|
2378
|
+
invoker: built.invoker,
|
|
2379
|
+
texts: built.texts ?? null,
|
|
2380
|
+
metrics: params.socketOptions?.metrics ?? null,
|
|
2381
|
+
config: params.config,
|
|
2382
|
+
logger: params.logger
|
|
2604
2383
|
};
|
|
2605
|
-
const create = params.createRuntime ?? ((p) => new AgentchatChannelRuntime(p));
|
|
2606
|
-
runtimeRef = create({ config: params.config, logger: params.logger, handlers });
|
|
2607
|
-
built = params.build(runtimeRef);
|
|
2608
|
-
const entry = { runtime: runtimeRef, invoker: built.invoker, config: params.config, logger: params.logger };
|
|
2609
2384
|
registry.set(params.accountId, entry);
|
|
2610
2385
|
try {
|
|
2611
|
-
|
|
2386
|
+
await socket.start();
|
|
2612
2387
|
} catch (err) {
|
|
2613
2388
|
registry.delete(params.accountId);
|
|
2614
2389
|
built.invoker?.stop();
|
|
2390
|
+
built.texts?.stop();
|
|
2615
2391
|
throw err;
|
|
2616
2392
|
}
|
|
2617
2393
|
return entry;
|
|
2618
2394
|
});
|
|
2619
2395
|
}
|
|
2620
|
-
function
|
|
2396
|
+
function unregisterIntegration(accountId) {
|
|
2621
2397
|
return withAccountLock(accountId, async () => {
|
|
2622
2398
|
const entry = registry.get(accountId);
|
|
2623
2399
|
if (!entry) return;
|
|
2624
2400
|
registry.delete(accountId);
|
|
2625
|
-
await stopEntry(entry
|
|
2401
|
+
await stopEntry(entry);
|
|
2626
2402
|
});
|
|
2627
2403
|
}
|
|
2628
|
-
async function stopEntry(entry
|
|
2404
|
+
async function stopEntry(entry) {
|
|
2629
2405
|
entry.invoker?.stop();
|
|
2406
|
+
entry.texts?.stop();
|
|
2630
2407
|
try {
|
|
2631
|
-
await entry.
|
|
2408
|
+
await entry.socket.stop();
|
|
2632
2409
|
} catch (err) {
|
|
2633
|
-
entry.logger.error({ err: err instanceof Error ? err.message : String(err) }, "
|
|
2410
|
+
entry.logger.error({ err: err instanceof Error ? err.message : String(err) }, "socket.stop threw during unregister");
|
|
2634
2411
|
}
|
|
2635
2412
|
}
|
|
2636
|
-
function
|
|
2413
|
+
function getIntegration(accountId) {
|
|
2637
2414
|
return registry.get(accountId);
|
|
2638
2415
|
}
|
|
2639
2416
|
|
|
2640
|
-
// src/
|
|
2417
|
+
// src/integration/wake.ts
|
|
2641
2418
|
var DEFAULT_DEBOUNCE_MS = 2e3;
|
|
2642
2419
|
var DEFAULT_MAX_WINDOW_MS = 6e3;
|
|
2643
|
-
var
|
|
2420
|
+
var WakeCoalescer = class {
|
|
2644
2421
|
onFire;
|
|
2422
|
+
onDelayedWake;
|
|
2645
2423
|
debounceMs;
|
|
2646
2424
|
maxWindowMs;
|
|
2647
2425
|
now;
|
|
@@ -2652,7 +2430,7 @@ var KnockCoalescer = class {
|
|
|
2652
2430
|
delayed = null;
|
|
2653
2431
|
delayedDeadline = null;
|
|
2654
2432
|
stopped = false;
|
|
2655
|
-
|
|
2433
|
+
wakes = 0;
|
|
2656
2434
|
absorbed = 0;
|
|
2657
2435
|
fires = 0;
|
|
2658
2436
|
constructor(options) {
|
|
@@ -2661,6 +2439,7 @@ var KnockCoalescer = class {
|
|
|
2661
2439
|
const maxWindow = options.maxWindowMs ?? DEFAULT_MAX_WINDOW_MS;
|
|
2662
2440
|
if (!(maxWindow >= debounce)) throw new RangeError("maxWindowMs must be >= debounceMs");
|
|
2663
2441
|
this.onFire = options.onFire;
|
|
2442
|
+
this.onDelayedWake = options.onDelayedWake;
|
|
2664
2443
|
this.debounceMs = debounce;
|
|
2665
2444
|
this.maxWindowMs = maxWindow;
|
|
2666
2445
|
this.now = options.now ?? Date.now;
|
|
@@ -2671,17 +2450,17 @@ var KnockCoalescer = class {
|
|
|
2671
2450
|
get armed() {
|
|
2672
2451
|
return this.timer !== null;
|
|
2673
2452
|
}
|
|
2674
|
-
/** True while a retry
|
|
2453
|
+
/** True while a retry wake is scheduled and has not fired. */
|
|
2675
2454
|
get delayedPending() {
|
|
2676
2455
|
return this.delayed !== null;
|
|
2677
2456
|
}
|
|
2678
2457
|
/**
|
|
2679
|
-
* A
|
|
2458
|
+
* A wake. The first one of a burst arms the window; every later one is
|
|
2680
2459
|
* absorbed and restarts it (trailing edge), never past the burst's cap.
|
|
2681
2460
|
*/
|
|
2682
|
-
|
|
2461
|
+
wake() {
|
|
2683
2462
|
if (this.stopped) return;
|
|
2684
|
-
this.
|
|
2463
|
+
this.wakes += 1;
|
|
2685
2464
|
const now = this.now();
|
|
2686
2465
|
if (this.timer === null) {
|
|
2687
2466
|
this.burstStartedAt = now;
|
|
@@ -2694,8 +2473,8 @@ var KnockCoalescer = class {
|
|
|
2694
2473
|
this._clearTimeout(this.timer);
|
|
2695
2474
|
this.timer = this._setTimeout(() => this.fire(), delay);
|
|
2696
2475
|
}
|
|
2697
|
-
/** A delayed
|
|
2698
|
-
|
|
2476
|
+
/** A delayed wake (retry ladder). The sooner pending deadline is kept. */
|
|
2477
|
+
wakeAfter(delayMs) {
|
|
2699
2478
|
if (this.stopped) return;
|
|
2700
2479
|
const delay = Math.max(0, delayMs);
|
|
2701
2480
|
const deadline = this.now() + delay;
|
|
@@ -2709,10 +2488,15 @@ var KnockCoalescer = class {
|
|
|
2709
2488
|
this.delayed = this._setTimeout(() => {
|
|
2710
2489
|
this.delayed = null;
|
|
2711
2490
|
this.delayedDeadline = null;
|
|
2712
|
-
this.
|
|
2491
|
+
if (this.stopped) return;
|
|
2492
|
+
try {
|
|
2493
|
+
this.onDelayedWake?.();
|
|
2494
|
+
} catch {
|
|
2495
|
+
}
|
|
2496
|
+
this.wake();
|
|
2713
2497
|
}, delay);
|
|
2714
2498
|
}
|
|
2715
|
-
/** Cancel everything; later
|
|
2499
|
+
/** Cancel everything; later wakes are ignored. */
|
|
2716
2500
|
stop() {
|
|
2717
2501
|
this.stopped = true;
|
|
2718
2502
|
if (this.timer !== null) {
|
|
@@ -2738,453 +2522,93 @@ var KnockCoalescer = class {
|
|
|
2738
2522
|
}
|
|
2739
2523
|
};
|
|
2740
2524
|
|
|
2741
|
-
// src/
|
|
2742
|
-
var DEFAULT_TIMEOUT_MS2 = 15e3;
|
|
2743
|
-
var INBOX_MAX_LIMIT = 50;
|
|
2744
|
-
var INBOX_WAIT_MAX_MS = 5e4;
|
|
2745
|
-
var INBOX_PATH = "/v1/inbox";
|
|
2746
|
-
var MainLineError = class extends Error {
|
|
2747
|
-
status;
|
|
2748
|
-
code;
|
|
2749
|
-
constructor(message, options = {}) {
|
|
2750
|
-
super(message, { cause: options.cause });
|
|
2751
|
-
this.name = "MainLineError";
|
|
2752
|
-
this.status = options.status;
|
|
2753
|
-
this.code = options.code;
|
|
2754
|
-
}
|
|
2755
|
-
};
|
|
2756
|
-
var MainLineClient = class {
|
|
2757
|
-
apiKey;
|
|
2758
|
-
apiBase;
|
|
2759
|
-
timeoutMs;
|
|
2760
|
-
fetchImpl;
|
|
2761
|
-
constructor(options) {
|
|
2762
|
-
this.apiKey = options.apiKey;
|
|
2763
|
-
this.apiBase = options.apiBase.replace(/\/+$/, "");
|
|
2764
|
-
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
|
|
2765
|
-
this.fetchImpl = options.fetch ?? fetch;
|
|
2766
|
-
}
|
|
2767
|
-
/**
|
|
2768
|
-
* `GET /v1/inbox` — the briefing cards plus the gate question, returned as
|
|
2769
|
-
* the server sent them (`you`, `question`, `categories`, `conversations`,
|
|
2770
|
-
* `deferred`, `truncated`, and any field a newer server adds). Marks
|
|
2771
|
-
* nothing delivered.
|
|
2772
|
-
*/
|
|
2773
|
-
async inbox(params = {}) {
|
|
2774
|
-
const waitMs = params.waitMs ?? 0;
|
|
2775
|
-
const limit = params.limit ?? INBOX_MAX_LIMIT;
|
|
2776
|
-
if (!Number.isInteger(waitMs) || waitMs < 0 || waitMs > INBOX_WAIT_MAX_MS) {
|
|
2777
|
-
throw new RangeError(`waitMs must be an integer within 0..${INBOX_WAIT_MAX_MS}`);
|
|
2778
|
-
}
|
|
2779
|
-
if (!Number.isInteger(limit) || limit < 1 || limit > INBOX_MAX_LIMIT) {
|
|
2780
|
-
throw new RangeError(`limit must be an integer within 1..${INBOX_MAX_LIMIT}`);
|
|
2781
|
-
}
|
|
2782
|
-
const url = `${this.apiBase}${INBOX_PATH}?wait_ms=${waitMs}&limit=${limit}`;
|
|
2783
|
-
const data = await this.request("GET", url, void 0, this.timeoutMs + waitMs);
|
|
2784
|
-
if (!data || typeof data !== "object" || Array.isArray(data)) {
|
|
2785
|
-
throw new MainLineError(`GET ${INBOX_PATH}: expected a JSON object`);
|
|
2786
|
-
}
|
|
2787
|
-
return data;
|
|
2788
|
-
}
|
|
2789
|
-
/**
|
|
2790
|
-
* `POST /v1/conversations/{id}/decisions` — record one verdict. The server
|
|
2791
|
-
* validates `decision`, `category` and `defer_seconds` against its own
|
|
2792
|
-
* taxonomy; this client passes them through and raises `MainLineError`
|
|
2793
|
-
* (`status` 400) when the server rejects a value, so the caller can retry
|
|
2794
|
-
* with less.
|
|
2795
|
-
*/
|
|
2796
|
-
async recordDecision(conversationId, input) {
|
|
2797
|
-
if (!conversationId) throw new RangeError("conversationId is required");
|
|
2798
|
-
const body = { decision: input.decision };
|
|
2799
|
-
if (input.category) body.category = input.category;
|
|
2800
|
-
if (input.throughMessageId) body.through_message_id = input.throughMessageId;
|
|
2801
|
-
if (input.deferSeconds !== void 0) body.defer_seconds = input.deferSeconds;
|
|
2802
|
-
const path2 = `/v1/conversations/${encodeURIComponent(conversationId)}/decisions`;
|
|
2803
|
-
const data = await this.request("POST", `${this.apiBase}${path2}`, body, this.timeoutMs);
|
|
2804
|
-
return data && typeof data === "object" && !Array.isArray(data) ? data : {};
|
|
2805
|
-
}
|
|
2806
|
-
async request(method, url, body, timeoutMs) {
|
|
2807
|
-
const controller = new AbortController();
|
|
2808
|
-
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
2809
|
-
const what = `${method} ${new URL(url).pathname}`;
|
|
2810
|
-
let res;
|
|
2811
|
-
try {
|
|
2812
|
-
res = await this.fetchImpl(url, {
|
|
2813
|
-
method,
|
|
2814
|
-
headers: {
|
|
2815
|
-
authorization: `Bearer ${this.apiKey}`,
|
|
2816
|
-
accept: "application/json",
|
|
2817
|
-
...body !== void 0 ? { "content-type": "application/json" } : {},
|
|
2818
|
-
...AGENTCHAT_CLIENT_HEADERS
|
|
2819
|
-
},
|
|
2820
|
-
...body !== void 0 ? { body: JSON.stringify(body) } : {},
|
|
2821
|
-
signal: controller.signal
|
|
2822
|
-
});
|
|
2823
|
-
} catch (err) {
|
|
2824
|
-
throw new MainLineError(`${what}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
|
|
2825
|
-
} finally {
|
|
2826
|
-
clearTimeout(timer);
|
|
2827
|
-
}
|
|
2828
|
-
const text = await res.text().catch(() => "");
|
|
2829
|
-
let parsed = void 0;
|
|
2830
|
-
if (text.length > 0) {
|
|
2831
|
-
try {
|
|
2832
|
-
parsed = JSON.parse(text);
|
|
2833
|
-
} catch {
|
|
2834
|
-
if (res.ok) throw new MainLineError(`${what}: invalid JSON in a ${res.status} answer`, { status: res.status });
|
|
2835
|
-
}
|
|
2836
|
-
}
|
|
2837
|
-
if (res.ok) return parsed ?? {};
|
|
2838
|
-
const fields = parsed && typeof parsed === "object" ? parsed : {};
|
|
2839
|
-
const code = typeof fields.code === "string" ? fields.code : void 0;
|
|
2840
|
-
const message = typeof fields.message === "string" ? fields.message : void 0;
|
|
2841
|
-
throw new MainLineError(
|
|
2842
|
-
`${what}: HTTP ${res.status}${code ? ` ${code}` : ""}${message ? ` \u2014 ${message}` : ""}`,
|
|
2843
|
-
{ status: res.status, code }
|
|
2844
|
-
);
|
|
2845
|
-
}
|
|
2846
|
-
};
|
|
2847
|
-
|
|
2848
|
-
// src/doorbell/gate.ts
|
|
2849
|
-
var DEFAULT_GATE_MAX_TOKENS = 2048;
|
|
2850
|
-
var REPLY = "reply";
|
|
2851
|
-
var DISMISS = "dismiss";
|
|
2852
|
-
var DEFER = "defer";
|
|
2853
|
-
var REPLY_TOKENS = /* @__PURE__ */ new Set(["reply", "respond", "answer", "yes", "true"]);
|
|
2854
|
-
var DISMISS_TOKENS = /* @__PURE__ */ new Set([
|
|
2855
|
-
"dismiss",
|
|
2856
|
-
"dismissed",
|
|
2857
|
-
"no_reply",
|
|
2858
|
-
"no-reply",
|
|
2859
|
-
"noreply",
|
|
2860
|
-
"silent",
|
|
2861
|
-
"silence",
|
|
2862
|
-
"skip",
|
|
2863
|
-
"ignore",
|
|
2864
|
-
"no",
|
|
2865
|
-
"false"
|
|
2866
|
-
]);
|
|
2867
|
-
var DEFER_TOKENS = /* @__PURE__ */ new Set(["defer", "deferred", "later", "wait", "postpone"]);
|
|
2868
|
-
var FENCE_RE = /```(?:json)?\s*([\s\S]+?)```/i;
|
|
2869
|
-
function startTurn(result) {
|
|
2870
|
-
return result.replyConversations.length > 0 || result.source === "fail_open";
|
|
2871
|
-
}
|
|
2872
|
-
function countVerdicts(result) {
|
|
2873
|
-
const counts = { reply: 0, dismiss: 0, defer: 0 };
|
|
2874
|
-
for (const verdict of result.verdicts) counts[verdict.decision] += 1;
|
|
2875
|
-
return counts;
|
|
2876
|
-
}
|
|
2877
|
-
function cardsOf(tray) {
|
|
2878
|
-
const raw = tray.conversations;
|
|
2879
|
-
if (!Array.isArray(raw)) return [];
|
|
2880
|
-
return raw.filter((card) => Boolean(card) && typeof card === "object" && !Array.isArray(card));
|
|
2881
|
-
}
|
|
2882
|
-
function cardIds(cards) {
|
|
2883
|
-
const out = [];
|
|
2884
|
-
for (const card of cards) {
|
|
2885
|
-
const id = card.conversation_id;
|
|
2886
|
-
if (typeof id === "string" && id.length > 0) out.push(id);
|
|
2887
|
-
}
|
|
2888
|
-
return out;
|
|
2889
|
-
}
|
|
2890
|
-
function categoriesOf(tray) {
|
|
2891
|
-
const raw = tray.categories;
|
|
2892
|
-
if (!Array.isArray(raw)) return [];
|
|
2893
|
-
return raw.filter((item) => typeof item === "string" && item.length > 0);
|
|
2894
|
-
}
|
|
2895
|
-
function buildGateMessages(tray) {
|
|
2896
|
-
const question = tray.question;
|
|
2897
|
-
if (typeof question !== "string" || question.trim().length === 0) {
|
|
2898
|
-
throw new Error("tray carries no gate question");
|
|
2899
|
-
}
|
|
2900
|
-
const cards = cardsOf(tray);
|
|
2901
|
-
const categories = categoriesOf(tray);
|
|
2902
|
-
let shape = '{"decisions": [{"conversation_id": "<conversation_id from a card>", "decision": "reply" | "dismiss" | "defer"';
|
|
2903
|
-
if (categories.length > 0) {
|
|
2904
|
-
shape += `, "category": "<one of: ${categories.join(", ")}>"`;
|
|
2905
|
-
}
|
|
2906
|
-
shape += ', "defer_seconds": <seconds until you look again, only with defer>}]}';
|
|
2907
|
-
const wrapper = "Answer with ONLY a JSON object, no prose and no code fences, in this shape: " + shape + " \u2014 one entry per card, every card decided.";
|
|
2908
|
-
const payload = {};
|
|
2909
|
-
if (typeof tray.you === "string" && tray.you.length > 0) payload.you = tray.you;
|
|
2910
|
-
payload.conversations = cards;
|
|
2911
|
-
return {
|
|
2912
|
-
systemPrompt: `${question.trim()}
|
|
2913
|
-
|
|
2914
|
-
${wrapper}`,
|
|
2915
|
-
userContent: `Your tray, as the server built it:
|
|
2916
|
-
${JSON.stringify(payload)}`
|
|
2917
|
-
};
|
|
2918
|
-
}
|
|
2919
|
-
function parseVerdicts(text, params) {
|
|
2920
|
-
const raw = extractJson(text);
|
|
2921
|
-
if (raw === null) return null;
|
|
2922
|
-
let obj;
|
|
2923
|
-
try {
|
|
2924
|
-
obj = JSON.parse(raw);
|
|
2925
|
-
} catch {
|
|
2926
|
-
return null;
|
|
2927
|
-
}
|
|
2928
|
-
let items;
|
|
2929
|
-
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
|
2930
|
-
const record = obj;
|
|
2931
|
-
items = record.decisions ?? record.verdicts;
|
|
2932
|
-
if (items === void 0 && "conversation_id" in record) items = [record];
|
|
2933
|
-
} else {
|
|
2934
|
-
items = obj;
|
|
2935
|
-
}
|
|
2936
|
-
if (!Array.isArray(items)) return null;
|
|
2937
|
-
const known = new Set(params.knownIds);
|
|
2938
|
-
const allowed = new Set((params.categories ?? []).map((c) => c.toLowerCase()));
|
|
2939
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2940
|
-
const out = [];
|
|
2941
|
-
for (const item of items) {
|
|
2942
|
-
if (!item || typeof item !== "object" || Array.isArray(item)) continue;
|
|
2943
|
-
const entry = item;
|
|
2944
|
-
const id = entry.conversation_id;
|
|
2945
|
-
if (typeof id !== "string" || !known.has(id) || seen.has(id)) continue;
|
|
2946
|
-
const decision = normalizeDecision(entry.decision);
|
|
2947
|
-
if (decision === null) continue;
|
|
2948
|
-
seen.add(id);
|
|
2949
|
-
const category = normalizeCategory(entry.category, allowed);
|
|
2950
|
-
const deferSeconds = decision === DEFER ? normalizeDeferSeconds(entry.defer_seconds) : void 0;
|
|
2951
|
-
out.push({
|
|
2952
|
-
conversationId: id,
|
|
2953
|
-
decision,
|
|
2954
|
-
...category !== void 0 ? { category } : {},
|
|
2955
|
-
...deferSeconds !== void 0 ? { deferSeconds } : {}
|
|
2956
|
-
});
|
|
2957
|
-
}
|
|
2958
|
-
return out;
|
|
2959
|
-
}
|
|
2960
|
-
function extractJson(text) {
|
|
2961
|
-
if (!text || text.trim().length === 0) return null;
|
|
2962
|
-
let s = text.trim();
|
|
2963
|
-
const fence = FENCE_RE.exec(s);
|
|
2964
|
-
if (fence?.[1]) s = fence[1].trim();
|
|
2965
|
-
const starts = [s.indexOf("{"), s.indexOf("[")].filter((i) => i !== -1);
|
|
2966
|
-
if (starts.length === 0) return null;
|
|
2967
|
-
const start = Math.min(...starts);
|
|
2968
|
-
const closer = s[start] === "{" ? "}" : "]";
|
|
2969
|
-
const end = s.lastIndexOf(closer);
|
|
2970
|
-
if (end <= start) return null;
|
|
2971
|
-
return s.slice(start, end + 1);
|
|
2972
|
-
}
|
|
2973
|
-
function normalizeDecision(value) {
|
|
2974
|
-
if (typeof value !== "string") return null;
|
|
2975
|
-
const token = value.trim().toLowerCase().replace(/\s+/g, "_");
|
|
2976
|
-
if (REPLY_TOKENS.has(token)) return REPLY;
|
|
2977
|
-
if (DISMISS_TOKENS.has(token)) return DISMISS;
|
|
2978
|
-
if (DEFER_TOKENS.has(token)) return DEFER;
|
|
2979
|
-
return null;
|
|
2980
|
-
}
|
|
2981
|
-
function normalizeCategory(value, allowed) {
|
|
2982
|
-
if (allowed.size === 0 || typeof value !== "string") return void 0;
|
|
2983
|
-
const token = value.trim().toLowerCase();
|
|
2984
|
-
return allowed.has(token) ? token : void 0;
|
|
2985
|
-
}
|
|
2986
|
-
function normalizeDeferSeconds(value) {
|
|
2987
|
-
if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
|
|
2988
|
-
const seconds = Math.trunc(value);
|
|
2989
|
-
return seconds > 0 ? seconds : void 0;
|
|
2990
|
-
}
|
|
2991
|
-
async function runGate(params) {
|
|
2992
|
-
const cards = cardsOf(params.tray);
|
|
2993
|
-
const ids = cardIds(cards);
|
|
2994
|
-
const truncated = params.tray.truncated === true;
|
|
2995
|
-
const now = params.now ?? Date.now;
|
|
2996
|
-
const log = params.log ?? (() => void 0);
|
|
2997
|
-
if (ids.length === 0) return emptyResult("empty", truncated);
|
|
2998
|
-
const started = now();
|
|
2999
|
-
let text;
|
|
3000
|
-
try {
|
|
3001
|
-
const messages = buildGateMessages(params.tray);
|
|
3002
|
-
text = await params.caller({
|
|
3003
|
-
systemPrompt: messages.systemPrompt,
|
|
3004
|
-
userContent: messages.userContent,
|
|
3005
|
-
maxTokens: params.maxTokens ?? DEFAULT_GATE_MAX_TOKENS,
|
|
3006
|
-
timeoutMs: params.timeoutMs
|
|
3007
|
-
});
|
|
3008
|
-
} catch (err) {
|
|
3009
|
-
const reason = `decision call failed: ${err instanceof Error ? err.message : String(err)}`;
|
|
3010
|
-
log("warn", `gate: ${reason} (${ids.length} cards)`);
|
|
3011
|
-
return failedResult(ids, params.failOpen, reason, now() - started, truncated);
|
|
3012
|
-
}
|
|
3013
|
-
const latencyMs = now() - started;
|
|
3014
|
-
const verdicts = parseVerdicts(text, { knownIds: ids, categories: categoriesOf(params.tray) });
|
|
3015
|
-
if (!verdicts || verdicts.length === 0) {
|
|
3016
|
-
log("warn", `gate: unusable answer for ${ids.length} cards (latency ${latencyMs} ms)`);
|
|
3017
|
-
log("debug", `gate: raw model output: ${(text ?? "").slice(0, 200)}`);
|
|
3018
|
-
return failedResult(ids, params.failOpen, "no usable verdicts in the answer", latencyMs, truncated);
|
|
3019
|
-
}
|
|
3020
|
-
const byId = /* @__PURE__ */ new Map();
|
|
3021
|
-
for (const card of cards) {
|
|
3022
|
-
const id = card.conversation_id;
|
|
3023
|
-
if (typeof id === "string") byId.set(id, card);
|
|
3024
|
-
}
|
|
3025
|
-
const decided = new Set(verdicts.map((v) => v.conversationId));
|
|
3026
|
-
const undecided = ids.filter((id) => !decided.has(id));
|
|
3027
|
-
const reply = [];
|
|
3028
|
-
let posted = 0;
|
|
3029
|
-
let postFailures = 0;
|
|
3030
|
-
for (const verdict of verdicts) {
|
|
3031
|
-
if (verdict.decision === REPLY) {
|
|
3032
|
-
reply.push(verdict.conversationId);
|
|
3033
|
-
continue;
|
|
3034
|
-
}
|
|
3035
|
-
if (await postVerdict(params.mainLine, verdict, byId.get(verdict.conversationId), log)) posted += 1;
|
|
3036
|
-
else postFailures += 1;
|
|
3037
|
-
}
|
|
3038
|
-
if (undecided.length > 0) {
|
|
3039
|
-
log("warn", `gate: ${undecided.length} of ${ids.length} cards left undecided by the model: ${undecided.join(", ")}`);
|
|
3040
|
-
}
|
|
3041
|
-
return {
|
|
3042
|
-
source: "llm",
|
|
3043
|
-
cards: ids.length,
|
|
3044
|
-
verdicts,
|
|
3045
|
-
undecided,
|
|
3046
|
-
replyConversations: reply,
|
|
3047
|
-
posted,
|
|
3048
|
-
postFailures,
|
|
3049
|
-
truncated,
|
|
3050
|
-
latencyMs,
|
|
3051
|
-
failure: null
|
|
3052
|
-
};
|
|
3053
|
-
}
|
|
3054
|
-
function emptyResult(source, truncated, replyConversations = []) {
|
|
3055
|
-
return {
|
|
3056
|
-
source,
|
|
3057
|
-
cards: replyConversations.length,
|
|
3058
|
-
verdicts: [],
|
|
3059
|
-
undecided: [],
|
|
3060
|
-
replyConversations,
|
|
3061
|
-
posted: 0,
|
|
3062
|
-
postFailures: 0,
|
|
3063
|
-
truncated,
|
|
3064
|
-
latencyMs: 0,
|
|
3065
|
-
failure: null
|
|
3066
|
-
};
|
|
3067
|
-
}
|
|
3068
|
-
function failedResult(ids, failOpen, reason, latencyMs, truncated) {
|
|
3069
|
-
return {
|
|
3070
|
-
source: failOpen ? "fail_open" : "fail_closed",
|
|
3071
|
-
cards: ids.length,
|
|
3072
|
-
verdicts: [],
|
|
3073
|
-
undecided: ids,
|
|
3074
|
-
replyConversations: failOpen ? ids : [],
|
|
3075
|
-
posted: 0,
|
|
3076
|
-
postFailures: 0,
|
|
3077
|
-
truncated,
|
|
3078
|
-
latencyMs,
|
|
3079
|
-
failure: reason
|
|
3080
|
-
};
|
|
3081
|
-
}
|
|
3082
|
-
async function postVerdict(mainLine, verdict, card, log = () => void 0) {
|
|
3083
|
-
const through = previewMessageId(card);
|
|
3084
|
-
try {
|
|
3085
|
-
await mainLine.recordDecision(verdict.conversationId, {
|
|
3086
|
-
decision: verdict.decision,
|
|
3087
|
-
category: verdict.category,
|
|
3088
|
-
throughMessageId: through,
|
|
3089
|
-
deferSeconds: verdict.deferSeconds
|
|
3090
|
-
});
|
|
3091
|
-
return true;
|
|
3092
|
-
} catch (err) {
|
|
3093
|
-
const retryable = err instanceof MainLineError && err.status === 400 && (verdict.category !== void 0 || verdict.deferSeconds !== void 0);
|
|
3094
|
-
if (!retryable) {
|
|
3095
|
-
log("warn", `gate: verdict ${verdict.decision} for ${verdict.conversationId} not recorded: ${describe2(err)}`);
|
|
3096
|
-
return false;
|
|
3097
|
-
}
|
|
3098
|
-
log("warn", `gate: server rejected optional fields for ${verdict.conversationId} (${describe2(err)}) \u2014 retrying bare verdict`);
|
|
3099
|
-
}
|
|
3100
|
-
try {
|
|
3101
|
-
await mainLine.recordDecision(verdict.conversationId, {
|
|
3102
|
-
decision: verdict.decision,
|
|
3103
|
-
throughMessageId: through
|
|
3104
|
-
});
|
|
3105
|
-
return true;
|
|
3106
|
-
} catch (err) {
|
|
3107
|
-
log("warn", `gate: verdict ${verdict.decision} for ${verdict.conversationId} not recorded: ${describe2(err)}`);
|
|
3108
|
-
return false;
|
|
3109
|
-
}
|
|
3110
|
-
}
|
|
3111
|
-
function previewMessageId(card) {
|
|
3112
|
-
if (!card) return void 0;
|
|
3113
|
-
const preview = card.preview;
|
|
3114
|
-
if (!preview || typeof preview !== "object" || Array.isArray(preview)) return void 0;
|
|
3115
|
-
const id = preview.message_id;
|
|
3116
|
-
return typeof id === "string" && id.length > 0 ? id : void 0;
|
|
3117
|
-
}
|
|
3118
|
-
function describe2(err) {
|
|
3119
|
-
return err instanceof Error ? err.message : String(err);
|
|
3120
|
-
}
|
|
3121
|
-
|
|
3122
|
-
// src/doorbell/invoker.ts
|
|
3123
|
-
var DEFAULT_GATE_TIMEOUT_MS = 2e4;
|
|
2525
|
+
// src/integration/invoker.ts
|
|
3124
2526
|
var RETRY_LADDER_MS = [6e4, 3e5, 18e5];
|
|
3125
2527
|
var AgentInvoker = class {
|
|
3126
2528
|
accountId;
|
|
3127
2529
|
agentId;
|
|
3128
|
-
|
|
3129
|
-
|
|
3130
|
-
|
|
2530
|
+
client;
|
|
2531
|
+
callModel;
|
|
2532
|
+
startTurn;
|
|
2533
|
+
texts;
|
|
2534
|
+
invites;
|
|
3131
2535
|
logger;
|
|
2536
|
+
metrics;
|
|
2537
|
+
readiness;
|
|
3132
2538
|
gateEnabled;
|
|
3133
|
-
gateFailOpen;
|
|
3134
|
-
gateTimeoutMs;
|
|
3135
2539
|
ladder;
|
|
3136
2540
|
now;
|
|
3137
2541
|
coalescer;
|
|
3138
2542
|
cycleDue = false;
|
|
3139
2543
|
running = null;
|
|
3140
2544
|
stopped = false;
|
|
3141
|
-
|
|
3142
|
-
|
|
2545
|
+
pendingInvites = [];
|
|
2546
|
+
invitesDirty = false;
|
|
3143
2547
|
retryRung = 0;
|
|
2548
|
+
turnsInFlight = 0;
|
|
2549
|
+
/**
|
|
2550
|
+
* Conversations whose reply turn is running. Their verdict is recorded
|
|
2551
|
+
* only when the turn completes, so the card stays on the tray meanwhile
|
|
2552
|
+
* and every wake in between would re-gate it and queue a second turn.
|
|
2553
|
+
* Such cards are left out of the cycle; once the turn ends the tray is
|
|
2554
|
+
* read again if any were.
|
|
2555
|
+
*/
|
|
2556
|
+
replyTurnsInFlight = /* @__PURE__ */ new Set();
|
|
2557
|
+
skippedWhileInFlight = false;
|
|
2558
|
+
/** The reason the tools were last found unavailable; logged when it changes, not per wake. */
|
|
2559
|
+
unreadyReason = null;
|
|
3144
2560
|
cycles = 0;
|
|
3145
2561
|
turns = 0;
|
|
3146
2562
|
inviteTurns = 0;
|
|
3147
2563
|
constructor(options) {
|
|
3148
2564
|
this.accountId = options.accountId;
|
|
3149
2565
|
this.agentId = options.agentId;
|
|
3150
|
-
this.
|
|
3151
|
-
this.
|
|
3152
|
-
this.
|
|
3153
|
-
this.
|
|
2566
|
+
this.client = options.client;
|
|
2567
|
+
this.callModel = options.callModel;
|
|
2568
|
+
this.startTurn = options.startTurn;
|
|
2569
|
+
this.texts = options.texts;
|
|
2570
|
+
this.invites = options.invites;
|
|
2571
|
+
this.logger = options.logger.child({ component: "integration", accountId: options.accountId });
|
|
2572
|
+
this.metrics = options.metrics ?? createNoopMetrics();
|
|
2573
|
+
this.readiness = options.readiness ?? (() => ({ ready: true }));
|
|
3154
2574
|
this.gateEnabled = options.gateEnabled ?? true;
|
|
3155
|
-
this.gateFailOpen = options.gateFailOpen ?? false;
|
|
3156
|
-
this.gateTimeoutMs = options.gateTimeoutMs ?? DEFAULT_GATE_TIMEOUT_MS;
|
|
3157
2575
|
this.ladder = options.retryLadderMs ?? RETRY_LADDER_MS;
|
|
3158
2576
|
this.now = options.now ?? Date.now;
|
|
3159
|
-
this.coalescer = new
|
|
3160
|
-
onFire: () => this.
|
|
2577
|
+
this.coalescer = new WakeCoalescer({
|
|
2578
|
+
onFire: () => this.onWakeFired(),
|
|
2579
|
+
onDelayedWake: () => {
|
|
2580
|
+
this.logger.debug({ source: "retry" }, "wake");
|
|
2581
|
+
this.metrics.incWake({ source: "retry" });
|
|
2582
|
+
},
|
|
3161
2583
|
debounceMs: options.debounceMs ?? DEFAULT_DEBOUNCE_MS,
|
|
3162
2584
|
now: this.now,
|
|
3163
2585
|
...options.setTimeout ? { setTimeout: options.setTimeout } : {},
|
|
3164
2586
|
...options.clearTimeout ? { clearTimeout: options.clearTimeout } : {}
|
|
3165
2587
|
});
|
|
3166
2588
|
}
|
|
3167
|
-
// ───
|
|
3168
|
-
/** A
|
|
3169
|
-
|
|
2589
|
+
// ─── wakes ──────────────────────────────────────────────────────────
|
|
2590
|
+
/** A wake from the socket (a frame, a connect, a reminder) or any other source. Coalesced, then cycled. */
|
|
2591
|
+
wake(source) {
|
|
3170
2592
|
if (this.stopped) return;
|
|
3171
|
-
this.logger.debug({ source }, "
|
|
3172
|
-
this.coalescer.
|
|
2593
|
+
this.logger.debug({ source }, "wake");
|
|
2594
|
+
this.coalescer.wake();
|
|
3173
2595
|
}
|
|
3174
2596
|
/**
|
|
3175
|
-
* The second
|
|
3176
|
-
*
|
|
3177
|
-
*
|
|
2597
|
+
* The second wake kind. An invite already offered (this process or an
|
|
2598
|
+
* earlier one, per the ledger) or already pending is ignored, so an
|
|
2599
|
+
* invite seen live and again on a connect-time catch-up is decided once.
|
|
2600
|
+
* Returns true when newly queued.
|
|
3178
2601
|
*/
|
|
3179
2602
|
groupInvite(invite, source) {
|
|
3180
2603
|
if (this.stopped) return false;
|
|
3181
|
-
if (this.
|
|
3182
|
-
this.
|
|
2604
|
+
if (this.invites.isOffered(invite.inviteId)) return false;
|
|
2605
|
+
if (this.pendingInvites.some((pending) => pending.inviteId === invite.inviteId)) return false;
|
|
3183
2606
|
this.logger.info(
|
|
3184
2607
|
{ groupId: invite.groupId, groupName: invite.groupName, inviter: invite.inviterHandle, inviteId: invite.inviteId, source },
|
|
3185
2608
|
"group invite \u2014 queuing one invite turn"
|
|
3186
2609
|
);
|
|
3187
|
-
this.
|
|
2610
|
+
this.pendingInvites.push(invite);
|
|
2611
|
+
this.invitesDirty = true;
|
|
3188
2612
|
this.schedule();
|
|
3189
2613
|
return true;
|
|
3190
2614
|
}
|
|
@@ -3193,7 +2617,7 @@ var AgentInvoker = class {
|
|
|
3193
2617
|
this.stopped = true;
|
|
3194
2618
|
this.coalescer.stop();
|
|
3195
2619
|
}
|
|
3196
|
-
/** The promise of the
|
|
2620
|
+
/** The promise of the work currently running, for tests and for graceful stops. */
|
|
3197
2621
|
settled() {
|
|
3198
2622
|
return this.running ?? Promise.resolve();
|
|
3199
2623
|
}
|
|
@@ -3202,14 +2626,17 @@ var AgentInvoker = class {
|
|
|
3202
2626
|
cycles: this.cycles,
|
|
3203
2627
|
turns: this.turns,
|
|
3204
2628
|
inviteTurns: this.inviteTurns,
|
|
3205
|
-
|
|
2629
|
+
turnsInFlight: this.turnsInFlight,
|
|
2630
|
+
wakes: this.coalescer.wakes,
|
|
3206
2631
|
absorbed: this.coalescer.absorbed,
|
|
3207
|
-
retryRung: this.retryRung
|
|
2632
|
+
retryRung: this.retryRung,
|
|
2633
|
+
pendingInvites: this.pendingInvites.length
|
|
3208
2634
|
};
|
|
3209
2635
|
}
|
|
3210
2636
|
// ─── worker ─────────────────────────────────────────────────────────
|
|
3211
|
-
|
|
2637
|
+
onWakeFired() {
|
|
3212
2638
|
this.cycleDue = true;
|
|
2639
|
+
if (this.pendingInvites.length > 0) this.invitesDirty = true;
|
|
3213
2640
|
this.schedule();
|
|
3214
2641
|
}
|
|
3215
2642
|
/** Run the worker if idle. One cycle at a time; work that lands mid-cycle runs afterwards. */
|
|
@@ -3217,14 +2644,14 @@ var AgentInvoker = class {
|
|
|
3217
2644
|
if (this.running) return;
|
|
3218
2645
|
this.running = this.drain().finally(() => {
|
|
3219
2646
|
this.running = null;
|
|
3220
|
-
if (!this.stopped && (this.cycleDue || this.
|
|
2647
|
+
if (!this.stopped && (this.cycleDue || this.invitesDirty)) this.schedule();
|
|
3221
2648
|
});
|
|
3222
2649
|
}
|
|
3223
2650
|
async drain() {
|
|
3224
2651
|
while (!this.stopped) {
|
|
3225
|
-
|
|
3226
|
-
|
|
3227
|
-
await this.
|
|
2652
|
+
if (this.invitesDirty) {
|
|
2653
|
+
this.invitesDirty = false;
|
|
2654
|
+
await this.runInviteTurns();
|
|
3228
2655
|
continue;
|
|
3229
2656
|
}
|
|
3230
2657
|
if (this.cycleDue) {
|
|
@@ -3232,8 +2659,7 @@ var AgentInvoker = class {
|
|
|
3232
2659
|
try {
|
|
3233
2660
|
await this.runCycle();
|
|
3234
2661
|
} catch (err) {
|
|
3235
|
-
this.logger.error({ err:
|
|
3236
|
-
this.scheduleRetry("unhandled error");
|
|
2662
|
+
this.logger.error({ err: describe4(err), ...this.retry() }, "cycle failed with an unhandled error \u2014 re-waking later");
|
|
3237
2663
|
}
|
|
3238
2664
|
continue;
|
|
3239
2665
|
}
|
|
@@ -3241,147 +2667,293 @@ var AgentInvoker = class {
|
|
|
3241
2667
|
}
|
|
3242
2668
|
}
|
|
3243
2669
|
// ─── one cycle ──────────────────────────────────────────────────────
|
|
3244
|
-
/** Read the tray, gate it, start a turn
|
|
2670
|
+
/** Read the tray, gate it, start a turn per reply. Public so tests can drive one cycle. */
|
|
3245
2671
|
async runCycle() {
|
|
3246
2672
|
this.cycles += 1;
|
|
2673
|
+
const started = this.now();
|
|
3247
2674
|
let tray;
|
|
3248
2675
|
try {
|
|
3249
|
-
tray = await this.
|
|
2676
|
+
tray = await this.client.inbox.tray({ waitMs: 0 });
|
|
3250
2677
|
} catch (err) {
|
|
3251
|
-
this.logger.warn({ err:
|
|
3252
|
-
this.
|
|
3253
|
-
return null;
|
|
2678
|
+
this.logger.warn({ err: describe4(err), ...this.retry() }, "tray read failed \u2014 re-waking later");
|
|
2679
|
+
return this.result("tray_failed", 0, false, started, describe4(err));
|
|
3254
2680
|
}
|
|
3255
|
-
const
|
|
2681
|
+
const allCards = agentchatme.gate.cardsOf(tray);
|
|
3256
2682
|
const truncated = tray.truncated === true;
|
|
3257
|
-
if (
|
|
2683
|
+
if (allCards.length === 0) {
|
|
3258
2684
|
this.logger.info({ deferred: tray.deferred ?? 0 }, "tray empty \u2014 nothing to decide");
|
|
3259
2685
|
this.retryRung = 0;
|
|
3260
|
-
return
|
|
2686
|
+
return this.result("empty", 0, truncated, started);
|
|
2687
|
+
}
|
|
2688
|
+
const cards = allCards.filter((card) => !this.replyTurnsInFlight.has(card.conversation_id));
|
|
2689
|
+
const skippedInFlight = allCards.length - cards.length;
|
|
2690
|
+
if (skippedInFlight > 0) this.skippedWhileInFlight = true;
|
|
2691
|
+
if (cards.length === 0) {
|
|
2692
|
+
this.logger.info({ skippedInFlight }, "every card on the tray has a reply turn running \u2014 nothing new to decide");
|
|
2693
|
+
return { ...this.result("empty", 0, truncated, started), skippedInFlight };
|
|
2694
|
+
}
|
|
2695
|
+
const texts = await this.texts.ensure();
|
|
2696
|
+
if (!texts) {
|
|
2697
|
+
this.logger.warn({ cards: cards.length, ...this.retry() }, "served texts not available \u2014 not gating; the cards wait on the tray");
|
|
2698
|
+
return { ...this.result("texts_missing", cards.length, truncated, started, "texts missing"), skippedInFlight };
|
|
2699
|
+
}
|
|
2700
|
+
const readiness = this.readiness();
|
|
2701
|
+
if (!readiness.ready) {
|
|
2702
|
+
const changed = this.unreadyReason !== readiness.reason;
|
|
2703
|
+
this.unreadyReason = readiness.reason;
|
|
2704
|
+
this.logger[changed ? "warn" : "debug"]({ cards: cards.length, reason: readiness.reason, ...this.retry() }, "AgentChat tools not available to a turn \u2014 not gating; the cards wait on the tray");
|
|
2705
|
+
return { ...this.result("tools_unavailable", cards.length, truncated, started, readiness.reason), skippedInFlight };
|
|
2706
|
+
}
|
|
2707
|
+
if (this.unreadyReason !== null) {
|
|
2708
|
+
this.unreadyReason = null;
|
|
2709
|
+
this.logger.info({}, "AgentChat tools available to turns again");
|
|
3261
2710
|
}
|
|
3262
2711
|
let result;
|
|
3263
2712
|
if (!this.gateEnabled) {
|
|
3264
|
-
this.
|
|
3265
|
-
result = emptyResult("disabled", truncated, cardIds(cards));
|
|
2713
|
+
result = await this.runUngated(cards.length, texts, truncated, started);
|
|
3266
2714
|
} else {
|
|
3267
|
-
|
|
3268
|
-
|
|
3269
|
-
mainLine: this.mainLine,
|
|
3270
|
-
caller: this.gateCaller,
|
|
3271
|
-
failOpen: this.gateFailOpen,
|
|
3272
|
-
timeoutMs: this.gateTimeoutMs,
|
|
3273
|
-
now: this.now,
|
|
3274
|
-
log: (level, message) => this.logger[level]({}, message)
|
|
3275
|
-
});
|
|
3276
|
-
const counts = countVerdicts(result);
|
|
3277
|
-
this.logger.info(
|
|
3278
|
-
{
|
|
3279
|
-
cards: result.cards,
|
|
3280
|
-
reply: counts.reply,
|
|
3281
|
-
dismiss: counts.dismiss,
|
|
3282
|
-
defer: counts.defer,
|
|
3283
|
-
undecided: result.undecided.length,
|
|
3284
|
-
posted: result.posted,
|
|
3285
|
-
postFailures: result.postFailures,
|
|
3286
|
-
source: result.source,
|
|
3287
|
-
latencyMs: result.latencyMs,
|
|
3288
|
-
...result.failure ? { failure: result.failure } : {}
|
|
3289
|
-
},
|
|
3290
|
-
"gate"
|
|
3291
|
-
);
|
|
2715
|
+
const trayToGate = skippedInFlight > 0 ? { ...tray, conversations: cards } : tray;
|
|
2716
|
+
result = await this.runGated(trayToGate, cards.length, texts, truncated, started, skippedInFlight);
|
|
3292
2717
|
}
|
|
3293
|
-
if (
|
|
3294
|
-
|
|
3295
|
-
|
|
2718
|
+
if (skippedInFlight > 0) result = { ...result, skippedInFlight };
|
|
2719
|
+
if (truncated && result.outcome !== "fail_closed") {
|
|
2720
|
+
this.logger.info({}, "tray truncated \u2014 waking again for the rest");
|
|
2721
|
+
this.coalescer.wake();
|
|
3296
2722
|
}
|
|
3297
|
-
|
|
3298
|
-
|
|
3299
|
-
|
|
3300
|
-
|
|
3301
|
-
|
|
3302
|
-
|
|
3303
|
-
|
|
3304
|
-
|
|
2723
|
+
return result;
|
|
2724
|
+
}
|
|
2725
|
+
/** Gate off: the agent judges in-turn with the hosted tools. One turn, nothing recorded here. */
|
|
2726
|
+
async runUngated(cards, texts, truncated, started) {
|
|
2727
|
+
this.logger.info({ cards }, "gate off \u2014 starting one turn with the served wake instruction");
|
|
2728
|
+
const sessionKey = wakeSessionKey(this.agentId, this.now());
|
|
2729
|
+
this.logger.info({ sessionKey }, "turn start");
|
|
2730
|
+
const admission = await this.startTurn({ sessionKey, prompt: wakeTurnPrompt(texts), lane: integrationLane(this.accountId) });
|
|
2731
|
+
if (!admission.ran) {
|
|
2732
|
+
this.logger.warn({ sessionKey, error: admission.error, ...this.retry() }, "turn not started \u2014 re-waking later");
|
|
3305
2733
|
} else {
|
|
2734
|
+
this.admitted(sessionKey, admission, "turn complete (final text discarded; the send is a hosted-tool call)");
|
|
3306
2735
|
this.retryRung = 0;
|
|
3307
2736
|
}
|
|
3308
|
-
|
|
3309
|
-
this.
|
|
3310
|
-
|
|
2737
|
+
return {
|
|
2738
|
+
...this.result("gate_off", cards, truncated, started),
|
|
2739
|
+
turnsStarted: admission.ran ? 1 : 0,
|
|
2740
|
+
turnsRefused: admission.ran ? 0 : 1
|
|
2741
|
+
};
|
|
2742
|
+
}
|
|
2743
|
+
async runGated(tray, cards, texts, truncated, started, skippedInFlight = 0) {
|
|
2744
|
+
const decided = await agentchatme.gate.run({ tray, callModel: this.callModel, client: this.client, toolNamer: OPENCLAW_TOOL_NAMER });
|
|
2745
|
+
const latencyMs = this.now() - started;
|
|
2746
|
+
const counts = { reply: 0, dismiss: 0, defer: 0 };
|
|
2747
|
+
for (const verdict of decided.verdicts) counts[verdict.decision] += 1;
|
|
2748
|
+
if (decided.outcome === "fail_closed") {
|
|
2749
|
+
this.logger.warn({ cards, failure: decided.failure, latencyMs, ...this.retry() }, "gate failed closed \u2014 nothing recorded, no turn started");
|
|
2750
|
+
return { ...this.result("fail_closed", cards, truncated, started, decided.failure), undecided: cards, latencyMs };
|
|
3311
2751
|
}
|
|
3312
|
-
|
|
2752
|
+
if (decided.outcome === "empty") {
|
|
2753
|
+
this.retryRung = 0;
|
|
2754
|
+
return this.result("empty", cards, truncated, started);
|
|
2755
|
+
}
|
|
2756
|
+
let turnsStarted = 0;
|
|
2757
|
+
let turnsRefused = 0;
|
|
2758
|
+
const recordFailures = decided.recordFailures.length;
|
|
2759
|
+
const recorded = decided.recorded;
|
|
2760
|
+
for (const entry of decided.reply) {
|
|
2761
|
+
if (this.replyTurnsInFlight.has(entry.conversationId)) {
|
|
2762
|
+
this.skippedWhileInFlight = true;
|
|
2763
|
+
continue;
|
|
2764
|
+
}
|
|
2765
|
+
const sessionKey = wakeSessionKey(this.agentId, this.now());
|
|
2766
|
+
this.logger.info({ sessionKey, conversationId: entry.conversationId }, "turn start");
|
|
2767
|
+
const admission = await this.startTurn({ sessionKey, prompt: wakeTurnPrompt(texts, entry.conversationId), lane: integrationLane(this.accountId) });
|
|
2768
|
+
if (!admission.ran) {
|
|
2769
|
+
turnsRefused += 1;
|
|
2770
|
+
this.logger.warn({ sessionKey, conversationId: entry.conversationId, error: admission.error }, "turn not started \u2014 reply not recorded; the conversation stays unread");
|
|
2771
|
+
continue;
|
|
2772
|
+
}
|
|
2773
|
+
turnsStarted += 1;
|
|
2774
|
+
this.replyTurnsInFlight.add(entry.conversationId);
|
|
2775
|
+
this.admitted(sessionKey, admission, "turn complete (final text discarded; the send is a hosted-tool call)", entry);
|
|
2776
|
+
}
|
|
2777
|
+
const summary = {
|
|
2778
|
+
cards,
|
|
2779
|
+
reply: counts.reply,
|
|
2780
|
+
dismiss: counts.dismiss,
|
|
2781
|
+
defer: counts.defer,
|
|
2782
|
+
undecided: decided.undecided.length,
|
|
2783
|
+
recorded,
|
|
2784
|
+
recordFailures,
|
|
2785
|
+
turnsStarted,
|
|
2786
|
+
turnsRefused,
|
|
2787
|
+
skippedInFlight,
|
|
2788
|
+
latencyMs
|
|
2789
|
+
};
|
|
2790
|
+
if (turnsRefused > 0) {
|
|
2791
|
+
this.logger.warn({ ...summary, ...this.retry() }, "gate \u2014 some turns were refused; re-waking later");
|
|
2792
|
+
} else if (recordFailures > 0 || decided.undecided.length > 0) {
|
|
2793
|
+
this.logger.warn({ ...summary, ...this.retry() }, "gate \u2014 cards left on the tray; re-waking later");
|
|
2794
|
+
} else {
|
|
2795
|
+
this.retryRung = 0;
|
|
2796
|
+
this.logger.info(summary, "gate");
|
|
2797
|
+
}
|
|
2798
|
+
return { ...this.result("decided", cards, truncated, started), ...summary };
|
|
3313
2799
|
}
|
|
3314
|
-
|
|
2800
|
+
result(outcome, cards, truncated, started, failure = null) {
|
|
2801
|
+
return {
|
|
2802
|
+
outcome,
|
|
2803
|
+
cards,
|
|
2804
|
+
reply: 0,
|
|
2805
|
+
dismiss: 0,
|
|
2806
|
+
defer: 0,
|
|
2807
|
+
undecided: 0,
|
|
2808
|
+
recorded: 0,
|
|
2809
|
+
recordFailures: 0,
|
|
2810
|
+
turnsStarted: 0,
|
|
2811
|
+
turnsRefused: 0,
|
|
2812
|
+
skippedInFlight: 0,
|
|
2813
|
+
truncated,
|
|
2814
|
+
latencyMs: this.now() - started,
|
|
2815
|
+
failure
|
|
2816
|
+
};
|
|
2817
|
+
}
|
|
2818
|
+
/** Arm the next rung (or report why not). Returned as log fields so every caller writes ONE line. */
|
|
2819
|
+
retry() {
|
|
3315
2820
|
if (this.coalescer.delayedPending) {
|
|
3316
|
-
|
|
3317
|
-
return;
|
|
2821
|
+
return { retry: { kind: "pending" } };
|
|
3318
2822
|
}
|
|
3319
2823
|
if (this.retryRung >= this.ladder.length) {
|
|
3320
|
-
|
|
3321
|
-
return;
|
|
2824
|
+
return { retry: { kind: "exhausted" } };
|
|
3322
2825
|
}
|
|
3323
|
-
const
|
|
2826
|
+
const delayMs = this.ladder[this.retryRung] ?? this.ladder[this.ladder.length - 1] ?? 6e4;
|
|
3324
2827
|
this.retryRung += 1;
|
|
3325
|
-
this.
|
|
3326
|
-
this.
|
|
2828
|
+
this.coalescer.wakeAfter(delayMs);
|
|
2829
|
+
return { retry: { kind: "armed", delayMs, rung: this.retryRung } };
|
|
3327
2830
|
}
|
|
3328
2831
|
// ─── turns ──────────────────────────────────────────────────────────
|
|
3329
|
-
/**
|
|
3330
|
-
|
|
3331
|
-
|
|
3332
|
-
|
|
3333
|
-
|
|
3334
|
-
|
|
3335
|
-
|
|
3336
|
-
|
|
3337
|
-
|
|
3338
|
-
|
|
3339
|
-
|
|
3340
|
-
this.
|
|
3341
|
-
|
|
3342
|
-
|
|
2832
|
+
/**
|
|
2833
|
+
* Book an admitted turn and log its end whenever it comes. The cycle moves
|
|
2834
|
+
* on at once; OpenClaw's lane keeps the runs of one account in order.
|
|
2835
|
+
*
|
|
2836
|
+
* For a reply turn the end is also when the `reply` verdict is recorded —
|
|
2837
|
+
* only if the run completed (`status: ok`, no error): a turn that looked
|
|
2838
|
+
* and chose not to send still counts as read. A run that ended in error,
|
|
2839
|
+
* on the wait timeout, or whose wait failed records nothing: the card stays
|
|
2840
|
+
* on the tray and the ladder re-wakes so the conversation is gated again.
|
|
2841
|
+
*/
|
|
2842
|
+
admitted(sessionKey, admission, completeLine, reply) {
|
|
2843
|
+
this.turns += 1;
|
|
2844
|
+
this.turnsInFlight += 1;
|
|
2845
|
+
void admission.done.then(
|
|
2846
|
+
async (outcome) => {
|
|
2847
|
+
this.turnsInFlight -= 1;
|
|
2848
|
+
const completed = outcome.ran && outcome.status === "ok" && !outcome.error;
|
|
2849
|
+
this.logger[completed ? "info" : "warn"](
|
|
2850
|
+
{ sessionKey, runId: outcome.runId, status: outcome.status, ...outcome.error ? { error: outcome.error } : {} },
|
|
2851
|
+
completeLine
|
|
2852
|
+
);
|
|
2853
|
+
if (!reply) return;
|
|
2854
|
+
try {
|
|
2855
|
+
if (!completed) {
|
|
2856
|
+
this.logger.warn(
|
|
2857
|
+
{ sessionKey, conversationId: reply.conversationId, status: outcome.status, ...outcome.error ? { error: outcome.error } : {}, ...this.retry() },
|
|
2858
|
+
"turn did not complete \u2014 reply not recorded; the conversation stays unread and is gated again"
|
|
2859
|
+
);
|
|
2860
|
+
return;
|
|
2861
|
+
}
|
|
2862
|
+
await this.recordReply(sessionKey, reply);
|
|
2863
|
+
} finally {
|
|
2864
|
+
this.replyTurnEnded(reply.conversationId);
|
|
2865
|
+
}
|
|
2866
|
+
},
|
|
2867
|
+
async (err) => {
|
|
2868
|
+
this.turnsInFlight -= 1;
|
|
2869
|
+
this.logger.warn({ sessionKey, runId: admission.runId, err: describe4(err) }, `${completeLine} \u2014 the wait failed`);
|
|
2870
|
+
if (reply) {
|
|
2871
|
+
this.logger.warn(
|
|
2872
|
+
{ sessionKey, conversationId: reply.conversationId, err: describe4(err), ...this.retry() },
|
|
2873
|
+
"turn did not complete \u2014 reply not recorded; the conversation stays unread and is gated again"
|
|
2874
|
+
);
|
|
2875
|
+
this.replyTurnEnded(reply.conversationId);
|
|
2876
|
+
}
|
|
2877
|
+
}
|
|
3343
2878
|
);
|
|
3344
|
-
return outcome.ran;
|
|
3345
2879
|
}
|
|
3346
|
-
|
|
3347
|
-
|
|
3348
|
-
this.
|
|
2880
|
+
/** The reply turn for `conversationId` is over: its card may be gated again, and a tray that held skipped cards is read once more. */
|
|
2881
|
+
replyTurnEnded(conversationId) {
|
|
2882
|
+
this.replyTurnsInFlight.delete(conversationId);
|
|
2883
|
+
if (this.skippedWhileInFlight && !this.stopped) {
|
|
2884
|
+
this.skippedWhileInFlight = false;
|
|
2885
|
+
this.logger.debug({ conversationId }, "reply turn ended \u2014 re-reading the tray for the cards left out meanwhile");
|
|
2886
|
+
this.coalescer.wake();
|
|
2887
|
+
}
|
|
2888
|
+
}
|
|
2889
|
+
/** The `reply` verdict for a completed turn. A record the server refuses leaves the conversation unread; the ladder re-wakes. */
|
|
2890
|
+
async recordReply(sessionKey, reply) {
|
|
3349
2891
|
try {
|
|
3350
|
-
|
|
3351
|
-
|
|
3352
|
-
this.logger[outcome.ran ? "info" : "warn"](
|
|
3353
|
-
{ sessionKey, ran: outcome.ran, runId: outcome.runId, status: outcome.status, ...outcome.error ? { error: outcome.error } : {} },
|
|
3354
|
-
outcome.ran ? "group-invite turn complete" : "group-invite turn not started \u2014 the invite stays pending server-side"
|
|
3355
|
-
);
|
|
2892
|
+
await reply.record();
|
|
2893
|
+
this.logger.info({ sessionKey, conversationId: reply.conversationId }, "reply verdict recorded \u2014 turn completed");
|
|
3356
2894
|
} catch (err) {
|
|
3357
|
-
this.logger.
|
|
2895
|
+
this.logger.warn(
|
|
2896
|
+
{ sessionKey, conversationId: reply.conversationId, err: describe4(err), ...this.retry() },
|
|
2897
|
+
"reply verdict not recorded after the turn completed \u2014 the conversation stays unread; the next wake gates it again"
|
|
2898
|
+
);
|
|
2899
|
+
}
|
|
2900
|
+
}
|
|
2901
|
+
/**
|
|
2902
|
+
* Every pending invite gets one attempt. An invite leaves the pending list
|
|
2903
|
+
* only once its turn was admitted (and is then remembered in the ledger);
|
|
2904
|
+
* a refused one stays there for the next wake. Invites that arrive while
|
|
2905
|
+
* this runs are appended and get their pass on the next drain.
|
|
2906
|
+
*/
|
|
2907
|
+
async runInviteTurns() {
|
|
2908
|
+
const batch = [...this.pendingInvites];
|
|
2909
|
+
if (batch.length > 0) {
|
|
2910
|
+
const readiness = this.readiness();
|
|
2911
|
+
if (!readiness.ready) {
|
|
2912
|
+
const changed = this.unreadyReason !== readiness.reason;
|
|
2913
|
+
this.unreadyReason = readiness.reason;
|
|
2914
|
+
this.logger[changed ? "warn" : "debug"]({ pending: batch.length, reason: readiness.reason, ...this.retry() }, "AgentChat tools not available to a turn \u2014 invite turns wait; re-waking later");
|
|
2915
|
+
return;
|
|
2916
|
+
}
|
|
2917
|
+
}
|
|
2918
|
+
let texts = null;
|
|
2919
|
+
let refused = 0;
|
|
2920
|
+
let waitingForTexts = 0;
|
|
2921
|
+
for (const invite of batch) {
|
|
2922
|
+
if (this.stopped) return;
|
|
2923
|
+
texts ??= await this.texts.ensure();
|
|
2924
|
+
if (!texts) {
|
|
2925
|
+
waitingForTexts = batch.length;
|
|
2926
|
+
break;
|
|
2927
|
+
}
|
|
2928
|
+
const sessionKey = inviteSessionKey(this.agentId, invite.inviteId);
|
|
2929
|
+
this.logger.info({ sessionKey, groupId: invite.groupId, inviteId: invite.inviteId }, "group-invite turn start");
|
|
2930
|
+
let admission;
|
|
2931
|
+
try {
|
|
2932
|
+
admission = await this.startTurn({ sessionKey, prompt: inviteTurnPrompt(texts), lane: integrationLane(this.accountId) });
|
|
2933
|
+
} catch (err) {
|
|
2934
|
+
admission = { ran: false, error: describe4(err) };
|
|
2935
|
+
}
|
|
2936
|
+
if (!admission.ran) {
|
|
2937
|
+
refused += 1;
|
|
2938
|
+
this.logger.warn({ sessionKey, inviteId: invite.inviteId, error: admission.error }, "group-invite turn not started \u2014 the invite stays pending; retried on the next wake");
|
|
2939
|
+
continue;
|
|
2940
|
+
}
|
|
2941
|
+
this.inviteTurns += 1;
|
|
2942
|
+
this.invites.markOffered(invite.inviteId);
|
|
2943
|
+
this.pendingInvites = this.pendingInvites.filter((pending) => pending.inviteId !== invite.inviteId);
|
|
2944
|
+
this.admitted(sessionKey, admission, "group-invite turn complete");
|
|
2945
|
+
}
|
|
2946
|
+
if (this.stopped) return;
|
|
2947
|
+
if (waitingForTexts > 0) {
|
|
2948
|
+
this.logger.warn({ pending: waitingForTexts, ...this.retry() }, "served texts not available \u2014 invite turns wait; re-waking later");
|
|
2949
|
+
} else if (refused > 0) {
|
|
2950
|
+
this.logger.warn({ pending: refused, ...this.retry() }, "invite turns refused \u2014 re-waking later");
|
|
3358
2951
|
}
|
|
3359
2952
|
}
|
|
3360
2953
|
};
|
|
3361
|
-
function
|
|
2954
|
+
function describe4(err) {
|
|
3362
2955
|
return err instanceof Error ? err.message : String(err);
|
|
3363
2956
|
}
|
|
3364
|
-
var cache = /* @__PURE__ */ new Map();
|
|
3365
|
-
function getClient({ accountId, config, options }) {
|
|
3366
|
-
const existing = cache.get(accountId);
|
|
3367
|
-
if (existing && existing.apiKey === config.apiKey && existing.apiBase === config.apiBase) {
|
|
3368
|
-
return existing.client;
|
|
3369
|
-
}
|
|
3370
|
-
const client = new agentchatme.AgentChatClient({
|
|
3371
|
-
apiKey: config.apiKey,
|
|
3372
|
-
baseUrl: config.apiBase,
|
|
3373
|
-
...options,
|
|
3374
|
-
fetch: withAgentChatClientIdentity(options?.fetch ?? globalThis.fetch)
|
|
3375
|
-
});
|
|
3376
|
-
cache.set(accountId, {
|
|
3377
|
-
client,
|
|
3378
|
-
apiKey: config.apiKey,
|
|
3379
|
-
apiBase: config.apiBase
|
|
3380
|
-
});
|
|
3381
|
-
return client;
|
|
3382
|
-
}
|
|
3383
|
-
|
|
3384
|
-
// src/binding/gateway.ts
|
|
3385
2957
|
function adaptLog(log) {
|
|
3386
2958
|
if (!log) return void 0;
|
|
3387
2959
|
const adapted = {
|
|
@@ -3397,18 +2969,6 @@ function adaptLog(log) {
|
|
|
3397
2969
|
function withLifecycle(snapshot, lifecycle) {
|
|
3398
2970
|
return Object.assign({}, snapshot, { lifecycle });
|
|
3399
2971
|
}
|
|
3400
|
-
function statusStateFor(kind) {
|
|
3401
|
-
switch (kind) {
|
|
3402
|
-
case "READY":
|
|
3403
|
-
return "linked";
|
|
3404
|
-
case "AUTH_FAIL":
|
|
3405
|
-
return "not-linked";
|
|
3406
|
-
case "CLOSED":
|
|
3407
|
-
return "configured";
|
|
3408
|
-
default:
|
|
3409
|
-
return "unstable";
|
|
3410
|
-
}
|
|
3411
|
-
}
|
|
3412
2972
|
function formatLogLine(obj, msg) {
|
|
3413
2973
|
const head = msg ?? "";
|
|
3414
2974
|
const keys = Object.keys(obj);
|
|
@@ -3439,24 +2999,30 @@ var agentchatGatewayAdapter = {
|
|
|
3439
2999
|
const config = account.config;
|
|
3440
3000
|
const logger = adaptLog(ctx.log) ?? createLogger({ level: config.observability.logLevel, redactKeys: config.observability.redactKeys });
|
|
3441
3001
|
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: true, connected: false }, "starting"));
|
|
3442
|
-
|
|
3002
|
+
const wakeMode = readEnv_js.readWakeModeFromEnv();
|
|
3003
|
+
if (wakeMode.mode === "off") {
|
|
3443
3004
|
ctx.log?.info?.(
|
|
3444
|
-
`[agentchat:${ctx.accountId}]
|
|
3005
|
+
`[agentchat:${ctx.accountId}] ${wakeMode.variable}=off \u2014 no socket, no wakes, no turns; the hosted tools and the manual stay placed` + (wakeMode.variable === readEnv_js.LEGACY_WAKE_MODE_ENV ? ` (${readEnv_js.LEGACY_WAKE_MODE_ENV} is the old spelling; ${readEnv_js.WAKE_MODE_ENV} is the new one)` : "")
|
|
3445
3006
|
);
|
|
3446
3007
|
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false, linked: true, statusState: "disabled" }, "stopped"));
|
|
3447
3008
|
await waitUntilAbort(ctx.abortSignal, () => void 0);
|
|
3448
3009
|
return;
|
|
3449
3010
|
}
|
|
3011
|
+
if (readEnv_js.readLegacyReplyGateFailOpenFromEnv()) {
|
|
3012
|
+
ctx.log?.warn?.(
|
|
3013
|
+
`[agentchat:${ctx.accountId}] ${readEnv_js.LEGACY_REPLY_GATE_FAIL_OPEN_ENV} is set but no longer honoured \u2014 a gate that cannot run fails closed (nothing recorded, no turn) and re-wakes on the ladder`
|
|
3014
|
+
);
|
|
3015
|
+
}
|
|
3450
3016
|
const refusal = multiAccountRefusal(ctx.cfg);
|
|
3451
3017
|
if (refusal) {
|
|
3452
|
-
ctx.log?.error?.(`[agentchat:${ctx.accountId}]
|
|
3018
|
+
ctx.log?.error?.(`[agentchat:${ctx.accountId}] integration not started \u2014 ${refusal}`);
|
|
3453
3019
|
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false, statusState: "not-linked", lastDisconnect: { at: Date.now(), error: refusal } }, "blocked"));
|
|
3454
3020
|
await waitUntilAbort(ctx.abortSignal, () => void 0);
|
|
3455
3021
|
return;
|
|
3456
3022
|
}
|
|
3457
3023
|
const channelRuntime = ctx.channelRuntime;
|
|
3458
3024
|
const { agentId, agentIdOverride } = resolveGateAgent({
|
|
3459
|
-
routedAgentId:
|
|
3025
|
+
routedAgentId: resolveIntegrationAgentId({ cfg: ctx.cfg, accountId: ctx.accountId, channelRuntime }),
|
|
3460
3026
|
ambientAgentId: openclawLayout_js.resolveOpenClawDefaultAgentId(ctx.cfg)
|
|
3461
3027
|
});
|
|
3462
3028
|
if (agentIdOverride && !readLlmAgentOverrideOptIn(ctx.cfg)) {
|
|
@@ -3464,69 +3030,101 @@ var agentchatGatewayAdapter = {
|
|
|
3464
3030
|
`[agentchat:${ctx.accountId}] this account is routed to agent "${agentIdOverride}", not OpenClaw's default \u2014 the gate call will be refused (LLM_COMPLETION_NOT_AUTHORIZED) until ${LLM_AGENT_OVERRIDE_PATH} is true; \`openclaw doctor --fix\` writes it`
|
|
3465
3031
|
);
|
|
3466
3032
|
}
|
|
3467
|
-
const
|
|
3033
|
+
const client = getClient({ accountId: ctx.accountId, config });
|
|
3468
3034
|
const gateTimeoutMs = readEnv_js.readReplyGateTimeoutMsFromEnv();
|
|
3469
|
-
|
|
3035
|
+
const texts = new TextsStore({ client, accountId: ctx.accountId, logger });
|
|
3036
|
+
const handle = config.agentHandle;
|
|
3037
|
+
if (handle) {
|
|
3038
|
+
texts.onServerCopy((copy) => {
|
|
3039
|
+
const refreshed = refreshIdentityLine(ctx.cfg, ctx.accountId, handle, copy.identity_line);
|
|
3040
|
+
if (refreshed.outcome === "updated") ctx.log?.info?.(`[agentchat:${ctx.accountId}] identity line refreshed from the served texts in ${refreshed.path}`);
|
|
3041
|
+
else if (refreshed.outcome === "failed") ctx.log?.warn?.(`[agentchat:${ctx.accountId}] identity line could not be refreshed in ${refreshed.path}: ${refreshed.detail ?? "unknown error"}`);
|
|
3042
|
+
});
|
|
3043
|
+
}
|
|
3044
|
+
await texts.start();
|
|
3045
|
+
const invites = new InviteLedger({
|
|
3046
|
+
accountId: ctx.accountId,
|
|
3047
|
+
onWriteError: (err) => ctx.log?.warn?.(`[agentchat:${ctx.accountId}] invite ledger could not be written: ${err instanceof Error ? err.message : String(err)}`)
|
|
3048
|
+
});
|
|
3049
|
+
const metrics = createInMemoryMetrics();
|
|
3050
|
+
await registerIntegration({
|
|
3470
3051
|
accountId: ctx.accountId,
|
|
3471
3052
|
config,
|
|
3472
3053
|
logger,
|
|
3473
|
-
|
|
3054
|
+
socketOptions: { client, metrics },
|
|
3055
|
+
build: (socket) => {
|
|
3474
3056
|
const invoker = new AgentInvoker({
|
|
3475
3057
|
accountId: ctx.accountId,
|
|
3476
3058
|
agentId,
|
|
3477
|
-
|
|
3478
|
-
|
|
3479
|
-
|
|
3059
|
+
client,
|
|
3060
|
+
callModel: createRuntimeModelCall({ agentIdOverride, ...gateTimeoutMs !== void 0 ? { timeoutMs: gateTimeoutMs } : {} }),
|
|
3061
|
+
startTurn: createRuntimeTurnStarter(),
|
|
3062
|
+
// Gating waits until a turn can have the hosted tools (the MCP
|
|
3063
|
+
// entry in the LIVE config — OpenClaw hot-applies `mcp.*` — and
|
|
3064
|
+
// its key in this process): a connect wake on a cold gateway
|
|
3065
|
+
// otherwise spends a gate call and runs a turn that cannot look.
|
|
3066
|
+
readiness: () => {
|
|
3067
|
+
const live = readLiveConfig(ctx.cfg);
|
|
3068
|
+
return turnReadiness({ cfg: live.cfg, apiBase: config.apiBase, apiKey: config.apiKey, live: live.live });
|
|
3069
|
+
},
|
|
3070
|
+
texts,
|
|
3071
|
+
invites,
|
|
3480
3072
|
logger,
|
|
3481
|
-
|
|
3482
|
-
|
|
3483
|
-
...gateTimeoutMs !== void 0 ? { gateTimeoutMs } : {}
|
|
3073
|
+
metrics,
|
|
3074
|
+
gateEnabled: readEnv_js.readReplyGateEnabledFromEnv()
|
|
3484
3075
|
});
|
|
3485
|
-
let
|
|
3076
|
+
let blocked = false;
|
|
3486
3077
|
return {
|
|
3487
3078
|
invoker,
|
|
3079
|
+
texts,
|
|
3488
3080
|
handlers: {
|
|
3489
|
-
|
|
3081
|
+
onWake: (source) => invoker.wake(source),
|
|
3490
3082
|
onGroupInvite: (invite) => invoker.groupInvite(invite, "live"),
|
|
3491
|
-
|
|
3492
|
-
|
|
3083
|
+
onConnected: (at) => {
|
|
3084
|
+
if (blocked) {
|
|
3085
|
+
blocked = false;
|
|
3086
|
+
ctx.log?.info?.(`[agentchat:${ctx.accountId}] key accepted again \u2014 blocked cleared`);
|
|
3087
|
+
}
|
|
3088
|
+
ctx.log?.info?.(`[agentchat:${ctx.accountId}] connected at ${new Date(at).toISOString()} (agent ${agentId})`);
|
|
3493
3089
|
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: true, connected: true, linked: true, statusState: "linked", lastConnectedAt: at }, "ready"));
|
|
3494
|
-
void catchUpInvites(ctx.accountId,
|
|
3090
|
+
void catchUpInvites(ctx.accountId, client, invoker, logger);
|
|
3091
|
+
},
|
|
3092
|
+
onBlocked: (info) => {
|
|
3093
|
+
const close = `close ${info.code}${info.reason ? ` ${info.reason}` : ""}`;
|
|
3094
|
+
const next = info.retryInMs === null ? "no retry scheduled" : `next HELLO in about ${Math.max(1, Math.round(info.retryInMs / 6e4))} min`;
|
|
3095
|
+
if (blocked) {
|
|
3096
|
+
ctx.log?.debug?.(`[agentchat:${ctx.accountId}] still blocked (${close}; ${next})`);
|
|
3097
|
+
return;
|
|
3098
|
+
}
|
|
3099
|
+
blocked = true;
|
|
3100
|
+
ctx.log?.error?.(
|
|
3101
|
+
`[agentchat:${ctx.accountId}] key rejected (${close}) \u2014 the server refused the key; the SDK retries a fresh HELLO every 10\u201315 min until it is accepted (${next}); rotate the key with openclaw channels add agentchat or openclaw config set channels.agentchat.apiKey \u2026`
|
|
3102
|
+
);
|
|
3103
|
+
ctx.setStatus(
|
|
3104
|
+
withLifecycle(
|
|
3105
|
+
{ ...ctx.getStatus(), running: false, connected: false, statusState: "not-linked", lastDisconnect: { at: Date.now(), error: `key rejected: ${close}` } },
|
|
3106
|
+
"blocked"
|
|
3107
|
+
)
|
|
3108
|
+
);
|
|
3495
3109
|
},
|
|
3496
3110
|
onError: (err) => {
|
|
3497
|
-
|
|
3498
|
-
ctx.log?.[level]?.(`[agentchat:${ctx.accountId}] runtime error: ${err.message} (class=${err.class_})`);
|
|
3111
|
+
ctx.log?.[blocked ? "debug" : "warn"]?.(`[agentchat:${ctx.accountId}] socket error: ${err.message}`);
|
|
3499
3112
|
},
|
|
3500
|
-
onStateChanged: (next) => {
|
|
3501
|
-
|
|
3502
|
-
|
|
3503
|
-
|
|
3113
|
+
onStateChanged: (next, prev) => {
|
|
3114
|
+
switch (next) {
|
|
3115
|
+
case "backoff":
|
|
3116
|
+
if (blocked) {
|
|
3117
|
+
ctx.log?.debug?.(`[agentchat:${ctx.accountId}] socket in backoff while blocked (from ${prev})`);
|
|
3118
|
+
return;
|
|
3119
|
+
}
|
|
3120
|
+
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: true, connected: false, statusState: "unstable" }, "recovering"));
|
|
3121
|
+
return;
|
|
3122
|
+
case "stopped":
|
|
3123
|
+
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false, statusState: "configured" }, "stopped"));
|
|
3124
|
+
return;
|
|
3125
|
+
default:
|
|
3504
3126
|
return;
|
|
3505
|
-
}
|
|
3506
|
-
authBlocked = true;
|
|
3507
|
-
ctx.log?.error?.(
|
|
3508
|
-
`[agentchat:${ctx.accountId}] AUTH_FAIL (${next.reason}) \u2014 the server rejected the key; retrying every 10\u201315 min; rotate the key or re-run openclaw channels add agentchat`
|
|
3509
|
-
);
|
|
3510
|
-
ctx.setStatus(
|
|
3511
|
-
withLifecycle(
|
|
3512
|
-
{ ...ctx.getStatus(), running: false, connected: false, statusState: "not-linked", lastDisconnect: { at: Date.now(), error: `AUTH_FAIL: ${next.reason}` } },
|
|
3513
|
-
"blocked"
|
|
3514
|
-
)
|
|
3515
|
-
);
|
|
3516
|
-
return;
|
|
3517
|
-
}
|
|
3518
|
-
if (authBlocked && next.kind !== "READY" && next.kind !== "CLOSED") {
|
|
3519
|
-
ctx.log?.debug?.(`[agentchat:${ctx.accountId}] AUTH_FAIL retry: ${next.kind.toLowerCase()}`);
|
|
3520
|
-
return;
|
|
3521
|
-
}
|
|
3522
|
-
if (authBlocked) {
|
|
3523
|
-
authBlocked = false;
|
|
3524
|
-
if (next.kind === "READY") ctx.log?.info?.(`[agentchat:${ctx.accountId}] key accepted again \u2014 AUTH_FAIL cleared`);
|
|
3525
3127
|
}
|
|
3526
|
-
const running = next.kind !== "CLOSED";
|
|
3527
|
-
const connected = next.kind === "READY" || next.kind === "DEGRADED";
|
|
3528
|
-
const lifecycle = next.kind === "READY" || next.kind === "DEGRADED" ? "ready" : next.kind === "CLOSED" ? "stopped" : runtime.getHealth().counters.knocks > 0 ? "recovering" : "starting";
|
|
3529
|
-
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running, connected, statusState: statusStateFor(next.kind) }, lifecycle));
|
|
3530
3128
|
}
|
|
3531
3129
|
}
|
|
3532
3130
|
};
|
|
@@ -3534,20 +3132,19 @@ var agentchatGatewayAdapter = {
|
|
|
3534
3132
|
});
|
|
3535
3133
|
await waitUntilAbort(ctx.abortSignal, async () => {
|
|
3536
3134
|
try {
|
|
3537
|
-
await
|
|
3135
|
+
await unregisterIntegration(ctx.accountId);
|
|
3538
3136
|
} catch (err) {
|
|
3539
3137
|
ctx.log?.error?.(`[agentchat:${ctx.accountId}] unregister failed on abort: ${err instanceof Error ? err.message : String(err)}`);
|
|
3540
3138
|
}
|
|
3541
3139
|
});
|
|
3542
3140
|
},
|
|
3543
3141
|
async stopAccount(ctx) {
|
|
3544
|
-
await
|
|
3142
|
+
await unregisterIntegration(ctx.accountId);
|
|
3545
3143
|
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false }, "stopped"));
|
|
3546
3144
|
}
|
|
3547
3145
|
};
|
|
3548
|
-
async function catchUpInvites(accountId,
|
|
3146
|
+
async function catchUpInvites(accountId, client, invoker, logger) {
|
|
3549
3147
|
try {
|
|
3550
|
-
const client = getClient({ accountId, config });
|
|
3551
3148
|
const invites = await client.listGroupInvites();
|
|
3552
3149
|
if (!Array.isArray(invites)) return;
|
|
3553
3150
|
let surfaced = 0;
|
|
@@ -3555,16 +3152,20 @@ async function catchUpInvites(accountId, config, invoker, logger) {
|
|
|
3555
3152
|
const invite = groupInviteFromRecord(row);
|
|
3556
3153
|
if (invite && invoker.groupInvite(invite, "catch-up")) surfaced += 1;
|
|
3557
3154
|
}
|
|
3558
|
-
if (surfaced > 0) logger.info({ surfaced }, "pending group invites surfaced on connect");
|
|
3155
|
+
if (surfaced > 0) logger.info({ accountId, surfaced }, "pending group invites surfaced on connect");
|
|
3559
3156
|
} catch (err) {
|
|
3560
3157
|
logger.warn(
|
|
3561
|
-
{ err: err instanceof Error ? err.message : String(err) },
|
|
3158
|
+
{ accountId, err: err instanceof Error ? err.message : String(err) },
|
|
3562
3159
|
"pending-invite catch-up failed \u2014 live invite frames are unaffected and the agent can still list invites with the hosted tools"
|
|
3563
3160
|
);
|
|
3564
3161
|
}
|
|
3565
3162
|
}
|
|
3566
3163
|
var PROBE_MIN_MS = 1e3;
|
|
3567
3164
|
var PROBE_MAX_MS = 1e4;
|
|
3165
|
+
function formatCounts(counts) {
|
|
3166
|
+
const parts = Object.entries(counts).map(([label, n]) => `${label} ${n}`);
|
|
3167
|
+
return parts.length > 0 ? parts.join(", ") : "none";
|
|
3168
|
+
}
|
|
3568
3169
|
var agentchatStatusAdapter = {
|
|
3569
3170
|
async probeAccount({ account, timeoutMs, cfg }) {
|
|
3570
3171
|
if (!account.config) {
|
|
@@ -3593,28 +3194,32 @@ var agentchatStatusAdapter = {
|
|
|
3593
3194
|
handle: config.agentHandle ?? me.handle,
|
|
3594
3195
|
apiKey: config.apiKey,
|
|
3595
3196
|
apiBase: config.apiBase,
|
|
3197
|
+
identityLine: cachedIdentityLine(account.accountId),
|
|
3596
3198
|
agentId: resolvePlacementAgentId(cfg, account.accountId),
|
|
3597
3199
|
accountId: account.accountId
|
|
3598
3200
|
});
|
|
3599
3201
|
const enabled = account.enabled && isAgentchatAccountEnabled(cfg, account.accountId);
|
|
3600
|
-
const live =
|
|
3601
|
-
const health = live?.
|
|
3202
|
+
const live = getIntegration(account.accountId);
|
|
3203
|
+
const health = live?.socket.getHealth();
|
|
3602
3204
|
const counters = live?.invoker?.counters();
|
|
3603
|
-
const
|
|
3604
|
-
|
|
3605
|
-
|
|
3606
|
-
|
|
3205
|
+
const textsSource = live ? live.texts?.source ?? "missing" : void 0;
|
|
3206
|
+
const socketCounters = live?.metrics?.snapshot?.();
|
|
3207
|
+
const integration = {
|
|
3208
|
+
mode: readEnv_js.readWakeModeFromEnv().mode,
|
|
3209
|
+
...health ? { state: health.state } : {},
|
|
3210
|
+
...counters ? { wakes: counters.wakes, cycles: counters.cycles, turns: counters.turns } : {},
|
|
3211
|
+
...textsSource ? { texts: textsSource } : {},
|
|
3212
|
+
...socketCounters ? { socket: socketCounters } : {}
|
|
3607
3213
|
};
|
|
3608
3214
|
const refusal = multiAccountRefusal(cfg);
|
|
3609
|
-
const legacyServer = health !== void 0 && health.authenticated && !health.ackNegotiated;
|
|
3610
3215
|
return {
|
|
3611
|
-
ok: enabled && me.status === "active" && mcp.ok && placement.every((c) => c.ok) && !refusal
|
|
3216
|
+
ok: enabled && me.status === "active" && mcp.ok && placement.every((c) => c.ok) && !refusal,
|
|
3612
3217
|
handle: me.handle,
|
|
3613
3218
|
status: me.status,
|
|
3614
3219
|
pausedByOwner: me.paused_by_owner ?? "none",
|
|
3615
3220
|
mcp,
|
|
3616
3221
|
placement,
|
|
3617
|
-
|
|
3222
|
+
integration,
|
|
3618
3223
|
...refusal ? { refusal } : {},
|
|
3619
3224
|
...enabled ? {} : { disabled: agentchatReenableHint(cfg, account.accountId) }
|
|
3620
3225
|
};
|
|
@@ -3637,22 +3242,27 @@ var agentchatStatusAdapter = {
|
|
|
3637
3242
|
for (const check of probe.placement ?? []) {
|
|
3638
3243
|
lines.push({ text: `${check.name}: ${check.detail}`, tone: check.ok ? "muted" : "warn" });
|
|
3639
3244
|
}
|
|
3640
|
-
if (probe.refusal) lines.push({ text: `
|
|
3641
|
-
if (probe.
|
|
3642
|
-
const d = probe.
|
|
3643
|
-
if (d.mode === "off") lines.push({ text:
|
|
3245
|
+
if (probe.refusal) lines.push({ text: `integration not started \u2014 ${probe.refusal}`, tone: "error" });
|
|
3246
|
+
if (probe.integration) {
|
|
3247
|
+
const d = probe.integration;
|
|
3248
|
+
if (d.mode === "off") lines.push({ text: `integration off (${readEnv_js.WAKE_MODE_ENV}=off or ${readEnv_js.LEGACY_WAKE_MODE_ENV}=off): no socket, no wakes, no turns`, tone: "warn" });
|
|
3644
3249
|
else if (d.state) {
|
|
3645
3250
|
lines.push({
|
|
3646
|
-
text: `
|
|
3647
|
-
tone: d.state === "
|
|
3251
|
+
text: `integration ${d.state} \u2014 wakes ${d.wakes ?? 0}, cycles ${d.cycles ?? 0}, turns ${d.turns ?? 0}`,
|
|
3252
|
+
tone: d.state === "ready" ? "success" : "warn"
|
|
3648
3253
|
});
|
|
3649
|
-
if (d.
|
|
3254
|
+
if (d.socket) {
|
|
3650
3255
|
lines.push({
|
|
3651
|
-
text:
|
|
3652
|
-
tone: "
|
|
3256
|
+
text: `socket \u2014 wakes: ${formatCounts(d.socket.wakes)} \xB7 closes: ${formatCounts(d.socket.disconnects)} \xB7 notices: ${formatCounts(d.socket.errors)}`,
|
|
3257
|
+
tone: "muted"
|
|
3653
3258
|
});
|
|
3654
3259
|
}
|
|
3655
|
-
|
|
3260
|
+
if (d.texts === "missing") {
|
|
3261
|
+
lines.push({ text: "served texts not available yet (AgentChat unreachable, nothing cached) \u2014 turns wait for the first copy", tone: "error" });
|
|
3262
|
+
} else if (d.texts === "cache") {
|
|
3263
|
+
lines.push({ text: "served texts from the cached copy \u2014 AgentChat was unreachable at start; refreshed when it is back", tone: "warn" });
|
|
3264
|
+
}
|
|
3265
|
+
} else if (!probe.refusal) lines.push({ text: "integration not running in this process", tone: "muted" });
|
|
3656
3266
|
}
|
|
3657
3267
|
return lines;
|
|
3658
3268
|
},
|
|
@@ -3667,7 +3277,7 @@ var agentchatDoctorAdapter = {
|
|
|
3667
3277
|
collectPreviewWarnings({ cfg, doctorFixCommand, env }) {
|
|
3668
3278
|
const warnings = [];
|
|
3669
3279
|
const refusal = multiAccountRefusal(cfg);
|
|
3670
|
-
if (refusal) warnings.push(`[${AGENTCHAT_CHANNEL_ID}]
|
|
3280
|
+
if (refusal) warnings.push(`[${AGENTCHAT_CHANNEL_ID}] integration will not start \u2014 ${refusal}`);
|
|
3671
3281
|
for (const accountId of listConfiguredAccountIds(cfg)) {
|
|
3672
3282
|
if (!isAgentchatAccountEnabled(cfg, accountId)) {
|
|
3673
3283
|
warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${agentchatReenableHint(cfg, accountId)}`);
|
|
@@ -3677,7 +3287,7 @@ var agentchatDoctorAdapter = {
|
|
|
3677
3287
|
const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
|
|
3678
3288
|
const handle = readAgentchatConfigField(cfg, accountId, "agentHandle");
|
|
3679
3289
|
const agentId = resolvePlacementAgentId(cfg, accountId);
|
|
3680
|
-
for (const check of checkPlacement({ cfg, handle, apiKey, apiBase, agentId, accountId, env })) {
|
|
3290
|
+
for (const check of checkPlacement({ cfg, handle, apiKey, apiBase, identityLine: cachedIdentityLine(accountId), agentId, accountId, env })) {
|
|
3681
3291
|
if (check.ok) continue;
|
|
3682
3292
|
const fix = check.name === "mcp" ? ` (${doctorFixCommand} adds it)` : "";
|
|
3683
3293
|
warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${check.name}: ${check.detail}${fix}`);
|
|
@@ -3725,9 +3335,11 @@ var agentchatDoctorAdapter = {
|
|
|
3725
3335
|
}
|
|
3726
3336
|
const handle = readAgentchatConfigField(next, accountId, "agentHandle");
|
|
3727
3337
|
if (apiKey && handle && placeIdentityLines) {
|
|
3728
|
-
const
|
|
3338
|
+
const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase }), accountId });
|
|
3339
|
+
const restored = restoreIdentityLine(next, accountId, handle, identityLine);
|
|
3729
3340
|
if (restored.outcome === "placed") changes.push(`placed the identity line for @${handle.replace(/^@/, "")} in ${restored.path}`);
|
|
3730
3341
|
else if (restored.outcome === "failed") warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] could not place the identity line for @${handle.replace(/^@/, "")}: ${restored.detail ?? "unknown error"}`);
|
|
3342
|
+
else if (restored.outcome === "skipped") warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] identity line for @${handle.replace(/^@/, "")} not placed: ${restored.detail ?? "the served text is not available"}`);
|
|
3731
3343
|
}
|
|
3732
3344
|
}
|
|
3733
3345
|
for (const [apiBase, apiKey] of bases) {
|
|
@@ -3859,12 +3471,12 @@ var agentchatSetupAdapter = {
|
|
|
3859
3471
|
const apiKey = readAgentchatConfigField(withAccount, accountId, "apiKey");
|
|
3860
3472
|
if (!apiKey) return withAccount;
|
|
3861
3473
|
const apiBase = readAgentchatConfigField(withAccount, accountId, "apiBase") ?? DEFAULT_API_BASE2;
|
|
3862
|
-
return
|
|
3474
|
+
return applyIntegrationConfig(withAccount, { accountId, handle, apiKey, apiBase }).cfg;
|
|
3863
3475
|
},
|
|
3864
3476
|
/**
|
|
3865
|
-
* Files only: the key into OpenClaw's state-dir `.env`, the
|
|
3866
|
-
* into the bound agent's `AGENTS.md`. Reports through
|
|
3867
|
-
* Never throws: setup-time UX is "warn and proceed".
|
|
3477
|
+
* Files only: the key into OpenClaw's state-dir `.env`, the served
|
|
3478
|
+
* identity line into the bound agent's `AGENTS.md`. Reports through
|
|
3479
|
+
* `RuntimeEnv.log`. Never throws: setup-time UX is "warn and proceed".
|
|
3868
3480
|
*/
|
|
3869
3481
|
async afterAccountConfigWritten({ cfg, accountId, input, runtime }) {
|
|
3870
3482
|
const apiKey = typeof input.token === "string" ? input.token : readAgentchatConfigField(cfg, accountId, "apiKey");
|
|
@@ -3887,7 +3499,8 @@ var agentchatSetupAdapter = {
|
|
|
3887
3499
|
}
|
|
3888
3500
|
}
|
|
3889
3501
|
try {
|
|
3890
|
-
const
|
|
3502
|
+
const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase }), accountId });
|
|
3503
|
+
const placed = placeIntegration({ cfg, handle, apiKey, apiBase, identityLine, accountId });
|
|
3891
3504
|
for (const line of formatPlacement(placed.steps.filter((s) => s.name !== "mcp"))) say(runtime, "log", `[agentchat:${accountId}] ${line}`);
|
|
3892
3505
|
say(runtime, "log", `[agentchat:${accountId}] \u2713 config: agentHandle and mcp.servers.agentchat written with the account (restart the gateway, or reload its config, so \${AGENTCHAT_API_KEY} resolves)`);
|
|
3893
3506
|
} catch (err) {
|
|
@@ -3896,11 +3509,11 @@ var agentchatSetupAdapter = {
|
|
|
3896
3509
|
}
|
|
3897
3510
|
};
|
|
3898
3511
|
function disableAccountConfig(cfg, accountId) {
|
|
3899
|
-
const stripped =
|
|
3512
|
+
const stripped = stripIntegrationConfig(cfg, accountId).cfg;
|
|
3900
3513
|
return channelPluginCommon.setAccountEnabledInConfigSection({ cfg: stripped, sectionKey: AGENTCHAT_CHANNEL_ID, accountId, enabled: false, allowTopLevel: true });
|
|
3901
3514
|
}
|
|
3902
3515
|
function deleteAccountConfig(cfg, accountId) {
|
|
3903
|
-
const stripped =
|
|
3516
|
+
const stripped = stripIntegrationConfig(cfg, accountId).cfg;
|
|
3904
3517
|
return channelPluginCommon.deleteAccountFromConfigSection({ cfg: stripped, sectionKey: AGENTCHAT_CHANNEL_ID, accountId, clearBaseFields: ["apiKey", "apiBase", "agentHandle"] });
|
|
3905
3518
|
}
|
|
3906
3519
|
function isAccountEnabled(cfg, accountId) {
|
|
@@ -3925,7 +3538,7 @@ var agentchatLifecycleAdapter = {
|
|
|
3925
3538
|
return;
|
|
3926
3539
|
}
|
|
3927
3540
|
if (!isEnabled) {
|
|
3928
|
-
for (const line of
|
|
3541
|
+
for (const line of removeIntegrationFiles(nextCfg, accountId, { clearKey: false })) say(runtime, "log", `[agentchat:${accountId}] ${line}`);
|
|
3929
3542
|
return;
|
|
3930
3543
|
}
|
|
3931
3544
|
const handle = validHandle(readAgentchatConfigField(nextCfg, accountId, "agentHandle"));
|
|
@@ -3933,12 +3546,16 @@ var agentchatLifecycleAdapter = {
|
|
|
3933
3546
|
say(runtime, "log", `[agentchat:${accountId}] agentHandle not in config \u2014 run \`openclaw doctor --fix\` to learn it from the key and place the identity line`);
|
|
3934
3547
|
return;
|
|
3935
3548
|
}
|
|
3936
|
-
const
|
|
3549
|
+
const apiKey = readAgentchatConfigField(nextCfg, accountId, "apiKey");
|
|
3550
|
+
const apiBase = readAgentchatConfigField(nextCfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
|
|
3551
|
+
const identityLine = apiKey ? await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase }), accountId }) : null;
|
|
3552
|
+
const restored = restoreIdentityLine(nextCfg, accountId, handle, identityLine);
|
|
3937
3553
|
if (restored.outcome === "placed") say(runtime, "log", `[agentchat:${accountId}] placed the identity line for @${handle} in ${restored.path}`);
|
|
3554
|
+
else if (restored.outcome === "skipped") say(runtime, "log", `[agentchat:${accountId}] identity line for @${handle} not placed: ${restored.detail ?? "the served text is not available"}`);
|
|
3938
3555
|
else if (restored.outcome === "failed") say(runtime, "error", `[agentchat:${accountId}] could not place the identity line for @${handle}: ${restored.detail ?? "unknown error"} \u2014 run \`openclaw doctor --fix\` after fixing the path`);
|
|
3939
3556
|
},
|
|
3940
3557
|
async onAccountRemoved({ prevCfg, accountId, runtime }) {
|
|
3941
|
-
for (const line of
|
|
3558
|
+
for (const line of removeIntegrationFiles(prevCfg, accountId, { clearKey: true })) say(runtime, "log", `[agentchat:${accountId}] ${line}`);
|
|
3942
3559
|
}
|
|
3943
3560
|
};
|
|
3944
3561
|
var agentchatPlugin = {
|
|
@@ -3950,7 +3567,7 @@ var agentchatPlugin = {
|
|
|
3950
3567
|
detailLabel: "AgentChat",
|
|
3951
3568
|
docsPath: "/channels/agentchat",
|
|
3952
3569
|
docsLabel: "agentchat",
|
|
3953
|
-
blurb: "the AgentChat
|
|
3570
|
+
blurb: "the AgentChat integration \u2014 your agent gets a permanent @handle on the messaging network for AI agents, is woken when a peer writes, and decides for itself with its own model whether to reply through the hosted AgentChat tools.",
|
|
3954
3571
|
systemImage: "message",
|
|
3955
3572
|
markdownCapable: true,
|
|
3956
3573
|
order: 100
|
|
@@ -4042,7 +3659,7 @@ var agentchatPlugin = {
|
|
|
4042
3659
|
setup: agentchatSetupAdapter,
|
|
4043
3660
|
// ─── OpenClaw ↔ AgentChat binding ─────────────────────────────────────
|
|
4044
3661
|
//
|
|
4045
|
-
// gateway — holds the socket,
|
|
3662
|
+
// gateway — holds the socket, wakes, gates, starts turns (the integration).
|
|
4046
3663
|
// status — the doctor-style probe: key, hosted MCP reachability, placement.
|
|
4047
3664
|
// doctor — `openclaw doctor` warnings and the mcp.servers.agentchat repair.
|
|
4048
3665
|
//
|
|
@@ -4059,11 +3676,11 @@ var agentchatPlugin = {
|
|
|
4059
3676
|
channelCore.defineChannelPluginEntry({
|
|
4060
3677
|
id: AGENTCHAT_CHANNEL_ID,
|
|
4061
3678
|
name: "AgentChat",
|
|
4062
|
-
description: "The AgentChat
|
|
3679
|
+
description: "The AgentChat integration: wakes your OpenClaw agent when a peer writes on the messaging network for AI agents.",
|
|
4063
3680
|
plugin: agentchatPlugin,
|
|
4064
3681
|
// Called in every registration mode except cli-metadata and tool-discovery
|
|
4065
3682
|
// (docs.openclaw.ai/plugins/sdk-entrypoints/define-channel-plugin-entry).
|
|
4066
|
-
// The
|
|
3683
|
+
// The integration reads `runtime.llm.complete` (the gate on the agent's own
|
|
4067
3684
|
// model) and `runtime.subagent.run` (one turn, `deliver: false`) from it.
|
|
4068
3685
|
setRuntime: (runtime) => setPluginRuntime(runtime)
|
|
4069
3686
|
});
|