@segmentstream/ontology 0.160.0 → 0.162.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import { Effect } from "effect";
2
- import { addressesOfDraft, AGENT_DRAFT_TEXT_LIMIT, participantsOfDraft, } from "../../agent-draft.js";
2
+ import { addressesOfDraft, AGENT_DRAFT_TEXT_LIMIT, draftFilesOf, participantsOfDraft, } from "../../agent-draft.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";
@@ -8,7 +8,8 @@ import { deliveryFingerprint, deliveryKeyDigest, deliveryScopeDigest } from "./i
8
8
  import { WORKSPACE_CHANNEL_KIND } from "../../chat-channel.js";
9
9
  import { chatRetentionDaysOf } from "../../manifest.js";
10
10
  import { channelProvider, chatConnection, chatKind } from "./providers/index.js";
11
- import { deliveryArchiveOf } from "./store-delivery.js";
11
+ import { storeDeliveryArchive } from "./store-delivery.js";
12
+ import { readDraftFiles, refuseChatFiles } from "./draft-files.js";
12
13
  /**
13
14
  * Whether a reply to mail goes to the people a review records it went to: its `to`, else its
14
15
  * recipient, and its `cc`, whatever their order and case.
@@ -19,6 +20,20 @@ function sameRecipients(recipients, review) {
19
20
  return (set(recipients.to) ===
20
21
  set(held.length > 0 ? held : typeof review.recipient === "string" ? [review.recipient] : []) && set(recipients.cc) === set(addressesOfDraft(review.cc)));
21
22
  }
23
+ /**
24
+ * A draft's files the approval cannot send, refused before anything is reserved: the code names
25
+ * why, and the draft still waits.
26
+ */
27
+ function refused(code, channel) {
28
+ return Effect.fail(new ActionRejected({
29
+ message: code === "files_unsupported"
30
+ ? `The ${channel} channel sends no files with an approved reply; nothing was sent.`
31
+ : code === "file_unavailable"
32
+ ? "A file of the reply is gone, or its person may no longer read it; nothing was sent."
33
+ : `The reply's files exceed what ${channel} sends in one reply; nothing was sent.`,
34
+ refusal: code,
35
+ }));
36
+ }
22
37
  /**
23
38
  * Sends a reply the agent held for review, once a member approved it: the draft or the member's
24
39
  * edit, to the person's chat through the ontology's chat connection of the channel the chat is on,
@@ -100,13 +115,15 @@ export function reviewSender(input) {
100
115
  text,
101
116
  messageId: typeof review.message_id === "string" ? review.message_id : null,
102
117
  duplicate: true,
118
+ ...(typeof review.message === "string" ? { message: review.message } : {}),
103
119
  ...(recipients === undefined ? {} : { recipients }),
104
120
  };
105
121
  }
106
122
  return yield* new ActionRejected({
107
- message: status === "rejected"
108
- ? "The reply was rejected; it is never sent."
123
+ message: status === "rejected" || status === "dismissed"
124
+ ? `The reply was ${status}; it is never sent.`
109
125
  : "The reply was already approved; it is never sent again.",
126
+ refusal: "draft_decided",
110
127
  });
111
128
  }
112
129
  // The channel the chat is on, by name. A review held before channels had names has none:
@@ -146,7 +163,8 @@ export function reviewSender(input) {
146
163
  try: () => provider.render(text, "", ""),
147
164
  catch: (cause) => new ActionRejected({ message: "The Markdown could not be rendered.", cause }),
148
165
  });
149
- if (text.trim() === "" ||
166
+ const files = draftFilesOf(review.files);
167
+ if ((text.trim() === "" && files.length === 0) ||
150
168
  text.length > AGENT_DRAFT_TEXT_LIMIT ||
151
169
  finalText.length > provider.limit ||
152
170
  plainText.length > provider.limit ||
@@ -158,6 +176,11 @@ export function reviewSender(input) {
158
176
  "sent or truncated.",
159
177
  });
160
178
  }
179
+ // The files the channel cannot send are refused before anything is reserved: no claim spent.
180
+ const filesRefusal = refuseChatFiles(provider, files);
181
+ if (filesRefusal !== undefined) {
182
+ return yield* refused(filesRefusal, providerName);
183
+ }
161
184
  // A guest is no user; `agent_draft` is not theirs to approve.
162
185
  if (principal.kind === "guest") {
163
186
  return yield* new PermissionDenied({ message: "The approver is unknown." });
@@ -221,7 +244,8 @@ export function reviewSender(input) {
221
244
  recipients.to[0] === externalId.toLowerCase())
222
245
  ? recipients
223
246
  : undefined;
224
- const fingerprint = deliveryFingerprint(preview, requester, undefined, undefined, bound);
247
+ const bindings = files.map((file) => [file.entity, file.id, file.property, file.revisionId]);
248
+ const fingerprint = deliveryFingerprint(preview, requester, undefined, undefined, bound, bindings.length === 0 ? undefined : bindings);
225
249
  const event = {
226
250
  eventId: `chat-delivery:${operationId}:reserve`,
227
251
  operationId,
@@ -251,23 +275,65 @@ export function reviewSender(input) {
251
275
  toolName: null,
252
276
  argsSummary: JSON.stringify(provider.payload(finalText)),
253
277
  status: "requested",
254
- attachments: [],
278
+ // The files as the chat's history shows them, as the agent's own sends record them.
279
+ attachments: files.map((file, index) => ({
280
+ id: `chat-delivery:${operationId}:file:${index}`,
281
+ kind: "file",
282
+ filename: file.filename,
283
+ contentType: file.contentType,
284
+ size: file.size,
285
+ })),
286
+ ...(bindings.length === 0 ? {} : { files: bindings }),
255
287
  requestedBy: requester,
256
288
  url: null,
257
289
  at: new Date().toISOString(),
258
290
  };
259
- // A redraft asked for is dropped before anything is sent, under the review's lock: one that
260
- // already replaced the reply leaves nothing to approve, and none arriving later replaces it.
261
- const keeps = yield* backend.agents?.cancelRevision?.({ review: send.review }) ??
262
- Effect.succeed(true);
263
- if (!keeps) {
264
- return yield* new ActionRejected({
265
- message: "The reply was redrafted meanwhile; approve the redraft instead.",
266
- });
267
- }
291
+ const store = backend.agents?.chatMessages;
268
292
  // The review's claim and receipt live on the workspace chat store once it holds a message.
269
- const archive = yield* deliveryArchiveOf(backend, input.cloud, chatRetentionDaysOf(input.ontology.manifest));
270
- const reserve = yield* archive({
293
+ // @legacy agent.cloud-chat-archive Until then, the chat archive in Cloud holds them.
294
+ const onStore = store !== undefined && (yield* store.holds());
295
+ const archive = onStore
296
+ ? storeDeliveryArchive(store, chatRetentionDaysOf(input.ontology.manifest))
297
+ : input.cloud;
298
+ // Files go only through the workspace chat store: the archive in Cloud is not extended.
299
+ // @legacy agent.cloud-chat-archive
300
+ if (files.length > 0 && !onStore) {
301
+ return yield* refused("files_unsupported", providerName);
302
+ }
303
+ // A replay of an approval that sent its files answers that delivery without reading them
304
+ // again: they may since be gone, which must not refuse what was already sent.
305
+ const earlier = files.length === 0 || archive.find === undefined
306
+ ? undefined
307
+ : yield* archive
308
+ .find({ delivery: { scope, key, fingerprint }, identityToken: input.identityToken })
309
+ .pipe(Effect.tapError((error) => report("find", error)), Effect.mapError((cause) => new ActionRejected({
310
+ cause,
311
+ message: cause.diagnostic === "chat_archive_conflict"
312
+ ? "The reply was already approved by another member, with another " +
313
+ "text or to other people; it is never sent again."
314
+ : "The delivery could not be read, and nothing was sent. Approve again.",
315
+ })));
316
+ if (earlier !== undefined) {
317
+ return {
318
+ status: earlier.status,
319
+ text,
320
+ messageId: earlier.messageId,
321
+ duplicate: true,
322
+ ...(recipients === undefined ? {} : { recipients }),
323
+ };
324
+ }
325
+ // Each file as its person may read it now, the revision held: everything that can fail is
326
+ // read before the claim, so a refusal spends none.
327
+ const sendFiles = yield* readDraftFiles({
328
+ backend,
329
+ person,
330
+ files,
331
+ fetch: input.fetch ?? fetch,
332
+ });
333
+ if (sendFiles === undefined) {
334
+ return yield* refused("file_unavailable", providerName);
335
+ }
336
+ const reservation = archive({
271
337
  event,
272
338
  delivery: { phase: "reserve", scope, key, fingerprint },
273
339
  identityToken: input.identityToken,
@@ -278,6 +344,69 @@ export function reviewSender(input) {
278
344
  "or to other people; it is never sent again."
279
345
  : "The delivery could not be reserved, and nothing was sent. Approve again.",
280
346
  })));
347
+ const reserveDraft = backend.agents?.reserveDraft;
348
+ let reserve;
349
+ if (onStore && reserveDraft !== undefined) {
350
+ // Under the draft's lock, in the reservation's transaction: the draft still waits, a
351
+ // redraft asked for is dropped, and with unlessNewer the person has not written since.
352
+ const reserved = yield* reserveDraft({
353
+ review: send.review,
354
+ principalId: principal.id,
355
+ unlessNewer: send.unlessNewer === true,
356
+ reserve: reservation,
357
+ claimOf: (receipt) => (receipt.claimed ? receipt.claimId : undefined),
358
+ });
359
+ switch (reserved.kind) {
360
+ case "reserved":
361
+ reserve = reserved.value;
362
+ break;
363
+ case "missing":
364
+ return yield* new ActionRejected({ message: "The draft does not exist." });
365
+ case "decided":
366
+ return yield* new ActionRejected({
367
+ message: `The reply was decided meanwhile (${reserved.status}); nothing was sent.`,
368
+ refusal: "draft_decided",
369
+ });
370
+ case "redrafted":
371
+ return yield* new ActionRejected({
372
+ message: "The reply was redrafted meanwhile; approve the redraft instead.",
373
+ });
374
+ case "newer":
375
+ return yield* new ActionRejected({
376
+ message: reserved.newer === true
377
+ ? "The person wrote after the turn that wrote the reply; nothing was sent."
378
+ : "Whether the person wrote after the reply cannot be told; nothing was sent.",
379
+ refusal: reserved.newer === true ? "newer_message" : "basis_unknown",
380
+ });
381
+ }
382
+ }
383
+ else {
384
+ // Without the chat store, whether the person wrote since cannot be told.
385
+ if (send.unlessNewer === true) {
386
+ return yield* new ActionRejected({
387
+ message: "Whether the person wrote after the reply cannot be told; nothing was sent.",
388
+ refusal: "basis_unknown",
389
+ });
390
+ }
391
+ // A redraft asked for is dropped before anything is sent, under the review's lock: one
392
+ // that already replaced the reply leaves nothing to approve, and none arriving later
393
+ // replaces it.
394
+ const keeps = yield* backend.agents?.cancelRevision?.({ review: send.review }) ??
395
+ Effect.succeed(true);
396
+ if (!keeps) {
397
+ return yield* new ActionRejected({
398
+ message: "The reply was redrafted meanwhile; approve the redraft instead.",
399
+ });
400
+ }
401
+ reserve = yield* reservation;
402
+ }
403
+ const message = onStore
404
+ ? reserve.claimed
405
+ ? (reserve.claimId ?? null)
406
+ : typeof review.message === "string"
407
+ ? review.message
408
+ : null
409
+ : null;
281
410
  if (!reserve.claimed) {
282
411
  if (reserve.version !== 1 || !reserve.duplicate || reserve.claimId !== undefined) {
283
412
  return yield* new ActionRejected({
@@ -289,6 +418,7 @@ export function reviewSender(input) {
289
418
  text,
290
419
  messageId: reserve.messageId,
291
420
  duplicate: true,
421
+ ...(message === null ? {} : { message }),
292
422
  ...(recipients === undefined ? {} : { recipients }),
293
423
  };
294
424
  }
@@ -314,6 +444,7 @@ export function reviewSender(input) {
314
444
  threadId,
315
445
  operationId,
316
446
  chatId,
447
+ ...(sendFiles.length === 0 ? {} : { files: sendFiles }),
317
448
  ...(recipients === undefined ? {} : { recipients }),
318
449
  ...(input.agent === undefined ? {} : { agent: input.agent }),
319
450
  ...(input.previews === undefined ? {} : { previews: input.previews }),
@@ -349,6 +480,7 @@ export function reviewSender(input) {
349
480
  text,
350
481
  messageId: outcome.messageId,
351
482
  duplicate: false,
483
+ ...(message === null ? {} : { message }),
352
484
  ...(recipients === undefined ? {} : { recipients }),
353
485
  };
354
486
  });
@@ -52,6 +52,8 @@ function payloadFingerprint(event) {
52
52
  requester.clientName,
53
53
  requester.attribution,
54
54
  ],
55
+ // A message's files bind it only when it has some, so a text's binding stays.
56
+ ...(event.files === undefined || event.files.length === 0 ? [] : [{ files: event.files }]),
55
57
  ]);
56
58
  }
57
59
  function object(value) {
@@ -169,6 +171,17 @@ export function storeDeliveryArchive(store, retentionDays) {
169
171
  : {}),
170
172
  ...(event.replyToMessageId === null ? {} : { replyTo: event.replyToMessageId }),
171
173
  text: event.text,
174
+ // A message's files as its history shows them, as the agent records the files it sends.
175
+ ...(event.attachments.length === 0
176
+ ? {}
177
+ : {
178
+ files: event.attachments.map((file) => ({
179
+ id: file.id,
180
+ name: file.filename,
181
+ type: file.contentType,
182
+ size: file.size,
183
+ })),
184
+ }),
172
185
  at: event.at,
173
186
  // Before the provider is called: the receipt settles it, a lost one leaves it unsent.
174
187
  status: "pending",
@@ -1,3 +1,4 @@
1
+ import type { AgentDraftFile } from "../agent-draft.js";
1
2
  import type { ActionRuntime } from "../runtime-source.js";
2
3
  import type { ConfirmationStore } from "../runtime/confirmations.js";
3
4
  import { Context, Schema, type Effect, type Layer, type Redacted } from "effect";
@@ -718,6 +719,27 @@ export interface AgentStore {
718
719
  readonly cancelRevision?: (input: {
719
720
  readonly review: string;
720
721
  }) => Effect.Effect<boolean>;
722
+ /**
723
+ * Reserves an approved draft's delivery under the draft's lock, in one transaction with
724
+ * `reserve`, the reservation on the chat store: the draft must still wait, a redraft asked for is
725
+ * dropped, and with `unlessNewer` the person must not have written after the draft's turn. Once
726
+ * `reserve` claims the delivery, the draft names its message, `claimOf` of what `reserve`
727
+ * answered, so that a rejection or a dismissal after it is refused. A draft whose delivery is
728
+ * reserved already passes to `reserve` unchecked, which answers its receipt. Absent on stores
729
+ * that predate it.
730
+ */
731
+ readonly reserveDraft?: <A, E>(input: {
732
+ readonly review: string;
733
+ readonly principalId: string;
734
+ readonly unlessNewer: boolean;
735
+ readonly reserve: Effect.Effect<A, E>;
736
+ readonly claimOf: (reserved: A) => string | undefined;
737
+ }) => Effect.Effect<DraftReservation<A>, E>;
738
+ /** Whether the person wrote after each draft's turn; `null` where it cannot be told. */
739
+ readonly draftsNewer?: (drafts: ReadonlyArray<string>) => Effect.Effect<ReadonlyArray<{
740
+ readonly draft: string;
741
+ readonly newer: boolean | null;
742
+ }>>;
721
743
  /** Records that the agent could not redraft a reply; false when it is no longer the redraft asked for. */
