@segmentstream/ontology 0.155.0 → 0.156.1

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 CHANGED
@@ -1,5 +1,41 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.156.1
4
+
5
+ Every reader of a chat in the workspace's chat store now reads only what reached the provider:
6
+ people's messages and the sends the provider took (`sent`, `delivered`, `read`, and one it took
7
+ and later failed, as `failed`). A person reading their own private chat, the agent in their
8
+ session, a group's members and readers with `agent_chat:read` no longer see a staff send still
9
+ `pending` or `uncertain`, a send refused before the provider took it, or the agent's internal
10
+ notes, such as the questions it could not answer, through `chat_history`, `chat_search` or
11
+ `POST /api/ontology/chat/history`, in one chat or across chats. Staff reading a chat the inbox
12
+ registered, and workflows, already read it so. A send appears once the provider takes it, under a
13
+ new revision, so a page polling with `after` receives it then. The agent's logs and figures are
14
+ unchanged.
15
+
16
+ ## 0.156.0
17
+
18
+ Staff sends live in the workspace chat store. Once `_chat_messages` holds a message, which means the
19
+ agent records its chats there, `agent_chat.postMessage`, `agent_chat.send` and the delivery of an
20
+ approved `agent_review` reserve their idempotency key on the message's own row, `pending` before the
21
+ provider is called, and record its receipt on the same row: `sent` with the provider's message id,
22
+ `uncertain` or `failed` with the refusal. Nothing is written to the chat archive in Cloud, so the
23
+ chat's history, the inbox and the agent's next session read the message at once, rather than after
24
+ the daily copy of the archive. The delivery works as before: a replay of the key with the same
25
+ request sends nothing and answers the recorded receipt, the same key with another request is
26
+ refused, a lost receipt leaves the delivery `uncertain` and never sends it again, and retention
27
+ keeps a send's key and outcome. A member's own reply in the inbox is a person's message (`human`),
28
+ with the member as its sender; anything sent as the agent is the agent's. A provider's echo of the
29
+ message recorded before its receipt leaves one message, the send's. A reservation whose receipt was
30
+ lost is never listed among a channel's sends still to deliver (`messages/read` with `pending`), so
31
+ it never takes the place of a reply the email channel still has to send. Until the store holds a
32
+ message, deliveries reserve in Cloud's archive as before.
33
+
34
+ `chat_search` without a chat searches every chat in the workspace chat store once it holds a
35
+ message, so it finds the agent's messages and staff sends, which live only there, with each row read
36
+ as `chat_history` reads it: a group's messages for its members and every group for `agent_chat:read`,
37
+ a private chat's for the people it names, and the chats the ontology checked for a service.
38
+
3
39
  ## 0.155.0
4
40
 
5
41
  An email thread can be one chat. `"chats": "thread"` on an email channel makes each Gmail thread one chat and one session of the agent, whoever writes in it; `"sender"`, the default, keeps each person's own chat in a thread, as before. Admission stays the sender's: each turn acts as the person who wrote. Each message, and the reply to it, is read by the members it went to, its sender and the members among its `To` and `Cc`, so a person dropped from `Cc` reads none of the thread's later mail. Each admitted person joins the thread's chat in the inbox, which is named after the thread's subject; with `"record": "all"`, any mail the channel records in a thread, even mail the agent does not take from or to members, brings its chat into the inbox where `inbox.channels` lists the channel, and makes no one its member. A reply held for review in a thread's chat is read, once approved, by the same members as a reply the agent sends itself. A new thread chat reads its history from Gmail once, the thread's last 20 messages before it, as imported history. Chats a thread had per person stay, and replies waiting or held there are still sent. A thread's chat replies to all; `"reply": "sender"` is refused with it. Staff answer a thread's chat in Gmail: the inbox's `postMessage` and `send` refuse it. While staff hold a thread's chat, taken over, the agent answers no one in the thread, whatever their role.
@@ -15,6 +15,13 @@ export type ChatDirection = (typeof CHAT_DIRECTIONS)[number];
15
15
  export type ChatMessageAuthor = (typeof CHAT_MESSAGE_AUTHORS)[number];
16
16
  export type ChatMessageStatus = (typeof CHAT_MESSAGE_STATUSES)[number];
17
17
  export type ChatDisposition = (typeof CHAT_DISPOSITIONS)[number];
18
+ /**
19
+ * The start of a delivery's key, the `operation` of a staff post, a send as the agent or an
20
+ * approved review the ontology service reserves (docs/agent-chat-storage.md, "Staff sends"). No
21
+ * channel sends such a row: the service sends it once, and a reservation whose receipt was lost
22
+ * stays `pending` without ever being sent again.
23
+ */
24
+ export declare const DELIVERY_OPERATION_PREFIX = "delivery:";
18
25
  /** How long a claim on an inbound message holds: an abandoned one is taken again after it. */
19
26
  export declare const CHAT_CLAIM_MINUTES = 10;
20
27
  /** The most rows one purge batch deletes or scrubs, and the most batches one purge runs. */
@@ -152,6 +159,11 @@ export type ChatMessageChange =
152
159
  readonly status: "sent" | "failed" | "uncertain";
153
160
  readonly providerMessageId?: string;
154
161
  readonly failure?: string;
162
+ /**
163
+ * The send's channel state as it went, in place of what its request held, in the receipt's
164
+ * own write; the service's deliveries alone give it, the runtime routes never take it.
165
+ */
166
+ readonly meta?: unknown;
155
167
  }
156
168
  /** A claim given up before its message was dispatched: the message is unclaimed again. */
