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