@segmentstream/ontology 0.150.2 → 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.
@@ -7,7 +7,7 @@ import { AgentChat, agentChatKey } from "../agent-chat.js";
7
7
  import { chatChannelKind } from "../chat-channel.js";
8
8
  import { AgentReview } from "../agent-review.js";
9
9
  import { AGENT_IDENTITIES_TABLE, AGENT_PAIRINGS_TABLE, CHANNEL_USERS_TABLE, IDENTITY_NOTICES_TABLE, USER_TABLE, } from "../migrate/storage.js";
10
- import { inboxRolesOf, takeoverChannelsOf, takeoverProvidersOf } from "../manifest.js";
10
+ import { inboxChannelsOf, inboxRolesOf, takeoverChannelsOf, takeoverProvidersOf, } from "../manifest.js";
11
11
  import { GUEST_ROLE } from "../names.js";
12
12
  import { MAX_QUERY_LIMIT } from "../query.js";
13
13
  import { beginReplicationWrite } from "../replication/transaction.js";
@@ -648,11 +648,21 @@ export function sqlAgentStore(ontology, sql) {
648
648
  }))
649
649
  .pipe(Effect.orDie),
650
650
  seeInboxChat: (input) => Effect.gen(function* () {
651
- const roles = inboxRolesOf(ontology.manifest);
652
- const member = isRecordId(input.memberId) ? yield* store.member(input.memberId) : undefined;
653
- // Only the private chats of people whose roles the inbox takes are recorded.
654
- if (member === undefined || !member.principal.roles.some((role) => roles.has(role))) {
655
- return undefined;
651
+ const { memberId } = input;
652
+ if (memberId === undefined) {
653
+ // A chat with someone who is no user joins only on a channel the inbox lists, without
654
+ // members: nobody is created for them, and staff read it within their scope.
655
+ if (!inboxChannelsOf(ontology.manifest).has(input.provider)) {
656
+ return undefined;
657
+ }
658
+ }
659
+ else {
660
+ const roles = inboxRolesOf(ontology.manifest);
661
+ const member = isRecordId(memberId) ? yield* store.member(memberId) : undefined;
662
+ // Only the private chats of people whose roles the inbox takes are recorded.
663
+ if (member === undefined || !member.principal.roles.some((role) => roles.has(role))) {
664
+ return undefined;
665
+ }
656
666
  }
657
667
  return yield* sql.withTransaction(Effect.gen(function* () {
658
668
  yield* beginReplicationWrite(sql);
@@ -707,29 +717,32 @@ export function sqlAgentStore(ontology, sql) {
707
717
  values: changes,
708
718
  });
709
719
  // A private chat has one member, its person now: an account paired with someone else
710
- // since leaves the earlier person out. A link already there changes nothing.
711
- const members = yield* runtime.related({
712
- entity: AgentChat.name,
713
- id: String(chat.id),
714
- relationship: "members",
715
- query: { limit: MAX_QUERY_LIMIT },
716
- });
717
- for (const member of members.items) {
718
- if (String(member.id) !== input.memberId) {
719
- yield* runtime.unlink({
720
- entity: AgentChat.name,
721
- relationship: "members",
722
- id: String(chat.id),
723
- targetId: String(member.id),
724
- });
720
+ // since leaves the earlier person out. A link already there changes nothing. A report
721
+ // without a person leaves the members as they are.
722
+ if (memberId !== undefined) {
723
+ const members = yield* runtime.related({
724
+ entity: AgentChat.name,
725
+ id: String(chat.id),
726
+ relationship: "members",
727
+ query: { limit: MAX_QUERY_LIMIT },
728
+ });
729
+ for (const member of members.items) {
730
+ if (String(member.id) !== memberId) {
731
+ yield* runtime.unlink({
732
+ entity: AgentChat.name,
733
+ relationship: "members",
734
+ id: String(chat.id),
735
+ targetId: String(member.id),
736
+ });
737
+ }
725
738
  }
739
+ yield* runtime.link({
740
+ entity: AgentChat.name,
741
+ relationship: "members",
742
+ id: String(chat.id),
743
+ targetId: memberId,
744
+ });
726
745
  }
727
- yield* runtime.link({
728
- entity: AgentChat.name,
729
- relationship: "members",
730
- id: String(chat.id),
731
- targetId: input.memberId,
732
- });
733
746
  return {
734
747
  id: String(chat.id),
735
748
  title: String(chat.title),
@@ -95,6 +95,11 @@ export interface ChatMessageInput {
95
95
  readonly sessionId?: string;
96
96
  readonly turnId?: string;
97
97
  readonly meta?: unknown;
98
+ /**
99
+ * When the message was imported: history from before the chat was recorded, which no session
100
+ * reads as new and no figure counts. The runtime routes never take it.
101
+ */
102
+ readonly importedAt?: string;
98
103
  }
99
104
  /** The message a change is to, by the provider's id of it. */
100
105
  interface Target {
@@ -250,8 +255,8 @@ export interface ChatMessageStore {
250
255
  readonly applied: boolean;
251
256
  }, ChatMessageConflict>;
252
257
  readonly read: (input: ChatMessageQuery) => Effect.Effect<ChatMessagePage>;
253
- /** Whether the store holds a message of the chat. */
254
- readonly holds: (chat: {
258
+ /** Whether the store holds a message of the chat; without one, a message of any chat. */
259
+ readonly holds: (chat?: {
255
260
  readonly channel: string;
256
261
  readonly chatId: string;
257
262
  }) => Effect.Effect<boolean>;
@@ -1,5 +1,6 @@
1
1
  import { Effect, Schema } from "effect";
2
2
  import { CHAT_MESSAGE_REVISIONS, CHAT_MESSAGES_TABLE } from "../migrate/storage.js";
3
+ import { ATTACHMENTS_TABLE } from "../storage/tables.js";
3
4
  import { uuidv7 } from "./ids.js";
4
5
  /**
5
6
  * The workspace's chat store: one row per message in `_chat_messages` (docs/agent-chat-storage.md,
@@ -218,12 +219,14 @@ export function sqlChatMessageStore(sql) {
218
219
  params.add(input.sessionId ?? null),
219
220
  params.add(input.turnId ?? null),
220
221
  params.add(input.meta === undefined ? null : JSON.stringify(input.meta), "jsonb"),
222
+ params.add(input.importedAt ?? null, "timestamptz"),
221
223
  ];
222
224
  // Any of the keys may be taken: a redelivery, an echo, a retried send. Nothing changes then.
223
225
  const [inserted] = yield* rows(`INSERT INTO ${TABLE} ("id", "channel", "chat_id", "thread_id", "chat_type", ` +
224
226
  `"participants", "direction", "author", "sender_id", "sender_name", "user_id", ` +
225
227
  `"message_id", "reply_to", "text", "parts", "files", "at", "status", "operation", ` +
226
- `"fingerprint", "session_id", "turn_id", "meta") VALUES (${values.join(", ")}) ` +
228
+ `"fingerprint", "session_id", "turn_id", "meta", "imported_at") ` +
229
+ `VALUES (${values.join(", ")}) ` +
227
230
  `ON CONFLICT DO NOTHING RETURNING "id"::text AS "id"`, params.values);
228
231
  if (inserted !== undefined) {
229
232
  return { id: String(inserted.id), first: true };
@@ -327,6 +330,39 @@ export function sqlChatMessageStore(sql) {
327
330
  ]);
328
331
  return { applied: true };
329
332
  }));
333
+ /**
334
+ * The person retracted the message: its content goes, the row stays as the message's place. The
335
+ * channel's `meta` goes with it: it holds the message's file references and what a turn read of
336
+ * it, and the dispatch fence that outlives the deletion is the disposition. The files it held, its
337
+ * chat's stored attachments, are discarded with it, as a channel that keeps them would otherwise
338
+ * keep them for as long as the chat's messages.
339
+ */
340
+ const remove = (input) => inChat(input.channel, input.chatId, Effect.gen(function* () {
341
+ const [deleted] = yield* rows(`WITH "before" AS (SELECT "id", "files" FROM ${TABLE} WHERE "channel" = $1 ` +
342
+ `AND "chat_id" = $2 AND "message_id" = $3 AND "purged_at" IS NULL ` +
343
+ `AND "deleted_at" IS NULL FOR UPDATE) ` +
344
+ `UPDATE ${TABLE} SET "text" = NULL, "parts" = '[]', "files" = '[]', ` +
345
+ `"reactions" = '[]', "meta" = NULL, ` +
346
+ `"deleted_at" = date_trunc('milliseconds', coalesce($4::timestamptz, now())), ` +
347
+ `${revised} FROM "before" WHERE ${TABLE}."id" = "before"."id" ` +
348
+ `RETURNING "before"."files"::text AS "files"`, [input.channel, input.chatId, input.messageId, input.at ?? null]);
349
+ if (deleted === undefined) {
350
+ return { applied: false };
351
+ }
352
+ const files = jsonArray(deleted.files).flatMap((file) => {
353
+ const id = file.id;
354
+ return typeof id === "string" ? [id] : [];
355
+ });
356
+ const [storage] = files.length === 0
357
+ ? []
358
+ : yield* rows(`SELECT to_regclass('"${ATTACHMENTS_TABLE}"') IS NOT NULL AS "present"`);
359
+ if (storage?.present === true || storage?.present === "t") {
360
+ yield* rows(`UPDATE "${ATTACHMENTS_TABLE}" SET "state" = 'discarded', "expires_at" = now() ` +
361
+ `WHERE "id"::text = ANY($1::text[]) AND "conversation" = $2 ` +
362
+ `AND "state" IN ('received', 'ready')`, [files, `${input.channel}:${input.chatId}`]);
363
+ }
364
+ return { applied: true };
365
+ }));
330
366
  const change = (input) => {
331
367
  const params = parameters();
332
368
  switch (input.change) {
@@ -358,18 +394,7 @@ export function sqlChatMessageStore(sql) {
358
394
  ]);
359
395
  }
360
396
  case "delete":
361
- // The person retracted it: its content goes, the row stays as the message's place. The
362
- // channel's `meta` goes with it: it holds the message's file references and what a turn
363
- // read of it, and the dispatch fence that outlives the deletion is the disposition.
364
- return update(input, params, [
365
- `"text" = NULL`,
366
- `"parts" = '[]'`,
367
- `"files" = '[]'`,
368
- `"reactions" = '[]'`,
369
- `"meta" = NULL`,
370
- `"deleted_at" = date_trunc('milliseconds', coalesce(${params.add(input.at ?? null, "timestamptz")}, now()))`,
371
- revised,
372
- ], [`"deleted_at" IS NULL`]);
397
+ return remove(input);
373
398
  case "reaction": {
374
399
  const sender = params.add(input.senderId, "text");
375
400
  const emoji = params.add(input.emoji, "text");
@@ -537,7 +562,9 @@ export function sqlChatMessageStore(sql) {
537
562
  conditions.push(`(${rules.join(" OR ")})`);
538
563
  return page(conditions, params, input);
539
564
  };
540
- const holds = ({ channel, chatId }) => rows(`SELECT EXISTS (SELECT 1 FROM ${TABLE} WHERE "channel" = $1 AND "chat_id" = $2) AS "holds"`, [channel, chatId]).pipe(Effect.map(([row]) => row?.holds === true || row?.holds === "t"));
565
+ const holds = (chat) => rows(chat === undefined
566
+ ? `SELECT EXISTS (SELECT 1 FROM ${TABLE}) AS "holds"`
567
+ : `SELECT EXISTS (SELECT 1 FROM ${TABLE} WHERE "channel" = $1 AND "chat_id" = $2) AS "holds"`, chat === undefined ? [] : [chat.channel, chat.chatId]).pipe(Effect.map(([row]) => row?.holds === true || row?.holds === "t"));
541
568
  const purge = ({ retentionDays }) => Effect.gen(function* () {
542
569
  let deleted = 0;
543
570
  let scrubbed = 0;
@@ -152,7 +152,8 @@ export const ChatSeenRequest = Schema.Struct({
152
152
  description: "The chat's id before it became a supergroup: its record moves to externalId.",
153
153
  })),
154
154
  kind: Schema.optionalKey(Schema.Literal("private").annotate({
155
- description: "A person's private chat, which the inbox registers when memberId holds one of its roles; " +
155
+ description: "A person's private chat, which the inbox registers when memberId holds one of its roles, " +
156
+ "or, without memberId, for someone who is no user on a channel inbox.channels lists; " +
156
157
  "absent for a group chat.",
157
158
  })),
158
159
  recipient: Schema.optionalKey(ChatId.annotate({
@@ -314,9 +314,9 @@ function seeChat(store) {
314
314
  }
315
315
  const { kind, recipient, threadId, ...seen } = decoded.success;
316
316
  if (kind === "private") {
317
- // A person's private chat joins the inbox, which records nothing for anyone else.
318
- const inboxed = seen.memberId === undefined ||
319
- store.seeInboxChat === undefined ||
317
+ // A person's private chat joins the inbox, which records nothing for anyone else; one
318
+ // without a person, someone who is no user, joins on a channel the inbox lists.
319
+ const inboxed = store.seeInboxChat === undefined ||
320
320
  seen.leftMemberId !== undefined ||
321
321
  seen.agentLeft !== undefined ||
322
322
  seen.migratedFrom !== undefined
@@ -325,7 +325,7 @@ function seeChat(store) {
325
325
  provider: seen.provider,
326
326
  externalId: seen.externalId,
327
327
  title: seen.title,
328
- memberId: seen.memberId,
328
+ ...(seen.memberId === undefined ? {} : { memberId: seen.memberId }),
329
329
  ...(recipient === undefined ? {} : { recipient }),
330
330
  ...(threadId === undefined ? {} : { threadId }),
331
331
  });
@@ -1,5 +1,5 @@
1
1
  import { validateTelegramPreviews } from "../../telegram.js";
2
- import { inboxAttributionOf, takeoverChannelsOf } from "../../manifest.js";
2
+ import { chatRetentionDaysOf, inboxAttributionOf, takeoverChannelsOf } from "../../manifest.js";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { Cause, Effect } from "effect";
5
5
  import { chatOperationId, chatPreviewDigest, } from "../../chat.js";
@@ -465,6 +465,8 @@ chats) {
465
465
  identityToken: context.identityToken,
466
466
  requestId: context.requestId,
467
467
  archive: history,
468
+ retentionDays: chatRetentionDaysOf(ontology.manifest),
469
+ channelKind: (name) => chatKind(ontology.manifest.chat, name),
468
470
  }),
469
471
  }),
470
472
  reviseReview: reviewReviser({
@@ -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({
@@ -666,8 +666,10 @@ export interface AgentStore {
666
666
  * Records a person's private chat with the agent for the inbox: creates the `agent_chat` of kind
667
667
  * `private`, with the person as its one member, or keeps its title, recipient and thread current,
668
668
  * and records when it last had a message, as `seeChat` does. `undefined`, recording nothing,
669
- * unless the person is an active member holding a role of the ontology's `inbox`. Absent on
670
- * stores that predate the inbox.
669
+ * unless the person is an active member holding a role of the ontology's `inbox`. Without
670
+ * `memberId`, the chat is someone's who is no user: recorded without members, whose members it
671
+ * leaves as they are, and only on a channel `inbox.channels` lists; no user is created. Absent
672
+ * on stores that predate the inbox.
671
673
  */
672
674
  readonly seeInboxChat?: (input: InboxChatInput) => Effect.Effect<SeenChat | undefined>;
673
675
  /**
@@ -762,8 +764,8 @@ export interface InboxChatInput {
762
764
  readonly externalId: string;
763
765
  /** The person's name on the channel. */
764
766
  readonly title: string;
765
- /** The person, a user id. */
766
- readonly memberId: string;
767
+ /** The person, a user id; absent for someone who is no user. */
768
+ readonly memberId?: string;
767
769
  /** Whom a reply is sent to, where it differs from `externalId`. */
768
770
  readonly recipient?: string;
769
771
  /** The thread a reply stays in. */