@segmentstream/ontology 0.154.0 → 0.156.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/dist/agent-review.d.ts +8 -0
- package/dist/agent-review.js +25 -0
- package/dist/runtime/agents.js +28 -8
- package/dist/runtime/chat-messages.d.ts +44 -5
- package/dist/runtime/chat-messages.js +51 -15
- package/dist/service/agent/chat-message-routes.d.ts +1 -0
- package/dist/service/agent/chat-message-routes.js +15 -2
- package/dist/service/agent/protocol.d.ts +2 -0
- package/dist/service/agent/protocol.js +11 -0
- package/dist/service/agent/server.js +5 -1
- package/dist/service/chat/archive.d.ts +12 -1
- package/dist/service/chat/archive.js +6 -1
- package/dist/service/chat/delivery.d.ts +7 -1
- package/dist/service/chat/delivery.js +17 -4
- package/dist/service/chat/local-reads.d.ts +4 -3
- package/dist/service/chat/local-reads.js +35 -20
- package/dist/service/chat/review-delivery.d.ts +11 -5
- package/dist/service/chat/review-delivery.js +22 -14
- package/dist/service/chat/store-delivery.d.ts +23 -0
- package/dist/service/chat/store-delivery.js +299 -0
- package/dist/service/config.d.ts +5 -1
- package/dist/service/runtime-contract.d.ts +15 -2
- package/dist/service/service.js +3 -1
- package/package.json +1 -1
|
@@ -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,
|
|
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) => {
|
|
@@ -359,7 +367,10 @@ chats) {
|
|
|
359
367
|
query: chatPeopleQuery(chat),
|
|
360
368
|
})
|
|
361
369
|
.pipe(Effect.mapError((cause) => new ActionRejected({ message: "The chat's person could not be read.", cause })))).items;
|
|
362
|
-
|
|
370
|
+
// A thread's chat on a mailbox has no one person to answer: staff answer it in the mail.
|
|
371
|
+
const mailThread = chatKind(ontology.manifest.chat, String(record.provider)) === "email" &&
|
|
372
|
+
!(typeof record.recipient === "string" && record.recipient !== "");
|
|
373
|
+
if (people.length !== 1 || mailThread) {
|
|
363
374
|
return yield* new ActionRejected({
|
|
364
375
|
message: "The chat has no person to answer. Nothing was sent.",
|
|
365
376
|
});
|
|
@@ -465,7 +476,7 @@ chats) {
|
|
|
465
476
|
identityToken: context.identityToken,
|
|
466
477
|
requestId: context.requestId,
|
|
467
478
|
archive: history,
|
|
468
|
-
retentionDays
|
|
479
|
+
retentionDays,
|
|
469
480
|
channelKind: (name) => chatKind(ontology.manifest.chat, name),
|
|
470
481
|
}),
|
|
471
482
|
}),
|
|
@@ -479,7 +490,7 @@ chats) {
|
|
|
479
490
|
ontology,
|
|
480
491
|
connections,
|
|
481
492
|
agent: agentTransport,
|
|
482
|
-
|
|
493
|
+
cloud,
|
|
483
494
|
previews: destinationPreviews,
|
|
484
495
|
backend: context.backend,
|
|
485
496
|
principal: context.principal,
|
|
@@ -503,6 +514,8 @@ chats) {
|
|
|
503
514
|
clientId: requester.clientId,
|
|
504
515
|
});
|
|
505
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);
|
|
506
519
|
const unreserved = (cause) => new ActionRejected({
|
|
507
520
|
cause,
|
|
508
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,
|
|
68
|
-
*
|
|
69
|
-
*
|
|
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,
|
|
94
|
-
*
|
|
95
|
-
*
|
|
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
|
|
112
|
-
// messages the store purged reads there too, never
|
|
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 = `${
|
|
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
|
-
},
|
|
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
|
|
17
|
-
* not by the member, makes it at most once: a replay
|
|
18
|
-
*
|
|
19
|
-
* provider that refused it consumes the claim: the
|
|
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
|
-
|
|
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"];
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import { Effect } from "effect";
|
|
2
|
-
import { addressesOfReview, AGENT_REVIEW_TEXT_LIMIT } from "../../agent-review.js";
|
|
2
|
+
import { addressesOfReview, AGENT_REVIEW_TEXT_LIMIT, participantsOfReview, } from "../../agent-review.js";
|
|
3
3
|
import { EMAIL_RECIPIENTS_LIMIT, emailRecipients } from "../../email.js";
|
|
4
4
|
import { ActionRejected, PermissionDenied } from "../../errors.js";
|
|
5
5
|
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
|
|
25
|
-
* not by the member, makes it at most once: a replay
|
|
26
|
-
*
|
|
27
|
-
* provider that refused it consumes the claim: the
|
|
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;
|
|
@@ -183,7 +186,14 @@ export function reviewSender(input) {
|
|
|
183
186
|
provider: providerName,
|
|
184
187
|
external_id: externalId,
|
|
185
188
|
kind,
|
|
186
|
-
|
|
189
|
+
// The reply is its person's and, in a chat several people share, such as an email thread,
|
|
190
|
+
// the members the agent named as its readers, as a reply it sent itself would be.
|
|
191
|
+
participantIds: [
|
|
192
|
+
...new Set([
|
|
193
|
+
...(person === null ? [] : [person]),
|
|
194
|
+
...participantsOfReview(review.participants),
|
|
195
|
+
]),
|
|
196
|
+
],
|
|
187
197
|
};
|
|
188
198
|
const preview = {
|
|
189
199
|
chatId: target.id,
|
|
@@ -254,13 +264,13 @@ export function reviewSender(input) {
|
|
|
254
264
|
message: "The reply was redrafted meanwhile; approve the redraft instead.",
|
|
255
265
|
});
|
|
256
266
|
}
|
|
257
|
-
|
|
258
|
-
|
|
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({
|
|
259
270
|
event,
|
|
260
271
|
delivery: { phase: "reserve", scope, key, fingerprint },
|
|
261
272
|
identityToken: input.identityToken,
|
|
262
|
-
})
|
|
263
|
-
.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({
|
|
264
274
|
cause,
|
|
265
275
|
message: cause.diagnostic === "chat_archive_conflict"
|
|
266
276
|
? "The reply was already approved by another member, with another text " +
|
|
@@ -318,8 +328,7 @@ export function reviewSender(input) {
|
|
|
318
328
|
if (outcome.cause !== undefined) {
|
|
319
329
|
yield* report("provider", outcome.cause);
|
|
320
330
|
}
|
|
321
|
-
const saved = yield*
|
|
322
|
-
.archive({
|
|
331
|
+
const saved = yield* archive({
|
|
323
332
|
event: {
|
|
324
333
|
...event,
|
|
325
334
|
eventId: `chat-delivery:${operationId}:receipt`,
|
|
@@ -330,8 +339,7 @@ export function reviewSender(input) {
|
|
|
330
339
|
},
|
|
331
340
|
delivery: { phase: "receipt", scope, key, fingerprint, claimId: reserve.claimId },
|
|
332
341
|
identityToken: input.identityToken,
|
|
333
|
-
})
|
|
334
|
-
.pipe(Effect.exit);
|
|
342
|
+
}).pipe(Effect.exit);
|
|
335
343
|
if (saved._tag === "Failure") {
|
|
336
344
|
yield* report("receipt", saved.cause);
|
|
337
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
|
+
}
|
package/dist/service/config.d.ts
CHANGED
|
@@ -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
|
-
/**
|
|
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;
|