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