agentschat-mcp 0.36.23 → 0.36.24
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/codex/README.md +14 -0
- package/codex/app-server.ts +28 -2
- package/codex/bridge.ts +2 -0
- package/codex/run.ts +7 -1
- package/dist/codex-bridge.js +33 -3
- package/dist/server.js +957 -65
- package/package.json +3 -2
- package/skills/onboarding.md +16 -1
- package/src/cli.mjs +42 -0
- package/src/rest-cli.ts +774 -0
- package/src/server.ts +159 -16
- package/src/session-bind.ts +22 -5
package/dist/server.js
CHANGED
|
@@ -538,6 +538,22 @@ function redactSecrets2(text, opts) {
|
|
|
538
538
|
const step = opts?.preserveAcKeys ? text : text.replace(/ac_[A-Za-z0-9_-]{16,}/g, "ac_***REDACTED***");
|
|
539
539
|
return step.replace(/eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "***JWT_REDACTED***");
|
|
540
540
|
}
|
|
541
|
+
var PHONE_PII_RE2 = /^\+?\d[\d\s()-]{5,}$/;
|
|
542
|
+
function redactParticipantPii2(rawId) {
|
|
543
|
+
const s = String(rawId ?? "").trim();
|
|
544
|
+
if (!s)
|
|
545
|
+
return "unknown";
|
|
546
|
+
const atIdx = s.indexOf("@");
|
|
547
|
+
if (atIdx >= 0) {
|
|
548
|
+
const local = s.slice(0, atIdx).replace(/[^a-zA-Z0-9]/g, "");
|
|
549
|
+
return `user:${(local.slice(0, 2) || "u").toLowerCase()}***`;
|
|
550
|
+
}
|
|
551
|
+
if (PHONE_PII_RE2.test(s)) {
|
|
552
|
+
const digits = s.replace(/\D/g, "");
|
|
553
|
+
return `user:phone_***${digits.slice(-2) || "00"}`;
|
|
554
|
+
}
|
|
555
|
+
return s;
|
|
556
|
+
}
|
|
541
557
|
|
|
542
558
|
// src/wake.ts
|
|
543
559
|
var WAKE_SIG_HEADER = "x-agentschat-signature";
|
|
@@ -1215,7 +1231,9 @@ function detectRuntimeSession(env = process.env, meta) {
|
|
|
1215
1231
|
if (explicitSid) {
|
|
1216
1232
|
return { sessionId: explicitSid, runtime: "custom" };
|
|
1217
1233
|
}
|
|
1218
|
-
|
|
1234
|
+
const hasExplicitAgyEnv = env.__CFBundleIdentifier === "com.google.antigravity" || Boolean(env.AGY_BROWSER_WS_URL) || Boolean(env.ANTIGRAVITY_LS_ADDRESS) || Boolean(env.ANTIGRAVITY_CSRF_TOKEN);
|
|
1235
|
+
const isMockHubSubprocess = !hasExplicitAgyEnv && typeof env.AGENTCHAT_REST_URL === "string" && /^http:\/\/127\.0\.0\.1:\d+/.test(env.AGENTCHAT_REST_URL);
|
|
1236
|
+
if (!isMockHubSubprocess && (env === process.env || hasExplicitAgyEnv)) {
|
|
1219
1237
|
const agyHost = discoverAntigravityHost();
|
|
1220
1238
|
if (agyHost && agyHost.openConversations.length === 1) {
|
|
1221
1239
|
return { sessionId: agyHost.openConversations[0], runtime: "antigravity" };
|
|
@@ -1270,6 +1288,10 @@ function discoverAntigravityHost(opts) {
|
|
|
1270
1288
|
const openConversations = (process.env.ANTIGRAVITY_OPEN_CONVERSATIONS || "").split(",").map((s) => s.trim()).filter((s) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s));
|
|
1271
1289
|
return { lsPid: process.ppid, csrfToken: envCsrf, ports, openConversations };
|
|
1272
1290
|
}
|
|
1291
|
+
const hasExplicitAgyEnv = process.env.__CFBundleIdentifier === "com.google.antigravity" || Boolean(process.env.AGY_BROWSER_WS_URL);
|
|
1292
|
+
if (!hasExplicitAgyEnv && typeof process.env.AGENTCHAT_REST_URL === "string" && /^http:\/\/127\.0\.0\.1:\d+/.test(process.env.AGENTCHAT_REST_URL)) {
|
|
1293
|
+
return null;
|
|
1294
|
+
}
|
|
1273
1295
|
}
|
|
1274
1296
|
const now = Date.now();
|
|
1275
1297
|
const cacheMs = opts?.cacheMs ?? 5000;
|
|
@@ -1711,7 +1733,7 @@ class HeartbeatMonitor {
|
|
|
1711
1733
|
var package_default = {
|
|
1712
1734
|
name: "agentschat-mcp",
|
|
1713
1735
|
mcpName: "io.github.swswordholy-tech/agentschat-mcp",
|
|
1714
|
-
version: "0.36.
|
|
1736
|
+
version: "0.36.24",
|
|
1715
1737
|
description: "Connect Claude Code to AgentsChat — AI Agent social network. Core tools stay lean while extended tool groups load on demand for lower token overhead and cleaner role-specific context.",
|
|
1716
1738
|
type: "module",
|
|
1717
1739
|
bin: {
|
|
@@ -1727,7 +1749,7 @@ var package_default = {
|
|
|
1727
1749
|
scripts: {
|
|
1728
1750
|
start: "bun src/server.ts",
|
|
1729
1751
|
dev: "bun --watch src/server.ts",
|
|
1730
|
-
test: "bun test
|
|
1752
|
+
test: "bun test tests dsh/tests && node --experimental-strip-types --test muse/tests/*.test.mjs",
|
|
1731
1753
|
typecheck: "tsc --noEmit",
|
|
1732
1754
|
build: "bun scripts/build.mjs",
|
|
1733
1755
|
"check:version": "bun scripts/check-version-sync.mjs",
|
|
@@ -1818,6 +1840,7 @@ var package_default = {
|
|
|
1818
1840
|
"src/wake.ts",
|
|
1819
1841
|
"src/profile-store.ts",
|
|
1820
1842
|
"src/read-cursor.ts",
|
|
1843
|
+
"src/rest-cli.ts",
|
|
1821
1844
|
"connector/auth.ts",
|
|
1822
1845
|
"connector/descriptor.ts",
|
|
1823
1846
|
"connector/normalize.ts",
|
|
@@ -1857,8 +1880,8 @@ import {
|
|
|
1857
1880
|
CallToolRequestSchema,
|
|
1858
1881
|
ListToolsRequestSchema
|
|
1859
1882
|
} from "@modelcontextprotocol/sdk/types.js";
|
|
1860
|
-
import { readFileSync as
|
|
1861
|
-
import { join as
|
|
1883
|
+
import { readFileSync as readFileSync11, existsSync as existsSync8, writeFileSync as writeFileSync6, mkdirSync as mkdirSync4, readdirSync as readdirSync5 } from "fs";
|
|
1884
|
+
import { join as join8, dirname as dirname2 } from "path";
|
|
1862
1885
|
import { fileURLToPath } from "url";
|
|
1863
1886
|
|
|
1864
1887
|
// src/profile-store.ts
|
|
@@ -2074,6 +2097,728 @@ function flushCursor(state, persist) {
|
|
|
2074
2097
|
return ok;
|
|
2075
2098
|
}
|
|
2076
2099
|
|
|
2100
|
+
// src/rest-cli.ts
|
|
2101
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync3, readFileSync as readFileSync10, writeFileSync as writeFileSync5 } from "node:fs";
|
|
2102
|
+
import { dirname, join as join7 } from "node:path";
|
|
2103
|
+
|
|
2104
|
+
// src/mentions.ts
|
|
2105
|
+
function matchesMention2(content, agentId) {
|
|
2106
|
+
if (!content || !agentId)
|
|
2107
|
+
return false;
|
|
2108
|
+
if (content.includes(`@${agentId}`))
|
|
2109
|
+
return true;
|
|
2110
|
+
const idEsc = agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2111
|
+
const displayMentionRe = new RegExp(`@[^(\\n]+\\(${idEsc}\\)`);
|
|
2112
|
+
return displayMentionRe.test(content);
|
|
2113
|
+
}
|
|
2114
|
+
|
|
2115
|
+
// src/read-cursor.ts
|
|
2116
|
+
import { readFileSync as readFileSync9, writeFileSync as writeFileSync4 } from "fs";
|
|
2117
|
+
function loadCursor2(file, warn) {
|
|
2118
|
+
try {
|
|
2119
|
+
return new Map(Object.entries(JSON.parse(readFileSync9(file, "utf-8"))));
|
|
2120
|
+
} catch (e) {
|
|
2121
|
+
if (e?.code !== "ENOENT") {
|
|
2122
|
+
warn(`[agentchat] WARNING: could not read ${file} — resetting that state: ${e}
|
|
2123
|
+
`);
|
|
2124
|
+
}
|
|
2125
|
+
return new Map;
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
2128
|
+
function persistCursor2(file, cursor, warn) {
|
|
2129
|
+
try {
|
|
2130
|
+
writeFileSync4(file, JSON.stringify(Object.fromEntries(cursor)));
|
|
2131
|
+
return true;
|
|
2132
|
+
} catch (e) {
|
|
2133
|
+
warn(`[agentchat] WARNING: failed to persist read cursor to ${file}: ${e}
|
|
2134
|
+
`);
|
|
2135
|
+
return false;
|
|
2136
|
+
}
|
|
2137
|
+
}
|
|
2138
|
+
|
|
2139
|
+
// src/timestamps.ts
|
|
2140
|
+
function normalizeTimestampForCursor2(ts, mode) {
|
|
2141
|
+
if (!ts || typeof ts !== "string")
|
|
2142
|
+
return ts;
|
|
2143
|
+
const padChar = mode === "before" ? "9" : "0";
|
|
2144
|
+
const withFrac = ts.match(/^(.*\.)(\d+)(Z)$/);
|
|
2145
|
+
if (withFrac) {
|
|
2146
|
+
const frac = withFrac[2];
|
|
2147
|
+
if (frac.length >= 9)
|
|
2148
|
+
return ts;
|
|
2149
|
+
return withFrac[1] + frac + padChar.repeat(9 - frac.length) + withFrac[3];
|
|
2150
|
+
}
|
|
2151
|
+
const noFrac = ts.match(/^(.*\d)(Z)$/);
|
|
2152
|
+
if (noFrac) {
|
|
2153
|
+
return noFrac[1] + "." + padChar.repeat(9) + noFrac[2];
|
|
2154
|
+
}
|
|
2155
|
+
return ts;
|
|
2156
|
+
}
|
|
2157
|
+
|
|
2158
|
+
// src/wake.ts
|
|
2159
|
+
var NATIVE_WAKE_CONTENT_MAX2 = 4000;
|
|
2160
|
+
function formatWakeAttachments2(attachments) {
|
|
2161
|
+
if (!Array.isArray(attachments) || attachments.length === 0)
|
|
2162
|
+
return "";
|
|
2163
|
+
const lines = [];
|
|
2164
|
+
for (const raw of attachments) {
|
|
2165
|
+
if (!raw || typeof raw !== "object")
|
|
2166
|
+
continue;
|
|
2167
|
+
const a = raw;
|
|
2168
|
+
if (typeof a.url !== "string" || !a.url)
|
|
2169
|
+
continue;
|
|
2170
|
+
const t = typeof a.type === "string" ? a.type : "file";
|
|
2171
|
+
const dim = typeof a.width === "number" && typeof a.height === "number" ? ` ${a.width}×${a.height}` : "";
|
|
2172
|
+
const dur = typeof a.duration_ms === "number" ? ` ${(a.duration_ms / 1000).toFixed(1)}s` : "";
|
|
2173
|
+
const icon = t === "image" ? "\uD83D\uDDBC" : t === "video" ? "\uD83C\uDFAC" : t === "audio" ? "\uD83D\uDD0A" : "\uD83D\uDCCE";
|
|
2174
|
+
let desc = `${icon} ${t}${dim}${dur}: ${a.url}`;
|
|
2175
|
+
if (typeof a.transcript === "string" && a.transcript.trim()) {
|
|
2176
|
+
desc += ` (transcript: "${redactSecrets2(a.transcript.trim().slice(0, 300))}")`;
|
|
2177
|
+
}
|
|
2178
|
+
lines.push(desc);
|
|
2179
|
+
}
|
|
2180
|
+
return lines.length > 0 ? ` [附件: ${lines.join("; ")}]` : "";
|
|
2181
|
+
}
|
|
2182
|
+
var GROK_GATEWAY_PATH_CANDIDATES2 = [
|
|
2183
|
+
`${process.env.HOME}/.grok/gateway.json`,
|
|
2184
|
+
"/home/box/sand-data/gateway.json"
|
|
2185
|
+
];
|
|
2186
|
+
function buildWakePrompt2(msg, contextPrefix = "") {
|
|
2187
|
+
const rawContent = typeof msg.content === "string" ? msg.content : "";
|
|
2188
|
+
const isTruncated = rawContent.length > NATIVE_WAKE_CONTENT_MAX2;
|
|
2189
|
+
const redactOpts = msg.same_owner_direct === true ? { preserveAcKeys: true } : undefined;
|
|
2190
|
+
const content = rawContent ? redactSecrets2(rawContent.slice(0, NATIVE_WAKE_CONTENT_MAX2), redactOpts) : "";
|
|
2191
|
+
const cleanPrefix = contextPrefix ? redactSecrets2(contextPrefix.trim(), redactOpts) : "";
|
|
2192
|
+
const channel = msg.channel_id ?? "?";
|
|
2193
|
+
const sender = msg.sender_id ?? "someone";
|
|
2194
|
+
const msgId = msg.id ?? msg.message_id ?? "";
|
|
2195
|
+
const isDm = channel.startsWith("dm-");
|
|
2196
|
+
const where = isDm ? `私聊 (${channel})` : `频道 ${channel}`;
|
|
2197
|
+
const actionHint = isTruncated ? ` —— 消息过长已截断,可调用 get_history(chat_id, message_id) 查看全文,再用 reply 回复并 mark_read 标记已读` : ` —— 请直接用 reply 回复并用 mark_read 标记已读;仅在需要更早上下文时调用 get_history`;
|
|
2198
|
+
const attSummary = formatWakeAttachments2(msg.attachments);
|
|
2199
|
+
return (cleanPrefix ? `${cleanPrefix}
|
|
2200
|
+
|
|
2201
|
+
` : "") + `[AgentsChat] ${sender} 在${where}给你发了消息` + (content ? `:"${content}${isTruncated ? " …[truncated]" : ""}"` : "。") + attSummary + ` (channel_id=${channel}` + (msgId ? `, message_id=${msgId}` : "") + `${actionHint})`;
|
|
2202
|
+
}
|
|
2203
|
+
var zcodeSessionQueues2 = new Map;
|
|
2204
|
+
|
|
2205
|
+
// src/rest-cli.ts
|
|
2206
|
+
var CURSOR_INIT_KEY = "__init_ts__";
|
|
2207
|
+
var CURSOR_LAST_ACTIVE_KEY = "__last_active_ts__";
|
|
2208
|
+
var CURSOR_MAX_IDLE_KEY = "__max_idle_ms__";
|
|
2209
|
+
var DEFAULT_MAX_IDLE_MS = 60 * 60 * 1000;
|
|
2210
|
+
function parseMaxIdleMs(raw) {
|
|
2211
|
+
if (raw === undefined || raw === null)
|
|
2212
|
+
return;
|
|
2213
|
+
if (typeof raw === "number") {
|
|
2214
|
+
return Number.isFinite(raw) && raw >= 0 ? Math.round(raw * 1000) : undefined;
|
|
2215
|
+
}
|
|
2216
|
+
const s = String(raw).trim().toLowerCase();
|
|
2217
|
+
if (!s)
|
|
2218
|
+
return;
|
|
2219
|
+
if (s === "0" || s === "never" || s === "infinite" || s === "forever" || s === "off") {
|
|
2220
|
+
return 0;
|
|
2221
|
+
}
|
|
2222
|
+
const m = s.match(/^(\d+(?:\.\d+)?)\s*(ms|s|sec|secs|m|min|mins|h|hr|hrs|hour|hours|d|day|days)?$/);
|
|
2223
|
+
if (!m)
|
|
2224
|
+
return;
|
|
2225
|
+
const val = Number(m[1]);
|
|
2226
|
+
if (!Number.isFinite(val) || val < 0)
|
|
2227
|
+
return;
|
|
2228
|
+
const unit = m[2] || "s";
|
|
2229
|
+
if (unit === "ms")
|
|
2230
|
+
return Math.round(val);
|
|
2231
|
+
if (unit === "s" || unit === "sec" || unit === "secs")
|
|
2232
|
+
return Math.round(val * 1000);
|
|
2233
|
+
if (unit === "m" || unit === "min" || unit === "mins")
|
|
2234
|
+
return Math.round(val * 60000);
|
|
2235
|
+
if (unit === "h" || unit === "hr" || unit === "hrs" || unit === "hour" || unit === "hours") {
|
|
2236
|
+
return Math.round(val * 3600000);
|
|
2237
|
+
}
|
|
2238
|
+
if (unit === "d" || unit === "day" || unit === "days")
|
|
2239
|
+
return Math.round(val * 86400000);
|
|
2240
|
+
return;
|
|
2241
|
+
}
|
|
2242
|
+
var MAX_SSE_STREAMS = 3;
|
|
2243
|
+
var MAX_SEEN_IDS = 200;
|
|
2244
|
+
function loadSeenIds(file) {
|
|
2245
|
+
if (!existsSync7(file))
|
|
2246
|
+
return [];
|
|
2247
|
+
try {
|
|
2248
|
+
const parsed = JSON.parse(readFileSync10(file, "utf8"));
|
|
2249
|
+
return Array.isArray(parsed) ? parsed.filter((x) => typeof x === "string") : [];
|
|
2250
|
+
} catch {
|
|
2251
|
+
return [];
|
|
2252
|
+
}
|
|
2253
|
+
}
|
|
2254
|
+
function saveSeenIds(file, ids) {
|
|
2255
|
+
try {
|
|
2256
|
+
mkdirSync3(dirname(file), { recursive: true });
|
|
2257
|
+
const list = [...ids].slice(-MAX_SEEN_IDS);
|
|
2258
|
+
safeWriteProfile(file, list);
|
|
2259
|
+
} catch {}
|
|
2260
|
+
}
|
|
2261
|
+
function loadJsonMap(file) {
|
|
2262
|
+
if (!existsSync7(file))
|
|
2263
|
+
return {};
|
|
2264
|
+
try {
|
|
2265
|
+
const raw = JSON.parse(readFileSync10(file, "utf8"));
|
|
2266
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
2267
|
+
return {};
|
|
2268
|
+
return raw;
|
|
2269
|
+
} catch {
|
|
2270
|
+
return {};
|
|
2271
|
+
}
|
|
2272
|
+
}
|
|
2273
|
+
function saveJsonMap(file, data) {
|
|
2274
|
+
try {
|
|
2275
|
+
mkdirSync3(dirname(file), { recursive: true });
|
|
2276
|
+
safeWriteProfile(file, data);
|
|
2277
|
+
} catch {}
|
|
2278
|
+
}
|
|
2279
|
+
function advanceChannelReadCursor(opts) {
|
|
2280
|
+
const { configDir, agentId, channelId, timestamp } = opts;
|
|
2281
|
+
if (!agentId || !channelId || !timestamp)
|
|
2282
|
+
return;
|
|
2283
|
+
const warn = opts.warn ?? ((m) => process.stderr.write(m));
|
|
2284
|
+
mkdirSync3(configDir, { recursive: true });
|
|
2285
|
+
const lastSeenFile = join7(configDir, `last-seen-msg-ts-${agentId}.json`);
|
|
2286
|
+
const cursor = loadCursor2(lastSeenFile, warn);
|
|
2287
|
+
const prev = cursor.get(channelId) || "";
|
|
2288
|
+
const nextNorm = normalizeTimestampForCursor2(timestamp, "after") || timestamp;
|
|
2289
|
+
const prevNorm = normalizeTimestampForCursor2(prev, "after") || prev;
|
|
2290
|
+
cursor.set(CURSOR_LAST_ACTIVE_KEY, timestamp);
|
|
2291
|
+
if (opts.maxIdleMs !== undefined && Number.isFinite(opts.maxIdleMs) && opts.maxIdleMs >= 0) {
|
|
2292
|
+
cursor.set(CURSOR_MAX_IDLE_KEY, String(Math.round(opts.maxIdleMs)));
|
|
2293
|
+
}
|
|
2294
|
+
if (!prev || nextNorm > prevNorm) {
|
|
2295
|
+
cursor.set(channelId, timestamp);
|
|
2296
|
+
}
|
|
2297
|
+
persistCursor2(lastSeenFile, cursor, warn);
|
|
2298
|
+
const readCursorsFile = join7(configDir, "read-cursors.json");
|
|
2299
|
+
const readCursors = loadJsonMap(readCursorsFile);
|
|
2300
|
+
const scopedKey = `${agentId}:${channelId}`;
|
|
2301
|
+
const prevRead = readCursors[scopedKey] || readCursors[channelId] || "";
|
|
2302
|
+
const prevReadNorm = normalizeTimestampForCursor2(prevRead, "after") || prevRead;
|
|
2303
|
+
if (!prevRead || nextNorm > prevReadNorm) {
|
|
2304
|
+
readCursors[scopedKey] = timestamp;
|
|
2305
|
+
readCursors[channelId] = timestamp;
|
|
2306
|
+
saveJsonMap(readCursorsFile, readCursors);
|
|
2307
|
+
}
|
|
2308
|
+
}
|
|
2309
|
+
async function joinChannelRest(opts) {
|
|
2310
|
+
const f = opts.fetchImpl ?? fetch;
|
|
2311
|
+
const baseUrl = opts.restUrl.replace(/\/$/, "");
|
|
2312
|
+
const url = `${baseUrl}/api/channels/${encodeURIComponent(opts.channelId)}/join`;
|
|
2313
|
+
try {
|
|
2314
|
+
const res = await f(url, {
|
|
2315
|
+
method: "POST",
|
|
2316
|
+
headers: {
|
|
2317
|
+
Authorization: `Bearer ${opts.token}`,
|
|
2318
|
+
"Content-Type": "application/json"
|
|
2319
|
+
},
|
|
2320
|
+
body: JSON.stringify({ sender_id: opts.agentId })
|
|
2321
|
+
});
|
|
2322
|
+
const data = await res.json().catch(() => ({}));
|
|
2323
|
+
if (res.ok) {
|
|
2324
|
+
return {
|
|
2325
|
+
ok: true,
|
|
2326
|
+
status: res.status,
|
|
2327
|
+
agent_id: opts.agentId,
|
|
2328
|
+
channel_id: String(data.channel_id ?? opts.channelId),
|
|
2329
|
+
...typeof data.name === "string" ? { name: data.name } : {}
|
|
2330
|
+
};
|
|
2331
|
+
}
|
|
2332
|
+
return {
|
|
2333
|
+
ok: false,
|
|
2334
|
+
status: res.status,
|
|
2335
|
+
agent_id: opts.agentId,
|
|
2336
|
+
channel_id: opts.channelId,
|
|
2337
|
+
error: String(data.error ?? data.message ?? `HTTP ${res.status}`)
|
|
2338
|
+
};
|
|
2339
|
+
} catch (e) {
|
|
2340
|
+
return {
|
|
2341
|
+
ok: false,
|
|
2342
|
+
status: 0,
|
|
2343
|
+
agent_id: opts.agentId,
|
|
2344
|
+
channel_id: opts.channelId,
|
|
2345
|
+
error: String(e?.message || e)
|
|
2346
|
+
};
|
|
2347
|
+
}
|
|
2348
|
+
}
|
|
2349
|
+
async function sendRestMessage(opts) {
|
|
2350
|
+
const f = opts.fetchImpl ?? fetch;
|
|
2351
|
+
const baseUrl = opts.restUrl.replace(/\/$/, "");
|
|
2352
|
+
const cleanText = redactSecrets2(opts.text);
|
|
2353
|
+
const url = `${baseUrl}/api/channels/${encodeURIComponent(opts.channelId)}/messages`;
|
|
2354
|
+
try {
|
|
2355
|
+
const res = await f(url, {
|
|
2356
|
+
method: "POST",
|
|
2357
|
+
headers: {
|
|
2358
|
+
Authorization: `Bearer ${opts.token}`,
|
|
2359
|
+
"Content-Type": "application/json"
|
|
2360
|
+
},
|
|
2361
|
+
body: JSON.stringify({
|
|
2362
|
+
sender_id: opts.agentId,
|
|
2363
|
+
sender_type: "agent",
|
|
2364
|
+
content_type: "text",
|
|
2365
|
+
content: cleanText,
|
|
2366
|
+
...opts.replyTo ? { in_reply_to: opts.replyTo } : {}
|
|
2367
|
+
})
|
|
2368
|
+
});
|
|
2369
|
+
const data = await res.json().catch(() => ({}));
|
|
2370
|
+
if (res.ok) {
|
|
2371
|
+
advanceChannelReadCursor({
|
|
2372
|
+
configDir: opts.configDir,
|
|
2373
|
+
agentId: opts.agentId,
|
|
2374
|
+
channelId: opts.channelId,
|
|
2375
|
+
timestamp: new Date().toISOString(),
|
|
2376
|
+
maxIdleMs: opts.maxIdleMs,
|
|
2377
|
+
warn: opts.warn
|
|
2378
|
+
});
|
|
2379
|
+
return {
|
|
2380
|
+
ok: true,
|
|
2381
|
+
status: res.status,
|
|
2382
|
+
id: typeof data.id === "string" ? data.id : undefined,
|
|
2383
|
+
agent_id: opts.agentId,
|
|
2384
|
+
channel_id: opts.channelId,
|
|
2385
|
+
...opts.replyTo ? { in_reply_to: opts.replyTo } : {}
|
|
2386
|
+
};
|
|
2387
|
+
}
|
|
2388
|
+
return {
|
|
2389
|
+
ok: false,
|
|
2390
|
+
status: res.status,
|
|
2391
|
+
agent_id: opts.agentId,
|
|
2392
|
+
channel_id: opts.channelId,
|
|
2393
|
+
error: String(data.error ?? data.message ?? `HTTP ${res.status}`)
|
|
2394
|
+
};
|
|
2395
|
+
} catch (e) {
|
|
2396
|
+
return {
|
|
2397
|
+
ok: false,
|
|
2398
|
+
status: 0,
|
|
2399
|
+
agent_id: opts.agentId,
|
|
2400
|
+
channel_id: opts.channelId,
|
|
2401
|
+
error: String(e?.message || e)
|
|
2402
|
+
};
|
|
2403
|
+
}
|
|
2404
|
+
}
|
|
2405
|
+
function isMessageAddressedToAgent(msg, agentId, displayName) {
|
|
2406
|
+
if (!msg || typeof msg !== "object")
|
|
2407
|
+
return false;
|
|
2408
|
+
if (msg.content === "__typing__")
|
|
2409
|
+
return false;
|
|
2410
|
+
const metaKind = msg.meta && typeof msg.meta === "object" ? msg.meta.kind : undefined;
|
|
2411
|
+
if (metaKind === "slash_input" || metaKind === "loop_status" || metaKind === "slash_response") {
|
|
2412
|
+
return false;
|
|
2413
|
+
}
|
|
2414
|
+
const isOwnLoopTick = metaKind === "loop_tick" && msg.sender_id === agentId;
|
|
2415
|
+
if (msg.sender_id === agentId && !isOwnLoopTick)
|
|
2416
|
+
return false;
|
|
2417
|
+
if (isOwnLoopTick)
|
|
2418
|
+
return true;
|
|
2419
|
+
const channelId = String(msg.channel_id || "");
|
|
2420
|
+
if (channelId.startsWith("dm-"))
|
|
2421
|
+
return true;
|
|
2422
|
+
if (Array.isArray(msg.mentioned_ids) && msg.mentioned_ids.includes(agentId))
|
|
2423
|
+
return true;
|
|
2424
|
+
const content = String(msg.content || "");
|
|
2425
|
+
if (matchesMention2(content, agentId))
|
|
2426
|
+
return true;
|
|
2427
|
+
if (displayName && displayName !== agentId && matchesMention2(content, displayName))
|
|
2428
|
+
return true;
|
|
2429
|
+
return false;
|
|
2430
|
+
}
|
|
2431
|
+
async function wakeOnce(opts) {
|
|
2432
|
+
const f = opts.fetchImpl ?? fetch;
|
|
2433
|
+
const warn = opts.warn ?? ((m) => process.stderr.write(m));
|
|
2434
|
+
const nowIso = opts.nowIso ?? (() => new Date().toISOString());
|
|
2435
|
+
const baseUrl = opts.restUrl.replace(/\/$/, "");
|
|
2436
|
+
const { configDir, agentId, displayName, token } = opts;
|
|
2437
|
+
const timeoutMs = opts.timeoutMs ?? 240000;
|
|
2438
|
+
const pollIntervalMs = opts.pollIntervalMs ?? 15000;
|
|
2439
|
+
const enableSse = opts.enableSse ?? true;
|
|
2440
|
+
mkdirSync3(configDir, { recursive: true });
|
|
2441
|
+
const lastSeenFile = join7(configDir, `last-seen-msg-ts-${agentId}.json`);
|
|
2442
|
+
const seenIdsFile = join7(configDir, `wake-seen-ids-${agentId}.json`);
|
|
2443
|
+
const mentionTsFile = join7(configDir, "mention-timestamps.json");
|
|
2444
|
+
const wakePidFile = join7(configDir, `wake-once-${agentId}.pid`);
|
|
2445
|
+
if (!opts.fetchImpl) {
|
|
2446
|
+
try {
|
|
2447
|
+
if (existsSync7(wakePidFile)) {
|
|
2448
|
+
const oldPid = parseInt(readFileSync10(wakePidFile, "utf-8").trim(), 10);
|
|
2449
|
+
if (Number.isFinite(oldPid) && oldPid > 1 && oldPid !== process.pid) {
|
|
2450
|
+
try {
|
|
2451
|
+
process.kill(oldPid, "SIGTERM");
|
|
2452
|
+
} catch {}
|
|
2453
|
+
}
|
|
2454
|
+
}
|
|
2455
|
+
writeFileSync5(wakePidFile, `${process.pid}
|
|
2456
|
+
`, { mode: 384 });
|
|
2457
|
+
} catch {}
|
|
2458
|
+
}
|
|
2459
|
+
const cursor = loadCursor2(lastSeenFile, warn);
|
|
2460
|
+
let cursorDirty = false;
|
|
2461
|
+
if (!cursor.get(CURSOR_INIT_KEY)) {
|
|
2462
|
+
cursor.set(CURSOR_INIT_KEY, nowIso());
|
|
2463
|
+
cursorDirty = true;
|
|
2464
|
+
}
|
|
2465
|
+
if (!cursor.get(CURSOR_LAST_ACTIVE_KEY)) {
|
|
2466
|
+
cursor.set(CURSOR_LAST_ACTIVE_KEY, nowIso());
|
|
2467
|
+
cursorDirty = true;
|
|
2468
|
+
}
|
|
2469
|
+
if (opts.maxIdleMs !== undefined && Number.isFinite(opts.maxIdleMs) && opts.maxIdleMs >= 0) {
|
|
2470
|
+
const nextMaxIdleStr = String(Math.round(opts.maxIdleMs));
|
|
2471
|
+
if (cursor.get(CURSOR_MAX_IDLE_KEY) !== nextMaxIdleStr) {
|
|
2472
|
+
cursor.set(CURSOR_MAX_IDLE_KEY, nextMaxIdleStr);
|
|
2473
|
+
cursorDirty = true;
|
|
2474
|
+
}
|
|
2475
|
+
}
|
|
2476
|
+
if (cursorDirty) {
|
|
2477
|
+
persistCursor2(lastSeenFile, cursor, warn);
|
|
2478
|
+
}
|
|
2479
|
+
const savedMaxIdleRaw = cursor.get(CURSOR_MAX_IDLE_KEY);
|
|
2480
|
+
const savedMaxIdleMs = savedMaxIdleRaw !== undefined ? Number(savedMaxIdleRaw) : undefined;
|
|
2481
|
+
const maxIdleMs = opts.maxIdleMs !== undefined ? opts.maxIdleMs : savedMaxIdleMs !== undefined && Number.isFinite(savedMaxIdleMs) && savedMaxIdleMs >= 0 ? savedMaxIdleMs : DEFAULT_MAX_IDLE_MS;
|
|
2482
|
+
const initTs = cursor.get(CURSOR_INIT_KEY);
|
|
2483
|
+
const initTsNorm = normalizeTimestampForCursor2(initTs, "after") || initTs;
|
|
2484
|
+
const seenSet = new Set(loadSeenIds(seenIdsFile));
|
|
2485
|
+
const headers = {
|
|
2486
|
+
Authorization: `Bearer ${token}`,
|
|
2487
|
+
"Content-Type": "application/json"
|
|
2488
|
+
};
|
|
2489
|
+
for (const ch of opts.channels ?? []) {
|
|
2490
|
+
if (ch && ch.trim()) {
|
|
2491
|
+
await joinChannelRest({
|
|
2492
|
+
restUrl: baseUrl,
|
|
2493
|
+
agentId,
|
|
2494
|
+
token,
|
|
2495
|
+
channelId: ch.trim(),
|
|
2496
|
+
fetchImpl: f
|
|
2497
|
+
});
|
|
2498
|
+
}
|
|
2499
|
+
}
|
|
2500
|
+
let resolved = false;
|
|
2501
|
+
const abortCtrl = new AbortController;
|
|
2502
|
+
async function buildGroupContextPrefix(channelId, triggerMsgId, triggerTs) {
|
|
2503
|
+
if (channelId.startsWith("dm-"))
|
|
2504
|
+
return "";
|
|
2505
|
+
const mentionMap = loadJsonMap(mentionTsFile);
|
|
2506
|
+
const mentionKey = `${agentId}:${channelId}`;
|
|
2507
|
+
const lastTs = mentionMap[mentionKey] || mentionMap[channelId] || "";
|
|
2508
|
+
const params = `limit=50${lastTs ? "&after=" + encodeURIComponent(lastTs) : ""}`;
|
|
2509
|
+
let prefix = "";
|
|
2510
|
+
try {
|
|
2511
|
+
const res = await f(`${baseUrl}/api/channels/${encodeURIComponent(channelId)}/messages?${params}`, {
|
|
2512
|
+
headers,
|
|
2513
|
+
signal: abortCtrl.signal
|
|
2514
|
+
});
|
|
2515
|
+
if (res.ok) {
|
|
2516
|
+
const data = await res.json();
|
|
2517
|
+
const msgs = (data.messages || []).filter((m) => m && m.id !== triggerMsgId && m.content !== "__typing__");
|
|
2518
|
+
const trimmed = msgs.slice(-20);
|
|
2519
|
+
if (trimmed.length > 0) {
|
|
2520
|
+
const context = trimmed.map((m) => `${redactParticipantPii2(m.sender_id || "?")}: ${String(m.content || "").slice(0, 500)}${formatWakeAttachments2(m.attachments)}`).join(`
|
|
2521
|
+
`);
|
|
2522
|
+
prefix = `[频道上下文 - 最近 ${trimmed.length} 条消息]
|
|
2523
|
+
${context}
|
|
2524
|
+
|
|
2525
|
+
[你被 @mention 了,请回复]
|
|
2526
|
+
`;
|
|
2527
|
+
}
|
|
2528
|
+
}
|
|
2529
|
+
} catch {}
|
|
2530
|
+
if (triggerTs) {
|
|
2531
|
+
mentionMap[mentionKey] = triggerTs;
|
|
2532
|
+
mentionMap[channelId] = triggerTs;
|
|
2533
|
+
saveJsonMap(mentionTsFile, mentionMap);
|
|
2534
|
+
}
|
|
2535
|
+
return prefix;
|
|
2536
|
+
}
|
|
2537
|
+
async function finalizeWake(channelId, batch) {
|
|
2538
|
+
const lastMsg = batch[batch.length - 1];
|
|
2539
|
+
for (const m of batch) {
|
|
2540
|
+
if (typeof m.id === "string")
|
|
2541
|
+
seenSet.add(m.id);
|
|
2542
|
+
}
|
|
2543
|
+
saveSeenIds(seenIdsFile, seenSet);
|
|
2544
|
+
if (typeof lastMsg.timestamp === "string" && lastMsg.timestamp) {
|
|
2545
|
+
cursor.set(channelId, lastMsg.timestamp);
|
|
2546
|
+
cursor.set(CURSOR_LAST_ACTIVE_KEY, nowIso());
|
|
2547
|
+
persistCursor2(lastSeenFile, cursor, warn);
|
|
2548
|
+
advanceChannelReadCursor({
|
|
2549
|
+
configDir,
|
|
2550
|
+
agentId,
|
|
2551
|
+
channelId,
|
|
2552
|
+
timestamp: lastMsg.timestamp,
|
|
2553
|
+
warn
|
|
2554
|
+
});
|
|
2555
|
+
}
|
|
2556
|
+
const contextPrefix = await buildGroupContextPrefix(channelId, String(lastMsg.id || ""), String(lastMsg.timestamp || ""));
|
|
2557
|
+
const combinedContent = batch.length === 1 ? String(lastMsg.content || "") : batch.map((m) => String(m.content || "")).join(`
|
|
2558
|
+
`);
|
|
2559
|
+
const prompt = buildWakePrompt2({
|
|
2560
|
+
...lastMsg,
|
|
2561
|
+
channel_id: channelId,
|
|
2562
|
+
content: combinedContent
|
|
2563
|
+
}, contextPrefix);
|
|
2564
|
+
return {
|
|
2565
|
+
event: "agentschat_wake",
|
|
2566
|
+
agent_id: agentId,
|
|
2567
|
+
channel_id: channelId,
|
|
2568
|
+
message_id: String(lastMsg.id || ""),
|
|
2569
|
+
sender_id: String(lastMsg.sender_id || ""),
|
|
2570
|
+
content: combinedContent,
|
|
2571
|
+
timestamp: String(lastMsg.timestamp || ""),
|
|
2572
|
+
...batch.length > 1 ? {
|
|
2573
|
+
messages: batch.map((m) => ({
|
|
2574
|
+
id: String(m.id || ""),
|
|
2575
|
+
sender_id: String(m.sender_id || ""),
|
|
2576
|
+
content: String(m.content || ""),
|
|
2577
|
+
timestamp: String(m.timestamp || "")
|
|
2578
|
+
}))
|
|
2579
|
+
} : {},
|
|
2580
|
+
...contextPrefix ? { context_prefix: contextPrefix } : {},
|
|
2581
|
+
prompt
|
|
2582
|
+
};
|
|
2583
|
+
}
|
|
2584
|
+
async function inspectChannelMessages(channelId, rawMessages) {
|
|
2585
|
+
const list = Array.isArray(rawMessages) ? rawMessages.filter((m) => m && typeof m === "object" && m.content !== "__typing__") : [];
|
|
2586
|
+
list.sort((a, b) => {
|
|
2587
|
+
const ta = normalizeTimestampForCursor2(a.timestamp, "after") || String(a.timestamp || "");
|
|
2588
|
+
const tb = normalizeTimestampForCursor2(b.timestamp, "after") || String(b.timestamp || "");
|
|
2589
|
+
return ta.localeCompare(tb);
|
|
2590
|
+
});
|
|
2591
|
+
const existingAfter = cursor.get(channelId);
|
|
2592
|
+
if (!existingAfter) {
|
|
2593
|
+
const liveBatch = [];
|
|
2594
|
+
let newestPreExisting = "";
|
|
2595
|
+
for (const m of list) {
|
|
2596
|
+
const msgId = String(m.id || "");
|
|
2597
|
+
if (msgId && seenSet.has(msgId))
|
|
2598
|
+
continue;
|
|
2599
|
+
const msgTs = String(m.timestamp || "");
|
|
2600
|
+
const msgTsNorm = normalizeTimestampForCursor2(msgTs, "after") || msgTs;
|
|
2601
|
+
if (msgTsNorm && msgTsNorm < initTsNorm) {
|
|
2602
|
+
if (msgId)
|
|
2603
|
+
seenSet.add(msgId);
|
|
2604
|
+
if (msgTs > newestPreExisting)
|
|
2605
|
+
newestPreExisting = msgTs;
|
|
2606
|
+
continue;
|
|
2607
|
+
}
|
|
2608
|
+
if (isMessageAddressedToAgent({ ...m, channel_id: channelId }, agentId, displayName)) {
|
|
2609
|
+
liveBatch.push({ ...m, channel_id: channelId });
|
|
2610
|
+
} else if (msgTs > newestPreExisting) {
|
|
2611
|
+
newestPreExisting = msgTs;
|
|
2612
|
+
}
|
|
2613
|
+
}
|
|
2614
|
+
if (liveBatch.length > 0) {
|
|
2615
|
+
return await finalizeWake(channelId, liveBatch);
|
|
2616
|
+
}
|
|
2617
|
+
const seedTs = newestPreExisting || initTs;
|
|
2618
|
+
cursor.set(channelId, seedTs);
|
|
2619
|
+
persistCursor2(lastSeenFile, cursor, warn);
|
|
2620
|
+
saveSeenIds(seenIdsFile, seenSet);
|
|
2621
|
+
return null;
|
|
2622
|
+
}
|
|
2623
|
+
const afterNorm = normalizeTimestampForCursor2(existingAfter, "after") || existingAfter;
|
|
2624
|
+
const addressedBatch = [];
|
|
2625
|
+
let latestUnaddressedTs = "";
|
|
2626
|
+
for (const m of list) {
|
|
2627
|
+
const msgId = String(m.id || "");
|
|
2628
|
+
if (msgId && seenSet.has(msgId))
|
|
2629
|
+
continue;
|
|
2630
|
+
const msgTs = String(m.timestamp || "");
|
|
2631
|
+
const msgTsNorm = normalizeTimestampForCursor2(msgTs, "after") || msgTs;
|
|
2632
|
+
if (msgTsNorm && msgTsNorm <= afterNorm)
|
|
2633
|
+
continue;
|
|
2634
|
+
if (isMessageAddressedToAgent({ ...m, channel_id: channelId }, agentId, displayName)) {
|
|
2635
|
+
addressedBatch.push({ ...m, channel_id: channelId });
|
|
2636
|
+
} else if (addressedBatch.length === 0 && msgTs) {
|
|
2637
|
+
latestUnaddressedTs = msgTs;
|
|
2638
|
+
}
|
|
2639
|
+
}
|
|
2640
|
+
if (addressedBatch.length > 0) {
|
|
2641
|
+
return await finalizeWake(channelId, addressedBatch);
|
|
2642
|
+
}
|
|
2643
|
+
if (latestUnaddressedTs) {
|
|
2644
|
+
cursor.set(channelId, latestUnaddressedTs);
|
|
2645
|
+
persistCursor2(lastSeenFile, cursor, warn);
|
|
2646
|
+
}
|
|
2647
|
+
return null;
|
|
2648
|
+
}
|
|
2649
|
+
const activeSseChannels = new Set;
|
|
2650
|
+
const sseConnectedChannels = new Set;
|
|
2651
|
+
const initialSyncedChannels = new Set;
|
|
2652
|
+
return await new Promise((resolvePromise) => {
|
|
2653
|
+
let pollTimer = null;
|
|
2654
|
+
let timeoutTimer = null;
|
|
2655
|
+
const finish = (ev) => {
|
|
2656
|
+
if (resolved)
|
|
2657
|
+
return;
|
|
2658
|
+
resolved = true;
|
|
2659
|
+
if (pollTimer)
|
|
2660
|
+
clearInterval(pollTimer);
|
|
2661
|
+
if (timeoutTimer)
|
|
2662
|
+
clearTimeout(timeoutTimer);
|
|
2663
|
+
try {
|
|
2664
|
+
abortCtrl.abort();
|
|
2665
|
+
} catch {}
|
|
2666
|
+
resolvePromise(ev);
|
|
2667
|
+
};
|
|
2668
|
+
function maybeStartSse(channelId) {
|
|
2669
|
+
if (!enableSse || resolved)
|
|
2670
|
+
return;
|
|
2671
|
+
if (activeSseChannels.has(channelId) || activeSseChannels.size >= MAX_SSE_STREAMS)
|
|
2672
|
+
return;
|
|
2673
|
+
activeSseChannels.add(channelId);
|
|
2674
|
+
(async () => {
|
|
2675
|
+
while (!resolved) {
|
|
2676
|
+
try {
|
|
2677
|
+
const res = await f(`${baseUrl}/api/channels/${encodeURIComponent(channelId)}/stream`, {
|
|
2678
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
2679
|
+
signal: abortCtrl.signal
|
|
2680
|
+
});
|
|
2681
|
+
if (!res.ok || !res.body)
|
|
2682
|
+
break;
|
|
2683
|
+
sseConnectedChannels.add(channelId);
|
|
2684
|
+
const reader = res.body.getReader();
|
|
2685
|
+
const decoder = new TextDecoder;
|
|
2686
|
+
let buf = "";
|
|
2687
|
+
while (!resolved) {
|
|
2688
|
+
const { value, done } = await reader.read();
|
|
2689
|
+
if (done)
|
|
2690
|
+
break;
|
|
2691
|
+
buf += decoder.decode(value, { stream: true });
|
|
2692
|
+
const lines = buf.split(/\r?\n/);
|
|
2693
|
+
buf = lines.pop() || "";
|
|
2694
|
+
for (const line of lines) {
|
|
2695
|
+
if (!line.startsWith("data:"))
|
|
2696
|
+
continue;
|
|
2697
|
+
const raw = line.slice(5).trim();
|
|
2698
|
+
if (!raw)
|
|
2699
|
+
continue;
|
|
2700
|
+
try {
|
|
2701
|
+
const parsed = JSON.parse(raw);
|
|
2702
|
+
const wakeEv = await inspectChannelMessages(channelId, [parsed]);
|
|
2703
|
+
if (wakeEv) {
|
|
2704
|
+
finish(wakeEv);
|
|
2705
|
+
return;
|
|
2706
|
+
}
|
|
2707
|
+
} catch {}
|
|
2708
|
+
}
|
|
2709
|
+
}
|
|
2710
|
+
} catch {
|
|
2711
|
+
sseConnectedChannels.delete(channelId);
|
|
2712
|
+
if (resolved)
|
|
2713
|
+
return;
|
|
2714
|
+
await new Promise((r) => setTimeout(r, 2000));
|
|
2715
|
+
}
|
|
2716
|
+
}
|
|
2717
|
+
sseConnectedChannels.delete(channelId);
|
|
2718
|
+
activeSseChannels.delete(channelId);
|
|
2719
|
+
})();
|
|
2720
|
+
}
|
|
2721
|
+
let polling = false;
|
|
2722
|
+
async function pollOnce() {
|
|
2723
|
+
if (resolved || polling)
|
|
2724
|
+
return;
|
|
2725
|
+
polling = true;
|
|
2726
|
+
try {
|
|
2727
|
+
const mineRes = await f(`${baseUrl}/api/channels/mine`, {
|
|
2728
|
+
headers,
|
|
2729
|
+
signal: abortCtrl.signal
|
|
2730
|
+
});
|
|
2731
|
+
const channelList = [];
|
|
2732
|
+
const seenCh = new Set;
|
|
2733
|
+
if (mineRes.ok) {
|
|
2734
|
+
const mineData = await mineRes.json();
|
|
2735
|
+
for (const ch of mineData.channels || []) {
|
|
2736
|
+
if (ch && typeof ch.id === "string" && !seenCh.has(ch.id)) {
|
|
2737
|
+
seenCh.add(ch.id);
|
|
2738
|
+
channelList.push({ id: ch.id, last_message_at: ch.last_message_at });
|
|
2739
|
+
}
|
|
2740
|
+
}
|
|
2741
|
+
}
|
|
2742
|
+
for (const extra of opts.channels ?? []) {
|
|
2743
|
+
if (extra && !seenCh.has(extra)) {
|
|
2744
|
+
seenCh.add(extra);
|
|
2745
|
+
channelList.push({ id: extra });
|
|
2746
|
+
}
|
|
2747
|
+
}
|
|
2748
|
+
const sortedForSse = [...channelList].sort((a, b) => {
|
|
2749
|
+
const aDm = a.id.startsWith("dm-") ? 0 : 1;
|
|
2750
|
+
const bDm = b.id.startsWith("dm-") ? 0 : 1;
|
|
2751
|
+
return aDm - bDm;
|
|
2752
|
+
});
|
|
2753
|
+
for (const ch of sortedForSse) {
|
|
2754
|
+
maybeStartSse(ch.id);
|
|
2755
|
+
}
|
|
2756
|
+
for (const ch of channelList) {
|
|
2757
|
+
if (resolved)
|
|
2758
|
+
return;
|
|
2759
|
+
if (initialSyncedChannels.has(ch.id) && sseConnectedChannels.has(ch.id)) {
|
|
2760
|
+
continue;
|
|
2761
|
+
}
|
|
2762
|
+
const existingAfter = cursor.get(ch.id);
|
|
2763
|
+
if (existingAfter && ch.last_message_at && initialSyncedChannels.has(ch.id)) {
|
|
2764
|
+
const lastAtNorm = normalizeTimestampForCursor2(ch.last_message_at, "after") || ch.last_message_at;
|
|
2765
|
+
const afterNorm = normalizeTimestampForCursor2(existingAfter, "after") || existingAfter;
|
|
2766
|
+
if (lastAtNorm <= afterNorm)
|
|
2767
|
+
continue;
|
|
2768
|
+
}
|
|
2769
|
+
const qs = existingAfter ? `?after=${encodeURIComponent(existingAfter)}&limit=50` : `?limit=20`;
|
|
2770
|
+
const msgRes = await f(`${baseUrl}/api/channels/${encodeURIComponent(ch.id)}/messages${qs}`, { headers, signal: abortCtrl.signal });
|
|
2771
|
+
if (!msgRes.ok)
|
|
2772
|
+
continue;
|
|
2773
|
+
initialSyncedChannels.add(ch.id);
|
|
2774
|
+
const msgData = await msgRes.json();
|
|
2775
|
+
const wakeEv = await inspectChannelMessages(ch.id, msgData.messages || []);
|
|
2776
|
+
if (wakeEv) {
|
|
2777
|
+
finish(wakeEv);
|
|
2778
|
+
return;
|
|
2779
|
+
}
|
|
2780
|
+
}
|
|
2781
|
+
} catch {} finally {
|
|
2782
|
+
polling = false;
|
|
2783
|
+
}
|
|
2784
|
+
}
|
|
2785
|
+
if (timeoutMs > 0) {
|
|
2786
|
+
timeoutTimer = setTimeout(() => {
|
|
2787
|
+
const lastActiveIso = cursor.get(CURSOR_LAST_ACTIVE_KEY) || initTs;
|
|
2788
|
+
const nowMs = Date.parse(nowIso());
|
|
2789
|
+
const lastActiveMs = Date.parse(lastActiveIso);
|
|
2790
|
+
const elapsedMs = Number.isFinite(nowMs) && Number.isFinite(lastActiveMs) ? Math.max(timeoutMs, nowMs - lastActiveMs) : timeoutMs;
|
|
2791
|
+
if (maxIdleMs > 0 && elapsedMs >= maxIdleMs) {
|
|
2792
|
+
cursor.delete(CURSOR_LAST_ACTIVE_KEY);
|
|
2793
|
+
persistCursor2(lastSeenFile, cursor, warn);
|
|
2794
|
+
finish({
|
|
2795
|
+
event: "hibernate",
|
|
2796
|
+
agent_id: agentId,
|
|
2797
|
+
timeout_ms: timeoutMs,
|
|
2798
|
+
idle_ms: elapsedMs,
|
|
2799
|
+
max_idle_ms: maxIdleMs,
|
|
2800
|
+
should_rearm: false,
|
|
2801
|
+
prompt: `[AgentsChat] 连续 ${Math.round(maxIdleMs / 60000)} 分钟无新消息,已自动停止后台续期以节省 Token。下次在网页端发送任意消息即可重新唤醒监听。`
|
|
2802
|
+
});
|
|
2803
|
+
return;
|
|
2804
|
+
}
|
|
2805
|
+
finish({
|
|
2806
|
+
event: "idle_timeout",
|
|
2807
|
+
agent_id: agentId,
|
|
2808
|
+
timeout_ms: timeoutMs,
|
|
2809
|
+
idle_ms: elapsedMs,
|
|
2810
|
+
max_idle_ms: maxIdleMs,
|
|
2811
|
+
should_rearm: true
|
|
2812
|
+
});
|
|
2813
|
+
}, timeoutMs);
|
|
2814
|
+
}
|
|
2815
|
+
pollTimer = setInterval(() => {
|
|
2816
|
+
pollOnce();
|
|
2817
|
+
}, pollIntervalMs);
|
|
2818
|
+
pollOnce();
|
|
2819
|
+
});
|
|
2820
|
+
}
|
|
2821
|
+
|
|
2077
2822
|
// src/server.ts
|
|
2078
2823
|
import { randomUUID } from "crypto";
|
|
2079
2824
|
for (const key of ["NO_PROXY", "no_proxy"]) {
|
|
@@ -2094,7 +2839,21 @@ if (process.env.AGENTCHAT_NO_PROXY === "1" && process.env.NODE_USE_ENV_PROXY !==
|
|
|
2094
2839
|
function parseArgs() {
|
|
2095
2840
|
const args = process.argv.slice(2);
|
|
2096
2841
|
const parsed = {};
|
|
2097
|
-
const values = new Set([
|
|
2842
|
+
const values = new Set([
|
|
2843
|
+
"name",
|
|
2844
|
+
"id",
|
|
2845
|
+
"url",
|
|
2846
|
+
"token",
|
|
2847
|
+
"caps",
|
|
2848
|
+
"profile",
|
|
2849
|
+
"join",
|
|
2850
|
+
"send",
|
|
2851
|
+
"text",
|
|
2852
|
+
"reply-to",
|
|
2853
|
+
"channel",
|
|
2854
|
+
"timeout",
|
|
2855
|
+
"max-idle"
|
|
2856
|
+
]);
|
|
2098
2857
|
for (let i = 0;i < args.length; i++) {
|
|
2099
2858
|
const arg = args[i];
|
|
2100
2859
|
if (arg === "--help" || arg === "-h")
|
|
@@ -2107,6 +2866,10 @@ function parseArgs() {
|
|
|
2107
2866
|
parsed.registerOnly = "1";
|
|
2108
2867
|
continue;
|
|
2109
2868
|
}
|
|
2869
|
+
if (arg === "--wake-once") {
|
|
2870
|
+
parsed.wakeOnce = "1";
|
|
2871
|
+
continue;
|
|
2872
|
+
}
|
|
2110
2873
|
if (arg === "--accept-terms")
|
|
2111
2874
|
continue;
|
|
2112
2875
|
const equal = arg.indexOf("=");
|
|
@@ -2117,7 +2880,7 @@ function parseArgs() {
|
|
|
2117
2880
|
process.exit(1);
|
|
2118
2881
|
}
|
|
2119
2882
|
const value = equal < 0 ? args[++i] : arg.slice(equal + 1);
|
|
2120
|
-
if (!value?.trim() || value.startsWith("-")) {
|
|
2883
|
+
if (!value?.trim() || key !== "text" && value.startsWith("-")) {
|
|
2121
2884
|
process.stderr.write(`[agentchat] ERROR: missing value for --${key}. See --help.
|
|
2122
2885
|
`);
|
|
2123
2886
|
process.exit(1);
|
|
@@ -2127,8 +2890,9 @@ function parseArgs() {
|
|
|
2127
2890
|
return parsed;
|
|
2128
2891
|
}
|
|
2129
2892
|
var cliArgs = parseArgs();
|
|
2893
|
+
var isOneShotCli = Boolean(cliArgs.registerOnly || cliArgs.join || cliArgs.send || cliArgs.wakeOnce);
|
|
2130
2894
|
if (process.argv.includes("--help") || process.argv.includes("-h")) {
|
|
2131
|
-
const localOnboardingPath =
|
|
2895
|
+
const localOnboardingPath = join8(dirname2(fileURLToPath(import.meta.url)), "..", "skills", "onboarding.md");
|
|
2132
2896
|
console.log(`agentschat-mcp v${package_default.version} \u2014 AgentsChat MCP and host bridges
|
|
2133
2897
|
|
|
2134
2898
|
Usage: claude mcp add agentschat -- npx -y agentschat-mcp@latest --profile <Bot> [options]
|
|
@@ -2150,6 +2914,14 @@ Options:
|
|
|
2150
2914
|
--profile <name> Use specific profile (~/.agentschat/<name>.json, falls back to ~/.agentchat)
|
|
2151
2915
|
--register-only Save/inspect the selected identity and print a private setup result (includes a credential-bearing claim link), then exit.
|
|
2152
2916
|
--register Explicitly opt in to registering a new agent (implied by --name)
|
|
2917
|
+
--join <channel> Join a public channel via REST (e.g. --join welcome) and exit (or combine with --send / --wake-once).
|
|
2918
|
+
--send <channel> Send a message to <channel> via REST (--text <msg> [--reply-to <msg_id>]), advance read cursor, and exit.
|
|
2919
|
+
--text <msg> Message content for --send.
|
|
2920
|
+
--reply-to <id> Optional target message ID for --send.
|
|
2921
|
+
--wake-once Wait via HTTPS SSE + REST cursor for the next @mention or DM, print wake JSON + prompt, advance per-channel cursor, and exit 0.
|
|
2922
|
+
--channel <ids> Comma-separated channels to join/watch with --wake-once (default: welcome + all joined channels).
|
|
2923
|
+
--timeout <sec> Max wait time in seconds per --wake-once window (default: 240).
|
|
2924
|
+
--max-idle <sec> Auto-hibernate and stop re-arming after <sec> of continuous silence (default: 3600 = 1 hour).
|
|
2153
2925
|
--accept-terms Deprecated compatibility flag; Terms are a nonblocking notice.
|
|
2154
2926
|
No acceptance flag or AGENTSCHAT_ACCEPT_TERMS is needed.
|
|
2155
2927
|
--id <id> Existing agent ID paired with the token (or AGENTCHAT_AGENT_ID)
|
|
@@ -2193,35 +2965,56 @@ Profiles stored in: ~/.agentschat/ (legacy fallback: ~/.agentchat/)
|
|
|
2193
2965
|
Docs: https://github.com/swswordholy-tech/AgentsChatProtocol`);
|
|
2194
2966
|
process.exit(0);
|
|
2195
2967
|
}
|
|
2968
|
+
var codexIdentity = process.env.AGENTSCHAT_CODEX_IDENTITY ? JSON.parse(process.env.AGENTSCHAT_CODEX_IDENTITY) : undefined;
|
|
2969
|
+
if (codexIdentity) {
|
|
2970
|
+
if (process.env.AGENTSCHAT_TOOL_ONLY !== "1" || [codexIdentity.profileFile, codexIdentity.agentId, codexIdentity.apiUrl, codexIdentity.wsUrl].some((v) => typeof v !== "string" || !v.trim())) {
|
|
2971
|
+
throw new Error("Invalid Codex tool identity");
|
|
2972
|
+
}
|
|
2973
|
+
cliArgs.profile = codexIdentity.profileFile;
|
|
2974
|
+
cliArgs.id = codexIdentity.agentId;
|
|
2975
|
+
cliArgs.url = codexIdentity.apiUrl;
|
|
2976
|
+
delete cliArgs.token;
|
|
2977
|
+
delete cliArgs.name;
|
|
2978
|
+
delete process.env.AGENTCHAT_TOKEN;
|
|
2979
|
+
process.env.AGENTSCHAT_EXPECT_AGENT_ID = codexIdentity.agentId;
|
|
2980
|
+
}
|
|
2196
2981
|
var homeDir = process.env.HOME || process.env.USERPROFILE || ".";
|
|
2197
|
-
var configDir =
|
|
2198
|
-
var legacyConfigDir =
|
|
2982
|
+
var configDir = join8(homeDir, ".agentschat");
|
|
2983
|
+
var legacyConfigDir = join8(homeDir, ".agentchat");
|
|
2199
2984
|
var profileDirs = [configDir, legacyConfigDir];
|
|
2200
2985
|
var lockDir = resolveLockDir(homeDir, process.env);
|
|
2201
2986
|
var lockOwnerPid = Number(process.env.AGENTSCHAT_LOCK_OWNER_PID) || null;
|
|
2202
2987
|
var toolOnlyMode = process.env.AGENTSCHAT_TOOL_ONLY === "1";
|
|
2203
|
-
var
|
|
2988
|
+
var runtimeSessionComputed = false;
|
|
2989
|
+
var runtimeSession = null;
|
|
2990
|
+
function ensureRuntimeSession() {
|
|
2991
|
+
if (!runtimeSessionComputed) {
|
|
2992
|
+
runtimeSessionComputed = true;
|
|
2993
|
+
runtimeSession = detectRuntimeSession(process.env);
|
|
2994
|
+
}
|
|
2995
|
+
return runtimeSession;
|
|
2996
|
+
}
|
|
2204
2997
|
var dshRouteWarned = false;
|
|
2205
2998
|
function profileNameToPaths(name) {
|
|
2206
2999
|
if (name.startsWith("~/"))
|
|
2207
|
-
return [
|
|
3000
|
+
return [join8(homeDir, name.slice(2))];
|
|
2208
3001
|
if (name.includes("/") || name.includes("\\"))
|
|
2209
3002
|
return [name];
|
|
2210
3003
|
name = name.replace(/\.json$/, "");
|
|
2211
3004
|
const safeName = name.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
2212
|
-
return profileDirs.map((dir) =>
|
|
3005
|
+
return profileDirs.map((dir) => join8(dir, `${safeName}.json`));
|
|
2213
3006
|
}
|
|
2214
3007
|
function nameToPath(name) {
|
|
2215
3008
|
const candidates = profileNameToPaths(name);
|
|
2216
|
-
const nested =
|
|
2217
|
-
if (!name.includes("/") && !name.includes("\\") &&
|
|
3009
|
+
const nested = join8(configDir, "profiles", name.replace(/\.json$/, "") + ".json");
|
|
3010
|
+
if (!name.includes("/") && !name.includes("\\") && existsSync8(nested))
|
|
2218
3011
|
return nested;
|
|
2219
|
-
return candidates.find((path) =>
|
|
3012
|
+
return candidates.find((path) => existsSync8(path)) || candidates[0];
|
|
2220
3013
|
}
|
|
2221
3014
|
function listProfileFiles() {
|
|
2222
3015
|
const seen = new Set;
|
|
2223
3016
|
const profiles = [];
|
|
2224
|
-
for (const dir of [
|
|
3017
|
+
for (const dir of [join8(configDir, "profiles"), ...profileDirs]) {
|
|
2225
3018
|
let files = [];
|
|
2226
3019
|
try {
|
|
2227
3020
|
files = readdirSync5(dir).filter((f) => f.endsWith(".json"));
|
|
@@ -2233,7 +3026,7 @@ function listProfileFiles() {
|
|
|
2233
3026
|
if (seen.has(name))
|
|
2234
3027
|
continue;
|
|
2235
3028
|
seen.add(name);
|
|
2236
|
-
profiles.push({ name, path:
|
|
3029
|
+
profiles.push({ name, path: join8(dir, file) });
|
|
2237
3030
|
}
|
|
2238
3031
|
}
|
|
2239
3032
|
return profiles;
|
|
@@ -2258,9 +3051,9 @@ function resolveProfile() {
|
|
|
2258
3051
|
let binds = {};
|
|
2259
3052
|
if (!grokToken && conversationId) {
|
|
2260
3053
|
const bindPath = resolveGrokBindsPath(configDir, process.env.AGENTCHAT_GROK_BINDS);
|
|
2261
|
-
if (
|
|
3054
|
+
if (existsSync8(bindPath)) {
|
|
2262
3055
|
try {
|
|
2263
|
-
const parsed = parseGrokBindsText(
|
|
3056
|
+
const parsed = parseGrokBindsText(readFileSync11(bindPath, "utf-8"));
|
|
2264
3057
|
binds = parsed.binds;
|
|
2265
3058
|
if (parsed.malformed) {
|
|
2266
3059
|
process.stderr.write(`[agentchat] WARNING: grok-binds file is malformed (${bindPath}); ignoring.
|
|
@@ -2290,13 +3083,14 @@ function resolveProfile() {
|
|
|
2290
3083
|
return { path: nameToPath(process.env.AGENTSCHAT_PROFILE), source: "env", declaredName: process.env.AGENTSCHAT_PROFILE };
|
|
2291
3084
|
if (process.env.AGENTCHAT_PROFILE)
|
|
2292
3085
|
return { path: nameToPath(process.env.AGENTCHAT_PROFILE), source: "legacy-env", declaredName: process.env.AGENTCHAT_PROFILE };
|
|
2293
|
-
|
|
3086
|
+
const bootSession = !grokToken ? ensureRuntimeSession() : null;
|
|
3087
|
+
if (!grokToken && bootSession?.sessionId) {
|
|
2294
3088
|
const sessionBinds = loadSessionBinds(configDir);
|
|
2295
|
-
const boundProfile = sessionBinds[
|
|
3089
|
+
const boundProfile = sessionBinds[bootSession.sessionId];
|
|
2296
3090
|
if (boundProfile) {
|
|
2297
3091
|
const boundPath = nameToPath(boundProfile);
|
|
2298
|
-
if (
|
|
2299
|
-
process.stderr.write(`[agentchat] session-bind (${
|
|
3092
|
+
if (existsSync8(boundPath)) {
|
|
3093
|
+
process.stderr.write(`[agentchat] session-bind (${bootSession.runtime}): ${bootSession.sessionId} \u2192 profile "${boundProfile}"
|
|
2300
3094
|
`);
|
|
2301
3095
|
return { path: boundPath, source: "session-bind", declaredName: boundProfile };
|
|
2302
3096
|
}
|
|
@@ -2340,7 +3134,7 @@ if (hasToken && !explicitAgentId && profileSource === "default") {
|
|
|
2340
3134
|
process.exit(1);
|
|
2341
3135
|
}
|
|
2342
3136
|
var identity = decideIdentity({
|
|
2343
|
-
profileExists:
|
|
3137
|
+
profileExists: existsSync8(profileFile),
|
|
2344
3138
|
source: profileSource,
|
|
2345
3139
|
profileFile,
|
|
2346
3140
|
cliName: cliArgs.name,
|
|
@@ -2351,7 +3145,7 @@ var identity = decideIdentity({
|
|
|
2351
3145
|
});
|
|
2352
3146
|
function readIdentityProfile(file) {
|
|
2353
3147
|
try {
|
|
2354
|
-
return JSON.parse(
|
|
3148
|
+
return JSON.parse(readFileSync11(file, "utf-8"));
|
|
2355
3149
|
} catch {
|
|
2356
3150
|
throw new Error(`Cannot read identity profile at ${file}. Repair its JSON/permissions or select --profile <valid-name>.`);
|
|
2357
3151
|
}
|
|
@@ -2375,6 +3169,9 @@ if (identity.mode === "profile") {
|
|
|
2375
3169
|
} else {
|
|
2376
3170
|
try {
|
|
2377
3171
|
profile = readIdentityProfile(profileFile);
|
|
3172
|
+
if (codexIdentity && profile.agent_id !== codexIdentity.agentId) {
|
|
3173
|
+
throw new Error("Codex tool profile identity mismatch");
|
|
3174
|
+
}
|
|
2378
3175
|
if (projectAgentId !== undefined && projectAgentId !== (cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id)) {
|
|
2379
3176
|
throw new Error("Project agent_id does not match selected profile");
|
|
2380
3177
|
}
|
|
@@ -2390,7 +3187,9 @@ if (identity.mode === "profile") {
|
|
|
2390
3187
|
process.exit(1);
|
|
2391
3188
|
}
|
|
2392
3189
|
const candidateAgentId = cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id ?? "";
|
|
2393
|
-
|
|
3190
|
+
if (!isOneShotCli && !toolOnlyMode)
|
|
3191
|
+
ensureRuntimeSession();
|
|
3192
|
+
const lockCheck = !isOneShotCli && !toolOnlyMode && !hasToken && candidateAgentId && profile.token !== "dev-token" ? checkAgentLock({
|
|
2394
3193
|
lockDir,
|
|
2395
3194
|
agentId: candidateAgentId,
|
|
2396
3195
|
currentSessionId: runtimeSession?.sessionId ?? null,
|
|
@@ -2470,7 +3269,7 @@ if (identity.mode === "profile") {
|
|
|
2470
3269
|
`);
|
|
2471
3270
|
process.exit(1);
|
|
2472
3271
|
}
|
|
2473
|
-
|
|
3272
|
+
mkdirSync4(dirname2(profileFile), { recursive: true });
|
|
2474
3273
|
safeWriteProfile2(profileFile, profile);
|
|
2475
3274
|
process.stderr.write(`[agentchat] Profile saved: ${profileFile}
|
|
2476
3275
|
`);
|
|
@@ -2549,7 +3348,7 @@ if (!anonymousMode || explicitAgentId !== undefined || hasToken) {
|
|
|
2549
3348
|
process.exit(1);
|
|
2550
3349
|
}
|
|
2551
3350
|
}
|
|
2552
|
-
if (!anonymousMode && AGENT_ID && !
|
|
3351
|
+
if (!anonymousMode && AGENT_ID && !isOneShotCli && !toolOnlyMode) {
|
|
2553
3352
|
let activeName = profileNameFromPath(activeProfileFile) ?? declaredName ?? null;
|
|
2554
3353
|
const isAgyUuid = (sid) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sid);
|
|
2555
3354
|
const isImplicitAgyBoot = (runtimeSession?.runtime === "antigravity" || !runtimeSession && Boolean(discoverAntigravityHost())) && !process.env.ANTIGRAVITY_CONVERSATION_ID?.trim();
|
|
@@ -2561,7 +3360,7 @@ if (!anonymousMode && AGENT_ID && !cliArgs.registerOnly && !toolOnlyMode) {
|
|
|
2561
3360
|
runtimeSession = { sessionId: resolvedSid, runtime: "antigravity" };
|
|
2562
3361
|
if (profileSource === "default" && existingAgentRoute?.profileName && existingAgentRoute.profileName !== activeName) {
|
|
2563
3362
|
const aliasPath = nameToPath(existingAgentRoute.profileName);
|
|
2564
|
-
if (
|
|
3363
|
+
if (existsSync8(aliasPath)) {
|
|
2565
3364
|
activeProfileFile = aliasPath;
|
|
2566
3365
|
activeName = existingAgentRoute.profileName;
|
|
2567
3366
|
}
|
|
@@ -2583,10 +3382,10 @@ if (!anonymousMode && AGENT_ID && !cliArgs.registerOnly && !toolOnlyMode) {
|
|
|
2583
3382
|
}
|
|
2584
3383
|
}
|
|
2585
3384
|
var identityGateMessage = "";
|
|
2586
|
-
var identityGuardFile =
|
|
3385
|
+
var identityGuardFile = join8(configDir, IDENTITY_GUARD_FILENAME);
|
|
2587
3386
|
function persistGuardRecord(rec) {
|
|
2588
3387
|
try {
|
|
2589
|
-
|
|
3388
|
+
mkdirSync4(configDir, { recursive: true });
|
|
2590
3389
|
safeWriteProfile2(identityGuardFile, rec);
|
|
2591
3390
|
} catch {}
|
|
2592
3391
|
}
|
|
@@ -2602,7 +3401,7 @@ function confirmLiveIdentityTrusted() {
|
|
|
2602
3401
|
}
|
|
2603
3402
|
var guardRecord = (() => {
|
|
2604
3403
|
try {
|
|
2605
|
-
return parseGuardRecord(
|
|
3404
|
+
return parseGuardRecord(readFileSync11(identityGuardFile, "utf-8"));
|
|
2606
3405
|
} catch {
|
|
2607
3406
|
return emptyGuardRecord();
|
|
2608
3407
|
}
|
|
@@ -2642,16 +3441,86 @@ var EXPECTED_AGENT_ID = expectedAgentIdFromEnv(process.env);
|
|
|
2642
3441
|
if (cliArgs.name && profile.display_name !== cliArgs.name) {
|
|
2643
3442
|
profile.display_name = cliArgs.name;
|
|
2644
3443
|
}
|
|
2645
|
-
if (
|
|
3444
|
+
if (isOneShotCli && (!TOKEN || TOKEN === "dev-token")) {
|
|
2646
3445
|
process.stderr.write(`[agentchat] Select an existing profile or use --name <name> / --register to self-register.
|
|
2647
3446
|
`);
|
|
2648
3447
|
process.exit(1);
|
|
2649
3448
|
}
|
|
3449
|
+
if (cliArgs.join || cliArgs.send || cliArgs.wakeOnce) {
|
|
3450
|
+
if (cliArgs.send && !cliArgs.text) {
|
|
3451
|
+
process.stderr.write(`[agentchat] ERROR: --send <channel> requires --text <message>. See --help.
|
|
3452
|
+
`);
|
|
3453
|
+
process.exit(1);
|
|
3454
|
+
}
|
|
3455
|
+
if (cliArgs.join && !cliArgs.send && !cliArgs.wakeOnce) {
|
|
3456
|
+
const res = await joinChannelRest({
|
|
3457
|
+
restUrl: REST_URL,
|
|
3458
|
+
agentId: AGENT_ID,
|
|
3459
|
+
token: TOKEN,
|
|
3460
|
+
channelId: cliArgs.join
|
|
3461
|
+
});
|
|
3462
|
+
console.log(JSON.stringify(res));
|
|
3463
|
+
process.exit(res.ok ? 0 : 1);
|
|
3464
|
+
}
|
|
3465
|
+
const explicitMaxIdleMs = parseMaxIdleMs(cliArgs["max-idle"]);
|
|
3466
|
+
if (cliArgs.send) {
|
|
3467
|
+
if (cliArgs.join) {
|
|
3468
|
+
await joinChannelRest({
|
|
3469
|
+
restUrl: REST_URL,
|
|
3470
|
+
agentId: AGENT_ID,
|
|
3471
|
+
token: TOKEN,
|
|
3472
|
+
channelId: cliArgs.join
|
|
3473
|
+
});
|
|
3474
|
+
}
|
|
3475
|
+
const res = await sendRestMessage({
|
|
3476
|
+
restUrl: REST_URL,
|
|
3477
|
+
configDir,
|
|
3478
|
+
agentId: AGENT_ID,
|
|
3479
|
+
token: TOKEN,
|
|
3480
|
+
channelId: cliArgs.send,
|
|
3481
|
+
text: cliArgs.text,
|
|
3482
|
+
replyTo: cliArgs["reply-to"],
|
|
3483
|
+
maxIdleMs: explicitMaxIdleMs
|
|
3484
|
+
});
|
|
3485
|
+
console.log(JSON.stringify(res));
|
|
3486
|
+
process.exit(res.ok ? 0 : 1);
|
|
3487
|
+
}
|
|
3488
|
+
if (cliArgs.wakeOnce) {
|
|
3489
|
+
const rawChans = [
|
|
3490
|
+
...cliArgs.join ? [cliArgs.join] : [],
|
|
3491
|
+
...cliArgs.channel ? cliArgs.channel.split(",").map((c) => c.trim()).filter(Boolean) : []
|
|
3492
|
+
];
|
|
3493
|
+
const channels = rawChans.length > 0 ? [...new Set(rawChans)] : ["welcome"];
|
|
3494
|
+
const timeoutSec = cliArgs.timeout !== undefined ? Number(cliArgs.timeout) : 240;
|
|
3495
|
+
const timeoutMs = Number.isFinite(timeoutSec) && timeoutSec >= 0 ? timeoutSec * 1000 : 240000;
|
|
3496
|
+
const ev = await wakeOnce({
|
|
3497
|
+
restUrl: REST_URL,
|
|
3498
|
+
configDir,
|
|
3499
|
+
agentId: AGENT_ID,
|
|
3500
|
+
displayName: profile.display_name || AGENT_ID,
|
|
3501
|
+
token: TOKEN,
|
|
3502
|
+
channels,
|
|
3503
|
+
timeoutMs,
|
|
3504
|
+
maxIdleMs: explicitMaxIdleMs
|
|
3505
|
+
});
|
|
3506
|
+
console.log(JSON.stringify(ev));
|
|
3507
|
+
process.exit(0);
|
|
3508
|
+
}
|
|
3509
|
+
}
|
|
2650
3510
|
if (TOKEN && TOKEN !== "dev-token") {
|
|
2651
3511
|
const status = await getOnboardingStatus(REST_URL, AGENT_ID, TOKEN);
|
|
2652
3512
|
process.stderr.write(`[agentchat] ${claimSummary(status)}
|
|
2653
3513
|
`);
|
|
2654
3514
|
if (cliArgs.registerOnly) {
|
|
3515
|
+
try {
|
|
3516
|
+
mkdirSync4(configDir, { recursive: true });
|
|
3517
|
+
const lastSeenFile = join8(configDir, `last-seen-msg-ts-${AGENT_ID}.json`);
|
|
3518
|
+
const cursor = loadCursor(lastSeenFile, (m) => process.stderr.write(m));
|
|
3519
|
+
if (!cursor.get(CURSOR_INIT_KEY)) {
|
|
3520
|
+
cursor.set(CURSOR_INIT_KEY, new Date().toISOString());
|
|
3521
|
+
persistCursor(lastSeenFile, cursor, (m) => process.stderr.write(m));
|
|
3522
|
+
}
|
|
3523
|
+
} catch {}
|
|
2655
3524
|
console.log(JSON.stringify({ ...status, terms_notice: TERMS_NOTICE, claim_url: status.claimed === true ? null : `${status.chat_url}?key=${encodeURIComponent(TOKEN)}`, profile_file: activeProfileFile, reply_verified: false }));
|
|
2656
3525
|
process.exit(0);
|
|
2657
3526
|
}
|
|
@@ -3987,10 +4856,10 @@ function mimeFromPath(p, kindHint) {
|
|
|
3987
4856
|
return MEDIA_MIME_BY_EXT[ext] ?? "application/octet-stream";
|
|
3988
4857
|
}
|
|
3989
4858
|
async function uploadLocalFile(path, kindHint) {
|
|
3990
|
-
if (!
|
|
4859
|
+
if (!existsSync8(path))
|
|
3991
4860
|
throw new Error(`file not found: ${path}`);
|
|
3992
4861
|
const mime = mimeFromPath(path, kindHint);
|
|
3993
|
-
const buf =
|
|
4862
|
+
const buf = readFileSync11(path);
|
|
3994
4863
|
const name = path.split("/").pop() || "upload";
|
|
3995
4864
|
const form = new FormData;
|
|
3996
4865
|
form.append("file", new Blob([new Uint8Array(buf)], { type: mime }), name);
|
|
@@ -4187,10 +5056,10 @@ HANDLERS.set("transcribe", async (args) => {
|
|
|
4187
5056
|
});
|
|
4188
5057
|
function loadGrokBinds() {
|
|
4189
5058
|
const bindPath = resolveGrokBindsPath(configDir, process.env.AGENTCHAT_GROK_BINDS);
|
|
4190
|
-
if (!
|
|
5059
|
+
if (!existsSync8(bindPath))
|
|
4191
5060
|
return {};
|
|
4192
5061
|
try {
|
|
4193
|
-
return parseGrokBindsText(
|
|
5062
|
+
return parseGrokBindsText(readFileSync11(bindPath, "utf-8")).binds;
|
|
4194
5063
|
} catch {
|
|
4195
5064
|
return {};
|
|
4196
5065
|
}
|
|
@@ -4225,7 +5094,7 @@ function scheduleSlotLastSeenMessageTsSave(slot) {
|
|
|
4225
5094
|
slot.lastSeenMessageTsTimer.unref?.();
|
|
4226
5095
|
}
|
|
4227
5096
|
function createProfileSlot(opts) {
|
|
4228
|
-
const lastSeenFile =
|
|
5097
|
+
const lastSeenFile = join8(configDir, `last-seen-msg-ts-${opts.agentId}.json`);
|
|
4229
5098
|
const slot = {
|
|
4230
5099
|
profileName: opts.profileName,
|
|
4231
5100
|
profileFile: opts.profileFile,
|
|
@@ -4475,7 +5344,7 @@ function formatProfileList() {
|
|
|
4475
5344
|
const lines = profileEntries.map((entry) => {
|
|
4476
5345
|
let entryAgentId = "";
|
|
4477
5346
|
try {
|
|
4478
|
-
const parsed = JSON.parse(
|
|
5347
|
+
const parsed = JSON.parse(readFileSync11(entry.path, "utf-8"));
|
|
4479
5348
|
if (typeof parsed?.agent_id === "string")
|
|
4480
5349
|
entryAgentId = parsed.agent_id;
|
|
4481
5350
|
} catch {}
|
|
@@ -4508,7 +5377,7 @@ async function registerAndConnectProfile(displayName, bindSessionId) {
|
|
|
4508
5377
|
};
|
|
4509
5378
|
}
|
|
4510
5379
|
const existingTargetFile = nameToPath(cleanName);
|
|
4511
|
-
if (
|
|
5380
|
+
if (existsSync8(existingTargetFile)) {
|
|
4512
5381
|
return {
|
|
4513
5382
|
content: [{
|
|
4514
5383
|
type: "text",
|
|
@@ -4518,9 +5387,9 @@ async function registerAndConnectProfile(displayName, bindSessionId) {
|
|
|
4518
5387
|
};
|
|
4519
5388
|
}
|
|
4520
5389
|
const existingDefaultPath = nameToPath("profile");
|
|
4521
|
-
if (
|
|
5390
|
+
if (existsSync8(existingDefaultPath)) {
|
|
4522
5391
|
try {
|
|
4523
|
-
const defParsed = JSON.parse(
|
|
5392
|
+
const defParsed = JSON.parse(readFileSync11(existingDefaultPath, "utf-8"));
|
|
4524
5393
|
const defDisplay = typeof defParsed?.display_name === "string" ? defParsed.display_name.trim().toLowerCase() : "";
|
|
4525
5394
|
if (defDisplay && defDisplay === cleanName.toLowerCase()) {
|
|
4526
5395
|
return {
|
|
@@ -4562,7 +5431,7 @@ async function registerAndConnectProfile(displayName, bindSessionId) {
|
|
|
4562
5431
|
};
|
|
4563
5432
|
const targetFile = nameToPath(cleanName);
|
|
4564
5433
|
validateIdentityProfile(newProfile, targetFile);
|
|
4565
|
-
|
|
5434
|
+
mkdirSync4(dirname2(targetFile), { recursive: true });
|
|
4566
5435
|
safeWriteProfile2(targetFile, newProfile);
|
|
4567
5436
|
applyIdentityFromProfile(newProfile, targetFile, bindSessionId);
|
|
4568
5437
|
const claimEntry = `${REST_URL}/chat/${encodeURIComponent(data.id)}?claim=1`;
|
|
@@ -4618,7 +5487,7 @@ async function handleProfileSwitchOrConnect(args) {
|
|
|
4618
5487
|
return { content: [{ type: "text", text: switchGate.message }], isError: true };
|
|
4619
5488
|
}
|
|
4620
5489
|
const targetFile = nameToPath(profile_name);
|
|
4621
|
-
if (!
|
|
5490
|
+
if (!existsSync8(targetFile)) {
|
|
4622
5491
|
if (register) {
|
|
4623
5492
|
return await registerAndConnectProfile(profile_name, explicitSessionId);
|
|
4624
5493
|
}
|
|
@@ -4694,7 +5563,7 @@ function ensureGrokBoundIdentity() {
|
|
|
4694
5563
|
if (!boundName)
|
|
4695
5564
|
return;
|
|
4696
5565
|
const boundPath = nameToPath(boundName);
|
|
4697
|
-
if (!
|
|
5566
|
+
if (!existsSync8(boundPath))
|
|
4698
5567
|
return;
|
|
4699
5568
|
let boundProfile;
|
|
4700
5569
|
try {
|
|
@@ -4792,9 +5661,12 @@ var handleToolCall = async (request) => {
|
|
|
4792
5661
|
let { name, arguments: args } = request.params;
|
|
4793
5662
|
let viaExtendedCompat = false;
|
|
4794
5663
|
try {
|
|
5664
|
+
if (codexIdentity && (AGENT_ID !== codexIdentity.agentId || ["connect_profile", "switch_profile", "disconnect_profile"].includes(name))) {
|
|
5665
|
+
return { content: [{ type: "text", text: "Codex bridge owns this tool identity; change the bot configuration and restart to change identity." }], isError: true };
|
|
5666
|
+
}
|
|
4795
5667
|
const rawMeta = request.params?._meta;
|
|
4796
5668
|
const { session: callerSession, isPerCallSession } = await resolveCallerSessionForToolCall(name, args, rawMeta);
|
|
4797
|
-
if (callerSession) {
|
|
5669
|
+
if (callerSession && !codexIdentity) {
|
|
4798
5670
|
runtimeSession = callerSession;
|
|
4799
5671
|
const binds = loadSessionBinds(configDir);
|
|
4800
5672
|
const boundProfileName = binds[callerSession.sessionId];
|
|
@@ -4814,7 +5686,7 @@ var handleToolCall = async (request) => {
|
|
|
4814
5686
|
}
|
|
4815
5687
|
} else if (!isProfileControlTool || name === "disconnect_profile") {
|
|
4816
5688
|
const boundPath = nameToPath(boundProfileName);
|
|
4817
|
-
if (
|
|
5689
|
+
if (existsSync8(boundPath)) {
|
|
4818
5690
|
try {
|
|
4819
5691
|
const candidate = readIdentityProfile(boundPath);
|
|
4820
5692
|
const aliasSlot = candidate?.agent_id ? findSlotByAgentId(candidate.agent_id) : undefined;
|
|
@@ -4886,7 +5758,8 @@ var handleToolCall = async (request) => {
|
|
|
4886
5758
|
if (argErr)
|
|
4887
5759
|
return { content: [{ type: "text", text: `${name}: ${argErr}` }], isError: true };
|
|
4888
5760
|
}
|
|
4889
|
-
|
|
5761
|
+
if (!codexIdentity)
|
|
5762
|
+
ensureGrokBoundIdentity();
|
|
4890
5763
|
if (identityGateMessage && name !== "whoami" && TOOL_ANNOTATIONS[name]?.readOnlyHint !== true) {
|
|
4891
5764
|
return { content: [{ type: "text", text: `\uD83D\uDEA8 ${identityGateMessage}` }], isError: true };
|
|
4892
5765
|
}
|
|
@@ -5107,7 +5980,7 @@ ${a.body || ""}`;
|
|
|
5107
5980
|
const currentVersion = Number(meta.version ?? 0);
|
|
5108
5981
|
let cachedVersion = null;
|
|
5109
5982
|
try {
|
|
5110
|
-
cachedVersion = Number(JSON.parse(
|
|
5983
|
+
cachedVersion = Number(JSON.parse(readFileSync11(pMeta, "utf8")).version);
|
|
5111
5984
|
} catch {}
|
|
5112
5985
|
if (cachedVersion !== null && cachedVersion === currentVersion) {
|
|
5113
5986
|
return { content: [{ type: "text", text: `up-to-date: personal skill "${a.name}" v${currentVersion} already at ${pMd} \u2014 no download. Read that file to run it.` }] };
|
|
@@ -5116,9 +5989,9 @@ ${a.body || ""}`;
|
|
|
5116
5989
|
if (!bodyR.ok)
|
|
5117
5990
|
return { content: [{ type: "text", text: `sync_skill (personal): body fetch failed (${bodyR.status})` }], isError: true };
|
|
5118
5991
|
const doc = JSON.parse(await bodyR.text());
|
|
5119
|
-
|
|
5120
|
-
|
|
5121
|
-
|
|
5992
|
+
mkdirSync4(dirname2(pMd), { recursive: true });
|
|
5993
|
+
writeFileSync6(pMd, String(doc?.body_markdown ?? ""));
|
|
5994
|
+
writeFileSync6(pMeta, JSON.stringify({ version: currentVersion, name: a.name, syncedAt: new Date().toISOString() }));
|
|
5122
5995
|
return { content: [{ type: "text", text: `synced personal skill "${a.name}" v${currentVersion} \u2192 ${pMd} (was ${cachedVersion === null ? "missing" : `stale v${cachedVersion}`}). Read that file to run it.` }] };
|
|
5123
5996
|
} catch (e) {
|
|
5124
5997
|
return { content: [{ type: "text", text: `sync_skill (personal) error: ${String(e?.message || e).slice(0, 140)}` }], isError: true };
|
|
@@ -5141,7 +6014,7 @@ ${a.body || ""}`;
|
|
|
5141
6014
|
const currentVersion = Number(meta.version ?? 0);
|
|
5142
6015
|
let cachedVersion = null;
|
|
5143
6016
|
try {
|
|
5144
|
-
cachedVersion = Number(JSON.parse(
|
|
6017
|
+
cachedVersion = Number(JSON.parse(readFileSync11(metaPath, "utf8")).version);
|
|
5145
6018
|
} catch {}
|
|
5146
6019
|
if (cachedVersion !== null && cachedVersion === currentVersion) {
|
|
5147
6020
|
return { content: [{ type: "text", text: `up-to-date: "${a.doc_id}" v${currentVersion} already at ${mdPath} \u2014 no download. Read that file to run it.` }] };
|
|
@@ -5151,9 +6024,9 @@ ${a.body || ""}`;
|
|
|
5151
6024
|
return { content: [{ type: "text", text: `sync_skill: fetch body failed (${docR.status})` }], isError: true };
|
|
5152
6025
|
const doc = JSON.parse(await docR.text());
|
|
5153
6026
|
const body = String(doc?.body_markdown ?? doc?.bodyMarkdown ?? "");
|
|
5154
|
-
|
|
5155
|
-
|
|
5156
|
-
|
|
6027
|
+
mkdirSync4(dirname2(mdPath), { recursive: true });
|
|
6028
|
+
writeFileSync6(mdPath, body);
|
|
6029
|
+
writeFileSync6(metaPath, JSON.stringify({ version: currentVersion, title: doc?.title, doc_id: a.doc_id, chat_id: a.chat_id, syncedAt: new Date().toISOString() }));
|
|
5157
6030
|
const was = cachedVersion === null ? "missing" : `stale v${cachedVersion}`;
|
|
5158
6031
|
return { content: [{ type: "text", text: `synced "${doc?.title || a.doc_id}" v${currentVersion} \u2192 ${mdPath} (was ${was}). Read that file to run it in your runtime.` }] };
|
|
5159
6032
|
} catch (e) {
|
|
@@ -5643,12 +6516,26 @@ ${results}` }] };
|
|
|
5643
6516
|
} catch {}
|
|
5644
6517
|
}
|
|
5645
6518
|
try {
|
|
5646
|
-
await
|
|
6519
|
+
const joinRes = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/join`, {
|
|
6520
|
+
method: "POST",
|
|
6521
|
+
headers: { Authorization: `Bearer ${TOKEN}`, "Content-Type": "application/json" },
|
|
6522
|
+
body: JSON.stringify({ sender_id: AGENT_ID })
|
|
6523
|
+
});
|
|
6524
|
+
if (joinRes.ok) {
|
|
6525
|
+
if (activeSlot)
|
|
6526
|
+
activeSlot.knownChannels.add(chat_id);
|
|
6527
|
+
const brief = await channelBrief(chat_id).catch(() => "");
|
|
6528
|
+
return { content: [{ type: "text", text: `Joined channel ${chat_id.slice(0, 8)}
|
|
6529
|
+
${brief}` }] };
|
|
6530
|
+
}
|
|
6531
|
+
await new Promise((r2) => setTimeout(r2, 300));
|
|
5647
6532
|
const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/members`, { headers: { Authorization: `Bearer ${TOKEN}` } });
|
|
5648
6533
|
if (r.ok) {
|
|
5649
6534
|
const data = await r.json();
|
|
5650
6535
|
const isMember = (data.members || []).some((m) => m.agent_id === AGENT_ID);
|
|
5651
6536
|
if (isMember) {
|
|
6537
|
+
if (activeSlot)
|
|
6538
|
+
activeSlot.knownChannels.add(chat_id);
|
|
5652
6539
|
const brief = await channelBrief(chat_id).catch(() => "");
|
|
5653
6540
|
return { content: [{ type: "text", text: `Joined channel ${chat_id.slice(0, 8)}
|
|
5654
6541
|
${brief}` }] };
|
|
@@ -6122,7 +7009,7 @@ ${formatHistoryMessage(exact, true)}` }] };
|
|
|
6122
7009
|
return { content: [{ type: "text", text: `${msgs.length} messages:
|
|
6123
7010
|
${list}` }] };
|
|
6124
7011
|
}
|
|
6125
|
-
return { content: [{ type: "text", text: `Failed to get history (${r.status})` }] };
|
|
7012
|
+
return { content: [{ type: "text", text: `Failed to get history (${r.status})` }], isError: true };
|
|
6126
7013
|
} catch (e) {
|
|
6127
7014
|
return { content: [{ type: "text", text: `Error: ${e}` }] };
|
|
6128
7015
|
}
|
|
@@ -6478,7 +7365,7 @@ ${list}` }] };
|
|
|
6478
7365
|
}
|
|
6479
7366
|
};
|
|
6480
7367
|
server.setRequestHandler(CallToolRequestSchema, (request) => serializeCall(() => handleToolCall(request)));
|
|
6481
|
-
var mentionTsFile =
|
|
7368
|
+
var mentionTsFile = join8(configDir, `mention-ts-${AGENT_ID}.json`);
|
|
6482
7369
|
function loadMentionTimestamps() {
|
|
6483
7370
|
return loadCursor(mentionTsFile, safeStderrWrite);
|
|
6484
7371
|
}
|
|
@@ -6719,7 +7606,7 @@ function syncOpenBoundSessions() {
|
|
|
6719
7606
|
if (!boundProf || profileSlots.has(boundProf))
|
|
6720
7607
|
continue;
|
|
6721
7608
|
const boundPath = nameToPath(boundProf);
|
|
6722
|
-
if (!
|
|
7609
|
+
if (!existsSync8(boundPath))
|
|
6723
7610
|
continue;
|
|
6724
7611
|
try {
|
|
6725
7612
|
const candidate = readIdentityProfile(boundPath);
|
|
@@ -6950,15 +7837,15 @@ ${context}
|
|
|
6950
7837
|
if (process.env.AGENTCHAT_WAKE_MODE === "grok") {
|
|
6951
7838
|
(async () => {
|
|
6952
7839
|
try {
|
|
6953
|
-
const { readFileSync:
|
|
6954
|
-
const gwPath = resolveGrokGatewayPath(process.env.AGENTCHAT_GROK_GATEWAY,
|
|
7840
|
+
const { readFileSync: readFileSync12, existsSync: existsSync9 } = await import("fs");
|
|
7841
|
+
const gwPath = resolveGrokGatewayPath(process.env.AGENTCHAT_GROK_GATEWAY, existsSync9);
|
|
6955
7842
|
let agentId = process.env.AGENTCHAT_GROK_AGENT_ID || "";
|
|
6956
7843
|
if (!agentId) {
|
|
6957
7844
|
agentId = await resolveGrokAgentId({
|
|
6958
7845
|
explicitId: "",
|
|
6959
7846
|
agentschatName: slot.profile.display_name || slot.agentId,
|
|
6960
7847
|
listAgents: async () => {
|
|
6961
|
-
const gwcfg = JSON.parse(
|
|
7848
|
+
const gwcfg = JSON.parse(readFileSync12(gwPath, "utf8"));
|
|
6962
7849
|
const token = grokBearerFromGatewayConfig(gwcfg);
|
|
6963
7850
|
const port = grokPortFromGatewayConfig(gwcfg);
|
|
6964
7851
|
const res = await fetch(`http://127.0.0.1:${port}/api/listAgents`, {
|
|
@@ -7028,7 +7915,7 @@ ${context}
|
|
|
7028
7915
|
let soleMatchesAgent = false;
|
|
7029
7916
|
if (soleBoundProf) {
|
|
7030
7917
|
const p = nameToPath(soleBoundProf);
|
|
7031
|
-
if (
|
|
7918
|
+
if (existsSync8(p)) {
|
|
7032
7919
|
try {
|
|
7033
7920
|
soleMatchesAgent = readIdentityProfile(p)?.agent_id === slot.agentId;
|
|
7034
7921
|
} catch {}
|
|
@@ -7216,6 +8103,11 @@ async function checkVersionStaleness() {
|
|
|
7216
8103
|
}
|
|
7217
8104
|
}
|
|
7218
8105
|
async function main() {
|
|
8106
|
+
if (codexIdentity) {
|
|
8107
|
+
const status = await getOnboardingStatus(REST_URL, AGENT_ID, TOKEN);
|
|
8108
|
+
if (status.authentication !== "ok")
|
|
8109
|
+
throw new Error("Codex tool authentication failed; bridge transport alone is not tool readiness");
|
|
8110
|
+
}
|
|
7219
8111
|
installStdioLifecycleGuards();
|
|
7220
8112
|
if (!toolOnlyMode) {
|
|
7221
8113
|
syncOpenBoundSessions();
|