@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.
Files changed (46) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/catalog/marketplaces.service.d.ts +1 -1
  3. package/dist/config/schema.d.ts +6 -0
  4. package/dist/config/schema.js +60 -0
  5. package/dist/conversations/attachments.service.d.ts +87 -11
  6. package/dist/conversations/attachments.service.js +275 -20
  7. package/dist/conversations/events.d.ts +9 -0
  8. package/dist/conversations/events.js +26 -3
  9. package/dist/conversations/model-image.d.ts +33 -0
  10. package/dist/conversations/model-image.js +71 -0
  11. package/dist/db/kernel-schema.d.ts +5 -2
  12. package/dist/evals/reconstruct.d.ts +6 -1
  13. package/dist/evals/reconstruct.js +8 -4
  14. package/dist/evals/recorded-tools.d.ts +7 -0
  15. package/dist/evals/recorded-tools.js +2 -0
  16. package/dist/infra/config/kernel-config.service.js +8 -0
  17. package/dist/media/image-header.d.ts +10 -0
  18. package/dist/media/image-header.js +87 -0
  19. package/dist/models/images.d.ts +2 -0
  20. package/dist/models/images.js +6 -4
  21. package/dist/models/purposes.d.ts +17 -57
  22. package/dist/models/purposes.js +25 -4
  23. package/dist/runtime/context/build.d.ts +73 -28
  24. package/dist/runtime/context/build.js +189 -35
  25. package/dist/runtime/model-call.js +16 -10
  26. package/dist/runtime/usage-report.d.ts +3 -2
  27. package/dist/runtime/usage-report.js +3 -2
  28. package/dist/tools/builtins/builtin-tools.d.ts +8 -1
  29. package/dist/tools/builtins/builtin-tools.js +54 -3
  30. package/dist/tools/builtins/conversation-files.d.ts +42 -0
  31. package/dist/tools/builtins/conversation-files.js +105 -0
  32. package/dist/tools/builtins/image/generate.d.ts +3 -3
  33. package/dist/tools/builtins/image/generate.js +63 -71
  34. package/dist/tools/builtins/image/size.d.ts +12 -0
  35. package/dist/tools/builtins/image/size.js +36 -0
  36. package/dist/tools/builtins/sandbox/common.d.ts +7 -0
  37. package/dist/tools/builtins/sandbox/read.d.ts +53 -2
  38. package/dist/tools/builtins/sandbox/read.js +260 -51
  39. package/dist/tools/builtins/size-text.d.ts +2 -0
  40. package/dist/tools/builtins/size-text.js +8 -0
  41. package/dist/tools/builtins/vision/read-image.d.ts +59 -0
  42. package/dist/tools/builtins/vision/read-image.js +220 -0
  43. package/dist/tools/pipeline.js +22 -3
  44. package/dist/tools/registry.d.ts +9 -1
  45. package/package.json +5 -4
  46. package/src/migrations/0163_read_attachments.sql +10 -0
package/bootstrap.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "schemaVersion": 1,
4
4
  "marketplace": {
5
5
  "url": "https://github.com/capybara-hq/plugins.git",
6
- "commit": "a9719690e38ef72258b3dd571f5c48f173c6b05e"
6
+ "commit": "fa745394ab347eeb1d59d2ba185328c2088a7e8b"
7
7
  },
