@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
@@ -838,8 +838,11 @@ export interface AttachmentsTable {
838
838
  /** 0068: the agent whose profile uses this avatar upload (set once, when it is saved). */
839
839
  agent_id: ColumnType<string | null, string | null | undefined, string | null>;
840
840
  }
841
- /** 预签名上传的用途:对话附件 / 技能包 zip / agent avatar image. */
842
- export type AttachmentPurpose = "chat" | "skill-package" | "agent-avatar";
841
+ /**
842
+ * What an attachment row is for: a chat attachment, a skill package zip, an agent avatar image, or
843
+ * (0163) an image the builtin Read stored with the calling conversation.
844
+ */
845
+ export type AttachmentPurpose = "chat" | "skill-package" | "agent-avatar" | "read";
843
846
  /** 技能版本的清单(`skill_versions.manifest`)。 */
844
847
  export interface SkillManifest {
845
848
  name: string;
@@ -58,6 +58,11 @@ export interface ReconstructOptions {
58
58
  media?: ReadonlyMap<string, MediaBytes | null>;
59
59
  /** The request's media byte budget; defaults to the recorded `mediaBudgetBytes` (recorded only when the request had media). */
60
60
  mediaBudgetBytes?: number;
61
+ /**
62
+ * The Read-image window; defaults to the recorded `readImagesPerRequest` (recorded only when the
63
+ * request rendered an image from Read).
64
+ */
65
+ readImagesPerRequest?: number;
61
66
  /** The candidate's model (a non-baseline reconstruction): checked against the run's switch. */
62
67
  modelRef?: ModelRef;
63
68
  /**
@@ -188,7 +193,7 @@ export declare function snapshotMediaRefs(s: CaseSnapshot, modelCallSeq: number,
188
193
  * 原对话或附件已删除 → 行不在结果里,还原时按「不再可用」占位(drift 记 `media_missing`);
189
194
  * 暂时故障(存储不可用)由来源抛出,调用方按可重试处理。
190
195
  */
191
- export declare function loadSnapshotMedia(s: CaseSnapshot, modelCallSeq: number, model: ModelInfo, source: MediaSourceDeps, mediaBudgetBytes?: number): Promise<{
196
+ export declare function loadSnapshotMedia(s: CaseSnapshot, modelCallSeq: number, model: ModelInfo, source: MediaSourceDeps, mediaBudgetBytes?: number, readImagesPerRequest?: number): Promise<{
192
197
  mediaInfo: Map<string, MediaInfo>;
193
198
  media: Map<string, MediaBytes | null>;
194
199
  }>;
@@ -192,6 +192,7 @@ export function reconstructInputs(s, modelCallSeq, opts) {
192
192
  }
193
193
  }
194
194
  const budget = opts.mediaBudgetBytes ?? rec.mediaBudgetBytes;
195
+ const readWindow = opts.readImagesPerRequest ?? rec.readImagesPerRequest;
195
196
  const input = {
196
197
  events: inputEvents(all, call),
197
198
  agent,
@@ -206,6 +207,7 @@ export function reconstructInputs(s, modelCallSeq, opts) {
206
207
  ...(opts.mediaInfo !== undefined && { mediaInfo: opts.mediaInfo }),
207
208
  ...(opts.media !== undefined && { media: opts.media }),
208
209
  ...(budget !== undefined && { mediaBudgetBytes: budget }),
210
+ ...(readWindow !== undefined && { readImagesPerRequest: readWindow }),
209
211
  defaultMaxOutputTokens: rec.maxOutputTokens,
210
212
  // The baseline replays the recorded output cap as sent: the runtime may have clamped it below
211
213
  // the agent's `maxOutputTokens` knob (context compaction spec §4.3), and recomputing it from the
@@ -413,7 +415,8 @@ export function subagentCaseChanged(s, c) {
413
415
  /** 还原该请求要查的附件 id(该模型用得到的引用,去重、按出现顺序;见 `mediaRefs`)。 */
414
416
  export function snapshotMediaRefs(s, modelCallSeq, model) {
415
417
  const all = toEvents(s);
416
- return mediaRefs(inputEvents(all, findCall(all, modelCallSeq)), model);
418
+ const call = findCall(all, modelCallSeq);
419
+ return mediaRefs(inputEvents(all, call), model, call.payload.request.readImagesPerRequest);
417
420
  }
418
421
  /**
419
422
  * 按快照自己的 `orgId` / `conversationId` 取还原该请求要用的附件(C3:媒体不进快照,回放时取原附件):
@@ -422,17 +425,18 @@ export function snapshotMediaRefs(s, modelCallSeq, model) {
422
425
  * 原对话或附件已删除 → 行不在结果里,还原时按「不再可用」占位(drift 记 `media_missing`);
423
426
  * 暂时故障(存储不可用)由来源抛出,调用方按可重试处理。
424
427
  */
425
- export async function loadSnapshotMedia(s, modelCallSeq, model, source, mediaBudgetBytes) {
428
+ export async function loadSnapshotMedia(s, modelCallSeq, model, source, mediaBudgetBytes, readImagesPerRequest) {
426
429
  const all = toEvents(s);
427
430
  const call = findCall(all, modelCallSeq);
428
431
  const events = inputEvents(all, call);
429
- const refs = mediaRefs(events, model);
432
+ const readWindow = readImagesPerRequest ?? call.payload.request.readImagesPerRequest;
433
+ const refs = mediaRefs(events, model, readWindow);
430
434
  const media = new Map();
431
435
  if (refs.length === 0)
432
436
  return { mediaInfo: new Map(), media };
433
437
  const mediaInfo = await source.info(s.orgId, s.conversationId, refs);
434
438
  const budget = mediaBudgetBytes ?? call.payload.request.mediaBudgetBytes;
435
- const plan = planMedia(events, model, mediaInfo, budget);
439
+ const plan = planMedia(events, model, mediaInfo, budget, readWindow);
436
440
  if (plan.fetch.length > 0) {
437
441
  const caps = new Map(plan.fetch.flatMap((id) => (plan.caps.has(id) ? [[id, plan.caps.get(id)]] : [])));
438
442
  const got = await source.fetch(s.orgId, s.conversationId, plan.fetch, caps.size > 0 ? caps : undefined);
@@ -1,5 +1,6 @@
1
1
  import type { EventLog } from "../conversations/event-log.js";
2
2
  import { type ReviewRecord } from "../conversations/events.js";
3
+ import type { ReadMedia } from "../runtime/context/build.js";
3
4
  import { type DevicePathsPayload } from "../runtime/context/device-paths.js";
4
5
  import { type ToolPipeline, type ToolStepContext } from "../tools/pipeline.js";
5
6
  import type { CaseSnapshot } from "./snapshot.js";
@@ -38,6 +39,12 @@ export interface RecordedCall {
38
39
  * original had none. Never part of matching, the content or any request.
39
40
  */
40
41
  review?: ReviewRecord;
42
+ /**
43
+ * The images the original Read stored (`tool_result.media`, vision-read design §1.4), copied
44
+ * verbatim: the replay renders the same `read` attachments of the original conversation (media
45
+ * lookups use the snapshot's conversation), never reads or stores again.
46
+ */
47
+ media?: ReadMedia[];
41
48
  }
42
49
  /** 规范化 JSON:对象键递归按码点排序,数组保持顺序;`undefined` 按 JSON 规则省略。 */
43
50
  export declare function canonicalJson(v: unknown): string;
@@ -108,6 +108,7 @@ export function recordedCalls(s) {
108
108
  ...(r.review !== undefined && {
109
109
  review: recordedReview(r.review, resultSeq.get(call.id) ?? 0),
110
110
  }),
111
+ ...(r.media !== undefined && { media: structuredClone(r.media) }),
111
112
  });
112
113
  }
113
114
  }
@@ -195,6 +196,7 @@ export class RecordedToolPipeline {
195
196
  ...(rec.contentTypes !== undefined && { contentTypes: rec.contentTypes }),
196
197
  // the recorded decision, verbatim: nothing is reviewed or admitted again
197
198
  ...(rec.review !== undefined && { review: structuredClone(rec.review) }),
199
+ ...(rec.media !== undefined && { media: structuredClone(rec.media) }),
198
200
  }
199
201
  : { content: REPLAY_NO_RECORDING, isError: true }),
200
202
  ]);
@@ -39,6 +39,14 @@ const HOT_APPLIERS = {
39
39
  "models.imageTimeoutMs": () => { },
40
40
  "models.imageMaxPerCall": () => { },
41
41
  "models.imagePromptMaxChars": () => { },
42
+ // Read and the image pipeline read the standard size and the vision call limits on every use.
43
+ "models.imageStandardPixels": () => { },
44
+ "models.visionTimeoutMs": () => { },
45
+ "models.visionMaxOutputTokens": () => { },
46
+ // Read reads its per-request and per-conversation image limits and the purge age on every use.
47
+ "attachments.readImagesPerRequest": () => { },
48
+ "attachments.readMaxBytesPerConversation": () => { },
49
+ "attachments.readPurgeAfterHours": () => { },
42
50
  // SandboxService reads the shared-lease cap at every acquisition.
43
51
  "sandbox.maxConcurrentCommands": () => { },
44
52
  // The command-review service reads the classifier's bounds at every classifier call.
@@ -0,0 +1,10 @@
1
+ export type SniffedImage = {
2
+ mediaType: "image/png" | "image/jpeg" | "image/gif" | "image/webp";
3
+ width?: number;
4
+ height?: number;
5
+ };
6
+ /**
7
+ * Identifies an image by its magic bytes and reads the pixel size from the header when the
8
+ * bytes cover it. Reads only the header, never decodes, and never throws on short input.
9
+ */
10
+ export declare function sniffImage(bytes: Uint8Array): SniffedImage | null;
@@ -0,0 +1,87 @@
1
+ const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
2
+ const MAX_JPEG_SEGMENTS = 256;
3
+ function startsWith(bytes, offset, text) {
4
+ const expected = typeof text === "string" ? [...text].map((c) => c.charCodeAt(0)) : text;
5
+ if (bytes.length < offset + expected.length)
6
+ return false;
7
+ return expected.every((b, i) => bytes[offset + i] === b);
8
+ }
9
+ const u16be = (b, o) => ((b[o] ?? 0) << 8) | (b[o + 1] ?? 0);
10
+ const u16le = (b, o) => (b[o] ?? 0) | ((b[o + 1] ?? 0) << 8);
11
+ const u24le = (b, o) => u16le(b, o) | ((b[o + 2] ?? 0) << 16);
12
+ const u32be = (b, o) => (b[o] ?? 0) * 0x1000000 + (((b[o + 1] ?? 0) << 16) | ((b[o + 2] ?? 0) << 8) | (b[o + 3] ?? 0));
13
+ const u32le = (b, o) => u24le(b, o) + (b[o + 3] ?? 0) * 0x1000000;
14
+ function size(width, height) {
15
+ return width > 0 && height > 0 ? { width, height } : {};
16
+ }
17
+ function pngSize(b) {
18
+ if (b.length < 24 || !startsWith(b, 12, "IHDR"))
19
+ return {};
20
+ return size(u32be(b, 16), u32be(b, 20));
21
+ }
22
+ function jpegSize(b) {
23
+ let pos = 2;
24
+ for (let i = 0; i < MAX_JPEG_SEGMENTS; i++) {
25
+ // Skip fill bytes, then read the marker.
26
+ while (pos < b.length && b[pos] === 0xff && b[pos + 1] === 0xff)
27
+ pos++;
28
+ if (pos + 4 > b.length || b[pos] !== 0xff)
29
+ return {};
30
+ const marker = b[pos + 1];
31
+ if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
32
+ pos += 2;
33
+ continue;
34
+ }
35
+ if (marker === 0xd9 || marker === 0xda)
36
+ return {};
37
+ const isSof = marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
38
+ if (isSof) {
39
+ if (pos + 9 > b.length)
40
+ return {};
41
+ return size(u16be(b, pos + 7), u16be(b, pos + 5));
42
+ }
43
+ pos += 2 + u16be(b, pos + 2);
44
+ }
45
+ return {};
46
+ }
47
+ function gifSize(b) {
48
+ if (b.length < 10)
49
+ return {};
50
+ return size(u16le(b, 6), u16le(b, 8));
51
+ }
52
+ function webpSize(b) {
53
+ if (startsWith(b, 12, "VP8 ")) {
54
+ if (b.length < 30 || !startsWith(b, 23, [0x9d, 0x01, 0x2a]))
55
+ return {};
56
+ return size(u16le(b, 26) & 0x3fff, u16le(b, 28) & 0x3fff);
57
+ }
58
+ if (startsWith(b, 12, "VP8L")) {
59
+ if (b.length < 25 || b[20] !== 0x2f)
60
+ return {};
61
+ const bits = u32le(b, 21);
62
+ return size((bits & 0x3fff) + 1, ((bits >>> 14) & 0x3fff) + 1);
63
+ }
64
+ if (startsWith(b, 12, "VP8X")) {
65
+ if (b.length < 30)
66
+ return {};
67
+ return size(u24le(b, 24) + 1, u24le(b, 27) + 1);
68
+ }
69
+ return {};
70
+ }
71
+ /**
72
+ * Identifies an image by its magic bytes and reads the pixel size from the header when the
73
+ * bytes cover it. Reads only the header, never decodes, and never throws on short input.
74
+ */
75
+ export function sniffImage(bytes) {
76
+ if (startsWith(bytes, 0, PNG_SIGNATURE))
77
+ return { mediaType: "image/png", ...pngSize(bytes) };
78
+ if (startsWith(bytes, 0, [0xff, 0xd8, 0xff]))
79
+ return { mediaType: "image/jpeg", ...jpegSize(bytes) };
80
+ if (startsWith(bytes, 0, "GIF87a") || startsWith(bytes, 0, "GIF89a")) {
81
+ return { mediaType: "image/gif", ...gifSize(bytes) };
82
+ }
83
+ if (startsWith(bytes, 0, "RIFF") && startsWith(bytes, 8, "WEBP")) {
84
+ return { mediaType: "image/webp", ...webpSize(bytes) };
85
+ }
86
+ return null;
87
+ }
@@ -13,6 +13,8 @@ export interface ImageCallInput {
13
13
  /** An exact size (only `ctx.models`); must be one the model declares. */
14
14
  size?: ImageSize;
15
15
  aspectRatio?: ImageAspectRatio;
16
+ /** Picks the size from the model's facts (the tool's standard size; wins over the other two). */
17
+ chooseSize?: (info: ModelImageGenerationInfo) => ImageSize;
16
18
  /** Images to produce (default 1). */
17
19
  n?: number;
18
20
  /** Base64 reference images. */
@@ -244,10 +244,12 @@ let ModelImages = class ModelImages {
244
244
  bad(`reference image ${i} must be PNG, JPEG, GIF or WebP up to ${IMAGE_LIMIT_MB} MB`);
245
245
  }
246
246
  });
247
- const size = pickImageSize(gen, {
248
- ...(input.size !== undefined && { size: input.size }),
249
- ...(input.aspectRatio !== undefined && { aspectRatio: input.aspectRatio }),
250
- });
247
+ const size = input.chooseSize
248
+ ? { ok: true, size: input.chooseSize(gen) }
249
+ : pickImageSize(gen, {
250
+ ...(input.size !== undefined && { size: input.size }),
251
+ ...(input.aspectRatio !== undefined && { aspectRatio: input.aspectRatio }),
252
+ });
251
253
  if (!size.ok)
252
254
  return bad(size.error);
253
255
  const params = sanitizeParams(info.parameters ?? [], target.params).value;
@@ -21,68 +21,26 @@ import { StorageService } from "../storage/storage.service.js";
21
21
  */
22
22
  /** The kinds a purpose can need: the callable model kinds. */
23
23
  export type PurposeKind = "chat" | "embedding" | "image_generation";
24
+ /** What a purpose needs of its target model beyond its kind. */
25
+ export interface PurposeRequires {
26
+ /** The target model must declare `capabilities.vision`. */
27
+ vision?: true;
28
+ }
29
+ interface KernelPurpose {
30
+ purpose: string;
31
+ kind: PurposeKind;
32
+ requires?: PurposeRequires;
33
+ label: {
34
+ zh: string;
35
+ en: string;
36
+ };
37
+ }
24
38
  /**
25
39
  * Purposes the kernel declares: the eval judge, and the three sub-agent model tiers (phase C,
26
40
  * spec §5.4: `fast` / `standard` / `capable` → `subagent_<tier>`; an unmapped tier runs on the
27
41
  * parent's model).
28
42
  */
29
- export declare const KERNEL_PURPOSES: readonly [{
30
- readonly purpose: "eval";
31
- readonly kind: "chat";
32
- readonly label: {
33
- readonly zh: "评测评委";
34
- readonly en: "Eval judge";
35
- };
36
- }, {
37
- readonly purpose: "title";
38
- readonly kind: "chat";
39
- readonly label: {
40
- readonly zh: "会话标题";
41
- readonly en: "Conversation titles";
42
- };
43
- }, {
44
- readonly purpose: "review";
45
- readonly kind: "chat";
46
- readonly label: {
47
- readonly zh: "命令审查";
48
- readonly en: "Command review";
49
- };
50
- }, {
51
- readonly purpose: "web_fetch";
52
- readonly kind: "chat";
53
- readonly label: {
54
- readonly zh: "网页提取";
55
- readonly en: "Web page extraction";
56
- };
57
- }, {
58
- readonly purpose: "subagent_fast";
59
- readonly kind: "chat";
60
- readonly label: {
61
- readonly zh: "子智能体:快速";
62
- readonly en: "Sub-agent: fast";
63
- };
64
- }, {
65
- readonly purpose: "subagent_standard";
66
- readonly kind: "chat";
67
- readonly label: {
68
- readonly zh: "子智能体:标准";
69
- readonly en: "Sub-agent: standard";
70
- };
71
- }, {
72
- readonly purpose: "subagent_capable";
73
- readonly kind: "chat";
74
- readonly label: {
75
- readonly zh: "子智能体:最强";
76
- readonly en: "Sub-agent: capable";
77
- };
78
- }, {
79
- readonly purpose: "image";
80
- readonly kind: "image_generation";
81
- readonly label: {
82
- readonly zh: "图片生成";
83
- readonly en: "Image generation";
84
- };
85
- }];
43
+ export declare const KERNEL_PURPOSES: readonly KernelPurpose[];
86
44
  /** 一个用途映射到的模型与参数。 */
87
45
  export interface PurposeTarget {
88
46
  model: ModelRef;
@@ -95,6 +53,8 @@ export interface PurposeView {
95
53
  zh: string;
96
54
  en: string;
97
55
  };
56
+ /** What the target model must support beyond its kind; absent = nothing. */
57
+ requires?: PurposeRequires;
98
58
  /** `kernel` 或声明它的插件名。 */
99
59
  declaredBy: string;
100
60
  default: PurposeTarget | null;
@@ -63,6 +63,16 @@ export const KERNEL_PURPOSES = [
63
63
  },
64
64
  /** The `GenerateImage` tool's model; no fallback: unmapped → `model.unconfigured`. */
65
65
  { purpose: "image", kind: "image_generation", label: { zh: "图片生成", en: "Image generation" } },
66
+ /**
67
+ * The model that reads an image for a model without vision; no fallback: unmapped, or a target
68
+ * without `capabilities.vision` → `model.unconfigured`.
69
+ */
70
+ {
71
+ purpose: "vision",
72
+ kind: "chat",
73
+ requires: { vision: true },
74
+ label: { zh: "识图", en: "Vision" },
75
+ },
66
76
  ];
67
77
  /** {@link PurposeListing}s of `views`, the display names read in one call. */
68
78
  export async function withDeclaredByNames(views, names) {
@@ -147,6 +157,7 @@ let ModelPurposesService = class ModelPurposesService {
147
157
  purpose: p.purpose,
148
158
  kind: p.kind,
149
159
  label: { ...p.label },
160
+ ...(p.requires !== undefined && { requires: { ...p.requires } }),
150
161
  declaredBy: "kernel",
151
162
  }));
