@segmentstream/ontology 0.160.0 → 0.162.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.
@@ -6,7 +6,7 @@ import { action } from "../action.js";
6
6
  import { AgentChat, agentChatKey } from "../agent-chat.js";
7
7
  import { chatChannelKind } from "../chat-channel.js";
8
8
  import { historyTableName, quoteIdentifier, tableName } from "../migrate/storage.js";
9
- import { addressesOfDraft, AgentDraft, participantsOfDraft, draftAddresses, draftParticipants, } from "../agent-draft.js";
9
+ import { addressesOfDraft, AgentDraft, participantsOfDraft, draftAddresses, draftFilesOf, draftParticipants, } from "../agent-draft.js";
10
10
  import { AGENT_IDENTITIES_TABLE, AGENT_PAIRINGS_TABLE, CHANNEL_USERS_TABLE, IDENTITY_NOTICES_TABLE, USER_TABLE, } from "../migrate/storage.js";
11
11
  import { inboxChannelsOf, inboxRolesOf, takeoverChannelsOf, takeoverProvidersOf, } from "../manifest.js";
12
12
  import { GUEST_ROLE } from "../names.js";
@@ -18,7 +18,7 @@ import { resolveAgentIdentity } from "./resolve-agent-identity.js";
18
18
  import { completeAgentLimitNotice } from "./agent-counters.js";
19
19
  import { isMemberBlocked, setMemberBlocked, resolveMemberById } from "./principals.js";
20
20
  import { sqlAgentWebStore } from "./agent-web.js";
21
- import { sqlChatMessageStore } from "./chat-messages.js";
21
+ import { chatCursorOf, parseChatCursor, sqlChatMessageStore } from "./chat-messages.js";
22
22
  import { guestChat } from "./guests.js";
23
23
  import { WEB_PROVIDER } from "../service/runtime-identity.js";
24
24
  import { isRecordId } from "./records.js";
