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