152
163
  const seen = new Set(out.map((p) => p.purpose));
@@ -231,7 +242,7 @@ let ModelPurposesService = class ModelPurposesService {
231
242
  * 校验目标:模型可解析且启用(an org's override for the org, a deployment default in the
232
243
  * platform view)、its kind is the purpose's `kind`、参数按它的声明严格通过。
233
244
  */
234
- async check(orgId, target, kind) {
245
+ async check(orgId, target, kind, requires) {
235
246
  let info;
236
247
  try {
237
248
  info =
@@ -255,6 +266,11 @@ let ModelPurposesService = class ModelPurposesService {
255
266
  },
256
267
  ]);
257
268
  }
269
+ if (requires?.vision === true && !info.capabilities.vision) {
270
+ throw invalid([
271
+ { path: "target.model", message: "this purpose needs a model that can view images" },
272
+ ]);
273
+ }
258
274
  const issues = paramIssues("target.params", info.parameters, target.params);
259
275
  if (issues.length > 0)
260
276
  throw invalid(issues);
@@ -262,7 +278,7 @@ let ModelPurposesService = class ModelPurposesService {
262
278
  async set(orgId, purpose, target, actor, actorTokenId, auditDetail) {
263
279
  const decl = this.find(purpose);
264
280
  if (target)
265
- await this.check(orgId, target, decl.kind);
281
+ await this.check(orgId, target, decl.kind, decl.requires);
266
282
  await this.write(orgId, purpose, target, actor, actorTokenId, auditDetail);
267
283
  const [view] = await this.views([decl], orgId ?? undefined);
268
284
  return view;
@@ -275,7 +291,7 @@ let ModelPurposesService = class ModelPurposesService {
275
291
  async validate(orgId, purpose, target) {
276
292
  const decl = this.find(purpose);
277
293
  if (target)
278
- await this.check(orgId, target, decl.kind);
294
+ await this.check(orgId, target, decl.kind, decl.requires);
279
295
  }
280
296
  /** The mapping write of {@link set}, under the super admin or org lock. */
281
297
  async write(orgId, purpose, target, actor, actorTokenId, auditDetail) {
@@ -343,7 +359,12 @@ let ModelPurposesService = class ModelPurposesService {
343
359
  throw new ApiError("model.unconfigured", `No model is configured for the "${purpose}" purpose`);
344
360
  }
345
361
  try {
346
- await this.providers.resolve(orgId, view.effective.model, { kind: decl.kind });
362
+ const { info } = await this.providers.resolve(orgId, view.effective.model, {
363
+ kind: decl.kind,
364
+ });
365
+ if (decl.requires?.vision === true && !info.capabilities.vision) {
366
+ throw new ApiError("model.unconfigured", `The model configured for the "${purpose}" purpose cannot view images`);
367
+ }
347
368
  }
348
369
  catch (e) {
349
370
  if (e instanceof ProviderListError)
@@ -51,6 +51,11 @@ export interface ModelCallMeta {
51
51
  media?: MediaOutcomeEntry[];
52
52
  /** 请求里有媒体、且给了有限的预算时:所用的媒体字节预算(还原时重现同样的省略)。 */
53
53
  mediaBudgetBytes?: number;
54
+ /**
55
+ * The Read-image window the request was built with, when it renders an image from Read and a
56
+ * window was given (reconstruction repeats the same evictions).
57
+ */
58
+ readImagesPerRequest?: number;
54
59
  }
55
60
  /** 构建请求用到的工具信息(`ResolvedTool` 的子集)。 */
56
61
  export type RequestTool = Pick<ResolvedTool, "key" | "spec" | "specHash">;
@@ -110,6 +115,11 @@ export interface BuildModelRequestInput {
110
115
  media?: ReadonlyMap<string, MediaBytes | null>;
111
116
  /** 单次请求里媒体原始字节的预算(见 {@link planMedia});默认不限。 */
112
117
  mediaBudgetBytes?: number;
118
+ /**
119
+ * The Read-image window (`attachments.readImagesPerRequest`, see {@link readImageWindow}); absent
120
+ * means no window. The runtime passes the config value, a reconstruction the recorded one.
121
+ */
122
+ readImagesPerRequest?: number;
113
123
  }
114
124
  /** 一个附件的字节。 */
115
125
  export interface MediaBytes {
@@ -154,61 +164,96 @@ export declare const PDF_BYTES_PER_PAGE_ESTIMATE: number;
154
164
  export declare function pdfTokens(size: number, pages: number | null): number;
155
165
  /** 日志里(按 zod 推导的形状)的内容块。 */
156
166
  type LogBlock = EventPayload<"user_message">["content"][number];
167
+ /** One image the builtin Read stored (`tool_result.media`, vision-read design §1.2). */
168
+ export type ReadMedia = NonNullable<EventPayload<"tool_result">["media"]>[number];
169
+ /**
170
+ * The Read-image window with chunked eviction (vision-read design §1.4): walks the images from Read
171
+ * in log order with a kept set; whenever the set grows past `window`, it is cut to its newest
172
+ * `floor(window / 2)`. So the kept set changes only at those overflow points and the request's
173
+ * prefix stays the same between them. Decided from the log alone (the ids in log order and the
174
+ * recorded window). Returns the kept ids; `window` undefined keeps every id.
175
+ */
176
+ export declare function readImageWindow(ids: readonly string[], window: number | undefined): Set<string>;
157
177
  /**
158
178
  * 日志里 `media_excluded` 排除的附件(全部事件的并集,不看摘要边界):此后的请求一律换成「被供应商拒绝」占位。
159
179
  */
160
180
  export declare function excludedMedia(events: readonly ConversationEvent[]): Set<string>;
161
181
  /**
162
- * 该模型需要其附件行的附件 id(去重、按出现顺序),调用方据此查行信息({@link MediaInfo})。
163
- * 模型不支持的图片 / PDF、被 `media_excluded` 排除的不在其中——只发占位,行与字节都不取。
164
- * `file` 块在结果里(引用行要行里的大小与 URI),但从不取字节。
182
+ * The attachment ids whose rows this model needs (deduplicated, in order of appearance), for the
183
+ * caller to look up ({@link MediaInfo}). Images / PDFs the model cannot take, ones excluded by
184
+ * `media_excluded`, and images from Read the window leaves out (`readWindow`, see
185
+ * {@link readImageWindow}) are not in it: they render without a row or bytes. `file` blocks are in
186
+ * it (the reference line needs the row's size and URI) but their bytes are never fetched.
165
187
  */
166
- export declare function mediaRefs(events: readonly ConversationEvent[], model: ModelInfo): string[];
167
- /** {@link planMedia} 的结果。 */
188
+ export declare function mediaRefs(events: readonly ConversationEvent[], model: ModelInfo, readWindow?: number): string[];
189
+ /** The result of {@link planMedia}. */
168
190
  export interface MediaPlan {
169
- /** 要取字节的附件 id(从新到旧)。 */
191
+ /** The attachment ids whose bytes are fetched (newest first). */
170
192
  fetch: string[];
171
193
  /**
172
- * 只取开头若干字节的附件(`text/*` 超过 {@link TEXT_FETCH_MAX_BYTES}):id → 字节数。
173
- * 现在总是空:超过取字节上限的文本不再取(它是引用行,§5.2),上限之内的取整份。
194
+ * Attachments fetched only up to a number of leading bytes (`text/*` over
195
+ * {@link TEXT_FETCH_MAX_BYTES}): id → bytes. Always empty now: text over the fetch cap is not
196
+ * fetched at all (it is the reference line, §5.2), text below it is fetched whole.
174
197
  */
175
198
  caps: Map<string, number>;
176
- /** 为控制请求大小而省略(预算)。 */
199
+ /** Omitted to keep the request size down (the budget). */
177
200
  dropped: Set<string>;
178
- /** 图片超过 {@link MAX_IMAGES_PER_REQUEST} 而省略。 */
201
+ /** Omitted because the images exceed {@link MAX_IMAGES_PER_REQUEST}. */
179
202
  tooManyImages: Set<string>;
180
- /** PDF 页数超过 {@link MAX_PDF_PAGES}。 */
203
+ /** A PDF over {@link MAX_PDF_PAGES} pages. */
181
204
  tooManyPages: Set<string>;
182
- /** 日志里 `media_excluded` 排除的。 */
205
+ /** Excluded by `media_excluded` in the log. */
183
206
  excluded: Set<string>;
207
+ /** Images from Read the Read-image window left out ({@link readImageWindow}): not fetched. */
208
+ notIncluded: Set<string>;
184
209
  }
185
210
  /**
186
- * 单次请求的媒体计划(Ruling M6 / M8),只取决于日志、模型能力与行信息,是确定的:
187
- * - 被 `media_excluded` 排除的:不取、不计;
188
- * - `file` 块(模型只看到引用行):不取、不计(行信息照常查);
189
- * - `text/*` 超过 {@link TEXT_FETCH_MAX_BYTES}:不取(它就是引用行,§5.2)——上限之内的取整份,
190
- * 解码后超过 {@link TEXT_INLINE_MAX_CHARS} 的在 {@link resolveMedia} 里也变成引用行;
191
- * - PDF 页数超过 {@link MAX_PDF_PAGES}:不取、不计;
192
- * - 从最新的媒体往前:图片最多保留 {@link MAX_IMAGES_PER_REQUEST} 张,更早的图片省略(不影响其他媒体);
193
- * - 预算:按行里的**声明大小**累计,第一次超出 `budgetBytes` 起,该附件及更早的全部省略;
194
- * - 同一附件只算一次(按最后一次出现的位置算新旧);没有行的不计(它们是「不再可用」)。
211
+ * The media plan of one request (Ruling M6 / M8): decided by the log, the model's capabilities and
212
+ * the rows alone, so it is deterministic:
213
+ * - excluded by `media_excluded`: not fetched, not counted;
214
+ * - a `file` block (the model sees only the reference line): not fetched, not counted (its row is
215
+ * still looked up);
216
+ * - `text/*` over {@link TEXT_FETCH_MAX_BYTES}: not fetched (it is the reference line, §5.2); below
217
+ * it, fetched whole, and one that decodes past {@link TEXT_INLINE_MAX_CHARS} also becomes the
218
+ * reference line in {@link resolveMedia};
219
+ * - a PDF over {@link MAX_PDF_PAGES} pages: not fetched, not counted;
220
+ * - images from Read (vision models only): first the Read-image window (`readWindow`,
221
+ * {@link readImageWindow}); the ones it leaves out are `notIncluded`, not fetched and not
222
+ * counted, the kept ones then count toward the image cap and the budget like pasted images;
223
+ * - from the newest media back: at most {@link MAX_IMAGES_PER_REQUEST} images, older images are
224
+ * omitted (other media unaffected);
225
+ * - the budget: the rows' **declared sizes** add up; from the first one past `budgetBytes`, that
226
+ * attachment and every older one are omitted;
227
+ * - an attachment counts once (its last position decides how new it is); one without a row does
228
+ * not count (it is "no longer available").
195
229
  *
196
- * 已知取舍(接受):新的媒体把较早的媒体挤成占位时,请求里**较早位置**的内容随之改变,这一处之后的提示词缓存
197
- * 失效(不是严格的只追加)。配置保证 `maxBytes ≤ requestMediaBytes`,所以最新的附件总能放进请求。
230
+ * Accepted trade-off: when newer media push older media out into placeholders, content at an
231
+ * **earlier position** of the request changes and the prompt cache after it is lost (not strictly
232
+ * append-only). The config keeps `maxBytes ≤ requestMediaBytes`, so the newest attachment always fits.
233
+ * The Read-image window makes this rare for images from Read: it evicts in chunks.
198
234
  */
199
- export declare function planMedia(events: readonly ConversationEvent[], model: ModelInfo, info: ReadonlyMap<string, MediaInfo>, budgetBytes?: number): MediaPlan;
235
+ export declare function planMedia(events: readonly ConversationEvent[], model: ModelInfo, info: ReadonlyMap<string, MediaInfo>, budgetBytes?: number, readWindow?: number): MediaPlan;
200
236
  /** 文字占位里的附件名:按 JSON 字符串转义(带引号),名字里的引号、括号不会打乱占位。 */
201
237
  export declare const quoted: (name: string) => string;
202
238
  /** 附件不可用时的占位(模型可见,英文)。 */
203
239
  export declare const mediaUnavailableText: (name: string) => string;
204
240
  /** 为控制单次请求大小而省略的附件(模型可见,英文)。 */
205
241
  export declare const mediaOmittedText: (name: string) => string;
206
- /** 单次请求图片太多而省略的附件(模型可见,英文)。 */
242
+ /** An attachment omitted because one request has too many images (model-facing, English). */
207
243
  export declare const mediaTooManyImagesText: (name: string) => string;
208
- /** PDF 页数超过上限(模型可见,英文)。 */
244
+ /** A PDF over the page limit (model-facing, English). */
209
245
  export declare const mediaTooManyPagesText: (name: string) => string;
210
- /** 被供应商拒绝、此后不再发送的附件(模型可见,英文)。 */
246
+ /** An attachment the provider rejected, never sent again (model-facing, English). */
211
247
  export declare const mediaRejectedText: (name: string) => string;
248
+ /** The label before an image from Read (model-facing, vision-read design §1.4). */
249
+ export declare const readImageLabelText: (id: string) => string;
250
+ /**
251
+ * An image from Read for a model without vision (static, so history stays append-only; any
252
+ * fallback answer is already in the tool result).
253
+ */
254
+ export declare const READ_IMAGE_NO_VISION_TEXT = "[This model cannot view images.]";
255
+ /** An image from Read the Read-image window left out of this request. */
256
+ export declare const readImageNotIncludedText: (id: string) => string;
212
257
  /**
213
258
  * A reference line (model-facing English, one text block, §5.2): the file's name and media type, its
214
259
  * size, the unsigned object URI, and how to get the bytes — `FetchAttachment` copies the file into the
@@ -304,7 +349,7 @@ export declare function summaryText(summary: string): string;
304
349
  export declare function buildModelRequest(input: BuildModelRequestInput): {
305
350
  request: ModelRequest;
306
351
  meta: ModelCallMeta;
307
- /** 请求里媒体块(base64 的图片 / 文档)的估算 token 数,传给 `estimateTokens`。 */
352
+ /** Estimated tokens of the request's media blocks (base64 images / documents), for `estimateTokens`. */
308
353
  mediaTokens: number;
309
354
  };
310
355
  /**