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/dsh.js
CHANGED
|
@@ -1,33 +1,48 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// dsh/src/cli.ts
|
|
4
|
-
import {
|
|
4
|
+
import { chmodSync as chmodSync3, copyFileSync as copyFileSync3, lstatSync as lstatSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync7, renameSync as renameSync3, unlinkSync as unlinkSync4, writeFileSync as writeFileSync3 } from "node:fs";
|
|
5
|
+
import { randomBytes as randomBytes3 } from "node:crypto";
|
|
5
6
|
import { spawn } from "node:child_process";
|
|
6
|
-
import { dirname as
|
|
7
|
-
import { homedir as
|
|
7
|
+
import { dirname as dirname6, join as join6 } from "node:path";
|
|
8
|
+
import { homedir as homedir5 } from "node:os";
|
|
8
9
|
|
|
9
10
|
// muse/src/policy.ts
|
|
10
11
|
var MAX_HISTORY_MESSAGES = 50;
|
|
11
12
|
var MAX_CONTEXT_BYTES = 15000;
|
|
12
13
|
var MAX_MESSAGE_BYTES = 2000;
|
|
13
14
|
function isMentioned(content, agentId, displayName) {
|
|
15
|
+
if (typeof content !== "string")
|
|
16
|
+
return false;
|
|
14
17
|
const haystack = content.toLowerCase();
|
|
15
|
-
const names = [`@${
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
18
|
+
const names = [agentId, displayName, "muse"].filter((name) => typeof name === "string" && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(name) && name.trim().length > 0).map((name) => `@${name.trim().toLowerCase()}`);
|
|
19
|
+
return names.some((name) => {
|
|
20
|
+
let index = haystack.indexOf(name);
|
|
21
|
+
while (index !== -1) {
|
|
22
|
+
const before = haystack[index - 1];
|
|
23
|
+
const afterCodePoint = haystack.codePointAt(index + name.length);
|
|
24
|
+
const after = afterCodePoint === undefined ? "" : String.fromCodePoint(afterCodePoint);
|
|
25
|
+
if ((!before || !/[a-z0-9@]/i.test(before)) && (!after || !/[\p{L}\p{N}\p{M}_-]/u.test(after)))
|
|
26
|
+
return true;
|
|
27
|
+
index = haystack.indexOf(name, index + 1);
|
|
28
|
+
}
|
|
29
|
+
return false;
|
|
30
|
+
});
|
|
20
31
|
}
|
|
21
32
|
function shouldDispatch(message, opts) {
|
|
33
|
+
if (!message || typeof message !== "object" || typeof message.content !== "string")
|
|
34
|
+
return false;
|
|
22
35
|
if (message.sender_id === opts.agentId)
|
|
23
36
|
return false;
|
|
24
37
|
if (opts.channelKind === "direct")
|
|
25
38
|
return true;
|
|
26
|
-
if (!opts.channelKind)
|
|
27
|
-
return
|
|
39
|
+
if (!opts.channelKind && typeof message.channel_id === "string" && /^dm[-:]/i.test(message.channel_id))
|
|
40
|
+
return true;
|
|
28
41
|
return isMentioned(message.content, opts.agentId, opts.displayName);
|
|
29
42
|
}
|
|
30
43
|
function truncateToBytes(text, maxBytes) {
|
|
44
|
+
if (typeof text !== "string" || maxBytes <= 0)
|
|
45
|
+
return "";
|
|
31
46
|
const encoder = new TextEncoder;
|
|
32
47
|
if (encoder.encode(text).length <= maxBytes)
|
|
33
48
|
return text;
|
|
@@ -40,6 +55,8 @@ function truncateToBytes(text, maxBytes) {
|
|
|
40
55
|
else
|
|
41
56
|
high = mid - 1;
|
|
42
57
|
}
|
|
58
|
+
if (low > 0 && low < text.length && text.charCodeAt(low - 1) >= 55296 && text.charCodeAt(low - 1) <= 56319 && text.charCodeAt(low) >= 56320 && text.charCodeAt(low) <= 57343)
|
|
59
|
+
low -= 1;
|
|
43
60
|
return text.slice(0, low);
|
|
44
61
|
}
|
|
45
62
|
function buildContext(messages, agentId) {
|
|
@@ -47,20 +64,23 @@ function buildContext(messages, agentId) {
|
|
|
47
64
|
const lines = [];
|
|
48
65
|
let bytes = 0;
|
|
49
66
|
for (const m of [...recent].reverse()) {
|
|
50
|
-
const
|
|
67
|
+
const sender = typeof m.sender_id === "string" ? m.sender_id.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, " ").slice(0, 128) : "unknown";
|
|
68
|
+
const line = `${sender}: ${truncateToBytes(m.content, MAX_MESSAGE_BYTES)}
|
|
51
69
|
`;
|
|
52
70
|
const lineBytes = new TextEncoder().encode(line).length;
|
|
53
71
|
if (bytes + lineBytes > MAX_CONTEXT_BYTES)
|
|
54
72
|
break;
|
|
55
73
|
bytes += lineBytes;
|
|
56
|
-
lines.
|
|
74
|
+
lines.push(line);
|
|
57
75
|
}
|
|
58
|
-
return lines.join("");
|
|
76
|
+
return lines.reverse().join("");
|
|
59
77
|
}
|
|
60
78
|
|
|
61
79
|
// muse/src/typing.ts
|
|
62
80
|
var TYPING_HEARTBEAT_MS = 2000;
|
|
63
81
|
var TYPING_HEARTBEAT_MAX_MS = 120000;
|
|
82
|
+
var MAX_TYPING_CHANNELS = 256;
|
|
83
|
+
var FORBIDDEN_TYPING_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
|
64
84
|
|
|
65
85
|
class TypingHeartbeat {
|
|
66
86
|
timers = new Map;
|
|
@@ -74,12 +94,20 @@ class TypingHeartbeat {
|
|
|
74
94
|
} catch {}
|
|
75
95
|
}
|
|
76
96
|
start(channelId) {
|
|
77
|
-
if (!channelId || process.env.AGENTSCHAT_AUTO_TYPING === "0")
|
|
97
|
+
if (typeof channelId !== "string" || !channelId || channelId.length > 128 || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(channelId) || FORBIDDEN_TYPING_KEYS.has(channelId.toLowerCase()) || process.env.AGENTSCHAT_AUTO_TYPING === "0") {
|
|
78
98
|
return;
|
|
99
|
+
}
|
|
79
100
|
this.stop(channelId);
|
|
101
|
+
if (this.timers.size >= MAX_TYPING_CHANNELS) {
|
|
102
|
+
const oldest = this.timers.keys().next().value;
|
|
103
|
+
if (oldest !== undefined)
|
|
104
|
+
this.stop(oldest);
|
|
105
|
+
}
|
|
80
106
|
this.pulse(channelId);
|
|
81
107
|
const interval = setInterval(() => this.pulse(channelId), TYPING_HEARTBEAT_MS);
|
|
108
|
+
interval.unref?.();
|
|
82
109
|
const cap = setTimeout(() => this.stop(channelId), TYPING_HEARTBEAT_MAX_MS);
|
|
110
|
+
cap.unref?.();
|
|
83
111
|
this.timers.set(channelId, { interval, cap });
|
|
84
112
|
}
|
|
85
113
|
stop(channelId) {
|
|
@@ -97,15 +125,19 @@ class TypingHeartbeat {
|
|
|
97
125
|
}
|
|
98
126
|
|
|
99
127
|
// muse/src/bridge.ts
|
|
128
|
+
var FORBIDDEN_BRIDGE_CHANNELS = new Set(["__proto__", "constructor", "prototype"]);
|
|
129
|
+
var BRIDGE_CHANNEL_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
130
|
+
|
|
100
131
|
class MuseBridge {
|
|
101
132
|
client;
|
|
133
|
+
activeReplies = new Map;
|
|
102
134
|
history = new Map;
|
|
103
135
|
opts;
|
|
104
136
|
typing = new TypingHeartbeat((channelId) => this.client.sendTyping(channelId));
|
|
105
137
|
constructor(client, opts) {
|
|
106
138
|
this.client = client;
|
|
107
139
|
this.opts = opts;
|
|
108
|
-
this.client.onMessage((m) =>
|
|
140
|
+
this.client.onMessage((m) => this.handleMessage(m));
|
|
109
141
|
}
|
|
110
142
|
async start() {
|
|
111
143
|
await this.client.connect();
|
|
@@ -117,41 +149,480 @@ class MuseBridge {
|
|
|
117
149
|
this.client.joinChannel(channelId);
|
|
118
150
|
}
|
|
119
151
|
stop() {
|
|
152
|
+
this.typing.stopAll();
|
|
153
|
+
this.activeReplies.clear();
|
|
120
154
|
this.client.disconnect();
|
|
121
155
|
}
|
|
122
156
|
get isConnected() {
|
|
123
157
|
return this.client.isConnected;
|
|
124
158
|
}
|
|
125
159
|
async handleMessage(message) {
|
|
160
|
+
if (!message || typeof message.channel_id !== "string" || !message.channel_id || message.channel_id.length > 256 || FORBIDDEN_BRIDGE_CHANNELS.has(message.channel_id.toLowerCase()) || Object.getOwnPropertyNames(Object.prototype).some((k) => k.toLowerCase() === message.channel_id.toLowerCase()) || message.content === "__typing__") {
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
if (!this.history.has(message.channel_id) && this.history.size >= 200) {
|
|
164
|
+
const oldest = this.history.keys().next().value;
|
|
165
|
+
if (oldest !== undefined)
|
|
166
|
+
this.history.delete(oldest);
|
|
167
|
+
}
|
|
126
168
|
const list = this.history.get(message.channel_id) ?? [];
|
|
127
169
|
list.push(message);
|
|
128
170
|
this.history.set(message.channel_id, list.slice(-50));
|
|
129
|
-
const
|
|
171
|
+
const kinds = this.opts.channelKinds;
|
|
172
|
+
const kind = kinds && Object.prototype.hasOwnProperty.call(kinds, message.channel_id) ? kinds[message.channel_id] : undefined;
|
|
130
173
|
if (!shouldDispatch(message, { agentId: this.opts.agentId, displayName: this.opts.displayName, channelKind: kind })) {
|
|
131
174
|
return;
|
|
132
175
|
}
|
|
133
|
-
this.
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
176
|
+
const active = this.activeReplies.get(message.channel_id) ?? 0;
|
|
177
|
+
this.activeReplies.set(message.channel_id, active + 1);
|
|
178
|
+
if (active === 0)
|
|
179
|
+
this.typing.start(message.channel_id);
|
|
180
|
+
try {
|
|
181
|
+
const ctx = {
|
|
182
|
+
message,
|
|
183
|
+
channelKind: kind,
|
|
184
|
+
history: [...this.history.get(message.channel_id) ?? []],
|
|
185
|
+
context: buildContext(this.history.get(message.channel_id) ?? [], this.opts.agentId)
|
|
186
|
+
};
|
|
187
|
+
const reply = await this.opts.responder(ctx);
|
|
188
|
+
if (reply && !BRIDGE_CHANNEL_CTRL_RE.test(message.channel_id)) {
|
|
189
|
+
if (message.thread_id && !BRIDGE_CHANNEL_CTRL_RE.test(message.thread_id)) {
|
|
190
|
+
this.client.sendMessage(message.channel_id, reply, "text", message.thread_id);
|
|
191
|
+
} else {
|
|
192
|
+
this.client.sendMessage(message.channel_id, reply);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
} finally {
|
|
196
|
+
const remaining = (this.activeReplies.get(message.channel_id) ?? 1) - 1;
|
|
197
|
+
if (remaining <= 0) {
|
|
198
|
+
this.activeReplies.delete(message.channel_id);
|
|
199
|
+
this.typing.stop(message.channel_id);
|
|
200
|
+
} else {
|
|
201
|
+
this.activeReplies.set(message.channel_id, remaining);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// muse/src/config.ts
|
|
208
|
+
import { existsSync, lstatSync, readFileSync, realpathSync } from "node:fs";
|
|
209
|
+
import { homedir } from "node:os";
|
|
210
|
+
import { dirname, isAbsolute, join, sep } from "node:path";
|
|
211
|
+
var PROFILE_PATH = join(homedir(), ".agentschat", "muse.json");
|
|
212
|
+
var MAX_PROFILE_BYTES = 64 * 1024;
|
|
213
|
+
function isLoopbackHost(hostname) {
|
|
214
|
+
const h = hostname.toLowerCase();
|
|
215
|
+
return h === "localhost" || h === "127.0.0.1" || h === "[::1]" || h === "::1";
|
|
216
|
+
}
|
|
217
|
+
function isUnsafeEndpointHost(hostname) {
|
|
218
|
+
let host = hostname.toLowerCase().replace(/\.+$/, "");
|
|
219
|
+
if (["metadata.google.internal", "metadata.goog", "metadata", "instance-data"].includes(host) || host.endsWith(".metadata.google.internal") || host.endsWith(".metadata.goog"))
|
|
220
|
+
return true;
|
|
221
|
+
const unsafeV4 = (ip) => ip.startsWith("0.") || ip === "100.100.100.200" || ip.startsWith("169.254.");
|
|
222
|
+
if (/^\d+\.\d+\.\d+\.\d+$/.test(host))
|
|
223
|
+
return unsafeV4(host);
|
|
224
|
+
if (!host.startsWith("["))
|
|
225
|
+
return false;
|
|
226
|
+
try {
|
|
227
|
+
host = new URL(`http://${host}`).hostname.toLowerCase();
|
|
228
|
+
} catch {
|
|
229
|
+
return true;
|
|
230
|
+
}
|
|
231
|
+
const address = host.slice(1, -1);
|
|
232
|
+
const [left, right = ""] = address.split("::");
|
|
233
|
+
const head = left ? left.split(":") : [];
|
|
234
|
+
const tail = right ? right.split(":") : [];
|
|
235
|
+
const words = (address.includes("::") ? [...head, ...Array(8 - head.length - tail.length).fill("0"), ...tail] : head).map((x) => parseInt(x, 16));
|
|
236
|
+
if (words.length !== 8)
|
|
237
|
+
return true;
|
|
238
|
+
const mapped = words.slice(0, 5).every((x) => x === 0) && words[5] === 65535 || words.slice(0, 4).every((x) => x === 0) && words[4] === 65535 && words[5] === 0;
|
|
239
|
+
if (mapped)
|
|
240
|
+
return unsafeV4(`${words[6] >> 8}.${words[6] & 255}.${words[7] >> 8}.${words[7] & 255}`);
|
|
241
|
+
return words.every((x) => x === 0) || (words[0] & 65472) === 65152 || words[0] === 64768 && words[1] === 3778 && words.slice(2, 7).every((x) => x === 0) && words[7] === 596;
|
|
242
|
+
}
|
|
243
|
+
function assertSafeParentDirectories(file) {
|
|
244
|
+
if (!file || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(file)) {
|
|
245
|
+
throw new Error("Refusing to write Muse file inside symlinked or non-directory parent");
|
|
246
|
+
}
|
|
247
|
+
const parent = dirname(isAbsolute(file) ? file : `${process.cwd()}${sep}${file}`);
|
|
248
|
+
const parts = parent.split(sep);
|
|
249
|
+
for (let i = 1;i <= parts.length; i++) {
|
|
250
|
+
const dir = parts.slice(0, i).join(sep) || sep;
|
|
251
|
+
try {
|
|
252
|
+
const st = lstatSync(dir);
|
|
253
|
+
const systemLink = process.platform === "darwin" && ["/var", "/tmp", "/etc"].includes(dir) && st.isSymbolicLink() && realpathSync(dir) === `/private${dir}` && !lstatSync("/private").isSymbolicLink() && lstatSync("/private").isDirectory() && !lstatSync(`/private${dir}`).isSymbolicLink() && lstatSync(`/private${dir}`).isDirectory();
|
|
254
|
+
if (!systemLink && st.isSymbolicLink() || !st.isDirectory() && !systemLink) {
|
|
255
|
+
throw new Error("Refusing to write Muse file inside symlinked or non-directory parent");
|
|
256
|
+
}
|
|
257
|
+
} catch (err) {
|
|
258
|
+
if (err?.code !== "ENOENT")
|
|
259
|
+
throw err;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
function validateEndpointUrl(raw, kind) {
|
|
264
|
+
if (raw !== raw.trim() || /["<>\\\x00-\x20\x7f-\x9f\u2028\u2029]/.test(raw)) {
|
|
265
|
+
throw new Error(`Invalid Muse ${kind} URL`);
|
|
266
|
+
}
|
|
267
|
+
const trimmed = raw;
|
|
268
|
+
let parsed;
|
|
269
|
+
try {
|
|
270
|
+
parsed = new URL(trimmed);
|
|
271
|
+
} catch {
|
|
272
|
+
throw new Error(`Invalid Muse ${kind} URL`);
|
|
273
|
+
}
|
|
274
|
+
if (isUnsafeEndpointHost(parsed.hostname)) {
|
|
275
|
+
throw new Error(`Unsafe Muse ${kind} URL host`);
|
|
276
|
+
}
|
|
277
|
+
if (parsed.port === "0" || parsed.search || parsed.hash || raw.includes("?") || raw.includes("#")) {
|
|
278
|
+
throw new Error(`Invalid Muse ${kind} URL port/query/hash`);
|
|
279
|
+
}
|
|
280
|
+
if (parsed.username || parsed.password) {
|
|
281
|
+
throw new Error(`Embedded credentials are not allowed in Muse ${kind} URL`);
|
|
282
|
+
}
|
|
283
|
+
if (kind === "ws") {
|
|
284
|
+
if (parsed.protocol !== "wss:" && parsed.protocol !== "ws:") {
|
|
285
|
+
throw new Error(`Invalid Muse ws URL protocol: ${parsed.protocol}`);
|
|
286
|
+
}
|
|
287
|
+
if (parsed.protocol === "ws:" && !isLoopbackHost(parsed.hostname)) {
|
|
288
|
+
throw new Error("Remote Muse ws URL must use wss://");
|
|
289
|
+
}
|
|
290
|
+
} else {
|
|
291
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
|
|
292
|
+
throw new Error(`Invalid Muse rest URL protocol: ${parsed.protocol}`);
|
|
293
|
+
}
|
|
294
|
+
if (parsed.protocol === "http:" && !isLoopbackHost(parsed.hostname)) {
|
|
295
|
+
throw new Error("Remote Muse rest URL must use https://");
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
return trimmed;
|
|
299
|
+
}
|
|
300
|
+
function redact(value) {
|
|
301
|
+
if (!value)
|
|
302
|
+
return "(missing)";
|
|
303
|
+
if (value.length <= 4)
|
|
304
|
+
return "****";
|
|
305
|
+
return `${value.slice(0, 2)}****${value.slice(-2)}`;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// muse/src/wake.ts
|
|
309
|
+
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
310
|
+
import { appendFileSync, chmodSync, copyFileSync, lstatSync as lstatSync2, mkdirSync, readFileSync as readFileSync2, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
311
|
+
import { dirname as dirname2 } from "node:path";
|
|
312
|
+
var WAKE_SIG_HEADER = "x-agentschat-signature";
|
|
313
|
+
var WAKE_CONTENT_MAX = 500;
|
|
314
|
+
function redactSecrets(text) {
|
|
315
|
+
return text.replace(/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----[\s\S]*?(?:-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----|$)/g, "[redacted]").replace(/\b(https?:\/\/)([^/\s@]*@)/gi, "$1[redacted]@").replace(/\b(?:Bearer|Basic)\s+[^\s"'<>\\]+/gi, "[redacted]").replace(/(?:ac_|agent_key_|mcp_(?:at|rt|code)_|sk-|sk_|rk_(?:live|test)_|gh[pousr]_|github_pat_|glpat-|xox[baprs]-|hf_|npm_|mr_|whsec_|AIza)[A-Za-z0-9_-]+/g, "[redacted]").replace(/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, "[redacted]").replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "[redacted]");
|
|
316
|
+
}
|
|
317
|
+
function sanitizeMuseText(text) {
|
|
318
|
+
return redactSecrets(redactSecrets(text).replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, ""));
|
|
319
|
+
}
|
|
320
|
+
function buildWakePayload(msg, opts = {}) {
|
|
321
|
+
const clean = (value, cap = 128) => typeof value === "string" ? sanitizeMuseText(value).slice(0, cap) : undefined;
|
|
322
|
+
const targetSessionId = clean(opts.targetSessionId);
|
|
323
|
+
return {
|
|
324
|
+
type: clean(msg.type, 64) ?? "message",
|
|
325
|
+
channel_id: clean(msg.channel_id),
|
|
326
|
+
message_id: clean(msg.id, 256),
|
|
327
|
+
sender_id: clean(msg.sender_id),
|
|
328
|
+
content: clean(msg.content, WAKE_CONTENT_MAX),
|
|
329
|
+
mentioned_ids: Array.isArray(msg.mentioned_ids) ? msg.mentioned_ids.filter((x) => typeof x === "string").slice(0, 256).map((x) => clean(x)) : undefined,
|
|
330
|
+
timestamp: clean(msg.timestamp, 64),
|
|
331
|
+
...targetSessionId ? { target_session_id: targetSessionId } : {}
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
function sanitizeWakeLogUrl(rawUrl) {
|
|
335
|
+
try {
|
|
336
|
+
const parsed = new URL(rawUrl);
|
|
337
|
+
parsed.username = "";
|
|
338
|
+
parsed.password = "";
|
|
339
|
+
parsed.search = "";
|
|
340
|
+
parsed.hash = "";
|
|
341
|
+
return parsed.toString();
|
|
342
|
+
} catch {
|
|
343
|
+
return redactSecrets(rawUrl.split(/[?#]/)[0] ?? "[invalid-url]");
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
function signWakeBody(body, secret) {
|
|
347
|
+
return createHmac("sha256", secret).update(body, "utf8").digest("hex");
|
|
348
|
+
}
|
|
349
|
+
function isUnsafeWakeHost(hostname) {
|
|
350
|
+
if (isUnsafeEndpointHost(hostname))
|
|
351
|
+
return true;
|
|
352
|
+
const host = hostname.toLowerCase().replace(/\.$/, "");
|
|
353
|
+
if (["metadata.google.internal", "metadata.goog"].includes(host))
|
|
354
|
+
return true;
|
|
355
|
+
const unsafeV4 = (ip) => {
|
|
356
|
+
const [a, b] = ip.split(".").map(Number);
|
|
357
|
+
return a === 0 || a === 10 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a >= 224;
|
|
358
|
+
};
|
|
359
|
+
if (/^\d+\.\d+\.\d+\.\d+$/.test(host))
|
|
360
|
+
return unsafeV4(host);
|
|
361
|
+
if (host.startsWith("[")) {
|
|
362
|
+
const address = host.slice(1, -1);
|
|
363
|
+
const [left, right = ""] = address.split("::");
|
|
364
|
+
const head = left ? left.split(":") : [];
|
|
365
|
+
const tail = right ? right.split(":") : [];
|
|
366
|
+
const words = address.includes("::") ? [...head, ...Array(8 - head.length - tail.length).fill("0"), ...tail].map((x) => parseInt(x, 16)) : head.map((x) => parseInt(x, 16));
|
|
367
|
+
if (words.length !== 8)
|
|
368
|
+
return true;
|
|
369
|
+
const mapped = words.slice(0, 5).every((x) => x === 0) && words[5] === 65535 || words.slice(0, 4).every((x) => x === 0) && words[4] === 65535 && words[5] === 0;
|
|
370
|
+
if (mapped)
|
|
371
|
+
return unsafeV4(`${words[6] >> 8}.${words[6] & 255}.${words[7] >> 8}.${words[7] & 255}`);
|
|
372
|
+
return words.every((x) => x === 0) || (words[0] & 65472) === 65152 || (words[0] & 65024) === 64512 || (words[0] & 65280) === 65280;
|
|
373
|
+
}
|
|
374
|
+
return false;
|
|
375
|
+
}
|
|
376
|
+
async function fireWake(msg, cfg) {
|
|
377
|
+
const log = (text) => cfg.logger?.(sanitizeMuseText(text));
|
|
378
|
+
const url = (cfg.url ?? "").trim();
|
|
379
|
+
if (!url)
|
|
380
|
+
return;
|
|
381
|
+
const safeLogUrl = sanitizeWakeLogUrl(url);
|
|
382
|
+
let parsedUrl;
|
|
383
|
+
try {
|
|
384
|
+
parsedUrl = new URL(url);
|
|
385
|
+
} catch {
|
|
386
|
+
log(`[muse-agentchat] wake POST rejected invalid URL: ${safeLogUrl}`);
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
|
|
390
|
+
log(`[muse-agentchat] wake POST rejected unsupported protocol: ${parsedUrl.protocol}`);
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
if (parsedUrl.port === "0" || parsedUrl.username || parsedUrl.password || isUnsafeWakeHost(parsedUrl.hostname)) {
|
|
394
|
+
log(`[muse-agentchat] wake POST rejected unsafe URL: ${safeLogUrl}`);
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
const timeoutMs = typeof cfg.timeoutMs === "number" && Number.isFinite(cfg.timeoutMs) && cfg.timeoutMs >= 1 ? Math.min(cfg.timeoutMs, 60000) : 5000;
|
|
398
|
+
const payload = buildWakePayload(msg, { targetSessionId: cfg.targetSessionId });
|
|
399
|
+
if (!payload.timestamp)
|
|
400
|
+
payload.timestamp = new Date().toISOString();
|
|
401
|
+
const body = JSON.stringify(payload);
|
|
402
|
+
const headers = { "Content-Type": "application/json" };
|
|
403
|
+
if (cfg.secret)
|
|
404
|
+
headers[WAKE_SIG_HEADER] = signWakeBody(body, cfg.secret);
|
|
405
|
+
const doPost = async () => {
|
|
406
|
+
const f = cfg.fetchImpl ?? fetch;
|
|
407
|
+
const ctrl = new AbortController;
|
|
408
|
+
const t = setTimeout(() => ctrl.abort(), timeoutMs);
|
|
409
|
+
t.unref?.();
|
|
410
|
+
try {
|
|
411
|
+
const res = await f(url, { method: "POST", headers, body, redirect: "error", signal: ctrl.signal });
|
|
412
|
+
try {
|
|
413
|
+
await res?.body?.cancel?.();
|
|
414
|
+
} catch {}
|
|
415
|
+
if (!res.ok)
|
|
416
|
+
log(`[muse-agentchat] wake POST ${safeLogUrl} → HTTP ${res.status}`);
|
|
417
|
+
} finally {
|
|
418
|
+
clearTimeout(t);
|
|
419
|
+
}
|
|
420
|
+
};
|
|
421
|
+
try {
|
|
422
|
+
await doPost();
|
|
423
|
+
} catch (e) {
|
|
424
|
+
try {
|
|
425
|
+
await doPost();
|
|
426
|
+
} catch (e2) {
|
|
427
|
+
log(`[muse-agentchat] wake POST ${safeLogUrl} failed: ${redactSecrets(String(e2))}`);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
var MAX_WAKE_QUEUE_LINES = 500;
|
|
432
|
+
var MAX_WAKE_QUEUE_BYTES = 16 * 1024 * 1024;
|
|
433
|
+
var wakeTmpSeq = 0;
|
|
434
|
+
function atomicReplaceWakeFile(tmp, queueFile, fsOps) {
|
|
435
|
+
const renameFn = fsOps?.renameSync ?? renameSync;
|
|
436
|
+
const copyFn = fsOps?.copyFileSync ?? copyFileSync;
|
|
437
|
+
const unlinkFn = fsOps?.unlinkSync ?? unlinkSync;
|
|
438
|
+
assertSafeParentDirectories(queueFile);
|
|
439
|
+
try {
|
|
440
|
+
const st = lstatSync2(queueFile);
|
|
441
|
+
if (st.isSymbolicLink() || !st.isFile()) {
|
|
442
|
+
throw new Error("Refusing to use symlink or non-regular file for Muse wake queue");
|
|
443
|
+
}
|
|
444
|
+
} catch (err) {
|
|
445
|
+
if (err?.code !== "ENOENT")
|
|
446
|
+
throw err;
|
|
447
|
+
}
|
|
448
|
+
try {
|
|
449
|
+
renameFn(tmp, queueFile);
|
|
450
|
+
} catch (renameErr) {
|
|
451
|
+
const code = renameErr?.code;
|
|
452
|
+
if (code === "EPERM" || code === "EACCES") {
|
|
453
|
+
assertSafeParentDirectories(queueFile);
|
|
454
|
+
try {
|
|
455
|
+
const st = lstatSync2(queueFile);
|
|
456
|
+
if (st.isSymbolicLink() || !st.isFile()) {
|
|
457
|
+
throw new Error("Refusing to use symlink or non-regular file for Muse wake queue");
|
|
458
|
+
}
|
|
459
|
+
} catch (err) {
|
|
460
|
+
if (err?.code !== "ENOENT")
|
|
461
|
+
throw err;
|
|
462
|
+
}
|
|
463
|
+
copyFn(tmp, queueFile);
|
|
464
|
+
if (process.platform !== "win32") {
|
|
465
|
+
try {
|
|
466
|
+
chmodSync(queueFile, 384);
|
|
467
|
+
} catch {}
|
|
468
|
+
}
|
|
469
|
+
try {
|
|
470
|
+
unlinkFn(tmp);
|
|
471
|
+
} catch {}
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
throw renameErr;
|
|
144
475
|
}
|
|
145
476
|
}
|
|
477
|
+
function appendWakeQueue(queueFile, payload, maxLines = MAX_WAKE_QUEUE_LINES, fsOps) {
|
|
478
|
+
const dir = dirname2(queueFile);
|
|
479
|
+
assertSafeParentDirectories(queueFile);
|
|
480
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
481
|
+
assertSafeParentDirectories(queueFile);
|
|
482
|
+
const line = JSON.stringify(payload);
|
|
483
|
+
let existingLines = [];
|
|
484
|
+
let existedBefore = false;
|
|
485
|
+
try {
|
|
486
|
+
const st = lstatSync2(queueFile);
|
|
487
|
+
if (st.isSymbolicLink() || !st.isFile()) {
|
|
488
|
+
throw new Error("Refusing to use symlink or non-regular file for Muse wake queue");
|
|
489
|
+
}
|
|
490
|
+
if (st.size > MAX_WAKE_QUEUE_BYTES) {
|
|
491
|
+
throw new Error("Muse wake queue exceeds maximum size limit");
|
|
492
|
+
}
|
|
493
|
+
existedBefore = true;
|
|
494
|
+
} catch (err) {
|
|
495
|
+
if (err?.code !== "ENOENT")
|
|
496
|
+
throw err;
|
|
497
|
+
}
|
|
498
|
+
if (existedBefore) {
|
|
499
|
+
const existing = readFileSync2(queueFile, "utf8");
|
|
500
|
+
existingLines = existing.split(`
|
|
501
|
+
`).filter((l) => l.length > 0);
|
|
502
|
+
if (payload.message_id && existingLines.some((l) => {
|
|
503
|
+
try {
|
|
504
|
+
return JSON.parse(l).message_id === payload.message_id;
|
|
505
|
+
} catch {
|
|
506
|
+
return false;
|
|
507
|
+
}
|
|
508
|
+
})) {
|
|
509
|
+
return false;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
const cap = Number.isFinite(maxLines) ? Math.max(1, Math.floor(maxLines)) : MAX_WAKE_QUEUE_LINES;
|
|
513
|
+
if (existingLines.length >= cap) {
|
|
514
|
+
const kept = [...cap === 1 ? [] : existingLines.slice(-(cap - 1)), line];
|
|
515
|
+
const tmp = `${queueFile}.${process.pid}.${Date.now()}.${++wakeTmpSeq}.${randomBytes(6).toString("hex")}.tmp`;
|
|
516
|
+
try {
|
|
517
|
+
assertSafeParentDirectories(queueFile);
|
|
518
|
+
writeFileSync(tmp, `${kept.join(`
|
|
519
|
+
`)}
|
|
520
|
+
`, { mode: 384, flag: "wx" });
|
|
521
|
+
atomicReplaceWakeFile(tmp, queueFile, fsOps);
|
|
522
|
+
} catch (err) {
|
|
523
|
+
try {
|
|
524
|
+
unlinkSync(tmp);
|
|
525
|
+
} catch {}
|
|
526
|
+
throw err;
|
|
527
|
+
}
|
|
528
|
+
return true;
|
|
529
|
+
}
|
|
530
|
+
if (!existedBefore) {
|
|
531
|
+
try {
|
|
532
|
+
writeFileSync(queueFile, `${line}
|
|
533
|
+
`, { mode: 384, flag: "wx" });
|
|
534
|
+
if (process.platform !== "win32") {
|
|
535
|
+
try {
|
|
536
|
+
chmodSync(queueFile, 384);
|
|
537
|
+
} catch {}
|
|
538
|
+
}
|
|
539
|
+
return true;
|
|
540
|
+
} catch (err) {
|
|
541
|
+
if (err?.code !== "EEXIST")
|
|
542
|
+
throw err;
|
|
543
|
+
const st = lstatSync2(queueFile);
|
|
544
|
+
if (st.isSymbolicLink() || !st.isFile()) {
|
|
545
|
+
throw new Error("Refusing to use symlink or non-regular file for Muse wake queue");
|
|
546
|
+
}
|
|
547
|
+
if (st.size > MAX_WAKE_QUEUE_BYTES) {
|
|
548
|
+
throw new Error("Muse wake queue exceeds maximum size limit");
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
assertSafeParentDirectories(queueFile);
|
|
553
|
+
const finalTarget = lstatSync2(queueFile);
|
|
554
|
+
if (finalTarget.isSymbolicLink() || !finalTarget.isFile()) {
|
|
555
|
+
throw new Error("Refusing to use symlink or non-regular file for Muse wake queue");
|
|
556
|
+
}
|
|
557
|
+
appendFileSync(queueFile, `${line}
|
|
558
|
+
`, { mode: 384 });
|
|
559
|
+
return true;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
// src/reconnect.ts
|
|
563
|
+
function safeUnitRand(rand) {
|
|
564
|
+
let r;
|
|
565
|
+
try {
|
|
566
|
+
r = rand();
|
|
567
|
+
} catch {
|
|
568
|
+
return 0;
|
|
569
|
+
}
|
|
570
|
+
if (!Number.isFinite(r) || r <= 0)
|
|
571
|
+
return 0;
|
|
572
|
+
return r >= 1 ? 0.999999 : r;
|
|
573
|
+
}
|
|
574
|
+
function computePleaseReconnectDelay(jitterMs, rand = Math.random) {
|
|
575
|
+
const maxJitter = typeof jitterMs === "number" && Number.isFinite(jitterMs) && jitterMs > 0 ? Math.min(Math.floor(jitterMs), 1e4) : 2000;
|
|
576
|
+
return 200 + Math.floor(safeUnitRand(rand) * maxJitter);
|
|
577
|
+
}
|
|
578
|
+
function resolveDrainReconnectDelay(frame, rand = Math.random) {
|
|
579
|
+
const safeFrame = frame && typeof frame === "object" && !Array.isArray(frame) && !Object.prototype.hasOwnProperty.call(frame, "__proto__") ? frame : null;
|
|
580
|
+
return computePleaseReconnectDelay(safeFrame?.jitter_ms ?? safeFrame?.within_ms, rand);
|
|
581
|
+
}
|
|
146
582
|
|
|
147
583
|
// muse/src/client.ts
|
|
584
|
+
var MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
|
|
585
|
+
var MAX_JOINED_CHANNELS = 256;
|
|
586
|
+
var MAX_WS_FRAME_BYTES = 1048576;
|
|
587
|
+
function rawFrameByteLength(data) {
|
|
588
|
+
if (typeof data === "string") {
|
|
589
|
+
if (data.length > MAX_WS_FRAME_BYTES)
|
|
590
|
+
return data.length;
|
|
591
|
+
if (data.length * 3 <= MAX_WS_FRAME_BYTES)
|
|
592
|
+
return data.length;
|
|
593
|
+
return Buffer.byteLength(data, "utf8");
|
|
594
|
+
}
|
|
595
|
+
if (data instanceof ArrayBuffer)
|
|
596
|
+
return data.byteLength;
|
|
597
|
+
if (ArrayBuffer.isView(data))
|
|
598
|
+
return data.byteLength;
|
|
599
|
+
return 0;
|
|
600
|
+
}
|
|
601
|
+
function safeDelayMs(value, fallback, min = 0) {
|
|
602
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < min)
|
|
603
|
+
return fallback;
|
|
604
|
+
return Math.min(value, MAX_TIMER_DELAY_MS);
|
|
605
|
+
}
|
|
606
|
+
function normalizeChannelId(raw) {
|
|
607
|
+
if (typeof raw !== "string")
|
|
608
|
+
return null;
|
|
609
|
+
const trimmed = raw.trim();
|
|
610
|
+
if (!trimmed || trimmed.length > 128 || /[\/\\\x00-\x20\x7f-\x9f\u2028\u2029]/.test(trimmed) || [".", "..", "__proto__", "constructor", "prototype"].includes(trimmed.toLowerCase()))
|
|
611
|
+
return null;
|
|
612
|
+
return trimmed;
|
|
613
|
+
}
|
|
614
|
+
|
|
148
615
|
class MuseAgentChatClient {
|
|
149
616
|
ws = null;
|
|
150
617
|
sessionId = null;
|
|
151
618
|
heartbeatTimer = null;
|
|
152
619
|
reconnectTimer = null;
|
|
620
|
+
connectTimer = null;
|
|
621
|
+
nextReconnectDelayOverrideMs = null;
|
|
153
622
|
messageHandlers = [];
|
|
154
623
|
errorHandlers = [];
|
|
624
|
+
joinedChannels = new Set;
|
|
625
|
+
sessionJoined = new Set;
|
|
155
626
|
connectResolve = null;
|
|
156
627
|
connectReject = null;
|
|
157
628
|
lifecycleResolve = null;
|
|
@@ -164,25 +635,58 @@ class MuseAgentChatClient {
|
|
|
164
635
|
token;
|
|
165
636
|
capabilities;
|
|
166
637
|
heartbeatIntervalMs;
|
|
638
|
+
connectTimeoutMs;
|
|
167
639
|
reconnect;
|
|
168
640
|
initialReconnectDelayMs;
|
|
169
641
|
maxReconnectDelayMs;
|
|
170
642
|
onDebug;
|
|
171
643
|
onReconnect;
|
|
172
644
|
constructor(options) {
|
|
173
|
-
this.url = options.url;
|
|
645
|
+
this.url = validateEndpointUrl(options.url, "ws");
|
|
174
646
|
this.agentId = options.agentId;
|
|
175
647
|
this.token = options.token;
|
|
176
648
|
this.capabilities = options.capabilities ?? ["chat"];
|
|
177
|
-
this.heartbeatIntervalMs = options.heartbeatIntervalMs
|
|
649
|
+
this.heartbeatIntervalMs = safeDelayMs(options.heartbeatIntervalMs, 30000, 100);
|
|
650
|
+
this.connectTimeoutMs = safeDelayMs(options.connectTimeoutMs, 15000, 0);
|
|
178
651
|
this.reconnect = options.reconnect ?? true;
|
|
179
|
-
this.initialReconnectDelayMs = options.initialReconnectDelayMs
|
|
180
|
-
this.maxReconnectDelayMs = options.maxReconnectDelayMs
|
|
652
|
+
this.initialReconnectDelayMs = safeDelayMs(options.initialReconnectDelayMs, 1000, 0);
|
|
653
|
+
this.maxReconnectDelayMs = safeDelayMs(options.maxReconnectDelayMs, 60000, 0);
|
|
181
654
|
this.onDebug = options.onDebug;
|
|
182
655
|
this.onReconnect = options.onReconnect;
|
|
183
656
|
}
|
|
657
|
+
clearConnectTimer() {
|
|
658
|
+
if (this.connectTimer) {
|
|
659
|
+
clearTimeout(this.connectTimer);
|
|
660
|
+
this.connectTimer = null;
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
emitError(err) {
|
|
664
|
+
for (const h of this.errorHandlers) {
|
|
665
|
+
try {
|
|
666
|
+
h(err);
|
|
667
|
+
} catch {}
|
|
668
|
+
}
|
|
669
|
+
}
|
|
184
670
|
connect() {
|
|
185
671
|
return new Promise((resolve, reject) => {
|
|
672
|
+
this.clearConnectTimer();
|
|
673
|
+
if (this.reconnectTimer) {
|
|
674
|
+
clearTimeout(this.reconnectTimer);
|
|
675
|
+
this.reconnectTimer = null;
|
|
676
|
+
}
|
|
677
|
+
if (this.heartbeatTimer) {
|
|
678
|
+
clearInterval(this.heartbeatTimer);
|
|
679
|
+
this.heartbeatTimer = null;
|
|
680
|
+
}
|
|
681
|
+
const prevWs = this.ws;
|
|
682
|
+
this.ws = null;
|
|
683
|
+
this.sessionId = null;
|
|
684
|
+
this.sessionJoined.clear();
|
|
685
|
+
if (prevWs) {
|
|
686
|
+
try {
|
|
687
|
+
prevWs.close();
|
|
688
|
+
} catch {}
|
|
689
|
+
}
|
|
186
690
|
this.connectSettled = false;
|
|
187
691
|
this.explicitlyDisconnected = false;
|
|
188
692
|
this.reconnectAttempt = 0;
|
|
@@ -208,16 +712,28 @@ class MuseAgentChatClient {
|
|
|
208
712
|
}
|
|
209
713
|
disconnect() {
|
|
210
714
|
this.explicitlyDisconnected = true;
|
|
715
|
+
this.clearConnectTimer();
|
|
211
716
|
if (this.reconnectTimer)
|
|
212
717
|
clearTimeout(this.reconnectTimer);
|
|
213
718
|
if (this.heartbeatTimer)
|
|
214
719
|
clearInterval(this.heartbeatTimer);
|
|
215
720
|
this.reconnectTimer = null;
|
|
216
721
|
this.heartbeatTimer = null;
|
|
217
|
-
this.
|
|
722
|
+
if (!this.connectSettled) {
|
|
723
|
+
this.connectSettled = true;
|
|
724
|
+
this.connectReject?.(new Error("Disconnected before authentication completed"));
|
|
725
|
+
}
|
|
726
|
+
this.connectResolve = null;
|
|
727
|
+
this.connectReject = null;
|
|
728
|
+
this.lifecycleResolve?.();
|
|
729
|
+
this.lifecycleResolve = null;
|
|
730
|
+
const prev = this.ws;
|
|
218
731
|
this.ws = null;
|
|
219
732
|
this.sessionId = null;
|
|
220
|
-
this.
|
|
733
|
+
this.sessionJoined.clear();
|
|
734
|
+
try {
|
|
735
|
+
prev?.close();
|
|
736
|
+
} catch {}
|
|
221
737
|
}
|
|
222
738
|
get isConnected() {
|
|
223
739
|
return this.ws?.readyState === WebSocket.OPEN && this.sessionId !== null;
|
|
@@ -232,60 +748,149 @@ class MuseAgentChatClient {
|
|
|
232
748
|
this.errorHandlers.push(handler);
|
|
233
749
|
}
|
|
234
750
|
joinChannel(channelId) {
|
|
235
|
-
|
|
751
|
+
const clean = normalizeChannelId(channelId);
|
|
752
|
+
if (!clean)
|
|
753
|
+
return;
|
|
754
|
+
if (!this.joinedChannels.has(clean) && this.joinedChannels.size >= MAX_JOINED_CHANNELS)
|
|
755
|
+
return;
|
|
756
|
+
this.joinedChannels.add(clean);
|
|
757
|
+
this.sessionJoined.add(clean);
|
|
758
|
+
this.send({ type: "join_channel", channel_id: clean, agent_id: this.agentId });
|
|
236
759
|
}
|
|
237
760
|
leaveChannel(channelId) {
|
|
238
|
-
|
|
761
|
+
const clean = normalizeChannelId(channelId);
|
|
762
|
+
if (!clean)
|
|
763
|
+
return;
|
|
764
|
+
this.joinedChannels.delete(clean);
|
|
765
|
+
this.sessionJoined.delete(clean);
|
|
766
|
+
this.send({ type: "leave_channel", channel_id: clean, agent_id: this.agentId });
|
|
239
767
|
}
|
|
240
|
-
sendMessage(channelId, content, contentType = "text") {
|
|
768
|
+
sendMessage(channelId, content, contentType = "text", replyTo) {
|
|
769
|
+
const clean = normalizeChannelId(channelId);
|
|
770
|
+
if (!clean || replyTo !== undefined && (typeof replyTo !== "string" || replyTo.length > 256 || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(replyTo)))
|
|
771
|
+
return;
|
|
241
772
|
this.send({
|
|
242
773
|
type: "message",
|
|
243
774
|
id: crypto.randomUUID(),
|
|
244
|
-
channel_id:
|
|
775
|
+
channel_id: clean,
|
|
245
776
|
sender_id: this.agentId,
|
|
246
777
|
sender_type: "agent",
|
|
247
778
|
content,
|
|
248
779
|
content_type: contentType,
|
|
249
|
-
timestamp: new Date().toISOString()
|
|
780
|
+
timestamp: new Date().toISOString(),
|
|
781
|
+
...replyTo ? { reply_to: replyTo } : {}
|
|
250
782
|
});
|
|
251
783
|
}
|
|
252
784
|
sendTyping(channelId) {
|
|
253
|
-
|
|
785
|
+
const clean = normalizeChannelId(channelId);
|
|
786
|
+
if (!clean)
|
|
787
|
+
return;
|
|
788
|
+
this.send({ type: "typing", channel_id: clean, sender_id: this.agentId, cross_pod: true });
|
|
254
789
|
}
|
|
255
790
|
debug(event, meta) {
|
|
256
791
|
this.onDebug?.(event, meta);
|
|
257
792
|
}
|
|
258
793
|
openSocket() {
|
|
259
794
|
this.debug("connect:start", { url: this.url, agentId: this.agentId });
|
|
795
|
+
this.clearConnectTimer();
|
|
796
|
+
this.sessionJoined.clear();
|
|
260
797
|
const ws = new WebSocket(this.url);
|
|
261
798
|
this.ws = ws;
|
|
799
|
+
if (this.connectTimeoutMs > 0) {
|
|
800
|
+
this.connectTimer = setTimeout(() => {
|
|
801
|
+
this.connectTimer = null;
|
|
802
|
+
if (this.ws !== ws)
|
|
803
|
+
return;
|
|
804
|
+
const err = new Error(`AgentsChat connect timed out after ${this.connectTimeoutMs}ms`);
|
|
805
|
+
if (!this.connectSettled) {
|
|
806
|
+
this.connectSettled = true;
|
|
807
|
+
this.explicitlyDisconnected = true;
|
|
808
|
+
try {
|
|
809
|
+
ws.close();
|
|
810
|
+
} catch {}
|
|
811
|
+
this.connectReject?.(err);
|
|
812
|
+
this.emitError(err);
|
|
813
|
+
} else if (this.sessionId === null) {
|
|
814
|
+
this.emitError(err);
|
|
815
|
+
try {
|
|
816
|
+
ws.close();
|
|
817
|
+
} catch {}
|
|
818
|
+
}
|
|
819
|
+
}, this.connectTimeoutMs);
|
|
820
|
+
this.connectTimer.unref?.();
|
|
821
|
+
}
|
|
262
822
|
ws.onopen = () => {
|
|
263
|
-
this.
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
823
|
+
if (this.ws !== ws)
|
|
824
|
+
return;
|
|
825
|
+
try {
|
|
826
|
+
this.send({
|
|
827
|
+
type: "auth",
|
|
828
|
+
agent_id: this.agentId,
|
|
829
|
+
token: this.token,
|
|
830
|
+
capabilities: this.capabilities
|
|
831
|
+
});
|
|
832
|
+
} catch (err) {
|
|
833
|
+
this.clearConnectTimer();
|
|
834
|
+
if (!this.connectSettled) {
|
|
835
|
+
this.connectSettled = true;
|
|
836
|
+
this.connectReject?.(err instanceof Error ? err : new Error(String(err)));
|
|
837
|
+
}
|
|
838
|
+
this.emitError(err instanceof Error ? err : new Error(String(err)));
|
|
839
|
+
try {
|
|
840
|
+
ws.close();
|
|
841
|
+
} catch {}
|
|
842
|
+
return;
|
|
843
|
+
}
|
|
269
844
|
if (this.heartbeatTimer)
|
|
270
845
|
clearInterval(this.heartbeatTimer);
|
|
271
846
|
this.heartbeatTimer = setInterval(() => {
|
|
272
|
-
this.
|
|
847
|
+
if (this.ws !== ws)
|
|
848
|
+
return;
|
|
849
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
850
|
+
try {
|
|
851
|
+
this.send({ type: "ping", timestamp: new Date().toISOString() });
|
|
852
|
+
} catch (err) {
|
|
853
|
+
this.emitError(err instanceof Error ? err : new Error(String(err)));
|
|
854
|
+
try {
|
|
855
|
+
ws.close();
|
|
856
|
+
} catch {}
|
|
857
|
+
}
|
|
858
|
+
}
|
|
273
859
|
}, this.heartbeatIntervalMs);
|
|
860
|
+
this.heartbeatTimer.unref?.();
|
|
861
|
+
};
|
|
862
|
+
ws.onmessage = (event) => {
|
|
863
|
+
if (this.ws !== ws)
|
|
864
|
+
return;
|
|
865
|
+
if (rawFrameByteLength(event.data) > MAX_WS_FRAME_BYTES)
|
|
866
|
+
return;
|
|
867
|
+
this.handleMessage(String(event.data));
|
|
274
868
|
};
|
|
275
|
-
ws.onmessage = (event) => this.handleMessage(String(event.data));
|
|
276
869
|
ws.onerror = () => {
|
|
870
|
+
if (this.ws !== ws)
|
|
871
|
+
return;
|
|
277
872
|
const err = new Error("WebSocket error");
|
|
278
873
|
if (!this.connectSettled) {
|
|
874
|
+
this.clearConnectTimer();
|
|
279
875
|
this.connectSettled = true;
|
|
280
876
|
this.connectReject?.(err);
|
|
281
877
|
}
|
|
282
|
-
this.
|
|
878
|
+
this.emitError(err);
|
|
283
879
|
};
|
|
284
880
|
ws.onclose = () => {
|
|
881
|
+
if (this.ws !== ws)
|
|
882
|
+
return;
|
|
883
|
+
this.clearConnectTimer();
|
|
285
884
|
if (this.heartbeatTimer)
|
|
286
885
|
clearInterval(this.heartbeatTimer);
|
|
287
886
|
this.heartbeatTimer = null;
|
|
288
887
|
this.sessionId = null;
|
|
888
|
+
this.sessionJoined.clear();
|
|
889
|
+
if (!this.connectSettled && !this.reconnect) {
|
|
890
|
+
this.clearConnectTimer();
|
|
891
|
+
this.connectSettled = true;
|
|
892
|
+
this.connectReject?.(new Error("WebSocket closed before authentication"));
|
|
893
|
+
}
|
|
289
894
|
if (this.explicitlyDisconnected) {
|
|
290
895
|
this.lifecycleResolve?.();
|
|
291
896
|
return;
|
|
@@ -294,11 +899,19 @@ class MuseAgentChatClient {
|
|
|
294
899
|
this.lifecycleResolve?.();
|
|
295
900
|
return;
|
|
296
901
|
}
|
|
297
|
-
|
|
298
|
-
this.
|
|
902
|
+
let delay;
|
|
903
|
+
if (this.nextReconnectDelayOverrideMs !== null) {
|
|
904
|
+
delay = this.nextReconnectDelayOverrideMs;
|
|
905
|
+
this.nextReconnectDelayOverrideMs = null;
|
|
906
|
+
} else {
|
|
907
|
+
const exp = Math.min(Math.max(0, this.reconnectAttempt), 30);
|
|
908
|
+
delay = Math.min(this.initialReconnectDelayMs * 2 ** exp, this.maxReconnectDelayMs);
|
|
909
|
+
this.reconnectAttempt += 1;
|
|
910
|
+
}
|
|
299
911
|
this.isReconnecting = true;
|
|
300
912
|
this.debug("reconnect:scheduled", { delayMs: delay, attempt: this.reconnectAttempt });
|
|
301
913
|
this.reconnectTimer = setTimeout(() => this.openSocket(), delay);
|
|
914
|
+
this.reconnectTimer.unref?.();
|
|
302
915
|
};
|
|
303
916
|
}
|
|
304
917
|
send(payload) {
|
|
@@ -308,13 +921,20 @@ class MuseAgentChatClient {
|
|
|
308
921
|
this.ws.send(JSON.stringify(payload));
|
|
309
922
|
}
|
|
310
923
|
handleMessage(raw) {
|
|
311
|
-
|
|
924
|
+
if (Buffer.byteLength(raw, "utf8") > 1048576)
|
|
925
|
+
return;
|
|
926
|
+
let parsed;
|
|
312
927
|
try {
|
|
313
|
-
|
|
928
|
+
parsed = JSON.parse(raw);
|
|
314
929
|
} catch {
|
|
315
930
|
return;
|
|
316
931
|
}
|
|
932
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.hasOwn(parsed, "__proto__")) {
|
|
933
|
+
return;
|
|
934
|
+
}
|
|
935
|
+
const msg = parsed;
|
|
317
936
|
if (msg.type === "auth_ok") {
|
|
937
|
+
this.clearConnectTimer();
|
|
318
938
|
this.sessionId = typeof msg.session_id === "string" ? msg.session_id : null;
|
|
319
939
|
this.reconnectAttempt = 0;
|
|
320
940
|
const wasReconnect = this.isReconnecting;
|
|
@@ -324,25 +944,49 @@ class MuseAgentChatClient {
|
|
|
324
944
|
this.connectResolve?.();
|
|
325
945
|
} else if (wasReconnect) {
|
|
326
946
|
this.onReconnect?.();
|
|
947
|
+
for (const ch of this.joinedChannels) {
|
|
948
|
+
if (!this.sessionJoined.has(ch) && this.ws?.readyState === WebSocket.OPEN) {
|
|
949
|
+
this.joinChannel(ch);
|
|
950
|
+
}
|
|
951
|
+
}
|
|
327
952
|
}
|
|
328
953
|
return;
|
|
329
954
|
}
|
|
330
|
-
if (msg.type === "error") {
|
|
331
|
-
const
|
|
955
|
+
if (msg.type === "auth_error" || msg.type === "error") {
|
|
956
|
+
const text = typeof msg.error === "string" ? msg.error : typeof msg.message === "string" ? msg.message : msg.type === "auth_error" ? "AgentsChat authentication error" : "AgentsChat error";
|
|
957
|
+
const err = new Error(sanitizeMuseText(text).slice(0, 1024));
|
|
958
|
+
if (msg.type === "auth_error") {
|
|
959
|
+
this.explicitlyDisconnected = true;
|
|
960
|
+
try {
|
|
961
|
+
this.ws?.close();
|
|
962
|
+
} catch {}
|
|
963
|
+
}
|
|
332
964
|
if (!this.connectSettled) {
|
|
965
|
+
this.clearConnectTimer();
|
|
333
966
|
this.connectSettled = true;
|
|
334
967
|
this.connectReject?.(err);
|
|
335
968
|
}
|
|
336
|
-
this.
|
|
969
|
+
this.emitError(err);
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
if (msg.type === "please_reconnect" || msg.type === "shard_moved") {
|
|
973
|
+
this.nextReconnectDelayOverrideMs = resolveDrainReconnectDelay(msg);
|
|
974
|
+
this.reconnectAttempt = 0;
|
|
975
|
+
try {
|
|
976
|
+
this.ws?.close();
|
|
977
|
+
} catch {}
|
|
337
978
|
return;
|
|
338
979
|
}
|
|
339
980
|
if (msg.type === "pong")
|
|
340
981
|
return;
|
|
341
982
|
if (msg.type === "channel_created" && typeof msg.channel_id === "string" && msg.channel_id) {
|
|
342
|
-
this.
|
|
983
|
+
if (this.ws?.readyState === WebSocket.OPEN)
|
|
984
|
+
this.joinChannel(msg.channel_id);
|
|
343
985
|
return;
|
|
344
986
|
}
|
|
345
|
-
if (msg.type === "message") {
|
|
987
|
+
if (msg.type === "message" || msg.type === "thread_reply") {
|
|
988
|
+
if (msg.content === "__typing__")
|
|
989
|
+
return;
|
|
346
990
|
const chat = {
|
|
347
991
|
id: String(msg.id ?? ""),
|
|
348
992
|
channel_id: String(msg.channel_id ?? ""),
|
|
@@ -352,179 +996,390 @@ class MuseAgentChatClient {
|
|
|
352
996
|
content_type: msg.content_type ?? "text",
|
|
353
997
|
timestamp: String(msg.timestamp ?? new Date().toISOString()),
|
|
354
998
|
channel_type: msg.channel_type,
|
|
355
|
-
thread_id: typeof msg.thread_id === "string" ? msg.thread_id : undefined
|
|
999
|
+
thread_id: typeof msg.thread_id === "string" ? msg.thread_id : typeof msg.parent_id === "string" ? msg.parent_id : undefined
|
|
356
1000
|
};
|
|
357
|
-
for (const h of this.messageHandlers)
|
|
358
|
-
|
|
1001
|
+
for (const h of this.messageHandlers) {
|
|
1002
|
+
try {
|
|
1003
|
+
Promise.resolve(h(chat)).catch((err) => {
|
|
1004
|
+
this.emitError(err instanceof Error ? err : new Error(String(err)));
|
|
1005
|
+
});
|
|
1006
|
+
} catch (err) {
|
|
1007
|
+
this.emitError(err instanceof Error ? err : new Error(String(err)));
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
359
1010
|
}
|
|
360
1011
|
}
|
|
361
1012
|
}
|
|
362
1013
|
|
|
363
|
-
//
|
|
364
|
-
import {
|
|
365
|
-
import {
|
|
366
|
-
|
|
367
|
-
function redact(value) {
|
|
368
|
-
if (!value)
|
|
369
|
-
return "(missing)";
|
|
370
|
-
if (value.length <= 4)
|
|
371
|
-
return "****";
|
|
372
|
-
return `${value.slice(0, 2)}****${value.slice(-2)}`;
|
|
373
|
-
}
|
|
1014
|
+
// src/session-route.ts
|
|
1015
|
+
import { lstatSync as lstatSync4, readFileSync as readFileSync4, readlinkSync as readlinkSync2, realpathSync as realpathSync3 } from "node:fs";
|
|
1016
|
+
import { homedir as homedir2 } from "node:os";
|
|
1017
|
+
import { dirname as dirname3, isAbsolute as isAbsolute3, join as join3, parse as parse2, resolve as resolve2, sep as sep2 } from "node:path";
|
|
374
1018
|
|
|
375
|
-
//
|
|
376
|
-
import {
|
|
377
|
-
import {
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
1019
|
+
// src/session-bind.ts
|
|
1020
|
+
import { closeSync, lstatSync as lstatSync3, mkdirSync as mkdirSync2, openSync, readFileSync as readFileSync3, readSync, readdirSync, readlinkSync, realpathSync as realpathSync2, statSync, unlinkSync as unlinkSync2 } from "node:fs";
|
|
1021
|
+
import { isAbsolute as isAbsolute2, join as join2, parse, resolve } from "node:path";
|
|
1022
|
+
|
|
1023
|
+
// src/profile-store.ts
|
|
1024
|
+
var MAX_PROFILE_JSON_BYTES = 64 * 1024;
|
|
1025
|
+
var DARWIN_SYSTEM_SYMLINKS = new Set(["/var", "/tmp", "/etc"]);
|
|
1026
|
+
var NON_PROFILE_JSON_FILES = new Set([
|
|
1027
|
+
"session-binds.json",
|
|
1028
|
+
"session-binds.meta.json",
|
|
1029
|
+
"session-binds-meta.json",
|
|
1030
|
+
"session-binds_meta.json",
|
|
1031
|
+
"agy-session-binds.json",
|
|
1032
|
+
"agy-session-binds.meta.json",
|
|
1033
|
+
"agy-session-binds_meta.json",
|
|
1034
|
+
"agy-binds.json",
|
|
1035
|
+
"agy-binds.meta.json",
|
|
1036
|
+
"agy-binds-meta.json",
|
|
1037
|
+
"agy-binds_meta.json",
|
|
1038
|
+
"grok-binds.json",
|
|
1039
|
+
"grok-binds-meta.json",
|
|
1040
|
+
"grok-binds.meta.json",
|
|
1041
|
+
"grok-binds_meta.json",
|
|
1042
|
+
"identity-guard.json",
|
|
1043
|
+
"cursor.json",
|
|
1044
|
+
"read-cursors.json",
|
|
1045
|
+
"mention-timestamps.json",
|
|
1046
|
+
"wake-pids.json",
|
|
1047
|
+
"codex-bots.json",
|
|
1048
|
+
"dsh.json",
|
|
1049
|
+
"config.json",
|
|
1050
|
+
"muse.json"
|
|
1051
|
+
]);
|
|
1052
|
+
|
|
1053
|
+
// src/session-bind.ts
|
|
1054
|
+
var DEFAULT_SESSION_BINDS_FILENAME = "session-binds.json";
|
|
1055
|
+
var LEGACY_AGY_BINDS_FILENAME = "agy-binds.json";
|
|
1056
|
+
var LOCK_FILE_MAX_BYTES = 64 * 1024;
|
|
1057
|
+
var SESSION_BINDS_MAX_BYTES = 1024 * 1024;
|
|
1058
|
+
var MAX_SESSION_BINDS_ENTRIES = 1024;
|
|
1059
|
+
var CONTROL_CHAR_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
1060
|
+
var RESERVED_BIND_SIDECARS = new Set([
|
|
1061
|
+
"session-binds",
|
|
1062
|
+
"session-binds.meta",
|
|
1063
|
+
"session-binds_meta",
|
|
1064
|
+
"agy-binds",
|
|
1065
|
+
"agy-binds.meta",
|
|
1066
|
+
"agy-binds_meta",
|
|
1067
|
+
"grok-binds",
|
|
1068
|
+
"grok-binds.meta",
|
|
1069
|
+
"grok-binds_meta",
|
|
1070
|
+
"agy-session-binds",
|
|
1071
|
+
"identity-guard",
|
|
1072
|
+
"cursor",
|
|
1073
|
+
"read-cursors",
|
|
1074
|
+
"mention-timestamps",
|
|
1075
|
+
"wake-pids",
|
|
1076
|
+
"config",
|
|
1077
|
+
"codex-bots",
|
|
1078
|
+
"dsh",
|
|
1079
|
+
"muse"
|
|
1080
|
+
]);
|
|
1081
|
+
function readBoundedRegularJson(path, maxBytes) {
|
|
1082
|
+
try {
|
|
1083
|
+
const st = lstatSync3(path);
|
|
1084
|
+
if (st.isSymbolicLink() || !st.isFile() || st.size > maxBytes)
|
|
1085
|
+
return null;
|
|
1086
|
+
const parsed = JSON.parse(readFileSync3(path, "utf8"));
|
|
1087
|
+
if (parsed && typeof parsed === "object" && Object.prototype.hasOwnProperty.call(parsed, "__proto__")) {
|
|
1088
|
+
return null;
|
|
1089
|
+
}
|
|
1090
|
+
return parsed;
|
|
1091
|
+
} catch {
|
|
1092
|
+
return null;
|
|
1093
|
+
}
|
|
396
1094
|
}
|
|
397
|
-
function
|
|
398
|
-
|
|
1095
|
+
function isAllowedDarwinSystemLink(dirPath) {
|
|
1096
|
+
if (process.platform !== "darwin")
|
|
1097
|
+
return false;
|
|
1098
|
+
if (dirPath !== "/var" && dirPath !== "/tmp" && dirPath !== "/etc")
|
|
1099
|
+
return false;
|
|
1100
|
+
try {
|
|
1101
|
+
const expected = `/private${dirPath}`;
|
|
1102
|
+
return readlinkSync(dirPath) === `private${dirPath}` && realpathSync2(dirPath) === expected && !lstatSync3("/private").isSymbolicLink() && lstatSync3("/private").isDirectory() && !lstatSync3(expected).isSymbolicLink() && statSync(expected).isDirectory();
|
|
1103
|
+
} catch {
|
|
1104
|
+
return false;
|
|
1105
|
+
}
|
|
399
1106
|
}
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
const
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
try {
|
|
414
|
-
const res = await f(url, { method: "POST", headers, body, signal: ctrl.signal });
|
|
415
|
-
if (!res.ok)
|
|
416
|
-
log(`[muse-agentchat] wake POST ${url} → HTTP ${res.status}`);
|
|
417
|
-
} finally {
|
|
418
|
-
clearTimeout(t);
|
|
1107
|
+
function hasSafeRawDotDotSegments(rawPath) {
|
|
1108
|
+
if (!rawPath.includes(".."))
|
|
1109
|
+
return true;
|
|
1110
|
+
const baseAbs = isAbsolute2(rawPath) ? rawPath : `${process.cwd()}/${rawPath}`;
|
|
1111
|
+
const root = parse(baseAbs).root;
|
|
1112
|
+
const rawParts = baseAbs.slice(root.length).split(/[\\/]+/).filter(Boolean);
|
|
1113
|
+
let cur = root;
|
|
1114
|
+
for (const part of rawParts) {
|
|
1115
|
+
if (part === ".")
|
|
1116
|
+
continue;
|
|
1117
|
+
if (part === "..") {
|
|
1118
|
+
cur = resolve(cur, "..");
|
|
1119
|
+
continue;
|
|
419
1120
|
}
|
|
420
|
-
|
|
421
|
-
try {
|
|
422
|
-
await doPost();
|
|
423
|
-
} catch (e) {
|
|
1121
|
+
cur = join2(cur, part);
|
|
424
1122
|
try {
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
1123
|
+
const st = lstatSync3(cur);
|
|
1124
|
+
if (st.isSymbolicLink()) {
|
|
1125
|
+
if (isAllowedDarwinSystemLink(cur))
|
|
1126
|
+
continue;
|
|
1127
|
+
return false;
|
|
1128
|
+
}
|
|
1129
|
+
if (!st.isDirectory())
|
|
1130
|
+
return false;
|
|
1131
|
+
} catch (e) {
|
|
1132
|
+
if (e && typeof e === "object" && e.code === "ENOENT")
|
|
1133
|
+
continue;
|
|
1134
|
+
return false;
|
|
428
1135
|
}
|
|
429
1136
|
}
|
|
1137
|
+
return true;
|
|
430
1138
|
}
|
|
431
|
-
function
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
1139
|
+
function isSafeDirOrMissing(dirPath) {
|
|
1140
|
+
if (!dirPath || CONTROL_CHAR_RE.test(dirPath))
|
|
1141
|
+
return false;
|
|
1142
|
+
if (!hasSafeRawDotDotSegments(dirPath))
|
|
1143
|
+
return false;
|
|
1144
|
+
const abs = resolve(dirPath);
|
|
1145
|
+
const root = parse(abs).root;
|
|
1146
|
+
const segments = abs.slice(root.length).split(/[\\/]+/).filter(Boolean);
|
|
1147
|
+
let cur = root;
|
|
1148
|
+
for (let i = 0;i < segments.length; i++) {
|
|
1149
|
+
cur = join2(cur, segments[i]);
|
|
1150
|
+
try {
|
|
1151
|
+
const st = lstatSync3(cur);
|
|
1152
|
+
if (st.isSymbolicLink()) {
|
|
1153
|
+
if (isAllowedDarwinSystemLink(cur))
|
|
1154
|
+
continue;
|
|
440
1155
|
return false;
|
|
441
1156
|
}
|
|
442
|
-
|
|
1157
|
+
if (!st.isDirectory())
|
|
1158
|
+
return false;
|
|
1159
|
+
} catch (e) {
|
|
1160
|
+
if (e && typeof e === "object" && e.code === "ENOENT")
|
|
1161
|
+
return true;
|
|
443
1162
|
return false;
|
|
444
1163
|
}
|
|
445
1164
|
}
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
1165
|
+
return true;
|
|
1166
|
+
}
|
|
1167
|
+
function isValidBindToken(value) {
|
|
1168
|
+
return value.length > 0 && value.length <= 256 && !CONTROL_CHAR_RE.test(value);
|
|
1169
|
+
}
|
|
1170
|
+
function isValidBoundProfileName(value) {
|
|
1171
|
+
if (!isValidBindToken(value) || value === "." || value === ".." || value.includes("/") || value.includes("\\")) {
|
|
1172
|
+
return false;
|
|
1173
|
+
}
|
|
1174
|
+
const stem = value.replace(/\.json$/i, "").toLowerCase();
|
|
1175
|
+
const normalizedStem = stem.replace(/[^a-z0-9_-]/g, "_");
|
|
1176
|
+
return Boolean(stem) && !isUnsafeBindKey(value) && !isUnsafeBindKey(stem) && !RESERVED_BIND_SIDECARS.has(stem) && !RESERVED_BIND_SIDECARS.has(normalizedStem);
|
|
1177
|
+
}
|
|
1178
|
+
function isUnsafeBindKey(key) {
|
|
1179
|
+
const lower = key.toLowerCase();
|
|
1180
|
+
return lower === "__proto__" || lower === "constructor" || lower === "prototype";
|
|
449
1181
|
}
|
|
450
|
-
|
|
451
|
-
// src/session-route.ts
|
|
452
|
-
import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
|
|
453
|
-
import { homedir as homedir2 } from "node:os";
|
|
454
|
-
import { join as join3 } from "node:path";
|
|
455
|
-
|
|
456
|
-
// src/session-bind.ts
|
|
457
|
-
import { closeSync, existsSync as existsSync2, mkdirSync, openSync, readFileSync as readFileSync2, readSync, readdirSync, statSync, unlinkSync } from "node:fs";
|
|
458
|
-
import { join as join2 } from "node:path";
|
|
459
|
-
|
|
460
|
-
// src/profile-store.ts
|
|
461
|
-
var NON_PROFILE_JSON_FILES = new Set([
|
|
462
|
-
"session-binds.json",
|
|
463
|
-
"agy-binds.json",
|
|
464
|
-
"grok-binds.json",
|
|
465
|
-
"grok-binds-meta.json",
|
|
466
|
-
"grok-binds.meta.json",
|
|
467
|
-
"identity-guard.json",
|
|
468
|
-
"dsh.json",
|
|
469
|
-
"config.json"
|
|
470
|
-
]);
|
|
471
|
-
|
|
472
|
-
// src/session-bind.ts
|
|
473
|
-
var DEFAULT_SESSION_BINDS_FILENAME = "session-binds.json";
|
|
474
|
-
var LEGACY_AGY_BINDS_FILENAME = "agy-binds.json";
|
|
475
1182
|
function parseSessionBinds(raw) {
|
|
476
1183
|
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
477
1184
|
return {};
|
|
478
1185
|
const out = {};
|
|
1186
|
+
let count = 0;
|
|
479
1187
|
for (const [k, v] of Object.entries(raw)) {
|
|
1188
|
+
if (count >= MAX_SESSION_BINDS_ENTRIES)
|
|
1189
|
+
break;
|
|
480
1190
|
const key = k.trim();
|
|
481
|
-
if (!key)
|
|
1191
|
+
if (!isValidBindToken(key) || key === "." || key === ".." || isUnsafeBindKey(key))
|
|
482
1192
|
continue;
|
|
483
|
-
if (typeof v === "string"
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
1193
|
+
if (typeof v === "string") {
|
|
1194
|
+
const val = v.trim();
|
|
1195
|
+
if (isValidBoundProfileName(val)) {
|
|
1196
|
+
out[key] = val;
|
|
1197
|
+
count += 1;
|
|
1198
|
+
}
|
|
1199
|
+
} else if (v && typeof v === "object" && typeof v.profile === "string") {
|
|
1200
|
+
const val = v.profile.trim();
|
|
1201
|
+
if (isValidBoundProfileName(val)) {
|
|
1202
|
+
out[key] = val;
|
|
1203
|
+
count += 1;
|
|
1204
|
+
}
|
|
487
1205
|
}
|
|
488
1206
|
}
|
|
489
1207
|
return out;
|
|
490
1208
|
}
|
|
491
1209
|
function loadSessionBinds(configDir) {
|
|
1210
|
+
if (!isSafeDirOrMissing(configDir))
|
|
1211
|
+
return {};
|
|
492
1212
|
const merged = {};
|
|
493
1213
|
for (const filename of [LEGACY_AGY_BINDS_FILENAME, DEFAULT_SESSION_BINDS_FILENAME]) {
|
|
494
1214
|
const path = join2(configDir, filename);
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
} catch {}
|
|
1215
|
+
const parsed = readBoundedRegularJson(path, SESSION_BINDS_MAX_BYTES);
|
|
1216
|
+
if (parsed !== null) {
|
|
1217
|
+
Object.assign(merged, parseSessionBinds(parsed));
|
|
1218
|
+
}
|
|
500
1219
|
}
|
|
501
1220
|
return merged;
|
|
502
1221
|
}
|
|
1222
|
+
var DSH_HEALTH_MAX_BYTES = 256 * 1024;
|
|
503
1223
|
|
|
504
1224
|
// src/session-route.ts
|
|
1225
|
+
var MAX_PROFILE_BYTES2 = 64 * 1024;
|
|
1226
|
+
var MAX_DIR_PATH_LENGTH = 4096;
|
|
1227
|
+
var MAX_SESSION_ID_LENGTH = 256;
|
|
1228
|
+
var RESERVED_PROFILE_KEY = /^(?:__proto__|constructor|prototype)$/i;
|
|
1229
|
+
var RESERVED_ROUTE_SIDECARS = new Set([
|
|
1230
|
+
"profile",
|
|
1231
|
+
"session-binds",
|
|
1232
|
+
"session-binds_meta",
|
|
1233
|
+
"session-binds-meta",
|
|
1234
|
+
"agy-binds",
|
|
1235
|
+
"agy-binds_meta",
|
|
1236
|
+
"agy-binds-meta",
|
|
1237
|
+
"agy-session-binds",
|
|
1238
|
+
"agy-session-binds_meta",
|
|
1239
|
+
"grok-binds",
|
|
1240
|
+
"grok-binds_meta",
|
|
1241
|
+
"grok-binds-meta",
|
|
1242
|
+
"identity-guard",
|
|
1243
|
+
"cursor",
|
|
1244
|
+
"read-cursors",
|
|
1245
|
+
"mention-timestamps",
|
|
1246
|
+
"wake-pids",
|
|
1247
|
+
"config",
|
|
1248
|
+
"codex-bots",
|
|
1249
|
+
"dsh",
|
|
1250
|
+
"muse"
|
|
1251
|
+
]);
|
|
1252
|
+
function isSafeAbsoluteDirEnv(raw) {
|
|
1253
|
+
if (typeof raw !== "string")
|
|
1254
|
+
return false;
|
|
1255
|
+
const s = raw.trim();
|
|
1256
|
+
return s.length > 0 && s.length <= MAX_DIR_PATH_LENGTH && !s.startsWith("-") && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(s) && isAbsolute3(s);
|
|
1257
|
+
}
|
|
505
1258
|
function agentschatConfigDir(env = process.env) {
|
|
506
|
-
|
|
1259
|
+
if (isSafeAbsoluteDirEnv(env.AGENTSCHAT_CONFIG_DIR)) {
|
|
1260
|
+
return env.AGENTSCHAT_CONFIG_DIR.trim();
|
|
1261
|
+
}
|
|
1262
|
+
const homeCandidate = env.HOME || env.USERPROFILE || "";
|
|
1263
|
+
const home = isSafeAbsoluteDirEnv(homeCandidate) ? homeCandidate.trim() : homedir2();
|
|
1264
|
+
return join3(home, ".agentschat");
|
|
1265
|
+
}
|
|
1266
|
+
function isSafeAgentId(id) {
|
|
1267
|
+
return id.length > 0 && id.length <= 128 && id !== "." && id !== ".." && !RESERVED_PROFILE_KEY.test(id) && !/[/\\\s\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(id);
|
|
1268
|
+
}
|
|
1269
|
+
function isSafeRegularProfileFile(path) {
|
|
1270
|
+
try {
|
|
1271
|
+
const st = lstatSync4(path);
|
|
1272
|
+
return !st.isSymbolicLink() && st.isFile() && st.size <= MAX_PROFILE_BYTES2;
|
|
1273
|
+
} catch {
|
|
1274
|
+
return false;
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
function isSafeSessionId(sessionId) {
|
|
1278
|
+
return sessionId.length > 0 && sessionId.length <= MAX_SESSION_ID_LENGTH && sessionId !== "." && sessionId !== ".." && !RESERVED_PROFILE_KEY.test(sessionId) && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(sessionId);
|
|
1279
|
+
}
|
|
1280
|
+
function isAllowedDarwinSystemLink2(dirPath) {
|
|
1281
|
+
if (process.platform !== "darwin")
|
|
1282
|
+
return false;
|
|
1283
|
+
if (dirPath !== "/var" && dirPath !== "/tmp" && dirPath !== "/etc")
|
|
1284
|
+
return false;
|
|
1285
|
+
try {
|
|
1286
|
+
return readlinkSync2(dirPath) === `private${dirPath}` && realpathSync3(dirPath) === `/private${dirPath}` && !lstatSync4("/private").isSymbolicLink() && lstatSync4("/private").isDirectory() && !lstatSync4(`/private${dirPath}`).isSymbolicLink() && lstatSync4(`/private${dirPath}`).isDirectory();
|
|
1287
|
+
} catch {
|
|
1288
|
+
return false;
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
function hasSafeRawDotDotSegments2(rawPath) {
|
|
1292
|
+
const absRaw = isAbsolute3(rawPath) ? rawPath : `${process.cwd()}${sep2}${rawPath}`;
|
|
1293
|
+
const root = parse2(absRaw).root;
|
|
1294
|
+
const segments = absRaw.slice(root.length).split(/[\\/]+/).filter(Boolean);
|
|
1295
|
+
if (!segments.includes(".."))
|
|
1296
|
+
return true;
|
|
1297
|
+
let cur = root;
|
|
1298
|
+
for (const seg of segments) {
|
|
1299
|
+
if (seg === ".")
|
|
1300
|
+
continue;
|
|
1301
|
+
if (seg === "..") {
|
|
1302
|
+
cur = dirname3(cur);
|
|
1303
|
+
continue;
|
|
1304
|
+
}
|
|
1305
|
+
const next = join3(cur, seg);
|
|
1306
|
+
try {
|
|
1307
|
+
const st = lstatSync4(next);
|
|
1308
|
+
if (st.isSymbolicLink() && !isAllowedDarwinSystemLink2(next)) {
|
|
1309
|
+
return false;
|
|
1310
|
+
}
|
|
1311
|
+
} catch (err) {
|
|
1312
|
+
if (err?.code !== "ENOENT")
|
|
1313
|
+
return false;
|
|
1314
|
+
}
|
|
1315
|
+
cur = next;
|
|
1316
|
+
}
|
|
1317
|
+
return true;
|
|
1318
|
+
}
|
|
1319
|
+
function isSafeRealDir(path) {
|
|
1320
|
+
try {
|
|
1321
|
+
if (!path || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(path) || !hasSafeRawDotDotSegments2(path)) {
|
|
1322
|
+
return false;
|
|
1323
|
+
}
|
|
1324
|
+
const st = lstatSync4(path);
|
|
1325
|
+
if (st.isSymbolicLink() || !st.isDirectory())
|
|
1326
|
+
return false;
|
|
1327
|
+
const abs = resolve2(path);
|
|
1328
|
+
const root = parse2(abs).root;
|
|
1329
|
+
const segments = abs.slice(root.length).split(/[\\/]+/).filter(Boolean);
|
|
1330
|
+
let cur = root;
|
|
1331
|
+
for (let i = 0;i < segments.length; i++) {
|
|
1332
|
+
cur = join3(cur, segments[i]);
|
|
1333
|
+
const anc = lstatSync4(cur);
|
|
1334
|
+
if (anc.isSymbolicLink()) {
|
|
1335
|
+
if (isAllowedDarwinSystemLink2(cur))
|
|
1336
|
+
continue;
|
|
1337
|
+
return false;
|
|
1338
|
+
}
|
|
1339
|
+
if (!anc.isDirectory())
|
|
1340
|
+
return false;
|
|
1341
|
+
}
|
|
1342
|
+
return true;
|
|
1343
|
+
} catch {
|
|
1344
|
+
return false;
|
|
1345
|
+
}
|
|
507
1346
|
}
|
|
508
1347
|
function profilePathForName(configDir, name) {
|
|
509
|
-
if (!name || name.includes("/") || name.includes("\\"))
|
|
1348
|
+
if (typeof name !== "string" || !name || name.length > 133 || name === "." || name === ".." || name.includes("/") || name.includes("\\") || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(name) || !isSafeRealDir(configDir)) {
|
|
1349
|
+
return;
|
|
1350
|
+
}
|
|
1351
|
+
const base = name.replace(/\.json$/i, "").replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
1352
|
+
if (!base || base.length > 128 || RESERVED_PROFILE_KEY.test(base) || RESERVED_ROUTE_SIDECARS.has(base.toLowerCase())) {
|
|
510
1353
|
return;
|
|
511
|
-
|
|
512
|
-
const
|
|
513
|
-
if (
|
|
514
|
-
|
|
1354
|
+
}
|
|
1355
|
+
const profilesDir = join3(configDir, "profiles");
|
|
1356
|
+
if (isSafeRealDir(profilesDir)) {
|
|
1357
|
+
const nested = join3(profilesDir, `${base}.json`);
|
|
1358
|
+
if (isSafeRegularProfileFile(nested))
|
|
1359
|
+
return nested;
|
|
1360
|
+
}
|
|
515
1361
|
const flat = join3(configDir, `${base}.json`);
|
|
516
|
-
return
|
|
1362
|
+
return isSafeRegularProfileFile(flat) ? flat : undefined;
|
|
517
1363
|
}
|
|
518
1364
|
function readAgentId(path) {
|
|
519
1365
|
try {
|
|
520
|
-
|
|
521
|
-
|
|
1366
|
+
if (!isSafeRegularProfileFile(path))
|
|
1367
|
+
return;
|
|
1368
|
+
const parsed = JSON.parse(readFileSync4(path, "utf8"));
|
|
1369
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.prototype.hasOwnProperty.call(parsed, "__proto__")) {
|
|
1370
|
+
return;
|
|
1371
|
+
}
|
|
1372
|
+
const id = typeof parsed.agent_id === "string" ? parsed.agent_id.trim() : "";
|
|
1373
|
+
return isSafeAgentId(id) ? id : undefined;
|
|
522
1374
|
} catch {
|
|
523
1375
|
return;
|
|
524
1376
|
}
|
|
525
1377
|
}
|
|
526
1378
|
function resolveSessionForAgent(agentId, opts = {}) {
|
|
527
|
-
if (typeof agentId !== "string" || agentId
|
|
1379
|
+
if (typeof agentId !== "string" || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(agentId))
|
|
1380
|
+
return;
|
|
1381
|
+
const targetAgentId = agentId.trim();
|
|
1382
|
+
if (!isSafeAgentId(targetAgentId))
|
|
528
1383
|
return;
|
|
529
1384
|
const configDir = opts.configDir ?? agentschatConfigDir(opts.env);
|
|
530
1385
|
let binds;
|
|
@@ -534,37 +1389,263 @@ function resolveSessionForAgent(agentId, opts = {}) {
|
|
|
534
1389
|
return;
|
|
535
1390
|
}
|
|
536
1391
|
for (const [sessionId, profileName] of Object.entries(binds).reverse()) {
|
|
1392
|
+
if (!isSafeSessionId(sessionId))
|
|
1393
|
+
continue;
|
|
537
1394
|
if (opts.filter && !opts.filter(sessionId))
|
|
538
1395
|
continue;
|
|
539
1396
|
const path = profilePathForName(configDir, profileName);
|
|
540
1397
|
if (path === undefined)
|
|
541
1398
|
continue;
|
|
542
|
-
if (readAgentId(path) !==
|
|
1399
|
+
if (readAgentId(path) !== targetAgentId)
|
|
543
1400
|
continue;
|
|
544
|
-
return { sessionId, profileName, agentId };
|
|
1401
|
+
return { sessionId, profileName, agentId: targetAgentId };
|
|
545
1402
|
}
|
|
546
1403
|
return;
|
|
547
1404
|
}
|
|
548
1405
|
|
|
549
|
-
//
|
|
550
|
-
import { existsSync as
|
|
551
|
-
import { dirname, join as join4 } from "node:path";
|
|
1406
|
+
// src/wake.ts
|
|
1407
|
+
import { existsSync as existsSync2, lstatSync as lstatSync5, readFileSync as readFileSync5, readlinkSync as readlinkSync3 } from "node:fs";
|
|
552
1408
|
import { homedir as homedir3 } from "node:os";
|
|
1409
|
+
import { dirname as dirname4, isAbsolute as isAbsolute4, join as join4, parse as parse3, resolve as resolve3, win32 as pathWin32 } from "node:path";
|
|
1410
|
+
var PROTOTYPE_WAKE_KEYS = new Set([
|
|
1411
|
+
"prototype",
|
|
1412
|
+
...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase())
|
|
1413
|
+
]);
|
|
1414
|
+
var GROK_GATEWAY_PATH_CANDIDATES = [
|
|
1415
|
+
join4(process.env.HOME || process.env.USERPROFILE || homedir3(), ".grok", "gateway.json"),
|
|
1416
|
+
"/home/box/sand-data/gateway.json"
|
|
1417
|
+
];
|
|
1418
|
+
var zcodeSessionQueues = new Map;
|
|
1419
|
+
function resolveWindowsCliSpawn(cmd, args, opts) {
|
|
1420
|
+
const platform = opts?.platform ?? process.platform;
|
|
1421
|
+
const trimmed = (cmd || "").trim();
|
|
1422
|
+
if (!trimmed)
|
|
1423
|
+
return { cmd, args };
|
|
1424
|
+
const execPath = opts?.execPath ?? process.execPath;
|
|
1425
|
+
if (/\.(?:cjs|mjs|js)$/i.test(trimmed)) {
|
|
1426
|
+
return { cmd: execPath, args: [trimmed, ...args] };
|
|
1427
|
+
}
|
|
1428
|
+
if (platform !== "win32") {
|
|
1429
|
+
return { cmd: trimmed, args };
|
|
1430
|
+
}
|
|
1431
|
+
const env = opts?.env ?? process.env;
|
|
1432
|
+
const exists = opts?.existsImpl ?? existsSync2;
|
|
1433
|
+
const readText = opts?.readTextImpl ?? ((p) => readFileSync5(p, "utf8"));
|
|
1434
|
+
const hasSep = /[\\/]/.test(trimmed) || /^[A-Za-z]:/.test(trimmed);
|
|
1435
|
+
const hasWinExt = /\.(?:exe|cmd|bat)$/i.test(trimmed);
|
|
1436
|
+
const candidates = [];
|
|
1437
|
+
if (hasSep) {
|
|
1438
|
+
if (hasWinExt) {
|
|
1439
|
+
candidates.push(trimmed);
|
|
1440
|
+
} else {
|
|
1441
|
+
candidates.push(`${trimmed}.exe`, `${trimmed}.cmd`, trimmed);
|
|
1442
|
+
}
|
|
1443
|
+
} else {
|
|
1444
|
+
const rawPath = env.PATH ?? env.Path ?? env.path ?? "";
|
|
1445
|
+
for (const rawDir of rawPath.split(";")) {
|
|
1446
|
+
const dir = rawDir.trim().replace(/^"+|"+$/g, "");
|
|
1447
|
+
if (!dir)
|
|
1448
|
+
continue;
|
|
1449
|
+
if (hasWinExt) {
|
|
1450
|
+
candidates.push(pathWin32.join(dir, trimmed));
|
|
1451
|
+
} else {
|
|
1452
|
+
candidates.push(pathWin32.join(dir, `${trimmed}.exe`), pathWin32.join(dir, `${trimmed}.cmd`));
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
for (const candidate of candidates) {
|
|
1457
|
+
if (!exists(candidate))
|
|
1458
|
+
continue;
|
|
1459
|
+
if (/\.exe$/i.test(candidate)) {
|
|
1460
|
+
return { cmd: candidate, args };
|
|
1461
|
+
}
|
|
1462
|
+
if (/\.(?:cmd|bat)$/i.test(candidate)) {
|
|
1463
|
+
try {
|
|
1464
|
+
const content = readText(candidate);
|
|
1465
|
+
const m = content.match(/%(?:~)?dp0%?[\\/]([^"\r\n]+?\.(?:cjs|mjs|js))/i);
|
|
1466
|
+
if (m && m[1]) {
|
|
1467
|
+
const cmdDir = pathWin32.dirname(candidate);
|
|
1468
|
+
const scriptPath = pathWin32.resolve(cmdDir, m[1].replace(/\//g, "\\"));
|
|
1469
|
+
if (exists(scriptPath)) {
|
|
1470
|
+
const bundledNode = pathWin32.join(cmdDir, "node.exe");
|
|
1471
|
+
const runner = exists(bundledNode) ? bundledNode : execPath;
|
|
1472
|
+
return { cmd: runner, args: [scriptPath, ...args] };
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
} catch {}
|
|
1476
|
+
return { cmd: candidate, args };
|
|
1477
|
+
}
|
|
1478
|
+
return { cmd: candidate, args };
|
|
1479
|
+
}
|
|
1480
|
+
return { cmd: trimmed, args };
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
// dsh/src/patch.ts
|
|
1484
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
1485
|
+
import { chmodSync as chmodSync2, copyFileSync as copyFileSync2, lstatSync as lstatSync6, mkdirSync as mkdirSync3, readFileSync as readFileSync6, realpathSync as realpathSync4, renameSync as renameSync2, unlinkSync as unlinkSync3, writeFileSync as writeFileSync2 } from "node:fs";
|
|
1486
|
+
import { dirname as dirname5, isAbsolute as isAbsolute5, join as join5, resolve as resolve4 } from "node:path";
|
|
1487
|
+
import { homedir as homedir4 } from "node:os";
|
|
1488
|
+
var FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
|
1489
|
+
var DARWIN_ROOT_LINKS = new Set(["/var", "/tmp", "/etc"]);
|
|
1490
|
+
var DSH_PATCH_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
1491
|
+
var DSH_PATCH_PRETRIM_CTRL_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
1492
|
+
function isAllowedDarwinSystemLink3(dirPath) {
|
|
1493
|
+
if (process.platform !== "darwin" || !DARWIN_ROOT_LINKS.has(dirPath))
|
|
1494
|
+
return false;
|
|
1495
|
+
try {
|
|
1496
|
+
const priv = lstatSync6("/private");
|
|
1497
|
+
if (priv.isSymbolicLink() || !priv.isDirectory())
|
|
1498
|
+
return false;
|
|
1499
|
+
const real = realpathSync4(dirPath);
|
|
1500
|
+
if (real !== `/private${dirPath}`)
|
|
1501
|
+
return false;
|
|
1502
|
+
const target = lstatSync6(real);
|
|
1503
|
+
return !target.isSymbolicLink() && target.isDirectory();
|
|
1504
|
+
} catch {
|
|
1505
|
+
return false;
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
function checkRawDotDotAncestors(rawPath) {
|
|
1509
|
+
const trimmed = rawPath.trim();
|
|
1510
|
+
if (!trimmed || !isAbsolute5(trimmed))
|
|
1511
|
+
return;
|
|
1512
|
+
const normalizedSep = process.platform === "win32" ? trimmed.replace(/\//g, "\\") : trimmed;
|
|
1513
|
+
const sepChar = process.platform === "win32" ? "\\" : "/";
|
|
1514
|
+
const parts = normalizedSep.split(sepChar);
|
|
1515
|
+
if (!parts.includes(".."))
|
|
1516
|
+
return;
|
|
1517
|
+
const winDrive = process.platform === "win32" && /^[A-Za-z]:$/.test(parts[0] || "");
|
|
1518
|
+
let current = winDrive ? `${parts[0]}\\` : sepChar;
|
|
1519
|
+
for (let i = 1;i < parts.length; i++) {
|
|
1520
|
+
const seg = parts[i];
|
|
1521
|
+
if (!seg || seg === ".")
|
|
1522
|
+
continue;
|
|
1523
|
+
if (seg === "..") {
|
|
1524
|
+
current = dirname5(current);
|
|
1525
|
+
continue;
|
|
1526
|
+
}
|
|
1527
|
+
const candidate = current.endsWith(sepChar) ? `${current}${seg}` : `${current}${sepChar}${seg}`;
|
|
1528
|
+
if (i < parts.length - 1 || parts.slice(i + 1).includes("..")) {
|
|
1529
|
+
if (!isAllowedDarwinSystemLink3(candidate)) {
|
|
1530
|
+
try {
|
|
1531
|
+
const stat = lstatSync6(candidate);
|
|
1532
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
1533
|
+
throw new Error(`Refusing symlinked or non-directory parent: ${candidate}`);
|
|
1534
|
+
}
|
|
1535
|
+
} catch (err) {
|
|
1536
|
+
if (err?.code !== "ENOENT")
|
|
1537
|
+
throw err;
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
}
|
|
1541
|
+
current = candidate;
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
function checkParentDirectory(path) {
|
|
1545
|
+
if (typeof path !== "string" || !path.trim() || DSH_PATCH_CTRL_RE.test(path)) {
|
|
1546
|
+
throw new Error("Invalid DSH target path");
|
|
1547
|
+
}
|
|
1548
|
+
checkRawDotDotAncestors(path);
|
|
1549
|
+
let parent = dirname5(resolve4(path));
|
|
1550
|
+
for (;; ) {
|
|
1551
|
+
if (!isAllowedDarwinSystemLink3(parent)) {
|
|
1552
|
+
try {
|
|
1553
|
+
const stat = lstatSync6(parent);
|
|
1554
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
1555
|
+
throw new Error(`Refusing symlinked or non-directory parent: ${parent}`);
|
|
1556
|
+
}
|
|
1557
|
+
} catch (err) {
|
|
1558
|
+
if (err?.code !== "ENOENT")
|
|
1559
|
+
throw err;
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
const next = dirname5(parent);
|
|
1563
|
+
if (next === parent)
|
|
1564
|
+
break;
|
|
1565
|
+
parent = next;
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
1568
|
+
function isBlockedNormalizedHost(host) {
|
|
1569
|
+
if (!host)
|
|
1570
|
+
return true;
|
|
1571
|
+
if (host === "0.0.0.0" || /^0\./.test(host) || host === "::" || host === "0:0:0:0:0:0:0:0" || host === "100.100.100.200" || host === "fd00:ec2::254" || host === "fd00:ec2:0:0:0:0:0:254" || host === "metadata" || host === "instance-data" || host === "metadata.google.internal" || host.endsWith(".metadata.google.internal") || host === "metadata.goog" || host.endsWith(".metadata.goog") || /^169\.254\./.test(host)) {
|
|
1572
|
+
return true;
|
|
1573
|
+
}
|
|
1574
|
+
if (/^::ffff:(?:0:)?(?:a9fe:[0-9a-f]{1,4}|169\.254\.\d{1,3}\.\d{1,3}|6464:64c8|100\.100\.100\.200|[0-9a-f]{1,2}:[0-9a-f]{1,4}|0\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.test(host) || /^(?:0:){5}ffff:(?:a9fe:[0-9a-f]{1,4}|169\.254\.\d{1,3}\.\d{1,3}|6464:64c8|100\.100\.100\.200|[0-9a-f]{1,2}:[0-9a-f]{1,4}|0\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.test(host)) {
|
|
1575
|
+
return true;
|
|
1576
|
+
}
|
|
1577
|
+
const first = host.split(":")[0];
|
|
1578
|
+
return host.includes(":") && /^[0-9a-f]{1,4}$/.test(first) && (parseInt(first, 16) & 65472) === 65152;
|
|
1579
|
+
}
|
|
1580
|
+
function isBlockedDshHost(hostname) {
|
|
1581
|
+
const raw = hostname.trim().toLowerCase().replace(/\.$/, "").replace(/^\[|\]$/g, "");
|
|
1582
|
+
if (isBlockedNormalizedHost(raw))
|
|
1583
|
+
return true;
|
|
1584
|
+
try {
|
|
1585
|
+
const bracketed = raw.includes(":") ? `[${raw}]` : raw;
|
|
1586
|
+
const canonical = new URL(`http://${bracketed}`).hostname.toLowerCase().replace(/\.$/, "").replace(/^\[|\]$/g, "");
|
|
1587
|
+
if (canonical && canonical !== raw && isBlockedNormalizedHost(canonical))
|
|
1588
|
+
return true;
|
|
1589
|
+
} catch {}
|
|
1590
|
+
return false;
|
|
1591
|
+
}
|
|
553
1592
|
function resolveDshPatchPath(opts = {}) {
|
|
554
|
-
const home = opts.dshHome ?? process.env.DSH_HOME ??
|
|
555
|
-
if (
|
|
556
|
-
|
|
1593
|
+
const home = opts.dshHome ?? process.env.DSH_HOME ?? join5(homedir4(), ".dsh");
|
|
1594
|
+
if (!home || home.length > 4096 || home.startsWith("-") || !isAbsolute5(home) || DSH_PATCH_CTRL_RE.test(home)) {
|
|
1595
|
+
throw new Error("Invalid DSH home path");
|
|
1596
|
+
}
|
|
1597
|
+
if (opts.dshProfile !== undefined) {
|
|
1598
|
+
if (typeof opts.dshProfile !== "string" || DSH_PATCH_PRETRIM_CTRL_RE.test(opts.dshProfile)) {
|
|
1599
|
+
throw new Error("Invalid DSH profile name");
|
|
1600
|
+
}
|
|
1601
|
+
const profile = opts.dshProfile.trim();
|
|
1602
|
+
if (!profile || profile.length > 64 || !/^[A-Za-z0-9._-]+$/.test(profile) || profile === "." || profile.includes("..") || FORBIDDEN_KEYS.has(profile.toLowerCase())) {
|
|
1603
|
+
throw new Error("Invalid DSH profile name");
|
|
1604
|
+
}
|
|
1605
|
+
return join5(home, "profiles", profile, "cordis.patch.yml");
|
|
557
1606
|
}
|
|
558
|
-
return
|
|
1607
|
+
return join5(home, "cordis.patch.yml");
|
|
559
1608
|
}
|
|
560
1609
|
function buildMcpAgentsChatArgs(opts = {}) {
|
|
561
|
-
const
|
|
1610
|
+
const rawPkg = opts.packageSpec ?? "agentschat-mcp@latest";
|
|
1611
|
+
if (typeof rawPkg !== "string" || DSH_PATCH_PRETRIM_CTRL_RE.test(rawPkg)) {
|
|
1612
|
+
throw new Error("Invalid packageSpec");
|
|
1613
|
+
}
|
|
1614
|
+
const pkg = rawPkg.trim();
|
|
1615
|
+
if (!pkg || pkg.startsWith("-") || /[\x00-\x20\x7f-\x9f\u2028\u2029]/.test(pkg)) {
|
|
1616
|
+
throw new Error("Invalid packageSpec");
|
|
1617
|
+
}
|
|
562
1618
|
const args = ["-y", pkg];
|
|
563
|
-
if (opts.agentsChatProfile) {
|
|
564
|
-
|
|
1619
|
+
if (opts.agentsChatProfile !== undefined && opts.agentsChatProfile !== "") {
|
|
1620
|
+
if (typeof opts.agentsChatProfile !== "string" || DSH_PATCH_PRETRIM_CTRL_RE.test(opts.agentsChatProfile)) {
|
|
1621
|
+
throw new Error("Invalid AgentsChat profile name");
|
|
1622
|
+
}
|
|
1623
|
+
const profile = opts.agentsChatProfile.trim();
|
|
1624
|
+
if (!profile || profile.length > 64 || profile.startsWith("-") || profile.includes("..") || profile.includes("/") || profile.includes("\\") || FORBIDDEN_KEYS.has(profile.toLowerCase()) || DSH_PATCH_CTRL_RE.test(profile)) {
|
|
1625
|
+
throw new Error("Invalid AgentsChat profile name");
|
|
1626
|
+
}
|
|
1627
|
+
args.push("--profile", profile);
|
|
565
1628
|
}
|
|
566
|
-
if (opts.apiUrl) {
|
|
567
|
-
|
|
1629
|
+
if (opts.apiUrl !== undefined && opts.apiUrl !== "") {
|
|
1630
|
+
if (typeof opts.apiUrl !== "string" || DSH_PATCH_PRETRIM_CTRL_RE.test(opts.apiUrl)) {
|
|
1631
|
+
throw new Error("Invalid AgentsChat API URL");
|
|
1632
|
+
}
|
|
1633
|
+
const rawUrl = opts.apiUrl.trim();
|
|
1634
|
+
if (!rawUrl || rawUrl.startsWith("-") || /[\x00-\x20\x7f-\x9f\u2028\u2029]/.test(rawUrl)) {
|
|
1635
|
+
throw new Error("Invalid AgentsChat API URL");
|
|
1636
|
+
}
|
|
1637
|
+
let parsed;
|
|
1638
|
+
try {
|
|
1639
|
+
parsed = new URL(rawUrl);
|
|
1640
|
+
} catch {
|
|
1641
|
+
throw new Error("Invalid AgentsChat API URL");
|
|
1642
|
+
}
|
|
1643
|
+
const host = parsed.hostname.toLowerCase().replace(/\.$/, "");
|
|
1644
|
+
const isLoopback = host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1";
|
|
1645
|
+
if (isBlockedDshHost(parsed.hostname) || parsed.username || parsed.password || parsed.port === "0" || parsed.search || parsed.hash || parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLoopback)) {
|
|
1646
|
+
throw new Error("Invalid AgentsChat API URL");
|
|
1647
|
+
}
|
|
1648
|
+
args.push("--url", rawUrl);
|
|
568
1649
|
}
|
|
569
1650
|
return args;
|
|
570
1651
|
}
|
|
@@ -607,12 +1688,33 @@ ${renderMcpAgentsChatEntry(" ", opts)}
|
|
|
607
1688
|
`;
|
|
608
1689
|
return { content: `${prefix}${block2}`, changed: true };
|
|
609
1690
|
}
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
`)
|
|
613
|
-
|
|
1691
|
+
const normalizedLines = existingContent.replace(/\r\n/g, `
|
|
1692
|
+
`).split(`
|
|
1693
|
+
`);
|
|
1694
|
+
const insertLineIdx = normalizedLines.findIndex((line) => /^-\s*insert:\s*(?:#.*)?$/.test(line));
|
|
1695
|
+
if (insertLineIdx >= 0) {
|
|
1696
|
+
let detectedIndent = null;
|
|
1697
|
+
let lastBodyLineIdx = insertLineIdx;
|
|
1698
|
+
for (let i = insertLineIdx + 1;i < normalizedLines.length; i++) {
|
|
1699
|
+
const line = normalizedLines[i];
|
|
1700
|
+
if (/^\s*$/.test(line) || /^\s*#/.test(line))
|
|
1701
|
+
continue;
|
|
1702
|
+
if (/^\S/.test(line))
|
|
1703
|
+
break;
|
|
1704
|
+
const itemMatch = line.match(/^([ \t]+)-\s+/);
|
|
1705
|
+
if (itemMatch && detectedIndent === null) {
|
|
1706
|
+
detectedIndent = itemMatch[1];
|
|
1707
|
+
}
|
|
1708
|
+
lastBodyLineIdx = i;
|
|
1709
|
+
}
|
|
1710
|
+
const entryLines = renderMcpAgentsChatEntry(detectedIndent ?? " ", opts).split(`
|
|
1711
|
+
`);
|
|
1712
|
+
normalizedLines.splice(lastBodyLineIdx + 1, 0, ...entryLines);
|
|
1713
|
+
const merged = normalizedLines.join(`
|
|
1714
|
+
`);
|
|
614
1715
|
return {
|
|
615
|
-
content:
|
|
1716
|
+
content: merged.endsWith(`
|
|
1717
|
+
`) ? merged : `${merged}
|
|
616
1718
|
`,
|
|
617
1719
|
changed: true
|
|
618
1720
|
};
|
|
@@ -629,48 +1731,232 @@ ${renderMcpAgentsChatEntry(" ", opts)}
|
|
|
629
1731
|
};
|
|
630
1732
|
}
|
|
631
1733
|
function applyDshCordisPatchFile(opts = {}) {
|
|
1734
|
+
const rawHome = opts.dshHome ?? process.env.DSH_HOME;
|
|
1735
|
+
if (rawHome) {
|
|
1736
|
+
checkRawDotDotAncestors(`${rawHome}/_`);
|
|
1737
|
+
}
|
|
632
1738
|
const patchPath = resolveDshPatchPath(opts);
|
|
633
|
-
|
|
1739
|
+
checkParentDirectory(patchPath);
|
|
1740
|
+
let existed = false;
|
|
1741
|
+
let mode = 384;
|
|
1742
|
+
try {
|
|
1743
|
+
const lst = lstatSync6(patchPath);
|
|
1744
|
+
if (lst.isSymbolicLink() || !lst.isFile()) {
|
|
1745
|
+
throw new Error(`Refusing to modify non-regular or symlinked DSH patch file: ${patchPath}`);
|
|
1746
|
+
}
|
|
1747
|
+
if (lst.size > 1048576) {
|
|
1748
|
+
throw new Error(`Refusing to modify oversized DSH patch file (>1MiB): ${patchPath}`);
|
|
1749
|
+
}
|
|
1750
|
+
existed = true;
|
|
1751
|
+
mode = lst.mode & 511;
|
|
1752
|
+
} catch (err) {
|
|
1753
|
+
if (err?.code !== "ENOENT")
|
|
1754
|
+
throw err;
|
|
1755
|
+
}
|
|
1756
|
+
const existing = existed ? readFileSync6(patchPath, "utf8") : "";
|
|
634
1757
|
const { content, changed } = mergeDshCordisPatch(existing, opts);
|
|
635
1758
|
if (changed) {
|
|
636
|
-
|
|
637
|
-
|
|
1759
|
+
mkdirSync3(dirname5(patchPath), { recursive: true });
|
|
1760
|
+
checkParentDirectory(patchPath);
|
|
1761
|
+
const tmp = `${patchPath}.${process.pid}.${randomBytes2(4).toString("hex")}.tmp`;
|
|
1762
|
+
let created = false;
|
|
1763
|
+
try {
|
|
1764
|
+
writeFileSync2(tmp, content, { encoding: "utf8", mode, flag: "wx" });
|
|
1765
|
+
created = true;
|
|
1766
|
+
checkParentDirectory(patchPath);
|
|
1767
|
+
try {
|
|
1768
|
+
const cur = lstatSync6(patchPath);
|
|
1769
|
+
if (cur.isSymbolicLink() || !cur.isFile()) {
|
|
1770
|
+
throw new Error(`Refusing to overwrite symlinked or non-regular DSH patch file: ${patchPath}`);
|
|
1771
|
+
}
|
|
1772
|
+
} catch (err) {
|
|
1773
|
+
if (err?.code !== "ENOENT")
|
|
1774
|
+
throw err;
|
|
1775
|
+
}
|
|
1776
|
+
const doRename = opts.fsOps?.renameSync ?? renameSync2;
|
|
1777
|
+
const doCopy = opts.fsOps?.copyFileSync ?? copyFileSync2;
|
|
1778
|
+
try {
|
|
1779
|
+
doRename(tmp, patchPath);
|
|
1780
|
+
} catch (renameErr) {
|
|
1781
|
+
if (renameErr?.code !== "EPERM" && renameErr?.code !== "EACCES") {
|
|
1782
|
+
throw renameErr;
|
|
1783
|
+
}
|
|
1784
|
+
checkParentDirectory(patchPath);
|
|
1785
|
+
try {
|
|
1786
|
+
const cur = lstatSync6(patchPath);
|
|
1787
|
+
if (cur.isSymbolicLink() || !cur.isFile()) {
|
|
1788
|
+
throw new Error(`Refusing to overwrite symlinked or non-regular DSH patch file: ${patchPath}`);
|
|
1789
|
+
}
|
|
1790
|
+
} catch (err) {
|
|
1791
|
+
if (err?.code !== "ENOENT")
|
|
1792
|
+
throw err;
|
|
1793
|
+
}
|
|
1794
|
+
doCopy(tmp, patchPath);
|
|
1795
|
+
try {
|
|
1796
|
+
unlinkSync3(tmp);
|
|
1797
|
+
} catch {}
|
|
1798
|
+
created = false;
|
|
1799
|
+
}
|
|
1800
|
+
if (process.platform !== "win32") {
|
|
1801
|
+
try {
|
|
1802
|
+
chmodSync2(patchPath, mode);
|
|
1803
|
+
} catch {}
|
|
1804
|
+
}
|
|
1805
|
+
} catch (err) {
|
|
1806
|
+
try {
|
|
1807
|
+
if (created)
|
|
1808
|
+
unlinkSync3(tmp);
|
|
1809
|
+
} catch {}
|
|
1810
|
+
throw err;
|
|
1811
|
+
}
|
|
638
1812
|
}
|
|
639
1813
|
return { patchPath, changed };
|
|
640
1814
|
}
|
|
641
1815
|
|
|
642
1816
|
// dsh/src/cli.ts
|
|
643
|
-
var DSH_PROFILE_PATH =
|
|
1817
|
+
var DSH_PROFILE_PATH = join6(homedir5(), ".agentschat", "dsh.json");
|
|
644
1818
|
var DEFAULT_WS_URL = "wss://agents-chat.com/ws";
|
|
645
1819
|
var DEFAULT_REST_URL = "https://agents-chat.com";
|
|
646
1820
|
function arg(name, argv) {
|
|
647
1821
|
const i = argv.indexOf(name);
|
|
648
|
-
|
|
1822
|
+
const value = i >= 0 ? argv[i + 1] : undefined;
|
|
1823
|
+
return value?.startsWith("--") ? undefined : value;
|
|
649
1824
|
}
|
|
650
1825
|
function has(name, argv) {
|
|
651
1826
|
return argv.includes(name);
|
|
652
1827
|
}
|
|
1828
|
+
var FORBIDDEN_KEYS2 = new Set(["__proto__", "constructor", "prototype"]);
|
|
1829
|
+
var DSH_CLI_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
1830
|
+
var DSH_CLI_PRETRIM_CTRL_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
1831
|
+
var RESERVED_DSH_PROFILE_BASENAMES = new Set([
|
|
1832
|
+
"profile",
|
|
1833
|
+
"session-binds",
|
|
1834
|
+
"session-binds_meta",
|
|
1835
|
+
"session-binds.meta",
|
|
1836
|
+
"session-binds-meta",
|
|
1837
|
+
"agy-binds",
|
|
1838
|
+
"agy-binds_meta",
|
|
1839
|
+
"agy-binds.meta",
|
|
1840
|
+
"agy-binds-meta",
|
|
1841
|
+
"grok-binds",
|
|
1842
|
+
"grok-binds_meta",
|
|
1843
|
+
"grok-binds.meta",
|
|
1844
|
+
"grok-binds-meta",
|
|
1845
|
+
"agy-session-binds",
|
|
1846
|
+
"agy-session-binds_meta",
|
|
1847
|
+
"agy-session-binds.meta",
|
|
1848
|
+
"agy-session-binds-meta",
|
|
1849
|
+
"identity-guard",
|
|
1850
|
+
"cursor",
|
|
1851
|
+
"read-cursors",
|
|
1852
|
+
"mention-timestamps",
|
|
1853
|
+
"wake-pids",
|
|
1854
|
+
"config",
|
|
1855
|
+
"codex-bots",
|
|
1856
|
+
"dsh",
|
|
1857
|
+
"muse"
|
|
1858
|
+
]);
|
|
1859
|
+
async function readRegistrationText(res) {
|
|
1860
|
+
if (!res.body)
|
|
1861
|
+
throw new Error("Empty registration response");
|
|
1862
|
+
const reader = res.body.getReader();
|
|
1863
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
1864
|
+
let bytes = 0;
|
|
1865
|
+
let text = "";
|
|
1866
|
+
try {
|
|
1867
|
+
for (;; ) {
|
|
1868
|
+
const { done, value } = await reader.read();
|
|
1869
|
+
if (done)
|
|
1870
|
+
break;
|
|
1871
|
+
bytes += value.byteLength;
|
|
1872
|
+
if (bytes > 1024 * 1024)
|
|
1873
|
+
throw new Error("Registration response exceeds 1MiB");
|
|
1874
|
+
text += decoder.decode(value, { stream: true });
|
|
1875
|
+
}
|
|
1876
|
+
return text + decoder.decode();
|
|
1877
|
+
} catch (error) {
|
|
1878
|
+
reader.cancel().catch(() => {});
|
|
1879
|
+
throw error;
|
|
1880
|
+
} finally {
|
|
1881
|
+
reader.releaseLock();
|
|
1882
|
+
}
|
|
1883
|
+
}
|
|
1884
|
+
function isSafeAgentId2(value) {
|
|
1885
|
+
return typeof value === "string" && !!value && value.length <= 128 && value !== "." && value !== ".." && !FORBIDDEN_KEYS2.has(value.toLowerCase()) && !/[\s\x00-\x1f\x7f-\x9f\u2028\u2029/\\]/.test(value);
|
|
1886
|
+
}
|
|
1887
|
+
function validateChannelId(value) {
|
|
1888
|
+
if (!value || value.startsWith("--") || !isSafeAgentId2(value) || Object.getOwnPropertyNames(Object.prototype).some((key) => key.toLowerCase() === value.toLowerCase()))
|
|
1889
|
+
throw new Error("Invalid channel id: --send requires a channel id and --channel requires a value");
|
|
1890
|
+
return value;
|
|
1891
|
+
}
|
|
1892
|
+
function logText(value) {
|
|
1893
|
+
return redact(value.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, ""));
|
|
1894
|
+
}
|
|
1895
|
+
function promptHeader(value) {
|
|
1896
|
+
return value.replace(/[\r\n\x00-\x1f\x7f-\x9f\u2028\u2029]/g, "");
|
|
1897
|
+
}
|
|
1898
|
+
function isLoopbackHost2(hostname) {
|
|
1899
|
+
const h = hostname.toLowerCase().replace(/\.$/, "");
|
|
1900
|
+
return h === "localhost" || h === "127.0.0.1" || h === "[::1]" || h === "::1";
|
|
1901
|
+
}
|
|
1902
|
+
function validateHttpOrWsUrl(raw, allowedProtocols, label) {
|
|
1903
|
+
if (typeof raw !== "string" || DSH_CLI_PRETRIM_CTRL_RE.test(raw)) {
|
|
1904
|
+
throw new Error(`Invalid ${label} URL`);
|
|
1905
|
+
}
|
|
1906
|
+
const trimmed = raw.trim();
|
|
1907
|
+
if (!trimmed || raw !== trimmed || /[\x00-\x20\x7f-\x9f\u2028\u2029"<>\\]/.test(raw)) {
|
|
1908
|
+
throw new Error(`Invalid ${label} URL`);
|
|
1909
|
+
}
|
|
1910
|
+
let parsed;
|
|
1911
|
+
try {
|
|
1912
|
+
parsed = new URL(trimmed);
|
|
1913
|
+
} catch {
|
|
1914
|
+
throw new Error(`Invalid ${label} URL`);
|
|
1915
|
+
}
|
|
1916
|
+
if (isBlockedDshHost(parsed.hostname) || parsed.username || parsed.password || parsed.port === "0" || parsed.search || parsed.hash) {
|
|
1917
|
+
throw new Error(`Invalid ${label} URL`);
|
|
1918
|
+
}
|
|
1919
|
+
if (!allowedProtocols.includes(parsed.protocol)) {
|
|
1920
|
+
throw new Error(`Unsupported ${label} protocol: ${parsed.protocol}`);
|
|
1921
|
+
}
|
|
1922
|
+
if ((parsed.protocol === "ws:" || parsed.protocol === "http:") && !isLoopbackHost2(parsed.hostname)) {
|
|
1923
|
+
throw new Error(`Remote ${label} URL must use TLS (${parsed.protocol === "ws:" ? "wss://" : "https://"})`);
|
|
1924
|
+
}
|
|
1925
|
+
return trimmed;
|
|
1926
|
+
}
|
|
653
1927
|
function loadDshConfig(env = process.env, profilePath = DSH_PROFILE_PATH) {
|
|
654
1928
|
let profile = {};
|
|
655
1929
|
try {
|
|
656
|
-
|
|
657
|
-
|
|
1930
|
+
checkParentDirectory(profilePath);
|
|
1931
|
+
const lst = lstatSync7(profilePath);
|
|
1932
|
+
if (!lst.isSymbolicLink() && lst.isFile() && lst.size <= 256 * 1024) {
|
|
1933
|
+
const parsed = JSON.parse(readFileSync7(profilePath, "utf8"));
|
|
1934
|
+
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) && !Object.prototype.hasOwnProperty.call(parsed, "__proto__")) {
|
|
1935
|
+
profile = parsed;
|
|
1936
|
+
}
|
|
658
1937
|
}
|
|
659
1938
|
} catch {
|
|
660
1939
|
profile = {};
|
|
661
1940
|
}
|
|
662
|
-
const
|
|
663
|
-
const
|
|
664
|
-
|
|
1941
|
+
const rawAgentId = env.AGENTCHAT_AGENT_ID ?? (typeof profile.agentId === "string" ? profile.agentId : undefined);
|
|
1942
|
+
const rawToken = env.AGENTCHAT_TOKEN ?? (typeof profile.token === "string" ? profile.token : undefined);
|
|
1943
|
+
const agentId = typeof rawAgentId === "string" && !DSH_CLI_PRETRIM_CTRL_RE.test(rawAgentId) ? rawAgentId.trim() : "";
|
|
1944
|
+
const token = typeof rawToken === "string" && !DSH_CLI_PRETRIM_CTRL_RE.test(rawToken) ? rawToken.trim() : "";
|
|
1945
|
+
if (!isSafeAgentId2(agentId) || !token || DSH_CLI_CTRL_RE.test(agentId) || DSH_CLI_CTRL_RE.test(token)) {
|
|
665
1946
|
throw new Error("Missing AgentsChat identity for DSH: set AGENTCHAT_AGENT_ID and AGENTCHAT_TOKEN, " + `or create ${profilePath} via 'agentschat-mcp --dsh --register-only --name <name>'.`);
|
|
666
1947
|
}
|
|
1948
|
+
const wsUrl = validateHttpOrWsUrl(env.AGENTCHAT_WS_URL ?? (typeof profile.wsUrl === "string" ? profile.wsUrl : DEFAULT_WS_URL), ["ws:", "wss:"], "AgentChat WebSocket");
|
|
1949
|
+
const restUrl = validateHttpOrWsUrl(env.AGENTCHAT_REST_URL ?? (typeof profile.restUrl === "string" ? profile.restUrl : DEFAULT_REST_URL), ["http:", "https:"], "AgentChat REST");
|
|
1950
|
+
const rawDisplay = env.AGENTCHAT_DISPLAY_NAME ?? (typeof profile.displayName === "string" ? profile.displayName : undefined);
|
|
1951
|
+
const rawChan = env.AGENTCHAT_CHANNEL_ID ?? (typeof profile.defaultChannelId === "string" ? profile.defaultChannelId : undefined);
|
|
1952
|
+
const cleanDisplay = typeof rawDisplay === "string" ? rawDisplay.replace(DSH_CLI_CTRL_RE, "").trim() : "";
|
|
667
1953
|
return {
|
|
668
1954
|
agentId,
|
|
669
1955
|
token,
|
|
670
|
-
wsUrl
|
|
671
|
-
restUrl
|
|
672
|
-
displayName:
|
|
673
|
-
defaultChannelId:
|
|
1956
|
+
wsUrl,
|
|
1957
|
+
restUrl,
|
|
1958
|
+
displayName: cleanDisplay || undefined,
|
|
1959
|
+
defaultChannelId: rawChan?.trim() || undefined
|
|
674
1960
|
};
|
|
675
1961
|
}
|
|
676
1962
|
function safeDshConfig(config) {
|
|
@@ -684,59 +1970,173 @@ function safeDshConfig(config) {
|
|
|
684
1970
|
};
|
|
685
1971
|
}
|
|
686
1972
|
async function registerOnly(name, restUrl, profilePath = DSH_PROFILE_PATH) {
|
|
1973
|
+
if (typeof name !== "string" || DSH_CLI_PRETRIM_CTRL_RE.test(name)) {
|
|
1974
|
+
throw new Error("Invalid --name value");
|
|
1975
|
+
}
|
|
1976
|
+
const cleanName = name.trim();
|
|
1977
|
+
if (!cleanName || cleanName.length > 64 || DSH_CLI_CTRL_RE.test(cleanName)) {
|
|
1978
|
+
throw new Error("Invalid --name value");
|
|
1979
|
+
}
|
|
1980
|
+
checkParentDirectory(profilePath);
|
|
1981
|
+
const safeRestUrl = validateHttpOrWsUrl(restUrl, ["http:", "https:"], "AgentChat REST");
|
|
687
1982
|
console.log("Terms notice: https://agents-chat.com/terms (notice only, no acceptance prompt)");
|
|
688
|
-
const res = await fetch(`${
|
|
1983
|
+
const res = await fetch(`${safeRestUrl.replace(/\/+$/, "")}/api/account/register`, {
|
|
689
1984
|
method: "POST",
|
|
690
1985
|
headers: { "content-type": "application/json" },
|
|
691
|
-
body: JSON.stringify({ name, type: "agent", capabilities: ["chat"] })
|
|
1986
|
+
body: JSON.stringify({ name: cleanName, type: "agent", capabilities: ["chat"] }),
|
|
1987
|
+
redirect: "error",
|
|
1988
|
+
signal: AbortSignal.timeout(15000)
|
|
692
1989
|
});
|
|
693
|
-
if (!res.ok)
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
const
|
|
698
|
-
if (
|
|
699
|
-
throw new Error("
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
1990
|
+
if (!res.ok) {
|
|
1991
|
+
const errText = redact((await readRegistrationText(res)).slice(0, 300));
|
|
1992
|
+
throw new Error(`Registration failed: ${res.status} ${errText}`);
|
|
1993
|
+
}
|
|
1994
|
+
const data = JSON.parse(await readRegistrationText(res));
|
|
1995
|
+
if (data === null || typeof data !== "object" || Array.isArray(data) || Object.getPrototypeOf(data) !== Object.prototype || Object.prototype.hasOwnProperty.call(data, "__proto__")) {
|
|
1996
|
+
throw new Error("Invalid registration response object");
|
|
1997
|
+
}
|
|
1998
|
+
const rawAgentId = data.agentId ?? data.agent_id ?? data.id;
|
|
1999
|
+
const rawToken = data.agentKey ?? data.token ?? data.key;
|
|
2000
|
+
const agentId = typeof rawAgentId === "string" && !DSH_CLI_CTRL_RE.test(rawAgentId) ? rawAgentId.trim() : "";
|
|
2001
|
+
const token = typeof rawToken === "string" && !DSH_CLI_CTRL_RE.test(rawToken) ? rawToken.trim() : "";
|
|
2002
|
+
if (!isSafeAgentId2(rawAgentId) || !token || DSH_CLI_CTRL_RE.test(agentId) || DSH_CLI_CTRL_RE.test(token)) {
|
|
2003
|
+
throw new Error("Registration response did not include a valid agent id/token");
|
|
2004
|
+
}
|
|
2005
|
+
try {
|
|
2006
|
+
const lst = lstatSync7(profilePath);
|
|
2007
|
+
if (lst.isSymbolicLink() || !lst.isFile()) {
|
|
2008
|
+
throw new Error(`Refusing to overwrite non-regular file ${profilePath}`);
|
|
2009
|
+
}
|
|
2010
|
+
} catch (err) {
|
|
2011
|
+
if (err?.code !== "ENOENT")
|
|
2012
|
+
throw err;
|
|
2013
|
+
}
|
|
2014
|
+
checkParentDirectory(profilePath);
|
|
2015
|
+
mkdirSync4(dirname6(profilePath), { recursive: true, mode: 448 });
|
|
2016
|
+
checkParentDirectory(profilePath);
|
|
2017
|
+
const tmp = `${profilePath}.${process.pid}.${randomBytes3(4).toString("hex")}.tmp`;
|
|
2018
|
+
let created = false;
|
|
2019
|
+
try {
|
|
2020
|
+
writeFileSync3(tmp, JSON.stringify({ agentId, token }, null, 2), { mode: 384, flag: "wx" });
|
|
2021
|
+
created = true;
|
|
2022
|
+
checkParentDirectory(profilePath);
|
|
2023
|
+
try {
|
|
2024
|
+
const lst = lstatSync7(profilePath);
|
|
2025
|
+
if (lst.isSymbolicLink() || !lst.isFile())
|
|
2026
|
+
throw new Error(`Refusing to overwrite non-regular file ${profilePath}`);
|
|
2027
|
+
} catch (err) {
|
|
2028
|
+
if (err?.code !== "ENOENT")
|
|
2029
|
+
throw err;
|
|
2030
|
+
}
|
|
2031
|
+
try {
|
|
2032
|
+
renameSync3(tmp, profilePath);
|
|
2033
|
+
} catch (renameErr) {
|
|
2034
|
+
if (renameErr?.code !== "EPERM" && renameErr?.code !== "EACCES") {
|
|
2035
|
+
throw renameErr;
|
|
2036
|
+
}
|
|
2037
|
+
checkParentDirectory(profilePath);
|
|
2038
|
+
try {
|
|
2039
|
+
const lst = lstatSync7(profilePath);
|
|
2040
|
+
if (lst.isSymbolicLink() || !lst.isFile())
|
|
2041
|
+
throw new Error(`Refusing to overwrite non-regular file ${profilePath}`);
|
|
2042
|
+
} catch (err) {
|
|
2043
|
+
if (err?.code !== "ENOENT")
|
|
2044
|
+
throw err;
|
|
2045
|
+
}
|
|
2046
|
+
copyFileSync3(tmp, profilePath);
|
|
2047
|
+
try {
|
|
2048
|
+
unlinkSync4(tmp);
|
|
2049
|
+
} catch {}
|
|
2050
|
+
created = false;
|
|
2051
|
+
}
|
|
2052
|
+
if (process.platform !== "win32") {
|
|
2053
|
+
try {
|
|
2054
|
+
chmodSync3(profilePath, 384);
|
|
2055
|
+
} catch {}
|
|
2056
|
+
}
|
|
2057
|
+
} catch (err) {
|
|
2058
|
+
if (created) {
|
|
2059
|
+
try {
|
|
2060
|
+
unlinkSync4(tmp);
|
|
2061
|
+
} catch {}
|
|
2062
|
+
}
|
|
2063
|
+
throw err;
|
|
2064
|
+
}
|
|
2065
|
+
console.log(`Registered DSH agent '${cleanName}' as ${agentId}. Identity saved to ${profilePath} (token not printed).`);
|
|
703
2066
|
}
|
|
704
2067
|
async function runDshHeadlessResponder(prompt, opts = {}) {
|
|
705
|
-
const
|
|
706
|
-
const
|
|
707
|
-
const
|
|
708
|
-
|
|
709
|
-
|
|
2068
|
+
const rawBin = opts.dshBin ?? process.env.DSH_BIN ?? "dsh";
|
|
2069
|
+
const rawProfile = opts.dshProfile ?? process.env.DSH_PROFILE ?? "headless";
|
|
2070
|
+
const dshBin = typeof rawBin === "string" && !DSH_CLI_PRETRIM_CTRL_RE.test(rawBin) ? rawBin.trim() : "";
|
|
2071
|
+
const dshProfile = typeof rawProfile === "string" && !DSH_CLI_PRETRIM_CTRL_RE.test(rawProfile) ? rawProfile.trim() : "";
|
|
2072
|
+
if (!dshBin || DSH_CLI_CTRL_RE.test(dshBin)) {
|
|
2073
|
+
console.error("[dsh] invalid dshBin");
|
|
2074
|
+
return null;
|
|
2075
|
+
}
|
|
2076
|
+
if (!dshProfile || dshProfile.startsWith("-") || DSH_CLI_CTRL_RE.test(dshProfile)) {
|
|
2077
|
+
console.error("[dsh] invalid dshProfile");
|
|
2078
|
+
return null;
|
|
2079
|
+
}
|
|
2080
|
+
const t = opts.timeoutMs ?? 120000;
|
|
2081
|
+
const timeoutMs = Number.isFinite(t) && t > 0 ? Math.min(Math.floor(t), 2147483647) : 120000;
|
|
2082
|
+
return new Promise((resolve5) => {
|
|
2083
|
+
const resolved = resolveWindowsCliSpawn(dshBin, ["--profile", dshProfile, prompt], { env: process.env });
|
|
2084
|
+
const child = spawn(resolved.cmd, resolved.args, {
|
|
710
2085
|
stdio: ["ignore", "pipe", "pipe"],
|
|
711
|
-
env: process.env
|
|
2086
|
+
env: process.env,
|
|
2087
|
+
windowsHide: true
|
|
712
2088
|
});
|
|
713
2089
|
let stdout = "";
|
|
714
2090
|
let stderr = "";
|
|
2091
|
+
let killTimer;
|
|
2092
|
+
const clearTimers = () => {
|
|
2093
|
+
clearTimeout(timer);
|
|
2094
|
+
if (killTimer) {
|
|
2095
|
+
clearTimeout(killTimer);
|
|
2096
|
+
killTimer = undefined;
|
|
2097
|
+
}
|
|
2098
|
+
};
|
|
715
2099
|
const timer = setTimeout(() => {
|
|
716
2100
|
try {
|
|
717
2101
|
child.kill("SIGTERM");
|
|
718
2102
|
} catch {}
|
|
2103
|
+
killTimer = setTimeout(() => {
|
|
2104
|
+
killTimer = undefined;
|
|
2105
|
+
if (child.exitCode === null) {
|
|
2106
|
+
try {
|
|
2107
|
+
child.kill("SIGKILL");
|
|
2108
|
+
} catch {}
|
|
2109
|
+
}
|
|
2110
|
+
}, 3000);
|
|
2111
|
+
killTimer.unref?.();
|
|
719
2112
|
}, timeoutMs);
|
|
2113
|
+
timer.unref?.();
|
|
720
2114
|
child.stdout.on("data", (chunk) => {
|
|
721
|
-
stdout
|
|
2115
|
+
if (stdout.length < 2000000) {
|
|
2116
|
+
const text = chunk.toString("utf8");
|
|
2117
|
+
stdout += text.slice(0, 2000000 - stdout.length);
|
|
2118
|
+
}
|
|
722
2119
|
});
|
|
723
2120
|
child.stderr.on("data", (chunk) => {
|
|
724
|
-
stderr
|
|
2121
|
+
if (stderr.length < 65536) {
|
|
2122
|
+
const text = chunk.toString("utf8");
|
|
2123
|
+
stderr += text.slice(0, 65536 - stderr.length);
|
|
2124
|
+
}
|
|
725
2125
|
});
|
|
726
2126
|
child.on("error", (err) => {
|
|
727
|
-
|
|
728
|
-
console.error(`[dsh] failed to spawn ${dshBin}: ${err.message}`);
|
|
729
|
-
|
|
2127
|
+
clearTimers();
|
|
2128
|
+
console.error(`[dsh] failed to spawn ${dshBin}: ${redact(err.message)}`);
|
|
2129
|
+
resolve5(null);
|
|
730
2130
|
});
|
|
731
2131
|
child.on("close", (code) => {
|
|
732
|
-
|
|
2132
|
+
clearTimers();
|
|
733
2133
|
if (code !== 0) {
|
|
734
|
-
console.error(`[dsh] exited with code ${code}: ${stderr.trim().slice(0, 300)}`);
|
|
735
|
-
|
|
2134
|
+
console.error(`[dsh] exited with code ${code}: ${redact(stderr.trim().slice(0, 300))}`);
|
|
2135
|
+
resolve5(null);
|
|
736
2136
|
return;
|
|
737
2137
|
}
|
|
738
2138
|
const trimmed = stdout.trim();
|
|
739
|
-
|
|
2139
|
+
resolve5(trimmed.length > 0 ? trimmed : null);
|
|
740
2140
|
});
|
|
741
2141
|
});
|
|
742
2142
|
}
|
|
@@ -758,6 +2158,10 @@ DeepSeek Harness (dsh) integration for AgentsChat:
|
|
|
758
2158
|
npx -y agentschat-mcp@latest --dsh --send <channel-id> --text <text>`);
|
|
759
2159
|
return;
|
|
760
2160
|
}
|
|
2161
|
+
for (let i = 0;i < argv.length; i++) {
|
|
2162
|
+
if (argv[i] === "--channel" || argv[i] === "--send")
|
|
2163
|
+
validateChannelId(argv[i + 1]);
|
|
2164
|
+
}
|
|
761
2165
|
if (has("--setup", argv)) {
|
|
762
2166
|
const dshHome = arg("--dsh-home", argv);
|
|
763
2167
|
const dshProfile = arg("--dsh-profile", argv);
|
|
@@ -788,15 +2192,16 @@ DeepSeek Harness (dsh) integration for AgentsChat:
|
|
|
788
2192
|
} catch {
|
|
789
2193
|
console.log("[dsh-wake] No global dsh.json identity; watching session-binds.json for bound DSH sessions.");
|
|
790
2194
|
}
|
|
791
|
-
const defaultWsUrl = primaryConfig?.wsUrl ?? process.env.AGENTCHAT_WS_URL ?? DEFAULT_WS_URL;
|
|
792
|
-
const
|
|
2195
|
+
const defaultWsUrl = validateHttpOrWsUrl(primaryConfig?.wsUrl ?? process.env.AGENTCHAT_WS_URL ?? DEFAULT_WS_URL, ["ws:", "wss:"], "AgentChat WebSocket");
|
|
2196
|
+
const rawWakeChannels = [];
|
|
793
2197
|
for (let i = 0;i < argv.length; i++) {
|
|
794
2198
|
if (argv[i] === "--channel" && argv[i + 1])
|
|
795
|
-
|
|
2199
|
+
rawWakeChannels.push(argv[i + 1]);
|
|
796
2200
|
}
|
|
797
2201
|
if (primaryConfig?.defaultChannelId)
|
|
798
|
-
|
|
799
|
-
const
|
|
2202
|
+
rawWakeChannels.push(validateChannelId(primaryConfig.defaultChannelId));
|
|
2203
|
+
const wakeChannels = [...new Set(rawWakeChannels)];
|
|
2204
|
+
const queueFile = process.env.DSH_WAKE_QUEUE ?? join6(homedir5(), ".agentschat", "dsh-wake-queue.jsonl");
|
|
800
2205
|
const wakeUrl = process.env.DSH_WAKE_URL ?? process.env.AGENTCHAT_WAKE_URL;
|
|
801
2206
|
const wakeSecret = process.env.DSH_WAKE_SECRET ?? process.env.AGENTCHAT_WAKE_SECRET;
|
|
802
2207
|
const connectedAgentIds = new Set;
|
|
@@ -811,7 +2216,7 @@ DeepSeek Harness (dsh) integration for AgentsChat:
|
|
|
811
2216
|
typing.stop(m.channel_id);
|
|
812
2217
|
return;
|
|
813
2218
|
}
|
|
814
|
-
const kind = m.channel_id
|
|
2219
|
+
const kind = /^dm[-:]/i.test(m.channel_id) ? "direct" : "group";
|
|
815
2220
|
if (!shouldDispatch(m, { agentId: botIdentity.agentId, displayName: botIdentity.displayName, channelKind: kind }))
|
|
816
2221
|
return;
|
|
817
2222
|
typing.start(m.channel_id);
|
|
@@ -819,7 +2224,7 @@ DeepSeek Harness (dsh) integration for AgentsChat:
|
|
|
819
2224
|
const payload = buildWakePayload({ ...m, type: "message" }, { targetSessionId: route?.sessionId });
|
|
820
2225
|
const queued = appendWakeQueue(queueFile, payload);
|
|
821
2226
|
fireWake({ ...m, type: "message" }, { url: wakeUrl, secret: wakeSecret, logger: console.error, targetSessionId: route?.sessionId });
|
|
822
|
-
console.log(`[dsh-wake] ${m.channel_id} ${m.sender_id} ${m.id} agent=${botIdentity.agentId} queued=${queued} target=${route?.sessionId ?? "unbound"}`);
|
|
2227
|
+
console.log(`[dsh-wake] ${logText(`${m.channel_id} ${m.sender_id} ${m.id} agent=${botIdentity.agentId} queued=${queued} target=${route?.sessionId ?? "unbound"}`)}`);
|
|
823
2228
|
});
|
|
824
2229
|
botClient.onReconnect = () => {
|
|
825
2230
|
for (const c of wakeChannels)
|
|
@@ -843,63 +2248,116 @@ DeepSeek Harness (dsh) integration for AgentsChat:
|
|
|
843
2248
|
for (const c of wakeChannels)
|
|
844
2249
|
primaryClient.joinChannel(c);
|
|
845
2250
|
}
|
|
2251
|
+
let syncInFlight = false;
|
|
846
2252
|
const syncBoundDshClients = async () => {
|
|
2253
|
+
if (syncInFlight)
|
|
2254
|
+
return;
|
|
2255
|
+
syncInFlight = true;
|
|
847
2256
|
try {
|
|
848
2257
|
const cfgDir = agentschatConfigDir();
|
|
849
2258
|
const binds = loadSessionBinds(cfgDir);
|
|
850
2259
|
for (const [sid, profName] of Object.entries(binds)) {
|
|
851
|
-
if (!sid.startsWith("session-") || !profName)
|
|
852
|
-
continue;
|
|
853
|
-
const base = profName.replace(/\.json$/, "").replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
854
|
-
const candidates = [join5(cfgDir, "profiles", `${base}.json`), join5(cfgDir, `${base}.json`)];
|
|
855
|
-
const profPath = candidates.find((p) => existsSync5(p));
|
|
856
|
-
if (!profPath)
|
|
2260
|
+
if (!sid.startsWith("session-") || sid.length > 128 || sid.includes("..") || /[\s\x00-\x1f\x7f-\x9f\u2028\u2029/\\]/.test(sid) || FORBIDDEN_KEYS2.has(sid.toLowerCase()) || !profName || typeof profName !== "string") {
|
|
857
2261
|
continue;
|
|
858
|
-
|
|
859
|
-
const
|
|
860
|
-
|
|
861
|
-
const botWsUrl = typeof raw.server === "string" && /^wss?:\/\//i.test(raw.server) ? raw.server : defaultWsUrl;
|
|
862
|
-
if (!botAgentId || !botToken || botToken === "dev-token" || connectedAgentIds.has(botAgentId))
|
|
2262
|
+
}
|
|
2263
|
+
const base = profName.replace(/\.json$/i, "").replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
2264
|
+
if (!base || base.length > 64 || FORBIDDEN_KEYS2.has(base.toLowerCase()) || RESERVED_DSH_PROFILE_BASENAMES.has(base.toLowerCase())) {
|
|
863
2265
|
continue;
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
2266
|
+
}
|
|
2267
|
+
let extraClient = null;
|
|
2268
|
+
try {
|
|
2269
|
+
const candidates = [join6(cfgDir, "profiles", `${base}.json`), join6(cfgDir, `${base}.json`)];
|
|
2270
|
+
const profPath = candidates.find((p) => {
|
|
2271
|
+
try {
|
|
2272
|
+
checkParentDirectory(p);
|
|
2273
|
+
const lst = lstatSync7(p);
|
|
2274
|
+
return !lst.isSymbolicLink() && lst.isFile() && lst.size <= 256 * 1024;
|
|
2275
|
+
} catch {
|
|
2276
|
+
return false;
|
|
2277
|
+
}
|
|
2278
|
+
});
|
|
2279
|
+
if (!profPath)
|
|
2280
|
+
continue;
|
|
2281
|
+
const raw = JSON.parse(readFileSync7(profPath, "utf8"));
|
|
2282
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw) || Object.prototype.hasOwnProperty.call(raw, "__proto__"))
|
|
2283
|
+
continue;
|
|
2284
|
+
const rawAgentId = typeof raw.agent_id === "string" ? raw.agent_id : typeof raw.agentId === "string" ? raw.agentId : "";
|
|
2285
|
+
const rawToken = typeof raw.token === "string" ? raw.token : "";
|
|
2286
|
+
const botAgentId = rawAgentId.trim();
|
|
2287
|
+
const botToken = rawToken.trim();
|
|
2288
|
+
let botWsUrl = defaultWsUrl;
|
|
2289
|
+
if (typeof raw.server === "string" && raw.server.trim()) {
|
|
2290
|
+
try {
|
|
2291
|
+
botWsUrl = validateHttpOrWsUrl(raw.server.trim(), ["ws:", "wss:"], "AgentChat WebSocket");
|
|
2292
|
+
} catch {
|
|
2293
|
+
botWsUrl = defaultWsUrl;
|
|
2294
|
+
}
|
|
2295
|
+
}
|
|
2296
|
+
if (!isSafeAgentId2(rawAgentId) || !botToken || botToken === "dev-token" || DSH_CLI_CTRL_RE.test(rawAgentId) || DSH_CLI_CTRL_RE.test(rawToken) || connectedAgentIds.has(botAgentId)) {
|
|
2297
|
+
continue;
|
|
2298
|
+
}
|
|
2299
|
+
extraClient = new MuseAgentChatClient({
|
|
2300
|
+
url: botWsUrl,
|
|
2301
|
+
agentId: botAgentId,
|
|
2302
|
+
token: botToken,
|
|
2303
|
+
capabilities: ["chat"]
|
|
2304
|
+
});
|
|
2305
|
+
await extraClient.connect();
|
|
2306
|
+
connectedAgentIds.add(botAgentId);
|
|
2307
|
+
attachWakeForClient(extraClient, {
|
|
2308
|
+
agentId: botAgentId,
|
|
2309
|
+
displayName: typeof raw.display_name === "string" ? raw.display_name : undefined
|
|
2310
|
+
});
|
|
2311
|
+
for (const c of wakeChannels)
|
|
2312
|
+
extraClient.joinChannel(c);
|
|
2313
|
+
console.log(`[dsh-wake] ${logText(`Connected bound session ${sid} -> ${profName} (${botAgentId})`)}`);
|
|
2314
|
+
} catch (err) {
|
|
2315
|
+
try {
|
|
2316
|
+
extraClient?.disconnect();
|
|
2317
|
+
} catch {}
|
|
2318
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2319
|
+
console.error(`[dsh-wake] ${logText(`Failed to connect bound session ${sid} (${profName}): ${msg}`)}`);
|
|
2320
|
+
}
|
|
879
2321
|
}
|
|
880
|
-
} catch {}
|
|
2322
|
+
} catch {} finally {
|
|
2323
|
+
syncInFlight = false;
|
|
2324
|
+
}
|
|
881
2325
|
};
|
|
882
2326
|
await syncBoundDshClients();
|
|
883
2327
|
const bindTimer = setInterval(() => void syncBoundDshClients(), 3000);
|
|
2328
|
+
bindTimer.unref?.();
|
|
884
2329
|
console.log(`DSH wake daemon listening on ${wakeChannels.join(", ") || "(no channels — pass --channel <id>)"}, queue=${queueFile}.`);
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
2330
|
+
let shutdownWakeRef;
|
|
2331
|
+
try {
|
|
2332
|
+
await new Promise((resolve5) => {
|
|
2333
|
+
const shutdown = () => {
|
|
2334
|
+
for (const t of activeTyping)
|
|
2335
|
+
t.stopAll();
|
|
2336
|
+
for (const c of activeClients) {
|
|
2337
|
+
try {
|
|
2338
|
+
c.disconnect();
|
|
2339
|
+
} catch {}
|
|
2340
|
+
}
|
|
2341
|
+
resolve5();
|
|
2342
|
+
};
|
|
2343
|
+
shutdownWakeRef = shutdown;
|
|
2344
|
+
process.once("SIGINT", shutdown);
|
|
2345
|
+
process.once("SIGTERM", shutdown);
|
|
2346
|
+
if (process.platform !== "win32")
|
|
2347
|
+
process.once("SIGHUP", shutdown);
|
|
2348
|
+
if (primaryClient) {
|
|
2349
|
+
primaryClient.waitUntilClosed().then(resolve5);
|
|
893
2350
|
}
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
2351
|
+
});
|
|
2352
|
+
} finally {
|
|
2353
|
+
clearInterval(bindTimer);
|
|
2354
|
+
if (shutdownWakeRef) {
|
|
2355
|
+
process.removeListener("SIGINT", shutdownWakeRef);
|
|
2356
|
+
process.removeListener("SIGTERM", shutdownWakeRef);
|
|
2357
|
+
if (process.platform !== "win32")
|
|
2358
|
+
process.removeListener("SIGHUP", shutdownWakeRef);
|
|
900
2359
|
}
|
|
901
|
-
}
|
|
902
|
-
clearInterval(bindTimer);
|
|
2360
|
+
}
|
|
903
2361
|
return;
|
|
904
2362
|
}
|
|
905
2363
|
const config = loadDshConfig();
|
|
@@ -924,18 +2382,19 @@ DeepSeek Harness (dsh) integration for AgentsChat:
|
|
|
924
2382
|
return;
|
|
925
2383
|
}
|
|
926
2384
|
if (has("--listen", argv)) {
|
|
927
|
-
const
|
|
2385
|
+
const rawChannels = [];
|
|
928
2386
|
for (let i = 0;i < argv.length; i++) {
|
|
929
2387
|
if (argv[i] === "--channel" && argv[i + 1])
|
|
930
|
-
|
|
2388
|
+
rawChannels.push(argv[i + 1]);
|
|
931
2389
|
}
|
|
932
2390
|
if (config.defaultChannelId)
|
|
933
|
-
|
|
2391
|
+
rawChannels.push(validateChannelId(config.defaultChannelId));
|
|
2392
|
+
const channels = [...new Set(rawChannels)];
|
|
934
2393
|
const autoReply = arg("--auto-reply", argv);
|
|
935
2394
|
const dshProfile = arg("--dsh-profile", argv) ?? "headless";
|
|
936
2395
|
const channelKinds = {};
|
|
937
2396
|
for (const c of channels) {
|
|
938
|
-
channelKinds[c] =
|
|
2397
|
+
channelKinds[c] = /^dm[-:]/i.test(c) ? "direct" : "group";
|
|
939
2398
|
}
|
|
940
2399
|
const bridge = new MuseBridge(client, {
|
|
941
2400
|
agentId: config.agentId,
|
|
@@ -943,15 +2402,15 @@ DeepSeek Harness (dsh) integration for AgentsChat:
|
|
|
943
2402
|
channels,
|
|
944
2403
|
channelKinds,
|
|
945
2404
|
responder: async (ctx) => {
|
|
946
|
-
console.log(`[inbound] ${ctx.message.channel_id} ${ctx.message.sender_id}: ${ctx.message.content}`);
|
|
2405
|
+
console.log(`[inbound] ${logText(`${ctx.message.channel_id} ${ctx.message.sender_id}: ${ctx.message.content}`)}`);
|
|
947
2406
|
if (autoReply)
|
|
948
2407
|
return autoReply;
|
|
949
2408
|
const prompt = [
|
|
950
2409
|
`You are DeepSeek Harness agent ${config.agentId} on AgentsChat.`,
|
|
951
|
-
`Reply concisely to the latest message in channel ${ctx.message.channel_id}.`,
|
|
2410
|
+
`Reply concisely to the latest message in channel ${promptHeader(ctx.message.channel_id)}.`,
|
|
952
2411
|
`Recent conversation context:
|
|
953
2412
|
${ctx.context}`,
|
|
954
|
-
`Latest message from ${ctx.message.sender_id}: ${ctx.message.content}`
|
|
2413
|
+
`Latest message from ${promptHeader(ctx.message.sender_id)}: ${ctx.message.content}`
|
|
955
2414
|
].join(`
|
|
956
2415
|
|
|
957
2416
|
`);
|
|
@@ -959,9 +2418,25 @@ ${ctx.context}`,
|
|
|
959
2418
|
}
|
|
960
2419
|
});
|
|
961
2420
|
client.onReconnect = () => bridge.rejoin();
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
2421
|
+
const shutdownListen = () => {
|
|
2422
|
+
try {
|
|
2423
|
+
client.disconnect();
|
|
2424
|
+
} catch {}
|
|
2425
|
+
};
|
|
2426
|
+
process.once("SIGINT", shutdownListen);
|
|
2427
|
+
process.once("SIGTERM", shutdownListen);
|
|
2428
|
+
if (process.platform !== "win32")
|
|
2429
|
+
process.once("SIGHUP", shutdownListen);
|
|
2430
|
+
try {
|
|
2431
|
+
await bridge.start();
|
|
2432
|
+
console.log(`DSH bridge listening on ${channels.join(", ") || "(no channels — pass --channel <id>)"} (profile=${dshProfile}).`);
|
|
2433
|
+
await client.waitUntilClosed();
|
|
2434
|
+
} finally {
|
|
2435
|
+
process.removeListener("SIGINT", shutdownListen);
|
|
2436
|
+
process.removeListener("SIGTERM", shutdownListen);
|
|
2437
|
+
if (process.platform !== "win32")
|
|
2438
|
+
process.removeListener("SIGHUP", shutdownListen);
|
|
2439
|
+
}
|
|
965
2440
|
return;
|
|
966
2441
|
}
|
|
967
2442
|
throw new Error("Specify --setup, --register-only, --wake, --listen, or --send (see --dsh --help)");
|
|
@@ -969,14 +2444,16 @@ ${ctx.context}`,
|
|
|
969
2444
|
var invokedDirectly = process.argv[1]?.endsWith("dsh/src/cli.ts") || process.argv[1]?.endsWith("dist/dsh.js") || process.argv.includes("--dsh");
|
|
970
2445
|
if (invokedDirectly) {
|
|
971
2446
|
main().catch((err) => {
|
|
972
|
-
console.error("DSH AgentsChat error:", err instanceof Error ? err.message : String(err));
|
|
2447
|
+
console.error("DSH AgentsChat error:", logText(err instanceof Error ? err.message : String(err)));
|
|
973
2448
|
process.exit(1);
|
|
974
2449
|
});
|
|
975
2450
|
}
|
|
976
2451
|
export {
|
|
977
2452
|
safeDshConfig,
|
|
978
2453
|
runDshHeadlessResponder,
|
|
2454
|
+
registerOnly,
|
|
979
2455
|
main,
|
|
980
2456
|
loadDshConfig,
|
|
2457
|
+
RESERVED_DSH_PROFILE_BASENAMES,
|
|
981
2458
|
DSH_PROFILE_PATH
|
|
982
2459
|
};
|