8
8
  "plugins": [
9
9
  {
@@ -58,8 +58,8 @@
58
58
  "name": "ark",
59
59
  "source": "npm",
60
60
  "npm": "@capybara-hq/plugin-ark",
61
- "version": "0.1.0-rc.10",
62
- "integrity": "sha512-8SRYcBBb/wROJX8ByBisL/SKNg7z4RvWFq8X7L+944QBzSed4YHwNATLRDTL4pW1l6VIC2rr+0DeSBCjmsF4Qw==",
61
+ "version": "0.1.0-rc.11",
62
+ "integrity": "sha512-rE0tPudbL0AjY9f6cTdM0wSFtyhWsKOaEFy6GOZ79wISw9F5Y0ap3RVaiaeW9c0lZPxKdhqIzi18xARu/A1jVQ==",
63
63
  "required": false
64
64
  },
65
65
  {
@@ -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.36";
191
+ readonly sdk: "0.1.0-rc.37";
192
192
  };
193
193
  /** Whether this deployment satisfies the entry's `minKernel`. */
194
194
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -191,6 +191,9 @@ export declare const KernelConfigSchema: z.ZodObject<{
191
191
  maxPerMessage: z.ZodDefault<z.ZodNumber>;
192
192
  unboundTtlHours: z.ZodDefault<z.ZodNumber>;
193
193
  requestMediaBytes: z.ZodDefault<z.ZodNumber>;
194
+ readImagesPerRequest: z.ZodDefault<z.ZodNumber>;
195
+ readMaxBytesPerConversation: z.ZodDefault<z.ZodNumber>;
196
+ readPurgeAfterHours: z.ZodDefault<z.ZodNumber>;
194
197
  }, z.core.$strict>>;
195
198
  sharing: z.ZodPrefault<z.ZodObject<{
196
199
  external: z.ZodOptional<z.ZodEnum<{
@@ -293,6 +296,9 @@ export declare const KernelConfigSchema: z.ZodObject<{
293
296
  imageTimeoutMs: z.ZodDefault<z.ZodNumber>;
294
297
  imageMaxPerCall: z.ZodDefault<z.ZodNumber>;
295
298
  imagePromptMaxChars: z.ZodDefault<z.ZodNumber>;
299
+ imageStandardPixels: z.ZodDefault<z.ZodNumber>;
300
+ visionTimeoutMs: z.ZodDefault<z.ZodNumber>;
301
+ visionMaxOutputTokens: z.ZodDefault<z.ZodNumber>;
296
302
  }, z.core.$strict>>;
297
303
  hooks: z.ZodPrefault<z.ZodObject<{
298
304
  timeoutMs: z.ZodDefault<z.ZodNumber>;
@@ -1151,6 +1151,36 @@ export const KernelConfigSchema = z.strictObject({
1151
1151
  .meta(meta({
1152
1152
  description: "Budget of raw attachment bytes in one model request; the newest attachments are kept and older ones are replaced with a placeholder. At most 24 MiB: base64 inflates it by about 4/3, and common providers cap a request at 32 MB",
1153
1153
  })),
1154
+ readImagesPerRequest: z
1155
+ .number()
1156
+ .int()
1157
+ .min(2)
1158
+ .max(20)
1159
+ .default(6)
1160
+ .meta(meta({
1161
+ hot: true,
1162
+ description: "Most images Read may show the model in one request; older Read images are replaced with a placeholder",
1163
+ })),
1164
+ readMaxBytesPerConversation: z
1165
+ .number()
1166
+ .int()
1167
+ .min(0)
1168
+ .max(17_179_869_184)
1169
+ .default(536_870_912)
1170
+ .meta(meta({
1171
+ hot: true,
1172
+ description: "Most bytes of Read image copies stored for one conversation; past it a Read image is not stored and does not stay in the history; 0 stores none",
1173
+ })),
1174
+ readPurgeAfterHours: z
1175
+ .number()
1176
+ .int()
1177
+ .min(1)
1178
+ .max(720)
1179
+ .default(24)
1180
+ .meta(meta({
1181
+ hot: true,
1182
+ description: "Hours after a conversation is deleted before its Read image copies are purged (row and object)",
1183
+ })),
1154
1184
  })
1155
1185
  // 单个附件不能大于单次请求的预算:否则它永远被省略(最新的附件总能放进请求)
1156
1186
  .refine((c) => c.maxBytes <= c.requestMediaBytes, {
@@ -1742,6 +1772,36 @@ export const KernelConfigSchema = z.strictObject({
1742
1772
  hot: true,
1743
1773
  description: "Longest prompt, in characters (code points), an image generation call accepts; longer is a validation error",
1744
1774
  })),
1775
+ imageStandardPixels: z
1776
+ .number()
1777
+ .int()
1778
+ .min(262_144)
1779
+ .max(16_777_216)
1780
+ .default(1_048_576)
1781
+ .meta(meta({
1782
+ hot: true,
1783
+ description: "Target pixel area (width times height) of a standard-resolution GenerateImage size: the model's size closest to it for the requested shape",
1784
+ })),
1785
+ visionTimeoutMs: z
1786
+ .number()
1787
+ .int()
1788
+ .min(5_000)
1789
+ .max(600_000)
1790
+ .default(120_000)
1791
+ .meta(meta({
1792
+ hot: true,
1793
+ description: "Milliseconds a vision model call for Read may take before it is aborted",
1794
+ })),
1795
+ visionMaxOutputTokens: z
1796
+ .number()
1797
+ .int()
1798
+ .min(100)
1799
+ .max(16_000)
1800
+ .default(2_000)
1801
+ .meta(meta({
1802
+ hot: true,
1803
+ description: "Most tokens a vision model may answer with when it reads an image for Read",
1804
+ })),
1745
1805
  })
1746
1806
  .prefault({}),
1747
1807
  hooks: z
@@ -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";
@@ -45,6 +46,17 @@ export declare const AGENT_AVATAR_DOWNLOAD_TTL_SECONDS = 300;
45
46
  export declare const skillFilesPrefix: (uploadId: string) => string;
46
47
  /** 周期任务:每小时清理过期未绑定的附件(`@LockedCron`)。 */
47
48
  export declare const ATTACHMENT_CLEANUP_JOB = "attachment-cleanup";
49
+ /** The hourly purge of `read` copies whose conversation was deleted long enough ago. */
50
+ export declare const ATTACHMENT_READ_PURGE_JOB = "attachments-read-purge";
51
+ /** {@link AttachmentsService.storeRead}'s result: the bound copy, or refused by the cap. */
52
+ export type StoreReadResult = {
53
+ ok: true;
54
+ attachmentId: string;
55
+ size: number;
56
+ } | {
57
+ ok: false;
58
+ reason: "cap";
59
+ };
48
60
  /** 附件元数据(finalize 的返回)。 */
49
61
  export interface AttachmentView {
50
62
  id: string;
@@ -131,9 +143,13 @@ export declare class AttachmentsService {
131
143
  private readonly access;
132
144
  private readonly log;
133
145
  readonly txHost: TransactionHost;
146
+ /** where the model-sized copies of images are kept between steps ({@link fetchMedia}) */
147
+ private readonly cache;
134
148
  constructor(db: KernelDb, storage: Pick<StorageService, "available" | "assertAvailable" | "kernel">, config: Pick<KernelConfigService, "get">,
135
149
  /** viewer 能否访问该会话(与会话流相同的规则)。 */
136
- 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">);
137
153
  /** 单个附件的大小上限:配置的 `maxBytes`,图片再受 `MEDIA_LIMITS.imageBytes` 限制。 */
138
154
  private limitFor;
139
155
  /** 当前配置下的上限(不需要对象存储)。 */
@@ -172,9 +188,11 @@ export declare class AttachmentsService {
172
188
  /**
173
189
  * The ready `chat` attachments bound to the conversation in this org (never another purpose, a
174
190
  * 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.
191
+ * Nothing here checks who reads them: callers check the conversation's access first. `purposes`
192
+ * widens it for a model-facing lookup only (`read` copies; vision-read design §1.1): every
193
+ * person- or device-facing caller keeps the default.
176
194
  */
177
- boundRows(orgId: string, conversationId: string, id?: string): Promise<BoundAttachment[]>;
195
+ boundRows(orgId: string, conversationId: string, id?: string, purposes?: readonly ("chat" | "read")[]): Promise<BoundAttachment[]>;
178
196
  /**
179
197
  * {@link attachmentContentMatches} for a bound attachment's stored object (`null`: gone), with
180
198
  * the warning logged when the content was replaced after finalize.
@@ -190,7 +208,16 @@ export declare class AttachmentsService {
190
208
  * 读取一个绑定在该会话、已 ready 的附件(沙箱同步等内核内部用途):没有行、未绑定到该会话、对象已不在、
191
209
  * 大小或 etag 与 finalize 时不符 → null。其余错误(存储不可用等)照常抛出。调用方负责读完或取消 `body`。
192
210
  */
193
- openForConversation(orgId: string, conversationId: string, attachmentId: string): Promise<OpenedAttachment | null>;
211
+ openForConversation(orgId: string, conversationId: string, attachmentId: string, opts?: {
212
+ /**
213
+ * Also `read` copies (the model-facing file lookup only, vision-read design §1.1); the
214
+ * default is `chat` attachments, which is all a person or a device may see.
215
+ */
216
+ purposes?: readonly ("chat" | "read")[];
217
+ /** Read at most this many bytes (a range read; a store that ignores it serves the whole). */
218
+ maxBytes?: number;
219
+ signal?: AbortSignal;
220
+ }): Promise<OpenedAttachment | null>;
194
221
  /**
195
222
  * 发消息时在调用方事务里绑定附件(行锁),返回写进 user_message 的媒体块(`ref`,按 ids 顺序):
196
223
  * - 超过 `attachments.maxPerMessage`、或同一个 id 出现多次 → `validation_failed`;
@@ -203,14 +230,21 @@ export declare class AttachmentsService {
203
230
  /** 下载 / 取字节时核对 etag:finalize 记下的与当前对象的不一致 → 内容被替换(记 warn)。没有记录时不核对。 */
204
231
  private sameContent;
205
232
  /**
206
- * 构建模型请求时查附件行的声明信息(只含绑定在该会话、已 ready 的):大小、PDF 页数,以及对象的无签名引用
207
- * (`ObjectStore.uri`,存储没有时退回 `capybara://attachments/<id>`)。没有行的不在结果里;查询失败照常抛出。
233
+ * The recorded facts request building needs about attachments (only ready `chat` or `read` rows
234
+ * bound to this conversation): size, PDF page count, and the object's unsigned reference
235
+ * (`ObjectStore.uri`, falling back to `capybara://attachments/<id>`). An id with no row is left
236
+ * out; a failed query throws.
208
237
  */
209
238
  mediaInfo(orgId: string, conversationId: string, ids: readonly string[]): Promise<Map<string, MediaInfo>>;
210
239
  /**
211
- * 构建模型请求时取附件字节:只取绑定在该会话、已 ready 的附件。只有「确定不存在」才为 null:没有行、对象已不在、
212
- * 大小或 etag 与 finalize 时不符(内容被替换,记 warn)。其余错误(存储不可用、网络错误)一律抛出(Ruling M4),
213
- * 由调用方按可重试处理,不会变成占位。`caps` 里的附件只按范围读开头若干字节(`text/*` 封顶,更后面的不取)。
240
+ * The bytes request building sends, only of ready `chat` or `read` rows bound to this
241
+ * conversation. Null only when certainly gone: no row, the object missing, or its size or etag
242
+ * not the recorded one (content replaced, logged as a warning). Every other error (storage
243
+ * unavailable, network) throws (Ruling M4) for the caller to treat as retryable, never a
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.
214
248
  */
215
249
  fetchMedia(orgId: string, conversationId: string, ids: readonly string[], caps?: ReadonlyMap<string, number>): Promise<Map<string, MediaBytes | null>>;
216
250
  /**
@@ -245,6 +279,43 @@ export declare class AttachmentsService {
245
279
  * to `agentId`; `null` when there is none or its object is gone or no longer the finalized one.
246
280
  */
247
281
  agentAvatarUrl(orgId: string, agentId: string, id: string): Promise<string | null>;
282
+ /**
283
+ * Stores the copy of an image the builtin Read read, bound to the calling conversation (never its
284
+ * root), intent first so a crash leaves nothing unowned (vision-read design §1.3):
285
+ * 1. the per-conversation cap `attachments.readMaxBytesPerConversation` (the sizes of the
286
+ * conversation's `read` rows plus this one; 0 refuses always) → `{ ok: false, reason: "cap" }`,
287
+ * nothing stored. Concurrent calls may pass it together: a soft cap;
288
+ * 2. the row, unbound, `pending`, expiring after `attachments.unboundTtlHours`, so
289
+ * {@link deleteExpired} collects it after a crash; with no `accountId` (a run nobody started)
290
+ * it is the conversation owner's;
291
+ * 3. the object under `read-images/<id>` (a failed put throws and leaves the row to expire);
292
+ * 4. one transaction binding it: the conversation, `ready`, no expiry, the stored size and etag.
293
+ * No object store → `storage.unavailable`. A conversation not in the org → an error, nothing stored.
294
+ */
295
+ storeRead(orgId: string, conversationId: string, accountId: string | null, file: {
296
+ name: string;
297
+ contentType: string;
298
+ data: Uint8Array;
299
+ }): Promise<StoreReadResult>;
300
+ /**
301
+ * Step 2 of {@link storeRead}: the unbound intent row, in its own transaction so it is committed
302
+ * before the put even when the caller holds one (a rollback must never leave an object with no
303
+ * row). The INSERT ... SELECT proves the conversation is in the org; with no `accountId` the row
304
+ * is the conversation owner's.
305
+ */
306
+ private insertReadIntent;
307
+ /** Step 4 of {@link storeRead}: binds the unbound row in one transaction. */
308
+ private bindRead;
309
+ /**
310
+ * Purges the `read` copies of conversations deleted more than `attachments.readPurgeAfterHours`
311
+ * ago (read at run time), and of the sub-agent conversations below them (a sub-agent
312
+ * conversation keeps `deleted_at` null when its root is deleted): claims up to
313
+ * {@link READ_PURGE_BATCH} rows at a time as `deleting` (`FOR UPDATE SKIP LOCKED`, so concurrent
314
+ * 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.
315
+ * Chat attachments of deleted conversations are not touched. Does nothing without an object
316
+ * store. Returns the number of rows deleted.
317
+ */
318
+ purgeRead(): Promise<number>;
248
319
  /**
249
320
  * 删除过期(`expires_at < now()`)且从未绑定到会话的附件:先把行认领为 `deleting`(`FOR UPDATE SKIP LOCKED`,
250
321
  * 多副本并发时互不重复),再删对象、删行。删对象失败的行保持 `deleting`,下次运行重试。
@@ -254,11 +325,16 @@ export declare class AttachmentsService {
254
325
  */
255
326
  deleteExpired(): Promise<number>;
256
327
  }
257
- /** The hourly cleanup of expired unbound attachments, once per tick across replicas. */
328
+ /**
329
+ * The hourly attachment jobs, each once per tick across replicas (provided only under
330
+ * `WorkerModule`): the cleanup of expired unbound attachments and the purge of `read` copies of
331
+ * deleted conversations.
332
+ */
258
333
  export declare class AttachmentCleanupJob {
259
334
  private readonly attachments;
260
335
  readonly lockService: LockService;
261
336
  readonly log: KernelLogger;
262
- constructor(attachments: Pick<AttachmentsService, "deleteExpired">, lockService: LockService, log: KernelLogger);
337
+ constructor(attachments: Pick<AttachmentsService, "deleteExpired" | "purgeRead">, lockService: LockService, log: KernelLogger);
263
338
  run(): Promise<void>;
339
+ purgeRead(): Promise<void>;
264
340
  }