@segmentstream/ontology 0.180.0 → 0.182.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.
Files changed (50) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/agent-chat.d.ts +2 -2
  3. package/dist/agent-chat.js +2 -1
  4. package/dist/agent-draft.d.ts +8 -8
  5. package/dist/analyze.d.ts +1 -8
  6. package/dist/analyze.js +108 -52
  7. package/dist/index.d.ts +1 -1
  8. package/dist/manifest.d.ts +110 -68
  9. package/dist/manifest.js +24 -2
  10. package/dist/migrate/model.d.ts +78 -50
  11. package/dist/review.d.ts +46 -0
  12. package/dist/review.js +47 -0
  13. package/dist/runtime/agent-web.js +47 -26
  14. package/dist/runtime/agents.js +53 -4
  15. package/dist/runtime/guests.d.ts +4 -1
  16. package/dist/runtime/guests.js +24 -5
  17. package/dist/service/agent/protocol.d.ts +51 -0
  18. package/dist/service/agent/protocol.js +66 -1
  19. package/dist/service/agent/server.d.ts +8 -2
  20. package/dist/service/agent/server.js +208 -48
  21. package/dist/service/authentication.js +14 -3
  22. package/dist/service/chat/archive.d.ts +8 -1
  23. package/dist/service/chat/delivery.js +3 -1
  24. package/dist/service/chat/envelope.d.ts +8 -8
  25. package/dist/service/chat/local-reads.d.ts +5 -5
  26. package/dist/service/chat/providers/custom.js +2 -0
  27. package/dist/service/chat/providers/provider.d.ts +5 -0
  28. package/dist/service/chat/reply-proposal.d.ts +122 -0
  29. package/dist/service/chat/reply-proposal.js +385 -0
  30. package/dist/service/chat/review-delivery.d.ts +131 -24
  31. package/dist/service/chat/review-delivery.js +393 -296
  32. package/dist/service/chat/store-delivery.d.ts +27 -5
  33. package/dist/service/chat/store-delivery.js +45 -33
  34. package/dist/service/discovery-search.d.ts +1 -1
  35. package/dist/service/operations.js +2 -1
  36. package/dist/service/runtime-contract.d.ts +33 -1
  37. package/dist/service/runtime-identity.d.ts +1 -0
  38. package/dist/service/runtime-identity.js +2 -0
  39. package/dist/service/schemas.d.ts +4 -0
  40. package/dist/service/service.js +12 -14
  41. package/dist/service/toolsets.d.ts +1 -1
  42. package/dist/service/toolsets.js +38 -4
  43. package/dist/sign-in.d.ts +14 -7
  44. package/dist/sign-in.js +4 -3
  45. package/dist/toolset.d.ts +17 -1
  46. package/dist/workspace-channel.d.ts +6 -0
  47. package/dist/workspace-channel.js +27 -0
  48. package/package.json +5 -1
  49. package/dist/service/agent/public-group-action.d.ts +0 -23
  50. package/dist/service/agent/public-group-action.js +0 -53
@@ -7,8 +7,8 @@ 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
9
  import { chatRetentionDaysOf, signsMail } from "../../manifest.js";
10
- import { channelProvider, chatConnection, chatKind } from "./providers/index.js";
11
- import { storeDeliveryArchive } from "./store-delivery.js";
10
+ import { chatConnection, chatKind, chatProvider } from "./providers/index.js";
11
+ import { deliveryOperation, storeDeliveryArchive } from "./store-delivery.js";
12
12
  import { readDraftFiles, refuseChatFiles } from "./draft-files.js";
13
13
  /**
14
14
  * Whether a reply to mail goes to the people a review records it went to: its `to`, else its
@@ -34,193 +34,85 @@ function refused(code, channel) {
34
34
  refusal: code,
35
35
  }));
36
36
  }
37
+ /** The scope and key of the agent's delivery under `subject`, as its claim is keyed. */
38
+ function agentReplyKey(subject) {
39
+ return {
40
+ scope: deliveryScopeDigest({ via: "service", subjectId: subject, clientId: null }),
41
+ key: deliveryKeyDigest(subject),
42
+ };
43
+ }
37
44
  /**
38
- * Sends a reply the agent held for review, once a member approved it: the draft or the member's
39
- * edit, to the person's chat through the ontology's chat connection of the channel the chat is on,
40
- * as the agent and without attribution. A reply to mail goes to the review's `to` and `cc`, or the
41
- * addresses the member names in their place. The delivery's claim, on the reply's row of the
42
- * workspace chat store, keyed by the review and not by the member, makes it at most once: a replay
43
- * of the same approval returns the delivery, and a different approval, by another member, with
44
- * another text or to other people, is refused. A provider that refused it consumes the claim: the
45
- * reply is never sent again.
45
+ * The workspace chat store's key of the agent's delivery under `subject`: the row its claim
46
+ * reserves, which a replay finds without the message it would send.
46
47
  */
