@segmentstream/ontology 0.180.0 → 0.181.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,23 +1,45 @@
1
1
  import { Effect } from "effect";
2
- import { type ChatMessageStore } from "../../runtime/chat-messages.js";
2
+ import { type ChatMessageStore, type ChatSend } from "../../runtime/chat-messages.js";
3
3
  import type { OntologyBackend } from "../runtime-contract.js";
4
- import { type DeliveryArchive } from "./archive.js";
4
+ import { type DeliveryArchive, type DeliveryReceipt } from "./archive.js";
5
5
  /**
6
6
  * A delivery's key on the store: one per caller scope and idempotency key, an opaque digest of
7
7
  * both, so neither digest is shown to the chat's readers. No channel's queue of sends due holds it.
8
8
  */
9
9
  export declare function deliveryOperation(scope: string, key: string): string;
10
+ /** The whole reply a proposal's first message belongs to, as its row keeps it; none otherwise. */
11
+ export declare function sendBinding(row: ChatSend): string | undefined;
12
+ /**
13
+ * What a key's delivery answers, from its row. Reported, a `sent` receipt whose message the
14
+ * provider later reported failed reads `failed` with its refusal; the receipt phase reads the
15
+ * receipt as recorded, which its caller compares with its own outcome. `operation` names the
16
+ * attempt that reserved it where the row no longer does, its `meta` gone with a deletion or
17
+ * retention. A row past `retentionDays` or scrubbed to its tombstone answers its outcome without
18
+ * its message.
19
+ */
20
+ export declare function storedReceipt(row: ChatSend, input: {
21
+ readonly operation: string;
22
+ readonly retentionDays: number;
23
+ readonly reported: boolean;
24
+ readonly inserted?: boolean;
25
+ }): DeliveryReceipt;
10
26
  /**
11
27
  * The delivery archive on the workspace chat store, by the chat archive in Cloud's protocol: the
12
28
  * first reservation of a key is `claimed` with the row's id as its claim; a replay with the same
13
29
  * request claims nothing and answers the row's receipt, and another request is a conflict. Only
14
30
  * 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.
31
+ * `retentionDays` or scrubbed to its tombstone answers its outcome without its message. A `sent`
32
+ * receipt names the provider's id of the message, unless `unnamedSends`: the channel's provider may
33
+ * take a message without naming it, as a workspace channel's code may.
16
34
  */
17
- export declare function storeDeliveryArchive(store: ChatMessageStore, retentionDays: number): DeliveryArchive;
35
+ export declare function storeDeliveryArchive(store: ChatMessageStore, retentionDays: number, options?: {
36
+ readonly unnamedSends?: boolean;
37
+ }): DeliveryArchive;
18
38
  /**
19
39
  * Where a delivery reserves and receipts its key: the workspace chat store once it holds a message,
20
40
  * the evidence that the agent records there, as a chat's history is imported there from then on.
21
41
  * `cloud` is the chat archive in Cloud, which takes the deliveries until then.
22
42
  */
23
- export declare function deliveryArchiveOf(backend: OntologyBackend["Service"], cloud: DeliveryArchive, retentionDays: number): Effect.Effect<DeliveryArchive>;
43
+ export declare function deliveryArchiveOf(backend: OntologyBackend["Service"], cloud: DeliveryArchive, retentionDays: number, options?: {
44
+ readonly unnamedSends?: boolean;
45
+ }): Effect.Effect<DeliveryArchive>;
@@ -61,6 +61,11 @@ function object(value) {
61
61
  ? value
62
62
  : undefined;
63
63
  }
