@capybara-hq/kernel 0.1.0-rc.52 → 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.
@@ -1,5 +1,6 @@
1
1
  import { type PresignedUpload } from "@capybara-hq/plugin-sdk";
2
2
  import type { AttachmentPurpose } from "../db/kernel-schema.js";
3
+ import { CacheService } from "../infra/cache/cache.service.js";
3
4
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
4
5
  import { KernelDb } from "../infra/database/kernel-db.js";
5
6
  import { TransactionHost } from "../infra/database/transaction-host.js";
@@ -142,9 +143,13 @@ export declare class AttachmentsService {
142
143
  private readonly access;
143
144
  private readonly log;
144
145
  readonly txHost: TransactionHost;
146
+ /** where the model-sized copies of images are kept between steps ({@link fetchMedia}) */
147
+ private readonly cache;
145
148
  constructor(db: KernelDb, storage: Pick<StorageService, "available" | "assertAvailable" | "kernel">, config: Pick<KernelConfigService, "get">,
146
149
  /** viewer 能否访问该会话(与会话流相同的规则)。 */
147
- access: Pick<ConversationAccess, "isAccessible">, log: Pick<KernelLogger, "info" | "warn">, txHost: TransactionHost);
150
+ access: Pick<ConversationAccess, "isAccessible">, log: Pick<KernelLogger, "info" | "warn">, txHost: TransactionHost,
151
+ /** where the model-sized copies of images are kept between steps ({@link fetchMedia}) */
152
+ cache: Pick<CacheService, "get" | "set">);
148
153
  /** 单个附件的大小上限:配置的 `maxBytes`,图片再受 `MEDIA_LIMITS.imageBytes` 限制。 */
149
154
  private limitFor;
150
155
  /** 当前配置下的上限(不需要对象存储)。 */
