@capybara-hq/kernel 0.1.0-rc.38 → 0.1.0-rc.39

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.
@@ -188,7 +188,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
188
188
  /** The host versions (an entry's `minKernel` is judged against them). */
189
189
  export declare const HOST_VERSIONS: {
190
190
  readonly kernel: string;
191
- readonly sdk: "0.1.0-rc.29";
191
+ readonly sdk: "0.1.0-rc.30";
192
192
  };
193
193
  /** Whether this deployment satisfies the entry's `minKernel`. */
194
194
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -76,6 +76,28 @@ export interface OpenedAttachment {
76
76
  size: number;
77
77
  body: ReadableStream<Uint8Array>;
78
78
  }
79
+ /** A ready `chat` attachment bound to a conversation ({@link AttachmentsService.boundRows}). */
80
+ export interface BoundAttachment {
81
+ id: string;
82
+ name: string;
83
+ contentType: string;
84
+ size: number;
85
+ objectKey: string;
86
+ /** The etag recorded at finalize (null: none recorded). */
87
+ etag: string | null;
88
+ createdAt: Date;
89
+ }
90
+ /**
91
+ * Whether a stored object is still the attachment finalize checked: the same size, and the same
92
+ * etag when one was recorded. Anything else is treated as no longer available.
93
+ */
94
+ export declare function attachmentContentMatches(recorded: {
95
+ size: number;
96
+ etag: string | null;
97
+ }, head: {
98
+ size: number;
99
+ etag?: string | undefined;
100
+ }): boolean;
79
101
  /** `POST /attachments` 的返回:浏览器按 `upload` 直传存储,然后调 finalize。 */
