@parcha/agentrun-kernel 0.1.0-beta.38 → 0.1.0-beta.40

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
@@ -26,6 +26,10 @@ const capRefusal = (error) => {
26
26
  const fields = error;
27
27
  return fields?.code === SPEND_CAP_REACHED || fields?.refusal === SPEND_CAP_REACHED;
28
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
+ }
29
33
  /** What one provider-native web search costs, in USD, beside the tokens: $10 per 1,000 searches (Anthropic's "Web search tool"
30
34
  * and OpenAI's "Web search (all models)" list the same price). The one figure every fee reads: the proxy policies of the
31
35
  * Claude and Codex harnesses and the runner's hosted search. */
@@ -486,6 +490,134 @@ export function reportedCostOf(headers) {
486
490
  return undefined;
487
491
  return costOf(headers.get(`${COST_HEADER}-original`));
488
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
+ }
489
621
  export class ProxyRefusal extends Error {
490
622
  status;
491
623
  constructor(status, message) {
@@ -637,19 +769,40 @@ export async function countedInputOf(policy, origin, body, headers, fetch, say =
637
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 });
638
770
  if (!response.ok) {
639
771
  await response.body?.cancel().catch(() => undefined);
640
- 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`);
641
773
  return undefined;
642
774
  }
643
775
  const tokens = counter.tokensOf(await response.json());
644
776
  const margin = counter.margin ? counter.margin(body) : 0;
645
777
  if (!Number.isSafeInteger(tokens) || tokens < 0 || !Number.isSafeInteger(margin) || margin < 0) {
646
- 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`);
647
779
  return undefined;
648
780
  }
649
781
  return tokens + margin;
650
782
  }
651
783
  catch (error) {
652
- 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) });
653
806
  return undefined;
654
807
  }
655
808
  }
@@ -692,12 +845,18 @@ export async function startModelProxy(options, key) {
692
845
  const hostHeaders = { ...options.headers };
693
846
  const forward = options.fetch ?? fetch;
694
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);
695
851
  const refusedStatus = policy.refusedStatus ?? 400;
696
852
  /** Why the turn's answer stopped, once the harness was told (onCut, onFiltered): the session's answer requests are
697
853
  * refused, unsent and unbooked, until it opens its next turn (openTurn). A client that asks again (Codex retries an
698
854
  * incomplete stream) is never paid for, whether or not the harness's own stop beat it. */
699
855
  let stopTold;
700
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();
701
860
  /** The requests whose answer the provider stopped on its content filter, read on for their usage, each until booked. */
702
861
  const draining = new Map();
703
862
  /** Set by close(): nothing is admitted or sent after it. */
@@ -732,9 +891,11 @@ export async function startModelProxy(options, key) {
732
891
  res.writeHead(status, { "content-type": "application/json", connection: "close" });
733
892
  res.end(JSON.stringify({ error: { message, type: "agentrun_proxy", ...(code ? { code } : {}) } }));
734
893
  };
735
- /** Serves one request. A note it took and did not bring to its admission (it left before `beforeRequest`: its client
736
- * gone while it was counted, a refusal, an error) is given back to the host then, however it left, so the next request
737
- * 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. */
738
899
  const serve = async (req, res) => {
739
900
  const taken = {};
740
901
  try {
@@ -815,52 +976,9 @@ export async function startModelProxy(options, key) {
815
976
  catch (error) {
816
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) });
817
978
  }