@@ -237,6 +242,9 @@ export declare class AttachmentsService {
237
242
  * not the recorded one (content replaced, logged as a warning). Every other error (storage
238
243
  * unavailable, network) throws (Ruling M4) for the caller to treat as retryable, never a
239
244
  * placeholder. An id in `caps` is read by range up to that many leading bytes (the `text/*` cap).
245
+ * A whole image comes back as its model-sized copy ({@link fitImageForModel}), whose media type
246
+ * may differ from the row's; the copy is cached for {@link MODEL_IMAGE_CACHE_SECONDS} under the
247
+ * attachment's id and etag, so later steps of the conversation only check the object's head.
240
248
  */
241
249
  fetchMedia(orgId: string, conversationId: string, ids: readonly string[], caps?: ReadonlyMap<string, number>): Promise<Map<string, MediaBytes | null>>;
242
250
  /**
@@ -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}(浏览器缓存的跳转仍可用)。 */
@@ -151,15 +153,19 @@ let AttachmentsService = class AttachmentsService {
151
153
  access;
152
154
  log;
153
155
  txHost;
156
+ cache;
154
157
  constructor(db, storage, config,
155
158
  /** viewer 能否访问该会话(与会话流相同的规则)。 */
156
- access, log, txHost) {
159
+ access, log, txHost,
160
+ /** where the model-sized copies of images are kept between steps ({@link fetchMedia}) */
161
+ cache) {
157
162
  this.db = db;
158
163
  this.storage = storage;
159
164
  this.config = config;
160
165
  this.access = access;
161
166
  this.log = log;
162
167
  this.txHost = txHost;
168
+ this.cache = cache;
163
169
  }
164
170
  /** 单个附件的大小上限:配置的 `maxBytes`,图片再受 `MEDIA_LIMITS.imageBytes` 限制。 */
165
171
  limitFor(contentType) {
@@ -569,6 +575,9 @@ let AttachmentsService = class AttachmentsService {
569
575
  * not the recorded one (content replaced, logged as a warning). Every other error (storage
570
576
  * unavailable, network) throws (Ruling M4) for the caller to treat as retryable, never a
571
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.
572
581
  */
573
582
  async fetchMedia(orgId, conversationId, ids, caps) {
574
583
  const out = new Map();
@@ -590,11 +599,28 @@ let AttachmentsService = class AttachmentsService {
590
599
  if (!r)
591
600
  return out.set(id, null);
592
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
+ }
593
620
  const want = cap !== undefined && cap < Number(r.size) ? Math.max(1, cap) : Number(r.size);
594
621
  const got = await store.get(r.object_key, want < Number(r.size) ? { range: { start: 0, end: want - 1 } } : undefined);
595
622
  if (!got)
596
623
  return out.set(id, null);
597
- const where = { orgId, conversationId, attachmentId: id };
598
624
  if (got.head.size !== Number(r.size) || !this.sameContent(r.etag, got.head.etag, where)) {
599
625
  if (got.head.size !== Number(r.size)) {
600
626
  this.log.warn("attachment size changed after finalize; treating it as unavailable", where);
@@ -605,7 +631,18 @@ let AttachmentsService = class AttachmentsService {
605
631
  // 提供方没按范围读、给了整个对象时只留开头
606
632
  const all = await readAll(got.body);
607
633
  const data = all.byteLength === Number(r.size) ? all.subarray(0, want) : all;
608
- out.set(id, data.byteLength === want ? { mediaType: r.content_type, data } : null);
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);
609
646
  }));
610
647
  return out;
611
648
  }
@@ -1020,7 +1057,8 @@ AttachmentsService = __decorate([
1020
1057
  __param(2, Inject(KernelConfigService)),
1021
1058
  __param(3, Inject(ConversationAccess)),
1022
1059
  __param(4, Inject(KERNEL_LOGGER)),
1023
- __param(5, Inject(TransactionHost))
1060
+ __param(5, Inject(TransactionHost)),
1061
+ __param(6, Inject(CacheService))
1024
1062
  ], AttachmentsService);
1025
1063
  export { AttachmentsService };
1026
1064
  /**
@@ -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
+ }
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { MEDIA_LIMITS, } from "@capybara-hq/plugin-sdk";
2
+ import { IMAGE_MEDIA_TYPES, MEDIA_LIMITS, } from "@capybara-hq/plugin-sdk";
3
3
  import { renderBackgroundFinished } from "../../background/render.js";
4
4
  import { isAbsorbable, } from "../../conversations/events.js";
5
5
  import { catalogText, isAlwaysLoaded } from "../../tools/builtins/tool-search.js";
@@ -493,7 +493,15 @@ export function resolveMedia(content, model, ctx) {
493
493
  data: Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString("base64"),
494
494
  };
495
495
  out.push(b.type === "image"
496
- ? { type: "image", mediaType: b.mediaType, source, ...(b.name !== undefined && { name }) }
496
+ ? {
497
+ type: "image",
498
+ // the fetched copy's type: an image may arrive re-encoded for the model
499
+ mediaType: IMAGE_MEDIA_TYPES.includes(got.mediaType)
500
+ ? got.mediaType
501
+ : b.mediaType,
502
+ source,
503
+ ...(b.name !== undefined && { name }),
504
+ }
497
505
  : {
498
506
  type: "document",
499
507
  mediaType: b.mediaType,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.52",
3
+ "version": "0.1.0-rc.53",
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": {
@@ -60,6 +60,7 @@
60
60
  "reflect-metadata": "0.2.2",
61
61
  "rxjs": "^7.8.2",
62
62
  "semver": "^7.8.5",
63
+ "sharp": "0.35.5",
63
64
  "tar-stream": "3.2.2",
64
65
  "undici": "^8.12.3",
65
66
  "yaml": "^2.9.1",
@@ -74,8 +75,8 @@
74
75
  "@types/ws": "^8.18.2",
75
76
  "@types/yauzl": "3.4.0",
76
77
  "ws": "^8.22.0",
77
- "@capybara-hq/device": "0.1.0-rc.17",
78
- "@capybara-hq/testing": "0.1.0-rc.28"
78
+ "@capybara-hq/testing": "0.1.0-rc.28",
79
+ "@capybara-hq/device": "0.1.0-rc.17"
79
80
  },
80
81
  "scripts": {
81
82
  "build": "tsc -b"