@parcha/agentrun-kernel 0.1.0-beta.38 → 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.
Files changed (67) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/NOTICE +2 -0
  3. package/dist/booking.d.ts +25 -6
  4. package/dist/booking.js +15 -4
  5. package/dist/host/index.d.ts +4 -3
  6. package/dist/host/index.js +3 -2
  7. package/dist/host/o200k.d.ts +11 -0
  8. package/dist/host/o200k.js +185 -0
  9. package/dist/host/overhead.d.ts +72 -12
  10. package/dist/host/overhead.js +220 -38
  11. package/dist/host/proxy.d.ts +85 -7
  12. package/dist/host/proxy.js +374 -87
  13. package/dist/index.d.ts +6 -6
  14. package/dist/index.js +4 -4
  15. package/dist/kernel/cap/admit.d.ts +5 -8
  16. package/dist/kernel/cap/admit.js +13 -19
  17. package/dist/kernel/cap/free.d.ts +43 -0
  18. package/dist/kernel/cap/free.js +71 -0
  19. package/dist/kernel/cap/index.d.ts +6 -5
  20. package/dist/kernel/cap/index.js +5 -4
  21. package/dist/kernel/cap/marks.d.ts +2 -3
  22. package/dist/kernel/cap/park.d.ts +3 -4
  23. package/dist/kernel/cap/park.js +4 -5
  24. package/dist/kernel/cap/port.d.ts +8 -13
  25. package/dist/kernel/cap/port.js +10 -18
  26. package/dist/kernel/cap/price.d.ts +10 -49
  27. package/dist/kernel/cap/price.js +15 -68
  28. package/dist/kernel/cap/recover.d.ts +1 -2
  29. package/dist/kernel/cap/recover.js +2 -4
  30. package/dist/kernel/cap/rule.d.ts +8 -16
  31. package/dist/kernel/cap/rule.js +35 -35
  32. package/dist/kernel/cap/run-cap.d.ts +21 -13
  33. package/dist/kernel/cap/run-cap.js +74 -36
  34. package/dist/kernel/cap/types.d.ts +11 -31
  35. package/dist/kernel/cap/words.d.ts +13 -8
  36. package/dist/kernel/cap/words.js +23 -14
  37. package/dist/kernel/cap/wrap-up.d.ts +4 -0
  38. package/dist/kernel/cap/wrap-up.js +5 -1
  39. package/dist/kernel/registry/computer-surface.generated.d.ts +1 -1
  40. package/dist/kernel/registry/computer-surface.generated.js +9 -25
  41. package/dist/kernel/registry/computer.d.ts +14 -7
  42. package/dist/kernel/registry/computer.js +52 -12
  43. package/dist/kernel/registry/gate.d.ts +2 -2
  44. package/dist/kernel/registry/gate.js +4 -7
  45. package/dist/kernel/registry/hands.d.ts +3 -4
  46. package/dist/kernel/registry/index.d.ts +1 -1
  47. package/dist/kernel/registry/index.js +1 -1
  48. package/dist/kernel/registry/registry.js +6 -9
  49. package/dist/process/recovery.d.ts +4 -1
  50. package/dist/process/recovery.js +15 -3
  51. package/dist/process/resume.d.ts +5 -2
  52. package/dist/process/resume.js +15 -3
  53. package/dist/process/tools.d.ts +26 -1
  54. package/dist/process/tools.js +47 -4
  55. package/dist/run-booking.d.ts +21 -2
  56. package/dist/run-booking.js +215 -18
  57. package/dist/runner.d.ts +82 -21
  58. package/dist/runner.js +176 -59
  59. package/dist/testing.d.ts +4 -2
  60. package/dist/testing.js +2 -2
  61. package/dist/tool-deferral.d.ts +3 -3
  62. package/dist/tool-deferral.js +4 -4
  63. package/dist/types.d.ts +70 -14
  64. package/dist/types.js +8 -0
  65. package/package.json +5 -3
  66. package/vendor/o200k/LICENSE +61 -0
  67. package/vendor/o200k/o200k_base.tiktoken +199998 -0