818
- // A note the host has for the session's next main-model request (the spend cap's wrap-up): a paid request on the
819
- // session's model whose policy can place it takes it, once, before the body is measured, so the cap admits its bytes.
820
- // Only the turn's own request (ProviderPolicy.answers): a side call on the session's model (a title, a summary, when
821
- // the client has no small model) takes none. One the policy fails to place is dropped, said once; the request goes as
822
- // the client sent it. The body as the client sent it is kept (`plain`): a request the cap admits only without the
823
- // note's bytes goes as that (ModelTicket.noteDropped).
824
- let noted = false;
825
- let plain;
826
- // Never on the host's own request (`host`): the note is for the harness's model, in its own conversation, so a host
827
- // request is neither measured for it nor noted.
828
- if (!route.free && asked === model && host === undefined && (policy.answers ? policy.answers(body) : true) && policy.addNote && hooks.note) {
829
- // The request as its client sent it, measured first, so the host prices it as its admission will (the wrap-up's least).
830
- let request = {};
831
- try {
832
- const measured = inputTokensMaxOf(policy, body, JSON.stringify(body), say);
833
- const askedOut = policy.outputAsked?.(body);
834
- const leastOut = policy.outputLeast?.(body);
835
- const count = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
836
- request = { ...(count(measured) === undefined ? {} : { inputTokensMax: measured }), ...(count(askedOut) === undefined ? {} : { outputTokensAsked: askedOut }), ...(count(leastOut) === undefined ? {} : { outputTokensLeast: leastOut }) };
837
- }
838
- catch {
839
- request = {};
840
- }
841
- const note = hooks.note(asked, request);
842
- // Taken: given back (serve) unless this request brings it to its admission, below. One the policy fails to place
843
- // goes back too: this request goes without it.
844
- if (note)
845
- taken.note = note;
846
- if (note) {
847
- try {
848
- const without = body;
849
- body = policy.addNote(body, note);
850
- plain = without;
851
- noted = true;
852
- }
853
- catch (error) {
854
- 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) });
855
- taken.note = undefined;
856
- try {
857
- hooks.noteReturned?.(note);
858
- }
859
- catch { /* the host's to say */ }
860
- }
861
- }
862
- }
863
- // 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.
864
982
  let sent;
865
983
  try {
866
984
  sent = JSON.stringify(body);
@@ -870,23 +988,22 @@ export async function startModelProxy(options, key) {
870
988
  return refuse(res, 500, "the body could not be serialized", req);
871
989
  }
872
990
  let inputTokensMax = inputTokensMaxOf(policy, body, sent, say);
873
- // The same, of the body as the client sent it, when a note was placed: the cap checks the request without the note.
874
- let plainSent;
875
- let inputTokensMaxWithoutNote;
876
- if (plain) {
877
- try {
878
- plainSent = JSON.stringify(plain);
879
- inputTokensMaxWithoutNote = inputTokensMaxOf(policy, plain, plainSent, say);
880
- }
881
- catch {
882
- plainSent = undefined;
883
- }
884
- }
991
+ /** Its byte bound, kept: a note adds to the bound what it adds to this. */
992
+ const byteBound = inputTokensMax;
885
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
886
994
  // read leaves the request's worst case unknown: its input is unmeasured.
887
995
  const figure = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
888
996
  let outputTokensAsked;
889
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
+ }
890
1007
  /** The reasoning a stop of this request leaves unseen (the policy's `reasoningHidden`), in tokens. */
891
1008
  let hiddenTokens = 0;