47
- export function reviewSender(input) {
48
- const { backend, principal } = input;
49
- const report = (phase, cause) => Effect.logWarning("ontology.agent_draft.delivery_diagnostic").pipe(Effect.annotateLogs({
48
+ export function agentReplyOperation(subject) {
49
+ const { scope, key } = agentReplyKey(subject);
50
+ return deliveryOperation(scope, key);
51
+ }
52
+ function reporter(transport, operation) {
53
+ return (phase, cause) => Effect.logWarning(operation).pipe(Effect.annotateLogs({
50
54
  phase,
51
- requestId: input.requestId,
52
- error: describeChatError(cause, (text) => input.identityToken ? text.split(input.identityToken).join("[redacted]") : text),
55
+ requestId: transport.requestId,
56
+ error: describeChatError(cause, (text) => transport.identityToken ? text.split(transport.identityToken).join("[redacted]") : text),
53
57
  }));
54
- return (send) => Effect.gen(function* () {
55
- // A role may hold the approval within a scope. The send happens before the action's
56
- // transaction, whose write guard comes too late for it: a review outside the scope is
57
- // refused here, read through the approval's own scope.
58
- const approvable = effectiveScope("agent_draft:approve", principal);
59
- if (approvable !== undefined) {
60
- yield* backend
61
- .get({
62
- entity: "agent_draft",
63
- id: send.review,
64
- reader: {
65
- ...principal,
66
- permissions: ["agent_draft:read"],
67
- scopes: [{ permission: "agent_draft:read", where: approvable }],
68
- },
69
- })
70
- .pipe(Effect.mapError(() => new PermissionDenied({
71
- message: "The draft is outside the records agent_draft:approve covers.",
72
- permission: "agent_draft:approve",
73
- })));
74
- }
75
- const review = yield* backend
76
- .get({ entity: "agent_draft", id: send.review })
77
- .pipe(Effect.mapError(() => new ActionRejected({ message: "The draft does not exist." })));
78
- const draft = String(review.draft ?? "");
79
- const text = send.text ?? draft;
80
- const status = String(review.status);
81
- const email = String(review.channel_kind) === "email";
82
- // Only a reply to mail names whom it goes to beside its chat.
83
- if (!email && (send.to !== undefined || send.cc !== undefined)) {
84
- return yield* new ActionRejected({
85
- message: "Only a reply to mail takes to and cc; this reply goes to its chat.",
86
- });
87
- }
88
- // A reply to mail goes to the review's `to` and `cc`, the thread's people, unless the member
89
- // names others; one held before replies named them goes to its recipient alone.
90
- const held = addressesOfDraft(review.to);
91
- const recipients = email
92
- ? yield* Effect.try({
93
- try: () => emailRecipients({
94
- to: send.to ??
95
- (held.length > 0
96
- ? held
97
- : typeof review.recipient === "string"
98
- ? [review.recipient]
99
- : []),
100
- cc: send.cc ?? addressesOfDraft(review.cc),
101
- }),
102
- catch: (cause) => new ActionRejected({
103
- message: `A reply to mail goes to 1 to ${EMAIL_RECIPIENTS_LIMIT} plain addresses ` +
104
- "together, in to and cc; nothing was sent.",
105
- cause,
106
- }),
107
- })
108
- : undefined;
109
- const heldFiles = draftFilesOf(review.files);
110
- // An approval may leave files out, never add one: each it names is one the draft holds.
111
- const files = send.files === undefined
112
- ? heldFiles
113
- : heldFiles.filter((file) => send.files.some((named) => named.entity === file.entity &&
114
- named.id.toLowerCase() === file.id &&
115
- named.property === file.property &&
116
- named.revisionId === file.revisionId));
117
- if (send.files !== undefined && files.length !== send.files.length) {
118
- return yield* new ActionRejected({
119
- message: "An approval sends only files the draft holds; nothing was sent.",
120
- refusal: "file_not_held",
121
- });
122
- }
123
- if (status !== "pending") {
124
- if ((status === "sent" || status === "uncertain") &&
125
- text === review.text &&
126
- (recipients === undefined || sameRecipients(recipients, review)) &&
127
- // The draft keeps the files it sent: another choice of them is another approval.
128
- (send.files === undefined || files.length === heldFiles.length)) {
129
- return {
130
- status,
131
- text,
132
- messageId: typeof review.message_id === "string" ? review.message_id : null,
133
- duplicate: true,
134
- ...(typeof review.message === "string" ? { message: review.message } : {}),
135
- ...(recipients === undefined ? {} : { recipients }),
136
- ...(files.length === 0 && send.files === undefined ? {} : { files }),
137
- };
138
- }
139
- return yield* new ActionRejected({
140
- message: status === "rejected" || status === "dismissed"
141
- ? `The reply was ${status}; it is never sent.`
142
- : "The reply was already approved; it is never sent again.",
143
- refusal: "draft_decided",
144
- });
145
- }
146
- // The channel the chat is on, by name. A review held before channels had names has none:
147
- // it is on the channel named after its kind.
148
- // @legacy ontology.reviews-without-channel
149
- const providerName = typeof review.channel === "string" && review.channel !== ""
150
- ? review.channel
151
- : String(review.channel_kind);
152
- const provider = channelProvider(input.ontology.manifest.chat, providerName);
153
- const connection = chatConnection(input.ontology.manifest.chat, providerName) ?? "";
154
- const channelKind = chatKind(input.ontology.manifest.chat, providerName);
58
+ }
59
+ /**
60
+ * Checks a reply of the agent's before anything is reserved or sent: its channel and connection,
61
+ * its text as the provider renders it, its destination and files, and who sends it. Answers the
62
+ * delivery it would be, bound to its key, on the workspace chat store once it holds a message.
63
+ */
64
+ export function prepareAgentReply(transport, reply) {
65
+ return Effect.gen(function* () {
66
+ const { backend, ontology } = transport;
67
+ const providerName = reply.channel;
68
+ const declaredKind = chatKind(ontology.manifest.chat, providerName);
69
+ const channelKind = reply.declared ? declaredKind : (declaredKind ?? reply.channelKind);
70
+ const provider = channelKind === undefined ? undefined : chatProvider(channelKind);
71
+ const connection = chatConnection(ontology.manifest.chat, providerName) ?? "";
155
72
  // A workspace channel needs no connection of the ontology's: the agent sends through it.
156
73
  if (provider === undefined ||
157
- (!connection && channelKind !== WORKSPACE_CHANNEL_KIND) ||
158
- channelKind !== String(review.channel_kind)) {
74
+ (reply.declared && !connection && channelKind !== WORKSPACE_CHANNEL_KIND) ||
75
+ channelKind !== reply.channelKind) {
159
76
  return yield* new ActionRejected({
160
77
  message: `Sending a reviewed reply needs chat.${providerName}.connection in defineOntology, ` +
161
- `of kind ${String(review.channel_kind)}: the connection of the bot, number or mailbox ` +
78
+ `of kind ${reply.channelKind}: the connection of the bot, number or mailbox ` +
162
79
  "the person talks to.",
163
80
  });
164
81
  }
165
- const kind = review.chat_kind === "group" ? "group" : "private";
82
+ const kind = reply.chatKind;
166
83
  // The archive keys the chat by its chat id; the provider takes the recipient, which
167
84
  // differs where a channel names a chat otherwise, as WhatsApp's threads do.
168
- const chatId = String(review.chat_id);
169
- const externalId = typeof review.recipient === "string" && review.recipient !== "" ? review.recipient : chatId;
170
- const threadId = typeof review.thread_id === "string" && review.thread_id !== "" ? review.thread_id : null;
85
+ const chatId = reply.chatId;
86
+ const externalId = reply.recipient !== null && reply.recipient !== "" ? reply.recipient : chatId;
87
+ const threadId = reply.threadId !== null && reply.threadId !== "" ? reply.threadId : null;
171
88
  // The reply is sent in the thread it answers and archived in the chat that keeps the
172
89
  // person's messages, where the agent and the judge read it.
173
90
  const archivedThreadId = kind === "private" && provider.privateChatSpansThreads === true ? null : threadId;
174
91
  // A private chat has one person: the reply needs no quote of their message, which
175
92
  // they may have deleted since.
176
- const replyTo = kind === "group" && typeof review.reply_to === "string" && review.reply_to !== ""
177
- ? review.reply_to
178
- : null;
93
+ const replyTo = kind === "group" && reply.replyTo !== null && reply.replyTo !== "" ? reply.replyTo : null;
94
+ const text = reply.text;
95
+ const files = reply.files;
179
96
  const { finalText, plainText } = yield* Effect.try({
180
97
  try: () => provider.render(text, "", ""),
181
98
  catch: (cause) => new ActionRejected({ message: "The Markdown could not be rendered.", cause }),
182
99
  });
183
100
  if ((text.trim() === "" && files.length === 0) ||
184
- text.length > AGENT_DRAFT_TEXT_LIMIT ||
101
+ (reply.textLimit !== undefined && text.length > reply.textLimit) ||
185
102
  finalText.length > provider.limit ||
186
103
  plainText.length > provider.limit ||
187
104
  !provider.isTargetId(externalId, kind) ||
188
105
  (replyTo !== null && !provider.isReplyId(replyTo))) {
189
- return yield* new ActionRejected({
190
- message: `The reply is empty or longer than ${provider.limit} characters, which ` +
191
- `${providerName} accepts in one message. Approve it with a shorter text; nothing was ` +
192
- "sent or truncated.",
193
- });
106
+ return yield* new ActionRejected({ message: reply.rejection(providerName, provider.limit) });
194
107
  }
195
108
  // The files the channel cannot send are refused before anything is reserved: no claim spent.
196
109
  const filesRefusal = refuseChatFiles(provider, files);
197
110
  if (filesRefusal !== undefined) {
198
111
  return yield* refused(filesRefusal, providerName);
199
112
  }
200
- // A guest is no user; `agent_draft` is not theirs to approve.
201
- if (principal.kind === "guest") {
202
- return yield* new PermissionDenied({ message: "The approver is unknown." });
203
- }
204
- const user = yield* backend
205
- .get({ entity: "user", id: principal.id })
206
- .pipe(Effect.mapError(() => new PermissionDenied({ message: "The approver is unknown." })));
207
- if (user.active !== true) {
208
- return yield* new PermissionDenied({ message: "The approver is inactive." });
209
- }
210
- const name = String(user.name ?? "").trim() || principal.id;
211
- // The archive's record of who sent it; the person never sees it.
212
- const requester = {
213
- id: principal.id,
214
- kind: principal.kind,
215
- name,
216
- via: principal.kind === "service" ? "service" : "hq",
217
- clientId: null,
218
- clientName: null,
219
- attribution: name,
220
- };
221
- const person = typeof review.person_id === "string" ? review.person_id : null;
113
+ const requester = yield* reply.requester;
222
114
  const target = {
223
- id: String(review.id),
115
+ id: reply.operationId,
224
116
  title: "",
225
117
  provider: providerName,
226
118
  external_id: externalId,
@@ -228,10 +120,7 @@ export function reviewSender(input) {
228
120
  // The reply is its person's and, in a chat several people share, such as an email thread,
229
121
  // the members the agent named as its readers, as a reply it sent itself would be.
230
122
  participantIds: [
231
- ...new Set([
232
- ...(person === null ? [] : [person]),
233
- ...participantsOfDraft(review.participants),
234
- ]),
123
+ ...new Set([...(reply.person === null ? [] : [reply.person]), ...reply.participants]),
235
124
  ],
236
125
  };
237
126
  const preview = {
@@ -244,16 +133,11 @@ export function reviewSender(input) {
244
133
  finalText,
245
134
  replyTo,
246
135
  };
247
- const operationId = String(review.id);
248
- const scope = deliveryScopeDigest({
249
- via: "service",
250
- // The delivery keys keep the entity's first name: a renamed key would send an approval again.
251
- subjectId: `agent_review:${operationId}`,
252
- clientId: null,
253
- });
254
- const key = deliveryKeyDigest(`agent_review:${operationId}`);
136
+ const operationId = reply.operationId;
137
+ const { scope, key } = agentReplyKey(reply.subject);
255
138
  // A reply to mail that names anyone beside its person binds them, so another approval naming
256
139
  // others is refused; one to its person alone keeps the binding it always had.
140
+ const recipients = reply.recipients;
257
141
  const bound = recipients !== undefined &&
258
142
  !(recipients.cc.length === 0 &&
259
143
  recipients.to.length === 1 &&
@@ -276,16 +160,8 @@ export function reviewSender(input) {
276
160
  kind: "outbound",
277
161
  messageId: null,
278
162
  replyToMessageId: replyTo,
279
- // The agent's session holds its draft: the session sees an edit, a redraft it never wrote,
280
- // and a reply sent without some of its files as a message it did not write, and its own
281
- // draft sent as written as its own.
282
- sessionId: text === draft &&
283
- files.length === heldFiles.length &&
284
- (review.revises_id === null || review.revises_id === undefined) &&
285
- typeof review.session_id === "string"
286
- ? review.session_id
287
- : null,
288
- turnId: null,
163
+ sessionId: reply.sessionId,
164
+ turnId: reply.turnId,
289
165
  text,
290
166
  decision: null,
291
167
  reason: null,
@@ -307,56 +183,97 @@ export function reviewSender(input) {
307
183
  at: new Date().toISOString(),
308
184
  };
309
185
  const store = backend.agents?.chatMessages;
310
- // The review's claim and receipt live on the workspace chat store once it holds a message.
186
+ // The reply's claim and receipt live on the workspace chat store once it holds a message.
311
187
  // @legacy agent.cloud-chat-archive Until then, the chat archive in Cloud holds them.
312
188
  const onStore = store !== undefined && (yield* store.holds());
313
189
  const archive = onStore
314
- ? storeDeliveryArchive(store, chatRetentionDaysOf(input.ontology.manifest))
315
- : input.cloud;
190
+ ? storeDeliveryArchive(store, chatRetentionDaysOf(ontology.manifest), {
191
+ unnamedSends: provider.unnamedSends === true,
192
+ })
193
+ : transport.cloud;
194
+ // Only the chat store keeps a proposal's binding: the archive in Cloud is not extended.
195
+ const stored = onStore && reply.binding !== undefined ? { ...event, binding: reply.binding } : event;
316
196
  // Files go only through the workspace chat store: the archive in Cloud is not extended.
317
197
  // @legacy agent.cloud-chat-archive
318
198
  if (files.length > 0 && !onStore) {
319
199
  return yield* refused("files_unsupported", providerName);
320
200
  }
321
- // A replay of an approval that sent its files answers that delivery without reading them
322
- // again: they may since be gone, which must not refuse what was already sent.
323
- const earlier = files.length === 0 || archive.find === undefined
324
- ? undefined
325
- : yield* archive
326
- .find({ delivery: { scope, key, fingerprint }, identityToken: input.identityToken })
327
- .pipe(Effect.tapError((error) => report("find", error)), Effect.mapError((cause) => new ActionRejected({
328
- cause,
329
- message: cause.diagnostic === "chat_archive_conflict"
330
- ? "The reply was already approved by another member, with another " +
331
- "text or to other people; it is never sent again."
332
- : "The delivery could not be read, and nothing was sent. Approve again.",
333
- })));
201
+ return {
202
+ reply,
203
+ provider,
204
+ connection,
205
+ target,
206
+ finalText,
207
+ plainText,
208
+ replyTo,
209
+ event: stored,
210
+ scope,
211
+ key,
212
+ fingerprint,
213
+ archive,
214
+ onStore,
215
+ };
216
+ });
217
+ }
218
+ /**
219
+ * The delivery a reply's key holds already, read without reserving anything: its receipt, or
220
+ * undefined when the key has none. Another request under the key is refused.
221
+ */
222
+ export function earlierAgentReply(transport, prepared) {
223
+ const { archive, scope, key, fingerprint } = prepared;
224
+ const report = reporter(transport, "ontology.agent_draft.delivery_diagnostic");
225
+ return archive.find === undefined
226
+ ? Effect.succeed(undefined)
227
+ : archive
228
+ .find({ delivery: { scope, key, fingerprint }, identityToken: transport.identityToken })
229
+ .pipe(Effect.tapError((error) => report("find", error)), Effect.mapError((cause) => new ActionRejected({
230
+ cause,
231
+ message: cause.diagnostic === "chat_archive_conflict"
232
+ ? "The reply was already approved by another member, with another " +
233
+ "text or to other people; it is never sent again."
234
+ : "The delivery could not be read, and nothing was sent. Approve again.",
235
+ })));
236
+ }
237
+ /**
238
+ * Sends a prepared reply of the agent's at most once: its key is claimed on the chat store, or the
239
+ * archive in Cloud before it, before the provider is called, and the provider's outcome is that
240
+ * claim's receipt. A replay of the same reply answers the delivery, and another under the key is
241
+ * refused. `reserve` runs the claim, as an approval runs it under its draft's lock.
242
+ */
243
+ export function deliverAgentReply(transport, prepared, reserve) {
244
+ return Effect.gen(function* () {
245
+ const { backend } = transport;
246
+ const { reply, provider, archive, onStore, scope, key, fingerprint, event } = prepared;
247
+ const report = reporter(transport, "ontology.agent_draft.delivery_diagnostic");
248
+ const files = reply.files;
249
+ const operationId = reply.operationId;
250
+ // A replay of a reply that sent its files answers that delivery without reading them again:
251
+ // they may since be gone, which must not refuse what was already sent.
252
+ const earlier = files.length === 0 ? undefined : yield* earlierAgentReply(transport, prepared);
334
253
  if (earlier !== undefined) {
335
254
  return {
336
255
  status: earlier.status,
337
- text,
338
256
  messageId: earlier.messageId,
339
257
  duplicate: true,
340
- ...(recipients === undefined ? {} : { recipients }),
341
- ...(files.length === 0 && send.files === undefined ? {} : { files }),
258
+ ...(earlier.refusal === undefined ? {} : { refusal: earlier.refusal }),
342
259
  };
343
260
  }
344
261
  // Each file as its person may read it now, the revision held: everything that can fail is
345
262
  // read before the claim, so a refusal spends none.
346
263
  const sendFiles = yield* readDraftFiles({
347
264
  backend,
348
- person,
265
+ person: reply.person,
349
266
  files,
350
- fetch: input.fetch ?? fetch,
267
+ fetch: transport.fetch ?? fetch,
351
268
  ...(provider.files?.transfer === undefined ? {} : { transfer: provider.files.transfer }),
352
269
  });
353
270
  if (sendFiles === undefined) {
354
- return yield* refused("file_unavailable", providerName);
271
+ return yield* refused("file_unavailable", reply.channel);
355
272
  }
356
273
  const reservation = archive({
357
274
  event,
358
275
  delivery: { phase: "reserve", scope, key, fingerprint },
359
- identityToken: input.identityToken,
276
+ identityToken: transport.identityToken,
360
277
  }).pipe(Effect.tapError((error) => report("reserve", error)), Effect.mapError((cause) => new ActionRejected({
361
278
  cause,
362
279
  message: cause.diagnostic === "chat_archive_conflict"
@@ -364,119 +281,56 @@ export function reviewSender(input) {
364
281
  "or to other people; it is never sent again."
365
282
  : "The delivery could not be reserved, and nothing was sent. Approve again.",
366
283
  })));
367
- const reserveDraft = backend.agents?.reserveDraft;
368
- let reserve;
369
- if (onStore && reserveDraft !== undefined) {
370
- // Under the draft's lock, in the reservation's transaction: the draft still waits, a
371
- // redraft asked for is dropped, and with unlessNewer the person has not written since.
372
- const reserved = yield* reserveDraft({
373
- review: send.review,
374
- principalId: principal.id,
375
- unlessNewer: send.unlessNewer === true,
376
- reserve: reservation,
377
- claimOf: (receipt) => (receipt.claimed ? receipt.claimId : undefined),
378
- });
379
- switch (reserved.kind) {
380
- case "reserved":
381
- reserve = reserved.value;
382
- break;
383
- case "missing":
384
- return yield* new ActionRejected({ message: "The draft does not exist." });
385
- case "decided":
386
- return yield* new ActionRejected({
387
- message: `The reply was decided meanwhile (${reserved.status}); nothing was sent.`,
388
- refusal: "draft_decided",
389
- });
390
- case "redrafted":
391
- return yield* new ActionRejected({
392
- message: "The reply was redrafted meanwhile; approve the redraft instead.",
393
- });
394
- case "newer":
395
- return yield* new ActionRejected({
396
- message: reserved.newer === true
397
- ? "The person wrote after the turn that wrote the reply; nothing was sent."
398
- : "Whether the person wrote after the reply cannot be told; nothing was sent.",
399
- refusal: reserved.newer === true ? "newer_message" : "basis_unknown",
400
- });
401
- }
402
- }
403
- else {
404
- // Without the chat store, whether the person wrote since cannot be told.
405
- if (send.unlessNewer === true) {
406
- return yield* new ActionRejected({
407
- message: "Whether the person wrote after the reply cannot be told; nothing was sent.",
408
- refusal: "basis_unknown",
409
- });
410
- }
411
- // A redraft asked for is dropped before anything is sent, under the review's lock: one
412
- // that already replaced the reply leaves nothing to approve, and none arriving later
413
- // replaces it.
414
- const keeps = yield* backend.agents?.cancelRevision?.({ review: send.review }) ??
415
- Effect.succeed(true);
416
- if (!keeps) {
417
- return yield* new ActionRejected({
418
- message: "The reply was redrafted meanwhile; approve the redraft instead.",
419
- });
420
- }
421
- reserve = yield* reservation;
422
- }
284
+ const reserved = yield* reserve(reservation, onStore);
423
285
  const message = onStore
424
- ? reserve.claimed
425
- ? (reserve.claimId ?? null)
426
- : typeof review.message === "string"
427
- ? review.message
428
- : null
286
+ ? reserved.claimed
287
+ ? (reserved.claimId ?? null)
288
+ : (reply.message ?? null)
429
289
  : null;
430
- if (!reserve.claimed) {
431
- if (reserve.version !== 1 || !reserve.duplicate || reserve.claimId !== undefined) {
290
+ if (!reserved.claimed) {
291
+ if (reserved.version !== 1 || !reserved.duplicate || reserved.claimId !== undefined) {
432
292
  return yield* new ActionRejected({
433
293
  message: "The archive did not return a valid delivery receipt.",
434
294
  });
435
295
  }
436
296
  return {
437
- status: reserve.status,
438
- text,
439
- messageId: reserve.messageId,
297
+ status: reserved.status,
298
+ messageId: reserved.messageId,
440
299
  duplicate: true,
441
300
  ...(message === null ? {} : { message }),
442
- ...(recipients === undefined ? {} : { recipients }),
443
- ...(files.length === 0 && send.files === undefined ? {} : { files }),
301
+ ...(reserved.refusal === undefined ? {} : { refusal: reserved.refusal }),
444
302
  };
445
303
  }
446
- if (reserve.version !== 1 ||
447
- reserve.duplicate ||
448
- !reserve.claimId ||
449
- reserve.operationId !== operationId ||
450
- reserve.status !== "uncertain" ||
451
- reserve.messageId !== null) {
304
+ if (reserved.version !== 1 ||
305
+ reserved.duplicate ||
306
+ !reserved.claimId ||
307
+ reserved.operationId !== operationId ||
308
+ reserved.status !== "uncertain" ||
309
+ reserved.messageId !== null) {
452
310
  return yield* new ActionRejected({
453
311
  message: "The archive did not grant a fresh delivery claim.",
454
312
  });
455
313
  }
456
314
  const outcome = yield* provider.send({
457
- destination: target,
458
- connection,
459
- text,
315
+ destination: prepared.target,
316
+ connection: prepared.connection,
317
+ text: reply.text,
460
318
  separator: "",
461
319
  attribution: "",
462
- finalText,
463
- plainText,
464
- replyTo,
465
- threadId,
320
+ finalText: prepared.finalText,
321
+ plainText: prepared.plainText,
322
+ replyTo: prepared.replyTo,
323
+ threadId: reply.threadId !== null && reply.threadId !== "" ? reply.threadId : null,
466
324
  operationId,
467
- chatId,
325
+ chatId: reply.chatId,
468
326
  ...(sendFiles.length === 0 ? {} : { files: sendFiles }),
469
- ...(recipients === undefined ? {} : { recipients }),
470
- ...(input.agent === undefined ? {} : { agent: input.agent }),
471
- ...(signsMail(input.ontology.manifest, providerName) ? { signature: true } : {}),
472
- ...(input.previews === undefined ? {} : { previews: input.previews }),
473
- transport: input.connections({
474
- identityToken: input.identityToken,
475
- audit: {
476
- action: "agent_draft.approve",
477
- principalId: principal.id,
478
- requestId: input.requestId,
479
- },
327
+ ...(reply.recipients === undefined ? {} : { recipients: reply.recipients }),
328
+ ...(transport.agent === undefined ? {} : { agent: transport.agent }),
329
+ ...(signsMail(transport.ontology.manifest, reply.channel) ? { signature: true } : {}),
330
+ ...(transport.previews === undefined ? {} : { previews: transport.previews }),
331
+ transport: transport.connections({
332
+ identityToken: transport.identityToken,
333
+ audit: { ...reply.audit, requestId: transport.requestId },
480
334
  }),
481
335
  });
482
336
  if (outcome.cause !== undefined) {
@@ -491,20 +345,263 @@ export function reviewSender(input) {
491
345
  messageId: outcome.messageId,
492
346
  url: outcome.url,
493
347
  },
494
- delivery: { phase: "receipt", scope, key, fingerprint, claimId: reserve.claimId },
495
- identityToken: input.identityToken,
348
+ delivery: { phase: "receipt", scope, key, fingerprint, claimId: reserved.claimId },
349
+ identityToken: transport.identityToken,
496
350
  }).pipe(Effect.exit);
497
351
  if (saved._tag === "Failure") {
498
352
  yield* report("receipt", saved.cause);
499
353
  }
500
354
  return {
501
355
  status: outcome.status,
502
- text,
503
356
  messageId: outcome.messageId,
504
357
  duplicate: false,
505
358
  ...(message === null ? {} : { message }),
359
+ ...(outcome.status === "failed" && outcome.refusal !== undefined
360
+ ? { refusal: outcome.refusal }
361
+ : {}),
362
+ };
363
+ });
364
+ }
365
+ /**
366
+ * Sends a reply the agent held for review, once a member approved it: the draft or the member's
367
+ * edit, to the person's chat through the ontology's chat connection of the channel the chat is on,
368
+ * as the agent and without attribution. A reply to mail goes to the review's `to` and `cc`, or the
369
+ * addresses the member names in their place. The delivery's claim, on the reply's row of the
370
+ * workspace chat store, keyed by the review and not by the member, makes it at most once: a replay
371
+ * of the same approval returns the delivery, and a different approval, by another member, with
372
+ * another text or to other people, is refused. A provider that refused it consumes the claim: the
373
+ * reply is never sent again.
374
+ */
375
+ export function reviewSender(input) {
376
+ const { backend, principal } = input;
377
+ return (send) => Effect.gen(function* () {
378
+ // A role may hold the approval within a scope. The send happens before the action's
379
+ // transaction, whose write guard comes too late for it: a review outside the scope is
380
+ // refused here, read through the approval's own scope.
381
+ const approvable = effectiveScope("agent_draft:approve", principal);
382
+ if (approvable !== undefined) {
383
+ yield* backend
384
+ .get({
385
+ entity: "agent_draft",
386
+ id: send.review,
387
+ reader: {
388
+ ...principal,
389
+ permissions: ["agent_draft:read"],
390
+ scopes: [{ permission: "agent_draft:read", where: approvable }],
391
+ },
392
+ })
393
+ .pipe(Effect.mapError(() => new PermissionDenied({
394
+ message: "The draft is outside the records agent_draft:approve covers.",
395
+ permission: "agent_draft:approve",
396
+ })));
397
+ }
398
+ const review = yield* backend
399
+ .get({ entity: "agent_draft", id: send.review })
400
+ .pipe(Effect.mapError(() => new ActionRejected({ message: "The draft does not exist." })));
401
+ const draft = String(review.draft ?? "");
402
+ const text = send.text ?? draft;
403
+ const status = String(review.status);
404
+ const email = String(review.channel_kind) === "email";
405
+ // Only a reply to mail names whom it goes to beside its chat.
406
+ if (!email && (send.to !== undefined || send.cc !== undefined)) {
407
+ return yield* new ActionRejected({
408
+ message: "Only a reply to mail takes to and cc; this reply goes to its chat.",
409
+ });
410
+ }
411
+ // A reply to mail goes to the review's `to` and `cc`, the thread's people, unless the member
412
+ // names others; one held before replies named them goes to its recipient alone.
413
+ const held = addressesOfDraft(review.to);
414
+ const recipients = email
415
+ ? yield* Effect.try({
416
+ try: () => emailRecipients({
417
+ to: send.to ??
418
+ (held.length > 0
419
+ ? held
420
+ : typeof review.recipient === "string"
421
+ ? [review.recipient]
422
+ : []),
423
+ cc: send.cc ?? addressesOfDraft(review.cc),
424
+ }),
425
+ catch: (cause) => new ActionRejected({
426
+ message: `A reply to mail goes to 1 to ${EMAIL_RECIPIENTS_LIMIT} plain addresses ` +
427
+ "together, in to and cc; nothing was sent.",
428
+ cause,
429
+ }),
430
+ })
431
+ : undefined;
432
+ const heldFiles = draftFilesOf(review.files);
433
+ // An approval may leave files out, never add one: each it names is one the draft holds.
434
+ const files = send.files === undefined
435
+ ? heldFiles
436
+ : heldFiles.filter((file) => send.files.some((named) => named.entity === file.entity &&
437
+ named.id.toLowerCase() === file.id &&
438
+ named.property === file.property &&
439
+ named.revisionId === file.revisionId));
440
+ if (send.files !== undefined && files.length !== send.files.length) {
441
+ return yield* new ActionRejected({
442
+ message: "An approval sends only files the draft holds; nothing was sent.",
443
+ refusal: "file_not_held",
444
+ });
445
+ }
446
+ if (status !== "pending") {
447
+ if ((status === "sent" || status === "uncertain") &&
448
+ text === review.text &&
449
+ (recipients === undefined || sameRecipients(recipients, review)) &&
450
+ // The draft keeps the files it sent: another choice of them is another approval.
451
+ (send.files === undefined || files.length === heldFiles.length)) {
452
+ return {
453
+ status,
454
+ text,
455
+ messageId: typeof review.message_id === "string" ? review.message_id : null,
456
+ duplicate: true,
457
+ ...(typeof review.message === "string" ? { message: review.message } : {}),
458
+ ...(recipients === undefined ? {} : { recipients }),
459
+ ...(files.length === 0 && send.files === undefined ? {} : { files }),
460
+ };
461
+ }
462
+ return yield* new ActionRejected({
463
+ message: status === "rejected" || status === "dismissed"
464
+ ? `The reply was ${status}; it is never sent.`
465
+ : "The reply was already approved; it is never sent again.",
466
+ refusal: "draft_decided",
467
+ });
468
+ }
469
+ const operationId = String(review.id);
470
+ const person = typeof review.person_id === "string" ? review.person_id : null;
471
+ const prepared = yield* prepareAgentReply(input, {
472
+ // The channel the chat is on, by name. A review held before channels had names has none:
473
+ // it is on the channel named after its kind.
474
+ // @legacy ontology.reviews-without-channel
475
+ channel: typeof review.channel === "string" && review.channel !== ""
476
+ ? review.channel
477
+ : String(review.channel_kind),
478
+ channelKind: String(review.channel_kind),
479
+ declared: true,
480
+ chatId: String(review.chat_id),
481
+ recipient: typeof review.recipient === "string" ? review.recipient : null,
482
+ chatKind: review.chat_kind === "group" ? "group" : "private",
483
+ threadId: typeof review.thread_id === "string" ? review.thread_id : null,
484
+ replyTo: typeof review.reply_to === "string" ? review.reply_to : null,
485
+ text,
486
+ textLimit: AGENT_DRAFT_TEXT_LIMIT,
487
+ files,
488
+ ...(recipients === undefined ? {} : { recipients }),
489
+ person,
490
+ participants: participantsOfDraft(review.participants),
491
+ // The agent's session holds its draft: the session sees an edit, a redraft it never wrote,
492
+ // and a reply sent without some of its files as a message it did not write, and its own
493
+ // draft sent as written as its own.
494
+ sessionId: text === draft &&
495
+ files.length === heldFiles.length &&
496
+ (review.revises_id === null || review.revises_id === undefined) &&
497
+ typeof review.session_id === "string"
498
+ ? review.session_id
499
+ : null,
500
+ turnId: null,
501
+ operationId,
502
+ // The delivery keys keep the entity's first name: a renamed key would send an approval again.
503
+ subject: `agent_review:${operationId}`,
504
+ requester: approver(backend, principal),
505
+ audit: { action: "agent_draft.approve", principalId: principal.id },
506
+ ...(typeof review.message === "string" ? { message: review.message } : {}),
507
+ rejection: (provider, limit) => `The reply is empty or longer than ${limit} characters, which ` +
508
+ `${provider} accepts in one message. Approve it with a shorter text; nothing was ` +
509
+ "sent or truncated.",
510
+ });
511
+ const delivered = yield* deliverAgentReply(input, prepared, (reservation, onStore) => approved(backend, send, principal, reservation, onStore));
512
+ return {
513
+ status: delivered.status,
514
+ text,
515
+ messageId: delivered.messageId,
516
+ duplicate: delivered.duplicate,
517
+ ...(delivered.message === undefined ? {} : { message: delivered.message }),
506
518
  ...(recipients === undefined ? {} : { recipients }),
507
519
  ...(files.length === 0 && send.files === undefined ? {} : { files }),
508
520
  };
509
521
  });
510
522
  }
523
+ /** Who approved a draft, as the archive records its sender; the person never sees it. */
524
+ function approver(backend, principal) {
525
+ return Effect.gen(function* () {
526
+ // A guest is no user; `agent_draft` is not theirs to approve.
527
+ if (principal.kind === "guest") {
528
+ return yield* new PermissionDenied({ message: "The approver is unknown." });
529
+ }
530
+ const user = yield* backend
531
+ .get({ entity: "user", id: principal.id })
532
+ .pipe(Effect.mapError(() => new PermissionDenied({ message: "The approver is unknown." })));
533
+ if (user.active !== true) {
534
+ return yield* new PermissionDenied({ message: "The approver is inactive." });
535
+ }
536
+ const name = String(user.name ?? "").trim() || principal.id;
537
+ return {
538
+ id: principal.id,
539
+ kind: principal.kind,
540
+ name,
541
+ via: principal.kind === "service" ? "service" : "hq",
542
+ clientId: null,
543
+ clientName: null,
544
+ attribution: name,
545
+ };
546
+ });
547
+ }
548
+ /**
549
+ * An approval's claim: under the draft's lock, in the reservation's transaction, on the chat
550
+ * store; before it, once a redraft asked for is dropped.
551
+ */
552
+ function approved(backend, send, principal, reservation, onStore) {
553
+ return Effect.gen(function* () {
554
+ const reserveDraft = backend.agents?.reserveDraft;
555
+ if (onStore && reserveDraft !== undefined) {
556
+ // Under the draft's lock, in the reservation's transaction: the draft still waits, a
557
+ // redraft asked for is dropped, and with unlessNewer the person has not written since.
558
+ const reserved = yield* reserveDraft({
559
+ review: send.review,
560
+ principalId: principal.id,
561
+ unlessNewer: send.unlessNewer === true,
562
+ reserve: reservation,
563
+ claimOf: (receipt) => (receipt.claimed ? receipt.claimId : undefined),
564
+ });
565
+ switch (reserved.kind) {
566
+ case "reserved":
567
+ return reserved.value;
568
+ case "missing":
569
+ return yield* new ActionRejected({ message: "The draft does not exist." });
570
+ case "decided":
571
+ return yield* new ActionRejected({
572
+ message: `The reply was decided meanwhile (${reserved.status}); nothing was sent.`,
573
+ refusal: "draft_decided",
574
+ });
575
+ case "redrafted":
576
+ return yield* new ActionRejected({
577
+ message: "The reply was redrafted meanwhile; approve the redraft instead.",
578
+ });
579
+ case "newer":
580
+ return yield* new ActionRejected({
581
+ message: reserved.newer === true
582
+ ? "The person wrote after the turn that wrote the reply; nothing was sent."
583
+ : "Whether the person wrote after the reply cannot be told; nothing was sent.",
584
+ refusal: reserved.newer === true ? "newer_message" : "basis_unknown",
585
+ });
586
+ }
587
+ }
588
+ // Without the chat store, whether the person wrote since cannot be told.
589
+ if (send.unlessNewer === true) {
590
+ return yield* new ActionRejected({
591
+ message: "Whether the person wrote after the reply cannot be told; nothing was sent.",
592
+ refusal: "basis_unknown",
593
+ });
594
+ }
595
+ // A redraft asked for is dropped before anything is sent, under the review's lock: one
596
+ // that already replaced the reply leaves nothing to approve, and none arriving later
597
+ // replaces it.
598
+ const keeps = yield* backend.agents?.cancelRevision?.({ review: send.review }) ??
599
+ Effect.succeed(true);
600
+ if (!keeps) {
601
+ return yield* new ActionRejected({
602
+ message: "The reply was redrafted meanwhile; approve the redraft instead.",
603
+ });
604
+ }
605
+ return yield* reservation;
606
+ });
607
+ }