@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.
Files changed (70) hide show
  1. package/CHANGELOG.md +136 -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 -5
  6. package/dist/host/index.js +3 -3
  7. package/dist/host/o200k.d.ts +11 -0
  8. package/dist/host/o200k.js +185 -0
  9. package/dist/host/overhead.d.ts +105 -3
  10. package/dist/host/overhead.js +276 -20
  11. package/dist/host/proxy.d.ts +97 -16
  12. package/dist/host/proxy.js +420 -108
  13. package/dist/index.d.ts +6 -5
  14. package/dist/index.js +4 -3
  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 +7 -6
  20. package/dist/kernel/cap/index.js +6 -5
  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 +11 -5
  25. package/dist/kernel/cap/port.js +26 -24
  26. package/dist/kernel/cap/price.d.ts +10 -30
  27. package/dist/kernel/cap/price.js +15 -48
  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 +11 -17
  31. package/dist/kernel/cap/rule.js +37 -19
  32. package/dist/kernel/cap/run-cap.d.ts +25 -10
  33. package/dist/kernel/cap/run-cap.js +78 -35
  34. package/dist/kernel/cap/types.d.ts +11 -27
  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 +18 -27
  41. package/dist/kernel/registry/computer.d.ts +14 -7
  42. package/dist/kernel/registry/computer.js +64 -16
  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 +4 -5
  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/kernel/types.d.ts +8 -1
  50. package/dist/process/recovery.d.ts +4 -1
  51. package/dist/process/recovery.js +15 -3
  52. package/dist/process/resume.d.ts +5 -2
  53. package/dist/process/resume.js +15 -3
  54. package/dist/process/tools.d.ts +28 -1
  55. package/dist/process/tools.js +102 -5
  56. package/dist/run-booking.d.ts +21 -2
  57. package/dist/run-booking.js +215 -18
  58. package/dist/runner.d.ts +82 -21
  59. package/dist/runner.js +271 -56
  60. package/dist/testing.d.ts +10 -4
  61. package/dist/testing.js +7 -5
  62. package/dist/tool-deferral.d.ts +12 -0
  63. package/dist/tool-deferral.js +17 -0
  64. package/dist/types.d.ts +133 -48
  65. package/dist/types.js +8 -0
  66. package/package.json +5 -3
  67. package/vendor/o200k/LICENSE +61 -0
  68. package/vendor/o200k/o200k_base.tiktoken +199998 -0
  69. package/dist/host/mcp-route.d.ts +0 -14
  70. package/dist/host/mcp-route.js +0 -125
@@ -16,7 +16,6 @@
16
16
  // Model spend is accounted only there, by the runner: the proxy keeps no ledger of its own.
17
17
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
18
18
  import { createServer } from "node:http";
19
- import { mcpRoute } from "./mcp-route.js";
20
19
  import { CONTENT_FILTERED } from "../types.js";
21
20
  import { isConnectCode, isGatewayTimeout, rejectionCode } from "../booking.js";
22
21
  import { SPEND_CAP_REACHED } from "../kernel/cap/words.js";
@@ -27,6 +26,14 @@ const capRefusal = (error) => {
27
26
  const fields = error;
28
27
  return fields?.code === SPEND_CAP_REACHED || fields?.refusal === SPEND_CAP_REACHED;
29
28
  };
29
+ /** A provider credential its host can't give now, for good until a person acts (a sign-in signed out or expired): thrown
30
+ * by `ModelProxyOptions.credential`, its message (words for a person, never a credential) is the request's refusal. */
31
+ export class CredentialUnavailable extends Error {
32
+ }
33
+ /** What one provider-native web search costs, in USD, beside the tokens: $10 per 1,000 searches (Anthropic's "Web search tool"
34
+ * and OpenAI's "Web search (all models)" list the same price). The one figure every fee reads: the proxy policies of the
35
+ * Claude and Codex harnesses and the runner's hosted search. */
36
+ export const NATIVE_SEARCH_USD = 0.01;
30
37
  /** The longest a response's text may run with no event boundary before the reasoning count lets it go (a body that is
31
38
  * not a stream of events, read whole as one). */
32
39
  const EVENT_MAX_CHARS = 1 << 22;
@@ -395,14 +402,44 @@ export function hostHeaderProblems(headers) {
395
402
  }
396
403
  return problems;
397
404
  }
398
- /** A server's endpoint, `/mcp/<server>`, with no query. */
399
- const MCP_PATH = /^\/mcp\/([a-z][a-z0-9-]{0,31})$/;
400
- /** Where an MCP client looks for OAuth after a 401: never served here, so it never starts a sign-in against the proxy. */
401
- const OAUTH_PATH = /^\/(?:\.well-known\/|register(?:$|[/?]))/;
402
405
  const UNSAFE_PATH = /[^A-Za-z0-9/_.\-?=&]|\.\.|\/\/|^[^/]|\?.*\?/;
403
406
  const MAX_BODY = 32 * 1024 * 1024;
404
407
  /** How much of a response's start and end the proxy keeps to read its usage from. */
405
408
  const USAGE_WINDOW = 64 * 1024;
409
+ /** The last `"<key>": {...}` object in `text`, parsed: how a policy reads a field of an answer's terminal event when the
410
+ * event's line was longer than USAGE_WINDOW, so the proxy kept only its end. JSON may put whitespace on either side of
411
+ * the colon (a Python gateway's `json.dumps` writes `"usage": {`), and the client parses the event whatever its spacing,
412
+ * so this reads it too: a usage the harness counted is never booked at an unknown cost for its spacing. A key's quoted
413
+ * name inside a JSON string is escaped (`\"usage\"`), so it never reads as one. Undefined when there is none, or the
414
+ * last one does not close in `text` or does not parse. */
415
+ export function lastObjectOf(text, key) {
416
+ const marks = new RegExp(`"${key.replace(/[^A-Za-z0-9_]/g, "")}"\\s*:\\s*\\{`, "g");
417
+ let open = -1;
418
+ for (let found = marks.exec(text); found; found = marks.exec(text))
419
+ open = found.index + found[0].length - 1;
420
+ if (open < 0)
421
+ return undefined;
422
+ let depth = 0;
423
+ for (let i = open; i < text.length; i++) {
424
+ const c = text[i];
425
+ if (c === "\"") {
426
+ for (i++; i < text.length && text[i] !== "\""; i++)
427
+ if (text[i] === "\\")
428
+ i++;
429
+ }
430
+ else if (c === "{")
431
+ depth++;
432
+ else if (c === "}" && --depth === 0) {
433
+ try {
434
+ return JSON.parse(text.slice(open, i + 1));
435
+ }
436
+ catch {
437
+ return undefined;
438
+ }
439
+ }
440
+ }
441
+ return undefined;
442
+ }
406
443
  /** How long an answer the provider stopped on its content filter is still read after its client left, or the proxy began
407
444
  * to close, so the request is booked at the usage its end reports; past it, it is cut off as any other. */
