@parcha/agentrun-kernel 0.1.0-beta.37 → 0.1.0-beta.39
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/CHANGELOG.md +136 -0
- package/NOTICE +2 -0
- package/dist/booking.d.ts +25 -6
- package/dist/booking.js +15 -4
- package/dist/host/index.d.ts +4 -5
- package/dist/host/index.js +3 -3
- package/dist/host/o200k.d.ts +11 -0
- package/dist/host/o200k.js +185 -0
- package/dist/host/overhead.d.ts +105 -3
- package/dist/host/overhead.js +276 -20
- package/dist/host/proxy.d.ts +97 -16
- package/dist/host/proxy.js +420 -108
- package/dist/index.d.ts +6 -5
- package/dist/index.js +4 -3
- package/dist/kernel/cap/admit.d.ts +5 -8
- package/dist/kernel/cap/admit.js +13 -19
- package/dist/kernel/cap/free.d.ts +43 -0
- package/dist/kernel/cap/free.js +71 -0
- package/dist/kernel/cap/index.d.ts +7 -6
- package/dist/kernel/cap/index.js +6 -5
- package/dist/kernel/cap/marks.d.ts +2 -3
- package/dist/kernel/cap/park.d.ts +3 -4
- package/dist/kernel/cap/park.js +4 -5
- package/dist/kernel/cap/port.d.ts +11 -5
- package/dist/kernel/cap/port.js +26 -24
- package/dist/kernel/cap/price.d.ts +10 -30
- package/dist/kernel/cap/price.js +15 -48
- package/dist/kernel/cap/recover.d.ts +1 -2
- package/dist/kernel/cap/recover.js +2 -4
- package/dist/kernel/cap/rule.d.ts +11 -17
- package/dist/kernel/cap/rule.js +37 -19
- package/dist/kernel/cap/run-cap.d.ts +25 -10
- package/dist/kernel/cap/run-cap.js +78 -35
- package/dist/kernel/cap/types.d.ts +11 -27
- package/dist/kernel/cap/words.d.ts +13 -8
- package/dist/kernel/cap/words.js +23 -14
- package/dist/kernel/cap/wrap-up.d.ts +4 -0
- package/dist/kernel/cap/wrap-up.js +5 -1
- package/dist/kernel/registry/computer-surface.generated.d.ts +1 -1
- package/dist/kernel/registry/computer-surface.generated.js +18 -27
- package/dist/kernel/registry/computer.d.ts +14 -7
- package/dist/kernel/registry/computer.js +64 -16
- package/dist/kernel/registry/gate.d.ts +2 -2
- package/dist/kernel/registry/gate.js +4 -7
- package/dist/kernel/registry/hands.d.ts +4 -5
- package/dist/kernel/registry/index.d.ts +1 -1
- package/dist/kernel/registry/index.js +1 -1
- package/dist/kernel/registry/registry.js +6 -9
- package/dist/kernel/types.d.ts +8 -1
- package/dist/process/recovery.d.ts +4 -1
- package/dist/process/recovery.js +15 -3
- package/dist/process/resume.d.ts +5 -2
- package/dist/process/resume.js +15 -3
- package/dist/process/tools.d.ts +28 -1
- package/dist/process/tools.js +102 -5
- package/dist/run-booking.d.ts +21 -2
- package/dist/run-booking.js +215 -18
- package/dist/runner.d.ts +82 -21
- package/dist/runner.js +271 -56
- package/dist/testing.d.ts +10 -4
- package/dist/testing.js +7 -5
- package/dist/tool-deferral.d.ts +12 -0
- package/dist/tool-deferral.js +17 -0
- package/dist/types.d.ts +133 -48
- package/dist/types.js +8 -0
- package/package.json +5 -3
- package/vendor/o200k/LICENSE +61 -0
- package/vendor/o200k/o200k_base.tiktoken +199998 -0
- package/dist/host/mcp-route.d.ts +0 -14
- package/dist/host/mcp-route.js +0 -125
package/dist/host/overhead.d.ts
CHANGED
|
@@ -115,10 +115,112 @@ export declare function imageSizeOf(data: string): {
|
|
|
115
115
|
* tool_result's content, in every turn. Each is a base64 source's data, or a URL's (no bytes). An image-shaped object
|
|
116
116
|
* anywhere else (a tool call's arguments) is text to the provider: its bytes stay counted as they are. */
|
|
117
117
|
export declare function messagesImagesIn(messages: unknown): ImageInput[];
|
|
118
|
-
/** A Responses body's images, only where the API reads one as an image
|
|
119
|
-
*
|
|
120
|
-
* bytes
|
|
118
|
+
/** A Responses body's images, only where the API reads one as an image (`responsesImageParts`), in every turn. Each is a
|
|
119
|
+
* data URL's, or a URL's or file id's (no bytes). An image-shaped object anywhere else is text to the provider: its
|
|
120
|
+
* bytes stay counted as they are. */
|
|
121
121
|
export declare function responsesImagesIn(input: unknown): ImageInput[];
|
|
122
|
+
/**
|
|
123
|
+
* The bytes JSON's escapes add to the text a Responses body carries for the model to read as it is, beyond that text's
|
|
124
|
+
* own UTF-8 bytes: in `instructions`, and in each `input` item, a message's text, a function call's arguments, a custom
|
|
125
|
+
* tool call's input, a tool's output (a string, or its text parts) and a reasoning summary's text.
|
|
126
|
+
*
|
|
127
|
+
* Why the input bound may count that text at its own bytes: the model reads it as the string itself, never as its JSON
|
|
128
|
+
* spelling in the body. OpenAI's counting recipe encodes each message's decoded value and adds a fixed few tokens a
|
|
129
|
+
* message (num_tokens_from_messages,
|
|
130
|
+
* https://github.com/openai/openai-cookbook/blob/db3144982aa26b87a9bdfb692b4fbedfdf8a14d5/examples/How_to_count_tokens_with_tiktoken.ipynb),
|
|
131
|
+
* and the harmony format OpenAI published for its models puts a message's content, a call's arguments and a tool's
|
|
132
|
+
* output between its special tokens as raw text (`<|message|>{"location":"San Francisco"}<|call|>`,
|
|
133
|
+
* https://github.com/openai/harmony/blob/e0ce87d1c3b9f59dec2e27de4770c769f03ebbd3/docs/format.md#receiving-tool-calls).
|
|
134
|
+
* A byte-level BPE token covers at least one byte of the text it encodes, so that text is at most its UTF-8 bytes in
|
|
135
|
+
* tokens; the escape characters JSON adds around it (`\"`, `\\`, `\n`, `\t`, `\u0000`) are bytes the body spends that no
|
|
136
|
+
* token of it is billed for. Every other byte is counted as sent, as before: the keys, ids and structure of each item
|
|
137
|
+
* still cover the framing the provider puts around it (a role, a recipient, a few special tokens: fewer than the bytes
|
|
138
|
+
* of the keys the item spends); the tool definitions (`tools`, and code mode's `additional_tools` item) are counted
|
|
139
|
+
* whole, since a template renders them into a prompt of its own that may quote their strings again (harmony's
|
|
140
|
+
* TypeScript namespace); and encrypted reasoning is base64, which JSON never escapes, so it keeps its own bytes.
|
|
141
|
+
*/
|
|
142
|
+
export declare function responsesEscapedBytes(body: Record<string, unknown>): number;
|
|
143
|
+
/**
|
|
144
|
+
* The input tokens the provider bills for a Responses `body` beyond its bytes (`providerInputOverhead`, with its
|
|
145
|
+
* sources), less the escapes in the text it carries (`responsesEscapedBytes`, with the argument for it). The Responses
|
|
146
|
+
* API documents no prompt of its own that it adds on these routes, and the framing it puts around each input item and
|
|
147
|
+
* tool definition is a few tokens each, fewer than the bytes of the JSON keys that item already spends in the body. An
|
|
148
|
+
* image is billed by its area, not its bytes: each counts at the most it can be billed as, in place of the bytes its
|
|
149
|
+
* data URL takes in the body. A file input (a PDF, billed by its pages) has no stated bound, so a body with one cannot
|
|
150
|
+
* be measured: this throws, and the request's input is unknown. Codex's and OpenCode's policies both use it.
|
|
151
|
+
*/
|
|
152
|
+
export declare function responsesInputOverhead(body: Record<string, unknown>): number;
|
|
153
|
+
/**
|
|
154
|
+
* The margin a local count adds, and why each part:
|
|
155
|
+
* - `share`, 10% of the counted tokens: the count is o200k_base's, the vocabulary tiktoken names for gpt-4o, gpt-4.1,
|
|
156
|
+
* gpt-4.5, gpt-5, the o-series and gpt-oss (MODEL_PREFIX_TO_ENCODING,
|
|
157
|
+
* https://github.com/openai/tiktoken/blob/79dc2c0533685b893616c78160b5d9e40876e724/tiktoken/model.py#L7-L37). A later
|
|
158
|
+
* model that bills by a revised vocabulary may split some text finer; a tenth more covers a revision of that order.
|
|
159
|
+
* - `perItem`, 16 tokens for each input item (and each part of a tool's result), each tool and the instructions: the framing the provider renders around
|
|
160
|
+
* each (harmony's `<|start|>assistant<|channel|>commentary to=functions.read <|constrain|>json<|message|>`, some 12
|
|
161
|
+
* tokens, https://github.com/openai/harmony/blob/e0ce87d1c3b9f59dec2e27de4770c769f03ebbd3/docs/format.md), beside
|
|
162
|
+
* the cookbook's 3 a message (num_tokens_from_messages,
|
|
163
|
+
* https://github.com/openai/openai-cookbook/blob/db3144982aa26b87a9bdfb692b4fbedfdf8a14d5/examples/How_to_count_tokens_with_tiktoken.ipynb).
|
|
164
|
+
* - `perRequest`, 256 tokens: the system message the provider writes itself (harmony's identity, dates, reasoning level
|
|
165
|
+
* and channels, some 60 tokens), the tools' namespace header and the reply's priming.
|
|
166
|
+
* The count is of the body as sent, its JSON keys, ids, quotes and escapes included, which the provider bills none of as
|
|
167
|
+
* text: that slack is on top of the margin. What the tokenizer cannot see is counted as the byte bound counts it: an
|
|
168
|
+
* encrypted reasoning or compaction item's `encrypted_content` at its bytes (its plaintext is billed, and a byte bounds a
|
|
169
|
+
* token), and each image at the most its provider bills it as (`imageTokens`), never at its base64.
|
|
170
|
+
*/
|
|
171
|
+
export declare const LOCAL_COUNT_MARGIN: Readonly<{
|
|
172
|
+
share: 0.1;
|
|
173
|
+
perItem: 16;
|
|
174
|
+
perRequest: 256;
|
|
175
|
+
}>;
|
|
176
|
+
/**
|
|
177
|
+
* The local count of a Responses `body`'s input tokens, margin included (`LOCAL_COUNT_MARGIN`): its JSON as sent, counted
|
|
178
|
+
* with o200k_base, with each `encrypted_content` at its bytes and each image at what it is billed as in place of their
|
|
179
|
+
* text. Undefined (the body keeps its byte bound) for a model whose tokenizer is not o200k_base (`o200kModel`), for a body
|
|
180
|
+
* with a file input (billed by its pages, with no stated bound), and for a body that is not an object.
|
|
181
|
+
*/
|
|
182
|
+
export declare function responsesLocalInputTokens(body: Record<string, unknown>): Promise<number | undefined>;
|
|
183
|
+
/**
|
|
184
|
+
* The local count of a Messages `body`'s input tokens, margin included (`LOCAL_COUNT_MARGIN`), by the same rule as a
|
|
185
|
+
* Responses body's (`responsesLocalInputTokens`), for a Messages request to a model whose tokenizer is o200k_base: one
|
|
186
|
+
* serve's translation sends on to a provider of another API (pi's session on `openai/gpt-6.1-sol` through OpenRouter,
|
|
187
|
+
* whose chat completions carry the same text). Its JSON as sent, counted with o200k_base, with a thinking block's
|
|
188
|
+
* `signature` and a redacted one's `data` at their bytes and each image at what it is billed as on the routed model, in
|
|
189
|
+
* place of their text. An item is each message's block and each block inside a tool_result (one for a message with
|
|
190
|
+
* none), each tool and each system block: the provider frames each turn, call, result and part of a result it renders.
|
|
191
|
+
* Undefined (the body keeps its byte bound) for a model whose tokenizer is not o200k_base (every Claude model: Anthropic
|
|
192
|
+
* counts those itself, or the byte bound holds), for a body with a document (billed by its pages, with no stated bound),
|
|
193
|
+
* and for a body that is not an object.
|
|
194
|
+
*/
|
|
195
|
+
export declare function messagesLocalInputTokens(body: Record<string, unknown>): Promise<number | undefined>;
|
|
196
|
+
/** An earlier request of a session and the input tokens its provider billed for it (input, cache reads and cache writes
|
|
197
|
+
* together), as its answer reported them. */
|
|
198
|
+
export interface BilledRequest {
|
|
199
|
+
readonly body: Record<string, unknown>;
|
|
200
|
+
readonly inputTokens: number;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* The most input tokens a Messages `body` can be billed for, from an earlier request of its session that the provider
|
|
204
|
+
* billed (`earlier`): that request's billed input, plus the bytes of the messages `body` carries after the ones the two
|
|
205
|
+
* share, each image among them at the most it is billed as in place of its data's bytes. Undefined (no figure: the body
|
|
206
|
+
* keeps its other bounds) when the two differ in anything but their messages and the fields that bill no input
|
|
207
|
+
* (`max_tokens`, `stream`, `metadata`), when the earlier request's figure is not a count, or when the messages it adds
|
|
208
|
+
* hold a document (billed by its pages, with no stated bound).
|
|
209
|
+
*
|
|
210
|
+
* Why it never undercounts: the provider renders a request as its system prompt and tools, then each message in turn,
|
|
211
|
+
* each between its own role markers, and bills each message's tokens whatever follows it. So the two requests' system
|
|
212
|
+
* prompt, tools (the tool-use prompt with them) and shared messages bill alike, and the earlier request was billed for all
|
|
213
|
+
* of them, and for any message of its own the later one dropped, which only adds to the figure. What the later request
|
|
214
|
+
* adds is bounded as the byte bound bounds any body (`inputTokensMaxOf`): a byte-level BPE token covers at least one
|
|
215
|
+
* byte, and the JSON keys each message spends cover its role markers. Two bodies are compared as the model reads them:
|
|
216
|
+
* a cache marker, where the API reads one (`readOf`), bills nothing, and a message's string content is the one text block the API reads it as (the Claude
|
|
217
|
+
* CLI sends its environment message as a block in one request and a string in the next). A thinking block the API leaves
|
|
218
|
+
* out of a later request's context (an earlier turn's) only makes the later request cheaper.
|
|
219
|
+
*
|
|
220
|
+
* It needs no tokenizer, so it bounds a Claude model through a gateway (OpenRouter), which counts nothing and whose
|
|
221
|
+
* tokenizer is not o200k_base: the CLI's second request, read at its bytes, is four times what it bills.
|
|
222
|
+
*/
|
|
223
|
+
export declare function messagesInputAfter(earlier: BilledRequest, body: Record<string, unknown>): number | undefined;
|
|
122
224
|
/** The image a body's `data` (base64, or a data URL) carries: the bytes it takes, and its size when its header says it.
|
|
123
225
|
* Anything else (an http URL, a file id): no bytes, no size. */
|
|
124
226
|
export declare function imageInputOf(data: unknown): ImageInput;
|
package/dist/host/overhead.js
CHANGED
|
@@ -7,7 +7,20 @@
|
|
|
7
7
|
// their area after it resizes them, not by their bytes. An image is counted at what the routed model's provider bills it
|
|
8
8
|
// as by its size (Anthropic's, OpenAI's or Google's rule; the most of the three for another provider), in place of the
|
|
9
9
|
// bytes its data takes in the body: a screenshot's base64 is a megabyte, and Claude bills it as some 1,200 tokens. Each
|
|
10
|
-
// figure is the largest the provider documents for any current model, so no model is undercounted.
|
|
10
|
+
// figure is the largest the provider documents for any current model, so no model is undercounted. On the Responses API
|
|
11
|
+
// the text a body carries for the model to read as it is counts at its own bytes, not its JSON-escaped ones
|
|
12
|
+
// (`responsesEscapedBytes`).
|
|
13
|
+
//
|
|
14
|
+
// The byte bound is a proof: a byte-level BPE token covers at least one byte, so a body is never more tokens than bytes.
|
|
15
|
+
// It is also four times what an English prompt bills, and on a capped run that is the difference between going on and
|
|
16
|
+
// parking (a $0.50 lead list whose request 7 holds $0.35 at its least on its bytes, $0.12 on its count). A Responses or
|
|
17
|
+
// Messages body to a model whose tokenizer is o200k_base (`o200kModel`) is counted locally, with o200k_base and a stated
|
|
18
|
+
// margin (`LOCAL_COUNT_MARGIN`, `responsesLocalInputTokens`, `messagesLocalInputTokens`), on every route: straight to
|
|
19
|
+
// OpenAI, through a gateway, or through serve's Messages translation. A body this cannot count with a margin it can state
|
|
20
|
+
// (a model on another tokenizer, a file input) has no local count, and keeps its byte bound; Anthropic counts its own
|
|
21
|
+
// models' (the claude-agent policy's countInput). A Messages request that carries an earlier one its provider billed
|
|
22
|
+
// (a session's next step) is bounded by that bill and the bytes it adds (`messagesInputAfter`), on any model and route.
|
|
23
|
+
import { o200kModel, o200kTokens } from "./o200k.js";
|
|
11
24
|
/**
|
|
12
25
|
* The tool-use system prompt the Messages API adds to a request with tools, in tokens, by tool_choice. Documented per
|
|
13
26
|
* model under "Pricing" in https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview, and taken at the largest
|
|
@@ -225,36 +238,37 @@ export function imageSizeOf(data) {
|
|
|
225
238
|
}
|
|
226
239
|
const plain = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
227
240
|
const list = (value) => (Array.isArray(value) ? value : []);
|
|
228
|
-
/** A Messages body's
|
|
229
|
-
* tool_result
|
|
230
|
-
|
|
231
|
-
export function messagesImagesIn(messages) {
|
|
241
|
+
/** A Messages body's content blocks where the API reads them, in order: each message's, and each block inside a
|
|
242
|
+
* tool_result among them. */
|
|
243
|
+
function messagesBlocks(messages) {
|
|
232
244
|
const out = [];
|
|
233
|
-
const image = (block) => {
|
|
234
|
-
if (plain(block) && block.type === "image")
|
|
235
|
-
out.push(plain(block.source) && block.source.type === "base64" ? imageInputOf(block.source.data) : { bytes: 0 });
|
|
236
|
-
};
|
|
237
245
|
for (const message of list(messages)) {
|
|
238
246
|
if (!plain(message))
|
|
239
247
|
continue;
|
|
240
248
|
for (const block of list(message.content)) {
|
|
241
|
-
|
|
242
|
-
|
|
249
|
+
if (!plain(block))
|
|
250
|
+
continue;
|
|
251
|
+
out.push(block);
|
|
252
|
+
if (block.type === "tool_result")
|
|
243
253
|
for (const inner of list(block.content))
|
|
244
|
-
|
|
254
|
+
if (plain(inner))
|
|
255
|
+
out.push(inner);
|
|
245
256
|
}
|
|
246
257
|
}
|
|
247
258
|
return out;
|
|
248
259
|
}
|
|
249
|
-
/** A
|
|
250
|
-
*
|
|
251
|
-
*
|
|
252
|
-
export function
|
|
260
|
+
/** A Messages body's images, only where the API reads one as an image: a block of a message's content, or of a
|
|
261
|
+
* tool_result's content, in every turn. Each is a base64 source's data, or a URL's (no bytes). An image-shaped object
|
|
262
|
+
* anywhere else (a tool call's arguments) is text to the provider: its bytes stay counted as they are. */
|
|
263
|
+
export function messagesImagesIn(messages) {
|
|
264
|
+
return messagesBlocks(messages).filter((block) => block.type === "image").map((block) => (plain(block.source) && block.source.type === "base64" ? imageInputOf(block.source.data) : { bytes: 0 }));
|
|
265
|
+
}
|
|
266
|
+
/** The parts of a Responses body the API reads as images, in order: an `input_image` item, a part of an item's content,
|
|
267
|
+
* a part of a function call's output. */
|
|
268
|
+
function responsesImageParts(input) {
|
|
253
269
|
const out = [];
|
|
254
|
-
const image = (part) => {
|
|
255
|
-
|
|
256
|
-
out.push({ ...imageInputOf(part.image_url), ...(typeof part.detail === "string" ? { detail: part.detail } : {}) });
|
|
257
|
-
};
|
|
270
|
+
const image = (part) => { if (plain(part) && part.type === "input_image")
|
|
271
|
+
out.push(part); };
|
|
258
272
|
for (const item of list(input)) {
|
|
259
273
|
if (!plain(item))
|
|
260
274
|
continue;
|
|
@@ -267,6 +281,248 @@ export function responsesImagesIn(input) {
|
|
|
267
281
|
}
|
|
268
282
|
return out;
|
|
269
283
|
}
|
|
284
|
+
/** A Responses body's images, only where the API reads one as an image (`responsesImageParts`), in every turn. Each is a
|
|
285
|
+
* data URL's, or a URL's or file id's (no bytes). An image-shaped object anywhere else is text to the provider: its
|
|
286
|
+
* bytes stay counted as they are. */
|
|
287
|
+
export function responsesImagesIn(input) {
|
|
288
|
+
return responsesImageParts(input).map((part) => ({ ...imageInputOf(part.image_url), ...(typeof part.detail === "string" ? { detail: part.detail } : {}) }));
|
|
289
|
+
}
|
|
290
|
+
/** The items of `type` in `value`, at any depth (a tool's output holds them). */
|
|
291
|
+
function itemsIn(value, type) {
|
|
292
|
+
if (Array.isArray(value))
|
|
293
|
+
return value.reduce((n, item) => n + itemsIn(item, type), 0);
|
|
294
|
+
if (!plain(value))
|
|
295
|
+
return 0;
|
|
296
|
+
return (value.type === type ? 1 : 0) + Object.values(value).reduce((n, item) => n + itemsIn(item, type), 0);
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* The bytes JSON's escapes add to the text a Responses body carries for the model to read as it is, beyond that text's
|
|
300
|
+
* own UTF-8 bytes: in `instructions`, and in each `input` item, a message's text, a function call's arguments, a custom
|
|
301
|
+
* tool call's input, a tool's output (a string, or its text parts) and a reasoning summary's text.
|
|
302
|
+
*
|
|
303
|
+
* Why the input bound may count that text at its own bytes: the model reads it as the string itself, never as its JSON
|
|
304
|
+
* spelling in the body. OpenAI's counting recipe encodes each message's decoded value and adds a fixed few tokens a
|
|
305
|
+
* message (num_tokens_from_messages,
|
|
306
|
+
* https://github.com/openai/openai-cookbook/blob/db3144982aa26b87a9bdfb692b4fbedfdf8a14d5/examples/How_to_count_tokens_with_tiktoken.ipynb),
|
|
307
|
+
* and the harmony format OpenAI published for its models puts a message's content, a call's arguments and a tool's
|
|
308
|
+
* output between its special tokens as raw text (`<|message|>{"location":"San Francisco"}<|call|>`,
|
|
309
|
+
* https://github.com/openai/harmony/blob/e0ce87d1c3b9f59dec2e27de4770c769f03ebbd3/docs/format.md#receiving-tool-calls).
|
|
310
|
+
* A byte-level BPE token covers at least one byte of the text it encodes, so that text is at most its UTF-8 bytes in
|
|
311
|
+
* tokens; the escape characters JSON adds around it (`\"`, `\\`, `\n`, `\t`, `\u0000`) are bytes the body spends that no
|
|
312
|
+
* token of it is billed for. Every other byte is counted as sent, as before: the keys, ids and structure of each item
|
|
313
|
+
* still cover the framing the provider puts around it (a role, a recipient, a few special tokens: fewer than the bytes
|
|
314
|
+
* of the keys the item spends); the tool definitions (`tools`, and code mode's `additional_tools` item) are counted
|
|
315
|
+
* whole, since a template renders them into a prompt of its own that may quote their strings again (harmony's
|
|
316
|
+
* TypeScript namespace); and encrypted reasoning is base64, which JSON never escapes, so it keeps its own bytes.
|
|
317
|
+
*/
|
|
318
|
+
export function responsesEscapedBytes(body) {
|
|
319
|
+
// What the proxy sends is JSON.stringify's spelling, so the escapes are measured by the same spelling.
|
|
320
|
+
const escaped = (text) => (typeof text === "string" ? Buffer.byteLength(JSON.stringify(text), "utf8") - 2 - Buffer.byteLength(text, "utf8") : 0);
|
|
321
|
+
const textOf = (content) => (typeof content === "string" ? escaped(content) : list(content).reduce((n, part) => n + (plain(part) && (part.type === "input_text" || part.type === "output_text" || part.type === "summary_text" || part.type === "reasoning_text") ? escaped(part.text) : 0), 0));
|
|
322
|
+
let sum = escaped(body.instructions);
|
|
323
|
+
for (const item of list(body.input)) {
|
|
324
|
+
if (!plain(item))
|
|
325
|
+
continue;
|
|
326
|
+
if (item.type === "message" || (item.type === undefined && typeof item.role === "string"))
|
|
327
|
+
sum += textOf(item.content);
|
|
328
|
+
else if (item.type === "function_call")
|
|
329
|
+
sum += escaped(item.arguments);
|
|
330
|
+
else if (item.type === "custom_tool_call")
|
|
331
|
+
sum += escaped(item.input);
|
|
332
|
+
else if (item.type === "function_call_output" || item.type === "custom_tool_call_output")
|
|
333
|
+
sum += textOf(item.output);
|
|
334
|
+
else if (item.type === "reasoning")
|
|
335
|
+
sum += textOf(item.summary) + textOf(item.content);
|
|
336
|
+
}
|
|
337
|
+
return sum;
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* The input tokens the provider bills for a Responses `body` beyond its bytes (`providerInputOverhead`, with its
|
|
341
|
+
* sources), less the escapes in the text it carries (`responsesEscapedBytes`, with the argument for it). The Responses
|
|
342
|
+
* API documents no prompt of its own that it adds on these routes, and the framing it puts around each input item and
|
|
343
|
+
* tool definition is a few tokens each, fewer than the bytes of the JSON keys that item already spends in the body. An
|
|
344
|
+
* image is billed by its area, not its bytes: each counts at the most it can be billed as, in place of the bytes its
|
|
345
|
+
* data URL takes in the body. A file input (a PDF, billed by its pages) has no stated bound, so a body with one cannot
|
|
346
|
+
* be measured: this throws, and the request's input is unknown. Codex's and OpenCode's policies both use it.
|
|
347
|
+
*/
|
|
348
|
+
export function responsesInputOverhead(body) {
|
|
349
|
+
if (itemsIn(body.input, "input_file") > 0)
|
|
350
|
+
throw new Error("a file input's billed size has no stated bound");
|
|
351
|
+
return providerInputOverhead("openai-responses", { tools: Array.isArray(body.tools) && body.tools.length > 0, images: responsesImagesIn(body.input), ...(typeof body.model === "string" ? { model: body.model } : {}) }) - responsesEscapedBytes(body);
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* The margin a local count adds, and why each part:
|
|
355
|
+
* - `share`, 10% of the counted tokens: the count is o200k_base's, the vocabulary tiktoken names for gpt-4o, gpt-4.1,
|
|
356
|
+
* gpt-4.5, gpt-5, the o-series and gpt-oss (MODEL_PREFIX_TO_ENCODING,
|
|
357
|
+
* https://github.com/openai/tiktoken/blob/79dc2c0533685b893616c78160b5d9e40876e724/tiktoken/model.py#L7-L37). A later
|
|
358
|
+
* model that bills by a revised vocabulary may split some text finer; a tenth more covers a revision of that order.
|
|
359
|
+
* - `perItem`, 16 tokens for each input item (and each part of a tool's result), each tool and the instructions: the framing the provider renders around
|
|
360
|
+
* each (harmony's `<|start|>assistant<|channel|>commentary to=functions.read <|constrain|>json<|message|>`, some 12
|
|
361
|
+
* tokens, https://github.com/openai/harmony/blob/e0ce87d1c3b9f59dec2e27de4770c769f03ebbd3/docs/format.md), beside
|
|
362
|
+
* the cookbook's 3 a message (num_tokens_from_messages,
|
|
363
|
+
* https://github.com/openai/openai-cookbook/blob/db3144982aa26b87a9bdfb692b4fbedfdf8a14d5/examples/How_to_count_tokens_with_tiktoken.ipynb).
|
|
364
|
+
* - `perRequest`, 256 tokens: the system message the provider writes itself (harmony's identity, dates, reasoning level
|
|
365
|
+
* and channels, some 60 tokens), the tools' namespace header and the reply's priming.
|
|
366
|
+
* The count is of the body as sent, its JSON keys, ids, quotes and escapes included, which the provider bills none of as
|
|
367
|
+
* text: that slack is on top of the margin. What the tokenizer cannot see is counted as the byte bound counts it: an
|
|
368
|
+
* encrypted reasoning or compaction item's `encrypted_content` at its bytes (its plaintext is billed, and a byte bounds a
|
|
369
|
+
* token), and each image at the most its provider bills it as (`imageTokens`), never at its base64.
|
|
370
|
+
*/
|
|
371
|
+
export const LOCAL_COUNT_MARGIN = Object.freeze({ share: 0.1, perItem: 16, perRequest: 256 });
|
|
372
|
+
/** `tokens` counted over a body of `items` items, with `opaque` tokens counted apart, as `LOCAL_COUNT_MARGIN` adds them. */
|
|
373
|
+
const withMargin = (tokens, items, opaque) => Math.ceil(tokens * (1 + LOCAL_COUNT_MARGIN.share)) + LOCAL_COUNT_MARGIN.perItem * items + LOCAL_COUNT_MARGIN.perRequest + opaque;
|
|
374
|
+
/**
|
|
375
|
+
* The local count of a Responses `body`'s input tokens, margin included (`LOCAL_COUNT_MARGIN`): its JSON as sent, counted
|
|
376
|
+
* with o200k_base, with each `encrypted_content` at its bytes and each image at what it is billed as in place of their
|
|
377
|
+
* text. Undefined (the body keeps its byte bound) for a model whose tokenizer is not o200k_base (`o200kModel`), for a body
|
|
378
|
+
* with a file input (billed by its pages, with no stated bound), and for a body that is not an object.
|
|
379
|
+
*/
|
|
380
|
+
export async function responsesLocalInputTokens(body) {
|
|
381
|
+
if (!plain(body) || !o200kModel(body.model))
|
|
382
|
+
return undefined;
|
|
383
|
+
const model = body.model;
|
|
384
|
+
if (itemsIn(body.input, "input_file") > 0)
|
|
385
|
+
return undefined;
|
|
386
|
+
const images = new Set(responsesImageParts(body.input));
|
|
387
|
+
// Every image the API reads counts once, at the most it is billed as, whatever names it: a data URL by its size, and an
|
|
388
|
+
// http URL, a file id or no reference at all at the most an image of unknown size is billed (`imageTokens`), as the
|
|
389
|
+
// byte bound counts it (`responsesImagesIn`). Never as the few tokens of its JSON.
|
|
390
|
+
let opaque = 0;
|
|
391
|
+
for (const part of images) {
|
|
392
|
+
const { image_url: url, detail } = part;
|
|
393
|
+
opaque += imageTokens(model, { ...imageInputOf(url), ...(typeof detail === "string" ? { detail } : {}) });
|
|
394
|
+
}
|
|
395
|
+
// The body as sent, with what the tokenizer cannot count left out of the text and counted on its own.
|
|
396
|
+
const text = JSON.stringify(body, function (key, value) {
|
|
397
|
+
if (key === "encrypted_content" && typeof value === "string") {
|
|
398
|
+
opaque += Buffer.byteLength(value, "utf8");
|
|
399
|
+
return "";
|
|
400
|
+
}
|
|
401
|
+
if (key === "image_url" && typeof value === "string" && typeof this === "object" && this !== null && images.has(this))
|
|
402
|
+
return "";
|
|
403
|
+
return value;
|
|
404
|
+
});
|
|
405
|
+
// Each input item, and each part of a function call's output (the provider frames each part it renders, as it does a
|
|
406
|
+
// Messages tool_result's blocks), each tool and the instructions.
|
|
407
|
+
const outputParts = list(body.input).reduce((sum, item) => sum + (plain(item) && item.type === "function_call_output" ? list(item.output).filter(plain).length : 0), 0);
|
|
408
|
+
const items = list(body.input).length + outputParts + list(body.tools).length + (typeof body.instructions === "string" && body.instructions !== "" ? 1 : 0);
|
|
409
|
+
return withMargin(await o200kTokens(text), items, opaque);
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* The local count of a Messages `body`'s input tokens, margin included (`LOCAL_COUNT_MARGIN`), by the same rule as a
|
|
413
|
+
* Responses body's (`responsesLocalInputTokens`), for a Messages request to a model whose tokenizer is o200k_base: one
|
|
414
|
+
* serve's translation sends on to a provider of another API (pi's session on `openai/gpt-6.1-sol` through OpenRouter,
|
|
415
|
+
* whose chat completions carry the same text). Its JSON as sent, counted with o200k_base, with a thinking block's
|
|
416
|
+
* `signature` and a redacted one's `data` at their bytes and each image at what it is billed as on the routed model, in
|
|
417
|
+
* place of their text. An item is each message's block and each block inside a tool_result (one for a message with
|
|
418
|
+
* none), each tool and each system block: the provider frames each turn, call, result and part of a result it renders.
|
|
419
|
+
* Undefined (the body keeps its byte bound) for a model whose tokenizer is not o200k_base (every Claude model: Anthropic
|
|
420
|
+
* counts those itself, or the byte bound holds), for a body with a document (billed by its pages, with no stated bound),
|
|
421
|
+
* and for a body that is not an object.
|
|
422
|
+
*/
|
|
423
|
+
export async function messagesLocalInputTokens(body) {
|
|
424
|
+
if (!plain(body) || !o200kModel(body.model))
|
|
425
|
+
return undefined;
|
|
426
|
+
const model = body.model;
|
|
427
|
+
const blocks = messagesBlocks(body.messages);
|
|
428
|
+
if (blocks.some((block) => block.type === "document"))
|
|
429
|
+
return undefined;
|
|
430
|
+
// Every image the API reads counts once, at the most it is billed as (`imageTokens`): a base64 source by the size its
|
|
431
|
+
// header says, a URL's at the most an image of unknown size is billed, as the byte bound counts it (`messagesImagesIn`).
|
|
432
|
+
let opaque = messagesImagesIn(body.messages).reduce((sum, image) => sum + imageTokens(model, image), 0);
|
|
433
|
+
const sources = new Set(blocks.filter((block) => block.type === "image" && plain(block.source)).map((block) => block.source));
|
|
434
|
+
// The body as sent, with what the tokenizer cannot count left out of the text and counted on its own.
|
|
435
|
+
const text = JSON.stringify(body, function (key, value) {
|
|
436
|
+
const holder = this;
|
|
437
|
+
if (typeof value === "string" && ((key === "signature" && holder?.type === "thinking") || (key === "data" && holder?.type === "redacted_thinking"))) {
|
|
438
|
+
opaque += Buffer.byteLength(value, "utf8");
|
|
439
|
+
return "";
|
|
440
|
+
}
|
|
441
|
+
if (key === "data" && typeof value === "string" && typeof this === "object" && this !== null && sources.has(this))
|
|
442
|
+
return "";
|
|
443
|
+
return value;
|
|
444
|
+
});
|
|
445
|
+
const messages = list(body.messages).filter(plain);
|
|
446
|
+
const system = typeof body.system === "string" ? (body.system === "" ? 0 : 1) : list(body.system).length;
|
|
447
|
+
const items = messages.reduce((sum, message) => sum + Math.max(1, messagesBlocks([message]).length), 0) + list(body.tools).length + system;
|
|
448
|
+
return withMargin(await o200kTokens(text), items, opaque);
|
|
449
|
+
}
|
|
450
|
+
/** The fields of a Messages body that bill no input: how much it may answer, whether it streams, and who asks. */
|
|
451
|
+
const UNBILLED_FIELDS = new Set(["messages", "max_tokens", "stream", "metadata"]);
|
|
452
|
+
/** A tool or a content block without its own cache marker, its `cache_control` key: a marker bills no token. Only that
|
|
453
|
+
* key: one deeper (a schema's property, a tool call's input) is text the model reads. */
|
|
454
|
+
const unmarked = (block) => {
|
|
455
|
+
if (!plain(block))
|
|
456
|
+
return block;
|
|
457
|
+
const { cache_control: _marker, ...rest } = block;
|
|
458
|
+
return rest;
|
|
459
|
+
};
|
|
460
|
+
/** Content blocks without the cache markers the API reads in them: on each block, and on each block of a tool result's
|
|
461
|
+
* content. */
|
|
462
|
+
const unmarkedBlocks = (blocks) => Array.isArray(blocks)
|
|
463
|
+
? blocks.map((block) => {
|
|
464
|
+
const bare = unmarked(block);
|
|
465
|
+
return plain(bare) && bare.type === "tool_result" && Array.isArray(bare.content) ? { ...bare, content: bare.content.map(unmarked) } : bare;
|
|
466
|
+
})
|
|
467
|
+
: blocks;
|
|
468
|
+
/** A content (a message's, or the system prompt) as the API reads it: a string is one text block. */
|
|
469
|
+
const asBlocks = (content) => (typeof content === "string" ? [{ type: "text", text: content }] : content);
|
|
470
|
+
/**
|
|
471
|
+
* A body's field (`name`), or one of its messages (`message`), as the model reads it: without the cache markers, where
|
|
472
|
+
* the Messages API reads one (Anthropic's prompt caching guide, "What can be cached": a tool definition, a block of the
|
|
473
|
+
* system prompt, a block of a message's content, and so a tool use or tool result, and the API's `ToolResultBlockParam`,
|
|
474
|
+
* whose content blocks each take one). A `cache_control` anywhere else is not a marker and bills as text.
|
|
475
|
+
*/
|
|
476
|
+
const readOf = (name, value) => {
|
|
477
|
+
if (name === undefined)
|
|
478
|
+
return JSON.stringify(plain(value) ? { ...value, content: unmarkedBlocks(asBlocks(value.content)) } : value);
|
|
479
|
+
if (name === "system")
|
|
480
|
+
return JSON.stringify(unmarkedBlocks(asBlocks(value)));
|
|
481
|
+
if (name === "tools")
|
|
482
|
+
return JSON.stringify(Array.isArray(value) ? value.map(unmarked) : value);
|
|
483
|
+
return JSON.stringify(value);
|
|
484
|
+
};
|
|
485
|
+
/**
|
|
486
|
+
* The most input tokens a Messages `body` can be billed for, from an earlier request of its session that the provider
|
|
487
|
+
* billed (`earlier`): that request's billed input, plus the bytes of the messages `body` carries after the ones the two
|
|
488
|
+
* share, each image among them at the most it is billed as in place of its data's bytes. Undefined (no figure: the body
|
|
489
|
+
* keeps its other bounds) when the two differ in anything but their messages and the fields that bill no input
|
|
490
|
+
* (`max_tokens`, `stream`, `metadata`), when the earlier request's figure is not a count, or when the messages it adds
|
|
491
|
+
* hold a document (billed by its pages, with no stated bound).
|
|
492
|
+
*
|
|
493
|
+
* Why it never undercounts: the provider renders a request as its system prompt and tools, then each message in turn,
|
|
494
|
+
* each between its own role markers, and bills each message's tokens whatever follows it. So the two requests' system
|
|
495
|
+
* prompt, tools (the tool-use prompt with them) and shared messages bill alike, and the earlier request was billed for all
|
|
496
|
+
* of them, and for any message of its own the later one dropped, which only adds to the figure. What the later request
|
|
497
|
+
* adds is bounded as the byte bound bounds any body (`inputTokensMaxOf`): a byte-level BPE token covers at least one
|
|
498
|
+
* byte, and the JSON keys each message spends cover its role markers. Two bodies are compared as the model reads them:
|
|
499
|
+
* a cache marker, where the API reads one (`readOf`), bills nothing, and a message's string content is the one text block the API reads it as (the Claude
|
|
500
|
+
* CLI sends its environment message as a block in one request and a string in the next). A thinking block the API leaves
|
|
501
|
+
* out of a later request's context (an earlier turn's) only makes the later request cheaper.
|
|
502
|
+
*
|
|
503
|
+
* It needs no tokenizer, so it bounds a Claude model through a gateway (OpenRouter), which counts nothing and whose
|
|
504
|
+
* tokenizer is not o200k_base: the CLI's second request, read at its bytes, is four times what it bills.
|
|
505
|
+
*/
|
|
506
|
+
export function messagesInputAfter(earlier, body) {
|
|
507
|
+
if (!plain(earlier?.body) || !plain(body) || !Number.isSafeInteger(earlier.inputTokens) || earlier.inputTokens <= 0)
|
|
508
|
+
return undefined;
|
|
509
|
+
const fields = new Set([...Object.keys(earlier.body), ...Object.keys(body)].filter((name) => !UNBILLED_FIELDS.has(name)));
|
|
510
|
+
for (const name of fields)
|
|
511
|
+
if (readOf(name, earlier.body[name]) !== readOf(name, body[name]))
|
|
512
|
+
return undefined;
|
|
513
|
+
const before = list(earlier.body.messages);
|
|
514
|
+
const after = list(body.messages);
|
|
515
|
+
let shared = 0;
|
|
516
|
+
while (shared < before.length && shared < after.length && readOf(undefined, before[shared]) === readOf(undefined, after[shared]))
|
|
517
|
+
shared += 1;
|
|
518
|
+
const added = after.slice(shared);
|
|
519
|
+
if (messagesBlocks(added).some((block) => block.type === "document"))
|
|
520
|
+
return undefined;
|
|
521
|
+
const model = typeof body.model === "string" ? body.model : undefined;
|
|
522
|
+
// Each image's data is part of the added bytes, so the sum is never below the earlier figure.
|
|
523
|
+
const images = messagesImagesIn(added).reduce((sum, image) => sum + imageTokens(model, image) - image.bytes, 0);
|
|
524
|
+
return earlier.inputTokens + Buffer.byteLength(JSON.stringify(added), "utf8") + images;
|
|
525
|
+
}
|
|
270
526
|
/** The image a body's `data` (base64, or a data URL) carries: the bytes it takes, and its size when its header says it.
|
|
271
527
|
* Anything else (an http URL, a file id): no bytes, no size. */
|
|
272
528
|
export function imageInputOf(data) {
|