@@ -1,3 +1,26 @@
1
+ // The input a provider bills for a request beyond the bytes of its body, by the provider's API: one place for the figures
2
+ // and their sources, used by the model proxy's policies and by a host that bounds a request it sends itself. Written for
3
+ // AgentRun.
4
+ //
5
+ // A request's input can never be more tokens than its body's UTF-8 bytes (`inputTokensMaxOf`), except for what the
6
+ // provider adds or bills by another measure: a prompt it adds itself when tools are present, and images, which it bills by
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
+ // 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
+ // 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. 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";
1
24
  /**
2
25
  * The tool-use system prompt the Messages API adds to a request with tools, in tokens, by tool_choice. Documented per
3
26
  * model under "Pricing" in https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview, and taken at the largest
@@ -215,36 +238,37 @@ export function imageSizeOf(data) {
215
238
  }
216
239
  const plain = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
217
240
  const list = (value) => (Array.isArray(value) ? value : []);
218
- /** A Messages body's images, only where the API reads one as an image: a block of a message's content, or of a
219
- * tool_result's content, in every turn. Each is a base64 source's data, or a URL's (no bytes). An image-shaped object
220
- * anywhere else (a tool call's arguments) is text to the provider: its bytes stay counted as they are. */
221
- 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) {
222
244
  const out = [];
223
- const image = (block) => {
224
- if (plain(block) && block.type === "image")
225
- out.push(plain(block.source) && block.source.type === "base64" ? imageInputOf(block.source.data) : { bytes: 0 });
226
- };
227
245
  for (const message of list(messages)) {
228
246
  if (!plain(message))
229
247
  continue;
230
248
  for (const block of list(message.content)) {
231
- image(block);
232
- if (plain(block) && block.type === "tool_result")
249
+ if (!plain(block))
250
+ continue;
251
+ out.push(block);
252
+ if (block.type === "tool_result")
233
253
  for (const inner of list(block.content))
234
- image(inner);
254
+ if (plain(inner))
255
+ out.push(inner);
235
256
  }
236
257
  }
237
258
  return out;
238
259
  }
