@segmentstream/ontology 0.151.0 → 0.152.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,10 +1,13 @@
1
1
  import { Effect, Schema } from "effect";
2
- import type { ChatHistoryImportInput, ChatHistoryImportResult } from "../../chat.js";
2
+ import { type ChatHistoryImportInput, type ChatHistoryImportResult } from "../../chat.js";
3
3
  import { ActionRejected, PermissionDenied } from "../../errors.js";
4
4
  import type { Principal } from "../../runtime.js";
5
5
  import type { OntologyEnvironment } from "../config.js";
6
6
  import type { OntologyBackend } from "../runtime-contract.js";
7
- /** A chat's messages from before the archive recorded it, as the archive takes them. */
7
+ /**
8
+ * A chat's messages from before the archive recorded it, as the chat archive in Cloud takes them.
9
+ * @legacy agent.cloud-chat-archive
10
+ */
8
11
  export interface HistoryImport {
9
12
  readonly provider: string;
10
13
  readonly chatId: string;
@@ -34,7 +37,11 @@ export type HistoryArchive = (input: {
34
37
  readonly history: HistoryImport;
35
38
  readonly identityToken: string | undefined;
36
39
  }) => Effect.Effect<ChatHistoryImportResult, HistoryArchiveError>;
37
- /** The platform's chat archive, which takes a chat's history from the deployment's runtime. */
40
+ /**
41
+ * The platform's chat archive, which takes a chat's history from the deployment's runtime while
42
+ * the workspace chat store holds no message.
43
+ * @legacy agent.cloud-chat-archive
44
+ */
38
45
  export declare function platformHistoryArchive(environment: OntologyEnvironment, fetchImpl?: typeof fetch): HistoryArchive;
39
46
  /**
40
47
  * The users a chat's `members` links: a private chat's person. Queries name relationships as the
@@ -53,16 +60,23 @@ export declare const chatPeopleQuery: (chat: string) => {
53
60
  limit: number;
54
61
  };
55
62
  /**
56
- * Imports a chat's messages from before the archive recorded it, for a caller
63
+ * Imports a chat's messages from before the agent recorded it, for a caller
57
64
  * `agent_chat:import_history` admitted: a chat the inbox registered, named by its record, or one
58
- * named by channel and chat id. A scoped grant covers registered chats within its scope alone.
65
+ * named by channel and chat id. A scoped grant covers registered chats within its scope alone. The
66
+ * messages go into the workspace chat store once it holds the agent's messages; until then, while
67
+ * the agent may still record into the chat archive in Cloud, they go there, text alone.
59
68
  */
60
69
  export declare function historyImporter(input: {
61
70
  readonly backend: OntologyBackend["Service"];
62
71
  readonly principal: Principal;
63
72
  readonly identityToken: string | undefined;
64
73
  readonly requestId: string;
74
+ /** @legacy agent.cloud-chat-archive */
65
75
  readonly archive: HistoryArchive;
76
+ /** How long the workspace keeps its chats' messages: an older one is not imported. */
77
+ readonly retentionDays: number;
78
+ /** The kind of the agent's channel `name`, which its files' attachments name as their source. */
79
+ readonly channelKind: (name: string) => string | undefined;
66
80
  }): (request: ChatHistoryImportInput) => Effect.Effect<{
67
81
  readonly imported: number;
68
82
  readonly duplicates: number;
@@ -1,7 +1,12 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { Effect, Schema } from "effect";
3
+ import { isSqlError } from "effect/unstable/sql/SqlError";
4
+ import { CHAT_HISTORY_FILES, } from "../../chat.js";
2
5
  import { ActionRejected, PermissionDenied } from "../../errors.js";
3
6
  import { effectiveScope } from "../../permissions.js";
7
+ import { ATTACHMENT_SOURCES } from "../../storage/tables.js";
4
8
  import { describeChatError } from "./diagnostics.js";
9
+ const DAY_MS = 86_400_000;
5
10
  export class HistoryArchiveError extends Schema.TaggedError()("HistoryArchiveError", {
6
11
  diagnostic: Schema.String,
7
12
  /** The archive refused the messages themselves: retrying them changes nothing. */
@@ -15,7 +20,11 @@ const ImportAnswer = Schema.Struct({
15
20
  skipped: Schema.Number,
16
21
  expired: Schema.Number,
17
22
  });
18
- /** The platform's chat archive, which takes a chat's history from the deployment's runtime. */
23
+ /**
24
+ * The platform's chat archive, which takes a chat's history from the deployment's runtime while
25
+ * the workspace chat store holds no message.
26
+ * @legacy agent.cloud-chat-archive
27
+ */
19
28
  export function platformHistoryArchive(environment, fetchImpl = fetch) {
20
29
  return ({ history, identityToken }) => Effect.tryPromise({
21
30
  try: async (signal) => {
@@ -71,9 +80,16 @@ const RESERVED_PROVIDERS = new Set(["task", "revision", "expired"]);
71
80
  /** The sender of every message the agent wrote, as the archive keeps the messages it writes now. */
72
81
  const AGENT_SENDER = "agent";
73
82
  const text = (value) => typeof value === "string" && value !== "" ? value : null;
74
- /** A message as the archive keeps it: who wrote it, from its direction and author. */
83
+ /** Who wrote a message: the default for its direction unless it says. */
84
+ function authorOf(message) {
85
+ return message.by ?? (message.direction === "inbound" ? "human" : "agent");
86
+ }
87
+ /**
88
+ * A message as the archive in Cloud keeps it: who wrote it, from its direction and author.
89
+ * @legacy agent.cloud-chat-archive
90
+ */
75
91
  function archived(message) {
76
- const by = message.by ?? (message.direction === "inbound" ? "human" : "agent");
92
+ const by = authorOf(message);
77
93
  return {
78
94
  messageId: message.id,
79
95
  kind: message.direction,
@@ -81,15 +97,139 @@ function archived(message) {
81
97
  senderId: by === "agent" ? AGENT_SENDER : null,
82
98
  senderName: message.name ?? null,
83
99
  senderIsBot: by !== "human",
84
- text: message.text,
100
+ text: message.text ?? "",
85
101
  replyToMessageId: message.replyTo ?? null,
86
102
  at: message.at,
87
103
  };
88
104
  }
105
+ /** A file's place in its imported message, as its attachment's source names it. */
106
+ function fileSource(messageId, index) {
107
+ return `import:${createHash("sha256").update(messageId).digest("hex").slice(0, 32)}:${index}`;
108
+ }
89
109
  /**
90
- * Imports a chat's messages from before the archive recorded it, for a caller
110
+ * Imports a chat's messages into the workspace chat store, each in its place by its time, marked
111
+ * imported: a session already running never reads them as new, and no figure counts them. A
112
+ * message the chat holds, by its id, is a duplicate; one older than the chat's retention is
113
+ * `expired`. A message's files become the chat's attachments, adopted from their uploads; the
114
+ * uploads of a message not added are released.
115
+ */
116
+ function importLocally(input) {
117
+ const { backend, principal, history } = input;
118
+ return Effect.gen(function* () {
119
+ const store = backend.agents.chatMessages;
120
+ const attachments = backend.attachments;
121
+ const chat = `${history.provider}:${history.chatId}`;
122
+ // A private chat's files are its person's, as the files they send the agent are.
123
+ const owner = history.participantIds.length === 1 ? history.participantIds[0] : principal.id;
124
+ const now = Date.now();
125
+ const importedAt = new Date(now).toISOString();
126
+ const unused = [];
127
+ let imported = 0;
128
+ let duplicates = 0;
129
+ let expired = 0;
130
+ if (attachments === undefined && input.messages.some((message) => message.files)) {
131
+ return yield* new ActionRejected({ message: "file_storage_unavailable" });
132
+ }
133
+ for (const message of input.messages) {
134
+ const uploads = (message.files ?? []).map((file) => file.upload.uploadId);
135
+ if (Date.parse(message.at) < now - input.retentionDays * DAY_MS) {
136
+ expired += 1;
137
+ unused.push(...uploads);
138
+ continue;
139
+ }
140
+ const held = yield* store.read({
141
+ channel: history.provider,
142
+ chatId: history.chatId,
143
+ messageId: message.id,
144
+ limit: 1,
145
+ });
146
+ if (held.messages.length > 0) {
147
+ duplicates += 1;
148
+ unused.push(...uploads);
149
+ continue;
150
+ }
151
+ const files = [];
152
+ for (const [index, uploadId] of uploads.entries()) {
153
+ const kept = yield* attachments
154
+ .adopt({
155
+ uploadId,
156
+ principal,
157
+ ownerId: owner,
158
+ chat,
159
+ source: input.source,
160
+ sourceRef: fileSource(message.id, index),
161
+ at: message.at,
162
+ })
163
+ .pipe(Effect.catchTags({
164
+ NotFound: (cause) => Effect.fail(new ActionRejected({
165
+ message: "A message's file is no completed upload of yours for importHistory.",
166
+ cause,
167
+ })),
168
+ Conflict: (cause) => Effect.fail(new ActionRejected({ message: cause.message, cause })),
169
+ BlobStorageError: (cause) => Effect.fail(new ActionRejected({ message: "file_storage_failed", cause })),
170
+ }), Effect.catchIf(isSqlError, Effect.die));
171
+ if (!kept.adopted) {
172
+ unused.push(uploadId);
173
+ }
174
+ files.push({
175
+ id: kept.attachment.id,
176
+ name: kept.attachment.filename,
177
+ type: kept.attachment.contentType,
178
+ size: kept.attachment.size,
179
+ });
180
+ }
181
+ const by = authorOf(message);
182
+ // An import names no send's key, so no other message's key can conflict with it.
183
+ const recorded = yield* store
184
+ .record({
185
+ channel: history.provider,
186
+ chatId: history.chatId,
187
+ ...(history.threadId === null ? {} : { threadId: history.threadId }),
188
+ chatType: history.chatType,
189
+ participants: history.participantIds,
190
+ direction: message.direction,
191
+ author: by,
192
+ ...(by === "agent" || message.name === undefined ? {} : { senderName: message.name }),
193
+ messageId: message.id,
194
+ ...(message.replyTo === undefined ? {} : { replyTo: message.replyTo }),
195
+ ...(message.text === undefined || message.text.trim() === ""
196
+ ? {}
197
+ : { text: message.text }),
198
+ ...(files.length === 0 ? {} : { files }),
199
+ at: message.at,
200
+ ...(message.direction === "outbound" ? { status: "sent" } : {}),
201
+ importedAt,
202
+ })
203
+ .pipe(Effect.orDie);
204
+ if (recorded.first) {
205
+ imported += 1;
206
+ }
207
+ else {
208
+ duplicates += 1;
209
+ }
210
+ }
211
+ // As an action that keeps no file releases its upload: the caller's open uploads go down.
212
+ for (const uploadId of unused) {
213
+ const blobs = backend.blobs;
214
+ if (blobs !== undefined) {
215
+ yield* blobs.cancel(uploadId, principal).pipe(Effect.asVoid,
216
+ // diagnostics-recovery: a ticket left open expires within a day; the import stands.
217
+ Effect.catchCause((cause) => Effect.logWarning("ontology.agent_chat.history_upload_release_failed").pipe(Effect.annotateLogs({
218
+ requestId: input.requestId,
219
+ uploadId,
220
+ error: describeChatError(cause, (value) => value),
221
+ }))));
222
+ }
223
+ }
224
+ return { imported, duplicates, skipped: 0, expired };
225
+ });
226
+ }
227
+ /**
228
+ * Imports a chat's messages from before the agent recorded it, for a caller
91
229
  * `agent_chat:import_history` admitted: a chat the inbox registered, named by its record, or one
92
- * named by channel and chat id. A scoped grant covers registered chats within its scope alone.
230
+ * named by channel and chat id. A scoped grant covers registered chats within its scope alone. The
231
+ * messages go into the workspace chat store once it holds the agent's messages; until then, while
232
+ * the agent may still record into the chat archive in Cloud, they go there, text alone.
93
233
  */
94
234
  export function historyImporter(input) {
95
235
  const { backend, principal } = input;
@@ -189,8 +329,43 @@ export function historyImporter(input) {
189
329
  message: "Each message's at is an ISO 8601 time no later than now.",
190
330
  });
191
331
  }
192
- if (request.messages.some((message) => message.text.trim() === "")) {
193
- return yield* new ActionRejected({ message: "Each message has text." });
332
+ if (request.messages.some((message) => (message.text === undefined || message.text.trim() === "") &&
333
+ (message.files ?? []).length === 0)) {
334
+ return yield* new ActionRejected({ message: "Each message has text or files." });
335
+ }
336
+ const uploads = request.messages.flatMap((message) => (message.files ?? []).map((file) => file.upload.uploadId.toLowerCase()));
337
+ if (uploads.length > CHAT_HISTORY_FILES) {
338
+ return yield* new ActionRejected({
339
+ message: `One import takes at most ${CHAT_HISTORY_FILES} files.`,
340
+ });
341
+ }
342
+ if (new Set(uploads).size !== uploads.length) {
343
+ return yield* new ActionRejected({ message: "Each file is one message's own upload." });
344
+ }
345
+ const store = backend.agents?.chatMessages;
346
+ // The store holds the agent's messages: the chat's history joins them there.
347
+ if (store !== undefined && (yield* store.holds())) {
348
+ const kind = input.channelKind(history.provider);
349
+ return yield* importLocally({
350
+ backend,
351
+ principal,
352
+ requestId: input.requestId,
353
+ history,
354
+ messages: request.messages,
355
+ retentionDays: input.retentionDays,
356
+ source: ATTACHMENT_SOURCES.includes(kind ?? "")
357
+ ? kind
358
+ : "channel",
359
+ });
360
+ }
361
+ // @legacy agent.cloud-chat-archive Until the agent records into the store, the archive in
362
+ // Cloud takes the history, as it takes the agent's messages: text alone.
363
+ if (uploads.length > 0 ||
364
+ request.messages.some((message) => message.text === undefined || message.text.trim() === "")) {
365
+ return yield* new ActionRejected({
366
+ message: "Files import into the workspace chat store, once it holds the agent's messages; " +
367
+ "until then each message has text alone.",
368
+ });
194
369
  }
195
370
  return yield* input
196
371
  .archive({
@@ -530,19 +530,34 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
530
530
  readonly chat: Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
531
531
  readonly telegram: Schema.optionalKey<Schema.Struct<{
532
532
  readonly connection: Schema.String;
533
+ readonly files: Schema.optionalKey<Schema.Struct<{
534
+ readonly keep: Schema.Boolean;
535
+ }>>;
533
536
  }>>;
534
537
  readonly slack: Schema.optionalKey<Schema.Struct<{
535
538
  readonly connection: Schema.String;
539
+ readonly files: Schema.optionalKey<Schema.Struct<{
540
+ readonly keep: Schema.Boolean;
541
+ }>>;
536
542
  }>>;
537
543
  readonly whatsapp: Schema.optionalKey<Schema.Struct<{
538
544
  readonly connection: Schema.String;
545
+ readonly files: Schema.optionalKey<Schema.Struct<{
546
+ readonly keep: Schema.Boolean;
547
+ }>>;
539
548
  }>>;
540
549
  readonly email: Schema.optionalKey<Schema.Struct<{
541
550
  readonly connection: Schema.String;
551
+ readonly files: Schema.optionalKey<Schema.Struct<{
552
+ readonly keep: Schema.Boolean;
553
+ }>>;
542
554
  }>>;
543
555
  readonly channels: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Struct<{
544
556
  readonly kind: Schema.Literals<readonly ["telegram", "slack", "whatsapp", "email", "custom"]>;
545
557
  readonly connection: Schema.optionalKey<Schema.String>;
558
+ readonly files: Schema.optionalKey<Schema.Struct<{
559
+ readonly keep: Schema.Boolean;
560
+ }>>;
546
561
  }>>>;
547
562
  readonly attribution: Schema.optionalKey<Schema.Struct<{
548
563
  readonly template: Schema.optionalKey<Schema.String>;
@@ -899,19 +914,34 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
899
914
  readonly chat: Schema.toEncoded<Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
900
915
  readonly telegram: Schema.optionalKey<Schema.Struct<{
901
916
  readonly connection: Schema.String;
917
+ readonly files: Schema.optionalKey<Schema.Struct<{
918
+ readonly keep: Schema.Boolean;
919
+ }>>;
902
920
  }>>;
903
921
  readonly slack: Schema.optionalKey<Schema.Struct<{
904
922
  readonly connection: Schema.String;
923
+ readonly files: Schema.optionalKey<Schema.Struct<{
924
+ readonly keep: Schema.Boolean;
925
+ }>>;
905
926
  }>>;
906
927
  readonly whatsapp: Schema.optionalKey<Schema.Struct<{
907
928
  readonly connection: Schema.String;
929
+ readonly files: Schema.optionalKey<Schema.Struct<{
930
+ readonly keep: Schema.Boolean;
931
+ }>>;
908
932
  }>>;
909
933
  readonly email: Schema.optionalKey<Schema.Struct<{
910
934
  readonly connection: Schema.String;
935
+ readonly files: Schema.optionalKey<Schema.Struct<{
936
+ readonly keep: Schema.Boolean;
937
+ }>>;
911
938
  }>>;
912
939
  readonly channels: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Struct<{
913
940
  readonly kind: Schema.Literals<readonly ["telegram", "slack", "whatsapp", "email", "custom"]>;
914
941
  readonly connection: Schema.optionalKey<Schema.String>;
942
+ readonly files: Schema.optionalKey<Schema.Struct<{
943
+ readonly keep: Schema.Boolean;
944
+ }>>;
915
945
  }>>>;
916
946
  readonly attribution: Schema.optionalKey<Schema.Struct<{
917
947
  readonly template: Schema.optionalKey<Schema.String>;
@@ -6,19 +6,27 @@ import type { Principal } from "../runtime.js";
6
6
  import type { BlobProvider, TransferGrant } from "./provider.js";
7
7
  import { ATTACHMENT_SOURCES } from "./tables.js";
8
8
  /**
9
- * The agent's temporary attachments: a file a member sends the app's agent is stored once, as a
10
- * `_blobs` revision in the ontology's private file storage. Group files belong to the chat's current
9
+ * The agent's attachments: a file a member sends the app's agent is stored once, as a `_blobs`
10
+ * revision in the ontology's private file storage. Group files belong to the chat's current
11
11
  * members; private files belong to their sender and the agent session that first reads them.
12
- * Nothing about it is an ontology record. It expires 24 hours after receipt; the agent may read it,
13
- * discard it, or promote it into a record through an action, which adopts the same stored object
14
- * without copying it. Every operation derives chat access from the caller and registry, never from
15
- * tool input.
12
+ * Nothing about it is an ontology record. It expires 24 hours after receipt, or, on a channel whose
13
+ * chats keep their files (`files: { keep: true }` in the ontology's `chat`), when its chat's
14
+ * messages do; the agent may read it, discard it, or promote it into a record through an action,
15
+ * which adopts the same stored object without copying it. A file imported with a chat's history is
16
+ * an attachment too, adopted from its upload. Every operation derives chat access from the caller
17
+ * and registry, never from tool input.
16
18
  */
17
19
  /** The largest file the agent takes: what Telegram's Bot API lets a bot download. */
18
20
  export declare const MAX_ATTACHMENT_BYTES: number;
19
- /** How long an attachment stays readable after it arrives; reads never extend it. */
21
+ /**
22
+ * How long an attachment stays readable after it arrives, unless its channel keeps its chats'
23
+ * files; reads never extend it.
24
+ */
20
25
  export declare const ATTACHMENT_TTL_HOURS = 24;
21
- /** Live attachments one member may hold at once, so a busy chat cannot fill the storage. */
26
+ /**
27
+ * Attachments one member may receive within {@link ATTACHMENT_TTL_HOURS}, so a busy chat cannot
28
+ * fill the storage. Files a channel keeps longer count only while they are that recent.
29
+ */
22
30
  export declare const MAX_LIVE_ATTACHMENTS = 50;
23
31
  export { ATTACHMENT_SOURCES };
24
32
  /** Who asks, as the agent's runtime knows it: the member, their chat and the agent session. */
@@ -54,6 +62,24 @@ export interface ReceiveAttachment {
54
62
  readonly size: number;
55
63
  readonly sha256: string;
56
64
  }
65
+ /**
66
+ * A completed upload for `agent_chat.importHistory` (`agent_chat.files`), which becomes an
67
+ * attachment of an imported message's chat, adopting the uploaded revision without copying it.
68
+ */
69
+ export interface AdoptUpload {
70
+ readonly uploadId: string;
71
+ /** The importer, whose upload it is. */
72
+ readonly principal: Principal;
73
+ /** Whose attachment it becomes: a private chat's person, or the importer. */
74
+ readonly ownerId: string;
75
+ /** The chat, `channel:chatId`. */
76
+ readonly chat: string;
77
+ readonly source: (typeof ATTACHMENT_SOURCES)[number];
78
+ /** The file at its source: the imported message, and the file's place in it. */
79
+ readonly sourceRef: string;
80
+ /** When the message was written, which the attachment's receipt and expiry follow. */
81
+ readonly at: string;
82
+ }
57
83
  export interface AttachmentView {
58
84
  readonly id: string;
59
85
  readonly filename: string;
@@ -127,6 +153,10 @@ export declare function attachmentRuntime(ontology: Ontology, sql: SqlClient.Sql
127
153
  deduplicated: boolean;
128
154
  result: {} | null;
129
155
  }, unknown, never>;
156
+ adopt: (input: AdoptUpload) => Effect.Effect<{
157
+ attachment: AttachmentView;
158
+ adopted: boolean;
159
+ }, PermissionDenied | Conflict | NotFound | import("effect/unstable/sql/SqlError").SqlError | import("./provider.js").BlobStorageError, never>;
130
160
  listForMember: (filters: AttachmentSearch, principal: Principal) => Effect.Effect<{
131
161
  attachments: AttachmentView[];
132
162
  nextCursor: string | null;
@@ -147,7 +177,8 @@ export type AttachmentFailure = ActionRejected | Conflict | NotFound | Permissio
147
177
  /**
148
178
  * Expires attachments past their deadline and removes the bytes of every expired or discarded one
149
179
  * that no record adopted. A revision a promotion ticket still points at is left to the upload
150
- * maintenance, once the ticket is canceled. Runs from the storage maintenance schedule, so files
180
+ * maintenance, once the ticket is canceled; an imported file's upload, consumed when the attachment
181
+ * adopted it, holds nothing. Runs from the storage maintenance schedule, so files
151
182
  * expire while the agent is idle.
152
183
  */
153
184
  export declare function maintainAttachments(sql: SqlClient.SqlClient, provider: BlobProvider["Service"], limit?: number): Effect.Effect<{