@segmentstream/ontology 0.148.0 → 0.149.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/README.md +24 -15
- package/dist/analyze.d.ts +11 -3
- package/dist/analyze.js +21 -4
- package/dist/diagnostics.d.ts +3 -3
- package/dist/diagnostics.js +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/manifest.d.ts +53 -5
- package/dist/manifest.js +34 -2
- package/dist/migrate/model.d.ts +14 -2
- package/dist/migrate/plan.js +1 -1
- package/dist/migrate/preview.js +4 -1
- package/dist/migrate/storage.d.ts +15 -3
- package/dist/migrate/storage.js +86 -3
- package/dist/runtime/agents.js +2 -0
- package/dist/runtime/chat-messages.d.ts +233 -0
- package/dist/runtime/chat-messages.js +523 -0
- package/dist/service/agent/archive-routes.d.ts +2 -0
- package/dist/service/agent/archive-routes.js +2 -1
- package/dist/service/agent/chat-archive.d.ts +12 -3
- package/dist/service/agent/chat-archive.js +5 -1
- package/dist/service/agent/chat-message-routes.d.ts +124 -0
- package/dist/service/agent/chat-message-routes.js +235 -0
- package/dist/service/agent/server.d.ts +5 -1
- package/dist/service/agent/server.js +15 -0
- package/dist/service/chat/local-reads.d.ts +71 -0
- package/dist/service/chat/local-reads.js +148 -0
- package/dist/service/chat/reads.js +7 -0
- package/dist/service/chat/routes.js +4 -1
- package/dist/service/chat/schemas.d.ts +5 -0
- package/dist/service/chat/schemas.js +5 -0
- package/dist/service/cron-secret.d.ts +6 -0
- package/dist/service/cron-secret.js +14 -0
- package/dist/service/mcp/server.js +4 -2
- package/dist/service/runtime-contract.d.ts +2 -0
- package/dist/service/schemas.d.ts +8 -2
- package/dist/service/service.js +4 -1
- package/dist/service/workflows.js +2 -9
- package/package.json +1 -1
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
import { Effect, Schema } from "effect";
|
|
2
|
+
import { CHAT_MESSAGE_REVISIONS, CHAT_MESSAGES_TABLE } from "../migrate/storage.js";
|
|
3
|
+
import { uuidv7 } from "./ids.js";
|
|
4
|
+
/**
|
|
5
|
+
* The workspace's chat store: one row per message in `_chat_messages` (docs/agent-chat-storage.md,
|
|
6
|
+
* "The workspace chat store"). A message's state is its latest state: edits, deletions, reactions,
|
|
7
|
+
* delivery statuses and what the agent did with it change its row and take a new `revision`.
|
|
8
|
+
*/
|
|
9
|
+
export const CHAT_TYPES = ["private", "group", "channel"];
|
|
10
|
+
export const CHAT_DIRECTIONS = ["inbound", "outbound", "internal"];
|
|
11
|
+
export const CHAT_MESSAGE_AUTHORS = ["human", "agent", "bot"];
|
|
12
|
+
export const CHAT_MESSAGE_STATUSES = [
|
|
13
|
+
"pending",
|
|
14
|
+
"sent",
|
|
15
|
+
"delivered",
|
|
16
|
+
"read",
|
|
17
|
+
"failed",
|
|
18
|
+
"uncertain",
|
|
19
|
+
];
|
|
20
|
+
export const CHAT_DISPOSITIONS = ["claimed", "turn", "skipped"];
|
|
21
|
+
/** How long a claim on an inbound message holds: an abandoned one is taken again after it. */
|
|
22
|
+
export const CHAT_CLAIM_MINUTES = 10;
|
|
23
|
+
/** The most rows one purge batch deletes or scrubs, and the most batches one purge runs. */
|
|
24
|
+
export const CHAT_PURGE_BATCH = 1000;
|
|
25
|
+
export const CHAT_PURGE_BATCHES = 20;
|
|
26
|
+
const INSTANT = String.raw `\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,6})?)?(?:Z|[+-]\d{2}:\d{2})`;
|
|
27
|
+
const UUID = String.raw `[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}`;
|
|
28
|
+
const CURSOR = new RegExp(`^(${INSTANT})(?:~(${UUID}))?$`, "i");
|
|
29
|
+
/** The cursor a page continues at; `undefined` for text that is none. */
|
|
30
|
+
export function parseChatCursor(value) {
|
|
31
|
+
const match = CURSOR.exec(value);
|
|
32
|
+
if (match === null || Number.isNaN(Date.parse(match[1]))) {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
return { at: match[1], ...(match[2] === undefined ? {} : { id: match[2].toLowerCase() }) };
|
|
36
|
+
}
|
|
37
|
+
export function chatCursorOf(message) {
|
|
38
|
+
return `${message.at}~${message.id}`;
|
|
39
|
+
}
|
|
40
|
+
/** An operation replayed with another request, or a provider id another send holds. */
|
|
41
|
+
export class ChatMessageConflict extends Schema.TaggedError()("ChatMessageConflict", { code: Schema.Literals(["operation_conflict", "message_conflict"]) }) {
|
|
42
|
+
}
|
|
43
|
+
const TABLE = `"${CHAT_MESSAGES_TABLE}"`;
|
|
44
|
+
const NEXT_REVISION = `nextval('"${CHAT_MESSAGE_REVISIONS}"')`;
|
|
45
|
+
function epochMs(column) {
|
|
46
|
+
return `round(extract(epoch from ${column}) * 1000)::double precision`;
|
|
47
|
+
}
|
|
48
|
+
const COLUMNS = [
|
|
49
|
+
`"id"::text AS "id"`,
|
|
50
|
+
`"channel"`,
|
|
51
|
+
`"chat_id"`,
|
|
52
|
+
`"thread_id"`,
|
|
53
|
+
`"chat_type"`,
|
|
54
|
+
`to_jsonb("participants") AS "participants"`,
|
|
55
|
+
`"direction"`,
|
|
56
|
+
`"author"`,
|
|
57
|
+
`"sender_id"`,
|
|
58
|
+
`"sender_name"`,
|
|
59
|
+
`"user_id"::text AS "user_id"`,
|
|
60
|
+
`"message_id"`,
|
|
61
|
+
`"reply_to"`,
|
|
62
|
+
`"text"`,
|
|
63
|
+
`"parts"::text AS "parts"`,
|
|
64
|
+
`"files"::text AS "files"`,
|
|
65
|
+
`"reactions"::text AS "reactions"`,
|
|
66
|
+
`${epochMs(`"at"`)} AS "at"`,
|
|
67
|
+
`${epochMs(`"edited_at"`)} AS "edited_at"`,
|
|
68
|
+
`${epochMs(`"deleted_at"`)} AS "deleted_at"`,
|
|
69
|
+
`"status"`,
|
|
70
|
+
`"failure"`,
|
|
71
|
+
`"operation"`,
|
|
72
|
+
`"disposition"`,
|
|
73
|
+
`"reason"`,
|
|
74
|
+
`${epochMs(`"disposition_at"`)} AS "disposition_at"`,
|
|
75
|
+
`"session_id"`,
|
|
76
|
+
`"turn_id"`,
|
|
77
|
+
`"meta"::text AS "meta"`,
|
|
78
|
+
`${epochMs(`"imported_at"`)} AS "imported_at"`,
|
|
79
|
+
`"revision"::text AS "revision"`,
|
|
80
|
+
`"replaced_by"::text AS "replaced_by"`,
|
|
81
|
+
].join(", ");
|
|
82
|
+
/** A JSON column, selected as its text so a JSON string stays a string whatever the driver does. */
|
|
83
|
+
function json(value) {
|
|
84
|
+
return typeof value === "string" ? JSON.parse(value) : value;
|
|
85
|
+
}
|
|
86
|
+
function jsonArray(value) {
|
|
87
|
+
const parsed = json(value);
|
|
88
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
89
|
+
}
|
|
90
|
+
function text(value) {
|
|
91
|
+
return value === null || value === undefined ? null : String(value);
|
|
92
|
+
}
|
|
93
|
+
function instant(value) {
|
|
94
|
+
return value === null || value === undefined ? null : new Date(Number(value)).toISOString();
|
|
95
|
+
}
|
|
96
|
+
function messageOf(row) {
|
|
97
|
+
return {
|
|
98
|
+
id: String(row.id),
|
|
99
|
+
channel: String(row.channel),
|
|
100
|
+
chatId: String(row.chat_id),
|
|
101
|
+
threadId: text(row.thread_id),
|
|
102
|
+
chatType: row.chat_type,
|
|
103
|
+
participants: jsonArray(row.participants).map(String),
|
|
104
|
+
direction: row.direction,
|
|
105
|
+
author: row.author,
|
|
106
|
+
senderId: text(row.sender_id),
|
|
107
|
+
senderName: text(row.sender_name),
|
|
108
|
+
userId: text(row.user_id),
|
|
109
|
+
messageId: text(row.message_id),
|
|
110
|
+
replyTo: text(row.reply_to),
|
|
111
|
+
text: text(row.text),
|
|
112
|
+
parts: jsonArray(row.parts),
|
|
113
|
+
files: jsonArray(row.files),
|
|
114
|
+
reactions: jsonArray(row.reactions).map((reaction) => {
|
|
115
|
+
const { sender_id, emoji } = reaction;
|
|
116
|
+
return { senderId: String(sender_id), emoji: String(emoji) };
|
|
117
|
+
}),
|
|
118
|
+
at: instant(row.at),
|
|
119
|
+
editedAt: instant(row.edited_at),
|
|
120
|
+
deletedAt: instant(row.deleted_at),
|
|
121
|
+
status: (row.status ?? null),
|
|
122
|
+
failure: text(row.failure),
|
|
123
|
+
operation: text(row.operation),
|
|
124
|
+
disposition: (row.disposition ?? null),
|
|
125
|
+
reason: text(row.reason),
|
|
126
|
+
dispositionAt: instant(row.disposition_at),
|
|
127
|
+
sessionId: text(row.session_id),
|
|
128
|
+
turnId: text(row.turn_id),
|
|
129
|
+
meta: row.meta === null || row.meta === undefined ? null : json(row.meta),
|
|
130
|
+
importedAt: instant(row.imported_at),
|
|
131
|
+
replacedBy: text(row.replaced_by),
|
|
132
|
+
revision: String(row.revision),
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/** Statement parameters, numbered as they are added. */
|
|
136
|
+
function parameters() {
|
|
137
|
+
const values = [];
|
|
138
|
+
return {
|
|
139
|
+
values,
|
|
140
|
+
add: (value, cast) => {
|
|
141
|
+
values.push(value);
|
|
142
|
+
return cast === undefined ? `$${values.length}` : `$${values.length}::${cast}`;
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/** How far a delivery status has come; `failed` is apart: any status but itself moves to it. */
|
|
147
|
+
/** A delivery status's place in its order, as {@link STATUS_RANK} ranks a column. */
|
|
148
|
+
function statusRank(status) {
|
|
149
|
+
return status === "sent" ? 1 : status === "delivered" ? 2 : status === "read" ? 3 : 0;
|
|
150
|
+
}
|
|
151
|
+
const STATUS_RANK = (column) => `(CASE ${column} WHEN 'sent' THEN 1 WHEN 'delivered' THEN 2 WHEN 'read' THEN 3 ELSE 0 END)`;
|
|
152
|
+
/** The chat store on `_chat_messages`, as `ontology_app`. Failures are defects. */
|
|
153
|
+
export function sqlChatMessageStore(sql) {
|
|
154
|
+
const rows = (statement, values = []) => sql.unsafe(statement, values).pipe(Effect.orDie);
|
|
155
|
+
/** A page of `conditions`, newest first, or in revision order after a revision. */
|
|
156
|
+
const page = (conditions, params, input) => Effect.gen(function* () {
|
|
157
|
+
if (input.after !== undefined) {
|
|
158
|
+
conditions.push(`"revision" > ${params.add(input.after, "bigint")}`);
|
|
159
|
+
}
|
|
160
|
+
else {
|
|
161
|
+
// A replaced row is a change for readers who kept it, never part of the chat.
|
|
162
|
+
conditions.push(`"replaced_by" IS NULL`);
|
|
163
|
+
}
|
|
164
|
+
if (input.before !== undefined) {
|
|
165
|
+
const at = params.add(input.before.at, "timestamptz");
|
|
166
|
+
conditions.push(input.before.id === undefined
|
|
167
|
+
? `"at" < ${at}`
|
|
168
|
+
: `("at", "id") < (${at}, ${params.add(input.before.id, "uuid")})`);
|
|
169
|
+
}
|
|
170
|
+
const order = input.after !== undefined ? `"revision" ASC` : `"at" DESC, "id" DESC`;
|
|
171
|
+
const found = (yield* rows(`SELECT ${COLUMNS} FROM ${TABLE} WHERE ${conditions.join(" AND ")} ` +
|
|
172
|
+
`ORDER BY ${order} LIMIT ${params.add(input.limit + 1, "int")}`, params.values)).map(messageOf);
|
|
173
|
+
const messages = found.slice(0, input.limit);
|
|
174
|
+
const last = messages.at(-1);
|
|
175
|
+
return {
|
|
176
|
+
messages,
|
|
177
|
+
nextCursor: found.length <= input.limit || last === undefined
|
|
178
|
+
? null
|
|
179
|
+
: input.after !== undefined
|
|
180
|
+
? last.revision
|
|
181
|
+
: chatCursorOf(last),
|
|
182
|
+
};
|
|
183
|
+
});
|
|
184
|
+
const find = (where, values) => rows(`SELECT "id"::text AS "id", "operation", "fingerprint" FROM ${TABLE} WHERE ${where} LIMIT 1`, values).pipe(Effect.map(([row]) => row));
|
|
185
|
+
/**
|
|
186
|
+
* Runs a write to a chat in a transaction that first takes the chat's lock, so the chat's
|
|
187
|
+
* messages take their revisions in the order they commit: a reader whose bookmark passed a
|
|
188
|
+
* revision never misses a lower one committed after it.
|
|
189
|
+
*/
|
|
190
|
+
const inChat = (channel, chatId, write) => sql
|
|
191
|
+
.withTransaction(rows(`SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, [
|
|
192
|
+
JSON.stringify([CHAT_MESSAGES_TABLE, channel, chatId]),
|
|
193
|
+
]).pipe(Effect.andThen(write)))
|
|
194
|
+
.pipe(Effect.catchTag("SqlError", Effect.die));
|
|
195
|
+
const insert = (input) => Effect.gen(function* () {
|
|
196
|
+
const params = parameters();
|
|
197
|
+
const values = [
|
|
198
|
+
params.add(uuidv7(), "uuid"),
|
|
199
|
+
params.add(input.channel),
|
|
200
|
+
params.add(input.chatId),
|
|
201
|
+
params.add(input.threadId ?? null),
|
|
202
|
+
params.add(input.chatType),
|
|
203
|
+
`ARRAY(SELECT "value"::uuid FROM jsonb_array_elements_text(${params.add(JSON.stringify(input.participants), "jsonb")}))`,
|
|
204
|
+
params.add(input.direction),
|
|
205
|
+
params.add(input.author),
|
|
206
|
+
params.add(input.senderId ?? null),
|
|
207
|
+
params.add(input.senderName ?? null),
|
|
208
|
+
params.add(input.userId ?? null, "uuid"),
|
|
209
|
+
params.add(input.messageId ?? null),
|
|
210
|
+
params.add(input.replyTo ?? null),
|
|
211
|
+
params.add(input.text ?? null),
|
|
212
|
+
params.add(JSON.stringify(input.parts ?? []), "jsonb"),
|
|
213
|
+
params.add(JSON.stringify(input.files ?? []), "jsonb"),
|
|
214
|
+
`date_trunc('milliseconds', coalesce(${params.add(input.at ?? null, "timestamptz")}, now()))`,
|
|
215
|
+
params.add(input.status ?? null),
|
|
216
|
+
params.add(input.operation ?? null),
|
|
217
|
+
params.add(input.fingerprint ?? null),
|
|
218
|
+
params.add(input.sessionId ?? null),
|
|
219
|
+
params.add(input.turnId ?? null),
|
|
220
|
+
params.add(input.meta === undefined ? null : JSON.stringify(input.meta), "jsonb"),
|
|
221
|
+
];
|
|
222
|
+
// Any of the keys may be taken: a redelivery, an echo, a retried send. Nothing changes then.
|
|
223
|
+
const [inserted] = yield* rows(`INSERT INTO ${TABLE} ("id", "channel", "chat_id", "thread_id", "chat_type", ` +
|
|
224
|
+
`"participants", "direction", "author", "sender_id", "sender_name", "user_id", ` +
|
|
225
|
+
`"message_id", "reply_to", "text", "parts", "files", "at", "status", "operation", ` +
|
|
226
|
+
`"fingerprint", "session_id", "turn_id", "meta") VALUES (${values.join(", ")}) ` +
|
|
227
|
+
`ON CONFLICT DO NOTHING RETURNING "id"::text AS "id"`, params.values);
|
|
228
|
+
if (inserted !== undefined) {
|
|
229
|
+
return { id: String(inserted.id), first: true };
|
|
230
|
+
}
|
|
231
|
+
const byOperation = input.operation === undefined
|
|
232
|
+
? undefined
|
|
233
|
+
: yield* find(`"operation" = $1`, [input.operation]);
|
|
234
|
+
if (byOperation !== undefined) {
|
|
235
|
+
// A replay with changed input is refused, never answered with the first request's row.
|
|
236
|
+
if (byOperation.fingerprint !== (input.fingerprint ?? null)) {
|
|
237
|
+
return yield* new ChatMessageConflict({ code: "operation_conflict" });
|
|
238
|
+
}
|
|
239
|
+
return { id: String(byOperation.id), first: false };
|
|
240
|
+
}
|
|
241
|
+
const byMessage = input.messageId === undefined
|
|
242
|
+
? undefined
|
|
243
|
+
: yield* find(`"channel" = $1 AND "chat_id" = $2 AND "message_id" = $3`, [
|
|
244
|
+
input.channel,
|
|
245
|
+
input.chatId,
|
|
246
|
+
input.messageId,
|
|
247
|
+
]);
|
|
248
|
+
if (byMessage === undefined) {
|
|
249
|
+
// The conflicting row was purged between the insert and the read: record it again.
|
|
250
|
+
return yield* insert(input);
|
|
251
|
+
}
|
|
252
|
+
if (input.operation !== undefined && byMessage.operation !== null) {
|
|
253
|
+
return yield* new ChatMessageConflict({ code: "message_conflict" });
|
|
254
|
+
}
|
|
255
|
+
return { id: String(byMessage.id), first: false };
|
|
256
|
+
});
|
|
257
|
+
const record = (input) => inChat(input.channel, input.chatId, insert(input));
|
|
258
|
+
/** Updates the message `change` names with `assignments` where `guard` holds. */
|
|
259
|
+
const update = (change, params, assignments, guard = []) => inChat(change.channel, change.chatId, rows(`UPDATE ${TABLE} SET ${assignments.join(", ")} ` +
|
|
260
|
+
`WHERE "channel" = ${params.add(change.channel)} ` +
|
|
261
|
+
`AND "chat_id" = ${params.add(change.chatId)} ` +
|
|
262
|
+
`AND "message_id" = ${params.add(change.messageId)} ` +
|
|
263
|
+
`AND "purged_at" IS NULL${guard.map((condition) => ` AND ${condition}`).join("")} ` +
|
|
264
|
+
`RETURNING "id"`, params.values)).pipe(Effect.map((updated) => ({ applied: updated.length > 0 })));
|
|
265
|
+
const revised = `"revision" = ${NEXT_REVISION}`;
|
|
266
|
+
const sent = (change) => inChat(change.channel, change.chatId, Effect.gen(function* () {
|
|
267
|
+
const [row] = yield* rows(`SELECT "id"::text AS "id", "status" FROM ${TABLE} ` +
|
|
268
|
+
`WHERE "operation" = $1 AND "channel" = $2 AND "chat_id" = $3 ` +
|
|
269
|
+
`AND "purged_at" IS NULL FOR UPDATE`, [change.operation, change.channel, change.chatId]);
|
|
270
|
+
// A receipt is written once: a replay, or one for a send no longer waiting, changes nothing.
|
|
271
|
+
if (row === undefined ||
|
|
272
|
+
(row.status !== "pending" && row.status !== "uncertain") ||
|
|
273
|
+
row.status === change.status) {
|
|
274
|
+
return { applied: false };
|
|
275
|
+
}
|
|
276
|
+
let echo;
|
|
277
|
+
if (change.providerMessageId !== undefined) {
|
|
278
|
+
const [holder] = yield* rows(`SELECT "id"::text AS "id", "operation" FROM ${TABLE} ` +
|
|
279
|
+
`WHERE "channel" = $1 AND "chat_id" = $2 AND "message_id" = $3 AND "id" <> $4::uuid ` +
|
|
280
|
+
`FOR UPDATE`, [change.channel, change.chatId, change.providerMessageId, row.id]);
|
|
281
|
+
if (holder !== undefined && holder.operation !== null) {
|
|
282
|
+
return yield* new ChatMessageConflict({ code: "message_conflict" });
|
|
283
|
+
}
|
|
284
|
+
// The provider's echo of this send came first: the send's own row is the message, and
|
|
285
|
+
// it takes what already changed on the echo, so the receipt's lateness loses nothing.
|
|
286
|
+
// The echo's row stays, emptied and `replaced_by` the send's, under a new revision, so a
|
|
287
|
+
// reader that polled the echo learns to drop it.
|
|
288
|
+
if (holder !== undefined) {
|
|
289
|
+
[echo] = yield* rows(`WITH "echo" AS (SELECT "text", "edited_at", "deleted_at", "reactions", "status" ` +
|
|
290
|
+
`FROM ${TABLE} WHERE "id" = $1::uuid) ` +
|
|
291
|
+
`UPDATE ${TABLE} SET "message_id" = NULL, "reply_to" = NULL, "text" = NULL, ` +
|
|
292
|
+
`"parts" = '[]', "files" = '[]', "reactions" = '[]', "meta" = NULL, ` +
|
|
293
|
+
`"replaced_by" = $2::uuid, ${revised} FROM "echo" WHERE "id" = $1::uuid ` +
|
|
294
|
+
`RETURNING "echo"."text", "echo"."edited_at"::text AS "edited_at", ` +
|
|
295
|
+
`"echo"."deleted_at"::text AS "deleted_at", ` +
|
|
296
|
+
`"echo"."reactions"::text AS "reactions", "echo"."status"`, [holder.id, row.id]);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
// A delivery or read the echo already had is later than the receipt's `sent`.
|
|
300
|
+
const status = change.status !== "failed" &&
|
|
301
|
+
echo !== undefined &&
|
|
302
|
+
statusRank(echo.status) > statusRank(change.status)
|
|
303
|
+
? String(echo.status)
|
|
304
|
+
: change.status;
|
|
305
|
+
const deleted = `$6::timestamptz IS NOT NULL`;
|
|
306
|
+
yield* rows(`UPDATE ${TABLE} SET "status" = $2::text, ` +
|
|
307
|
+
`"message_id" = coalesce($3::text, "message_id"), ` +
|
|
308
|
+
`"failure" = CASE WHEN $2::text = 'failed' THEN $4::text ELSE NULL END, ` +
|
|
309
|
+
`"text" = CASE WHEN ${deleted} THEN NULL ` +
|
|
310
|
+
`WHEN $5::timestamptz IS NOT NULL THEN $7::text ELSE "text" END, ` +
|
|
311
|
+
`"edited_at" = coalesce($5::timestamptz, "edited_at"), ` +
|
|
312
|
+
`"deleted_at" = coalesce($6::timestamptz, "deleted_at"), ` +
|
|
313
|
+
`"parts" = CASE WHEN ${deleted} THEN '[]' ELSE "parts" END, ` +
|
|
314
|
+
`"files" = CASE WHEN ${deleted} THEN '[]' ELSE "files" END, ` +
|
|
315
|
+
`"reactions" = CASE WHEN ${deleted} THEN '[]' ` +
|
|
316
|
+
`WHEN coalesce($8::jsonb, '[]') <> '[]' THEN $8::jsonb ELSE "reactions" END, ` +
|
|
317
|
+
`${revised} WHERE "id" = $1::uuid`, [
|
|
318
|
+
row.id,
|
|
319
|
+
status,
|
|
320
|
+
change.providerMessageId ?? null,
|
|
321
|
+
change.failure ?? null,
|
|
322
|
+
echo?.edited_at ?? null,
|
|
323
|
+
echo?.deleted_at ?? null,
|
|
324
|
+
echo?.text ?? null,
|
|
325
|
+
echo?.reactions ?? null,
|
|
326
|
+
]);
|
|
327
|
+
return { applied: true };
|
|
328
|
+
}));
|
|
329
|
+
const change = (input) => {
|
|
330
|
+
const params = parameters();
|
|
331
|
+
switch (input.change) {
|
|
332
|
+
case "edit": {
|
|
333
|
+
const edited = params.add(input.text, "text");
|
|
334
|
+
const at = `date_trunc('milliseconds', coalesce(${params.add(input.at ?? null, "timestamptz")}, now()))`;
|
|
335
|
+
// An edit older than the one applied, a late or retried delivery, changes nothing.
|
|
336
|
+
return update(input, params, [`"text" = ${edited}`, `"edited_at" = ${at}`, revised], [
|
|
337
|
+
`"deleted_at" IS NULL`,
|
|
338
|
+
`"text" IS DISTINCT FROM ${edited}`,
|
|
339
|
+
`("edited_at" IS NULL OR "edited_at" <= ${at})`,
|
|
340
|
+
]);
|
|
341
|
+
}
|
|
342
|
+
case "delete":
|
|
343
|
+
// The person retracted it: its content goes, the row stays as the message's place.
|
|
344
|
+
return update(input, params, [
|
|
345
|
+
`"text" = NULL`,
|
|
346
|
+
`"parts" = '[]'`,
|
|
347
|
+
`"files" = '[]'`,
|
|
348
|
+
`"reactions" = '[]'`,
|
|
349
|
+
`"deleted_at" = date_trunc('milliseconds', coalesce(${params.add(input.at ?? null, "timestamptz")}, now()))`,
|
|
350
|
+
revised,
|
|
351
|
+
], [`"deleted_at" IS NULL`]);
|
|
352
|
+
case "reaction": {
|
|
353
|
+
const sender = params.add(input.senderId, "text");
|
|
354
|
+
const emoji = params.add(input.emoji, "text");
|
|
355
|
+
const others = `(SELECT coalesce(jsonb_agg("e" ORDER BY "n"), '[]'::jsonb) ` +
|
|
356
|
+
`FROM jsonb_array_elements("reactions") WITH ORDINALITY AS "r"("e", "n") ` +
|
|
357
|
+
`WHERE "e" ->> 'sender_id' IS DISTINCT FROM ${sender})`;
|
|
358
|
+
const next = `${others} || CASE WHEN ${emoji} = '' THEN '[]'::jsonb ` +
|
|
359
|
+
`ELSE jsonb_build_array(jsonb_build_object('sender_id', ${sender}, 'emoji', ${emoji})) END`;
|
|
360
|
+
// A sender has one reaction; an empty emoji removes theirs. A repeat changes nothing.
|
|
361
|
+
return update(input, params, [`"reactions" = ${next}`, revised], [
|
|
362
|
+
`"deleted_at" IS NULL`,
|
|
363
|
+
`"reactions" IS DISTINCT FROM ${next}`,
|
|
364
|
+
`NOT EXISTS (SELECT 1 FROM jsonb_array_elements("reactions") AS "r"("e") ` +
|
|
365
|
+
`WHERE "e" ->> 'sender_id' = ${sender} AND "e" ->> 'emoji' = ${emoji})`,
|
|
366
|
+
]);
|
|
367
|
+
}
|
|
368
|
+
case "status": {
|
|
369
|
+
const status = params.add(input.status, "text");
|
|
370
|
+
// Never backwards, except to failed; read implies delivered. A failed send stays failed.
|
|
371
|
+
return update(input, params, [
|
|
372
|
+
`"status" = ${status}`,
|
|
373
|
+
`"failure" = CASE WHEN ${status} = 'failed' THEN ${params.add(input.failure ?? null, "text")} ELSE "failure" END`,
|
|
374
|
+
revised,
|
|
375
|
+
], [
|
|
376
|
+
`"direction" = 'outbound'`,
|
|
377
|
+
`"status" IS DISTINCT FROM 'failed'`,
|
|
378
|
+
`(${status} = 'failed' OR ${STATUS_RANK(status)} > ${STATUS_RANK(`"status"`)})`,
|
|
379
|
+
]);
|
|
380
|
+
}
|
|
381
|
+
case "disposition": {
|
|
382
|
+
const reason = params.add(input.reason ?? null, "text");
|
|
383
|
+
const session = params.add(input.sessionId ?? null, "text");
|
|
384
|
+
const turn = params.add(input.turnId ?? null, "text");
|
|
385
|
+
const expired = `"disposition_at" < now() - interval '${CHAT_CLAIM_MINUTES} minutes'`;
|
|
386
|
+
const assignments = [
|
|
387
|
+
`"disposition" = ${params.add(input.disposition, "text")}`,
|
|
388
|
+
`"disposition_at" = now()`,
|
|
389
|
+
input.disposition === "claimed"
|
|
390
|
+
? `"reason" = ${reason}`
|
|
391
|
+
: `"reason" = coalesce(${reason}, "reason")`,
|
|
392
|
+
`"session_id" = coalesce(${session}, "session_id")`,
|
|
393
|
+
`"turn_id" = coalesce(${turn}, "turn_id")`,
|
|
394
|
+
revised,
|
|
395
|
+
];
|
|
396
|
+
const unchanged = `"reason" IS NOT DISTINCT FROM coalesce(${reason}, "reason") ` +
|
|
397
|
+
`AND "session_id" IS NOT DISTINCT FROM coalesce(${session}, "session_id") ` +
|
|
398
|
+
`AND "turn_id" IS NOT DISTINCT FROM coalesce(${turn}, "turn_id")`;
|
|
399
|
+
// The dispatch fence: one conditional update, so only one caller's claim returns the row.
|
|
400
|
+
const allowed = {
|
|
401
|
+
claimed: `("disposition" IS NULL OR ("disposition" = 'claimed' AND ${expired}))`,
|
|
402
|
+
turn: `("disposition" IS NULL OR "disposition" = 'claimed' ` +
|
|
403
|
+
`OR ("disposition" = 'turn' AND NOT (${unchanged})))`,
|
|
404
|
+
skipped: `("disposition" IS NULL OR ("disposition" = 'claimed' AND ${expired}) ` +
|
|
405
|
+
`OR ("disposition" = 'skipped' AND NOT (${unchanged})))`,
|
|
406
|
+
}[input.disposition];
|
|
407
|
+
return update(input, params, assignments, [`"direction" = 'inbound'`, allowed]);
|
|
408
|
+
}
|
|
409
|
+
case "sent":
|
|
410
|
+
return sent(input);
|
|
411
|
+
case "meta": {
|
|
412
|
+
const meta = params.add(JSON.stringify(input.meta), "jsonb");
|
|
413
|
+
// Channel-private routing state: no reader sees it, so it takes no revision.
|
|
414
|
+
return update(input, params, [`"meta" = ${meta}`], [`"meta" IS DISTINCT FROM ${meta}`]);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
};
|
|
418
|
+
const read = (input) => {
|
|
419
|
+
const params = parameters();
|
|
420
|
+
const conditions = [`"channel" = ${params.add(input.channel)}`, `"purged_at" IS NULL`];
|
|
421
|
+
if (input.chatId !== undefined) {
|
|
422
|
+
conditions.push(`"chat_id" = ${params.add(input.chatId)}`);
|
|
423
|
+
}
|
|
424
|
+
if (input.threadId !== undefined) {
|
|
425
|
+
conditions.push(input.threadId === null
|
|
426
|
+
? `"thread_id" IS NULL`
|
|
427
|
+
: `"thread_id" = ${params.add(input.threadId)}`);
|
|
428
|
+
}
|
|
429
|
+
if (input.messageId !== undefined) {
|
|
430
|
+
conditions.push(`"message_id" = ${params.add(input.messageId)}`);
|
|
431
|
+
}
|
|
432
|
+
if (input.pending === true) {
|
|
433
|
+
conditions.push(`"direction" = 'outbound'`, `"status" = 'pending'`);
|
|
434
|
+
}
|
|
435
|
+
return page(conditions, params, input);
|
|
436
|
+
};
|
|
437
|
+
const search = (input, reader) => {
|
|
438
|
+
const params = parameters();
|
|
439
|
+
const conditions = [
|
|
440
|
+
`"channel" = ${params.add(input.channel)}`,
|
|
441
|
+
`"chat_id" = ${params.add(input.chatId)}`,
|
|
442
|
+
`"purged_at" IS NULL`,
|
|
443
|
+
];
|
|
444
|
+
if (input.threadId !== undefined) {
|
|
445
|
+
conditions.push(`"thread_id" = ${params.add(input.threadId)}`);
|
|
446
|
+
}
|
|
447
|
+
if (input.from !== undefined) {
|
|
448
|
+
conditions.push(`"at" >= ${params.add(input.from, "timestamptz")}`);
|
|
449
|
+
}
|
|
450
|
+
if (input.to !== undefined) {
|
|
451
|
+
conditions.push(`"at" <= ${params.add(input.to, "timestamptz")}`);
|
|
452
|
+
}
|
|
453
|
+
if (input.senderId !== undefined) {
|
|
454
|
+
const sender = params.add(input.senderId, "text");
|
|
455
|
+
// The agent's own messages answer to its sender, `agent`, as the archive keeps them.
|
|
456
|
+
conditions.push(`("sender_id" = ${sender} OR (${sender} = 'agent' AND "author" = 'agent'))`);
|
|
457
|
+
}
|
|
458
|
+
if (input.q !== undefined && input.q.trim() !== "") {
|
|
459
|
+
conditions.push(`to_tsvector('simple', coalesce("text", '')) @@ plainto_tsquery('simple', ${params.add(input.q, "text")})`);
|
|
460
|
+
}
|
|
461
|
+
// The archive's reader rule, row by row: a private message by its own participants.
|
|
462
|
+
const rules = [
|
|
463
|
+
...(reader.groups ? [`"chat_type" <> 'private'`] : []),
|
|
464
|
+
// An exact chat reads what reached the provider: never a send still unsent, nor one that
|
|
465
|
+
// failed before the provider took it. One it took and later failed stays, `failed`, so a
|
|
466
|
+
// reader polling after a revision sees the same chat as one reading it whole.
|
|
467
|
+
...(reader.chat
|
|
468
|
+
? [
|
|
469
|
+
`("direction" = 'inbound' OR ("direction" = 'outbound' AND ` +
|
|
470
|
+
`("status" IS NULL OR "status" IN ('sent', 'delivered', 'read') OR ` +
|
|
471
|
+
`("status" = 'failed' AND "message_id" IS NOT NULL))))`,
|
|
472
|
+
]
|
|
473
|
+
: []),
|
|
474
|
+
...(reader.participantId === null
|
|
475
|
+
? []
|
|
476
|
+
: [
|
|
477
|
+
`("chat_type" = 'private' AND ${params.add(reader.participantId, "text")} = ` +
|
|
478
|
+
`ANY("participants"::text[]))`,
|
|
479
|
+
]),
|
|
480
|
+
];
|
|
481
|
+
if (rules.length === 0) {
|
|
482
|
+
return Effect.succeed({ messages: [], nextCursor: null });
|
|
483
|
+
}
|
|
484
|
+
conditions.push(`(${rules.join(" OR ")})`);
|
|
485
|
+
return page(conditions, params, input);
|
|
486
|
+
};
|
|
487
|
+
const holds = ({ channel, chatId }) => rows(`SELECT EXISTS (SELECT 1 FROM ${TABLE} WHERE "channel" = $1 AND "chat_id" = $2) AS "holds"`, [channel, chatId]).pipe(Effect.map(([row]) => row?.holds === true || row?.holds === "t"));
|
|
488
|
+
const purge = ({ retentionDays }) => Effect.gen(function* () {
|
|
489
|
+
let deleted = 0;
|
|
490
|
+
let scrubbed = 0;
|
|
491
|
+
let more = false;
|
|
492
|
+
for (let batch = 0; batch < CHAT_PURGE_BATCHES; batch++) {
|
|
493
|
+
// Each batch commits on its own and skips rows another writer holds, so the purge never
|
|
494
|
+
// waits on a live chat and never holds a long lock.
|
|
495
|
+
const [counted] = yield* rows(`WITH "expired" AS MATERIALIZED (` +
|
|
496
|
+
`SELECT "id", "operation" IS NOT NULL AS "tombstone" FROM ${TABLE} ` +
|
|
497
|
+
`WHERE "at" < now() - make_interval(days => $1::int) AND "purged_at" IS NULL ` +
|
|
498
|
+
`ORDER BY "at" LIMIT $2::int FOR UPDATE SKIP LOCKED` +
|
|
499
|
+
`), "scrubbed" AS (` +
|
|
500
|
+
`UPDATE ${TABLE} SET "chat_id" = '', "thread_id" = NULL, "participants" = '{}', ` +
|
|
501
|
+
`"sender_id" = NULL, "sender_name" = NULL, "user_id" = NULL, "message_id" = NULL, ` +
|
|
502
|
+
`"reply_to" = NULL, "text" = NULL, "parts" = '[]', "files" = '[]', ` +
|
|
503
|
+
`"reactions" = '[]', "reason" = NULL, "session_id" = NULL, "turn_id" = NULL, ` +
|
|
504
|
+
`"meta" = NULL, "purged_at" = now(), ${revised} ` +
|
|
505
|
+
`WHERE "id" IN (SELECT "id" FROM "expired" WHERE "tombstone") RETURNING 1` +
|
|
506
|
+
`), "deleted" AS (` +
|
|
507
|
+
`DELETE FROM ${TABLE} WHERE "id" IN (SELECT "id" FROM "expired" WHERE NOT "tombstone") ` +
|
|
508
|
+
`RETURNING 1` +
|
|
509
|
+
`) SELECT (SELECT count(*) FROM "scrubbed")::int AS "scrubbed", ` +
|
|
510
|
+
`(SELECT count(*) FROM "deleted")::int AS "deleted"`, [retentionDays, CHAT_PURGE_BATCH]);
|
|
511
|
+
const batchScrubbed = Number(counted?.scrubbed ?? 0);
|
|
512
|
+
const batchDeleted = Number(counted?.deleted ?? 0);
|
|
513
|
+
scrubbed += batchScrubbed;
|
|
514
|
+
deleted += batchDeleted;
|
|
515
|
+
more = batchScrubbed + batchDeleted >= CHAT_PURGE_BATCH;
|
|
516
|
+
if (!more) {
|
|
517
|
+
break;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
return { deleted, scrubbed, more };
|
|
521
|
+
});
|
|
522
|
+
return { record, change, read, holds, search, purge };
|
|
523
|
+
}
|
|
@@ -11,6 +11,8 @@ import { type ChatArchiveTransport } from "./chat-archive.js";
|
|
|
11
11
|
*/
|
|
12
12
|
export declare function archiveRoutes(options: {
|
|
13
13
|
readonly transport: ChatArchiveTransport;
|
|
14
|
+
/** The days the ontology declares it keeps its chats' messages, if it declares them. */
|
|
15
|
+
readonly chatRetentionDays?: number | undefined;
|
|
14
16
|
readonly verifyToken: TokenVerifier;
|
|
15
17
|
readonly verifyRuntime?: RuntimeTokenVerifier | undefined;
|
|
16
18
|
readonly exchangeSession?: SessionExchange | undefined;
|
|
@@ -8,6 +8,7 @@ import { OntologyBackend } from "../runtime-contract.js";
|
|
|
8
8
|
import { runtimeCredential } from "../runtime-identity.js";
|
|
9
9
|
import { ChatSearch } from "./chat-archive.js";
|
|
10
10
|
import { withChatMembership } from "../chat/resolve.js";
|
|
11
|
+
import { withChatStore } from "../chat/local-reads.js";
|
|
11
12
|
/**
|
|
12
13
|
* Same member scope as MCP, accessible to app clients with their usual bearer/session.
|
|
13
14
|
* @legacy agent.legacy-conversation-routes The route keeps its published path until it is removed.
|
|
@@ -16,7 +17,7 @@ export function archiveRoutes(options) {
|
|
|
16
17
|
return Layer.effectDiscard(Effect.gen(function* () {
|
|
17
18
|
const router = yield* HttpRouter.HttpRouter;
|
|
18
19
|
const backend = yield* OntologyBackend;
|
|
19
|
-
const transport = withChatMembership(options.transport, backend);
|
|
20
|
+
const transport = withChatMembership(withChatStore(options.transport, backend, options.chatRetentionDays), backend);
|
|
20
21
|
yield* router.add("POST", "/api/ontology/agent/conversations/search", (request) => Effect.gen(function* () {
|
|
21
22
|
const bearer = yield* HttpApiBuilder.securityDecode(HttpApiSecurity.bearer).pipe(Effect.provideService(HttpServerRequest.HttpServerRequest, request));
|
|
22
23
|
const operation = Effect.gen(function* () {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Effect, Schema } from "effect";
|
|
2
2
|
import type { Principal } from "../../runtime.js";
|
|
3
|
-
import { PermissionDenied } from "../../errors.js";
|
|
3
|
+
import { ActionRejected, PermissionDenied } from "../../errors.js";
|
|
4
4
|
import type { OntologyEnvironment } from "../config.js";
|
|
5
5
|
export declare const ChatSearch: Schema.Struct<{
|
|
6
6
|
readonly q: Schema.optionalKey<Schema.String>;
|
|
@@ -40,7 +40,16 @@ export type ChatArchiveTransport = (input: {
|
|
|
40
40
|
* principal, such as a workflow's user, reads these alone.
|
|
41
41
|
*/
|
|
42
42
|
readonly chats?: ReadonlyArray<string>;
|
|
43
|
-
|
|
44
|
-
|
|
43
|
+
/**
|
|
44
|
+
* The chat's messages changed after this `revision` of the workspace's chat store, oldest change
|
|
45
|
+
* first: a read of the store alone (`withChatStore`).
|
|
46
|
+
*/
|
|
47
|
+
readonly after?: string;
|
|
48
|
+
}) => Effect.Effect<ChatPage, ChatArchiveUnavailable | PermissionDenied | ActionRejected>;
|
|
49
|
+
/**
|
|
50
|
+
* The authenticated ontology service forwards its resolved member, never a caller-supplied ID.
|
|
51
|
+
* @legacy agent.cloud-chat-archive The chat archive in Cloud, read where the workspace's chat store
|
|
52
|
+
* does not hold a chat.
|
|
53
|
+
*/
|
|
45
54
|
export declare function platformChatArchive(environment: OntologyEnvironment, fetchImpl?: typeof fetch): ChatArchiveTransport;
|
|
46
55
|
export {};
|
|
@@ -20,7 +20,11 @@ export const ChatPage = Schema.Struct({
|
|
|
20
20
|
});
|
|
21
21
|
export class ChatArchiveUnavailable extends Schema.TaggedError()("ChatArchiveUnavailable", { diagnostic: Schema.String, cause: Schema.optionalKey(Schema.Unknown) }) {
|
|
22
22
|
}
|
|
23
|
-
/**
|
|
23
|
+
/**
|
|
24
|
+
* The authenticated ontology service forwards its resolved member, never a caller-supplied ID.
|
|
25
|
+
* @legacy agent.cloud-chat-archive The chat archive in Cloud, read where the workspace's chat store
|
|
26
|
+
* does not hold a chat.
|
|
27
|
+
*/
|
|
24
28
|
export function platformChatArchive(environment, fetchImpl = fetch) {
|
|
25
29
|
return ({ search, principal, identityToken, memberGroups, chats }) => {
|
|
26
30
|
// A service, such as a workflow's user, reads only the exact chats the ontology checked.
|