722
744
  readonly failRevision?: (input: {
723
745
  readonly review: string;
@@ -745,6 +767,25 @@ export interface AgentStore {
745
767
  /** The chats' messages, in `_chat_messages`. Absent on stores that predate the chat store. */
746
768
  readonly chatMessages?: import("../runtime/chat-messages.js").ChatMessageStore;
747
769
  }
770
+ /**
771
+ * What reserving an approved draft's delivery came to: `reserved` with what the reservation answered,
772
+ * or refused before anything was reserved: the draft is gone or `decided`, a redraft replaced it,
773
+ * or with `unlessNewer` the person wrote after its turn (`newer` true) or that cannot be told (null).
774
+ */
775
+ export type DraftReservation<A> = {
776
+ readonly kind: "reserved";
777
+ readonly value: A;
778
+ } | {
779
+ readonly kind: "missing";
780
+ } | {
781
+ readonly kind: "decided";
782
+ readonly status: string;
783
+ } | {
784
+ readonly kind: "redrafted";
785
+ } | {
786
+ readonly kind: "newer";
787
+ readonly newer: true | null;
788
+ };
748
789
  /** A reply the agent held for review, as `POST /api/ontology/agent/drafts` reports it. */
749
790
  export interface HeldReplyInput {
750
791
  readonly key: string;
@@ -769,8 +810,12 @@ export interface HeldReplyInput {
769
810
  readonly memberId: string;
770
811
  readonly sessionId: string;
771
812
  readonly text: string;
813
+ /** Record files the reply carries, as the person could read them when it was held. */
814
+ readonly files?: ReadonlyArray<AgentDraftFile>;
772
815
  readonly mode: "always" | "whenUnsure";
773
816
  readonly confidence: number | null;
817
+ /** The agent's turn that wrote the reply; absent from agents that predate it. */
818
+ readonly turnId?: string;
774
819
  }
775
820
  /** A reply the agent redrafted, as `POST /api/ontology/agent/drafts/revision` reports it. */
776
821
  export interface RevisedReplyInput {
@@ -614,7 +614,7 @@ export const ErrorSchemas = {
614
614
  limit: Schema.optionalKey(LimitErrorWire),
615
615
  // The idempotency key is spent on an operation that did not happen: retry with a new one.
616
616
  key_consumed: Schema.optionalKey(Schema.Literal(true)),
617
- // Why a chat's provider refused a message, such as outside_reply_window.
617
+ // Why a message or a draft was refused, such as outside_reply_window or newer_message.
618
618
  refusal: Schema.optionalKey(Schema.String),
619
619
  }),
620
620
  rateLimited: errorBody("RateLimited", 429, ["rate_limited"]),
@@ -427,6 +427,7 @@ export function createOntologyService(ontology, config) {
427
427
  deploymentId: deployment.deploymentId,
428
428
  }),
429
429
  emailSignUp: signUpRolesOf(ontology.manifest, "email") !== undefined,
430
+ manifest: ontology.manifest,
430
431
  emailCodes,
431
432
  cronSecret: config.cronSecret,
432
433
  chatRetentionDays: chatRetentionDaysOf(ontology.manifest),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.160.0",
3
+ "version": "0.162.0",
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",