@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
@@ -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";
@@ -63,20 +63,103 @@ function mediaMode(b, model) {
63
63
  return "bytes";
64
64
  return isText(b.mediaType) ? "inline" : "placeholder";
65
65
  }
66
+ /** The key a tool result is matched to its call by: (runId, callId). */
67
+ const resultKey = (runId, callId) => `${runId ?? ""}\u0000${callId}`;
66
68
  /**
67
- * 最近摘要之后、会进请求的消息里,该模型需要其附件行(大小、页数、无签名引用)的媒体块(按 seq 与块顺序),
68
- * 也包括随摘要再次发送的用户消息(摘要的 `openingSeqs`,{@link summaryOpeners})。`file` 块只在其中取行信息,
69
- * 从不取字节(见 {@link planMedia})。
69
+ * The tool results a request renders (`events` sorted by seq): after the summary boundary, the
70
+ * first result of each call, and only when an assistant message after the boundary (with content)
71
+ * carries the call. Keyed by {@link resultKey}.
70
72
  */
71
- function mediaBlocks(events, model) {
73
+ function renderedResults(events, after) {
74
+ const first = new Map();
75
+ const called = new Set();
76
+ for (const e of events) {
77
+ if (e.seq <= after)
78
+ continue;
79
+ if (e.type === "tool_result") {
80
+ const k = resultKey(e.runId, e.payload.callId);
81
+ if (!first.has(k))
82
+ first.set(k, e);
83
+ }
84
+ else if (e.type === "assistant_message" && e.payload.content.length > 0) {
85
+ for (const b of e.payload.content) {
86
+ if (b.type === "tool_call")
87
+ called.add(resultKey(e.runId, b.id));
88
+ }
89
+ }
90
+ }
91
+ for (const k of [...first.keys()])
92
+ if (!called.has(k))
93
+ first.delete(k);
94
+ return first;
95
+ }
96
+ /**
97
+ * The images from Read a request renders, in log order (`events` sorted by seq): by their result's
98
+ * seq. Rendering places them in call order (after the step's results), so parallel calls that
99
+ * finish out of order are "newer" for the window and the image cap in the order they finished,
100
+ * not the order they show; both orders come from the log, so this stays deterministic.
101
+ */
102
+ function readImages(events, after) {
103
+ return [...renderedResults(events, after).values()]
104
+ .sort((a, b) => a.seq - b.seq)
105
+ .flatMap((e) => e.payload.media ?? []);
106
+ }
107
+ /**
108
+ * The Read-image window with chunked eviction (vision-read design §1.4): walks the images from Read
109
+ * in log order with a kept set; whenever the set grows past `window`, it is cut to its newest
110
+ * `floor(window / 2)`. So the kept set changes only at those overflow points and the request's
111
+ * prefix stays the same between them. Decided from the log alone (the ids in log order and the
112
+ * recorded window). Returns the kept ids; `window` undefined keeps every id.
113
+ */
114
+ export function readImageWindow(ids, window) {
115
+ if (window === undefined)
116
+ return new Set(ids);
117
+ let kept = [];
118
+ for (const id of ids) {
119
+ kept.push(id);
120
+ if (kept.length > window)
121
+ kept = kept.slice(kept.length - Math.floor(window / 2));
122
+ }
123
+ return new Set(kept);
124
+ }
125
+ /** An image from Read as a log media block (a `ref` to its `read` attachment). */
126
+ function readBlock(m) {
127
+ return {
128
+ type: "image",
129
+ mediaType: m.mediaType,
130
+ source: { kind: "ref", attachmentId: m.attachmentId },
131
+ name: m.name,
132
+ };
133
+ }
134
+ /**
135
+ * The media blocks after the latest summary, in the messages the request renders, whose attachment
136
+ * rows (size, pages, unsigned reference) this model needs, by seq and block order; the user messages
137
+ * re-sent with the summary (its `openingSeqs`, {@link summaryOpeners}) count too. A `file` block
138
+ * only needs its row, never its bytes (see {@link planMedia}). Images from Read (`tool_result.media`
139
+ * of the rendered results) join at their result's position when the model has vision and the
140
+ * Read-image window keeps them ({@link readImageWindow}; no window given keeps all).
141
+ */
142
+ function mediaBlocks(events, model, readWindow) {
72
143
  const sorted = [...events].sort((a, b) => a.seq - b.seq);
73
144
  const summary = latestSummary(sorted);
74
145
  const after = summary?.payload.coversUpToSeq ?? Number.NEGATIVE_INFINITY;
75
146
  const openers = new Set(summaryOpeners(sorted, summary));
147
+ const rendered = new Set(renderedResults(sorted, after).values());
148
+ const kept = readImageWindow(readImages(sorted, after).map((m) => m.attachmentId), readWindow);
76
149
  const out = [];
77
150
  for (const e of sorted) {
78
151
  if (e.seq <= after && !openers.has(e))
79
152
  continue;
153
+ if (e.type === "tool_result") {
154
+ const media = e.payload.media ?? [];
155
+ if (media.length === 0 || !rendered.has(e) || !model.capabilities.vision)
156
+ continue;
157
+ for (const m of media) {
158
+ if (kept.has(m.attachmentId))
159
+ out.push(readBlock(m));
160
+ }
161
+ continue;
162
+ }
80
163
  if (e.type !== "user_message" && e.type !== "assistant_message")
81
164
  continue;
82
165
  for (const b of e.payload.content) {
@@ -101,33 +184,50 @@ export function excludedMedia(events) {
101
184
  return out;
102
185
  }
103
186
  /**
104
- * 该模型需要其附件行的附件 id(去重、按出现顺序),调用方据此查行信息({@link MediaInfo})。
105
- * 模型不支持的图片 / PDF、被 `media_excluded` 排除的不在其中——只发占位,行与字节都不取。
106
- * `file` 块在结果里(引用行要行里的大小与 URI),但从不取字节。
187
+ * The attachment ids whose rows this model needs (deduplicated, in order of appearance), for the
188
+ * caller to look up ({@link MediaInfo}). Images / PDFs the model cannot take, ones excluded by
189
+ * `media_excluded`, and images from Read the window leaves out (`readWindow`, see
190
+ * {@link readImageWindow}) are not in it: they render without a row or bytes. `file` blocks are in
191
+ * it (the reference line needs the row's size and URI) but their bytes are never fetched.
107
192
  */
108
- export function mediaRefs(events, model) {
193
+ export function mediaRefs(events, model, readWindow) {
109
194
  const excluded = excludedMedia(events);
110
195
  return [
111
- ...new Set(mediaBlocks(events, model)
196
+ ...new Set(mediaBlocks(events, model, readWindow)
112
197
  .map((b) => b.source.attachmentId)
113
198
  .filter((id) => !excluded.has(id))),
114
199
  ];
115
200
  }
116
201
  /**
117
- * 单次请求的媒体计划(Ruling M6 / M8),只取决于日志、模型能力与行信息,是确定的:
118
- * - 被 `media_excluded` 排除的:不取、不计;
119
- * - `file` 块(模型只看到引用行):不取、不计(行信息照常查);
120
- * - `text/*` 超过 {@link TEXT_FETCH_MAX_BYTES}:不取(它就是引用行,§5.2)——上限之内的取整份,
121
- * 解码后超过 {@link TEXT_INLINE_MAX_CHARS} 的在 {@link resolveMedia} 里也变成引用行;
122
- * - PDF 页数超过 {@link MAX_PDF_PAGES}:不取、不计;
123
- * - 从最新的媒体往前:图片最多保留 {@link MAX_IMAGES_PER_REQUEST} 张,更早的图片省略(不影响其他媒体);
124
- * - 预算:按行里的**声明大小**累计,第一次超出 `budgetBytes` 起,该附件及更早的全部省略;
125
- * - 同一附件只算一次(按最后一次出现的位置算新旧);没有行的不计(它们是「不再可用」)。
202
+ * The media plan of one request (Ruling M6 / M8): decided by the log, the model's capabilities and
203
+ * the rows alone, so it is deterministic:
204
+ * - excluded by `media_excluded`: not fetched, not counted;
205
+ * - a `file` block (the model sees only the reference line): not fetched, not counted (its row is
206
+ * still looked up);
207
+ * - `text/*` over {@link TEXT_FETCH_MAX_BYTES}: not fetched (it is the reference line, §5.2); below
208
+ * it, fetched whole, and one that decodes past {@link TEXT_INLINE_MAX_CHARS} also becomes the
209
+ * reference line in {@link resolveMedia};
210
+ * - a PDF over {@link MAX_PDF_PAGES} pages: not fetched, not counted;
211
+ * - images from Read (vision models only): first the Read-image window (`readWindow`,
212
+ * {@link readImageWindow}); the ones it leaves out are `notIncluded`, not fetched and not
213
+ * counted, the kept ones then count toward the image cap and the budget like pasted images;
214
+ * - from the newest media back: at most {@link MAX_IMAGES_PER_REQUEST} images, older images are
215
+ * omitted (other media unaffected);
216
+ * - the budget: the rows' **declared sizes** add up; from the first one past `budgetBytes`, that
217
+ * attachment and every older one are omitted;
218
+ * - an attachment counts once (its last position decides how new it is); one without a row does
219
+ * not count (it is "no longer available").
126
220
  *
127
- * 已知取舍(接受):新的媒体把较早的媒体挤成占位时,请求里**较早位置**的内容随之改变,这一处之后的提示词缓存
128
- * 失效(不是严格的只追加)。配置保证 `maxBytes ≤ requestMediaBytes`,所以最新的附件总能放进请求。
221
+ * Accepted trade-off: when newer media push older media out into placeholders, content at an
222
+ * **earlier position** of the request changes and the prompt cache after it is lost (not strictly
223
+ * append-only). The config keeps `maxBytes ≤ requestMediaBytes`, so the newest attachment always fits.
224
+ * The Read-image window makes this rare for images from Read: it evicts in chunks.
129
225
  */
130
- export function planMedia(events, model, info, budgetBytes = Number.POSITIVE_INFINITY) {
226
+ export function planMedia(events, model, info, budgetBytes = Number.POSITIVE_INFINITY, readWindow) {
227
+ const sorted = [...events].sort((a, b) => a.seq - b.seq);
228
+ const after = latestSummary(sorted)?.payload.coversUpToSeq ?? Number.NEGATIVE_INFINITY;
229
+ const reads = readImages(sorted, after).map((m) => m.attachmentId);
230
+ const kept = readImageWindow(reads, readWindow);
131
231
  const plan = {
132
232
  fetch: [],
133
233
  caps: new Map(),
@@ -135,9 +235,10 @@ export function planMedia(events, model, info, budgetBytes = Number.POSITIVE_INF
135
235
  tooManyImages: new Set(),
136
236
  tooManyPages: new Set(),
137
237
  excluded: excludedMedia(events),
238
+ notIncluded: new Set(reads.length > 0 && model.capabilities.vision ? reads.filter((id) => !kept.has(id)) : []),
138
239
  };
139
240
  // 每个附件按最后一次出现的位置算新旧
140
- const blocks = mediaBlocks(events, model);
241
+ const blocks = mediaBlocks(events, model, readWindow);
141
242
  const last = new Map();
142
243
  for (const b of blocks) {
143
244
  const id = b.source.attachmentId;
@@ -187,12 +288,21 @@ export const quoted = (name) => JSON.stringify(name);
187
288
  export const mediaUnavailableText = (name) => `[Attachment ${quoted(name)} is no longer available.]`;
188
289
  /** 为控制单次请求大小而省略的附件(模型可见,英文)。 */
189
290
  export const mediaOmittedText = (name) => `[Attachment ${quoted(name)} omitted to fit the request size limit.]`;
190
- /** 单次请求图片太多而省略的附件(模型可见,英文)。 */
291
+ /** An attachment omitted because one request has too many images (model-facing, English). */
191
292
  export const mediaTooManyImagesText = (name) => `[Attachment ${quoted(name)} omitted (too many images in one request).]`;
192
- /** PDF 页数超过上限(模型可见,英文)。 */
293
+ /** A PDF over the page limit (model-facing, English). */
193
294
  export const mediaTooManyPagesText = (name) => `[Attachment ${quoted(name)} has too many pages for this model.]`;
194
- /** 被供应商拒绝、此后不再发送的附件(模型可见,英文)。 */
295
+ /** An attachment the provider rejected, never sent again (model-facing, English). */
195
296
  export const mediaRejectedText = (name) => `[Attachment ${quoted(name)} was rejected by the model provider.]`;
297
+ /** The label before an image from Read (model-facing, vision-read design §1.4). */
298
+ export const readImageLabelText = (id) => `Image from Read (file_id ${id}):`;
299
+ /**
300
+ * An image from Read for a model without vision (static, so history stays append-only; any
301
+ * fallback answer is already in the tool result).
302
+ */
303
+ export const READ_IMAGE_NO_VISION_TEXT = "[This model cannot view images.]";
304
+ /** An image from Read the Read-image window left out of this request. */
305
+ export const readImageNotIncludedText = (id) => `[Image from Read (file_id ${id}) not included in this request.]`;
196
306
  /**
197
307
  * The usual file extension per content type: the label of a `file` block logged without a name (every
198
308
  * accepted type, so the reference line always names something a person could recognise).
@@ -233,7 +343,7 @@ export const attachmentReferenceText = (input) => {
233
343
  };
234
344
  function placeholder(b, name) {
235
345
  if (b.type === "image") {
236
- return `[Attached image ${quoted(name)} — this model cannot view images.]`;
346
+ return `[Attached image ${quoted(name)} — this model cannot view images. Read with file_id ${b.source.attachmentId} sends it to the organization's vision model, if one is set.]`;
237
347
  }
238
348
  return `[Attached document ${quoted(name)} — this model cannot read ${b.mediaType === "application/pdf" ? "PDF documents" : "documents"}.]`;
239
349
  }
@@ -383,7 +493,15 @@ export function resolveMedia(content, model, ctx) {
383
493
  data: Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString("base64"),
384
494
  };
385
495
  out.push(b.type === "image"
386
- ? { 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
+ }
387
505
  : {
388
506
  type: "document",
389
507
  mediaType: b.mediaType,
@@ -456,7 +574,7 @@ export function buildModelRequest(input) {
456
574
  const mediaCtx = {
457
575
  info: input.mediaInfo,
458
576
  bytes: input.media,
459
- plan: planMedia(events, model, input.mediaInfo ?? new Map(), input.mediaBudgetBytes),
577
+ plan: planMedia(events, model, input.mediaInfo ?? new Map(), input.mediaBudgetBytes, input.readImagesPerRequest),
460
578
  };
461
579
  let mediaTokens = 0;
462
580
  /** 本次请求里每个附件的处理结果(按首次出现,同一附件只记一次)。 */
@@ -623,9 +741,11 @@ export function buildModelRequest(input) {
623
741
  }
624
742
  };
625
743
  /**
626
- * 把已被吸收(seq ≤ upTo)的延后消息按 seq 顺序放进 messages,插在末尾连续的 system 提醒之前
627
- * (若有)。这样某一步自己写在 model_call 之前的提醒(含收尾提醒)仍排在它所跟随的用户消息之后,
628
- * 收尾提醒保持在请求末尾。只要求确定性:本次请求与由日志还原时执行的是同一套规则,结果一致。
744
+ * Puts the deferred messages already absorbed (seq ≤ upTo) into messages in seq order, before the
745
+ * trailing run of system reminders (if any). So a reminder a step wrote before its model_call
746
+ * (the wrap-up one included) still follows the user message it goes with, and the wrap-up
747
+ * reminder stays at the end of the request. Only determinism is required: this request and a
748
+ * reconstruction from the log run the same rules and get the same result.
629
749
  */
630
750
  const flush = (upTo) => {
631
751
  const ready = deferred.filter((u) => u.seq <= upTo);
@@ -637,9 +757,33 @@ export function buildModelRequest(input) {
637
757
  at--;
638
758
  messages.splice(at, 0, ...ready.map(absorbableMessage));
639
759
  };
640
- /** (runId, callId) → 该调用的 tool_result 事件(同一调用只取第一个)。 */
760
+ /**
761
+ * The blocks of the images from Read of one result (vision-read design §1.4), each after its
762
+ * label: the image (through {@link resolveMedia}, so the cap, the budget and `media_excluded`
763
+ * apply), the static text for a model without vision, or the window's "not included" text.
764
+ */
765
+ const readBlocks = (media) => media.flatMap((m) => {
766
+ const id = m.attachmentId;
767
+ const note = (text, outcome) => {
768
+ if (!mediaOutcomes.has(id))
769
+ mediaOutcomes.set(id, { attachmentId: id, outcome });
770
+ return [{ type: "text", text }];
771
+ };
772
+ if (!model.capabilities.vision) {
773
+ return [
774
+ { type: "text", text: readImageLabelText(id) },
775
+ ...note(READ_IMAGE_NO_VISION_TEXT, "placeholder_unsupported"),
776
+ ];
777
+ }
778
+ if (mediaCtx.plan.notIncluded.has(id)) {
779
+ return note(readImageNotIncludedText(id), "not_included");
780
+ }
781
+ return [{ type: "text", text: readImageLabelText(id) }, ...blocksOf([readBlock(m)])];
782
+ });
783
+ /** Whether the request renders an image from Read (the window is then recorded). */
784
+ let hasReadImages = false;
785
+ /** (runId, callId) → the call's tool_result (the first one per call). */
641
786
  const results = new Map();
642
- const resultKey = (runId, callId) => `${runId ?? ""}\u0000${callId}`;
643
787
  for (const e of events) {
644
788
  if (e.seq <= after || e.type !== "tool_result")
645
789
  continue;
@@ -732,6 +876,8 @@ export function buildModelRequest(input) {
732
876
  if (e.payload.content.length > 0) {
733
877
  messages.push({ role: "assistant", content: blocksOf(e.payload.content) });
734
878
  const blocks = [];
879
+ /** Images from Read (vision-read design §1.4): after all tool results, in call order. */
880
+ const images = [];
735
881
  for (const b of e.payload.content) {
736
882
  if (b.type !== "tool_call")
737
883
  continue;
@@ -743,10 +889,14 @@ export function buildModelRequest(input) {
743
889
  content: r.content,
744
890
  isError: r.isError,
745
891
  });
892
+ if (r.media !== undefined && r.media.length > 0) {
893
+ hasReadImages = true;
894
+ images.push(...readBlocks(r.media));
895
+ }
746
896
  }
747
897
  }
748
898
  if (blocks.length > 0)
749
- messages.push({ role: "user", content: blocks });
899
+ messages.push({ role: "user", content: [...blocks, ...images] });
750
900
  }
751
901
  break;
752
902
  case "reminder":
@@ -921,6 +1071,10 @@ export function buildModelRequest(input) {
921
1071
  ...(mediaOutcomes.size > 0 &&
922
1072
  input.mediaBudgetBytes !== undefined &&
923
1073
  Number.isFinite(input.mediaBudgetBytes) && { mediaBudgetBytes: input.mediaBudgetBytes }),
1074
+ ...(hasReadImages &&
1075
+ input.readImagesPerRequest !== undefined && {
1076
+ readImagesPerRequest: input.readImagesPerRequest,
1077
+ }),
924
1078
  };
925
1079
  return { request, meta, mediaTokens };
926
1080
  }
@@ -575,13 +575,17 @@ export function assembleModelRequest(input) {
575
575
  request.messages = applyFit(request, fit).messages;
576
576
  return built;
577
577
  }
578
+ function mediaLimits(deps) {
579
+ const { requestMediaBytes, readImagesPerRequest } = deps.config.get().attachments;
580
+ return { budgetBytes: requestMediaBytes, readImagesPerRequest };
581
+ }
578
582
  /**
579
583
  * 由事件构建本步的模型请求({@link assembleModelRequest})并给出输入 token 估算。
580
584
  *
581
585
  * 调用方不变式:不得在「已记录 tool_call、尚未记录其 tool_result」之间构建请求——
582
586
  * 否则配对守卫会给进行中的调用补上 unknown 结果并发给模型。运行循环在工具结果落日志后才进入下一步。
583
587
  */
584
- function buildRequest(deps, events, input, info, params, runtime, tools, wrapUp) {
588
+ function buildRequest(limits, events, input, info, params, runtime, tools, wrapUp) {
585
589
  const { request, meta, mediaTokens } = assembleModelRequest({
586
590
  events,
587
591
  agent: input.agent,
@@ -595,7 +599,8 @@ function buildRequest(deps, events, input, info, params, runtime, tools, wrapUp)
595
599
  ...(wrapUp && { toolChoice: "none" }),
596
600
  mediaInfo: tools.media.info,
597
601
  media: tools.media.bytes,
598
- mediaBudgetBytes: deps.config.get().attachments.requestMediaBytes,
602
+ mediaBudgetBytes: limits.budgetBytes,
603
+ readImagesPerRequest: limits.readImagesPerRequest,
599
604
  defaultMaxOutputTokens: runtime.maxOutputTokens,
600
605
  });
601
606
  return {
@@ -610,9 +615,9 @@ function buildRequest(deps, events, input, info, params, runtime, tools, wrapUp)
610
615
  * 并入 `tools.media`。先查本次运行的缓存(键含 etag),未命中才取。
611
616
  * 取不到(确定不存在)的缓存为 null;暂时故障抛 {@link MediaUnavailableError},不缓存,下一次尝试重新取。
612
617
  */
613
- async function loadMedia(deps, input, events, info, tools) {
618
+ async function loadMedia(deps, limits, input, events, info, tools) {
614
619
  const cache = tools.media;
615
- const look = mediaRefs(events, info).filter((id) => !cache.looked.has(id));
620
+ const look = mediaRefs(events, info, limits.readImagesPerRequest).filter((id) => !cache.looked.has(id));
616
621
  if (look.length > 0) {
617
622
  if (deps.media) {
618
623
  let rows;
@@ -628,8 +633,7 @@ async function loadMedia(deps, input, events, info, tools) {
628
633
  for (const id of look)
629
634
  cache.looked.add(id);
630
635
  }
631
- const budget = deps.config.get().attachments.requestMediaBytes;
632
- const plan = planMedia(events, info, cache.info, budget);
636
+ const plan = planMedia(events, info, cache.info, limits.budgetBytes, limits.readImagesPerRequest);
633
637
  const runKey = (id) => MediaCache.key(id, cache.info.get(id), plan.caps.get(id));
634
638
  const need = [];
635
639
  for (const id of plan.fetch) {
@@ -751,8 +755,9 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
751
755
  deps.log.warn("compaction skipped: model unavailable", { model: modelRef, err });
752
756
  return skipped(events);
753
757
  }
758
+ const limits = mediaLimits(deps);
754
759
  try {
755
- await loadMedia(deps, input, events, info, tools);
760
+ await loadMedia(deps, limits, input, events, info, tools);
756
761
  }
757
762
  catch (err) {
758
763
  if (!(err instanceof MediaUnavailableError))
@@ -765,7 +770,7 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
765
770
  });
766
771
  return skipped(events);
767
772
  }
768
- const { request: built, estimate: raw } = buildRequest(deps, events, input, info, attemptParams(input.agent, info, opts.fallback === true).value, runtime, tools, false);
773
+ const { request: built, estimate: raw } = buildRequest(limits, events, input, info, attemptParams(input.agent, info, opts.fallback === true).value, runtime, tools, false);
769
774
  const estimate = calibrate(raw, lastActual(events));
770
775
  // The trigger's output cap is the step's own cap, min(agent max, model max) (spec §4.1), not the
771
776
  // settings' maxOutputTokens — that one caps the summary call (spec §4.8).
@@ -1262,8 +1267,9 @@ async function ladder(deps, input, events, runtime, compaction, tools, wrapUpRea
1262
1267
  const refreshed = await permissionContextBoundary(deps, input, attempt);
1263
1268
  if (refreshed !== undefined)
1264
1269
  evs = refreshed;
1265
- await loadMedia(deps, input, evs, info, tools);
1266
- const built = buildRequest(deps, evs, input, info, params.value, runtime, tools, wrapUp);
1270
+ const limits = mediaLimits(deps);
1271
+ await loadMedia(deps, limits, input, evs, info, tools);
1272
+ const built = buildRequest(limits, evs, input, info, params.value, runtime, tools, wrapUp);
1267
1273
  const { request, estimate } = built;
1268
1274
  const fitInput = {
1269
1275
  events: evs,
@@ -54,8 +54,9 @@ export declare function narrowPending(stored: readonly string[] | undefined, fai
54
54
  * as are conversation title calls (`purpose: "title"`, no run: `runId` is "") and `WebFetch`
55
55
  * extraction calls (`purpose: "web_fetch"`). Command-review classifier calls log usage with
56
56
  * `purpose: "review"` and the reviewed tool call's `callId`; `GenerateImage` calls with
57
- * `purpose: "image"` and their `outputImages`, passed through in `usage`. Prompt suggestion calls
58
- * (`purpose: "suggestion"`) have no run either: `runId` is "".
57
+ * `purpose: "image"` and their `outputImages`, passed through in `usage`; vision reads of an
58
+ * image (`Read` for a model without vision) with `purpose: "vision"` and the call's `callId`.
59
+ * Prompt suggestion calls (`purpose: "suggestion"`) have no run either: `runId` is "".
59
60
  * Single-step eval replays and judge requests log no usage: not reported (M7).
60
61
  * - **Model usage outside conversations** (spec B §5.4): each `ctx.models.embed` and
61
62
  * `ctx.models.generateImage` call writes a `model_usage` row and owes job `usage-model-<rowId>`
@@ -109,8 +109,9 @@ export function narrowPending(stored, failed) {
109
109
  * as are conversation title calls (`purpose: "title"`, no run: `runId` is "") and `WebFetch`
110
110
  * extraction calls (`purpose: "web_fetch"`). Command-review classifier calls log usage with
111
111
  * `purpose: "review"` and the reviewed tool call's `callId`; `GenerateImage` calls with
112
- * `purpose: "image"` and their `outputImages`, passed through in `usage`. Prompt suggestion calls
113
- * (`purpose: "suggestion"`) have no run either: `runId` is "".
112
+ * `purpose: "image"` and their `outputImages`, passed through in `usage`; vision reads of an
113
+ * image (`Read` for a model without vision) with `purpose: "vision"` and the call's `callId`.
114
+ * Prompt suggestion calls (`purpose: "suggestion"`) have no run either: `runId` is "".
114
115
  * Single-step eval replays and judge requests log no usage: not reported (M7).
115
116
  * - **Model usage outside conversations** (spec B §5.4): each `ctx.models.embed` and
116
117
  * `ctx.models.generateImage` call writes a `model_usage` row and owes job `usage-model-<rowId>`
@@ -21,7 +21,7 @@ import { SandboxService } from "../../sandbox/sandbox.service.js";
21
21
  import { ScheduledTaskStore } from "../../schedules/store.js";
22
22
  import { StorageService } from "../../storage/storage.service.js";
23
23
  import { ToolOutputs } from "../outputs.js";
24
- import type { BuiltinTool } from "../registry.js";
24
+ import type { BuiltinCallContext, BuiltinTool } from "../registry.js";
25
25
  import type { SandboxToolDeps } from "./sandbox/common.js";
26
26
  import { ScheduleToolsPort, ScheduleUpdates } from "./schedules.js";
27
27
  import { WebPages } from "./web/index.js";
@@ -60,3 +60,10 @@ export declare class BuiltinTools {
60
60
  * legacy writer stays.
61
61
  */
62
62
  export declare function managedSandboxDeps(recorder: ManagedDeviceContextPort, activation: boolean | undefined): Pick<SandboxToolDeps, "managedDeviceContext" | "managedDeviceContextRequired">;
63
+ /**
64
+ * Whether "the chat model" of a `Read` call can view images (vision-read design §1.2): the model
65
+ * of the latest `model_call` of the call's run (a fallback step's model when the step fell back),
66
+ * its capabilities from the model list cache. A run with no model call yet, or a model the org can
67
+ * no longer resolve, counts as one that cannot: the vision purpose reads the image then.
68
+ */
69
+ export declare function chatModelSeesImages(db: KernelDb, providers: Pick<ProviderRegistry, "resolve">, ctx: BuiltinCallContext): Promise<boolean>;
@@ -16,6 +16,7 @@ import { AttachmentsService } from "../../conversations/attachments.service.js";
16
16
  import { EventLog } from "../../conversations/event-log.js";
17
17
  import { conversationAncestors } from "../../conversations/tree.js";
18
18
  import { ConversationDevices } from "../../devices/conversation-devices.js";
19
+ import { ApiError } from "../../errors.js";
19
20
  import { ExtensionHost } from "../../extensions/host.js";
20
21
  import { ExtensionPointDefaults } from "../../extensions/point-defaults.js";
21
22
  import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
@@ -27,7 +28,7 @@ import { readOrgSettings } from "../../orgs/settings.service.js";
27
28
  import { PlatformActor } from "../../platform/actor.js";
28
29
  import { AgentDocs } from "../../platform/agent-docs.js";
29
30
  import { PlatformOperations } from "../../platform/registry.js";
30
- import { ProviderRegistry } from "../../runtime/providers.js";
31
+ import { ProviderListError, ProviderRegistry } from "../../runtime/providers.js";
31
32
  import { conversationTimeZone, RUN_CONTEXT_CLOCK } from "../../runtime/run-context.service.js";
32
33
  import { StepLog } from "../../runtime/step-log.js";
33
34
  import { ManagedDeviceContextRecorder, } from "../../sandbox/managed-device-context.js";
@@ -76,6 +77,21 @@ let BuiltinTools = class BuiltinTools {
76
77
  // dormant: the builtins keep the legacy route until the paired activation turns the gate on;
77
78
  // then every builtin entering a device (the skill tool too) takes the managed route
78
79
  const managed = managedSandboxDeps(managedDeviceContext, activation);
80
+ // `Read` beyond the device (vision-read design §1): files by id, the vision read with its
81
+ // hooks (as the WebFetch extraction), the stored copies and the chat model's capabilities
82
+ const vision = { purposes, eventLog, stepLog, config, log, hooks: host?.hooks };
83
+ const read = {
84
+ files: {
85
+ get db() {
86
+ return db.db;
87
+ },
88
+ attachments,
89
+ storage,
90
+ },
91
+ reads: attachments,
92
+ vision,
93
+ chatModelSeesImages: (ctx) => chatModelSeesImages(db, providers, ctx),
94
+ };
79
95
  const sandboxDeps = {
80
96
  sandbox,
81
97
  devices,
@@ -91,6 +107,7 @@ let BuiltinTools = class BuiltinTools {
91
107
  config,
92
108
  log,
93
109
  ...managed,
110
+ read,
94
111
  };
95
112
  this.tools = [
96
113
  askUserTool({ config }),
@@ -123,7 +140,7 @@ let BuiltinTools = class BuiltinTools {
123
140
  points,
124
141
  config,
125
142
  cache: webPages,
126
- extract: (ctx, page, prompt) => extractAnswer({ purposes, eventLog, stepLog, config, log, hooks: host?.hooks }, ctx, page, prompt),
143
+ extract: (ctx, page, prompt) => extractAnswer(vision, ctx, page, prompt),
127
144
  }),
128
145
  // images from the org's `image` purpose model, delivered as artifacts (image generation
129
146
  // spec §5.3); written into the device too with `file_path`
@@ -137,7 +154,7 @@ let BuiltinTools = class BuiltinTools {
137
154
  config,
138
155
  log,
139
156
  hooks: host?.hooks,
140
- db: () => db.db,
157
+ db,
141
158
  attachments,
142
159
  sandbox: sandboxDeps,
143
160
  }),
@@ -215,3 +232,37 @@ export function managedSandboxDeps(recorder, activation) {
215
232
  return {};
216
233
  return { managedDeviceContext: recorder, managedDeviceContextRequired: true };
217
234
  }
235
+ /**
236
+ * Whether "the chat model" of a `Read` call can view images (vision-read design §1.2): the model
237
+ * of the latest `model_call` of the call's run (a fallback step's model when the step fell back),
238
+ * its capabilities from the model list cache. A run with no model call yet, or a model the org can
239
+ * no longer resolve, counts as one that cannot: the vision purpose reads the image then.
240
+ */
241
+ export async function chatModelSeesImages(db, providers, ctx) {
242
+ if (ctx.runId === undefined)
243
+ return false;
244
+ const row = await db.db
245
+ .selectFrom("conversation_events")
246
+ .select("payload")
247
+ .where("conversation_id", "=", ctx.conversationId)
248
+ .where("run_id", "=", ctx.runId)
249
+ .where("type", "=", "model_call")
250
+ .orderBy("seq", "desc")
251
+ .limit(1)
252
+ .executeTakeFirst();
253
+ if (!row)
254
+ return false;
255
+ const call = row.payload;
256
+ try {
257
+ const { info } = await providers.resolve(ctx.orgId, {
258
+ provider: call.provider,
259
+ model: call.model,
260
+ });
261
+ return info.capabilities.vision;
262
+ }
263
+ catch (e) {
264
+ if (e instanceof ApiError || e instanceof ProviderListError)
265
+ return false;
266
+ throw e;
267
+ }
268
+ }
@@ -0,0 +1,42 @@
1
+ import type { AttachmentsService } from "../../conversations/attachments.service.js";
2
+ import type { KernelDb } from "../../infra/database/kernel-db.js";
3
+ import type { StorageService } from "../../storage/storage.service.js";
4
+ /** An id of the conversation's files: an attachment or an artifact (generated or delivered). */
5
+ export interface ConversationFile {
6
+ kind: "attachment" | "artifact";
7
+ id: string;
8
+ name: string;
9
+ contentType: string;
10
+ size: number;
11
+ /**
12
+ * Reads the bytes, at most `maxBytes` of them when given (the head of a larger file: an
13
+ * attachment's stream is cancelled there, an artifact is read with a range). Call it, or
14
+ * {@link discard}, exactly once: an attachment holds its stream.
15
+ */
16
+ open(opts?: {
17
+ maxBytes?: number;
18
+ }): Promise<Uint8Array>;
19
+ /** Releases the file without reading it (a refusal before the bytes are needed). */
20
+ discard(): Promise<void>;
21
+ }
22
+ export interface ConversationFileDeps {
23
+ db: Pick<KernelDb, "selectFrom">;
24
+ attachments: Pick<AttachmentsService, "openForConversation">;
25
+ storage: Pick<StorageService, "kernel">;
26
+ }
27
+ /**
28
+ * A file of the conversation by id, always inside `orgId`: an attachment bound to the
29
+ * conversation or to its root (a `chat` attachment or a `read` copy: this lookup is the model's,
30
+ * vision-read design §1.1), else an `artifact_created` event of either. Anything else (another
31
+ * conversation or org, a missing object, an id that is not a UUID) is `null`. Storage errors are
32
+ * thrown as they are. `signal` aborts the storage reads.
33
+ */
34
+ export declare function findConversationFile(deps: ConversationFileDeps, q: {
35
+ orgId: string;
36
+ conversationId: string;
37
+ rootConversationId: string;
38
+ id: string;
39
+ /** The most bytes {@link ConversationFile.open} may be asked for (an attachment's range). */
40
+ maxBytes?: number;
41
+ signal?: AbortSignal;
42
+ }): Promise<ConversationFile | null>;