157
169
  | (Target & {
@@ -201,7 +213,10 @@ export interface ChatMessageQuery {
201
213
  readonly after?: string;
202
214
  readonly before?: ChatCursor;
203
215
  readonly messageId?: string;
204
- /** Outbound messages still `pending`: sends still to deliver. */
216
+ /**
217
+ * Outbound messages still `pending`: sends still to deliver. A delivery the service reserved
218
+ * (`operation` under {@link DELIVERY_OPERATION_PREFIX}) is never one of them.
219
+ */
205
220
  readonly pending?: boolean;
206
221
  /** With `pending`, only the sends requested no later than this time (ISO 8601). */
207
222
  readonly pendingBefore?: string;
@@ -209,10 +224,13 @@ export interface ChatMessageQuery {
209
224
  readonly senderId?: string;
210
225
  readonly limit: number;
211
226
  }
212
- /** A reader's search of one chat, as `chat_history` and `chat_search` ask it. */
227
+ /**
228
+ * A reader's search, as `chat_history` and `chat_search` ask it: of one chat, or, without `chatId`
229
+ * or without `channel`, of every chat they leave open, newest first.
230
+ */
213
231
  export interface ChatMessageSearch {
214
- readonly channel: string;
215
- readonly chatId: string;
232
+ readonly channel?: string;
233
+ readonly chatId?: string;
216
234
  readonly threadId?: string;
217
235
  readonly q?: string;
218
236
  readonly senderId?: string;
@@ -224,20 +242,40 @@ export interface ChatMessageSearch {
224
242
  }
225
243
  /**
226
244
  * Who reads, as the chat archive's reader rule takes it: every group message (`groups`, from
227
- * `agent_chat:read` or membership of the chat), this exact chat's messages, never its internal
228
- * rows nor sends still unsent (`chat`, a chat the ontology checked the reader may read), and the
229
- * private messages whose `participants` hold `participantId`, row by row.
245
+ * `agent_chat:read` or membership of the chat), this exact chat's messages (`chat`, a chat the
246
+ * ontology checked the reader may read), and the private messages whose `participants` hold
247
+ * `participantId`, row by row. A search of several chats names, by `<channel>:<chat id>`, the
248
+ * groups the reader is in (`groupChats`), read as `groups` reads every group, and the chats the
249
+ * ontology checked (`chats`), each read as `chat` reads the one searched. Every rule reads only
250
+ * what reached the provider: never an internal row, a send still unsent, or one that failed
251
+ * before the provider took it.
230
252
  */
231
253
  export interface ChatMessageReader {
232
254
  readonly participantId: string | null;
233
255
  readonly groups: boolean;
234
256
  readonly chat: boolean;
257
+ readonly groupChats?: ReadonlyArray<string>;
258
+ readonly chats?: ReadonlyArray<string>;
235
259
  }
236
260
  export interface ChatMessagePage {
237
261
  readonly messages: ReadonlyArray<ChatMessage>;
238
262
  /** `after` mode: the revision to read after next; otherwise the cursor of the next page. */
239
263
  readonly nextCursor: string | null;
240
264
  }
265
+ /** A send as its `operation` finds it, its tombstone included. Times are ISO 8601. */
266
+ export interface ChatSend {
267
+ readonly id: string;
268
+ readonly channel: string;
269
+ readonly chatId: string;
270
+ readonly status: ChatMessageStatus | null;
271
+ readonly messageId: string | null;
272
+ readonly failure: string | null;
273
+ readonly fingerprint: string | null;
274
+ readonly meta: unknown;
275
+ readonly at: string;
276
+ /** Retention scrubbed it to its tombstone: its key, fingerprint and outcome stay. */
277
+ readonly purged: boolean;
278
+ }
241
279
  declare const ChatMessageConflict_base: Schema.Class<ChatMessageConflict, Schema.TaggedStruct<"ChatMessageConflict", {
242
280
  readonly code: Schema.Literals<readonly ["operation_conflict", "message_conflict"]>;
243
281
  }>, import("effect/Cause").YieldableError>;
@@ -260,7 +298,9 @@ export interface ChatMessageStore {
260
298
  readonly channel: string;
261
299
  readonly chatId: string;
262
300
  }) => Effect.Effect<boolean>;
263
- /** One chat's messages as a reader may read them, row by row. */
301
+ /** The send an `operation` keys, its tombstone included; `undefined` when the key has none. */
302
+ readonly findSend: (operation: string) => Effect.Effect<ChatSend | undefined>;
303
+ /** Messages as a reader may read them, row by row: only what reached the provider. */
264
304
  readonly search: (search: ChatMessageSearch, reader: ChatMessageReader) => Effect.Effect<ChatMessagePage>;
265
305
  /**
266
306
  * Deletes the messages older than `retentionDays`, in bounded batches, and scrubs a send's row to
@@ -19,6 +19,13 @@ export const CHAT_MESSAGE_STATUSES = [
19
19
  "uncertain",
20
20
  ];
21
21
  export const CHAT_DISPOSITIONS = ["claimed", "turn", "skipped"];
22
+ /**
23
+ * The start of a delivery's key, the `operation` of a staff post, a send as the agent or an
24
+ * approved review the ontology service reserves (docs/agent-chat-storage.md, "Staff sends"). No
25
+ * channel sends such a row: the service sends it once, and a reservation whose receipt was lost
26
+ * stays `pending` without ever being sent again.
27
+ */
28
+ export const DELIVERY_OPERATION_PREFIX = "delivery:";
22
29
  /** How long a claim on an inbound message holds: an abandoned one is taken again after it. */
23
30
  export const CHAT_CLAIM_MINUTES = 10;
24
31
  /** The most rows one purge batch deletes or scrubs, and the most batches one purge runs. */
@@ -335,7 +342,7 @@ export function sqlChatMessageStore(sql) {
335
342
  `"deleted_at" = coalesce($6::timestamptz, "deleted_at"), ` +
336
343
  `"parts" = CASE WHEN ${deleted} THEN '[]' ELSE "parts" END, ` +
337
344
  `"files" = CASE WHEN ${deleted} THEN '[]' ELSE "files" END, ` +
338
- `"meta" = CASE WHEN ${deleted} THEN NULL ELSE "meta" END, ` +
345
+ `"meta" = CASE WHEN ${deleted} THEN NULL ELSE coalesce($9::jsonb, "meta") END, ` +
339
346
  `"reactions" = CASE WHEN ${deleted} THEN '[]' ` +
340
347
  `WHEN coalesce($8::jsonb, '[]') <> '[]' THEN $8::jsonb ELSE "reactions" END, ` +
341
348
  `${revised} WHERE "id" = $1::uuid`, [
@@ -347,6 +354,7 @@ export function sqlChatMessageStore(sql) {
347
354
  echo?.deleted_at ?? null,
348
355
  echo?.text ?? null,
349
356
  echo?.reactions ?? null,
357
+ change.meta === undefined ? null : JSON.stringify(change.meta),
350
358
  ]);
351
359
  return { applied: true };
352
360
  }));
@@ -535,7 +543,10 @@ export function sqlChatMessageStore(sql) {
535
543
  conditions.push(`"message_id" = ${params.add(input.messageId)}`);
536
544
  }
537
545
  if (input.pending === true) {
538
- conditions.push(`"direction" = 'outbound'`, `"status" = 'pending'`);
546
+ conditions.push(`"direction" = 'outbound'`, `"status" = 'pending'`,
547
+ // A delivery the service reserved is never a channel's to send: one whose receipt was
548
+ // lost stays pending, and must not take the place of a send still due.
549
+ `("operation" IS NULL OR "operation" NOT LIKE ${params.add(`${DELIVERY_OPERATION_PREFIX}%`)})`);
539
550
  // Before the limit, so newer sends never fill a page ahead of older ones due.
540
551
  if (input.pendingBefore !== undefined) {
541
552
  conditions.push(`"at" <= ${params.add(input.pendingBefore, "timestamptz")}`);
@@ -548,9 +559,11 @@ export function sqlChatMessageStore(sql) {
548
559
  };
549
560
  const search = (input, reader) => {
550
561
  const params = parameters();
562
+ // Only the filters the search names, never `$1 IS NULL OR …`, which no plan turns into an
563
+ // index condition: one chat is read along its own index, several along the time's.
551
564
  const conditions = [
552
- `"channel" = ${params.add(input.channel)}`,
553
- `"chat_id" = ${params.add(input.chatId)}`,
565
+ ...(input.channel === undefined ? [] : [`"channel" = ${params.add(input.channel)}`]),
566
+ ...(input.chatId === undefined ? [] : [`"chat_id" = ${params.add(input.chatId)}`]),
554
567
  `"purged_at" IS NULL`,
555
568
  ];
556
569
  if (input.threadId !== undefined) {
@@ -570,19 +583,19 @@ export function sqlChatMessageStore(sql) {
570
583
  if (input.q !== undefined && input.q.trim() !== "") {
571
584
  conditions.push(`to_tsvector('simple', coalesce("text", '')) @@ plainto_tsquery('simple', ${params.add(input.q, "text")})`);
572
585
  }
586
+ // A row's chat as the reader's lists name it.
587
+ const chatKey = `("channel" || ':' || "chat_id")`;
588
+ const groupChats = reader.groupChats ?? [];
589
+ const chats = reader.chats ?? [];
573
590
  // The archive's reader rule, row by row: a private message by its own participants.
574
591
  const rules = [
575
592
  ...(reader.groups ? [`"chat_type" <> 'private'`] : []),
576
- // An exact chat reads what reached the provider: never a send still unsent, nor one that
577
- // failed before the provider took it. One it took and later failed stays, `failed`, so a
578
- // reader polling after a revision sees the same chat as one reading it whole.
579
- ...(reader.chat
580
- ? [
581
- `("direction" = 'inbound' OR ("direction" = 'outbound' AND ` +
582
- `("status" IS NULL OR "status" IN ('sent', 'delivered', 'read') OR ` +
583
- `("status" = 'failed' AND "message_id" IS NOT NULL))))`,
584
- ]
585
- : []),
593
+ ...(groupChats.length === 0
594
+ ? []
595
+ : [`("chat_type" <> 'private' AND ${chatKey} = ANY(${params.add(groupChats, "text[]")}))`]),
596
+ // The chat searched, which the ontology checked: every message of it.
597
+ ...(reader.chat ? ["TRUE"] : []),
598
+ ...(chats.length === 0 ? [] : [`${chatKey} = ANY(${params.add(chats, "text[]")})`]),
586
599
  ...(reader.participantId === null
587
600
  ? []
588
601
  : [
@@ -594,11 +607,35 @@ export function sqlChatMessageStore(sql) {
594
607
  return Effect.succeed({ messages: [], nextCursor: null });
595
608
  }
596
609
  conditions.push(`(${rules.join(" OR ")})`);
610
+ // Every rule reads what reached the provider: never an internal row, a send still unsent, nor
611
+ // one that failed before the provider took it; a send becomes readable under the revision its
612
+ // receipt takes. One the provider took and later failed stays, `failed`, and an echo a send
613
+ // took over stays a change, so a reader polling after a revision sees the same chat as one
614
+ // reading it whole.
615
+ conditions.push(`("direction" = 'inbound' OR "replaced_by" IS NOT NULL OR ("direction" = 'outbound' AND ` +
616
+ `("status" IS NULL OR "status" IN ('sent', 'delivered', 'read') OR ` +
617
+ `("status" = 'failed' AND "message_id" IS NOT NULL))))`);
597
618
  return page(conditions, params, input);
598
619
  };
599
620
  const holds = (chat) => rows(chat === undefined
600
621
  ? `SELECT EXISTS (SELECT 1 FROM ${TABLE}) AS "holds"`
601
622
  : `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"));
623
+ const findSend = (operation) => rows(`SELECT "id"::text AS "id", "channel", "chat_id", "status", "message_id", "failure", ` +
624
+ `"fingerprint", "meta"::text AS "meta", ${epochMs(`"at"`)} AS "at", ` +
625
+ `"purged_at" IS NOT NULL AS "purged" FROM ${TABLE} WHERE "operation" = $1 LIMIT 1`, [operation]).pipe(Effect.map(([row]) => row === undefined
626
+ ? undefined
627
+ : {
628
+ id: String(row.id),
629
+ channel: String(row.channel),
630
+ chatId: String(row.chat_id),
631
+ status: (row.status ?? null),
632
+ messageId: text(row.message_id),
633
+ failure: text(row.failure),
634
+ fingerprint: text(row.fingerprint),
635
+ meta: row.meta === null || row.meta === undefined ? null : json(row.meta),
636
+ at: instant(row.at),
637
+ purged: row.purged === true || row.purged === "t",
638
+ }));
602
639
  const purge = ({ retentionDays }) => Effect.gen(function* () {
603
640
  let deleted = 0;
604
641
  let scrubbed = 0;
@@ -633,5 +670,5 @@ export function sqlChatMessageStore(sql) {
633
670
  }
634
671
  return { deleted, scrubbed, more };
635
672
  });
636
- return { record, change, read, holds, search, purge };
673
+ return { record, change, read, holds, findSend, search, purge };
637
674
  }
@@ -67,6 +67,12 @@ export type DeliveryFinder = (input: {
67
67
  readonly delivery: Pick<DeliveryCommand, "scope" | "key" | "fingerprint">;
68
68
  readonly identityToken: string | undefined;
69
69
  }) => Effect.Effect<DeliveryReceipt | undefined, DeliveryArchiveError>;
70
+ /**
71
+ * Where an exact delivery reserves its key before the provider is called, and records its receipt
72
+ * after: the workspace chat store once it holds a message (`storeDeliveryArchive`), the chat
73
+ * archive in Cloud before it (`platformDeliveryArchive`). Only a `claimed` reservation grants one
74
+ * provider attempt.
75
+ */
70
76
  export type DeliveryArchive = ((input: {
71
77
  readonly event: DeliveryEvent;
72
78
  readonly delivery: DeliveryCommand;
@@ -75,6 +81,11 @@ export type DeliveryArchive = ((input: {
75
81
  /** Finds a key's receipt before a message that is read when it is sent, such as a template. */
76
82
  readonly find?: DeliveryFinder;
77
83
  };
78
- /** One append attempt only. A response without the v1 claim protocol cannot authorize a send. */
84
+ /**
85
+ * The chat archive in Cloud, which reserves and receipts a delivery while the workspace chat store
86
+ * holds no message. One append attempt only. A response without the v1 claim protocol cannot
87
+ * authorize a send.
88
+ * @legacy agent.cloud-chat-archive
89
+ */
79
90
  export declare function platformDeliveryArchive(environment: OntologyEnvironment, fetchImpl?: typeof fetch): DeliveryArchive;
80
91
  export {};
@@ -16,7 +16,12 @@ export class DeliveryArchiveError extends Schema.TaggedError()("DeliveryArchiveE
16
16
  cause: Schema.optionalKey(Schema.Unknown),
17
17
  }) {
18
18
  }
19
- /** One append attempt only. A response without the v1 claim protocol cannot authorize a send. */
19
+ /**
20
+ * The chat archive in Cloud, which reserves and receipts a delivery while the workspace chat store
21
+ * holds no message. One append attempt only. A response without the v1 claim protocol cannot
22
+ * authorize a send.
23
+ * @legacy agent.cloud-chat-archive
24
+ */
20
25
  export function platformDeliveryArchive(environment, fetchImpl = fetch) {
21
26
  const call = (path, body, identityToken, failure, answer) => Effect.tryPromise({
22
27
  try: async (signal) => {
@@ -25,7 +25,13 @@ export type ChatDeliveryFactory = (input: {
25
25
  * private source matches a private destination on the same provider by its `peer`.
26
26
  */
27
27
  export declare function sameChat(source: NonNullable<RuntimeChatEnvelope["source"]>, target: Pick<Destination, "provider" | "external_id" | "kind">): boolean;
28
- export declare function makeChatDelivery(ontology: Ontology, connections: ConnectionTransportFactory, archive: DeliveryArchive, previews?: TelegramPreviewContext,
28
+ export declare function makeChatDelivery(ontology: Ontology, connections: ConnectionTransportFactory,
29
+ /**
30
+ * The chat archive in Cloud, where a delivery reserves its key while the workspace chat store
31
+ * holds no message; on the store after that.
32
+ * @legacy agent.cloud-chat-archive
33
+ */
34
+ cloud: DeliveryArchive, previews?: TelegramPreviewContext,
29
35
  /**
30
36
  * The app's agent at the deployment's production origin, which sends through a workspace
31
37
  * channel; `fetch` by default. Without an origin nothing goes through one.
@@ -8,6 +8,7 @@ import { effectiveScope, isAllowed } from "../../permissions.js";
8
8
  import { describeChatError } from "./diagnostics.js";
9
9
  import { deliveryRequester } from "./attribution.js";
10
10
  import { deliveryFingerprint, deliveryKeyDigest, deliveryScopeDigest } from "./idempotency.js";
11
+ import { deliveryArchiveOf } from "./store-delivery.js";
11
12
  import { channelProvider, chatConnection, chatKind, listedChatProviders, } from "./providers/index.js";
12
13
  import { chatResolver } from "./resolve.js";
13
14
  import { buttonLines } from "./providers/provider.js";
@@ -36,7 +37,13 @@ export function sameChat(source, target) {
36
37
  target.kind === "private" &&
37
38
  source.peer === target.external_id);
38
39
  }
39
- export function makeChatDelivery(ontology, connections, archive, previews = {},
40
+ export function makeChatDelivery(ontology, connections,
41
+ /**
42
+ * The chat archive in Cloud, where a delivery reserves its key while the workspace chat store
43
+ * holds no message; on the store after that.
44
+ * @legacy agent.cloud-chat-archive
45
+ */
46
+ cloud, previews = {},
40
47
  /**
41
48
  * The app's agent at the deployment's production origin, which sends through a workspace
42
49
  * channel; `fetch` by default. Without an origin nothing goes through one.
@@ -54,6 +61,7 @@ chats) {
54
61
  const takeoverChannels = takeoverChannelsOf(ontology.manifest);
55
62
  const unsignedReplies = inboxAttributionOf(ontology.manifest) === "none";
56
63
  const providers = listedChatProviders(ontology.manifest.chat);
64
+ const retentionDays = chatRetentionDaysOf(ontology.manifest);
57
65
  const destination = ontology.manifest.chat?.telegram?.connection;
58
66
  const destinationPreviews = previews.settings?.connection === destination ? previews : { ownOrigins: previews.ownOrigins };
59
67
  return (context) => {
@@ -468,7 +476,7 @@ chats) {
468
476
  identityToken: context.identityToken,
469
477
  requestId: context.requestId,
470
478
  archive: history,
471
- retentionDays: chatRetentionDaysOf(ontology.manifest),
479
+ retentionDays,
472
480
  channelKind: (name) => chatKind(ontology.manifest.chat, name),
473
481
  }),
474
482
  }),
@@ -482,7 +490,7 @@ chats) {
482
490
  ontology,
483
491
  connections,
484
492
  agent: agentTransport,
485
- archive,
493
+ cloud,
486
494
  previews: destinationPreviews,
487
495
  backend: context.backend,
488
496
  principal: context.principal,
@@ -506,6 +514,8 @@ chats) {
506
514
  clientId: requester.clientId,
507
515
  });
508
516
  const key = deliveryKeyDigest(input.idempotencyKey);
517
+ // The key's claim and receipt live on the workspace chat store once it holds a message.
518
+ const archive = yield* deliveryArchiveOf(context.backend, cloud, retentionDays);
509
519
  const unreserved = (cause) => new ActionRejected({
510
520
  cause,
511
521
  message: cause.diagnostic === "chat_archive_conflict"
@@ -64,8 +64,9 @@ export declare function chatMessageEvent(message: ChatMessage): {
64
64
  };
65
65
  /**
66
66
  * Reads a chat from the workspace's chat store, `_chat_messages`, when the store holds its
67
- * messages, as the reader the chat archive's rule admits, row by row; reads after a `revision`,
68
- * or before a cursor of the store, are the store's alone. Any other read goes to `transport`,
69
- * within the retention the ontology declares, `retentionDays`.
67
+ * messages, and a search of several chats once the store holds any message, the evidence that the
68
+ * agent records there; each as the reader the chat archive's rule admits, row by row. Reads after
69
+ * a `revision`, or before a cursor of the store, are the store's alone. Any other read goes to
70
+ * `transport`, within the retention the ontology declares, `retentionDays`.
70
71
  */
71
72
  export declare function withChatStore(transport: ChatArchiveTransport, backend: OntologyBackend["Service"], retentionDays: number | undefined): ChatArchiveTransport;
@@ -1,7 +1,7 @@
1
1
  import { Clock, Effect } from "effect";
2
2
  import { ActionRejected, PermissionDenied } from "../../errors.js";
3
3
  import { isAllowed } from "../../permissions.js";
4
- import { parseChatCursor } from "../../runtime/chat-messages.js";
4
+ import { parseChatCursor, } from "../../runtime/chat-messages.js";
5
5
  /** A cursor of the chat archive in Cloud: its sequence, negative for imported history. */
6
6
  const ARCHIVE_SEQUENCE = /^-?\d+$/;
7
7
  /** The sender the chat archive gives the agent's own messages; `author` says it now. */
@@ -90,9 +90,10 @@ function withinRetention(input, retentionDays, now) {
90
90
  }
91
91
  /**
92
92
  * Reads a chat from the workspace's chat store, `_chat_messages`, when the store holds its
93
- * messages, as the reader the chat archive's rule admits, row by row; reads after a `revision`,
94
- * or before a cursor of the store, are the store's alone. Any other read goes to `transport`,
95
- * within the retention the ontology declares, `retentionDays`.
93
+ * messages, and a search of several chats once the store holds any message, the evidence that the
94
+ * agent records there; each as the reader the chat archive's rule admits, row by row. Reads after
95
+ * a `revision`, or before a cursor of the store, are the store's alone. Any other read goes to
96
+ * `transport`, within the retention the ontology declares, `retentionDays`.
96
97
  */
97
98
  export function withChatStore(transport, backend, retentionDays) {
98
99
  return (input) => Effect.gen(function* () {
@@ -100,20 +101,22 @@ export function withChatStore(transport, backend, retentionDays) {
100
101
  const { search, after } = input;
101
102
  const archived = search.before !== undefined && ARCHIVE_SEQUENCE.test(search.before);
102
103
  const cursor = search.before === undefined || archived ? undefined : parseChatCursor(search.before);
104
+ // One chat, or with either left open a search of every chat it leaves open.
105
+ const chat = search.provider === undefined || search.chatId === undefined
106
+ ? undefined
107
+ : { channel: search.provider, chatId: search.chatId };
103
108
  if (store === undefined ||
104
- search.provider === undefined ||
105
- search.chatId === undefined ||
106
109
  !(after !== undefined ||
107
110
  cursor !== undefined ||
108
- (search.before === undefined &&
109
- (yield* store.holds({ channel: search.provider, chatId: search.chatId }))))) {
111
+ (search.before === undefined && (yield* store.holds(chat))))) {
110
112
  // @legacy agent.cloud-chat-archive A chat the store does not hold, a search of every chat
111
- // and a page of the archive's own are read from the chat archive in Cloud. A chat whose
112
- // messages the store purged reads there too, never beyond the declared retention.
113
+ // while the store holds no message, and a page of the archive's own are read from the
114
+ // chat archive in Cloud. A chat whose messages the store purged reads there too, never
115
+ // beyond the declared retention.
113
116
  return yield* transport(withinRetention(input, retentionDays, yield* Clock.currentTimeMillis));
114
117
  }
115
118
  const { principal, memberGroups, chats } = input;
116
- const key = `${search.provider}:${search.chatId}`;
119
+ const key = chat === undefined ? undefined : `${chat.channel}:${chat.chatId}`;
117
120
  // A service, such as a workflow's user, reads only the exact chats the ontology checked.
118
121
  const service = principal.kind === "service" && (chats ?? []).length > 0;
119
122
  if (principal.kind !== "member" && !service) {
@@ -125,9 +128,27 @@ export function withChatStore(transport, backend, retentionDays) {
125
128
  if ([search.from, search.to].some((time) => time !== undefined && Number.isNaN(Date.parse(time)))) {
126
129
  return yield* new ActionRejected({ message: "invalid_chat_search" });
127
130
  }
131
+ // One chat's reader is decided for the chat; several chats' row by row, by each row's chat.
132
+ const reader = key !== undefined
133
+ ? service
134
+ ? { participantId: null, groups: false, chat: (chats ?? []).includes(key) }
135
+ : {
136
+ participantId: principal.id,
137
+ groups: isAllowed("agent_chat:read", principal) || (memberGroups ?? []).includes(key),
138
+ chat: (chats ?? []).includes(key),
139
+ }
140
+ : service
141
+ ? { participantId: null, groups: false, chat: false, chats: chats ?? [] }
142
+ : {
143
+ participantId: principal.id,
144
+ groups: isAllowed("agent_chat:read", principal),
145
+ chat: false,
146
+ groupChats: memberGroups ?? [],
147
+ chats: chats ?? [],
148
+ };
128
149
  const page = yield* store.search({
129
- channel: search.provider,
130
- chatId: search.chatId,
150
+ ...(search.provider === undefined ? {} : { channel: search.provider }),
151
+ ...(search.chatId === undefined ? {} : { chatId: search.chatId }),
131
152
  ...(search.threadId === undefined ? {} : { threadId: search.threadId }),
132
153
  ...(search.q === undefined ? {} : { q: search.q }),
133
154
  ...(search.senderId === undefined ? {} : { senderId: search.senderId }),
@@ -136,13 +157,7 @@ export function withChatStore(transport, backend, retentionDays) {
136
157
  ...(after === undefined ? {} : { after }),
137
158
  ...(cursor === undefined ? {} : { before: cursor }),
138
159
  limit: search.limit ?? 50,
139
- }, service
140
- ? { participantId: null, groups: false, chat: (chats ?? []).includes(key) }
141
- : {
142
- participantId: principal.id,
143
- groups: isAllowed("agent_chat:read", principal) || (memberGroups ?? []).includes(key),
144
- chat: (chats ?? []).includes(key),
145
- });
160
+ }, reader);
146
161
  return { events: page.messages.map(chatMessageEvent), nextCursor: page.nextCursor };
147
162
  });
148
163
  }
@@ -13,17 +13,23 @@ import type { AgentChannelTransport } from "./providers/provider.js";
13
13
  * Sends a reply the agent held for review, once a member approved it: the draft or the member's
14
14
  * edit, to the person's chat through the ontology's chat connection of the channel the chat is on,
15
15
  * as the agent and without attribution. A reply to mail goes to the review's `to` and `cc`, or the
16
- * addresses the member names in their place. The archive's delivery claim, keyed by the review and
17
- * not by the member, makes it at most once: a replay of the same approval returns the delivery, and
18
- * a different approval, by another member, with another text or to other people, is refused. A
19
- * provider that refused it consumes the claim: the reply is never sent again.
16
+ * addresses the member names in their place. The delivery's claim, on the reply's row of the
17
+ * workspace chat store, keyed by the review and not by the member, makes it at most once: a replay
18
+ * of the same approval returns the delivery, and a different approval, by another member, with
19
+ * another text or to other people, is refused. A provider that refused it consumes the claim: the
20
+ * reply is never sent again.
20
21
  */
21
22
  export declare function reviewSender(input: {
22
23
  readonly ontology: Ontology;
23
24
  readonly connections: ConnectionTransportFactory;
24
25
  /** The app's agent, which sends through a workspace channel. */
25
26
  readonly agent?: AgentChannelTransport;
26
- readonly archive: DeliveryArchive;
27
+ /**
28
+ * The chat archive in Cloud, where the delivery reserves its key while the workspace chat store
29
+ * holds no message; on the store after that.
30
+ * @legacy agent.cloud-chat-archive
31
+ */
32
+ readonly cloud: DeliveryArchive;
27
33
  /** Link previews for the destination connection, as a chat post gets them. */
28
34
  readonly previews?: TelegramPreviewContext;
29
35
  readonly backend: OntologyBackend["Service"];
@@ -6,7 +6,9 @@ import { effectiveScope } from "../../permissions.js";
6
6
  import { describeChatError } from "./diagnostics.js";
7
7
  import { deliveryFingerprint, deliveryKeyDigest, deliveryScopeDigest } from "./idempotency.js";
8
8
  import { WORKSPACE_CHANNEL_KIND } from "../../chat-channel.js";
9
+ import { chatRetentionDaysOf } from "../../manifest.js";
9
10
  import { channelProvider, chatConnection, chatKind } from "./providers/index.js";
11
+ import { deliveryArchiveOf } from "./store-delivery.js";
10
12
  /**
11
13
  * Whether a reply to mail goes to the people a review records it went to: its `to`, else its
12
14
  * recipient, and its `cc`, whatever their order and case.
@@ -21,10 +23,11 @@ function sameRecipients(recipients, review) {
21
23
  * Sends a reply the agent held for review, once a member approved it: the draft or the member's
22
24
  * edit, to the person's chat through the ontology's chat connection of the channel the chat is on,
23
25
  * as the agent and without attribution. A reply to mail goes to the review's `to` and `cc`, or the
24
- * addresses the member names in their place. The archive's delivery claim, keyed by the review and
25
- * not by the member, makes it at most once: a replay of the same approval returns the delivery, and
26
- * a different approval, by another member, with another text or to other people, is refused. A
27
- * provider that refused it consumes the claim: the reply is never sent again.
26
+ * addresses the member names in their place. The delivery's claim, on the reply's row of the
27
+ * workspace chat store, keyed by the review and not by the member, makes it at most once: a replay
28
+ * of the same approval returns the delivery, and a different approval, by another member, with
29
+ * another text or to other people, is refused. A provider that refused it consumes the claim: the
30
+ * reply is never sent again.
28
31
  */
29
32
  export function reviewSender(input) {
30
33
  const { backend, principal } = input;
@@ -261,13 +264,13 @@ export function reviewSender(input) {
261
264
  message: "The reply was redrafted meanwhile; approve the redraft instead.",
262
265
  });
263
266
  }
264
- const reserve = yield* input
265
- .archive({
267
+ // The review's claim and receipt live on the workspace chat store once it holds a message.
268
+ const archive = yield* deliveryArchiveOf(backend, input.cloud, chatRetentionDaysOf(input.ontology.manifest));
269
+ const reserve = yield* archive({
266
270
  event,
267
271
  delivery: { phase: "reserve", scope, key, fingerprint },
268
272
  identityToken: input.identityToken,
269
- })
270
- .pipe(Effect.tapError((error) => report("reserve", error)), Effect.mapError((cause) => new ActionRejected({
273
+ }).pipe(Effect.tapError((error) => report("reserve", error)), Effect.mapError((cause) => new ActionRejected({
271
274
  cause,
272
275
  message: cause.diagnostic === "chat_archive_conflict"
273
276
  ? "The reply was already approved by another member, with another text " +
@@ -325,8 +328,7 @@ export function reviewSender(input) {
325
328
  if (outcome.cause !== undefined) {
326
329
  yield* report("provider", outcome.cause);
327
330
  }
328
- const saved = yield* input
329
- .archive({
331
+ const saved = yield* archive({
330
332
  event: {
331
333
  ...event,
332
334
  eventId: `chat-delivery:${operationId}:receipt`,
@@ -337,8 +339,7 @@ export function reviewSender(input) {
337
339
  },
338
340
  delivery: { phase: "receipt", scope, key, fingerprint, claimId: reserve.claimId },
339
341
  identityToken: input.identityToken,
340
- })
341
- .pipe(Effect.exit);
342
+ }).pipe(Effect.exit);
342
343
  if (saved._tag === "Failure") {
343
344
  yield* report("receipt", saved.cause);
344
345
  }
@@ -0,0 +1,23 @@
1
+ import { Effect } from "effect";
2
+ import { type ChatMessageStore } from "../../runtime/chat-messages.js";
3
+ import type { OntologyBackend } from "../runtime-contract.js";
4
+ import { type DeliveryArchive } from "./archive.js";
5
+ /**
6
+ * A delivery's key on the store: one per caller scope and idempotency key, an opaque digest of
7
+ * both, so neither digest is shown to the chat's readers. No channel's queue of sends due holds it.
8
+ */
9
+ export declare function deliveryOperation(scope: string, key: string): string;
10
+ /**
11
+ * The delivery archive on the workspace chat store, by the chat archive in Cloud's protocol: the
12
+ * first reservation of a key is `claimed` with the row's id as its claim; a replay with the same
13
+ * request claims nothing and answers the row's receipt, and another request is a conflict. Only
14
+ * the claim records the receipt, once; another outcome for it is a conflict. A row past
15
+ * `retentionDays` or scrubbed to its tombstone answers its outcome without its message.
16
+ */
17
+ export declare function storeDeliveryArchive(store: ChatMessageStore, retentionDays: number): DeliveryArchive;
18
+ /**
19
+ * Where a delivery reserves and receipts its key: the workspace chat store once it holds a message,
20
+ * the evidence that the agent records there, as a chat's history is imported there from then on.
21
+ * `cloud` is the chat archive in Cloud, which takes the deliveries until then.
22
+ */
23
+ export declare function deliveryArchiveOf(backend: OntologyBackend["Service"], cloud: DeliveryArchive, retentionDays: number): Effect.Effect<DeliveryArchive>;
@@ -0,0 +1,299 @@
1
+ import { createHash } from "node:crypto";
2
+ import { Effect } from "effect";
3
+ import { DELIVERY_OPERATION_PREFIX, } from "../../runtime/chat-messages.js";
4
+ import { DeliveryArchiveError, } from "./archive.js";
5
+ /**
6
+ * Exact deliveries on the workspace chat store (docs/agent-chat-storage.md, "Staff sends"): a
7
+ * staff post, a send as the agent or an approved review reserves its key on a row of
8
+ * `_chat_messages` before the provider is called and records its receipt on that row, as the chat
9
+ * archive in Cloud did on its own rows. The row is the message: the chat's readers, the inbox and
10
+ * the agent's next session read it as they read every other message.
11
+ */
12
+ const DAY_MS = 86_400_000;
13
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
14
+ /** Why a provider refused a delivery, as its receipt names it: a code, such as outside_reply_window. */
15
+ const REFUSAL = /^[a-z][a-z_]{0,63}$/;
16
+ /** A refusal as the store keeps it. */
17
+ const CODE = /^[a-z][a-z0-9_]{0,63}$/;
18
+ /** The sender the store's readers give the agent's own messages. */
19
+ const AGENT_SENDER = "agent";
20
+ const digest = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
21
+ /**
22
+ * A delivery's key on the store: one per caller scope and idempotency key, an opaque digest of
23
+ * both, so neither digest is shown to the chat's readers. No channel's queue of sends due holds it.
24
+ */
25
+ export function deliveryOperation(scope, key) {
26
+ return `${DELIVERY_OPERATION_PREFIX}${digest([scope, key])}`;
27
+ }
28
+ /**
29
+ * The message a delivery binds beside its request, as the chat archive in Cloud bound it: its chat,
30
+ * thread, reply, text, readers, sender and requester. The same request with any of them changed is
31
+ * another delivery.
32
+ */
33
+ function payloadFingerprint(event) {
34
+ const requester = event.requestedBy;
35
+ return digest([
36
+ event.provider,
37
+ event.chatId,
38
+ event.chatType,
39
+ event.threadId,
40
+ event.replyToMessageId,
41
+ event.text,
42
+ [...event.participantIds].sort(),
43
+ event.senderId,
44
+ event.senderName,
45
+ event.senderIsBot,
46
+ [
47
+ requester.id,
48
+ requester.kind,
49
+ requester.name,
50
+ requester.via,
51
+ requester.clientId,
52
+ requester.clientName,
53
+ requester.attribution,
54
+ ],
55
+ ]);
56
+ }
57
+ function object(value) {
58
+ return value !== null && typeof value === "object" && !Array.isArray(value)
59
+ ? value
60
+ : undefined;
61
+ }
62
+ function claimOf(row) {
63
+ const claim = object(object(row.meta)?.delivery);
64
+ return {
65
+ ...(typeof claim?.operation === "string" ? { operation: claim.operation } : {}),
66
+ ...(typeof claim?.url === "string" ? { url: claim.url } : {}),
67
+ };
68
+ }
69
+ /** What the provider was sent, as the event's summary holds it: the send's channel state. */
70
+ function payloadOf(event) {
71
+ try {
72
+ return object(JSON.parse(event.argsSummary ?? "null")) ?? {};
73
+ }
74
+ catch {
75
+ return {};
76
+ }
77
+ }
78
+ /**
79
+ * The receipt a row records, as recorded: none while it is `pending`. A `sent` receipt keeps its
80
+ * provider id when the provider later reports the message failed, which a refusal never has.
81
+ */
82
+ function recordedOf(row) {
83
+ switch (row.status) {
84
+ case null:
85
+ case "pending":
86
+ return undefined;
87
+ case "uncertain":
88
+ return "uncertain";
89
+ case "failed":
90
+ return row.messageId === null ? "failed" : "sent";
91
+ default:
92
+ return "sent";
93
+ }
94
+ }
95
+ /** A conflict the callers tell apart: another request under the key, or another attempt's claim. */
96
+ const conflict = (reason, cause) => new DeliveryArchiveError({
97
+ diagnostic: "chat_archive_conflict",
98
+ cause: new Error(reason, cause === undefined ? undefined : { cause }),
99
+ });
100
+ /** The store could not be read or written: nothing was reserved, or the receipt is not recorded. */
101
+ const storeFailure = (diagnostic, cause) => Effect.fail(new DeliveryArchiveError({ diagnostic, cause }));
102
+ /**
103
+ * The delivery archive on the workspace chat store, by the chat archive in Cloud's protocol: the
104
+ * first reservation of a key is `claimed` with the row's id as its claim; a replay with the same
105
+ * request claims nothing and answers the row's receipt, and another request is a conflict. Only
106
+ * the claim records the receipt, once; another outcome for it is a conflict. A row past
107
+ * `retentionDays` or scrubbed to its tombstone answers its outcome without its message.
108
+ */
109
+ export function storeDeliveryArchive(store, retentionDays) {
110
+ const expired = (row) => row.purged || Date.parse(row.at) < Date.now() - retentionDays * DAY_MS;
111
+ /**
112
+ * What a key's delivery answers. Reported, a `sent` receipt whose message the provider later
113
+ * reported failed reads `failed` with its refusal; the receipt phase reads the receipt as
114
+ * recorded, which its caller compares with its own outcome. `operation` names the attempt that
115
+ * reserved it where the row no longer does, its `meta` gone with a deletion or retention.
116
+ */
117
+ const answer = (row, operation, reported, inserted = false) => {
118
+ const claim = claimOf(row);
119
+ const recorded = recordedOf(row);
120
+ const retained = !expired(row) && recorded !== undefined;
121
+ const failedLater = reported && recorded === "sent" && row.status === "failed";
122
+ const status = failedLater ? "failed" : (recorded ?? "uncertain");
123
+ // Retention scrubs a refusal with the message, as the archive in Cloud did.
124
+ const reason = status === "failed" && !row.purged ? row.failure : null;
125
+ return {
126
+ version: 1,
127
+ claimed: false,
128
+ duplicate: !inserted,
129
+ operationId: claim.operation ?? operation,
130
+ status,
131
+ messageId: retained ? row.messageId : null,
132
+ url: retained ? (claim.url ?? null) : null,
133
+ historyRecorded: retained,
134
+ ...(status === "failed" && reason !== null && REFUSAL.test(reason)
135
+ ? { refusal: reason }
136
+ : {}),
137
+ };
138
+ };
139
+ /** The key's row, which a reservation that found it must have. */
140
+ const sendOf = (operation) => store
141
+ .findSend(operation)
142
+ .pipe(Effect.flatMap((row) => row === undefined
143
+ ? Effect.fail(new DeliveryArchiveError({ diagnostic: "chat_store_send_missing" }))
144
+ : Effect.succeed(row)));
145
+ const reserve = (event, delivery) => Effect.gen(function* () {
146
+ if (event.status !== "requested" || event.messageId !== null || event.url !== null) {
147
+ return yield* new DeliveryArchiveError({ diagnostic: "chat_store_invalid_reservation" });
148
+ }
149
+ const operation = deliveryOperation(delivery.scope, delivery.key);
150
+ const author = !event.senderIsBot
151
+ ? "human"
152
+ : event.senderId === AGENT_SENDER
153
+ ? "agent"
154
+ : "bot";
155
+ const requester = event.requestedBy;
156
+ const message = {
157
+ channel: event.provider,
158
+ chatId: event.chatId,
159
+ ...(event.threadId === null ? {} : { threadId: event.threadId }),
160
+ chatType: event.chatType,
161
+ participants: event.participantIds.filter((id) => UUID.test(id)),
162
+ direction: "outbound",
163
+ author,
164
+ // The agent's own messages have one sender, which its readers give them.
165
+ ...(author === "agent" ? {} : { senderId: event.senderId, senderName: event.senderName }),
166
+ // A member's own reply is the member's, among the workspace's members.
167
+ ...(author === "human" && requester.kind === "member" && UUID.test(requester.id)
168
+ ? { userId: requester.id }
169
+ : {}),
170
+ ...(event.replyToMessageId === null ? {} : { replyTo: event.replyToMessageId }),
171
+ text: event.text,
172
+ at: event.at,
173
+ // Before the provider is called: the receipt settles it, a lost one leaves it unsent.
174
+ status: "pending",
175
+ operation,
176
+ // The request and the message it binds, so a replay that changes either is refused,
177
+ // while the request alone still finds the key's receipt.
178
+ fingerprint: `${delivery.fingerprint}:${payloadFingerprint(event)}`,
179
+ ...(event.sessionId === null ? {} : { sessionId: event.sessionId }),
180
+ meta: {
181
+ ...payloadOf(event),
182
+ delivery: {
183
+ operation: event.operationId,
184
+ requestedBy: {
185
+ id: requester.id,
186
+ kind: requester.kind,
187
+ via: requester.via,
188
+ clientId: requester.clientId,
189
+ },
190
+ },
191
+ },
192
+ };
193
+ const recorded = yield* store
194
+ .record(message)
195
+ .pipe(Effect.catchTag("ChatMessageConflict", (cause) => Effect.fail(conflict("request_binding_mismatch", cause))));
196
+ if (recorded.first) {
197
+ return {
198
+ version: 1,
199
+ claimed: true,
200
+ duplicate: false,
201
+ operationId: event.operationId,
202
+ claimId: recorded.id,
203
+ status: "uncertain",
204
+ messageId: null,
205
+ url: null,
206
+ historyRecorded: false,
207
+ };
208
+ }
209
+ return answer(yield* sendOf(operation), operation, true);
210
+ });
211
+ const receipt = (event, delivery) => Effect.gen(function* () {
212
+ const status = event.status;
213
+ if (status === "requested" || (status === "sent" && event.messageId === null)) {
214
+ return yield* new DeliveryArchiveError({ diagnostic: "chat_store_invalid_receipt" });
215
+ }
216
+ const operation = deliveryOperation(delivery.scope, delivery.key);
217
+ const row = yield* store.findSend(operation);
218
+ if (row === undefined ||
219
+ row.fingerprint !== `${delivery.fingerprint}:${payloadFingerprint(event)}`) {
220
+ return yield* conflict("request_binding_mismatch");
221
+ }
222
+ const claim = claimOf(row);
223
+ if (delivery.claimId !== row.id ||
224
+ (claim.operation !== undefined && claim.operation !== event.operationId)) {
225
+ return yield* conflict("receipt_claim_mismatch");
226
+ }
227
+ // A late receipt never brings back a message retention removed.
228
+ if (expired(row)) {
229
+ return answer(row, event.operationId, false);
230
+ }
231
+ const recorded = recordedOf(row);
232
+ if (recorded !== undefined) {
233
+ if (recorded !== status ||
234
+ row.messageId !== event.messageId ||
235
+ (claim.url ?? null) !== event.url) {
236
+ return yield* conflict("receipt_already_recorded");
237
+ }
238
+ return answer(row, event.operationId, false);
239
+ }
240
+ const failure = status === "failed" ? event.reason : null;
241
+ const { applied } = yield* store
242
+ .change({
243
+ change: "sent",
244
+ channel: row.channel,
245
+ chatId: row.chatId,
246
+ operation,
247
+ status,
248
+ ...(event.messageId === null ? {} : { providerMessageId: event.messageId }),
249
+ ...(failure !== null && CODE.test(failure) ? { failure } : {}),
250
+ // What the provider was sent, with the link it answered.
251
+ meta: {
252
+ ...payloadOf(event),
253
+ delivery: {
254
+ ...object(object(row.meta)?.delivery),
255
+ ...(event.url === null ? {} : { url: event.url }),
256
+ },
257
+ },
258
+ })
259
+ .pipe(
260
+ // Another send holds the provider's id: the receipt is not recorded, and the key reads
261
+ // uncertain, as a receipt the archive in Cloud could not take did.
262
+ Effect.catchTag("ChatMessageConflict", (cause) => Effect.fail(new DeliveryArchiveError({ diagnostic: "chat_store_receipt_failed", cause }))));
263
+ if (!applied) {
264
+ return yield* conflict("receipt_insert_conflict");
265
+ }
266
+ return answer(yield* sendOf(operation), event.operationId, false, true);
267
+ });
268
+ const find = ({ delivery }) => Effect.gen(function* () {
269
+ const operation = deliveryOperation(delivery.scope, delivery.key);
270
+ const row = yield* store.findSend(operation);
271
+ if (row === undefined) {
272
+ return undefined;
273
+ }
274
+ // The request alone, which a replay derives without the message it reads when it sends.
275
+ if (row.fingerprint?.split(":")[0] !== delivery.fingerprint) {
276
+ return yield* conflict("request_binding_mismatch");
277
+ }
278
+ return answer(row, operation, true);
279
+ }).pipe(Effect.catchDefect((cause) => storeFailure("chat_store_find_failed", cause)));
280
+ return Object.assign(({ event, delivery }) => (delivery.phase === "reserve" ? reserve(event, delivery) : receipt(event, delivery)).pipe(Effect.catchDefect((cause) => storeFailure(delivery.phase === "reserve"
281
+ ? "chat_store_reserve_failed"
282
+ : "chat_store_receipt_failed", cause))), { find });
283
+ }
284
+ /**
285
+ * Where a delivery reserves and receipts its key: the workspace chat store once it holds a message,
286
+ * the evidence that the agent records there, as a chat's history is imported there from then on.
287
+ * `cloud` is the chat archive in Cloud, which takes the deliveries until then.
288
+ */
289
+ export function deliveryArchiveOf(backend, cloud, retentionDays) {
290
+ const store = backend.agents?.chatMessages;
291
+ // @legacy agent.cloud-chat-archive Until the agent records into the store, the archive in Cloud
292
+ // reserves and receipts the delivery, as it keeps the agent's messages.
293
+ if (store === undefined) {
294
+ return Effect.succeed(cloud);
295
+ }
296
+ return store
297
+ .holds()
298
+ .pipe(Effect.map((held) => (held ? storeDeliveryArchive(store, retentionDays) : cloud)));
299
+ }
@@ -161,7 +161,11 @@ export interface OntologyServiceConfig extends OntologyEnvironment {
161
161
  readonly warehouseQueries?: import("./warehouse-platform.js").WarehouseReadTransport;
162
162
  /** Explicit adapters for other verified channel apps. */
163
163
  readonly channelAppProviders?: readonly import("./channel/provider.js").ChannelAppProvider[];
164
- /** Override the archive transport for isolated integrations; defaults to the authenticated platform archive. */
164
+ /**
165
+ * Override, for isolated integrations, where a delivery reserves its key while the workspace chat
166
+ * store holds no message; the authenticated platform archive by default.
167
+ * @legacy agent.cloud-chat-archive
168
+ */
165
169
  readonly chatArchive?: DeliveryArchive;
166
170
  /** Override where a chat's earlier history is imported, for isolated integrations. */
167
171
  readonly chatHistoryArchive?: HistoryArchive;
@@ -345,7 +345,9 @@ export function createOntologyService(ontology, config) {
345
345
  : localConnections(config.localConnections)));
346
346
  const replicate = deployedReplication(config);
347
347
  const chatHistory = config.runtimeIdentity === undefined ? undefined : platformChatArchive(config);
348
- const chatDelivery = makeChatDelivery(ontology, connections, config.chatArchive ?? platformDeliveryArchive(config), { settings: config.channels?.telegram, ownOrigins: config.appOrigins },
348
+ const chatDelivery = makeChatDelivery(ontology, connections,
349
+ // @legacy agent.cloud-chat-archive Deliveries reserve here while the store holds no message.
350
+ config.chatArchive ?? platformDeliveryArchive(config), { settings: config.channels?.telegram, ownOrigins: config.appOrigins },
349
351
  // The app's agent sends through a workspace channel, at the origin it takes its tasks at.
350
352
  {
351
353
  origin: config.agentOrigin,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.155.0",
3
+ "version": "0.156.1",
4
4
  "description": "Define a SegmentStream workspace app's ontology: entities, relationships, roles and actions, written with Effect.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",