80
102
  export interface CreatedAttachment {
81
103
  id: string;
@@ -147,6 +169,23 @@ export declare class AttachmentsService {
147
169
  id: string;
148
170
  name: string;
149
171
  }[]>;
172
+ /**
173
+ * The ready `chat` attachments bound to the conversation in this org (never another purpose, a
174
+ * pending or an unbound upload), oldest first by upload time, then id; with `id`, only that one.
175
+ * Nothing here checks who reads them: callers check the conversation's access first.
176
+ */
177
+ boundRows(orgId: string, conversationId: string, id?: string): Promise<BoundAttachment[]>;
178
+ /**
179
+ * {@link attachmentContentMatches} for a bound attachment's stored object (`null`: gone), with
180
+ * the warning logged when the content was replaced after finalize.
181
+ */
182
+ storedMatches(a: Pick<BoundAttachment, "id" | "size" | "etag">, head: {
183
+ size: number;
184
+ etag?: string | undefined;
185
+ } | null, where: {
186
+ orgId: string;
187
+ conversationId?: string;
188
+ }): boolean;
150
189
  /**
151
190
  * 读取一个绑定在该会话、已 ready 的附件(沙箱同步等内核内部用途):没有行、未绑定到该会话、对象已不在、
152
191
  * 大小或 etag 与 finalize 时不符 → null。其余错误(存储不可用等)照常抛出。调用方负责读完或取消 `body`。
@@ -62,6 +62,13 @@ export const ATTACHMENT_CLEANUP_JOB = "attachment-cleanup";
62
62
  const CLEANUP_BATCH = 100;
63
63
  /** finalize 时读取开头多少字节核对文件签名。 */
64
64
  const SNIFF_BYTES = 1024;
65
+ /**
66
+ * Whether a stored object is still the attachment finalize checked: the same size, and the same
67
+ * etag when one was recorded. Anything else is treated as no longer available.
68
+ */
69
+ export function attachmentContentMatches(recorded, head) {
70
+ return head.size === recorded.size && (recorded.etag === null || recorded.etag === head.etag);
71
+ }
65
72
  const notFound = () => new ApiError("attachment.not_found", "Attachment not found");
66
73
  /** 去掉参数、转小写:`Text/Plain; charset=utf-8` → `text/plain`。 */
67
74
  export const normalizeContentType = (ct) => (ct.split(";")[0] ?? "").trim().toLowerCase();
@@ -297,7 +304,15 @@ let AttachmentsService = class AttachmentsService {
297
304
  this.storage.assertAvailable();
298
305
  const row = await this.db
299
306
  .selectFrom("attachments")
300
- .select(["account_id", "conversation_id", "name", "content_type", "object_key", "etag"])
307
+ .select([
308
+ "account_id",
309
+ "conversation_id",
310
+ "name",
311
+ "content_type",
312
+ "object_key",
313
+ "size",
314
+ "etag",
315
+ ])
301
316
  .where("id", "=", id)
302
317
  .where("org_id", "=", orgId)
303
318
  .where("status", "=", "ready")
@@ -312,7 +327,7 @@ let AttachmentsService = class AttachmentsService {
312
327
  throw notFound();
313
328
  const store = this.storage.kernel(orgId);
314
329
  const head = await store.head(row.object_key);
315
- if (!head || !this.sameContent(row.etag, head.etag, { orgId, attachmentId: id })) {
330
+ if (!this.storedMatches({ id, size: Number(row.size), etag: row.etag }, head, { orgId })) {
316
331
  throw notFound();
317
332
  }
318
333
  const inline = isImageContentType(row.content_type) || row.content_type === "application/pdf";
@@ -327,43 +342,65 @@ let AttachmentsService = class AttachmentsService {
327
342
  * 绑定在该会话、已 ready 的附件(id 与原始文件名),按上传时间、id 排序(沙箱同步按这个顺序分配文件名)。
328
343
  */
329
344
  async listForConversation(orgId, conversationId) {
330
- return this.db
345
+ return (await this.boundRows(orgId, conversationId)).map((r) => ({ id: r.id, name: r.name }));
346
+ }
347
+ /**
348
+ * The ready `chat` attachments bound to the conversation in this org (never another purpose, a
349
+ * pending or an unbound upload), oldest first by upload time, then id; with `id`, only that one.
350
+ * Nothing here checks who reads them: callers check the conversation's access first.
351
+ */
352
+ async boundRows(orgId, conversationId, id) {
353
+ let q = this.db
331
354
  .selectFrom("attachments")
332
- .select(["id", "name"])
355
+ .select(["id", "name", "content_type", "size", "object_key", "etag", "created_at"])
333
356
  .where("org_id", "=", orgId)
334
357
  .where("conversation_id", "=", conversationId)
335
358
  .where("purpose", "=", "chat")
336
- .where("status", "=", "ready")
337
- .orderBy("created_at")
338
- .orderBy("id")
339
- .execute();
359
+ .where("status", "=", "ready");
360
+ if (id !== undefined)
361
+ q = q.where("id", "=", id);
362
+ const rows = await q.orderBy("created_at").orderBy("id").execute();
363
+ return rows.map((r) => ({
364
+ id: r.id,
365
+ name: r.name,
366
+ contentType: r.content_type,
367
+ size: Number(r.size),
368
+ objectKey: r.object_key,
369
+ etag: r.etag,
370
+ createdAt: r.created_at,
371
+ }));
372
+ }
373
+ /**
374
+ * {@link attachmentContentMatches} for a bound attachment's stored object (`null`: gone), with
375
+ * the warning logged when the content was replaced after finalize.
376
+ */
377
+ storedMatches(a, head, where) {
378
+ if (!head)
379
+ return false;
380
+ if (attachmentContentMatches(a, head))
381
+ return true;
382
+ this.log.warn("attachment content changed after finalize; treating it as unavailable", {
383
+ ...where,
384
+ attachmentId: a.id,
385
+ });
386
+ return false;
340
387
  }
341
388
  /**
342
389
  * 读取一个绑定在该会话、已 ready 的附件(沙箱同步等内核内部用途):没有行、未绑定到该会话、对象已不在、
343
390
  * 大小或 etag 与 finalize 时不符 → null。其余错误(存储不可用等)照常抛出。调用方负责读完或取消 `body`。
344
391
  */
345
392
  async openForConversation(orgId, conversationId, attachmentId) {
346
- const row = await this.db
347
- .selectFrom("attachments")
348
- .select(["name", "content_type", "object_key", "size", "etag"])
349
- .where("id", "=", attachmentId)
350
- .where("org_id", "=", orgId)
351
- .where("conversation_id", "=", conversationId)
352
- .where("purpose", "=", "chat")
353
- .where("status", "=", "ready")
354
- .executeTakeFirst();
393
+ const [row] = await this.boundRows(orgId, conversationId, attachmentId);
355
394
  if (!row)
356
395
  return null;
357
- const got = await this.storage.kernel(orgId).get(row.object_key);
396
+ const got = await this.storage.kernel(orgId).get(row.objectKey);
358
397
  if (!got)
359
398
  return null;
360
- const size = Number(row.size);
361
- if (got.head.size !== size ||
362
- !this.sameContent(row.etag, got.head.etag, { orgId, conversationId, attachmentId })) {
399
+ if (!this.storedMatches(row, got.head, { orgId, conversationId })) {
363
400
  await got.body.cancel().catch(() => { });
364
401
  return null;
365
402
  }
366
- return { name: row.name, contentType: row.content_type, size, body: got.body };
403
+ return { name: row.name, contentType: row.contentType, size: row.size, body: got.body };
367
404
  }
368
405
  /**
369
406
  * 发消息时在调用方事务里绑定附件(行锁),返回写进 user_message 的媒体块(`ref`,按 ids 顺序):
@@ -223,7 +223,7 @@ export declare class ConversationsController {
223
223
  preview: ArtifactPreview;
224
224
  }>;
225
225
  /**
226
- * The conversation's file outputs, newest first, grouped by source path into versions (UI
226
+ * The conversation's file outputs and the attachments sent in it, newest first, grouped by source path into versions (UI
227
227
  * refresh B). `next` is the last file's id (passed back as `after`), null at the end.
228
228
  */
229
229
  listFiles(principal: Principal, org: OrgContext, id: string, q: z.infer<typeof FilesQuery>): Promise<{
@@ -348,7 +348,7 @@ let ConversationsController = class ConversationsController {
348
348
  return { preview: await this.artifacts.preview(org.orgId, id, p.account.id, artifactId) };
349
349
  }
350
350
  /**
351
- * The conversation's file outputs, newest first, grouped by source path into versions (UI
351
+ * The conversation's file outputs and the attachments sent in it, newest first, grouped by source path into versions (UI
352
352
  * refresh B). `next` is the last file's id (passed back as `after`), null at the end.
353
353
  */
354
354
  async listFiles(principal, org, id, q) {
@@ -574,7 +574,11 @@ export declare class ConversationsService {
574
574
  * with the queue, which reads them when a message is queued (decision 15).
575
575
  */
576
576
  resolveExtra(orgId: string, accountId: string, input: Pick<UserMessageInput, "attachments">): Promise<ResolvedExtra>;
577
- /** Binds uploaded files inside the message's (or queue item's) transaction; none → no blocks. */
577
+ /**
578
+ * Binds uploaded files inside the message's (or queue item's) transaction; none → no blocks.
579
+ * The bound files join the conversation's files, so open pages read the list again after the
580
+ * commit (`changed: files`, a hint).
581
+ */
578
582
  bindIn(orgId: string, conversationId: string, accountId: string, files: readonly string[]): Promise<LogContentBlock[]>;
579
583
  private userMessage;
580
584
  /**
@@ -15,6 +15,7 @@ import { unbindConversation } from "../channels/threads.js";
15
15
  import { ConversationDevices, } from "../devices/conversation-devices.js";
16
16
  import { DeviceProjectsService } from "../devices/device-projects.service.js";
17
17
  import { ApiError } from "../errors.js";
18
+ import { afterCommit } from "../infra/database/after-commit.js";
18
19
  import { KernelDb } from "../infra/database/kernel-db.js";
19
20
  import { TransactionHost } from "../infra/database/transaction-host.js";
20
21
  import { Transactional } from "../infra/database/transactional.decorator.js";
@@ -1042,11 +1043,17 @@ let ConversationsService = class ConversationsService {
1042
1043
  return { blocks: [], attachments: [] };
1043
1044
  return this.content.resolveAttachments(orgId, accountId, refs);
1044
1045
  }
1045
- /** Binds uploaded files inside the message's (or queue item's) transaction; none → no blocks. */
1046
+ /**
1047
+ * Binds uploaded files inside the message's (or queue item's) transaction; none → no blocks.
1048
+ * The bound files join the conversation's files, so open pages read the list again after the
1049
+ * commit (`changed: files`, a hint).
1050
+ */
1046
1051
  async bindIn(orgId, conversationId, accountId, files) {
1047
1052
  if (files.length === 0)
1048
1053
  return [];
1049
- return this.attachments.bindForMessage(orgId, conversationId, accountId, files);
1054
+ const blocks = await this.attachments.bindForMessage(orgId, conversationId, accountId, files);
1055
+ afterCommit(() => this.eventLog.publishChanged(conversationId, "files"));
1056
+ return blocks;
1050
1057
  }
1051
1058
  userMessage(accountId, input, extra, fileBlocks, invoked, context, schedule) {
1052
1059
  // a skill invocation's rendered text replaces the typed arguments as content[0]
@@ -1,10 +1,13 @@
1
1
  import { KernelDb } from "../infra/database/kernel-db.js";
2
2
  import { StorageService } from "../storage/storage.service.js";
3
3
  import { ConversationAccess } from "./access.js";
4
+ import { AttachmentsService } from "./attachments.service.js";
4
5
  /**
5
- * A conversation's file outputs (UI refresh B, spec §5.8 / §5.9): the files the agent delivered
6
- * (`artifact_created`), grouped by `sourcePath` into versions, newest first. Read from the log on
7
- * every request (no cache); `status` comes from the object store.
6
+ * A conversation's files (UI refresh B, spec §5.8 / §5.9): the files the agent delivered
7
+ * (`artifact_created`), grouped by `sourcePath` into versions, and the files users sent in it
8
+ * (ready `chat` attachments bound to the conversation), newest first. Read on every request (no
9
+ * cache); `status` comes from the object store. Both kinds are read under the conversation's
10
+ * access: whoever may read the conversation may read the attachments sent in it, nobody else.
8
11
  */
9
12
  /** Versions listed per file (newest first). */
10
13
  export declare const FILE_VERSIONS_MAX = 20;
@@ -32,6 +35,12 @@ export interface FileOutput {
32
35
  /** `removed`: the latest version's object is gone from storage (decision 8). */
33
36
  status: "available" | "removed";
34
37
  previewable: "image" | "text" | null;
38
+ /**
39
+ * `delivered`: the agent delivered it (`artifact_created`); `uploaded`: a user sent it with a
40
+ * message (an attachment: `id` is the attachment id, one version, `sourcePath` is its name and
41
+ * `callId` is empty).
42
+ */
43
+ origin: "delivered" | "uploaded";
35
44
  }
36
45
  /** Text content of one file version, at most the requested bytes. */
37
46
  export interface FileContent {
@@ -52,17 +61,28 @@ export declare class ConversationFiles {
52
61
  private readonly storage;
53
62
  /** Same visibility as the event stream. */
54
63
  private readonly access;
64
+ /** The attachments sent in the conversation, and the rule their stored content must meet. */
65
+ private readonly attachments;
55
66
  constructor(db: KernelDb, storage: Pick<StorageService, "kernel">,
56
67
  /** Same visibility as the event stream. */
57
- access: Pick<ConversationAccess, "isAccessible">);
68
+ access: Pick<ConversationAccess, "isAccessible">,
69
+ /** The attachments sent in the conversation, and the rule their stored content must meet. */
70
+ attachments: Pick<AttachmentsService, "boundRows" | "storedMatches">);
58
71
  private checkAccess;
59
72
  /** Every delivery of the conversation in log order. */
60
73
  private deliveries;
61
74
  /**
62
- * Files newest first by their **first** delivery, so a new version keeps the file's place and a
63
- * cursor stays stable while files are re-delivered (review M2). `after` is a file id from the
64
- * previous page (any version's id finds its file); a cursor that names no file gives an empty
65
- * page. Storage HEADs run at most {@link HEAD_CONCURRENCY} at a time.
75
+ * One file of the conversation by id: a delivered version first, then an attachment sent in it;
76
+ * neither → `conversation.artifact_not_found`. An attachment carries `upload`, the row its stored
77
+ * object must still match. Call after {@link checkAccess}.
78
+ */
79
+ private resolve;
80
+ /**
81
+ * Files newest first: a delivered file by its **first** delivery, so a new version keeps the
82
+ * file's place and a cursor stays stable while files are re-delivered (review M2); an uploaded
83
+ * file by its upload time; equal times by id. `after` is a file id from the previous page (any
84
+ * version's id finds its file); a cursor that names no file gives an empty page. Storage HEADs run
85
+ * at most {@link HEAD_CONCURRENCY} at a time.
66
86
  */
67
87
  list(orgId: string, conversationId: string, viewer: string, opts: {
68
88
  after?: string;
@@ -72,9 +92,11 @@ export declare class ConversationFiles {
72
92
  next: string | null;
73
93
  }>;
74
94
  /**
75
- * One file version of the conversation (any version's id) with its object key, after checking
76
- * the viewer can read the conversation. For the kernel only (previewers, embed grants): the key
77
- * never leaves the kernel.
95
+ * One file version of the conversation (any version's id, or an attachment sent in it) with its
96
+ * object key, after checking the viewer can read the conversation. For the kernel only
97
+ * (previewers, embed grants): the key never leaves the kernel. An attachment whose stored object
98
+ * is gone or no longer the one finalize checked → `conversation.artifact_removed`; `recorded` is
99
+ * then what a later read of the object must still match ({@link attachmentContentMatches}).
78
100
  */
79
101
  file(orgId: string, conversationId: string, viewer: string, fileId: string): Promise<{
80
102
  id: string;
@@ -82,9 +104,14 @@ export declare class ConversationFiles {
82
104
  contentType: string;
83
105
  size: number;
84
106
  objectKey: string;
107
+ recorded?: {
108
+ size: number;
109
+ etag: string | null;
110
+ };
85
111
  }>;
86
112
  /**
87
- * The first `limit` bytes of a text file version (any version's id). Not text, or NUL bytes in
113
+ * The first `limit` bytes of a text file version (any version's id, or an attachment sent in the
114
+ * conversation). Not text, or NUL bytes in
88
115
  * what was read → `conversation.artifact_not_previewable`; the object is gone →
89
116
  * `conversation.artifact_removed`. A cut never splits a UTF-8 character.
90
117
  */
@@ -15,10 +15,13 @@ import { StorageService } from "../storage/storage.service.js";
15
15
  import { UUID_RE } from "../ui/registry.js";
16
16
  import { ConversationAccess } from "./access.js";
17
17
  import { isInlineArtifactType, isTextArtifactType } from "./artifacts.js";
18
+ import { AttachmentsService } from "./attachments.service.js";
18
19
  /**
19
- * A conversation's file outputs (UI refresh B, spec §5.8 / §5.9): the files the agent delivered
20
- * (`artifact_created`), grouped by `sourcePath` into versions, newest first. Read from the log on
21
- * every request (no cache); `status` comes from the object store.
20
+ * A conversation's files (UI refresh B, spec §5.8 / §5.9): the files the agent delivered
21
+ * (`artifact_created`), grouped by `sourcePath` into versions, and the files users sent in it
22
+ * (ready `chat` attachments bound to the conversation), newest first. Read on every request (no
23
+ * cache); `status` comes from the object store. Both kinds are read under the conversation's
24
+ * access: whoever may read the conversation may read the attachments sent in it, nobody else.
22
25
  */
23
26
  /** Versions listed per file (newest first). */
24
27
  export const FILE_VERSIONS_MAX = 20;
@@ -28,6 +31,10 @@ export const FILES_PAGE_MAX = 100;
28
31
  export const FILE_CONTENT_MAX_BYTES = 1024 * 1024;
29
32
  const conversationNotFound = () => new ApiError("conversation.not_found", "Conversation not found");
30
33
  const artifactNotFound = () => new ApiError("conversation.artifact_not_found", "Artifact not found");
34
+ const removed = () => new ApiError("conversation.artifact_removed", "The file is no longer available");
35
+ /** Whether `a` lists before `b`: newer first, then the larger id (a total, stable order). */
36
+ const before = (a, b) => a.at.getTime() !== b.at.getTime() ? a.at.getTime() > b.at.getTime() : a.id > b.id;
37
+ const previewKind = (contentType) => isInlineArtifactType(contentType) ? "image" : isTextArtifactType(contentType) ? "text" : null;
31
38
  /** Drops an incomplete UTF-8 sequence at the end of a cut buffer. */
32
39
  function trimUtf8(b) {
33
40
  let i = b.length - 1;
@@ -82,12 +89,16 @@ let ConversationFiles = class ConversationFiles {
82
89
  db;
83
90
  storage;
84
91
  access;
92
+ attachments;
85
93
  constructor(db, storage,
86
94
  /** Same visibility as the event stream. */
87
- access) {
95
+ access,
96
+ /** The attachments sent in the conversation, and the rule their stored content must meet. */
97
+ attachments) {
88
98
  this.db = db;
89
99
  this.storage = storage;
90
100
  this.access = access;
101
+ this.attachments = attachments;
91
102
  }
92
103
  async checkAccess(orgId, conversationId, viewer) {
93
104
  if (!UUID_RE.test(conversationId))
@@ -110,10 +121,49 @@ let ConversationFiles = class ConversationFiles {
110
121
  }));
111
122
  }
112
123
  /**
113
- * Files newest first by their **first** delivery, so a new version keeps the file's place and a
114
- * cursor stays stable while files are re-delivered (review M2). `after` is a file id from the
115
- * previous page (any version's id finds its file); a cursor that names no file gives an empty
116
- * page. Storage HEADs run at most {@link HEAD_CONCURRENCY} at a time.
124
+ * One file of the conversation by id: a delivered version first, then an attachment sent in it;
125
+ * neither → `conversation.artifact_not_found`. An attachment carries `upload`, the row its stored
126
+ * object must still match. Call after {@link checkAccess}.
127
+ */
128
+ async resolve(orgId, conversationId, fileId) {
129
+ if (!UUID_RE.test(fileId))
130
+ throw artifactNotFound();
131
+ const row = await this.db
132
+ .selectFrom("conversation_events")
133
+ .select("payload")
134
+ .where("conversation_id", "=", conversationId)
135
+ .where("type", "=", "artifact_created")
136
+ .where(sql `payload->>'artifactId'`, "=", fileId)
137
+ .limit(1)
138
+ .executeTakeFirst();
139
+ if (row) {
140
+ const a = row.payload;
141
+ return {
142
+ id: a.artifactId,
143
+ name: a.name,
144
+ contentType: a.contentType,
145
+ size: a.size,
146
+ objectKey: a.objectKey,
147
+ };
148
+ }
149
+ const [u] = await this.attachments.boundRows(orgId, conversationId, fileId);
150
+ if (!u)
151
+ throw artifactNotFound();
152
+ return {
153
+ id: u.id,
154
+ name: u.name,
155
+ contentType: u.contentType,
156
+ size: u.size,
157
+ objectKey: u.objectKey,
158
+ upload: u,
159
+ };
160
+ }
161
+ /**
162
+ * Files newest first: a delivered file by its **first** delivery, so a new version keeps the
163
+ * file's place and a cursor stays stable while files are re-delivered (review M2); an uploaded
164
+ * file by its upload time; equal times by id. `after` is a file id from the previous page (any
165
+ * version's id finds its file); a cursor that names no file gives an empty page. Storage HEADs run
166
+ * at most {@link HEAD_CONCURRENCY} at a time.
117
167
  */
118
168
  async list(orgId, conversationId, viewer, opts) {
119
169
  await this.checkAccess(orgId, conversationId, viewer);
@@ -124,18 +174,65 @@ let ConversationFiles = class ConversationFiles {
124
174
  g.push(d);
125
175
  groups.set(d.sourcePath, g);
126
176
  }
127
- const ordered = [...groups.values()].reverse();
177
+ const delivered = [...groups.values()].reverse().map((g) => {
178
+ const first = g[0];
179
+ return { origin: "delivered", at: first.createdAt, id: first.artifactId, group: g };
180
+ });
181
+ // newest first, the larger id first at equal times
182
+ const bound = (await this.attachments.boundRows(orgId, conversationId)).reverse();
183
+ const uploaded = bound.map((u) => ({
184
+ origin: "uploaded",
185
+ at: u.createdAt,
186
+ id: u.id,
187
+ upload: u,
188
+ }));
189
+ // merge the two newest-first lists (each keeps its own order)
190
+ const ordered = [];
191
+ let i = 0;
192
+ let j = 0;
193
+ while (i < delivered.length || j < uploaded.length) {
194
+ const d = delivered[i];
195
+ const u = uploaded[j];
196
+ if (d && (!u || before(d, u))) {
197
+ ordered.push(d);
198
+ i++;
199
+ }
200
+ else {
201
+ ordered.push(u);
202
+ j++;
203
+ }
204
+ }
128
205
  let start = 0;
129
206
  if (opts.after !== undefined) {
130
207
  const after = opts.after;
131
- const at = ordered.findIndex((g) => g.some((d) => d.artifactId === after));
208
+ const at = ordered.findIndex((e) => e.origin === "delivered" ? e.group.some((d) => d.artifactId === after) : e.id === after);
132
209
  if (at < 0)
133
210
  return { files: [], next: null };
134
211
  start = at + 1;
135
212
  }
136
213
  const page = ordered.slice(start, start + opts.limit);
137
214
  const store = this.storage.kernel(orgId);
138
- const files = await mapLimit(page, HEAD_CONCURRENCY, async (g) => {
215
+ const files = await mapLimit(page, HEAD_CONCURRENCY, async (e) => {
216
+ if (e.origin === "uploaded") {
217
+ const u = e.upload;
218
+ const head = await store.head(u.objectKey);
219
+ const same = this.attachments.storedMatches(u, head, { orgId, conversationId });
220
+ return {
221
+ id: u.id,
222
+ name: u.name,
223
+ contentType: u.contentType,
224
+ size: u.size,
225
+ sourcePath: u.name,
226
+ version: 1,
227
+ versions: [{ id: u.id, size: u.size, createdAt: u.createdAt }],
228
+ callId: "",
229
+ createdAt: u.createdAt,
230
+ status: same ? "available" : "removed",
231
+ previewable: previewKind(u.contentType),
232
+ origin: "uploaded",
233
+ };
234
+ }
235
+ const g = e.group;
139
236
  const latest = g.at(-1);
140
237
  const head = await store.head(latest.objectKey);
141
238
  return {
@@ -152,64 +249,39 @@ let ConversationFiles = class ConversationFiles {
152
249
  callId: latest.callId,
153
250
  createdAt: latest.createdAt,
154
251
  status: head ? "available" : "removed",
155
- previewable: isInlineArtifactType(latest.contentType)
156
- ? "image"
157
- : isTextArtifactType(latest.contentType)
158
- ? "text"
159
- : null,
252
+ previewable: previewKind(latest.contentType),
253
+ origin: "delivered",
160
254
  };
161
255
  });
162
256
  const next = start + opts.limit < ordered.length ? (files.at(-1)?.id ?? null) : null;
163
257
  return { files, next };
164
258
  }
165
259
  /**
166
- * One file version of the conversation (any version's id) with its object key, after checking
167
- * the viewer can read the conversation. For the kernel only (previewers, embed grants): the key
168
- * never leaves the kernel.
260
+ * One file version of the conversation (any version's id, or an attachment sent in it) with its
261
+ * object key, after checking the viewer can read the conversation. For the kernel only
262
+ * (previewers, embed grants): the key never leaves the kernel. An attachment whose stored object
263
+ * is gone or no longer the one finalize checked → `conversation.artifact_removed`; `recorded` is
264
+ * then what a later read of the object must still match ({@link attachmentContentMatches}).
169
265
  */
170
266
  async file(orgId, conversationId, viewer, fileId) {
171
267
  await this.checkAccess(orgId, conversationId, viewer);
172
- if (!UUID_RE.test(fileId))
173
- throw artifactNotFound();
174
- const row = await this.db
175
- .selectFrom("conversation_events")
176
- .select("payload")
177
- .where("conversation_id", "=", conversationId)
178
- .where("type", "=", "artifact_created")
179
- .where(sql `payload->>'artifactId'`, "=", fileId)
180
- .limit(1)
181
- .executeTakeFirst();
182
- if (!row)
183
- throw artifactNotFound();
184
- const a = row.payload;
185
- return {
186
- id: a.artifactId,
187
- name: a.name,
188
- contentType: a.contentType,
189
- size: a.size,
190
- objectKey: a.objectKey,
191
- };
268
+ const { upload, ...f } = await this.resolve(orgId, conversationId, fileId);
269
+ if (!upload)
270
+ return f;
271
+ const head = await this.storage.kernel(orgId).head(upload.objectKey);
272
+ if (!this.attachments.storedMatches(upload, head, { orgId, conversationId }))
273
+ throw removed();
274
+ return { ...f, recorded: { size: upload.size, etag: upload.etag } };
192
275
  }
193
276
  /**
194
- * The first `limit` bytes of a text file version (any version's id). Not text, or NUL bytes in
277
+ * The first `limit` bytes of a text file version (any version's id, or an attachment sent in the
278
+ * conversation). Not text, or NUL bytes in
195
279
  * what was read → `conversation.artifact_not_previewable`; the object is gone →
196
280
  * `conversation.artifact_removed`. A cut never splits a UTF-8 character.
197
281
  */
198
282
  async content(orgId, conversationId, viewer, fileId, limit) {
199
283
  await this.checkAccess(orgId, conversationId, viewer);
200
- if (!UUID_RE.test(fileId))
201
- throw artifactNotFound();
202
- const row = await this.db
203
- .selectFrom("conversation_events")
204
- .select("payload")
205
- .where("conversation_id", "=", conversationId)
206
- .where("type", "=", "artifact_created")
207
- .where(sql `payload->>'artifactId'`, "=", fileId)
208
- .limit(1)
209
- .executeTakeFirst();
210
- if (!row)
211
- throw artifactNotFound();
212
- const a = row.payload;
284
+ const a = await this.resolve(orgId, conversationId, fileId);
213
285
  if (!isTextArtifactType(a.contentType)) {
214
286
  throw new ApiError("conversation.artifact_not_previewable", "Only text files have content");
215
287
  }
@@ -218,7 +290,13 @@ let ConversationFiles = class ConversationFiles {
218
290
  .kernel(orgId)
219
291
  .get(a.objectKey, { range: { start: 0, end: max - 1 } });
220
292
  if (!got)
221
- throw new ApiError("conversation.artifact_removed", "The file is no longer available");
293
+ throw removed();
294
+ // an attachment whose object changed after finalize is not the upload any more
295
+ if (a.upload &&
296
+ !this.attachments.storedMatches(a.upload, got.head, { orgId, conversationId })) {
297
+ await got.body.cancel().catch(() => { });
298
+ throw removed();
299
+ }
222
300
  let body = await readPrefix(got.body, max);
223
301
  if (body.includes(0)) {
224
302
  throw new ApiError("conversation.artifact_not_previewable", "This file contains binary data and has no text content");
@@ -234,6 +312,7 @@ ConversationFiles = __decorate([
234
312
  Injectable(),
235
313
  __param(0, Inject(KernelDb)),
236
314
  __param(1, Inject(StorageService)),
237
- __param(2, Inject(ConversationAccess))
315
+ __param(2, Inject(ConversationAccess)),
316
+ __param(3, Inject(AttachmentsService))
238
317
  ], ConversationFiles);
239
318
  export { ConversationFiles };
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { FILE_PREVIEW_EXTENSION_POINT, previewerAccepts, validateUiView, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable, Optional } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
+ import { attachmentContentMatches } from "../conversations/attachments.service.js";
13
14
  import { ConversationFiles } from "../conversations/files.js";
14
15
  import { ApiError } from "../errors.js";
15
16
  import { EffectiveConfigs } from "../extensions/effective-config.js";
@@ -268,6 +269,11 @@ let PreviewerRegistry = class PreviewerRegistry {
268
269
  const got = await store.get(file.objectKey, { signal: s });
269
270
  if (!got)
270
271
  throw new Error("the file is no longer available");
272
+ // an attachment replaced since it was checked is not the file any more
273
+ if (file.recorded && !attachmentContentMatches(file.recorded, got.head)) {
274
+ await got.body.cancel().catch(() => { });
275
+ throw new Error("the file is no longer available");
276
+ }
271
277
  if (!open || s.aborted) {
272
278
  await got.body.cancel().catch(() => { });
273
279
  throw expired();
@@ -314,7 +314,7 @@ let ConversationsOperations = class ConversationsOperations {
314
314
  }),
315
315
  defineOperation({
316
316
  id: "conversations.files",
317
- description: "List the files one of your conversations produced, newest first: id, name, state (available or removed), type, size and version. File contents are downloaded on the web. Pages by 50: pass the returned next as params.after.",
317
+ description: "List the files of one of your conversations, newest first: the files the agent delivered and the files sent with messages (origin delivered or uploaded), with id, name, state (available or removed), type, size and version. File contents are downloaded on the web. Pages by 50: pass the returned next as params.after.",
318
318
  input: FilesQuery.pick({ after: true }).extend({ conversationId: ConversationId }).strict(),
319
319
  example: { conversationId: "3f2b8a40-6c1d-4e0b-9a77-5d1e2c8b9f10" },
320
320
  authz: { orgAction: "agents.use" },
@@ -342,6 +342,7 @@ let ConversationsOperations = class ConversationsOperations {
342
342
  contentType: f.contentType,
343
343
  size: f.size,
344
344
  version: f.version,
345
+ origin: f.origin,
345
346
  })),
346
347
  next: out.next,
347
348
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.38",
3
+ "version": "0.1.0-rc.39",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -65,7 +65,7 @@
65
65
  "yaml": "^2.9.1",
66
66
  "yauzl": "3.4.0",
67
67
  "zod": "^4.6.7",
68
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.29"
68
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.30"
69
69
  },
70
70
  "devDependencies": {
71
71
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",