892
1009
  /** The content and the reasoning the client was sent, by the policy's reading of each event (content: text,
@@ -922,6 +1039,10 @@ export async function startModelProxy(options, key) {
922
1039
  }
923
1040
  catch (error) {
924
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");
925
1046
  }
926
1047
  if (!credential)
927
1048
  return refuse(res, 500, "the session has no provider credential", req);
@@ -960,20 +1081,19 @@ export async function startModelProxy(options, key) {
960
1081
  if (answering && !route.free && stopTold !== undefined)
961
1082
  return refuse(res, refusedStatus, `refused: the turn's answer was ${stopTold}, and the turn ends there`, req);
962
1083
  // An answer request on an upstream that is its provider's own (policy.countInput): its input bound is the provider's
963
- // exact count when that is below its bytes, so a small cap admits a first turn its bytes would not. Each answer request
964
- // 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
965
- // counted bound beside a byte bound would read the bytes as growth. A count that fails or times out leaves the byte
966
- // bound, and never holds the request up for long. A noted request is counted with its note, which bounds it without
967
- // 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).
968
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.
969
- 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;
970
1091
  if (answering && !route.free && host === undefined && inputTokensMax !== undefined && policy.countInput) {
971
1092
  // A client that goes while its request is counted is gone before anything is admitted: the count is cut, and the
972
1093
  // request is neither admitted nor sent (nothing is booked, and no paid answer starts for no one).
973
1094
  const gone = new AbortController();
974
1095
  const onGone = () => gone.abort(new Error("the client went while its request was counted"));
975
1096
  res.once("close", onGone);
976
- let counted;
977
1097
  try {
978
1098
  counted = await countedInputOf(policy, origin, body, headers, forward, say, COUNT_TIMEOUT_MS, gone.signal);
979
1099
  }
@@ -982,31 +1102,106 @@ export async function startModelProxy(options, key) {
982
1102
  }
983
1103
  if (gone.signal.aborted || res.destroyed)
984
1104
  return;
985
- if (counted !== undefined && inputTokensMax !== undefined && counted < inputTokensMax) {
1105
+ if (counted !== undefined && inputTokensMax !== undefined && counted < inputTokensMax)
986
1106
  inputTokensMax = counted;
987
- inputTokensCounted = true;
988
- if (inputTokensMaxWithoutNote !== undefined)
989
- 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
+ }
990
1177
  }
991
1178
  }
992
1179
  // This request's own admission, handed back to its booking (requests may be in flight together).
993
1180
  let ticket;
994
- // 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.
995
1182
  if (noted)
996
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();
997
1191
  try {
998
1192
  if (!route.free)
999
1193
  ticket = await hooks.beforeRequest({
1194
+ signal: left.signal,
1000
1195
  // A side call: on another model than the session's, or the host's own (it counts toward no typical request). One on
1001
1196
  // the session's model that is no answer of the turn (a title, a summary, a child's: `answering`, the policy's
1002
- // 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.
1003
1198
  model: asked, inputTokensMax, ...(asked !== model || host !== undefined ? { side: true } : {}), ...(!answering && host === undefined ? { unanswered: true } : {}),
1004
1199
  ...(noted ? { noted: true, ...(inputTokensMaxWithoutNote === undefined ? {} : { inputTokensMaxWithoutNote }) } : {}),
1005
1200
  ...(outputTokensAsked === undefined ? {} : { outputTokensAsked }),
1006
1201
  ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }),
1202
+ ...(effort === undefined ? {} : { effort }),
1007
1203
  ...(feeUsd > 0 ? { feeUsd } : {}),
1008
1204
  ...(host === undefined ? {} : { host }),
1009
- ...(inputTokensCounted ? { inputTokensCounted: true } : {}),
1010
1205
  ...(options.route === undefined ? {} : { route: options.route }),
1011
1206
  });
1012
1207
  }
@@ -1014,6 +1209,9 @@ export async function startModelProxy(options, key) {
1014
1209
  // Not 429: clients retry that, and the runner already refused this request (a turn cap, the host's budget).
1015
1210
  return refuse(res, refusedStatus, `refused before it was sent: ${String(error?.message ?? error).slice(0, 300)}`, req, capRefusal(error) ? SPEND_CAP_REACHED : undefined);
1016
1211
  }
1212
+ finally {
1213
+ res.off("close", onLeft);
1214
+ }
1017
1215
  /** An admitted request that is not sent after all: refused to its client, and released, booked at nothing, so the
1018
1216
  * runner's count agrees. */
1019
1217
  const release = async (status, message) => {
@@ -1181,7 +1379,7 @@ export async function startModelProxy(options, key) {
1181
1379
  };
1182
1380
  try {
1183
1381
  // From here a paid request may be paid, so every way out below books it exactly once.
1184
- 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 });
1185
1383
  // The provider answered (and a paid request was paid): a host callback that throws must not lose the answer or
