@capybara-hq/kernel 0.1.0-rc.51 → 0.1.0-rc.53
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.
- package/bootstrap.json +3 -3
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/config/schema.d.ts +6 -0
- package/dist/config/schema.js +60 -0
- package/dist/conversations/attachments.service.d.ts +87 -11
- package/dist/conversations/attachments.service.js +275 -20
- package/dist/conversations/events.d.ts +9 -0
- package/dist/conversations/events.js +26 -3
- package/dist/conversations/model-image.d.ts +33 -0
- package/dist/conversations/model-image.js +71 -0
- package/dist/db/kernel-schema.d.ts +5 -2
- package/dist/evals/reconstruct.d.ts +6 -1
- package/dist/evals/reconstruct.js +8 -4
- package/dist/evals/recorded-tools.d.ts +7 -0
- package/dist/evals/recorded-tools.js +2 -0
- package/dist/infra/config/kernel-config.service.js +8 -0
- package/dist/media/image-header.d.ts +10 -0
- package/dist/media/image-header.js +87 -0
- package/dist/models/images.d.ts +2 -0
- package/dist/models/images.js +6 -4
- package/dist/models/purposes.d.ts +17 -57
- package/dist/models/purposes.js +25 -4
- package/dist/runtime/context/build.d.ts +73 -28
- package/dist/runtime/context/build.js +189 -35
- package/dist/runtime/model-call.js +16 -10
- package/dist/runtime/usage-report.d.ts +3 -2
- package/dist/runtime/usage-report.js +3 -2
- package/dist/tools/builtins/builtin-tools.d.ts +8 -1
- package/dist/tools/builtins/builtin-tools.js +54 -3
- package/dist/tools/builtins/conversation-files.d.ts +42 -0
- package/dist/tools/builtins/conversation-files.js +105 -0
- package/dist/tools/builtins/image/generate.d.ts +3 -3
- package/dist/tools/builtins/image/generate.js +63 -71
- package/dist/tools/builtins/image/size.d.ts +12 -0
- package/dist/tools/builtins/image/size.js +36 -0
- package/dist/tools/builtins/sandbox/common.d.ts +7 -0
- package/dist/tools/builtins/sandbox/read.d.ts +53 -2
- package/dist/tools/builtins/sandbox/read.js +260 -51
- package/dist/tools/builtins/size-text.d.ts +2 -0
- package/dist/tools/builtins/size-text.js +8 -0
- package/dist/tools/builtins/vision/read-image.d.ts +59 -0
- package/dist/tools/builtins/vision/read-image.js +220 -0
- package/dist/tools/pipeline.js +22 -3
- package/dist/tools/registry.d.ts +9 -1
- package/package.json +5 -4
- package/src/migrations/0163_read_attachments.sql +10 -0
|
@@ -12,6 +12,7 @@ import { MEDIA_LIMITS } from "@capybara-hq/plugin-sdk";
|
|
|
12
12
|
import { Inject, Injectable } from "@nestjs/common";
|
|
13
13
|
import { sql } from "kysely";
|
|
14
14
|
import { ApiError } from "../errors.js";
|
|
15
|
+
import { CacheService } from "../infra/cache/cache.service.js";
|
|
15
16
|
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
16
17
|
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
17
18
|
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
@@ -22,6 +23,7 @@ import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
|
22
23
|
import { StorageService } from "../storage/storage.service.js";
|
|
23
24
|
import { ConversationAccess } from "./access.js";
|
|
24
25
|
import { acceptedContent, isImageContentType, isMediaContentType } from "./media-types.js";
|
|
26
|
+
import { fitImageForModel, MODEL_IMAGE_CACHE_SECONDS, modelImageKey, parseModelImage, serializeModelImage, } from "./model-image.js";
|
|
25
27
|
/** 预签名上传的有效期(秒)。尽量短:表单在有效期内可被再次使用(内容替换由 etag 核对兜底)。 */
|
|
26
28
|
export const ATTACHMENT_UPLOAD_TTL_SECONDS = 300;
|
|
27
29
|
/** 下载跳转的预签名有效期(秒);不短于 {@link ATTACHMENT_DOWNLOAD_CACHE_SECONDS}(浏览器缓存的跳转仍可用)。 */
|
|
@@ -60,6 +62,15 @@ export const skillFilesPrefix = (uploadId) => `skills/${uploadId}/`;
|
|
|
60
62
|
export const ATTACHMENT_CLEANUP_JOB = "attachment-cleanup";
|
|
61
63
|
/** 每批认领的行数。 */
|
|
62
64
|
const CLEANUP_BATCH = 100;
|
|
65
|
+
/** The hourly purge of `read` copies whose conversation was deleted long enough ago. */
|
|
66
|
+
export const ATTACHMENT_READ_PURGE_JOB = "attachments-read-purge";
|
|
67
|
+
/** Rows one claim of the read purge takes. */
|
|
68
|
+
const READ_PURGE_BATCH = 500;
|
|
69
|
+
/**
|
|
70
|
+
* How many sub-agent levels below a deleted conversation the read purge walks (the bound of
|
|
71
|
+
* `conversations/tree.ts`: far above `subagents.maxDepth`, so a corrupt chain cannot loop).
|
|
72
|
+
*/
|
|
73
|
+
const READ_PURGE_TREE_LEVELS = 16;
|
|
63
74
|
/** finalize 时读取开头多少字节核对文件签名。 */
|
|
64
75
|
const SNIFF_BYTES = 1024;
|
|
65
76
|
/**
|
|
@@ -70,14 +81,24 @@ export function attachmentContentMatches(recorded, head) {
|
|
|
70
81
|
return head.size === recorded.size && (recorded.etag === null || recorded.etag === head.etag);
|
|
71
82
|
}
|
|
72
83
|
const notFound = () => new ApiError("attachment.not_found", "Attachment not found");
|
|
84
|
+
/**
|
|
85
|
+
* The purposes request building reads bytes of: chat attachments and the `read` copies of the
|
|
86
|
+
* builtin Read. Every other lookup (listing, sandbox sync, download, binding) stays `chat` only.
|
|
87
|
+
*/
|
|
88
|
+
const MEDIA_PURPOSES = ["chat", "read"];
|
|
73
89
|
/** 去掉参数、转小写:`Text/Plain; charset=utf-8` → `text/plain`。 */
|
|
74
90
|
export const normalizeContentType = (ct) => (ct.split(";")[0] ?? "").trim().toLowerCase();
|
|
75
|
-
/**
|
|
91
|
+
/**
|
|
92
|
+
* The object key: the attachment id only (the user's file name never goes into a key), under one
|
|
93
|
+
* prefix per purpose.
|
|
94
|
+
*/
|
|
76
95
|
const objectKey = (id, purpose = "chat") => purpose === "chat"
|
|
77
96
|
? `attachments/${id}`
|
|
78
97
|
: purpose === "agent-avatar"
|
|
79
98
|
? `agent-avatars/${id}`
|
|
80
|
-
:
|
|
99
|
+
: purpose === "read"
|
|
100
|
+
? `read-images/${id}`
|
|
101
|
+
: `skill-packages/${id}`;
|
|
81
102
|
const startsWith = (b, sig, at = 0) => sig.every((x, i) => b[at + i] === x);
|
|
82
103
|
const ascii = (s) => [...s].map((c) => c.charCodeAt(0));
|
|
83
104
|
/**
|
|
@@ -132,15 +153,19 @@ let AttachmentsService = class AttachmentsService {
|
|
|
132
153
|
access;
|
|
133
154
|
log;
|
|
134
155
|
txHost;
|
|
156
|
+
cache;
|
|
135
157
|
constructor(db, storage, config,
|
|
136
158
|
/** viewer 能否访问该会话(与会话流相同的规则)。 */
|
|
137
|
-
access, log, txHost
|
|
159
|
+
access, log, txHost,
|
|
160
|
+
/** where the model-sized copies of images are kept between steps ({@link fetchMedia}) */
|
|
161
|
+
cache) {
|
|
138
162
|
this.db = db;
|
|
139
163
|
this.storage = storage;
|
|
140
164
|
this.config = config;
|
|
141
165
|
this.access = access;
|
|
142
166
|
this.log = log;
|
|
143
167
|
this.txHost = txHost;
|
|
168
|
+
this.cache = cache;
|
|
144
169
|
}
|
|
145
170
|
/** 单个附件的大小上限:配置的 `maxBytes`,图片再受 `MEDIA_LIMITS.imageBytes` 限制。 */
|
|
146
171
|
limitFor(contentType) {
|
|
@@ -251,6 +276,8 @@ let AttachmentsService = class AttachmentsService {
|
|
|
251
276
|
.where("org_id", "=", orgId)
|
|
252
277
|
.where("account_id", "=", accountId)
|
|
253
278
|
.where("status", "in", ["pending", "ready"])
|
|
279
|
+
// read copies are the kernel's own (storeRead binds them); nobody finalizes them
|
|
280
|
+
.where("purpose", "<>", "read")
|
|
254
281
|
.executeTakeFirst();
|
|
255
282
|
if (!row)
|
|
256
283
|
throw notFound();
|
|
@@ -347,15 +374,17 @@ let AttachmentsService = class AttachmentsService {
|
|
|
347
374
|
/**
|
|
348
375
|
* The ready `chat` attachments bound to the conversation in this org (never another purpose, a
|
|
349
376
|
* 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.
|
|
377
|
+
* Nothing here checks who reads them: callers check the conversation's access first. `purposes`
|
|
378
|
+
* widens it for a model-facing lookup only (`read` copies; vision-read design §1.1): every
|
|
379
|
+
* person- or device-facing caller keeps the default.
|
|
351
380
|
*/
|
|
352
|
-
async boundRows(orgId, conversationId, id) {
|
|
381
|
+
async boundRows(orgId, conversationId, id, purposes = ["chat"]) {
|
|
353
382
|
let q = this.db
|
|
354
383
|
.selectFrom("attachments")
|
|
355
384
|
.select(["id", "name", "content_type", "size", "object_key", "etag", "created_at"])
|
|
356
385
|
.where("org_id", "=", orgId)
|
|
357
386
|
.where("conversation_id", "=", conversationId)
|
|
358
|
-
.where("purpose", "
|
|
387
|
+
.where("purpose", "in", [...purposes])
|
|
359
388
|
.where("status", "=", "ready");
|
|
360
389
|
if (id !== undefined)
|
|
361
390
|
q = q.where("id", "=", id);
|
|
@@ -389,11 +418,16 @@ let AttachmentsService = class AttachmentsService {
|
|
|
389
418
|
* 读取一个绑定在该会话、已 ready 的附件(沙箱同步等内核内部用途):没有行、未绑定到该会话、对象已不在、
|
|
390
419
|
* 大小或 etag 与 finalize 时不符 → null。其余错误(存储不可用等)照常抛出。调用方负责读完或取消 `body`。
|
|
391
420
|
*/
|
|
392
|
-
async openForConversation(orgId, conversationId, attachmentId) {
|
|
393
|
-
const [row] = await this.boundRows(orgId, conversationId, attachmentId);
|
|
421
|
+
async openForConversation(orgId, conversationId, attachmentId, opts = {}) {
|
|
422
|
+
const [row] = await this.boundRows(orgId, conversationId, attachmentId, opts.purposes);
|
|
394
423
|
if (!row)
|
|
395
424
|
return null;
|
|
396
|
-
const got = await this.storage.kernel(orgId).get(row.objectKey
|
|
425
|
+
const got = await this.storage.kernel(orgId).get(row.objectKey, {
|
|
426
|
+
...(opts.signal !== undefined && { signal: opts.signal }),
|
|
427
|
+
// only a larger object is ranged (a range on an empty object is unsatisfiable)
|
|
428
|
+
...(opts.maxBytes !== undefined &&
|
|
429
|
+
row.size > opts.maxBytes && { range: { start: 0, end: opts.maxBytes - 1 } }),
|
|
430
|
+
});
|
|
397
431
|
if (!got)
|
|
398
432
|
return null;
|
|
399
433
|
if (!this.storedMatches(row, got.head, { orgId, conversationId })) {
|
|
@@ -507,8 +541,10 @@ let AttachmentsService = class AttachmentsService {
|
|
|
507
541
|
return false;
|
|
508
542
|
}
|
|
509
543
|
/**
|
|
510
|
-
*
|
|
511
|
-
*
|
|
544
|
+
* The recorded facts request building needs about attachments (only ready `chat` or `read` rows
|
|
545
|
+
* bound to this conversation): size, PDF page count, and the object's unsigned reference
|
|
546
|
+
* (`ObjectStore.uri`, falling back to `capybara://attachments/<id>`). An id with no row is left
|
|
547
|
+
* out; a failed query throws.
|
|
512
548
|
*/
|
|
513
549
|
async mediaInfo(orgId, conversationId, ids) {
|
|
514
550
|
if (ids.length === 0)
|
|
@@ -518,7 +554,7 @@ let AttachmentsService = class AttachmentsService {
|
|
|
518
554
|
.select(["id", "size", "pages", "etag", "object_key"])
|
|
519
555
|
.where("org_id", "=", orgId)
|
|
520
556
|
.where("conversation_id", "=", conversationId)
|
|
521
|
-
.where("purpose", "
|
|
557
|
+
.where("purpose", "in", MEDIA_PURPOSES)
|
|
522
558
|
.where("status", "=", "ready")
|
|
523
559
|
.where("id", "in", [...ids])
|
|
524
560
|
.execute();
|
|
@@ -534,9 +570,14 @@ let AttachmentsService = class AttachmentsService {
|
|
|
534
570
|
]));
|
|
535
571
|
}
|
|
536
572
|
/**
|
|
537
|
-
*
|
|
538
|
-
*
|
|
539
|
-
*
|
|
573
|
+
* The bytes request building sends, only of ready `chat` or `read` rows bound to this
|
|
574
|
+
* conversation. Null only when certainly gone: no row, the object missing, or its size or etag
|
|
575
|
+
* not the recorded one (content replaced, logged as a warning). Every other error (storage
|
|
576
|
+
* unavailable, network) throws (Ruling M4) for the caller to treat as retryable, never a
|
|
577
|
+
* placeholder. An id in `caps` is read by range up to that many leading bytes (the `text/*` cap).
|
|
578
|
+
* A whole image comes back as its model-sized copy ({@link fitImageForModel}), whose media type
|
|
579
|
+
* may differ from the row's; the copy is cached for {@link MODEL_IMAGE_CACHE_SECONDS} under the
|
|
580
|
+
* attachment's id and etag, so later steps of the conversation only check the object's head.
|
|
540
581
|
*/
|
|
541
582
|
async fetchMedia(orgId, conversationId, ids, caps) {
|
|
542
583
|
const out = new Map();
|
|
@@ -547,7 +588,7 @@ let AttachmentsService = class AttachmentsService {
|
|
|
547
588
|
.select(["id", "content_type", "object_key", "size", "etag"])
|
|
548
589
|
.where("org_id", "=", orgId)
|
|
549
590
|
.where("conversation_id", "=", conversationId)
|
|
550
|
-
.where("purpose", "
|
|
591
|
+
.where("purpose", "in", MEDIA_PURPOSES)
|
|
551
592
|
.where("status", "=", "ready")
|
|
552
593
|
.where("id", "in", [...ids])
|
|
553
594
|
.execute();
|
|
@@ -558,11 +599,28 @@ let AttachmentsService = class AttachmentsService {
|
|
|
558
599
|
if (!r)
|
|
559
600
|
return out.set(id, null);
|
|
560
601
|
const cap = caps?.get(id);
|
|
602
|
+
const where = { orgId, conversationId, attachmentId: id };
|
|
603
|
+
// a whole image already scaled for the model: the cached copy, once the object checks out
|
|
604
|
+
const cacheKey = cap === undefined && isImageContentType(r.content_type)
|
|
605
|
+
? modelImageKey(orgId, r)
|
|
606
|
+
: undefined;
|
|
607
|
+
const cached = cacheKey === undefined ? null : parseModelImage(await this.cache.get(cacheKey));
|
|
608
|
+
if (cached) {
|
|
609
|
+
const head = await store.head(r.object_key);
|
|
610
|
+
if (!head)
|
|
611
|
+
return out.set(id, null);
|
|
612
|
+
if (head.size !== Number(r.size) || !this.sameContent(r.etag, head.etag, where)) {
|
|
613
|
+
if (head.size !== Number(r.size)) {
|
|
614
|
+
this.log.warn("attachment size changed after finalize; treating it as unavailable", where);
|
|
615
|
+
}
|
|
616
|
+
return out.set(id, null);
|
|
617
|
+
}
|
|
618
|
+
return out.set(id, cached);
|
|
619
|
+
}
|
|
561
620
|
const want = cap !== undefined && cap < Number(r.size) ? Math.max(1, cap) : Number(r.size);
|
|
562
621
|
const got = await store.get(r.object_key, want < Number(r.size) ? { range: { start: 0, end: want - 1 } } : undefined);
|
|
563
622
|
if (!got)
|
|
564
623
|
return out.set(id, null);
|
|
565
|
-
const where = { orgId, conversationId, attachmentId: id };
|
|
566
624
|
if (got.head.size !== Number(r.size) || !this.sameContent(r.etag, got.head.etag, where)) {
|
|
567
625
|
if (got.head.size !== Number(r.size)) {
|
|
568
626
|
this.log.warn("attachment size changed after finalize; treating it as unavailable", where);
|
|
@@ -573,7 +631,18 @@ let AttachmentsService = class AttachmentsService {
|
|
|
573
631
|
// 提供方没按范围读、给了整个对象时只留开头
|
|
574
632
|
const all = await readAll(got.body);
|
|
575
633
|
const data = all.byteLength === Number(r.size) ? all.subarray(0, want) : all;
|
|
576
|
-
|
|
634
|
+
if (data.byteLength !== want)
|
|
635
|
+
return out.set(id, null);
|
|
636
|
+
const media = { mediaType: r.content_type, data };
|
|
637
|
+
if (cacheKey === undefined) {
|
|
638
|
+
return out.set(id, media);
|
|
639
|
+
}
|
|
640
|
+
// a whole image goes out as the model-sized copy (the stored object stays unchanged)
|
|
641
|
+
const fitted = await fitImageForModel(media);
|
|
642
|
+
if (fitted !== media) {
|
|
643
|
+
await this.cache.set(cacheKey, serializeModelImage(fitted), MODEL_IMAGE_CACHE_SECONDS);
|
|
644
|
+
}
|
|
645
|
+
out.set(id, fitted);
|
|
577
646
|
}));
|
|
578
647
|
return out;
|
|
579
648
|
}
|
|
@@ -733,6 +802,173 @@ let AttachmentsService = class AttachmentsService {
|
|
|
733
802
|
responseContentType: row.content_type,
|
|
734
803
|
});
|
|
735
804
|
}
|
|
805
|
+
/**
|
|
806
|
+
* Stores the copy of an image the builtin Read read, bound to the calling conversation (never its
|
|
807
|
+
* root), intent first so a crash leaves nothing unowned (vision-read design §1.3):
|
|
808
|
+
* 1. the per-conversation cap `attachments.readMaxBytesPerConversation` (the sizes of the
|
|
809
|
+
* conversation's `read` rows plus this one; 0 refuses always) → `{ ok: false, reason: "cap" }`,
|
|
810
|
+
* nothing stored. Concurrent calls may pass it together: a soft cap;
|
|
811
|
+
* 2. the row, unbound, `pending`, expiring after `attachments.unboundTtlHours`, so
|
|
812
|
+
* {@link deleteExpired} collects it after a crash; with no `accountId` (a run nobody started)
|
|
813
|
+
* it is the conversation owner's;
|
|
814
|
+
* 3. the object under `read-images/<id>` (a failed put throws and leaves the row to expire);
|
|
815
|
+
* 4. one transaction binding it: the conversation, `ready`, no expiry, the stored size and etag.
|
|
816
|
+
* No object store → `storage.unavailable`. A conversation not in the org → an error, nothing stored.
|
|
817
|
+
*/
|
|
818
|
+
async storeRead(orgId, conversationId, accountId, file) {
|
|
819
|
+
this.storage.assertAvailable();
|
|
820
|
+
const size = file.data.byteLength;
|
|
821
|
+
const cap = this.config.get().attachments.readMaxBytesPerConversation;
|
|
822
|
+
if (cap === 0)
|
|
823
|
+
return { ok: false, reason: "cap" };
|
|
824
|
+
const used = await this.db
|
|
825
|
+
.selectFrom("attachments")
|
|
826
|
+
.select(sql `coalesce(sum(size), 0)`.as("n"))
|
|
827
|
+
.where("org_id", "=", orgId)
|
|
828
|
+
.where("conversation_id", "=", conversationId)
|
|
829
|
+
.where("purpose", "=", "read")
|
|
830
|
+
.executeTakeFirst();
|
|
831
|
+
if (Number(used?.n ?? 0) + size > cap)
|
|
832
|
+
return { ok: false, reason: "cap" };
|
|
833
|
+
const id = randomUUID();
|
|
834
|
+
const key = objectKey(id, "read");
|
|
835
|
+
const contentType = normalizeContentType(file.contentType);
|
|
836
|
+
await this.insertReadIntent(orgId, conversationId, accountId, {
|
|
837
|
+
id,
|
|
838
|
+
key,
|
|
839
|
+
name: file.name,
|
|
840
|
+
contentType,
|
|
841
|
+
size,
|
|
842
|
+
});
|
|
843
|
+
const head = await this.storage
|
|
844
|
+
.kernel(orgId)
|
|
845
|
+
.put(key, file.data, { contentType: contentType || "application/octet-stream" });
|
|
846
|
+
await this.bindRead(id, conversationId, head.size, head.etag ?? null);
|
|
847
|
+
return { ok: true, attachmentId: id, size: head.size };
|
|
848
|
+
}
|
|
849
|
+
/**
|
|
850
|
+
* Step 2 of {@link storeRead}: the unbound intent row, in its own transaction so it is committed
|
|
851
|
+
* before the put even when the caller holds one (a rollback must never leave an object with no
|
|
852
|
+
* row). The INSERT ... SELECT proves the conversation is in the org; with no `accountId` the row
|
|
853
|
+
* is the conversation owner's.
|
|
854
|
+
*/
|
|
855
|
+
async insertReadIntent(orgId, conversationId, accountId, r) {
|
|
856
|
+
const { unboundTtlHours } = this.config.get().attachments;
|
|
857
|
+
const inserted = await this.db.db
|
|
858
|
+
.insertInto("attachments")
|
|
859
|
+
.columns([
|
|
860
|
+
"id",
|
|
861
|
+
"org_id",
|
|
862
|
+
"account_id",
|
|
863
|
+
"name",
|
|
864
|
+
"content_type",
|
|
865
|
+
"size",
|
|
866
|
+
"object_key",
|
|
867
|
+
"status",
|
|
868
|
+
"purpose",
|
|
869
|
+
"expires_at",
|
|
870
|
+
])
|
|
871
|
+
.expression((eb) => eb
|
|
872
|
+
.selectFrom("conversations")
|
|
873
|
+
.select([
|
|
874
|
+
sql.val(r.id).as("id"),
|
|
875
|
+
"org_id",
|
|
876
|
+
accountId === null ? "account_id" : sql.val(accountId).as("account_id"),
|
|
877
|
+
sql.val(r.name).as("name"),
|
|
878
|
+
sql.val(r.contentType).as("content_type"),
|
|
879
|
+
sql.val(r.size).as("size"),
|
|
880
|
+
sql.val(r.key).as("object_key"),
|
|
881
|
+
sql.lit("pending").as("status"),
|
|
882
|
+
sql.lit("read").as("purpose"),
|
|
883
|
+
sql `now() + make_interval(hours => ${unboundTtlHours})`.as("expires_at"),
|
|
884
|
+
])
|
|
885
|
+
.where("id", "=", conversationId)
|
|
886
|
+
.where("org_id", "=", orgId))
|
|
887
|
+
.executeTakeFirst();
|
|
888
|
+
if (Number(inserted.numInsertedOrUpdatedRows ?? 0) !== 1) {
|
|
889
|
+
throw new Error(`conversation ${conversationId} not found in org ${orgId}`);
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
/** Step 4 of {@link storeRead}: binds the unbound row in one transaction. */
|
|
893
|
+
async bindRead(id, conversationId, size, etag) {
|
|
894
|
+
const bound = await this.db.db
|
|
895
|
+
.updateTable("attachments")
|
|
896
|
+
.set({ conversation_id: conversationId, status: "ready", expires_at: null, size, etag })
|
|
897
|
+
.where("id", "=", id)
|
|
898
|
+
.where("purpose", "=", "read")
|
|
899
|
+
.where("status", "=", "pending")
|
|
900
|
+
.where("conversation_id", "is", null)
|
|
901
|
+
.executeTakeFirst();
|
|
902
|
+
if (Number(bound.numUpdatedRows) !== 1) {
|
|
903
|
+
throw new Error(`read attachment ${id} is no longer pending; cannot bind it`);
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
/**
|
|
907
|
+
* Purges the `read` copies of conversations deleted more than `attachments.readPurgeAfterHours`
|
|
908
|
+
* ago (read at run time), and of the sub-agent conversations below them (a sub-agent
|
|
909
|
+
* conversation keeps `deleted_at` null when its root is deleted): claims up to
|
|
910
|
+
* {@link READ_PURGE_BATCH} rows at a time as `deleting` (`FOR UPDATE SKIP LOCKED`, so concurrent
|
|
911
|
+
* runs never share a row), deletes each object, then the row. A row whose object delete fails stays `deleting` and is claimed again on the next run.
|
|
912
|
+
* Chat attachments of deleted conversations are not touched. Does nothing without an object
|
|
913
|
+
* store. Returns the number of rows deleted.
|
|
914
|
+
*/
|
|
915
|
+
async purgeRead() {
|
|
916
|
+
if (!this.storage.available)
|
|
917
|
+
return 0;
|
|
918
|
+
const hours = this.config.get().attachments.readPurgeAfterHours;
|
|
919
|
+
let deleted = 0;
|
|
920
|
+
const failed = [];
|
|
921
|
+
for (;;) {
|
|
922
|
+
const claimed = await this.db
|
|
923
|
+
.updateTable("attachments")
|
|
924
|
+
.set({ status: "deleting" })
|
|
925
|
+
.where("id", "in", this.db
|
|
926
|
+
.selectFrom("attachments")
|
|
927
|
+
.select("id")
|
|
928
|
+
.where("purpose", "=", "read")
|
|
929
|
+
.where("conversation_id", "in", sql `(
|
|
930
|
+
WITH RECURSIVE gone(id, level) AS (
|
|
931
|
+
SELECT c.id, 0 FROM capybara.conversations c
|
|
932
|
+
WHERE c.deleted_at < now() - make_interval(hours => ${hours})
|
|
933
|
+
UNION ALL
|
|
934
|
+
SELECT c.id, g.level + 1
|
|
935
|
+
FROM capybara.conversations c JOIN gone g ON c.parent_conversation_id = g.id
|
|
936
|
+
WHERE c.kind = 'subagent' AND g.level < ${READ_PURGE_TREE_LEVELS}
|
|
937
|
+
)
|
|
938
|
+
SELECT id FROM gone
|
|
939
|
+
)`)
|
|
940
|
+
.$if(failed.length > 0, (q) => q.where("id", "not in", failed))
|
|
941
|
+
.orderBy("created_at")
|
|
942
|
+
.limit(READ_PURGE_BATCH)
|
|
943
|
+
.forUpdate()
|
|
944
|
+
.skipLocked())
|
|
945
|
+
.returning(["id", "org_id", "object_key"])
|
|
946
|
+
.execute();
|
|
947
|
+
if (claimed.length === 0)
|
|
948
|
+
return deleted;
|
|
949
|
+
for (const r of claimed) {
|
|
950
|
+
try {
|
|
951
|
+
await this.storage.kernel(r.org_id).delete(r.object_key);
|
|
952
|
+
await this.db
|
|
953
|
+
.deleteFrom("attachments")
|
|
954
|
+
.where("id", "=", r.id)
|
|
955
|
+
.where("purpose", "=", "read")
|
|
956
|
+
.execute();
|
|
957
|
+
deleted++;
|
|
958
|
+
}
|
|
959
|
+
catch (err) {
|
|
960
|
+
failed.push(r.id);
|
|
961
|
+
this.log.warn("cannot purge read attachment; will retry", {
|
|
962
|
+
orgId: r.org_id,
|
|
963
|
+
attachmentId: r.id,
|
|
964
|
+
err,
|
|
965
|
+
});
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
if (claimed.length < READ_PURGE_BATCH)
|
|
969
|
+
return deleted;
|
|
970
|
+
}
|
|
971
|
+
}
|
|
736
972
|
/**
|
|
737
973
|
* 删除过期(`expires_at < now()`)且从未绑定到会话的附件:先把行认领为 `deleting`(`FOR UPDATE SKIP LOCKED`,
|
|
738
974
|
* 多副本并发时互不重复),再删对象、删行。删对象失败的行保持 `deleting`,下次运行重试。
|
|
@@ -808,6 +1044,12 @@ __decorate([
|
|
|
808
1044
|
__decorate([
|
|
809
1045
|
Transactional({ propagation: "mandatory" })
|
|
810
1046
|
], AttachmentsService.prototype, "consumeAgentAvatar", null);
|
|
1047
|
+
__decorate([
|
|
1048
|
+
Transactional({ propagation: "requires_new" })
|
|
1049
|
+
], AttachmentsService.prototype, "insertReadIntent", null);
|
|
1050
|
+
__decorate([
|
|
1051
|
+
Transactional()
|
|
1052
|
+
], AttachmentsService.prototype, "bindRead", null);
|
|
811
1053
|
AttachmentsService = __decorate([
|
|
812
1054
|
Injectable(),
|
|
813
1055
|
__param(0, Inject(KernelDb)),
|
|
@@ -815,10 +1057,15 @@ AttachmentsService = __decorate([
|
|
|
815
1057
|
__param(2, Inject(KernelConfigService)),
|
|
816
1058
|
__param(3, Inject(ConversationAccess)),
|
|
817
1059
|
__param(4, Inject(KERNEL_LOGGER)),
|
|
818
|
-
__param(5, Inject(TransactionHost))
|
|
1060
|
+
__param(5, Inject(TransactionHost)),
|
|
1061
|
+
__param(6, Inject(CacheService))
|
|
819
1062
|
], AttachmentsService);
|
|
820
1063
|
export { AttachmentsService };
|
|
821
|
-
/**
|
|
1064
|
+
/**
|
|
1065
|
+
* The hourly attachment jobs, each once per tick across replicas (provided only under
|
|
1066
|
+
* `WorkerModule`): the cleanup of expired unbound attachments and the purge of `read` copies of
|
|
1067
|
+
* deleted conversations.
|
|
1068
|
+
*/
|
|
822
1069
|
let AttachmentCleanupJob = class AttachmentCleanupJob {
|
|
823
1070
|
attachments;
|
|
824
1071
|
lockService;
|
|
@@ -833,10 +1080,18 @@ let AttachmentCleanupJob = class AttachmentCleanupJob {
|
|
|
833
1080
|
if (n > 0)
|
|
834
1081
|
this.log.info("expired attachments deleted", { count: n });
|
|
835
1082
|
}
|
|
1083
|
+
async purgeRead() {
|
|
1084
|
+
const n = await this.attachments.purgeRead();
|
|
1085
|
+
if (n > 0)
|
|
1086
|
+
this.log.info("read attachments of deleted conversations purged", { count: n });
|
|
1087
|
+
}
|
|
836
1088
|
};
|
|
837
1089
|
__decorate([
|
|
838
1090
|
LockedCron("0 * * * *", { name: ATTACHMENT_CLEANUP_JOB })
|
|
839
1091
|
], AttachmentCleanupJob.prototype, "run", null);
|
|
1092
|
+
__decorate([
|
|
1093
|
+
LockedCron("0 * * * *", { name: ATTACHMENT_READ_PURGE_JOB })
|
|
1094
|
+
], AttachmentCleanupJob.prototype, "purgeRead", null);
|
|
840
1095
|
AttachmentCleanupJob = __decorate([
|
|
841
1096
|
Injectable(),
|
|
842
1097
|
__param(0, Inject(AttachmentsService)),
|
|
@@ -824,6 +824,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
|
|
|
824
824
|
bytes: "bytes";
|
|
825
825
|
excluded: "excluded";
|
|
826
826
|
inline: "inline";
|
|
827
|
+
not_included: "not_included";
|
|
827
828
|
omitted: "omitted";
|
|
828
829
|
placeholder_unsupported: "placeholder_unsupported";
|
|
829
830
|
reference: "reference";
|
|
@@ -835,6 +836,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
|
|
|
835
836
|
etag: z.ZodOptional<z.ZodString>;
|
|
836
837
|
}, z.core.$strip>>>;
|
|
837
838
|
mediaBudgetBytes: z.ZodOptional<z.ZodNumber>;
|
|
839
|
+
readImagesPerRequest: z.ZodOptional<z.ZodNumber>;
|
|
838
840
|
fit: z.ZodOptional<z.ZodObject<{
|
|
839
841
|
droppedMessageIndexes: z.ZodArray<z.ZodNumber>;
|
|
840
842
|
truncated: z.ZodArray<z.ZodObject<{
|
|
@@ -944,6 +946,7 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
|
|
|
944
946
|
review: "review";
|
|
945
947
|
suggestion: "suggestion";
|
|
946
948
|
title: "title";
|
|
949
|
+
vision: "vision";
|
|
947
950
|
web_fetch: "web_fetch";
|
|
948
951
|
}>>;
|
|
949
952
|
chunk: z.ZodOptional<z.ZodNumber>;
|
|
@@ -1191,6 +1194,12 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
|
|
|
1191
1194
|
view: z.ZodString;
|
|
1192
1195
|
key: z.ZodOptional<z.ZodString>;
|
|
1193
1196
|
}, z.core.$strip>>;
|
|
1197
|
+
media: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
1198
|
+
attachmentId: z.ZodString & z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>;
|
|
1199
|
+
name: z.ZodString;
|
|
1200
|
+
mediaType: z.ZodString;
|
|
1201
|
+
size: z.ZodNumber;
|
|
1202
|
+
}, z.core.$strip>>>;
|
|
1194
1203
|
}, z.core.$strip>;
|
|
1195
1204
|
}, z.core.$strip>, z.ZodObject<{
|
|
1196
1205
|
type: z.ZodLiteral<"connection_required">;
|
|
@@ -813,8 +813,9 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
|
|
|
813
813
|
* reference line only (`reference`: a `file` block, or text over the inline cap), a
|
|
814
814
|
* placeholder for an unsupported kind, left out for the request's media budget
|
|
815
815
|
* (`omitted`), too many images (`too_many_images`), one over the provider's limit
|
|
816
|
-
* (`too_large`), no longer available, too many PDF pages,
|
|
817
|
-
*
|
|
816
|
+
* (`too_large`), no longer available, too many PDF pages, excluded by `media_excluded`,
|
|
817
|
+
* or an image from Read left out by the Read-image window (`not_included`). Absent without
|
|
818
|
+
* media; written together with `mediaBudgetBytes`.
|
|
818
819
|
*/
|
|
819
820
|
media: z
|
|
820
821
|
.array(z.object({
|
|
@@ -830,6 +831,7 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
|
|
|
830
831
|
"unavailable",
|
|
831
832
|
"too_many_pages",
|
|
832
833
|
"excluded",
|
|
834
|
+
"not_included",
|
|
833
835
|
]),
|
|
834
836
|
etag: z.string().max(1024).optional(),
|
|
835
837
|
}))
|
|
@@ -840,6 +842,12 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
|
|
|
840
842
|
* it to repeat the same omissions.
|
|
841
843
|
*/
|
|
842
844
|
mediaBudgetBytes: count.optional(),
|
|
845
|
+
/**
|
|
846
|
+
* The Read-image window (`attachments.readImagesPerRequest`, see planMedia) the request was
|
|
847
|
+
* built with: written only when the request renders an image from Read
|
|
848
|
+
* (`tool_result.media`); reconstruction uses it to repeat the same evictions.
|
|
849
|
+
*/
|
|
850
|
+
readImagesPerRequest: count.optional(),
|
|
843
851
|
/**
|
|
844
852
|
* The hard fit guard's plan (context compaction spec §4.3): indexes into the assembled
|
|
845
853
|
* request's message list that were dropped, and text / tool_result blocks replaced by the
|
|
@@ -884,7 +892,7 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
|
|
|
884
892
|
model: z.string(),
|
|
885
893
|
...ModelUsageShape,
|
|
886
894
|
purpose: z
|
|
887
|
-
.enum(["compaction", "title", "web_fetch", "review", "image", "suggestion"])
|
|
895
|
+
.enum(["compaction", "title", "web_fetch", "review", "image", "vision", "suggestion"])
|
|
888
896
|
.optional(),
|
|
889
897
|
/**
|
|
890
898
|
* The chunk a chunked compaction call summarised (1-based), with the number of calls the
|
|
@@ -1081,6 +1089,21 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
|
|
|
1081
1089
|
key: z.string().min(1).max(200).optional(),
|
|
1082
1090
|
})
|
|
1083
1091
|
.optional(),
|
|
1092
|
+
/**
|
|
1093
|
+
* The images the builtin Read stored for the call (vision-read design §1.2): `read`
|
|
1094
|
+
* attachments bound to this conversation, one per image. Model-visible: request building
|
|
1095
|
+
* renders each after the step's tool results (`Image from Read (file_id <id>):` and the image,
|
|
1096
|
+
* or the no-vision text), inside the Read-image window. Only the builtin Read sets it.
|
|
1097
|
+
*/
|
|
1098
|
+
media: z
|
|
1099
|
+
.array(z.object({
|
|
1100
|
+
attachmentId: AttachmentIdSchema,
|
|
1101
|
+
name: z.string().min(1).max(1000),
|
|
1102
|
+
mediaType: z.string().min(1).max(200),
|
|
1103
|
+
size: count,
|
|
1104
|
+
}))
|
|
1105
|
+
.min(1)
|
|
1106
|
+
.optional(),
|
|
1084
1107
|
})),
|
|
1085
1108
|
/**
|
|
1086
1109
|
* 工具调用时发现发起人尚未连接个人凭据的连接器:界面据此显示连接卡片(不进模型请求;模型看到的是
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { MediaBytes } from "../runtime/context/build.js";
|
|
2
|
+
/**
|
|
3
|
+
* The longest edge, in pixels, of an image sent to a model. Providers scale larger images down on
|
|
4
|
+
* their side anyway (to roughly 1.5k-2k pixels), so the extra pixels only cost upload time on every
|
|
5
|
+
* request that carries the image again.
|
|
6
|
+
*/
|
|
7
|
+
export declare const MODEL_IMAGE_MAX_EDGE = 2048;
|
|
8
|
+
/** An image at most this large and within {@link MODEL_IMAGE_MAX_EDGE} is sent unchanged. */
|
|
9
|
+
export declare const MODEL_IMAGE_KEEP_BYTES = 1048576;
|
|
10
|
+
/**
|
|
11
|
+
* The copy of an image a model request carries. Images over {@link MODEL_IMAGE_KEEP_BYTES} or
|
|
12
|
+
* larger than {@link MODEL_IMAGE_MAX_EDGE} on an edge are scaled to fit that edge (never enlarged)
|
|
13
|
+
* and re-encoded: JPEG when every pixel is opaque, WebP when some are transparent, so transparency
|
|
14
|
+
* stays visible. The result is a pure function of the stored bytes, so rebuilding a recorded request
|
|
15
|
+
* gives the same copy. The stored attachment is never changed. Bytes that fail to decode, and a
|
|
16
|
+
* re-encoded copy no smaller than the original, are returned unchanged.
|
|
17
|
+
*/
|
|
18
|
+
export declare function fitImageForModel(media: MediaBytes): Promise<MediaBytes>;
|
|
19
|
+
/** How long a model-sized copy stays cached (the steps of a conversation reuse it). */
|
|
20
|
+
export declare const MODEL_IMAGE_CACHE_SECONDS = 3600;
|
|
21
|
+
/**
|
|
22
|
+
* The cache key of an attachment's model-sized copy: its id plus its recorded etag (or size), with
|
|
23
|
+
* the scaling version, so a changed rule or object never serves an old copy.
|
|
24
|
+
*/
|
|
25
|
+
export declare const modelImageKey: (orgId: string, row: {
|
|
26
|
+
id: string;
|
|
27
|
+
etag: string | null;
|
|
28
|
+
size: number | string;
|
|
29
|
+
}) => string;
|
|
30
|
+
/** The cached form of a copy: its media type, a newline, then the bytes in base64. */
|
|
31
|
+
export declare function serializeModelImage(media: MediaBytes): string;
|
|
32
|
+
/** A cached copy read back, or null on a miss or a value that is not one. */
|
|
33
|
+
export declare function parseModelImage(raw: string | undefined): MediaBytes | null;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import sharp from "sharp";
|
|
2
|
+
/**
|
|
3
|
+
* The longest edge, in pixels, of an image sent to a model. Providers scale larger images down on
|
|
4
|
+
* their side anyway (to roughly 1.5k-2k pixels), so the extra pixels only cost upload time on every
|
|
5
|
+
* request that carries the image again.
|
|
6
|
+
*/
|
|
7
|
+
export const MODEL_IMAGE_MAX_EDGE = 2048;
|
|
8
|
+
/** An image at most this large and within {@link MODEL_IMAGE_MAX_EDGE} is sent unchanged. */
|
|
9
|
+
export const MODEL_IMAGE_KEEP_BYTES = 1_048_576;
|
|
10
|
+
/** Quality of the re-encoded copy (JPEG, or WebP for an image with transparent pixels). */
|
|
11
|
+
const QUALITY = 85;
|
|
12
|
+
/** Types {@link fitImageForModel} re-encodes; others (GIF, which may be animated) pass through. */
|
|
13
|
+
const RESIZABLE = new Set(["image/png", "image/jpeg", "image/webp"]);
|
|
14
|
+
/**
|
|
15
|
+
* The copy of an image a model request carries. Images over {@link MODEL_IMAGE_KEEP_BYTES} or
|
|
16
|
+
* larger than {@link MODEL_IMAGE_MAX_EDGE} on an edge are scaled to fit that edge (never enlarged)
|
|
17
|
+
* and re-encoded: JPEG when every pixel is opaque, WebP when some are transparent, so transparency
|
|
18
|
+
* stays visible. The result is a pure function of the stored bytes, so rebuilding a recorded request
|
|
19
|
+
* gives the same copy. The stored attachment is never changed. Bytes that fail to decode, and a
|
|
20
|
+
* re-encoded copy no smaller than the original, are returned unchanged.
|
|
21
|
+
*/
|
|
22
|
+
export async function fitImageForModel(media) {
|
|
23
|
+
if (!RESIZABLE.has(media.mediaType))
|
|
24
|
+
return media;
|
|
25
|
+
try {
|
|
26
|
+
const image = sharp(media.data, { failOn: "error" });
|
|
27
|
+
const meta = await image.metadata();
|
|
28
|
+
if (media.data.byteLength <= MODEL_IMAGE_KEEP_BYTES &&
|
|
29
|
+
Math.max(meta.width, meta.height) <= MODEL_IMAGE_MAX_EDGE) {
|
|
30
|
+
return media;
|
|
31
|
+
}
|
|
32
|
+
const opaque = !meta.hasAlpha || (await image.stats()).isOpaque;
|
|
33
|
+
const resized = image.autoOrient().resize({
|
|
34
|
+
width: MODEL_IMAGE_MAX_EDGE,
|
|
35
|
+
height: MODEL_IMAGE_MAX_EDGE,
|
|
36
|
+
fit: "inside",
|
|
37
|
+
withoutEnlargement: true,
|
|
38
|
+
});
|
|
39
|
+
const data = opaque
|
|
40
|
+
? await resized.flatten({ background: "#ffffff" }).jpeg({ quality: QUALITY }).toBuffer()
|
|
41
|
+
: await resized.webp({ quality: QUALITY }).toBuffer();
|
|
42
|
+
if (data.byteLength >= media.data.byteLength)
|
|
43
|
+
return media;
|
|
44
|
+
return { mediaType: opaque ? "image/jpeg" : "image/webp", data: new Uint8Array(data) };
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return media;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** How long a model-sized copy stays cached (the steps of a conversation reuse it). */
|
|
51
|
+
export const MODEL_IMAGE_CACHE_SECONDS = 3600;
|
|
52
|
+
/**
|
|
53
|
+
* The cache key of an attachment's model-sized copy: its id plus its recorded etag (or size), with
|
|
54
|
+
* the scaling version, so a changed rule or object never serves an old copy.
|
|
55
|
+
*/
|
|
56
|
+
export const modelImageKey = (orgId, row) => `model_image:v1:${orgId}:${row.id}:${row.etag ?? `size-${row.size}`}`;
|
|
57
|
+
/** The cached form of a copy: its media type, a newline, then the bytes in base64. */
|
|
58
|
+
export function serializeModelImage(media) {
|
|
59
|
+
return `${media.mediaType}\n${Buffer.from(media.data).toString("base64")}`;
|
|
60
|
+
}
|
|
61
|
+
/** A cached copy read back, or null on a miss or a value that is not one. */
|
|
62
|
+
export function parseModelImage(raw) {
|
|
63
|
+
if (raw === undefined)
|
|
64
|
+
return null;
|
|
65
|
+
const nl = raw.indexOf("\n");
|
|
66
|
+
const mediaType = raw.slice(0, nl);
|
|
67
|
+
if (nl < 0 || !RESIZABLE.has(mediaType))
|
|
68
|
+
return null;
|
|
69
|
+
const data = Buffer.from(raw.slice(nl + 1), "base64");
|
|
70
|
+
return data.byteLength === 0 ? null : { mediaType, data: new Uint8Array(data) };
|
|
71
|
+
}
|