agentschat-mcp 0.36.24 → 0.36.26
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 +12 -0
- package/README.md +8 -0
- package/codex/README.md +1 -1
- package/codex/app-server.ts +79 -22
- package/codex/bots-config.ts +31 -11
- package/codex/bridge.ts +123 -25
- package/codex/config.ts +128 -21
- package/codex/gui-channel.ts +66 -9
- package/codex/inbox-sync.ts +65 -12
- package/codex/loop-grants.ts +41 -11
- package/codex/manager.ts +101 -25
- package/codex/owner.ts +81 -9
- package/codex/processes.ts +51 -7
- package/codex/run.ts +70 -17
- package/codex/runtime-home.ts +41 -11
- package/codex/thread-history.ts +77 -30
- package/codex/transport.ts +122 -19
- package/connector/auth.ts +57 -5
- package/connector/backfill.ts +92 -10
- package/connector/descriptor.ts +27 -1
- package/connector/identities.ts +82 -14
- package/connector/ingest.ts +11 -2
- package/connector/normalize.ts +32 -12
- package/connector/run.ts +314 -67
- package/connector/server.ts +95 -26
- package/dist/codex-bots.js +410 -73
- package/dist/codex-bridge.js +1996 -576
- package/dist/connector.js +1286 -493
- package/dist/dsh.js +1776 -299
- package/dist/muse.js +967 -221
- package/dist/server.js +7645 -1172
- package/dsh/client.js +7 -5
- package/dsh/identity-ui/client.js +7 -5
- package/dsh/identity-ui/index.js +43 -8
- package/dsh/inbound-bridge/index.js +595 -146
- package/dsh/src/cli.ts +430 -91
- package/dsh/src/patch.ts +295 -15
- package/dsh/tests/dsh-hardening-127.test.ts +207 -0
- package/dsh/tests/dsh.test.ts +990 -3
- package/muse/scripts/ensure-muse-wakes.mjs +5 -3
- package/muse/scripts/muse-wake-receiver.mjs +4 -1
- package/muse/src/bridge.ts +54 -13
- package/muse/src/cli.ts +226 -41
- package/muse/src/client.ts +249 -34
- package/muse/src/config.ts +128 -12
- package/muse/src/policy.ts +28 -8
- package/muse/src/types.ts +1 -0
- package/muse/src/typing.ts +18 -1
- package/muse/src/wake.ts +237 -35
- package/muse/tests/bridge.test.mjs +131 -0
- package/muse/tests/client.test.mjs +327 -0
- package/muse/tests/config.test.mjs +78 -1
- package/muse/tests/hardening.test.mjs +199 -0
- package/muse/tests/hardening126.test.mjs +292 -0
- package/muse/tests/policy.test.mjs +83 -1
- package/muse/tests/wake.test.mjs +134 -6
- package/package.json +3 -3
- package/scripts/ensure-grok-wakes.mjs +93 -8
- package/scripts/example-url-wake-receiver.mjs +254 -61
- package/scripts/grok-bind-register.sh +38 -8
- package/skills/agentschat-team-lead/SKILL.md +1 -1
- package/skills/onboarding.md +14 -10
- package/src/argcheck.ts +1890 -1
- package/src/cli.mjs +98 -14
- package/src/dedup.ts +57 -8
- package/src/grok-bind.ts +160 -33
- package/src/heartbeat.ts +39 -11
- package/src/identity-guard.ts +93 -20
- package/src/identity.ts +67 -11
- package/src/mentions.ts +26 -5
- package/src/onboarding-status.ts +134 -11
- package/src/profile-selection.ts +269 -18
- package/src/profile-store.ts +222 -28
- package/src/read-cursor.ts +256 -9
- package/src/reconnect.ts +98 -2
- package/src/redact.ts +34 -15
- package/src/rest-cli.ts +713 -159
- package/src/server.ts +2487 -342
- package/src/session-bind.ts +731 -132
- package/src/session-route.ts +183 -12
- package/src/team-lead-skill.ts +3 -0
- package/src/timestamps.ts +56 -23
- package/src/tool-annotations.ts +22 -1
- package/src/wake.ts +524 -90
package/dist/connector.js
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
4
|
+
|
|
2
5
|
// connector/run.ts
|
|
3
6
|
import WS from "ws";
|
|
4
|
-
import { readFileSync as readFileSync2 } from "node:fs";
|
|
7
|
+
import { lstatSync as lstatSync2, readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
|
|
8
|
+
import { dirname as dirname2, isAbsolute as isAbsolute2, resolve as resolve2 } from "node:path";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
5
10
|
|
|
6
11
|
// connector/server.ts
|
|
12
|
+
import { createHash, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
|
|
7
13
|
import { createServer } from "node:http";
|
|
8
14
|
import { WebSocketServer, WebSocket } from "ws";
|
|
9
15
|
|
|
@@ -14,6 +20,10 @@ function hmacHex(payload, secret) {
|
|
|
14
20
|
return createHmac("sha256", secret).update(payload, "utf8").digest("hex");
|
|
15
21
|
}
|
|
16
22
|
function verifySignature(payload, sigHex, secrets) {
|
|
23
|
+
if (typeof payload !== "string" || !Array.isArray(secrets))
|
|
24
|
+
return false;
|
|
25
|
+
if (typeof sigHex !== "string" || !/^[0-9a-f]{64}$/i.test(sigHex))
|
|
26
|
+
return false;
|
|
17
27
|
let sigBuf;
|
|
18
28
|
try {
|
|
19
29
|
sigBuf = Buffer.from(sigHex, "hex");
|
|
@@ -23,8 +33,9 @@ function verifySignature(payload, sigHex, secrets) {
|
|
|
23
33
|
if (sigBuf.length === 0)
|
|
24
34
|
return false;
|
|
25
35
|
for (const secret of secrets) {
|
|
26
|
-
if (
|
|
36
|
+
if (typeof secret !== "string" || secret.length === 0 || secret.length > 8192 || DISALLOWED_TOKEN_PAYLOAD_CTRL_RE.test(secret)) {
|
|
27
37
|
continue;
|
|
38
|
+
}
|
|
28
39
|
const expected = Buffer.from(hmacHex(payload, secret), "hex");
|
|
29
40
|
if (expected.length !== sigBuf.length)
|
|
30
41
|
continue;
|
|
@@ -33,10 +44,19 @@ function verifySignature(payload, sigHex, secrets) {
|
|
|
33
44
|
}
|
|
34
45
|
return false;
|
|
35
46
|
}
|
|
47
|
+
var DISALLOWED_TOKEN_PAYLOAD_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
48
|
+
var PROTOTYPE_PAYLOAD_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
|
49
|
+
var STRICT_BASE64URL_RE = /^[A-Za-z0-9_-]+$/;
|
|
36
50
|
function verifyToken(token, secrets) {
|
|
51
|
+
if (typeof token !== "string" || token.length === 0 || token.length > 4096 || !STRICT_BASE64URL_RE.test(token) || !Array.isArray(secrets)) {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
37
54
|
let decoded;
|
|
38
55
|
try {
|
|
39
|
-
|
|
56
|
+
const rawBuf = Buffer.from(token, "base64url");
|
|
57
|
+
if (rawBuf.toString("base64url") !== token)
|
|
58
|
+
return null;
|
|
59
|
+
decoded = rawBuf.toString("utf8");
|
|
40
60
|
} catch {
|
|
41
61
|
return null;
|
|
42
62
|
}
|
|
@@ -44,10 +64,16 @@ function verifyToken(token, secrets) {
|
|
|
44
64
|
if (parts.length < 3)
|
|
45
65
|
return null;
|
|
46
66
|
const sig = parts[parts.length - 1];
|
|
47
|
-
const
|
|
48
|
-
if (
|
|
67
|
+
const expText = parts[parts.length - 2];
|
|
68
|
+
if (!/^\d+$/.test(expText))
|
|
69
|
+
return null;
|
|
70
|
+
const exp = Number(expText);
|
|
71
|
+
if (!Number.isSafeInteger(exp) || String(exp) !== expText)
|
|
49
72
|
return null;
|
|
50
73
|
const payload = parts.slice(0, -2).join(":");
|
|
74
|
+
if (DISALLOWED_TOKEN_PAYLOAD_CTRL_RE.test(payload) || PROTOTYPE_PAYLOAD_KEYS.has(payload.toLowerCase())) {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
51
77
|
if (exp !== 0 && Math.floor(Date.now() / 1000) > exp)
|
|
52
78
|
return null;
|
|
53
79
|
const signed = `${payload}:${exp}`;
|
|
@@ -61,7 +87,25 @@ function verifyUpgradeToken(token, secrets) {
|
|
|
61
87
|
var CONTRACT_VERSION = 1;
|
|
62
88
|
var AGENTSCHAT_MAX_MESSAGE_LENGTH = 4000;
|
|
63
89
|
var SUPPORTED_OPS = ["send", "typing", "get_chat_info"];
|
|
90
|
+
var DESCRIPTOR_PROTO_KEYS = new Set([
|
|
91
|
+
"prototype",
|
|
92
|
+
...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase())
|
|
93
|
+
]);
|
|
64
94
|
function buildDescriptor(overrides = {}) {
|
|
95
|
+
if (!overrides || typeof overrides !== "object" || Array.isArray(overrides) || Object.prototype.hasOwnProperty.call(overrides, "__proto__")) {
|
|
96
|
+
throw new Error("invalid descriptor overrides");
|
|
97
|
+
}
|
|
98
|
+
const keys = new Set;
|
|
99
|
+
for (const key of Object.keys(overrides)) {
|
|
100
|
+
const trimmed = key.trim();
|
|
101
|
+
if (!trimmed || DESCRIPTOR_PROTO_KEYS.has(trimmed.toLowerCase()) || keys.has(trimmed))
|
|
102
|
+
throw new Error("invalid or duplicate descriptor override key");
|
|
103
|
+
keys.add(trimmed);
|
|
104
|
+
}
|
|
105
|
+
if ([...keys].some((key) => !Object.hasOwn(overrides, key))) {
|
|
106
|
+
throw new Error("descriptor override keys must not contain surrounding whitespace");
|
|
107
|
+
}
|
|
108
|
+
const resolvedOps = Array.isArray(overrides.supported_ops) ? [...overrides.supported_ops] : [...SUPPORTED_OPS];
|
|
65
109
|
return {
|
|
66
110
|
contract_version: CONTRACT_VERSION,
|
|
67
111
|
platform: "agentschat",
|
|
@@ -75,39 +119,48 @@ function buildDescriptor(overrides = {}) {
|
|
|
75
119
|
emoji: "\uD83E\uDD16",
|
|
76
120
|
pii_safe: false,
|
|
77
121
|
platform_hint: "AgentsChat named skills are reusable instructions. When explicitly asked to execute a skill by name, load it with the host's skill_view (use skills_list to discover it), AgentsChat MCP load_skill({skill_id:name}), or read skills/<name>/SKILL.md from the installed AgentsChat MCP package in this runtime. Report a missing loader or skill; do not pretend it ran. Keep skill text out of chat and keep replies in the originating chat.",
|
|
78
|
-
|
|
79
|
-
|
|
122
|
+
...overrides,
|
|
123
|
+
supported_ops: resolvedOps
|
|
80
124
|
};
|
|
81
125
|
}
|
|
82
126
|
|
|
83
127
|
// connector/normalize.ts
|
|
84
128
|
function toWireEvent(msg, platform = "agentschat") {
|
|
85
|
-
|
|
129
|
+
if (!msg || typeof msg !== "object")
|
|
130
|
+
return null;
|
|
131
|
+
const content = typeof msg.content === "string" ? msg.content : "";
|
|
86
132
|
if (content === "__typing__")
|
|
87
133
|
return null;
|
|
88
|
-
const
|
|
134
|
+
const metadata = (value) => typeof value === "string" ? value.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, "") : undefined;
|
|
135
|
+
const chatId = metadata(msg.channel_id) ?? "";
|
|
89
136
|
if (!chatId)
|
|
90
137
|
return null;
|
|
91
|
-
const isDm =
|
|
138
|
+
const isDm = /^dm[-:]/i.test(chatId);
|
|
92
139
|
return {
|
|
93
140
|
text: content,
|
|
94
141
|
message_type: "text",
|
|
95
|
-
message_id: msg.id,
|
|
96
|
-
reply_to_message_id: msg.reply_to,
|
|
142
|
+
message_id: metadata(msg.id),
|
|
143
|
+
reply_to_message_id: metadata(msg.reply_to ?? msg.parent_id),
|
|
97
144
|
source: {
|
|
98
145
|
platform,
|
|
99
146
|
chat_id: chatId,
|
|
100
147
|
chat_type: isDm ? "dm" : "group",
|
|
101
|
-
chat_name:
|
|
102
|
-
user_id: msg.sender_id,
|
|
103
|
-
user_name: msg.sender_name ?? msg.sender_id,
|
|
148
|
+
chat_name: chatId,
|
|
149
|
+
user_id: metadata(msg.sender_id),
|
|
150
|
+
user_name: metadata(msg.sender_name ?? msg.sender_id),
|
|
104
151
|
thread_id: null
|
|
105
152
|
}
|
|
106
153
|
};
|
|
107
154
|
}
|
|
155
|
+
var LOOP_TICK_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
156
|
+
function hasOwnProto(value) {
|
|
157
|
+
return Boolean(value && typeof value === "object" && Object.prototype.hasOwnProperty.call(value, "__proto__"));
|
|
158
|
+
}
|
|
108
159
|
function serverLoopTick(msg) {
|
|
160
|
+
if (!msg || typeof msg !== "object" || hasOwnProto(msg))
|
|
161
|
+
return null;
|
|
109
162
|
const meta = msg.meta;
|
|
110
|
-
if (!meta || meta.kind !== "loop_tick" || typeof msg.id !== "string" || !msg.id || typeof msg.channel_id !== "string" || !msg.channel_id || typeof msg.sender_id !== "string" || !msg.sender_id || msg.sender_type !== "agent" || msg.content_type !== "text" || typeof msg.timestamp !== "string" || !Number.isFinite(Date.parse(msg.timestamp)) || typeof meta.loop_id !== "string" || !/^loop_[a-zA-Z0-9_-]+$/.test(meta.loop_id) || typeof meta.prompt !== "string" || !meta.prompt.trim() || meta.prompt.length > 4000 || !Number.isSafeInteger(meta.interval_ms) || meta.interval_ms < 60000 || meta.interval_ms > 86400000 || !Number.isSafeInteger(meta.next_tick_ms) || meta.next_tick_ms <= meta.interval_ms || meta.expires_at !== null || msg.content !== `(loop tick — ${meta.prompt})`)
|
|
163
|
+
if (!meta || typeof meta !== "object" || Array.isArray(meta) || hasOwnProto(meta) || meta.kind !== "loop_tick" || typeof msg.id !== "string" || !msg.id || LOOP_TICK_CTRL_RE.test(msg.id) || typeof msg.channel_id !== "string" || !msg.channel_id || LOOP_TICK_CTRL_RE.test(msg.channel_id) || typeof msg.sender_id !== "string" || !msg.sender_id || LOOP_TICK_CTRL_RE.test(msg.sender_id) || msg.sender_type !== "agent" || msg.content_type !== "text" || typeof msg.timestamp !== "string" || !Number.isFinite(Date.parse(msg.timestamp)) || typeof meta.loop_id !== "string" || !/^loop_[a-zA-Z0-9_-]+$/.test(meta.loop_id) || typeof meta.prompt !== "string" || !meta.prompt.trim() || meta.prompt.length > 4000 || !Number.isSafeInteger(meta.interval_ms) || meta.interval_ms < 60000 || meta.interval_ms > 86400000 || !Number.isSafeInteger(meta.next_tick_ms) || meta.next_tick_ms <= meta.interval_ms || meta.expires_at !== null || msg.content !== `(loop tick — ${meta.prompt})`)
|
|
111
164
|
return null;
|
|
112
165
|
return meta;
|
|
113
166
|
}
|
|
@@ -115,40 +168,70 @@ function matchesLiveLoop(msg, agentId, response) {
|
|
|
115
168
|
const tick = serverLoopTick(msg);
|
|
116
169
|
if (!tick || msg.sender_id !== agentId)
|
|
117
170
|
return false;
|
|
171
|
+
if (!response || typeof response !== "object" || Array.isArray(response) || hasOwnProto(response))
|
|
172
|
+
return false;
|
|
118
173
|
const rows = response?.loops;
|
|
119
174
|
if (!Array.isArray(rows))
|
|
120
175
|
return false;
|
|
121
|
-
const matches = rows.filter((row2) => row2
|
|
176
|
+
const matches = rows.filter((row2) => row2 && typeof row2 === "object" && !Array.isArray(row2) && !hasOwnProto(row2) && row2.loop_id === tick.loop_id);
|
|
122
177
|
if (matches.length !== 1)
|
|
123
178
|
return false;
|
|
124
179
|
const row = matches[0];
|
|
125
180
|
return row.status === "active" && row.channel_id === msg.channel_id && row.prompt === tick.prompt && row.interval_ms === tick.interval_ms && row.next_tick_ms === tick.next_tick_ms && row.expires_at === null && (row.mode === undefined || row.mode === "static") && Number.isSafeInteger(row.last_tick_at) && row.last_tick_at > 0 && row.last_tick_at + row.interval_ms === row.next_tick_ms;
|
|
126
181
|
}
|
|
127
182
|
|
|
183
|
+
// src/redact.ts
|
|
184
|
+
function redactSecrets(text, opts) {
|
|
185
|
+
if (typeof text !== "string" || !text)
|
|
186
|
+
return "";
|
|
187
|
+
const step = opts?.preserveAcKeys ? text : text.replace(/ac_[A-Za-z0-9_-]{16,}/g, "ac_***REDACTED***");
|
|
188
|
+
return step.replace(/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----[\s\S]*?(?:-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----|$)/g, "***PRIVATE_KEY_REDACTED***").replace(/mcp_(?:at|rt|code)_[A-Za-z0-9_-]{16,}/g, "mcp_***REDACTED***").replace(/agent_key_[A-Za-z0-9_-]{12,}/g, "agent_key_***REDACTED***").replace(/whsec_[A-Za-z0-9_-]{12,}/g, "whsec_***REDACTED***").replace(/\bsk-(?:proj-|ant-|live-|test-)?[A-Za-z0-9_-]{16,}/g, "sk-***REDACTED***").replace(/\brk_(?:live|test)_[A-Za-z0-9]{12,}/g, "rk_***REDACTED***").replace(/\bgh[pousr]_[A-Za-z0-9_]{16,}/g, "gh_***REDACTED***").replace(/\bgithub_pat_[A-Za-z0-9_]{16,}/g, "github_pat_***REDACTED***").replace(/\bglpat-[A-Za-z0-9_-]{12,}/g, "glpat-***REDACTED***").replace(/\bxox[baprs]-[A-Za-z0-9-]{10,}/g, "xox-***REDACTED***").replace(/\bhf_[A-Za-z0-9]{20,}/g, "hf_***REDACTED***").replace(/\bnpm_[A-Za-z0-9]{20,}/g, "npm_***REDACTED***").replace(/\bAIza[0-9A-Za-z_-]{20,}/g, "AIza***REDACTED***").replace(/(?<![A-Za-z0-9])(?:AKIA|ASIA)[0-9A-Z]{16}(?![A-Za-z0-9])/g, "AKIA***REDACTED***").replace(/eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "***JWT_REDACTED***");
|
|
189
|
+
}
|
|
190
|
+
|
|
128
191
|
// src/dedup.ts
|
|
192
|
+
var MAX_DEDUP_ID_CHARS = 256;
|
|
193
|
+
var MAX_DEDUP_KEY_CHARS = 1024;
|
|
194
|
+
var MAX_DEDUP_CAPACITY = 1e6;
|
|
195
|
+
var RESERVED_DEDUP_KEY = /^(?:__proto__|constructor|prototype)$/i;
|
|
129
196
|
function messageDedupKey(data) {
|
|
130
|
-
if (!data || typeof data.id !== "string" || typeof data.channel_id !== "string")
|
|
197
|
+
if (!data || typeof data !== "object" || Array.isArray(data) || Object.prototype.hasOwnProperty.call(data, "__proto__") || typeof data.id !== "string" || typeof data.channel_id !== "string") {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
const channelTrim = data.channel_id.trim();
|
|
201
|
+
const idTrim = data.id.trim();
|
|
202
|
+
if (!idTrim || !channelTrim || channelTrim === "." || channelTrim === ".." || idTrim === "." || idTrim === ".." || RESERVED_DEDUP_KEY.test(channelTrim) || RESERVED_DEDUP_KEY.test(idTrim) || data.id.length > MAX_DEDUP_ID_CHARS || data.channel_id.length > MAX_DEDUP_ID_CHARS || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(data.id) || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(data.channel_id)) {
|
|
131
203
|
return null;
|
|
132
|
-
|
|
204
|
+
}
|
|
205
|
+
const safeChannel = data.channel_id.replace(/\\/g, "\\\\").replace(/:/g, "\\:");
|
|
206
|
+
return `${safeChannel}:${data.id}`;
|
|
133
207
|
}
|
|
134
208
|
|
|
135
209
|
class MessageDedup {
|
|
210
|
+
seen = new Set;
|
|
136
211
|
max;
|
|
137
212
|
dropOnEvict;
|
|
138
|
-
seen = new Set;
|
|
139
213
|
constructor(max = 5000, dropOnEvict = 1000) {
|
|
140
|
-
|
|
141
|
-
|
|
214
|
+
const safeMax = Number.isFinite(max) ? Math.min(MAX_DEDUP_CAPACITY, Math.max(1, Math.floor(max))) : 5000;
|
|
215
|
+
const safeDrop = Number.isFinite(dropOnEvict) ? Math.min(safeMax, Math.max(1, Math.floor(dropOnEvict))) : Math.min(safeMax, 1000);
|
|
216
|
+
this.max = safeMax;
|
|
217
|
+
this.dropOnEvict = safeDrop;
|
|
142
218
|
}
|
|
143
219
|
recordOrSkip(key) {
|
|
220
|
+
if (typeof key !== "string" || key.length === 0 || key.length > MAX_DEDUP_KEY_CHARS || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(key)) {
|
|
221
|
+
return false;
|
|
222
|
+
}
|
|
144
223
|
if (this.seen.has(key))
|
|
145
224
|
return true;
|
|
146
225
|
this.seen.add(key);
|
|
147
226
|
if (this.seen.size > this.max) {
|
|
148
|
-
const
|
|
149
|
-
|
|
150
|
-
for (const
|
|
151
|
-
this.seen.
|
|
227
|
+
const toDrop = Math.max(this.dropOnEvict, this.seen.size - this.max);
|
|
228
|
+
let dropped = 0;
|
|
229
|
+
for (const oldest of this.seen) {
|
|
230
|
+
this.seen.delete(oldest);
|
|
231
|
+
dropped += 1;
|
|
232
|
+
if (dropped >= toDrop)
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
152
235
|
}
|
|
153
236
|
return false;
|
|
154
237
|
}
|
|
@@ -157,19 +240,64 @@ class MessageDedup {
|
|
|
157
240
|
}
|
|
158
241
|
}
|
|
159
242
|
|
|
243
|
+
// src/mentions.ts
|
|
244
|
+
var PROTOTYPE_MENTION_IDS = new Set(["__proto__", "constructor", "prototype"]);
|
|
245
|
+
|
|
160
246
|
// connector/identities.ts
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
247
|
+
var GATEWAY_PROTO_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
|
248
|
+
var IDENTITY_PROTO_KEYS = new Set([
|
|
249
|
+
"prototype",
|
|
250
|
+
...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase())
|
|
251
|
+
]);
|
|
252
|
+
var IDENTITY_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
253
|
+
function validIdentityId(value) {
|
|
254
|
+
return typeof value === "string" && value.length > 0 && value.length <= 128 && value !== "." && value !== ".." && !value.includes("..") && !/(?:%2f|%5c|%00|%2e%2e)/i.test(value) && !/[/\\\s\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value) && !IDENTITY_PROTO_KEYS.has(value.toLowerCase());
|
|
255
|
+
}
|
|
256
|
+
function validOptionalProfile(profile) {
|
|
257
|
+
if (profile === undefined)
|
|
258
|
+
return true;
|
|
259
|
+
if (typeof profile !== "string" || IDENTITY_CTRL_RE.test(profile))
|
|
260
|
+
return false;
|
|
261
|
+
const trimmed = profile.trim();
|
|
262
|
+
return trimmed.length > 0 && trimmed.length <= 128 && trimmed !== "." && !trimmed.includes("..") && !/[/\\]/.test(trimmed) && !/(?:%2f|%5c|%00|%2e%2e)/i.test(trimmed) && !IDENTITY_PROTO_KEYS.has(trimmed.toLowerCase());
|
|
263
|
+
}
|
|
264
|
+
function validateIdentities(identities, allowEmptyCredentials = false) {
|
|
265
|
+
const bots = new Set;
|
|
266
|
+
const agents = new Set;
|
|
267
|
+
for (const id of identities) {
|
|
268
|
+
if (!id || !validIdentityId(id.botId) || !validIdentityId(id.agentId)) {
|
|
269
|
+
throw new Error("invalid identity botId or agentId");
|
|
270
|
+
}
|
|
271
|
+
if ([id.token, id.gatewayId, id.secret].some((value) => typeof value !== "string" || !value.trim() && !(allowEmptyCredentials && value === ""))) {
|
|
272
|
+
throw new Error("missing identity credentials");
|
|
273
|
+
}
|
|
274
|
+
if (!allowEmptyCredentials) {
|
|
275
|
+
if (IDENTITY_CTRL_RE.test(id.gatewayId) || id.gatewayId.length > 256 || GATEWAY_PROTO_KEYS.has(id.gatewayId.trim().toLowerCase())) {
|
|
276
|
+
throw new Error("invalid identity gatewayId");
|
|
277
|
+
}
|
|
278
|
+
if (IDENTITY_CTRL_RE.test(id.token) || IDENTITY_CTRL_RE.test(id.secret)) {
|
|
279
|
+
throw new Error("invalid identity credentials");
|
|
167
280
|
}
|
|
168
|
-
this.byBot.set(id.botId, id);
|
|
169
281
|
}
|
|
282
|
+
if (!validOptionalProfile(id.profile)) {
|
|
283
|
+
throw new Error("invalid identity profile");
|
|
284
|
+
}
|
|
285
|
+
if (bots.has(id.botId.trim()) || agents.has(id.agentId.trim())) {
|
|
286
|
+
throw new Error("duplicate identity botId or agentId — ambiguous routing");
|
|
287
|
+
}
|
|
288
|
+
bots.add(id.botId.trim());
|
|
289
|
+
agents.add(id.agentId.trim());
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
class IdentityTable {
|
|
294
|
+
byBot = new Map;
|
|
295
|
+
constructor(identities, opts) {
|
|
296
|
+
validateIdentities(identities, opts?.allowEmptyCredentials === true);
|
|
297
|
+
this.install(identities);
|
|
170
298
|
}
|
|
171
299
|
forBot(botId) {
|
|
172
|
-
return this.byBot.get(botId) ?? null;
|
|
300
|
+
return validIdentityId(botId) ? this.byBot.get(botId) ?? null : null;
|
|
173
301
|
}
|
|
174
302
|
isSingle() {
|
|
175
303
|
return this.byBot.size === 1;
|
|
@@ -181,12 +309,16 @@ class IdentityTable {
|
|
|
181
309
|
return [...this.byBot.values()];
|
|
182
310
|
}
|
|
183
311
|
replace(identities) {
|
|
312
|
+
validateIdentities(identities);
|
|
313
|
+
this.install(identities);
|
|
314
|
+
}
|
|
315
|
+
install(identities) {
|
|
184
316
|
const next = new Map;
|
|
185
317
|
for (const id of identities) {
|
|
186
318
|
if (next.has(id.botId)) {
|
|
187
319
|
throw new Error(`duplicate identity botId "${id.botId}" — ambiguous routing`);
|
|
188
320
|
}
|
|
189
|
-
next.set(id.botId, id);
|
|
321
|
+
next.set(id.botId, Object.freeze({ ...id }));
|
|
190
322
|
}
|
|
191
323
|
this.byBot.clear();
|
|
192
324
|
for (const [k, v] of next)
|
|
@@ -194,7 +326,8 @@ class IdentityTable {
|
|
|
194
326
|
}
|
|
195
327
|
}
|
|
196
328
|
function requireIdentity(identities, botId) {
|
|
197
|
-
|
|
329
|
+
validateIdentities(identities);
|
|
330
|
+
const id = validIdentityId(botId) ? identities.find((id2) => id2.botId === botId) : undefined;
|
|
198
331
|
if (!id)
|
|
199
332
|
throw new Error(`unknown identity: ${botId}`);
|
|
200
333
|
return id;
|
|
@@ -206,7 +339,7 @@ function matchesExactMention(content, id) {
|
|
|
206
339
|
return new RegExp(`(?:^|[^\\p{L}\\p{N}_@-])@(?:${escaped}(?![\\p{L}\\p{N}_(-])|[^\\s@()]+\\(${escaped}\\))`, "u").test(content);
|
|
207
340
|
}
|
|
208
341
|
function routeInboundTargets(table, ctx) {
|
|
209
|
-
if (ctx.channel_id
|
|
342
|
+
if (/^dm[-:]/i.test(ctx.channel_id ?? "")) {
|
|
210
343
|
const owner = ctx.dmOwnerBotId ? table.forBot(ctx.dmOwnerBotId) : null;
|
|
211
344
|
return owner ? [owner] : [];
|
|
212
345
|
}
|
|
@@ -215,14 +348,27 @@ function routeInboundTargets(table, ctx) {
|
|
|
215
348
|
}
|
|
216
349
|
function hermesSourceProfile(id, frontedCount) {
|
|
217
350
|
const named = typeof id.profile === "string" ? id.profile.trim() : "";
|
|
218
|
-
if (named)
|
|
351
|
+
if (named && validOptionalProfile(id.profile))
|
|
219
352
|
return named;
|
|
220
|
-
if (frontedCount > 1)
|
|
353
|
+
if (frontedCount > 1 && validIdentityId(id.botId))
|
|
221
354
|
return id.botId;
|
|
222
355
|
return;
|
|
223
356
|
}
|
|
224
357
|
|
|
225
358
|
// connector/server.ts
|
|
359
|
+
var CONNECTOR_LOG_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g;
|
|
360
|
+
function safeSecretEqual(a, b) {
|
|
361
|
+
if (typeof a !== "string" || typeof b !== "string")
|
|
362
|
+
return false;
|
|
363
|
+
const da = createHash("sha256").update(a, "utf8").digest();
|
|
364
|
+
const db = createHash("sha256").update(b, "utf8").digest();
|
|
365
|
+
return timingSafeEqual2(da, db) && a.length === b.length;
|
|
366
|
+
}
|
|
367
|
+
function sanitizeConnectorLogField(value, maxLen = 128) {
|
|
368
|
+
const cleaned = redactSecrets(String(value ?? "")).replace(CONNECTOR_LOG_CTRL_RE, " ").trim().slice(0, maxLen);
|
|
369
|
+
return cleaned || "?";
|
|
370
|
+
}
|
|
371
|
+
|
|
226
372
|
class PlatformHttpError extends Error {
|
|
227
373
|
status;
|
|
228
374
|
constructor(status) {
|
|
@@ -240,14 +386,15 @@ function startConnector(config) {
|
|
|
240
386
|
const log = config.logger ?? (() => {});
|
|
241
387
|
const descriptor = buildDescriptor(config.descriptor);
|
|
242
388
|
const legacy = !config.identities || config.identities.length === 0;
|
|
243
|
-
const table = new IdentityTable(legacy ? [{ botId: "default", agentId: "default", token: "", gatewayId: "", secret: "" }] : config.identities);
|
|
389
|
+
const table = new IdentityTable(legacy ? [{ botId: "default", agentId: "default", token: "", gatewayId: "", secret: "" }] : config.identities, legacy ? { allowEmptyCredentials: true } : undefined);
|
|
244
390
|
function safeLabel(value) {
|
|
391
|
+
let scrubbed = redactSecrets(String(value ?? "")).replace(CONNECTOR_LOG_CTRL_RE, " ");
|
|
245
392
|
for (const id of table.all())
|
|
246
393
|
for (const secret of [id.token, id.secret]) {
|
|
247
394
|
if (secret)
|
|
248
|
-
|
|
395
|
+
scrubbed = scrubbed.split(secret).join("[redacted]");
|
|
249
396
|
}
|
|
250
|
-
return JSON.stringify(
|
|
397
|
+
return JSON.stringify(scrubbed.slice(0, 128));
|
|
251
398
|
}
|
|
252
399
|
const hooks = legacy ? {
|
|
253
400
|
sendMessage: (_b, chatId, content, replyTo) => config.agentschat.sendMessage(chatId, content, replyTo),
|
|
@@ -263,17 +410,23 @@ function startConnector(config) {
|
|
|
263
410
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
264
411
|
res.end(JSON.stringify({ ok: true, service: "agentschat-connector", contract_version: 1, identities: table.size }));
|
|
265
412
|
});
|
|
266
|
-
const wss = new WebSocketServer({ noServer: true });
|
|
413
|
+
const wss = new WebSocketServer({ noServer: true, maxPayload: 2 * 1024 * 1024 });
|
|
267
414
|
http.on("upgrade", (req, socket, head) => {
|
|
268
|
-
|
|
415
|
+
let pathname;
|
|
416
|
+
try {
|
|
417
|
+
pathname = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
418
|
+
} catch {
|
|
419
|
+
socket.destroy();
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
269
422
|
if (pathname !== "/relay") {
|
|
270
423
|
socket.destroy();
|
|
271
424
|
return;
|
|
272
425
|
}
|
|
273
426
|
const auth = req.headers.authorization ?? "";
|
|
274
|
-
const token = auth.startsWith("Bearer ") ? auth.slice(7).trim() : "";
|
|
427
|
+
const token = auth.length <= 8192 && auth.startsWith("Bearer ") ? auth.slice(7).trim() : "";
|
|
275
428
|
const payload = peekPayload(token);
|
|
276
|
-
const secrets = payload ? config.secrets[payload] : undefined;
|
|
429
|
+
const secrets = payload && Object.prototype.hasOwnProperty.call(config.secrets, payload) && Array.isArray(config.secrets[payload]) ? config.secrets[payload] : undefined;
|
|
277
430
|
const secret = secrets?.find((s) => verifyUpgradeToken(token, [s]) === payload);
|
|
278
431
|
const gatewayId = secret ? payload : null;
|
|
279
432
|
if (!gatewayId) {
|
|
@@ -292,18 +445,28 @@ function startConnector(config) {
|
|
|
292
445
|
sockets.add(conn);
|
|
293
446
|
log(`[connector] gateway connected: ${safeLabel(gatewayId)} (${sockets.size} total)`);
|
|
294
447
|
ws.on("message", async (data) => {
|
|
448
|
+
const bytes = Array.isArray(data) ? data.reduce((n, chunk) => n + chunk.byteLength, 0) : data.byteLength;
|
|
449
|
+
if (bytes > 2 * 1024 * 1024) {
|
|
450
|
+
ws.close(1009, "message too large");
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
295
453
|
const text = data.toString();
|
|
296
|
-
|
|
297
|
-
`))
|
|
298
|
-
|
|
299
|
-
|
|
454
|
+
const lines = text.split(`
|
|
455
|
+
`).filter((line) => line.trim());
|
|
456
|
+
if (lines.length > 128) {
|
|
457
|
+
ws.close(1009, "batch too large");
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
for (const line of lines) {
|
|
300
461
|
let frame;
|
|
301
462
|
try {
|
|
302
463
|
frame = JSON.parse(line);
|
|
464
|
+
if (frame && typeof frame === "object" && Object.prototype.hasOwnProperty.call(frame, "__proto__"))
|
|
465
|
+
continue;
|
|
303
466
|
} catch {
|
|
304
467
|
continue;
|
|
305
468
|
}
|
|
306
|
-
await handleFrame(conn, frame).catch((e) => log(`[connector] frame error: ${e}`));
|
|
469
|
+
await handleFrame(conn, frame).catch((e) => log(`[connector] frame error: ${redactSecrets(String(e))}`));
|
|
307
470
|
}
|
|
308
471
|
});
|
|
309
472
|
ws.on("close", () => {
|
|
@@ -317,7 +480,7 @@ function startConnector(config) {
|
|
|
317
480
|
if (t === "hello") {
|
|
318
481
|
const botId = String(frame.botId ?? "");
|
|
319
482
|
const identity = legacy ? table.all()[0] : table.forBot(botId);
|
|
320
|
-
const reason = frame.platform !== "agentschat" ? "unsupported_platform" : !identity ? "unknown_identity" : !legacy && (identity.gatewayId !== conn.gatewayId || identity.secret
|
|
483
|
+
const reason = frame.platform !== "agentschat" ? "unsupported_platform" : !identity ? "unknown_identity" : !legacy && (identity.gatewayId !== conn.gatewayId || !safeSecretEqual(identity.secret, conn.secret)) ? "credential_mismatch" : null;
|
|
321
484
|
const labels = `gatewayId=${safeLabel(conn.gatewayId)} platform=${safeLabel(frame.platform === "agentschat" ? "agentschat" : "(unsupported)")} botId=${safeLabel(identity ? botId : "(unknown)")}`;
|
|
322
485
|
if (reason) {
|
|
323
486
|
log(`[connector] hello rejected ${labels} reason=${reason}`);
|
|
@@ -355,15 +518,21 @@ function startConnector(config) {
|
|
|
355
518
|
if (legacy && requested && requested === conn.legacyAlias)
|
|
356
519
|
requested = "default";
|
|
357
520
|
let identity = requested && conn.fronted.has(requested) ? table.forBot(requested) : null;
|
|
358
|
-
if (identity && (!legacy && (identity.gatewayId !== conn.gatewayId || identity.secret
|
|
521
|
+
if (identity && (!legacy && (identity.gatewayId !== conn.gatewayId || !safeSecretEqual(identity.secret, conn.secret)) || frame.platform !== undefined && frame.platform !== "agentschat"))
|
|
359
522
|
identity = null;
|
|
360
523
|
if (!identity) {
|
|
361
|
-
|
|
362
|
-
|
|
524
|
+
const safeReq = sanitizeConnectorLogField(requested ?? "?", 128);
|
|
525
|
+
log(`[connector] outbound failed: no usable identity for botId=${safeReq}`);
|
|
526
|
+
return { success: false, error: `no usable identity for outbound (botId=${safeReq})` };
|
|
527
|
+
}
|
|
528
|
+
if (typeof chatId !== "string" || chatId !== chatId.trim() || chatId.length < 1 || chatId.length > 128 || /[\s\x00-\x1f\x7f-\x9f\u2028\u2029/\\]/.test(chatId) || /(?:%2f|%5c|%00|%2e%2e)/i.test(chatId) || chatId === "." || chatId.includes("..") || ["__proto__", "constructor", "prototype"].includes(chatId.toLowerCase())) {
|
|
529
|
+
return { success: false, error: "invalid chat_id" };
|
|
363
530
|
}
|
|
364
531
|
switch (op) {
|
|
365
532
|
case "send": {
|
|
366
|
-
const
|
|
533
|
+
const rawReplyTo = action.reply_to;
|
|
534
|
+
const safeReplyTo = typeof rawReplyTo === "string" && rawReplyTo.length > 0 && rawReplyTo.length <= 256 && !/[\s\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(rawReplyTo) && !["__proto__", "constructor", "prototype"].includes(rawReplyTo.toLowerCase()) ? rawReplyTo : undefined;
|
|
535
|
+
const r = await hooks.sendMessage(identity.botId, chatId, action.content ?? "", safeReplyTo);
|
|
367
536
|
return { success: true, message_id: r?.id };
|
|
368
537
|
}
|
|
369
538
|
case "typing": {
|
|
@@ -374,15 +543,20 @@ function startConnector(config) {
|
|
|
374
543
|
const info = await hooks.getChatInfo(identity.botId, chatId);
|
|
375
544
|
return info ?? {};
|
|
376
545
|
}
|
|
377
|
-
default:
|
|
378
|
-
|
|
379
|
-
|
|
546
|
+
default: {
|
|
547
|
+
const safeOp = sanitizeConnectorLogField(op, 64);
|
|
548
|
+
log(`[connector] outbound failed: unsupported op ${safeOp}`);
|
|
549
|
+
return { success: false, error: `unsupported op: ${safeOp}` };
|
|
550
|
+
}
|
|
380
551
|
}
|
|
381
552
|
}
|
|
382
553
|
function send(ws, obj) {
|
|
383
|
-
if (ws.readyState === WebSocket.OPEN)
|
|
384
|
-
|
|
554
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
555
|
+
try {
|
|
556
|
+
ws.send(JSON.stringify(obj) + `
|
|
385
557
|
`);
|
|
558
|
+
} catch {}
|
|
559
|
+
}
|
|
386
560
|
}
|
|
387
561
|
const ready = new Promise((resolve, reject) => {
|
|
388
562
|
http.once("listening", resolve);
|
|
@@ -405,7 +579,9 @@ function startConnector(config) {
|
|
|
405
579
|
http.close();
|
|
406
580
|
},
|
|
407
581
|
async injectAgentsChatMessage(msg) {
|
|
408
|
-
|
|
582
|
+
if (!msg || typeof msg !== "object")
|
|
583
|
+
return;
|
|
584
|
+
const isDm = typeof msg.channel_id === "string" && /^dm[-:]/i.test(msg.channel_id);
|
|
409
585
|
const owner = msg.__botId ?? msg.dm_owner;
|
|
410
586
|
const isTick = msg.meta?.kind === "loop_tick";
|
|
411
587
|
const tick = serverLoopTick(msg);
|
|
@@ -416,7 +592,9 @@ function startConnector(config) {
|
|
|
416
592
|
content: msg.content
|
|
417
593
|
});
|
|
418
594
|
if (!targets.length) {
|
|
419
|
-
|
|
595
|
+
const safeChan = sanitizeConnectorLogField(msg.channel_id ?? "?", 128);
|
|
596
|
+
const rawMentions = Array.isArray(msg.mentioned_ids) ? msg.mentioned_ids.slice(0, 16).map((m) => sanitizeConnectorLogField(m, 64)) : [];
|
|
597
|
+
log(`[connector] inbound unaddressed (channel=${safeChan} mentions=${JSON.stringify(rawMentions)}) — dropped`);
|
|
420
598
|
return;
|
|
421
599
|
}
|
|
422
600
|
await Promise.all(targets.map((target) => {
|
|
@@ -457,11 +635,12 @@ function startConnector(config) {
|
|
|
457
635
|
controller.abort();
|
|
458
636
|
resolve(null);
|
|
459
637
|
}, 1000);
|
|
638
|
+
timer.unref?.();
|
|
460
639
|
})
|
|
461
640
|
]);
|
|
462
641
|
if (ctx && ctx.length) {
|
|
463
642
|
baseEvent.context = ctx.slice(-10).map((c) => ({
|
|
464
|
-
text: String(c?.text ?? "").slice(0, 500),
|
|
643
|
+
text: redactSecrets(String(c?.text ?? "").slice(0, 4096)).slice(0, 500),
|
|
465
644
|
source: { user_name: c?.user_name, user_id: c?.user_id }
|
|
466
645
|
}));
|
|
467
646
|
}
|
|
@@ -472,8 +651,15 @@ function startConnector(config) {
|
|
|
472
651
|
clearTimeout(timer);
|
|
473
652
|
}
|
|
474
653
|
}
|
|
475
|
-
if (msg.timestamp && Number.isFinite(Date.parse(msg.timestamp)) && (!since || Date.parse(msg.timestamp) > Date.parse(since)))
|
|
654
|
+
if (msg.timestamp && Number.isFinite(Date.parse(msg.timestamp)) && (!since || Date.parse(msg.timestamp) > Date.parse(since))) {
|
|
655
|
+
lastAddressed.delete(key);
|
|
476
656
|
lastAddressed.set(key, msg.timestamp);
|
|
657
|
+
if (lastAddressed.size > 2000) {
|
|
658
|
+
const oldestKey = lastAddressed.keys().next().value;
|
|
659
|
+
if (oldestKey !== undefined)
|
|
660
|
+
lastAddressed.delete(oldestKey);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
477
663
|
}
|
|
478
664
|
if (tick) {
|
|
479
665
|
baseEvent.context = [...baseEvent.context ?? [], {
|
|
@@ -512,59 +698,255 @@ function startConnector(config) {
|
|
|
512
698
|
for (const conn of sockets) {
|
|
513
699
|
for (const botId of conn.fronted) {
|
|
514
700
|
const id = table.forBot(botId);
|
|
515
|
-
if (!id || id.gatewayId !== conn.gatewayId || id.secret
|
|
701
|
+
if (!id || id.gatewayId !== conn.gatewayId || !safeSecretEqual(id.secret, conn.secret))
|
|
516
702
|
conn.fronted.delete(botId);
|
|
517
703
|
}
|
|
518
704
|
}
|
|
519
705
|
for (const k of Object.keys(config.secrets))
|
|
520
706
|
delete config.secrets[k];
|
|
521
707
|
for (const id of next) {
|
|
522
|
-
(config.secrets
|
|
708
|
+
if (!Object.prototype.hasOwnProperty.call(config.secrets, id.gatewayId)) {
|
|
709
|
+
config.secrets[id.gatewayId] = [];
|
|
710
|
+
}
|
|
711
|
+
config.secrets[id.gatewayId].push(id.secret);
|
|
523
712
|
}
|
|
524
713
|
log(`[connector] identities reloaded: ${table.size}`);
|
|
525
714
|
}
|
|
526
715
|
};
|
|
527
716
|
}
|
|
528
717
|
function peekPayload(token) {
|
|
718
|
+
if (typeof token !== "string" || token.length === 0 || token.length > 4096)
|
|
719
|
+
return null;
|
|
529
720
|
try {
|
|
530
721
|
const decoded = Buffer.from(token, "base64url").toString("utf8");
|
|
531
722
|
const parts = decoded.split(":");
|
|
532
723
|
if (parts.length < 3)
|
|
533
724
|
return null;
|
|
534
|
-
|
|
725
|
+
const payload = parts.slice(0, -2).join(":");
|
|
726
|
+
return ["__proto__", "constructor", "prototype"].includes(payload.toLowerCase()) ? null : payload;
|
|
535
727
|
} catch {
|
|
536
728
|
return null;
|
|
537
729
|
}
|
|
538
730
|
}
|
|
539
731
|
|
|
540
|
-
// connector/run.ts
|
|
541
|
-
import { join } from "node:path";
|
|
542
|
-
|
|
543
|
-
// src/redact.ts
|
|
544
|
-
function redactSecrets(text, opts) {
|
|
545
|
-
const step = opts?.preserveAcKeys ? text : text.replace(/ac_[A-Za-z0-9_-]{16,}/g, "ac_***REDACTED***");
|
|
546
|
-
return step.replace(/eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "***JWT_REDACTED***");
|
|
547
|
-
}
|
|
548
|
-
|
|
549
732
|
// src/read-cursor.ts
|
|
550
|
-
import {
|
|
733
|
+
import { randomBytes } from "crypto";
|
|
734
|
+
import {
|
|
735
|
+
chmodSync,
|
|
736
|
+
copyFileSync,
|
|
737
|
+
lstatSync,
|
|
738
|
+
readFileSync,
|
|
739
|
+
realpathSync,
|
|
740
|
+
renameSync,
|
|
741
|
+
unlinkSync,
|
|
742
|
+
writeFileSync
|
|
743
|
+
} from "fs";
|
|
744
|
+
import { dirname, isAbsolute, join, parse, resolve, sep } from "path";
|
|
745
|
+
var MAX_CURSOR_BYTES = 4 * 1024 * 1024;
|
|
746
|
+
var MAX_CURSOR_ENTRIES = 50000;
|
|
747
|
+
var RESERVED_PROTO_KEY = /^(?:__proto__|constructor|prototype)$/i;
|
|
748
|
+
var tmpCounter = 0;
|
|
749
|
+
function scrubDiag(value) {
|
|
750
|
+
return redactSecrets(String(value ?? "")).replace(/\b(https?:\/\/)([^/\s@]*@)/gi, "$1[REDACTED]@").replace(/\b(?:Bearer|Basic)\s+[^\s"'<>\\]+/gi, "[REDACTED]").replace(/(?:ac_|mcp_at_|mcp_rt_|mcp_|agent_key_|sk-|rk_live_|rk_test_|whsec_|gh[pousr]_|github_pat_|glpat-|xox[baprs]-|hf_|npm_|mr_|AIza|AKIA|ASIA)[A-Za-z0-9+/=._-]{8,}/g, "[REDACTED]").replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, " ");
|
|
751
|
+
}
|
|
752
|
+
function isDarwinCanonicalRootLink(dir, st) {
|
|
753
|
+
if (process.platform !== "darwin" || dir !== "/var" && dir !== "/tmp" && dir !== "/etc" || !st.isSymbolicLink()) {
|
|
754
|
+
return false;
|
|
755
|
+
}
|
|
756
|
+
try {
|
|
757
|
+
return realpathSync(dir) === `/private${dir}` && !lstatSync("/private").isSymbolicLink() && lstatSync("/private").isDirectory() && !lstatSync(`/private${dir}`).isSymbolicLink() && lstatSync(`/private${dir}`).isDirectory();
|
|
758
|
+
} catch {
|
|
759
|
+
return false;
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
function hasSafeRawDotDotAncestors(rawDirPath) {
|
|
763
|
+
const absRaw = isAbsolute(rawDirPath) ? rawDirPath : `${process.cwd()}${sep}${rawDirPath}`;
|
|
764
|
+
const root = parse(absRaw).root;
|
|
765
|
+
const segments = absRaw.slice(root.length).split(/[\\/]+/).filter(Boolean);
|
|
766
|
+
if (!segments.includes(".."))
|
|
767
|
+
return true;
|
|
768
|
+
let cur = root;
|
|
769
|
+
for (const seg of segments) {
|
|
770
|
+
if (seg === ".")
|
|
771
|
+
continue;
|
|
772
|
+
if (seg === "..") {
|
|
773
|
+
cur = dirname(cur);
|
|
774
|
+
continue;
|
|
775
|
+
}
|
|
776
|
+
const next = join(cur, seg);
|
|
777
|
+
try {
|
|
778
|
+
const st = lstatSync(next);
|
|
779
|
+
if (st.isSymbolicLink() && !isDarwinCanonicalRootLink(next, st)) {
|
|
780
|
+
return false;
|
|
781
|
+
}
|
|
782
|
+
} catch (err) {
|
|
783
|
+
if (err?.code !== "ENOENT")
|
|
784
|
+
return false;
|
|
785
|
+
}
|
|
786
|
+
cur = next;
|
|
787
|
+
}
|
|
788
|
+
return true;
|
|
789
|
+
}
|
|
790
|
+
function hasSafeAncestorDirs(targetFile) {
|
|
791
|
+
if (typeof targetFile !== "string" || !targetFile || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(targetFile)) {
|
|
792
|
+
return false;
|
|
793
|
+
}
|
|
794
|
+
const rawParent = dirname(isAbsolute(targetFile) ? targetFile : `${process.cwd()}${sep}${targetFile}`);
|
|
795
|
+
if (!hasSafeRawDotDotAncestors(rawParent)) {
|
|
796
|
+
return false;
|
|
797
|
+
}
|
|
798
|
+
let dir = resolve(rawParent);
|
|
799
|
+
while (true) {
|
|
800
|
+
let st;
|
|
801
|
+
try {
|
|
802
|
+
st = lstatSync(dir);
|
|
803
|
+
} catch {
|
|
804
|
+
return false;
|
|
805
|
+
}
|
|
806
|
+
const isDarwinRootLink = isDarwinCanonicalRootLink(dir, st);
|
|
807
|
+
if (!isDarwinRootLink && (st.isSymbolicLink() || !st.isDirectory())) {
|
|
808
|
+
return false;
|
|
809
|
+
}
|
|
810
|
+
const parent = dirname(dir);
|
|
811
|
+
if (parent === dir)
|
|
812
|
+
break;
|
|
813
|
+
dir = parent;
|
|
814
|
+
}
|
|
815
|
+
return true;
|
|
816
|
+
}
|
|
551
817
|
function loadCursor(file, warn) {
|
|
552
818
|
try {
|
|
553
|
-
|
|
819
|
+
if (!hasSafeAncestorDirs(file)) {
|
|
820
|
+
let exists = false;
|
|
821
|
+
try {
|
|
822
|
+
lstatSync(file);
|
|
823
|
+
exists = true;
|
|
824
|
+
} catch (err) {
|
|
825
|
+
if (err?.code !== "ENOENT")
|
|
826
|
+
exists = true;
|
|
827
|
+
}
|
|
828
|
+
if (!exists)
|
|
829
|
+
return new Map;
|
|
830
|
+
throw new Error("cursor parent path must be a real directory");
|
|
831
|
+
}
|
|
832
|
+
const st = lstatSync(file);
|
|
833
|
+
if (st.isSymbolicLink() || !st.isFile()) {
|
|
834
|
+
throw new Error("cursor path must be a regular file");
|
|
835
|
+
}
|
|
836
|
+
if (st.size > MAX_CURSOR_BYTES) {
|
|
837
|
+
throw new Error(`cursor file exceeds ${MAX_CURSOR_BYTES} byte limit`);
|
|
838
|
+
}
|
|
839
|
+
const parsed = JSON.parse(readFileSync(file, "utf-8"));
|
|
840
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
841
|
+
throw new Error("cursor root must be a JSON object");
|
|
842
|
+
}
|
|
843
|
+
const entries = [];
|
|
844
|
+
for (const [k, v] of Object.entries(parsed)) {
|
|
845
|
+
if (RESERVED_PROTO_KEY.test(k))
|
|
846
|
+
continue;
|
|
847
|
+
if (typeof v !== "string") {
|
|
848
|
+
throw new Error(`cursor value for ${scrubDiag(k)} must be a string`);
|
|
849
|
+
}
|
|
850
|
+
if (!k || k.length > 256 || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(k) || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(v) || v.length > 256) {
|
|
851
|
+
throw new Error(`cursor entry for ${scrubDiag(k)} contains invalid characters or length`);
|
|
852
|
+
}
|
|
853
|
+
if (entries.length >= MAX_CURSOR_ENTRIES) {
|
|
854
|
+
throw new Error(`cursor entry count exceeds ${MAX_CURSOR_ENTRIES}`);
|
|
855
|
+
}
|
|
856
|
+
entries.push([k, v]);
|
|
857
|
+
}
|
|
858
|
+
return new Map(entries);
|
|
554
859
|
} catch (e) {
|
|
555
860
|
if (e?.code !== "ENOENT") {
|
|
556
|
-
warn(`[agentchat] WARNING: could not read ${file} — resetting that state: ${e}
|
|
861
|
+
warn(`[agentchat] WARNING: could not read ${scrubDiag(file)} — resetting that state: ${scrubDiag(e)}
|
|
557
862
|
`);
|
|
558
863
|
}
|
|
559
864
|
return new Map;
|
|
560
865
|
}
|
|
561
866
|
}
|
|
562
|
-
function persistCursor(file, cursor, warn) {
|
|
867
|
+
function persistCursor(file, cursor, warn, fsOps) {
|
|
868
|
+
try {
|
|
869
|
+
const parentStat = lstatSync(dirname(file));
|
|
870
|
+
if (parentStat.isSymbolicLink() || !parentStat.isDirectory() || !hasSafeAncestorDirs(file)) {
|
|
871
|
+
warn(`[agentchat] WARNING: failed to persist read cursor to ${scrubDiag(file)}: parent is not a real directory
|
|
872
|
+
`);
|
|
873
|
+
return false;
|
|
874
|
+
}
|
|
875
|
+
} catch (e) {
|
|
876
|
+
warn(`[agentchat] WARNING: failed to persist read cursor to ${scrubDiag(file)}: ${scrubDiag(e)}
|
|
877
|
+
`);
|
|
878
|
+
return false;
|
|
879
|
+
}
|
|
880
|
+
try {
|
|
881
|
+
const existing = lstatSync(file);
|
|
882
|
+
if (existing.isSymbolicLink() || !existing.isFile()) {
|
|
883
|
+
warn(`[agentchat] WARNING: failed to persist read cursor to ${scrubDiag(file)}: target is not a regular file
|
|
884
|
+
`);
|
|
885
|
+
return false;
|
|
886
|
+
}
|
|
887
|
+
} catch (e) {
|
|
888
|
+
if (e?.code !== "ENOENT") {
|
|
889
|
+
warn(`[agentchat] WARNING: failed to persist read cursor to ${scrubDiag(file)}: ${scrubDiag(e)}
|
|
890
|
+
`);
|
|
891
|
+
return false;
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
const validEntries = [];
|
|
895
|
+
for (const [k, v] of cursor) {
|
|
896
|
+
if (!k || k.length > 256 || RESERVED_PROTO_KEY.test(k) || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(k) || typeof v !== "string" || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(v) || v.length > 256) {
|
|
897
|
+
continue;
|
|
898
|
+
}
|
|
899
|
+
validEntries.push([k, v]);
|
|
900
|
+
}
|
|
901
|
+
const boundedEntries = validEntries.length > MAX_CURSOR_ENTRIES ? validEntries.slice(validEntries.length - MAX_CURSOR_ENTRIES) : validEntries;
|
|
902
|
+
const payloadObj = Object.create(null);
|
|
903
|
+
for (const [k, v] of boundedEntries) {
|
|
904
|
+
payloadObj[k] = v;
|
|
905
|
+
}
|
|
906
|
+
const renameFn = fsOps?.renameSync ?? renameSync;
|
|
907
|
+
const copyFn = fsOps?.copyFileSync ?? copyFileSync;
|
|
908
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.${++tmpCounter}.${randomBytes(4).toString("hex")}.tmp`;
|
|
563
909
|
try {
|
|
564
|
-
writeFileSync(
|
|
910
|
+
writeFileSync(tmp, JSON.stringify(payloadObj), { mode: 384, flag: "wx" });
|
|
911
|
+
if (process.platform !== "win32") {
|
|
912
|
+
chmodSync(tmp, 384);
|
|
913
|
+
}
|
|
914
|
+
if (!hasSafeAncestorDirs(file)) {
|
|
915
|
+
throw new Error("parent is not a real directory");
|
|
916
|
+
}
|
|
917
|
+
const current = lstatSync(file, { throwIfNoEntry: false });
|
|
918
|
+
if (current && (current.isSymbolicLink() || !current.isFile())) {
|
|
919
|
+
throw new Error("target was replaced by a symlink or non-file");
|
|
920
|
+
}
|
|
921
|
+
try {
|
|
922
|
+
renameFn(tmp, file);
|
|
923
|
+
} catch (renameErr) {
|
|
924
|
+
const code = renameErr?.code;
|
|
925
|
+
if (code === "EPERM" || code === "EACCES") {
|
|
926
|
+
if (!hasSafeAncestorDirs(file)) {
|
|
927
|
+
throw new Error("parent is not a real directory");
|
|
928
|
+
}
|
|
929
|
+
const recheck = lstatSync(file, { throwIfNoEntry: false });
|
|
930
|
+
if (recheck && (recheck.isSymbolicLink() || !recheck.isFile())) {
|
|
931
|
+
throw new Error("target was replaced by a symlink or non-file");
|
|
932
|
+
}
|
|
933
|
+
copyFn(tmp, file);
|
|
934
|
+
if (process.platform !== "win32") {
|
|
935
|
+
chmodSync(file, 384);
|
|
936
|
+
}
|
|
937
|
+
try {
|
|
938
|
+
unlinkSync(tmp);
|
|
939
|
+
} catch {}
|
|
940
|
+
return true;
|
|
941
|
+
}
|
|
942
|
+
throw renameErr;
|
|
943
|
+
}
|
|
565
944
|
return true;
|
|
566
945
|
} catch (e) {
|
|
567
|
-
|
|
946
|
+
try {
|
|
947
|
+
unlinkSync(tmp);
|
|
948
|
+
} catch {}
|
|
949
|
+
warn(`[agentchat] WARNING: failed to persist read cursor to ${scrubDiag(file)}: ${scrubDiag(e)}
|
|
568
950
|
`);
|
|
569
951
|
return false;
|
|
570
952
|
}
|
|
@@ -578,57 +960,142 @@ function flushCursor(state, persist) {
|
|
|
578
960
|
return ok;
|
|
579
961
|
}
|
|
580
962
|
|
|
963
|
+
// connector/backfill.ts
|
|
964
|
+
import { join as join2 } from "node:path";
|
|
965
|
+
|
|
581
966
|
// src/timestamps.ts
|
|
967
|
+
var ISO_OFFSET_RE = /^(\d{4}-\d{2}-\d{2})[Tt ](\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|z|[+-]\d{2}:\d{2})$/;
|
|
968
|
+
function isValidCalendarDateTime(datePart, timePart, tzPart) {
|
|
969
|
+
const year = Number(datePart.slice(0, 4));
|
|
970
|
+
const month = Number(datePart.slice(5, 7));
|
|
971
|
+
const day = Number(datePart.slice(8, 10));
|
|
972
|
+
const hour = Number(timePart.slice(0, 2));
|
|
973
|
+
const minute = Number(timePart.slice(3, 5));
|
|
974
|
+
const second = Number(timePart.slice(6, 8));
|
|
975
|
+
if (month < 1 || month > 12 || hour > 23 || minute > 59 || second > 59)
|
|
976
|
+
return false;
|
|
977
|
+
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
978
|
+
const maxDay = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
|
|
979
|
+
if (day < 1 || day > maxDay)
|
|
980
|
+
return false;
|
|
981
|
+
if (tzPart !== "Z" && tzPart !== "z") {
|
|
982
|
+
const offHour = Number(tzPart.slice(1, 3));
|
|
983
|
+
const offMin = Number(tzPart.slice(4, 6));
|
|
984
|
+
if (offHour > 23 || offMin > 59)
|
|
985
|
+
return false;
|
|
986
|
+
}
|
|
987
|
+
return true;
|
|
988
|
+
}
|
|
582
989
|
function normalizeTimestampForCursor(ts, mode) {
|
|
583
|
-
if (!ts || typeof ts !== "string")
|
|
990
|
+
if (!ts || typeof ts !== "string" || ts.length > 128)
|
|
991
|
+
return ts;
|
|
992
|
+
if (/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(ts))
|
|
993
|
+
return;
|
|
994
|
+
if (mode !== "before" && mode !== "after")
|
|
584
995
|
return ts;
|
|
585
996
|
const padChar = mode === "before" ? "9" : "0";
|
|
586
|
-
const
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
997
|
+
const trimmed = ts.trim();
|
|
998
|
+
const m = trimmed.match(ISO_OFFSET_RE);
|
|
999
|
+
if (m) {
|
|
1000
|
+
const datePart = m[1];
|
|
1001
|
+
const timePart = m[2];
|
|
1002
|
+
const rawFrac = m[3] ?? "";
|
|
1003
|
+
const tzPart = m[4];
|
|
1004
|
+
if (!isValidCalendarDateTime(datePart, timePart, tzPart))
|
|
590
1005
|
return ts;
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
1006
|
+
const frac9 = rawFrac.length === 9 ? rawFrac : rawFrac.length > 9 ? rawFrac.slice(0, 9) : rawFrac + padChar.repeat(9 - rawFrac.length);
|
|
1007
|
+
if (tzPart === "Z" || tzPart === "z") {
|
|
1008
|
+
return `${datePart}T${timePart}.${frac9}Z`;
|
|
1009
|
+
}
|
|
1010
|
+
const wholeUtcMs = Date.parse(`${datePart}T${timePart}${tzPart}`);
|
|
1011
|
+
if (Number.isFinite(wholeUtcMs)) {
|
|
1012
|
+
const iso = new Date(wholeUtcMs).toISOString();
|
|
1013
|
+
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(iso)) {
|
|
1014
|
+
return `${iso.slice(0, 19)}.${frac9}Z`;
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
596
1017
|
}
|
|
597
1018
|
return ts;
|
|
598
1019
|
}
|
|
599
1020
|
|
|
600
1021
|
// connector/backfill.ts
|
|
1022
|
+
var CANONICAL_CURSOR_TS_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{9}Z$/;
|
|
1023
|
+
var RESERVED_CURSOR_BOT_NAMES = /^(?:__proto__|constructor|prototype|con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;
|
|
1024
|
+
function canonicalCursorTimestamp(raw) {
|
|
1025
|
+
if (typeof raw !== "string" || raw.length === 0 || raw.length > 128)
|
|
1026
|
+
return null;
|
|
1027
|
+
const norm = normalizeTimestampForCursor(raw, "after");
|
|
1028
|
+
return typeof norm === "string" && CANONICAL_CURSOR_TS_RE.test(norm) ? norm : null;
|
|
1029
|
+
}
|
|
1030
|
+
function isPlainMessageRecord(m) {
|
|
1031
|
+
return Boolean(m && typeof m === "object" && !Array.isArray(m) && !Object.prototype.hasOwnProperty.call(m, "__proto__"));
|
|
1032
|
+
}
|
|
1033
|
+
function compareNormalizedTimestamps(aRaw, bRaw) {
|
|
1034
|
+
const aNorm = canonicalCursorTimestamp(aRaw) ?? "";
|
|
1035
|
+
const bNorm = canonicalCursorTimestamp(bRaw) ?? "";
|
|
1036
|
+
return aNorm < bNorm ? -1 : aNorm > bNorm ? 1 : 0;
|
|
1037
|
+
}
|
|
601
1038
|
function planBackfill(after, msgs, agentId) {
|
|
602
1039
|
const list = Array.isArray(msgs) ? msgs : [];
|
|
603
|
-
|
|
604
|
-
|
|
1040
|
+
const afterTs = canonicalCursorTimestamp(after);
|
|
1041
|
+
if (!afterTs) {
|
|
1042
|
+
let newestRaw = "";
|
|
1043
|
+
let newestNorm = "";
|
|
605
1044
|
for (const m of list) {
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
1045
|
+
if (!isPlainMessageRecord(m) || typeof m.content !== "string" || m.content === "__typing__")
|
|
1046
|
+
continue;
|
|
1047
|
+
const raw = typeof m.timestamp === "string" ? m.timestamp : "";
|
|
1048
|
+
const norm = canonicalCursorTimestamp(raw);
|
|
1049
|
+
if (!norm)
|
|
1050
|
+
continue;
|
|
1051
|
+
if (norm > newestNorm) {
|
|
1052
|
+
newestNorm = norm;
|
|
1053
|
+
newestRaw = raw;
|
|
1054
|
+
}
|
|
609
1055
|
}
|
|
610
|
-
return
|
|
1056
|
+
return newestRaw ? { seed: newestRaw, replay: [] } : { replay: [] };
|
|
611
1057
|
}
|
|
612
|
-
const afterTs = normalizeTimestampForCursor(after, "after") || after;
|
|
613
1058
|
const replay = list.filter((m) => {
|
|
614
|
-
if (!m || m.content === "__typing__")
|
|
1059
|
+
if (!isPlainMessageRecord(m) || typeof m.content !== "string" || m.content === "__typing__")
|
|
615
1060
|
return false;
|
|
616
1061
|
if (m.sender_id === agentId && !serverLoopTick(m))
|
|
617
1062
|
return false;
|
|
618
|
-
const msgTs =
|
|
619
|
-
return
|
|
1063
|
+
const msgTs = canonicalCursorTimestamp(m.timestamp);
|
|
1064
|
+
return msgTs !== null && msgTs > afterTs;
|
|
620
1065
|
});
|
|
621
|
-
replay.sort((a, b) =>
|
|
1066
|
+
replay.sort((a, b) => compareNormalizedTimestamps(a.timestamp, b.timestamp));
|
|
622
1067
|
return { replay };
|
|
623
1068
|
}
|
|
1069
|
+
function selectChannelContextMessages(msgs, sinceTs, excludeId) {
|
|
1070
|
+
const list = Array.isArray(msgs) ? msgs : [];
|
|
1071
|
+
const filtered = list.filter((m) => isPlainMessageRecord(m) && typeof m.content === "string" && m.content.length > 0 && m.content !== "__typing__" && (!excludeId || m.id !== excludeId)).sort((a, b) => compareNormalizedTimestamps(a.timestamp, b.timestamp));
|
|
1072
|
+
if (!sinceTs)
|
|
1073
|
+
return filtered.slice(-10);
|
|
1074
|
+
const normSince = canonicalCursorTimestamp(sinceTs);
|
|
1075
|
+
if (!normSince)
|
|
1076
|
+
return [];
|
|
1077
|
+
return filtered.filter((m) => {
|
|
1078
|
+
const norm = canonicalCursorTimestamp(m.timestamp);
|
|
1079
|
+
return norm !== null && norm > normSince;
|
|
1080
|
+
}).slice(-10);
|
|
1081
|
+
}
|
|
1082
|
+
function safeCursorBotFile(cursorDir, botId) {
|
|
1083
|
+
const raw = typeof botId === "string" && botId.trim() ? botId : "default";
|
|
1084
|
+
const cleaned = raw.replace(/[^A-Za-z0-9._-]/g, "_").replace(/\.+$/, "").replace(/\.{2,}/g, "_");
|
|
1085
|
+
const safeId = cleaned && !RESERVED_CURSOR_BOT_NAMES.test(cleaned) ? cleaned.slice(0, 128) : "default";
|
|
1086
|
+
return join2(cursorDir, `last-seen-msg-ts-${safeId}.json`);
|
|
1087
|
+
}
|
|
624
1088
|
|
|
625
1089
|
// connector/ingest.ts
|
|
626
1090
|
function ingestAgentsChatFrame(id, frame, deps) {
|
|
627
|
-
if (frame
|
|
1091
|
+
if (!frame || typeof frame !== "object" || Array.isArray(frame) || Object.prototype.hasOwnProperty.call(frame, "__proto__")) {
|
|
1092
|
+
return false;
|
|
1093
|
+
}
|
|
1094
|
+
if (frame.content !== "__typing__" && canonicalCursorTimestamp(frame.timestamp) !== null) {
|
|
628
1095
|
deps.advanceCursor(id, frame.channel_id, frame.timestamp);
|
|
629
1096
|
}
|
|
630
1097
|
const key = messageDedupKey(frame);
|
|
631
|
-
const isDm = frame.channel_id
|
|
1098
|
+
const isDm = typeof frame.channel_id === "string" && /^dm[-:]/i.test(frame.channel_id);
|
|
632
1099
|
const scopedKey = key && (isDm ? JSON.stringify([id.botId, frame.channel_id, frame.id]) : key);
|
|
633
1100
|
if (scopedKey && deps.dedup.recordOrSkip(scopedKey))
|
|
634
1101
|
return false;
|
|
@@ -646,18 +1113,18 @@ var WS_CLOSED = 3;
|
|
|
646
1113
|
|
|
647
1114
|
class HeartbeatMonitor {
|
|
648
1115
|
deps;
|
|
649
|
-
pingInterval;
|
|
650
|
-
pongTimeout;
|
|
651
|
-
connectTimeout;
|
|
652
1116
|
lastPong;
|
|
653
1117
|
timer = null;
|
|
654
1118
|
connectingSince = null;
|
|
655
1119
|
reconnecting = false;
|
|
1120
|
+
pingInterval;
|
|
1121
|
+
pongTimeout;
|
|
1122
|
+
connectTimeout;
|
|
656
1123
|
constructor(deps, pingInterval = 30000, pongTimeout = 90000, connectTimeout = 30000) {
|
|
657
1124
|
this.deps = deps;
|
|
658
|
-
this.pingInterval = pingInterval;
|
|
659
|
-
this.pongTimeout = pongTimeout;
|
|
660
|
-
this.connectTimeout = connectTimeout;
|
|
1125
|
+
this.pingInterval = Number.isFinite(pingInterval) && pingInterval > 0 ? Math.max(1, Math.min(Math.floor(pingInterval), 2147483647)) : 30000;
|
|
1126
|
+
this.pongTimeout = Number.isFinite(pongTimeout) && pongTimeout > 0 ? Math.max(1, Math.min(Math.floor(pongTimeout), 2147483647)) : 90000;
|
|
1127
|
+
this.connectTimeout = Number.isFinite(connectTimeout) && connectTimeout > 0 ? Math.max(1, Math.min(Math.floor(connectTimeout), 2147483647)) : 30000;
|
|
661
1128
|
this.lastPong = Date.now();
|
|
662
1129
|
}
|
|
663
1130
|
receivedPong() {
|
|
@@ -671,6 +1138,7 @@ class HeartbeatMonitor {
|
|
|
671
1138
|
this.connectingSince = null;
|
|
672
1139
|
this.reconnecting = false;
|
|
673
1140
|
this.timer = setInterval(() => this.tick(), this.pingInterval);
|
|
1141
|
+
this.timer?.unref?.();
|
|
674
1142
|
}
|
|
675
1143
|
stop() {
|
|
676
1144
|
if (this.timer) {
|
|
@@ -682,20 +1150,35 @@ class HeartbeatMonitor {
|
|
|
682
1150
|
this.reconnecting = false;
|
|
683
1151
|
}
|
|
684
1152
|
tick() {
|
|
685
|
-
|
|
1153
|
+
let state;
|
|
1154
|
+
try {
|
|
1155
|
+
state = this.deps.getReadyState();
|
|
1156
|
+
} catch {
|
|
1157
|
+
this.connectingSince = null;
|
|
1158
|
+
this.safeReconnect("readyState failed");
|
|
1159
|
+
return;
|
|
1160
|
+
}
|
|
1161
|
+
const now = Date.now();
|
|
686
1162
|
if (state === WS_OPEN) {
|
|
687
1163
|
this.connectingSince = null;
|
|
688
|
-
if (
|
|
1164
|
+
if (this.lastPong > now) {
|
|
1165
|
+
this.lastPong = now;
|
|
1166
|
+
}
|
|
1167
|
+
if (now - this.lastPong > this.pongTimeout) {
|
|
689
1168
|
this.safeReconnect("pong timeout");
|
|
690
1169
|
return;
|
|
691
1170
|
}
|
|
692
|
-
|
|
1171
|
+
try {
|
|
1172
|
+
this.deps.sendPing();
|
|
1173
|
+
} catch {
|
|
1174
|
+
this.safeReconnect("ping send failed");
|
|
1175
|
+
}
|
|
693
1176
|
return;
|
|
694
1177
|
}
|
|
695
1178
|
if (state === WS_CONNECTING) {
|
|
696
|
-
if (
|
|
697
|
-
this.connectingSince =
|
|
698
|
-
} else if (
|
|
1179
|
+
if (this.connectingSince === null || this.connectingSince > now) {
|
|
1180
|
+
this.connectingSince = now;
|
|
1181
|
+
} else if (now - this.connectingSince > this.connectTimeout) {
|
|
699
1182
|
this.connectingSince = null;
|
|
700
1183
|
this.safeReconnect("connect timeout");
|
|
701
1184
|
}
|
|
@@ -708,12 +1191,88 @@ class HeartbeatMonitor {
|
|
|
708
1191
|
if (this.reconnecting)
|
|
709
1192
|
return;
|
|
710
1193
|
this.reconnecting = true;
|
|
711
|
-
|
|
1194
|
+
try {
|
|
1195
|
+
this.deps.reconnect();
|
|
1196
|
+
} catch {
|
|
1197
|
+
this.reconnecting = false;
|
|
1198
|
+
}
|
|
712
1199
|
}
|
|
713
1200
|
}
|
|
714
1201
|
|
|
1202
|
+
// src/reconnect.ts
|
|
1203
|
+
var MAX_TIMEOUT_MS = 2147483647;
|
|
1204
|
+
function safeUnitRand(rand) {
|
|
1205
|
+
let r;
|
|
1206
|
+
try {
|
|
1207
|
+
r = rand();
|
|
1208
|
+
} catch {
|
|
1209
|
+
return 0;
|
|
1210
|
+
}
|
|
1211
|
+
if (!Number.isFinite(r) || r <= 0)
|
|
1212
|
+
return 0;
|
|
1213
|
+
return r >= 1 ? 0.999999 : r;
|
|
1214
|
+
}
|
|
1215
|
+
function computePleaseReconnectDelay(jitterMs, rand = Math.random) {
|
|
1216
|
+
const maxJitter = typeof jitterMs === "number" && Number.isFinite(jitterMs) && jitterMs > 0 ? Math.min(Math.floor(jitterMs), 1e4) : 2000;
|
|
1217
|
+
return 200 + Math.floor(safeUnitRand(rand) * maxJitter);
|
|
1218
|
+
}
|
|
1219
|
+
function resolveDrainReconnectDelay(frame, rand = Math.random) {
|
|
1220
|
+
const safeFrame = frame && typeof frame === "object" && !Array.isArray(frame) && !Object.prototype.hasOwnProperty.call(frame, "__proto__") ? frame : null;
|
|
1221
|
+
return computePleaseReconnectDelay(safeFrame?.jitter_ms ?? safeFrame?.within_ms, rand);
|
|
1222
|
+
}
|
|
1223
|
+
function withTimeoutController(parentSignal, timeoutMs) {
|
|
1224
|
+
const controller = new AbortController;
|
|
1225
|
+
let timer = null;
|
|
1226
|
+
const onParentAbort = () => {
|
|
1227
|
+
if (timer) {
|
|
1228
|
+
clearTimeout(timer);
|
|
1229
|
+
timer = null;
|
|
1230
|
+
}
|
|
1231
|
+
if (!controller.signal.aborted) {
|
|
1232
|
+
controller.abort(parentSignal?.reason);
|
|
1233
|
+
}
|
|
1234
|
+
};
|
|
1235
|
+
if (parentSignal) {
|
|
1236
|
+
if (parentSignal.aborted) {
|
|
1237
|
+
controller.abort(parentSignal.reason);
|
|
1238
|
+
return { signal: controller.signal, cleanup: () => {} };
|
|
1239
|
+
}
|
|
1240
|
+
parentSignal.addEventListener("abort", onParentAbort, { once: true });
|
|
1241
|
+
}
|
|
1242
|
+
const boundedTimeoutMs = typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.min(Math.floor(timeoutMs), MAX_TIMEOUT_MS) : 0;
|
|
1243
|
+
if (boundedTimeoutMs > 0) {
|
|
1244
|
+
timer = setTimeout(() => {
|
|
1245
|
+
timer = null;
|
|
1246
|
+
if (parentSignal)
|
|
1247
|
+
parentSignal.removeEventListener("abort", onParentAbort);
|
|
1248
|
+
const err = new Error(`HTTP request timed out after ${boundedTimeoutMs}ms`);
|
|
1249
|
+
err.name = "TimeoutError";
|
|
1250
|
+
controller.abort(err);
|
|
1251
|
+
}, boundedTimeoutMs);
|
|
1252
|
+
timer?.unref?.();
|
|
1253
|
+
}
|
|
1254
|
+
return {
|
|
1255
|
+
signal: controller.signal,
|
|
1256
|
+
cleanup: () => {
|
|
1257
|
+
if (timer) {
|
|
1258
|
+
clearTimeout(timer);
|
|
1259
|
+
timer = null;
|
|
1260
|
+
}
|
|
1261
|
+
if (parentSignal)
|
|
1262
|
+
parentSignal.removeEventListener("abort", onParentAbort);
|
|
1263
|
+
}
|
|
1264
|
+
};
|
|
1265
|
+
}
|
|
1266
|
+
|
|
715
1267
|
// connector/run.ts
|
|
716
|
-
var
|
|
1268
|
+
var CONNECTOR_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
1269
|
+
var CONNECTOR_LOG_STRIP_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g;
|
|
1270
|
+
var GATEWAY_PROTO_KEYS2 = new Set(["__proto__", "constructor", "prototype"]);
|
|
1271
|
+
var CONNECTOR_PROTO_KEYS = new Set([
|
|
1272
|
+
"prototype",
|
|
1273
|
+
...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase())
|
|
1274
|
+
]);
|
|
1275
|
+
var log = (m) => process.stderr.write(`[agentschat-connector] ${redactSecrets(m).replace(CONNECTOR_LOG_STRIP_RE, " ")}
|
|
717
1276
|
`);
|
|
718
1277
|
function need(name) {
|
|
719
1278
|
const v = process.env[name];
|
|
@@ -723,10 +1282,120 @@ function need(name) {
|
|
|
723
1282
|
}
|
|
724
1283
|
return v;
|
|
725
1284
|
}
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
1285
|
+
function isUnsafeConnectorHost(hostname) {
|
|
1286
|
+
const host = hostname.toLowerCase().replace(/\.$/, "").replace(/^\[|\]$/g, "");
|
|
1287
|
+
if (["metadata", "instance-data", "metadata.google.internal", "metadata.goog"].includes(host) || host.endsWith(".metadata.google.internal") || host.endsWith(".metadata.goog")) {
|
|
1288
|
+
return true;
|
|
1289
|
+
}
|
|
1290
|
+
const unsafeV4 = (ip) => ip === "0.0.0.0" || ip.startsWith("0.") || ip.startsWith("169.254.") || ip === "100.100.100.200";
|
|
1291
|
+
if (!host.includes(":"))
|
|
1292
|
+
return unsafeV4(host);
|
|
1293
|
+
const halves = host.split("::");
|
|
1294
|
+
const left = halves[0] ? halves[0].split(":") : [];
|
|
1295
|
+
const right = halves[1] ? halves[1].split(":") : [];
|
|
1296
|
+
const words = [...left, ...Array(Math.max(0, 8 - left.length - right.length)).fill("0"), ...right].map((v) => parseInt(v, 16));
|
|
1297
|
+
if (words.every((v) => v === 0) || (words[0] & 65472) === 65152 || host === "fd00:ec2::254")
|
|
1298
|
+
return true;
|
|
1299
|
+
if (words.slice(0, 5).every((v) => v === 0) && words[5] === 65535 || words.slice(0, 4).every((v) => v === 0) && words[4] === 65535 && words[5] === 0) {
|
|
1300
|
+
return unsafeV4(`${words[6] >>> 8}.${words[6] & 255}.${words[7] >>> 8}.${words[7] & 255}`);
|
|
1301
|
+
}
|
|
1302
|
+
return false;
|
|
1303
|
+
}
|
|
1304
|
+
function assertSafeConnectorAncestors(target, directoryLeaf = false) {
|
|
1305
|
+
const absolute = (isAbsolute2(target) ? target : `${process.cwd()}/${target}`).replace(/\/+$/, "") || "/";
|
|
1306
|
+
let dir = directoryLeaf ? absolute : dirname2(absolute);
|
|
1307
|
+
let leaf = directoryLeaf;
|
|
1308
|
+
for (;; ) {
|
|
1309
|
+
const stat = lstatSync2(dir);
|
|
1310
|
+
let systemAlias = false;
|
|
1311
|
+
if (!leaf && process.platform === "darwin" && ["/tmp", "/var", "/etc"].includes(dir) && stat.isSymbolicLink()) {
|
|
1312
|
+
const privateRoot = lstatSync2("/private");
|
|
1313
|
+
const privateDir = lstatSync2(`/private${dir}`);
|
|
1314
|
+
systemAlias = realpathSync2(dir) === `/private${dir}` && !privateRoot.isSymbolicLink() && privateRoot.isDirectory() && !privateDir.isSymbolicLink() && privateDir.isDirectory();
|
|
1315
|
+
}
|
|
1316
|
+
if (!systemAlias && (stat.isSymbolicLink() || !stat.isDirectory()))
|
|
1317
|
+
throw new Error("unsafe connector directory");
|
|
1318
|
+
const parent = dirname2(dir);
|
|
1319
|
+
if (parent === dir)
|
|
1320
|
+
return;
|
|
1321
|
+
dir = parent;
|
|
1322
|
+
leaf = false;
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
function loadConnectorCursor(file, warn) {
|
|
1326
|
+
try {
|
|
1327
|
+
assertSafeConnectorAncestors(dirname2(file), true);
|
|
1328
|
+
} catch {
|
|
1329
|
+
warn("[connector] unsafe cursor directory; cursor not loaded");
|
|
1330
|
+
return new Map;
|
|
1331
|
+
}
|
|
1332
|
+
return loadCursor(file, warn);
|
|
1333
|
+
}
|
|
1334
|
+
function persistConnectorCursor(file, map, warn) {
|
|
1335
|
+
try {
|
|
1336
|
+
assertSafeConnectorAncestors(dirname2(file), true);
|
|
1337
|
+
} catch {
|
|
1338
|
+
warn("[connector] unsafe cursor directory; cursor not persisted");
|
|
1339
|
+
return false;
|
|
1340
|
+
}
|
|
1341
|
+
return persistCursor(file, map, warn);
|
|
1342
|
+
}
|
|
1343
|
+
function readConnectorConfig(env = process.env) {
|
|
1344
|
+
const API = (env.AGENTCHAT_API_URL || "https://agents-chat.com").replace(/\/$/, "");
|
|
1345
|
+
const WS_URL = env.AGENTCHAT_WS_URL || API.replace(/^http/, "ws") + "/ws";
|
|
1346
|
+
const PORT = Number(env.RELAY_PORT || 8765);
|
|
1347
|
+
if (!Number.isInteger(PORT) || PORT < 0 || PORT > 65535)
|
|
1348
|
+
throw new Error("invalid RELAY_PORT");
|
|
1349
|
+
for (const [name, raw, protocols] of [
|
|
1350
|
+
["AGENTCHAT_API_URL", API, ["http:", "https:"]],
|
|
1351
|
+
["AGENTCHAT_WS_URL", WS_URL, ["ws:", "wss:"]]
|
|
1352
|
+
]) {
|
|
1353
|
+
if (CONNECTOR_CTRL_RE.test(raw))
|
|
1354
|
+
throw new Error(`invalid ${name}`);
|
|
1355
|
+
let url;
|
|
1356
|
+
try {
|
|
1357
|
+
url = new URL(raw);
|
|
1358
|
+
} catch {
|
|
1359
|
+
throw new Error(`invalid ${name}`);
|
|
1360
|
+
}
|
|
1361
|
+
const loopback = ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);
|
|
1362
|
+
if (!protocols.includes(url.protocol) || url.username || url.password || url.port === "0" || isUnsafeConnectorHost(url.hostname) || name === "AGENTCHAT_API_URL" && (url.search || url.hash || raw.includes("?") || raw.includes("#")) || (url.protocol === "http:" || url.protocol === "ws:") && !loopback && env.AGENTSCHAT_ALLOW_INSECURE_HTTP !== "1") {
|
|
1363
|
+
throw new Error(`invalid ${name}`);
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
return { API, WS_URL, PORT, HOST: env.RELAY_HOST || "127.0.0.1" };
|
|
1367
|
+
}
|
|
1368
|
+
async function readBoundedJson(response) {
|
|
1369
|
+
const limit = 4 * 1024 * 1024;
|
|
1370
|
+
const reader = response.body?.getReader();
|
|
1371
|
+
if (!reader)
|
|
1372
|
+
throw new Error("invalid JSON response");
|
|
1373
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
1374
|
+
let bytes = 0;
|
|
1375
|
+
let text = "";
|
|
1376
|
+
try {
|
|
1377
|
+
for (;; ) {
|
|
1378
|
+
const { done, value } = await reader.read();
|
|
1379
|
+
if (done)
|
|
1380
|
+
break;
|
|
1381
|
+
bytes += value.byteLength;
|
|
1382
|
+
if (bytes > limit)
|
|
1383
|
+
throw new Error("JSON response too large");
|
|
1384
|
+
text += decoder.decode(value, { stream: true });
|
|
1385
|
+
}
|
|
1386
|
+
text += decoder.decode();
|
|
1387
|
+
const parsed = JSON.parse(text);
|
|
1388
|
+
if (parsed && typeof parsed === "object" && Object.prototype.hasOwnProperty.call(parsed, "__proto__")) {
|
|
1389
|
+
throw new Error("invalid JSON response");
|
|
1390
|
+
}
|
|
1391
|
+
return parsed;
|
|
1392
|
+
} catch (error) {
|
|
1393
|
+
reader.cancel().catch(() => {});
|
|
1394
|
+
throw error;
|
|
1395
|
+
} finally {
|
|
1396
|
+
reader.releaseLock();
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
730
1399
|
function parseIdentitiesJson(raw, source) {
|
|
731
1400
|
let parsed;
|
|
732
1401
|
try {
|
|
@@ -734,16 +1403,33 @@ function parseIdentitiesJson(raw, source) {
|
|
|
734
1403
|
} catch {
|
|
735
1404
|
throw new Error(`${source} is not valid JSON`);
|
|
736
1405
|
}
|
|
737
|
-
if (!Array.isArray(parsed) || parsed.length === 0) {
|
|
738
|
-
throw new Error(`${source} must be a
|
|
1406
|
+
if (!Array.isArray(parsed) || parsed.length === 0 || parsed.length > 256) {
|
|
1407
|
+
throw new Error(`${source} must be a JSON array of 1..256 identities`);
|
|
739
1408
|
}
|
|
740
1409
|
const seen = new Set;
|
|
741
1410
|
for (const [index, it] of parsed.entries()) {
|
|
1411
|
+
if (!it || typeof it !== "object" || Object.getPrototypeOf(it) !== Object.prototype || Object.prototype.hasOwnProperty.call(it, "__proto__")) {
|
|
1412
|
+
throw new Error(`${source} entry ${index}: invalid identity object`);
|
|
1413
|
+
}
|
|
742
1414
|
const invalid = ["botId", "token", "gatewayId", "secret"].filter((k) => typeof it?.[k] !== "string" || !it[k].trim());
|
|
743
1415
|
for (const k of ["agentId", "profile"]) {
|
|
744
1416
|
if (it?.[k] !== undefined && (typeof it[k] !== "string" || !it[k].trim()))
|
|
745
1417
|
invalid.push(k);
|
|
746
1418
|
}
|
|
1419
|
+
for (const k of ["botId", "agentId", "token", "gatewayId", "secret", "profile"]) {
|
|
1420
|
+
if (typeof it[k] === "string" && CONNECTOR_CTRL_RE.test(it[k]))
|
|
1421
|
+
invalid.push(k);
|
|
1422
|
+
}
|
|
1423
|
+
if (typeof it.botId === "string" && !validIdentityId(it.botId))
|
|
1424
|
+
invalid.push("botId");
|
|
1425
|
+
if (it.agentId !== undefined && (typeof it.agentId !== "string" || !validIdentityId(it.agentId)))
|
|
1426
|
+
invalid.push("agentId");
|
|
1427
|
+
if (typeof it.gatewayId === "string" && (it.gatewayId.length > 256 || GATEWAY_PROTO_KEYS2.has(it.gatewayId.trim().toLowerCase()))) {
|
|
1428
|
+
invalid.push("gatewayId");
|
|
1429
|
+
}
|
|
1430
|
+
if (it.profile !== undefined && (typeof it.profile !== "string" || it.profile.trim().length > 128 || it.profile.trim() === "." || it.profile.includes("..") || /[/\\]/.test(it.profile.trim()) || /(?:%2f|%5c|%00|%2e%2e)/i.test(it.profile.trim()) || CONNECTOR_PROTO_KEYS.has(it.profile.trim().toLowerCase()))) {
|
|
1431
|
+
invalid.push("profile");
|
|
1432
|
+
}
|
|
747
1433
|
if (invalid.length)
|
|
748
1434
|
throw new Error(`${source} entry ${index}: missing or invalid string fields: ${invalid.join(", ")}`);
|
|
749
1435
|
if (seen.has(it.botId))
|
|
@@ -764,6 +1450,11 @@ function loadIdentities() {
|
|
|
764
1450
|
if (file) {
|
|
765
1451
|
let raw2;
|
|
766
1452
|
try {
|
|
1453
|
+
assertSafeConnectorAncestors(file);
|
|
1454
|
+
const stat = lstatSync2(file);
|
|
1455
|
+
if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 1048576) {
|
|
1456
|
+
throw new Error("Unsafe identities file");
|
|
1457
|
+
}
|
|
767
1458
|
raw2 = readFileSync2(file, "utf8");
|
|
768
1459
|
} catch {
|
|
769
1460
|
throw new Error("RELAY_IDENTITIES_FILE could not be read");
|
|
@@ -788,411 +1479,513 @@ function resolveIdentitiesAtStartup() {
|
|
|
788
1479
|
process.exit(1);
|
|
789
1480
|
}
|
|
790
1481
|
}
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
(secrets[id.gatewayId] ??= []).push(id.secret);
|
|
1482
|
+
function clampTimerMs(raw, fallback, minMs) {
|
|
1483
|
+
const value = Number(raw);
|
|
1484
|
+
return Math.min(2147483647, Math.max(minMs, Math.floor(Number.isFinite(value) && value > 0 ? value : fallback)));
|
|
795
1485
|
}
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
var reconnectTimerByBot = new Map;
|
|
799
|
-
var currentIdentity = (id) => !process.__shutdown && identities.includes(id);
|
|
800
|
-
function cancelReconnect(botId) {
|
|
801
|
-
const timer = reconnectTimerByBot.get(botId);
|
|
802
|
-
if (timer)
|
|
803
|
-
clearTimeout(timer);
|
|
804
|
-
reconnectTimerByBot.delete(botId);
|
|
1486
|
+
function isConnectorEntrypoint(entry, moduleUrl, isMain = false) {
|
|
1487
|
+
return isMain || Boolean(entry && resolve2(entry) === fileURLToPath(moduleUrl));
|
|
805
1488
|
}
|
|
806
|
-
function
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
const
|
|
811
|
-
|
|
1489
|
+
async function main() {
|
|
1490
|
+
const { API, WS_URL, PORT, HOST } = readConnectorConfig();
|
|
1491
|
+
let identities = resolveIdentitiesAtStartup();
|
|
1492
|
+
const secrets = {};
|
|
1493
|
+
for (const id of identities) {
|
|
1494
|
+
(secrets[id.gatewayId] ??= []).push(id.secret);
|
|
1495
|
+
}
|
|
1496
|
+
let broadcast = null;
|
|
1497
|
+
const socketsByBot = new Map;
|
|
1498
|
+
const reconnectTimerByBot = new Map;
|
|
1499
|
+
const currentIdentity = (id) => !process.__shutdown && identities.includes(id);
|
|
1500
|
+
function cancelReconnect(botId) {
|
|
1501
|
+
const timer = reconnectTimerByBot.get(botId);
|
|
1502
|
+
if (timer)
|
|
1503
|
+
clearTimeout(timer);
|
|
1504
|
+
reconnectTimerByBot.delete(botId);
|
|
1505
|
+
}
|
|
1506
|
+
function scheduleReconnect(id, delay) {
|
|
1507
|
+
if (!currentIdentity(id))
|
|
812
1508
|
return;
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
var HB_PING_MS = Math.max(5000, Number(process.env.AGENTSCHAT_CONNECTOR_PING_MS || 15000));
|
|
824
|
-
var HB_PONG_MS = Math.max(HB_PING_MS + 5000, Number(process.env.AGENTSCHAT_CONNECTOR_PONG_TIMEOUT_MS || 45000));
|
|
825
|
-
var HB_CONNECT_MS = Math.max(5000, Number(process.env.AGENTSCHAT_CONNECTOR_CONNECT_TIMEOUT_MS || 30000));
|
|
826
|
-
function stopHeartbeat(botId) {
|
|
827
|
-
const hb = heartbeatsByBot.get(botId);
|
|
828
|
-
if (!hb)
|
|
829
|
-
return;
|
|
830
|
-
hb.stop();
|
|
831
|
-
heartbeatsByBot.delete(botId);
|
|
832
|
-
}
|
|
833
|
-
var CURSOR_DIR = process.env.AGENTCHAT_CURSOR_DIR || process.cwd();
|
|
834
|
-
var cursorFlushMs = Math.max(500, Number(process.env.AGENTSCHAT_MCP_CURSOR_FLUSH_MS || 5000));
|
|
835
|
-
var cursors = new Map;
|
|
836
|
-
function cursorFor(id) {
|
|
837
|
-
let s = cursors.get(id.botId);
|
|
838
|
-
if (s)
|
|
839
|
-
return s;
|
|
840
|
-
const file = join(CURSOR_DIR, `last-seen-msg-ts-${id.botId}.json`);
|
|
841
|
-
s = { file, map: loadCursor(file, (m) => log(m.trimEnd())), state: { dirty: false }, timer: null };
|
|
842
|
-
cursors.set(id.botId, s);
|
|
843
|
-
return s;
|
|
844
|
-
}
|
|
845
|
-
function flushOne(s) {
|
|
846
|
-
if (s.timer) {
|
|
847
|
-
clearTimeout(s.timer);
|
|
848
|
-
s.timer = null;
|
|
1509
|
+
cancelReconnect(id.botId);
|
|
1510
|
+
const timer = setTimeout(() => {
|
|
1511
|
+
if (reconnectTimerByBot.get(id.botId) !== timer)
|
|
1512
|
+
return;
|
|
1513
|
+
reconnectTimerByBot.delete(id.botId);
|
|
1514
|
+
if (currentIdentity(id))
|
|
1515
|
+
connectIdentity(id);
|
|
1516
|
+
}, delay);
|
|
1517
|
+
timer.unref?.();
|
|
1518
|
+
reconnectTimerByBot.set(id.botId, timer);
|
|
849
1519
|
}
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
return;
|
|
865
|
-
const s = cursorFor(id);
|
|
866
|
-
const prev = s.map.get(channelId) || "";
|
|
867
|
-
const currentTs = normalizeTimestampForCursor(timestamp, "after") || timestamp;
|
|
868
|
-
const prevTs = normalizeTimestampForCursor(prev, "after") || prev;
|
|
869
|
-
if (currentTs > prevTs) {
|
|
870
|
-
s.map.set(channelId, timestamp);
|
|
871
|
-
scheduleSave(s);
|
|
1520
|
+
const backoffByBot = new Map;
|
|
1521
|
+
const backfillTimerByBot = new Map;
|
|
1522
|
+
const heartbeatsByBot = new Map;
|
|
1523
|
+
const dedup = new MessageDedup;
|
|
1524
|
+
const HB_PING_MS = clampTimerMs(process.env.AGENTSCHAT_CONNECTOR_PING_MS, 15000, 5000);
|
|
1525
|
+
const HB_PONG_MS = clampTimerMs(process.env.AGENTSCHAT_CONNECTOR_PONG_TIMEOUT_MS, 45000, Math.min(2147483647, HB_PING_MS + 5000));
|
|
1526
|
+
const HB_CONNECT_MS = clampTimerMs(process.env.AGENTSCHAT_CONNECTOR_CONNECT_TIMEOUT_MS, 30000, 5000);
|
|
1527
|
+
const HTTP_TIMEOUT_MS = clampTimerMs(process.env.AGENTSCHAT_CONNECTOR_HTTP_TIMEOUT_MS, 1e4, 2000);
|
|
1528
|
+
function stopHeartbeat(botId) {
|
|
1529
|
+
const hb = heartbeatsByBot.get(botId);
|
|
1530
|
+
if (!hb)
|
|
1531
|
+
return;
|
|
1532
|
+
hb.stop();
|
|
1533
|
+
heartbeatsByBot.delete(botId);
|
|
872
1534
|
}
|
|
873
|
-
|
|
874
|
-
function joinChannel(ws, id, channelId, name) {
|
|
1535
|
+
const CURSOR_DIR = process.env.AGENTCHAT_CURSOR_DIR || process.cwd();
|
|
875
1536
|
try {
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
log(`join ${channelId} failed: ${e?.message ?? e}`);
|
|
1537
|
+
assertSafeConnectorAncestors(CURSOR_DIR, true);
|
|
1538
|
+
} catch {
|
|
1539
|
+
throw new Error("unsafe connector cursor directory");
|
|
880
1540
|
}
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
if (
|
|
886
|
-
|
|
887
|
-
|
|
1541
|
+
const cursorFlushMs = clampTimerMs(process.env.AGENTSCHAT_MCP_CURSOR_FLUSH_MS, 5000, 500);
|
|
1542
|
+
const cursors = new Map;
|
|
1543
|
+
function cursorFor(id) {
|
|
1544
|
+
let s = cursors.get(id.botId);
|
|
1545
|
+
if (s)
|
|
1546
|
+
return s;
|
|
1547
|
+
const file = safeCursorBotFile(CURSOR_DIR, id.botId);
|
|
1548
|
+
s = { file, map: loadConnectorCursor(file, (m) => log(m.trimEnd())), state: { dirty: false }, timer: null };
|
|
1549
|
+
cursors.set(id.botId, s);
|
|
1550
|
+
return s;
|
|
1551
|
+
}
|
|
1552
|
+
function flushOne(s) {
|
|
1553
|
+
if (s.timer) {
|
|
1554
|
+
clearTimeout(s.timer);
|
|
1555
|
+
s.timer = null;
|
|
888
1556
|
}
|
|
889
|
-
|
|
890
|
-
|
|
1557
|
+
flushCursor(s.state, () => persistConnectorCursor(s.file, s.map, (m) => log(m.trimEnd())));
|
|
1558
|
+
}
|
|
1559
|
+
function scheduleSave(s) {
|
|
1560
|
+
s.state.dirty = true;
|
|
1561
|
+
if (s.timer)
|
|
891
1562
|
return;
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
continue;
|
|
898
|
-
joinChannel(ws, id, channelId, ch?.name);
|
|
899
|
-
joined.push(channelId);
|
|
900
|
-
}
|
|
901
|
-
const prev = backfillTimerByBot.get(id.botId);
|
|
902
|
-
if (prev)
|
|
903
|
-
clearTimeout(prev);
|
|
904
|
-
const t = setTimeout(() => {
|
|
905
|
-
backfillTimerByBot.delete(id.botId);
|
|
906
|
-
if (!currentIdentity(id) || socketsByBot.get(id.botId) !== ws)
|
|
907
|
-
return;
|
|
908
|
-
backfillIdentity(id, joined);
|
|
909
|
-
}, 2000);
|
|
910
|
-
t.unref?.();
|
|
911
|
-
backfillTimerByBot.set(id.botId, t);
|
|
912
|
-
} catch (e) {
|
|
913
|
-
log(`join-on-auth failed: ${e?.message ?? e}`);
|
|
1563
|
+
s.timer = setTimeout(() => {
|
|
1564
|
+
s.timer = null;
|
|
1565
|
+
flushOne(s);
|
|
1566
|
+
}, cursorFlushMs);
|
|
1567
|
+
s.timer.unref?.();
|
|
914
1568
|
}
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
if (!
|
|
1569
|
+
function advanceCursor(id, channelId, timestamp) {
|
|
1570
|
+
if (!validIdentityId(channelId) || typeof timestamp !== "string" || !timestamp)
|
|
1571
|
+
return;
|
|
1572
|
+
const currentTs = canonicalCursorTimestamp(timestamp);
|
|
1573
|
+
if (!currentTs)
|
|
920
1574
|
return;
|
|
1575
|
+
const s = cursorFor(id);
|
|
1576
|
+
const prev = s.map.get(channelId) || "";
|
|
1577
|
+
const prevTs = canonicalCursorTimestamp(prev) ?? "";
|
|
1578
|
+
if (currentTs > prevTs) {
|
|
1579
|
+
s.map.set(channelId, timestamp);
|
|
1580
|
+
scheduleSave(s);
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
function joinChannel(ws, id, channelId, name) {
|
|
1584
|
+
if (!validIdentityId(channelId))
|
|
1585
|
+
return;
|
|
1586
|
+
try {
|
|
1587
|
+
ws.send(JSON.stringify({ type: "join_channel", channel_id: channelId, agent_id: id.agentId }));
|
|
1588
|
+
const safeName = typeof name === "string" ? redactSecrets(name).replace(CONNECTOR_LOG_STRIP_RE, " ").trim().slice(0, 128) : "";
|
|
1589
|
+
log(`joined channel ${channelId}${safeName ? ` (${safeName})` : ""}`);
|
|
1590
|
+
} catch (e) {
|
|
1591
|
+
log(`join ${channelId} failed: ${e?.message ?? e}`);
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
async function joinMemberships(ws, id) {
|
|
921
1595
|
try {
|
|
922
|
-
const
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
1596
|
+
const r = await fetch(`${API}/api/channels/mine`, {
|
|
1597
|
+
redirect: "error",
|
|
1598
|
+
headers: { Authorization: `Bearer ${id.token}` },
|
|
1599
|
+
signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
|
|
926
1600
|
});
|
|
927
|
-
if (!r.ok)
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
if (!currentIdentity(id))
|
|
1601
|
+
if (!r.ok) {
|
|
1602
|
+
await r.body?.cancel().catch(() => {});
|
|
1603
|
+
log(`list mine failed: ${r.status}`);
|
|
931
1604
|
return;
|
|
932
|
-
const plan = planBackfill(after, msgs, id.agentId);
|
|
933
|
-
if (plan.seed) {
|
|
934
|
-
s.map.set(channelId, plan.seed);
|
|
935
|
-
scheduleSave(s);
|
|
936
|
-
continue;
|
|
937
1605
|
}
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
1606
|
+
const body = await readBoundedJson(r);
|
|
1607
|
+
if (!currentIdentity(id) || socketsByBot.get(id.botId) !== ws)
|
|
1608
|
+
return;
|
|
1609
|
+
const channels = Array.isArray(body) ? body : body.channels || [];
|
|
1610
|
+
const joined = [];
|
|
1611
|
+
for (const ch of channels) {
|
|
1612
|
+
const channelId = ch?.id || ch?.channel_id;
|
|
1613
|
+
if (!validIdentityId(channelId))
|
|
1614
|
+
continue;
|
|
1615
|
+
joinChannel(ws, id, channelId, ch?.name);
|
|
1616
|
+
joined.push(channelId);
|
|
946
1617
|
}
|
|
1618
|
+
const prev = backfillTimerByBot.get(id.botId);
|
|
1619
|
+
if (prev)
|
|
1620
|
+
clearTimeout(prev);
|
|
1621
|
+
const t = setTimeout(() => {
|
|
1622
|
+
backfillTimerByBot.delete(id.botId);
|
|
1623
|
+
if (!currentIdentity(id) || socketsByBot.get(id.botId) !== ws)
|
|
1624
|
+
return;
|
|
1625
|
+
backfillIdentity(id, joined);
|
|
1626
|
+
}, 2000);
|
|
1627
|
+
t.unref?.();
|
|
1628
|
+
backfillTimerByBot.set(id.botId, t);
|
|
947
1629
|
} catch (e) {
|
|
948
|
-
log(`
|
|
1630
|
+
log(`join-on-auth failed: ${e?.message ?? e}`);
|
|
949
1631
|
}
|
|
950
1632
|
}
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
if (prev) {
|
|
959
|
-
try {
|
|
960
|
-
prev.removeAllListeners("close");
|
|
961
|
-
prev.close();
|
|
962
|
-
} catch {}
|
|
963
|
-
socketsByBot.delete(id.botId);
|
|
964
|
-
}
|
|
965
|
-
let heartbeatForced = false;
|
|
966
|
-
const ws = new WS(WS_URL);
|
|
967
|
-
socketsByBot.set(id.botId, ws);
|
|
968
|
-
const hb = new HeartbeatMonitor({
|
|
969
|
-
sendPing: () => {
|
|
1633
|
+
async function backfillIdentity(id, channelIds) {
|
|
1634
|
+
const s = cursorFor(id);
|
|
1635
|
+
for (const channelId of channelIds) {
|
|
1636
|
+
if (!validIdentityId(channelId))
|
|
1637
|
+
continue;
|
|
1638
|
+
if (!currentIdentity(id))
|
|
1639
|
+
return;
|
|
970
1640
|
try {
|
|
971
|
-
|
|
972
|
-
|
|
1641
|
+
const after = s.map.get(channelId);
|
|
1642
|
+
const params = after ? `?after=${encodeURIComponent(after)}&limit=50` : `?limit=1`;
|
|
1643
|
+
const r = await fetch(`${API}/api/channels/${encodeURIComponent(channelId)}/messages${params}`, {
|
|
1644
|
+
redirect: "error",
|
|
1645
|
+
headers: { Authorization: `Bearer ${id.token}` },
|
|
1646
|
+
signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
|
|
1647
|
+
});
|
|
1648
|
+
if (!r.ok) {
|
|
1649
|
+
await r.body?.cancel().catch(() => {});
|
|
1650
|
+
continue;
|
|
973
1651
|
}
|
|
1652
|
+
const msgs = (await readBoundedJson(r))?.messages ?? [];
|
|
1653
|
+
if (!currentIdentity(id))
|
|
1654
|
+
return;
|
|
1655
|
+
const plan = planBackfill(after, msgs, id.agentId);
|
|
1656
|
+
if (plan.seed) {
|
|
1657
|
+
s.map.set(channelId, plan.seed);
|
|
1658
|
+
scheduleSave(s);
|
|
1659
|
+
continue;
|
|
1660
|
+
}
|
|
1661
|
+
if (!plan.replay.length)
|
|
1662
|
+
continue;
|
|
1663
|
+
log(`backfill ${id.botId} ${channelId}: ${plan.replay.length} missed msg(s)`);
|
|
1664
|
+
for (const m of plan.replay) {
|
|
1665
|
+
const frame = { ...m, type: "message", channel_id: m.channel_id ?? channelId, __botId: id.botId, __source: "backfill" };
|
|
1666
|
+
if (ingestAgentsChatFrame(id, frame, { advanceCursor, dedup })) {
|
|
1667
|
+
broadcast?.(frame);
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
} catch (e) {
|
|
1671
|
+
log(`backfill failed for ${id.botId} ${channelId}: ${e?.message ?? e}`);
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
function connectIdentity(id) {
|
|
1676
|
+
if (!currentIdentity(id))
|
|
1677
|
+
return;
|
|
1678
|
+
cancelReconnect(id.botId);
|
|
1679
|
+
stopHeartbeat(id.botId);
|
|
1680
|
+
const prev = socketsByBot.get(id.botId);
|
|
1681
|
+
if (prev) {
|
|
1682
|
+
try {
|
|
1683
|
+
prev.removeAllListeners("close");
|
|
1684
|
+
prev.close();
|
|
974
1685
|
} catch {}
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
1686
|
+
socketsByBot.delete(id.botId);
|
|
1687
|
+
}
|
|
1688
|
+
let heartbeatForced = false;
|
|
1689
|
+
const MAX_PLATFORM_WS_BYTES = 4 * 1024 * 1024;
|
|
1690
|
+
const ws = new WS(WS_URL, { maxPayload: MAX_PLATFORM_WS_BYTES });
|
|
1691
|
+
socketsByBot.set(id.botId, ws);
|
|
1692
|
+
const hb = new HeartbeatMonitor({
|
|
1693
|
+
sendPing: () => {
|
|
1694
|
+
try {
|
|
1695
|
+
if (ws.readyState === WS.OPEN) {
|
|
1696
|
+
ws.send(JSON.stringify({ type: "ping", timestamp: new Date().toISOString() }));
|
|
1697
|
+
}
|
|
1698
|
+
} catch {}
|
|
1699
|
+
},
|
|
1700
|
+
reconnect: () => {
|
|
1701
|
+
if (!currentIdentity(id) || socketsByBot.get(id.botId) !== ws || heartbeatForced)
|
|
1702
|
+
return;
|
|
1703
|
+
heartbeatForced = true;
|
|
1704
|
+
log(`agentschat WS heartbeat timeout for ${id.botId}; forcing reconnect`);
|
|
1705
|
+
backoffByBot.set(id.botId, 1000);
|
|
1706
|
+
try {
|
|
1707
|
+
ws.removeAllListeners("close");
|
|
1708
|
+
ws.close();
|
|
1709
|
+
} catch {}
|
|
1710
|
+
socketsByBot.delete(id.botId);
|
|
1711
|
+
stopHeartbeat(id.botId);
|
|
1712
|
+
scheduleReconnect(id, 500);
|
|
1713
|
+
},
|
|
1714
|
+
getReadyState: () => ws.readyState ?? WS_CLOSED
|
|
1715
|
+
}, HB_PING_MS, HB_PONG_MS, HB_CONNECT_MS);
|
|
1716
|
+
heartbeatsByBot.set(id.botId, hb);
|
|
1717
|
+
hb.start();
|
|
1718
|
+
ws.on("open", () => {
|
|
1719
|
+
if (!currentIdentity(id) || socketsByBot.get(id.botId) !== ws) {
|
|
1720
|
+
ws.close();
|
|
978
1721
|
return;
|
|
979
|
-
|
|
980
|
-
log(`agentschat WS heartbeat timeout for ${id.botId}; forcing reconnect`);
|
|
981
|
-
backoffByBot.set(id.botId, 1000);
|
|
1722
|
+
}
|
|
982
1723
|
try {
|
|
983
|
-
ws.
|
|
984
|
-
ws.close();
|
|
1724
|
+
ws.send(JSON.stringify({ type: "auth", agent_id: id.agentId, token: id.token, capabilities: ["chat"] }));
|
|
985
1725
|
} catch {}
|
|
986
|
-
|
|
1726
|
+
});
|
|
1727
|
+
ws.on("message", (raw) => {
|
|
1728
|
+
if (!currentIdentity(id) || socketsByBot.get(id.botId) !== ws)
|
|
1729
|
+
return;
|
|
1730
|
+
const rawBytes = Array.isArray(raw) ? raw.reduce((n, chunk) => n + (chunk?.byteLength ?? Buffer.byteLength(String(chunk), "utf8")), 0) : typeof raw === "string" ? Buffer.byteLength(raw, "utf8") : raw?.byteLength ?? 0;
|
|
1731
|
+
if (rawBytes > MAX_PLATFORM_WS_BYTES)
|
|
1732
|
+
return;
|
|
1733
|
+
let data;
|
|
1734
|
+
try {
|
|
1735
|
+
data = JSON.parse(String(raw));
|
|
1736
|
+
} catch {
|
|
1737
|
+
return;
|
|
1738
|
+
}
|
|
1739
|
+
if (!data || typeof data !== "object" || Array.isArray(data) || Object.prototype.hasOwnProperty.call(data, "__proto__"))
|
|
1740
|
+
return;
|
|
1741
|
+
if (data.type === "pong") {
|
|
1742
|
+
hb.receivedPong();
|
|
1743
|
+
return;
|
|
1744
|
+
}
|
|
1745
|
+
if (data.type === "auth_ok") {
|
|
1746
|
+
hb.receivedPong();
|
|
1747
|
+
backoffByBot.set(id.botId, 1000);
|
|
1748
|
+
log(`connected to agentschat as ${id.agentId}`);
|
|
1749
|
+
joinMemberships(ws, id);
|
|
1750
|
+
return;
|
|
1751
|
+
}
|
|
1752
|
+
if (data.type === "auth_error") {
|
|
1753
|
+
const reason = redactSecrets(String(data.error ?? data.reason ?? "rejected")).slice(0, 200);
|
|
1754
|
+
log(`agentschat WS auth_error for ${id.botId}: ${reason}; backing off 30000ms`);
|
|
1755
|
+
backoffByBot.set(id.botId, 30000);
|
|
1756
|
+
try {
|
|
1757
|
+
ws.close();
|
|
1758
|
+
} catch {}
|
|
1759
|
+
return;
|
|
1760
|
+
}
|
|
1761
|
+
if (data.type === "channel_created" && validIdentityId(data.channel_id)) {
|
|
1762
|
+
hb.receivedPong();
|
|
1763
|
+
joinChannel(ws, id, data.channel_id, data.name);
|
|
1764
|
+
return;
|
|
1765
|
+
}
|
|
1766
|
+
if (data.type === "please_reconnect" || data.type === "shard_moved") {
|
|
1767
|
+
if (heartbeatForced)
|
|
1768
|
+
return;
|
|
1769
|
+
heartbeatForced = true;
|
|
1770
|
+
const delay = resolveDrainReconnectDelay(data);
|
|
1771
|
+
log(`agentschat WS ${data.type} for ${id.botId}; reconnecting after jitter ${delay}ms`);
|
|
1772
|
+
backoffByBot.set(id.botId, 1000);
|
|
1773
|
+
try {
|
|
1774
|
+
ws.removeAllListeners("close");
|
|
1775
|
+
ws.close();
|
|
1776
|
+
} catch {}
|
|
1777
|
+
socketsByBot.delete(id.botId);
|
|
1778
|
+
stopHeartbeat(id.botId);
|
|
1779
|
+
scheduleReconnect(id, delay);
|
|
1780
|
+
return;
|
|
1781
|
+
}
|
|
1782
|
+
if (data.type === "message" || data.type === "thread_reply") {
|
|
1783
|
+
hb.receivedPong();
|
|
1784
|
+
if (!data.__source)
|
|
1785
|
+
data.__source = "live";
|
|
1786
|
+
if (ingestAgentsChatFrame(id, data, { advanceCursor, dedup })) {
|
|
1787
|
+
broadcast?.({ ...data, __botId: id.botId });
|
|
1788
|
+
}
|
|
1789
|
+
}
|
|
1790
|
+
});
|
|
1791
|
+
ws.on("close", () => {
|
|
1792
|
+
if (!currentIdentity(id) || socketsByBot.get(id.botId) !== ws)
|
|
1793
|
+
return;
|
|
987
1794
|
stopHeartbeat(id.botId);
|
|
988
|
-
|
|
1795
|
+
if (process.__shutdown)
|
|
1796
|
+
return;
|
|
1797
|
+
if (heartbeatForced)
|
|
1798
|
+
return;
|
|
1799
|
+
const delay = backoffByBot.get(id.botId) ?? 1000;
|
|
1800
|
+
log(`agentschat WS closed for ${id.botId}; reconnecting in ${delay}ms`);
|
|
1801
|
+
scheduleReconnect(id, delay);
|
|
1802
|
+
backoffByBot.set(id.botId, Math.min(delay * 2, 30000));
|
|
1803
|
+
});
|
|
1804
|
+
ws.on("error", (e) => log(`agentschat WS error (${id.botId}): ${e?.message ?? e}`));
|
|
1805
|
+
}
|
|
1806
|
+
const connector = startConnector({
|
|
1807
|
+
port: PORT,
|
|
1808
|
+
host: HOST,
|
|
1809
|
+
secrets,
|
|
1810
|
+
identities,
|
|
1811
|
+
agentschat: {
|
|
1812
|
+
async sendMessage(botId, chatId, content, replyTo) {
|
|
1813
|
+
const id = requireIdentity(identities, botId);
|
|
1814
|
+
const res = await fetch(`${API}/api/channels/${encodeURIComponent(chatId)}/messages`, {
|
|
1815
|
+
redirect: "error",
|
|
1816
|
+
method: "POST",
|
|
1817
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${id.token}` },
|
|
1818
|
+
body: JSON.stringify({ sender_id: id.agentId, content_type: "text", content, ...replyTo ? { parent_id: replyTo } : {} }),
|
|
1819
|
+
signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
|
|
1820
|
+
}).catch(() => {
|
|
1821
|
+
throw new PlatformNetworkError;
|
|
1822
|
+
});
|
|
1823
|
+
if (!res.ok) {
|
|
1824
|
+
await res.body?.cancel().catch(() => {});
|
|
1825
|
+
throw new PlatformHttpError(res.status);
|
|
1826
|
+
}
|
|
1827
|
+
const data = await readBoundedJson(res);
|
|
1828
|
+
return { id: data?.id };
|
|
1829
|
+
},
|
|
1830
|
+
async getLoops(botId) {
|
|
1831
|
+
const id = requireIdentity(identities, botId);
|
|
1832
|
+
const res = await fetch(`${API}/api/loops/mine`, {
|
|
1833
|
+
redirect: "error",
|
|
1834
|
+
headers: { Authorization: `Bearer ${id.token}` },
|
|
1835
|
+
signal: AbortSignal.timeout(5000)
|
|
1836
|
+
});
|
|
1837
|
+
if (!res.ok) {
|
|
1838
|
+
await res.body?.cancel().catch(() => {});
|
|
1839
|
+
throw new PlatformHttpError(res.status);
|
|
1840
|
+
}
|
|
1841
|
+
return await readBoundedJson(res);
|
|
1842
|
+
},
|
|
1843
|
+
async getChatInfo(botId, chatId) {
|
|
1844
|
+
const id = requireIdentity(identities, botId);
|
|
1845
|
+
const res = await fetch(`${API}/api/channels/${encodeURIComponent(chatId)}`, {
|
|
1846
|
+
redirect: "error",
|
|
1847
|
+
headers: { Authorization: `Bearer ${id.token}` },
|
|
1848
|
+
signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
|
|
1849
|
+
});
|
|
1850
|
+
if (!res.ok) {
|
|
1851
|
+
await res.body?.cancel().catch(() => {});
|
|
1852
|
+
return { name: chatId, type: /^dm[-:]/i.test(chatId) ? "dm" : "group" };
|
|
1853
|
+
}
|
|
1854
|
+
const data = await readBoundedJson(res);
|
|
1855
|
+
return { name: data?.name ?? chatId, type: /^dm[-:]/i.test(chatId) ? "dm" : "group" };
|
|
1856
|
+
},
|
|
1857
|
+
async sendTyping(botId, chatId) {
|
|
1858
|
+
const id = requireIdentity(identities, botId);
|
|
1859
|
+
const ws = socketsByBot.get(id.botId);
|
|
1860
|
+
if (ws && ws.readyState === WS.OPEN) {
|
|
1861
|
+
try {
|
|
1862
|
+
ws.send(JSON.stringify({ type: "typing", channel_id: chatId, sender_id: id.agentId }));
|
|
1863
|
+
} catch {}
|
|
1864
|
+
}
|
|
1865
|
+
},
|
|
1866
|
+
async getChannelContext(botId, chatId, sinceTs, excludeId, signal) {
|
|
1867
|
+
const id = requireIdentity(identities, botId);
|
|
1868
|
+
const { signal: boundedSignal, cleanup } = withTimeoutController(signal, HTTP_TIMEOUT_MS);
|
|
1869
|
+
let res;
|
|
1870
|
+
try {
|
|
1871
|
+
res = await fetch(`${API}/api/channels/${encodeURIComponent(chatId)}/messages?limit=50`, {
|
|
1872
|
+
redirect: "error",
|
|
1873
|
+
signal: boundedSignal,
|
|
1874
|
+
headers: { Authorization: `Bearer ${id.token}` }
|
|
1875
|
+
});
|
|
1876
|
+
if (!res.ok) {
|
|
1877
|
+
await res.body?.cancel().catch(() => {});
|
|
1878
|
+
return null;
|
|
1879
|
+
}
|
|
1880
|
+
const rawMsgs = (await readBoundedJson(res))?.messages ?? [];
|
|
1881
|
+
const tail = selectChannelContextMessages(rawMsgs, sinceTs, excludeId);
|
|
1882
|
+
if (!tail.length)
|
|
1883
|
+
return null;
|
|
1884
|
+
return tail.map((m) => ({
|
|
1885
|
+
text: redactSecrets(String(m.content ?? "").slice(0, 4096)).slice(0, 500),
|
|
1886
|
+
user_name: m.sender_name ?? m.sender_id,
|
|
1887
|
+
user_id: m.sender_id
|
|
1888
|
+
}));
|
|
1889
|
+
} finally {
|
|
1890
|
+
cleanup();
|
|
1891
|
+
}
|
|
1892
|
+
}
|
|
989
1893
|
},
|
|
990
|
-
|
|
991
|
-
}, HB_PING_MS, HB_PONG_MS, HB_CONNECT_MS);
|
|
992
|
-
heartbeatsByBot.set(id.botId, hb);
|
|
993
|
-
hb.start();
|
|
994
|
-
ws.on("open", () => {
|
|
995
|
-
if (!currentIdentity(id) || socketsByBot.get(id.botId) !== ws) {
|
|
996
|
-
ws.close();
|
|
997
|
-
return;
|
|
998
|
-
}
|
|
999
|
-
backoffByBot.set(id.botId, 1000);
|
|
1000
|
-
try {
|
|
1001
|
-
ws.send(JSON.stringify({ type: "auth", agent_id: id.agentId, token: id.token, capabilities: ["chat"] }));
|
|
1002
|
-
} catch {}
|
|
1894
|
+
logger: log
|
|
1003
1895
|
});
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
return;
|
|
1027
|
-
}
|
|
1028
|
-
if (data.type === "message") {
|
|
1029
|
-
hb.receivedPong();
|
|
1030
|
-
if (!data.__source)
|
|
1031
|
-
data.__source = "live";
|
|
1032
|
-
if (ingestAgentsChatFrame(id, data, { advanceCursor, dedup })) {
|
|
1033
|
-
broadcast?.({ ...data, __botId: id.botId });
|
|
1896
|
+
broadcast = (msg) => connector.injectAgentsChatMessage(msg);
|
|
1897
|
+
await connector.ready;
|
|
1898
|
+
log(`listening on ${HOST}:${connector.port} (contract v1, ${identities.length} identit${identities.length === 1 ? "y" : "ies"})`);
|
|
1899
|
+
for (const id of identities)
|
|
1900
|
+
connectIdentity(id);
|
|
1901
|
+
function reloadIdentitiesFromConfig() {
|
|
1902
|
+
const next = loadIdentities().map((id) => identities.find((prev) => prev.botId === id.botId && prev.agentId === id.agentId && prev.token === id.token && prev.gatewayId === id.gatewayId && prev.secret === id.secret && prev.profile === id.profile) ?? id);
|
|
1903
|
+
const prevByBot = new Map(identities.map((i) => [i.botId, i]));
|
|
1904
|
+
const nextByBot = new Map(next.map((i) => [i.botId, i]));
|
|
1905
|
+
const added = next.filter((i) => !prevByBot.has(i.botId));
|
|
1906
|
+
const removed = identities.filter((i) => !nextByBot.has(i.botId));
|
|
1907
|
+
const kept = next.filter((i) => prevByBot.has(i.botId));
|
|
1908
|
+
connector.reloadIdentities(next);
|
|
1909
|
+
identities = next;
|
|
1910
|
+
for (const id of removed) {
|
|
1911
|
+
cancelReconnect(id.botId);
|
|
1912
|
+
log(`hot-reload: disconnecting removed identity ${id.botId}`);
|
|
1913
|
+
stopHeartbeat(id.botId);
|
|
1914
|
+
const t = backfillTimerByBot.get(id.botId);
|
|
1915
|
+
if (t) {
|
|
1916
|
+
clearTimeout(t);
|
|
1917
|
+
backfillTimerByBot.delete(id.botId);
|
|
1034
1918
|
}
|
|
1035
|
-
}
|
|
1036
|
-
});
|
|
1037
|
-
ws.on("close", () => {
|
|
1038
|
-
if (!currentIdentity(id) || socketsByBot.get(id.botId) !== ws)
|
|
1039
|
-
return;
|
|
1040
|
-
stopHeartbeat(id.botId);
|
|
1041
|
-
if (process.__shutdown)
|
|
1042
|
-
return;
|
|
1043
|
-
if (heartbeatForced)
|
|
1044
|
-
return;
|
|
1045
|
-
const delay = backoffByBot.get(id.botId) ?? 1000;
|
|
1046
|
-
log(`agentschat WS closed for ${id.botId}; reconnecting in ${delay}ms`);
|
|
1047
|
-
scheduleReconnect(id, delay);
|
|
1048
|
-
backoffByBot.set(id.botId, Math.min(delay * 2, 30000));
|
|
1049
|
-
});
|
|
1050
|
-
ws.on("error", (e) => log(`agentschat WS error (${id.botId}): ${e?.message ?? e}`));
|
|
1051
|
-
}
|
|
1052
|
-
var connector = startConnector({
|
|
1053
|
-
port: PORT,
|
|
1054
|
-
host: HOST,
|
|
1055
|
-
secrets,
|
|
1056
|
-
identities,
|
|
1057
|
-
agentschat: {
|
|
1058
|
-
async sendMessage(botId, chatId, content, replyTo) {
|
|
1059
|
-
const id = requireIdentity(identities, botId);
|
|
1060
|
-
const res = await fetch(`${API}/api/channels/${encodeURIComponent(chatId)}/messages`, {
|
|
1061
|
-
method: "POST",
|
|
1062
|
-
headers: { "Content-Type": "application/json", Authorization: `Bearer ${id.token}` },
|
|
1063
|
-
body: JSON.stringify({ sender_id: id.agentId, content_type: "text", content, ...replyTo ? { parent_id: replyTo } : {} })
|
|
1064
|
-
}).catch(() => {
|
|
1065
|
-
throw new PlatformNetworkError;
|
|
1066
|
-
});
|
|
1067
|
-
if (!res.ok)
|
|
1068
|
-
throw new PlatformHttpError(res.status);
|
|
1069
|
-
const data = await res.json();
|
|
1070
|
-
return { id: data?.id };
|
|
1071
|
-
},
|
|
1072
|
-
async getLoops(botId) {
|
|
1073
|
-
const id = requireIdentity(identities, botId);
|
|
1074
|
-
const res = await fetch(`${API}/api/loops/mine`, {
|
|
1075
|
-
headers: { Authorization: `Bearer ${id.token}` },
|
|
1076
|
-
signal: AbortSignal.timeout(5000)
|
|
1077
|
-
});
|
|
1078
|
-
if (!res.ok)
|
|
1079
|
-
throw new PlatformHttpError(res.status);
|
|
1080
|
-
return await res.json();
|
|
1081
|
-
},
|
|
1082
|
-
async getChatInfo(botId, chatId) {
|
|
1083
|
-
const id = requireIdentity(identities, botId);
|
|
1084
|
-
const res = await fetch(`${API}/api/channels/${encodeURIComponent(chatId)}`, {
|
|
1085
|
-
headers: { Authorization: `Bearer ${id.token}` }
|
|
1086
|
-
});
|
|
1087
|
-
if (!res.ok)
|
|
1088
|
-
return { name: chatId, type: chatId.startsWith("dm-") ? "dm" : "group" };
|
|
1089
|
-
const data = await res.json();
|
|
1090
|
-
return { name: data?.name ?? chatId, type: chatId.startsWith("dm-") ? "dm" : "group" };
|
|
1091
|
-
},
|
|
1092
|
-
async sendTyping(botId, chatId) {
|
|
1093
|
-
const id = requireIdentity(identities, botId);
|
|
1094
1919
|
const ws = socketsByBot.get(id.botId);
|
|
1095
|
-
if (ws
|
|
1920
|
+
if (ws) {
|
|
1096
1921
|
try {
|
|
1097
|
-
ws.
|
|
1922
|
+
ws.removeAllListeners("close");
|
|
1923
|
+
ws.close();
|
|
1098
1924
|
} catch {}
|
|
1925
|
+
socketsByBot.delete(id.botId);
|
|
1099
1926
|
}
|
|
1100
|
-
|
|
1101
|
-
async getChannelContext(botId, chatId, sinceTs, excludeId, signal) {
|
|
1102
|
-
const id = requireIdentity(identities, botId);
|
|
1103
|
-
const res = await fetch(`${API}/api/channels/${encodeURIComponent(chatId)}/messages?limit=50`, {
|
|
1104
|
-
signal,
|
|
1105
|
-
headers: { Authorization: `Bearer ${id.token}` }
|
|
1106
|
-
});
|
|
1107
|
-
if (!res.ok)
|
|
1108
|
-
return null;
|
|
1109
|
-
const msgs = ((await res.json())?.messages ?? []).filter((m) => m?.content && m.content !== "__typing__" && m?.id !== excludeId).sort((a, b) => String(a.timestamp ?? "").localeCompare(String(b.timestamp ?? "")));
|
|
1110
|
-
const windowed = sinceTs ? msgs.filter((m) => String(m.timestamp ?? "") > sinceTs) : msgs;
|
|
1111
|
-
const tail = windowed.slice(-10);
|
|
1112
|
-
if (!tail.length)
|
|
1113
|
-
return null;
|
|
1114
|
-
return tail.map((m) => ({
|
|
1115
|
-
text: redactSecrets(String(m.content)).slice(0, 500),
|
|
1116
|
-
user_name: m.sender_name ?? m.sender_id,
|
|
1117
|
-
user_id: m.sender_id
|
|
1118
|
-
}));
|
|
1927
|
+
backoffByBot.delete(id.botId);
|
|
1119
1928
|
}
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
const nextByBot = new Map(next.map((i) => [i.botId, i]));
|
|
1132
|
-
const added = next.filter((i) => !prevByBot.has(i.botId));
|
|
1133
|
-
const removed = identities.filter((i) => !nextByBot.has(i.botId));
|
|
1134
|
-
const kept = next.filter((i) => prevByBot.has(i.botId));
|
|
1135
|
-
connector.reloadIdentities(next);
|
|
1136
|
-
identities = next;
|
|
1137
|
-
for (const id of removed) {
|
|
1138
|
-
cancelReconnect(id.botId);
|
|
1139
|
-
log(`hot-reload: disconnecting removed identity ${id.botId}`);
|
|
1140
|
-
stopHeartbeat(id.botId);
|
|
1141
|
-
const t = backfillTimerByBot.get(id.botId);
|
|
1142
|
-
if (t) {
|
|
1143
|
-
clearTimeout(t);
|
|
1144
|
-
backfillTimerByBot.delete(id.botId);
|
|
1145
|
-
}
|
|
1146
|
-
const ws = socketsByBot.get(id.botId);
|
|
1147
|
-
if (ws) {
|
|
1148
|
-
try {
|
|
1149
|
-
ws.removeAllListeners("close");
|
|
1150
|
-
ws.close();
|
|
1151
|
-
} catch {}
|
|
1152
|
-
socketsByBot.delete(id.botId);
|
|
1929
|
+
for (const id of kept) {
|
|
1930
|
+
const prev = prevByBot.get(id.botId);
|
|
1931
|
+
if (prev !== id) {
|
|
1932
|
+
cancelReconnect(id.botId);
|
|
1933
|
+
const timer = backfillTimerByBot.get(id.botId);
|
|
1934
|
+
if (timer)
|
|
1935
|
+
clearTimeout(timer);
|
|
1936
|
+
backfillTimerByBot.delete(id.botId);
|
|
1937
|
+
log(`hot-reload: reconnecting ${id.botId} (credentials changed)`);
|
|
1938
|
+
connectIdentity(id);
|
|
1939
|
+
}
|
|
1153
1940
|
}
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
for (const id of kept) {
|
|
1157
|
-
const prev = prevByBot.get(id.botId);
|
|
1158
|
-
if (prev !== id) {
|
|
1159
|
-
cancelReconnect(id.botId);
|
|
1160
|
-
const timer = backfillTimerByBot.get(id.botId);
|
|
1161
|
-
if (timer)
|
|
1162
|
-
clearTimeout(timer);
|
|
1163
|
-
backfillTimerByBot.delete(id.botId);
|
|
1164
|
-
log(`hot-reload: reconnecting ${id.botId} (credentials changed)`);
|
|
1941
|
+
for (const id of added) {
|
|
1942
|
+
log(`hot-reload: connecting new identity ${id.botId}`);
|
|
1165
1943
|
connectIdentity(id);
|
|
1166
1944
|
}
|
|
1945
|
+
log(`hot-reload complete: ${identities.length} identit${identities.length === 1 ? "y" : "ies"} (${added.length} added, ${removed.length} removed)`);
|
|
1167
1946
|
}
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1947
|
+
if (process.platform !== "win32") {
|
|
1948
|
+
process.on("SIGHUP", () => {
|
|
1949
|
+
try {
|
|
1950
|
+
reloadIdentitiesFromConfig();
|
|
1951
|
+
} catch (e) {
|
|
1952
|
+
log(`hot-reload FAILED (keeping previous identities): ${e?.message ?? e}`);
|
|
1953
|
+
}
|
|
1954
|
+
});
|
|
1955
|
+
}
|
|
1956
|
+
for (const sig of ["SIGINT", "SIGTERM"]) {
|
|
1957
|
+
process.on(sig, () => {
|
|
1958
|
+
process.__shutdown = true;
|
|
1959
|
+
for (const botId of reconnectTimerByBot.keys())
|
|
1960
|
+
cancelReconnect(botId);
|
|
1961
|
+
for (const [, t] of backfillTimerByBot)
|
|
1962
|
+
clearTimeout(t);
|
|
1963
|
+
backfillTimerByBot.clear();
|
|
1964
|
+
for (const botId of [...heartbeatsByBot.keys()])
|
|
1965
|
+
stopHeartbeat(botId);
|
|
1966
|
+
for (const ws of socketsByBot.values()) {
|
|
1967
|
+
try {
|
|
1968
|
+
ws.close();
|
|
1969
|
+
} catch {}
|
|
1970
|
+
}
|
|
1971
|
+
for (const s of cursors.values())
|
|
1972
|
+
flushOne(s);
|
|
1973
|
+
connector.stop();
|
|
1974
|
+
process.exit(0);
|
|
1975
|
+
});
|
|
1171
1976
|
}
|
|
1172
|
-
log(`hot-reload complete: ${identities.length} identit${identities.length === 1 ? "y" : "ies"} (${added.length} added, ${removed.length} removed)`);
|
|
1173
1977
|
}
|
|
1174
|
-
process.
|
|
1175
|
-
|
|
1176
|
-
reloadIdentitiesFromConfig();
|
|
1177
|
-
} catch (e) {
|
|
1178
|
-
log(`hot-reload FAILED (keeping previous identities): ${e?.message ?? e}`);
|
|
1179
|
-
}
|
|
1180
|
-
});
|
|
1181
|
-
for (const sig of ["SIGINT", "SIGTERM"]) {
|
|
1182
|
-
process.on(sig, () => {
|
|
1183
|
-
process.__shutdown = true;
|
|
1184
|
-
for (const botId of reconnectTimerByBot.keys())
|
|
1185
|
-
cancelReconnect(botId);
|
|
1186
|
-
for (const botId of [...heartbeatsByBot.keys()])
|
|
1187
|
-
stopHeartbeat(botId);
|
|
1188
|
-
for (const ws of socketsByBot.values()) {
|
|
1189
|
-
try {
|
|
1190
|
-
ws.close();
|
|
1191
|
-
} catch {}
|
|
1192
|
-
}
|
|
1193
|
-
for (const s of cursors.values())
|
|
1194
|
-
flushOne(s);
|
|
1195
|
-
connector.stop();
|
|
1196
|
-
process.exit(0);
|
|
1197
|
-
});
|
|
1978
|
+
if (isConnectorEntrypoint(process.argv[1], import.meta.url, __require.main == __require.module) || process.argv.includes("--connector")) {
|
|
1979
|
+
await main();
|
|
1198
1980
|
}
|
|
1981
|
+
export {
|
|
1982
|
+
readConnectorConfig,
|
|
1983
|
+
readBoundedJson,
|
|
1984
|
+
persistConnectorCursor,
|
|
1985
|
+
parseIdentitiesJson,
|
|
1986
|
+
loadIdentities,
|
|
1987
|
+
loadConnectorCursor,
|
|
1988
|
+
isConnectorEntrypoint,
|
|
1989
|
+
clampTimerMs,
|
|
1990
|
+
assertSafeConnectorAncestors
|
|
1991
|
+
};
|