agentschat-mcp 0.36.22 → 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/CHANGELOG.md +5 -0
- 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 +54 -14
- package/dist/dsh.js +16 -0
- package/dist/server.js +1461 -171
- package/package.json +4 -3
- package/skills/onboarding.md +20 -1
- package/src/cli.mjs +42 -0
- package/src/profile-store.ts +85 -1
- package/src/redact.ts +34 -0
- package/src/rest-cli.ts +774 -0
- package/src/server.ts +555 -107
- package/src/session-bind.ts +125 -30
- package/src/session-route.ts +6 -1
package/src/rest-cli.ts
ADDED
|
@@ -0,0 +1,774 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stateless REST + SSE CLI operations (`--join`, `--send`, `--wake-once`) for
|
|
3
|
+
* environments where stdio MCP is not mounted or HTTP proxies block WebSocket
|
|
4
|
+
* upgrades (e.g. Antigravity Cloud VM `agy-plugin-proxy` returning 403 on WS Upgrade
|
|
5
|
+
* while allowing HTTPS REST & Server-Sent Events `/api/channels/:id/stream`).
|
|
6
|
+
*
|
|
7
|
+
* Cursor contract:
|
|
8
|
+
* - Shares `~/.agentschat/last-seen-msg-ts-<agent_id>.json` (`loadCursor` /
|
|
9
|
+
* `persistCursor` from `./read-cursor.ts`) with the MCP server so per-channel
|
|
10
|
+
* progress is 100% unified across CLI turns and MCP tool calls.
|
|
11
|
+
* - Shares `~/.agentschat/mention-timestamps.json` so group `@mention` wakes
|
|
12
|
+
* automatically include recent group context since the previous `@mention`.
|
|
13
|
+
* - Records `__init_ts__` in the per-agent cursor map on first initialization:
|
|
14
|
+
* pre-existing group history older than `__init_ts__` seeds the channel cursor
|
|
15
|
+
* without replaying stale messages, while a brand-new DM channel (`dm-*`) or
|
|
16
|
+
* any message arriving at/after `__init_ts__` is delivered immediately without
|
|
17
|
+
* being swallowed by cold-start seeding.
|
|
18
|
+
*/
|
|
19
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
20
|
+
import { dirname, join } from "node:path";
|
|
21
|
+
import { matchesMention } from "./mentions.ts";
|
|
22
|
+
import { safeWriteProfile } from "./profile-store.ts";
|
|
23
|
+
import { loadCursor, persistCursor, type Warn } from "./read-cursor.ts";
|
|
24
|
+
import { redactParticipantPii, redactSecrets } from "./redact.ts";
|
|
25
|
+
import { normalizeTimestampForCursor } from "./timestamps.ts";
|
|
26
|
+
import { buildWakePrompt, formatWakeAttachments } from "./wake.ts";
|
|
27
|
+
|
|
28
|
+
export const CURSOR_INIT_KEY = "__init_ts__";
|
|
29
|
+
export const CURSOR_LAST_ACTIVE_KEY = "__last_active_ts__";
|
|
30
|
+
export const CURSOR_MAX_IDLE_KEY = "__max_idle_ms__";
|
|
31
|
+
export const DEFAULT_MAX_IDLE_MS = 60 * 60 * 1000; // 1 hour
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Parse `--max-idle` value into milliseconds.
|
|
35
|
+
* Accepts plain seconds (`"3600"`), human suffixes (`"30m"`, `"2h"`, `"1.5h"`, `"1d"`, `"90s"`),
|
|
36
|
+
* or `"0"` / `"never"` / `"infinite"` / `"off"` (`0`, meaning never auto-hibernate).
|
|
37
|
+
*/
|
|
38
|
+
export function parseMaxIdleMs(raw: string | number | undefined): number | undefined {
|
|
39
|
+
if (raw === undefined || raw === null) return undefined;
|
|
40
|
+
if (typeof raw === "number") {
|
|
41
|
+
return Number.isFinite(raw) && raw >= 0 ? Math.round(raw * 1000) : undefined;
|
|
42
|
+
}
|
|
43
|
+
const s = String(raw).trim().toLowerCase();
|
|
44
|
+
if (!s) return undefined;
|
|
45
|
+
if (s === "0" || s === "never" || s === "infinite" || s === "forever" || s === "off") {
|
|
46
|
+
return 0;
|
|
47
|
+
}
|
|
48
|
+
const m = s.match(/^(\d+(?:\.\d+)?)\s*(ms|s|sec|secs|m|min|mins|h|hr|hrs|hour|hours|d|day|days)?$/);
|
|
49
|
+
if (!m) return undefined;
|
|
50
|
+
const val = Number(m[1]);
|
|
51
|
+
if (!Number.isFinite(val) || val < 0) return undefined;
|
|
52
|
+
const unit = m[2] || "s";
|
|
53
|
+
if (unit === "ms") return Math.round(val);
|
|
54
|
+
if (unit === "s" || unit === "sec" || unit === "secs") return Math.round(val * 1000);
|
|
55
|
+
if (unit === "m" || unit === "min" || unit === "mins") return Math.round(val * 60_000);
|
|
56
|
+
if (unit === "h" || unit === "hr" || unit === "hrs" || unit === "hour" || unit === "hours") {
|
|
57
|
+
return Math.round(val * 3_600_000);
|
|
58
|
+
}
|
|
59
|
+
if (unit === "d" || unit === "day" || unit === "days") return Math.round(val * 86_400_000);
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
const MAX_SSE_STREAMS = 3;
|
|
63
|
+
const MAX_SEEN_IDS = 200;
|
|
64
|
+
|
|
65
|
+
export interface JoinChannelResult {
|
|
66
|
+
ok: boolean;
|
|
67
|
+
status: number;
|
|
68
|
+
agent_id: string;
|
|
69
|
+
channel_id: string;
|
|
70
|
+
name?: string;
|
|
71
|
+
error?: string;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface SendMessageResult {
|
|
75
|
+
ok: boolean;
|
|
76
|
+
status: number;
|
|
77
|
+
id?: string;
|
|
78
|
+
agent_id: string;
|
|
79
|
+
channel_id: string;
|
|
80
|
+
in_reply_to?: string;
|
|
81
|
+
error?: string;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface WakeOnceMessageItem {
|
|
85
|
+
id: string;
|
|
86
|
+
sender_id: string;
|
|
87
|
+
content: string;
|
|
88
|
+
timestamp: string;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface WakeOnceEvent {
|
|
92
|
+
event: "agentschat_wake" | "idle_timeout" | "hibernate";
|
|
93
|
+
agent_id: string;
|
|
94
|
+
channel_id?: string;
|
|
95
|
+
message_id?: string;
|
|
96
|
+
sender_id?: string;
|
|
97
|
+
content?: string;
|
|
98
|
+
timestamp?: string;
|
|
99
|
+
messages?: WakeOnceMessageItem[];
|
|
100
|
+
context_prefix?: string;
|
|
101
|
+
prompt?: string;
|
|
102
|
+
timeout_ms?: number;
|
|
103
|
+
idle_ms?: number;
|
|
104
|
+
max_idle_ms?: number;
|
|
105
|
+
should_rearm?: boolean;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function loadSeenIds(file: string): string[] {
|
|
109
|
+
if (!existsSync(file)) return [];
|
|
110
|
+
try {
|
|
111
|
+
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
112
|
+
return Array.isArray(parsed) ? parsed.filter((x) => typeof x === "string") : [];
|
|
113
|
+
} catch {
|
|
114
|
+
return [];
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function saveSeenIds(file: string, ids: Iterable<string>): void {
|
|
119
|
+
try {
|
|
120
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
121
|
+
const list = [...ids].slice(-MAX_SEEN_IDS);
|
|
122
|
+
safeWriteProfile(file, list);
|
|
123
|
+
} catch {}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function loadJsonMap(file: string): Record<string, string> {
|
|
127
|
+
if (!existsSync(file)) return {};
|
|
128
|
+
try {
|
|
129
|
+
const raw = JSON.parse(readFileSync(file, "utf8"));
|
|
130
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
|
|
131
|
+
return raw as Record<string, string>;
|
|
132
|
+
} catch {
|
|
133
|
+
return {};
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function saveJsonMap(file: string, data: Record<string, string>): void {
|
|
138
|
+
try {
|
|
139
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
140
|
+
safeWriteProfile(file, data);
|
|
141
|
+
} catch {}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Update both `last-seen-msg-ts-<agent>.json` and `read-cursors.json` for a channel. */
|
|
145
|
+
export function advanceChannelReadCursor(opts: {
|
|
146
|
+
configDir: string;
|
|
147
|
+
agentId: string;
|
|
148
|
+
channelId: string;
|
|
149
|
+
timestamp: string;
|
|
150
|
+
maxIdleMs?: number;
|
|
151
|
+
warn?: Warn;
|
|
152
|
+
}): void {
|
|
153
|
+
const { configDir, agentId, channelId, timestamp } = opts;
|
|
154
|
+
if (!agentId || !channelId || !timestamp) return;
|
|
155
|
+
const warn = opts.warn ?? ((m: string) => process.stderr.write(m));
|
|
156
|
+
mkdirSync(configDir, { recursive: true });
|
|
157
|
+
|
|
158
|
+
const lastSeenFile = join(configDir, `last-seen-msg-ts-${agentId}.json`);
|
|
159
|
+
const cursor = loadCursor(lastSeenFile, warn);
|
|
160
|
+
const prev = cursor.get(channelId) || "";
|
|
161
|
+
const nextNorm = normalizeTimestampForCursor(timestamp, "after") || timestamp;
|
|
162
|
+
const prevNorm = normalizeTimestampForCursor(prev, "after") || prev;
|
|
163
|
+
cursor.set(CURSOR_LAST_ACTIVE_KEY, timestamp);
|
|
164
|
+
if (opts.maxIdleMs !== undefined && Number.isFinite(opts.maxIdleMs) && opts.maxIdleMs >= 0) {
|
|
165
|
+
cursor.set(CURSOR_MAX_IDLE_KEY, String(Math.round(opts.maxIdleMs)));
|
|
166
|
+
}
|
|
167
|
+
if (!prev || nextNorm > prevNorm) {
|
|
168
|
+
cursor.set(channelId, timestamp);
|
|
169
|
+
}
|
|
170
|
+
persistCursor(lastSeenFile, cursor, warn);
|
|
171
|
+
|
|
172
|
+
const readCursorsFile = join(configDir, "read-cursors.json");
|
|
173
|
+
const readCursors = loadJsonMap(readCursorsFile);
|
|
174
|
+
const scopedKey = `${agentId}:${channelId}`;
|
|
175
|
+
const prevRead = readCursors[scopedKey] || readCursors[channelId] || "";
|
|
176
|
+
const prevReadNorm = normalizeTimestampForCursor(prevRead, "after") || prevRead;
|
|
177
|
+
if (!prevRead || nextNorm > prevReadNorm) {
|
|
178
|
+
readCursors[scopedKey] = timestamp;
|
|
179
|
+
readCursors[channelId] = timestamp;
|
|
180
|
+
saveJsonMap(readCursorsFile, readCursors);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Join a channel via `POST /api/channels/:id/join` (works without WebSocket). */
|
|
185
|
+
export async function joinChannelRest(opts: {
|
|
186
|
+
restUrl: string;
|
|
187
|
+
agentId: string;
|
|
188
|
+
token: string;
|
|
189
|
+
channelId: string;
|
|
190
|
+
fetchImpl?: typeof fetch;
|
|
191
|
+
}): Promise<JoinChannelResult> {
|
|
192
|
+
const f = opts.fetchImpl ?? fetch;
|
|
193
|
+
const baseUrl = opts.restUrl.replace(/\/$/, "");
|
|
194
|
+
const url = `${baseUrl}/api/channels/${encodeURIComponent(opts.channelId)}/join`;
|
|
195
|
+
try {
|
|
196
|
+
const res = await f(url, {
|
|
197
|
+
method: "POST",
|
|
198
|
+
headers: {
|
|
199
|
+
Authorization: `Bearer ${opts.token}`,
|
|
200
|
+
"Content-Type": "application/json",
|
|
201
|
+
},
|
|
202
|
+
body: JSON.stringify({ sender_id: opts.agentId }),
|
|
203
|
+
});
|
|
204
|
+
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
|
205
|
+
if (res.ok) {
|
|
206
|
+
return {
|
|
207
|
+
ok: true,
|
|
208
|
+
status: res.status,
|
|
209
|
+
agent_id: opts.agentId,
|
|
210
|
+
channel_id: String(data.channel_id ?? opts.channelId),
|
|
211
|
+
...(typeof data.name === "string" ? { name: data.name } : {}),
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
return {
|
|
215
|
+
ok: false,
|
|
216
|
+
status: res.status,
|
|
217
|
+
agent_id: opts.agentId,
|
|
218
|
+
channel_id: opts.channelId,
|
|
219
|
+
error: String(data.error ?? data.message ?? `HTTP ${res.status}`),
|
|
220
|
+
};
|
|
221
|
+
} catch (e: any) {
|
|
222
|
+
return {
|
|
223
|
+
ok: false,
|
|
224
|
+
status: 0,
|
|
225
|
+
agent_id: opts.agentId,
|
|
226
|
+
channel_id: opts.channelId,
|
|
227
|
+
error: String(e?.message || e),
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Send a message via `POST /api/channels/:id/messages` and advance the channel cursor. */
|
|
233
|
+
export async function sendRestMessage(opts: {
|
|
234
|
+
restUrl: string;
|
|
235
|
+
configDir: string;
|
|
236
|
+
agentId: string;
|
|
237
|
+
token: string;
|
|
238
|
+
channelId: string;
|
|
239
|
+
text: string;
|
|
240
|
+
replyTo?: string;
|
|
241
|
+
maxIdleMs?: number;
|
|
242
|
+
fetchImpl?: typeof fetch;
|
|
243
|
+
warn?: Warn;
|
|
244
|
+
}): Promise<SendMessageResult> {
|
|
245
|
+
const f = opts.fetchImpl ?? fetch;
|
|
246
|
+
const baseUrl = opts.restUrl.replace(/\/$/, "");
|
|
247
|
+
const cleanText = redactSecrets(opts.text);
|
|
248
|
+
const url = `${baseUrl}/api/channels/${encodeURIComponent(opts.channelId)}/messages`;
|
|
249
|
+
try {
|
|
250
|
+
const res = await f(url, {
|
|
251
|
+
method: "POST",
|
|
252
|
+
headers: {
|
|
253
|
+
Authorization: `Bearer ${opts.token}`,
|
|
254
|
+
"Content-Type": "application/json",
|
|
255
|
+
},
|
|
256
|
+
body: JSON.stringify({
|
|
257
|
+
sender_id: opts.agentId,
|
|
258
|
+
sender_type: "agent",
|
|
259
|
+
content_type: "text",
|
|
260
|
+
content: cleanText,
|
|
261
|
+
...(opts.replyTo ? { in_reply_to: opts.replyTo } : {}),
|
|
262
|
+
}),
|
|
263
|
+
});
|
|
264
|
+
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
|
265
|
+
if (res.ok) {
|
|
266
|
+
advanceChannelReadCursor({
|
|
267
|
+
configDir: opts.configDir,
|
|
268
|
+
agentId: opts.agentId,
|
|
269
|
+
channelId: opts.channelId,
|
|
270
|
+
timestamp: new Date().toISOString(),
|
|
271
|
+
maxIdleMs: opts.maxIdleMs,
|
|
272
|
+
warn: opts.warn,
|
|
273
|
+
});
|
|
274
|
+
return {
|
|
275
|
+
ok: true,
|
|
276
|
+
status: res.status,
|
|
277
|
+
id: typeof data.id === "string" ? data.id : undefined,
|
|
278
|
+
agent_id: opts.agentId,
|
|
279
|
+
channel_id: opts.channelId,
|
|
280
|
+
...(opts.replyTo ? { in_reply_to: opts.replyTo } : {}),
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
return {
|
|
284
|
+
ok: false,
|
|
285
|
+
status: res.status,
|
|
286
|
+
agent_id: opts.agentId,
|
|
287
|
+
channel_id: opts.channelId,
|
|
288
|
+
error: String(data.error ?? data.message ?? `HTTP ${res.status}`),
|
|
289
|
+
};
|
|
290
|
+
} catch (e: any) {
|
|
291
|
+
return {
|
|
292
|
+
ok: false,
|
|
293
|
+
status: 0,
|
|
294
|
+
agent_id: opts.agentId,
|
|
295
|
+
channel_id: opts.channelId,
|
|
296
|
+
error: String(e?.message || e),
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
export function isMessageAddressedToAgent(
|
|
302
|
+
msg: Record<string, any>,
|
|
303
|
+
agentId: string,
|
|
304
|
+
displayName?: string,
|
|
305
|
+
): boolean {
|
|
306
|
+
if (!msg || typeof msg !== "object") return false;
|
|
307
|
+
if (msg.content === "__typing__") return false;
|
|
308
|
+
const metaKind = msg.meta && typeof msg.meta === "object" ? msg.meta.kind : undefined;
|
|
309
|
+
if (metaKind === "slash_input" || metaKind === "loop_status" || metaKind === "slash_response") {
|
|
310
|
+
return false;
|
|
311
|
+
}
|
|
312
|
+
const isOwnLoopTick = metaKind === "loop_tick" && msg.sender_id === agentId;
|
|
313
|
+
if (msg.sender_id === agentId && !isOwnLoopTick) return false;
|
|
314
|
+
if (isOwnLoopTick) return true;
|
|
315
|
+
|
|
316
|
+
const channelId = String(msg.channel_id || "");
|
|
317
|
+
if (channelId.startsWith("dm-")) return true;
|
|
318
|
+
if (Array.isArray(msg.mentioned_ids) && msg.mentioned_ids.includes(agentId)) return true;
|
|
319
|
+
const content = String(msg.content || "");
|
|
320
|
+
if (matchesMention(content, agentId)) return true;
|
|
321
|
+
if (displayName && displayName !== agentId && matchesMention(content, displayName)) return true;
|
|
322
|
+
return false;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Wait for the next inbound `@mention` or DM using per-channel cursors
|
|
327
|
+
* (`last-seen-msg-ts-<agent_id>.json`), SSE streams (`/api/channels/:id/stream`),
|
|
328
|
+
* and `/api/channels/mine` discovery.
|
|
329
|
+
*/
|
|
330
|
+
export async function wakeOnce(opts: {
|
|
331
|
+
restUrl: string;
|
|
332
|
+
configDir: string;
|
|
333
|
+
agentId: string;
|
|
334
|
+
displayName?: string;
|
|
335
|
+
token: string;
|
|
336
|
+
channels?: string[];
|
|
337
|
+
timeoutMs?: number;
|
|
338
|
+
maxIdleMs?: number;
|
|
339
|
+
pollIntervalMs?: number;
|
|
340
|
+
enableSse?: boolean;
|
|
341
|
+
nowIso?: () => string;
|
|
342
|
+
fetchImpl?: typeof fetch;
|
|
343
|
+
warn?: Warn;
|
|
344
|
+
}): Promise<WakeOnceEvent> {
|
|
345
|
+
const f = opts.fetchImpl ?? fetch;
|
|
346
|
+
const warn = opts.warn ?? ((m: string) => process.stderr.write(m));
|
|
347
|
+
const nowIso = opts.nowIso ?? (() => new Date().toISOString());
|
|
348
|
+
const baseUrl = opts.restUrl.replace(/\/$/, "");
|
|
349
|
+
const { configDir, agentId, displayName, token } = opts;
|
|
350
|
+
const timeoutMs = opts.timeoutMs ?? 240_000;
|
|
351
|
+
const pollIntervalMs = opts.pollIntervalMs ?? 15_000;
|
|
352
|
+
const enableSse = opts.enableSse ?? true;
|
|
353
|
+
|
|
354
|
+
mkdirSync(configDir, { recursive: true });
|
|
355
|
+
const lastSeenFile = join(configDir, `last-seen-msg-ts-${agentId}.json`);
|
|
356
|
+
const seenIdsFile = join(configDir, `wake-seen-ids-${agentId}.json`);
|
|
357
|
+
const mentionTsFile = join(configDir, "mention-timestamps.json");
|
|
358
|
+
const wakePidFile = join(configDir, `wake-once-${agentId}.pid`);
|
|
359
|
+
|
|
360
|
+
// When running against live network (not unit test mock fetch), ensure at most one wake-once listener per agent
|
|
361
|
+
if (!opts.fetchImpl) {
|
|
362
|
+
try {
|
|
363
|
+
if (existsSync(wakePidFile)) {
|
|
364
|
+
const oldPid = parseInt(readFileSync(wakePidFile, "utf-8").trim(), 10);
|
|
365
|
+
if (Number.isFinite(oldPid) && oldPid > 1 && oldPid !== process.pid) {
|
|
366
|
+
try {
|
|
367
|
+
process.kill(oldPid, "SIGTERM");
|
|
368
|
+
} catch {}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
writeFileSync(wakePidFile, `${process.pid}\n`, { mode: 0o600 });
|
|
372
|
+
} catch {}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
const cursor = loadCursor(lastSeenFile, warn);
|
|
376
|
+
let cursorDirty = false;
|
|
377
|
+
if (!cursor.get(CURSOR_INIT_KEY)) {
|
|
378
|
+
cursor.set(CURSOR_INIT_KEY, nowIso());
|
|
379
|
+
cursorDirty = true;
|
|
380
|
+
}
|
|
381
|
+
if (!cursor.get(CURSOR_LAST_ACTIVE_KEY)) {
|
|
382
|
+
cursor.set(CURSOR_LAST_ACTIVE_KEY, nowIso());
|
|
383
|
+
cursorDirty = true;
|
|
384
|
+
}
|
|
385
|
+
if (opts.maxIdleMs !== undefined && Number.isFinite(opts.maxIdleMs) && opts.maxIdleMs >= 0) {
|
|
386
|
+
const nextMaxIdleStr = String(Math.round(opts.maxIdleMs));
|
|
387
|
+
if (cursor.get(CURSOR_MAX_IDLE_KEY) !== nextMaxIdleStr) {
|
|
388
|
+
cursor.set(CURSOR_MAX_IDLE_KEY, nextMaxIdleStr);
|
|
389
|
+
cursorDirty = true;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
if (cursorDirty) {
|
|
393
|
+
persistCursor(lastSeenFile, cursor, warn);
|
|
394
|
+
}
|
|
395
|
+
const savedMaxIdleRaw = cursor.get(CURSOR_MAX_IDLE_KEY);
|
|
396
|
+
const savedMaxIdleMs = savedMaxIdleRaw !== undefined ? Number(savedMaxIdleRaw) : undefined;
|
|
397
|
+
const maxIdleMs =
|
|
398
|
+
opts.maxIdleMs !== undefined
|
|
399
|
+
? opts.maxIdleMs
|
|
400
|
+
: savedMaxIdleMs !== undefined && Number.isFinite(savedMaxIdleMs) && savedMaxIdleMs >= 0
|
|
401
|
+
? savedMaxIdleMs
|
|
402
|
+
: DEFAULT_MAX_IDLE_MS;
|
|
403
|
+
const initTs = cursor.get(CURSOR_INIT_KEY)!;
|
|
404
|
+
const initTsNorm = normalizeTimestampForCursor(initTs, "after") || initTs;
|
|
405
|
+
|
|
406
|
+
const seenSet = new Set<string>(loadSeenIds(seenIdsFile));
|
|
407
|
+
const headers = {
|
|
408
|
+
Authorization: `Bearer ${token}`,
|
|
409
|
+
"Content-Type": "application/json",
|
|
410
|
+
};
|
|
411
|
+
|
|
412
|
+
for (const ch of opts.channels ?? []) {
|
|
413
|
+
if (ch && ch.trim()) {
|
|
414
|
+
await joinChannelRest({
|
|
415
|
+
restUrl: baseUrl,
|
|
416
|
+
agentId,
|
|
417
|
+
token,
|
|
418
|
+
channelId: ch.trim(),
|
|
419
|
+
fetchImpl: f,
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
let resolved = false;
|
|
425
|
+
const abortCtrl = new AbortController();
|
|
426
|
+
|
|
427
|
+
async function buildGroupContextPrefix(channelId: string, triggerMsgId: string, triggerTs: string): Promise<string> {
|
|
428
|
+
if (channelId.startsWith("dm-")) return "";
|
|
429
|
+
const mentionMap = loadJsonMap(mentionTsFile);
|
|
430
|
+
const mentionKey = `${agentId}:${channelId}`;
|
|
431
|
+
const lastTs = mentionMap[mentionKey] || mentionMap[channelId] || "";
|
|
432
|
+
const params = `limit=50${lastTs ? "&after=" + encodeURIComponent(lastTs) : ""}`;
|
|
433
|
+
let prefix = "";
|
|
434
|
+
try {
|
|
435
|
+
const res = await f(`${baseUrl}/api/channels/${encodeURIComponent(channelId)}/messages?${params}`, {
|
|
436
|
+
headers,
|
|
437
|
+
signal: abortCtrl.signal,
|
|
438
|
+
});
|
|
439
|
+
if (res.ok) {
|
|
440
|
+
const data = (await res.json()) as { messages?: any[] };
|
|
441
|
+
const msgs = (data.messages || []).filter(
|
|
442
|
+
(m: any) => m && m.id !== triggerMsgId && m.content !== "__typing__",
|
|
443
|
+
);
|
|
444
|
+
const trimmed = msgs.slice(-20);
|
|
445
|
+
if (trimmed.length > 0) {
|
|
446
|
+
const context = trimmed
|
|
447
|
+
.map((m: any) => `${redactParticipantPii(m.sender_id || "?")}: ${String(m.content || "").slice(0, 500)}${formatWakeAttachments(m.attachments)}`)
|
|
448
|
+
.join("\n");
|
|
449
|
+
prefix = `[频道上下文 - 最近 ${trimmed.length} 条消息]\n${context}\n\n[你被 @mention 了,请回复]\n`;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
} catch {}
|
|
453
|
+
if (triggerTs) {
|
|
454
|
+
mentionMap[mentionKey] = triggerTs;
|
|
455
|
+
mentionMap[channelId] = triggerTs;
|
|
456
|
+
saveJsonMap(mentionTsFile, mentionMap);
|
|
457
|
+
}
|
|
458
|
+
return prefix;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
async function finalizeWake(channelId: string, batch: any[]): Promise<WakeOnceEvent> {
|
|
462
|
+
const lastMsg = batch[batch.length - 1]!;
|
|
463
|
+
for (const m of batch) {
|
|
464
|
+
if (typeof m.id === "string") seenSet.add(m.id);
|
|
465
|
+
}
|
|
466
|
+
saveSeenIds(seenIdsFile, seenSet);
|
|
467
|
+
|
|
468
|
+
if (typeof lastMsg.timestamp === "string" && lastMsg.timestamp) {
|
|
469
|
+
cursor.set(channelId, lastMsg.timestamp);
|
|
470
|
+
cursor.set(CURSOR_LAST_ACTIVE_KEY, nowIso());
|
|
471
|
+
persistCursor(lastSeenFile, cursor, warn);
|
|
472
|
+
advanceChannelReadCursor({
|
|
473
|
+
configDir,
|
|
474
|
+
agentId,
|
|
475
|
+
channelId,
|
|
476
|
+
timestamp: lastMsg.timestamp,
|
|
477
|
+
warn,
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
const contextPrefix = await buildGroupContextPrefix(
|
|
482
|
+
channelId,
|
|
483
|
+
String(lastMsg.id || ""),
|
|
484
|
+
String(lastMsg.timestamp || ""),
|
|
485
|
+
);
|
|
486
|
+
const combinedContent =
|
|
487
|
+
batch.length === 1
|
|
488
|
+
? String(lastMsg.content || "")
|
|
489
|
+
: batch.map((m) => String(m.content || "")).join("\n");
|
|
490
|
+
const prompt = buildWakePrompt(
|
|
491
|
+
{
|
|
492
|
+
...lastMsg,
|
|
493
|
+
channel_id: channelId,
|
|
494
|
+
content: combinedContent,
|
|
495
|
+
},
|
|
496
|
+
contextPrefix,
|
|
497
|
+
);
|
|
498
|
+
|
|
499
|
+
return {
|
|
500
|
+
event: "agentschat_wake",
|
|
501
|
+
agent_id: agentId,
|
|
502
|
+
channel_id: channelId,
|
|
503
|
+
message_id: String(lastMsg.id || ""),
|
|
504
|
+
sender_id: String(lastMsg.sender_id || ""),
|
|
505
|
+
content: combinedContent,
|
|
506
|
+
timestamp: String(lastMsg.timestamp || ""),
|
|
507
|
+
...(batch.length > 1
|
|
508
|
+
? {
|
|
509
|
+
messages: batch.map((m) => ({
|
|
510
|
+
id: String(m.id || ""),
|
|
511
|
+
sender_id: String(m.sender_id || ""),
|
|
512
|
+
content: String(m.content || ""),
|
|
513
|
+
timestamp: String(m.timestamp || ""),
|
|
514
|
+
})),
|
|
515
|
+
}
|
|
516
|
+
: {}),
|
|
517
|
+
...(contextPrefix ? { context_prefix: contextPrefix } : {}),
|
|
518
|
+
prompt,
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
async function inspectChannelMessages(channelId: string, rawMessages: any[]): Promise<WakeOnceEvent | null> {
|
|
523
|
+
const list = Array.isArray(rawMessages)
|
|
524
|
+
? rawMessages.filter((m) => m && typeof m === "object" && m.content !== "__typing__")
|
|
525
|
+
: [];
|
|
526
|
+
list.sort((a, b) => {
|
|
527
|
+
const ta = normalizeTimestampForCursor(a.timestamp, "after") || String(a.timestamp || "");
|
|
528
|
+
const tb = normalizeTimestampForCursor(b.timestamp, "after") || String(b.timestamp || "");
|
|
529
|
+
return ta.localeCompare(tb);
|
|
530
|
+
});
|
|
531
|
+
|
|
532
|
+
const existingAfter = cursor.get(channelId);
|
|
533
|
+
if (!existingAfter) {
|
|
534
|
+
// First time seeing this channel:
|
|
535
|
+
// Any message strictly older than `__init_ts__` is pre-existing history and only seeds the cursor.
|
|
536
|
+
// Any addressed message at/after `__init_ts__` (e.g. first DM after claiming!) is live and must fire.
|
|
537
|
+
const liveBatch: any[] = [];
|
|
538
|
+
let newestPreExisting = "";
|
|
539
|
+
for (const m of list) {
|
|
540
|
+
const msgId = String(m.id || "");
|
|
541
|
+
if (msgId && seenSet.has(msgId)) continue;
|
|
542
|
+
const msgTs = String(m.timestamp || "");
|
|
543
|
+
const msgTsNorm = normalizeTimestampForCursor(msgTs, "after") || msgTs;
|
|
544
|
+
if (msgTsNorm && msgTsNorm < initTsNorm) {
|
|
545
|
+
if (msgId) seenSet.add(msgId);
|
|
546
|
+
if (msgTs > newestPreExisting) newestPreExisting = msgTs;
|
|
547
|
+
continue;
|
|
548
|
+
}
|
|
549
|
+
if (isMessageAddressedToAgent({ ...m, channel_id: channelId }, agentId, displayName)) {
|
|
550
|
+
liveBatch.push({ ...m, channel_id: channelId });
|
|
551
|
+
} else if (msgTs > newestPreExisting) {
|
|
552
|
+
newestPreExisting = msgTs;
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
if (liveBatch.length > 0) {
|
|
556
|
+
return await finalizeWake(channelId, liveBatch);
|
|
557
|
+
}
|
|
558
|
+
const seedTs = newestPreExisting || initTs;
|
|
559
|
+
cursor.set(channelId, seedTs);
|
|
560
|
+
persistCursor(lastSeenFile, cursor, warn);
|
|
561
|
+
saveSeenIds(seenIdsFile, seenSet);
|
|
562
|
+
return null;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
const afterNorm = normalizeTimestampForCursor(existingAfter, "after") || existingAfter;
|
|
566
|
+
const addressedBatch: any[] = [];
|
|
567
|
+
let latestUnaddressedTs = "";
|
|
568
|
+
|
|
569
|
+
for (const m of list) {
|
|
570
|
+
const msgId = String(m.id || "");
|
|
571
|
+
if (msgId && seenSet.has(msgId)) continue;
|
|
572
|
+
const msgTs = String(m.timestamp || "");
|
|
573
|
+
const msgTsNorm = normalizeTimestampForCursor(msgTs, "after") || msgTs;
|
|
574
|
+
if (msgTsNorm && msgTsNorm <= afterNorm) continue;
|
|
575
|
+
|
|
576
|
+
if (isMessageAddressedToAgent({ ...m, channel_id: channelId }, agentId, displayName)) {
|
|
577
|
+
addressedBatch.push({ ...m, channel_id: channelId });
|
|
578
|
+
} else if ( addressedBatch.length === 0 && msgTs ) {
|
|
579
|
+
latestUnaddressedTs = msgTs;
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
if (addressedBatch.length > 0) {
|
|
584
|
+
return await finalizeWake(channelId, addressedBatch);
|
|
585
|
+
}
|
|
586
|
+
if (latestUnaddressedTs) {
|
|
587
|
+
cursor.set(channelId, latestUnaddressedTs);
|
|
588
|
+
persistCursor(lastSeenFile, cursor, warn);
|
|
589
|
+
}
|
|
590
|
+
return null;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
const activeSseChannels = new Set<string>();
|
|
594
|
+
const sseConnectedChannels = new Set<string>();
|
|
595
|
+
const initialSyncedChannels = new Set<string>();
|
|
596
|
+
|
|
597
|
+
return await new Promise<WakeOnceEvent>((resolvePromise) => {
|
|
598
|
+
let pollTimer: ReturnType<typeof setInterval> | null = null;
|
|
599
|
+
let timeoutTimer: ReturnType<typeof setTimeout> | null = null;
|
|
600
|
+
|
|
601
|
+
const finish = (ev: WakeOnceEvent) => {
|
|
602
|
+
if (resolved) return;
|
|
603
|
+
resolved = true;
|
|
604
|
+
if (pollTimer) clearInterval(pollTimer);
|
|
605
|
+
if (timeoutTimer) clearTimeout(timeoutTimer);
|
|
606
|
+
try {
|
|
607
|
+
abortCtrl.abort();
|
|
608
|
+
} catch {}
|
|
609
|
+
resolvePromise(ev);
|
|
610
|
+
};
|
|
611
|
+
|
|
612
|
+
function maybeStartSse(channelId: string) {
|
|
613
|
+
if (!enableSse || resolved) return;
|
|
614
|
+
if (activeSseChannels.has(channelId) || activeSseChannels.size >= MAX_SSE_STREAMS) return;
|
|
615
|
+
activeSseChannels.add(channelId);
|
|
616
|
+
void (async () => {
|
|
617
|
+
while (!resolved) {
|
|
618
|
+
try {
|
|
619
|
+
const res = await f(
|
|
620
|
+
`${baseUrl}/api/channels/${encodeURIComponent(channelId)}/stream`,
|
|
621
|
+
{
|
|
622
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
623
|
+
signal: abortCtrl.signal,
|
|
624
|
+
},
|
|
625
|
+
);
|
|
626
|
+
if (!res.ok || !res.body) break;
|
|
627
|
+
sseConnectedChannels.add(channelId);
|
|
628
|
+
const reader = res.body.getReader();
|
|
629
|
+
const decoder = new TextDecoder();
|
|
630
|
+
let buf = "";
|
|
631
|
+
while (!resolved) {
|
|
632
|
+
const { value, done } = await reader.read();
|
|
633
|
+
if (done) break;
|
|
634
|
+
buf += decoder.decode(value, { stream: true });
|
|
635
|
+
const lines = buf.split(/\r?\n/);
|
|
636
|
+
buf = lines.pop() || "";
|
|
637
|
+
for (const line of lines) {
|
|
638
|
+
if (!line.startsWith("data:")) continue;
|
|
639
|
+
const raw = line.slice(5).trim();
|
|
640
|
+
if (!raw) continue;
|
|
641
|
+
try {
|
|
642
|
+
const parsed = JSON.parse(raw);
|
|
643
|
+
const wakeEv = await inspectChannelMessages(channelId, [parsed]);
|
|
644
|
+
if (wakeEv) {
|
|
645
|
+
finish(wakeEv);
|
|
646
|
+
return;
|
|
647
|
+
}
|
|
648
|
+
} catch {}
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
} catch {
|
|
652
|
+
sseConnectedChannels.delete(channelId);
|
|
653
|
+
if (resolved) return;
|
|
654
|
+
await new Promise((r) => setTimeout(r, 2000));
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
sseConnectedChannels.delete(channelId);
|
|
658
|
+
activeSseChannels.delete(channelId);
|
|
659
|
+
})();
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
let polling = false;
|
|
663
|
+
async function pollOnce() {
|
|
664
|
+
if (resolved || polling) return;
|
|
665
|
+
polling = true;
|
|
666
|
+
try {
|
|
667
|
+
const mineRes = await f(`${baseUrl}/api/channels/mine`, {
|
|
668
|
+
headers,
|
|
669
|
+
signal: abortCtrl.signal,
|
|
670
|
+
});
|
|
671
|
+
const channelList: Array<{ id: string; last_message_at?: string }> = [];
|
|
672
|
+
const seenCh = new Set<string>();
|
|
673
|
+
if (mineRes.ok) {
|
|
674
|
+
const mineData = (await mineRes.json()) as { channels?: any[] };
|
|
675
|
+
for (const ch of mineData.channels || []) {
|
|
676
|
+
if (ch && typeof ch.id === "string" && !seenCh.has(ch.id)) {
|
|
677
|
+
seenCh.add(ch.id);
|
|
678
|
+
channelList.push({ id: ch.id, last_message_at: ch.last_message_at });
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
for (const extra of opts.channels ?? []) {
|
|
683
|
+
if (extra && !seenCh.has(extra)) {
|
|
684
|
+
seenCh.add(extra);
|
|
685
|
+
channelList.push({ id: extra });
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
// Prioritize DMs first for SSE slots, then explicit channels
|
|
690
|
+
const sortedForSse = [...channelList].sort((a, b) => {
|
|
691
|
+
const aDm = a.id.startsWith("dm-") ? 0 : 1;
|
|
692
|
+
const bDm = b.id.startsWith("dm-") ? 0 : 1;
|
|
693
|
+
return aDm - bDm;
|
|
694
|
+
});
|
|
695
|
+
for (const ch of sortedForSse) {
|
|
696
|
+
maybeStartSse(ch.id);
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
for (const ch of channelList) {
|
|
700
|
+
if (resolved) return;
|
|
701
|
+
// Once a channel has completed its initial catch-up check and has an active SSE stream,
|
|
702
|
+
// rely on the SSE listener rather than polling /messages.
|
|
703
|
+
if (initialSyncedChannels.has(ch.id) && sseConnectedChannels.has(ch.id)) {
|
|
704
|
+
continue;
|
|
705
|
+
}
|
|
706
|
+
const existingAfter = cursor.get(ch.id);
|
|
707
|
+
if (existingAfter && ch.last_message_at && initialSyncedChannels.has(ch.id)) {
|
|
708
|
+
const lastAtNorm = normalizeTimestampForCursor(ch.last_message_at, "after") || ch.last_message_at;
|
|
709
|
+
const afterNorm = normalizeTimestampForCursor(existingAfter, "after") || existingAfter;
|
|
710
|
+
if (lastAtNorm <= afterNorm) continue;
|
|
711
|
+
}
|
|
712
|
+
const qs = existingAfter
|
|
713
|
+
? `?after=${encodeURIComponent(existingAfter)}&limit=50`
|
|
714
|
+
: `?limit=20`;
|
|
715
|
+
const msgRes = await f(
|
|
716
|
+
`${baseUrl}/api/channels/${encodeURIComponent(ch.id)}/messages${qs}`,
|
|
717
|
+
{ headers, signal: abortCtrl.signal },
|
|
718
|
+
);
|
|
719
|
+
if (!msgRes.ok) continue;
|
|
720
|
+
initialSyncedChannels.add(ch.id);
|
|
721
|
+
const msgData = (await msgRes.json()) as { messages?: any[] };
|
|
722
|
+
const wakeEv = await inspectChannelMessages(ch.id, msgData.messages || []);
|
|
723
|
+
if (wakeEv) {
|
|
724
|
+
finish(wakeEv);
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
} catch {
|
|
729
|
+
// Ignore transient network errors during poll
|
|
730
|
+
} finally {
|
|
731
|
+
polling = false;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
if (timeoutMs > 0) {
|
|
736
|
+
timeoutTimer = setTimeout(() => {
|
|
737
|
+
const lastActiveIso = cursor.get(CURSOR_LAST_ACTIVE_KEY) || initTs;
|
|
738
|
+
const nowMs = Date.parse(nowIso());
|
|
739
|
+
const lastActiveMs = Date.parse(lastActiveIso);
|
|
740
|
+
const elapsedMs =
|
|
741
|
+
Number.isFinite(nowMs) && Number.isFinite(lastActiveMs)
|
|
742
|
+
? Math.max(timeoutMs, nowMs - lastActiveMs)
|
|
743
|
+
: timeoutMs;
|
|
744
|
+
if (maxIdleMs > 0 && elapsedMs >= maxIdleMs) {
|
|
745
|
+
cursor.delete(CURSOR_LAST_ACTIVE_KEY);
|
|
746
|
+
persistCursor(lastSeenFile, cursor, warn);
|
|
747
|
+
finish({
|
|
748
|
+
event: "hibernate",
|
|
749
|
+
agent_id: agentId,
|
|
750
|
+
timeout_ms: timeoutMs,
|
|
751
|
+
idle_ms: elapsedMs,
|
|
752
|
+
max_idle_ms: maxIdleMs,
|
|
753
|
+
should_rearm: false,
|
|
754
|
+
prompt: `[AgentsChat] 连续 ${Math.round(maxIdleMs / 60000)} 分钟无新消息,已自动停止后台续期以节省 Token。下次在网页端发送任意消息即可重新唤醒监听。`,
|
|
755
|
+
});
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
finish({
|
|
759
|
+
event: "idle_timeout",
|
|
760
|
+
agent_id: agentId,
|
|
761
|
+
timeout_ms: timeoutMs,
|
|
762
|
+
idle_ms: elapsedMs,
|
|
763
|
+
max_idle_ms: maxIdleMs,
|
|
764
|
+
should_rearm: true,
|
|
765
|
+
});
|
|
766
|
+
}, timeoutMs);
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
pollTimer = setInterval(() => {
|
|
770
|
+
void pollOnce();
|
|
771
|
+
}, pollIntervalMs);
|
|
772
|
+
void pollOnce();
|
|
773
|
+
});
|
|
774
|
+
}
|