64
+ /** The whole reply a proposal's first message belongs to, as its row keeps it; none otherwise. */
65
+ export function sendBinding(row) {
66
+ const binding = object(object(row.meta)?.delivery)?.binding;
67
+ return typeof binding === "string" ? binding : undefined;
68
+ }
64
69
  function claimOf(row) {
65
70
  const claim = object(object(row.meta)?.delivery);
66
71
  return {
@@ -101,43 +106,47 @@ const conflict = (reason, cause) => new DeliveryArchiveError({
101
106
  });
102
107
  /** The store could not be read or written: nothing was reserved, or the receipt is not recorded. */
103
108
  const storeFailure = (diagnostic, cause) => Effect.fail(new DeliveryArchiveError({ diagnostic, cause }));
109
+ /**
110
+ * What a key's delivery answers, from its row. Reported, a `sent` receipt whose message the
111
+ * provider later reported failed reads `failed` with its refusal; the receipt phase reads the
112
+ * receipt as recorded, which its caller compares with its own outcome. `operation` names the
113
+ * attempt that reserved it where the row no longer does, its `meta` gone with a deletion or
114
+ * retention. A row past `retentionDays` or scrubbed to its tombstone answers its outcome without
115
+ * its message.
116
+ */
117
+ export function storedReceipt(row, input) {
118
+ const claim = claimOf(row);
119
+ const recorded = recordedOf(row);
120
+ const expired = row.purged || Date.parse(row.at) < Date.now() - input.retentionDays * DAY_MS;
121
+ const retained = !expired && recorded !== undefined;
122
+ const failedLater = input.reported && recorded === "sent" && row.status === "failed";
123
+ const status = failedLater ? "failed" : (recorded ?? "uncertain");
124
+ // Retention scrubs a refusal with the message, as the archive in Cloud did.
125
+ const reason = status === "failed" && !row.purged ? row.failure : null;
126
+ return {
127
+ version: 1,
128
+ claimed: false,
129
+ duplicate: input.inserted !== true,
130
+ operationId: claim.operation ?? input.operation,
131
+ status,
132
+ messageId: retained ? row.messageId : null,
133
+ url: retained ? (claim.url ?? null) : null,
134
+ historyRecorded: retained,
135
+ ...(status === "failed" && reason !== null && REFUSAL.test(reason) ? { refusal: reason } : {}),
136
+ };
137
+ }
104
138
  /**
105
139
  * The delivery archive on the workspace chat store, by the chat archive in Cloud's protocol: the
106
140
  * first reservation of a key is `claimed` with the row's id as its claim; a replay with the same
107
141
  * request claims nothing and answers the row's receipt, and another request is a conflict. Only
108
142
  * the claim records the receipt, once; another outcome for it is a conflict. A row past
109
- * `retentionDays` or scrubbed to its tombstone answers its outcome without its message.
143
+ * `retentionDays` or scrubbed to its tombstone answers its outcome without its message. A `sent`
144
+ * receipt names the provider's id of the message, unless `unnamedSends`: the channel's provider may
145
+ * take a message without naming it, as a workspace channel's code may.
110
146
  */
111
- export function storeDeliveryArchive(store, retentionDays) {
147
+ export function storeDeliveryArchive(store, retentionDays, options = {}) {
112
148
  const expired = (row) => row.purged || Date.parse(row.at) < Date.now() - retentionDays * DAY_MS;
113
- /**
114
- * What a key's delivery answers. Reported, a `sent` receipt whose message the provider later
115
- * reported failed reads `failed` with its refusal; the receipt phase reads the receipt as
116
- * recorded, which its caller compares with its own outcome. `operation` names the attempt that
117
- * reserved it where the row no longer does, its `meta` gone with a deletion or retention.
118
- */
119
- const answer = (row, operation, reported, inserted = false) => {
120
- const claim = claimOf(row);
121
- const recorded = recordedOf(row);
122
- const retained = !expired(row) && recorded !== undefined;
123
- const failedLater = reported && recorded === "sent" && row.status === "failed";
124
- const status = failedLater ? "failed" : (recorded ?? "uncertain");
125
- // Retention scrubs a refusal with the message, as the archive in Cloud did.
126
- const reason = status === "failed" && !row.purged ? row.failure : null;
127
- return {
128
- version: 1,
129
- claimed: false,
130
- duplicate: !inserted,
131
- operationId: claim.operation ?? operation,
132
- status,
133
- messageId: retained ? row.messageId : null,
134
- url: retained ? (claim.url ?? null) : null,
135
- historyRecorded: retained,
136
- ...(status === "failed" && reason !== null && REFUSAL.test(reason)
137
- ? { refusal: reason }
138
- : {}),
139
- };
140
- };
149
+ const answer = (row, operation, reported, inserted = false) => storedReceipt(row, { operation, retentionDays, reported, inserted });
141
150
  /** The key's row, which a reservation that found it must have. */
142
151
  const sendOf = (operation) => store
143
152
  .findSend(operation)
@@ -191,6 +200,7 @@ export function storeDeliveryArchive(store, retentionDays) {
191
200
  // while the request alone still finds the key's receipt.
192
201
  fingerprint: `${delivery.fingerprint}:${payloadFingerprint(event)}`,
193
202
  ...(event.sessionId === null ? {} : { sessionId: event.sessionId }),
203
+ ...(event.turnId === null ? {} : { turnId: event.turnId }),
194
204
  meta: {
195
205
  ...payloadOf(event),
196
206
  delivery: {
@@ -201,6 +211,7 @@ export function storeDeliveryArchive(store, retentionDays) {
201
211
  via: requester.via,
202
212
  clientId: requester.clientId,
203
213
  },
214
+ ...(event.binding === undefined ? {} : { binding: event.binding }),
204
215
  },
205
216
  },
206
217
  };
@@ -224,7 +235,8 @@ export function storeDeliveryArchive(store, retentionDays) {
224
235
  });
225
236
  const receipt = (event, delivery) => Effect.gen(function* () {
226
237
  const status = event.status;
227
- if (status === "requested" || (status === "sent" && event.messageId === null)) {
238
+ if (status === "requested" ||
239
+ (status === "sent" && event.messageId === null && options.unnamedSends !== true)) {
228
240
  return yield* new DeliveryArchiveError({ diagnostic: "chat_store_invalid_receipt" });
229
241
  }
230
242
  const operation = deliveryOperation(delivery.scope, delivery.key);
@@ -301,7 +313,7 @@ export function storeDeliveryArchive(store, retentionDays) {
301
313
  * the evidence that the agent records there, as a chat's history is imported there from then on.
302
314
  * `cloud` is the chat archive in Cloud, which takes the deliveries until then.
303
315
  */
304
- export function deliveryArchiveOf(backend, cloud, retentionDays) {
316
+ export function deliveryArchiveOf(backend, cloud, retentionDays, options = {}) {
305
317
  const store = backend.agents?.chatMessages;
306
318
  // @legacy agent.cloud-chat-archive Until the agent records into the store, the archive in Cloud
307
319
  // reserves and receipts the delivery, as it keeps the agent's messages.
@@ -310,5 +322,5 @@ export function deliveryArchiveOf(backend, cloud, retentionDays) {
310
322
  }
311
323
  return store
312
324
  .holds()
313
- .pipe(Effect.map((held) => (held ? storeDeliveryArchive(store, retentionDays) : cloud)));
325
+ .pipe(Effect.map((held) => (held ? storeDeliveryArchive(store, retentionDays, options) : cloud)));
314
326
  }
@@ -728,6 +728,31 @@ export interface AgentStore {
728
728
  * not an active member of the app. Absent on stores that predate reviews.
729
729
  */
730
730
  readonly holdReply?: (input: HeldReplyInput) => Effect.Effect<HeldReview | undefined>;
731
+ /**
732
+ * A reply the agent proposed, held under the lock `holdReply` takes on its key, once per key and
733
+ * only while `delivered`, read under that lock, finds no delivery of it: `delivered` when one
734
+ * began, and nothing is held. With {@link AgentStore.reserveProposal}, which takes the same lock,
735
+ * one proposal of a key decides it, however proposals of it overlap: a reply once held is never
736
+ * sent, nor one sent held. `undefined` when its person is no active member. Absent on stores
737
+ * that predate proposals.
738
+ */
739
+ readonly holdProposal?: (input: HeldReplyInput, delivered: Effect.Effect<boolean>) => Effect.Effect<HeldReview | "delivered" | undefined>;
740
+ /**
741
+ * Reserves a proposed reply's delivery under the lock its hold takes, in one transaction with
742
+ * `reserve`, the reservation on the chat store, only while no draft holds its key: `held` with
743
+ * that draft otherwise, and nothing is reserved. The lock is released with the transaction,
744
+ * before the provider is called. Absent on stores that predate proposals.
745
+ */
746
+ readonly reserveProposal?: <A, E>(input: {
747
+ readonly key: string;
748
+ readonly reserve: Effect.Effect<A, E>;
749
+ }) => Effect.Effect<{
750
+ readonly kind: "reserved";
751
+ readonly value: A;
752
+ } | {
753
+ readonly kind: "held";
754
+ readonly review: HeldReview;
755
+ }, E>;
731
756
  /**
732
757
  * Holds a reply the agent redrafted at a member's request: a pending review that replaces the one
733
758
  * it redrafts, which becomes `superseded`. `discarded` when that review was decided, or another
@@ -858,6 +883,11 @@ export interface HeldReplyInput {
858
883
  };
859
884
  /** The agent's turn that wrote the reply; absent from agents that predate it. */
860
885
  readonly turnId?: string;
886
+ /**
887
+ * Where the chat stood when the turn read it, `<time>~<id>`, as a proposed reply names it: the
888
+ * draft's basis. Without it, the newest message the turn took in the chat store.
889
+ */
890
+ readonly basis?: string;
861
891
  }
862
892
  /** A reply the agent redrafted, as `POST /api/ontology/agent/drafts/revision` reports it. */
863
893
  export interface RevisedReplyInput {
@@ -23,6 +23,7 @@ import { workspaceSourceLayer } from "./agent/source.js";
23
23
  import { platformChatArchive } from "./agent/chat-archive.js";
24
24
  import { archiveRoutes } from "./agent/archive-routes.js";
25
25
  import { makeChatDelivery } from "./chat/delivery.js";
26
+ import { replyProposals } from "./chat/reply-proposal.js";
26
27
  import { platformDeliveryArchive } from "./chat/archive.js";
27
28
  import { platformHistoryArchive } from "./chat/history-import.js";
28
29
  import { chatRoutes } from "./chat/routes.js";
@@ -383,14 +384,14 @@ export function createOntologyService(ontology, config) {
383
384
  const replicate = deployedReplication(config);
384
385
  // The platform keeps chat history for production agents only.
385
386
  const chatHistory = config.runtimeIdentity === undefined || preview ? undefined : platformChatArchive(config);
386
- const chatDelivery = makeChatDelivery(ontology, connections,
387
387
  // @legacy agent.cloud-chat-archive Deliveries reserve here while the store holds no message.
388
- config.chatArchive ?? platformDeliveryArchive(config), { settings: config.channels?.telegram, ownOrigins: config.appOrigins },
388
+ const deliveries = config.chatArchive ?? platformDeliveryArchive(config);
389
389
  // The app's agent sends through a workspace channel, at the origin it takes its tasks at.
390
- {
390
+ const agentChannels = {
391
391
  origin: config.agentOrigin,
392
392
  ...(config.agentTaskTransport === undefined ? {} : { fetch: config.agentTaskTransport }),
393
- }, config.chatHistoryArchive ?? platformHistoryArchive(config), chatHistory);
393
+ };
394
+ const chatDelivery = makeChatDelivery(ontology, connections, deliveries, { settings: config.channels?.telegram, ownOrigins: config.appOrigins }, agentChannels, config.chatHistoryArchive ?? platformHistoryArchive(config), chatHistory);
394
395
  const metricQueries = makeMetricQueries({
395
396
  ontology,
396
397
  transport: platformMetricQueries({ ...config, manifestHash: ontology.manifest.hash }),
@@ -478,6 +479,13 @@ export function createOntologyService(ontology, config) {
478
479
  }),
479
480
  emailSignUp: signUpRolesOf(ontology.manifest, "email") !== undefined,
480
481
  manifest: ontology.manifest,
482
+ // The turn replies the agent proposes go as approved drafts do, through its channels.
483
+ replies: replyProposals({
484
+ ontology,
485
+ connections,
486
+ cloud: deliveries,
487
+ agent: agentChannels,
488
+ }),
481
489
  emailCodes,
482
490
  cronSecret: config.cronSecret,
483
491
  chatRetentionDays: chatRetentionDaysOf(ontology.manifest),
@@ -28,6 +28,12 @@ export declare const WORKSPACE_CHANNEL_ID: RegExp;
28
28
  export declare const WORKSPACE_CHANNEL_TEXT_LIMIT = 20000;
29
29
  /** The text a workspace channel sends: the text as written, then the separator and attribution. */
30
30
  export declare function renderWorkspaceChannelText(text: string, attribution: string, separator: string): string;
31
+ /**
32
+ * A reply in parts of at most `maxLength` characters, as a workspace channel whose code sets
33
+ * `limits.maxLength` sends a longer one: at a paragraph, else a line, else a space, else where the
34
+ * length ends. The agent splits its own replies so, and the ontology the turn replies it sends.
35
+ */
36
+ export declare function splitReply(text: string, maxLength: number | undefined): ReadonlyArray<string>;
31
37
  /** `POST` {@link workspaceChannelSendRoute}: one message to one person's chat. */
32
38
  export interface WorkspaceChannelSend {
33
39
  /** Names the message, so a send the ontology tries again is the same message. */
@@ -34,6 +34,33 @@ export const WORKSPACE_CHANNEL_TEXT_LIMIT = 20_000;
34
34
  export function renderWorkspaceChannelText(text, attribution, separator) {
35
35
  return attribution === "" ? text : `${text}${separator}${attribution}`;
36
36
  }
37
+ /**
38
+ * A reply in parts of at most `maxLength` characters, as a workspace channel whose code sets
39
+ * `limits.maxLength` sends a longer one: at a paragraph, else a line, else a space, else where the
40
+ * length ends. The agent splits its own replies so, and the ontology the turn replies it sends.
41
+ */
42
+ export function splitReply(text, maxLength) {
43
+ if (maxLength === undefined || text.length <= maxLength) {
44
+ return [text];
45
+ }
46
+ const parts = [];
47
+ let rest = text;
48
+ while (rest.length > maxLength) {
49
+ const window = rest.slice(0, maxLength);
50
+ const cut = [
51
+ window.lastIndexOf("\n\n"),
52
+ window.lastIndexOf("\n"),
53
+ window.lastIndexOf(" "),
54
+ ].find((index) => index > 0);
55
+ const end = cut ?? maxLength;
56
+ parts.push(rest.slice(0, end).trimEnd());
57
+ rest = rest.slice(end).trimStart();
58
+ }
59
+ if (rest !== "") {
60
+ parts.push(rest);
61
+ }
62
+ return parts;
63
+ }
37
64
  /**
38
65
  * The most bytes of files one message through a workspace channel carries unless the channel's
39
66
  * code takes more (`limits.fileBytes`).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.180.0",
3
+ "version": "0.181.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",
@@ -45,6 +45,10 @@
45
45
  "types": "./dist/workspace-channel.d.ts",
46
46
  "import": "./dist/workspace-channel.js"
47
47
  },
48
+ "./review": {
49
+ "types": "./dist/review.d.ts",
50
+ "import": "./dist/review.js"
51
+ },
48
52
  "./chat-personas": {
49
53
  "types": "./dist/chat-personas.d.ts",
50
54
  "import": "./dist/chat-personas.js"