@@ -155,6 +155,35 @@ const HOLD_DEFINITION = action({
155
155
  export function sqlAgentStore(ontology, sql) {
156
156
  const rows = (statement, values = []) => sql.unsafe(statement, values).pipe(Effect.orDie);
157
157
  const memberPrincipal = (userId) => resolveMemberById(ontology, userId).pipe(Effect.provideService(SqlClient.SqlClient, sql));
158
+ const messages = sqlChatMessageStore(sql);
159
+ /** The newest message the turn took in the chat, as the chat store's place; null without one. */
160
+ const turnBasis = (channel, chatId, turnId) => messages
161
+ .turnBasis({ channel, chatId, turnId })
162
+ .pipe(Effect.map((cursor) => (cursor === undefined ? null : chatCursorOf(cursor))));
163
+ /**
164
+ * Whether the person wrote in a draft's chat after the turn that wrote it: one definition for
165
+ * `approve`'s `unlessNewer` and the `newer` action. The place the turn read to is the draft's
166
+ * basis, or, when its hold came before the chat store named the turn's messages, those messages
167
+ * now; null when neither is known. In a group, only the draft's person counts.
168
+ */
169
+ const newerOf = (review) => Effect.gen(function* () {
170
+ const channel = nullableText(review.channel) ?? String(review.channel_kind);
171
+ const chatId = String(review.chat_id);
172
+ const turnId = nullableText(review.turn_id);
173
+ const basis = parseChatCursor(nullableText(review.basis) ?? "") ??
174
+ (turnId === null ? undefined : yield* messages.turnBasis({ channel, chatId, turnId }));
175
+ if (basis === undefined) {
176
+ return null;
177
+ }
178
+ const person = nullableText(review.person_id);
179
+ return yield* messages.wroteAfter({
180
+ channel,
181
+ chatId,
182
+ after: basis,
183
+ ...(turnId === null ? {} : { turnId }),
184
+ ...(review.chat_kind === "group" && person !== null ? { userId: person } : {}),
185
+ });
186
+ });
158
187
  /**
159
188
  * Holds a reply for review once per key, in a transaction bounded and admitted as an action's,
160
189
  * and starts the workflows whose triggers on `agent_draft` fire for it. `resolve` runs in the
@@ -263,7 +292,17 @@ export function sqlAgentStore(ontology, sql) {
263
292
  thread_id: input.threadId === "" ? null : input.threadId,
264
293
  reply_to: input.replyTo,
265
294
  session_id: input.sessionId,
295
+ // A redraft answers what the reply it replaces answered.
296
+ turn_id: resolved.kind === "revision"
297
+ ? nullableText(resolved.previous.turn_id)
298
+ : (input.turnId ?? null),
299
+ basis: resolved.kind === "revision"
300
+ ? nullableText(resolved.previous.basis)
301
+ : input.turnId === undefined
302
+ ? null
303
+ : yield* turnBasis(input.channel, input.chatId, input.turnId),
266
304
  draft: input.text,
305
+ files: (input.files ?? []).length === 0 ? null : input.files,
267
306
  text: null,
268
307
  status: "pending",
269
308
  // Select values are stored by their wire names.
@@ -960,6 +999,10 @@ export function sqlAgentStore(ontology, sql) {
960
999
  memberId: String(previous.person_id),
961
1000
  sessionId: String(previous.session_id),
962
1001
  text: input.text,
1002
+ // A redraft rewrites the text: the files the reply carries stay with it.
1003
+ ...(draftFilesOf(previous.files).length === 0
1004
+ ? {}
1005
+ : { files: draftFilesOf(previous.files) }),
963
1006
  mode: "always",
964
1007
  confidence: null,
965
1008
  },
@@ -996,6 +1039,86 @@ export function sqlAgentStore(ontology, sql) {
996
1039
  return true;
997
1040
  }))
998
1041
  .pipe(Effect.orDie),
1042
+ reserveDraft: (input) => sql
1043
+ .withTransaction(Effect.gen(function* () {
1044
+ if (!isRecordId(input.review)) {
1045
+ return { kind: "missing" };
1046
+ }
1047
+ yield* beginReplicationWrite(sql);
1048
+ const runtime = makeOntologyRuntime(ontology, sql, {
1049
+ action: `${AgentDraft.name}.approve`,
1050
+ actionId: randomUUID(),
1051
+ principalId: isRecordId(input.principalId) ? input.principalId : null,
1052
+ });
1053
+ // The draft's lock orders this reservation and any rejection or dismissal of it.
1054
+ const [review] = yield* runtime
1055
+ .find({
1056
+ entity: AgentDraft.name,
1057
+ options: { where: { id: input.review }, limit: 1, forUpdate: true },
1058
+ })
1059
+ .pipe(Effect.orDie);
1060
+ if (review === undefined) {
1061
+ return { kind: "missing" };
1062
+ }
1063
+ const reserved = nullableText(review.message);
1064
+ // An approval reserved the delivery already: its replay reads the receipt.
1065
+ if (reserved === null) {
1066
+ if (review.status !== "pending") {
1067
+ return { kind: "decided", status: String(review.status) };
1068
+ }
1069
+ if (input.unlessNewer) {
1070
+ // The chat's lock, which the reservation takes too, before reading it: a message
1071
+ // being recorded is read once it commits, and none commits before the reservation.
1072
+ yield* messages.lockChat({
1073
+ channel: nullableText(review.channel) ?? String(review.channel_kind),
1074
+ chatId: String(review.chat_id),
1075
+ });
1076
+ const newer = yield* newerOf(review);
1077
+ // Refused before anything changes: a redraft asked for still replaces it.
1078
+ if (newer !== false) {
1079
+ return { kind: "newer", newer };
1080
+ }
1081
+ }
1082
+ if (review.revision !== null && review.revision !== undefined) {
1083
+ yield* runtime
1084
+ .update({
1085
+ entity: AgentDraft.name,
1086
+ id: String(review.id),
1087
+ values: { revision: null, revision_state: null },
1088
+ })
1089
+ .pipe(Effect.orDie);
1090
+ }
1091
+ }
1092
+ const value = yield* input.reserve;
1093
+ const claim = input.claimOf(value);
1094
+ if (claim !== undefined && claim !== reserved) {
1095
+ yield* runtime
1096
+ .update({
1097
+ entity: AgentDraft.name,
1098
+ id: String(review.id),
1099
+ values: { message: claim },
1100
+ })
1101
+ .pipe(Effect.orDie);
1102
+ }
1103
+ return { kind: "reserved", value };
1104
+ }))
1105
+ .pipe(Effect.catchTag("SqlError", Effect.die)),
1106
+ draftsNewer: (drafts) => Effect.gen(function* () {
1107
+ const ids = drafts.filter(isRecordId);
1108
+ const found = ids.length === 0
1109
+ ? []
1110
+ : yield* makeOntologyRuntime(ontology, sql).find({
1111
+ entity: AgentDraft.name,
1112
+ options: { where: { id: { in: ids } }, limit: ids.length },
1113
+ });
1114
+ const byId = new Map(found.map((record) => [String(record.id), record]));
1115
+ return yield* Effect.forEach(drafts, (draft) => {
1116
+ const record = byId.get(draft);
1117
+ return (record === undefined || record.status !== "pending"
1118
+ ? Effect.succeed(null)
1119
+ : newerOf(record)).pipe(Effect.map((newer) => ({ draft, newer })));
1120
+ });
1121
+ }).pipe(Effect.orDie),
999
1122
  cancelRevision: (input) => sql
1000
1123
  .withTransaction(Effect.gen(function* () {
1001
1124
  if (!isRecordId(input.review)) {
@@ -1128,7 +1251,7 @@ export function sqlAgentStore(ontology, sql) {
1128
1251
  : timestampText(record.decided_at),
1129
1252
  }));
1130
1253
  }).pipe(Effect.orDie),
1131
- chatMessages: sqlChatMessageStore(sql),
1254
+ chatMessages: messages,
1132
1255
  web: sqlAgentWebStore(ontology, sql, {
1133
1256
  signUp: (visitorId) => resolveChannelSignIn(ontology, sql, { provider: WEB_PROVIDER, externalId: visitorId }),
1134
1257
  }),
@@ -298,6 +298,38 @@ export interface ChatMessageStore {
298
298
  readonly channel: string;
299
299
  readonly chatId: string;
300
300
  }) => Effect.Effect<boolean>;
301
+ /**
302
+ * Takes a chat's lock until the caller's transaction ends: the lock every write to the chat takes
303
+ * first, so what the caller reads of the chat holds until it commits.
304
+ */
305
+ readonly lockChat: (chat: {
306
+ readonly channel: string;
307
+ readonly chatId: string;
308
+ }) => Effect.Effect<void>;
309
+ /**
310
+ * The newest message a turn took in a chat (`turn_id`), as the place a draft of the turn's reply
311
+ * was written from; `undefined` when the store holds none of the turn's messages.
312
+ */
313
+ readonly turnBasis: (input: {
314
+ readonly channel: string;
315
+ readonly chatId: string;
316
+ readonly turnId: string;
317
+ }) => Effect.Effect<{
318
+ readonly at: string;
319
+ readonly id: string;
320
+ } | undefined>;
321
+ /**
322
+ * Whether a person wrote in a chat after `after`: an inbound message of a person, recorded as it
323
+ * arrived and not imported, after that place in the chat, that the turn `turnId` did not take.
324
+ * With `userId`, only that member's messages count, as in a group several people write in.
325
+ */
326
+ readonly wroteAfter: (input: {
327
+ readonly channel: string;
328
+ readonly chatId: string;
329
+ readonly after: ChatCursor;
330
+ readonly turnId?: string;
331
+ readonly userId?: string;
332
+ }) => Effect.Effect<boolean>;
301
333
  /** The send an `operation` keys, its tombstone included; `undefined` when the key has none. */
302
334
  readonly findSend: (operation: string) => Effect.Effect<ChatSend | undefined>;
303
335
  /** Messages as a reader may read them, row by row: only what reached the provider. */
@@ -195,10 +195,11 @@ export function sqlChatMessageStore(sql) {
195
195
  * messages take their revisions in the order they commit: a reader whose bookmark passed a
196
196
  * revision never misses a lower one committed after it.
197
197
  */
198
- const inChat = (channel, chatId, write) => sql
199
- .withTransaction(rows(`SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, [
198
+ const lockChat = ({ channel, chatId }) => rows(`SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, [
200
199
  JSON.stringify([CHAT_MESSAGES_TABLE, channel, chatId]),
201
- ]).pipe(Effect.andThen(write)))
200
+ ]).pipe(Effect.asVoid);
201
+ const inChat = (channel, chatId, write) => sql
202
+ .withTransaction(lockChat({ channel, chatId }).pipe(Effect.andThen(write)))
202
203
  .pipe(Effect.catchTag("SqlError", Effect.die));
203
204
  const insert = (input) => Effect.gen(function* () {
204
205
  const params = parameters();
@@ -620,6 +621,29 @@ export function sqlChatMessageStore(sql) {
620
621
  const holds = (chat) => rows(chat === undefined
621
622
  ? `SELECT EXISTS (SELECT 1 FROM ${TABLE}) AS "holds"`
622
623
  : `SELECT EXISTS (SELECT 1 FROM ${TABLE} WHERE "channel" = $1 AND "chat_id" = $2) AS "holds"`, chat === undefined ? [] : [chat.channel, chat.chatId]).pipe(Effect.map(([row]) => row?.holds === true || row?.holds === "t"));
624
+ const turnBasis = (input) => rows(`SELECT "id"::text AS "id", ${epochMs(`"at"`)} AS "at" FROM ${TABLE} ` +
625
+ `WHERE "channel" = $1 AND "chat_id" = $2 AND "turn_id" = $3 AND "direction" = 'inbound' ` +
626
+ `AND "purged_at" IS NULL ORDER BY "at" DESC, "id" DESC LIMIT 1`, [input.channel, input.chatId, input.turnId]).pipe(Effect.map(([row]) => row === undefined ? undefined : { at: instant(row.at), id: String(row.id) }));
627
+ const wroteAfter = (input) => {
628
+ const params = parameters();
629
+ const at = params.add(input.after.at, "timestamptz");
630
+ const conditions = [
631
+ `"channel" = ${params.add(input.channel)}`,
632
+ `"chat_id" = ${params.add(input.chatId)}`,
633
+ `"direction" = 'inbound'`,
634
+ `"author" = 'human'`,
635
+ `"imported_at" IS NULL`,
636
+ `"purged_at" IS NULL`,
637
+ input.after.id === undefined
638
+ ? `"at" > ${at}`
639
+ : `("at" > ${at} OR ("at" = ${at} AND "id" > ${params.add(input.after.id, "uuid")}))`,
640
+ ...(input.turnId === undefined
641
+ ? []
642
+ : [`"turn_id" IS DISTINCT FROM ${params.add(input.turnId)}`]),
643
+ ...(input.userId === undefined ? [] : [`"user_id" = ${params.add(input.userId, "uuid")}`]),
644
+ ];
645
+ return rows(`SELECT EXISTS (SELECT 1 FROM ${TABLE} WHERE ${conditions.join(" AND ")}) AS "wrote"`, params.values).pipe(Effect.map(([row]) => row?.wrote === true || row?.wrote === "t"));
646
+ };
623
647
  const findSend = (operation) => rows(`SELECT "id"::text AS "id", "channel", "chat_id", "status", "message_id", "failure", ` +
624
648
  `"fingerprint", "meta"::text AS "meta", ${epochMs(`"at"`)} AS "at", ` +
625
649
  `"purged_at" IS NOT NULL AS "purged" FROM ${TABLE} WHERE "operation" = $1 LIMIT 1`, [operation]).pipe(Effect.map(([row]) => row === undefined
@@ -670,5 +694,16 @@ export function sqlChatMessageStore(sql) {
670
694
  }
671
695
  return { deleted, scrubbed, more };
672
696
  });
673
- return { record, change, read, holds, findSend, search, purge };
697
+ return {
698
+ record,
699
+ change,
700
+ read,
701
+ holds,
702
+ lockChat,
703
+ turnBasis,
704
+ wroteAfter,
705
+ findSend,
706
+ search,
707
+ purge,
708
+ };
674
709
  }
@@ -138,10 +138,6 @@ export declare const ChatHandoffRequest: Schema.Struct<{
138
138
  readonly memberId: Schema.String;
139
139
  readonly reason: Schema.String;
140
140
  }>;
141
- /**
142
- * `POST /api/ontology/agent/drafts`: a reply the agent kept for a member to review, for the member
143
- * it answers. `key` names the reply, so a report repeated after a failure finds its draft.
144
- */
145
141
  export declare const ReviewRequest: Schema.Struct<{
146
142
  readonly key: Schema.String;
147
143
  readonly provider: Schema.String;
@@ -155,11 +151,31 @@ export declare const ReviewRequest: Schema.Struct<{
155
151
  readonly reply_to: Schema.NullOr<Schema.String>;
156
152
  readonly member_id: Schema.String;
157
153
  readonly session_id: Schema.String;
158
- readonly text: Schema.String;
154
+ readonly text: Schema.optionalKey<Schema.String>;
155
+ readonly files: Schema.optionalKey<Schema.$Array<Schema.Struct<{
156
+ readonly entity: Schema.String;
157
+ readonly id: Schema.String;
158
+ readonly property: Schema.optionalKey<Schema.String>;
159
+ }>>>;
159
160
  readonly mode: Schema.Literals<readonly ["always", "whenUnsure"]>;
160
161
  readonly confidence: Schema.NullOr<Schema.Number>;
162
+ readonly turn_id: Schema.optionalKey<Schema.String>;
161
163
  }>;
162
164
  export type ReviewRequest = typeof ReviewRequest.Type;
165
+ /**
166
+ * `POST /api/ontology/agent/drafts/files`: whether a reply on a channel may carry these files, read
167
+ * as the member it is for, checked as holding it would check them, without holding anything.
168
+ */
169
+ export declare const DraftFilesRequest: Schema.Struct<{
170
+ readonly provider: Schema.String;
171
+ readonly channel: Schema.optionalKey<Schema.String>;
172
+ readonly member_id: Schema.String;
173
+ readonly files: Schema.$Array<Schema.Struct<{
174
+ readonly entity: Schema.String;
175
+ readonly id: Schema.String;
176
+ readonly property: Schema.optionalKey<Schema.String>;
177
+ }>>;
178
+ }>;
163
179
  /**
164
180
  * `POST /api/ontology/agent/drafts/revision`: what became of a redraft a member asked for: the new
165
181
  * draft, or, without `text`, that the agent could not write one.
@@ -1,6 +1,6 @@
1
1
  import { randomInt } from "node:crypto";
2
2
  import { Schema } from "effect";
3
- import { AGENT_DRAFT_PARTICIPANTS_LIMIT } from "../../agent-draft.js";
3
+ import { AGENT_DRAFT_FILES_LIMIT, AGENT_DRAFT_PARTICIPANTS_LIMIT } from "../../agent-draft.js";
4
4
  import { ChatChannelName } from "../../chat-channel.js";
5
5
  import { EMAIL_RECIPIENTS_LIMIT } from "../../email.js";
6
6
  import { EMAIL_PATTERN } from "../../property.js";
@@ -186,6 +186,12 @@ export const ChatHandoffRequest = Schema.Struct({
186
186
  * `POST /api/ontology/agent/drafts`: a reply the agent kept for a member to review, for the member
187
187
  * it answers. `key` names the reply, so a report repeated after a failure finds its draft.
188
188
  */
189
+ /** A record file a held reply carries, by its entity, record and file property. */
190
+ const HeldFile = Schema.Struct({
191
+ entity: Schema.String.check(Schema.isPattern(/^[a-z][a-z0-9_]{0,63}$/)),
192
+ id: Schema.String.check(Schema.isUUID()),
193
+ property: Schema.optionalKey(Schema.String.check(Schema.isPattern(/^[a-z][a-z0-9_]{0,63}$/))),
194
+ });
189
195
  export const ReviewRequest = Schema.Struct({
190
196
  key: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512)).annotate({
191
197
  description: "The agent's key for the reply: its session and content part.",
@@ -223,15 +229,34 @@ export const ReviewRequest = Schema.Struct({
223
229
  session_id: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512)).annotate({
224
230
  description: "The agent's session that wrote the reply.",
225
231
  }),
226
- text: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(20_000)).annotate({
227
- description: "The reply as the agent wrote it, in Markdown.",
232
+ text: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(20_000))).annotate({
233
+ description: "The reply as the agent wrote it, in Markdown; empty or absent only for a reply of files.",
228
234
  }),
235
+ files: Schema.optionalKey(Schema.Array(HeldFile)
236
+ .check(Schema.isMinLength(1), Schema.isMaxLength(AGENT_DRAFT_FILES_LIMIT))
237
+ .annotate({
238
+ description: "Record files the reply carries, in order, which the person may read: approval sends " +
239
+ "the revision each holds now.",
240
+ })),
229
241
  mode: Schema.Literals(["always", "whenUnsure"]).annotate({
230
242
  description: "Why the reply was held: every reply is reviewed, or the model was unsure.",
231
243
  }),
232
244
  confidence: Schema.NullOr(Schema.Number.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(1))).annotate({
233
245
  description: "The decision model's probability that staff would send it as written.",
234
246
  }),
247
+ turn_id: Schema.optionalKey(Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)).annotate({
248
+ description: "The agent's turn that wrote the reply.",
249
+ })),
250
+ });
251
+ /**
252
+ * `POST /api/ontology/agent/drafts/files`: whether a reply on a channel may carry these files, read
253
+ * as the member it is for, checked as holding it would check them, without holding anything.
254
+ */
255
+ export const DraftFilesRequest = Schema.Struct({
256
+ provider: Provider,
257
+ channel: Schema.optionalKey(ChatChannelName),
258
+ member_id: Schema.String,
259
+ files: Schema.Array(HeldFile).check(Schema.isMinLength(1), Schema.isMaxLength(AGENT_DRAFT_FILES_LIMIT)),
235
260
  });
236
261
  /**
237
262
  * `POST /api/ontology/agent/drafts/revision`: what became of a redraft a member asked for: the new
@@ -8,6 +8,7 @@ import { type RuntimeTokenVerifier } from "../runtime-identity.js";
8
8
  import { type AgentToolsOf } from "./protocol.js";
9
9
  import { type VisitorWebsites } from "./web-tokens.js";
10
10
  import type { BotCheckVerifier } from "./bot-check.js";
11
+ import { type OntologyManifest } from "../../manifest.js";
11
12
  import { GUEST_LINK_PATH, type EmailCodes } from "./guest-sign-up.js";
12
13
  import type { ResolvedGuest } from "../../sign-in.js";
13
14
  /** The agent's endpoints, under the ontology service's path. */
@@ -52,6 +53,8 @@ export interface AgentServerOptions {
52
53
  readonly cronSecret?: Redacted.Redacted<string> | undefined;
53
54
  /** How many days the chats' messages are kept, as the ontology declares it. */
54
55
  readonly chatRetentionDays?: number;
56
+ /** The ontology, whose record files a held reply carries and whose channels send them. */
57
+ readonly manifest?: OntologyManifest;
55
58
  }
56
59
  /**
57
60
  * The routes that pair channel accounts with members for the app's own agent, and record the group
@@ -13,10 +13,11 @@ import { secretHash } from "../oauth/protocol.js";
13
13
  import { clientAddress, fixedWindowLimiter, } from "../rate-limit.js";
14
14
  import { OntologyBackend } from "../runtime-contract.js";
15
15
  import { AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
16
- import { ChatHandoffRequest, ChatSeenRequest, ReviewRequest, RevisionRequest, SessionReviewsRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
16
+ import { ChatHandoffRequest, ChatSeenRequest, DraftFilesRequest, ReviewRequest, RevisionRequest, SessionReviewsRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
17
17
  import { AGENT_TOKEN_LIMIT, BOT_CHECK_LIMIT, introspectAgentToken, issueAgentToken, issueVisitorToken, visitorPreflight, } from "./web-tokens.js";
18
18
  import { CHAT_MESSAGE_PATHS, changeChatMessage, purgeChatMessages, readChatMessages, recordChatMessage, } from "./chat-message-routes.js";
19
19
  import { CHAT_RETENTION_DAYS } from "../../manifest.js";
20
+ import { snapshotDraftFiles } from "../chat/draft-files.js";
20
21
  import { GUEST_LINK_PATH, guestRoutesPreflight, guestSignUpRoutes, recordGuestUsage, } from "./guest-sign-up.js";
21
22
  import { identityToken } from "../operations.js";
22
23
  /** The agent's endpoints, under the ontology service's path. */
@@ -353,7 +354,7 @@ function seeChat(store) {
353
354
  * pending `agent_draft` for the member it answers, once per key; 404 when that member is not an
354
355
  * active member, so the reply is neither sent nor kept.
355
356
  */
356
- function holdReply(store) {
357
+ function holdReply(store, backend, manifest) {
357
358
  return (request) => Effect.gen(function* () {
358
359
  const requestId = yield* RequestId;
359
360
  const decoded = Schema.decodeUnknownResult(ReviewRequest)(yield* jsonBody(request), {
@@ -387,6 +388,51 @@ function holdReply(store) {
387
388
  { path: [body.to === undefined ? "cc" : "to"], message: "Only a reply to mail has it." },
388
389
  ]);
389
390
  }
391
+ const text = body.text ?? "";
392
+ // A reply is its text, its files, or both.
393
+ if (text.trim() === "" && body.files === undefined) {
394
+ return invalidBody(requestId, [
395
+ { path: ["text"], message: "A reply without files has text." },
396
+ ]);
397
+ }
398
+ const channel = body.channel ?? body.provider;
399
+ let files;
400
+ // A report repeated after a lost answer finds the draft its key holds, whatever became of
401
+ // its files since: only a new draft reads them.
402
+ const [existing] = body.files === undefined
403
+ ? []
404
+ : (yield* backend
405
+ .find({ entity: "agent_draft", query: { where: { key: body.key }, limit: 1 } })
406
+ .pipe(Effect.orDie)).items;
407
+ if (existing !== undefined) {
408
+ return json({ id: String(existing.id), status: String(existing.status), created: false });
409
+ }
410
+ // Each file as the person may read it now, and as the channel sends it.
411
+ if (body.files !== undefined) {
412
+ const member = yield* store.member(body.member_id);
413
+ if (member === undefined) {
414
+ return toServerResponse(notFound(requestId, "The reply is for no active member."));
415
+ }
416
+ if (manifest === undefined) {
417
+ return HttpServerResponse.jsonUnsafe({ error: "files_unsupported", request_id: requestId }, { status: 422, headers: NO_STORE });
418
+ }
419
+ const snapshot = yield* snapshotDraftFiles({
420
+ manifest,
421
+ backend,
422
+ principal: member.principal,
423
+ channel,
424
+ files: body.files,
425
+ });
426
+ if ("refusal" in snapshot) {
427
+ yield* Effect.logInfo("ontology.agent.reply_files_refused").pipe(Effect.annotateLogs({ requestId, channel, refusal: snapshot.refusal }));
428
+ return HttpServerResponse.jsonUnsafe({
429
+ error: snapshot.refusal,
430
+ ...(snapshot.index === undefined ? {} : { index: snapshot.index }),
431
+ request_id: requestId,
432
+ }, { status: 422, headers: NO_STORE });
433
+ }
434
+ files = snapshot.files;
435
+ }
390
436
  const review = yield* store.holdReply({
391
437
  key: body.key,
392
438
  provider: body.provider,
@@ -402,9 +448,11 @@ function holdReply(store) {
402
448
  replyTo: body.reply_to,
403
449
  memberId: body.member_id,
404
450
  sessionId: body.session_id,
405
- text: body.text,
451
+ text,
452
+ ...(files === undefined ? {} : { files }),
406
453
  mode: body.mode,
407
454
  confidence: body.confidence,
455
+ ...(body.turn_id === undefined ? {} : { turnId: body.turn_id }),
408
456
  });
409
457
  if (review === undefined) {
410
458
  return toServerResponse(notFound(requestId, "The reply is for no active member."));
@@ -420,6 +468,57 @@ function holdReply(store) {
420
468
  return json({ id: review.id, status: review.status, created: review.created });
421
469
  });
422
470
  }
471
+ /**
472
+ * `POST /api/ontology/agent/drafts/files` (runtime): the files a reply would carry, read as the
473
+ * member it is for and checked against its channel as holding the reply checks them, without
474
+ * holding anything: the agent asks before it promises a file in a reviewed chat. An ontology
475
+ * without draft files answers 404, which the agent takes as no files in reviewed chats.
476
+ */
477
+ function checkDraftFiles(store, backend, manifest) {
478
+ return (request) => Effect.gen(function* () {
479
+ const requestId = yield* RequestId;
480
+ const decoded = Schema.decodeUnknownResult(DraftFilesRequest)(yield* jsonBody(request), {
481
+ errors: "all",
482
+ onExcessProperty: "error",
483
+ });
484
+ if (Result.isFailure(decoded)) {
485
+ return invalidBody(requestId, schemaIssues(decoded.failure));
486
+ }
487
+ const body = decoded.success;
488
+ const member = yield* store.member(body.member_id);
489
+ if (member === undefined) {
490
+ return toServerResponse(notFound(requestId, "The reply is for no active member."));
491
+ }
492
+ const snapshot = manifest === undefined
493
+ ? { refusal: "files_unsupported" }
494
+ : yield* snapshotDraftFiles({
495
+ manifest,
496
+ backend,
497
+ principal: member.principal,
498
+ channel: body.channel ?? body.provider,
499
+ files: body.files,
500
+ });
501
+ return "refusal" in snapshot
502
+ ? HttpServerResponse.jsonUnsafe({
503
+ error: snapshot.refusal,
504
+ ...("index" in snapshot && snapshot.index !== undefined
505
+ ? { index: snapshot.index }
506
+ : {}),
507
+ request_id: requestId,
508
+ }, { status: 422, headers: NO_STORE })
509
+ : HttpServerResponse.jsonUnsafe({
510
+ files: snapshot.files.map((file) => ({
511
+ entity: file.entity,
512
+ id: file.id,
513
+ property: file.property,
514
+ revision_id: file.revisionId,
515
+ filename: file.filename,
516
+ content_type: file.contentType,
517
+ size: file.size,
518
+ })),
519
+ }, { headers: NO_STORE });
520
+ });
521
+ }
423
522
  /**
424
523
  * `POST /api/ontology/agent/drafts/revision` (runtime): the agent redrafted a reply a member sent
425
524
  * back, or could not. The new draft becomes a pending draft for the same person and chat that
@@ -623,10 +722,11 @@ export function agentLayer(options) {
623
722
  yield* router.add("POST", `${AGENT_PATH}${CHAT_MESSAGE_PATHS.purge}`, purge);
624
723
  }
625
724
  for (const path of [DRAFTS_PATH, REVIEWS_PATH]) {
626
- yield* router.add("POST", path, asRuntime(holdReply(store)));
725
+ yield* router.add("POST", path, asRuntime(holdReply(store, backend, options.manifest)));
627
726
  yield* router.add("POST", `${path}/session`, asRuntime(sessionReviews(store)));
628
727
  yield* router.add("POST", `${path}/revision`, asRuntime(revision(store)));
629
728
  }
729
+ yield* router.add("POST", `${DRAFTS_PATH}/files`, asRuntime(checkDraftFiles(store, backend, options.manifest)));
630
730
  yield* router.add("DELETE", `${IDENTITIES_PATH}/:id`, asMember((_, member) => revokeIdentity(store, member)));
631
731
  if (store.web !== undefined && backend.oauth !== undefined) {
632
732
  yield* router.add("POST", AGENT_TOKENS_PATH, asMember(issueAgentToken(store, store.web, fixedWindowLimiter(AGENT_TOKEN_LIMIT))));
@@ -1,6 +1,14 @@
1
1
  import { Effect, Schema } from "effect";
2
2
  import type { OntologyEnvironment } from "../config.js";
3
3
  import type { ChatRequester } from "./attribution.js";
4
+ /** A file of a delivered message, as the chat's history shows it: its name, type and size. */
5
+ export interface DeliveryAttachment {
6
+ readonly id: string;
7
+ readonly kind: "file";
8
+ readonly filename: string;
9
+ readonly contentType: string;
10
+ readonly size: number;
11
+ }
4
12
  export interface DeliveryEvent {
5
13
  readonly eventId: string;
6
14
  readonly operationId: string;
@@ -27,7 +35,13 @@ export interface DeliveryEvent {
27
35
  readonly toolName: null;
28
36
  readonly argsSummary: string | null;
29
37
  readonly status: "requested" | "sent" | "uncertain" | "failed";
30
- readonly attachments: readonly [];
38
+ /** The files the message carries, as its history shows them: none but an approved draft's. */
39
+ readonly attachments: ReadonlyArray<DeliveryAttachment>;
40
+ /**
41
+ * The record files the message carries, each `[entity, id, property, revisionId]` in order,
42
+ * which bind the delivery: absent for a message of text alone, so its binding stays.
43
+ */
44
+ readonly files?: ReadonlyArray<readonly [string, string, string, string]>;
31
45
  readonly requestedBy: ChatRequester;
32
46
  readonly url: string | null;
33
47
  readonly at: string;
@@ -486,6 +486,9 @@ chats) {
486
486
  principal: context.principal,
487
487
  requestId: context.requestId,
488
488
  }),
489
+ ...(context.backend.agents?.draftsNewer === undefined
490
+ ? {}
491
+ : { draftsNewer: draftsNewer(context, context.backend.agents.draftsNewer) }),
489
492
  sendReview: reviewSender({
490
493
  ontology,
491
494
  connections,
@@ -691,3 +694,27 @@ chats) {
691
694
  }
692
695
  };
693
696
  }
697
+ /**
698
+ * Whether the person wrote after each draft's turn, for the drafts the caller reads: one outside the
699
+ * records a scoped `agent_draft:read` covers answers `null`, as one that does not exist does.
700
+ */
701
+ function draftsNewer(context, newer) {
702
+ return (drafts) => Effect.gen(function* () {
703
+ const scope = effectiveScope("agent_draft:read", context.principal);
704
+ const readable = scope === undefined
705
+ ? drafts
706
+ : yield* Effect.filter(drafts, (id) => context.backend
707
+ .get({
708
+ entity: "agent_draft",
709
+ id,
710
+ reader: {
711
+ ...context.principal,
712
+ permissions: ["agent_draft:read"],
713
+ scopes: [{ permission: "agent_draft:read", where: scope }],
714
+ },
715
+ })
716
+ .pipe(Effect.as(true), Effect.catch(() => Effect.succeed(false))));
717
+ const answered = new Map((yield* newer(readable)).map((entry) => [entry.draft, entry.newer]));
718
+ return drafts.map((draft) => ({ draft, newer: answered.get(draft) ?? null }));
719
+ });
720
+ }