408
445
  const FILTERED_DRAIN_MS = 5_000;
@@ -453,6 +490,134 @@ export function reportedCostOf(headers) {
453
490
  return undefined;
454
491
  return costOf(headers.get(`${COST_HEADER}-original`));
455
492
  }
493
+ /** A cost a provider states in its answer's usage: a number, finite, above 0 and below MAX_REQUEST_USD. */
494
+ const usageFigure = (value) => (typeof value === "number" && Number.isFinite(value) && value > 0 && value <= MAX_REQUEST_USD ? value : undefined);
495
+ /** The origin a route with its own fetch names (serve's translation to a model that speaks neither API): nothing is ever
496
+ * sent there, its fetch answers every request, and it writes an answer's cost in its usage only where the provider
497
+ * stated one (OpenRouter's). */
498
+ export const ROUTE_ORIGIN = "https://model-route.invalid";
499
+ /** Whether every answer from `origin` states what it cost in its usage's `cost`, in USD (`usageCostOf`): OpenRouter's
500
+ * (https://openrouter.ai/docs/use-cases/usage-accounting, on every API it serves), and a translation route's
501
+ * (`ROUTE_ORIGIN`), which passes OpenRouter's figure on. No other origin's usage is read for a cost. */
502
+ export function statesUsageCost(origin) {
503
+ if (!URL.canParse(origin))
504
+ return false;
505
+ const url = new URL(origin);
506
+ return url.hostname === "openrouter.ai" || url.origin === ROUTE_ORIGIN;
507
+ }
508
+ /** What an answer says it cost in its own usage, when it says so (OpenRouter's usage accounting, on every answer of every
509
+ * API it serves: https://openrouter.ai/docs/use-cases/usage-accounting): the answer's last `usage` object (a stream's
510
+ * terminal event, a whole body's own), its `cost` in USD. With the person's own provider key (`is_byok`), `cost` is
511
+ * OpenRouter's fee alone and the provider's charge is `cost_details.upstream_inference_cost` (or its prompt and
512
+ * completion parts): the two together, else unknown. Only a positive figure counts, as for a gateway's header
513
+ * (reportedCostOf): a missing, malformed or zero one is unknown, never $0. */
514
+ export function usageCostOf(text) {
515
+ const usage = lastObjectOf(text, "usage");
516
+ if (typeof usage !== "object" || usage === null)
517
+ return undefined;
518
+ const cost = usageFigure(usage.cost);
519
+ if (cost === undefined || usage.is_byok !== true)
520
+ return cost;
521
+ const details = usage.cost_details;
522
+ if (typeof details !== "object" || details === null)
523
+ return undefined;
524
+ const part = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
525
+ const prompt = part(details.upstream_inference_prompt_cost);
526
+ const completion = part(details.upstream_inference_completions_cost);
527
+ const upstream = part(details.upstream_inference_cost) ?? (prompt !== undefined && completion !== undefined ? prompt + completion : undefined);
528
+ return upstream === undefined ? undefined : usageFigure(cost + upstream);
529
+ }
530
+ /** A parsed event's error, read from its fields alone, never its words, as each API writes one inside a stream and as
531
+ * OpenRouter writes one on each API it serves (https://openrouter.ai/docs/api-reference/errors, "Mid-stream errors" and
532
+ * "Skin-specific error formats"): Messages' `error` event (`error.type` `overloaded_error`, `api_error`,
533
+ * `rate_limit_error`, ...), Chat Completions' chunk with an `error` object (`code` 429 for a rate limit, its
534
+ * `metadata.error_type` "rate_limit_exceeded"), Responses' `response.failed` (its `response.error`) or `error` event (its
535
+ * `code`). A rate limit is told by its fields too. Undefined for an event that is no error. */
536
+ function streamErrorIn(event) {
537
+ const response = event.response;
538
+ const error = (typeof response === "object" && response !== null && typeof response.error === "object" && response.error !== null ? response.error : typeof event.error === "object" && event.error !== null ? event.error : event.type === "error" ? event : undefined);
539
+ if (!error)
540
+ return undefined;
541
+ const metadata = error.metadata;
542
+ const rateLimit = error.code === 429 || error.code === "rate_limit_exceeded" || error.type === "rate_limit_error" || error.error_type === "rate_limit_exceeded"
543
+ || metadata?.error_type === "rate_limit_exceeded" || event.error_type === "rate_limit_exceeded" || response?.error_type === "rate_limit_exceeded";
544
+ const words = typeof error.message === "string" && error.message ? error.message : rateLimit ? "rate limited" : "the provider ended its answer in an error";
545
+ return { words, rateLimit };
546
+ }
547
+ /** The provider's error its answer, a stream it began with a 200, ends in: a provider answers 200 once it takes the
548
+ * request, before the model's first token (OpenRouter; Anthropic's stream too), so an overload, a rate limit or a failure
549
+ * met after that comes inside the stream, and the status could not say so. Read from the stream's last event that carries
550
+ * data (`[DONE]` read past), and only that one, parsed: an event whose data is not JSON (words a translation wrote) is
551
+ * none. Undefined for any other answer, a whole JSON body's included. */
552
+ export function streamErrorOf(text) {
553
+ const events = text.replace(/\r\n|\r/g, "\n").split("\n\n");
554
+ for (let at = events.length - 1; at >= 0; at--) {
555
+ const data = events[at].split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).replace(/^ /, "")).join("\n");
556
+ if (!data.trim() || data.trim() === "[DONE]")
557
+ continue;
558
+ try {
559
+ const event = JSON.parse(data);
560
+ return typeof event === "object" && event !== null && !Array.isArray(event) ? streamErrorIn(event) : undefined;
561
+ }
562
+ catch {
563
+ return undefined;
564
+ }
565
+ }
566
+ return undefined;
567
+ }
568
+ /** The words of a stream's last event that carries data when it is an error event (`event: error`) whose data is words,
569
+ * not JSON: how a translation sends a failure it cannot read for the provider's error event (serve's model-route
570
+ * messagesFetch: a provider's error status, a transport error), for its client to throw as the request's error. Never
571
+ * read for a refusal: what such a failure cost is unknown. Undefined for any other stream. */
572
+ export function wordsErrorOf(text) {
573
+ const events = text.replace(/\r\n|\r/g, "\n").split("\n\n");
574
+ for (let at = events.length - 1; at >= 0; at--) {
575
+ const lines = events[at].split("\n");
576
+ const data = lines.filter((line) => line.startsWith("data:")).map((line) => line.slice(5).replace(/^ /, "")).join("\n").trim();
577
+ if (!data || data === "[DONE]")
578
+ continue;
579
+ if (!lines.some((line) => /^event:\s*error\s*$/.test(line)))
580
+ return undefined;
581
+ try {
582
+ JSON.parse(data);
583
+ return undefined;
584
+ }
585
+ catch {
586
+ return data;
587
+ }
588
+ }
589
+ return undefined;
590
+ }
591
+ /** Whether a stream shows the model began its output, read from each event's data by its fields, never its words: a
592
+ * Messages block it opened (`content_block_start`), a Responses output item (`response.output_item.added`) or a
593
+ * Responses delta with something in it, a Chat Completions chunk whose delta holds content, reasoning, a refusal or a
594
+ * tool call. Its content need not have streamed: a model's hidden reasoning (a Responses reasoning item) shows none, and
595
+ * neither does a block a translation held until its end. An empty delta (a first chunk's `content: ""`, the one a
596
+ * mid-stream error comes in) is no output. */
597
+ export function outputBeganIn(text) {
598
+ const filled = (value) => (typeof value === "string" && value.length > 0) || (Array.isArray(value) && value.length > 0);
599
+ for (const raw of text.replace(/\r\n|\r/g, "\n").split("\n\n")) {
600
+ const data = raw.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).replace(/^ /, "")).join("\n").trim();
601
+ if (!data.startsWith("{"))
602
+ continue;
603
+ let event;
604
+ try {
605
+ event = JSON.parse(data);
606
+ }
607
+ catch {
608
+ continue;
609
+ }
610
+ const type = event.type;
611
+ if (type === "content_block_start" || type === "response.output_item.added")
612
+ return true;
613
+ if (typeof type === "string" && type.startsWith("response.") && type.endsWith(".delta") && filled(event.delta))
614
+ return true;
615
+ const choices = Array.isArray(event.choices) ? event.choices : [];
616
+ if (choices.some((choice) => ["content", "reasoning", "reasoning_content", "reasoning_text", "refusal", "tool_calls"].some((field) => filled(choice?.delta?.[field]))))
617
+ return true;
618
+ }
619
+ return false;
620
+ }
456
621
  export class ProxyRefusal extends Error {
457
622
  status;
458
623
  constructor(status, message) {
@@ -604,19 +769,40 @@ export async function countedInputOf(policy, origin, body, headers, fetch, say =
604
769
  const response = await fetch(`${origin}${counter.path}`, { method: "POST", headers: { ...counter.headers(headers), "content-type": "application/json" }, body: JSON.stringify(counter.body(body)), signal: cut });
605
770
  if (!response.ok) {
606
771
  await response.body?.cancel().catch(() => undefined);
607
- say(`model proxy (${policy.id}): the provider's token count answered ${response.status}; the request keeps its byte bound`);
772
+ say(`model proxy (${policy.id}): the provider's token count answered ${response.status}; the request keeps its byte bound or its local count`);
608
773
  return undefined;
609
774
  }
610
775
  const tokens = counter.tokensOf(await response.json());
611
776
  const margin = counter.margin ? counter.margin(body) : 0;
612
777
  if (!Number.isSafeInteger(tokens) || tokens < 0 || !Number.isSafeInteger(margin) || margin < 0) {
613
- say(`model proxy (${policy.id}): the provider's token count said no count; the request keeps its byte bound`);
778
+ say(`model proxy (${policy.id}): the provider's token count said no count; the request keeps its byte bound or its local count`);
614
779
  return undefined;
615
780
  }
616
781
  return tokens + margin;
617
782
  }
618
783
  catch (error) {
619
- say(`model proxy (${policy.id}): the provider's token count failed; the request keeps its byte bound`, { error: String(error?.message ?? error).slice(0, 200) });
784
+ say(`model proxy (${policy.id}): the provider's token count failed; the request keeps its byte bound or its local count`, { error: String(error?.message ?? error).slice(0, 200) });
785
+ return undefined;
786
+ }
787
+ }
788
+ /**
789
+ * The local count of a request with body `body`, its margin included (`policy.countInputLocally`); undefined (the request
790
+ * keeps its byte bound) when the policy has none, says none for this body, or its count throws or is not a whole number
791
+ * of tokens. Never throws.
792
+ */
793
+ export async function localInputOf(policy, body, say = () => { }) {
794
+ if (!policy.countInputLocally)
795
+ return undefined;
796
+ try {
797
+ const tokens = await policy.countInputLocally(body);
798
+ if (tokens === undefined)
799
+ return undefined;
800
+ if (!Number.isSafeInteger(tokens) || tokens < 0)
801
+ throw new Error(`not a token count: ${String(tokens).slice(0, 40)}`);
802
+ return tokens;
803
+ }
804
+ catch (error) {
805
+ say(`model proxy (${policy.id}): the local token count failed; the request keeps its byte bound`, { error: String(error?.message ?? error).slice(0, 200) });
620
806
  return undefined;
621
807
  }
622
808
  }
@@ -659,12 +845,18 @@ export async function startModelProxy(options, key) {
659
845
  const hostHeaders = { ...options.headers };
660
846
  const forward = options.fetch ?? fetch;
661
847
  const origin = baseOf(options.origin);
848
+ /** Whether each answer states what it cost in its usage (`statesUsageCost`): read as the request's reported figure when
849
+ * no header gave one, the price's figure kept beside it. */
850
+ const costStated = statesUsageCost(origin);
662
851
  const refusedStatus = policy.refusedStatus ?? 400;
663
852
  /** Why the turn's answer stopped, once the harness was told (onCut, onFiltered): the session's answer requests are
664
853
  * refused, unsent and unbooked, until it opens its next turn (openTurn). A client that asks again (Codex retries an
665
854
  * incomplete stream) is never paid for, whether or not the harness's own stop beat it. */
666
855
  let stopTold;
667
856
  const inflight = new Set();
857
+ /** By model, the last request whose answer reported what its whole input billed: the body it was sent with and that
858
+ * count (`policy.inputAfter` bounds a later request by it). */
859
+ const billed = new Map();
668
860
  /** The requests whose answer the provider stopped on its content filter, read on for their usage, each until booked. */
669
861
  const draining = new Map();
670
862
  /** Set by close(): nothing is admitted or sent after it. */
@@ -699,11 +891,11 @@ export async function startModelProxy(options, key) {
699
891
  res.writeHead(status, { "content-type": "application/json", connection: "close" });
700
892
  res.end(JSON.stringify({ error: { message, type: "agentrun_proxy", ...(code ? { code } : {}) } }));
701
893
  };
702
- // The session's MCP door, mounted once here for whichever harness's client calls it (the call id from its fact).
703
- const mcpDoor = options.mcp && mcpRoute(options.mcp.session, { callIdMeta: options.mcp.client.callIdMeta, ...(options.mcp.keepaliveMs !== undefined ? { keepaliveMs: options.mcp.keepaliveMs } : {}) });
704
- /** Serves one request. A note it took and did not bring to its admission (it left before `beforeRequest`: its client
705
- * gone while it was counted, a refusal, an error) is given back to the host then, however it left, so the next request
706
- * can take it at once. From its admission on the note is the admission's: told, or given back by its refusal. */
894
+ /** Serves one request. A note it took and did not bring to its admission (it left before `beforeRequest`: a body with
895
+ * the note that could not be serialized, an error) is given back to the host then, however it left, so the next
896
+ * request can take it at once. A request is counted before it takes one, so a client that goes while its request is
897
+ * counted never holds the note. From its admission on the note is the admission's: given back by its refusal, else held by the
898
+ * request until its end (afterRequest), which tells it if answered and gives it back if not. */
707
899
  const serve = async (req, res) => {
708
900
  const taken = {};
709
901
  try {
@@ -726,19 +918,6 @@ export async function startModelProxy(options, key) {
726
918
  // A request refused before its body is read is drained, so its client gets the answer instead of a reset.
727
919
  res.once("finish", () => { if (!req.complete)
728
920
  req.resume(); });
729
- const path = req.url ?? "";
730
- if (options.mcp && OAUTH_PATH.test(path)) {
731
- res.writeHead(404, { "content-length": "0" });
732
- return res.end();
733
- }
734
- const mcp = mcpDoor ? MCP_PATH.exec(path) : null;
735
- if (mcp) {
736
- if (!sameKey(policy.keyOf(req.headers), key))
737
- return refuse(res, 401, "this session's key is required", req);
738
- if (closing)
739
- return refuse(res, 503, "the model proxy is closing", req);
740
- return mcpDoor(mcp[1], req, res);
741
- }
742
921
  let route;
743
922
  let query;
744
923
  try {
@@ -797,52 +976,9 @@ export async function startModelProxy(options, key) {
797
976
  catch (error) {
798
977
  say(`model proxy (${policy.id}): the policy could not name the request's model; it is booked as the session's`, { error: String(error?.message ?? error).slice(0, 200) });
799
978
  }
800
- // A note the host has for the session's next main-model request (the spend cap's wrap-up): a paid request on the
801
- // session's model whose policy can place it takes it, once, before the body is measured, so the cap admits its bytes.
802
- // Only the turn's own request (ProviderPolicy.answers): a side call on the session's model (a title, a summary, when
803
- // the client has no small model) takes none. One the policy fails to place is dropped, said once; the request goes as
804
- // the client sent it. The body as the client sent it is kept (`plain`): a request the cap admits only without the
805
- // note's bytes goes as that (ModelTicket.noteDropped).
806
- let noted = false;
807
- let plain;
808
- // Never on the host's own request (`host`): the note is for the harness's model, in its own conversation, so a host
809
- // request is neither measured for it nor noted.
810
- if (!route.free && asked === model && host === undefined && (policy.answers ? policy.answers(body) : true) && policy.addNote && hooks.note) {
811
- // The request as its client sent it, measured first, so the host prices it as its admission will (the wrap-up's least).
812
- let request = {};
813
- try {
814
- const measured = inputTokensMaxOf(policy, body, JSON.stringify(body), say);
815
- const askedOut = policy.outputAsked?.(body);
816
- const leastOut = policy.outputLeast?.(body);
817
- const count = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
818
- request = { ...(count(measured) === undefined ? {} : { inputTokensMax: measured }), ...(count(askedOut) === undefined ? {} : { outputTokensAsked: askedOut }), ...(count(leastOut) === undefined ? {} : { outputTokensLeast: leastOut }) };
819
- }
820
- catch {
821
- request = {};
822
- }
823
- const note = hooks.note(asked, request);
824
- // Taken: given back (serve) unless this request brings it to its admission, below. One the policy fails to place
825
- // goes back too: this request goes without it.
826
- if (note)
827
- taken.note = note;
828
- if (note) {
829
- try {
830
- const without = body;
831
- body = policy.addNote(body, note);
832
- plain = without;
833
- noted = true;
834
- }
835
- catch (error) {
836
- say(`model proxy (${policy.id}): the host's note could not be placed; the request goes without it`, { error: String(error?.message ?? error).slice(0, 200) });
837
- taken.note = undefined;
838
- try {
839
- hooks.noteReturned?.(note);
840
- }
841
- catch { /* the host's to say */ }
842
- }
843
- }
844
- }
845
- // The body as it is sent, and the most input tokens it can be billed for, measured before the runner is asked.
979
+ // The body as its client sent it, and the most input tokens it can be billed for, measured before the runner is asked:
980
+ // its bytes here, then the provider's count or the policy's local count below, and only then a note (the wrap-up's),
981
+ // which is decided on that same figure.
846
982
  let sent;
847
983
  try {
848
984
  sent = JSON.stringify(body);
@@ -852,23 +988,22 @@ export async function startModelProxy(options, key) {
852
988
  return refuse(res, 500, "the body could not be serialized", req);
853
989
  }
854
990
  let inputTokensMax = inputTokensMaxOf(policy, body, sent, say);
855
- // The same, of the body as the client sent it, when a note was placed: the cap checks the request without the note.
856
- let plainSent;
857
- let inputTokensMaxWithoutNote;
858
- if (plain) {
859
- try {
860
- plainSent = JSON.stringify(plain);
861
- inputTokensMaxWithoutNote = inputTokensMaxOf(policy, plain, plainSent, say);
862
- }
863
- catch {
864
- plainSent = undefined;
865
- }
866
- }
991
+ /** Its byte bound, kept: a note adds to the bound what it adds to this. */
992
+ const byteBound = inputTokensMax;
867
993
  // What the body asks for at most, and the least it may be limited to, as the policy reads them. One the policy cannot
868
994
  // read leaves the request's worst case unknown: its input is unmeasured.
869
995
  const figure = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
870
996
  let outputTokensAsked;
871
997
  let outputTokensLeast;
998
+ /** The effort the body names (the policy's `effortOf`): words only, never a figure, so one it cannot read is none. */
999
+ let effort;
1000
+ try {
1001
+ const named = policy.effortOf?.(body);
1002
+ effort = typeof named === "string" && named.length > 0 && named.length <= 32 ? named : undefined;
1003
+ }
1004
+ catch {
1005
+ effort = undefined;
1006
+ }
872
1007
  /** The reasoning a stop of this request leaves unseen (the policy's `reasoningHidden`), in tokens. */
873
1008
  let hiddenTokens = 0;
874
1009
  /** The content and the reasoning the client was sent, by the policy's reading of each event (content: text,
@@ -904,6 +1039,10 @@ export async function startModelProxy(options, key) {
904
1039
  }
905
1040
  catch (error) {
906
1041
  say(`model proxy (${policy.id}): the provider credential could not be read`, { error: String(error?.message ?? error).slice(0, 200) });
1042
+ // A credential its host says is gone (signed out, expired) is refused in the host's words, which the client does
1043
+ // not try again.
1044
+ if (error instanceof CredentialUnavailable)
1045
+ return refuse(res, refusedStatus, error.message, req, "credential_unavailable");
907
1046
  }
908
1047
  if (!credential)
909
1048
  return refuse(res, 500, "the session has no provider credential", req);
@@ -942,20 +1081,19 @@ export async function startModelProxy(options, key) {
942
1081
  if (answering && !route.free && stopTold !== undefined)
943
1082
  return refuse(res, refusedStatus, `refused: the turn's answer was ${stopTold}, and the turn ends there`, req);
944
1083
  // An answer request on an upstream that is its provider's own (policy.countInput): its input bound is the provider's
945
- // exact count when that is below its bytes, so a small cap admits a first turn its bytes would not. Each answer request
946
- // is counted, not only the first: the cap prices a step by the last one's tokens plus how far its bound grew, so a
947
- // counted bound beside a byte bound would read the bytes as growth. A count that fails or times out leaves the byte
948
- // bound, and never holds the request up for long. A noted request is counted with its note, which bounds it without
949
- // the note too (the note only adds).
1084
+ // exact count when that is below its bytes, so a small cap admits a turn its bytes would not: the cap holds each
1085
+ // request at its whole input uncached, and the count is that input to the token. A count that fails or times out
1086
+ // leaves the byte bound, and never holds the request up for long. The body is counted as its client sent it, before
1087
+ // any note (below).
950
1088
  // Only a bound that is a number is lowered: an unmeasured one (a fee with no bound, a hosted tool's reads) stays so.
951
- let inputTokensCounted = false;
1089
+ /** The provider's count, when it gave one: then no local count is taken, even when the provider's is the higher. */
1090
+ let counted;
952
1091
  if (answering && !route.free && host === undefined && inputTokensMax !== undefined && policy.countInput) {
953
1092
  // A client that goes while its request is counted is gone before anything is admitted: the count is cut, and the
954
1093
  // request is neither admitted nor sent (nothing is booked, and no paid answer starts for no one).
955
1094
  const gone = new AbortController();
956
1095
  const onGone = () => gone.abort(new Error("the client went while its request was counted"));
957
1096
  res.once("close", onGone);
958
- let counted;
959
1097
  try {
960
1098
  counted = await countedInputOf(policy, origin, body, headers, forward, say, COUNT_TIMEOUT_MS, gone.signal);
961
1099
  }
@@ -964,31 +1102,106 @@ export async function startModelProxy(options, key) {
964
1102
  }
965
1103
  if (gone.signal.aborted || res.destroyed)
966
1104
  return;
967
- if (counted !== undefined && inputTokensMax !== undefined && counted < inputTokensMax) {
1105
+ if (counted !== undefined && inputTokensMax !== undefined && counted < inputTokensMax)
968
1106
  inputTokensMax = counted;
969
- inputTokensCounted = true;
970
- if (inputTokensMaxWithoutNote !== undefined)
971
- inputTokensMaxWithoutNote = Math.min(inputTokensMaxWithoutNote, counted);
1107
+ }
1108
+ // A request its provider did not count (no counter, a gateway, a side or host request, a count that failed): its input
1109
+ // bound is the policy's local count (countInputLocally, its margin included) when that is below its bytes.
1110
+ if (counted === undefined && !route.free && inputTokensMax !== undefined && policy.countInputLocally) {
1111
+ const local = await localInputOf(policy, body, say);
1112
+ if (res.destroyed)
1113
+ return;
1114
+ if (local !== undefined && inputTokensMax !== undefined && local < inputTokensMax)
1115
+ inputTokensMax = local;
1116
+ }
1117
+ // A request its provider did not count that carries an earlier one the provider billed (a session's next step, on a
1118
+ // model no local count reads: Claude through a gateway): its input bound is that bill and the bytes it adds
1119
+ // (policy.inputAfter), when that is below its bound so far.
1120
+ const earlier = billed.get(asked);
1121
+ if (counted === undefined && !route.free && inputTokensMax !== undefined && earlier && policy.inputAfter) {
1122
+ try {
1123
+ const after = policy.inputAfter(earlier, body);
1124
+ if (after !== undefined && (!Number.isSafeInteger(after) || after < 0))
1125
+ throw new Error(`not a token count: ${String(after).slice(0, 40)}`);
1126
+ if (after !== undefined && after < inputTokensMax)
1127
+ inputTokensMax = after;
1128
+ }
1129
+ catch (error) {
1130
+ say(`model proxy (${policy.id}): the bound from the earlier billed request failed; the request keeps its bound`, { error: String(error?.message ?? error).slice(0, 200) });
1131
+ }
1132
+ }
1133
+ // A note the host has for the session's next main-model request (the spend cap's wrap-up): a paid request on the
1134
+ // session's model whose policy can place it takes it, once, now that it is measured as its admission reads it
1135
+ // (NoteRequest: the input bound above, a count where there is one, and the output it asks for and needs), so the note
1136
+ // comes due on the figures the cap admits it by, never on its bytes where it was counted. Only the turn's own request
1137
+ // (ProviderPolicy.answers): a side call on the session's model (a title, a summary, when the client has no small model)
1138
+ // takes none, nor does the host's own (`host`): the note is for the harness's model, in its own conversation. One the
1139
+ // policy fails to place, or whose body it cannot measure, is given back, said once; the request goes as the client sent
1140
+ // it. The noted request's bound is that figure and the note's own bytes (what the body grows by, with what its policy
1141
+ // says the provider adds for it): a token covers at least a byte, so it is never under what the noted request bills.
1142
+ // The body as the client sent it is kept (`plain`): a request the cap admits only without the note's bytes goes as
1143
+ // that (ModelTicket.noteDropped).
1144
+ let noted = false;
1145
+ let plain;
1146
+ let plainSent;
1147
+ let inputTokensMaxWithoutNote;
1148
+ if (!route.free && asked === model && host === undefined && answering && policy.addNote && hooks.note) {
1149
+ const note = hooks.note(asked, { ...(inputTokensMax === undefined ? {} : { inputTokensMax }), ...(outputTokensAsked === undefined ? {} : { outputTokensAsked }), ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }) });
1150
+ if (note) {
1151
+ // Taken: given back (serve) unless this request brings it to its admission, below.
1152
+ taken.note = note;
1153
+ try {
1154
+ const withNote = policy.addNote(body, note);
1155
+ const withNoteSent = JSON.stringify(withNote);
1156
+ const grown = inputTokensMaxOf(policy, withNote, withNoteSent, say);
1157
+ if (grown === undefined || byteBound === undefined || grown < byteBound)
1158
+ throw new Error("the body with the note could not be measured");
1159
+ if (inputTokensMax !== undefined) {
1160
+ inputTokensMaxWithoutNote = inputTokensMax;
1161
+ inputTokensMax += grown - byteBound;
1162
+ }
1163
+ plain = body;
1164
+ plainSent = sent;
1165
+ body = withNote;
1166
+ sent = withNoteSent;
1167
+ noted = true;
1168
+ }
1169
+ catch (error) {
1170
+ say(`model proxy (${policy.id}): the host's note could not be placed; the request goes without it`, { error: String(error?.message ?? error).slice(0, 200) });
1171
+ taken.note = undefined;
1172
+ try {
1173
+ hooks.noteReturned?.(note);
1174
+ }
1175
+ catch { /* the host's to say */ }
1176
+ }
972
1177
  }
973
1178
  }
974
1179
  // This request's own admission, handed back to its booking (requests may be in flight together).
975
1180
  let ticket;
976
- // The note, if this request carries it, is its admission's from here: told once admitted, given back by a refusal.
1181
+ // The note, if this request carries it, is its admission's from here: given back by a refusal, else told if it is answered.
977
1182
  if (noted)
978
1183
  taken.note = undefined;
1184
+ // A client that goes while its request waits for room under the run's cap (runBooking) takes it out of the line: it
1185
+ // is never admitted, nothing is held or booked for it.
1186
+ const left = new AbortController();
1187
+ const onLeft = () => left.abort(new Error("the client went while its request waited for room under the run's cap"));
1188
+ res.once("close", onLeft);
1189
+ if (res.destroyed)
1190
+ onLeft();
979
1191
  try {
980
1192
  if (!route.free)
981
1193
  ticket = await hooks.beforeRequest({
1194
+ signal: left.signal,
982
1195
  // A side call: on another model than the session's, or the host's own (it counts toward no typical request). One on
983
1196
  // the session's model that is no answer of the turn (a title, a summary, a child's: `answering`, the policy's
984
- // answers) is `unanswered`: booked as any request, but a conversation of its own to the cap's expected pricing.
1197
+ // answers) is `unanswered`: booked as any request, but no answer the host keeps its reserve back for.
985
1198
  model: asked, inputTokensMax, ...(asked !== model || host !== undefined ? { side: true } : {}), ...(!answering && host === undefined ? { unanswered: true } : {}),
986
1199
  ...(noted ? { noted: true, ...(inputTokensMaxWithoutNote === undefined ? {} : { inputTokensMaxWithoutNote }) } : {}),
987
1200
  ...(outputTokensAsked === undefined ? {} : { outputTokensAsked }),
988
1201
  ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }),
1202
+ ...(effort === undefined ? {} : { effort }),
989
1203
  ...(feeUsd > 0 ? { feeUsd } : {}),
990
1204
  ...(host === undefined ? {} : { host }),
991
- ...(inputTokensCounted ? { inputTokensCounted: true } : {}),
992
1205
  ...(options.route === undefined ? {} : { route: options.route }),
993
1206
  });
994
1207
  }
@@ -996,10 +1209,14 @@ export async function startModelProxy(options, key) {
996
1209
  // Not 429: clients retry that, and the runner already refused this request (a turn cap, the host's budget).
997
1210
  return refuse(res, refusedStatus, `refused before it was sent: ${String(error?.message ?? error).slice(0, 300)}`, req, capRefusal(error) ? SPEND_CAP_REACHED : undefined);
998
1211
  }
1212
+ finally {
1213
+ res.off("close", onLeft);
1214
+ }
999
1215
  /** An admitted request that is not sent after all: refused to its client, and released, booked at nothing, so the
1000
1216
  * runner's count agrees. */
1001
1217
  const release = async (status, message) => {
1002
- refuse(res, status, message, req);
1218
+ if (!res.destroyed)
1219
+ refuse(res, status, message, req);
1003
1220
  if (!route.free) {
1004
1221
  try {
1005
1222
  await hooks.afterRequest({ input: 0, output: 0, cacheRead: 0, usd: 0 }, ticket, { end: "nothing", label: "never_left" });
@@ -1012,6 +1229,12 @@ export async function startModelProxy(options, key) {
1012
1229
  // Admitted while the proxy was closing, and never sent.
1013
1230
  if (closing)
1014
1231
  return release(503, "the model proxy is closing");
1232
+ // Admitted after its client left (a stop or a cancel while its hold was made durable): never sent, booked at nothing.
1233
+ // Sent anyway it would be a paid answer for no one, and one never stopped (its client's close came before the proxy
1234
+ // listened for it, below), booked only once the provider ended it: past the run's end, which then read the request as
1235
+ // cut at an unknown cost. Nothing from here to that listener waits, so a client that leaves later is heard there.
1236
+ if (res.destroyed || req.socket.destroyed)
1237
+ return release(499, "the client left before its request was sent");
1015
1238
  // Admitted only without the note (its bytes did not fit what is left of the cap): the body as the client sent it.
1016
1239
  if (typeof ticket === "object" && ticket !== null && ticket.noteDropped === true) {
1017
1240
  if (!plain || plainSent === undefined)
@@ -1156,7 +1379,7 @@ export async function startModelProxy(options, key) {
1156
1379
  };
1157
1380
  try {
1158
1381
  // From here a paid request may be paid, so every way out below books it exactly once.
1159
- const upstream = await forward(`${origin}${route.path}${query ? `?${query}` : ""}`, { method: route.method, headers, body: sent, signal: controller.signal });
1382
+ let upstream = await forward(`${origin}${route.path}${query ? `?${query}` : ""}`, { method: route.method, headers, body: sent, signal: controller.signal });
1160
1383
  // The provider answered (and a paid request was paid): a host callback that throws must not lose the answer or
1161
1384
  // its booking.
1162
1385
  try {
@@ -1165,6 +1388,47 @@ export async function startModelProxy(options, key) {
1165
1388
  catch (error) {
1166
1389
  say(`model proxy (${policy.id}): onResponse threw`, { error: String(error?.message ?? error).slice(0, 200) });
1167
1390
  }
1391
+ if (upstream.status === 401 && options.credentialRefused) {
1392
+ try {
1393
+ await options.credentialRefused(credential);
1394
+ }
1395
+ catch {
1396
+ say(`model proxy (${policy.id}): the host could not renew a refused credential`);
1397
+ }
1398
+ }
1399
+ // An error no retry mends (ProviderPolicy.finalError, a plan's limit reached): its client is answered the policy's
1400
+ // words at refusedStatus, a status it never asks again on, in place of the provider's. It was not paid: booked as
1401
+ // the provider's error answer is, at nothing.
1402
+ if (!upstream.ok && policy.finalError) {
1403
+ const text = await upstream.text();
1404
+ let final;
1405
+ try {
1406
+ final = policy.finalError(upstream.status, text);
1407
+ }
1408
+ catch (error) {
1409
+ say(`model proxy (${policy.id}): whether an error answer is final could not be read`, { error: String(error?.message ?? error).slice(0, 200) });
1410
+ }
1411
+ if (final)
1412
+ say(`model proxy (${policy.id}): the provider's error answer ends the run`, { status: upstream.status, code: final.code });
1413
+ // The body read is decoded: passed on, it carries no encoding or length of the provider's.
1414
+ const headers = new Headers(upstream.headers);
1415
+ headers.delete("content-encoding");
1416
+ headers.delete("content-length");
1417
+ // The policy's answer keeps the provider's request ids (providerIdsOf reads them below), so the request's records
1418
+ // still name it at the provider.
1419
+ upstream = final
1420
+ ? new Response(JSON.stringify({ error: { message: final.message, type: "agentrun_proxy", code: final.code } }), { status: refusedStatus, headers: { ...providerIdsOf(upstream.headers), "content-type": "application/json" } })
1421
+ : new Response(text, { status: upstream.status, headers });
1422
+ // The harness ends the turn in the policy's words, whatever its client makes of the answer.
1423
+ if (final) {
1424
+ try {
1425
+ options.onFinal?.(final.message, final.code);
1426
+ }
1427
+ catch (error) {
1428
+ say(`model proxy (${policy.id}): onFinal threw`, { error: String(error?.message ?? error).slice(0, 200) });
1429
+ }
1430
+ }
1431
+ }
1168
1432
  // Its ids are kept before its body is read: from here the provider has seen it, whatever cuts it off.
1169
1433
  ids = route.free ? undefined : providerIdsOf(upstream.headers);
1170
1434
  reported = route.free ? undefined : reportedCostOf(upstream.headers);
@@ -1325,6 +1589,12 @@ export async function startModelProxy(options, key) {
1325
1589
  // Whether `usd` is a figure the provider gave (an error answer's nothing included), not one this proxy made up.
1326
1590
  let own = false;
1327
1591
  let tableUsd;
1592
+ /** The provider's words when it refused the request inside a successful answer (streamErrorOf, no tokens reported):
1593
+ * booked at nothing. */
1594
+ let refusedIn;
1595
+ /** The provider's words when its successful answer ended in its error after it reported tokens (or a cost, or after
1596
+ * the model's content streamed): booked at what it reported, as an answer. */
1597
+ let erredIn;
1328
1598
  // A client may leave once it has read the response's usage (Codex does, at the completion event) while the provider
1329
1599
  // still holds the stream open: what was read of a successful answer is read for its usage as a whole one is. With none
1330
1600
  // in it, the cost is unknown, as for any answer cut short.
@@ -1349,27 +1619,68 @@ export async function startModelProxy(options, key) {
1349
1619
  }
1350
1620
  else {
1351
1621
  let unread = false;
1622
+ const kept = length <= USAGE_WINDOW ? tail : `${head}\n${lastOf(tail)}`;
1352
1623
  try {
1353
- usage = policy.usageOf(length <= USAGE_WINDOW ? tail : `${head}\n${lastOf(tail)}`, body);
1624
+ usage = policy.usageOf(kept, body);
1354
1625
  }
1355
1626
  catch (error) {
1356
1627
  say(`model proxy (${policy.id}): the usage could not be read; the request is booked at an unknown cost`, { error: String(error?.message ?? error).slice(0, 200) });
1357
1628
  usage = { input: 0, output: 0, cacheRead: 0 };
1358
1629
  unread = true;
1359
1630
  }
1631
+ // A stream the provider ended in its error event (an overload, a rate limit, a failure, at any point): what it reported
1632
+ // before the error is booked at the table's price (or at the cost it stated), a known figure, never the hold. Usage
1633
+ // whose every count is 0 (a translation's start, written before the provider said any) reports no tokens.
1634
+ const failed = streamErrorOf(kept);
1635
+ if (failed !== undefined && usage && usage.input + usage.output + usage.cacheRead + (usage.cacheWrite ?? 0) === 0)
1636
+ usage = undefined;
1637
+ // What the answer's own usage says it cost (OpenRouter's), when no header said: what was paid, as a gateway's header.
1638
+ if (reported === undefined && costStated)
1639
+ reported = usageCostOf(kept);
1640
+ // In the provider's words, the credential and the host's header values cut, then the host's redactor, as its client
1641
+ // was sent them.
1642
+ const wordsOf = (said) => {
1643
+ const words = errorCut("error", echoForms([credential, ...Object.values(hostHeaders)]), options.redact, (message) => say(`model proxy (${policy.id}): ${message}`));
1644
+ return `${words.push(said)}${words.end()}`.slice(0, 300);
1645
+ };
1360
1646
  if (!usage) {
1361
1647
  usage = { input: 0, output: 0, cacheRead: 0 };
1362
1648
  unread = true;
1649
+ // A stream that ends in the provider's error with no tokens and no cost reported (a 200 the provider sent before
1650
+ // the model's first token, then a rate limit or an overload as an error event): refused, never run, so it cost
1651
+ // nothing. Never once the model's content streamed with no usage said, nor once the stream shows it began its
1652
+ // output with none of it streamed (outputBeganIn: hidden reasoning, a block a translation held): that was run,
1653
+ // and is booked at an unknown cost as any answer cut short. Missing content is no proof of a refusal.
1654
+ if (failed !== undefined && reported === undefined && !(policy.contentBytesOf && sentOf.bytes("content") > 0) && !outputBeganIn(kept)) {
1655
+ refusedIn = wordsOf(failed.words);
1656
+ say(`model proxy (${policy.id}): the provider refused the request inside its answer (${failed.rateLimit ? "a rate limit" : "an error"}); booked at nothing`);
1657
+ }
1658
+ }
1659
+ if (failed !== undefined && refusedIn === undefined) {
1660
+ erredIn = wordsOf(failed.words);
1661
+ say(`model proxy (${policy.id}): the provider ended its answer in an error; booked at what it reported${unread && reported === undefined ? " (none: an unknown cost)" : ""}`);
1363
1662
  }
1663
+ // A translation's failure in words (wordsErrorOf): an answer that ended in an error all the same, its client asking
1664
+ // again. Booked as before, as any answer cut short; only its end says the error.
1665
+ const translated = failed === undefined ? wordsErrorOf(kept) : undefined;
1666
+ if (translated !== undefined)
1667
+ erredIn = wordsOf(translated);
1668
+ // An answer of the client's own that reached it whole and reported its usage: what its whole input billed, kept
1669
+ // with the body it was sent with, for the session's next request on its model (policy.inputAfter).
1670
+ const billedInput = usage.input + usage.cacheRead + (usage.cacheWrite ?? 0);
1671
+ if (answered?.ok && !stoppedByClient && !unread && failed === undefined && translated === undefined && refusedIn === undefined && host === undefined && Number.isSafeInteger(billedInput) && billedInput > 0)
1672
+ billed.set(asked, { body, inputTokens: billedInput });
1364
1673
  try {
1365
- usd = unread ? null : options.price?.(asked, usage) ?? null;
1674
+ usd = refusedIn !== undefined ? 0 : unread ? null : options.price?.(asked, usage) ?? null;
1675
+ if (refusedIn !== undefined)
1676
+ own = true;
1366
1677
  }
1367
1678
  catch (error) {
1368
1679
  say(`model proxy (${policy.id}): the price could not be computed; the request is booked at an unknown cost`, { error: String(error?.message ?? error).slice(0, 200) });
1369
1680
  usd = null;
1370
1681
  }
1371
1682
  // What the gateway says it cost is what was paid; the table's figure stays beside it, to audit the table.
1372
- if (reported !== undefined) {
1683
+ if (reported !== undefined && refusedIn === undefined) {
1373
1684
  tableUsd = usd;
1374
1685
  usd = reported;
1375
1686
  own = true;
@@ -1383,11 +1694,12 @@ export async function startModelProxy(options, key) {
1383
1694
  const stopped = stoppedByClient && usd === null ? { stoppedAfterBytes: streamed, ...(hiddenTokens > 0 ? { stoppedHiddenTokens: hiddenTokens, stoppedReasoningBytes: sentOf.bytes("reasoning") } : {}) } : {};
1384
1695
  // How it ended, for the runner to book it by (booking.ts). A stop counts what the stop fields above say of it: its
1385
1696
  // content, and the part of its hidden reasoning budget that did not stream, max(0, budget - the reasoning sent).
1386
- const ended = stoppedByClient && usd === null ? { end: "stopped", streamedTokens: streamed + Math.max(0, hiddenTokens - sentOf.bytes("reasoning")) }
1387
- : !seen ? (isConnectCode(failedCode) ? { end: "nothing", label: "never_left" } : { end: "lost", label: "error_before" })
1388
- : !seen.ok ? (isGatewayTimeout(began?.status ?? 0) ? { end: "lost", label: "gateway_timeout" } : { end: "nothing", label: "status" })
1389
- : !answered && usd === null ? { end: "lost", label: "error_after", began: true }
1390
- : { end: "answered", usd, ...(filteredTold ? { label: "filtered" } : {}) };
1697
+ const ended = refusedIn !== undefined ? { end: "nothing", label: "refused", reason: refusedIn }
1698
+ : stoppedByClient && usd === null ? { end: "stopped", streamedTokens: streamed + Math.max(0, hiddenTokens - sentOf.bytes("reasoning")) }
1699
+ : !seen ? (isConnectCode(failedCode) ? { end: "nothing", label: "never_left" } : { end: "lost", label: "error_before" })
1700
+ : !seen.ok ? (isGatewayTimeout(began?.status ?? 0) ? { end: "lost", label: "gateway_timeout" } : { end: "nothing", label: "status" })
1701
+ : !answered && usd === null ? { end: "lost", label: "error_after", began: true }
1702
+ : { end: "answered", usd, ...(erredIn !== undefined ? { label: "error", reason: erredIn } : filteredTold ? { label: "filtered" } : {}), ...(tableUsd === undefined ? {} : { tableUsd }) };
1391
1703
  await hooks.afterRequest({ ...usage, usd, ...(own ? {} : { estimated: true }), ...(tableUsd === undefined ? {} : { tableUsd }), ...(ids ? { providerIds: ids } : {}), ...stopped }, ticket, ended);
1392
1704
  }
1393
1705
  catch (error) {