@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.
@@ -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>;
@@ -554,6 +569,7 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
554
569
  }>>;
555
570
  readonly inbox: Schema.optionalKey<Schema.Struct<{
556
571
  readonly roles: Schema.$Array<Schema.String>;
572
+ readonly channels: Schema.optionalKey<Schema.$Array<Schema.String>>;
557
573
  readonly takeover: Schema.optionalKey<Schema.Struct<{
558
574
  readonly channels: Schema.$Array<Schema.String>;
559
575
  }>>;
@@ -898,19 +914,34 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
898
914
  readonly chat: Schema.toEncoded<Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
899
915
  readonly telegram: Schema.optionalKey<Schema.Struct<{
900
916
  readonly connection: Schema.String;
917
+ readonly files: Schema.optionalKey<Schema.Struct<{
918
+ readonly keep: Schema.Boolean;
919
+ }>>;
901
920
  }>>;
902
921
  readonly slack: Schema.optionalKey<Schema.Struct<{
903
922
  readonly connection: Schema.String;
923
+ readonly files: Schema.optionalKey<Schema.Struct<{
924
+ readonly keep: Schema.Boolean;
925
+ }>>;
904
926
  }>>;
905
927
  readonly whatsapp: Schema.optionalKey<Schema.Struct<{
906
928
  readonly connection: Schema.String;
929
+ readonly files: Schema.optionalKey<Schema.Struct<{
930
+ readonly keep: Schema.Boolean;
931
+ }>>;
907
932
  }>>;
908
933
  readonly email: Schema.optionalKey<Schema.Struct<{
909
934
  readonly connection: Schema.String;
935
+ readonly files: Schema.optionalKey<Schema.Struct<{
936
+ readonly keep: Schema.Boolean;
937
+ }>>;
910
938
  }>>;
911
939
  readonly channels: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Struct<{
912
940
  readonly kind: Schema.Literals<readonly ["telegram", "slack", "whatsapp", "email", "custom"]>;
913
941
  readonly connection: Schema.optionalKey<Schema.String>;
942
+ readonly files: Schema.optionalKey<Schema.Struct<{
943
+ readonly keep: Schema.Boolean;
944
+ }>>;
914
945
  }>>>;
915
946
  readonly attribution: Schema.optionalKey<Schema.Struct<{
916
947
  readonly template: Schema.optionalKey<Schema.String>;
@@ -922,6 +953,7 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
922
953
  }>>>;
923
954
  readonly inbox: Schema.toEncoded<Schema.optionalKey<Schema.Struct<{
924
955
  readonly roles: Schema.$Array<Schema.String>;
956
+ readonly channels: Schema.optionalKey<Schema.$Array<Schema.String>>;
925
957
  readonly takeover: Schema.optionalKey<Schema.Struct<{
926
958
  readonly channels: Schema.$Array<Schema.String>;
927
959
  }>>;
@@ -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<{
@@ -2,26 +2,37 @@ import { createHash, randomUUID } from "node:crypto";
2
2
  import { Effect } from "effect";
3
3
  import { acceptsBlobContentType, isBlobContentType, BLOB_UPLOAD_ANNOTATION, MAX_BLOB_BYTES, } from "../blob.js";
4
4
  import { ActionRejected, Conflict, NotFound } from "../errors.js";
5
- import { canonicalJson } from "../manifest.js";
5
+ import { CHAT_FILES, CHAT_FILES_ACTION } from "../files.js";
6
+ import { canonicalJson, chatRetentionDaysOf, keepsChatFiles } from "../manifest.js";
7
+ import { effectiveScope } from "../permissions.js";
6
8
  import { actionInputJsonSchema } from "../runtime/generated-actions.js";
7
9
  import { resolveAction } from "../runtime/pipeline.js";
10
+ import { makeOntologyRuntime } from "../runtime/sql-runtime.js";
8
11
  import { authorizeBlobOperation } from "./authorization.js";
9
12
  import { storageQuotaRejection } from "./limits.js";
10
13
  import { ATTACHMENT_SOURCES, ATTACHMENTS_TABLE } from "./tables.js";
11
14
  /**
12
- * The agent's temporary attachments: a file a member sends the app's agent is stored once, as a
13
- * `_blobs` revision in the ontology's private file storage. Group files belong to the chat's current
15
+ * The agent's attachments: a file a member sends the app's agent is stored once, as a `_blobs`
16
+ * revision in the ontology's private file storage. Group files belong to the chat's current
14
17
  * members; private files belong to their sender and the agent session that first reads them.
15
- * Nothing about it is an ontology record. It expires 24 hours after receipt; the agent may read it,
16
- * discard it, or promote it into a record through an action, which adopts the same stored object
17
- * without copying it. Every operation derives chat access from the caller and registry, never from
18
- * tool input.
18
+ * Nothing about it is an ontology record. It expires 24 hours after receipt, or, on a channel whose
19
+ * chats keep their files (`files: { keep: true }` in the ontology's `chat`), when its chat's
20
+ * messages do; the agent may read it, discard it, or promote it into a record through an action,
21
+ * which adopts the same stored object without copying it. A file imported with a chat's history is
22
+ * an attachment too, adopted from its upload. Every operation derives chat access from the caller
23
+ * and registry, never from tool input.
19
24
  */
20
25
  /** The largest file the agent takes: what Telegram's Bot API lets a bot download. */
21
26
  export const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;
22
- /** How long an attachment stays readable after it arrives; reads never extend it. */
27
+ /**
28
+ * How long an attachment stays readable after it arrives, unless its channel keeps its chats'
29
+ * files; reads never extend it.
30
+ */
23
31
  export const ATTACHMENT_TTL_HOURS = 24;
24
- /** Live attachments one member may hold at once, so a busy chat cannot fill the storage. */
32
+ /**
33
+ * Attachments one member may receive within {@link ATTACHMENT_TTL_HOURS}, so a busy chat cannot
34
+ * fill the storage. Files a channel keeps longer count only while they are that recent.
35
+ */
25
36
  export const MAX_LIVE_ATTACHMENTS = 50;
26
37
  export { ATTACHMENT_SOURCES };
27
38
  const SHA256 = /^[0-9a-f]{64}$/;
@@ -107,6 +118,38 @@ export function attachmentRuntime(ontology, sql, provider) {
107
118
  const binding = provider.binding;
108
119
  const missing = (id) => new NotFound({ entity: "attachment", id, message: "Attachment not found." });
109
120
  const unavailable = (message) => new Conflict({ entity: "attachment", message });
121
+ const retentionDays = chatRetentionDaysOf(ontology.manifest);
122
+ /**
123
+ * When a file of `chat` that arrived at `arrived`, a SQL time, expires: with its chat's messages
124
+ * where the chat's channel keeps its files, else {@link ATTACHMENT_TTL_HOURS} after it arrived.
125
+ */
126
+ const expiry = (chat, arrived) => keepsChatFiles(ontology.manifest, chat.slice(0, chat.indexOf(":")))
127
+ ? `${arrived} + make_interval(days => ${retentionDays})`
128
+ : `now() + make_interval(hours => ${ATTACHMENT_TTL_HOURS})`;
129
+ /**
130
+ * Whether a member reads `chat` as the ontology lets them read its `agent_chat` record: with
131
+ * `agent_chat:read`, within its scope where the grant has one. A chat without a record, such as
132
+ * a private chat the inbox does not take, is no member's to read this way.
133
+ */
134
+ const readsChat = (principalId, chat) => Effect.gen(function* () {
135
+ const separator = chat.indexOf(":");
136
+ const [record] = yield* sql.unsafe(`SELECT id::text FROM "agent_chat" WHERE provider = $1 AND external_id = $2`, [chat.slice(0, separator), chat.slice(separator + 1)]);
137
+ if (record === undefined) {
138
+ return false;
139
+ }
140
+ const reader = yield* authorizeBlobOperation(ontology, sql, principalId, [
141
+ "agent_chat:read",
142
+ ]).pipe(Effect.catchTag("PermissionDenied", () => Effect.succeed(undefined)));
143
+ if (reader === undefined) {
144
+ return false;
145
+ }
146
+ if (effectiveScope("agent_chat:read", reader) === undefined) {
147
+ return true;
148
+ }
149
+ return yield* makeOntologyRuntime(ontology, sql)
150
+ .get({ entity: "agent_chat", id: record.id, reader })
151
+ .pipe(Effect.as(true), Effect.catchTag("NotFound", () => Effect.succeed(false)));
152
+ });
110
153
  /**
111
154
  * Group chats come from the registry, whose private chats the inbox registered stay private
112
155
  * here. Neither a tool argument nor a caller's roles name a group.
@@ -124,6 +167,10 @@ export function attachmentRuntime(ontology, sql, provider) {
124
167
  if (admin) {
125
168
  return "administrator";
126
169
  }
170
+ // A member who reads the chat's record reads its files, as its messages.
171
+ if (yield* readsChat(caller.principal.id, caller.chat)) {
172
+ return "reader";
173
+ }
127
174
  }
128
175
  const separator = caller.chat.indexOf(":");
129
176
  const [chat] = yield* sql.unsafe(`SELECT id::text FROM "agent_chat"
@@ -163,7 +210,8 @@ export function attachmentRuntime(ontology, sql, provider) {
163
210
  caller.principal.id,
164
211
  caller.chat,
165
212
  binding.branchId,
166
- (access === "group" || access === "administrator") && scope === "session",
213
+ (access === "group" || access === "administrator" || access === "reader") &&
214
+ scope === "session",
167
215
  ]);
168
216
  const row = rows[0];
169
217
  if (!row) {
@@ -224,7 +272,8 @@ export function attachmentRuntime(ontology, sql, provider) {
224
272
  }
225
273
  const [usage] = yield* sql.unsafe(`SELECT (SELECT coalesce(sum(size), 0)::text FROM "_blobs" WHERE state <> 'deleted') AS bytes,
226
274
  (SELECT count(*)::text FROM "${ATTACHMENTS_TABLE}" WHERE owner_id = $1::uuid
227
- AND state IN ('received', 'ready') AND expires_at > now()) AS live`, [caller.principal.id]);
275
+ AND state IN ('received', 'ready') AND expires_at > now()
276
+ AND created_at > now() - make_interval(hours => ${ATTACHMENT_TTL_HOURS})) AS live`, [caller.principal.id]);
228
277
  const overQuota = storageQuotaRejection({
229
278
  usedBytes: Number(usage.bytes),
230
279
  requestedBytes: input.size,
@@ -258,7 +307,7 @@ export function attachmentRuntime(ontology, sql, provider) {
258
307
  (id, blob_id, branch_id, owner_id, conversation, session_id, source, source_ref,
259
308
  filename, content_type, size, sha256, state, expires_at)
260
309
  VALUES ($1::uuid, $2::uuid, $3, $4::uuid, $5, $6, $7, $8, $9, $10, $11::bigint, $12,
261
- 'received', now() + make_interval(hours => ${ATTACHMENT_TTL_HOURS}))`, [
310
+ 'received', ${expiry(caller.chat, "now()")})`, [
262
311
  id,
263
312
  blobId,
264
313
  binding.branchId,
@@ -472,13 +521,16 @@ export function attachmentRuntime(ontology, sql, provider) {
472
521
  WHERE id = $2::uuid`, [JSON.stringify(promotion), row.id]);
473
522
  return { kind: "done", row: yield* load(row.id, caller) };
474
523
  }
475
- const [existing] = yield* sql.unsafe(`SELECT id::text, state, record_id::text, create_intent::text FROM "_blob_uploads"
476
- WHERE blob_id = $1::uuid FOR UPDATE`, [row.blob_id]);
477
- if (existing && existing.state === "consumed") {
524
+ const [existing] = yield* sql.unsafe(`SELECT id::text, state, record_id::text, create_intent::text, action
525
+ FROM "_blob_uploads" WHERE blob_id = $1::uuid FOR UPDATE`, [row.blob_id]);
526
+ // The upload a chat's history import consumed adopted the file into the chat, not into a
527
+ // record: it is bound to the promotion like a ready one.
528
+ const imported = existing?.state === "consumed" && existing.action === CHAT_FILES_ACTION;
529
+ if (existing && existing.state === "consumed" && !imported) {
478
530
  // An earlier promotion committed but its answer was lost; the action replays it.
479
531
  return { kind: "run", row, upload: existing };
480
532
  }
481
- if (existing && existing.state !== "ready") {
533
+ if (existing && existing.state !== "ready" && !imported) {
482
534
  return yield* unavailable("The attachment's file is being removed.");
483
535
  }
484
536
  const upload = {
@@ -507,7 +559,8 @@ export function attachmentRuntime(ontology, sql, provider) {
507
559
  yield* sql.unsafe(`UPDATE "_blob_uploads" SET blob_id = $2::uuid, principal_id = $3::uuid,
508
560
  branch_id = $4, manifest_hash = $5, action = $6, entity_id = $7, property_id = $8,
509
561
  record_id = $9::uuid, create_intent = $10::uuid, filename = $11,
510
- content_type = $12, size = $13::bigint,
562
+ content_type = $12, size = $13::bigint, state = 'ready', claim = NULL,
563
+ claimed_at = NULL,
511
564
  expires_at = (SELECT expires_at FROM "${ATTACHMENTS_TABLE}" WHERE id = $14::uuid)
512
565
  WHERE id = $1::uuid`, values);
513
566
  }
@@ -561,6 +614,110 @@ export function attachmentRuntime(ontology, sql, provider) {
561
614
  }));
562
615
  return { attachment: view(promoted), deduplicated: false, result: outcome.result ?? null };
563
616
  });
617
+ /**
618
+ * Keeps a completed upload for `agent_chat.importHistory` as an attachment of the imported
619
+ * message's chat, adopting the uploaded revision: the upload is consumed, and the attachment,
620
+ * received when the message was written, expires as the chat's files do. A replay of an upload
621
+ * already adopted answers its attachment. `adopted` is false when the chat already holds a file
622
+ * at the same source; the upload is then left as it was, for the caller to release.
623
+ */
624
+ const adopt = (input) => Effect.gen(function* () {
625
+ const entity = ontology.manifest.entities.find((item) => item.name === CHAT_FILES.entity);
626
+ const lock = sql.unsafe(`SELECT u.id::text, u.blob_id::text, b.key, u.state, u.size::text,
627
+ u.expires_at <= now() AS expired, b.state AS blob_state
628
+ FROM "_blob_uploads" u JOIN "_blobs" b ON b.id = u.blob_id
629
+ WHERE u.id = $1::uuid AND u.principal_id = $2::uuid AND u.branch_id = $3
630
+ AND u.manifest_hash = $4 AND u.action = $5 AND u.entity_id = $6 AND u.property_id = $7
631
+ FOR UPDATE OF u, b`, [
632
+ input.uploadId,
633
+ input.principal.id,
634
+ binding.branchId,
635
+ ontology.manifest.hash,
636
+ CHAT_FILES_ACTION,
637
+ entity?.id ?? "",
638
+ CHAT_FILES.property,
639
+ ]);
640
+ // The attachment an earlier import made of the upload, which only the same message's file
641
+ // replays: a consumed upload is no other message's file.
642
+ const adopted = (blobId) => Effect.gen(function* () {
643
+ const [row] = yield* sql.unsafe(`${SELECT.replace("SELECT ", "SELECT (a.owner_id = $3::uuid AND a.conversation = $4 AND a.source_ref = $5) AS same, ")} WHERE a.blob_id = $1::uuid AND a.branch_id = $2`, [blobId, binding.branchId, input.ownerId, input.chat, input.sourceRef]);
644
+ if (row !== undefined && row.same !== true) {
645
+ return yield* new Conflict({
646
+ entity: "upload",
647
+ message: "The upload is already the file of another message.",
648
+ });
649
+ }
650
+ return row;
651
+ });
652
+ const found = yield* sql.withTransaction(Effect.gen(function* () {
653
+ yield* authorizeBlobOperation(ontology, sql, input.principal.id, [], input.principal.execution, input.principal.workflow);
654
+ const [upload] = yield* lock;
655
+ if (upload === undefined) {
656
+ return yield* new NotFound({
657
+ entity: "upload",
658
+ id: input.uploadId,
659
+ message: "Upload not found.",
660
+ });
661
+ }
662
+ const held = yield* adopted(upload.blob_id);
663
+ if (held !== undefined) {
664
+ return { held };
665
+ }
666
+ if (upload.state !== "ready" || upload.expired || upload.blob_state !== "ready") {
667
+ return yield* new Conflict({
668
+ entity: "upload",
669
+ message: "The upload is not a completed file.",
670
+ });
671
+ }
672
+ return { upload };
673
+ }));
674
+ if (found.held !== undefined) {
675
+ return { attachment: view(found.held), adopted: true };
676
+ }
677
+ // Its digest, read outside any transaction.
678
+ const sha256 = yield* provider.sha256(found.upload.key, Number(found.upload.size));
679
+ return yield* sql.withTransaction(Effect.gen(function* () {
680
+ const [upload] = yield* lock;
681
+ if (upload === undefined || upload.state !== "ready" || upload.expired) {
682
+ const held = upload === undefined ? undefined : yield* adopted(upload.blob_id);
683
+ return held === undefined
684
+ ? yield* new Conflict({
685
+ entity: "upload",
686
+ message: "The upload is not a completed file.",
687
+ })
688
+ : { attachment: view(held), adopted: true };
689
+ }
690
+ const [inserted] = yield* sql.unsafe(`INSERT INTO "${ATTACHMENTS_TABLE}"
691
+ (id, blob_id, branch_id, owner_id, conversation, session_id, source, source_ref,
692
+ filename, content_type, size, sha256, state, created_at, expires_at)
693
+ SELECT $1::uuid, u.blob_id, u.branch_id, $3::uuid, $4, NULL, $5, $6, u.filename,
694
+ u.content_type, u.size, $7, 'ready', $8::timestamptz,
695
+ ${expiry(input.chat, "$8::timestamptz")}
696
+ FROM "_blob_uploads" u WHERE u.id = $2::uuid
697
+ ON CONFLICT ("owner_id", "conversation", "source_ref") DO NOTHING
698
+ RETURNING id::text`, [
699
+ randomUUID(),
700
+ upload.id,
701
+ input.ownerId,
702
+ input.chat,
703
+ input.source,
704
+ input.sourceRef,
705
+ sha256,
706
+ input.at,
707
+ ]);
708
+ if (inserted === undefined) {
709
+ const [held] = yield* sql.unsafe(`${SELECT} WHERE a.owner_id = $1::uuid AND a.conversation = $2
710
+ AND a.source_ref = $3 AND a.branch_id = $4`, [input.ownerId, input.chat, input.sourceRef, binding.branchId]);
711
+ return { attachment: view(held), adopted: false };
712
+ }
713
+ yield* sql.unsafe(`UPDATE "_blob_uploads" SET state = 'consumed', claim = NULL, claimed_at = NULL
714
+ WHERE id = $1::uuid`, [upload.id]);
715
+ const [row] = yield* sql.unsafe(`${SELECT} WHERE a.id = $1::uuid`, [
716
+ inserted.id,
717
+ ]);
718
+ return { attachment: view(row), adopted: true };
719
+ }));
720
+ });
564
721
  /** Resolve the chat from storage, then authorize with the same locked loader. */
565
722
  const memberCaller = (id, principal) => sql.withTransaction(Effect.gen(function* () {
566
723
  if (!/^[0-9a-f-]{36}$/i.test(id)) {
@@ -601,6 +758,8 @@ export function attachmentRuntime(ontology, sql, provider) {
601
758
  const admin = yield* authorizeBlobOperation(ontology, sql, principal.id, [
602
759
  "agent_chat:update",
603
760
  ]).pipe(Effect.as(true), Effect.catchTag("PermissionDenied", () => Effect.succeed(false)));
761
+ // A member who reads the chat's record lists all its files, as an administrator does.
762
+ let reads = false;
604
763
  if (filters.chat !== undefined) {
605
764
  const scope = yield* accessScope({
606
765
  principal,
@@ -610,6 +769,7 @@ export function attachmentRuntime(ontology, sql, provider) {
610
769
  if (scope === "denied") {
611
770
  return yield* missing("chat");
612
771
  }
772
+ reads = scope === "reader";
613
773
  if (scope === "private") {
614
774
  const [sent] = yield* sql.unsafe(`SELECT 1 FROM "${ATTACHMENTS_TABLE}" WHERE branch_id = $1 AND conversation = $2
615
775
  AND owner_id = $3::uuid LIMIT 1`, [binding.branchId, filters.chat, principal.id]);
@@ -637,7 +797,7 @@ export function attachmentRuntime(ontology, sql, provider) {
637
797
  ))
638
798
  ORDER BY a.created_at DESC, a.id DESC LIMIT $9`, [
639
799
  binding.branchId,
640
- admin,
800
+ admin || reads,
641
801
  principal.id,
642
802
  filters.chat ?? null,
643
803
  filters.senderId ?? null,
@@ -658,6 +818,7 @@ export function attachmentRuntime(ontology, sql, provider) {
658
818
  read,
659
819
  discard,
660
820
  promote,
821
+ adopt,
661
822
  listForMember,
662
823
  getForMember,
663
824
  readForMember,
@@ -667,7 +828,8 @@ export function attachmentRuntime(ontology, sql, provider) {
667
828
  /**
668
829
  * Expires attachments past their deadline and removes the bytes of every expired or discarded one
669
830
  * that no record adopted. A revision a promotion ticket still points at is left to the upload
670
- * maintenance, once the ticket is canceled. Runs from the storage maintenance schedule, so files
831
+ * maintenance, once the ticket is canceled; an imported file's upload, consumed when the attachment
832
+ * adopted it, holds nothing. Runs from the storage maintenance schedule, so files
671
833
  * expire while the agent is idle.
672
834
  */
673
835
  export function maintainAttachments(sql, provider, limit = 100) {
@@ -696,7 +858,8 @@ export function maintainAttachments(sql, provider, limit = 100) {
696
858
  AND (a.state IN ('discarded', 'expired') OR a.expires_at <= now()
697
859
  OR a.branch_id <> $1)
698
860
  AND NOT EXISTS (SELECT 1 FROM "_blob_references" r WHERE r.blob_id = b.id)
699
- AND NOT EXISTS (SELECT 1 FROM "_blob_uploads" u WHERE u.blob_id = b.id)
861
+ AND NOT EXISTS (SELECT 1 FROM "_blob_uploads" u
862
+ WHERE u.blob_id = b.id AND u.state <> 'consumed')
700
863
  ORDER BY a.created_at LIMIT 1 FOR UPDATE OF a, b SKIP LOCKED`, [provider.binding.branchId]);
701
864
  if (!row) {
702
865
  return undefined;
@@ -732,7 +895,8 @@ export function maintainAttachments(sql, provider, limit = 100) {
732
895
  AND (a.state IN ('discarded', 'expired') OR a.expires_at <= now()
733
896
  OR a.branch_id <> $1)
734
897
  AND NOT EXISTS (SELECT 1 FROM "_blob_references" r WHERE r.blob_id = b.id)
735
- AND NOT EXISTS (SELECT 1 FROM "_blob_uploads" u WHERE u.blob_id = b.id)
898
+ AND NOT EXISTS (SELECT 1 FROM "_blob_uploads" u
899
+ WHERE u.blob_id = b.id AND u.state <> 'consumed')
736
900
  ) AS remaining`, [provider.binding.branchId]);
737
901
  return { expired, removed, hasMore: backlog.remaining || removed >= limit };
738
902
  });
@@ -4,11 +4,12 @@ import { isSqlError } from "effect/unstable/sql/SqlError";
4
4
  import { acceptsBlobContentType, uploadInput, BLOB_UPLOAD_ANNOTATION, MAX_BLOB_BYTES, } from "../blob.js";
5
5
  import { wireStruct } from "../wire.js";
6
6
  import { ActionRejected, Conflict, NotFound } from "../errors.js";
7
- import { Files } from "../files.js";
7
+ import { CHAT_FILES, CHAT_FILES_ACTION, Files } from "../files.js";
8
8
  import { uploadFile, openFile } from "./transfers.js";
9
9
  import { canonicalJson } from "../manifest.js";
10
10
  import { effectiveScope } from "../permissions.js";
11
11
  import { isRecordId } from "../runtime/records.js";
12
+ import { MAX_ATTACHMENT_BYTES } from "./attachments.js";
12
13
  import { authorizeBlobOperation } from "./authorization.js";
13
14
  import { MAX_PENDING_UPLOADS, storageQuotaRejection } from "./limits.js";
14
15
  import { resolveAction } from "../runtime/pipeline.js";
@@ -145,17 +146,26 @@ export function blobRuntime(ontology, sql, provider, fetchImpl = fetch) {
145
146
  return row;
146
147
  });
147
148
  const beginUpload = (given, principal, preparedAction) => Effect.gen(function* () {
149
+ const qualified = preparedAction ?? `${given.entity}.${given.action}`;
150
+ // A chat's file is no record's: it becomes the chat's attachment, as a file the agent
151
+ // receives does, and takes the attachments' bound. The session stands for the record.
152
+ const chatFiles = given.entity === CHAT_FILES.entity &&
153
+ given.property === CHAT_FILES.property &&
154
+ qualified === CHAT_FILES_ACTION &&
155
+ given.recordId === undefined;
156
+ // A caller-generated UUID is also the session identity, without changing existing tables.
157
+ const id = given.idempotencyKey ?? randomUUID();
158
+ const createIntent = given.createIntent ?? (chatFiles ? id : undefined);
148
159
  // UUIDs in either case name one record; uuid columns answer in lower case.
149
160
  const input = {
150
161
  ...given,
151
162
  ...(given.recordId === undefined ? {} : { recordId: given.recordId.toLowerCase() }),
152
- ...(given.createIntent === undefined
153
- ? {}
154
- : { createIntent: given.createIntent.toLowerCase() }),
163
+ ...(createIntent === undefined ? {} : { createIntent: createIntent.toLowerCase() }),
155
164
  };
156
165
  const entity = ontology.manifest.entities.find((item) => item.name === input.entity);
157
- const property = entity?.properties.find((item) => item.name === input.property && item.type === "blob");
158
- const qualified = preparedAction ?? `${input.entity}.${input.action}`;
166
+ const property = chatFiles
167
+ ? { name: CHAT_FILES.property, accept: undefined, maxBytes: MAX_ATTACHMENT_BYTES }
168
+ : entity?.properties.find((item) => item.name === input.property && item.type === "blob");
159
169
  const [actionEntity, actionName] = qualified.split(".");
160
170
  const found = resolveAction(ontology, actionEntity, actionName);
161
171
  if (!entity ||
@@ -185,8 +195,6 @@ export function blobRuntime(ontology, sql, provider, fetchImpl = fetch) {
185
195
  message: "This action does not accept an upload for that field.",
186
196
  });
187
197
  }
188
- // A caller-generated UUID is also the session identity, without changing existing tables.
189
- const id = input.idempotencyKey ?? randomUUID();
190
198
  const blobId = randomUUID();
191
199
  const claim = randomUUID();
192
200
  const key = `revisions/${blobId}`;
@@ -14,7 +14,8 @@ export declare const ATTACHMENT_SOURCE_CHECK = "_agent_attachments_source_check"
14
14
  * A file a member sent the app's agent: platform metadata, never an ontology record. The bytes are
15
15
  * a `_blobs` revision in the same storage as uploads; the row binds them to their owner, the chat
16
16
  * and, for private chats, the first agent session that reads them. Group access follows the chat
17
- * registry's current members. Attachments expire 24 hours after receipt unless promoted.
17
+ * registry's current members. Attachments expire 24 hours after receipt unless promoted, or, on a
18
+ * channel that keeps its chats' files, with their messages.
18
19
  *
19
20
  * @legacy ontology.attachment-conversation-column
20
21
  * The column `conversation` holds the chat, `provider:external_id`: SDKs sharing this database
@@ -75,7 +75,8 @@ const SOURCE_CHECK = `CHECK ("source" IN (${ATTACHMENT_SOURCES.map((source) => `
75
75
  * A file a member sent the app's agent: platform metadata, never an ontology record. The bytes are
76
76
  * a `_blobs` revision in the same storage as uploads; the row binds them to their owner, the chat
77
77
  * and, for private chats, the first agent session that reads them. Group access follows the chat
78
- * registry's current members. Attachments expire 24 hours after receipt unless promoted.
78
+ * registry's current members. Attachments expire 24 hours after receipt unless promoted, or, on a
79
+ * channel that keeps its chats' files, with their messages.
79
80
  *
80
81
  * @legacy ontology.attachment-conversation-column
81
82
  * The column `conversation` holds the chat, `provider:external_id`: SDKs sharing this database
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.150.2",
3
+ "version": "0.152.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",