@agentchatme/openclaw 0.8.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/README.md +72 -70
- package/RUNBOOK.md +54 -41
- package/SECURITY.md +8 -5
- 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 +995 -1528
- 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 +986 -1522
- 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-Dq5Dwg8O.d.cts +655 -0
- package/dist/setup-entry-Dq5Dwg8O.d.ts +655 -0
- package/dist/setup-entry.cjs +984 -1534
- 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 +985 -1535
- 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.0";
|
|
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,40 @@ 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
|
-
var DECIDE_TOOL = mcpToolName("agentchat_decide");
|
|
461
439
|
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}
|
|
440
|
+
var OPENCLAW_TOOL_NAMER = (tool) => tool.startsWith(MCP_TOOL_PREFIX) ? tool : mcpToolName(tool);
|
|
441
|
+
var HOSTED_TOOL_TOKEN = /\bagentchat_(?!_)[a-z0-9_]+\b/g;
|
|
442
|
+
function spellToolsForOpenClaw(text) {
|
|
443
|
+
return text.replace(HOSTED_TOOL_TOKEN, (token) => OPENCLAW_TOOL_NAMER(token));
|
|
444
|
+
}
|
|
445
|
+
function wakeTurnPrompt(texts, conversationId) {
|
|
446
|
+
const instruction = texts.wake_instruction.trim();
|
|
447
|
+
if (!conversationId) return instruction;
|
|
448
|
+
return `${instruction}
|
|
483
449
|
|
|
484
|
-
${
|
|
485
|
-
|
|
486
|
-
|
|
450
|
+
${conversationLine(conversationId)}`;
|
|
451
|
+
}
|
|
452
|
+
function conversationLine(conversationId) {
|
|
453
|
+
return `Conversation to answer in this turn: ${conversationId}. The gate decided reply and your reply verdict for it is being recorded; if this conversation still shows on the tray, do not record another verdict for it \u2014 open it with ${GET_CONVERSATION_TOOL} and reply.`;
|
|
487
454
|
}
|
|
488
|
-
function inviteTurnPrompt() {
|
|
489
|
-
return
|
|
455
|
+
function inviteTurnPrompt(texts) {
|
|
456
|
+
return texts.invite_prompt.trim();
|
|
490
457
|
}
|
|
491
|
-
function
|
|
492
|
-
return `agent:${agentId}:subagent:agentchat-
|
|
458
|
+
function wakeSessionKey(agentId, now = Date.now(), nonce = randomNonce()) {
|
|
459
|
+
return `agent:${agentId}:subagent:agentchat-wake-${utcStamp(now)}-${nonce}`;
|
|
493
460
|
}
|
|
494
461
|
function inviteSessionKey(agentId, inviteId) {
|
|
495
462
|
return `agent:${agentId}:subagent:agentchat-invite-${sanitizeKeyPart(inviteId)}`;
|
|
496
463
|
}
|
|
497
|
-
function
|
|
498
|
-
return `agentchat-
|
|
464
|
+
function integrationLane(accountId) {
|
|
465
|
+
return `agentchat-integration:${sanitizeKeyPart(accountId)}`;
|
|
499
466
|
}
|
|
500
467
|
function utcStamp(ms) {
|
|
501
468
|
return new Date(ms).toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
|
|
@@ -508,7 +475,7 @@ function sanitizeKeyPart(value) {
|
|
|
508
475
|
return clean.length > 0 ? clean : "x";
|
|
509
476
|
}
|
|
510
477
|
|
|
511
|
-
// src/
|
|
478
|
+
// src/integration/mcp.ts
|
|
512
479
|
var MCP_PATH = "/mcp";
|
|
513
480
|
var AUTH_HEADER_TEMPLATE = `Bearer \${${readEnv_js.API_KEY_ENV}}`;
|
|
514
481
|
var DEFAULT_API_BASE2 = "https://api.agentchat.me";
|
|
@@ -644,7 +611,7 @@ function readInitializeResult(text) {
|
|
|
644
611
|
return null;
|
|
645
612
|
}
|
|
646
613
|
|
|
647
|
-
// src/
|
|
614
|
+
// src/integration/runtime-holder.ts
|
|
648
615
|
var current = null;
|
|
649
616
|
function isUsablePluginRuntime(runtime) {
|
|
650
617
|
if (!runtime || typeof runtime !== "object" && typeof runtime !== "function") return false;
|
|
@@ -662,9 +629,11 @@ function getPluginRuntime() {
|
|
|
662
629
|
return current;
|
|
663
630
|
}
|
|
664
631
|
|
|
665
|
-
// src/
|
|
632
|
+
// src/integration/model.ts
|
|
666
633
|
var DEFAULT_AGENT_ID = "main";
|
|
667
634
|
var GATE_TEMPERATURE = 0;
|
|
635
|
+
var DEFAULT_GATE_MAX_TOKENS = 2048;
|
|
636
|
+
var DEFAULT_GATE_TIMEOUT_MS = 2e4;
|
|
668
637
|
var DEFAULT_TURN_WAIT_MS = 15 * 6e4;
|
|
669
638
|
var RuntimeUnavailableError = class extends Error {
|
|
670
639
|
constructor(what) {
|
|
@@ -672,13 +641,13 @@ var RuntimeUnavailableError = class extends Error {
|
|
|
672
641
|
this.name = "RuntimeUnavailableError";
|
|
673
642
|
}
|
|
674
643
|
};
|
|
675
|
-
function
|
|
644
|
+
function resolveIntegrationAgentId(params) {
|
|
676
645
|
try {
|
|
677
646
|
const route = params.channelRuntime?.routing?.resolveAgentRoute?.({
|
|
678
647
|
cfg: params.cfg,
|
|
679
648
|
channel: AGENTCHAT_CHANNEL_ID,
|
|
680
649
|
accountId: params.accountId,
|
|
681
|
-
peer: { kind: "direct", id: "
|
|
650
|
+
peer: { kind: "direct", id: "wake" }
|
|
682
651
|
});
|
|
683
652
|
const agentId = route?.agentId;
|
|
684
653
|
if (typeof agentId === "string" && agentId.trim().length > 0) return agentId.trim();
|
|
@@ -686,18 +655,19 @@ function resolveDoorbellAgentId(params) {
|
|
|
686
655
|
}
|
|
687
656
|
return DEFAULT_AGENT_ID;
|
|
688
657
|
}
|
|
689
|
-
function
|
|
658
|
+
function createRuntimeModelCall(params) {
|
|
690
659
|
const getRuntime = params.runtime ?? getPluginRuntime;
|
|
691
|
-
|
|
660
|
+
const maxTokens = params.maxTokens ?? DEFAULT_GATE_MAX_TOKENS;
|
|
661
|
+
const timeoutMs = params.timeoutMs ?? DEFAULT_GATE_TIMEOUT_MS;
|
|
662
|
+
return async (prompt) => {
|
|
692
663
|
const runtime = getRuntime();
|
|
693
664
|
if (!runtime) throw new RuntimeUnavailableError("the gate call");
|
|
694
665
|
const result = await runtime.llm.complete({
|
|
695
|
-
|
|
696
|
-
messages: [{ role: "user", content: userContent }],
|
|
666
|
+
messages: [{ role: "user", content: prompt }],
|
|
697
667
|
maxTokens,
|
|
698
668
|
temperature: GATE_TEMPERATURE,
|
|
699
669
|
...params.agentIdOverride ? { agentId: params.agentIdOverride } : {},
|
|
700
|
-
purpose: "AgentChat reply gate: the server's question about the server's cards",
|
|
670
|
+
purpose: "AgentChat reply gate: the server's question about the server's cards (tool-free triage)",
|
|
701
671
|
...Number.isFinite(timeoutMs) && timeoutMs > 0 ? { signal: AbortSignal.timeout(timeoutMs) } : {}
|
|
702
672
|
});
|
|
703
673
|
return typeof result?.text === "string" ? result.text : "";
|
|
@@ -727,7 +697,7 @@ function resolveGateAgent(params) {
|
|
|
727
697
|
const ambient = params.ambientAgentId?.trim().toLowerCase();
|
|
728
698
|
return { agentId: routed, agentIdOverride: routed === (ambient ?? routed) ? void 0 : routed };
|
|
729
699
|
}
|
|
730
|
-
function
|
|
700
|
+
function createRuntimeTurnStarter(params = {}) {
|
|
731
701
|
const getRuntime = params.runtime ?? getPluginRuntime;
|
|
732
702
|
const waitMs = params.waitMs ?? DEFAULT_TURN_WAIT_MS;
|
|
733
703
|
return async (request) => {
|
|
@@ -745,12 +715,12 @@ function createRuntimeTurnRunner(params = {}) {
|
|
|
745
715
|
} catch (err) {
|
|
746
716
|
return { ran: false, error: err instanceof Error ? err.message : String(err) };
|
|
747
717
|
}
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
}
|
|
718
|
+
const done = runtime.subagent.waitForRun({ runId, timeoutMs: waitMs }).then(
|
|
719
|
+
(waited) => ({ ran: true, runId, status: waited.status, ...waited.error ? { error: waited.error } : {} }),
|
|
720
|
+
// The run was admitted; only the wait failed. The turn is OpenClaw's now.
|
|
721
|
+
(err) => ({ ran: true, runId, status: "unknown", error: err instanceof Error ? err.message : String(err) })
|
|
722
|
+
);
|
|
723
|
+
return { ran: true, runId, done };
|
|
754
724
|
};
|
|
755
725
|
}
|
|
756
726
|
var HANDLE_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
|
|
@@ -759,7 +729,7 @@ function isValidHandleShape(value) {
|
|
|
759
729
|
}
|
|
760
730
|
var DOTENV_NAME = ".env";
|
|
761
731
|
function dotEnvPath(stateDir = openclawLayout_js.resolveOpenClawStateDir()) {
|
|
762
|
-
return
|
|
732
|
+
return path2__namespace.join(stateDir, DOTENV_NAME);
|
|
763
733
|
}
|
|
764
734
|
function placeApiKeyInDotEnv(apiKey, stateDir = openclawLayout_js.resolveOpenClawStateDir()) {
|
|
765
735
|
const trimmed = apiKey.trim();
|
|
@@ -828,7 +798,7 @@ function stripQuotes(value) {
|
|
|
828
798
|
}
|
|
829
799
|
return value;
|
|
830
800
|
}
|
|
831
|
-
function
|
|
801
|
+
function applyIntegrationConfig(cfg, params) {
|
|
832
802
|
const changes = [];
|
|
833
803
|
let next = cfg;
|
|
834
804
|
const bareHandle = (params.handle ?? "").trim().replace(/^@/, "");
|
|
@@ -851,13 +821,13 @@ function applyDoorbellConfig(cfg, params) {
|
|
|
851
821
|
function resolvePlacementAgentId(cfg, accountId) {
|
|
852
822
|
return openclawLayout_js.resolveBoundAgentId(cfg, AGENTCHAT_CHANNEL_ID, accountId) ?? openclawLayout_js.resolveOpenClawDefaultAgentId(cfg);
|
|
853
823
|
}
|
|
854
|
-
function
|
|
824
|
+
function stripIntegrationConfig(cfg, accountId) {
|
|
855
825
|
const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? "https://api.agentchat.me";
|
|
856
826
|
const apiKey = readAgentchatConfigField(cfg, accountId, "apiKey");
|
|
857
827
|
const { cfg: next, removed } = withoutHostedMcpEntry(cfg, apiBase, apiKey);
|
|
858
828
|
return { cfg: next, changes: removed ? ["removed mcp.servers.agentchat"] : [] };
|
|
859
829
|
}
|
|
860
|
-
function
|
|
830
|
+
function removeIntegrationFiles(cfg, accountId, options) {
|
|
861
831
|
const changes = [];
|
|
862
832
|
try {
|
|
863
833
|
const removed = agentsAnchor_js.removeAgentsAnchor({ cfg, agentId: resolvePlacementAgentId(cfg, accountId) });
|
|
@@ -873,23 +843,38 @@ function removeDoorbellFiles(cfg, accountId, options) {
|
|
|
873
843
|
}
|
|
874
844
|
return changes;
|
|
875
845
|
}
|
|
876
|
-
function restoreIdentityLine(cfg, accountId, handle) {
|
|
846
|
+
function restoreIdentityLine(cfg, accountId, handle, identityLine) {
|
|
877
847
|
const agentId = resolvePlacementAgentId(cfg, accountId);
|
|
878
848
|
const bare = handle.trim().replace(/^@/, "");
|
|
879
849
|
let filePath = "";
|
|
880
850
|
try {
|
|
881
851
|
filePath = agentsAnchor_js.agentsAnchorPath(cfg, agentId);
|
|
882
852
|
if (!isValidHandleShape(bare)) return { outcome: "failed", path: filePath, detail: `agentHandle "${bare}" is not a valid AgentChat handle` };
|
|
883
|
-
|
|
853
|
+
if (identityLine === null) {
|
|
854
|
+
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" };
|
|
855
|
+
}
|
|
856
|
+
const present = agentsAnchor_js.hasAgentsAnchorFor({ cfg, handle: bare, text: identityLine, agentId });
|
|
884
857
|
filePath = present.path;
|
|
885
858
|
if (present.present) return { outcome: "present", path: present.path };
|
|
886
|
-
const written = agentsAnchor_js.writeAgentsAnchor({ cfg, handle: bare, agentId });
|
|
859
|
+
const written = agentsAnchor_js.writeAgentsAnchor({ cfg, handle: bare, text: identityLine, agentId });
|
|
887
860
|
return { outcome: "placed", path: written.path };
|
|
888
861
|
} catch (err) {
|
|
889
862
|
return { outcome: "failed", path: filePath, detail: describe(err) };
|
|
890
863
|
}
|
|
891
864
|
}
|
|
892
|
-
function
|
|
865
|
+
function refreshIdentityLine(cfg, accountId, handle, identityLine) {
|
|
866
|
+
const agentId = resolvePlacementAgentId(cfg, accountId);
|
|
867
|
+
try {
|
|
868
|
+
const found = agentsAnchor_js.readAgentsAnchor({ cfg, agentId });
|
|
869
|
+
if (!found.present) return { outcome: "absent", path: found.path };
|
|
870
|
+
if (found.text === identityLine.trim()) return { outcome: "unchanged", path: found.path };
|
|
871
|
+
const written = agentsAnchor_js.writeAgentsAnchor({ cfg, handle, text: identityLine, agentId });
|
|
872
|
+
return { outcome: "updated", path: written.path };
|
|
873
|
+
} catch (err) {
|
|
874
|
+
return { outcome: "failed", path: agentsAnchor_js.agentsAnchorPath(cfg, agentId), detail: describe(err) };
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
function placeIntegration(params) {
|
|
893
878
|
const steps = [];
|
|
894
879
|
if (params.placeKey !== false) {
|
|
895
880
|
try {
|
|
@@ -904,11 +889,20 @@ function placeDoorbell(params) {
|
|
|
904
889
|
}
|
|
905
890
|
}
|
|
906
891
|
const agentId = params.agentId ?? resolvePlacementAgentId(params.cfg, params.accountId ?? AGENTCHAT_DEFAULT_ACCOUNT_ID);
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
steps.push({
|
|
910
|
-
|
|
911
|
-
|
|
892
|
+
const handle = params.handle.replace(/^@/, "");
|
|
893
|
+
if (params.identityLine === null) {
|
|
894
|
+
steps.push({
|
|
895
|
+
name: "anchor",
|
|
896
|
+
status: "skipped",
|
|
897
|
+
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`
|
|
898
|
+
});
|
|
899
|
+
} else {
|
|
900
|
+
try {
|
|
901
|
+
const anchor = agentsAnchor_js.writeAgentsAnchor({ cfg: params.cfg, handle: params.handle, text: params.identityLine, agentId });
|
|
902
|
+
steps.push({ name: "anchor", status: "ok", detail: `identity line for @${handle} in ${anchor.path}` });
|
|
903
|
+
} catch (err) {
|
|
904
|
+
steps.push({ name: "anchor", status: "failed", detail: `could not write the identity line to AGENTS.md: ${describe(err)}` });
|
|
905
|
+
}
|
|
912
906
|
}
|
|
913
907
|
steps.push({ name: "manual", status: "ok", detail: "manual bundled as the agentchat skill (skills/agentchat/SKILL.md, https://agentchat.me/skill.md verbatim)" });
|
|
914
908
|
const mcp = withHostedMcpEntry(params.cfg, params.apiBase, params.apiKey);
|
|
@@ -950,7 +944,7 @@ function checkPlacement(params) {
|
|
|
950
944
|
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
945
|
}
|
|
952
946
|
if (params.handle) {
|
|
953
|
-
const anchor = agentsAnchor_js.hasAgentsAnchorFor({ cfg: params.cfg, handle: params.handle, agentId: params.agentId });
|
|
947
|
+
const anchor = agentsAnchor_js.hasAgentsAnchorFor({ cfg: params.cfg, handle: params.handle, text: params.identityLine, agentId: params.agentId });
|
|
954
948
|
checks.push({
|
|
955
949
|
name: "anchor",
|
|
956
950
|
ok: anchor.present,
|
|
@@ -971,6 +965,266 @@ function checkPlacement(params) {
|
|
|
971
965
|
function describe(err) {
|
|
972
966
|
return err instanceof Error ? err.message : String(err);
|
|
973
967
|
}
|
|
968
|
+
var PLUGIN_STATE_DIRNAME = "agentchat";
|
|
969
|
+
function safeSegment(value) {
|
|
970
|
+
const clean = value.replace(/[^A-Za-z0-9_.-]/g, "-").replace(/^\.+/, "");
|
|
971
|
+
return clean.length > 0 ? clean : "default";
|
|
972
|
+
}
|
|
973
|
+
function integrationStateDir(accountId, stateDir = openclawLayout_js.resolveOpenClawStateDir()) {
|
|
974
|
+
return path2__namespace.join(stateDir, PLUGIN_STATE_DIRNAME, safeSegment(accountId));
|
|
975
|
+
}
|
|
976
|
+
function readJsonFile(file) {
|
|
977
|
+
let raw;
|
|
978
|
+
try {
|
|
979
|
+
raw = fs__namespace.readFileSync(file, "utf8");
|
|
980
|
+
} catch {
|
|
981
|
+
return null;
|
|
982
|
+
}
|
|
983
|
+
try {
|
|
984
|
+
return JSON.parse(raw);
|
|
985
|
+
} catch {
|
|
986
|
+
return null;
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
function writeJsonFile(file, value) {
|
|
990
|
+
fs__namespace.mkdirSync(path2__namespace.dirname(file), { recursive: true });
|
|
991
|
+
const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`;
|
|
992
|
+
fs__namespace.writeFileSync(tmp, `${JSON.stringify(value, null, 2)}
|
|
993
|
+
`, "utf8");
|
|
994
|
+
try {
|
|
995
|
+
fs__namespace.renameSync(tmp, file);
|
|
996
|
+
} catch (err) {
|
|
997
|
+
try {
|
|
998
|
+
fs__namespace.unlinkSync(tmp);
|
|
999
|
+
} catch {
|
|
1000
|
+
}
|
|
1001
|
+
throw err;
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
// src/integration/texts.ts
|
|
1006
|
+
var TEXTS_RUNTIME = "openclaw";
|
|
1007
|
+
var TEXTS_REFRESH_MS = 24 * 60 * 6e4;
|
|
1008
|
+
var TEXTS_RETRY_MS = 5 * 6e4;
|
|
1009
|
+
var TEXTS_FETCH_TIMEOUT_MS = 1e4;
|
|
1010
|
+
var TEXTS_CACHE_FILE = "texts.json";
|
|
1011
|
+
function isTexts(value) {
|
|
1012
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1013
|
+
const t = value;
|
|
1014
|
+
const manual = t.manual;
|
|
1015
|
+
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";
|
|
1016
|
+
}
|
|
1017
|
+
function textsCachePath(accountId, stateDir) {
|
|
1018
|
+
return path2__namespace.join(integrationStateDir(accountId, stateDir), TEXTS_CACHE_FILE);
|
|
1019
|
+
}
|
|
1020
|
+
function readCachedTexts(accountId, stateDir) {
|
|
1021
|
+
const raw = readJsonFile(textsCachePath(accountId, stateDir));
|
|
1022
|
+
if (!raw || typeof raw !== "object") return null;
|
|
1023
|
+
const entry = raw;
|
|
1024
|
+
if (typeof entry.fetched_at !== "string" || !isTexts(entry.texts)) return null;
|
|
1025
|
+
return { fetched_at: entry.fetched_at, texts: entry.texts };
|
|
1026
|
+
}
|
|
1027
|
+
function writeCachedTexts(accountId, texts, fetchedAt, stateDir) {
|
|
1028
|
+
const file = textsCachePath(accountId, stateDir);
|
|
1029
|
+
const entry = { fetched_at: fetchedAt.toISOString(), texts };
|
|
1030
|
+
writeJsonFile(file, entry);
|
|
1031
|
+
return file;
|
|
1032
|
+
}
|
|
1033
|
+
function spellTextsForOpenClaw(texts) {
|
|
1034
|
+
return {
|
|
1035
|
+
...texts,
|
|
1036
|
+
wake_instruction: spellToolsForOpenClaw(texts.wake_instruction),
|
|
1037
|
+
invite_prompt: spellToolsForOpenClaw(texts.invite_prompt),
|
|
1038
|
+
identity_line: spellToolsForOpenClaw(texts.identity_line),
|
|
1039
|
+
identity_line_template: spellToolsForOpenClaw(texts.identity_line_template)
|
|
1040
|
+
};
|
|
1041
|
+
}
|
|
1042
|
+
async function fetchTexts(client, timeoutMs = TEXTS_FETCH_TIMEOUT_MS) {
|
|
1043
|
+
const texts = await client.texts.get({ runtime: TEXTS_RUNTIME, timeoutMs });
|
|
1044
|
+
if (!isTexts(texts)) throw new Error("GET /v1/texts: answer is not a texts set (missing wake_instruction, invite_prompt or identity_line)");
|
|
1045
|
+
return texts;
|
|
1046
|
+
}
|
|
1047
|
+
async function loadTexts(params) {
|
|
1048
|
+
const now = params.now ?? Date.now;
|
|
1049
|
+
try {
|
|
1050
|
+
const texts = await fetchTexts(params.client, params.timeoutMs);
|
|
1051
|
+
const fetchedAt = new Date(now());
|
|
1052
|
+
try {
|
|
1053
|
+
writeCachedTexts(params.accountId, texts, fetchedAt, params.stateDir);
|
|
1054
|
+
} catch (err) {
|
|
1055
|
+
params.log?.warn({ err: describe2(err) }, "texts fetched but the cache could not be written");
|
|
1056
|
+
}
|
|
1057
|
+
return { texts: spellTextsForOpenClaw(texts), source: "server", fetchedAt: fetchedAt.toISOString() };
|
|
1058
|
+
} catch (err) {
|
|
1059
|
+
const cached = readCachedTexts(params.accountId, params.stateDir);
|
|
1060
|
+
if (cached) {
|
|
1061
|
+
params.log?.info({ err: describe2(err), fetchedAt: cached.fetched_at }, "texts: server unreachable \u2014 using the cached copy");
|
|
1062
|
+
return { texts: spellTextsForOpenClaw(cached.texts), source: "cache", fetchedAt: cached.fetched_at };
|
|
1063
|
+
}
|
|
1064
|
+
params.log?.debug({ err: describe2(err) }, "texts: server unreachable and nothing cached");
|
|
1065
|
+
return null;
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
async function loadIdentityLine(params) {
|
|
1069
|
+
const loaded = await loadTexts(params);
|
|
1070
|
+
return loaded ? loaded.texts.identity_line : null;
|
|
1071
|
+
}
|
|
1072
|
+
function cachedIdentityLine(accountId, stateDir) {
|
|
1073
|
+
const cached = readCachedTexts(accountId, stateDir);
|
|
1074
|
+
return cached ? spellToolsForOpenClaw(cached.texts.identity_line) : null;
|
|
1075
|
+
}
|
|
1076
|
+
var TextsStore = class {
|
|
1077
|
+
client;
|
|
1078
|
+
accountId;
|
|
1079
|
+
logger;
|
|
1080
|
+
stateDir;
|
|
1081
|
+
refreshMs;
|
|
1082
|
+
retryMs;
|
|
1083
|
+
fetchTimeoutMs;
|
|
1084
|
+
now;
|
|
1085
|
+
_setTimeout;
|
|
1086
|
+
_clearTimeout;
|
|
1087
|
+
loaded = null;
|
|
1088
|
+
timer = null;
|
|
1089
|
+
inFlight = null;
|
|
1090
|
+
stopped = false;
|
|
1091
|
+
missingAnnounced = false;
|
|
1092
|
+
listeners = /* @__PURE__ */ new Set();
|
|
1093
|
+
loads = 0;
|
|
1094
|
+
serverLoads = 0;
|
|
1095
|
+
constructor(options) {
|
|
1096
|
+
this.client = options.client;
|
|
1097
|
+
this.accountId = options.accountId;
|
|
1098
|
+
this.logger = options.logger.child({ component: "texts", accountId: options.accountId });
|
|
1099
|
+
this.stateDir = options.stateDir;
|
|
1100
|
+
this.refreshMs = options.refreshMs ?? TEXTS_REFRESH_MS;
|
|
1101
|
+
this.retryMs = options.retryMs ?? TEXTS_RETRY_MS;
|
|
1102
|
+
this.fetchTimeoutMs = options.fetchTimeoutMs ?? TEXTS_FETCH_TIMEOUT_MS;
|
|
1103
|
+
this.now = options.now ?? Date.now;
|
|
1104
|
+
this._setTimeout = options.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
|
|
1105
|
+
this._clearTimeout = options.clearTimeout ?? ((h) => clearTimeout(h));
|
|
1106
|
+
}
|
|
1107
|
+
/** The texts spelled for OpenClaw, or null until the first copy exists. */
|
|
1108
|
+
get current() {
|
|
1109
|
+
return this.loaded?.texts ?? null;
|
|
1110
|
+
}
|
|
1111
|
+
get source() {
|
|
1112
|
+
return this.loaded?.source ?? null;
|
|
1113
|
+
}
|
|
1114
|
+
get fetchedAt() {
|
|
1115
|
+
return this.loaded?.fetchedAt ?? null;
|
|
1116
|
+
}
|
|
1117
|
+
/** Called with every copy that arrives from the server (not with a cached one). */
|
|
1118
|
+
onServerCopy(listener) {
|
|
1119
|
+
this.listeners.add(listener);
|
|
1120
|
+
return () => {
|
|
1121
|
+
this.listeners.delete(listener);
|
|
1122
|
+
};
|
|
1123
|
+
}
|
|
1124
|
+
/** First load (server, then cache), then the timer. Resolves after the first attempt; never throws. */
|
|
1125
|
+
async start() {
|
|
1126
|
+
const texts = await this.load();
|
|
1127
|
+
if (!texts && !this.missingAnnounced) {
|
|
1128
|
+
this.missingAnnounced = true;
|
|
1129
|
+
this.logger.warn(
|
|
1130
|
+
{ retryMs: this.retryMs },
|
|
1131
|
+
"AgentChat texts unreachable and nothing cached \u2014 starting anyway; turns wait for the first copy, retried until it arrives"
|
|
1132
|
+
);
|
|
1133
|
+
}
|
|
1134
|
+
this.arm();
|
|
1135
|
+
return texts;
|
|
1136
|
+
}
|
|
1137
|
+
/** The current copy, or one load attempt now (coalesced with any in flight). */
|
|
1138
|
+
async ensure() {
|
|
1139
|
+
if (this.loaded) return this.loaded.texts;
|
|
1140
|
+
if (this.stopped) return null;
|
|
1141
|
+
return this.load();
|
|
1142
|
+
}
|
|
1143
|
+
/** Force a refresh (tests, operators). Coalesced. */
|
|
1144
|
+
refresh() {
|
|
1145
|
+
return this.load();
|
|
1146
|
+
}
|
|
1147
|
+
stop() {
|
|
1148
|
+
this.stopped = true;
|
|
1149
|
+
if (this.timer !== null) {
|
|
1150
|
+
this._clearTimeout(this.timer);
|
|
1151
|
+
this.timer = null;
|
|
1152
|
+
}
|
|
1153
|
+
this.listeners.clear();
|
|
1154
|
+
}
|
|
1155
|
+
load() {
|
|
1156
|
+
if (this.inFlight) return this.inFlight;
|
|
1157
|
+
this.inFlight = (async () => {
|
|
1158
|
+
this.loads += 1;
|
|
1159
|
+
const next = await loadTexts({
|
|
1160
|
+
client: this.client,
|
|
1161
|
+
accountId: this.accountId,
|
|
1162
|
+
stateDir: this.stateDir,
|
|
1163
|
+
now: this.now,
|
|
1164
|
+
log: this.logger,
|
|
1165
|
+
timeoutMs: this.fetchTimeoutMs
|
|
1166
|
+
});
|
|
1167
|
+
if (this.stopped) return next?.texts ?? null;
|
|
1168
|
+
if (next) {
|
|
1169
|
+
const changed = this.loaded?.texts.version !== next.texts.version || this.loaded?.texts.wake_instruction !== next.texts.wake_instruction;
|
|
1170
|
+
this.loaded = next;
|
|
1171
|
+
if (next.source === "server") {
|
|
1172
|
+
this.serverLoads += 1;
|
|
1173
|
+
this.logger[changed ? "info" : "debug"](
|
|
1174
|
+
{ version: next.texts.version, manual: next.texts.manual.version },
|
|
1175
|
+
"texts fetched from the server"
|
|
1176
|
+
);
|
|
1177
|
+
for (const listener of this.listeners) {
|
|
1178
|
+
try {
|
|
1179
|
+
listener(next.texts, next.source);
|
|
1180
|
+
} catch (err) {
|
|
1181
|
+
this.logger.warn({ err: describe2(err) }, "texts listener threw \u2014 continuing");
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
return next?.texts ?? null;
|
|
1187
|
+
})().finally(() => {
|
|
1188
|
+
this.inFlight = null;
|
|
1189
|
+
});
|
|
1190
|
+
return this.inFlight;
|
|
1191
|
+
}
|
|
1192
|
+
arm() {
|
|
1193
|
+
if (this.stopped) return;
|
|
1194
|
+
if (this.timer !== null) this._clearTimeout(this.timer);
|
|
1195
|
+
const delay = this.loaded === null ? this.retryMs : this.loaded.source === "cache" ? this.retryMs : this.refreshMs;
|
|
1196
|
+
this.timer = this._setTimeout(() => {
|
|
1197
|
+
this.timer = null;
|
|
1198
|
+
void this.load().finally(() => this.arm());
|
|
1199
|
+
}, delay);
|
|
1200
|
+
this.timer.unref?.();
|
|
1201
|
+
}
|
|
1202
|
+
};
|
|
1203
|
+
function describe2(err) {
|
|
1204
|
+
return err instanceof Error ? err.message : String(err);
|
|
1205
|
+
}
|
|
1206
|
+
var cache = /* @__PURE__ */ new Map();
|
|
1207
|
+
function createSdkClient(params) {
|
|
1208
|
+
return new agentchatme.AgentChatClient({
|
|
1209
|
+
apiKey: params.apiKey,
|
|
1210
|
+
...params.apiBase ? { baseUrl: params.apiBase } : {},
|
|
1211
|
+
clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
|
|
1212
|
+
...params.options
|
|
1213
|
+
});
|
|
1214
|
+
}
|
|
1215
|
+
function getClient({ accountId, config, options }) {
|
|
1216
|
+
const existing = cache.get(accountId);
|
|
1217
|
+
if (existing && existing.apiKey === config.apiKey && existing.apiBase === config.apiBase) {
|
|
1218
|
+
return existing.client;
|
|
1219
|
+
}
|
|
1220
|
+
const client = createSdkClient({ apiKey: config.apiKey, apiBase: config.apiBase, options });
|
|
1221
|
+
cache.set(accountId, {
|
|
1222
|
+
client,
|
|
1223
|
+
apiKey: config.apiKey,
|
|
1224
|
+
apiBase: config.apiBase
|
|
1225
|
+
});
|
|
1226
|
+
return client;
|
|
1227
|
+
}
|
|
974
1228
|
|
|
975
1229
|
// src/channel.wizard.ts
|
|
976
1230
|
var JUST_REGISTERED_SENTINEL = "_agentchatJustRegistered";
|
|
@@ -1641,18 +1895,22 @@ var agentchatSetupWizard = {
|
|
|
1641
1895
|
if (result.ok) {
|
|
1642
1896
|
spinner.stop(`Authenticated as @${result.agent.handle}`);
|
|
1643
1897
|
const handle = result.agent.handle;
|
|
1644
|
-
const
|
|
1898
|
+
const resolvedBase = apiBase ?? DEFAULT_API_BASE2;
|
|
1899
|
+
const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase: resolvedBase }), accountId });
|
|
1900
|
+
const placed = placeIntegration({ cfg, handle, apiKey, apiBase: resolvedBase, identityLine, accountId });
|
|
1645
1901
|
const failed = placed.steps.filter((s) => s.status === "failed");
|
|
1902
|
+
const skipped = placed.steps.filter((s) => s.status === "skipped" && s.name === "anchor");
|
|
1646
1903
|
await prompter.note(
|
|
1647
1904
|
[
|
|
1648
1905
|
...formatPlacement(placed.steps),
|
|
1649
1906
|
"",
|
|
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."] : []
|
|
1907
|
+
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.",
|
|
1908
|
+
...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."] : [],
|
|
1909
|
+
...skipped.length > 0 ? ["", "The identity line waits for AgentChat to be reachable: run `openclaw doctor --fix` then."] : []
|
|
1652
1910
|
].join("\n"),
|
|
1653
|
-
"AgentChat
|
|
1911
|
+
"AgentChat integration placed"
|
|
1654
1912
|
);
|
|
1655
|
-
const applied =
|
|
1913
|
+
const applied = applyIntegrationConfig(placed.cfg, { accountId, handle, apiKey, apiBase: resolvedBase });
|
|
1656
1914
|
return { cfg: applied.cfg };
|
|
1657
1915
|
}
|
|
1658
1916
|
spinner.stop(`API key did not pass the live check (${result.reason})`);
|
|
@@ -1701,7 +1959,7 @@ var agentchatSetupWizard = {
|
|
|
1701
1959
|
// when the user explicitly removes the channel; orphans are documented in
|
|
1702
1960
|
// RUNBOOK.md.
|
|
1703
1961
|
disable: (cfg) => {
|
|
1704
|
-
return setup.setSetupChannelEnabled(
|
|
1962
|
+
return setup.setSetupChannelEnabled(stripIntegrationConfig(cfg, "default").cfg, AGENTCHAT_CHANNEL_ID, false);
|
|
1705
1963
|
}
|
|
1706
1964
|
};
|
|
1707
1965
|
var reconnectConfigSchema = zod.z.object({
|
|
@@ -1790,808 +2048,283 @@ function wrapPino(p) {
|
|
|
1790
2048
|
// src/metrics.ts
|
|
1791
2049
|
function createNoopMetrics() {
|
|
1792
2050
|
return {
|
|
1793
|
-
|
|
2051
|
+
incDisconnect: () => void 0,
|
|
1794
2052
|
incError: () => void 0,
|
|
1795
2053
|
setConnectionState: () => void 0,
|
|
1796
|
-
|
|
2054
|
+
incWake: () => void 0
|
|
1797
2055
|
};
|
|
1798
2056
|
}
|
|
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
|
-
|
|
2057
|
+
function groupInviteFromRecord(record) {
|
|
2058
|
+
if (!record || typeof record !== "object" || Array.isArray(record)) return null;
|
|
2059
|
+
const row = record;
|
|
2060
|
+
const inviteId = str(row.id);
|
|
2061
|
+
const groupId = str(row.group_id);
|
|
2062
|
+
if (!inviteId || !groupId) return null;
|
|
2063
|
+
return {
|
|
2064
|
+
inviteId,
|
|
2065
|
+
groupId,
|
|
2066
|
+
groupName: str(row.group_name) ?? "",
|
|
2067
|
+
inviterHandle: (str(row.inviter_handle) ?? "").replace(/^@/, "")
|
|
2068
|
+
};
|
|
2069
|
+
}
|
|
2070
|
+
function str(value) {
|
|
2071
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
2072
|
+
}
|
|
2073
|
+
var INVITE_LEDGER_FILE = "invites.json";
|
|
2074
|
+
var INVITE_LEDGER_MAX_AGE_MS = 30 * 24 * 60 * 6e4;
|
|
2075
|
+
function inviteLedgerPath(accountId, stateDir) {
|
|
2076
|
+
return path2__namespace.join(integrationStateDir(accountId, stateDir), INVITE_LEDGER_FILE);
|
|
2077
|
+
}
|
|
2078
|
+
var InviteLedger = class {
|
|
2079
|
+
file;
|
|
2080
|
+
now;
|
|
2081
|
+
maxAgeMs;
|
|
2082
|
+
onWriteError;
|
|
2083
|
+
offered;
|
|
2084
|
+
constructor(options) {
|
|
2085
|
+
this.file = options.file ?? inviteLedgerPath(options.accountId, options.stateDir);
|
|
2086
|
+
this.now = options.now ?? Date.now;
|
|
2087
|
+
this.maxAgeMs = options.maxAgeMs ?? INVITE_LEDGER_MAX_AGE_MS;
|
|
2088
|
+
this.onWriteError = options.onWriteError;
|
|
2089
|
+
this.offered = this.read();
|
|
2090
|
+
}
|
|
2091
|
+
get path() {
|
|
2092
|
+
return this.file;
|
|
2093
|
+
}
|
|
2094
|
+
get size() {
|
|
2095
|
+
return this.offered.size;
|
|
2096
|
+
}
|
|
2097
|
+
/** True when a turn for this invite was started before (in this process or an earlier one). */
|
|
2098
|
+
isOffered(inviteId) {
|
|
2099
|
+
return this.offered.has(inviteId);
|
|
2100
|
+
}
|
|
2101
|
+
/** Record that a turn for this invite was admitted. Persists at once. */
|
|
2102
|
+
markOffered(inviteId) {
|
|
2103
|
+
this.offered.set(inviteId, new Date(this.now()).toISOString());
|
|
2104
|
+
this.prune();
|
|
2105
|
+
try {
|
|
2106
|
+
writeJsonFile(this.file, { offered: Object.fromEntries(this.offered) });
|
|
2107
|
+
} catch (err) {
|
|
2108
|
+
this.onWriteError?.(err);
|
|
1851
2109
|
}
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
2110
|
+
}
|
|
2111
|
+
read() {
|
|
2112
|
+
const raw = readJsonFile(this.file);
|
|
2113
|
+
const out = /* @__PURE__ */ new Map();
|
|
2114
|
+
if (!raw || typeof raw !== "object") return out;
|
|
2115
|
+
const offered = raw.offered;
|
|
2116
|
+
if (!offered || typeof offered !== "object" || Array.isArray(offered)) return out;
|
|
2117
|
+
for (const [id, at] of Object.entries(offered)) {
|
|
2118
|
+
if (typeof at === "string" && id.length > 0) out.set(id, at);
|
|
1859
2119
|
}
|
|
1860
|
-
|
|
1861
|
-
|
|
2120
|
+
this.offered = out;
|
|
2121
|
+
this.prune();
|
|
2122
|
+
return this.offered;
|
|
2123
|
+
}
|
|
2124
|
+
prune() {
|
|
2125
|
+
const cutoff = this.now() - this.maxAgeMs;
|
|
2126
|
+
for (const [id, at] of this.offered) {
|
|
2127
|
+
const t = Date.parse(at);
|
|
2128
|
+
if (!Number.isFinite(t) || t < cutoff) this.offered.delete(id);
|
|
1862
2129
|
}
|
|
1863
2130
|
}
|
|
2131
|
+
};
|
|
2132
|
+
|
|
2133
|
+
// src/integration/socket.ts
|
|
2134
|
+
function wakeSourceOf(reason) {
|
|
2135
|
+
return reason === "reminder" ? "reminder" : "other";
|
|
1864
2136
|
}
|
|
1865
|
-
function
|
|
1866
|
-
return
|
|
2137
|
+
function realtimeOptionsFor(config, extra = {}) {
|
|
2138
|
+
return {
|
|
2139
|
+
apiKey: config.apiKey,
|
|
2140
|
+
baseUrl: config.apiBase.replace(/^http/, "ws").replace(/\/+$/, ""),
|
|
2141
|
+
clientIdentity: AGENTCHAT_CLIENT_IDENTITY,
|
|
2142
|
+
ackOnReceipt: true,
|
|
2143
|
+
reconnect: true,
|
|
2144
|
+
reconnectInterval: config.reconnect.initialBackoffMs,
|
|
2145
|
+
maxReconnectInterval: config.reconnect.maxBackoffMs,
|
|
2146
|
+
...extra.client ? { client: extra.client } : {},
|
|
2147
|
+
...extra.webSocket ? { webSocket: extra.webSocket } : {}
|
|
2148
|
+
};
|
|
1867
2149
|
}
|
|
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 {
|
|
2150
|
+
var IntegrationSocket = class {
|
|
1886
2151
|
config;
|
|
1887
2152
|
logger;
|
|
2153
|
+
handlers;
|
|
1888
2154
|
metrics;
|
|
2155
|
+
client;
|
|
2156
|
+
createRealtime;
|
|
2157
|
+
webSocket;
|
|
1889
2158
|
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
|
-
};
|
|
2159
|
+
selfHandle;
|
|
2160
|
+
realtime = null;
|
|
2161
|
+
/** The SDK's state as last reported through its `state` event; `stopped` is set here only for a stop before any start. */
|
|
2162
|
+
state = "idle";
|
|
2163
|
+
connectedAt = null;
|
|
2164
|
+
stopping = false;
|
|
2165
|
+
frames = 0;
|
|
2166
|
+
selfFiltered = 0;
|
|
2167
|
+
wakes = 0;
|
|
2168
|
+
invites = 0;
|
|
2169
|
+
disconnects = 0;
|
|
1921
2170
|
constructor(options) {
|
|
1922
2171
|
this.config = options.config;
|
|
1923
|
-
this.logger = options.logger.child({ component: "
|
|
1924
|
-
this.
|
|
2172
|
+
this.logger = options.logger.child({ component: "socket" });
|
|
2173
|
+
this.handlers = options.handlers ?? {};
|
|
2174
|
+
this.metrics = options.metrics ?? createNoopMetrics();
|
|
2175
|
+
this.client = options.client;
|
|
2176
|
+
this.createRealtime = options.createRealtime ?? ((opts) => new agentchatme.RealtimeClient(opts));
|
|
2177
|
+
this.webSocket = options.webSocket;
|
|
1925
2178
|
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;
|
|
2179
|
+
this.selfHandle = this.config.agentHandle?.replace(/^@/, "").toLowerCase();
|
|
2180
|
+
this.metrics.setConnectionState(this.state);
|
|
1946
2181
|
}
|
|
1947
2182
|
/**
|
|
1948
|
-
*
|
|
1949
|
-
*
|
|
2183
|
+
* Open the socket. Idempotent. Resolves once the SDK has started its
|
|
2184
|
+
* connect loop; a failure to resolve a WebSocket implementation is logged
|
|
2185
|
+
* and left to the SDK's own retry. Never throws.
|
|
1950
2186
|
*/
|
|
1951
|
-
start() {
|
|
1952
|
-
if (this.
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
2187
|
+
async start() {
|
|
2188
|
+
if (this.realtime || this.stopping) return;
|
|
2189
|
+
const realtime = this.createRealtime(realtimeOptionsFor(this.config, { client: this.client, webSocket: this.webSocket }));
|
|
2190
|
+
this.realtime = realtime;
|
|
2191
|
+
this.bind(realtime);
|
|
2192
|
+
try {
|
|
2193
|
+
await realtime.connect();
|
|
2194
|
+
} catch (err) {
|
|
2195
|
+
this.logger.warn({ err: describe3(err) }, "socket connect failed \u2014 the SDK retries on its own schedule");
|
|
1957
2196
|
}
|
|
1958
|
-
this.openSocket(1);
|
|
1959
2197
|
}
|
|
1960
|
-
/**
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
this.
|
|
1971
|
-
this.scheduleDrainDeadline(computedDeadline);
|
|
2198
|
+
/** Close the socket for good; a stopped socket does not reconnect. Idempotent. */
|
|
2199
|
+
async stop() {
|
|
2200
|
+
this.stopping = true;
|
|
2201
|
+
const realtime = this.realtime;
|
|
2202
|
+
this.realtime = null;
|
|
2203
|
+
this.connectedAt = null;
|
|
2204
|
+
if (realtime) {
|
|
2205
|
+
try {
|
|
2206
|
+
realtime.disconnect();
|
|
2207
|
+
} catch (err) {
|
|
2208
|
+
this.logger.warn({ err: describe3(err) }, "socket disconnect threw \u2014 continuing");
|
|
1972
2209
|
}
|
|
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
2210
|
}
|
|
2211
|
+
if (this.state !== "stopped") this.onState("stopped", this.state);
|
|
1986
2212
|
}
|
|
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);
|
|
2213
|
+
getHealth() {
|
|
2214
|
+
return {
|
|
2215
|
+
state: this.state,
|
|
2216
|
+
connectedAt: this.connectedAt,
|
|
2217
|
+
counters: { frames: this.frames, selfFiltered: this.selfFiltered, wakes: this.wakes, invites: this.invites, disconnects: this.disconnects }
|
|
2002
2218
|
};
|
|
2003
2219
|
}
|
|
2004
|
-
// ─── Internals
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
});
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
this.scheduleReconnect("ctor-failed");
|
|
2029
|
-
return;
|
|
2030
|
-
}
|
|
2031
|
-
this.ws = ws;
|
|
2032
|
-
this.bindSocket(ws);
|
|
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
|
-
)
|
|
2220
|
+
// ─── Internals ─────────────────────────────────────────────────────
|
|
2221
|
+
bind(realtime) {
|
|
2222
|
+
realtime.on("state", (next, prev) => this.onState(next, prev));
|
|
2223
|
+
realtime.onConnect(() => {
|
|
2224
|
+
const at = this.now();
|
|
2225
|
+
this.connectedAt = at;
|
|
2226
|
+
this.logger.info({ at: new Date(at).toISOString() }, "connected (HELLO accepted)");
|
|
2227
|
+
this.guard("onConnected", () => this.handlers.onConnected?.(at));
|
|
2228
|
+
this.wake("connect", {});
|
|
2229
|
+
});
|
|
2230
|
+
realtime.onDisconnect((info) => {
|
|
2231
|
+
if (this.stopping) return;
|
|
2232
|
+
this.disconnects += 1;
|
|
2233
|
+
this.connectedAt = null;
|
|
2234
|
+
this.metrics.incDisconnect({ code: String(info.code), initiator: info.initiator });
|
|
2235
|
+
this.logger.info({ code: info.code, reason: info.reason, initiator: info.initiator }, "socket closed \u2014 the SDK decides what follows (backoff or blocked)");
|
|
2236
|
+
this.guard("onDisconnected", () => this.handlers.onDisconnected?.(info));
|
|
2237
|
+
});
|
|
2238
|
+
realtime.on("blocked", (info) => {
|
|
2239
|
+
if (this.stopping) return;
|
|
2240
|
+
this.metrics.incError({ errorClass: "auth" });
|
|
2241
|
+
this.logger.warn(
|
|
2242
|
+
{ code: info.code, reason: info.reason, retryInMs: info.retryInMs },
|
|
2243
|
+
"the server rejected the key during the handshake \u2014 the SDK retries a fresh HELLO on its own"
|
|
2046
2244
|
);
|
|
2245
|
+
this.guard("onBlocked", () => this.handlers.onBlocked?.(info));
|
|
2246
|
+
});
|
|
2247
|
+
realtime.onError((error) => {
|
|
2248
|
+
if (this.stopping) return;
|
|
2249
|
+
if (realtime.state === "blocked") {
|
|
2250
|
+
this.logger.debug({ err: error.message }, "SDK notice while blocked");
|
|
2251
|
+
return;
|
|
2252
|
+
}
|
|
2253
|
+
this.metrics.incError({ errorClass: classifyRealtimeError(error) });
|
|
2254
|
+
this.logger.debug({ err: error.message }, "socket error");
|
|
2255
|
+
this.guard("onError", () => this.handlers.onError?.(error));
|
|
2047
2256
|
});
|
|
2257
|
+
realtime.on("message.new", (message) => this.onMessageNew(message));
|
|
2258
|
+
realtime.on("wake", (frame) => this.onWakeFrame(frame));
|
|
2259
|
+
realtime.on("group.invite.received", (message) => this.onInvite(message));
|
|
2048
2260
|
}
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
const
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
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");
|
|
2261
|
+
onMessageNew(message) {
|
|
2262
|
+
this.frames += 1;
|
|
2263
|
+
const payload = message.payload ?? {};
|
|
2264
|
+
const senderRaw = payload.sender ?? payload.from ?? "";
|
|
2265
|
+
const sender = typeof senderRaw === "string" ? senderRaw.replace(/^@/, "").toLowerCase() : "";
|
|
2266
|
+
const detail = {
|
|
2267
|
+
...typeof payload.conversation_id === "string" ? { conversationId: payload.conversation_id } : {},
|
|
2268
|
+
...typeof payload.id === "string" ? { messageId: payload.id } : {},
|
|
2269
|
+
...sender ? { from: sender } : {}
|
|
2270
|
+
};
|
|
2271
|
+
if (this.selfHandle && sender === this.selfHandle) {
|
|
2272
|
+
this.selfFiltered += 1;
|
|
2273
|
+
this.logger.debug(detail, "own echo \u2014 not a wake");
|
|
2072
2274
|
return;
|
|
2073
2275
|
}
|
|
2074
|
-
this.
|
|
2075
|
-
|
|
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);
|
|
2276
|
+
this.logger.debug(detail, "wake \u2014 message.new");
|
|
2277
|
+
this.wake("message", detail);
|
|
2082
2278
|
}
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
}
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2279
|
+
onWakeFrame(frame) {
|
|
2280
|
+
this.frames += 1;
|
|
2281
|
+
const reason = frame.payload?.reason;
|
|
2282
|
+
const detail = { conversationId: frame.payload.conversation_id };
|
|
2283
|
+
this.logger.info({ ...detail, reason, step: frame.payload.step }, "wake \u2014 server wake frame");
|
|
2284
|
+
this.wake(wakeSourceOf(reason), detail);
|
|
2285
|
+
}
|
|
2286
|
+
onInvite(message) {
|
|
2287
|
+
this.frames += 1;
|
|
2288
|
+
const invite = groupInviteFromRecord(message.payload);
|
|
2289
|
+
if (!invite) {
|
|
2290
|
+
this.logger.warn({ keys: Object.keys(message.payload ?? {}).sort() }, "group.invite.received without ids \u2014 dropped");
|
|
2092
2291
|
return;
|
|
2093
2292
|
}
|
|
2094
|
-
|
|
2293
|
+
this.invites += 1;
|
|
2294
|
+
this.guard("onGroupInvite", () => this.handlers.onGroupInvite?.(invite));
|
|
2295
|
+
}
|
|
2296
|
+
wake(source, detail) {
|
|
2297
|
+
this.wakes += 1;
|
|
2298
|
+
this.metrics.incWake({ source });
|
|
2299
|
+
this.guard("onWake", () => this.handlers.onWake?.(source, detail));
|
|
2300
|
+
}
|
|
2301
|
+
/** The SDK's state transition, mirrored for the health probe and the gauge, then handed on. */
|
|
2302
|
+
onState(next, prev) {
|
|
2303
|
+
this.state = next;
|
|
2304
|
+
this.metrics.setConnectionState(next);
|
|
2305
|
+
this.logger.debug({ from: prev, to: next }, "socket state");
|
|
2306
|
+
this.guard("onStateChanged", () => this.handlers.onStateChanged?.(next, prev));
|
|
2307
|
+
}
|
|
2308
|
+
/** A failing handler never takes the socket down; the next frame wakes again and the tray keeps the cards. */
|
|
2309
|
+
guard(name, fn) {
|
|
2095
2310
|
try {
|
|
2096
|
-
|
|
2311
|
+
fn();
|
|
2097
2312
|
} catch (err) {
|
|
2098
|
-
this.
|
|
2099
|
-
new AgentChatChannelError(
|
|
2100
|
-
"validation",
|
|
2101
|
-
"malformed json frame",
|
|
2102
|
-
{ cause: err }
|
|
2103
|
-
)
|
|
2104
|
-
);
|
|
2105
|
-
return;
|
|
2313
|
+
this.logger.error({ err: describe3(err), handler: name }, "handler threw \u2014 continuing");
|
|
2106
2314
|
}
|
|
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
|
-
}
|
|
2258
|
-
}
|
|
2259
|
-
sendPing() {
|
|
2260
|
-
if (!this.ws || this.ws.readyState !== ws.WebSocket.OPEN) return;
|
|
2261
|
-
try {
|
|
2262
|
-
this.ws.ping();
|
|
2263
|
-
} catch (err) {
|
|
2264
|
-
this.emitError(
|
|
2265
|
-
new AgentChatChannelError(
|
|
2266
|
-
"retry-transient",
|
|
2267
|
-
"ws ping failed",
|
|
2268
|
-
{ cause: err }
|
|
2269
|
-
)
|
|
2270
|
-
);
|
|
2271
|
-
return;
|
|
2272
|
-
}
|
|
2273
|
-
const timeoutMs = this.config.ping.timeoutMs;
|
|
2274
|
-
if (this.pongTimer) this._clearTimeout(this.pongTimer);
|
|
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
|
-
}
|
|
2291
|
-
}
|
|
2292
|
-
// ─── Internals: reconnect ────────────────────────────────────────────
|
|
2293
|
-
scheduleReconnect(reason) {
|
|
2294
|
-
if (this.state.kind === "CLOSED" || this.state.kind === "AUTH_FAIL") return;
|
|
2295
|
-
if (this.reconnectTimer) return;
|
|
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
|
-
}
|
|
2336
|
-
}
|
|
2337
|
-
computeReconnectDelay(attempt) {
|
|
2338
|
-
const { initialBackoffMs, maxBackoffMs } = this.config.reconnect;
|
|
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
|
-
}
|
|
2394
|
-
this.state = next;
|
|
2395
|
-
if (next.kind === "CLOSED") {
|
|
2396
|
-
this.clearReconnectTimer();
|
|
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
2315
|
}
|
|
2426
2316
|
};
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
if (
|
|
2431
|
-
|
|
2432
|
-
|
|
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
|
-
};
|
|
2317
|
+
function classifyRealtimeError(error) {
|
|
2318
|
+
const message = error.message;
|
|
2319
|
+
if (/handler failed/i.test(message)) return "handler";
|
|
2320
|
+
if (/failed validation|not an object|expected a bare array/i.test(message)) return "protocol";
|
|
2321
|
+
if (error.name === "ConnectionError" || /websocket|hello|handshake|liveness|reconnecting|sync drain|sync ack/i.test(message)) return "transport";
|
|
2322
|
+
return "other";
|
|
2458
2323
|
}
|
|
2459
|
-
function
|
|
2460
|
-
return
|
|
2324
|
+
function describe3(err) {
|
|
2325
|
+
return err instanceof Error ? err.message : String(err);
|
|
2461
2326
|
}
|
|
2462
2327
|
|
|
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();
|
|
2522
|
-
}
|
|
2523
|
-
getHealth() {
|
|
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. */
|
|
2586
|
-
guard(name, fn) {
|
|
2587
|
-
try {
|
|
2588
|
-
fn();
|
|
2589
|
-
} catch (err) {
|
|
2590
|
-
this.logger.error({ err: err instanceof Error ? err.message : String(err), handler: name }, "handler threw \u2014 continuing");
|
|
2591
|
-
}
|
|
2592
|
-
}
|
|
2593
|
-
};
|
|
2594
|
-
|
|
2595
2328
|
// src/binding/runtime-registry.ts
|
|
2596
2329
|
var registry = /* @__PURE__ */ new Map();
|
|
2597
2330
|
var accountLocks = /* @__PURE__ */ new Map();
|
|
@@ -2609,62 +2342,66 @@ function withAccountLock(accountId, op) {
|
|
|
2609
2342
|
);
|
|
2610
2343
|
return next;
|
|
2611
2344
|
}
|
|
2612
|
-
function
|
|
2345
|
+
function registerIntegration(params) {
|
|
2613
2346
|
return withAccountLock(params.accountId, async () => {
|
|
2614
2347
|
const existing = registry.get(params.accountId);
|
|
2615
2348
|
if (existing) {
|
|
2616
|
-
await stopEntry(existing
|
|
2349
|
+
await stopEntry(existing);
|
|
2617
2350
|
registry.delete(params.accountId);
|
|
2618
2351
|
}
|
|
2619
|
-
let runtimeRef = null;
|
|
2620
2352
|
let built = null;
|
|
2621
2353
|
const handlers = {
|
|
2622
|
-
|
|
2354
|
+
onWake: (source, detail) => built?.handlers.onWake?.(source, detail),
|
|
2623
2355
|
onGroupInvite: (invite) => built?.handlers.onGroupInvite?.(invite),
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2356
|
+
onConnected: (at) => built?.handlers.onConnected?.(at),
|
|
2357
|
+
onDisconnected: (info) => built?.handlers.onDisconnected?.(info),
|
|
2358
|
+
onBlocked: (info) => built?.handlers.onBlocked?.(info),
|
|
2359
|
+
onError: (error) => built?.handlers.onError?.(error),
|
|
2360
|
+
onStateChanged: (next, prev) => built?.handlers.onStateChanged?.(next, prev)
|
|
2627
2361
|
};
|
|
2628
|
-
const create = params.
|
|
2629
|
-
|
|
2630
|
-
built = params.build(
|
|
2631
|
-
const entry = {
|
|
2362
|
+
const create = params.createSocket ?? ((options) => new IntegrationSocket(options));
|
|
2363
|
+
const socket = create({ config: params.config, logger: params.logger, handlers, ...params.socketOptions ?? {} });
|
|
2364
|
+
built = params.build(socket);
|
|
2365
|
+
const entry = { socket, invoker: built.invoker, texts: built.texts ?? null, config: params.config, logger: params.logger };
|
|
2632
2366
|
registry.set(params.accountId, entry);
|
|
2633
2367
|
try {
|
|
2634
|
-
|
|
2368
|
+
await socket.start();
|
|
2635
2369
|
} catch (err) {
|
|
2636
2370
|
registry.delete(params.accountId);
|
|
2637
2371
|
built.invoker?.stop();
|
|
2372
|
+
built.texts?.stop();
|
|
2638
2373
|
throw err;
|
|
2639
2374
|
}
|
|
2640
2375
|
return entry;
|
|
2641
2376
|
});
|
|
2642
2377
|
}
|
|
2643
|
-
function
|
|
2378
|
+
function unregisterIntegration(accountId) {
|
|
2644
2379
|
return withAccountLock(accountId, async () => {
|
|
2645
2380
|
const entry = registry.get(accountId);
|
|
2646
2381
|
if (!entry) return;
|
|
2647
2382
|
registry.delete(accountId);
|
|
2648
|
-
await stopEntry(entry
|
|
2383
|
+
await stopEntry(entry);
|
|
2649
2384
|
});
|
|
2650
2385
|
}
|
|
2651
|
-
async function stopEntry(entry
|
|
2386
|
+
async function stopEntry(entry) {
|
|
2652
2387
|
entry.invoker?.stop();
|
|
2388
|
+
entry.texts?.stop();
|
|
2653
2389
|
try {
|
|
2654
|
-
await entry.
|
|
2390
|
+
await entry.socket.stop();
|
|
2655
2391
|
} catch (err) {
|
|
2656
|
-
entry.logger.error({ err: err instanceof Error ? err.message : String(err) }, "
|
|
2392
|
+
entry.logger.error({ err: err instanceof Error ? err.message : String(err) }, "socket.stop threw during unregister");
|
|
2657
2393
|
}
|
|
2658
2394
|
}
|
|
2659
|
-
function
|
|
2395
|
+
function getIntegration(accountId) {
|
|
2660
2396
|
return registry.get(accountId);
|
|
2661
2397
|
}
|
|
2662
2398
|
|
|
2663
|
-
// src/
|
|
2399
|
+
// src/integration/wake.ts
|
|
2664
2400
|
var DEFAULT_DEBOUNCE_MS = 2e3;
|
|
2665
2401
|
var DEFAULT_MAX_WINDOW_MS = 6e3;
|
|
2666
|
-
var
|
|
2402
|
+
var WakeCoalescer = class {
|
|
2667
2403
|
onFire;
|
|
2404
|
+
onDelayedWake;
|
|
2668
2405
|
debounceMs;
|
|
2669
2406
|
maxWindowMs;
|
|
2670
2407
|
now;
|
|
@@ -2675,7 +2412,7 @@ var KnockCoalescer = class {
|
|
|
2675
2412
|
delayed = null;
|
|
2676
2413
|
delayedDeadline = null;
|
|
2677
2414
|
stopped = false;
|
|
2678
|
-
|
|
2415
|
+
wakes = 0;
|
|
2679
2416
|
absorbed = 0;
|
|
2680
2417
|
fires = 0;
|
|
2681
2418
|
constructor(options) {
|
|
@@ -2684,6 +2421,7 @@ var KnockCoalescer = class {
|
|
|
2684
2421
|
const maxWindow = options.maxWindowMs ?? DEFAULT_MAX_WINDOW_MS;
|
|
2685
2422
|
if (!(maxWindow >= debounce)) throw new RangeError("maxWindowMs must be >= debounceMs");
|
|
2686
2423
|
this.onFire = options.onFire;
|
|
2424
|
+
this.onDelayedWake = options.onDelayedWake;
|
|
2687
2425
|
this.debounceMs = debounce;
|
|
2688
2426
|
this.maxWindowMs = maxWindow;
|
|
2689
2427
|
this.now = options.now ?? Date.now;
|
|
@@ -2694,17 +2432,17 @@ var KnockCoalescer = class {
|
|
|
2694
2432
|
get armed() {
|
|
2695
2433
|
return this.timer !== null;
|
|
2696
2434
|
}
|
|
2697
|
-
/** True while a retry
|
|
2435
|
+
/** True while a retry wake is scheduled and has not fired. */
|
|
2698
2436
|
get delayedPending() {
|
|
2699
2437
|
return this.delayed !== null;
|
|
2700
2438
|
}
|
|
2701
2439
|
/**
|
|
2702
|
-
* A
|
|
2440
|
+
* A wake. The first one of a burst arms the window; every later one is
|
|
2703
2441
|
* absorbed and restarts it (trailing edge), never past the burst's cap.
|
|
2704
2442
|
*/
|
|
2705
|
-
|
|
2443
|
+
wake() {
|
|
2706
2444
|
if (this.stopped) return;
|
|
2707
|
-
this.
|
|
2445
|
+
this.wakes += 1;
|
|
2708
2446
|
const now = this.now();
|
|
2709
2447
|
if (this.timer === null) {
|
|
2710
2448
|
this.burstStartedAt = now;
|
|
@@ -2717,8 +2455,8 @@ var KnockCoalescer = class {
|
|
|
2717
2455
|
this._clearTimeout(this.timer);
|
|
2718
2456
|
this.timer = this._setTimeout(() => this.fire(), delay);
|
|
2719
2457
|
}
|
|
2720
|
-
/** A delayed
|
|
2721
|
-
|
|
2458
|
+
/** A delayed wake (retry ladder). The sooner pending deadline is kept. */
|
|
2459
|
+
wakeAfter(delayMs) {
|
|
2722
2460
|
if (this.stopped) return;
|
|
2723
2461
|
const delay = Math.max(0, delayMs);
|
|
2724
2462
|
const deadline = this.now() + delay;
|
|
@@ -2732,10 +2470,15 @@ var KnockCoalescer = class {
|
|
|
2732
2470
|
this.delayed = this._setTimeout(() => {
|
|
2733
2471
|
this.delayed = null;
|
|
2734
2472
|
this.delayedDeadline = null;
|
|
2735
|
-
this.
|
|
2473
|
+
if (this.stopped) return;
|
|
2474
|
+
try {
|
|
2475
|
+
this.onDelayedWake?.();
|
|
2476
|
+
} catch {
|
|
2477
|
+
}
|
|
2478
|
+
this.wake();
|
|
2736
2479
|
}, delay);
|
|
2737
2480
|
}
|
|
2738
|
-
/** Cancel everything; later
|
|
2481
|
+
/** Cancel everything; later wakes are ignored. */
|
|
2739
2482
|
stop() {
|
|
2740
2483
|
this.stopped = true;
|
|
2741
2484
|
if (this.timer !== null) {
|
|
@@ -2761,453 +2504,80 @@ var KnockCoalescer = class {
|
|
|
2761
2504
|
}
|
|
2762
2505
|
};
|
|
2763
2506
|
|
|
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;
|
|
2507
|
+
// src/integration/invoker.ts
|
|
3147
2508
|
var RETRY_LADDER_MS = [6e4, 3e5, 18e5];
|
|
3148
2509
|
var AgentInvoker = class {
|
|
3149
2510
|
accountId;
|
|
3150
2511
|
agentId;
|
|
3151
|
-
|
|
3152
|
-
|
|
3153
|
-
|
|
2512
|
+
client;
|
|
2513
|
+
callModel;
|
|
2514
|
+
startTurn;
|
|
2515
|
+
texts;
|
|
2516
|
+
invites;
|
|
3154
2517
|
logger;
|
|
2518
|
+
metrics;
|
|
3155
2519
|
gateEnabled;
|
|
3156
|
-
gateFailOpen;
|
|
3157
|
-
gateTimeoutMs;
|
|
3158
2520
|
ladder;
|
|
3159
2521
|
now;
|
|
3160
2522
|
coalescer;
|
|
3161
2523
|
cycleDue = false;
|
|
3162
2524
|
running = null;
|
|
3163
2525
|
stopped = false;
|
|
3164
|
-
|
|
3165
|
-
|
|
2526
|
+
pendingInvites = [];
|
|
2527
|
+
invitesDirty = false;
|
|
3166
2528
|
retryRung = 0;
|
|
2529
|
+
turnsInFlight = 0;
|
|
3167
2530
|
cycles = 0;
|
|
3168
2531
|
turns = 0;
|
|
3169
2532
|
inviteTurns = 0;
|
|
3170
2533
|
constructor(options) {
|
|
3171
2534
|
this.accountId = options.accountId;
|
|
3172
2535
|
this.agentId = options.agentId;
|
|
3173
|
-
this.
|
|
3174
|
-
this.
|
|
3175
|
-
this.
|
|
3176
|
-
this.
|
|
2536
|
+
this.client = options.client;
|
|
2537
|
+
this.callModel = options.callModel;
|
|
2538
|
+
this.startTurn = options.startTurn;
|
|
2539
|
+
this.texts = options.texts;
|
|
2540
|
+
this.invites = options.invites;
|
|
2541
|
+
this.logger = options.logger.child({ component: "integration", accountId: options.accountId });
|
|
2542
|
+
this.metrics = options.metrics ?? createNoopMetrics();
|
|
3177
2543
|
this.gateEnabled = options.gateEnabled ?? true;
|
|
3178
|
-
this.gateFailOpen = options.gateFailOpen ?? false;
|
|
3179
|
-
this.gateTimeoutMs = options.gateTimeoutMs ?? DEFAULT_GATE_TIMEOUT_MS;
|
|
3180
2544
|
this.ladder = options.retryLadderMs ?? RETRY_LADDER_MS;
|
|
3181
2545
|
this.now = options.now ?? Date.now;
|
|
3182
|
-
this.coalescer = new
|
|
3183
|
-
onFire: () => this.
|
|
2546
|
+
this.coalescer = new WakeCoalescer({
|
|
2547
|
+
onFire: () => this.onWakeFired(),
|
|
2548
|
+
onDelayedWake: () => {
|
|
2549
|
+
this.logger.debug({ source: "retry" }, "wake");
|
|
2550
|
+
this.metrics.incWake({ source: "retry" });
|
|
2551
|
+
},
|
|
3184
2552
|
debounceMs: options.debounceMs ?? DEFAULT_DEBOUNCE_MS,
|
|
3185
2553
|
now: this.now,
|
|
3186
2554
|
...options.setTimeout ? { setTimeout: options.setTimeout } : {},
|
|
3187
2555
|
...options.clearTimeout ? { clearTimeout: options.clearTimeout } : {}
|
|
3188
2556
|
});
|
|
3189
2557
|
}
|
|
3190
|
-
// ───
|
|
3191
|
-
/** A
|
|
3192
|
-
|
|
2558
|
+
// ─── wakes ──────────────────────────────────────────────────────────
|
|
2559
|
+
/** A wake from the socket (a frame, a connect, a reminder) or any other source. Coalesced, then cycled. */
|
|
2560
|
+
wake(source) {
|
|
3193
2561
|
if (this.stopped) return;
|
|
3194
|
-
this.logger.debug({ source }, "
|
|
3195
|
-
this.coalescer.
|
|
2562
|
+
this.logger.debug({ source }, "wake");
|
|
2563
|
+
this.coalescer.wake();
|
|
3196
2564
|
}
|
|
3197
2565
|
/**
|
|
3198
|
-
* The second
|
|
3199
|
-
*
|
|
3200
|
-
*
|
|
2566
|
+
* The second wake kind. An invite already offered (this process or an
|
|
2567
|
+
* earlier one, per the ledger) or already pending is ignored, so an
|
|
2568
|
+
* invite seen live and again on a connect-time catch-up is decided once.
|
|
2569
|
+
* Returns true when newly queued.
|
|
3201
2570
|
*/
|
|
3202
2571
|
groupInvite(invite, source) {
|
|
3203
2572
|
if (this.stopped) return false;
|
|
3204
|
-
if (this.
|
|
3205
|
-
this.
|
|
2573
|
+
if (this.invites.isOffered(invite.inviteId)) return false;
|
|
2574
|
+
if (this.pendingInvites.some((pending) => pending.inviteId === invite.inviteId)) return false;
|
|
3206
2575
|
this.logger.info(
|
|
3207
2576
|
{ groupId: invite.groupId, groupName: invite.groupName, inviter: invite.inviterHandle, inviteId: invite.inviteId, source },
|
|
3208
2577
|
"group invite \u2014 queuing one invite turn"
|
|
3209
2578
|
);
|
|
3210
|
-
this.
|
|
2579
|
+
this.pendingInvites.push(invite);
|
|
2580
|
+
this.invitesDirty = true;
|
|
3211
2581
|
this.schedule();
|
|
3212
2582
|
return true;
|
|
3213
2583
|
}
|
|
@@ -3216,7 +2586,7 @@ var AgentInvoker = class {
|
|
|
3216
2586
|
this.stopped = true;
|
|
3217
2587
|
this.coalescer.stop();
|
|
3218
2588
|
}
|
|
3219
|
-
/** The promise of the
|
|
2589
|
+
/** The promise of the work currently running, for tests and for graceful stops. */
|
|
3220
2590
|
settled() {
|
|
3221
2591
|
return this.running ?? Promise.resolve();
|
|
3222
2592
|
}
|
|
@@ -3225,14 +2595,17 @@ var AgentInvoker = class {
|
|
|
3225
2595
|
cycles: this.cycles,
|
|
3226
2596
|
turns: this.turns,
|
|
3227
2597
|
inviteTurns: this.inviteTurns,
|
|
3228
|
-
|
|
2598
|
+
turnsInFlight: this.turnsInFlight,
|
|
2599
|
+
wakes: this.coalescer.wakes,
|
|
3229
2600
|
absorbed: this.coalescer.absorbed,
|
|
3230
|
-
retryRung: this.retryRung
|
|
2601
|
+
retryRung: this.retryRung,
|
|
2602
|
+
pendingInvites: this.pendingInvites.length
|
|
3231
2603
|
};
|
|
3232
2604
|
}
|
|
3233
2605
|
// ─── worker ─────────────────────────────────────────────────────────
|
|
3234
|
-
|
|
2606
|
+
onWakeFired() {
|
|
3235
2607
|
this.cycleDue = true;
|
|
2608
|
+
if (this.pendingInvites.length > 0) this.invitesDirty = true;
|
|
3236
2609
|
this.schedule();
|
|
3237
2610
|
}
|
|
3238
2611
|
/** Run the worker if idle. One cycle at a time; work that lands mid-cycle runs afterwards. */
|
|
@@ -3240,14 +2613,14 @@ var AgentInvoker = class {
|
|
|
3240
2613
|
if (this.running) return;
|
|
3241
2614
|
this.running = this.drain().finally(() => {
|
|
3242
2615
|
this.running = null;
|
|
3243
|
-
if (!this.stopped && (this.cycleDue || this.
|
|
2616
|
+
if (!this.stopped && (this.cycleDue || this.invitesDirty)) this.schedule();
|
|
3244
2617
|
});
|
|
3245
2618
|
}
|
|
3246
2619
|
async drain() {
|
|
3247
2620
|
while (!this.stopped) {
|
|
3248
|
-
|
|
3249
|
-
|
|
3250
|
-
await this.
|
|
2621
|
+
if (this.invitesDirty) {
|
|
2622
|
+
this.invitesDirty = false;
|
|
2623
|
+
await this.runInviteTurns();
|
|
3251
2624
|
continue;
|
|
3252
2625
|
}
|
|
3253
2626
|
if (this.cycleDue) {
|
|
@@ -3255,8 +2628,7 @@ var AgentInvoker = class {
|
|
|
3255
2628
|
try {
|
|
3256
2629
|
await this.runCycle();
|
|
3257
2630
|
} catch (err) {
|
|
3258
|
-
this.logger.error({ err:
|
|
3259
|
-
this.scheduleRetry("unhandled error");
|
|
2631
|
+
this.logger.error({ err: describe4(err), ...this.retry() }, "cycle failed with an unhandled error \u2014 re-waking later");
|
|
3260
2632
|
}
|
|
3261
2633
|
continue;
|
|
3262
2634
|
}
|
|
@@ -3264,147 +2636,216 @@ var AgentInvoker = class {
|
|
|
3264
2636
|
}
|
|
3265
2637
|
}
|
|
3266
2638
|
// ─── one cycle ──────────────────────────────────────────────────────
|
|
3267
|
-
/** Read the tray, gate it, start a turn
|
|
2639
|
+
/** Read the tray, gate it, start a turn per reply. Public so tests can drive one cycle. */
|
|
3268
2640
|
async runCycle() {
|
|
3269
2641
|
this.cycles += 1;
|
|
2642
|
+
const started = this.now();
|
|
3270
2643
|
let tray;
|
|
3271
2644
|
try {
|
|
3272
|
-
tray = await this.
|
|
2645
|
+
tray = await this.client.inbox.tray({ waitMs: 0 });
|
|
3273
2646
|
} catch (err) {
|
|
3274
|
-
this.logger.warn({ err:
|
|
3275
|
-
this.
|
|
3276
|
-
return null;
|
|
2647
|
+
this.logger.warn({ err: describe4(err), ...this.retry() }, "tray read failed \u2014 re-waking later");
|
|
2648
|
+
return this.result("tray_failed", 0, false, started, describe4(err));
|
|
3277
2649
|
}
|
|
3278
|
-
const cards = cardsOf(tray);
|
|
2650
|
+
const cards = agentchatme.gate.cardsOf(tray);
|
|
3279
2651
|
const truncated = tray.truncated === true;
|
|
3280
2652
|
if (cards.length === 0) {
|
|
3281
2653
|
this.logger.info({ deferred: tray.deferred ?? 0 }, "tray empty \u2014 nothing to decide");
|
|
3282
2654
|
this.retryRung = 0;
|
|
3283
|
-
return
|
|
2655
|
+
return this.result("empty", 0, truncated, started);
|
|
2656
|
+
}
|
|
2657
|
+
const texts = await this.texts.ensure();
|
|
2658
|
+
if (!texts) {
|
|
2659
|
+
this.logger.warn({ cards: cards.length, ...this.retry() }, "served texts not available \u2014 not gating; the cards wait on the tray");
|
|
2660
|
+
return this.result("texts_missing", cards.length, truncated, started, "texts missing");
|
|
3284
2661
|
}
|
|
3285
2662
|
let result;
|
|
3286
2663
|
if (!this.gateEnabled) {
|
|
3287
|
-
this.
|
|
3288
|
-
result = emptyResult("disabled", truncated, cardIds(cards));
|
|
2664
|
+
result = await this.runUngated(cards.length, texts, truncated, started);
|
|
3289
2665
|
} else {
|
|
3290
|
-
result = await
|
|
3291
|
-
tray,
|
|
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
|
-
);
|
|
2666
|
+
result = await this.runGated(tray, cards.length, texts, truncated, started);
|
|
3315
2667
|
}
|
|
3316
|
-
if (result.
|
|
3317
|
-
this.
|
|
3318
|
-
|
|
2668
|
+
if (truncated && result.outcome !== "fail_closed") {
|
|
2669
|
+
this.logger.info({}, "tray truncated \u2014 waking again for the rest");
|
|
2670
|
+
this.coalescer.wake();
|
|
3319
2671
|
}
|
|
3320
|
-
|
|
3321
|
-
|
|
3322
|
-
|
|
3323
|
-
|
|
3324
|
-
|
|
3325
|
-
|
|
3326
|
-
|
|
3327
|
-
|
|
2672
|
+
return result;
|
|
2673
|
+
}
|
|
2674
|
+
/** Gate off: the agent judges in-turn with the hosted tools. One turn, nothing recorded here. */
|
|
2675
|
+
async runUngated(cards, texts, truncated, started) {
|
|
2676
|
+
this.logger.info({ cards }, "gate off \u2014 starting one turn with the served wake instruction");
|
|
2677
|
+
const sessionKey = wakeSessionKey(this.agentId, this.now());
|
|
2678
|
+
this.logger.info({ sessionKey }, "turn start");
|
|
2679
|
+
const admission = await this.startTurn({ sessionKey, prompt: wakeTurnPrompt(texts), lane: integrationLane(this.accountId) });
|
|
2680
|
+
if (!admission.ran) {
|
|
2681
|
+
this.logger.warn({ sessionKey, error: admission.error, ...this.retry() }, "turn not started \u2014 re-waking later");
|
|
3328
2682
|
} else {
|
|
2683
|
+
this.admitted(sessionKey, admission, "turn complete (final text discarded; the send is a hosted-tool call)");
|
|
3329
2684
|
this.retryRung = 0;
|
|
3330
2685
|
}
|
|
3331
|
-
|
|
3332
|
-
this.
|
|
3333
|
-
|
|
2686
|
+
return {
|
|
2687
|
+
...this.result("gate_off", cards, truncated, started),
|
|
2688
|
+
turnsStarted: admission.ran ? 1 : 0,
|
|
2689
|
+
turnsRefused: admission.ran ? 0 : 1
|
|
2690
|
+
};
|
|
2691
|
+
}
|
|
2692
|
+
async runGated(tray, cards, texts, truncated, started) {
|
|
2693
|
+
const decided = await agentchatme.gate.run({ tray, callModel: this.callModel, client: this.client, toolNamer: OPENCLAW_TOOL_NAMER });
|
|
2694
|
+
const latencyMs = this.now() - started;
|
|
2695
|
+
const counts = { reply: 0, dismiss: 0, defer: 0 };
|
|
2696
|
+
for (const verdict of decided.verdicts) counts[verdict.decision] += 1;
|
|
2697
|
+
if (decided.outcome === "fail_closed") {
|
|
2698
|
+
this.logger.warn({ cards, failure: decided.failure, latencyMs, ...this.retry() }, "gate failed closed \u2014 nothing recorded, no turn started");
|
|
2699
|
+
return { ...this.result("fail_closed", cards, truncated, started, decided.failure), undecided: cards, latencyMs };
|
|
3334
2700
|
}
|
|
3335
|
-
|
|
2701
|
+
if (decided.outcome === "empty") {
|
|
2702
|
+
this.retryRung = 0;
|
|
2703
|
+
return this.result("empty", cards, truncated, started);
|
|
2704
|
+
}
|
|
2705
|
+
let turnsStarted = 0;
|
|
2706
|
+
let turnsRefused = 0;
|
|
2707
|
+
let recordFailures = decided.recordFailures.length;
|
|
2708
|
+
let recorded = decided.recorded;
|
|
2709
|
+
for (const entry of decided.reply) {
|
|
2710
|
+
const sessionKey = wakeSessionKey(this.agentId, this.now());
|
|
2711
|
+
this.logger.info({ sessionKey, conversationId: entry.conversationId }, "turn start");
|
|
2712
|
+
const admission = await this.startTurn({ sessionKey, prompt: wakeTurnPrompt(texts, entry.conversationId), lane: integrationLane(this.accountId) });
|
|
2713
|
+
if (!admission.ran) {
|
|
2714
|
+
turnsRefused += 1;
|
|
2715
|
+
this.logger.warn({ sessionKey, conversationId: entry.conversationId, error: admission.error }, "turn not started \u2014 reply not recorded; the conversation stays unread");
|
|
2716
|
+
continue;
|
|
2717
|
+
}
|
|
2718
|
+
turnsStarted += 1;
|
|
2719
|
+
this.admitted(sessionKey, admission, "turn complete (final text discarded; the send is a hosted-tool call)");
|
|
2720
|
+
try {
|
|
2721
|
+
await entry.record();
|
|
2722
|
+
recorded += 1;
|
|
2723
|
+
} catch (err) {
|
|
2724
|
+
recordFailures += 1;
|
|
2725
|
+
this.logger.warn({ conversationId: entry.conversationId, err: describe4(err) }, "reply verdict not recorded \u2014 the turn runs; the conversation stays unread until it decides");
|
|
2726
|
+
}
|
|
2727
|
+
}
|
|
2728
|
+
const summary = {
|
|
2729
|
+
cards,
|
|
2730
|
+
reply: counts.reply,
|
|
2731
|
+
dismiss: counts.dismiss,
|
|
2732
|
+
defer: counts.defer,
|
|
2733
|
+
undecided: decided.undecided.length,
|
|
2734
|
+
recorded,
|
|
2735
|
+
recordFailures,
|
|
2736
|
+
turnsStarted,
|
|
2737
|
+
turnsRefused,
|
|
2738
|
+
latencyMs
|
|
2739
|
+
};
|
|
2740
|
+
if (turnsRefused > 0) {
|
|
2741
|
+
this.logger.warn({ ...summary, ...this.retry() }, "gate \u2014 some turns were refused; re-waking later");
|
|
2742
|
+
} else if (recordFailures > 0 || decided.undecided.length > 0) {
|
|
2743
|
+
this.logger.warn({ ...summary, ...this.retry() }, "gate \u2014 cards left on the tray; re-waking later");
|
|
2744
|
+
} else {
|
|
2745
|
+
this.retryRung = 0;
|
|
2746
|
+
this.logger.info(summary, "gate");
|
|
2747
|
+
}
|
|
2748
|
+
return { ...this.result("decided", cards, truncated, started), ...summary };
|
|
2749
|
+
}
|
|
2750
|
+
result(outcome, cards, truncated, started, failure = null) {
|
|
2751
|
+
return {
|
|
2752
|
+
outcome,
|
|
2753
|
+
cards,
|
|
2754
|
+
reply: 0,
|
|
2755
|
+
dismiss: 0,
|
|
2756
|
+
defer: 0,
|
|
2757
|
+
undecided: 0,
|
|
2758
|
+
recorded: 0,
|
|
2759
|
+
recordFailures: 0,
|
|
2760
|
+
turnsStarted: 0,
|
|
2761
|
+
turnsRefused: 0,
|
|
2762
|
+
truncated,
|
|
2763
|
+
latencyMs: this.now() - started,
|
|
2764
|
+
failure
|
|
2765
|
+
};
|
|
3336
2766
|
}
|
|
3337
|
-
|
|
2767
|
+
/** Arm the next rung (or report why not). Returned as log fields so every caller writes ONE line. */
|
|
2768
|
+
retry() {
|
|
3338
2769
|
if (this.coalescer.delayedPending) {
|
|
3339
|
-
|
|
3340
|
-
return;
|
|
2770
|
+
return { retry: { kind: "pending" } };
|
|
3341
2771
|
}
|
|
3342
2772
|
if (this.retryRung >= this.ladder.length) {
|
|
3343
|
-
|
|
3344
|
-
return;
|
|
2773
|
+
return { retry: { kind: "exhausted" } };
|
|
3345
2774
|
}
|
|
3346
|
-
const
|
|
2775
|
+
const delayMs = this.ladder[this.retryRung] ?? this.ladder[this.ladder.length - 1] ?? 6e4;
|
|
3347
2776
|
this.retryRung += 1;
|
|
3348
|
-
this.
|
|
3349
|
-
this.
|
|
2777
|
+
this.coalescer.wakeAfter(delayMs);
|
|
2778
|
+
return { retry: { kind: "armed", delayMs, rung: this.retryRung } };
|
|
3350
2779
|
}
|
|
3351
2780
|
// ─── turns ──────────────────────────────────────────────────────────
|
|
3352
|
-
/**
|
|
3353
|
-
|
|
3354
|
-
|
|
3355
|
-
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
|
|
3361
|
-
|
|
3362
|
-
|
|
3363
|
-
|
|
3364
|
-
|
|
3365
|
-
|
|
2781
|
+
/**
|
|
2782
|
+
* Book an admitted turn and log its end whenever it comes. The cycle moves
|
|
2783
|
+
* on at once; OpenClaw's lane keeps the runs of one account in order.
|
|
2784
|
+
*/
|
|
2785
|
+
admitted(sessionKey, admission, completeLine) {
|
|
2786
|
+
this.turns += 1;
|
|
2787
|
+
this.turnsInFlight += 1;
|
|
2788
|
+
void admission.done.then(
|
|
2789
|
+
(outcome) => {
|
|
2790
|
+
this.turnsInFlight -= 1;
|
|
2791
|
+
this.logger[outcome.error ? "warn" : "info"](
|
|
2792
|
+
{ sessionKey, runId: outcome.runId, status: outcome.status, ...outcome.error ? { error: outcome.error } : {} },
|
|
2793
|
+
completeLine
|
|
2794
|
+
);
|
|
2795
|
+
},
|
|
2796
|
+
(err) => {
|
|
2797
|
+
this.turnsInFlight -= 1;
|
|
2798
|
+
this.logger.warn({ sessionKey, runId: admission.runId, err: describe4(err) }, `${completeLine} \u2014 the wait failed`);
|
|
2799
|
+
}
|
|
3366
2800
|
);
|
|
3367
|
-
return outcome.ran;
|
|
3368
2801
|
}
|
|
3369
|
-
|
|
3370
|
-
|
|
3371
|
-
|
|
3372
|
-
|
|
3373
|
-
|
|
3374
|
-
|
|
3375
|
-
|
|
3376
|
-
|
|
3377
|
-
|
|
3378
|
-
|
|
3379
|
-
|
|
3380
|
-
|
|
2802
|
+
/**
|
|
2803
|
+
* Every pending invite gets one attempt. An invite leaves the pending list
|
|
2804
|
+
* only once its turn was admitted (and is then remembered in the ledger);
|
|
2805
|
+
* a refused one stays there for the next wake. Invites that arrive while
|
|
2806
|
+
* this runs are appended and get their pass on the next drain.
|
|
2807
|
+
*/
|
|
2808
|
+
async runInviteTurns() {
|
|
2809
|
+
const batch = [...this.pendingInvites];
|
|
2810
|
+
let texts = null;
|
|
2811
|
+
let refused = 0;
|
|
2812
|
+
let waitingForTexts = 0;
|
|
2813
|
+
for (const invite of batch) {
|
|
2814
|
+
if (this.stopped) return;
|
|
2815
|
+
texts ??= await this.texts.ensure();
|
|
2816
|
+
if (!texts) {
|
|
2817
|
+
waitingForTexts = batch.length;
|
|
2818
|
+
break;
|
|
2819
|
+
}
|
|
2820
|
+
const sessionKey = inviteSessionKey(this.agentId, invite.inviteId);
|
|
2821
|
+
this.logger.info({ sessionKey, groupId: invite.groupId, inviteId: invite.inviteId }, "group-invite turn start");
|
|
2822
|
+
let admission;
|
|
2823
|
+
try {
|
|
2824
|
+
admission = await this.startTurn({ sessionKey, prompt: inviteTurnPrompt(texts), lane: integrationLane(this.accountId) });
|
|
2825
|
+
} catch (err) {
|
|
2826
|
+
admission = { ran: false, error: describe4(err) };
|
|
2827
|
+
}
|
|
2828
|
+
if (!admission.ran) {
|
|
2829
|
+
refused += 1;
|
|
2830
|
+
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");
|
|
2831
|
+
continue;
|
|
2832
|
+
}
|
|
2833
|
+
this.inviteTurns += 1;
|
|
2834
|
+
this.invites.markOffered(invite.inviteId);
|
|
2835
|
+
this.pendingInvites = this.pendingInvites.filter((pending) => pending.inviteId !== invite.inviteId);
|
|
2836
|
+
this.admitted(sessionKey, admission, "group-invite turn complete");
|
|
2837
|
+
}
|
|
2838
|
+
if (this.stopped) return;
|
|
2839
|
+
if (waitingForTexts > 0) {
|
|
2840
|
+
this.logger.warn({ pending: waitingForTexts, ...this.retry() }, "served texts not available \u2014 invite turns wait; re-waking later");
|
|
2841
|
+
} else if (refused > 0) {
|
|
2842
|
+
this.logger.warn({ pending: refused, ...this.retry() }, "invite turns refused \u2014 re-waking later");
|
|
3381
2843
|
}
|
|
3382
2844
|
}
|
|
3383
2845
|
};
|
|
3384
|
-
function
|
|
2846
|
+
function describe4(err) {
|
|
3385
2847
|
return err instanceof Error ? err.message : String(err);
|
|
3386
2848
|
}
|
|
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
2849
|
function adaptLog(log) {
|
|
3409
2850
|
if (!log) return void 0;
|
|
3410
2851
|
const adapted = {
|
|
@@ -3420,18 +2861,6 @@ function adaptLog(log) {
|
|
|
3420
2861
|
function withLifecycle(snapshot, lifecycle) {
|
|
3421
2862
|
return Object.assign({}, snapshot, { lifecycle });
|
|
3422
2863
|
}
|
|
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
2864
|
function formatLogLine(obj, msg) {
|
|
3436
2865
|
const head = msg ?? "";
|
|
3437
2866
|
const keys = Object.keys(obj);
|
|
@@ -3462,24 +2891,30 @@ var agentchatGatewayAdapter = {
|
|
|
3462
2891
|
const config = account.config;
|
|
3463
2892
|
const logger = adaptLog(ctx.log) ?? createLogger({ level: config.observability.logLevel, redactKeys: config.observability.redactKeys });
|
|
3464
2893
|
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: true, connected: false }, "starting"));
|
|
3465
|
-
|
|
2894
|
+
const wakeMode = readEnv_js.readWakeModeFromEnv();
|
|
2895
|
+
if (wakeMode.mode === "off") {
|
|
3466
2896
|
ctx.log?.info?.(
|
|
3467
|
-
`[agentchat:${ctx.accountId}]
|
|
2897
|
+
`[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
2898
|
);
|
|
3469
2899
|
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false, linked: true, statusState: "disabled" }, "stopped"));
|
|
3470
2900
|
await waitUntilAbort(ctx.abortSignal, () => void 0);
|
|
3471
2901
|
return;
|
|
3472
2902
|
}
|
|
2903
|
+
if (readEnv_js.readLegacyReplyGateFailOpenFromEnv()) {
|
|
2904
|
+
ctx.log?.warn?.(
|
|
2905
|
+
`[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`
|
|
2906
|
+
);
|
|
2907
|
+
}
|
|
3473
2908
|
const refusal = multiAccountRefusal(ctx.cfg);
|
|
3474
2909
|
if (refusal) {
|
|
3475
|
-
ctx.log?.error?.(`[agentchat:${ctx.accountId}]
|
|
2910
|
+
ctx.log?.error?.(`[agentchat:${ctx.accountId}] integration not started \u2014 ${refusal}`);
|
|
3476
2911
|
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false, statusState: "not-linked", lastDisconnect: { at: Date.now(), error: refusal } }, "blocked"));
|
|
3477
2912
|
await waitUntilAbort(ctx.abortSignal, () => void 0);
|
|
3478
2913
|
return;
|
|
3479
2914
|
}
|
|
3480
2915
|
const channelRuntime = ctx.channelRuntime;
|
|
3481
2916
|
const { agentId, agentIdOverride } = resolveGateAgent({
|
|
3482
|
-
routedAgentId:
|
|
2917
|
+
routedAgentId: resolveIntegrationAgentId({ cfg: ctx.cfg, accountId: ctx.accountId, channelRuntime }),
|
|
3483
2918
|
ambientAgentId: openclawLayout_js.resolveOpenClawDefaultAgentId(ctx.cfg)
|
|
3484
2919
|
});
|
|
3485
2920
|
if (agentIdOverride && !readLlmAgentOverrideOptIn(ctx.cfg)) {
|
|
@@ -3487,69 +2922,91 @@ var agentchatGatewayAdapter = {
|
|
|
3487
2922
|
`[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
2923
|
);
|
|
3489
2924
|
}
|
|
3490
|
-
const
|
|
2925
|
+
const client = getClient({ accountId: ctx.accountId, config });
|
|
3491
2926
|
const gateTimeoutMs = readEnv_js.readReplyGateTimeoutMsFromEnv();
|
|
3492
|
-
|
|
2927
|
+
const texts = new TextsStore({ client, accountId: ctx.accountId, logger });
|
|
2928
|
+
const handle = config.agentHandle;
|
|
2929
|
+
if (handle) {
|
|
2930
|
+
texts.onServerCopy((copy) => {
|
|
2931
|
+
const refreshed = refreshIdentityLine(ctx.cfg, ctx.accountId, handle, copy.identity_line);
|
|
2932
|
+
if (refreshed.outcome === "updated") ctx.log?.info?.(`[agentchat:${ctx.accountId}] identity line refreshed from the served texts in ${refreshed.path}`);
|
|
2933
|
+
else if (refreshed.outcome === "failed") ctx.log?.warn?.(`[agentchat:${ctx.accountId}] identity line could not be refreshed in ${refreshed.path}: ${refreshed.detail ?? "unknown error"}`);
|
|
2934
|
+
});
|
|
2935
|
+
}
|
|
2936
|
+
await texts.start();
|
|
2937
|
+
const invites = new InviteLedger({
|
|
2938
|
+
accountId: ctx.accountId,
|
|
2939
|
+
onWriteError: (err) => ctx.log?.warn?.(`[agentchat:${ctx.accountId}] invite ledger could not be written: ${err instanceof Error ? err.message : String(err)}`)
|
|
2940
|
+
});
|
|
2941
|
+
await registerIntegration({
|
|
3493
2942
|
accountId: ctx.accountId,
|
|
3494
2943
|
config,
|
|
3495
2944
|
logger,
|
|
3496
|
-
|
|
2945
|
+
socketOptions: { client },
|
|
2946
|
+
build: (socket) => {
|
|
3497
2947
|
const invoker = new AgentInvoker({
|
|
3498
2948
|
accountId: ctx.accountId,
|
|
3499
2949
|
agentId,
|
|
3500
|
-
|
|
3501
|
-
|
|
3502
|
-
|
|
2950
|
+
client,
|
|
2951
|
+
callModel: createRuntimeModelCall({ agentIdOverride, ...gateTimeoutMs !== void 0 ? { timeoutMs: gateTimeoutMs } : {} }),
|
|
2952
|
+
startTurn: createRuntimeTurnStarter(),
|
|
2953
|
+
texts,
|
|
2954
|
+
invites,
|
|
3503
2955
|
logger,
|
|
3504
|
-
gateEnabled: readEnv_js.readReplyGateEnabledFromEnv()
|
|
3505
|
-
gateFailOpen: readEnv_js.readReplyGateFailOpenFromEnv(),
|
|
3506
|
-
...gateTimeoutMs !== void 0 ? { gateTimeoutMs } : {}
|
|
2956
|
+
gateEnabled: readEnv_js.readReplyGateEnabledFromEnv()
|
|
3507
2957
|
});
|
|
3508
|
-
let
|
|
2958
|
+
let blocked = false;
|
|
3509
2959
|
return {
|
|
3510
2960
|
invoker,
|
|
2961
|
+
texts,
|
|
3511
2962
|
handlers: {
|
|
3512
|
-
|
|
2963
|
+
onWake: (source) => invoker.wake(source),
|
|
3513
2964
|
onGroupInvite: (invite) => invoker.groupInvite(invite, "live"),
|
|
3514
|
-
|
|
3515
|
-
|
|
2965
|
+
onConnected: (at) => {
|
|
2966
|
+
if (blocked) {
|
|
2967
|
+
blocked = false;
|
|
2968
|
+
ctx.log?.info?.(`[agentchat:${ctx.accountId}] key accepted again \u2014 blocked cleared`);
|
|
2969
|
+
}
|
|
2970
|
+
ctx.log?.info?.(`[agentchat:${ctx.accountId}] connected at ${new Date(at).toISOString()} (agent ${agentId})`);
|
|
3516
2971
|
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: true, connected: true, linked: true, statusState: "linked", lastConnectedAt: at }, "ready"));
|
|
3517
|
-
void catchUpInvites(ctx.accountId,
|
|
2972
|
+
void catchUpInvites(ctx.accountId, client, invoker, logger);
|
|
2973
|
+
},
|
|
2974
|
+
onBlocked: (info) => {
|
|
2975
|
+
const close = `close ${info.code}${info.reason ? ` ${info.reason}` : ""}`;
|
|
2976
|
+
const next = info.retryInMs === null ? "no retry scheduled" : `next HELLO in about ${Math.max(1, Math.round(info.retryInMs / 6e4))} min`;
|
|
2977
|
+
if (blocked) {
|
|
2978
|
+
ctx.log?.debug?.(`[agentchat:${ctx.accountId}] still blocked (${close}; ${next})`);
|
|
2979
|
+
return;
|
|
2980
|
+
}
|
|
2981
|
+
blocked = true;
|
|
2982
|
+
ctx.log?.error?.(
|
|
2983
|
+
`[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`
|
|
2984
|
+
);
|
|
2985
|
+
ctx.setStatus(
|
|
2986
|
+
withLifecycle(
|
|
2987
|
+
{ ...ctx.getStatus(), running: false, connected: false, statusState: "not-linked", lastDisconnect: { at: Date.now(), error: `key rejected: ${close}` } },
|
|
2988
|
+
"blocked"
|
|
2989
|
+
)
|
|
2990
|
+
);
|
|
3518
2991
|
},
|
|
3519
2992
|
onError: (err) => {
|
|
3520
|
-
|
|
3521
|
-
ctx.log?.[level]?.(`[agentchat:${ctx.accountId}] runtime error: ${err.message} (class=${err.class_})`);
|
|
2993
|
+
ctx.log?.[blocked ? "debug" : "warn"]?.(`[agentchat:${ctx.accountId}] socket error: ${err.message}`);
|
|
3522
2994
|
},
|
|
3523
|
-
onStateChanged: (next) => {
|
|
3524
|
-
|
|
3525
|
-
|
|
3526
|
-
|
|
2995
|
+
onStateChanged: (next, prev) => {
|
|
2996
|
+
switch (next) {
|
|
2997
|
+
case "backoff":
|
|
2998
|
+
if (blocked) {
|
|
2999
|
+
ctx.log?.debug?.(`[agentchat:${ctx.accountId}] socket in backoff while blocked (from ${prev})`);
|
|
3000
|
+
return;
|
|
3001
|
+
}
|
|
3002
|
+
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: true, connected: false, statusState: "unstable" }, "recovering"));
|
|
3003
|
+
return;
|
|
3004
|
+
case "stopped":
|
|
3005
|
+
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false, statusState: "configured" }, "stopped"));
|
|
3006
|
+
return;
|
|
3007
|
+
default:
|
|
3527
3008
|
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
3009
|
}
|
|
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
3010
|
}
|
|
3554
3011
|
}
|
|
3555
3012
|
};
|
|
@@ -3557,20 +3014,19 @@ var agentchatGatewayAdapter = {
|
|
|
3557
3014
|
});
|
|
3558
3015
|
await waitUntilAbort(ctx.abortSignal, async () => {
|
|
3559
3016
|
try {
|
|
3560
|
-
await
|
|
3017
|
+
await unregisterIntegration(ctx.accountId);
|
|
3561
3018
|
} catch (err) {
|
|
3562
3019
|
ctx.log?.error?.(`[agentchat:${ctx.accountId}] unregister failed on abort: ${err instanceof Error ? err.message : String(err)}`);
|
|
3563
3020
|
}
|
|
3564
3021
|
});
|
|
3565
3022
|
},
|
|
3566
3023
|
async stopAccount(ctx) {
|
|
3567
|
-
await
|
|
3024
|
+
await unregisterIntegration(ctx.accountId);
|
|
3568
3025
|
ctx.setStatus(withLifecycle({ ...ctx.getStatus(), running: false, connected: false }, "stopped"));
|
|
3569
3026
|
}
|
|
3570
3027
|
};
|
|
3571
|
-
async function catchUpInvites(accountId,
|
|
3028
|
+
async function catchUpInvites(accountId, client, invoker, logger) {
|
|
3572
3029
|
try {
|
|
3573
|
-
const client = getClient({ accountId, config });
|
|
3574
3030
|
const invites = await client.listGroupInvites();
|
|
3575
3031
|
if (!Array.isArray(invites)) return;
|
|
3576
3032
|
let surfaced = 0;
|
|
@@ -3578,10 +3034,10 @@ async function catchUpInvites(accountId, config, invoker, logger) {
|
|
|
3578
3034
|
const invite = groupInviteFromRecord(row);
|
|
3579
3035
|
if (invite && invoker.groupInvite(invite, "catch-up")) surfaced += 1;
|
|
3580
3036
|
}
|
|
3581
|
-
if (surfaced > 0) logger.info({ surfaced }, "pending group invites surfaced on connect");
|
|
3037
|
+
if (surfaced > 0) logger.info({ accountId, surfaced }, "pending group invites surfaced on connect");
|
|
3582
3038
|
} catch (err) {
|
|
3583
3039
|
logger.warn(
|
|
3584
|
-
{ err: err instanceof Error ? err.message : String(err) },
|
|
3040
|
+
{ accountId, err: err instanceof Error ? err.message : String(err) },
|
|
3585
3041
|
"pending-invite catch-up failed \u2014 live invite frames are unaffected and the agent can still list invites with the hosted tools"
|
|
3586
3042
|
);
|
|
3587
3043
|
}
|
|
@@ -3616,28 +3072,30 @@ var agentchatStatusAdapter = {
|
|
|
3616
3072
|
handle: config.agentHandle ?? me.handle,
|
|
3617
3073
|
apiKey: config.apiKey,
|
|
3618
3074
|
apiBase: config.apiBase,
|
|
3075
|
+
identityLine: cachedIdentityLine(account.accountId),
|
|
3619
3076
|
agentId: resolvePlacementAgentId(cfg, account.accountId),
|
|
3620
3077
|
accountId: account.accountId
|
|
3621
3078
|
});
|
|
3622
3079
|
const enabled = account.enabled && isAgentchatAccountEnabled(cfg, account.accountId);
|
|
3623
|
-
const live =
|
|
3624
|
-
const health = live?.
|
|
3080
|
+
const live = getIntegration(account.accountId);
|
|
3081
|
+
const health = live?.socket.getHealth();
|
|
3625
3082
|
const counters = live?.invoker?.counters();
|
|
3626
|
-
const
|
|
3627
|
-
|
|
3628
|
-
|
|
3629
|
-
...
|
|
3083
|
+
const textsSource = live ? live.texts?.source ?? "missing" : void 0;
|
|
3084
|
+
const integration = {
|
|
3085
|
+
mode: readEnv_js.readWakeModeFromEnv().mode,
|
|
3086
|
+
...health ? { state: health.state } : {},
|
|
3087
|
+
...counters ? { wakes: counters.wakes, cycles: counters.cycles, turns: counters.turns } : {},
|
|
3088
|
+
...textsSource ? { texts: textsSource } : {}
|
|
3630
3089
|
};
|
|
3631
3090
|
const refusal = multiAccountRefusal(cfg);
|
|
3632
|
-
const legacyServer = health !== void 0 && health.authenticated && !health.ackNegotiated;
|
|
3633
3091
|
return {
|
|
3634
|
-
ok: enabled && me.status === "active" && mcp.ok && placement.every((c) => c.ok) && !refusal
|
|
3092
|
+
ok: enabled && me.status === "active" && mcp.ok && placement.every((c) => c.ok) && !refusal,
|
|
3635
3093
|
handle: me.handle,
|
|
3636
3094
|
status: me.status,
|
|
3637
3095
|
pausedByOwner: me.paused_by_owner ?? "none",
|
|
3638
3096
|
mcp,
|
|
3639
3097
|
placement,
|
|
3640
|
-
|
|
3098
|
+
integration,
|
|
3641
3099
|
...refusal ? { refusal } : {},
|
|
3642
3100
|
...enabled ? {} : { disabled: agentchatReenableHint(cfg, account.accountId) }
|
|
3643
3101
|
};
|
|
@@ -3660,22 +3118,21 @@ var agentchatStatusAdapter = {
|
|
|
3660
3118
|
for (const check of probe.placement ?? []) {
|
|
3661
3119
|
lines.push({ text: `${check.name}: ${check.detail}`, tone: check.ok ? "muted" : "warn" });
|
|
3662
3120
|
}
|
|
3663
|
-
if (probe.refusal) lines.push({ text: `
|
|
3664
|
-
if (probe.
|
|
3665
|
-
const d = probe.
|
|
3666
|
-
if (d.mode === "off") lines.push({ text:
|
|
3121
|
+
if (probe.refusal) lines.push({ text: `integration not started \u2014 ${probe.refusal}`, tone: "error" });
|
|
3122
|
+
if (probe.integration) {
|
|
3123
|
+
const d = probe.integration;
|
|
3124
|
+
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
3125
|
else if (d.state) {
|
|
3668
3126
|
lines.push({
|
|
3669
|
-
text: `
|
|
3670
|
-
tone: d.state === "
|
|
3127
|
+
text: `integration ${d.state} \u2014 wakes ${d.wakes ?? 0}, cycles ${d.cycles ?? 0}, turns ${d.turns ?? 0}`,
|
|
3128
|
+
tone: d.state === "ready" ? "success" : "warn"
|
|
3671
3129
|
});
|
|
3672
|
-
if (d.
|
|
3673
|
-
lines.push({
|
|
3674
|
-
|
|
3675
|
-
|
|
3676
|
-
});
|
|
3130
|
+
if (d.texts === "missing") {
|
|
3131
|
+
lines.push({ text: "served texts not available yet (AgentChat unreachable, nothing cached) \u2014 turns wait for the first copy", tone: "error" });
|
|
3132
|
+
} else if (d.texts === "cache") {
|
|
3133
|
+
lines.push({ text: "served texts from the cached copy \u2014 AgentChat was unreachable at start; refreshed when it is back", tone: "warn" });
|
|
3677
3134
|
}
|
|
3678
|
-
} else if (!probe.refusal) lines.push({ text: "
|
|
3135
|
+
} else if (!probe.refusal) lines.push({ text: "integration not running in this process", tone: "muted" });
|
|
3679
3136
|
}
|
|
3680
3137
|
return lines;
|
|
3681
3138
|
},
|
|
@@ -3690,7 +3147,7 @@ var agentchatDoctorAdapter = {
|
|
|
3690
3147
|
collectPreviewWarnings({ cfg, doctorFixCommand, env }) {
|
|
3691
3148
|
const warnings = [];
|
|
3692
3149
|
const refusal = multiAccountRefusal(cfg);
|
|
3693
|
-
if (refusal) warnings.push(`[${AGENTCHAT_CHANNEL_ID}]
|
|
3150
|
+
if (refusal) warnings.push(`[${AGENTCHAT_CHANNEL_ID}] integration will not start \u2014 ${refusal}`);
|
|
3694
3151
|
for (const accountId of listConfiguredAccountIds(cfg)) {
|
|
3695
3152
|
if (!isAgentchatAccountEnabled(cfg, accountId)) {
|
|
3696
3153
|
warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${agentchatReenableHint(cfg, accountId)}`);
|
|
@@ -3700,7 +3157,7 @@ var agentchatDoctorAdapter = {
|
|
|
3700
3157
|
const apiBase = readAgentchatConfigField(cfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
|
|
3701
3158
|
const handle = readAgentchatConfigField(cfg, accountId, "agentHandle");
|
|
3702
3159
|
const agentId = resolvePlacementAgentId(cfg, accountId);
|
|
3703
|
-
for (const check of checkPlacement({ cfg, handle, apiKey, apiBase, agentId, accountId, env })) {
|
|
3160
|
+
for (const check of checkPlacement({ cfg, handle, apiKey, apiBase, identityLine: cachedIdentityLine(accountId), agentId, accountId, env })) {
|
|
3704
3161
|
if (check.ok) continue;
|
|
3705
3162
|
const fix = check.name === "mcp" ? ` (${doctorFixCommand} adds it)` : "";
|
|
3706
3163
|
warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] ${check.name}: ${check.detail}${fix}`);
|
|
@@ -3748,9 +3205,11 @@ var agentchatDoctorAdapter = {
|
|
|
3748
3205
|
}
|
|
3749
3206
|
const handle = readAgentchatConfigField(next, accountId, "agentHandle");
|
|
3750
3207
|
if (apiKey && handle && placeIdentityLines) {
|
|
3751
|
-
const
|
|
3208
|
+
const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase }), accountId });
|
|
3209
|
+
const restored = restoreIdentityLine(next, accountId, handle, identityLine);
|
|
3752
3210
|
if (restored.outcome === "placed") changes.push(`placed the identity line for @${handle.replace(/^@/, "")} in ${restored.path}`);
|
|
3753
3211
|
else if (restored.outcome === "failed") warnings.push(`[${AGENTCHAT_CHANNEL_ID}:${accountId}] could not place the identity line for @${handle.replace(/^@/, "")}: ${restored.detail ?? "unknown error"}`);
|
|
3212
|
+
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
3213
|
}
|
|
3755
3214
|
}
|
|
3756
3215
|
for (const [apiBase, apiKey] of bases) {
|
|
@@ -3882,12 +3341,12 @@ var agentchatSetupAdapter = {
|
|
|
3882
3341
|
const apiKey = readAgentchatConfigField(withAccount, accountId, "apiKey");
|
|
3883
3342
|
if (!apiKey) return withAccount;
|
|
3884
3343
|
const apiBase = readAgentchatConfigField(withAccount, accountId, "apiBase") ?? DEFAULT_API_BASE2;
|
|
3885
|
-
return
|
|
3344
|
+
return applyIntegrationConfig(withAccount, { accountId, handle, apiKey, apiBase }).cfg;
|
|
3886
3345
|
},
|
|
3887
3346
|
/**
|
|
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".
|
|
3347
|
+
* Files only: the key into OpenClaw's state-dir `.env`, the served
|
|
3348
|
+
* identity line into the bound agent's `AGENTS.md`. Reports through
|
|
3349
|
+
* `RuntimeEnv.log`. Never throws: setup-time UX is "warn and proceed".
|
|
3891
3350
|
*/
|
|
3892
3351
|
async afterAccountConfigWritten({ cfg, accountId, input, runtime }) {
|
|
3893
3352
|
const apiKey = typeof input.token === "string" ? input.token : readAgentchatConfigField(cfg, accountId, "apiKey");
|
|
@@ -3910,7 +3369,8 @@ var agentchatSetupAdapter = {
|
|
|
3910
3369
|
}
|
|
3911
3370
|
}
|
|
3912
3371
|
try {
|
|
3913
|
-
const
|
|
3372
|
+
const identityLine = await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase }), accountId });
|
|
3373
|
+
const placed = placeIntegration({ cfg, handle, apiKey, apiBase, identityLine, accountId });
|
|
3914
3374
|
for (const line of formatPlacement(placed.steps.filter((s) => s.name !== "mcp"))) say(runtime, "log", `[agentchat:${accountId}] ${line}`);
|
|
3915
3375
|
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
3376
|
} catch (err) {
|
|
@@ -3919,11 +3379,11 @@ var agentchatSetupAdapter = {
|
|
|
3919
3379
|
}
|
|
3920
3380
|
};
|
|
3921
3381
|
function disableAccountConfig(cfg, accountId) {
|
|
3922
|
-
const stripped =
|
|
3382
|
+
const stripped = stripIntegrationConfig(cfg, accountId).cfg;
|
|
3923
3383
|
return channelPluginCommon.setAccountEnabledInConfigSection({ cfg: stripped, sectionKey: AGENTCHAT_CHANNEL_ID, accountId, enabled: false, allowTopLevel: true });
|
|
3924
3384
|
}
|
|
3925
3385
|
function deleteAccountConfig(cfg, accountId) {
|
|
3926
|
-
const stripped =
|
|
3386
|
+
const stripped = stripIntegrationConfig(cfg, accountId).cfg;
|
|
3927
3387
|
return channelPluginCommon.deleteAccountFromConfigSection({ cfg: stripped, sectionKey: AGENTCHAT_CHANNEL_ID, accountId, clearBaseFields: ["apiKey", "apiBase", "agentHandle"] });
|
|
3928
3388
|
}
|
|
3929
3389
|
function isAccountEnabled(cfg, accountId) {
|
|
@@ -3948,7 +3408,7 @@ var agentchatLifecycleAdapter = {
|
|
|
3948
3408
|
return;
|
|
3949
3409
|
}
|
|
3950
3410
|
if (!isEnabled) {
|
|
3951
|
-
for (const line of
|
|
3411
|
+
for (const line of removeIntegrationFiles(nextCfg, accountId, { clearKey: false })) say(runtime, "log", `[agentchat:${accountId}] ${line}`);
|
|
3952
3412
|
return;
|
|
3953
3413
|
}
|
|
3954
3414
|
const handle = validHandle(readAgentchatConfigField(nextCfg, accountId, "agentHandle"));
|
|
@@ -3956,12 +3416,16 @@ var agentchatLifecycleAdapter = {
|
|
|
3956
3416
|
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
3417
|
return;
|
|
3958
3418
|
}
|
|
3959
|
-
const
|
|
3419
|
+
const apiKey = readAgentchatConfigField(nextCfg, accountId, "apiKey");
|
|
3420
|
+
const apiBase = readAgentchatConfigField(nextCfg, accountId, "apiBase") ?? DEFAULT_API_BASE2;
|
|
3421
|
+
const identityLine = apiKey ? await loadIdentityLine({ client: createSdkClient({ apiKey, apiBase }), accountId }) : null;
|
|
3422
|
+
const restored = restoreIdentityLine(nextCfg, accountId, handle, identityLine);
|
|
3960
3423
|
if (restored.outcome === "placed") say(runtime, "log", `[agentchat:${accountId}] placed the identity line for @${handle} in ${restored.path}`);
|
|
3424
|
+
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
3425
|
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
3426
|
},
|
|
3963
3427
|
async onAccountRemoved({ prevCfg, accountId, runtime }) {
|
|
3964
|
-
for (const line of
|
|
3428
|
+
for (const line of removeIntegrationFiles(prevCfg, accountId, { clearKey: true })) say(runtime, "log", `[agentchat:${accountId}] ${line}`);
|
|
3965
3429
|
}
|
|
3966
3430
|
};
|
|
3967
3431
|
var agentchatPlugin = {
|
|
@@ -3973,7 +3437,7 @@ var agentchatPlugin = {
|
|
|
3973
3437
|
detailLabel: "AgentChat",
|
|
3974
3438
|
docsPath: "/channels/agentchat",
|
|
3975
3439
|
docsLabel: "agentchat",
|
|
3976
|
-
blurb: "the AgentChat
|
|
3440
|
+
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
3441
|
systemImage: "message",
|
|
3978
3442
|
markdownCapable: true,
|
|
3979
3443
|
order: 100
|
|
@@ -4065,7 +3529,7 @@ var agentchatPlugin = {
|
|
|
4065
3529
|
setup: agentchatSetupAdapter,
|
|
4066
3530
|
// ─── OpenClaw ↔ AgentChat binding ─────────────────────────────────────
|
|
4067
3531
|
//
|
|
4068
|
-
// gateway — holds the socket,
|
|
3532
|
+
// gateway — holds the socket, wakes, gates, starts turns (the integration).
|
|
4069
3533
|
// status — the doctor-style probe: key, hosted MCP reachability, placement.
|
|
4070
3534
|
// doctor — `openclaw doctor` warnings and the mcp.servers.agentchat repair.
|
|
4071
3535
|
//
|
|
@@ -4082,11 +3546,11 @@ var agentchatPlugin = {
|
|
|
4082
3546
|
var agentchatChannelEntry = channelCore.defineChannelPluginEntry({
|
|
4083
3547
|
id: AGENTCHAT_CHANNEL_ID,
|
|
4084
3548
|
name: "AgentChat",
|
|
4085
|
-
description: "The AgentChat
|
|
3549
|
+
description: "The AgentChat integration: wakes your OpenClaw agent when a peer writes on the messaging network for AI agents.",
|
|
4086
3550
|
plugin: agentchatPlugin,
|
|
4087
3551
|
// Called in every registration mode except cli-metadata and tool-discovery
|
|
4088
3552
|
// (docs.openclaw.ai/plugins/sdk-entrypoints/define-channel-plugin-entry).
|
|
4089
|
-
// The
|
|
3553
|
+
// The integration reads `runtime.llm.complete` (the gate on the agent's own
|
|
4090
3554
|
// model) and `runtime.subagent.run` (one turn, `deliver: false`) from it.
|
|
4091
3555
|
setRuntime: (runtime) => setPluginRuntime(runtime)
|
|
4092
3556
|
});
|
|
@@ -4106,33 +3570,36 @@ exports.AGENTCHAT_CHANNEL_ID = AGENTCHAT_CHANNEL_ID;
|
|
|
4106
3570
|
exports.AGENTCHAT_DEFAULT_ACCOUNT_ID = AGENTCHAT_DEFAULT_ACCOUNT_ID;
|
|
4107
3571
|
exports.AgentChatChannelError = AgentChatChannelError;
|
|
4108
3572
|
exports.AgentInvoker = AgentInvoker;
|
|
4109
|
-
exports.
|
|
4110
|
-
exports.
|
|
4111
|
-
exports.KNOCK_TURN_PROMPT = KNOCK_TURN_PROMPT;
|
|
4112
|
-
exports.KnockCoalescer = KnockCoalescer;
|
|
3573
|
+
exports.IntegrationSocket = IntegrationSocket;
|
|
3574
|
+
exports.InviteLedger = InviteLedger;
|
|
4113
3575
|
exports.MCP_SERVER_NAME = MCP_SERVER_NAME;
|
|
4114
|
-
exports.
|
|
4115
|
-
exports.
|
|
4116
|
-
exports.
|
|
3576
|
+
exports.OPENCLAW_TOOL_NAMER = OPENCLAW_TOOL_NAMER;
|
|
3577
|
+
exports.TextsStore = TextsStore;
|
|
3578
|
+
exports.WakeCoalescer = WakeCoalescer;
|
|
4117
3579
|
exports.agentchatChannelEntry = agentchatChannelEntry;
|
|
4118
3580
|
exports.agentchatPlugin = agentchatPlugin;
|
|
4119
3581
|
exports.agentchatSetupEntry = agentchatSetupEntry;
|
|
4120
3582
|
exports.agentchatSetupPlugin = agentchatPlugin;
|
|
4121
3583
|
exports.assertApiKeyValid = assertApiKeyValid;
|
|
4122
3584
|
exports.default = agentchatChannelEntry;
|
|
3585
|
+
exports.groupInviteFromRecord = groupInviteFromRecord;
|
|
4123
3586
|
exports.hasAgentChatConfiguredState = hasAgentChatConfiguredState;
|
|
4124
3587
|
exports.hostedMcpServerEntry = hostedMcpServerEntry;
|
|
4125
3588
|
exports.hostedMcpSnippet = hostedMcpSnippet;
|
|
4126
3589
|
exports.hostedMcpUrl = hostedMcpUrl;
|
|
4127
3590
|
exports.inviteTurnPrompt = inviteTurnPrompt;
|
|
4128
|
-
exports.
|
|
3591
|
+
exports.loadIdentityLine = loadIdentityLine;
|
|
3592
|
+
exports.loadTexts = loadTexts;
|
|
4129
3593
|
exports.mcpToolName = mcpToolName;
|
|
4130
3594
|
exports.parseChannelConfig = parseChannelConfig;
|
|
4131
3595
|
exports.probeHostedMcp = probeHostedMcp;
|
|
3596
|
+
exports.realtimeOptionsFor = realtimeOptionsFor;
|
|
4132
3597
|
exports.recoverAgentStart = recoverAgentStart;
|
|
4133
3598
|
exports.recoverAgentVerify = recoverAgentVerify;
|
|
4134
3599
|
exports.registerAgentStart = registerAgentStart;
|
|
4135
3600
|
exports.registerAgentVerify = registerAgentVerify;
|
|
3601
|
+
exports.spellToolsForOpenClaw = spellToolsForOpenClaw;
|
|
4136
3602
|
exports.validateApiKey = validateApiKey;
|
|
3603
|
+
exports.wakeTurnPrompt = wakeTurnPrompt;
|
|
4137
3604
|
//# sourceMappingURL=index.cjs.map
|
|
4138
3605
|
//# sourceMappingURL=index.cjs.map
|