1186
1384
  // its booking.
1187
1385
  try {
@@ -1190,6 +1388,47 @@ export async function startModelProxy(options, key) {
1190
1388
  catch (error) {
1191
1389
  say(`model proxy (${policy.id}): onResponse threw`, { error: String(error?.message ?? error).slice(0, 200) });
1192
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
+ }
1193
1432
  // Its ids are kept before its body is read: from here the provider has seen it, whatever cuts it off.
1194
1433
  ids = route.free ? undefined : providerIdsOf(upstream.headers);
1195
1434
  reported = route.free ? undefined : reportedCostOf(upstream.headers);
@@ -1350,6 +1589,12 @@ export async function startModelProxy(options, key) {
1350
1589
  // Whether `usd` is a figure the provider gave (an error answer's nothing included), not one this proxy made up.
1351
1590
  let own = false;
1352
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;
1353
1598
  // A client may leave once it has read the response's usage (Codex does, at the completion event) while the provider
1354
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
1355
1600
  // in it, the cost is unknown, as for any answer cut short.
@@ -1374,27 +1619,68 @@ export async function startModelProxy(options, key) {
1374
1619
  }
1375
1620
  else {
1376
1621
  let unread = false;
1622
+ const kept = length <= USAGE_WINDOW ? tail : `${head}\n${lastOf(tail)}`;
1377
1623
  try {
1378
- usage = policy.usageOf(length <= USAGE_WINDOW ? tail : `${head}\n${lastOf(tail)}`, body);
1624
+ usage = policy.usageOf(kept, body);
1379
1625
  }
1380
1626
  catch (error) {
1381
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) });
1382
1628
  usage = { input: 0, output: 0, cacheRead: 0 };
1383
1629
  unread = true;
1384
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
+ };
1385
1646
  if (!usage) {
1386
1647
  usage = { input: 0, output: 0, cacheRead: 0 };
1387
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)" : ""}`);
1388
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 });
1389
1673
  try {
1390
- 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;
1391
1677
  }
1392
1678
  catch (error) {
1393
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) });
1394
1680
  usd = null;
1395
1681
  }
1396
1682
  // What the gateway says it cost is what was paid; the table's figure stays beside it, to audit the table.
1397
- if (reported !== undefined) {
1683
+ if (reported !== undefined && refusedIn === undefined) {
1398
1684
  tableUsd = usd;
1399
1685
  usd = reported;
1400
1686
  own = true;
@@ -1408,11 +1694,12 @@ export async function startModelProxy(options, key) {
1408
1694
  const stopped = stoppedByClient && usd === null ? { stoppedAfterBytes: streamed, ...(hiddenTokens > 0 ? { stoppedHiddenTokens: hiddenTokens, stoppedReasoningBytes: sentOf.bytes("reasoning") } : {}) } : {};
1409
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
1410
1696
  // content, and the part of its hidden reasoning budget that did not stream, max(0, budget - the reasoning sent).
1411
- const ended = stoppedByClient && usd === null ? { end: "stopped", streamedTokens: streamed + Math.max(0, hiddenTokens - sentOf.bytes("reasoning")) }
1412
- : !seen ? (isConnectCode(failedCode) ? { end: "nothing", label: "never_left" } : { end: "lost", label: "error_before" })
1413
- : !seen.ok ? (isGatewayTimeout(began?.status ?? 0) ? { end: "lost", label: "gateway_timeout" } : { end: "nothing", label: "status" })
1414
- : !answered && usd === null ? { end: "lost", label: "error_after", began: true }
1415
- : { 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 }) };
1416
1703
  await hooks.afterRequest({ ...usage, usd, ...(own ? {} : { estimated: true }), ...(tableUsd === undefined ? {} : { tableUsd }), ...(ids ? { providerIds: ids } : {}), ...stopped }, ticket, ended);
1417
1704
  }
1418
1705
  catch (error) {