239
- /** A Responses body's images, only where the API reads one as an image: an `input_image` item, a part of an item's
240
- * content, or a part of a function call's output, in every turn. Each is a data URL's, or a URL's or file id's (no
241
- * bytes). An image-shaped object anywhere else is text to the provider: its bytes stay counted as they are. */
242
- export function responsesImagesIn(input) {
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) {
243
269
  const out = [];
244
- const image = (part) => {
245
- if (plain(part) && part.type === "input_image")
246
- out.push({ ...imageInputOf(part.image_url), ...(typeof part.detail === "string" ? { detail: part.detail } : {}) });
247
- };
270
+ const image = (part) => { if (plain(part) && part.type === "input_image")
271
+ out.push(part); };
248
272
  for (const item of list(input)) {
249
273
  if (!plain(item))
250
274
  continue;
@@ -257,6 +281,12 @@ export function responsesImagesIn(input) {
257
281
  }
258
282
  return out;
259
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
+ }
260
290
  /** The items of `type` in `value`, at any depth (a tool's output holds them). */
261
291
  function itemsIn(value, type) {
262
292
  if (Array.isArray(value))
@@ -320,27 +350,179 @@ export function responsesInputOverhead(body) {
320
350
  throw new Error("a file input's billed size has no stated bound");
321
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);
322
352
  }
323
- /** The fields of a Responses body the input-token count takes (the rest, such as stream, store, include and
324
- * max_output_tokens, change nothing it counts). */
325
- const RESPONSES_COUNTED_FIELDS = ["model", "input", "instructions", "tools", "tool_choice", "parallel_tool_calls", "reasoning", "text"];
326
- /** The request headers the count is sent with: the credential's and the account's, nothing else. */
327
- const OPENAI_COUNT_HEADERS = new Set(["authorization", "openai-organization", "openai-project"]);
328
353
  /**
329
- * OpenAI's own count of a Responses request's input tokens: POST /v1/responses/input_tokens on api.openai.com only, which
330
- * "accepts the same input format as the Responses API" and answers `{object: "response.input_tokens", input_tokens}`,
331
- * "the exact count the model will receive", formatting tokens, tools and images included ("Counting tokens",
332
- * https://developers.openai.com/api/docs/guides/token-counting; the SDK's `responses.inputTokens.count`,
333
- * https://github.com/openai/openai-node/blob/543ed94e6451d2eaf43f1a4a16a0fc8c8f42eade/src/resources/responses/input-tokens.ts).
334
- * The model proxy asks it before each answer request on that origin (never through a gateway), as Anthropic's count is
335
- * asked (ProviderPolicy.countInput): a count that fails, times out, or answers anything else leaves the byte bound.
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.
336
475
  */
337
- export const OPENAI_INPUT_COUNTER = Object.freeze({
338
- origin: "https://api.openai.com",
339
- path: "/v1/responses/input_tokens",
340
- body: (body) => Object.fromEntries(RESPONSES_COUNTED_FIELDS.filter((field) => body[field] !== undefined).map((field) => [field, body[field]])),
341
- headers: (sent) => Object.fromEntries(Object.entries(sent).filter(([name]) => OPENAI_COUNT_HEADERS.has(name.toLowerCase()))),
342
- tokensOf: (answer) => (plain(answer) && answer.object === "response.input_tokens" && typeof answer.input_tokens === "number" ? answer.input_tokens : undefined),
343
- });
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
+ }
344
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.
345
527
  * Anything else (an http URL, a file id): no bytes, no size. */
