@agent-team-foundation/first-tree-hub 0.14.1 → 0.14.3
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/dist/{bootstrap-C15ZBOCC.mjs → bootstrap-CQQGgIx1.mjs} +0 -7
- package/dist/cli/index.mjs +14 -39
- package/dist/{client-CzXmweS9-DhUiuQvL.mjs → client-BSfCc0pJ-BP_1f21y.mjs} +3095 -1291
- package/dist/{client-CREn8bJ0-C5fHJir6.mjs → client-q1EYQD1n-ypjoumIO.mjs} +3 -3
- package/dist/{dist-1XGLJMOq.mjs → dist-CwsiHGX7.mjs} +51 -19
- package/dist/{feishu-BGx71p5s.mjs → feishu-DHSy6WDD.mjs} +1 -1
- package/dist/index.mjs +7 -7
- package/dist/invitation-C9m2gQx4-BSErdb8x.mjs +4 -0
- package/dist/{invitation-DZO4NX3P-BPxTeHf-.mjs → invitation-D_ENPHyj-5ETiae5r.mjs} +3 -23
- package/dist/{saas-connect-BBRxjmBS.mjs → saas-connect-ChxZv2YQ.mjs} +621 -2078
- package/dist/{errors-LPcARA4K-Dbrptiyz.mjs → uuid-DbS_4vFh-iFghv4zA.mjs} +37 -2
- package/dist/web/assets/{index-DMqnX4IR.js → index-B76SVAz8.js} +1 -1
- package/dist/web/assets/index-DAAemCLz.js +416 -0
- package/dist/web/assets/index-DE7Q3QWE.css +1 -0
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/invitation-CNv7gfFF-DOFZ75wb.mjs +0 -4
- package/dist/web/assets/index-BOK7e_td.css +0 -1
- package/dist/web/assets/index-QDcpYpEa.js +0 -416
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { O as withSpan, f as messageAttrs, s as createLogger } from "./observability-BAScT_5S-BcW9HgkG.mjs";
|
|
2
|
-
import { L as extractMentions, N as defaultParticipantMode, S as clientCapabilitiesSchema, b as agentTypeSchema, ct as questionAnswerMessageContentSchema, i as AGENT_STATUSES, lt as questionMessageContentSchema, mt as scanMentionTokens, o as AGENT_VISIBILITY, s as CHAT_ENGAGEMENT_STATUSES } from "./dist-
|
|
3
|
-
import { a as
|
|
1
|
+
import { A as FIRST_TREE_HUB_ATTR, O as withSpan, f as messageAttrs, s as createLogger } from "./observability-BAScT_5S-BcW9HgkG.mjs";
|
|
2
|
+
import { L as extractMentions, N as defaultParticipantMode, P as defaultRuntimeConfigPayload, S as clientCapabilitiesSchema, St as stripCode, Z as isReservedAgentName, a as AGENT_TYPES, b as agentTypeSchema, ct as questionAnswerMessageContentSchema, d as MENTION_REGEX, i as AGENT_STATUSES, l as GITHUB_ENTITY_TYPES, lt as questionMessageContentSchema, mt as scanMentionTokens, n as AGENT_NAME_REGEX, nt as messageSourceSchema, o as AGENT_VISIBILITY, s as CHAT_ENGAGEMENT_STATUSES } from "./dist-CwsiHGX7.mjs";
|
|
3
|
+
import { a as ClientUserMismatchError, c as NotFoundError, d as users, f as uuidv7, o as ConflictError, r as BadRequestError, s as ForbiddenError, t as AgentSendNonMemberError, u as organizations } from "./uuid-DbS_4vFh-iFghv4zA.mjs";
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
|
-
import { and, desc, eq, inArray, isNotNull, lt, ne, or, sql } from "drizzle-orm";
|
|
6
|
-
import { bigserial, boolean, customType, index, integer, jsonb, pgTable, primaryKey, text, timestamp, unique } from "drizzle-orm/pg-core";
|
|
7
|
-
//#region ../server/dist/client-
|
|
5
|
+
import { and, asc, count, desc, eq, gt, gte, inArray, isNotNull, lt, ne, or, sql } from "drizzle-orm";
|
|
6
|
+
import { bigserial, boolean, customType, index, integer, jsonb, pgTable, primaryKey, serial, text, timestamp, unique } from "drizzle-orm/pg-core";
|
|
7
|
+
//#region ../server/dist/client-BSfCc0pJ.mjs
|
|
8
8
|
/**
|
|
9
9
|
* Client connections. A client is a single SDK process (AgentRuntime) that may
|
|
10
10
|
* host multiple agents. From the unified-user-token milestone on, a client is
|
|
@@ -69,6 +69,17 @@ const agents = pgTable("agents", {
|
|
|
69
69
|
index("idx_agents_client").on(table.clientId),
|
|
70
70
|
unique("uq_agents_org_name").on(table.organizationId, table.name)
|
|
71
71
|
]);
|
|
72
|
+
/** Maps external user identities to internal Agents. */
|
|
73
|
+
const adapterAgentMappings = pgTable("adapter_agent_mappings", {
|
|
74
|
+
id: serial("id").primaryKey(),
|
|
75
|
+
platform: text("platform").notNull(),
|
|
76
|
+
externalUserId: text("external_user_id").notNull(),
|
|
77
|
+
agentId: text("agent_id").notNull().references(() => agents.uuid),
|
|
78
|
+
boundVia: text("bound_via"),
|
|
79
|
+
displayName: text("display_name"),
|
|
80
|
+
metadata: jsonb("metadata").$type().notNull().default({}),
|
|
81
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
|
|
82
|
+
}, (table) => [unique("uq_adapter_agent_mapping").on(table.platform, table.externalUserId)]);
|
|
72
83
|
/**
|
|
73
84
|
* Unified membership table. Replaces the two-table split
|
|
74
85
|
* (chat_participants speakers ∪ chat_subscriptions watchers) — both
|
|
@@ -130,6 +141,30 @@ const members = pgTable("members", {
|
|
|
130
141
|
index("idx_members_user").on(table.userId),
|
|
131
142
|
index("idx_members_org").on(table.organizationId)
|
|
132
143
|
]);
|
|
144
|
+
/** Bot credentials for external platform adapters. Credentials are encrypted at application layer (AES-256-GCM). */
|
|
145
|
+
const adapterConfigs = pgTable("adapter_configs", {
|
|
146
|
+
id: serial("id").primaryKey(),
|
|
147
|
+
platform: text("platform").notNull(),
|
|
148
|
+
agentId: text("agent_id").notNull().references(() => agents.uuid),
|
|
149
|
+
credentials: jsonb("credentials").$type().notNull(),
|
|
150
|
+
status: text("status").notNull().default("active"),
|
|
151
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
|
152
|
+
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
|
|
153
|
+
}, (t) => [unique("uq_adapter_configs_agent_platform").on(t.agentId, t.platform)]);
|
|
154
|
+
/** Messages. Immutable after creation. Each message belongs to exactly one Chat. */
|
|
155
|
+
const messages = pgTable("messages", {
|
|
156
|
+
id: text("id").primaryKey(),
|
|
157
|
+
chatId: text("chat_id").notNull().references(() => chats.id),
|
|
158
|
+
senderId: text("sender_id").notNull(),
|
|
159
|
+
format: text("format").notNull(),
|
|
160
|
+
content: jsonb("content").$type().notNull(),
|
|
161
|
+
metadata: jsonb("metadata").$type().notNull().default({}),
|
|
162
|
+
replyToInbox: text("reply_to_inbox"),
|
|
163
|
+
replyToChat: text("reply_to_chat"),
|
|
164
|
+
inReplyTo: text("in_reply_to"),
|
|
165
|
+
source: text("source"),
|
|
166
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
|
|
167
|
+
}, (table) => [index("idx_messages_chat_time").on(table.chatId, table.createdAt), index("idx_messages_in_reply_to").on(table.inReplyTo)]);
|
|
133
168
|
/**
|
|
134
169
|
* Process-local cache for the per-chat realtime push audience
|
|
135
170
|
* (every row in `chat_membership` for the chat — speakers + watchers,
|
|
@@ -193,6 +228,552 @@ async function getCachedAudience(db, chatId) {
|
|
|
193
228
|
function invalidateChatAudience(chatId) {
|
|
194
229
|
cache.delete(chatId);
|
|
195
230
|
}
|
|
231
|
+
/** Delivery queue (envelope). One entry per recipient created during message fan-out. Uses SKIP LOCKED for concurrent-safe consumption. */
|
|
232
|
+
const inboxEntries = pgTable("inbox_entries", {
|
|
233
|
+
id: bigserial("id", { mode: "number" }).primaryKey(),
|
|
234
|
+
inboxId: text("inbox_id").notNull(),
|
|
235
|
+
messageId: text("message_id").notNull().references(() => messages.id),
|
|
236
|
+
chatId: text("chat_id"),
|
|
237
|
+
status: text("status").notNull().default("pending"),
|
|
238
|
+
notify: boolean("notify").notNull().default(true),
|
|
239
|
+
retryCount: integer("retry_count").notNull().default(0),
|
|
240
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
|
241
|
+
deliveredAt: timestamp("delivered_at", { withTimezone: true }),
|
|
242
|
+
ackedAt: timestamp("acked_at", { withTimezone: true })
|
|
243
|
+
}, (table) => [
|
|
244
|
+
unique("uq_inbox_delivery").on(table.inboxId, table.messageId, table.chatId),
|
|
245
|
+
index("idx_inbox_pending").on(table.inboxId, table.createdAt),
|
|
246
|
+
index("idx_inbox_pending_notify").on(table.inboxId, table.createdAt).where(sql`status = 'pending' AND notify = true`),
|
|
247
|
+
index("idx_inbox_chat_silent").on(table.inboxId, table.chatId, table.notify, table.status)
|
|
248
|
+
]);
|
|
249
|
+
/**
|
|
250
|
+
* Per-agent runtime configuration (Hub-managed; not the local YAML config).
|
|
251
|
+
*
|
|
252
|
+
* One row per agent. `version` increments on every successful UPDATE
|
|
253
|
+
* (optimistic locking via WHERE version = :expected). Sensitive env values
|
|
254
|
+
* inside `payload.env[*]` are AES-256-GCM encrypted at write time and
|
|
255
|
+
* masked when echoed via the Admin API (see Step 2).
|
|
256
|
+
*
|
|
257
|
+
* Integrity is enforced by the service layer per project convention:
|
|
258
|
+
* no FK / CHECK / triggers on this table.
|
|
259
|
+
*/
|
|
260
|
+
const agentConfigs = pgTable("agent_configs", {
|
|
261
|
+
agentId: text("agent_id").primaryKey(),
|
|
262
|
+
version: integer("version").notNull().default(1),
|
|
263
|
+
payload: jsonb("payload").$type().notNull(),
|
|
264
|
+
updatedBy: text("updated_by").notNull(),
|
|
265
|
+
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
|
|
266
|
+
});
|
|
267
|
+
function normaliseSource(source) {
|
|
268
|
+
if (source === null) return null;
|
|
269
|
+
const parsed = messageSourceSchema.safeParse(source);
|
|
270
|
+
return parsed.success ? parsed.data : null;
|
|
271
|
+
}
|
|
272
|
+
function normaliseMode(mode) {
|
|
273
|
+
return mode === "mention_only" ? "mention_only" : "full";
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Batch variant — builds all payloads with a single DB lookup per agent plus
|
|
277
|
+
* batched lookups for participant modes and inReplyTo snapshots.
|
|
278
|
+
*/
|
|
279
|
+
async function buildClientMessagePayloadsForInbox(db, inboxId, items) {
|
|
280
|
+
if (items.length === 0) return [];
|
|
281
|
+
const agentId = await resolveAgentId(db, {
|
|
282
|
+
kind: "inboxId",
|
|
283
|
+
inboxId
|
|
284
|
+
});
|
|
285
|
+
const [cfg] = await db.select({ version: agentConfigs.version }).from(agentConfigs).where(eq(agentConfigs.agentId, agentId)).limit(1);
|
|
286
|
+
const version = cfg?.version ?? 1;
|
|
287
|
+
const chatIds = [...new Set(items.map((it) => it.entryChatId ?? it.message.chatId).filter((id) => id !== null))];
|
|
288
|
+
const modeByChat = /* @__PURE__ */ new Map();
|
|
289
|
+
if (chatIds.length > 0) {
|
|
290
|
+
const rows = await db.select({
|
|
291
|
+
chatId: chatMembership.chatId,
|
|
292
|
+
mode: chatMembership.mode
|
|
293
|
+
}).from(chatMembership).where(and(eq(chatMembership.agentId, agentId), inArray(chatMembership.chatId, chatIds), eq(chatMembership.accessMode, "speaker")));
|
|
294
|
+
for (const r of rows) modeByChat.set(r.chatId, normaliseMode(r.mode));
|
|
295
|
+
}
|
|
296
|
+
const inReplyToIds = [...new Set(items.map((it) => it.message.inReplyTo).filter((id) => id !== null))];
|
|
297
|
+
const snapshotById = /* @__PURE__ */ new Map();
|
|
298
|
+
if (inReplyToIds.length > 0) {
|
|
299
|
+
const origs = await db.select({
|
|
300
|
+
id: messages.id,
|
|
301
|
+
senderId: messages.senderId,
|
|
302
|
+
chatId: messages.chatId,
|
|
303
|
+
replyToChat: messages.replyToChat
|
|
304
|
+
}).from(messages).where(inArray(messages.id, inReplyToIds));
|
|
305
|
+
for (const o of origs) snapshotById.set(o.id, {
|
|
306
|
+
senderId: o.senderId,
|
|
307
|
+
chatId: o.chatId,
|
|
308
|
+
replyToChat: o.replyToChat
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
return items.map(({ entryChatId, message: m, precedingMessages = [] }) => ({
|
|
312
|
+
id: m.id,
|
|
313
|
+
chatId: m.chatId,
|
|
314
|
+
senderId: m.senderId,
|
|
315
|
+
format: m.format,
|
|
316
|
+
content: m.content,
|
|
317
|
+
metadata: m.metadata,
|
|
318
|
+
replyToInbox: m.replyToInbox,
|
|
319
|
+
replyToChat: m.replyToChat,
|
|
320
|
+
inReplyTo: m.inReplyTo,
|
|
321
|
+
source: normaliseSource(m.source),
|
|
322
|
+
createdAt: m.createdAt,
|
|
323
|
+
configVersion: version,
|
|
324
|
+
recipientMode: modeByChat.get(entryChatId ?? m.chatId) ?? "full",
|
|
325
|
+
inReplyToSnapshot: m.inReplyTo ? snapshotById.get(m.inReplyTo) ?? null : null,
|
|
326
|
+
precedingMessages
|
|
327
|
+
}));
|
|
328
|
+
}
|
|
329
|
+
async function resolveAgentId(db, source) {
|
|
330
|
+
if (source.kind === "agentId") return source.agentId;
|
|
331
|
+
const [agent] = await db.select({ uuid: agents.uuid }).from(agents).where(eq(agents.inboxId, source.inboxId)).limit(1);
|
|
332
|
+
if (!agent) throw new Error(`No agent owns inbox "${source.inboxId}"`);
|
|
333
|
+
return agent.uuid;
|
|
334
|
+
}
|
|
335
|
+
const DEFAULT_INBOX_TIMEOUT_SECONDS = 300;
|
|
336
|
+
const DEFAULT_MAX_RETRY_COUNT = 3;
|
|
337
|
+
const PRECEDING_CONTEXT_WINDOW_SECONDS = 1440 * 60;
|
|
338
|
+
/**
|
|
339
|
+
* Backfill the most recent `PRECEDING_CONTEXT_MAX_ENTRIES` messages of `chatId`
|
|
340
|
+
* as silent (notify=false) inbox rows for every new participant. Called from
|
|
341
|
+
* `addParticipant()` inside the participant-insert transaction so a freshly
|
|
342
|
+
* added member already has prior chat history available the first time they
|
|
343
|
+
* are woken (mentioned / `chat send`-ed).
|
|
344
|
+
*
|
|
345
|
+
* Invariants the implementation upholds:
|
|
346
|
+
*
|
|
347
|
+
* - **`notify=false` everywhere**: adding a participant is not itself a
|
|
348
|
+
* wake event. The new participant only runs the LLM when an actual
|
|
349
|
+
* trigger lands later; the backfill rows then piggy-back as preceding
|
|
350
|
+
* context (see `collectPrecedingContext`).
|
|
351
|
+
* - **Old members are not woken**: only inbox rows for the brand-new
|
|
352
|
+
* participants are written.
|
|
353
|
+
* - **Transaction-scoped**: writes go through the caller's `tx`, so a
|
|
354
|
+
* rollback of `addParticipant` rolls the backfill back too.
|
|
355
|
+
* - **Quiet on chats with no prior history**: a chat with zero messages
|
|
356
|
+
* produces zero backfill rows; no error, no INSERT.
|
|
357
|
+
* - **Idempotent**: collides cleanly on the
|
|
358
|
+
* `(inbox_id, message_id, chat_id)` unique key via
|
|
359
|
+
* `ON CONFLICT DO NOTHING`. This matters when a watcher → speaker
|
|
360
|
+
* promotion already had inbox rows for some of these messages.
|
|
361
|
+
*
|
|
362
|
+
* Pure data write — no PG NOTIFY, no participant-mode logic, no watcher
|
|
363
|
+
* recompute. Callers stay responsible for those.
|
|
364
|
+
*
|
|
365
|
+
* **Caller responsibility — bulk batching**: writes a single
|
|
366
|
+
* `INSERT VALUES (...)` of `newParticipants.length * PRECEDING_CONTEXT_MAX_ENTRIES`
|
|
367
|
+
* tuples. v1's only caller (`addParticipant`) always passes 1 participant
|
|
368
|
+
* (≤ 50 rows). Future bulk-add paths (sub-chat / spawn / etc.) should split
|
|
369
|
+
* input into chunks (suggested: ≤ 512 rows per call) before passing here.
|
|
370
|
+
*
|
|
371
|
+
* See proposals/hub-chat-message-v1-design §四 改造 2.
|
|
372
|
+
*/
|
|
373
|
+
async function backfillSilentContextForNewParticipants(tx, chatId, newParticipants) {
|
|
374
|
+
if (newParticipants.length === 0) return;
|
|
375
|
+
const recent = await tx.select({ id: messages.id }).from(messages).where(eq(messages.chatId, chatId)).orderBy(desc(messages.createdAt)).limit(50);
|
|
376
|
+
if (recent.length === 0) return;
|
|
377
|
+
const rows = [];
|
|
378
|
+
for (const p of newParticipants) for (const m of recent) rows.push({
|
|
379
|
+
inboxId: p.inboxId,
|
|
380
|
+
messageId: m.id,
|
|
381
|
+
chatId,
|
|
382
|
+
notify: false
|
|
383
|
+
});
|
|
384
|
+
await tx.insert(inboxEntries).values(rows).onConflictDoNothing();
|
|
385
|
+
}
|
|
386
|
+
async function pollInbox(db, inboxId, limit) {
|
|
387
|
+
return withSpan("inbox.deliver", {
|
|
388
|
+
"inbox.id": inboxId,
|
|
389
|
+
"inbox.poll.limit": limit
|
|
390
|
+
}, () => pollInboxInner(db, inboxId, limit));
|
|
391
|
+
}
|
|
392
|
+
async function pollInboxInner(db, inboxId, limit) {
|
|
393
|
+
return db.transaction(async (tx) => {
|
|
394
|
+
const targetIds = tx.select({ id: inboxEntries.id }).from(inboxEntries).where(and(eq(inboxEntries.inboxId, inboxId), eq(inboxEntries.status, "pending"), eq(inboxEntries.notify, true))).orderBy(asc(inboxEntries.createdAt)).limit(limit).for("update", { skipLocked: true });
|
|
395
|
+
return bundleDeliveryWithSilentContext(tx, inboxId, await tx.update(inboxEntries).set({
|
|
396
|
+
status: "delivered",
|
|
397
|
+
deliveredAt: /* @__PURE__ */ new Date()
|
|
398
|
+
}).where(inArray(inboxEntries.id, targetIds)).returning());
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Shared payload assembler for already-claimed `inbox_entries` rows.
|
|
403
|
+
*
|
|
404
|
+
* Both the debug `GET /inbox` path (`pollInbox`) and the WS push path
|
|
405
|
+
* (`claimAndBuildForPush`) call this with rows they have just `UPDATE`d to
|
|
406
|
+
* `status='delivered'`. Keeping the silent-context bundling in one place is
|
|
407
|
+
* the only way to keep the two paths from drifting (proposal
|
|
408
|
+
* hub-inbox-ws-data-plane §3.2 risk #1).
|
|
409
|
+
*
|
|
410
|
+
* Steps:
|
|
411
|
+
* 1. Sort by `createdAt` ASC (PG `RETURNING` does not guarantee order).
|
|
412
|
+
* 2. For each trigger, collect silent context & bulk-ack stale silent rows.
|
|
413
|
+
* 3. Fetch the trigger messages.
|
|
414
|
+
* 4. Build wire payloads via the single dispatcher.
|
|
415
|
+
*
|
|
416
|
+
* Returns `[]` if `claimed` is empty.
|
|
417
|
+
*/
|
|
418
|
+
async function bundleDeliveryWithSilentContext(tx, inboxId, claimed) {
|
|
419
|
+
if (claimed.length === 0) return [];
|
|
420
|
+
claimed.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
|
|
421
|
+
const precedingByEntryId = await collectPrecedingContext(tx, inboxId, claimed);
|
|
422
|
+
const messageIds = claimed.map((e) => e.messageId);
|
|
423
|
+
const msgs = await tx.select().from(messages).where(inArray(messages.id, messageIds));
|
|
424
|
+
const msgMap = new Map(msgs.map((m) => [m.id, m]));
|
|
425
|
+
const payloads = await buildClientMessagePayloadsForInbox(tx, inboxId, claimed.map((entry) => {
|
|
426
|
+
const msg = msgMap.get(entry.messageId);
|
|
427
|
+
if (!msg) throw new Error(`Unexpected: message ${entry.messageId} not found`);
|
|
428
|
+
return {
|
|
429
|
+
entryChatId: entry.chatId,
|
|
430
|
+
precedingMessages: precedingByEntryId.get(entry.id) ?? [],
|
|
431
|
+
message: {
|
|
432
|
+
id: msg.id,
|
|
433
|
+
chatId: msg.chatId,
|
|
434
|
+
senderId: msg.senderId,
|
|
435
|
+
format: msg.format,
|
|
436
|
+
content: msg.content,
|
|
437
|
+
metadata: msg.metadata,
|
|
438
|
+
replyToInbox: msg.replyToInbox,
|
|
439
|
+
replyToChat: msg.replyToChat,
|
|
440
|
+
inReplyTo: msg.inReplyTo,
|
|
441
|
+
source: msg.source,
|
|
442
|
+
createdAt: msg.createdAt.toISOString()
|
|
443
|
+
}
|
|
444
|
+
};
|
|
445
|
+
}));
|
|
446
|
+
return claimed.map((entry, idx) => {
|
|
447
|
+
const payload = payloads[idx];
|
|
448
|
+
if (!payload) throw new Error(`Unexpected: payload for entry ${entry.id} not built`);
|
|
449
|
+
return {
|
|
450
|
+
id: entry.id,
|
|
451
|
+
inboxId: entry.inboxId,
|
|
452
|
+
messageId: entry.messageId,
|
|
453
|
+
chatId: entry.chatId,
|
|
454
|
+
status: entry.status,
|
|
455
|
+
retryCount: entry.retryCount,
|
|
456
|
+
createdAt: entry.createdAt.toISOString(),
|
|
457
|
+
deliveredAt: entry.deliveredAt?.toISOString() ?? null,
|
|
458
|
+
ackedAt: entry.ackedAt?.toISOString() ?? null,
|
|
459
|
+
message: payload
|
|
460
|
+
};
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Realistic upper bound on rows a single NOTIFY references. The unique
|
|
465
|
+
* constraint `(inbox_id, message_id, chat_id)` caps a `(inbox, message)`
|
|
466
|
+
* pair at one row per chatId; the only way to exceed 1 today is the replyTo
|
|
467
|
+
* cross-chat path (`message.ts` writes a second row keyed by the original's
|
|
468
|
+
* `replyToChat`). 8 leaves headroom for any future fan-out variant without
|
|
469
|
+
* requiring a schema change here.
|
|
470
|
+
*/
|
|
471
|
+
const PUSH_CLAIM_BATCH_LIMIT = 8;
|
|
472
|
+
/**
|
|
473
|
+
* WS-push path: atomically claim every pending entry the just-fired
|
|
474
|
+
* `NOTIFY (inboxId:messageId)` references and assemble their wire payloads.
|
|
475
|
+
*
|
|
476
|
+
* Returns `[]` if no row matches — benign race with another server instance
|
|
477
|
+
* (or the debug `GET /inbox` endpoint) that already claimed the entry.
|
|
478
|
+
* NOTIFY is fire-and-forget (proposal §3.2).
|
|
479
|
+
*
|
|
480
|
+
* Why an array, not a single row: `sendMessage` can write **two** rows for
|
|
481
|
+
* the same `(inbox, messageId)` pair when the recipient is both a chat
|
|
482
|
+
* participant and the `replyToInbox` of an earlier message — the unique key
|
|
483
|
+
* is `(inbox_id, message_id, chat_id)`, so the rows differ by chatId. The
|
|
484
|
+
* old `LIMIT 1` shape would only push the first; the second sat `pending`
|
|
485
|
+
* until reconnect. Aligning with `pollInboxInner`'s `LIMIT N` shape closes
|
|
486
|
+
* that gap and keeps push/poll behaviour interchangeable.
|
|
487
|
+
*/
|
|
488
|
+
async function claimAndBuildForPush(db, inboxId, messageId) {
|
|
489
|
+
return withSpan("inbox.deliver.push", {
|
|
490
|
+
"inbox.id": inboxId,
|
|
491
|
+
"message.id": messageId
|
|
492
|
+
}, () => db.transaction(async (tx) => {
|
|
493
|
+
const targetIds = tx.select({ id: inboxEntries.id }).from(inboxEntries).where(and(eq(inboxEntries.inboxId, inboxId), eq(inboxEntries.messageId, messageId), eq(inboxEntries.status, "pending"), eq(inboxEntries.notify, true))).orderBy(asc(inboxEntries.createdAt)).limit(PUSH_CLAIM_BATCH_LIMIT).for("update", { skipLocked: true });
|
|
494
|
+
return bundleDeliveryWithSilentContext(tx, inboxId, await tx.update(inboxEntries).set({
|
|
495
|
+
status: "delivered",
|
|
496
|
+
deliveredAt: /* @__PURE__ */ new Date()
|
|
497
|
+
}).where(inArray(inboxEntries.id, targetIds)).returning());
|
|
498
|
+
}));
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* WS-push backlog path: on agent rebind (or once an in-flight slot frees up
|
|
502
|
+
* after an ack), drain up to `limit` pending `notify=true` entries oldest-
|
|
503
|
+
* first and assemble wire payloads. Identical claim shape to `pollInbox` —
|
|
504
|
+
* they are intentionally interchangeable so a hot-path bug fixed in one
|
|
505
|
+
* shows up in the other (proposal §3.3 / §3.5).
|
|
506
|
+
*/
|
|
507
|
+
async function claimBacklogForPush(db, inboxId, limit) {
|
|
508
|
+
return withSpan("inbox.deliver.backlog", {
|
|
509
|
+
"inbox.id": inboxId,
|
|
510
|
+
"inbox.backlog.limit": limit
|
|
511
|
+
}, () => pollInboxInner(db, inboxId, limit));
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Per claimed trigger: SELECT silent (notify=false) pending rows in the same
|
|
515
|
+
* chat that occurred between the previous trigger in this batch (or beginning
|
|
516
|
+
* of time) and this trigger, capped by `PRECEDING_CONTEXT_MAX_ENTRIES` and
|
|
517
|
+
* `PRECEDING_CONTEXT_WINDOW_SECONDS`. Returned messages are oldest-first.
|
|
518
|
+
*
|
|
519
|
+
* Side effect: bulk-ack ALL silent pending rows in each chat with
|
|
520
|
+
* createdAt < latest_trigger.createdAt — including ones that fell outside
|
|
521
|
+
* the window/cap. Otherwise stale silent rows would accumulate and re-load
|
|
522
|
+
* on every poll.
|
|
523
|
+
*/
|
|
524
|
+
async function collectPrecedingContext(tx, inboxId, triggers) {
|
|
525
|
+
const result = /* @__PURE__ */ new Map();
|
|
526
|
+
const byChat = /* @__PURE__ */ new Map();
|
|
527
|
+
for (const t of triggers) {
|
|
528
|
+
if (t.chatId === null) continue;
|
|
529
|
+
const list = byChat.get(t.chatId) ?? [];
|
|
530
|
+
list.push(t);
|
|
531
|
+
byChat.set(t.chatId, list);
|
|
532
|
+
}
|
|
533
|
+
for (const [chatId, chatTriggers] of byChat) {
|
|
534
|
+
chatTriggers.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
|
|
535
|
+
let prevCreatedAt = null;
|
|
536
|
+
for (const trigger of chatTriggers) {
|
|
537
|
+
const preceding = (await tx.select({
|
|
538
|
+
messageId: messages.id,
|
|
539
|
+
senderId: messages.senderId,
|
|
540
|
+
format: messages.format,
|
|
541
|
+
content: messages.content,
|
|
542
|
+
metadata: messages.metadata,
|
|
543
|
+
createdAt: messages.createdAt
|
|
544
|
+
}).from(inboxEntries).innerJoin(messages, eq(messages.id, inboxEntries.messageId)).where(and(eq(inboxEntries.inboxId, inboxId), eq(inboxEntries.chatId, chatId), eq(inboxEntries.status, "pending"), eq(inboxEntries.notify, false), lt(inboxEntries.createdAt, trigger.createdAt), prevCreatedAt === null ? void 0 : gt(inboxEntries.createdAt, prevCreatedAt), sql`${inboxEntries.createdAt} > NOW() - make_interval(secs => ${PRECEDING_CONTEXT_WINDOW_SECONDS})`)).orderBy(desc(messages.createdAt)).limit(50).for("update", {
|
|
545
|
+
of: inboxEntries,
|
|
546
|
+
skipLocked: true
|
|
547
|
+
})).map((r) => ({
|
|
548
|
+
id: r.messageId,
|
|
549
|
+
senderId: r.senderId,
|
|
550
|
+
format: r.format,
|
|
551
|
+
content: r.content,
|
|
552
|
+
metadata: r.metadata ?? {},
|
|
553
|
+
createdAt: r.createdAt.toISOString()
|
|
554
|
+
})).reverse();
|
|
555
|
+
result.set(trigger.id, preceding);
|
|
556
|
+
prevCreatedAt = trigger.createdAt;
|
|
557
|
+
}
|
|
558
|
+
const latestTrigger = chatTriggers[chatTriggers.length - 1];
|
|
559
|
+
if (latestTrigger) await tx.update(inboxEntries).set({
|
|
560
|
+
status: "acked",
|
|
561
|
+
ackedAt: /* @__PURE__ */ new Date()
|
|
562
|
+
}).where(and(eq(inboxEntries.inboxId, inboxId), eq(inboxEntries.chatId, chatId), eq(inboxEntries.status, "pending"), eq(inboxEntries.notify, false), lt(inboxEntries.createdAt, latestTrigger.createdAt)));
|
|
563
|
+
}
|
|
564
|
+
return result;
|
|
565
|
+
}
|
|
566
|
+
/**
|
|
567
|
+
* Ack a delivered entry from the WS data plane, scoped to the inboxes the
|
|
568
|
+
* connected socket has bound. Returns the acked row on success, `null` if no
|
|
569
|
+
* row matches — a benign outcome the caller should ignore (the entry may
|
|
570
|
+
* have already been acked, timed out, or never belonged to this socket).
|
|
571
|
+
*
|
|
572
|
+
* Trusts only the `inboxId` set the connected socket has bound (no `inboxId`
|
|
573
|
+
* on the wire), and short-circuits on an empty `inboxIds`.
|
|
574
|
+
*/
|
|
575
|
+
async function ackEntryByIdForBoundAgents(db, entryId, inboxIds) {
|
|
576
|
+
if (inboxIds.length === 0) return null;
|
|
577
|
+
return withSpan("inbox.ack.ws", { [FIRST_TREE_HUB_ATTR.INBOX_ENTRY_ID]: String(entryId) }, async () => {
|
|
578
|
+
const [entry] = await db.update(inboxEntries).set({
|
|
579
|
+
status: "acked",
|
|
580
|
+
ackedAt: /* @__PURE__ */ new Date()
|
|
581
|
+
}).where(and(eq(inboxEntries.id, entryId), inArray(inboxEntries.inboxId, inboxIds), eq(inboxEntries.status, "delivered"))).returning();
|
|
582
|
+
return entry ?? null;
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
async function resetTimedOutEntries(db, timeoutSeconds = DEFAULT_INBOX_TIMEOUT_SECONDS, maxRetries = DEFAULT_MAX_RETRY_COUNT) {
|
|
586
|
+
const reset = await db.update(inboxEntries).set({
|
|
587
|
+
status: "pending",
|
|
588
|
+
retryCount: sql`${inboxEntries.retryCount} + 1`
|
|
589
|
+
}).where(and(eq(inboxEntries.status, "delivered"), sql`${inboxEntries.deliveredAt} < NOW() - make_interval(secs => ${timeoutSeconds})`, lt(inboxEntries.retryCount, maxRetries))).returning({ id: inboxEntries.id });
|
|
590
|
+
const failed = await db.update(inboxEntries).set({ status: "failed" }).where(and(eq(inboxEntries.status, "delivered"), sql`${inboxEntries.deliveredAt} < NOW() - make_interval(secs => ${timeoutSeconds})`, gte(inboxEntries.retryCount, maxRetries))).returning({ id: inboxEntries.id });
|
|
591
|
+
return {
|
|
592
|
+
reset: reset.length,
|
|
593
|
+
failed: failed.length
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
/** Default age (30 days) past which silent rows that no notify-true delivery
|
|
597
|
+
* ever picked up are physically deleted. */
|
|
598
|
+
const SILENT_ROW_GC_MAX_AGE_SECONDS = 720 * 60 * 60;
|
|
599
|
+
/**
|
|
600
|
+
* Garbage-collect silent inbox rows so the table doesn't grow forever in
|
|
601
|
+
* chats where a `mention_only` agent is never @mentioned.
|
|
602
|
+
*
|
|
603
|
+
* Two cleanup paths:
|
|
604
|
+
*
|
|
605
|
+
* 1. `notify=false AND status='acked'` of any age — these are fully
|
|
606
|
+
* consumed (either bundled into a previous trigger or aged out via the
|
|
607
|
+
* bulk-ack in `collectPrecedingContext`); keep them only as long as
|
|
608
|
+
* the corresponding message rows we link to. The unique constraint
|
|
609
|
+
* `(inbox_id, message_id, chat_id)` means leaving them around blocks
|
|
610
|
+
* legitimate retries with the same key.
|
|
611
|
+
*
|
|
612
|
+
* 2. `notify=false AND status='pending' AND createdAt < NOW() - maxAge` —
|
|
613
|
+
* stale silent rows that no trigger ever caught up with. After 30
|
|
614
|
+
* days they're useless as preceding context (the @mention almost
|
|
615
|
+
* certainly already happened or the chat went dormant).
|
|
616
|
+
*
|
|
617
|
+
* Returns the number of rows deleted in each bucket so the background task
|
|
618
|
+
* can log meaningful counts.
|
|
619
|
+
*/
|
|
620
|
+
async function pruneStaleSilentEntries(db, maxAgeSeconds = SILENT_ROW_GC_MAX_AGE_SECONDS) {
|
|
621
|
+
const ackedDeleted = await db.delete(inboxEntries).where(and(eq(inboxEntries.notify, false), eq(inboxEntries.status, "acked"))).returning({ id: inboxEntries.id });
|
|
622
|
+
const stalePendingDeleted = await db.delete(inboxEntries).where(and(eq(inboxEntries.notify, false), eq(inboxEntries.status, "pending"), sql`${inboxEntries.createdAt} < NOW() - make_interval(secs => ${maxAgeSeconds})`)).returning({ id: inboxEntries.id });
|
|
623
|
+
return {
|
|
624
|
+
ackedDeleted: ackedDeleted.length,
|
|
625
|
+
stalePendingDeleted: stalePendingDeleted.length
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
/** Per-session state snapshot. One row per (agent, chat) pair, upserted on each session:state message. */
|
|
629
|
+
const agentChatSessions = pgTable("agent_chat_sessions", {
|
|
630
|
+
agentId: text("agent_id").notNull().references(() => agents.uuid, { onDelete: "cascade" }),
|
|
631
|
+
chatId: text("chat_id").notNull().references(() => chats.id, { onDelete: "cascade" }),
|
|
632
|
+
state: text("state").notNull(),
|
|
633
|
+
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
|
|
634
|
+
}, (table) => [primaryKey({ columns: [table.agentId, table.chatId] })]);
|
|
635
|
+
/**
|
|
636
|
+
* Per-(chat, agent) user state — independent from membership structure.
|
|
637
|
+
*
|
|
638
|
+
* This is the third layer of the chat data model: while `chats` owns
|
|
639
|
+
* the entity and `chat_membership` owns the structural relation
|
|
640
|
+
* (who can speak, who watches), this table owns the user's private
|
|
641
|
+
* state about a chat. The reason it lives apart: structural changes
|
|
642
|
+
* (speaker ↔ watcher, manager rebind, recompute) must never overwrite
|
|
643
|
+
* user-private state — physical separation makes that an invariant
|
|
644
|
+
* rather than a service-layer discipline.
|
|
645
|
+
*
|
|
646
|
+
* Columns evolve incrementally as new per-user state is needed.
|
|
647
|
+
* Currently:
|
|
648
|
+
* - `last_read_at`, `unread_mention_count` — seeded by PR-A from
|
|
649
|
+
* the legacy `chat_participants` / `chat_subscriptions` columns.
|
|
650
|
+
* - `engagement_status` — added in 0040; per-(chat, user) view
|
|
651
|
+
* state (active / archived / deleted). Auto-revives archived →
|
|
652
|
+
* active on new message; deleted is sticky (only the user can
|
|
653
|
+
* restore from the chat detail page).
|
|
654
|
+
*
|
|
655
|
+
* Future fields slated for this table: pinned, mute_until, draft,
|
|
656
|
+
* custom_title, last_seen_at — each as a separate change.
|
|
657
|
+
*
|
|
658
|
+
* Rows are lazy-upserted on first user write (markRead / mention
|
|
659
|
+
* counter bump / engagement transition). Reads use COALESCE for
|
|
660
|
+
* defaults so callers see `'active'` etc. even when no row exists.
|
|
661
|
+
* Service-layer integrity (no FK / CHECK / trigger).
|
|
662
|
+
*
|
|
663
|
+
* See proposals/chat-data-model-restructure.20260512.md §8.6.
|
|
664
|
+
*/
|
|
665
|
+
const chatUserState = pgTable("chat_user_state", {
|
|
666
|
+
chatId: text("chat_id").notNull(),
|
|
667
|
+
agentId: text("agent_id").notNull(),
|
|
668
|
+
lastReadAt: timestamp("last_read_at", { withTimezone: true }),
|
|
669
|
+
unreadMentionCount: integer("unread_mention_count").notNull().default(0),
|
|
670
|
+
engagementStatus: text("engagement_status").notNull().default("active")
|
|
671
|
+
}, (table) => [
|
|
672
|
+
primaryKey({ columns: [table.chatId, table.agentId] }),
|
|
673
|
+
index("idx_user_state_agent").on(table.agentId),
|
|
674
|
+
index("idx_user_state_unread").on(table.agentId).where(sql`unread_mention_count > 0`)
|
|
675
|
+
]);
|
|
676
|
+
/** Agent presence and runtime state. Tracked via WebSocket connections; stale entries are cleaned up using server_instances heartbeat. */
|
|
677
|
+
const agentPresence = pgTable("agent_presence", {
|
|
678
|
+
agentId: text("agent_id").primaryKey().references(() => agents.uuid, { onDelete: "cascade" }),
|
|
679
|
+
status: text("status").notNull().default("offline"),
|
|
680
|
+
instanceId: text("instance_id"),
|
|
681
|
+
connectedAt: timestamp("connected_at", { withTimezone: true }),
|
|
682
|
+
lastSeenAt: timestamp("last_seen_at", { withTimezone: true }).notNull().defaultNow(),
|
|
683
|
+
clientId: text("client_id").references(() => clients.id, { onDelete: "set null" }),
|
|
684
|
+
runtimeType: text("runtime_type"),
|
|
685
|
+
runtimeVersion: text("runtime_version"),
|
|
686
|
+
runtimeState: text("runtime_state"),
|
|
687
|
+
activeSessions: integer("active_sessions"),
|
|
688
|
+
totalSessions: integer("total_sessions"),
|
|
689
|
+
runtimeUpdatedAt: timestamp("runtime_updated_at", { withTimezone: true })
|
|
690
|
+
});
|
|
691
|
+
/**
|
|
692
|
+
* Shared access-control primitives. Most route-level gating now lives in
|
|
693
|
+
* `scope/require-*.ts` — this module is reduced to two helpers that need
|
|
694
|
+
* SQL building blocks reused across routes and tests:
|
|
695
|
+
*
|
|
696
|
+
* - `agentVisibilityCondition` — WHERE clause for "agents visible to a
|
|
697
|
+
* member" (org-visible OR managerId = the caller's member). Composed
|
|
698
|
+
* into list queries that already select from `agents`.
|
|
699
|
+
* - `listAgentsManagedByUser` — cross-org list of agents personally
|
|
700
|
+
* managed by a user; powers the CLI `agent list --remote` view.
|
|
701
|
+
*
|
|
702
|
+
* Visibility is the same for all roles — admin sees the same set as a
|
|
703
|
+
* regular member. Admin privilege is expressed through manageability
|
|
704
|
+
* (`requireAgentAccess(..., "manage")`), not visibility.
|
|
705
|
+
*/
|
|
706
|
+
/**
|
|
707
|
+
* SQL WHERE conditions for agents visible to a member.
|
|
708
|
+
* target org + not deleted + (organization-visible OR managerId = caller's member)
|
|
709
|
+
*/
|
|
710
|
+
function agentVisibilityCondition(orgId, memberId) {
|
|
711
|
+
return and(eq(agents.organizationId, orgId), ne(agents.status, AGENT_STATUSES.DELETED), or(eq(agents.visibility, AGENT_VISIBILITY.ORGANIZATION), eq(agents.managerId, memberId)));
|
|
712
|
+
}
|
|
713
|
+
/**
|
|
714
|
+
* Cross-org listing helper for "agents I personally manage". Used by the
|
|
715
|
+
* CLI `agent list --remote` view — JOINs `agents → members.id` and filters
|
|
716
|
+
* by `members.user_id`.
|
|
717
|
+
*/
|
|
718
|
+
async function listAgentsManagedByUser(db, userId) {
|
|
719
|
+
return db.select({
|
|
720
|
+
uuid: agents.uuid,
|
|
721
|
+
name: agents.name,
|
|
722
|
+
displayName: agents.displayName,
|
|
723
|
+
type: agents.type,
|
|
724
|
+
organizationId: agents.organizationId,
|
|
725
|
+
inboxId: agents.inboxId,
|
|
726
|
+
visibility: agents.visibility,
|
|
727
|
+
runtimeProvider: agents.runtimeProvider,
|
|
728
|
+
clientId: agents.clientId
|
|
729
|
+
}).from(agents).innerJoin(members, eq(agents.managerId, members.id)).where(and(eq(members.userId, userId), eq(members.status, "active"), ne(agents.status, AGENT_STATUSES.DELETED)));
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* Resolve the UUID of the "default" organization. Internal use only —
|
|
733
|
+
* webhooks, fallbacks, etc. The HTTP API layer no longer falls back to
|
|
734
|
+
* the JWT default org.
|
|
735
|
+
*/
|
|
736
|
+
async function resolveDefaultOrgId(db) {
|
|
737
|
+
const [org] = await db.select({ id: organizations.id }).from(organizations).where(eq(organizations.name, "default")).limit(1);
|
|
738
|
+
if (!org) throw new Error("Default organization not found. Ensure the server has started and ensureDefaultOrganization() ran.");
|
|
739
|
+
return org.id;
|
|
740
|
+
}
|
|
741
|
+
async function getOrganization(db, id) {
|
|
742
|
+
const [org] = await db.select().from(organizations).where(eq(organizations.id, id)).limit(1);
|
|
743
|
+
if (!org) throw new NotFoundError(`Organization "${id}" not found`);
|
|
744
|
+
return org;
|
|
745
|
+
}
|
|
746
|
+
async function updateOrganization(db, id, data) {
|
|
747
|
+
const updates = { updatedAt: /* @__PURE__ */ new Date() };
|
|
748
|
+
if (data.name !== void 0) updates.name = data.name;
|
|
749
|
+
if (data.displayName !== void 0) updates.displayName = data.displayName;
|
|
750
|
+
if (data.maxAgents !== void 0) updates.maxAgents = data.maxAgents;
|
|
751
|
+
if (data.maxMessagesPerMinute !== void 0) updates.maxMessagesPerMinute = data.maxMessagesPerMinute;
|
|
752
|
+
if (data.features !== void 0) updates.features = data.features;
|
|
753
|
+
try {
|
|
754
|
+
const [org] = await db.update(organizations).set(updates).where(eq(organizations.id, id)).returning();
|
|
755
|
+
if (!org) throw new NotFoundError(`Organization "${id}" not found`);
|
|
756
|
+
return org;
|
|
757
|
+
} catch (err) {
|
|
758
|
+
if ((err?.code ?? err?.cause?.code ?? "") === "23505") throw new ConflictError(`Organization name "${data.name}" is already taken`);
|
|
759
|
+
throw err;
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
/**
|
|
763
|
+
* Ensure the default organization exists. Called on server startup.
|
|
764
|
+
* Uses a fixed UUID for the default org to ensure idempotency.
|
|
765
|
+
*/
|
|
766
|
+
async function ensureDefaultOrganization(db) {
|
|
767
|
+
const [existing] = await db.select({ id: organizations.id }).from(organizations).where(eq(organizations.name, "default")).limit(1);
|
|
768
|
+
if (existing) return existing;
|
|
769
|
+
const id = uuidv7();
|
|
770
|
+
const [org] = await db.insert(organizations).values({
|
|
771
|
+
id,
|
|
772
|
+
name: "default",
|
|
773
|
+
displayName: "Default Organization"
|
|
774
|
+
}).onConflictDoNothing().returning();
|
|
775
|
+
return org ?? existing;
|
|
776
|
+
}
|
|
196
777
|
/**
|
|
197
778
|
* Single source of truth for writing speaker rows into `chat_membership`.
|
|
198
779
|
*
|
|
@@ -563,586 +1144,615 @@ function ensureCanJoin(membership) {
|
|
|
563
1144
|
if (membership === "participant") throw new ConflictError("Already a participant in this chat");
|
|
564
1145
|
if (membership === null) throw new ForbiddenError("Not a watcher of this chat — open the chat from your workspace before joining");
|
|
565
1146
|
}
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
organizationId: orgId,
|
|
587
|
-
type: data.type,
|
|
588
|
-
topic: data.topic ?? null,
|
|
589
|
-
metadata: data.metadata ?? {}
|
|
590
|
-
}).returning();
|
|
591
|
-
await addChatParticipants(tx, chatId, [...allParticipantIds].map((agentId) => ({
|
|
592
|
-
agentId,
|
|
593
|
-
role: agentId === creatorId ? "owner" : "member"
|
|
594
|
-
})));
|
|
595
|
-
await recomputeChatWatchers(tx, chatId);
|
|
596
|
-
const participants = await tx.select().from(chatMembership).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.accessMode, "speaker")));
|
|
597
|
-
if (!chat) throw new Error("Unexpected: INSERT RETURNING produced no row");
|
|
598
|
-
return {
|
|
599
|
-
...chat,
|
|
600
|
-
participants
|
|
601
|
-
};
|
|
602
|
-
});
|
|
603
|
-
}
|
|
604
|
-
async function getChat(db, chatId) {
|
|
605
|
-
const [chat] = await db.select().from(chats).where(eq(chats.id, chatId)).limit(1);
|
|
606
|
-
if (!chat) throw new NotFoundError(`Chat "${chatId}" not found`);
|
|
607
|
-
return chat;
|
|
1147
|
+
/**
|
|
1148
|
+
* Names beginning with `__` are reserved for Hub-internal pseudo agents.
|
|
1149
|
+
* User-facing creation must not be able to squat on them, otherwise
|
|
1150
|
+
* internal traffic could be routed through a real account.
|
|
1151
|
+
*/
|
|
1152
|
+
const RESERVED_AGENT_NAME_PREFIX = "__";
|
|
1153
|
+
/**
|
|
1154
|
+
* Derive the relative URL clients should use to fetch a manager-uploaded
|
|
1155
|
+
* avatar image. Returns `null` when no image is set. Embeds the upload
|
|
1156
|
+
* timestamp as `?v=<epoch>` so a fresh upload busts any browser cache
|
|
1157
|
+
* that may have memoised the previous version.
|
|
1158
|
+
*
|
|
1159
|
+
* Auth: the image route is intentionally public read — the URL leaks no
|
|
1160
|
+
* more than the agent's UUID, which is already required to address it.
|
|
1161
|
+
* Keeping it unauthenticated lets `<img src>` render without bespoke
|
|
1162
|
+
* fetch-and-blob plumbing.
|
|
1163
|
+
*/
|
|
1164
|
+
function agentAvatarImageUrl(uuid, updatedAt) {
|
|
1165
|
+
if (!updatedAt) return null;
|
|
1166
|
+
return `/api/v1/agents/${uuid}/avatar?v=${updatedAt.getTime()}`;
|
|
608
1167
|
}
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
items: [],
|
|
621
|
-
nextCursor: null
|
|
622
|
-
};
|
|
623
|
-
const where = cursor ? and(inArray(chats.id, chatIds), lt(chats.updatedAt, new Date(cursor))) : inArray(chats.id, chatIds);
|
|
624
|
-
const rows = await db.select().from(chats).where(where).orderBy(desc(chats.updatedAt)).limit(limit + 1);
|
|
625
|
-
const hasMore = rows.length > limit;
|
|
626
|
-
const items = hasMore ? rows.slice(0, limit) : rows;
|
|
627
|
-
const last = items[items.length - 1];
|
|
628
|
-
return {
|
|
629
|
-
items,
|
|
630
|
-
nextCursor: hasMore && last ? last.updatedAt.toISOString() : null
|
|
631
|
-
};
|
|
1168
|
+
/**
|
|
1169
|
+
* True iff `clients.metadata.capabilities` is a non-empty object — i.e. the
|
|
1170
|
+
* client has reported at least one runtime probe result. Used to distinguish
|
|
1171
|
+
* "we don't know what's installed yet" (empty / never reported) from
|
|
1172
|
+
* "client explicitly reports this provider is missing".
|
|
1173
|
+
*/
|
|
1174
|
+
function clientCapabilitiesReported(metadata) {
|
|
1175
|
+
if (!metadata || typeof metadata !== "object") return false;
|
|
1176
|
+
const caps = metadata.capabilities;
|
|
1177
|
+
if (!caps || typeof caps !== "object") return false;
|
|
1178
|
+
return Object.keys(caps).length > 0;
|
|
632
1179
|
}
|
|
633
1180
|
/**
|
|
634
|
-
*
|
|
635
|
-
* runtime
|
|
636
|
-
*
|
|
1181
|
+
* Inspect a `clients.metadata.capabilities` blob (jsonb) for a specific
|
|
1182
|
+
* runtime provider entry. Capabilities live under the `metadata.capabilities`
|
|
1183
|
+
* subkey (Option C); the column is unstructured at the DB layer, so we
|
|
1184
|
+
* defensively narrow before key access.
|
|
1185
|
+
*
|
|
1186
|
+
* "Supports" requires the entry's SDK to be **available** — `state: "ok"` or
|
|
1187
|
+
* `state: "unauthenticated"`. A `missing` or `error` entry is *reported* but
|
|
1188
|
+
* not usable, so we explicitly reject those rather than treating mere key
|
|
1189
|
+
* presence as support. Auth state is left to the user to fix at runtime
|
|
1190
|
+
* (the re-bind dialog surfaces an `unauthenticated` hint).
|
|
637
1191
|
*/
|
|
638
|
-
|
|
639
|
-
return
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
displayName: agents.displayName,
|
|
646
|
-
type: agents.type
|
|
647
|
-
}).from(chatMembership).innerJoin(agents, eq(chatMembership.agentId, agents.uuid)).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.accessMode, "speaker")));
|
|
1192
|
+
function clientSupportsRuntimeProvider(metadata, provider) {
|
|
1193
|
+
if (!metadata || typeof metadata !== "object") return false;
|
|
1194
|
+
const caps = metadata.capabilities;
|
|
1195
|
+
if (!caps || typeof caps !== "object") return false;
|
|
1196
|
+
const entry = caps[provider];
|
|
1197
|
+
if (!entry || typeof entry !== "object") return false;
|
|
1198
|
+
return entry.available === true;
|
|
648
1199
|
}
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
1200
|
+
/** Default visibility per agent type. */
|
|
1201
|
+
function defaultVisibility(type) {
|
|
1202
|
+
switch (type) {
|
|
1203
|
+
case "human":
|
|
1204
|
+
case "autonomous_agent": return AGENT_VISIBILITY.ORGANIZATION;
|
|
1205
|
+
case "personal_assistant": return AGENT_VISIBILITY.PRIVATE;
|
|
1206
|
+
default: return AGENT_VISIBILITY.PRIVATE;
|
|
1207
|
+
}
|
|
652
1208
|
}
|
|
653
1209
|
/**
|
|
654
|
-
*
|
|
655
|
-
*
|
|
656
|
-
*
|
|
1210
|
+
* Resolve + validate the client that will own the new agent.
|
|
1211
|
+
*
|
|
1212
|
+
* Rule (unified-user-token, post-first-bind relaxation):
|
|
1213
|
+
* - Human agents represent the member themselves and have no runtime; a
|
|
1214
|
+
* missing `clientId` is required and the column stays NULL.
|
|
1215
|
+
* - Non-human agents MAY omit `clientId` at creation; the row stays NULL
|
|
1216
|
+
* and is claimed on the first WS bind (see `api/agent/ws-client.ts`).
|
|
1217
|
+
* - When a non-human agent IS created with a `clientId`, the pinned client
|
|
1218
|
+
* must already be owned by the manager's user (Rule R-RUN).
|
|
657
1219
|
*/
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
1220
|
+
/**
|
|
1221
|
+
* Check that a client's reported capabilities show the given runtime provider
|
|
1222
|
+
* as **available** (SDK installed, regardless of auth state).
|
|
1223
|
+
*
|
|
1224
|
+
* Tri-state semantics by `clients.metadata.capabilities` shape:
|
|
1225
|
+
* - empty / absent — client hasn't probed yet (newly registered or pre-P2
|
|
1226
|
+
* install). Treat as "unknown" and allow; the in-band repair path
|
|
1227
|
+
* (RUNTIME_PROVIDER_MISMATCH on bind) catches actual incompatibility.
|
|
1228
|
+
* - reported, entry shows `state: ok | unauthenticated` (i.e. `available:
|
|
1229
|
+
* true`) — allow.
|
|
1230
|
+
* - reported, entry missing OR `state: missing | error` — block unless
|
|
1231
|
+
* `force` is set. We deliberately do NOT treat mere key presence as
|
|
1232
|
+
* support: probeCapabilities() always emits an entry per built-in
|
|
1233
|
+
* provider, including `{ state: "missing" }` for absent SDKs.
|
|
1234
|
+
*
|
|
1235
|
+
* Skipped entirely for human agents (no clientId) and when `force` is set
|
|
1236
|
+
* (e.g. operator overrides for an offline client).
|
|
1237
|
+
*/
|
|
1238
|
+
async function ensureClientSupportsRuntimeProvider(db, clientId, runtimeProvider, options = {}) {
|
|
1239
|
+
if (clientId === null) return;
|
|
1240
|
+
if (options.force) return;
|
|
1241
|
+
const [client] = await db.select({ metadata: clients.metadata }).from(clients).where(eq(clients.id, clientId)).limit(1);
|
|
1242
|
+
if (!client) return;
|
|
1243
|
+
if (!clientCapabilitiesReported(client.metadata)) return;
|
|
1244
|
+
if (!clientSupportsRuntimeProvider(client.metadata, runtimeProvider)) throw new BadRequestError(`Client "${clientId}" does not have runtime provider "${runtimeProvider}" available. Install the matching SDK on that machine and re-run capability detection, or retry with \`force: true\` if the client is offline / capabilities are stale.`);
|
|
661
1245
|
}
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
1246
|
+
async function resolveAgentClient(db, data) {
|
|
1247
|
+
if (data.type === "human") {
|
|
1248
|
+
if (data.clientId) throw new BadRequestError("Human agents cannot be pinned to a client");
|
|
1249
|
+
return null;
|
|
1250
|
+
}
|
|
1251
|
+
if (!data.clientId) return null;
|
|
1252
|
+
const [manager] = await db.select({ userId: members.userId }).from(members).where(eq(members.id, data.managerId)).limit(1);
|
|
1253
|
+
if (!manager) throw new BadRequestError(`Manager "${data.managerId}" not found`);
|
|
1254
|
+
const [client] = await db.select({
|
|
1255
|
+
id: clients.id,
|
|
1256
|
+
userId: clients.userId
|
|
1257
|
+
}).from(clients).where(eq(clients.id, data.clientId)).limit(1);
|
|
1258
|
+
if (!client) throw new BadRequestError(`Client "${data.clientId}" not found`);
|
|
1259
|
+
if (!client.userId) throw new BadRequestError(`Client "${data.clientId}" has not been claimed by a user yet. Have the operator run \`first-tree-hub connect <token>\` on that machine before pinning an agent to it.`);
|
|
1260
|
+
if (client.userId !== manager.userId) throw new ForbiddenError(`Client "${data.clientId}" is not owned by the manager's user — pick a client belonging to that user.`);
|
|
1261
|
+
return client.id;
|
|
672
1262
|
}
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
1263
|
+
/**
|
|
1264
|
+
* Validate a `delegateMention` write at the service layer. Two checks:
|
|
1265
|
+
* 1. Target uuid must resolve to an existing agent — dangling references
|
|
1266
|
+
* would silently break webhook delegation at runtime.
|
|
1267
|
+
* 2. Target must belong to the same organization as the source agent —
|
|
1268
|
+
* cross-org delegate links are rejected here at the source so the
|
|
1269
|
+
* database never accumulates dirty rows. The webhook router has a
|
|
1270
|
+
* defense-in-depth check that filters them at fan-out time, but this
|
|
1271
|
+
* keeps the data clean and gives the admin UI an immediate 422 instead
|
|
1272
|
+
* of a silent runtime drop.
|
|
1273
|
+
*
|
|
1274
|
+
* `null` clears the field — handled by the caller; we are only invoked when
|
|
1275
|
+
* the caller wrote a non-null uuid.
|
|
1276
|
+
*/
|
|
1277
|
+
async function validateDelegateMentionTarget(db, targetUuid, sourceOrgId) {
|
|
1278
|
+
const [target] = await db.select({
|
|
1279
|
+
uuid: agents.uuid,
|
|
678
1280
|
organizationId: agents.organizationId
|
|
679
|
-
}).from(agents).where(eq(agents.uuid,
|
|
680
|
-
if (!
|
|
681
|
-
if (
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
1281
|
+
}).from(agents).where(eq(agents.uuid, targetUuid)).limit(1);
|
|
1282
|
+
if (!target) throw new BadRequestError(`delegateMention target "${targetUuid}" not found`);
|
|
1283
|
+
if (target.organizationId !== sourceOrgId) throw new BadRequestError("delegateMention target must belong to the same organization as the agent");
|
|
1284
|
+
}
|
|
1285
|
+
/**
|
|
1286
|
+
* Service-layer guard: `delegateMention` is only available for `human` agents.
|
|
1287
|
+
* Mirrors the Web UI in `identity-section.tsx`, which only renders the
|
|
1288
|
+
* delegate-mention selector when `agent.type === "human"`. Without this
|
|
1289
|
+
* server-side check, CLI / Admin API / internal scripts could write
|
|
1290
|
+
* delegateMention onto non-human rows, silently re-enabling the
|
|
1291
|
+
* autonomous-agent-self-mention path that resolveAudience would then fan
|
|
1292
|
+
* out. Called from `createAgent` / `updateAgent` before
|
|
1293
|
+
* `validateDelegateMentionTarget` so a wrong source type fails fast without
|
|
1294
|
+
* the target lookup round-trip.
|
|
1295
|
+
*/
|
|
1296
|
+
function assertDelegateMentionAllowed(sourceType) {
|
|
1297
|
+
if (sourceType !== AGENT_TYPES.HUMAN) throw new BadRequestError("delegateMention can only be set on human agents");
|
|
1298
|
+
}
|
|
1299
|
+
/**
|
|
1300
|
+
* Pick the first admin member in the org for internal system agents. Throws
|
|
1301
|
+
* if the org has no admin — the caller should surface the error so an admin
|
|
1302
|
+
* is created before the system tries to register more agents.
|
|
1303
|
+
*/
|
|
1304
|
+
async function resolveFallbackManagerId(db, orgId) {
|
|
1305
|
+
const [row] = await db.select({ id: members.id }).from(members).where(and(eq(members.organizationId, orgId), eq(members.role, "admin"))).orderBy(members.createdAt).limit(1);
|
|
1306
|
+
if (!row) throw new BadRequestError(`Cannot create agent in organization "${orgId}" — no admin member exists. Create an admin member first (see \`first-tree-hub onboard\`).`);
|
|
1307
|
+
return row.id;
|
|
1308
|
+
}
|
|
1309
|
+
async function createAgent(db, data, options = {}) {
|
|
1310
|
+
const uuid = uuidv7();
|
|
1311
|
+
const name = data.name ?? null;
|
|
1312
|
+
const runtimeProvider = data.runtimeProvider ?? "claude-code";
|
|
1313
|
+
if (name?.startsWith(RESERVED_AGENT_NAME_PREFIX)) throw new BadRequestError(`Agent name "${name}" is reserved — names starting with "${RESERVED_AGENT_NAME_PREFIX}" are Hub-internal`);
|
|
1314
|
+
if (name && isReservedAgentName(name)) throw new BadRequestError(`Agent name "${name}" is reserved — pick a different one.`);
|
|
1315
|
+
const inboxId = `inbox_${uuid}`;
|
|
1316
|
+
let orgId;
|
|
1317
|
+
let managerId;
|
|
1318
|
+
if (data.managerId && data.organizationId) {
|
|
1319
|
+
orgId = data.organizationId;
|
|
1320
|
+
managerId = data.managerId;
|
|
1321
|
+
} else if (data.managerId) {
|
|
1322
|
+
const [manager] = await db.select({
|
|
1323
|
+
id: members.id,
|
|
1324
|
+
organizationId: members.organizationId
|
|
1325
|
+
}).from(members).where(eq(members.id, data.managerId)).limit(1);
|
|
1326
|
+
if (!manager) throw new BadRequestError(`Manager "${data.managerId}" not found`);
|
|
1327
|
+
orgId = manager.organizationId;
|
|
1328
|
+
managerId = manager.id;
|
|
1329
|
+
} else {
|
|
1330
|
+
orgId = data.organizationId ?? await resolveDefaultOrgId(db);
|
|
1331
|
+
managerId = await resolveFallbackManagerId(db, orgId);
|
|
1332
|
+
}
|
|
1333
|
+
const clientId = await resolveAgentClient(db, {
|
|
1334
|
+
clientId: data.clientId,
|
|
1335
|
+
managerId,
|
|
1336
|
+
type: data.type
|
|
688
1337
|
});
|
|
689
|
-
|
|
690
|
-
|
|
1338
|
+
await ensureClientSupportsRuntimeProvider(db, clientId, runtimeProvider, { force: options.force });
|
|
1339
|
+
if (data.delegateMention) {
|
|
1340
|
+
assertDelegateMentionAllowed(data.type);
|
|
1341
|
+
await validateDelegateMentionTarget(db, data.delegateMention, orgId);
|
|
1342
|
+
}
|
|
1343
|
+
const [org] = await db.select({ maxAgents: organizations.maxAgents }).from(organizations).where(eq(organizations.id, orgId)).limit(1);
|
|
1344
|
+
if (org && org.maxAgents > 0) {
|
|
1345
|
+
if (((await db.select({ value: count() }).from(agents).where(and(eq(agents.organizationId, orgId), ne(agents.status, AGENT_STATUSES.DELETED))))[0]?.value ?? 0) >= org.maxAgents) throw new ForbiddenError(`Organization "${orgId}" has reached its agent limit (${org.maxAgents}). Upgrade your plan or delete unused agents.`);
|
|
1346
|
+
}
|
|
1347
|
+
const resolvedDisplayName = data.displayName?.trim() || name || "Unnamed Agent";
|
|
1348
|
+
try {
|
|
1349
|
+
return await db.transaction(async (tx) => {
|
|
1350
|
+
const [row] = await tx.insert(agents).values({
|
|
1351
|
+
uuid,
|
|
1352
|
+
name,
|
|
1353
|
+
organizationId: orgId,
|
|
1354
|
+
type: data.type,
|
|
1355
|
+
displayName: resolvedDisplayName,
|
|
1356
|
+
delegateMention: data.delegateMention ?? null,
|
|
1357
|
+
inboxId,
|
|
1358
|
+
source: data.source ?? null,
|
|
1359
|
+
visibility: data.visibility ?? defaultVisibility(data.type),
|
|
1360
|
+
metadata: data.metadata ?? {},
|
|
1361
|
+
managerId,
|
|
1362
|
+
clientId,
|
|
1363
|
+
runtimeProvider
|
|
1364
|
+
}).returning();
|
|
1365
|
+
if (!row) throw new Error("Unexpected: INSERT RETURNING produced no row");
|
|
1366
|
+
const initialPayload = defaultRuntimeConfigPayload(runtimeProvider);
|
|
1367
|
+
if (data.gitRepos && data.gitRepos.length > 0) initialPayload.gitRepos = data.gitRepos;
|
|
1368
|
+
await tx.insert(agentConfigs).values({
|
|
1369
|
+
agentId: row.uuid,
|
|
1370
|
+
version: 1,
|
|
1371
|
+
payload: initialPayload,
|
|
1372
|
+
updatedBy: "system"
|
|
1373
|
+
}).onConflictDoNothing();
|
|
1374
|
+
return row;
|
|
1375
|
+
});
|
|
1376
|
+
} catch (err) {
|
|
1377
|
+
if ((err?.code ?? err?.cause?.code ?? "") === "23505" && name) throw new ConflictError(`Agent name "${name}" already exists in organization "${orgId}"`);
|
|
1378
|
+
throw err;
|
|
1379
|
+
}
|
|
691
1380
|
}
|
|
692
|
-
async function
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
1381
|
+
async function checkAgentNameAvailability(db, orgId, name) {
|
|
1382
|
+
if (!AGENT_NAME_REGEX.test(name)) return {
|
|
1383
|
+
available: false,
|
|
1384
|
+
reason: "invalid"
|
|
1385
|
+
};
|
|
1386
|
+
if (isReservedAgentName(name) || name.startsWith(RESERVED_AGENT_NAME_PREFIX)) return {
|
|
1387
|
+
available: false,
|
|
1388
|
+
reason: "reserved"
|
|
1389
|
+
};
|
|
1390
|
+
const [existing] = await db.select({ uuid: agents.uuid }).from(agents).where(and(eq(agents.organizationId, orgId), eq(agents.name, name), ne(agents.status, AGENT_STATUSES.DELETED))).limit(1);
|
|
1391
|
+
return existing ? {
|
|
1392
|
+
available: false,
|
|
1393
|
+
reason: "taken"
|
|
1394
|
+
} : { available: true };
|
|
1395
|
+
}
|
|
1396
|
+
async function getAgent(db, uuid) {
|
|
1397
|
+
const [agent] = await db.select().from(agents).where(and(eq(agents.uuid, uuid), ne(agents.status, AGENT_STATUSES.DELETED))).limit(1);
|
|
1398
|
+
if (!agent) throw new NotFoundError(`Agent "${uuid}" not found`);
|
|
1399
|
+
return agent;
|
|
700
1400
|
}
|
|
701
1401
|
/**
|
|
702
|
-
*
|
|
703
|
-
*
|
|
704
|
-
*
|
|
705
|
-
*
|
|
1402
|
+
* Admin-only variant: return every non-deleted agent in the org, ignoring
|
|
1403
|
+
* the visibility filter. Used by the `/admin` "All Agents" view so a team
|
|
1404
|
+
* admin can see and act on private agents owned by other members. The
|
|
1405
|
+
* route layer is responsible for gating this to admin callers — the
|
|
1406
|
+
* service does not enforce role by itself, but it does enforce org scope
|
|
1407
|
+
* and the not-deleted predicate.
|
|
706
1408
|
*/
|
|
707
|
-
async function
|
|
708
|
-
const
|
|
1409
|
+
async function listAgentsForAdmin(db, scope, limit, cursor) {
|
|
1410
|
+
const conditions = [eq(agents.organizationId, scope.organizationId), ne(agents.status, AGENT_STATUSES.DELETED)];
|
|
1411
|
+
if (cursor) conditions.push(lt(agents.createdAt, new Date(cursor)));
|
|
1412
|
+
const where = and(...conditions);
|
|
1413
|
+
const rows = await db.select({
|
|
709
1414
|
uuid: agents.uuid,
|
|
710
1415
|
name: agents.name,
|
|
1416
|
+
organizationId: agents.organizationId,
|
|
711
1417
|
type: agents.type,
|
|
712
|
-
displayName: agents.displayName
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
1418
|
+
displayName: agents.displayName,
|
|
1419
|
+
delegateMention: agents.delegateMention,
|
|
1420
|
+
inboxId: agents.inboxId,
|
|
1421
|
+
status: agents.status,
|
|
1422
|
+
visibility: agents.visibility,
|
|
1423
|
+
metadata: agents.metadata,
|
|
1424
|
+
managerId: agents.managerId,
|
|
1425
|
+
clientId: agents.clientId,
|
|
1426
|
+
runtimeProvider: agents.runtimeProvider,
|
|
1427
|
+
avatarColorToken: agents.avatarColorToken,
|
|
1428
|
+
avatarImageUpdatedAt: agents.avatarImageUpdatedAt,
|
|
1429
|
+
createdAt: agents.createdAt,
|
|
1430
|
+
updatedAt: agents.updatedAt,
|
|
1431
|
+
presenceStatus: agentPresence.status,
|
|
1432
|
+
runtimeType: agentPresence.runtimeType,
|
|
1433
|
+
runtimeState: agentPresence.runtimeState,
|
|
1434
|
+
activeSessions: agentPresence.activeSessions
|
|
1435
|
+
}).from(agents).leftJoin(agentPresence, eq(agents.uuid, agentPresence.agentId)).where(where).orderBy(desc(agents.createdAt)).limit(limit + 1);
|
|
1436
|
+
const hasMore = rows.length > limit;
|
|
1437
|
+
const items = hasMore ? rows.slice(0, limit) : rows;
|
|
1438
|
+
const last = items[items.length - 1];
|
|
1439
|
+
return {
|
|
1440
|
+
items,
|
|
1441
|
+
nextCursor: hasMore && last ? last.createdAt.toISOString() : null
|
|
1442
|
+
};
|
|
1443
|
+
}
|
|
1444
|
+
/**
|
|
1445
|
+
* List agents visible to a specific member.
|
|
1446
|
+
* Uses agentVisibilityCondition from access-control (same rules for all roles).
|
|
1447
|
+
*/
|
|
1448
|
+
async function listAgentsForMember(db, scope, limit, cursor, type) {
|
|
1449
|
+
const conditions = [agentVisibilityCondition(scope.organizationId, scope.memberId)];
|
|
1450
|
+
if (cursor) conditions.push(lt(agents.createdAt, new Date(cursor)));
|
|
1451
|
+
if (type) conditions.push(eq(agents.type, type));
|
|
1452
|
+
const where = and(...conditions);
|
|
1453
|
+
const rows = await db.select({
|
|
1454
|
+
uuid: agents.uuid,
|
|
1455
|
+
name: agents.name,
|
|
1456
|
+
organizationId: agents.organizationId,
|
|
1457
|
+
type: agents.type,
|
|
1458
|
+
displayName: agents.displayName,
|
|
1459
|
+
delegateMention: agents.delegateMention,
|
|
1460
|
+
inboxId: agents.inboxId,
|
|
1461
|
+
status: agents.status,
|
|
1462
|
+
visibility: agents.visibility,
|
|
1463
|
+
metadata: agents.metadata,
|
|
1464
|
+
managerId: agents.managerId,
|
|
1465
|
+
clientId: agents.clientId,
|
|
1466
|
+
runtimeProvider: agents.runtimeProvider,
|
|
1467
|
+
avatarColorToken: agents.avatarColorToken,
|
|
1468
|
+
avatarImageUpdatedAt: agents.avatarImageUpdatedAt,
|
|
1469
|
+
createdAt: agents.createdAt,
|
|
1470
|
+
updatedAt: agents.updatedAt,
|
|
1471
|
+
presenceStatus: agentPresence.status,
|
|
1472
|
+
runtimeType: agentPresence.runtimeType,
|
|
1473
|
+
runtimeState: agentPresence.runtimeState,
|
|
1474
|
+
activeSessions: agentPresence.activeSessions
|
|
1475
|
+
}).from(agents).leftJoin(agentPresence, eq(agents.uuid, agentPresence.agentId)).where(where).orderBy(desc(agents.createdAt)).limit(limit + 1);
|
|
1476
|
+
const hasMore = rows.length > limit;
|
|
1477
|
+
const items = hasMore ? rows.slice(0, limit) : rows;
|
|
1478
|
+
const last = items[items.length - 1];
|
|
1479
|
+
return {
|
|
1480
|
+
items,
|
|
1481
|
+
nextCursor: hasMore && last ? last.createdAt.toISOString() : null
|
|
1482
|
+
};
|
|
1483
|
+
}
|
|
1484
|
+
async function updateAgent(db, uuid, data) {
|
|
1485
|
+
const agent = await getAgent(db, uuid);
|
|
1486
|
+
if (data.clientId !== void 0) {
|
|
1487
|
+
if (data.clientId === null) throw new BadRequestError("clientId cannot be cleared — once bound, an agent stays bound to its client");
|
|
1488
|
+
if (agent.clientId !== null && agent.clientId !== data.clientId) throw new BadRequestError("clientId is immutable through this entry — cross-client moves go through rebindAgent (PATCH /agents/:uuid/rebind), which runs owner / org / capability checks atomically.");
|
|
724
1489
|
}
|
|
725
|
-
const
|
|
726
|
-
if (
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
agentId: chatMembership.agentId,
|
|
730
|
-
role: chatMembership.role,
|
|
731
|
-
mode: chatMembership.mode
|
|
732
|
-
}).from(chatMembership).where(and(inArray(chatMembership.agentId, agentIds), eq(chatMembership.accessMode, "speaker")));
|
|
733
|
-
if (participations.length === 0) return [];
|
|
734
|
-
const chatIds = [...new Set(participations.map((p) => p.chatId))];
|
|
735
|
-
const agentChatMap = /* @__PURE__ */ new Map();
|
|
736
|
-
for (const p of participations) {
|
|
737
|
-
const list = agentChatMap.get(p.agentId) ?? [];
|
|
738
|
-
list.push(p.chatId);
|
|
739
|
-
agentChatMap.set(p.agentId, list);
|
|
1490
|
+
const updates = { updatedAt: /* @__PURE__ */ new Date() };
|
|
1491
|
+
if (data.type !== void 0) {
|
|
1492
|
+
if (data.type !== AGENT_TYPES.HUMAN && agent.delegateMention !== null && data.delegateMention !== null) throw new BadRequestError("Cannot change type away from `human` while delegateMention is set — clear delegateMention in the same patch.");
|
|
1493
|
+
updates.type = data.type;
|
|
740
1494
|
}
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
const
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
updatedAt: chat.updatedAt.toISOString()
|
|
768
|
-
};
|
|
769
|
-
}).filter((c) => c !== null);
|
|
770
|
-
if (agentChats.length > 0) result.push({
|
|
771
|
-
agent: agentInfo,
|
|
772
|
-
chats: agentChats
|
|
1495
|
+
if (data.displayName !== void 0) updates.displayName = data.displayName;
|
|
1496
|
+
if (data.delegateMention !== void 0) {
|
|
1497
|
+
if (data.delegateMention !== null) {
|
|
1498
|
+
assertDelegateMentionAllowed(data.type ?? agent.type);
|
|
1499
|
+
await validateDelegateMentionTarget(db, data.delegateMention, agent.organizationId);
|
|
1500
|
+
}
|
|
1501
|
+
updates.delegateMention = data.delegateMention;
|
|
1502
|
+
}
|
|
1503
|
+
if (data.visibility !== void 0) updates.visibility = data.visibility;
|
|
1504
|
+
if (data.metadata !== void 0) updates.metadata = data.metadata;
|
|
1505
|
+
if (data.avatarColorToken !== void 0) updates.avatarColorToken = data.avatarColorToken;
|
|
1506
|
+
if (data.managerId !== void 0) {
|
|
1507
|
+
if (data.managerId === null) throw new BadRequestError("managerId cannot be cleared — every agent must have a manager");
|
|
1508
|
+
const [manager] = await db.select({
|
|
1509
|
+
id: members.id,
|
|
1510
|
+
organizationId: members.organizationId
|
|
1511
|
+
}).from(members).where(eq(members.id, data.managerId)).limit(1);
|
|
1512
|
+
if (!manager) throw new BadRequestError(`Manager "${data.managerId}" not found`);
|
|
1513
|
+
if (manager.organizationId !== agent.organizationId) throw new BadRequestError("Manager must belong to the same organization as the agent");
|
|
1514
|
+
updates.managerId = data.managerId;
|
|
1515
|
+
}
|
|
1516
|
+
if (data.clientId !== void 0 && data.clientId !== null && agent.clientId === null) {
|
|
1517
|
+
const resolvedClientId = await resolveAgentClient(db, {
|
|
1518
|
+
clientId: data.clientId,
|
|
1519
|
+
managerId: updates.managerId ?? agent.managerId,
|
|
1520
|
+
type: agent.type
|
|
773
1521
|
});
|
|
1522
|
+
if (resolvedClientId !== null) updates.clientId = resolvedClientId;
|
|
774
1523
|
}
|
|
775
|
-
|
|
1524
|
+
const [updated] = await db.update(agents).set(updates).where(eq(agents.uuid, agent.uuid)).returning();
|
|
1525
|
+
if (!updated) throw new Error("Unexpected: UPDATE RETURNING produced no row");
|
|
1526
|
+
if (data.managerId !== void 0 && data.managerId !== agent.managerId) await recomputeWatchersForAgent(db, agent.uuid);
|
|
1527
|
+
return updated;
|
|
776
1528
|
}
|
|
777
1529
|
/**
|
|
778
|
-
*
|
|
779
|
-
*
|
|
1530
|
+
* Atomically re-bind an agent to a new client and/or runtime provider.
|
|
1531
|
+
*
|
|
1532
|
+
* Validations: agent must exist and not be human; new client must belong to
|
|
1533
|
+
* the same owner (manager.userId) and same organization; client must report
|
|
1534
|
+
* the requested runtime provider in its capabilities (skipped under `force`).
|
|
1535
|
+
*
|
|
1536
|
+
* Intended caller: PATCH /agents/:uuid/rebind. The Web "Re-bind"
|
|
1537
|
+
* dialog routes both same-client runtime-only switches and cross-client
|
|
1538
|
+
* moves through this single entry.
|
|
1539
|
+
*
|
|
1540
|
+
* NOTE: active sessions on the previous client are not auto-suspended in P1.
|
|
1541
|
+
* P3 will wire in cross-service coordination (inbox + presence + session)
|
|
1542
|
+
* so the destination client can resume cleanly.
|
|
780
1543
|
*/
|
|
781
|
-
async function
|
|
782
|
-
const
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
if (!humanAgent || humanAgent.organizationId !== chat.organizationId) throw new BadRequestError("Agent does not belong to the same organization as the chat");
|
|
789
|
-
await db.transaction(async (tx) => {
|
|
790
|
-
if (wouldUpgradeToGroup(participantAgentIds.length, 1)) await changeChatType(tx, chatId, "group");
|
|
791
|
-
await addChatParticipants(tx, chatId, [{
|
|
792
|
-
agentId: humanAgentId,
|
|
793
|
-
role: "member"
|
|
794
|
-
}], {
|
|
795
|
-
assertHuman: true,
|
|
796
|
-
upgradeWatcherToSpeaker: true
|
|
797
|
-
});
|
|
798
|
-
await recomputeChatWatchers(tx, chatId);
|
|
1544
|
+
async function rebindAgent(db, uuid, data) {
|
|
1545
|
+
const agent = await getAgent(db, uuid);
|
|
1546
|
+
if (agent.type === "human") throw new BadRequestError("Human agents have no runtime — they cannot be re-bound to a client.");
|
|
1547
|
+
const newClientId = await resolveAgentClient(db, {
|
|
1548
|
+
clientId: data.clientId,
|
|
1549
|
+
managerId: agent.managerId,
|
|
1550
|
+
type: agent.type
|
|
799
1551
|
});
|
|
800
|
-
|
|
801
|
-
|
|
1552
|
+
if (newClientId === null) throw new BadRequestError("Rebind requires a non-null clientId.");
|
|
1553
|
+
await ensureClientSupportsRuntimeProvider(db, newClientId, data.runtimeProvider, { force: data.force });
|
|
1554
|
+
const [updated] = await db.update(agents).set({
|
|
1555
|
+
clientId: newClientId,
|
|
1556
|
+
runtimeProvider: data.runtimeProvider,
|
|
1557
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1558
|
+
}).where(eq(agents.uuid, uuid)).returning();
|
|
1559
|
+
if (!updated) throw new Error("Unexpected: UPDATE RETURNING produced no row");
|
|
1560
|
+
return updated;
|
|
802
1561
|
}
|
|
803
1562
|
/**
|
|
804
|
-
*
|
|
805
|
-
* Only allowed if the human agent is a participant.
|
|
806
|
-
*
|
|
807
|
-
* Delegates the participant→watcher transition to `leaveAsParticipant`
|
|
808
|
-
* so admin-side and `/me/chats/:id/leave` share one canonical path. The
|
|
809
|
-
* earlier "recompute then UPDATE-back state" variant violated the design
|
|
810
|
-
* rule that recompute is only for set rebuild — never on a transition
|
|
811
|
-
* path (review #228 issue #2). The returned participant list is fetched
|
|
812
|
-
* after the tx commits, matching the admin route's existing contract.
|
|
1563
|
+
* Reactivate a suspended agent.
|
|
813
1564
|
*/
|
|
814
|
-
async function
|
|
815
|
-
await
|
|
816
|
-
invalidateChatAudience(chatId);
|
|
817
|
-
return db.select().from(chatMembership).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.accessMode, "speaker")));
|
|
818
|
-
}
|
|
819
|
-
async function findOrCreateDirectChat(db, agentAId, agentBId) {
|
|
820
|
-
const ends = await db.select({
|
|
1565
|
+
async function reactivateAgent(db, uuid) {
|
|
1566
|
+
const [existing] = await db.select({
|
|
821
1567
|
uuid: agents.uuid,
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
if (commonChatIds.length > 0) {
|
|
833
|
-
const directChats = await db.select().from(chats).where(and(inArray(chats.id, commonChatIds), eq(chats.type, "direct"), eq(chats.organizationId, orgId))).orderBy(chats.createdAt, chats.id).limit(1);
|
|
834
|
-
if (directChats.length > 0 && directChats[0]) return directChats[0];
|
|
835
|
-
}
|
|
836
|
-
const chatId = randomUUID();
|
|
837
|
-
return db.transaction(async (tx) => {
|
|
838
|
-
const [chat] = await tx.insert(chats).values({
|
|
839
|
-
id: chatId,
|
|
840
|
-
organizationId: orgId,
|
|
841
|
-
type: "direct"
|
|
842
|
-
}).returning();
|
|
843
|
-
await addChatParticipants(tx, chatId, [{
|
|
844
|
-
agentId: agentAId,
|
|
845
|
-
role: "member"
|
|
846
|
-
}, {
|
|
847
|
-
agentId: agentBId,
|
|
848
|
-
role: "member"
|
|
849
|
-
}]);
|
|
850
|
-
await recomputeChatWatchers(tx, chatId);
|
|
851
|
-
if (!chat) throw new Error("Unexpected: INSERT RETURNING produced no row");
|
|
852
|
-
return chat;
|
|
853
|
-
});
|
|
1568
|
+
status: agents.status
|
|
1569
|
+
}).from(agents).where(eq(agents.uuid, uuid)).limit(1);
|
|
1570
|
+
if (!existing || existing.status === AGENT_STATUSES.DELETED) throw new NotFoundError(`Agent "${uuid}" not found`);
|
|
1571
|
+
if (existing.status !== AGENT_STATUSES.SUSPENDED) throw new BadRequestError("Only suspended agents can be reactivated.");
|
|
1572
|
+
const [agent] = await db.update(agents).set({
|
|
1573
|
+
status: AGENT_STATUSES.ACTIVE,
|
|
1574
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1575
|
+
}).where(eq(agents.uuid, uuid)).returning();
|
|
1576
|
+
if (!agent) throw new Error("Unexpected: UPDATE RETURNING produced no row");
|
|
1577
|
+
return agent;
|
|
854
1578
|
}
|
|
855
|
-
/** Agent presence and runtime state. Tracked via WebSocket connections; stale entries are cleaned up using server_instances heartbeat. */
|
|
856
|
-
const agentPresence = pgTable("agent_presence", {
|
|
857
|
-
agentId: text("agent_id").primaryKey().references(() => agents.uuid, { onDelete: "cascade" }),
|
|
858
|
-
status: text("status").notNull().default("offline"),
|
|
859
|
-
instanceId: text("instance_id"),
|
|
860
|
-
connectedAt: timestamp("connected_at", { withTimezone: true }),
|
|
861
|
-
lastSeenAt: timestamp("last_seen_at", { withTimezone: true }).notNull().defaultNow(),
|
|
862
|
-
clientId: text("client_id").references(() => clients.id, { onDelete: "set null" }),
|
|
863
|
-
runtimeType: text("runtime_type"),
|
|
864
|
-
runtimeVersion: text("runtime_version"),
|
|
865
|
-
runtimeState: text("runtime_state"),
|
|
866
|
-
activeSessions: integer("active_sessions"),
|
|
867
|
-
totalSessions: integer("total_sessions"),
|
|
868
|
-
runtimeUpdatedAt: timestamp("runtime_updated_at", { withTimezone: true })
|
|
869
|
-
});
|
|
870
1579
|
/**
|
|
871
|
-
*
|
|
872
|
-
*
|
|
873
|
-
* SQL building blocks reused across routes and tests:
|
|
874
|
-
*
|
|
875
|
-
* - `agentVisibilityCondition` — WHERE clause for "agents visible to a
|
|
876
|
-
* member" (org-visible OR managerId = the caller's member). Composed
|
|
877
|
-
* into list queries that already select from `agents`.
|
|
878
|
-
* - `listAgentsManagedByUser` — cross-org list of agents personally
|
|
879
|
-
* managed by a user; powers the CLI `agent list --remote` view.
|
|
880
|
-
*
|
|
881
|
-
* Visibility is the same for all roles — admin sees the same set as a
|
|
882
|
-
* regular member. Admin privilege is expressed through manageability
|
|
883
|
-
* (`requireAgentAccess(..., "manage")`), not visibility.
|
|
1580
|
+
* Suspend an agent. Once suspended, Rule R-RUN refuses every runtime bind
|
|
1581
|
+
* and every agent-selector-authorised HTTP call.
|
|
884
1582
|
*/
|
|
1583
|
+
async function suspendAgent(db, uuid) {
|
|
1584
|
+
const [agent] = await db.update(agents).set({
|
|
1585
|
+
status: AGENT_STATUSES.SUSPENDED,
|
|
1586
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1587
|
+
}).where(and(eq(agents.uuid, uuid), ne(agents.status, AGENT_STATUSES.DELETED))).returning();
|
|
1588
|
+
if (!agent) throw new NotFoundError(`Agent "${uuid}" not found`);
|
|
1589
|
+
return agent;
|
|
1590
|
+
}
|
|
885
1591
|
/**
|
|
886
|
-
*
|
|
887
|
-
*
|
|
1592
|
+
* Delete an agent. Only allowed when status is "suspended". Sets name to NULL
|
|
1593
|
+
* so the name becomes reusable.
|
|
888
1594
|
*/
|
|
889
|
-
function
|
|
890
|
-
|
|
1595
|
+
async function deleteAgent(db, uuid) {
|
|
1596
|
+
const [existing] = await db.select({
|
|
1597
|
+
uuid: agents.uuid,
|
|
1598
|
+
status: agents.status
|
|
1599
|
+
}).from(agents).where(eq(agents.uuid, uuid)).limit(1);
|
|
1600
|
+
if (!existing || existing.status === AGENT_STATUSES.DELETED) throw new NotFoundError(`Agent "${uuid}" not found`);
|
|
1601
|
+
if (existing.status !== AGENT_STATUSES.SUSPENDED) throw new BadRequestError("Only suspended agents can be deleted. Suspend the agent first.");
|
|
1602
|
+
const [agent] = await db.update(agents).set({
|
|
1603
|
+
status: AGENT_STATUSES.DELETED,
|
|
1604
|
+
name: null,
|
|
1605
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1606
|
+
}).where(eq(agents.uuid, uuid)).returning();
|
|
1607
|
+
await db.delete(adapterConfigs).where(eq(adapterConfigs.agentId, uuid));
|
|
1608
|
+
await db.delete(adapterAgentMappings).where(eq(adapterAgentMappings.agentId, uuid));
|
|
1609
|
+
if (!agent) throw new Error("Unexpected: UPDATE RETURNING produced no row");
|
|
1610
|
+
return agent;
|
|
891
1611
|
}
|
|
892
1612
|
/**
|
|
893
|
-
*
|
|
894
|
-
*
|
|
895
|
-
*
|
|
1613
|
+
* Supported avatar-image MIME types. The web client always uploads WEBP after
|
|
1614
|
+
* its own resize step; we accept PNG/JPEG too so a caller using the raw HTTP
|
|
1615
|
+
* API (curl, scripts) doesn't have to re-encode. Anything else is rejected at
|
|
1616
|
+
* the boundary — we never store an unknown content type.
|
|
896
1617
|
*/
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
runtimeProvider: agents.runtimeProvider,
|
|
907
|
-
clientId: agents.clientId
|
|
908
|
-
}).from(agents).innerJoin(members, eq(agents.managerId, members.id)).where(and(eq(members.userId, userId), eq(members.status, "active"), ne(agents.status, AGENT_STATUSES.DELETED)));
|
|
1618
|
+
const SUPPORTED_AVATAR_IMAGE_MIMES = [
|
|
1619
|
+
"image/webp",
|
|
1620
|
+
"image/png",
|
|
1621
|
+
"image/jpeg"
|
|
1622
|
+
];
|
|
1623
|
+
/** Hard server-side ceiling for the stored bytea blob. Client pre-resizes to ~50KB. */
|
|
1624
|
+
const MAX_AVATAR_IMAGE_BYTES = 512 * 1024;
|
|
1625
|
+
function isSupportedAvatarMime(mime) {
|
|
1626
|
+
return SUPPORTED_AVATAR_IMAGE_MIMES.find((m) => m === mime) !== void 0;
|
|
909
1627
|
}
|
|
910
|
-
/**
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
|
|
923
|
-
}, (table) => [index("idx_messages_chat_time").on(table.chatId, table.createdAt), index("idx_messages_in_reply_to").on(table.inReplyTo)]);
|
|
924
|
-
/** Delivery queue (envelope). One entry per recipient created during message fan-out. Uses SKIP LOCKED for concurrent-safe consumption. */
|
|
925
|
-
const inboxEntries = pgTable("inbox_entries", {
|
|
926
|
-
id: bigserial("id", { mode: "number" }).primaryKey(),
|
|
927
|
-
inboxId: text("inbox_id").notNull(),
|
|
928
|
-
messageId: text("message_id").notNull().references(() => messages.id),
|
|
929
|
-
chatId: text("chat_id"),
|
|
930
|
-
status: text("status").notNull().default("pending"),
|
|
931
|
-
notify: boolean("notify").notNull().default(true),
|
|
932
|
-
retryCount: integer("retry_count").notNull().default(0),
|
|
933
|
-
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
|
934
|
-
deliveredAt: timestamp("delivered_at", { withTimezone: true }),
|
|
935
|
-
ackedAt: timestamp("acked_at", { withTimezone: true })
|
|
936
|
-
}, (table) => [
|
|
937
|
-
unique("uq_inbox_delivery").on(table.inboxId, table.messageId, table.chatId),
|
|
938
|
-
index("idx_inbox_pending").on(table.inboxId, table.createdAt),
|
|
939
|
-
index("idx_inbox_pending_notify").on(table.inboxId, table.createdAt).where(sql`status = 'pending' AND notify = true`),
|
|
940
|
-
index("idx_inbox_chat_silent").on(table.inboxId, table.chatId, table.notify, table.status)
|
|
941
|
-
]);
|
|
942
|
-
/** Server instance heartbeat. Used to detect crashed instances and clean up associated agent_presence records. */
|
|
943
|
-
const serverInstances = pgTable("server_instances", {
|
|
944
|
-
instanceId: text("instance_id").primaryKey(),
|
|
945
|
-
lastHeartbeat: timestamp("last_heartbeat", { withTimezone: true }).notNull().defaultNow()
|
|
946
|
-
});
|
|
947
|
-
/** Common field reset when agent goes offline or is unbound. */
|
|
948
|
-
function runtimeFieldsReset(now) {
|
|
1628
|
+
/**
|
|
1629
|
+
* Fetch the avatar image blob for an agent. Returns `null` when no image
|
|
1630
|
+
* is set (the column is NULL). The data + mime pair is always coherent
|
|
1631
|
+
* (set/cleared together by the service writes below).
|
|
1632
|
+
*/
|
|
1633
|
+
async function getAgentAvatarImage(db, uuid) {
|
|
1634
|
+
const [row] = await db.select({
|
|
1635
|
+
data: agents.avatarImageData,
|
|
1636
|
+
mime: agents.avatarImageMime,
|
|
1637
|
+
updatedAt: agents.avatarImageUpdatedAt
|
|
1638
|
+
}).from(agents).where(and(eq(agents.uuid, uuid), ne(agents.status, AGENT_STATUSES.DELETED))).limit(1);
|
|
1639
|
+
if (!row || !row.data || !row.mime || !row.updatedAt) return null;
|
|
949
1640
|
return {
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
runtimeUpdatedAt: now,
|
|
954
|
-
lastSeenAt: now
|
|
1641
|
+
data: row.data,
|
|
1642
|
+
mime: row.mime,
|
|
1643
|
+
updatedAt: row.updatedAt
|
|
955
1644
|
};
|
|
956
1645
|
}
|
|
957
|
-
|
|
1646
|
+
/** Replace (or set) an agent's avatar image. Validates mime + size. */
|
|
1647
|
+
async function setAgentAvatarImage(db, uuid, data, mime) {
|
|
1648
|
+
if (!isSupportedAvatarMime(mime)) throw new BadRequestError(`Unsupported avatar image type "${mime}". Use PNG, JPEG, or WEBP.`);
|
|
1649
|
+
if (data.length === 0) throw new BadRequestError("Avatar image payload is empty.");
|
|
1650
|
+
if (data.length > 524288) throw new BadRequestError(`Avatar image is too large (${data.length} bytes; max ${MAX_AVATAR_IMAGE_BYTES}).`);
|
|
958
1651
|
const now = /* @__PURE__ */ new Date();
|
|
959
|
-
await db.update(
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
1652
|
+
if ((await db.update(agents).set({
|
|
1653
|
+
avatarImageData: data,
|
|
1654
|
+
avatarImageMime: mime,
|
|
1655
|
+
avatarImageUpdatedAt: now,
|
|
1656
|
+
updatedAt: now
|
|
1657
|
+
}).where(and(eq(agents.uuid, uuid), ne(agents.status, AGENT_STATUSES.DELETED))).returning({ uuid: agents.uuid })).length === 0) throw new NotFoundError(`Agent "${uuid}" not found`);
|
|
1658
|
+
return now;
|
|
964
1659
|
}
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
1660
|
+
/** Clear an agent's avatar image (falls back to color + initial). */
|
|
1661
|
+
async function clearAgentAvatarImage(db, uuid) {
|
|
1662
|
+
if ((await db.update(agents).set({
|
|
1663
|
+
avatarImageData: null,
|
|
1664
|
+
avatarImageMime: null,
|
|
1665
|
+
avatarImageUpdatedAt: null,
|
|
1666
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1667
|
+
}).where(and(eq(agents.uuid, uuid), ne(agents.status, AGENT_STATUSES.DELETED))).returning({ uuid: agents.uuid })).length === 0) throw new NotFoundError(`Agent "${uuid}" not found`);
|
|
968
1668
|
}
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
1669
|
+
/**
|
|
1670
|
+
* Server-side lifecycle tracker for `format=question` messages.
|
|
1671
|
+
*
|
|
1672
|
+
* Written when an agent emits a question through `sendMessage`; status
|
|
1673
|
+
* flips to `answered` when the user posts an answer, or to `superseded`
|
|
1674
|
+
* when the chat session is archived or its client is claimed away.
|
|
1675
|
+
*
|
|
1676
|
+
* Per the team's "integrity in service layer" convention, NO foreign-key
|
|
1677
|
+
* constraints — referential integrity is enforced by the question
|
|
1678
|
+
* service itself (chat-id / agent-id / message-id are validated at
|
|
1679
|
+
* write time and the lifecycle hooks supersede orphaned rows).
|
|
1680
|
+
*/
|
|
1681
|
+
const pendingQuestions = pgTable("pending_questions", {
|
|
1682
|
+
id: text("id").primaryKey(),
|
|
1683
|
+
agentId: text("agent_id").notNull(),
|
|
1684
|
+
chatId: text("chat_id").notNull(),
|
|
1685
|
+
messageId: text("message_id").notNull(),
|
|
1686
|
+
status: text("status").notNull().default("pending"),
|
|
1687
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
|
1688
|
+
answeredAt: timestamp("answered_at", { withTimezone: true }),
|
|
1689
|
+
supersededAt: timestamp("superseded_at", { withTimezone: true }),
|
|
1690
|
+
supersededReason: text("superseded_reason")
|
|
1691
|
+
}, (table) => [index("idx_pending_questions_agent_status").on(table.agentId, table.status), index("idx_pending_questions_chat_status").on(table.chatId, table.status)]);
|
|
1692
|
+
/**
|
|
1693
|
+
* Upsert session state + refresh presence aggregates + NOTIFY.
|
|
1694
|
+
*
|
|
1695
|
+
* `agent_chat_sessions.(agent_id, chat_id)` is a single-row "current session
|
|
1696
|
+
* state" cache, not a session history log. A new runtime session starting on
|
|
1697
|
+
* the same (agent, chat) pair MUST overwrite whatever ended before — including
|
|
1698
|
+
* an `evicted` row left by a previous terminate. The previous "revival
|
|
1699
|
+
* defense" conflated two concerns: "this runtime session ended" (which is
|
|
1700
|
+
* what `evicted` actually means) and "this chat is permanently archived for
|
|
1701
|
+
* this agent" (a chat-level decision that should live on `chats`, not here).
|
|
1702
|
+
* See proposals/hub-agent-messaging-reply-and-mentions §M2-session-lifecycle.
|
|
1703
|
+
*
|
|
1704
|
+
* Presence row contract: this function tolerates a missing `agent_presence`
|
|
1705
|
+
* row by using `INSERT ... ON CONFLICT DO UPDATE`. The predictive-write path
|
|
1706
|
+
* (sendMessage on first message) may target an agent whose client has never
|
|
1707
|
+
* bound, so a prior `update agent_presence ... where agentId` would silently
|
|
1708
|
+
* drop the activeSessions/totalSessions refresh. See PR #198 review §2.
|
|
1709
|
+
*/
|
|
1710
|
+
async function upsertSessionState(db, agentId, chatId, state, organizationId, notifier, options) {
|
|
1711
|
+
const now = /* @__PURE__ */ new Date();
|
|
1712
|
+
let wrote = false;
|
|
1713
|
+
await db.transaction(async (tx) => {
|
|
1714
|
+
await tx.insert(agentChatSessions).values({
|
|
1715
|
+
agentId,
|
|
1716
|
+
chatId,
|
|
1717
|
+
state,
|
|
1718
|
+
updatedAt: now
|
|
1719
|
+
}).onConflictDoUpdate({
|
|
1720
|
+
target: [agentChatSessions.agentId, agentChatSessions.chatId],
|
|
1721
|
+
set: {
|
|
1722
|
+
state,
|
|
1723
|
+
updatedAt: now
|
|
1724
|
+
},
|
|
1725
|
+
setWhere: ne(agentChatSessions.state, state)
|
|
1726
|
+
});
|
|
1727
|
+
const [counts] = await tx.select({
|
|
1728
|
+
active: sql`count(*) FILTER (WHERE ${agentChatSessions.state} = 'active')::int`,
|
|
1729
|
+
total: sql`count(*) FILTER (WHERE ${agentChatSessions.state} != 'evicted')::int`
|
|
1730
|
+
}).from(agentChatSessions).where(eq(agentChatSessions.agentId, agentId));
|
|
1731
|
+
const activeSessions = counts?.active ?? 0;
|
|
1732
|
+
const totalSessions = counts?.total ?? 0;
|
|
1733
|
+
const presenceSet = options?.touchPresenceLastSeen ?? true ? {
|
|
1734
|
+
activeSessions,
|
|
1735
|
+
totalSessions,
|
|
1736
|
+
lastSeenAt: now
|
|
1737
|
+
} : {
|
|
1738
|
+
activeSessions,
|
|
1739
|
+
totalSessions
|
|
1740
|
+
};
|
|
1741
|
+
await tx.insert(agentPresence).values({
|
|
1742
|
+
agentId,
|
|
1743
|
+
activeSessions,
|
|
1744
|
+
totalSessions
|
|
1745
|
+
}).onConflictDoUpdate({
|
|
1746
|
+
target: [agentPresence.agentId],
|
|
1747
|
+
set: presenceSet
|
|
1748
|
+
});
|
|
1749
|
+
wrote = true;
|
|
1750
|
+
});
|
|
1751
|
+
if (wrote && notifier) notifier.notifySessionStateChange(agentId, chatId, state, organizationId).catch(() => {});
|
|
972
1752
|
}
|
|
973
|
-
async function
|
|
1753
|
+
async function resetActivity(db, agentId) {
|
|
974
1754
|
const now = /* @__PURE__ */ new Date();
|
|
975
|
-
await db.
|
|
976
|
-
agentId,
|
|
977
|
-
status: "online",
|
|
978
|
-
instanceId: data.instanceId,
|
|
979
|
-
clientId: data.clientId,
|
|
980
|
-
runtimeType: data.runtimeType,
|
|
981
|
-
runtimeVersion: data.runtimeVersion ?? null,
|
|
982
|
-
runtimeState: "idle",
|
|
983
|
-
connectedAt: now,
|
|
984
|
-
lastSeenAt: now,
|
|
985
|
-
runtimeUpdatedAt: now
|
|
986
|
-
}).onConflictDoUpdate({
|
|
987
|
-
target: agentPresence.agentId,
|
|
988
|
-
set: {
|
|
989
|
-
status: "online",
|
|
990
|
-
instanceId: data.instanceId,
|
|
991
|
-
clientId: data.clientId,
|
|
992
|
-
runtimeType: data.runtimeType,
|
|
993
|
-
runtimeVersion: data.runtimeVersion ?? null,
|
|
994
|
-
runtimeState: "idle",
|
|
995
|
-
activeSessions: null,
|
|
996
|
-
totalSessions: null,
|
|
997
|
-
connectedAt: now,
|
|
998
|
-
lastSeenAt: now,
|
|
999
|
-
runtimeUpdatedAt: now
|
|
1000
|
-
}
|
|
1001
|
-
});
|
|
1002
|
-
}
|
|
1003
|
-
async function unbindAgent(db, agentId) {
|
|
1004
|
-
const now = /* @__PURE__ */ new Date();
|
|
1005
|
-
await db.update(agentPresence).set({
|
|
1006
|
-
status: "offline",
|
|
1007
|
-
clientId: null,
|
|
1008
|
-
...runtimeFieldsReset(now)
|
|
1009
|
-
}).where(eq(agentPresence.agentId, agentId));
|
|
1010
|
-
}
|
|
1011
|
-
/** Set runtime state directly from client-reported value.
|
|
1012
|
-
*
|
|
1013
|
-
* When an org-scoped notifier is provided, emit a PG NOTIFY on the
|
|
1014
|
-
* `runtime_state_changes` channel so the pulse aggregator (and any future
|
|
1015
|
-
* admin-side consumers) can observe the transition. Fire-and-forget to match
|
|
1016
|
-
* notifier semantics elsewhere in this module. */
|
|
1017
|
-
async function setRuntimeState(db, agentId, runtimeState, options) {
|
|
1018
|
-
const now = /* @__PURE__ */ new Date();
|
|
1019
|
-
await db.update(agentPresence).set({
|
|
1020
|
-
runtimeState,
|
|
1021
|
-
runtimeUpdatedAt: now,
|
|
1022
|
-
lastSeenAt: now
|
|
1023
|
-
}).where(eq(agentPresence.agentId, agentId));
|
|
1024
|
-
if (options?.notifier && options.organizationId) options.notifier.notifyRuntimeStateChange(agentId, runtimeState, options.organizationId).catch(() => {});
|
|
1025
|
-
}
|
|
1026
|
-
/** Touch agent last_seen_at on heartbeat (per-agent liveness). */
|
|
1027
|
-
async function touchAgent(db, agentId) {
|
|
1028
|
-
await db.update(agentPresence).set({ lastSeenAt: /* @__PURE__ */ new Date() }).where(eq(agentPresence.agentId, agentId));
|
|
1029
|
-
}
|
|
1030
|
-
async function heartbeatInstance(db, instanceId) {
|
|
1031
|
-
await db.insert(serverInstances).values({
|
|
1032
|
-
instanceId,
|
|
1033
|
-
lastHeartbeat: /* @__PURE__ */ new Date()
|
|
1034
|
-
}).onConflictDoUpdate({
|
|
1035
|
-
target: serverInstances.instanceId,
|
|
1036
|
-
set: { lastHeartbeat: /* @__PURE__ */ new Date() }
|
|
1037
|
-
});
|
|
1038
|
-
}
|
|
1039
|
-
/**
|
|
1040
|
-
* M1: Mark agents as offline whose last_seen_at is older than staleSeconds.
|
|
1041
|
-
* Unlike cleanupStalePresence (which checks instance liveness), this checks
|
|
1042
|
-
* per-agent heartbeat liveness — detecting agents that stopped heartbeating
|
|
1043
|
-
* while the client process may still be alive.
|
|
1044
|
-
*
|
|
1045
|
-
* Returns the list of agent IDs that were marked stale (for notification in Step 6).
|
|
1046
|
-
*/
|
|
1047
|
-
async function markStaleAgents(db, staleSeconds = 60) {
|
|
1048
|
-
return (await db.execute(sql`
|
|
1049
|
-
UPDATE agent_presence SET
|
|
1050
|
-
status = 'offline',
|
|
1051
|
-
client_id = NULL,
|
|
1052
|
-
runtime_state = NULL,
|
|
1053
|
-
active_sessions = NULL,
|
|
1054
|
-
total_sessions = NULL,
|
|
1055
|
-
runtime_updated_at = NOW()
|
|
1056
|
-
WHERE status = 'online'
|
|
1057
|
-
AND last_seen_at < NOW() - make_interval(secs => ${staleSeconds})
|
|
1058
|
-
RETURNING agent_id
|
|
1059
|
-
`)).map((r) => r.agent_id);
|
|
1060
|
-
}
|
|
1061
|
-
async function cleanupStalePresence(db, staleSeconds = 60) {
|
|
1062
|
-
return (await db.execute(sql`
|
|
1063
|
-
UPDATE agent_presence SET status = 'offline', instance_id = NULL,
|
|
1064
|
-
runtime_state = NULL,
|
|
1065
|
-
active_sessions = NULL, total_sessions = NULL,
|
|
1066
|
-
runtime_updated_at = NOW()
|
|
1067
|
-
WHERE instance_id IN (
|
|
1068
|
-
SELECT instance_id FROM server_instances
|
|
1069
|
-
WHERE last_heartbeat < NOW() - make_interval(secs => ${staleSeconds})
|
|
1070
|
-
)
|
|
1071
|
-
AND status = 'online'
|
|
1072
|
-
RETURNING agent_id
|
|
1073
|
-
`)).length;
|
|
1074
|
-
}
|
|
1075
|
-
/** Per-session state snapshot. One row per (agent, chat) pair, upserted on each session:state message. */
|
|
1076
|
-
const agentChatSessions = pgTable("agent_chat_sessions", {
|
|
1077
|
-
agentId: text("agent_id").notNull().references(() => agents.uuid, { onDelete: "cascade" }),
|
|
1078
|
-
chatId: text("chat_id").notNull().references(() => chats.id, { onDelete: "cascade" }),
|
|
1079
|
-
state: text("state").notNull(),
|
|
1080
|
-
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
|
|
1081
|
-
}, (table) => [primaryKey({ columns: [table.agentId, table.chatId] })]);
|
|
1082
|
-
/**
|
|
1083
|
-
* Upsert session state + refresh presence aggregates + NOTIFY.
|
|
1084
|
-
*
|
|
1085
|
-
* `agent_chat_sessions.(agent_id, chat_id)` is a single-row "current session
|
|
1086
|
-
* state" cache, not a session history log. A new runtime session starting on
|
|
1087
|
-
* the same (agent, chat) pair MUST overwrite whatever ended before — including
|
|
1088
|
-
* an `evicted` row left by a previous terminate. The previous "revival
|
|
1089
|
-
* defense" conflated two concerns: "this runtime session ended" (which is
|
|
1090
|
-
* what `evicted` actually means) and "this chat is permanently archived for
|
|
1091
|
-
* this agent" (a chat-level decision that should live on `chats`, not here).
|
|
1092
|
-
* See proposals/hub-agent-messaging-reply-and-mentions §M2-session-lifecycle.
|
|
1093
|
-
*
|
|
1094
|
-
* Presence row contract: this function tolerates a missing `agent_presence`
|
|
1095
|
-
* row by using `INSERT ... ON CONFLICT DO UPDATE`. The predictive-write path
|
|
1096
|
-
* (sendMessage on first message) may target an agent whose client has never
|
|
1097
|
-
* bound, so a prior `update agent_presence ... where agentId` would silently
|
|
1098
|
-
* drop the activeSessions/totalSessions refresh. See PR #198 review §2.
|
|
1099
|
-
*/
|
|
1100
|
-
async function upsertSessionState(db, agentId, chatId, state, organizationId, notifier, options) {
|
|
1101
|
-
const now = /* @__PURE__ */ new Date();
|
|
1102
|
-
let wrote = false;
|
|
1103
|
-
await db.transaction(async (tx) => {
|
|
1104
|
-
await tx.insert(agentChatSessions).values({
|
|
1105
|
-
agentId,
|
|
1106
|
-
chatId,
|
|
1107
|
-
state,
|
|
1108
|
-
updatedAt: now
|
|
1109
|
-
}).onConflictDoUpdate({
|
|
1110
|
-
target: [agentChatSessions.agentId, agentChatSessions.chatId],
|
|
1111
|
-
set: {
|
|
1112
|
-
state,
|
|
1113
|
-
updatedAt: now
|
|
1114
|
-
},
|
|
1115
|
-
setWhere: ne(agentChatSessions.state, state)
|
|
1116
|
-
});
|
|
1117
|
-
const [counts] = await tx.select({
|
|
1118
|
-
active: sql`count(*) FILTER (WHERE ${agentChatSessions.state} = 'active')::int`,
|
|
1119
|
-
total: sql`count(*) FILTER (WHERE ${agentChatSessions.state} != 'evicted')::int`
|
|
1120
|
-
}).from(agentChatSessions).where(eq(agentChatSessions.agentId, agentId));
|
|
1121
|
-
const activeSessions = counts?.active ?? 0;
|
|
1122
|
-
const totalSessions = counts?.total ?? 0;
|
|
1123
|
-
const presenceSet = options?.touchPresenceLastSeen ?? true ? {
|
|
1124
|
-
activeSessions,
|
|
1125
|
-
totalSessions,
|
|
1126
|
-
lastSeenAt: now
|
|
1127
|
-
} : {
|
|
1128
|
-
activeSessions,
|
|
1129
|
-
totalSessions
|
|
1130
|
-
};
|
|
1131
|
-
await tx.insert(agentPresence).values({
|
|
1132
|
-
agentId,
|
|
1133
|
-
activeSessions,
|
|
1134
|
-
totalSessions
|
|
1135
|
-
}).onConflictDoUpdate({
|
|
1136
|
-
target: [agentPresence.agentId],
|
|
1137
|
-
set: presenceSet
|
|
1138
|
-
});
|
|
1139
|
-
wrote = true;
|
|
1140
|
-
});
|
|
1141
|
-
if (wrote && notifier) notifier.notifySessionStateChange(agentId, chatId, state, organizationId).catch(() => {});
|
|
1142
|
-
}
|
|
1143
|
-
async function resetActivity(db, agentId) {
|
|
1144
|
-
const now = /* @__PURE__ */ new Date();
|
|
1145
|
-
await db.update(agentPresence).set({
|
|
1755
|
+
await db.update(agentPresence).set({
|
|
1146
1756
|
runtimeState: "idle",
|
|
1147
1757
|
runtimeUpdatedAt: now
|
|
1148
1758
|
}).where(eq(agentPresence.agentId, agentId));
|
|
@@ -1225,7 +1835,7 @@ async function listAgentsWithRuntime(db, scope) {
|
|
|
1225
1835
|
* - Mention candidate set is `chat_membership` speakers only;
|
|
1226
1836
|
* watchers are not direct `@`-mention targets.
|
|
1227
1837
|
*/
|
|
1228
|
-
const { ACTIVE, ARCHIVED } = CHAT_ENGAGEMENT_STATUSES;
|
|
1838
|
+
const { ACTIVE: ACTIVE$1, ARCHIVED: ARCHIVED$1 } = CHAT_ENGAGEMENT_STATUSES;
|
|
1229
1839
|
let dispatcher = null;
|
|
1230
1840
|
function registerChatMessageDispatcher(fn) {
|
|
1231
1841
|
dispatcher = fn;
|
|
@@ -1260,9 +1870,9 @@ async function applyAfterFanOut(tx, input) {
|
|
|
1260
1870
|
}).where(eq(chats.id, chatId));
|
|
1261
1871
|
await tx.execute(sql`
|
|
1262
1872
|
UPDATE chat_user_state
|
|
1263
|
-
SET engagement_status = ${ACTIVE}
|
|
1873
|
+
SET engagement_status = ${ACTIVE$1}
|
|
1264
1874
|
WHERE chat_id = ${chatId}
|
|
1265
|
-
AND engagement_status = ${ARCHIVED}
|
|
1875
|
+
AND engagement_status = ${ARCHIVED$1}
|
|
1266
1876
|
`);
|
|
1267
1877
|
if (mentionedAgentIds.length === 0) return;
|
|
1268
1878
|
const mentionedList = sql.join(mentionedAgentIds.map((id) => sql`${id}`), sql`, `);
|
|
@@ -1291,791 +1901,1985 @@ async function applyAfterFanOut(tx, input) {
|
|
|
1291
1901
|
DO UPDATE SET unread_mention_count = chat_user_state.unread_mention_count + 1
|
|
1292
1902
|
`);
|
|
1293
1903
|
}
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
}
|
|
1317
|
-
|
|
1318
|
-
const
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
* emit a JSON-stringified `AdminBroadcastPayload`; every server instance
|
|
1332
|
-
* LISTENs and hands the envelope to its local admin-socket fanout. Keeps
|
|
1333
|
-
* cross-instance and single-instance code paths identical from the admin WS
|
|
1334
|
-
* route's perspective.
|
|
1335
|
-
*/
|
|
1336
|
-
const ADMIN_BROADCAST_CHANNEL = "admin_broadcast_envelopes";
|
|
1337
|
-
function createNotifier(listenClient) {
|
|
1338
|
-
const subscriptions = /* @__PURE__ */ new Map();
|
|
1339
|
-
const configChangeHandlers = [];
|
|
1340
|
-
const sessionStateChangeHandlers = [];
|
|
1341
|
-
const sessionEventHandlers = [];
|
|
1342
|
-
const runtimeStateChangeHandlers = [];
|
|
1343
|
-
const chatMessageHandlers = [];
|
|
1344
|
-
const adminBroadcastHandlers = [];
|
|
1345
|
-
let unlistenInboxFn = null;
|
|
1346
|
-
let unlistenConfigFn = null;
|
|
1347
|
-
let unlistenSessionStateFn = null;
|
|
1348
|
-
let unlistenSessionEventFn = null;
|
|
1349
|
-
let unlistenRuntimeStateFn = null;
|
|
1350
|
-
let unlistenChatMessageFn = null;
|
|
1351
|
-
let unlistenAdminBroadcastFn = null;
|
|
1352
|
-
function handleNotification(payload) {
|
|
1353
|
-
const sepIdx = payload.indexOf(":");
|
|
1354
|
-
if (sepIdx === -1) return;
|
|
1355
|
-
const inboxId = payload.slice(0, sepIdx);
|
|
1356
|
-
const messageId = payload.slice(sepIdx + 1);
|
|
1357
|
-
const sockets = subscriptions.get(inboxId);
|
|
1358
|
-
if (!sockets) return;
|
|
1359
|
-
const doorbellFrame = JSON.stringify({
|
|
1360
|
-
type: "new_message",
|
|
1361
|
-
inboxId,
|
|
1362
|
-
messageId
|
|
1363
|
-
});
|
|
1364
|
-
for (const [ws, pushHandler] of sockets) {
|
|
1365
|
-
if (ws.readyState !== ws.OPEN) continue;
|
|
1366
|
-
if (pushHandler) Promise.resolve(pushHandler(messageId)).catch(() => {});
|
|
1367
|
-
else ws.send(doorbellFrame);
|
|
1904
|
+
const log$1 = createLogger("message");
|
|
1905
|
+
async function sendMessage(db, chatId, senderId, data, options = {}) {
|
|
1906
|
+
return withSpan("inbox.enqueue", messageAttrs({
|
|
1907
|
+
chatId,
|
|
1908
|
+
senderAgentId: senderId,
|
|
1909
|
+
source: data.source ?? void 0
|
|
1910
|
+
}), () => sendMessageInner(db, chatId, senderId, data, options));
|
|
1911
|
+
}
|
|
1912
|
+
async function sendMessageInner(db, chatId, senderId, data, options) {
|
|
1913
|
+
const txResult = await db.transaction(async (tx) => {
|
|
1914
|
+
const [participants, [chatRow], [senderRow]] = await Promise.all([
|
|
1915
|
+
tx.select({
|
|
1916
|
+
agentId: chatMembership.agentId,
|
|
1917
|
+
inboxId: agents.inboxId,
|
|
1918
|
+
mode: chatMembership.mode,
|
|
1919
|
+
name: agents.name
|
|
1920
|
+
}).from(chatMembership).innerJoin(agents, eq(chatMembership.agentId, agents.uuid)).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.accessMode, "speaker"))),
|
|
1921
|
+
tx.select({ type: chats.type }).from(chats).where(eq(chats.id, chatId)).limit(1),
|
|
1922
|
+
tx.select({
|
|
1923
|
+
inboxId: agents.inboxId,
|
|
1924
|
+
organizationId: agents.organizationId,
|
|
1925
|
+
type: agents.type
|
|
1926
|
+
}).from(agents).where(eq(agents.uuid, senderId)).limit(1)
|
|
1927
|
+
]);
|
|
1928
|
+
const chatType = chatRow?.type ?? null;
|
|
1929
|
+
if (!senderRow) throw new NotFoundError(`Sender agent "${senderId}" not found`);
|
|
1930
|
+
let effectiveContent = data.content;
|
|
1931
|
+
if (senderRow.type !== "human" && typeof effectiveContent === "string") {
|
|
1932
|
+
const unwrapped = maybeUnwrapDoubleEncoded(effectiveContent);
|
|
1933
|
+
if (unwrapped !== null) {
|
|
1934
|
+
log$1.warn({
|
|
1935
|
+
metric: "double_encoded_content_unwrapped_total",
|
|
1936
|
+
chatId,
|
|
1937
|
+
senderId
|
|
1938
|
+
}, "agent sent JSON-encoded string content — unwrapping to restore markdown rendering");
|
|
1939
|
+
effectiveContent = unwrapped;
|
|
1940
|
+
}
|
|
1368
1941
|
}
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
},
|
|
1396
|
-
async notifySessionStateChange(agentId, chatId, state, organizationId) {
|
|
1397
|
-
try {
|
|
1398
|
-
await listenClient`SELECT pg_notify(${SESSION_STATE_CHANNEL}, ${`${agentId}:${chatId}:${state}:${organizationId}`})`;
|
|
1399
|
-
} catch {}
|
|
1400
|
-
},
|
|
1401
|
-
async notifySessionEvent(agentId, chatId, kind, organizationId) {
|
|
1402
|
-
try {
|
|
1403
|
-
await listenClient`SELECT pg_notify(${SESSION_EVENT_CHANNEL}, ${`${agentId}:${chatId}:${kind}:${organizationId}`})`;
|
|
1404
|
-
} catch {}
|
|
1405
|
-
},
|
|
1406
|
-
async notifyRuntimeStateChange(agentId, state, organizationId) {
|
|
1407
|
-
try {
|
|
1408
|
-
await listenClient`SELECT pg_notify(${RUNTIME_STATE_CHANNEL}, ${`${agentId}:${state}:${organizationId}`})`;
|
|
1409
|
-
} catch {}
|
|
1410
|
-
},
|
|
1411
|
-
async notifyChatMessage(chatId, messageId) {
|
|
1412
|
-
try {
|
|
1413
|
-
await listenClient`SELECT pg_notify(${CHAT_MESSAGE_CHANNEL}, ${`${chatId}:${messageId}`})`;
|
|
1414
|
-
} catch {}
|
|
1415
|
-
},
|
|
1416
|
-
async notifyAdminBroadcast(payload) {
|
|
1417
|
-
let encoded;
|
|
1418
|
-
try {
|
|
1419
|
-
encoded = JSON.stringify(payload);
|
|
1420
|
-
} catch {
|
|
1421
|
-
return;
|
|
1422
|
-
}
|
|
1423
|
-
if (encoded.length > 7500) {
|
|
1424
|
-
console.error(`[notifier] admin broadcast payload too large (${encoded.length} bytes); refusing to NOTIFY`);
|
|
1425
|
-
return;
|
|
1426
|
-
}
|
|
1427
|
-
try {
|
|
1428
|
-
await listenClient`SELECT pg_notify(${ADMIN_BROADCAST_CHANNEL}, ${encoded})`;
|
|
1429
|
-
} catch {}
|
|
1430
|
-
},
|
|
1431
|
-
async pushFrameToInbox(inboxId, frame) {
|
|
1432
|
-
const map = subscriptions.get(inboxId);
|
|
1433
|
-
if (!map) return 0;
|
|
1434
|
-
let queued = 0;
|
|
1435
|
-
const pending = [];
|
|
1436
|
-
for (const ws of map.keys()) {
|
|
1437
|
-
if (ws.readyState !== ws.OPEN) continue;
|
|
1438
|
-
pending.push(new Promise((resolve) => {
|
|
1439
|
-
ws.send(frame, (err) => {
|
|
1440
|
-
if (!err) queued += 1;
|
|
1441
|
-
resolve();
|
|
1442
|
-
});
|
|
1443
|
-
}));
|
|
1444
|
-
}
|
|
1445
|
-
await Promise.all(pending);
|
|
1446
|
-
return queued;
|
|
1447
|
-
},
|
|
1448
|
-
onConfigChange(handler) {
|
|
1449
|
-
configChangeHandlers.push(handler);
|
|
1450
|
-
},
|
|
1451
|
-
onSessionStateChange(handler) {
|
|
1452
|
-
sessionStateChangeHandlers.push(handler);
|
|
1453
|
-
},
|
|
1454
|
-
onSessionEvent(handler) {
|
|
1455
|
-
sessionEventHandlers.push(handler);
|
|
1456
|
-
},
|
|
1457
|
-
onRuntimeStateChange(handler) {
|
|
1458
|
-
runtimeStateChangeHandlers.push(handler);
|
|
1459
|
-
},
|
|
1460
|
-
onChatMessage(handler) {
|
|
1461
|
-
chatMessageHandlers.push(handler);
|
|
1462
|
-
},
|
|
1463
|
-
onAdminBroadcast(handler) {
|
|
1464
|
-
adminBroadcastHandlers.push(handler);
|
|
1465
|
-
},
|
|
1466
|
-
async start() {
|
|
1467
|
-
unlistenInboxFn = (await listenClient.listen(INBOX_CHANNEL, (payload) => {
|
|
1468
|
-
if (payload) handleNotification(payload);
|
|
1469
|
-
})).unlisten;
|
|
1470
|
-
unlistenConfigFn = (await listenClient.listen(CONFIG_CHANNEL, (payload) => {
|
|
1471
|
-
if (payload) for (const handler of configChangeHandlers) handler(payload);
|
|
1472
|
-
})).unlisten;
|
|
1473
|
-
unlistenSessionStateFn = (await listenClient.listen(SESSION_STATE_CHANNEL, (payload) => {
|
|
1474
|
-
if (payload) {
|
|
1475
|
-
const firstSep = payload.indexOf(":");
|
|
1476
|
-
const secondSep = payload.indexOf(":", firstSep + 1);
|
|
1477
|
-
const thirdSep = payload.indexOf(":", secondSep + 1);
|
|
1478
|
-
if (firstSep > 0 && secondSep > firstSep && thirdSep > secondSep) {
|
|
1479
|
-
const agentId = payload.slice(0, firstSep);
|
|
1480
|
-
const chatId = payload.slice(firstSep + 1, secondSep);
|
|
1481
|
-
const state = payload.slice(secondSep + 1, thirdSep);
|
|
1482
|
-
const organizationId = payload.slice(thirdSep + 1);
|
|
1483
|
-
for (const handler of sessionStateChangeHandlers) handler({
|
|
1484
|
-
agentId,
|
|
1485
|
-
chatId,
|
|
1486
|
-
state,
|
|
1487
|
-
organizationId
|
|
1488
|
-
});
|
|
1489
|
-
}
|
|
1490
|
-
}
|
|
1491
|
-
})).unlisten;
|
|
1492
|
-
unlistenSessionEventFn = (await listenClient.listen(SESSION_EVENT_CHANNEL, (payload) => {
|
|
1493
|
-
if (payload) {
|
|
1494
|
-
const firstSep = payload.indexOf(":");
|
|
1495
|
-
const secondSep = payload.indexOf(":", firstSep + 1);
|
|
1496
|
-
const thirdSep = payload.indexOf(":", secondSep + 1);
|
|
1497
|
-
if (firstSep > 0 && secondSep > firstSep && thirdSep > secondSep) {
|
|
1498
|
-
const agentId = payload.slice(0, firstSep);
|
|
1499
|
-
const chatId = payload.slice(firstSep + 1, secondSep);
|
|
1500
|
-
const kind = payload.slice(secondSep + 1, thirdSep);
|
|
1501
|
-
const organizationId = payload.slice(thirdSep + 1);
|
|
1502
|
-
for (const handler of sessionEventHandlers) try {
|
|
1503
|
-
handler({
|
|
1504
|
-
agentId,
|
|
1505
|
-
chatId,
|
|
1506
|
-
kind,
|
|
1507
|
-
organizationId
|
|
1508
|
-
});
|
|
1509
|
-
} catch {}
|
|
1510
|
-
}
|
|
1511
|
-
}
|
|
1512
|
-
})).unlisten;
|
|
1513
|
-
unlistenRuntimeStateFn = (await listenClient.listen(RUNTIME_STATE_CHANNEL, (payload) => {
|
|
1514
|
-
if (payload) {
|
|
1515
|
-
const firstSep = payload.indexOf(":");
|
|
1516
|
-
const secondSep = payload.indexOf(":", firstSep + 1);
|
|
1517
|
-
if (firstSep > 0 && secondSep > firstSep) {
|
|
1518
|
-
const agentId = payload.slice(0, firstSep);
|
|
1519
|
-
const state = payload.slice(firstSep + 1, secondSep);
|
|
1520
|
-
const organizationId = payload.slice(secondSep + 1);
|
|
1521
|
-
for (const handler of runtimeStateChangeHandlers) handler({
|
|
1522
|
-
agentId,
|
|
1523
|
-
state,
|
|
1524
|
-
organizationId
|
|
1525
|
-
});
|
|
1526
|
-
}
|
|
1527
|
-
}
|
|
1528
|
-
})).unlisten;
|
|
1529
|
-
unlistenChatMessageFn = (await listenClient.listen(CHAT_MESSAGE_CHANNEL, (payload) => {
|
|
1530
|
-
if (!payload) return;
|
|
1531
|
-
const sep = payload.indexOf(":");
|
|
1532
|
-
if (sep <= 0) return;
|
|
1533
|
-
const chatId = payload.slice(0, sep);
|
|
1534
|
-
const messageId = payload.slice(sep + 1);
|
|
1535
|
-
for (const handler of chatMessageHandlers) try {
|
|
1536
|
-
handler({
|
|
1537
|
-
chatId,
|
|
1538
|
-
messageId
|
|
1539
|
-
});
|
|
1540
|
-
} catch {}
|
|
1541
|
-
})).unlisten;
|
|
1542
|
-
unlistenAdminBroadcastFn = (await listenClient.listen(ADMIN_BROADCAST_CHANNEL, (payload) => {
|
|
1543
|
-
if (!payload) return;
|
|
1544
|
-
let parsed;
|
|
1545
|
-
try {
|
|
1546
|
-
parsed = JSON.parse(payload);
|
|
1547
|
-
} catch {
|
|
1548
|
-
return;
|
|
1942
|
+
if (data.replyToInbox !== void 0 && data.replyToInbox !== null) {
|
|
1943
|
+
if (senderRow.inboxId !== data.replyToInbox) throw new BadRequestError("replyToInbox must reference the sender's own inbox");
|
|
1944
|
+
}
|
|
1945
|
+
const incomingMeta = data.metadata ?? {};
|
|
1946
|
+
const explicitMentionsRaw = incomingMeta.mentions;
|
|
1947
|
+
const explicitMentions = Array.isArray(explicitMentionsRaw) ? explicitMentionsRaw.filter((m) => typeof m === "string") : [];
|
|
1948
|
+
const contentText = typeof effectiveContent === "string" ? effectiveContent : "";
|
|
1949
|
+
const resolved = contentText ? extractMentions(contentText, participants) : [];
|
|
1950
|
+
const mergedMentions = [...new Set([...explicitMentions, ...resolved])];
|
|
1951
|
+
const metadataToStore = mergedMentions.length > 0 ? {
|
|
1952
|
+
...incomingMeta,
|
|
1953
|
+
mentions: mergedMentions
|
|
1954
|
+
} : incomingMeta;
|
|
1955
|
+
const dmAutoProjection = chatType === "direct" ? [...new Set([...mergedMentions, ...participants.filter((p) => p.agentId !== senderId).map((p) => p.agentId)])] : mergedMentions;
|
|
1956
|
+
const isAgentFinalText = data.purpose === "agent-final-text";
|
|
1957
|
+
if (options.enforceGroupMention && chatType === "group" && !isAgentFinalText) {
|
|
1958
|
+
if (mergedMentions.filter((id) => id !== senderId).length === 0) throw new BadRequestError("Sending to a group chat requires an explicit @mention. Use `first-tree-hub chat send <name>` to message a single agent, or @<name> in the content to address one or more group members.");
|
|
1959
|
+
}
|
|
1960
|
+
if (options.enforceGroupMention && !isAgentFinalText && typeof effectiveContent === "string") {
|
|
1961
|
+
const rawTokens = scanMentionTokens(effectiveContent);
|
|
1962
|
+
if (rawTokens.length > 0) {
|
|
1963
|
+
const speakerNames = new Set(participants.map((p) => p.name).filter((n) => typeof n === "string" && n.length > 0).map((n) => n.toLowerCase()));
|
|
1964
|
+
const unresolved = rawTokens.filter((t) => !speakerNames.has(t));
|
|
1965
|
+
if (unresolved.length > 0) {
|
|
1966
|
+
const sample = unresolved[0];
|
|
1967
|
+
throw new BadRequestError(`Cannot @-mention "${sample}" — they are not a participant of this chat. Use \`first-tree-hub chat send --direct ${sample} "..."\` to message them in a side conversation, or ask a human in this chat to add them as a participant first.`);
|
|
1549
1968
|
}
|
|
1550
|
-
if (typeof parsed !== "object" || parsed === null) return;
|
|
1551
|
-
const envelope = parsed;
|
|
1552
|
-
for (const handler of adminBroadcastHandlers) try {
|
|
1553
|
-
handler(envelope);
|
|
1554
|
-
} catch {}
|
|
1555
|
-
})).unlisten;
|
|
1556
|
-
},
|
|
1557
|
-
async stop() {
|
|
1558
|
-
if (unlistenInboxFn) {
|
|
1559
|
-
await unlistenInboxFn();
|
|
1560
|
-
unlistenInboxFn = null;
|
|
1561
|
-
}
|
|
1562
|
-
if (unlistenConfigFn) {
|
|
1563
|
-
await unlistenConfigFn();
|
|
1564
|
-
unlistenConfigFn = null;
|
|
1565
|
-
}
|
|
1566
|
-
if (unlistenSessionStateFn) {
|
|
1567
|
-
await unlistenSessionStateFn();
|
|
1568
|
-
unlistenSessionStateFn = null;
|
|
1569
|
-
}
|
|
1570
|
-
if (unlistenSessionEventFn) {
|
|
1571
|
-
await unlistenSessionEventFn();
|
|
1572
|
-
unlistenSessionEventFn = null;
|
|
1573
|
-
}
|
|
1574
|
-
if (unlistenRuntimeStateFn) {
|
|
1575
|
-
await unlistenRuntimeStateFn();
|
|
1576
|
-
unlistenRuntimeStateFn = null;
|
|
1577
1969
|
}
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1970
|
+
}
|
|
1971
|
+
let outboundContent = effectiveContent;
|
|
1972
|
+
if (options.normalizeMentionsInContent && typeof outboundContent === "string") {
|
|
1973
|
+
const present = new Set(scanMentionTokens(outboundContent));
|
|
1974
|
+
const missingNames = [];
|
|
1975
|
+
for (const id of mergedMentions) {
|
|
1976
|
+
if (id === senderId) continue;
|
|
1977
|
+
const p = participants.find((q) => q.agentId === id);
|
|
1978
|
+
if (!p?.name) continue;
|
|
1979
|
+
if (present.has(p.name.toLowerCase())) continue;
|
|
1980
|
+
missingNames.push(p.name);
|
|
1581
1981
|
}
|
|
1582
|
-
if (
|
|
1583
|
-
|
|
1584
|
-
|
|
1982
|
+
if (missingNames.length > 0) {
|
|
1983
|
+
const prefix = missingNames.map((n) => `@${n}`).join(" ");
|
|
1984
|
+
outboundContent = outboundContent.length > 0 ? `${prefix} ${outboundContent}` : prefix;
|
|
1585
1985
|
}
|
|
1586
1986
|
}
|
|
1587
|
-
|
|
1987
|
+
if (data.format === "question") await assertSenderMayEmitQuestion(tx, senderId);
|
|
1988
|
+
const isSilentSend = typeof outboundContent === "string" && outboundContent.replace(/^(@\S+\s*)+/, "").trim().length === 0;
|
|
1989
|
+
if (isSilentSend) log$1.info({
|
|
1990
|
+
chatId,
|
|
1991
|
+
senderId,
|
|
1992
|
+
source: data.source ?? null
|
|
1993
|
+
}, "silent send: empty content after mention strip — no fan-out wake-up");
|
|
1994
|
+
const projectionMentions = isSilentSend ? [] : dmAutoProjection;
|
|
1995
|
+
const messageId = randomUUID();
|
|
1996
|
+
const [msg] = await tx.insert(messages).values({
|
|
1997
|
+
id: messageId,
|
|
1998
|
+
chatId,
|
|
1999
|
+
senderId,
|
|
2000
|
+
format: data.format,
|
|
2001
|
+
content: outboundContent,
|
|
2002
|
+
metadata: metadataToStore,
|
|
2003
|
+
replyToInbox: data.replyToInbox ?? null,
|
|
2004
|
+
replyToChat: data.replyToChat ?? null,
|
|
2005
|
+
inReplyTo: data.inReplyTo ?? null,
|
|
2006
|
+
source: data.source ?? null
|
|
2007
|
+
}).returning();
|
|
2008
|
+
if (data.format === "question" && msg) await recordPendingQuestionFromMessage(tx, {
|
|
2009
|
+
agentId: senderId,
|
|
2010
|
+
chatId,
|
|
2011
|
+
messageId: msg.id,
|
|
2012
|
+
content: outboundContent
|
|
2013
|
+
});
|
|
2014
|
+
const mentionSet = new Set(mergedMentions);
|
|
2015
|
+
const fanout = participants.filter((p) => p.agentId !== senderId).map((p) => ({
|
|
2016
|
+
agentId: p.agentId,
|
|
2017
|
+
inboxId: p.inboxId,
|
|
2018
|
+
notify: !isSilentSend && !isAgentFinalText && (p.mode !== "mention_only" || mentionSet.has(p.agentId))
|
|
2019
|
+
}));
|
|
2020
|
+
if (fanout.length > 0) await tx.insert(inboxEntries).values(fanout.map((f) => ({
|
|
2021
|
+
inboxId: f.inboxId,
|
|
2022
|
+
messageId,
|
|
2023
|
+
chatId,
|
|
2024
|
+
notify: f.notify
|
|
2025
|
+
})));
|
|
2026
|
+
const notified = fanout.filter((f) => f.notify);
|
|
2027
|
+
const recipients = notified.map((f) => f.inboxId);
|
|
2028
|
+
const recipientAgentIds = notified.map((f) => f.agentId);
|
|
2029
|
+
if (data.inReplyTo) {
|
|
2030
|
+
const [original] = await tx.select({
|
|
2031
|
+
replyToInbox: messages.replyToInbox,
|
|
2032
|
+
replyToChat: messages.replyToChat
|
|
2033
|
+
}).from(messages).where(eq(messages.id, data.inReplyTo)).limit(1);
|
|
2034
|
+
if (original?.replyToInbox && original?.replyToChat) {
|
|
2035
|
+
const replyNotify = !isSilentSend;
|
|
2036
|
+
await tx.insert(inboxEntries).values({
|
|
2037
|
+
inboxId: original.replyToInbox,
|
|
2038
|
+
messageId,
|
|
2039
|
+
chatId: original.replyToChat,
|
|
2040
|
+
notify: replyNotify
|
|
2041
|
+
}).onConflictDoNothing();
|
|
2042
|
+
if (replyNotify && !recipients.includes(original.replyToInbox)) recipients.push(original.replyToInbox);
|
|
2043
|
+
}
|
|
2044
|
+
}
|
|
2045
|
+
await tx.update(chats).set({ updatedAt: /* @__PURE__ */ new Date() }).where(eq(chats.id, chatId));
|
|
2046
|
+
if (!msg) throw new Error("Unexpected: INSERT RETURNING produced no row");
|
|
2047
|
+
const previewText = typeof outboundContent === "string" ? outboundContent.trim() : "";
|
|
2048
|
+
await applyAfterFanOut(tx, {
|
|
2049
|
+
chatId,
|
|
2050
|
+
messageId: msg.id,
|
|
2051
|
+
senderId,
|
|
2052
|
+
mentionedAgentIds: projectionMentions,
|
|
2053
|
+
contentPreview: previewText,
|
|
2054
|
+
messageCreatedAt: msg.createdAt
|
|
2055
|
+
});
|
|
2056
|
+
return {
|
|
2057
|
+
message: msg,
|
|
2058
|
+
recipients,
|
|
2059
|
+
recipientAgentIds,
|
|
2060
|
+
organizationId: senderRow.organizationId
|
|
2061
|
+
};
|
|
2062
|
+
});
|
|
2063
|
+
const settled = await Promise.allSettled(txResult.recipientAgentIds.map((agentId) => upsertSessionState(db, agentId, chatId, "active", txResult.organizationId, void 0, { touchPresenceLastSeen: false })));
|
|
2064
|
+
for (let i = 0; i < settled.length; i++) {
|
|
2065
|
+
const r = settled[i];
|
|
2066
|
+
if (r?.status === "rejected") log$1.error({
|
|
2067
|
+
err: r.reason,
|
|
2068
|
+
chatId,
|
|
2069
|
+
agentId: txResult.recipientAgentIds[i]
|
|
2070
|
+
}, "predictive session activation failed");
|
|
2071
|
+
}
|
|
2072
|
+
fireChatMessageKick(chatId, txResult.message.id);
|
|
2073
|
+
observeLoopPattern(db, chatId).catch((err) => {
|
|
2074
|
+
log$1.error({
|
|
2075
|
+
err,
|
|
2076
|
+
chatId
|
|
2077
|
+
}, "loop pattern observation failed");
|
|
2078
|
+
});
|
|
2079
|
+
return {
|
|
2080
|
+
message: txResult.message,
|
|
2081
|
+
recipients: txResult.recipients
|
|
2082
|
+
};
|
|
2083
|
+
}
|
|
2084
|
+
/**
|
|
2085
|
+
* Detect agent-sent content that was JSON.stringify-ed once before reaching
|
|
2086
|
+
* the CLI / API. The bad shape is an outer `"..."` wrapper + interior `\n` /
|
|
2087
|
+
* `\"` escape sequences, which the UI renders as a quoted literal instead of
|
|
2088
|
+
* markdown (issue #389). Returns the unwrapped inner string on a confident
|
|
2089
|
+
* match, or `null` to leave the content alone.
|
|
2090
|
+
*
|
|
2091
|
+
* Match conditions (all required) — kept strict so legitimate human content
|
|
2092
|
+
* that happens to look like a quoted phrase is never touched. The caller is
|
|
2093
|
+
* additionally responsible for restricting this to non-human senders.
|
|
2094
|
+
*
|
|
2095
|
+
* - first and last char are `"`
|
|
2096
|
+
* - body contains at least one typical JSON escape sequence
|
|
2097
|
+
* (`\n`, `\r`, `\t`, `\"`, or `\\`)
|
|
2098
|
+
* - `JSON.parse` succeeds
|
|
2099
|
+
* - the parse result is a `string` (excludes `{...}`, `[...]`, numbers)
|
|
2100
|
+
*/
|
|
2101
|
+
function maybeUnwrapDoubleEncoded(content) {
|
|
2102
|
+
if (content.length < 4) return null;
|
|
2103
|
+
if (content.charCodeAt(0) !== 34) return null;
|
|
2104
|
+
if (content.charCodeAt(content.length - 1) !== 34) return null;
|
|
2105
|
+
if (!/\\[nrt"\\]/.test(content)) return null;
|
|
2106
|
+
try {
|
|
2107
|
+
const parsed = JSON.parse(content);
|
|
2108
|
+
return typeof parsed === "string" ? parsed : null;
|
|
2109
|
+
} catch {
|
|
2110
|
+
return null;
|
|
2111
|
+
}
|
|
2112
|
+
}
|
|
2113
|
+
function stripMentionPrefix(content) {
|
|
2114
|
+
return content.replace(/^(@\S+\s*)+/, "").trim();
|
|
2115
|
+
}
|
|
2116
|
+
const defaultLoopObserver = (data) => {
|
|
2117
|
+
log$1.warn({
|
|
2118
|
+
metric: "loop_pattern_observed_total",
|
|
2119
|
+
...data
|
|
2120
|
+
}, "loop pattern observed (not blocked) — prompt discipline may be drifting");
|
|
2121
|
+
};
|
|
2122
|
+
/**
|
|
2123
|
+
* Pure observation: detect short, fast, two-agent ping-pong reply chains and
|
|
2124
|
+
* surface them via a structured log line. Does NOT modify the `notify` flag
|
|
2125
|
+
* or otherwise interfere with delivery — loop *prevention* lives client-side
|
|
2126
|
+
* (prompt + silent-turn protocol in `result-sink`). Six conjunctive
|
|
2127
|
+
* conditions (see design `agent-reply-loop-prevention-design.md` §3.4) so
|
|
2128
|
+
* normal multi-agent collaboration is never flagged:
|
|
2129
|
+
*
|
|
2130
|
+
* C1 — every message is `format=text`
|
|
2131
|
+
* C2 — no human sender in the window (any human reply resets the chain)
|
|
2132
|
+
* C3 — exactly two senders, perfectly alternating
|
|
2133
|
+
* C4 — strict `inReplyTo` chain across the whole window
|
|
2134
|
+
* C5 — every message body (after stripping leading `@<name>` tokens) is
|
|
2135
|
+
* ≤ `LOOP_OBSERVATION_SHORT_CHARS` characters
|
|
2136
|
+
* C6 — the whole window spans ≤ `LOOP_OBSERVATION_TIME_WINDOW_MS` ms
|
|
2137
|
+
*
|
|
2138
|
+
* Exported for direct test coverage of the detection logic; the `sendMessage`
|
|
2139
|
+
* call site uses the default observer.
|
|
2140
|
+
*/
|
|
2141
|
+
async function observeLoopPattern(db, chatId, observer = defaultLoopObserver) {
|
|
2142
|
+
const window = await db.select({
|
|
2143
|
+
id: messages.id,
|
|
2144
|
+
senderId: messages.senderId,
|
|
2145
|
+
content: messages.content,
|
|
2146
|
+
inReplyTo: messages.inReplyTo,
|
|
2147
|
+
createdAt: messages.createdAt,
|
|
2148
|
+
format: messages.format,
|
|
2149
|
+
senderType: agents.type
|
|
2150
|
+
}).from(messages).innerJoin(agents, eq(messages.senderId, agents.uuid)).where(eq(messages.chatId, chatId)).orderBy(desc(messages.createdAt)).limit(4);
|
|
2151
|
+
if (window.length < 4) return;
|
|
2152
|
+
if (window.some((m) => m.format !== "text")) return;
|
|
2153
|
+
if (window.some((m) => m.senderType === "human")) return;
|
|
2154
|
+
if (new Set(window.map((m) => m.senderId)).size !== 2) return;
|
|
2155
|
+
for (let i = 0; i < window.length - 1; i++) if (window[i]?.senderId === window[i + 1]?.senderId) return;
|
|
2156
|
+
for (let i = 0; i < window.length - 1; i++) if (window[i]?.inReplyTo !== window[i + 1]?.id) return;
|
|
2157
|
+
const lens = [];
|
|
2158
|
+
for (const m of window) {
|
|
2159
|
+
const text = typeof m.content === "string" ? m.content : null;
|
|
2160
|
+
if (text === null) return;
|
|
2161
|
+
const len = stripMentionPrefix(text).length;
|
|
2162
|
+
if (len > 10) return;
|
|
2163
|
+
lens.push(len);
|
|
2164
|
+
}
|
|
2165
|
+
const newest = window[0];
|
|
2166
|
+
const oldest = window[window.length - 1];
|
|
2167
|
+
if (!newest || !oldest) return;
|
|
2168
|
+
const spanMs = newest.createdAt.getTime() - oldest.createdAt.getTime();
|
|
2169
|
+
if (spanMs > 3e4) return;
|
|
2170
|
+
observer({
|
|
2171
|
+
chatId,
|
|
2172
|
+
recentMessageIds: window.map((m) => m.id),
|
|
2173
|
+
windowSpanMs: spanMs,
|
|
2174
|
+
contentLengths: lens
|
|
2175
|
+
});
|
|
2176
|
+
}
|
|
2177
|
+
async function sendToAgent(db, senderUuid, targetName, data) {
|
|
2178
|
+
const [sender] = await db.select({
|
|
2179
|
+
uuid: agents.uuid,
|
|
2180
|
+
organizationId: agents.organizationId
|
|
2181
|
+
}).from(agents).where(eq(agents.uuid, senderUuid)).limit(1);
|
|
2182
|
+
if (!sender) throw new NotFoundError(`Agent "${senderUuid}" not found`);
|
|
2183
|
+
const [target] = await db.select({ uuid: agents.uuid }).from(agents).where(and(eq(agents.organizationId, sender.organizationId), eq(agents.name, targetName), ne(agents.status, "deleted"))).limit(1);
|
|
2184
|
+
if (!target) throw new NotFoundError(`Agent "${targetName}" not found${/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(targetName) ? " — `first-tree-hub chat send` expects an agent NAME, not a uuid. Run `first-tree-hub agent list` to see available names." : ""}`);
|
|
2185
|
+
const incomingMeta = data.metadata ?? {};
|
|
2186
|
+
const existingMentionsRaw = incomingMeta.mentions;
|
|
2187
|
+
const existingMentions = Array.isArray(existingMentionsRaw) ? existingMentionsRaw.filter((m) => typeof m === "string") : [];
|
|
2188
|
+
const mergedMentions = existingMentions.includes(target.uuid) ? existingMentions : [...existingMentions, target.uuid];
|
|
2189
|
+
const metadata = {
|
|
2190
|
+
...incomingMeta,
|
|
2191
|
+
mentions: mergedMentions
|
|
2192
|
+
};
|
|
2193
|
+
if (data.replyToChat) {
|
|
2194
|
+
const [targetIsMember, senderIsMember] = await Promise.all([isParticipant(db, data.replyToChat, target.uuid), isParticipant(db, data.replyToChat, senderUuid)]);
|
|
2195
|
+
if (targetIsMember && senderIsMember) return sendMessage(db, data.replyToChat, senderUuid, {
|
|
2196
|
+
format: data.format,
|
|
2197
|
+
content: data.content,
|
|
2198
|
+
metadata,
|
|
2199
|
+
replyToInbox: void 0,
|
|
2200
|
+
replyToChat: void 0,
|
|
2201
|
+
source: data.source
|
|
2202
|
+
}, { normalizeMentionsInContent: true });
|
|
2203
|
+
}
|
|
2204
|
+
if (!data.direct) throw new AgentSendNonMemberError(`Agent "${targetName}" is not a member of your current chat. Either open or reuse a side-conversation explicitly with \`first-tree-hub chat send --direct ${targetName} "..."\`, or ask a human in this chat to add ${targetName} as a participant.`);
|
|
2205
|
+
return sendMessage(db, (await findOrCreateDirectChat(db, senderUuid, target.uuid)).id, senderUuid, {
|
|
2206
|
+
format: data.format,
|
|
2207
|
+
content: data.content,
|
|
2208
|
+
metadata,
|
|
2209
|
+
replyToInbox: data.replyToInbox,
|
|
2210
|
+
replyToChat: data.replyToChat,
|
|
2211
|
+
source: data.source
|
|
2212
|
+
}, { normalizeMentionsInContent: true });
|
|
2213
|
+
}
|
|
2214
|
+
async function editMessage(db, chatId, messageId, senderId, data) {
|
|
2215
|
+
const [msg] = await db.select().from(messages).where(eq(messages.id, messageId)).limit(1);
|
|
2216
|
+
if (!msg) throw new NotFoundError(`Message "${messageId}" not found`);
|
|
2217
|
+
if (msg.chatId !== chatId) throw new NotFoundError(`Message "${messageId}" not found in this chat`);
|
|
2218
|
+
if (msg.senderId !== senderId) throw new ForbiddenError("Only the sender can edit a message");
|
|
2219
|
+
const setClause = {};
|
|
2220
|
+
if (data.format !== void 0) setClause.format = data.format;
|
|
2221
|
+
if (data.content !== void 0) setClause.content = data.content;
|
|
2222
|
+
const meta = msg.metadata ?? {};
|
|
2223
|
+
meta.editedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2224
|
+
setClause.metadata = meta;
|
|
2225
|
+
const [updated] = await db.update(messages).set(setClause).where(eq(messages.id, messageId)).returning();
|
|
2226
|
+
if (!updated) throw new Error("Unexpected: UPDATE RETURNING produced no row");
|
|
2227
|
+
return updated;
|
|
2228
|
+
}
|
|
2229
|
+
async function listMessages(db, chatId, limit, cursor) {
|
|
2230
|
+
const where = cursor ? and(eq(messages.chatId, chatId), lt(messages.createdAt, new Date(cursor))) : eq(messages.chatId, chatId);
|
|
2231
|
+
const rows = await db.select().from(messages).where(where).orderBy(desc(messages.createdAt)).limit(limit + 1);
|
|
2232
|
+
const hasMore = rows.length > limit;
|
|
2233
|
+
const items = hasMore ? rows.slice(0, limit) : rows;
|
|
2234
|
+
const last = items[items.length - 1];
|
|
2235
|
+
return {
|
|
2236
|
+
items,
|
|
2237
|
+
nextCursor: hasMore && last ? last.createdAt.toISOString() : null
|
|
2238
|
+
};
|
|
2239
|
+
}
|
|
2240
|
+
const INBOX_CHANNEL = "inbox_notifications";
|
|
2241
|
+
const CONFIG_CHANNEL = "config_changes";
|
|
2242
|
+
const SESSION_STATE_CHANNEL = "session_state_changes";
|
|
2243
|
+
const SESSION_EVENT_CHANNEL = "session_event_changes";
|
|
2244
|
+
const RUNTIME_STATE_CHANNEL = "runtime_state_changes";
|
|
2245
|
+
/**
|
|
2246
|
+
* Chat-first workspace cross-process kick. Carries `<chatId>:<messageId>`.
|
|
2247
|
+
* Lets admin WS sockets translate every chat message (speaker AND watcher
|
|
2248
|
+
* audience) into a `chat:message` frame, without being coupled to the
|
|
2249
|
+
* inbox NOTIFY path that only reaches speakers.
|
|
2250
|
+
*/
|
|
2251
|
+
const CHAT_MESSAGE_CHANNEL = "chat_message_events";
|
|
2252
|
+
/**
|
|
2253
|
+
* Generic admin-broadcast envelope channel. Producers (e.g. notification.ts)
|
|
2254
|
+
* emit a JSON-stringified `AdminBroadcastPayload`; every server instance
|
|
2255
|
+
* LISTENs and hands the envelope to its local admin-socket fanout. Keeps
|
|
2256
|
+
* cross-instance and single-instance code paths identical from the admin WS
|
|
2257
|
+
* route's perspective.
|
|
2258
|
+
*/
|
|
2259
|
+
const ADMIN_BROADCAST_CHANNEL = "admin_broadcast_envelopes";
|
|
2260
|
+
function createNotifier(listenClient) {
|
|
2261
|
+
const subscriptions = /* @__PURE__ */ new Map();
|
|
2262
|
+
const configChangeHandlers = [];
|
|
2263
|
+
const sessionStateChangeHandlers = [];
|
|
2264
|
+
const sessionEventHandlers = [];
|
|
2265
|
+
const runtimeStateChangeHandlers = [];
|
|
2266
|
+
const chatMessageHandlers = [];
|
|
2267
|
+
const adminBroadcastHandlers = [];
|
|
2268
|
+
let unlistenInboxFn = null;
|
|
2269
|
+
let unlistenConfigFn = null;
|
|
2270
|
+
let unlistenSessionStateFn = null;
|
|
2271
|
+
let unlistenSessionEventFn = null;
|
|
2272
|
+
let unlistenRuntimeStateFn = null;
|
|
2273
|
+
let unlistenChatMessageFn = null;
|
|
2274
|
+
let unlistenAdminBroadcastFn = null;
|
|
2275
|
+
function handleNotification(payload) {
|
|
2276
|
+
const sepIdx = payload.indexOf(":");
|
|
2277
|
+
if (sepIdx === -1) return;
|
|
2278
|
+
const inboxId = payload.slice(0, sepIdx);
|
|
2279
|
+
const messageId = payload.slice(sepIdx + 1);
|
|
2280
|
+
const sockets = subscriptions.get(inboxId);
|
|
2281
|
+
if (!sockets) return;
|
|
2282
|
+
for (const [ws, pushHandler] of sockets) {
|
|
2283
|
+
if (ws.readyState !== ws.OPEN) continue;
|
|
2284
|
+
Promise.resolve(pushHandler(messageId)).catch(() => {});
|
|
2285
|
+
}
|
|
2286
|
+
}
|
|
2287
|
+
return {
|
|
2288
|
+
subscribe(inboxId, ws, pushHandler) {
|
|
2289
|
+
let map = subscriptions.get(inboxId);
|
|
2290
|
+
if (!map) {
|
|
2291
|
+
map = /* @__PURE__ */ new Map();
|
|
2292
|
+
subscriptions.set(inboxId, map);
|
|
2293
|
+
}
|
|
2294
|
+
map.set(ws, pushHandler);
|
|
2295
|
+
},
|
|
2296
|
+
unsubscribe(inboxId, ws) {
|
|
2297
|
+
const map = subscriptions.get(inboxId);
|
|
2298
|
+
if (map) {
|
|
2299
|
+
map.delete(ws);
|
|
2300
|
+
if (map.size === 0) subscriptions.delete(inboxId);
|
|
2301
|
+
}
|
|
2302
|
+
},
|
|
2303
|
+
async notify(inboxId, messageId) {
|
|
2304
|
+
try {
|
|
2305
|
+
await listenClient`SELECT pg_notify(${INBOX_CHANNEL}, ${`${inboxId}:${messageId}`})`;
|
|
2306
|
+
} catch {}
|
|
2307
|
+
},
|
|
2308
|
+
async notifyConfigChange(configType) {
|
|
2309
|
+
try {
|
|
2310
|
+
await listenClient`SELECT pg_notify(${CONFIG_CHANNEL}, ${configType})`;
|
|
2311
|
+
} catch {}
|
|
2312
|
+
},
|
|
2313
|
+
async notifySessionStateChange(agentId, chatId, state, organizationId) {
|
|
2314
|
+
try {
|
|
2315
|
+
await listenClient`SELECT pg_notify(${SESSION_STATE_CHANNEL}, ${`${agentId}:${chatId}:${state}:${organizationId}`})`;
|
|
2316
|
+
} catch {}
|
|
2317
|
+
},
|
|
2318
|
+
async notifySessionEvent(agentId, chatId, kind, organizationId) {
|
|
2319
|
+
try {
|
|
2320
|
+
await listenClient`SELECT pg_notify(${SESSION_EVENT_CHANNEL}, ${`${agentId}:${chatId}:${kind}:${organizationId}`})`;
|
|
2321
|
+
} catch {}
|
|
2322
|
+
},
|
|
2323
|
+
async notifyRuntimeStateChange(agentId, state, organizationId) {
|
|
2324
|
+
try {
|
|
2325
|
+
await listenClient`SELECT pg_notify(${RUNTIME_STATE_CHANNEL}, ${`${agentId}:${state}:${organizationId}`})`;
|
|
2326
|
+
} catch {}
|
|
2327
|
+
},
|
|
2328
|
+
async notifyChatMessage(chatId, messageId) {
|
|
2329
|
+
try {
|
|
2330
|
+
await listenClient`SELECT pg_notify(${CHAT_MESSAGE_CHANNEL}, ${`${chatId}:${messageId}`})`;
|
|
2331
|
+
} catch {}
|
|
2332
|
+
},
|
|
2333
|
+
async notifyAdminBroadcast(payload) {
|
|
2334
|
+
let encoded;
|
|
2335
|
+
try {
|
|
2336
|
+
encoded = JSON.stringify(payload);
|
|
2337
|
+
} catch {
|
|
2338
|
+
return;
|
|
2339
|
+
}
|
|
2340
|
+
if (encoded.length > 7500) {
|
|
2341
|
+
console.error(`[notifier] admin broadcast payload too large (${encoded.length} bytes); refusing to NOTIFY`);
|
|
2342
|
+
return;
|
|
2343
|
+
}
|
|
2344
|
+
try {
|
|
2345
|
+
await listenClient`SELECT pg_notify(${ADMIN_BROADCAST_CHANNEL}, ${encoded})`;
|
|
2346
|
+
} catch {}
|
|
2347
|
+
},
|
|
2348
|
+
async pushFrameToInbox(inboxId, frame) {
|
|
2349
|
+
const map = subscriptions.get(inboxId);
|
|
2350
|
+
if (!map) return 0;
|
|
2351
|
+
let queued = 0;
|
|
2352
|
+
const pending = [];
|
|
2353
|
+
for (const ws of map.keys()) {
|
|
2354
|
+
if (ws.readyState !== ws.OPEN) continue;
|
|
2355
|
+
pending.push(new Promise((resolve) => {
|
|
2356
|
+
ws.send(frame, (err) => {
|
|
2357
|
+
if (!err) queued += 1;
|
|
2358
|
+
resolve();
|
|
2359
|
+
});
|
|
2360
|
+
}));
|
|
2361
|
+
}
|
|
2362
|
+
await Promise.all(pending);
|
|
2363
|
+
return queued;
|
|
2364
|
+
},
|
|
2365
|
+
onConfigChange(handler) {
|
|
2366
|
+
configChangeHandlers.push(handler);
|
|
2367
|
+
},
|
|
2368
|
+
onSessionStateChange(handler) {
|
|
2369
|
+
sessionStateChangeHandlers.push(handler);
|
|
2370
|
+
},
|
|
2371
|
+
onSessionEvent(handler) {
|
|
2372
|
+
sessionEventHandlers.push(handler);
|
|
2373
|
+
},
|
|
2374
|
+
onRuntimeStateChange(handler) {
|
|
2375
|
+
runtimeStateChangeHandlers.push(handler);
|
|
2376
|
+
},
|
|
2377
|
+
onChatMessage(handler) {
|
|
2378
|
+
chatMessageHandlers.push(handler);
|
|
2379
|
+
},
|
|
2380
|
+
onAdminBroadcast(handler) {
|
|
2381
|
+
adminBroadcastHandlers.push(handler);
|
|
2382
|
+
},
|
|
2383
|
+
async start() {
|
|
2384
|
+
unlistenInboxFn = (await listenClient.listen(INBOX_CHANNEL, (payload) => {
|
|
2385
|
+
if (payload) handleNotification(payload);
|
|
2386
|
+
})).unlisten;
|
|
2387
|
+
unlistenConfigFn = (await listenClient.listen(CONFIG_CHANNEL, (payload) => {
|
|
2388
|
+
if (payload) for (const handler of configChangeHandlers) handler(payload);
|
|
2389
|
+
})).unlisten;
|
|
2390
|
+
unlistenSessionStateFn = (await listenClient.listen(SESSION_STATE_CHANNEL, (payload) => {
|
|
2391
|
+
if (payload) {
|
|
2392
|
+
const firstSep = payload.indexOf(":");
|
|
2393
|
+
const secondSep = payload.indexOf(":", firstSep + 1);
|
|
2394
|
+
const thirdSep = payload.indexOf(":", secondSep + 1);
|
|
2395
|
+
if (firstSep > 0 && secondSep > firstSep && thirdSep > secondSep) {
|
|
2396
|
+
const agentId = payload.slice(0, firstSep);
|
|
2397
|
+
const chatId = payload.slice(firstSep + 1, secondSep);
|
|
2398
|
+
const state = payload.slice(secondSep + 1, thirdSep);
|
|
2399
|
+
const organizationId = payload.slice(thirdSep + 1);
|
|
2400
|
+
for (const handler of sessionStateChangeHandlers) handler({
|
|
2401
|
+
agentId,
|
|
2402
|
+
chatId,
|
|
2403
|
+
state,
|
|
2404
|
+
organizationId
|
|
2405
|
+
});
|
|
2406
|
+
}
|
|
2407
|
+
}
|
|
2408
|
+
})).unlisten;
|
|
2409
|
+
unlistenSessionEventFn = (await listenClient.listen(SESSION_EVENT_CHANNEL, (payload) => {
|
|
2410
|
+
if (payload) {
|
|
2411
|
+
const firstSep = payload.indexOf(":");
|
|
2412
|
+
const secondSep = payload.indexOf(":", firstSep + 1);
|
|
2413
|
+
const thirdSep = payload.indexOf(":", secondSep + 1);
|
|
2414
|
+
if (firstSep > 0 && secondSep > firstSep && thirdSep > secondSep) {
|
|
2415
|
+
const agentId = payload.slice(0, firstSep);
|
|
2416
|
+
const chatId = payload.slice(firstSep + 1, secondSep);
|
|
2417
|
+
const kind = payload.slice(secondSep + 1, thirdSep);
|
|
2418
|
+
const organizationId = payload.slice(thirdSep + 1);
|
|
2419
|
+
for (const handler of sessionEventHandlers) try {
|
|
2420
|
+
handler({
|
|
2421
|
+
agentId,
|
|
2422
|
+
chatId,
|
|
2423
|
+
kind,
|
|
2424
|
+
organizationId
|
|
2425
|
+
});
|
|
2426
|
+
} catch {}
|
|
2427
|
+
}
|
|
2428
|
+
}
|
|
2429
|
+
})).unlisten;
|
|
2430
|
+
unlistenRuntimeStateFn = (await listenClient.listen(RUNTIME_STATE_CHANNEL, (payload) => {
|
|
2431
|
+
if (payload) {
|
|
2432
|
+
const firstSep = payload.indexOf(":");
|
|
2433
|
+
const secondSep = payload.indexOf(":", firstSep + 1);
|
|
2434
|
+
if (firstSep > 0 && secondSep > firstSep) {
|
|
2435
|
+
const agentId = payload.slice(0, firstSep);
|
|
2436
|
+
const state = payload.slice(firstSep + 1, secondSep);
|
|
2437
|
+
const organizationId = payload.slice(secondSep + 1);
|
|
2438
|
+
for (const handler of runtimeStateChangeHandlers) handler({
|
|
2439
|
+
agentId,
|
|
2440
|
+
state,
|
|
2441
|
+
organizationId
|
|
2442
|
+
});
|
|
2443
|
+
}
|
|
2444
|
+
}
|
|
2445
|
+
})).unlisten;
|
|
2446
|
+
unlistenChatMessageFn = (await listenClient.listen(CHAT_MESSAGE_CHANNEL, (payload) => {
|
|
2447
|
+
if (!payload) return;
|
|
2448
|
+
const sep = payload.indexOf(":");
|
|
2449
|
+
if (sep <= 0) return;
|
|
2450
|
+
const chatId = payload.slice(0, sep);
|
|
2451
|
+
const messageId = payload.slice(sep + 1);
|
|
2452
|
+
for (const handler of chatMessageHandlers) try {
|
|
2453
|
+
handler({
|
|
2454
|
+
chatId,
|
|
2455
|
+
messageId
|
|
2456
|
+
});
|
|
2457
|
+
} catch {}
|
|
2458
|
+
})).unlisten;
|
|
2459
|
+
unlistenAdminBroadcastFn = (await listenClient.listen(ADMIN_BROADCAST_CHANNEL, (payload) => {
|
|
2460
|
+
if (!payload) return;
|
|
2461
|
+
let parsed;
|
|
2462
|
+
try {
|
|
2463
|
+
parsed = JSON.parse(payload);
|
|
2464
|
+
} catch {
|
|
2465
|
+
return;
|
|
2466
|
+
}
|
|
2467
|
+
if (typeof parsed !== "object" || parsed === null) return;
|
|
2468
|
+
const envelope = parsed;
|
|
2469
|
+
for (const handler of adminBroadcastHandlers) try {
|
|
2470
|
+
handler(envelope);
|
|
2471
|
+
} catch {}
|
|
2472
|
+
})).unlisten;
|
|
2473
|
+
},
|
|
2474
|
+
async stop() {
|
|
2475
|
+
if (unlistenInboxFn) {
|
|
2476
|
+
await unlistenInboxFn();
|
|
2477
|
+
unlistenInboxFn = null;
|
|
2478
|
+
}
|
|
2479
|
+
if (unlistenConfigFn) {
|
|
2480
|
+
await unlistenConfigFn();
|
|
2481
|
+
unlistenConfigFn = null;
|
|
2482
|
+
}
|
|
2483
|
+
if (unlistenSessionStateFn) {
|
|
2484
|
+
await unlistenSessionStateFn();
|
|
2485
|
+
unlistenSessionStateFn = null;
|
|
2486
|
+
}
|
|
2487
|
+
if (unlistenSessionEventFn) {
|
|
2488
|
+
await unlistenSessionEventFn();
|
|
2489
|
+
unlistenSessionEventFn = null;
|
|
2490
|
+
}
|
|
2491
|
+
if (unlistenRuntimeStateFn) {
|
|
2492
|
+
await unlistenRuntimeStateFn();
|
|
2493
|
+
unlistenRuntimeStateFn = null;
|
|
2494
|
+
}
|
|
2495
|
+
if (unlistenChatMessageFn) {
|
|
2496
|
+
await unlistenChatMessageFn();
|
|
2497
|
+
unlistenChatMessageFn = null;
|
|
2498
|
+
}
|
|
2499
|
+
if (unlistenAdminBroadcastFn) {
|
|
2500
|
+
await unlistenAdminBroadcastFn();
|
|
2501
|
+
unlistenAdminBroadcastFn = null;
|
|
2502
|
+
}
|
|
2503
|
+
}
|
|
2504
|
+
};
|
|
2505
|
+
}
|
|
2506
|
+
/** Fire-and-forget: notify all recipients that a new message is available. */
|
|
2507
|
+
function notifyRecipients(notifier, recipients, messageId) {
|
|
2508
|
+
for (const inboxId of recipients) notifier.notify(inboxId, messageId).catch(() => {});
|
|
2509
|
+
}
|
|
2510
|
+
const log = createLogger("questions");
|
|
2511
|
+
/**
|
|
2512
|
+
* Insert a `pending_questions` row inside the same transaction that wrote a
|
|
2513
|
+
* `format=question` message. Caller is `sendMessage` after the message INSERT
|
|
2514
|
+
* returns, so a rollback drops both rows together. No-op (returns silently)
|
|
2515
|
+
* if the message content is not a valid `QuestionMessageContent` — the caller
|
|
2516
|
+
* will already have rejected such input upstream, but we defend in depth so a
|
|
2517
|
+
* malformed write never leaves a dangling pending row.
|
|
2518
|
+
*/
|
|
2519
|
+
async function recordPendingQuestionFromMessage(tx, args) {
|
|
2520
|
+
const parsed = questionMessageContentSchema.safeParse(args.content);
|
|
2521
|
+
if (!parsed.success) throw new BadRequestError("Invalid question message content", { "question.parse_error": parsed.error.message.slice(0, 200) });
|
|
2522
|
+
const { correlationId } = parsed.data;
|
|
2523
|
+
await tx.insert(pendingQuestions).values({
|
|
2524
|
+
id: correlationId,
|
|
2525
|
+
agentId: args.agentId,
|
|
2526
|
+
chatId: args.chatId,
|
|
2527
|
+
messageId: args.messageId,
|
|
2528
|
+
status: "pending"
|
|
2529
|
+
});
|
|
2530
|
+
}
|
|
2531
|
+
/**
|
|
2532
|
+
* Defensive write-side check: codex-runtime agents must never emit
|
|
2533
|
+
* `format=question` (Codex SDK 0.125 has no ask-user surface, so any such
|
|
2534
|
+
* message would be a runtime regression). Looks up the sender's
|
|
2535
|
+
* `runtime_provider` and rejects if it is `codex`. Throws `ForbiddenError`
|
|
2536
|
+
* (HTTP 403) so the bug surfaces loudly to the offending writer.
|
|
2537
|
+
*
|
|
2538
|
+
* Returns the runtime provider for telemetry / further checks (e.g. the
|
|
2539
|
+
* caller can attach it to the active span).
|
|
2540
|
+
*/
|
|
2541
|
+
async function assertSenderMayEmitQuestion(tx, senderAgentId) {
|
|
2542
|
+
const [row] = await tx.select({ runtimeProvider: agents.runtimeProvider }).from(agents).where(eq(agents.uuid, senderAgentId)).limit(1);
|
|
2543
|
+
if (!row) throw new NotFoundError(`Sender agent "${senderAgentId}" not found`);
|
|
2544
|
+
if (row.runtimeProvider === "codex") {
|
|
2545
|
+
log.error({
|
|
2546
|
+
agentId: senderAgentId,
|
|
2547
|
+
runtimeProvider: row.runtimeProvider
|
|
2548
|
+
}, "rejected format=question emit from codex-runtime agent");
|
|
2549
|
+
throw new ForbiddenError("Codex runtime cannot emit ask-user questions", {
|
|
2550
|
+
"question.codex_emit_attempt": true,
|
|
2551
|
+
"agent.id": senderAgentId
|
|
2552
|
+
});
|
|
2553
|
+
}
|
|
2554
|
+
return row.runtimeProvider;
|
|
2555
|
+
}
|
|
2556
|
+
/**
|
|
2557
|
+
* User-side answer submission. Atomically:
|
|
2558
|
+
* 1. Lock the `pending_questions` row by correlationId.
|
|
2559
|
+
* 2. Refuse if status !== "pending" (409 if already-answered, 410-shaped
|
|
2560
|
+
* 400 if superseded — both surface as ConflictError so the caller knows
|
|
2561
|
+
* the question is no longer answerable).
|
|
2562
|
+
* 3. Validate that the answer keys match the original `questions[]`.
|
|
2563
|
+
* 4. Flip status to `answered` INSIDE the lock-tx, before releasing the
|
|
2564
|
+
* row lock. This is the linearisation point: the second concurrent
|
|
2565
|
+
* submitter (waiting on the same row lock) will, on its turn, see
|
|
2566
|
+
* status=answered and exit with ConflictError BEFORE it can write a
|
|
2567
|
+
* second `format=question_answer` message.
|
|
2568
|
+
* 5. Send the `format=question_answer` message OUTSIDE the lock-tx
|
|
2569
|
+
* (sendMessage opens its own transaction; nesting wasn't supported by
|
|
2570
|
+
* the existing call site). At this point we hold an exclusive logical
|
|
2571
|
+
* claim — only one submitter ever reaches this step per correlationId.
|
|
2572
|
+
*
|
|
2573
|
+
* `submitterAgentId` is the human agent on whose behalf the answer is
|
|
2574
|
+
* written (it must be a participant of the question's chat). Returns the
|
|
2575
|
+
* created `question_answer` message id so the route can include it in the
|
|
2576
|
+
* 201 response.
|
|
2577
|
+
*
|
|
2578
|
+
* Failure semantics: if step 5 (sendMessage) fails after status was flipped,
|
|
2579
|
+
* we revert the row to `pending` so the user can retry. This is best-effort —
|
|
2580
|
+
* the revert UPDATE is guarded by `status='answered'` to avoid clobbering a
|
|
2581
|
+
* supersede that might race in. If the revert itself fails, the row is
|
|
2582
|
+
* stranded as `answered` with no answer message; an operator would need to
|
|
2583
|
+
* intervene, but a sendMessage failure (local DB tx) is already
|
|
2584
|
+
* extraordinarily rare.
|
|
2585
|
+
*/
|
|
2586
|
+
async function submitAnswer(db, notifier, args) {
|
|
2587
|
+
const questionRow = await db.transaction(async (tx) => {
|
|
2588
|
+
const [row] = await tx.select({
|
|
2589
|
+
id: pendingQuestions.id,
|
|
2590
|
+
status: pendingQuestions.status,
|
|
2591
|
+
chatId: pendingQuestions.chatId,
|
|
2592
|
+
agentId: pendingQuestions.agentId,
|
|
2593
|
+
messageId: pendingQuestions.messageId
|
|
2594
|
+
}).from(pendingQuestions).where(eq(pendingQuestions.id, args.correlationId)).for("update").limit(1);
|
|
2595
|
+
if (!row) throw new NotFoundError(`Question "${args.correlationId}" not found`);
|
|
2596
|
+
if (row.chatId !== args.chatId) throw new NotFoundError(`Question "${args.correlationId}" not found in this chat`);
|
|
2597
|
+
if (row.status !== "pending") throw new ConflictError(`Question "${args.correlationId}" is no longer pending`, { "question.status": row.status });
|
|
2598
|
+
const [msg] = await tx.select({ content: messages.content }).from(messages).where(eq(messages.id, row.messageId)).limit(1);
|
|
2599
|
+
if (!msg) throw new NotFoundError(`Question message "${row.messageId}" not found`);
|
|
2600
|
+
const parsedQuestion = questionMessageContentSchema.safeParse(msg.content);
|
|
2601
|
+
if (!parsedQuestion.success) throw new BadRequestError("Stored question content is malformed", { "question.parse_error": parsedQuestion.error.message.slice(0, 200) });
|
|
2602
|
+
const expectedKeys = new Set(parsedQuestion.data.questions.map((q) => q.question));
|
|
2603
|
+
for (const key of Object.keys(args.answers)) if (!expectedKeys.has(key)) throw new BadRequestError(`Answer key "${key}" does not match any question`, { "question.id": args.correlationId });
|
|
2604
|
+
for (const key of expectedKeys) if (!(key in args.answers)) throw new BadRequestError(`Answer missing for question "${key}"`, { "question.id": args.correlationId });
|
|
2605
|
+
await tx.update(pendingQuestions).set({
|
|
2606
|
+
status: "answered",
|
|
2607
|
+
answeredAt: /* @__PURE__ */ new Date()
|
|
2608
|
+
}).where(eq(pendingQuestions.id, args.correlationId));
|
|
2609
|
+
return row;
|
|
2610
|
+
});
|
|
2611
|
+
const answerContent = {
|
|
2612
|
+
correlationId: args.correlationId,
|
|
2613
|
+
answers: args.answers
|
|
2614
|
+
};
|
|
2615
|
+
questionAnswerMessageContentSchema.parse(answerContent);
|
|
2616
|
+
let result;
|
|
2617
|
+
try {
|
|
2618
|
+
result = await sendMessage(db, args.chatId, args.submitterAgentId, {
|
|
2619
|
+
format: "question_answer",
|
|
2620
|
+
content: answerContent,
|
|
2621
|
+
inReplyTo: questionRow.messageId,
|
|
2622
|
+
source: "hub_ui"
|
|
2623
|
+
});
|
|
2624
|
+
} catch (err) {
|
|
2625
|
+
log.error({
|
|
2626
|
+
correlationId: args.correlationId,
|
|
2627
|
+
chatId: args.chatId,
|
|
2628
|
+
err: err instanceof Error ? err.message : String(err)
|
|
2629
|
+
}, "sendMessage failed after status flip; reverting pending_questions row to 'pending'");
|
|
2630
|
+
try {
|
|
2631
|
+
await db.update(pendingQuestions).set({
|
|
2632
|
+
status: "pending",
|
|
2633
|
+
answeredAt: null
|
|
2634
|
+
}).where(and(eq(pendingQuestions.id, args.correlationId), eq(pendingQuestions.status, "answered")));
|
|
2635
|
+
} catch (revertErr) {
|
|
2636
|
+
log.error({
|
|
2637
|
+
correlationId: args.correlationId,
|
|
2638
|
+
chatId: args.chatId,
|
|
2639
|
+
revertErr: revertErr instanceof Error ? revertErr.message : String(revertErr)
|
|
2640
|
+
}, "revert UPDATE also failed; row may be stranded as 'answered' without an answer message");
|
|
2641
|
+
}
|
|
2642
|
+
throw err;
|
|
2643
|
+
}
|
|
2644
|
+
if (notifier) notifyRecipients(notifier, result.recipients, result.message.id);
|
|
2645
|
+
return {
|
|
2646
|
+
messageId: result.message.id,
|
|
2647
|
+
recipients: result.recipients
|
|
2648
|
+
};
|
|
2649
|
+
}
|
|
2650
|
+
/**
|
|
2651
|
+
* Mark every pending row whose chat is `chatId` as superseded. Used when a
|
|
2652
|
+
* chat session is archived — the agent runtime that emitted the question
|
|
2653
|
+
* may already be gone, so leaving the row pending would block forever.
|
|
2654
|
+
*/
|
|
2655
|
+
async function markSupersededByChat(tx, chatId, reason = "chat_archived") {
|
|
2656
|
+
return (await tx.update(pendingQuestions).set({
|
|
2657
|
+
status: "superseded",
|
|
2658
|
+
supersededAt: /* @__PURE__ */ new Date(),
|
|
2659
|
+
supersededReason: reason
|
|
2660
|
+
}).where(and(eq(pendingQuestions.chatId, chatId), eq(pendingQuestions.status, "pending"))).returning({ id: pendingQuestions.id })).length;
|
|
2661
|
+
}
|
|
2662
|
+
/**
|
|
2663
|
+
* Mark every pending row owned by any of `agentIds` as superseded. Used when
|
|
2664
|
+
* the client carrying these agents is claimed by a new user — the previous
|
|
2665
|
+
* owner's runtime is detached and cannot deliver an answer back.
|
|
2666
|
+
*/
|
|
2667
|
+
async function markSupersededByAgents(tx, agentIds, reason = "client_claimed") {
|
|
2668
|
+
if (agentIds.length === 0) return 0;
|
|
2669
|
+
return (await tx.update(pendingQuestions).set({
|
|
2670
|
+
status: "superseded",
|
|
2671
|
+
supersededAt: /* @__PURE__ */ new Date(),
|
|
2672
|
+
supersededReason: reason
|
|
2673
|
+
}).where(and(inArray(pendingQuestions.agentId, agentIds), eq(pendingQuestions.status, "pending"))).returning({ id: pendingQuestions.id })).length;
|
|
2674
|
+
}
|
|
2675
|
+
/** Extract a plain-text summary from a message's JSONB content field.
|
|
2676
|
+
* Used as the auto-title fallback in chat list rendering — see
|
|
2677
|
+
* `me-chat.ts:resolveChatTitle` and `admin/chats.ts:getChat`.
|
|
2678
|
+
*
|
|
2679
|
+
* - `@<name>` mention tokens are stripped before truncation: in the
|
|
2680
|
+
* chat-first model they're routing/audience metadata, not part of
|
|
2681
|
+
* the user's intent. Leaving them in produces noisy titles like
|
|
2682
|
+
* "@hub-agent-01 帮我重构这个文件" or "你好 @hub-agent-02 看看".
|
|
2683
|
+
* - Whitespace runs (including those left behind by mention removal)
|
|
2684
|
+
* collapse to single spaces.
|
|
2685
|
+
* - If the cleaned text is empty (e.g., a message that's only
|
|
2686
|
+
* `@hub-agent-01`), returns null so the caller falls through to
|
|
2687
|
+
* the participant-join fallback.
|
|
2688
|
+
* - Slicing is code-point-aware (`Array.from + join`) so emoji /
|
|
2689
|
+
* surrogate pairs aren't split into garbled half-characters. */
|
|
2690
|
+
function extractSummary(content, maxLen = 50) {
|
|
2691
|
+
let text = "";
|
|
2692
|
+
if (typeof content === "object" && content !== null && "text" in content) text = String(content.text ?? "");
|
|
2693
|
+
else if (typeof content === "string") text = content;
|
|
2694
|
+
if (!text) return null;
|
|
2695
|
+
const cleaned = stripCode(text).replace(MENTION_REGEX, "").replace(/\s+/g, " ").trim();
|
|
2696
|
+
if (!cleaned) return null;
|
|
2697
|
+
return Array.from(cleaned).slice(0, maxLen).join("");
|
|
2698
|
+
}
|
|
2699
|
+
/** List sessions for a specific agent, with optional state filters. */
|
|
2700
|
+
async function listAgentSessions(db, agentId, filters) {
|
|
2701
|
+
const conditions = [eq(agentChatSessions.agentId, agentId)];
|
|
2702
|
+
if (filters?.state) conditions.push(eq(agentChatSessions.state, filters.state));
|
|
2703
|
+
else conditions.push(ne(agentChatSessions.state, "evicted"));
|
|
2704
|
+
const rows = await db.select({
|
|
2705
|
+
agentId: agentChatSessions.agentId,
|
|
2706
|
+
chatId: agentChatSessions.chatId,
|
|
2707
|
+
state: agentChatSessions.state,
|
|
2708
|
+
updatedAt: agentChatSessions.updatedAt,
|
|
2709
|
+
chatCreatedAt: chats.createdAt,
|
|
2710
|
+
chatTopic: chats.topic
|
|
2711
|
+
}).from(agentChatSessions).innerJoin(chats, eq(agentChatSessions.chatId, chats.id)).where(and(...conditions)).orderBy(desc(agentChatSessions.updatedAt));
|
|
2712
|
+
const [presence] = await db.select({ runtimeState: agentPresence.runtimeState }).from(agentPresence).where(eq(agentPresence.agentId, agentId)).limit(1);
|
|
2713
|
+
const agentRuntimeState = presence?.runtimeState ?? null;
|
|
2714
|
+
if (filters?.runtimeState && agentRuntimeState !== filters.runtimeState) return [];
|
|
2715
|
+
const chatIds = rows.map((r) => r.chatId);
|
|
2716
|
+
const messageCounts = chatIds.length > 0 ? await db.select({
|
|
2717
|
+
chatId: inboxEntries.chatId,
|
|
2718
|
+
count: sql`count(*)::int`
|
|
2719
|
+
}).from(inboxEntries).where(and(eq(inboxEntries.inboxId, sql`(SELECT inbox_id FROM agents WHERE uuid = ${agentId})`), inArray(inboxEntries.chatId, chatIds))).groupBy(inboxEntries.chatId) : [];
|
|
2720
|
+
const countMap = new Map(messageCounts.map((r) => [r.chatId, r.count]));
|
|
2721
|
+
const firstMessages = chatIds.length > 0 ? await db.selectDistinctOn([messages.chatId], {
|
|
2722
|
+
chatId: messages.chatId,
|
|
2723
|
+
content: messages.content
|
|
2724
|
+
}).from(messages).where(inArray(messages.chatId, chatIds)).orderBy(messages.chatId, messages.createdAt) : [];
|
|
2725
|
+
const summaryMap = /* @__PURE__ */ new Map();
|
|
2726
|
+
for (const row of firstMessages) {
|
|
2727
|
+
const summary = extractSummary(row.content);
|
|
2728
|
+
if (summary) summaryMap.set(row.chatId, summary);
|
|
2729
|
+
}
|
|
2730
|
+
return rows.map((r) => ({
|
|
2731
|
+
agentId: r.agentId,
|
|
2732
|
+
chatId: r.chatId,
|
|
2733
|
+
state: r.state,
|
|
2734
|
+
runtimeState: agentRuntimeState,
|
|
2735
|
+
startedAt: r.chatCreatedAt.toISOString(),
|
|
2736
|
+
lastActivityAt: r.updatedAt.toISOString(),
|
|
2737
|
+
messageCount: countMap.get(r.chatId) ?? 0,
|
|
2738
|
+
summary: summaryMap.get(r.chatId) ?? null,
|
|
2739
|
+
topic: r.chatTopic ?? null
|
|
2740
|
+
}));
|
|
2741
|
+
}
|
|
2742
|
+
/** Get a single session's detail. */
|
|
2743
|
+
async function getSession(db, agentId, chatId) {
|
|
2744
|
+
const [row] = await db.select({
|
|
2745
|
+
agentId: agentChatSessions.agentId,
|
|
2746
|
+
chatId: agentChatSessions.chatId,
|
|
2747
|
+
state: agentChatSessions.state,
|
|
2748
|
+
updatedAt: agentChatSessions.updatedAt,
|
|
2749
|
+
chatCreatedAt: chats.createdAt,
|
|
2750
|
+
chatTopic: chats.topic
|
|
2751
|
+
}).from(agentChatSessions).innerJoin(chats, eq(agentChatSessions.chatId, chats.id)).where(and(eq(agentChatSessions.agentId, agentId), eq(agentChatSessions.chatId, chatId))).limit(1);
|
|
2752
|
+
if (!row) throw new NotFoundError(`Session (${agentId}, ${chatId}) not found`);
|
|
2753
|
+
const [presence] = await db.select({ runtimeState: agentPresence.runtimeState }).from(agentPresence).where(eq(agentPresence.agentId, agentId)).limit(1);
|
|
2754
|
+
const [countRow] = await db.select({ count: sql`count(*)::int` }).from(inboxEntries).where(and(eq(inboxEntries.inboxId, sql`(SELECT inbox_id FROM agents WHERE uuid = ${agentId})`), eq(inboxEntries.chatId, chatId)));
|
|
2755
|
+
const firstMsg = (await db.execute(sql`SELECT content FROM messages WHERE chat_id = ${chatId} ORDER BY created_at ASC LIMIT 1`))[0];
|
|
2756
|
+
const summary = firstMsg ? extractSummary(firstMsg.content) : null;
|
|
2757
|
+
return {
|
|
2758
|
+
agentId: row.agentId,
|
|
2759
|
+
chatId: row.chatId,
|
|
2760
|
+
state: row.state,
|
|
2761
|
+
runtimeState: presence?.runtimeState ?? null,
|
|
2762
|
+
startedAt: row.chatCreatedAt.toISOString(),
|
|
2763
|
+
lastActivityAt: row.updatedAt.toISOString(),
|
|
2764
|
+
messageCount: countRow?.count ?? 0,
|
|
2765
|
+
summary,
|
|
2766
|
+
topic: row.chatTopic ?? null
|
|
2767
|
+
};
|
|
2768
|
+
}
|
|
2769
|
+
/** List all sessions across all agents, with pagination. Scoped to organization. */
|
|
2770
|
+
async function listAllSessions(db, limit, cursor, filters) {
|
|
2771
|
+
const conditions = [];
|
|
2772
|
+
if (filters?.state) conditions.push(eq(agentChatSessions.state, filters.state));
|
|
2773
|
+
else conditions.push(ne(agentChatSessions.state, "evicted"));
|
|
2774
|
+
if (filters?.agentId) conditions.push(eq(agentChatSessions.agentId, filters.agentId));
|
|
2775
|
+
if (filters?.organizationId) conditions.push(eq(agents.organizationId, filters.organizationId));
|
|
2776
|
+
if (cursor) conditions.push(sql`${agentChatSessions.updatedAt} < ${new Date(cursor)}`);
|
|
2777
|
+
const rows = await db.select({
|
|
2778
|
+
agentId: agentChatSessions.agentId,
|
|
2779
|
+
chatId: agentChatSessions.chatId,
|
|
2780
|
+
state: agentChatSessions.state,
|
|
2781
|
+
updatedAt: agentChatSessions.updatedAt,
|
|
2782
|
+
chatCreatedAt: chats.createdAt,
|
|
2783
|
+
chatTopic: chats.topic
|
|
2784
|
+
}).from(agentChatSessions).innerJoin(chats, eq(agentChatSessions.chatId, chats.id)).innerJoin(agents, eq(agentChatSessions.agentId, agents.uuid)).where(conditions.length > 0 ? and(...conditions) : void 0).orderBy(desc(agentChatSessions.updatedAt)).limit(limit + 1);
|
|
2785
|
+
const hasMore = rows.length > limit;
|
|
2786
|
+
const items = hasMore ? rows.slice(0, limit) : rows;
|
|
2787
|
+
const agentIds = [...new Set(items.map((r) => r.agentId))];
|
|
2788
|
+
const presenceRows = agentIds.length > 0 ? await db.select({
|
|
2789
|
+
agentId: agentPresence.agentId,
|
|
2790
|
+
runtimeState: agentPresence.runtimeState
|
|
2791
|
+
}).from(agentPresence).where(inArray(agentPresence.agentId, agentIds)) : [];
|
|
2792
|
+
const runtimeMap = new Map(presenceRows.map((r) => [r.agentId, r.runtimeState]));
|
|
2793
|
+
const chatIds = [...new Set(items.map((r) => r.chatId))];
|
|
2794
|
+
const firstMessages = chatIds.length > 0 ? await db.selectDistinctOn([messages.chatId], {
|
|
2795
|
+
chatId: messages.chatId,
|
|
2796
|
+
content: messages.content
|
|
2797
|
+
}).from(messages).where(inArray(messages.chatId, chatIds)).orderBy(messages.chatId, messages.createdAt) : [];
|
|
2798
|
+
const summaryMap = /* @__PURE__ */ new Map();
|
|
2799
|
+
for (const row of firstMessages) {
|
|
2800
|
+
const summary = extractSummary(row.content);
|
|
2801
|
+
if (summary) summaryMap.set(row.chatId, summary);
|
|
2802
|
+
}
|
|
2803
|
+
const last = items[items.length - 1];
|
|
2804
|
+
const nextCursor = hasMore && last ? last.updatedAt.toISOString() : null;
|
|
2805
|
+
return {
|
|
2806
|
+
items: items.map((r) => ({
|
|
2807
|
+
agentId: r.agentId,
|
|
2808
|
+
chatId: r.chatId,
|
|
2809
|
+
state: r.state,
|
|
2810
|
+
runtimeState: runtimeMap.get(r.agentId) ?? null,
|
|
2811
|
+
startedAt: r.chatCreatedAt.toISOString(),
|
|
2812
|
+
lastActivityAt: r.updatedAt.toISOString(),
|
|
2813
|
+
messageCount: 0,
|
|
2814
|
+
summary: summaryMap.get(r.chatId) ?? null,
|
|
2815
|
+
topic: r.chatTopic ?? null
|
|
2816
|
+
})),
|
|
2817
|
+
nextCursor
|
|
2818
|
+
};
|
|
2819
|
+
}
|
|
2820
|
+
/** Commit `active → suspended`. No-op on suspended/evicted. Throws if row is missing. */
|
|
2821
|
+
async function suspendSession(db, agentId, chatId, organizationId, notifier) {
|
|
2822
|
+
return transitionSessionState(db, agentId, chatId, "suspended", ["active"], organizationId, notifier);
|
|
2823
|
+
}
|
|
2824
|
+
/** Commit `suspended → evicted` (terminal — listings hide it, revival defense blocks resurrection). */
|
|
2825
|
+
async function archiveSession(db, agentId, chatId, organizationId, notifier) {
|
|
2826
|
+
return transitionSessionState(db, agentId, chatId, "evicted", ["suspended"], organizationId, notifier);
|
|
2827
|
+
}
|
|
2828
|
+
async function transitionSessionState(db, agentId, chatId, target, from, organizationId, notifier) {
|
|
2829
|
+
const now = /* @__PURE__ */ new Date();
|
|
2830
|
+
let finalState = null;
|
|
2831
|
+
let transitioned = false;
|
|
2832
|
+
await db.transaction(async (tx) => {
|
|
2833
|
+
const [existing] = await tx.select({ state: agentChatSessions.state }).from(agentChatSessions).where(and(eq(agentChatSessions.agentId, agentId), eq(agentChatSessions.chatId, chatId))).for("update");
|
|
2834
|
+
if (!existing) return;
|
|
2835
|
+
const current = existing.state;
|
|
2836
|
+
finalState = current;
|
|
2837
|
+
if (!from.includes(current)) return;
|
|
2838
|
+
await tx.update(agentChatSessions).set({
|
|
2839
|
+
state: target,
|
|
2840
|
+
updatedAt: now
|
|
2841
|
+
}).where(and(eq(agentChatSessions.agentId, agentId), eq(agentChatSessions.chatId, chatId)));
|
|
2842
|
+
const [counts] = await tx.select({
|
|
2843
|
+
active: sql`count(*) FILTER (WHERE ${agentChatSessions.state} = 'active')::int`,
|
|
2844
|
+
total: sql`count(*) FILTER (WHERE ${agentChatSessions.state} != 'evicted')::int`
|
|
2845
|
+
}).from(agentChatSessions).where(eq(agentChatSessions.agentId, agentId));
|
|
2846
|
+
await tx.update(agentPresence).set({
|
|
2847
|
+
activeSessions: counts?.active ?? 0,
|
|
2848
|
+
totalSessions: counts?.total ?? 0,
|
|
2849
|
+
lastSeenAt: now
|
|
2850
|
+
}).where(eq(agentPresence.agentId, agentId));
|
|
2851
|
+
if (target === "evicted") await markSupersededByChat(tx, chatId, "chat_archived");
|
|
2852
|
+
finalState = target;
|
|
2853
|
+
transitioned = true;
|
|
2854
|
+
});
|
|
2855
|
+
if (finalState === null) throw new NotFoundError(`Session (${agentId}, ${chatId}) not found`);
|
|
2856
|
+
if (transitioned && notifier) notifier.notifySessionStateChange(agentId, chatId, target, organizationId).catch(() => {});
|
|
2857
|
+
return {
|
|
2858
|
+
state: finalState,
|
|
2859
|
+
transitioned
|
|
2860
|
+
};
|
|
2861
|
+
}
|
|
2862
|
+
/**
|
|
2863
|
+
* Filter sessions to only those where the given agent is also a participant in the chat.
|
|
2864
|
+
* Used when a non-manager views sessions of an org-visible agent — they should only see
|
|
2865
|
+
* sessions for chats they participate in.
|
|
2866
|
+
*/
|
|
2867
|
+
async function filterSessionsByParticipant(db, sessions, participantAgentId) {
|
|
2868
|
+
if (sessions.length === 0) return [];
|
|
2869
|
+
const chatIds = sessions.map((s) => s.chatId);
|
|
2870
|
+
const participantRows = await db.select({ chatId: chatMembership.chatId }).from(chatMembership).where(and(inArray(chatMembership.chatId, chatIds), eq(chatMembership.agentId, participantAgentId), eq(chatMembership.accessMode, "speaker")));
|
|
2871
|
+
const allowedChatIds = new Set(participantRows.map((r) => r.chatId));
|
|
2872
|
+
return sessions.filter((s) => allowedChatIds.has(s.chatId));
|
|
2873
|
+
}
|
|
2874
|
+
/**
|
|
2875
|
+
* Member-facing chat service backing `/me/chats*` endpoints (chat-first
|
|
2876
|
+
* workspace).
|
|
2877
|
+
*
|
|
2878
|
+
* Responsibilities:
|
|
2879
|
+
* - Cursor-paginated conversation list (single-stream JOIN over the
|
|
2880
|
+
* unified `chat_membership` + `chat_user_state` tables).
|
|
2881
|
+
* - Create a new chat (no dedupe, runs `recomputeChatWatchers` after).
|
|
2882
|
+
* - Add participants (idempotent, UPSERT into `chat_membership`,
|
|
2883
|
+
* runs `recomputeChatWatchers` after).
|
|
2884
|
+
* - Mark-read (UPSERT into `chat_user_state`).
|
|
2885
|
+
* - Join → watcher to speaker (delegates to `watcher.ts`).
|
|
2886
|
+
* - Leave → speaker to watcher or detach (delegates to `watcher.ts`).
|
|
2887
|
+
*
|
|
2888
|
+
* See proposals/chat-data-model-restructure.20260512.md §8 (schema)
|
|
2889
|
+
* and §11.1 (per-route mapping).
|
|
2890
|
+
*/
|
|
2891
|
+
function encodeCursor(lastMessageAt, chatId) {
|
|
2892
|
+
const payload = `${lastMessageAt ? lastMessageAt.toISOString() : ""}|${chatId}`;
|
|
2893
|
+
return Buffer.from(payload, "utf8").toString("base64url");
|
|
2894
|
+
}
|
|
2895
|
+
function decodeCursor(cursor) {
|
|
2896
|
+
try {
|
|
2897
|
+
const decoded = Buffer.from(cursor, "base64url").toString("utf8");
|
|
2898
|
+
const sep = decoded.indexOf("|");
|
|
2899
|
+
if (sep < 0) return null;
|
|
2900
|
+
const tsPart = decoded.slice(0, sep);
|
|
2901
|
+
const chatId = decoded.slice(sep + 1);
|
|
2902
|
+
if (!chatId) return null;
|
|
2903
|
+
const lastMessageAt = tsPart.length > 0 ? new Date(tsPart) : null;
|
|
2904
|
+
if (lastMessageAt && Number.isNaN(lastMessageAt.getTime())) return null;
|
|
2905
|
+
return {
|
|
2906
|
+
lastMessageAt,
|
|
2907
|
+
chatId
|
|
2908
|
+
};
|
|
2909
|
+
} catch {
|
|
2910
|
+
return null;
|
|
2911
|
+
}
|
|
2912
|
+
}
|
|
2913
|
+
const { ACTIVE, ARCHIVED, DELETED } = CHAT_ENGAGEMENT_STATUSES;
|
|
2914
|
+
/**
|
|
2915
|
+
* SQL predicate for each engagement view tab. `deleted` is never a valid view
|
|
2916
|
+
* value — deleted rows are reachable only through `GET /chats/:chatId` + the
|
|
2917
|
+
* Restore banner on the chat detail page.
|
|
2918
|
+
*/
|
|
2919
|
+
const ENGAGEMENT_VIEW_PREDICATE = {
|
|
2920
|
+
active: sql`COALESCE(cus.engagement_status, ${ACTIVE}) = ${ACTIVE}`,
|
|
2921
|
+
archived: sql`COALESCE(cus.engagement_status, ${ACTIVE}) = ${ARCHIVED}`,
|
|
2922
|
+
all: sql`COALESCE(cus.engagement_status, ${ACTIVE}) IN (${ACTIVE}, ${ARCHIVED})`
|
|
2923
|
+
};
|
|
2924
|
+
/**
|
|
2925
|
+
* Write the caller's engagement state for this chat. UPSERT into
|
|
2926
|
+
* `chat_user_state` — the row may not yet exist (the user might not have
|
|
2927
|
+
* marked-read or been @-mentioned), so an INSERT with the engagement value
|
|
2928
|
+
* is the first write; subsequent transitions are UPDATEs.
|
|
2929
|
+
*
|
|
2930
|
+
* Idempotent. Mirrors the UPSERT shape used by `markMeChatRead`.
|
|
2931
|
+
*/
|
|
2932
|
+
async function setChatEngagement(db, chatId, agentId, status) {
|
|
2933
|
+
await db.insert(chatUserState).values({
|
|
2934
|
+
chatId,
|
|
2935
|
+
agentId,
|
|
2936
|
+
unreadMentionCount: 0,
|
|
2937
|
+
engagementStatus: status
|
|
2938
|
+
}).onConflictDoUpdate({
|
|
2939
|
+
target: [chatUserState.chatId, chatUserState.agentId],
|
|
2940
|
+
set: { engagementStatus: status }
|
|
2941
|
+
});
|
|
2942
|
+
}
|
|
2943
|
+
/**
|
|
2944
|
+
* Read the caller's engagement state. Returns `'active'` when no
|
|
2945
|
+
* `chat_user_state` row exists yet (lazy-materialised; matches the SQL
|
|
2946
|
+
* `COALESCE(..., 'active')` used elsewhere).
|
|
2947
|
+
*/
|
|
2948
|
+
async function getCallerEngagement(db, chatId, agentId) {
|
|
2949
|
+
const [row] = await db.select({ engagementStatus: chatUserState.engagementStatus }).from(chatUserState).where(and(eq(chatUserState.chatId, chatId), eq(chatUserState.agentId, agentId))).limit(1);
|
|
2950
|
+
return row?.engagementStatus ?? ACTIVE;
|
|
2951
|
+
}
|
|
2952
|
+
const KNOWN_NON_MANUAL_PREDICATE = sql`(
|
|
2953
|
+
(c.metadata->>'source' = 'github' AND c.metadata->>'entityType' IN (${sql.join(GITHUB_ENTITY_TYPES.map((t) => sql`${t}`), sql.raw(", "))}))
|
|
2954
|
+
OR c.metadata->>'source' = 'feishu'
|
|
2955
|
+
)`;
|
|
2956
|
+
const chatSourceSqlExpression = sql`CASE
|
|
2957
|
+
${sql.join(GITHUB_ENTITY_TYPES.map((t) => sql`WHEN c.metadata->>'source' = 'github' AND c.metadata->>'entityType' = ${t} THEN ${`github_${t}`}`), sql.raw("\n "))}
|
|
2958
|
+
WHEN c.metadata->>'source' = 'feishu' THEN 'feishu'
|
|
2959
|
+
ELSE 'manual'
|
|
2960
|
+
END`;
|
|
2961
|
+
function sourceFilterSql(source) {
|
|
2962
|
+
switch (source) {
|
|
2963
|
+
case "manual": return sql`(${KNOWN_NON_MANUAL_PREDICATE}) IS NOT TRUE`;
|
|
2964
|
+
case "github_issue": return sql`(c.metadata->>'source' = 'github' AND c.metadata->>'entityType' = 'issue')`;
|
|
2965
|
+
case "github_pull_request": return sql`(c.metadata->>'source' = 'github' AND c.metadata->>'entityType' = 'pull_request')`;
|
|
2966
|
+
case "github_discussion": return sql`(c.metadata->>'source' = 'github' AND c.metadata->>'entityType' = 'discussion')`;
|
|
2967
|
+
case "github_commit": return sql`(c.metadata->>'source' = 'github' AND c.metadata->>'entityType' = 'commit')`;
|
|
2968
|
+
case "feishu": return sql`(c.metadata->>'source' = 'feishu')`;
|
|
2969
|
+
}
|
|
2970
|
+
}
|
|
2971
|
+
/**
|
|
2972
|
+
* GET /me/chats — cursor-paginated conversation list.
|
|
2973
|
+
*
|
|
2974
|
+
* SQL strategy:
|
|
2975
|
+
* - Single-stream query: `chats JOIN chat_membership LEFT JOIN
|
|
2976
|
+
* chat_user_state`. The membership row carries access_mode
|
|
2977
|
+
* (speaker → "participant" / watcher → "watching"); the user
|
|
2978
|
+
* state row supplies the unread counter (COALESCE → 0 when
|
|
2979
|
+
* row is missing).
|
|
2980
|
+
* - Filter `parent_chat_id IS NULL` (nested chats not surfaced in v1).
|
|
2981
|
+
* - Filter `c.organization_id = ?` to defend against historical
|
|
2982
|
+
* cross-org pollution rows that may still reference the caller
|
|
2983
|
+
* (see fix/cross-org-direct-chat-pollution).
|
|
2984
|
+
* - Sort `(last_message_at DESC NULLS LAST, chat_id DESC)`.
|
|
2985
|
+
* - Cursor narrows the result to rows STRICTLY before the cursor.
|
|
2986
|
+
* - Followed by a participants-list lookup for the page only.
|
|
2987
|
+
*/
|
|
2988
|
+
async function listMeChats(db, humanAgentId, organizationId, query) {
|
|
2989
|
+
const limit = query.limit;
|
|
2990
|
+
const cursor = query.cursor ? decodeCursor(query.cursor) : null;
|
|
2991
|
+
if (query.cursor && !cursor) throw new BadRequestError("Invalid cursor");
|
|
2992
|
+
const filterUnreadOnly = query.filter === "unread";
|
|
2993
|
+
const filterWatchingOnly = query.filter === "watching";
|
|
2994
|
+
const engagementPredicate = ENGAGEMENT_VIEW_PREDICATE[query.engagement];
|
|
2995
|
+
const sourcePredicate = query.source ? sourceFilterSql(query.source) : sql`TRUE`;
|
|
2996
|
+
const cursorTsIso = cursor?.lastMessageAt ? cursor.lastMessageAt.toISOString() : null;
|
|
2997
|
+
const cursorPredicate = !cursor ? sql`TRUE` : cursor.lastMessageAt === null ? sql`(c.last_message_at IS NULL AND c.id < ${cursor.chatId})` : sql`(c.last_message_at IS NULL
|
|
2998
|
+
OR c.last_message_at < ${cursorTsIso}::timestamptz
|
|
2999
|
+
OR (c.last_message_at = ${cursorTsIso}::timestamptz AND c.id < ${cursor.chatId}))`;
|
|
3000
|
+
const rawRows = await db.execute(sql`
|
|
3001
|
+
SELECT
|
|
3002
|
+
c.id AS chat_id,
|
|
3003
|
+
c.type AS type,
|
|
3004
|
+
c.topic AS topic,
|
|
3005
|
+
c.parent_chat_id AS parent_chat_id,
|
|
3006
|
+
c.last_message_at AS last_message_at,
|
|
3007
|
+
c.last_message_preview AS last_message_preview,
|
|
3008
|
+
(SELECT count(*) FROM chat_membership
|
|
3009
|
+
WHERE chat_id = c.id AND access_mode = 'speaker') AS participant_count,
|
|
3010
|
+
cm.access_mode AS access_mode,
|
|
3011
|
+
COALESCE(cus.unread_mention_count, 0) AS unread_mention_count,
|
|
3012
|
+
COALESCE(cus.engagement_status, ${ACTIVE}) AS engagement_status
|
|
3013
|
+
FROM chats c
|
|
3014
|
+
JOIN chat_membership cm
|
|
3015
|
+
ON cm.chat_id = c.id AND cm.agent_id = ${humanAgentId}
|
|
3016
|
+
LEFT JOIN chat_user_state cus
|
|
3017
|
+
ON cus.chat_id = c.id AND cus.agent_id = ${humanAgentId}
|
|
3018
|
+
WHERE c.parent_chat_id IS NULL
|
|
3019
|
+
/* Scope to the caller's org. Without this, cross-org dirty
|
|
3020
|
+
chats whose chat_membership still references the caller's
|
|
3021
|
+
human agent (historical pollution — see
|
|
3022
|
+
fix/cross-org-direct-chat-pollution) would leak into the
|
|
3023
|
+
list and 404 on click via requireChatAccess. */
|
|
3024
|
+
AND c.organization_id = ${organizationId}
|
|
3025
|
+
AND (${!filterUnreadOnly}::bool OR COALESCE(cus.unread_mention_count, 0) > 0)
|
|
3026
|
+
AND (${!filterWatchingOnly}::bool OR cm.access_mode = 'watcher')
|
|
3027
|
+
AND ${engagementPredicate}
|
|
3028
|
+
AND ${sourcePredicate}
|
|
3029
|
+
AND ${cursorPredicate}
|
|
3030
|
+
ORDER BY c.last_message_at DESC NULLS LAST, c.id DESC
|
|
3031
|
+
LIMIT ${limit + 1}
|
|
3032
|
+
`);
|
|
3033
|
+
const toDate = (v) => {
|
|
3034
|
+
if (v === null) return null;
|
|
3035
|
+
return v instanceof Date ? v : new Date(v);
|
|
3036
|
+
};
|
|
3037
|
+
const hasMore = rawRows.length > limit;
|
|
3038
|
+
const pageRaw = hasMore ? rawRows.slice(0, limit) : rawRows;
|
|
3039
|
+
const last = pageRaw[pageRaw.length - 1];
|
|
3040
|
+
const nextCursor = hasMore && last ? encodeCursor(toDate(last.last_message_at), last.chat_id) : null;
|
|
3041
|
+
if (pageRaw.length === 0) return {
|
|
3042
|
+
rows: [],
|
|
3043
|
+
nextCursor: null
|
|
3044
|
+
};
|
|
3045
|
+
const chatIds = pageRaw.map((r) => r.chat_id);
|
|
3046
|
+
const participantRows = await db.select({
|
|
3047
|
+
chatId: chatMembership.chatId,
|
|
3048
|
+
agentId: chatMembership.agentId,
|
|
3049
|
+
displayName: agents.displayName,
|
|
3050
|
+
type: agents.type,
|
|
3051
|
+
avatarColorToken: agents.avatarColorToken,
|
|
3052
|
+
avatarImageUpdatedAt: agents.avatarImageUpdatedAt,
|
|
3053
|
+
sessionState: agentChatSessions.state
|
|
3054
|
+
}).from(chatMembership).innerJoin(agents, eq(chatMembership.agentId, agents.uuid)).leftJoin(agentChatSessions, and(eq(agentChatSessions.agentId, chatMembership.agentId), eq(agentChatSessions.chatId, chatMembership.chatId))).where(and(inArray(chatMembership.chatId, chatIds), eq(chatMembership.accessMode, "speaker")));
|
|
3055
|
+
const participantsByChat = /* @__PURE__ */ new Map();
|
|
3056
|
+
const engagedByChat = /* @__PURE__ */ new Map();
|
|
3057
|
+
for (const p of participantRows) {
|
|
3058
|
+
const list = participantsByChat.get(p.chatId) ?? [];
|
|
3059
|
+
list.push({
|
|
3060
|
+
agentId: p.agentId,
|
|
3061
|
+
displayName: p.displayName,
|
|
3062
|
+
type: p.type,
|
|
3063
|
+
avatarColorToken: p.avatarColorToken,
|
|
3064
|
+
avatarImageUrl: agentAvatarImageUrl(p.agentId, p.avatarImageUpdatedAt)
|
|
3065
|
+
});
|
|
3066
|
+
participantsByChat.set(p.chatId, list);
|
|
3067
|
+
if (p.sessionState === "active") {
|
|
3068
|
+
const engaged = engagedByChat.get(p.chatId) ?? [];
|
|
3069
|
+
engaged.push(p.agentId);
|
|
3070
|
+
engagedByChat.set(p.chatId, engaged);
|
|
3071
|
+
}
|
|
3072
|
+
}
|
|
3073
|
+
const liveActivityByChat = await deriveLiveActivity(db, chatIds);
|
|
3074
|
+
const firstMessageRows = chatIds.length > 0 ? await db.selectDistinctOn([messages.chatId], {
|
|
3075
|
+
chatId: messages.chatId,
|
|
3076
|
+
content: messages.content
|
|
3077
|
+
}).from(messages).where(inArray(messages.chatId, chatIds)).orderBy(messages.chatId, messages.createdAt) : [];
|
|
3078
|
+
const firstMessageSummary = /* @__PURE__ */ new Map();
|
|
3079
|
+
for (const row of firstMessageRows) {
|
|
3080
|
+
const s = extractSummary(row.content);
|
|
3081
|
+
if (s) firstMessageSummary.set(row.chatId, s);
|
|
3082
|
+
}
|
|
3083
|
+
return {
|
|
3084
|
+
rows: pageRaw.map((r) => {
|
|
3085
|
+
const participants = participantsByChat.get(r.chat_id) ?? [];
|
|
3086
|
+
const title = resolveChatTitle(r.topic, firstMessageSummary.get(r.chat_id) ?? null, participants, humanAgentId);
|
|
3087
|
+
const isSpeaker = r.access_mode === "speaker";
|
|
3088
|
+
return {
|
|
3089
|
+
chatId: r.chat_id,
|
|
3090
|
+
type: r.type,
|
|
3091
|
+
membershipKind: isSpeaker ? "participant" : "watching",
|
|
3092
|
+
title,
|
|
3093
|
+
topic: r.topic,
|
|
3094
|
+
participants,
|
|
3095
|
+
participantCount: Number(r.participant_count),
|
|
3096
|
+
lastMessageAt: toDate(r.last_message_at)?.toISOString() ?? null,
|
|
3097
|
+
lastMessagePreview: r.last_message_preview,
|
|
3098
|
+
unreadMentionCount: r.unread_mention_count,
|
|
3099
|
+
canReply: isSpeaker,
|
|
3100
|
+
engagementStatus: r.engagement_status,
|
|
3101
|
+
engagedAgentIds: engagedByChat.get(r.chat_id) ?? [],
|
|
3102
|
+
liveActivity: liveActivityByChat.get(r.chat_id) ?? null
|
|
3103
|
+
};
|
|
3104
|
+
}),
|
|
3105
|
+
nextCursor
|
|
3106
|
+
};
|
|
3107
|
+
}
|
|
3108
|
+
/**
|
|
3109
|
+
* Per-chat live activity, derived from the most recent `session_events` row.
|
|
3110
|
+
*
|
|
3111
|
+
* Returns a chatId → LiveActivity map; chats with no activity (or where the
|
|
3112
|
+
* latest event is terminal / stale) are absent from the map (caller treats
|
|
3113
|
+
* absence as null).
|
|
3114
|
+
*/
|
|
3115
|
+
async function deriveLiveActivity(db, chatIds) {
|
|
3116
|
+
if (chatIds.length === 0) return /* @__PURE__ */ new Map();
|
|
3117
|
+
const chatIdInClause = sql.join(chatIds.map((id) => sql`${id}`), sql`, `);
|
|
3118
|
+
const rows = (await db.execute(sql`
|
|
3119
|
+
SELECT acs.agent_id AS agent_id,
|
|
3120
|
+
acs.chat_id AS chat_id,
|
|
3121
|
+
e.kind AS kind,
|
|
3122
|
+
e.payload AS payload,
|
|
3123
|
+
e.created_at AS created_at
|
|
3124
|
+
FROM agent_chat_sessions acs
|
|
3125
|
+
CROSS JOIN LATERAL (
|
|
3126
|
+
SELECT kind, payload, created_at, seq
|
|
3127
|
+
FROM session_events se
|
|
3128
|
+
WHERE se.agent_id = acs.agent_id
|
|
3129
|
+
AND se.chat_id = acs.chat_id
|
|
3130
|
+
ORDER BY se.seq DESC
|
|
3131
|
+
LIMIT 1
|
|
3132
|
+
) e
|
|
3133
|
+
WHERE acs.chat_id IN (${chatIdInClause})
|
|
3134
|
+
AND acs.state <> 'evicted'
|
|
3135
|
+
`)).map((r) => ({
|
|
3136
|
+
agent_id: r.agent_id,
|
|
3137
|
+
chat_id: r.chat_id,
|
|
3138
|
+
kind: r.kind,
|
|
3139
|
+
payload: r.payload,
|
|
3140
|
+
created_at: r.created_at
|
|
3141
|
+
}));
|
|
3142
|
+
const now = Date.now();
|
|
3143
|
+
const byChat = /* @__PURE__ */ new Map();
|
|
3144
|
+
for (const row of rows) {
|
|
3145
|
+
const activity = toLiveActivity(row);
|
|
3146
|
+
if (!activity) continue;
|
|
3147
|
+
const createdAtMs = new Date(row.created_at).getTime();
|
|
3148
|
+
if (now - createdAtMs > 6e4) continue;
|
|
3149
|
+
const existing = byChat.get(row.chat_id);
|
|
3150
|
+
if (!existing || createdAtMs > existing.createdAtMs) byChat.set(row.chat_id, {
|
|
3151
|
+
activity,
|
|
3152
|
+
createdAtMs
|
|
3153
|
+
});
|
|
3154
|
+
}
|
|
3155
|
+
const out = /* @__PURE__ */ new Map();
|
|
3156
|
+
for (const [chatId, { activity }] of byChat) out.set(chatId, activity);
|
|
3157
|
+
return out;
|
|
3158
|
+
}
|
|
3159
|
+
/**
|
|
3160
|
+
* Translate a `session_events` row into a `LiveActivity`, or null when the
|
|
3161
|
+
* kind is terminal (`turn_end` / `error`) or unrecognised. Pure & exported
|
|
3162
|
+
* for unit testing.
|
|
3163
|
+
*/
|
|
3164
|
+
function toLiveActivity(row) {
|
|
3165
|
+
const startedAt = new Date(row.created_at).toISOString();
|
|
3166
|
+
switch (row.kind) {
|
|
3167
|
+
case "tool_call": {
|
|
3168
|
+
const payload = row.payload ?? {};
|
|
3169
|
+
const label = typeof payload.name === "string" && payload.name.length > 0 ? payload.name : "Tool";
|
|
3170
|
+
return {
|
|
3171
|
+
agentId: row.agent_id,
|
|
3172
|
+
kind: "tool_call",
|
|
3173
|
+
label,
|
|
3174
|
+
startedAt
|
|
3175
|
+
};
|
|
3176
|
+
}
|
|
3177
|
+
case "thinking": return {
|
|
3178
|
+
agentId: row.agent_id,
|
|
3179
|
+
kind: "thinking",
|
|
3180
|
+
label: "Thinking",
|
|
3181
|
+
startedAt
|
|
3182
|
+
};
|
|
3183
|
+
case "assistant_text": return {
|
|
3184
|
+
agentId: row.agent_id,
|
|
3185
|
+
kind: "assistant_text",
|
|
3186
|
+
label: "Writing",
|
|
3187
|
+
startedAt
|
|
3188
|
+
};
|
|
3189
|
+
default: return null;
|
|
3190
|
+
}
|
|
3191
|
+
}
|
|
3192
|
+
/**
|
|
3193
|
+
* Title resolution priority:
|
|
3194
|
+
*
|
|
3195
|
+
* 1. `chat.topic` (manual, set via `PATCH /chats/:chatId`)
|
|
3196
|
+
* 2. First message summary (auto, ≤ 50 chars from `extractSummary`)
|
|
3197
|
+
* 3. Participant join (fallback when chat has no messages yet)
|
|
3198
|
+
*/
|
|
3199
|
+
function resolveChatTitle(topic, firstMessageSummary, participants, selfAgentId) {
|
|
3200
|
+
if (topic && topic.length > 0) return topic;
|
|
3201
|
+
if (firstMessageSummary && firstMessageSummary.length > 0) return firstMessageSummary;
|
|
3202
|
+
const others = participants.filter((p) => p.agentId !== selfAgentId);
|
|
3203
|
+
if (others.length === 0) return "Empty chat";
|
|
3204
|
+
if (others.length <= 3) return others.map((p) => p.displayName).join(", ");
|
|
3205
|
+
return `${others[0]?.displayName}, ${others[1]?.displayName} +${others.length - 2}`;
|
|
3206
|
+
}
|
|
3207
|
+
async function createMeChat(db, humanAgentId, organizationId, body) {
|
|
3208
|
+
const distinctIds = [...new Set(body.participantIds)].filter((id) => id !== humanAgentId);
|
|
3209
|
+
if (distinctIds.length === 0) throw new BadRequestError("At least one non-self participant required");
|
|
3210
|
+
const allIds = [humanAgentId, ...distinctIds];
|
|
3211
|
+
const found = await db.select({
|
|
3212
|
+
uuid: agents.uuid,
|
|
3213
|
+
organizationId: agents.organizationId,
|
|
3214
|
+
type: agents.type,
|
|
3215
|
+
visibility: agents.visibility,
|
|
3216
|
+
managerId: agents.managerId
|
|
3217
|
+
}).from(agents).where(inArray(agents.uuid, allIds));
|
|
3218
|
+
if (found.length !== allIds.length) {
|
|
3219
|
+
const foundSet = new Set(found.map((a) => a.uuid));
|
|
3220
|
+
throw new BadRequestError(`Agents not found: ${allIds.filter((id) => !foundSet.has(id)).join(", ")}`);
|
|
3221
|
+
}
|
|
3222
|
+
const crossOrg = found.filter((a) => a.organizationId !== organizationId);
|
|
3223
|
+
if (crossOrg.length > 0) throw new BadRequestError(`Cross-organization chat not allowed: ${crossOrg.map((a) => a.uuid).join(", ")}`);
|
|
3224
|
+
const caller = found.find((a) => a.uuid === humanAgentId);
|
|
3225
|
+
if (!caller) throw new BadRequestError("Caller agent not found in the chat's organization");
|
|
3226
|
+
const privateNotOwned = found.filter((a) => a.uuid !== humanAgentId && a.visibility === AGENT_VISIBILITY.PRIVATE && a.managerId !== caller.managerId);
|
|
3227
|
+
if (privateNotOwned.length > 0) throw new ForbiddenError(`Only the owner can add a private agent to a chat: ${privateNotOwned.map((a) => a.uuid).join(", ")}`);
|
|
3228
|
+
const chatType = distinctIds.length === 1 ? "direct" : "group";
|
|
3229
|
+
const chatId = randomUUID();
|
|
3230
|
+
const topic = body.topic ?? null;
|
|
3231
|
+
await db.transaction(async (tx) => {
|
|
3232
|
+
await tx.insert(chats).values({
|
|
3233
|
+
id: chatId,
|
|
3234
|
+
organizationId,
|
|
3235
|
+
type: chatType,
|
|
3236
|
+
topic
|
|
3237
|
+
});
|
|
3238
|
+
await addChatParticipants(tx, chatId, allIds.map((agentId) => ({
|
|
3239
|
+
agentId,
|
|
3240
|
+
role: agentId === humanAgentId ? "owner" : "member"
|
|
3241
|
+
})));
|
|
3242
|
+
await recomputeChatWatchers(tx, chatId);
|
|
3243
|
+
});
|
|
3244
|
+
invalidateChatAudience(chatId);
|
|
3245
|
+
return { chatId };
|
|
3246
|
+
}
|
|
3247
|
+
async function addMeChatParticipants(db, chatId, callerHumanAgentId, callerOrganizationId, body) {
|
|
3248
|
+
const distinct = [...new Set(body.participantIds)];
|
|
3249
|
+
if (distinct.length === 0) throw new BadRequestError("At least one participant required");
|
|
3250
|
+
const [chat] = await db.select({
|
|
3251
|
+
id: chats.id,
|
|
3252
|
+
organizationId: chats.organizationId,
|
|
3253
|
+
type: chats.type
|
|
3254
|
+
}).from(chats).where(eq(chats.id, chatId)).limit(1);
|
|
3255
|
+
if (!chat) throw new NotFoundError(`Chat "${chatId}" not found`);
|
|
3256
|
+
if (chat.organizationId !== callerOrganizationId) throw new NotFoundError(`Chat "${chatId}" not found`);
|
|
3257
|
+
const [callerRow] = await db.select({ ownerMemberId: agents.managerId }).from(chatMembership).innerJoin(agents, eq(agents.uuid, chatMembership.agentId)).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.agentId, callerHumanAgentId), eq(chatMembership.accessMode, "speaker"))).limit(1);
|
|
3258
|
+
if (!callerRow) throw new NotFoundError(`Chat "${chatId}" not found`);
|
|
3259
|
+
const callerMemberId = callerRow.ownerMemberId;
|
|
3260
|
+
const found = await db.select({
|
|
3261
|
+
uuid: agents.uuid,
|
|
3262
|
+
organizationId: agents.organizationId,
|
|
3263
|
+
type: agents.type,
|
|
3264
|
+
visibility: agents.visibility,
|
|
3265
|
+
managerId: agents.managerId
|
|
3266
|
+
}).from(agents).where(inArray(agents.uuid, distinct));
|
|
3267
|
+
if (found.length !== distinct.length) {
|
|
3268
|
+
const foundSet = new Set(found.map((a) => a.uuid));
|
|
3269
|
+
throw new BadRequestError(`Agents not found: ${distinct.filter((id) => !foundSet.has(id)).join(", ")}`);
|
|
3270
|
+
}
|
|
3271
|
+
const crossOrg = found.filter((a) => a.organizationId !== chat.organizationId);
|
|
3272
|
+
if (crossOrg.length > 0) throw new BadRequestError(`Cross-organization participant rejected: ${crossOrg.map((a) => a.uuid).join(", ")}`);
|
|
3273
|
+
const privateNotOwned = found.filter((a) => a.visibility === AGENT_VISIBILITY.PRIVATE && a.managerId !== callerMemberId);
|
|
3274
|
+
if (privateNotOwned.length > 0) throw new ForbiddenError(`Only the owner can add a private agent to a chat: ${privateNotOwned.map((a) => a.uuid).join(", ")}`);
|
|
3275
|
+
await db.transaction(async (tx) => {
|
|
3276
|
+
const existingSpeakers = await tx.select({ agentId: chatMembership.agentId }).from(chatMembership).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.accessMode, "speaker")));
|
|
3277
|
+
const existingSpeakerSet = new Set(existingSpeakers.map((e) => e.agentId));
|
|
3278
|
+
const toUpsert = distinct.filter((id) => !existingSpeakerSet.has(id));
|
|
3279
|
+
if (toUpsert.length === 0) {
|
|
3280
|
+
await recomputeChatWatchers(tx, chatId);
|
|
3281
|
+
return;
|
|
3282
|
+
}
|
|
3283
|
+
if (existingSpeakers.length + toUpsert.length >= 3 && chat.type === "direct") await changeChatType(tx, chatId, "group");
|
|
3284
|
+
await addChatParticipants(tx, chatId, toUpsert.map((agentId) => ({
|
|
3285
|
+
agentId,
|
|
3286
|
+
role: "member"
|
|
3287
|
+
})), { upgradeWatcherToSpeaker: true });
|
|
3288
|
+
await recomputeChatWatchers(tx, chatId);
|
|
3289
|
+
});
|
|
3290
|
+
invalidateChatAudience(chatId);
|
|
3291
|
+
}
|
|
3292
|
+
async function markMeChatRead(db, chatId, humanAgentId) {
|
|
3293
|
+
const now = /* @__PURE__ */ new Date();
|
|
3294
|
+
await db.insert(chatUserState).values({
|
|
3295
|
+
chatId,
|
|
3296
|
+
agentId: humanAgentId,
|
|
3297
|
+
lastReadAt: now,
|
|
3298
|
+
unreadMentionCount: 0
|
|
3299
|
+
}).onConflictDoUpdate({
|
|
3300
|
+
target: [chatUserState.chatId, chatUserState.agentId],
|
|
3301
|
+
set: {
|
|
3302
|
+
lastReadAt: now,
|
|
3303
|
+
unreadMentionCount: 0
|
|
3304
|
+
}
|
|
3305
|
+
});
|
|
3306
|
+
return {
|
|
3307
|
+
chatId,
|
|
3308
|
+
lastReadAt: now.toISOString(),
|
|
3309
|
+
unreadMentionCount: 0
|
|
3310
|
+
};
|
|
3311
|
+
}
|
|
3312
|
+
/**
|
|
3313
|
+
* Bump `unread_mention_count` to at least 1 so the chat shows up as unread
|
|
3314
|
+
* in the conversation list (and is matched by `?filter=unread`). Idempotent:
|
|
3315
|
+
* if the row already has a positive count, it stays as-is. `last_read_at`
|
|
3316
|
+
* is intentionally untouched — this is a UI affordance, not a "rewind the
|
|
3317
|
+
* read cursor" operation.
|
|
3318
|
+
*
|
|
3319
|
+
* Contract note — semantic overload: the column is named `unread_mention_count`
|
|
3320
|
+
* but is co-opted here as a generic "manual unread" flag. Every existing
|
|
3321
|
+
* consumer (conversation list bold styling, `?filter=unread`, source-counts,
|
|
3322
|
+
* the bell badge) only checks `> 0`, so the exact value carries no meaning
|
|
3323
|
+
* for callers. If a future feature ever renders the literal mention count
|
|
3324
|
+
* (e.g. a "N mentions" pill), it must NOT read this column directly — it
|
|
3325
|
+
* needs a separate mention-only counter, otherwise a manually-marked-unread
|
|
3326
|
+
* chat would show a fictitious "1 mention".
|
|
3327
|
+
*/
|
|
3328
|
+
async function markMeChatUnread(db, chatId, humanAgentId) {
|
|
3329
|
+
await db.insert(chatUserState).values({
|
|
3330
|
+
chatId,
|
|
3331
|
+
agentId: humanAgentId,
|
|
3332
|
+
unreadMentionCount: 1
|
|
3333
|
+
}).onConflictDoUpdate({
|
|
3334
|
+
target: [chatUserState.chatId, chatUserState.agentId],
|
|
3335
|
+
set: { unreadMentionCount: sql`GREATEST(${chatUserState.unreadMentionCount}, 1)` }
|
|
3336
|
+
});
|
|
3337
|
+
const [row] = await db.select({ unreadMentionCount: chatUserState.unreadMentionCount }).from(chatUserState).where(and(eq(chatUserState.chatId, chatId), eq(chatUserState.agentId, humanAgentId))).limit(1);
|
|
3338
|
+
return {
|
|
3339
|
+
chatId,
|
|
3340
|
+
unreadMentionCount: row?.unreadMentionCount ?? 1
|
|
3341
|
+
};
|
|
3342
|
+
}
|
|
3343
|
+
async function joinMeChat(db, chatId, humanAgentId) {
|
|
3344
|
+
ensureCanJoin(await resolveChatMembership(db, chatId, humanAgentId));
|
|
3345
|
+
await joinAsParticipant(db, chatId, humanAgentId);
|
|
3346
|
+
invalidateChatAudience(chatId);
|
|
3347
|
+
}
|
|
3348
|
+
async function leaveMeChat(db, chatId, humanAgentId) {
|
|
3349
|
+
const result = await leaveAsParticipant(db, chatId, humanAgentId);
|
|
3350
|
+
invalidateChatAudience(chatId);
|
|
3351
|
+
return result;
|
|
3352
|
+
}
|
|
3353
|
+
/**
|
|
3354
|
+
* Used by future bell-badge / list-pill counts. The partial index
|
|
3355
|
+
* `idx_user_state_unread WHERE unread_mention_count > 0` bounds the
|
|
3356
|
+
* driving scan; we then join `chat_membership` + `chats` so the badge
|
|
3357
|
+
* stays consistent with `listMeChats`.
|
|
3358
|
+
*
|
|
3359
|
+
* Why the joins (not just a single-table count): per §11.4 a user's
|
|
3360
|
+
* `chat_user_state` row is **preserved on detach** so read state
|
|
3361
|
+
* survives a leave/rejoin cycle. Without the membership join, any
|
|
3362
|
+
* preserved row with `unread_mention_count > 0` would keep
|
|
3363
|
+
* contributing to the badge even though the chat no longer appears in
|
|
3364
|
+
* the list. The `chats` join applies the same org-scoping +
|
|
3365
|
+
* `parent_chat_id IS NULL` filter as `listMeChats` so the two counts
|
|
3366
|
+
* cannot drift in the cross-org pollution or nested-chat cases either.
|
|
3367
|
+
*
|
|
3368
|
+
* Engagement parity: deleted chats are excluded from `listMeChats`
|
|
3369
|
+
* (any `engagement` view), so the badge must exclude them too — otherwise
|
|
3370
|
+
* the user sees an unread red dot for a chat they've removed from view.
|
|
3371
|
+
*/
|
|
3372
|
+
/**
|
|
3373
|
+
* Per-source aggregate for the conversation-list tag bar.
|
|
3374
|
+
*
|
|
3375
|
+
* Returns one row per source the caller has at least one chat for, plus an
|
|
3376
|
+
* always-present `manual` entry (zero counts when there are no manual chats —
|
|
3377
|
+
* the workspace UI uses `manual` as its default tab and must render it even
|
|
3378
|
+
* when empty).
|
|
3379
|
+
*
|
|
3380
|
+
* Filtering matches `listMeChats` for the corresponding tab so the badges
|
|
3381
|
+
* cannot drift from the list: same membership join, same `parent_chat_id IS
|
|
3382
|
+
* NULL` and `organization_id` scopes, same engagement view, same
|
|
3383
|
+
* `chat_user_state.unread_mention_count` source.
|
|
3384
|
+
*/
|
|
3385
|
+
async function listMeChatSourceCounts(db, humanAgentId, organizationId, query) {
|
|
3386
|
+
const engagementPredicate = ENGAGEMENT_VIEW_PREDICATE[query.engagement];
|
|
3387
|
+
const rows = await db.execute(sql`
|
|
3388
|
+
SELECT
|
|
3389
|
+
${chatSourceSqlExpression} AS source,
|
|
3390
|
+
count(*)::int AS chat_count,
|
|
3391
|
+
count(*) FILTER (WHERE COALESCE(cus.unread_mention_count, 0) > 0)::int AS unread_chat_count
|
|
3392
|
+
FROM chats c
|
|
3393
|
+
JOIN chat_membership cm
|
|
3394
|
+
ON cm.chat_id = c.id AND cm.agent_id = ${humanAgentId}
|
|
3395
|
+
LEFT JOIN chat_user_state cus
|
|
3396
|
+
ON cus.chat_id = c.id AND cus.agent_id = ${humanAgentId}
|
|
3397
|
+
WHERE c.parent_chat_id IS NULL
|
|
3398
|
+
AND c.organization_id = ${organizationId}
|
|
3399
|
+
AND ${engagementPredicate}
|
|
3400
|
+
GROUP BY 1
|
|
3401
|
+
`);
|
|
3402
|
+
const counts = {};
|
|
3403
|
+
for (const row of rows) counts[row.source] = {
|
|
3404
|
+
chatCount: Number(row.chat_count),
|
|
3405
|
+
unreadChatCount: Number(row.unread_chat_count)
|
|
3406
|
+
};
|
|
3407
|
+
if (!counts.manual) counts.manual = {
|
|
3408
|
+
chatCount: 0,
|
|
3409
|
+
unreadChatCount: 0
|
|
3410
|
+
};
|
|
3411
|
+
return { counts };
|
|
3412
|
+
}
|
|
3413
|
+
async function createChat(db, creatorId, data) {
|
|
3414
|
+
const chatId = randomUUID();
|
|
3415
|
+
const allParticipantIds = new Set([creatorId, ...data.participantIds]);
|
|
3416
|
+
const existingAgents = await db.select({
|
|
3417
|
+
id: agents.uuid,
|
|
3418
|
+
organizationId: agents.organizationId,
|
|
3419
|
+
type: agents.type,
|
|
3420
|
+
visibility: agents.visibility,
|
|
3421
|
+
managerId: agents.managerId
|
|
3422
|
+
}).from(agents).where(inArray(agents.uuid, [...allParticipantIds]));
|
|
3423
|
+
if (existingAgents.length !== allParticipantIds.size) {
|
|
3424
|
+
const found = new Set(existingAgents.map((a) => a.id));
|
|
3425
|
+
throw new BadRequestError(`Agents not found: ${[...allParticipantIds].filter((id) => !found.has(id)).join(", ")}`);
|
|
3426
|
+
}
|
|
3427
|
+
const creator = existingAgents.find((a) => a.id === creatorId);
|
|
3428
|
+
if (!creator) throw new Error("Unexpected: creator not in existingAgents");
|
|
3429
|
+
const orgId = creator.organizationId;
|
|
3430
|
+
const crossOrg = existingAgents.filter((a) => a.organizationId !== orgId);
|
|
3431
|
+
if (crossOrg.length > 0) throw new BadRequestError(`Cross-organization chat not allowed: ${crossOrg.map((a) => a.id).join(", ")}`);
|
|
3432
|
+
const privateNotOwned = existingAgents.filter((a) => a.id !== creatorId && a.visibility === AGENT_VISIBILITY.PRIVATE && a.managerId !== creator.managerId);
|
|
3433
|
+
if (privateNotOwned.length > 0) throw new ForbiddenError(`Only the owner can add a private agent to a chat: ${privateNotOwned.map((a) => a.id).join(", ")}`);
|
|
3434
|
+
return db.transaction(async (tx) => {
|
|
3435
|
+
const [chat] = await tx.insert(chats).values({
|
|
3436
|
+
id: chatId,
|
|
3437
|
+
organizationId: orgId,
|
|
3438
|
+
type: data.type,
|
|
3439
|
+
topic: data.topic ?? null,
|
|
3440
|
+
metadata: data.metadata ?? {}
|
|
3441
|
+
}).returning();
|
|
3442
|
+
await addChatParticipants(tx, chatId, [...allParticipantIds].map((agentId) => ({
|
|
3443
|
+
agentId,
|
|
3444
|
+
role: agentId === creatorId ? "owner" : "member"
|
|
3445
|
+
})));
|
|
3446
|
+
await recomputeChatWatchers(tx, chatId);
|
|
3447
|
+
const participants = await tx.select().from(chatMembership).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.accessMode, "speaker")));
|
|
3448
|
+
if (!chat) throw new Error("Unexpected: INSERT RETURNING produced no row");
|
|
3449
|
+
return {
|
|
3450
|
+
...chat,
|
|
3451
|
+
participants
|
|
3452
|
+
};
|
|
3453
|
+
});
|
|
3454
|
+
}
|
|
3455
|
+
async function getChat(db, chatId) {
|
|
3456
|
+
const [chat] = await db.select().from(chats).where(eq(chats.id, chatId)).limit(1);
|
|
3457
|
+
if (!chat) throw new NotFoundError(`Chat "${chatId}" not found`);
|
|
3458
|
+
return chat;
|
|
3459
|
+
}
|
|
3460
|
+
/**
|
|
3461
|
+
* Read a chat row + speaker participants + server-resolved display
|
|
3462
|
+
* metadata (`title`, `firstMessagePreview`) so the agent route can return
|
|
3463
|
+
* a payload that matches the wire `chatDetailSchema` contract.
|
|
3464
|
+
*
|
|
3465
|
+
* `selfAgentId` only affects the participant-join fallback in
|
|
3466
|
+
* `resolveChatTitle` (e.g. `"alice, bob"` excluding self when topic + first
|
|
3467
|
+
* message are both empty). Callers that don't have a self agent (admin
|
|
3468
|
+
* paths) can pass `null` — the fallback degrades to "all displayNames".
|
|
3469
|
+
*/
|
|
3470
|
+
async function getChatDetail(db, chatId, selfAgentId = null) {
|
|
3471
|
+
const chat = await getChat(db, chatId);
|
|
3472
|
+
const participantRows = await db.select({
|
|
3473
|
+
agentId: chatMembership.agentId,
|
|
3474
|
+
role: chatMembership.role,
|
|
3475
|
+
mode: chatMembership.mode,
|
|
3476
|
+
joinedAt: chatMembership.joinedAt,
|
|
3477
|
+
name: agents.name,
|
|
3478
|
+
displayName: agents.displayName,
|
|
3479
|
+
type: agents.type
|
|
3480
|
+
}).from(chatMembership).innerJoin(agents, eq(chatMembership.agentId, agents.uuid)).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.accessMode, "speaker")));
|
|
3481
|
+
const [firstMessageRow] = await db.select({ content: messages.content }).from(messages).where(eq(messages.chatId, chatId)).orderBy(messages.createdAt, messages.id).limit(1);
|
|
3482
|
+
const firstMessagePreview = firstMessageRow ? extractSummary(firstMessageRow.content) : null;
|
|
3483
|
+
const title = resolveChatTitle(chat.topic, firstMessagePreview, participantRows, selfAgentId ?? "");
|
|
3484
|
+
const participants = participantRows.map((p) => ({
|
|
3485
|
+
chatId,
|
|
3486
|
+
agentId: p.agentId,
|
|
3487
|
+
role: p.role,
|
|
3488
|
+
mode: p.mode,
|
|
3489
|
+
joinedAt: p.joinedAt,
|
|
3490
|
+
name: p.name,
|
|
3491
|
+
displayName: p.displayName,
|
|
3492
|
+
type: p.type
|
|
3493
|
+
}));
|
|
3494
|
+
return {
|
|
3495
|
+
...chat,
|
|
3496
|
+
participants,
|
|
3497
|
+
title,
|
|
3498
|
+
firstMessagePreview
|
|
3499
|
+
};
|
|
3500
|
+
}
|
|
3501
|
+
async function listChats(db, agentId, limit, cursor) {
|
|
3502
|
+
const chatIds = (await db.select({ chatId: chatMembership.chatId }).from(chatMembership).where(and(eq(chatMembership.agentId, agentId), eq(chatMembership.accessMode, "speaker")))).map((r) => r.chatId);
|
|
3503
|
+
if (chatIds.length === 0) return {
|
|
3504
|
+
items: [],
|
|
3505
|
+
nextCursor: null
|
|
3506
|
+
};
|
|
3507
|
+
const where = cursor ? and(inArray(chats.id, chatIds), lt(chats.updatedAt, new Date(cursor))) : inArray(chats.id, chatIds);
|
|
3508
|
+
const rows = await db.select().from(chats).where(where).orderBy(desc(chats.updatedAt)).limit(limit + 1);
|
|
3509
|
+
const hasMore = rows.length > limit;
|
|
3510
|
+
const items = hasMore ? rows.slice(0, limit) : rows;
|
|
3511
|
+
const last = items[items.length - 1];
|
|
3512
|
+
return {
|
|
3513
|
+
items,
|
|
3514
|
+
nextCursor: hasMore && last ? last.updatedAt.toISOString() : null
|
|
3515
|
+
};
|
|
3516
|
+
}
|
|
3517
|
+
/**
|
|
3518
|
+
* List participants of a chat with their agent names — used by the client
|
|
3519
|
+
* runtime to resolve `@<name>` mentions against the authoritative participant
|
|
3520
|
+
* set (see proposals/hub-agent-messaging-reply-and-mentions §4).
|
|
3521
|
+
*/
|
|
3522
|
+
async function listChatParticipantsWithNames(db, chatId) {
|
|
3523
|
+
return await db.select({
|
|
3524
|
+
agentId: chatMembership.agentId,
|
|
3525
|
+
role: chatMembership.role,
|
|
3526
|
+
mode: chatMembership.mode,
|
|
3527
|
+
joinedAt: chatMembership.joinedAt,
|
|
3528
|
+
name: agents.name,
|
|
3529
|
+
displayName: agents.displayName,
|
|
3530
|
+
type: agents.type
|
|
3531
|
+
}).from(chatMembership).innerJoin(agents, eq(chatMembership.agentId, agents.uuid)).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.accessMode, "speaker")));
|
|
1588
3532
|
}
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
3533
|
+
async function assertParticipant(db, chatId, agentId) {
|
|
3534
|
+
const [row] = await db.select({ chatId: chatMembership.chatId }).from(chatMembership).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.agentId, agentId), eq(chatMembership.accessMode, "speaker"))).limit(1);
|
|
3535
|
+
if (!row) throw new ForbiddenError("Not a participant of this chat");
|
|
1592
3536
|
}
|
|
1593
|
-
const log$1 = createLogger("questions");
|
|
1594
3537
|
/**
|
|
1595
|
-
*
|
|
1596
|
-
*
|
|
1597
|
-
*
|
|
1598
|
-
* if the message content is not a valid `QuestionMessageContent` — the caller
|
|
1599
|
-
* will already have rejected such input upstream, but we defend in depth so a
|
|
1600
|
-
* malformed write never leaves a dangling pending row.
|
|
3538
|
+
* Non-throwing membership check. Used by routing logic that needs to fall
|
|
3539
|
+
* back to a different chat when the candidate target isn't a member of the
|
|
3540
|
+
* caller's current chat (see `sendToAgent`'s current-chat routing branch).
|
|
1601
3541
|
*/
|
|
1602
|
-
async function
|
|
1603
|
-
const
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
3542
|
+
async function isParticipant(db, chatId, agentId) {
|
|
3543
|
+
const [row] = await db.select({ chatId: chatMembership.chatId }).from(chatMembership).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.agentId, agentId), eq(chatMembership.accessMode, "speaker"))).limit(1);
|
|
3544
|
+
return Boolean(row);
|
|
3545
|
+
}
|
|
3546
|
+
/** Ensure an agent is a speaker of a chat. Silently adds them if not already. */
|
|
3547
|
+
async function ensureParticipant(db, chatId, agentId) {
|
|
3548
|
+
const [existing] = await db.select({ accessMode: chatMembership.accessMode }).from(chatMembership).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.agentId, agentId))).limit(1);
|
|
3549
|
+
if (existing?.accessMode === "speaker") return;
|
|
3550
|
+
await db.transaction(async (tx) => {
|
|
3551
|
+
if (wouldUpgradeToGroup((await tx.select({ agentId: chatMembership.agentId }).from(chatMembership).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.accessMode, "speaker")))).length, 1)) await changeChatType(tx, chatId, "group");
|
|
3552
|
+
await addChatParticipants(tx, chatId, [{ agentId }], { upgradeWatcherToSpeaker: true });
|
|
3553
|
+
await recomputeChatWatchers(tx, chatId);
|
|
3554
|
+
});
|
|
3555
|
+
invalidateChatAudience(chatId);
|
|
3556
|
+
}
|
|
3557
|
+
async function addParticipant(db, chatId, requesterId, data) {
|
|
3558
|
+
const chat = await getChat(db, chatId);
|
|
3559
|
+
await assertParticipant(db, chatId, requesterId);
|
|
3560
|
+
const [targetAgent] = await db.select({
|
|
3561
|
+
id: agents.uuid,
|
|
3562
|
+
organizationId: agents.organizationId,
|
|
3563
|
+
inboxId: agents.inboxId,
|
|
3564
|
+
visibility: agents.visibility,
|
|
3565
|
+
managerId: agents.managerId
|
|
3566
|
+
}).from(agents).where(eq(agents.uuid, data.agentId)).limit(1);
|
|
3567
|
+
if (!targetAgent) throw new NotFoundError(`Agent "${data.agentId}" not found`);
|
|
3568
|
+
if (targetAgent.organizationId !== chat.organizationId) throw new BadRequestError("Cannot add agent from different organization");
|
|
3569
|
+
if (targetAgent.visibility === AGENT_VISIBILITY.PRIVATE && targetAgent.id !== requesterId) {
|
|
3570
|
+
const [requester] = await db.select({ managerId: agents.managerId }).from(agents).where(eq(agents.uuid, requesterId)).limit(1);
|
|
3571
|
+
if (!requester) throw new NotFoundError(`Agent "${requesterId}" not found`);
|
|
3572
|
+
if (requester.managerId !== targetAgent.managerId) throw new ForbiddenError(`Only the owner can add a private agent to a chat: ${targetAgent.id}`);
|
|
3573
|
+
}
|
|
3574
|
+
const [existing] = await db.select({ accessMode: chatMembership.accessMode }).from(chatMembership).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.agentId, data.agentId))).limit(1);
|
|
3575
|
+
if (existing?.accessMode === "speaker") throw new ConflictError(`Agent "${data.agentId}" is already a participant`);
|
|
3576
|
+
await db.transaction(async (tx) => {
|
|
3577
|
+
if (wouldUpgradeToGroup((await tx.select({ agentId: chatMembership.agentId }).from(chatMembership).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.accessMode, "speaker")))).length, 1)) await changeChatType(tx, chatId, "group");
|
|
3578
|
+
await addChatParticipants(tx, chatId, [{ agentId: data.agentId }], { upgradeWatcherToSpeaker: true });
|
|
3579
|
+
await recomputeChatWatchers(tx, chatId);
|
|
3580
|
+
await backfillSilentContextForNewParticipants(tx, chatId, [{ inboxId: targetAgent.inboxId }]);
|
|
1612
3581
|
});
|
|
3582
|
+
invalidateChatAudience(chatId);
|
|
3583
|
+
return db.select().from(chatMembership).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.accessMode, "speaker")));
|
|
3584
|
+
}
|
|
3585
|
+
async function removeParticipant(db, chatId, requesterId, targetAgentId) {
|
|
3586
|
+
await assertParticipant(db, chatId, requesterId);
|
|
3587
|
+
if (requesterId === targetAgentId) throw new BadRequestError("Cannot remove yourself from a chat");
|
|
3588
|
+
const [removed] = await db.delete(chatMembership).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.agentId, targetAgentId), eq(chatMembership.accessMode, "speaker"))).returning();
|
|
3589
|
+
if (!removed) throw new NotFoundError(`Agent "${targetAgentId}" is not a participant of this chat`);
|
|
3590
|
+
await recomputeChatWatchers(db, chatId);
|
|
3591
|
+
invalidateChatAudience(chatId);
|
|
3592
|
+
return db.select().from(chatMembership).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.accessMode, "speaker")));
|
|
1613
3593
|
}
|
|
1614
3594
|
/**
|
|
1615
|
-
*
|
|
1616
|
-
*
|
|
1617
|
-
*
|
|
1618
|
-
*
|
|
1619
|
-
* (HTTP 403) so the bug surfaces loudly to the offending writer.
|
|
1620
|
-
*
|
|
1621
|
-
* Returns the runtime provider for telemetry / further checks (e.g. the
|
|
1622
|
-
* caller can attach it to the active span).
|
|
3595
|
+
* List chats visible to a member, grouped by agent.
|
|
3596
|
+
* A member sees chats where:
|
|
3597
|
+
* 1. Their human agent is a participant, OR
|
|
3598
|
+
* 2. Any agent they manage (managerId = memberId) is a participant (supervision)
|
|
1623
3599
|
*/
|
|
1624
|
-
async function
|
|
1625
|
-
const
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
3600
|
+
async function listChatsForMember(db, memberId, humanAgentId) {
|
|
3601
|
+
const managedAgents = await db.select({
|
|
3602
|
+
uuid: agents.uuid,
|
|
3603
|
+
name: agents.name,
|
|
3604
|
+
type: agents.type,
|
|
3605
|
+
displayName: agents.displayName
|
|
3606
|
+
}).from(agents).where(eq(agents.managerId, memberId));
|
|
3607
|
+
const agentMap = /* @__PURE__ */ new Map();
|
|
3608
|
+
for (const a of managedAgents) agentMap.set(a.uuid, a);
|
|
3609
|
+
if (!agentMap.has(humanAgentId)) {
|
|
3610
|
+
const [ha] = await db.select({
|
|
3611
|
+
uuid: agents.uuid,
|
|
3612
|
+
name: agents.name,
|
|
3613
|
+
type: agents.type,
|
|
3614
|
+
displayName: agents.displayName
|
|
3615
|
+
}).from(agents).where(eq(agents.uuid, humanAgentId)).limit(1);
|
|
3616
|
+
if (ha) agentMap.set(ha.uuid, ha);
|
|
3617
|
+
}
|
|
3618
|
+
const agentIds = [...agentMap.keys()];
|
|
3619
|
+
if (agentIds.length === 0) return [];
|
|
3620
|
+
const participations = await db.select({
|
|
3621
|
+
chatId: chatMembership.chatId,
|
|
3622
|
+
agentId: chatMembership.agentId,
|
|
3623
|
+
role: chatMembership.role,
|
|
3624
|
+
mode: chatMembership.mode
|
|
3625
|
+
}).from(chatMembership).where(and(inArray(chatMembership.agentId, agentIds), eq(chatMembership.accessMode, "speaker")));
|
|
3626
|
+
if (participations.length === 0) return [];
|
|
3627
|
+
const chatIds = [...new Set(participations.map((p) => p.chatId))];
|
|
3628
|
+
const agentChatMap = /* @__PURE__ */ new Map();
|
|
3629
|
+
for (const p of participations) {
|
|
3630
|
+
const list = agentChatMap.get(p.agentId) ?? [];
|
|
3631
|
+
list.push(p.chatId);
|
|
3632
|
+
agentChatMap.set(p.agentId, list);
|
|
3633
|
+
}
|
|
3634
|
+
const chatRows = await db.select({
|
|
3635
|
+
id: chats.id,
|
|
3636
|
+
type: chats.type,
|
|
3637
|
+
topic: chats.topic,
|
|
3638
|
+
metadata: chats.metadata,
|
|
3639
|
+
createdAt: chats.createdAt,
|
|
3640
|
+
updatedAt: chats.updatedAt,
|
|
3641
|
+
participantCount: sql`(SELECT count(*)::int FROM chat_membership WHERE chat_id = ${chats.id} AND access_mode = 'speaker')`
|
|
3642
|
+
}).from(chats).where(inArray(chats.id, chatIds)).orderBy(desc(chats.updatedAt));
|
|
3643
|
+
const chatMap = new Map(chatRows.map((c) => [c.id, c]));
|
|
3644
|
+
const humanParticipantChatIds = new Set(participations.filter((p) => p.agentId === humanAgentId).map((p) => p.chatId));
|
|
3645
|
+
const result = [];
|
|
3646
|
+
for (const [agentId, agentChatIds] of agentChatMap) {
|
|
3647
|
+
const agentInfo = agentMap.get(agentId);
|
|
3648
|
+
if (!agentInfo) continue;
|
|
3649
|
+
const agentChats = agentChatIds.map((chatId) => {
|
|
3650
|
+
const chat = chatMap.get(chatId);
|
|
3651
|
+
if (!chat) return null;
|
|
3652
|
+
const isSupervisionOnly = agentId !== humanAgentId && !humanParticipantChatIds.has(chatId);
|
|
3653
|
+
return {
|
|
3654
|
+
id: chat.id,
|
|
3655
|
+
type: chat.type,
|
|
3656
|
+
topic: chat.topic,
|
|
3657
|
+
participantCount: chat.participantCount,
|
|
3658
|
+
isSupervisionOnly,
|
|
3659
|
+
createdAt: chat.createdAt.toISOString(),
|
|
3660
|
+
updatedAt: chat.updatedAt.toISOString()
|
|
3661
|
+
};
|
|
3662
|
+
}).filter((c) => c !== null);
|
|
3663
|
+
if (agentChats.length > 0) result.push({
|
|
3664
|
+
agent: agentInfo,
|
|
3665
|
+
chats: agentChats
|
|
1635
3666
|
});
|
|
1636
3667
|
}
|
|
1637
|
-
return
|
|
3668
|
+
return result;
|
|
1638
3669
|
}
|
|
1639
3670
|
/**
|
|
1640
|
-
*
|
|
1641
|
-
*
|
|
1642
|
-
* 2. Refuse if status !== "pending" (409 if already-answered, 410-shaped
|
|
1643
|
-
* 400 if superseded — both surface as ConflictError so the caller knows
|
|
1644
|
-
* the question is no longer answerable).
|
|
1645
|
-
* 3. Validate that the answer keys match the original `questions[]`.
|
|
1646
|
-
* 4. Flip status to `answered` INSIDE the lock-tx, before releasing the
|
|
1647
|
-
* row lock. This is the linearisation point: the second concurrent
|
|
1648
|
-
* submitter (waiting on the same row lock) will, on its turn, see
|
|
1649
|
-
* status=answered and exit with ConflictError BEFORE it can write a
|
|
1650
|
-
* second `format=question_answer` message.
|
|
1651
|
-
* 5. Send the `format=question_answer` message OUTSIDE the lock-tx
|
|
1652
|
-
* (sendMessage opens its own transaction; nesting wasn't supported by
|
|
1653
|
-
* the existing call site). At this point we hold an exclusive logical
|
|
1654
|
-
* claim — only one submitter ever reaches this step per correlationId.
|
|
1655
|
-
*
|
|
1656
|
-
* `submitterAgentId` is the human agent on whose behalf the answer is
|
|
1657
|
-
* written (it must be a participant of the question's chat). Returns the
|
|
1658
|
-
* created `question_answer` message id so the route can include it in the
|
|
1659
|
-
* 201 response.
|
|
1660
|
-
*
|
|
1661
|
-
* Failure semantics: if step 5 (sendMessage) fails after status was flipped,
|
|
1662
|
-
* we revert the row to `pending` so the user can retry. This is best-effort —
|
|
1663
|
-
* the revert UPDATE is guarded by `status='answered'` to avoid clobbering a
|
|
1664
|
-
* supersede that might race in. If the revert itself fails, the row is
|
|
1665
|
-
* stranded as `answered` with no answer message; an operator would need to
|
|
1666
|
-
* intervene, but a sendMessage failure (local DB tx) is already
|
|
1667
|
-
* extraordinarily rare.
|
|
3671
|
+
* Manager joins a chat. Adds their human agent as a participant.
|
|
3672
|
+
* Requires the member to have supervision rights (manages at least one existing participant).
|
|
1668
3673
|
*/
|
|
1669
|
-
async function
|
|
1670
|
-
const
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
if (
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
throw err;
|
|
3674
|
+
async function joinChat(db, chatId, memberId, humanAgentId) {
|
|
3675
|
+
const chat = await getChat(db, chatId);
|
|
3676
|
+
const participantAgentIds = (await db.select().from(chatMembership).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.accessMode, "speaker")))).map((p) => p.agentId);
|
|
3677
|
+
if (participantAgentIds.length === 0) throw new NotFoundError("Chat has no participants");
|
|
3678
|
+
if (participantAgentIds.includes(humanAgentId)) throw new ConflictError("Already a participant in this chat");
|
|
3679
|
+
if ((await db.select({ uuid: agents.uuid }).from(agents).where(and(inArray(agents.uuid, participantAgentIds), eq(agents.managerId, memberId)))).length === 0) throw new ForbiddenError("You can only join chats where you manage at least one participant");
|
|
3680
|
+
const [humanAgent] = await db.select({ organizationId: agents.organizationId }).from(agents).where(eq(agents.uuid, humanAgentId)).limit(1);
|
|
3681
|
+
if (!humanAgent || humanAgent.organizationId !== chat.organizationId) throw new BadRequestError("Agent does not belong to the same organization as the chat");
|
|
3682
|
+
await db.transaction(async (tx) => {
|
|
3683
|
+
if (wouldUpgradeToGroup(participantAgentIds.length, 1)) await changeChatType(tx, chatId, "group");
|
|
3684
|
+
await addChatParticipants(tx, chatId, [{
|
|
3685
|
+
agentId: humanAgentId,
|
|
3686
|
+
role: "member"
|
|
3687
|
+
}], {
|
|
3688
|
+
assertHuman: true,
|
|
3689
|
+
upgradeWatcherToSpeaker: true
|
|
3690
|
+
});
|
|
3691
|
+
await recomputeChatWatchers(tx, chatId);
|
|
3692
|
+
});
|
|
3693
|
+
invalidateChatAudience(chatId);
|
|
3694
|
+
return db.select().from(chatMembership).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.accessMode, "speaker")));
|
|
3695
|
+
}
|
|
3696
|
+
/**
|
|
3697
|
+
* Manager leaves a chat. Removes their human agent from participants.
|
|
3698
|
+
* Only allowed if the human agent is a participant.
|
|
3699
|
+
*
|
|
3700
|
+
* Delegates the participant→watcher transition to `leaveAsParticipant`
|
|
3701
|
+
* so admin-side and `/me/chats/:id/leave` share one canonical path. The
|
|
3702
|
+
* earlier "recompute then UPDATE-back state" variant violated the design
|
|
3703
|
+
* rule that recompute is only for set rebuild — never on a transition
|
|
3704
|
+
* path (review #228 issue #2). The returned participant list is fetched
|
|
3705
|
+
* after the tx commits, matching the admin route's existing contract.
|
|
3706
|
+
*/
|
|
3707
|
+
async function leaveChat(db, chatId, humanAgentId) {
|
|
3708
|
+
await leaveAsParticipant(db, chatId, humanAgentId);
|
|
3709
|
+
invalidateChatAudience(chatId);
|
|
3710
|
+
return db.select().from(chatMembership).where(and(eq(chatMembership.chatId, chatId), eq(chatMembership.accessMode, "speaker")));
|
|
3711
|
+
}
|
|
3712
|
+
async function findOrCreateDirectChat(db, agentAId, agentBId) {
|
|
3713
|
+
const ends = await db.select({
|
|
3714
|
+
uuid: agents.uuid,
|
|
3715
|
+
organizationId: agents.organizationId,
|
|
3716
|
+
type: agents.type,
|
|
3717
|
+
visibility: agents.visibility,
|
|
3718
|
+
managerId: agents.managerId
|
|
3719
|
+
}).from(agents).where(inArray(agents.uuid, [agentAId, agentBId]));
|
|
3720
|
+
const agentA = ends.find((a) => a.uuid === agentAId);
|
|
3721
|
+
if (!agentA) throw new NotFoundError(`Agent "${agentAId}" not found`);
|
|
3722
|
+
const agentB = ends.find((a) => a.uuid === agentBId);
|
|
3723
|
+
if (!agentB) throw new NotFoundError(`Agent "${agentBId}" not found`);
|
|
3724
|
+
if (agentA.organizationId !== agentB.organizationId) throw new BadRequestError(`Cannot create direct chat across organizations: agent "${agentAId}" (org "${agentA.organizationId}") vs agent "${agentBId}" (org "${agentB.organizationId}")`);
|
|
3725
|
+
const orgId = agentA.organizationId;
|
|
3726
|
+
const commonChatIds = (await db.select({ chatId: chatMembership.chatId }).from(chatMembership).where(and(inArray(chatMembership.agentId, [agentAId, agentBId]), eq(chatMembership.accessMode, "speaker"))).groupBy(chatMembership.chatId).having(sql`COUNT(DISTINCT ${chatMembership.agentId}) = 2`)).map((r) => r.chatId);
|
|
3727
|
+
if (commonChatIds.length > 0) {
|
|
3728
|
+
const directChats = await db.select().from(chats).where(and(inArray(chats.id, commonChatIds), eq(chats.type, "direct"), eq(chats.organizationId, orgId))).orderBy(chats.createdAt, chats.id).limit(1);
|
|
3729
|
+
if (directChats.length > 0 && directChats[0]) return directChats[0];
|
|
1726
3730
|
}
|
|
1727
|
-
if (
|
|
3731
|
+
if ((agentA.visibility === AGENT_VISIBILITY.PRIVATE || agentB.visibility === AGENT_VISIBILITY.PRIVATE) && agentA.managerId !== agentB.managerId) throw new ForbiddenError(`Cannot open a direct chat with a private agent across owners: "${agentAId}" ↔ "${agentBId}"`);
|
|
3732
|
+
const chatId = randomUUID();
|
|
3733
|
+
return db.transaction(async (tx) => {
|
|
3734
|
+
const [chat] = await tx.insert(chats).values({
|
|
3735
|
+
id: chatId,
|
|
3736
|
+
organizationId: orgId,
|
|
3737
|
+
type: "direct"
|
|
3738
|
+
}).returning();
|
|
3739
|
+
await addChatParticipants(tx, chatId, [{
|
|
3740
|
+
agentId: agentAId,
|
|
3741
|
+
role: "member"
|
|
3742
|
+
}, {
|
|
3743
|
+
agentId: agentBId,
|
|
3744
|
+
role: "member"
|
|
3745
|
+
}]);
|
|
3746
|
+
await recomputeChatWatchers(tx, chatId);
|
|
3747
|
+
if (!chat) throw new Error("Unexpected: INSERT RETURNING produced no row");
|
|
3748
|
+
return chat;
|
|
3749
|
+
});
|
|
3750
|
+
}
|
|
3751
|
+
/** Server instance heartbeat. Used to detect crashed instances and clean up associated agent_presence records. */
|
|
3752
|
+
const serverInstances = pgTable("server_instances", {
|
|
3753
|
+
instanceId: text("instance_id").primaryKey(),
|
|
3754
|
+
lastHeartbeat: timestamp("last_heartbeat", { withTimezone: true }).notNull().defaultNow()
|
|
3755
|
+
});
|
|
3756
|
+
/** Common field reset when agent goes offline or is unbound. */
|
|
3757
|
+
function runtimeFieldsReset(now) {
|
|
1728
3758
|
return {
|
|
1729
|
-
|
|
1730
|
-
|
|
3759
|
+
runtimeState: null,
|
|
3760
|
+
activeSessions: null,
|
|
3761
|
+
totalSessions: null,
|
|
3762
|
+
runtimeUpdatedAt: now,
|
|
3763
|
+
lastSeenAt: now
|
|
1731
3764
|
};
|
|
1732
3765
|
}
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
status: "superseded",
|
|
1741
|
-
supersededAt: /* @__PURE__ */ new Date(),
|
|
1742
|
-
supersededReason: reason
|
|
1743
|
-
}).where(and(eq(pendingQuestions.chatId, chatId), eq(pendingQuestions.status, "pending"))).returning({ id: pendingQuestions.id })).length;
|
|
3766
|
+
async function setOffline(db, agentId) {
|
|
3767
|
+
const now = /* @__PURE__ */ new Date();
|
|
3768
|
+
await db.update(agentPresence).set({
|
|
3769
|
+
status: "offline",
|
|
3770
|
+
instanceId: null,
|
|
3771
|
+
...runtimeFieldsReset(now)
|
|
3772
|
+
}).where(eq(agentPresence.agentId, agentId));
|
|
1744
3773
|
}
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
* owner's runtime is detached and cannot deliver an answer back.
|
|
1749
|
-
*/
|
|
1750
|
-
async function markSupersededByAgents(tx, agentIds, reason = "client_claimed") {
|
|
1751
|
-
if (agentIds.length === 0) return 0;
|
|
1752
|
-
return (await tx.update(pendingQuestions).set({
|
|
1753
|
-
status: "superseded",
|
|
1754
|
-
supersededAt: /* @__PURE__ */ new Date(),
|
|
1755
|
-
supersededReason: reason
|
|
1756
|
-
}).where(and(inArray(pendingQuestions.agentId, agentIds), eq(pendingQuestions.status, "pending"))).returning({ id: pendingQuestions.id })).length;
|
|
3774
|
+
async function getPresence(db, agentId) {
|
|
3775
|
+
const [row] = await db.select().from(agentPresence).where(eq(agentPresence.agentId, agentId)).limit(1);
|
|
3776
|
+
return row ?? null;
|
|
1757
3777
|
}
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
return
|
|
1761
|
-
chatId,
|
|
1762
|
-
senderAgentId: senderId,
|
|
1763
|
-
source: data.source ?? void 0
|
|
1764
|
-
}), () => sendMessageInner(db, chatId, senderId, data, options));
|
|
3778
|
+
async function getOnlineCount(db) {
|
|
3779
|
+
const [result] = await db.select({ count: sql`count(*)::int` }).from(agentPresence).where(eq(agentPresence.status, "online"));
|
|
3780
|
+
return result?.count ?? 0;
|
|
1765
3781
|
}
|
|
1766
|
-
async function
|
|
1767
|
-
const
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
effectiveContent = unwrapped;
|
|
1794
|
-
}
|
|
1795
|
-
}
|
|
1796
|
-
if (data.replyToInbox !== void 0 && data.replyToInbox !== null) {
|
|
1797
|
-
if (senderRow.inboxId !== data.replyToInbox) throw new BadRequestError("replyToInbox must reference the sender's own inbox");
|
|
1798
|
-
}
|
|
1799
|
-
const incomingMeta = data.metadata ?? {};
|
|
1800
|
-
const explicitMentionsRaw = incomingMeta.mentions;
|
|
1801
|
-
const explicitMentions = Array.isArray(explicitMentionsRaw) ? explicitMentionsRaw.filter((m) => typeof m === "string") : [];
|
|
1802
|
-
const contentText = typeof effectiveContent === "string" ? effectiveContent : "";
|
|
1803
|
-
const resolved = contentText ? extractMentions(contentText, participants) : [];
|
|
1804
|
-
const mergedMentions = [...new Set([...explicitMentions, ...resolved])];
|
|
1805
|
-
const metadataToStore = mergedMentions.length > 0 ? {
|
|
1806
|
-
...incomingMeta,
|
|
1807
|
-
mentions: mergedMentions
|
|
1808
|
-
} : incomingMeta;
|
|
1809
|
-
const dmAutoProjection = chatType === "direct" ? [...new Set([...mergedMentions, ...participants.filter((p) => p.agentId !== senderId).map((p) => p.agentId)])] : mergedMentions;
|
|
1810
|
-
if (options.enforceGroupMention && chatType === "group") {
|
|
1811
|
-
if (mergedMentions.filter((id) => id !== senderId).length === 0) throw new BadRequestError("Sending to a group chat requires an explicit @mention. Use `first-tree-hub chat send <name>` to message a single agent, or @<name> in the content to address one or more group members.");
|
|
1812
|
-
}
|
|
1813
|
-
let outboundContent = effectiveContent;
|
|
1814
|
-
if (options.normalizeMentionsInContent && typeof outboundContent === "string") {
|
|
1815
|
-
const present = new Set(scanMentionTokens(outboundContent));
|
|
1816
|
-
const missingNames = [];
|
|
1817
|
-
for (const id of mergedMentions) {
|
|
1818
|
-
if (id === senderId) continue;
|
|
1819
|
-
const p = participants.find((q) => q.agentId === id);
|
|
1820
|
-
if (!p?.name) continue;
|
|
1821
|
-
if (present.has(p.name.toLowerCase())) continue;
|
|
1822
|
-
missingNames.push(p.name);
|
|
1823
|
-
}
|
|
1824
|
-
if (missingNames.length > 0) {
|
|
1825
|
-
const prefix = missingNames.map((n) => `@${n}`).join(" ");
|
|
1826
|
-
outboundContent = outboundContent.length > 0 ? `${prefix} ${outboundContent}` : prefix;
|
|
1827
|
-
}
|
|
1828
|
-
}
|
|
1829
|
-
if (data.format === "question") await assertSenderMayEmitQuestion(tx, senderId);
|
|
1830
|
-
const isSilentSend = typeof outboundContent === "string" && outboundContent.replace(/^(@\S+\s*)+/, "").trim().length === 0;
|
|
1831
|
-
if (isSilentSend) log.info({
|
|
1832
|
-
chatId,
|
|
1833
|
-
senderId,
|
|
1834
|
-
source: data.source ?? null
|
|
1835
|
-
}, "silent send: empty content after mention strip — no fan-out wake-up");
|
|
1836
|
-
const projectionMentions = isSilentSend ? [] : dmAutoProjection;
|
|
1837
|
-
const messageId = randomUUID();
|
|
1838
|
-
const [msg] = await tx.insert(messages).values({
|
|
1839
|
-
id: messageId,
|
|
1840
|
-
chatId,
|
|
1841
|
-
senderId,
|
|
1842
|
-
format: data.format,
|
|
1843
|
-
content: outboundContent,
|
|
1844
|
-
metadata: metadataToStore,
|
|
1845
|
-
replyToInbox: data.replyToInbox ?? null,
|
|
1846
|
-
replyToChat: data.replyToChat ?? null,
|
|
1847
|
-
inReplyTo: data.inReplyTo ?? null,
|
|
1848
|
-
source: data.source ?? null
|
|
1849
|
-
}).returning();
|
|
1850
|
-
if (data.format === "question" && msg) await recordPendingQuestionFromMessage(tx, {
|
|
1851
|
-
agentId: senderId,
|
|
1852
|
-
chatId,
|
|
1853
|
-
messageId: msg.id,
|
|
1854
|
-
content: outboundContent
|
|
1855
|
-
});
|
|
1856
|
-
const mentionSet = new Set(mergedMentions);
|
|
1857
|
-
const fanout = participants.filter((p) => p.agentId !== senderId).map((p) => ({
|
|
1858
|
-
agentId: p.agentId,
|
|
1859
|
-
inboxId: p.inboxId,
|
|
1860
|
-
notify: !isSilentSend && (p.mode !== "mention_only" || mentionSet.has(p.agentId))
|
|
1861
|
-
}));
|
|
1862
|
-
if (fanout.length > 0) await tx.insert(inboxEntries).values(fanout.map((f) => ({
|
|
1863
|
-
inboxId: f.inboxId,
|
|
1864
|
-
messageId,
|
|
1865
|
-
chatId,
|
|
1866
|
-
notify: f.notify
|
|
1867
|
-
})));
|
|
1868
|
-
const notified = fanout.filter((f) => f.notify);
|
|
1869
|
-
const recipients = notified.map((f) => f.inboxId);
|
|
1870
|
-
const recipientAgentIds = notified.map((f) => f.agentId);
|
|
1871
|
-
if (data.inReplyTo) {
|
|
1872
|
-
const [original] = await tx.select({
|
|
1873
|
-
replyToInbox: messages.replyToInbox,
|
|
1874
|
-
replyToChat: messages.replyToChat
|
|
1875
|
-
}).from(messages).where(eq(messages.id, data.inReplyTo)).limit(1);
|
|
1876
|
-
if (original?.replyToInbox && original?.replyToChat) {
|
|
1877
|
-
await tx.insert(inboxEntries).values({
|
|
1878
|
-
inboxId: original.replyToInbox,
|
|
1879
|
-
messageId,
|
|
1880
|
-
chatId: original.replyToChat,
|
|
1881
|
-
notify: !isSilentSend
|
|
1882
|
-
}).onConflictDoNothing();
|
|
1883
|
-
if (!isSilentSend && !recipients.includes(original.replyToInbox)) recipients.push(original.replyToInbox);
|
|
1884
|
-
}
|
|
3782
|
+
async function bindAgent(db, agentId, data) {
|
|
3783
|
+
const now = /* @__PURE__ */ new Date();
|
|
3784
|
+
await db.insert(agentPresence).values({
|
|
3785
|
+
agentId,
|
|
3786
|
+
status: "online",
|
|
3787
|
+
instanceId: data.instanceId,
|
|
3788
|
+
clientId: data.clientId,
|
|
3789
|
+
runtimeType: data.runtimeType,
|
|
3790
|
+
runtimeVersion: data.runtimeVersion ?? null,
|
|
3791
|
+
runtimeState: "idle",
|
|
3792
|
+
connectedAt: now,
|
|
3793
|
+
lastSeenAt: now,
|
|
3794
|
+
runtimeUpdatedAt: now
|
|
3795
|
+
}).onConflictDoUpdate({
|
|
3796
|
+
target: agentPresence.agentId,
|
|
3797
|
+
set: {
|
|
3798
|
+
status: "online",
|
|
3799
|
+
instanceId: data.instanceId,
|
|
3800
|
+
clientId: data.clientId,
|
|
3801
|
+
runtimeType: data.runtimeType,
|
|
3802
|
+
runtimeVersion: data.runtimeVersion ?? null,
|
|
3803
|
+
runtimeState: "idle",
|
|
3804
|
+
activeSessions: null,
|
|
3805
|
+
totalSessions: null,
|
|
3806
|
+
connectedAt: now,
|
|
3807
|
+
lastSeenAt: now,
|
|
3808
|
+
runtimeUpdatedAt: now
|
|
1885
3809
|
}
|
|
1886
|
-
await tx.update(chats).set({ updatedAt: /* @__PURE__ */ new Date() }).where(eq(chats.id, chatId));
|
|
1887
|
-
if (!msg) throw new Error("Unexpected: INSERT RETURNING produced no row");
|
|
1888
|
-
const previewText = typeof outboundContent === "string" ? outboundContent.trim() : "";
|
|
1889
|
-
await applyAfterFanOut(tx, {
|
|
1890
|
-
chatId,
|
|
1891
|
-
messageId: msg.id,
|
|
1892
|
-
senderId,
|
|
1893
|
-
mentionedAgentIds: projectionMentions,
|
|
1894
|
-
contentPreview: previewText,
|
|
1895
|
-
messageCreatedAt: msg.createdAt
|
|
1896
|
-
});
|
|
1897
|
-
return {
|
|
1898
|
-
message: msg,
|
|
1899
|
-
recipients,
|
|
1900
|
-
recipientAgentIds,
|
|
1901
|
-
organizationId: senderRow.organizationId
|
|
1902
|
-
};
|
|
1903
|
-
});
|
|
1904
|
-
const settled = await Promise.allSettled(txResult.recipientAgentIds.map((agentId) => upsertSessionState(db, agentId, chatId, "active", txResult.organizationId, void 0, { touchPresenceLastSeen: false })));
|
|
1905
|
-
for (let i = 0; i < settled.length; i++) {
|
|
1906
|
-
const r = settled[i];
|
|
1907
|
-
if (r?.status === "rejected") log.error({
|
|
1908
|
-
err: r.reason,
|
|
1909
|
-
chatId,
|
|
1910
|
-
agentId: txResult.recipientAgentIds[i]
|
|
1911
|
-
}, "predictive session activation failed");
|
|
1912
|
-
}
|
|
1913
|
-
fireChatMessageKick(chatId, txResult.message.id);
|
|
1914
|
-
observeLoopPattern(db, chatId).catch((err) => {
|
|
1915
|
-
log.error({
|
|
1916
|
-
err,
|
|
1917
|
-
chatId
|
|
1918
|
-
}, "loop pattern observation failed");
|
|
1919
3810
|
});
|
|
1920
|
-
return {
|
|
1921
|
-
message: txResult.message,
|
|
1922
|
-
recipients: txResult.recipients
|
|
1923
|
-
};
|
|
1924
3811
|
}
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
* additionally responsible for restricting this to non-human senders.
|
|
3812
|
+
async function unbindAgent(db, agentId) {
|
|
3813
|
+
const now = /* @__PURE__ */ new Date();
|
|
3814
|
+
await db.update(agentPresence).set({
|
|
3815
|
+
status: "offline",
|
|
3816
|
+
clientId: null,
|
|
3817
|
+
...runtimeFieldsReset(now)
|
|
3818
|
+
}).where(eq(agentPresence.agentId, agentId));
|
|
3819
|
+
}
|
|
3820
|
+
/** Set runtime state directly from client-reported value.
|
|
1935
3821
|
*
|
|
1936
|
-
*
|
|
1937
|
-
*
|
|
1938
|
-
*
|
|
1939
|
-
*
|
|
1940
|
-
|
|
1941
|
-
*/
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
const parsed = JSON.parse(content);
|
|
1949
|
-
return typeof parsed === "string" ? parsed : null;
|
|
1950
|
-
} catch {
|
|
1951
|
-
return null;
|
|
1952
|
-
}
|
|
3822
|
+
* When an org-scoped notifier is provided, emit a PG NOTIFY on the
|
|
3823
|
+
* `runtime_state_changes` channel so the pulse aggregator (and any future
|
|
3824
|
+
* admin-side consumers) can observe the transition. Fire-and-forget to match
|
|
3825
|
+
* notifier semantics elsewhere in this module. */
|
|
3826
|
+
async function setRuntimeState(db, agentId, runtimeState, options) {
|
|
3827
|
+
const now = /* @__PURE__ */ new Date();
|
|
3828
|
+
await db.update(agentPresence).set({
|
|
3829
|
+
runtimeState,
|
|
3830
|
+
runtimeUpdatedAt: now,
|
|
3831
|
+
lastSeenAt: now
|
|
3832
|
+
}).where(eq(agentPresence.agentId, agentId));
|
|
3833
|
+
if (options?.notifier && options.organizationId) options.notifier.notifyRuntimeStateChange(agentId, runtimeState, options.organizationId).catch(() => {});
|
|
1953
3834
|
}
|
|
1954
|
-
|
|
1955
|
-
|
|
3835
|
+
/** Touch agent last_seen_at on heartbeat (per-agent liveness). */
|
|
3836
|
+
async function touchAgent(db, agentId) {
|
|
3837
|
+
await db.update(agentPresence).set({ lastSeenAt: /* @__PURE__ */ new Date() }).where(eq(agentPresence.agentId, agentId));
|
|
3838
|
+
}
|
|
3839
|
+
async function heartbeatInstance(db, instanceId) {
|
|
3840
|
+
await db.insert(serverInstances).values({
|
|
3841
|
+
instanceId,
|
|
3842
|
+
lastHeartbeat: /* @__PURE__ */ new Date()
|
|
3843
|
+
}).onConflictDoUpdate({
|
|
3844
|
+
target: serverInstances.instanceId,
|
|
3845
|
+
set: { lastHeartbeat: /* @__PURE__ */ new Date() }
|
|
3846
|
+
});
|
|
1956
3847
|
}
|
|
1957
|
-
const defaultLoopObserver = (data) => {
|
|
1958
|
-
log.warn({
|
|
1959
|
-
metric: "loop_pattern_observed_total",
|
|
1960
|
-
...data
|
|
1961
|
-
}, "loop pattern observed (not blocked) — prompt discipline may be drifting");
|
|
1962
|
-
};
|
|
1963
3848
|
/**
|
|
1964
|
-
*
|
|
1965
|
-
*
|
|
1966
|
-
*
|
|
1967
|
-
*
|
|
1968
|
-
* conditions (see design `agent-reply-loop-prevention-design.md` §3.4) so
|
|
1969
|
-
* normal multi-agent collaboration is never flagged:
|
|
1970
|
-
*
|
|
1971
|
-
* C1 — every message is `format=text`
|
|
1972
|
-
* C2 — no human sender in the window (any human reply resets the chain)
|
|
1973
|
-
* C3 — exactly two senders, perfectly alternating
|
|
1974
|
-
* C4 — strict `inReplyTo` chain across the whole window
|
|
1975
|
-
* C5 — every message body (after stripping leading `@<name>` tokens) is
|
|
1976
|
-
* ≤ `LOOP_OBSERVATION_SHORT_CHARS` characters
|
|
1977
|
-
* C6 — the whole window spans ≤ `LOOP_OBSERVATION_TIME_WINDOW_MS` ms
|
|
3849
|
+
* M1: Mark agents as offline whose last_seen_at is older than staleSeconds.
|
|
3850
|
+
* Unlike cleanupStalePresence (which checks instance liveness), this checks
|
|
3851
|
+
* per-agent heartbeat liveness — detecting agents that stopped heartbeating
|
|
3852
|
+
* while the client process may still be alive.
|
|
1978
3853
|
*
|
|
1979
|
-
*
|
|
1980
|
-
* call site uses the default observer.
|
|
3854
|
+
* Returns the list of agent IDs that were marked stale (for notification in Step 6).
|
|
1981
3855
|
*/
|
|
1982
|
-
async function
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
if (new Set(window.map((m) => m.senderId)).size !== 2) return;
|
|
1996
|
-
for (let i = 0; i < window.length - 1; i++) if (window[i]?.senderId === window[i + 1]?.senderId) return;
|
|
1997
|
-
for (let i = 0; i < window.length - 1; i++) if (window[i]?.inReplyTo !== window[i + 1]?.id) return;
|
|
1998
|
-
const lens = [];
|
|
1999
|
-
for (const m of window) {
|
|
2000
|
-
const text = typeof m.content === "string" ? m.content : null;
|
|
2001
|
-
if (text === null) return;
|
|
2002
|
-
const len = stripMentionPrefix(text).length;
|
|
2003
|
-
if (len > 10) return;
|
|
2004
|
-
lens.push(len);
|
|
2005
|
-
}
|
|
2006
|
-
const newest = window[0];
|
|
2007
|
-
const oldest = window[window.length - 1];
|
|
2008
|
-
if (!newest || !oldest) return;
|
|
2009
|
-
const spanMs = newest.createdAt.getTime() - oldest.createdAt.getTime();
|
|
2010
|
-
if (spanMs > 3e4) return;
|
|
2011
|
-
observer({
|
|
2012
|
-
chatId,
|
|
2013
|
-
recentMessageIds: window.map((m) => m.id),
|
|
2014
|
-
windowSpanMs: spanMs,
|
|
2015
|
-
contentLengths: lens
|
|
2016
|
-
});
|
|
2017
|
-
}
|
|
2018
|
-
async function sendToAgent(db, senderUuid, targetName, data) {
|
|
2019
|
-
const [sender] = await db.select({
|
|
2020
|
-
uuid: agents.uuid,
|
|
2021
|
-
organizationId: agents.organizationId
|
|
2022
|
-
}).from(agents).where(eq(agents.uuid, senderUuid)).limit(1);
|
|
2023
|
-
if (!sender) throw new NotFoundError(`Agent "${senderUuid}" not found`);
|
|
2024
|
-
const [target] = await db.select({ uuid: agents.uuid }).from(agents).where(and(eq(agents.organizationId, sender.organizationId), eq(agents.name, targetName), ne(agents.status, "deleted"))).limit(1);
|
|
2025
|
-
if (!target) throw new NotFoundError(`Agent "${targetName}" not found${/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(targetName) ? " — `first-tree-hub chat send` expects an agent NAME, not a uuid. Run `first-tree-hub agent list` to see available names." : ""}`);
|
|
2026
|
-
const incomingMeta = data.metadata ?? {};
|
|
2027
|
-
const existingMentionsRaw = incomingMeta.mentions;
|
|
2028
|
-
const existingMentions = Array.isArray(existingMentionsRaw) ? existingMentionsRaw.filter((m) => typeof m === "string") : [];
|
|
2029
|
-
const mergedMentions = existingMentions.includes(target.uuid) ? existingMentions : [...existingMentions, target.uuid];
|
|
2030
|
-
const metadata = {
|
|
2031
|
-
...incomingMeta,
|
|
2032
|
-
mentions: mergedMentions
|
|
2033
|
-
};
|
|
2034
|
-
if (data.replyToChat) {
|
|
2035
|
-
const [targetIsMember, senderIsMember] = await Promise.all([isParticipant(db, data.replyToChat, target.uuid), isParticipant(db, data.replyToChat, senderUuid)]);
|
|
2036
|
-
if (targetIsMember && senderIsMember) return sendMessage(db, data.replyToChat, senderUuid, {
|
|
2037
|
-
format: data.format,
|
|
2038
|
-
content: data.content,
|
|
2039
|
-
metadata,
|
|
2040
|
-
replyToInbox: void 0,
|
|
2041
|
-
replyToChat: void 0,
|
|
2042
|
-
source: data.source
|
|
2043
|
-
}, { normalizeMentionsInContent: true });
|
|
2044
|
-
}
|
|
2045
|
-
return sendMessage(db, (await findOrCreateDirectChat(db, senderUuid, target.uuid)).id, senderUuid, {
|
|
2046
|
-
format: data.format,
|
|
2047
|
-
content: data.content,
|
|
2048
|
-
metadata,
|
|
2049
|
-
replyToInbox: data.replyToInbox,
|
|
2050
|
-
replyToChat: data.replyToChat,
|
|
2051
|
-
source: data.source
|
|
2052
|
-
}, { normalizeMentionsInContent: true });
|
|
2053
|
-
}
|
|
2054
|
-
async function editMessage(db, chatId, messageId, senderId, data) {
|
|
2055
|
-
const [msg] = await db.select().from(messages).where(eq(messages.id, messageId)).limit(1);
|
|
2056
|
-
if (!msg) throw new NotFoundError(`Message "${messageId}" not found`);
|
|
2057
|
-
if (msg.chatId !== chatId) throw new NotFoundError(`Message "${messageId}" not found in this chat`);
|
|
2058
|
-
if (msg.senderId !== senderId) throw new ForbiddenError("Only the sender can edit a message");
|
|
2059
|
-
const setClause = {};
|
|
2060
|
-
if (data.format !== void 0) setClause.format = data.format;
|
|
2061
|
-
if (data.content !== void 0) setClause.content = data.content;
|
|
2062
|
-
const meta = msg.metadata ?? {};
|
|
2063
|
-
meta.editedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2064
|
-
setClause.metadata = meta;
|
|
2065
|
-
const [updated] = await db.update(messages).set(setClause).where(eq(messages.id, messageId)).returning();
|
|
2066
|
-
if (!updated) throw new Error("Unexpected: UPDATE RETURNING produced no row");
|
|
2067
|
-
return updated;
|
|
3856
|
+
async function markStaleAgents(db, staleSeconds = 60) {
|
|
3857
|
+
return (await db.execute(sql`
|
|
3858
|
+
UPDATE agent_presence SET
|
|
3859
|
+
status = 'offline',
|
|
3860
|
+
client_id = NULL,
|
|
3861
|
+
runtime_state = NULL,
|
|
3862
|
+
active_sessions = NULL,
|
|
3863
|
+
total_sessions = NULL,
|
|
3864
|
+
runtime_updated_at = NOW()
|
|
3865
|
+
WHERE status = 'online'
|
|
3866
|
+
AND last_seen_at < NOW() - make_interval(secs => ${staleSeconds})
|
|
3867
|
+
RETURNING agent_id
|
|
3868
|
+
`)).map((r) => r.agent_id);
|
|
2068
3869
|
}
|
|
2069
|
-
async function
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
3870
|
+
async function cleanupStalePresence(db, staleSeconds = 60) {
|
|
3871
|
+
return (await db.execute(sql`
|
|
3872
|
+
UPDATE agent_presence SET status = 'offline', instance_id = NULL,
|
|
3873
|
+
runtime_state = NULL,
|
|
3874
|
+
active_sessions = NULL, total_sessions = NULL,
|
|
3875
|
+
runtime_updated_at = NOW()
|
|
3876
|
+
WHERE instance_id IN (
|
|
3877
|
+
SELECT instance_id FROM server_instances
|
|
3878
|
+
WHERE last_heartbeat < NOW() - make_interval(secs => ${staleSeconds})
|
|
3879
|
+
)
|
|
3880
|
+
AND status = 'online'
|
|
3881
|
+
RETURNING agent_id
|
|
3882
|
+
`)).length;
|
|
2079
3883
|
}
|
|
2080
3884
|
/**
|
|
2081
3885
|
* Assert the caller can act on this client. Throws 404 for both "not found"
|
|
@@ -2381,4 +4185,4 @@ async function cleanupStaleClients(db, staleSeconds = 60) {
|
|
|
2381
4185
|
return result.length;
|
|
2382
4186
|
}
|
|
2383
4187
|
//#endregion
|
|
2384
|
-
export {
|
|
4188
|
+
export { heartbeatClient as $, unbindAgent as $t, createChat as A, pruneStaleSilentEntries as At, filterSessionsByParticipant as B, resolveDefaultOrgId as Bt, claimBacklogForPush as C, markMeChatUnread as Ct, clearAgentAvatarImage as D, notifyRecipients as Dt, cleanupStalePresence as E, messages as Et, disconnectClient as F, registerClient as Ft, getCachedAudience as G, setAgentAvatarImage as Gt, getActivityOverview as H, sendMessage as Ht, editMessage as I, removeParticipant as It, getClient as J, setRuntimeState as Jt, getCallerEngagement as K, setChatEngagement as Kt, ensureDefaultOrganization as L, resetActivity as Lt, createNotifier as M, rebindAgent as Mt, deleteAgent as N, recomputeWatchersForMember as Nt, clients as O, pendingQuestions as Ot, deriveAuthState as P, registerChatMessageDispatcher as Pt, getSession as Q, touchAgent as Qt, ensureParticipant as R, resetTimedOutEntries as Rt, claimAndBuildForPush as S, markMeChatRead as St, cleanupStaleClients as T, members as Tt, getAgent as U, sendToAgent as Ut, findOrCreateDirectChat as V, retireClient as Vt, getAgentAvatarImage as W, serverInstances as Wt, getOrganization as X, suspendAgent as Xt, getOnlineCount as Y, submitAnswer as Yt, getPresence as Z, suspendSession as Zt, bindAgent as _, listClientsForOrgAdmin as _t, adapterConfigs as a, leaveMeChat as at, chats as b, listMessages as bt, addParticipant as c, listAgentsForAdmin as ct, agentConfigs as d, listAgentsWithRuntime as dt, updateAgent as en, heartbeatInstance as et, agentPresence as f, listAllSessions as ft, assertParticipant as g, listClients as gt, assertClientOwner as h, listChatsForMember as ht, adapterAgentMappings as i, leaveChat as it, createMeChat as j, reactivateAgent as jt, createAgent as k, pollInbox as kt, agentAvatarImageUrl as l, listAgentsForMember as lt, archiveSession as m, listChats as mt, SUPPORTED_AVATAR_IMAGE_MIMES as n, updateOrganization as nn, joinChat as nt, addChatParticipants as o, listActiveAgentsPinnedToClient as ot, agents as p, listChatParticipantsWithNames as pt, getChatDetail as q, setOffline as qt, ackEntryByIdForBoundAgents as r, upsertSessionState as rn, joinMeChat as rt, addMeChatParticipants as s, listAgentSessions as st, MAX_AVATAR_IMAGE_BYTES as t, updateClientCapabilities as tn, inboxEntries as tt, agentChatSessions as u, listAgentsManagedByUser as ut, chatMembership as v, listMeChatSourceCounts as vt, claimClient as w, markStaleAgents as wt, checkAgentNameAvailability as x, listMyPinnedAgents as xt, chatUserState as y, listMeChats as yt, extractSummary as z, resolveChatTitle as zt };
|