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