346
528
  export function imageInputOf(data) {
@@ -1,6 +1,7 @@
1
1
  import { type IncomingHttpHeaders } from "node:http";
2
2
  import { type NoteRequest } from "../types.js";
3
3
  import { type Ended } from "../booking.js";
4
+ import type { BilledRequest } from "./overhead.js";
4
5
  /** A route a policy admits: its method, its exact path, and the request headers forwarded with it. */
5
6
  export interface ProxyRoute {
6
7
  readonly method: string;
@@ -19,6 +20,12 @@ export interface ProxyUsage {
19
20
  output: number;
20
21
  cacheRead: number;
21
22
  cacheWrite?: number;
23
+ /** `plan`: the policy's route bills a person's subscription plan, not the tokens (ModelUsage.billing). */
24
+ billing?: "plan";
25
+ }
26
+ /** A provider credential its host can't give now, for good until a person acts (a sign-in signed out or expired): thrown
27
+ * by `ModelProxyOptions.credential`, its message (words for a person, never a credential) is the request's refusal. */
28
+ export declare class CredentialUnavailable extends Error {
22
29
  }
23
30
  /** What one provider-native web search costs, in USD, beside the tokens: $10 per 1,000 searches (Anthropic's "Web search tool"
24
31
  * and OpenAI's "Web search (all models)" list the same price). The one figure every fee reads: the proxy policies of the
@@ -91,14 +98,28 @@ export interface ProviderPolicy {
91
98
  /** The output tokens the body `apply` returned asks for at most (its own limit, as `apply` shaped it). Absent or
92
99
  * undefined: the body does not say. */
93
100
  outputAsked?(body: Record<string, unknown>): number | undefined;
94
- /** The provider's own count of a request's input tokens (Anthropic's free count_tokens, OpenAI's input_tokens), which the proxy asks before
101
+ /** The provider's own count of a request's input tokens (Anthropic's free count_tokens), which the proxy asks before
95
102
  * each of the session's answer requests (`countedInputOf`) when its upstream is exactly `origin`, the provider's own: never
96
103
  * through a gateway or any other base, so the key and the request go nowhere the request itself would not. Its count,
97
104
  * plus `margin`, is that request's input bound when it is below the byte bound. Absent: never counted. */
98
105
  countInput?: InputCounter;
106
+ /** A local count of the body `apply` returned, its margin included (`responsesLocalInputTokens`), for a request the
107
+ * provider did not count: no `countInput`, an upstream that is not its origin (a gateway), a side or host request, or a
108
+ * count that failed or said none. That request's input bound when it is below the byte bound. Undefined: the body has
109
+ * no local count (a model whose tokenizer the policy does not have), and keeps its byte bound. Absent: never counted. */
110
+ countInputLocally?(body: Record<string, unknown>): Promise<number | undefined> | number | undefined;
111
+ /** The most input tokens the body `apply` returned can be billed for, from `earlier`, the session's last request on
112
+ * the same model whose answer reported what its whole input billed (`messagesInputAfter`): for a request the provider
113
+ * did not count, its input bound when it is below its other bounds. Undefined: the earlier request says nothing of this
114
+ * one (they differ in more than what this one adds). Absent: never used. */
115
+ inputAfter?(earlier: BilledRequest, body: Record<string, unknown>): number | undefined;
99
116
  /** The least output the body may be limited to and still answer: 1,024 tokens for the answer, plus the least thinking
100
117
  * its provider takes when it thinks. Absent: 1,024. */
101
118
  outputLeast?(body: Record<string, unknown>): number;
119
+ /** The reasoning effort the body asks its model at, as its provider names it (Responses' `reasoning.effort`,
120
+ * Messages' `output_config.effort`): what `outputLeast` read it at, handed to the host beside it (ProxyRequest.effort).
121
+ * Absent, or undefined for a body: it names none. */
122
+ effortOf?(body: Record<string, unknown>): string | undefined;
102
123
  /** The reasoning tokens the body's request may bill that its response does not stream (a provider that streams only a
103
124
  * summary of its reasoning, or none): its effort's or its thinking's budget, else its output limit when it reasons at
104
125
  * an effort the body does not say. A stopped request counts them beside what streamed. Absent or 0: none. */
@@ -121,6 +142,13 @@ export interface ProviderPolicy {
121
142
  addNote?(body: Record<string, unknown>, text: string): Record<string, unknown>;
122
143
  /** The status a request the runner refused gets: one the client does not retry. Default 400. */
123
144
  readonly refusedStatus?: number;
145
+ /** An error answer of the provider's that no retry can mend (a subscription plan's limit reached), read from its status
146
+ * and its body: the words and code its client is answered with instead, at `refusedStatus`, so the client never asks
147
+ * again and its run ends in those words. Undefined: the provider's answer goes through as it came. */
148
+ finalError?(status: number, body: string): {
149
+ message: string;
150
+ code: string;
151
+ } | undefined;
124
152
  }
125
153
  export interface ModelUsageReport extends ProxyUsage {
126
154
  /** The provider's (or its gateway's) own figure when the response gave one (`reportedCostOf`); else the price table's,
@@ -189,22 +217,22 @@ export interface ProxyRequest {
189
217
  outputTokensAsked?: number;
190
218
  /** The least output it may be limited to and still answer (the policy's `outputLeast`). */
191
219
  outputTokensLeast?: number;
220
+ /** The reasoning effort its body names (the policy's `effortOf`), when it names one. */
221
+ effort?: string;
192
222
  /** What it may charge beside its tokens at most (the policy's `feeMaxUsd`), in USD: held with them. */
193
223
  feeUsd?: number;
194
224
  /** A side call, never its turn's own: on another model than the session's (a client's small-model call: a title, a
195
225
  * summary), or the host's own request beside the harness's (`host`). */
196
226
  side?: true;
197
227
  /** On the session's model but no answer of the turn (the policy's `answers` reads it so: a title, a summary, a child's
198
- * request). Still the turn's to book, but a conversation of its own: the cap never prices the session's next request
199
- * from it, nor it from the session's. */
228
+ * request). Still the turn's to book, but no answer the host keeps its wrap-up's reserve back for. */
200
229
  unanswered?: true;
201
- /** It carries the host's note (`ModelProxyHooks.note`), placed in its body: the host's to record once it is admitted. */
230
+ /** It carries the host's note (`ModelProxyHooks.note`), placed in its body: the host's to record once it is answered. */
202
231
  noted?: true;
203
232
  /** The label of the side key it came under (ModelProxy.sideKey): the host's own request, beside the harness's. */
204
233
  host?: string;
205
- /** Its `inputTokensMax` is its provider's count (ProviderPolicy.countInput), not its bytes: a host that compares one
206
- * request's bound with another's (how far a conversation grew) pairs a counted bound only with a counted one. */
207
- inputTokensCounted?: true;
234
+ /** Aborted when its client goes before it is admitted (ModelRequest.signal): a wait for room ends then. */
235
+ signal?: AbortSignal;
208
236
  }
209
237
  export interface ModelProxyHooks {
210
238
  /** Before a paid request leaves; a throw refuses it. What it returns (a ticket) is handed back to this request's
@@ -255,6 +283,9 @@ export interface ModelProxyOptions {
255
283
  free: boolean;
256
284
  status: number;
257
285
  }) => void;
286
+ /** Told the credential a request was sent with when the provider answered 401 to it, so a host whose credential
287
+ * renews (a sign-in's token) can renew it before the next request. Never logged. */
288
+ credentialRefused?: (credential: string) => void | Promise<void>;
258
289
  /** Headers the host adds to every request it forwards (a gateway's spend tags, LiteLLM's `x-litellm-tags`, say):
259
290
  * after the client's, so the client can neither set nor override them, and before the credential's. Checked when the
260
291
  * proxy starts (`hostHeaderProblems`). */
@@ -270,6 +301,9 @@ export interface ModelProxyOptions {
270
301
  onCut?: (stop: {
271
302
  outputTokens?: number;
272
303
  }) => void;
304
+ /** Told, with its words and code, once the provider's error answer is one no retry mends (`ProviderPolicy.finalError`:
305
+ * a plan's limit reached), as its client is answered those words: the harness ends the turn in them. */
306
+ onFinal?: (message: string, code: string) => void;
273
307
  }
274
308
  /** What is wrong with headers a host would add to forwarded requests: a name that is not a token or is reserved, a value
275
309
  * an HTTP header cannot carry (a line break or other control character, or a character beyond Latin-1, which the fetch
@@ -311,6 +345,44 @@ export declare function providerIdsOf(headers: Headers): Record<string, string>
311
345
  * the discount and margin it reports are both exactly 0. Only a positive number counts. A missing, malformed or zero
312
346
  * figure is unknown, never $0: a streamed answer's headers leave before it is priced, and LiteLLM writes 0.0 there. */
313
347
  export declare function reportedCostOf(headers: Headers): number | undefined;
348
+ /** The origin a route with its own fetch names (serve's translation to a model that speaks neither API): nothing is ever
349
+ * sent there, its fetch answers every request, and it writes an answer's cost in its usage only where the provider
350
+ * stated one (OpenRouter's). */
351
+ export declare const ROUTE_ORIGIN = "https://model-route.invalid";
352
+ /** Whether every answer from `origin` states what it cost in its usage's `cost`, in USD (`usageCostOf`): OpenRouter's
353
+ * (https://openrouter.ai/docs/use-cases/usage-accounting, on every API it serves), and a translation route's
354
+ * (`ROUTE_ORIGIN`), which passes OpenRouter's figure on. No other origin's usage is read for a cost. */
355
+ export declare function statesUsageCost(origin: string): boolean;
356
+ /** What an answer says it cost in its own usage, when it says so (OpenRouter's usage accounting, on every answer of every
357
+ * API it serves: https://openrouter.ai/docs/use-cases/usage-accounting): the answer's last `usage` object (a stream's
358
+ * terminal event, a whole body's own), its `cost` in USD. With the person's own provider key (`is_byok`), `cost` is
359
+ * OpenRouter's fee alone and the provider's charge is `cost_details.upstream_inference_cost` (or its prompt and
360
+ * completion parts): the two together, else unknown. Only a positive figure counts, as for a gateway's header
361
+ * (reportedCostOf): a missing, malformed or zero one is unknown, never $0. */
362
+ export declare function usageCostOf(text: string): number | undefined;
363
+ /** A provider's error inside a stream it began with a 200: its words, and whether it is a rate limit. */
364
+ export type StreamError = {
365
+ words: string;
366
+ rateLimit: boolean;
367
+ };
368
+ /** The provider's error its answer, a stream it began with a 200, ends in: a provider answers 200 once it takes the
369
+ * request, before the model's first token (OpenRouter; Anthropic's stream too), so an overload, a rate limit or a failure
370
+ * met after that comes inside the stream, and the status could not say so. Read from the stream's last event that carries
371
+ * data (`[DONE]` read past), and only that one, parsed: an event whose data is not JSON (words a translation wrote) is
372
+ * none. Undefined for any other answer, a whole JSON body's included. */
373
+ export declare function streamErrorOf(text: string): StreamError | undefined;
374
+ /** The words of a stream's last event that carries data when it is an error event (`event: error`) whose data is words,
375
+ * not JSON: how a translation sends a failure it cannot read for the provider's error event (serve's model-route
376
+ * messagesFetch: a provider's error status, a transport error), for its client to throw as the request's error. Never
377
+ * read for a refusal: what such a failure cost is unknown. Undefined for any other stream. */
378
+ export declare function wordsErrorOf(text: string): string | undefined;
379
+ /** Whether a stream shows the model began its output, read from each event's data by its fields, never its words: a
380
+ * Messages block it opened (`content_block_start`), a Responses output item (`response.output_item.added`) or a
381
+ * Responses delta with something in it, a Chat Completions chunk whose delta holds content, reasoning, a refusal or a
382
+ * tool call. Its content need not have streamed: a model's hidden reasoning (a Responses reasoning item) shows none, and
383
+ * neither does a block a translation held until its end. An empty delta (a first chunk's `content: ""`, the one a
384
+ * mid-stream error comes in) is no output. */
385
+ export declare function outputBeganIn(text: string): boolean;
314
386
  export declare class ProxyRefusal extends Error {
315
387
  readonly status: number;
316
388
  constructor(status: number, message: string);
@@ -348,6 +420,12 @@ export declare const COUNT_TIMEOUT_MS = 3000;
348
420
  * the counter's own, or the count fails, times out or says no count. Never throws: a count is only ever a tighter bound.
349
421
  */
350
422
  export declare function countedInputOf(policy: ProviderPolicy, origin: string, body: Record<string, unknown>, headers: Record<string, string>, fetch: typeof globalThis.fetch, say?: (message: string, detail?: Record<string, unknown>) => void, timeoutMs?: number, signal?: AbortSignal): Promise<number | undefined>;
423
+ /**
424
+ * The local count of a request with body `body`, its margin included (`policy.countInputLocally`); undefined (the request
425
+ * keeps its byte bound) when the policy has none, says none for this body, or its count throws or is not a whole number
426
+ * of tokens. Never throws.
427
+ */
428
+ export declare function localInputOf(policy: ProviderPolicy, body: Record<string, unknown>, say?: (message: string, detail?: Record<string, unknown>) => void): Promise<number | undefined>;
351
429
  /** Start a session's model proxy on the loopback interface, admitting `key`. */
352
430
  /**
353
431
  * The most input tokens a request with body `sent` (the body `apply` returned, as it is sent) can be billed for: its UTF-8