@capybara-hq/kernel 0.1.0-rc.51 → 0.1.0-rc.52
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bootstrap.json +3 -3
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/config/schema.d.ts +6 -0
- package/dist/config/schema.js +60 -0
- package/dist/conversations/attachments.service.d.ts +78 -10
- package/dist/conversations/attachments.service.js +233 -16
- package/dist/conversations/events.d.ts +9 -0
- package/dist/conversations/events.js +26 -3
- package/dist/db/kernel-schema.d.ts +5 -2
- package/dist/evals/reconstruct.d.ts +6 -1
- package/dist/evals/reconstruct.js +8 -4
- package/dist/evals/recorded-tools.d.ts +7 -0
- package/dist/evals/recorded-tools.js +2 -0
- package/dist/infra/config/kernel-config.service.js +8 -0
- package/dist/media/image-header.d.ts +10 -0
- package/dist/media/image-header.js +87 -0
- package/dist/models/images.d.ts +2 -0
- package/dist/models/images.js +6 -4
- package/dist/models/purposes.d.ts +17 -57
- package/dist/models/purposes.js +25 -4
- package/dist/runtime/context/build.d.ts +73 -28
- package/dist/runtime/context/build.js +179 -33
- package/dist/runtime/model-call.js +16 -10
- package/dist/runtime/usage-report.d.ts +3 -2
- package/dist/runtime/usage-report.js +3 -2
- package/dist/tools/builtins/builtin-tools.d.ts +8 -1
- package/dist/tools/builtins/builtin-tools.js +54 -3
- package/dist/tools/builtins/conversation-files.d.ts +42 -0
- package/dist/tools/builtins/conversation-files.js +105 -0
- package/dist/tools/builtins/image/generate.d.ts +3 -3
- package/dist/tools/builtins/image/generate.js +63 -71
- package/dist/tools/builtins/image/size.d.ts +12 -0
- package/dist/tools/builtins/image/size.js +36 -0
- package/dist/tools/builtins/sandbox/common.d.ts +7 -0
- package/dist/tools/builtins/sandbox/read.d.ts +53 -2
- package/dist/tools/builtins/sandbox/read.js +260 -51
- package/dist/tools/builtins/size-text.d.ts +2 -0
- package/dist/tools/builtins/size-text.js +8 -0
- package/dist/tools/builtins/vision/read-image.d.ts +59 -0
- package/dist/tools/builtins/vision/read-image.js +220 -0
- package/dist/tools/pipeline.js +22 -3
- package/dist/tools/registry.d.ts +9 -1
- package/package.json +3 -3
- package/src/migrations/0163_read_attachments.sql +10 -0
|
@@ -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
|
-
*
|
|
163
|
-
*
|
|
164
|
-
* `
|
|
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
|
-
/**
|
|
191
|
+
/** The attachment ids whose bytes are fetched (newest first). */
|
|
170
192
|
fetch: string[];
|
|
171
193
|
/**
|
|
172
|
-
*
|
|
173
|
-
*
|
|
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
|
-
/**
|
|
201
|
+
/** Omitted because the images exceed {@link MAX_IMAGES_PER_REQUEST}. */
|
|
179
202
|
tooManyImages: Set<string>;
|
|
180
|
-
/** PDF
|
|
203
|
+
/** A PDF over {@link MAX_PDF_PAGES} pages. */
|
|
181
204
|
tooManyPages: Set<string>;
|
|
182
|
-
/**
|
|
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
|
-
*
|
|
187
|
-
*
|
|
188
|
-
* - `
|
|
189
|
-
* - `
|
|
190
|
-
*
|
|
191
|
-
* -
|
|
192
|
-
*
|
|
193
|
-
*
|
|
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
|
-
*
|
|
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
|
-
/**
|
|
352
|
+
/** Estimated tokens of the request's media blocks (base64 images / documents), for `estimateTokens`. */
|
|
308
353
|
mediaTokens: number;
|
|
309
354
|
};
|
|
310
355
|
/**
|
|
@@ -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
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
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
|
|
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
|
-
*
|
|
105
|
-
*
|
|
106
|
-
* `
|
|
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
|
-
*
|
|
118
|
-
*
|
|
119
|
-
* - `
|
|
120
|
-
* - `
|
|
121
|
-
*
|
|
122
|
-
* -
|
|
123
|
-
*
|
|
124
|
-
*
|
|
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
|
-
*
|
|
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
|
}
|
|
@@ -456,7 +566,7 @@ export function buildModelRequest(input) {
|
|
|
456
566
|
const mediaCtx = {
|
|
457
567
|
info: input.mediaInfo,
|
|
458
568
|
bytes: input.media,
|
|
459
|
-
plan: planMedia(events, model, input.mediaInfo ?? new Map(), input.mediaBudgetBytes),
|
|
569
|
+
plan: planMedia(events, model, input.mediaInfo ?? new Map(), input.mediaBudgetBytes, input.readImagesPerRequest),
|
|
460
570
|
};
|
|
461
571
|
let mediaTokens = 0;
|
|
462
572
|
/** 本次请求里每个附件的处理结果(按首次出现,同一附件只记一次)。 */
|
|
@@ -623,9 +733,11 @@ export function buildModelRequest(input) {
|
|
|
623
733
|
}
|
|
624
734
|
};
|
|
625
735
|
/**
|
|
626
|
-
*
|
|
627
|
-
*
|
|
628
|
-
*
|
|
736
|
+
* Puts the deferred messages already absorbed (seq ≤ upTo) into messages in seq order, before the
|
|
737
|
+
* trailing run of system reminders (if any). So a reminder a step wrote before its model_call
|
|
738
|
+
* (the wrap-up one included) still follows the user message it goes with, and the wrap-up
|
|
739
|
+
* reminder stays at the end of the request. Only determinism is required: this request and a
|
|
740
|
+
* reconstruction from the log run the same rules and get the same result.
|
|
629
741
|
*/
|
|
630
742
|
const flush = (upTo) => {
|
|
631
743
|
const ready = deferred.filter((u) => u.seq <= upTo);
|
|
@@ -637,9 +749,33 @@ export function buildModelRequest(input) {
|
|
|
637
749
|
at--;
|
|
638
750
|
messages.splice(at, 0, ...ready.map(absorbableMessage));
|
|
639
751
|
};
|
|
640
|
-
/**
|
|
752
|
+
/**
|
|
753
|
+
* The blocks of the images from Read of one result (vision-read design §1.4), each after its
|
|
754
|
+
* label: the image (through {@link resolveMedia}, so the cap, the budget and `media_excluded`
|
|
755
|
+
* apply), the static text for a model without vision, or the window's "not included" text.
|
|
756
|
+
*/
|
|
757
|
+
const readBlocks = (media) => media.flatMap((m) => {
|
|
758
|
+
const id = m.attachmentId;
|
|
759
|
+
const note = (text, outcome) => {
|
|
760
|
+
if (!mediaOutcomes.has(id))
|
|
761
|
+
mediaOutcomes.set(id, { attachmentId: id, outcome });
|
|
762
|
+
return [{ type: "text", text }];
|
|
763
|
+
};
|
|
764
|
+
if (!model.capabilities.vision) {
|
|
765
|
+
return [
|
|
766
|
+
{ type: "text", text: readImageLabelText(id) },
|
|
767
|
+
...note(READ_IMAGE_NO_VISION_TEXT, "placeholder_unsupported"),
|
|
768
|
+
];
|
|
769
|
+
}
|
|
770
|
+
if (mediaCtx.plan.notIncluded.has(id)) {
|
|
771
|
+
return note(readImageNotIncludedText(id), "not_included");
|
|
772
|
+
}
|
|
773
|
+
return [{ type: "text", text: readImageLabelText(id) }, ...blocksOf([readBlock(m)])];
|
|
774
|
+
});
|
|
775
|
+
/** Whether the request renders an image from Read (the window is then recorded). */
|
|
776
|
+
let hasReadImages = false;
|
|
777
|
+
/** (runId, callId) → the call's tool_result (the first one per call). */
|
|
641
778
|
const results = new Map();
|
|
642
|
-
const resultKey = (runId, callId) => `${runId ?? ""}\u0000${callId}`;
|
|
643
779
|
for (const e of events) {
|
|
644
780
|
if (e.seq <= after || e.type !== "tool_result")
|
|
645
781
|
continue;
|
|
@@ -732,6 +868,8 @@ export function buildModelRequest(input) {
|
|
|
732
868
|
if (e.payload.content.length > 0) {
|
|
733
869
|
messages.push({ role: "assistant", content: blocksOf(e.payload.content) });
|
|
734
870
|
const blocks = [];
|
|
871
|
+
/** Images from Read (vision-read design §1.4): after all tool results, in call order. */
|
|
872
|
+
const images = [];
|
|
735
873
|
for (const b of e.payload.content) {
|
|
736
874
|
if (b.type !== "tool_call")
|
|
737
875
|
continue;
|
|
@@ -743,10 +881,14 @@ export function buildModelRequest(input) {
|
|
|
743
881
|
content: r.content,
|
|
744
882
|
isError: r.isError,
|
|
745
883
|
});
|
|
884
|
+
if (r.media !== undefined && r.media.length > 0) {
|
|
885
|
+
hasReadImages = true;
|
|
886
|
+
images.push(...readBlocks(r.media));
|
|
887
|
+
}
|
|
746
888
|
}
|
|
747
889
|
}
|
|
748
890
|
if (blocks.length > 0)
|
|
749
|
-
messages.push({ role: "user", content: blocks });
|
|
891
|
+
messages.push({ role: "user", content: [...blocks, ...images] });
|
|
750
892
|
}
|
|
751
893
|
break;
|
|
752
894
|
case "reminder":
|
|
@@ -921,6 +1063,10 @@ export function buildModelRequest(input) {
|
|
|
921
1063
|
...(mediaOutcomes.size > 0 &&
|
|
922
1064
|
input.mediaBudgetBytes !== undefined &&
|
|
923
1065
|
Number.isFinite(input.mediaBudgetBytes) && { mediaBudgetBytes: input.mediaBudgetBytes }),
|
|
1066
|
+
...(hasReadImages &&
|
|
1067
|
+
input.readImagesPerRequest !== undefined && {
|
|
1068
|
+
readImagesPerRequest: input.readImagesPerRequest,
|
|
1069
|
+
}),
|
|
924
1070
|
};
|
|
925
1071
|
return { request, meta, mediaTokens };
|
|
926
1072
|
}
|
|
@@ -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(
|
|
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:
|
|
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
|
|
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(
|
|
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
|
-
|
|
1266
|
-
|
|
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
|
|
58
|
-
* (`purpose: "
|
|
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
|
|
113
|
-
* (`purpose: "
|
|
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>;
|