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

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 (52) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/dist/host/index.d.ts +2 -4
  3. package/dist/host/index.js +2 -3
  4. package/dist/host/overhead.d.ts +42 -0
  5. package/dist/host/overhead.js +84 -10
  6. package/dist/host/proxy.d.ts +34 -15
  7. package/dist/host/proxy.js +99 -25
  8. package/dist/index.d.ts +2 -1
  9. package/dist/index.js +1 -0
  10. package/dist/kernel/cap/index.d.ts +4 -4
  11. package/dist/kernel/cap/index.js +3 -3
  12. package/dist/kernel/cap/port.d.ts +14 -3
  13. package/dist/kernel/cap/port.js +29 -16
  14. package/dist/kernel/cap/price.d.ts +31 -6
  15. package/dist/kernel/cap/price.js +49 -15
  16. package/dist/kernel/cap/rule.d.ts +11 -1
  17. package/dist/kernel/cap/rule.js +30 -3
  18. package/dist/kernel/cap/run-cap.d.ts +9 -2
  19. package/dist/kernel/cap/run-cap.js +8 -3
  20. package/dist/kernel/cap/types.d.ts +11 -5
  21. package/dist/kernel/registry/computer-surface.generated.d.ts +9 -0
  22. package/dist/kernel/registry/computer-surface.generated.js +618 -0
  23. package/dist/kernel/registry/computer.d.ts +14 -0
  24. package/dist/kernel/registry/computer.js +75 -0
  25. package/dist/kernel/registry/defs.d.ts +1 -4
  26. package/dist/kernel/registry/defs.js +1 -13
  27. package/dist/kernel/registry/handoff.js +4 -4
  28. package/dist/kernel/registry/hands.d.ts +22 -115
  29. package/dist/kernel/registry/hands.js +0 -2
  30. package/dist/kernel/registry/index.d.ts +4 -4
  31. package/dist/kernel/registry/index.js +5 -5
  32. package/dist/kernel/registry/registry.d.ts +4 -5
  33. package/dist/kernel/registry/registry.js +27 -29
  34. package/dist/kernel/types.d.ts +10 -2
  35. package/dist/process/tools.d.ts +5 -1
  36. package/dist/process/tools.js +62 -8
  37. package/dist/run-booking.d.ts +3 -0
  38. package/dist/run-booking.js +7 -0
  39. package/dist/runner.d.ts +21 -2
  40. package/dist/runner.js +126 -11
  41. package/dist/testing.d.ts +6 -2
  42. package/dist/testing.js +5 -3
  43. package/dist/tool-deferral.d.ts +12 -0
  44. package/dist/tool-deferral.js +17 -0
  45. package/dist/types.d.ts +83 -39
  46. package/package.json +2 -2
  47. package/dist/host/mcp-route.d.ts +0 -14
  48. package/dist/host/mcp-route.js +0 -125
  49. package/dist/kernel/registry/desktop.d.ts +0 -11
  50. package/dist/kernel/registry/desktop.js +0 -90
  51. package/dist/kernel/registry/phone.d.ts +0 -15
  52. package/dist/kernel/registry/phone.js +0 -135
@@ -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,10 @@ const capRefusal = (error) => {
27
26
  const fields = error;
28
27
  return fields?.code === SPEND_CAP_REACHED || fields?.refusal === SPEND_CAP_REACHED;
29
28
  };
29
+ /** What one provider-native web search costs, in USD, beside the tokens: $10 per 1,000 searches (Anthropic's "Web search tool"
30
+ * and OpenAI's "Web search (all models)" list the same price). The one figure every fee reads: the proxy policies of the
31
+ * Claude and Codex harnesses and the runner's hosted search. */
32
+ export const NATIVE_SEARCH_USD = 0.01;
30
33
  /** The longest a response's text may run with no event boundary before the reasoning count lets it go (a body that is
31
34
  * not a stream of events, read whole as one). */
32
35
  const EVENT_MAX_CHARS = 1 << 22;
@@ -395,14 +398,44 @@ export function hostHeaderProblems(headers) {
395
398
  }
396
399
  return problems;
397
400
  }
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
401
  const UNSAFE_PATH = /[^A-Za-z0-9/_.\-?=&]|\.\.|\/\/|^[^/]|\?.*\?/;
403
402
  const MAX_BODY = 32 * 1024 * 1024;
404
403
  /** How much of a response's start and end the proxy keeps to read its usage from. */
405
404
  const USAGE_WINDOW = 64 * 1024;
405
+ /** The last `"<key>": {...}` object in `text`, parsed: how a policy reads a field of an answer's terminal event when the
406
+ * event's line was longer than USAGE_WINDOW, so the proxy kept only its end. JSON may put whitespace on either side of
407
+ * the colon (a Python gateway's `json.dumps` writes `"usage": {`), and the client parses the event whatever its spacing,
408
+ * so this reads it too: a usage the harness counted is never booked at an unknown cost for its spacing. A key's quoted
409
+ * name inside a JSON string is escaped (`\"usage\"`), so it never reads as one. Undefined when there is none, or the
410
+ * last one does not close in `text` or does not parse. */
411
+ export function lastObjectOf(text, key) {
412
+ const marks = new RegExp(`"${key.replace(/[^A-Za-z0-9_]/g, "")}"\\s*:\\s*\\{`, "g");
413
+ let open = -1;
414
+ for (let found = marks.exec(text); found; found = marks.exec(text))
415
+ open = found.index + found[0].length - 1;
416
+ if (open < 0)
417
+ return undefined;
418
+ let depth = 0;
419
+ for (let i = open; i < text.length; i++) {
420
+ const c = text[i];
421
+ if (c === "\"") {
422
+ for (i++; i < text.length && text[i] !== "\""; i++)
423
+ if (text[i] === "\\")
424
+ i++;
425
+ }
426
+ else if (c === "{")
427
+ depth++;
428
+ else if (c === "}" && --depth === 0) {
429
+ try {
430
+ return JSON.parse(text.slice(open, i + 1));
431
+ }
432
+ catch {
433
+ return undefined;
434
+ }
435
+ }
436
+ }
437
+ return undefined;
438
+ }
406
439
  /** How long an answer the provider stopped on its content filter is still read after its client left, or the proxy began
407
440
  * to close, so the request is booked at the usage its end reports; past it, it is cut off as any other. */
408
441
  const FILTERED_DRAIN_MS = 5_000;
@@ -699,25 +732,31 @@ export async function startModelProxy(options, key) {
699
732
  res.writeHead(status, { "content-type": "application/json", connection: "close" });
700
733
  res.end(JSON.stringify({ error: { message, type: "agentrun_proxy", ...(code ? { code } : {}) } }));
701
734
  };
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 } : {}) });
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. */
704
738
  const serve = async (req, res) => {
739
+ const taken = {};
740
+ try {
741
+ await serveRequest(req, res, taken);
742
+ }
743
+ finally {
744
+ if (taken.note !== undefined) {
745
+ const note = taken.note;
746
+ taken.note = undefined;
747
+ try {
748
+ hooks.noteReturned?.(note);
749
+ }
750
+ catch (error) {
751
+ say(`model proxy (${policy.id}): the host's note could not be given back`, { error: String(error?.message ?? error).slice(0, 200) });
752
+ }
753
+ }
754
+ }
755
+ };
756
+ const serveRequest = async (req, res, taken) => {
705
757
  // A request refused before its body is read is drained, so its client gets the answer instead of a reset.
706
758
  res.once("finish", () => { if (!req.complete)
707
759
  req.resume(); });
708
- const path = req.url ?? "";
709
- if (options.mcp && OAUTH_PATH.test(path)) {
710
- res.writeHead(404, { "content-length": "0" });
711
- return res.end();
712
- }
713
- const mcp = mcpDoor ? MCP_PATH.exec(path) : null;
714
- if (mcp) {
715
- if (!sameKey(policy.keyOf(req.headers), key))
716
- return refuse(res, 401, "this session's key is required", req);
717
- if (closing)
718
- return refuse(res, 503, "the model proxy is closing", req);
719
- return mcpDoor(mcp[1], req, res);
720
- }
721
760
  let route;
722
761
  let query;
723
762
  try {
@@ -752,7 +791,7 @@ export async function startModelProxy(options, key) {
752
791
  let body;
753
792
  const headers = { "content-type": "application/json" };
754
793
  try {
755
- body = policy.apply(parseStrict(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks))), route, host === undefined ? {} : { host });
794
+ body = await policy.apply(parseStrict(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks))), route, host === undefined ? {} : { host });
756
795
  // The listed headers, as the policy keeps them (or refuses them), before the runner is asked.
757
796
  for (const name of route.headers ?? []) {
758
797
  const value = req.headers[name.toLowerCase()];
@@ -800,6 +839,10 @@ export async function startModelProxy(options, key) {
800
839
  request = {};
801
840
  }
802
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;
803
846
  if (note) {
804
847
  try {
805
848
  const without = body;
@@ -809,6 +852,11 @@ export async function startModelProxy(options, key) {
809
852
  }
810
853
  catch (error) {
811
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 */ }
812
860
  }
813
861
  }
814
862
  }
@@ -853,6 +901,19 @@ export async function startModelProxy(options, key) {
853
901
  say(`model proxy (${policy.id}): the policy could not read the body's output; its worst case is unmeasured`, { error: String(error?.message ?? error).slice(0, 200) });
854
902
  inputTokensMax = undefined;
855
903
  }
904
+ // What it may charge beside its tokens (a hosted tool's per-use fees), held with them. One the policy cannot bound
905
+ // leaves its worst case unknown, as an unmeasured input does.
906
+ let feeUsd = 0;
907
+ try {
908
+ const fee = policy.feeMaxUsd ? policy.feeMaxUsd(body) : 0;
909
+ if (figure(fee) === undefined)
910
+ throw new Error(`no bound on its fees (${String(fee)})`);
911
+ feeUsd = fee;
912
+ }
913
+ catch (error) {
914
+ say(`model proxy (${policy.id}): the request's fees have no bound; its worst case is unmeasured`, { error: String(error?.message ?? error).slice(0, 200) });
915
+ inputTokensMax = undefined;
916
+ }
856
917
  // The provider's credential and its headers come before the runner is asked: a request that could not be sent is
857
918
  // refused without being admitted, so it is never booked and spends no turn.
858
919
  let credential = "";
@@ -930,14 +991,20 @@ export async function startModelProxy(options, key) {
930
991
  }
931
992
  // This request's own admission, handed back to its booking (requests may be in flight together).
932
993
  let ticket;
994
+ // The note, if this request carries it, is its admission's from here: told once admitted, given back by a refusal.
995
+ if (noted)
996
+ taken.note = undefined;
933
997
  try {
934
998
  if (!route.free)
935
999
  ticket = await hooks.beforeRequest({
936
- // A side call: on another model than the session's, or the host's own (it counts toward no typical request).
937
- model: asked, inputTokensMax, ...(asked !== model || host !== undefined ? { side: true } : {}),
1000
+ // A side call: on another model than the session's, or the host's own (it counts toward no typical request). One on
1001
+ // 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.
1003
+ model: asked, inputTokensMax, ...(asked !== model || host !== undefined ? { side: true } : {}), ...(!answering && host === undefined ? { unanswered: true } : {}),
938
1004
  ...(noted ? { noted: true, ...(inputTokensMaxWithoutNote === undefined ? {} : { inputTokensMaxWithoutNote }) } : {}),
939
1005
  ...(outputTokensAsked === undefined ? {} : { outputTokensAsked }),
940
1006
  ...(outputTokensLeast === undefined ? {} : { outputTokensLeast }),
1007
+ ...(feeUsd > 0 ? { feeUsd } : {}),
941
1008
  ...(host === undefined ? {} : { host }),
942
1009
  ...(inputTokensCounted ? { inputTokensCounted: true } : {}),
943
1010
  ...(options.route === undefined ? {} : { route: options.route }),
@@ -950,7 +1017,8 @@ export async function startModelProxy(options, key) {
950
1017
  /** An admitted request that is not sent after all: refused to its client, and released, booked at nothing, so the
951
1018
  * runner's count agrees. */
952
1019
  const release = async (status, message) => {
953
- refuse(res, status, message, req);
1020
+ if (!res.destroyed)
1021
+ refuse(res, status, message, req);
954
1022
  if (!route.free) {
955
1023
  try {
956
1024
  await hooks.afterRequest({ input: 0, output: 0, cacheRead: 0, usd: 0 }, ticket, { end: "nothing", label: "never_left" });
@@ -963,6 +1031,12 @@ export async function startModelProxy(options, key) {
963
1031
  // Admitted while the proxy was closing, and never sent.
964
1032
  if (closing)
965
1033
  return release(503, "the model proxy is closing");
1034
+ // Admitted after its client left (a stop or a cancel while its hold was made durable): never sent, booked at nothing.
1035
+ // Sent anyway it would be a paid answer for no one, and one never stopped (its client's close came before the proxy
1036
+ // listened for it, below), booked only once the provider ended it: past the run's end, which then read the request as
1037
+ // cut at an unknown cost. Nothing from here to that listener waits, so a client that leaves later is heard there.
1038
+ if (res.destroyed || req.socket.destroyed)
1039
+ return release(499, "the client left before its request was sent");
966
1040
  // Admitted only without the note (its bytes did not fit what is left of the cap): the body as the client sent it.
967
1041
  if (typeof ticket === "object" && ticket !== null && ticket.noteDropped === true) {
968
1042
  if (!plain || plainSent === undefined)
@@ -1301,7 +1375,7 @@ export async function startModelProxy(options, key) {
1301
1375
  else {
1302
1376
  let unread = false;
1303
1377
  try {
1304
- usage = policy.usageOf(length <= USAGE_WINDOW ? tail : `${head}\n${lastOf(tail)}`);
1378
+ usage = policy.usageOf(length <= USAGE_WINDOW ? tail : `${head}\n${lastOf(tail)}`, body);
1305
1379
  }
1306
1380
  catch (error) {
1307
1381
  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) });
package/dist/index.d.ts CHANGED
@@ -2,6 +2,7 @@ export { answeredUnpriced, createHarnessRunner, modelPortFor, sessionSpendOf, SU
2
2
  export { runBooking, type RunSessions } from "./run-booking.js";
3
3
  export type { Admission, BeforeRequest, Refusal, HarnessRunner, HarnessRunnerOptions, InFlight, ModelBooking, ModelPortEvent, ModelPortOptions, SessionCost } from "./runner.js";
4
4
  export { HarnessRunError, SessionFenced, TurnParked } from "./errors.js";
5
+ export { CODEMODE, DEFER_CATALOG_OVER, defersCatalog, isCatalogName, META_TOOLS, TOOLS_CALL, TOOLS_SEARCH } from "./tool-deferral.js";
5
6
  export { toolSchemaProblems } from "./schema-check.js";
6
7
  export { READ_SKILL_FILE, readSkillFileTool, SKILL_BYTES, skillProblems } from "./skill-files.js";
7
8
  export type { HostSkill, SkillFileList } from "./skill-files.js";
@@ -9,4 +10,4 @@ export type { HarnessRunReason } from "./errors.js";
9
10
  export { CONTENT_FILTERED, HOST_RESULT_MAX_CHARS, hostedTool } from "./types.js";
10
11
  export { bookRequest, isConnectCode, isGatewayTimeout, rejectionCode } from "./booking.js";
11
12
  export type { Booked, Ended, Priced } from "./booking.js";
12
- export type { AdapterCapabilities, AdapterEvent, AdapterSession, AgentAdapter, AdapterFacts, GateAnswer, GateCall, SessionPort, Wire, HarnessEvent, HostTool, McpCallResult, McpClient, McpTool, ToolImage, JsonValue, ModelPort, ModelTicket, ModelRequest, ModelUsage, NoteRequest, NodeRequest, SessionIO, SessionMcp, SessionRecord, SessionSpec, SessionState, SessionStore, SessionWriter, TurnStatus, } from "./types.js";
13
+ export type { AdapterEvent, AdapterSession, AgentAdapter, AdapterFacts, GateAnswer, GateCall, SessionPort, Wire, HarnessEvent, HostTool, McpCallResult, McpTool, NestedCalls, NestedResult, ToolImage, JsonValue, ModelPort, ModelTicket, ModelRequest, ModelUsage, NoteRequest, NodeRequest, SessionIO, SessionRecord, SessionSpec, SessionState, SessionStore, SessionWriter, ToolPermission, TurnStatus, } from "./types.js";
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  export { answeredUnpriced, createHarnessRunner, modelPortFor, sessionSpendOf, SUBMIT_TOOL, RUNNER_RECORDS } from "./runner.js";
2
2
  export { runBooking } from "./run-booking.js";
3
3
  export { HarnessRunError, SessionFenced, TurnParked } from "./errors.js";
4
+ export { CODEMODE, DEFER_CATALOG_OVER, defersCatalog, isCatalogName, META_TOOLS, TOOLS_CALL, TOOLS_SEARCH } from "./tool-deferral.js";
4
5
  export { toolSchemaProblems } from "./schema-check.js";
5
6
  export { READ_SKILL_FILE, readSkillFileTool, SKILL_BYTES, skillProblems } from "./skill-files.js";
6
7
  export { CONTENT_FILTERED, HOST_RESULT_MAX_CHARS, hostedTool } from "./types.js";
@@ -1,8 +1,8 @@
1
1
  export { CapRefused, createCap, DECISION_IMAGE_TOKENS, DECISION_OUTPUT_TOKENS, DecisionPriceUnreadable, END_MARK_WAIT_MS, END_NOT_WRITTEN, MARK_NOT_WRITTEN, openCap } from "./admit.js";
2
- export { capRule, noteFor, type Judged, type JudgeState, type NoteState } from "./rule.js";
3
- export { beforeRequestOf, type BeforeRequestOptions } from "./port.js";
2
+ export { capRule, noteFor, requestFigures, type Judged, type JudgeState, type NoteState } from "./rule.js";
3
+ export { beforeRequestOf, capRequestOf, type BeforeRequestOptions, type PricedRequest } from "./port.js";
4
4
  export { DECISION_SESSION, overCapOf, paidCalls, runCap, TOOL_SESSION, type RunCap, type RunCapOptions, type RunDecisions, type RunTools } from "./run-cap.js";
5
- export { ANSWER_TOKENS_LEAST, CACHE_WARM_MS, CAP_TOLERANCE, FIT_TOLERANCE, STOP_ALLOWANCE_TOKENS, THINKING_BUDGET_LEAST, expectedInput, inputBound, mostOutput, pricingOf, ratesFor, requestPrice } from "./price.js";
5
+ export { ANSWER_TOKENS_LEAST, CACHE_WARM_MS, CAP_TOLERANCE, FIT_TOLERANCE, STOP_ALLOWANCE_TOKENS, THINKING_BUDGET_LEAST, expectedInput, inputBound, mostOutput, pricingOf, RECENT_REQUESTS_KEPT, recentAfter, ratesFor, requestPrice, warmFrom } from "./price.js";
6
6
  export { CAP_REFUSAL_CODE, SPEND_CAP_REACHED, SUGGESTED_RAISE_FACTOR, centsMoney, leastMoney, money, OVER_CAP_END, overCapEnd, overCapMessage, overCapWords, paidRefusal, raiseFigure, raiseTo, spentMoney, suggestedRaise } from "./words.js";
7
7
  export { checkRaise, followUpOf, parkOf, takeRaises, type BudgetPending, type Park, type RaiseCheck, type RaiseState } from "./park.js";
8
8
  export { WRAP_UP_FACTOR, WRAP_UP_LEAST_FACTOR, WRAP_UP_STEP0_ANSWER_TOKENS, typicalCost, wrapUpDue, wrapUpWords } from "./wrap-up.js";
@@ -11,4 +11,4 @@ export { memoryMarks, type CapMark, type CapMarks, type EndMark, type StartMark,
11
11
  export { ownCostsOf, spendOf, toldIn, type Spend } from "./recover.js";
12
12
  export { StepNotHeld, StepNotSettled } from "./ledger.js";
13
13
  export { reasoningBytes, stoppedTokens, streamedBytes } from "./stopped.js";
14
- export type { Admission, Cap, CapMode, CapModel, CapOptions, CapRequest, DecisionCapRequest, ModelCapRequest, ModelPrice, PriceRates, PriceTier, Previous, RefusalFigures, Settled, ToolCapRequest } from "./types.js";
14
+ export type { Admission, Cap, CapMode, CapModel, CapOptions, CapRequest, DecisionCapRequest, ModelCapRequest, ModelPrice, PriceRates, PriceTier, RecentRequest, RefusalFigures, Settled, ToolCapRequest } from "./types.js";
@@ -1,10 +1,10 @@
1
1
  // The kernel cap (kernel tangle 2: the cap lives in the kernel, the same for every harness). Not exported from the
2
2
  // package's index until the cutover: its tests import it from dist/kernel/cap/.
3
3
  export { CapRefused, createCap, DECISION_IMAGE_TOKENS, DECISION_OUTPUT_TOKENS, DecisionPriceUnreadable, END_MARK_WAIT_MS, END_NOT_WRITTEN, MARK_NOT_WRITTEN, openCap } from "./admit.js";
4
- export { capRule, noteFor } from "./rule.js";
5
- export { beforeRequestOf } from "./port.js";
4
+ export { capRule, noteFor, requestFigures } from "./rule.js";
5
+ export { beforeRequestOf, capRequestOf } from "./port.js";
6
6
  export { DECISION_SESSION, overCapOf, paidCalls, runCap, TOOL_SESSION } from "./run-cap.js";
7
- export { ANSWER_TOKENS_LEAST, CACHE_WARM_MS, CAP_TOLERANCE, FIT_TOLERANCE, STOP_ALLOWANCE_TOKENS, THINKING_BUDGET_LEAST, expectedInput, inputBound, mostOutput, pricingOf, ratesFor, requestPrice } from "./price.js";
7
+ export { ANSWER_TOKENS_LEAST, CACHE_WARM_MS, CAP_TOLERANCE, FIT_TOLERANCE, STOP_ALLOWANCE_TOKENS, THINKING_BUDGET_LEAST, expectedInput, inputBound, mostOutput, pricingOf, RECENT_REQUESTS_KEPT, recentAfter, ratesFor, requestPrice, warmFrom } from "./price.js";
8
8
  export { CAP_REFUSAL_CODE, SPEND_CAP_REACHED, SUGGESTED_RAISE_FACTOR, centsMoney, leastMoney, money, OVER_CAP_END, overCapEnd, overCapMessage, overCapWords, paidRefusal, raiseFigure, raiseTo, spentMoney, suggestedRaise } from "./words.js";
9
9
  export { checkRaise, followUpOf, parkOf, takeRaises } from "./park.js";
10
10
  export { WRAP_UP_FACTOR, WRAP_UP_LEAST_FACTOR, WRAP_UP_STEP0_ANSWER_TOKENS, typicalCost, wrapUpDue, wrapUpWords } from "./wrap-up.js";
@@ -1,13 +1,14 @@
1
1
  import type { BeforeRequest } from "../../runner.js";
2
- import type { CapMode, CapModel, Previous } from "./types.js";
2
+ import type { CapMode, CapModel, ModelCapRequest, RecentRequest } from "./types.js";
3
3
  export interface BeforeRequestOptions {
4
4
  /** The run's cap, read before every request. Undefined: no cap, nothing refused. */
5
5
  capUsd(): number | undefined;
6
6
  /** A model as the cap prices it, by its id and the route its request came by (ModelRequest.route; absent, the
7
7
  * session's own): one id two routes price apart is priced as its route books it. Undefined: a model with no price here. */
8
8
  modelOf(id: string, route?: string): CapModel | undefined;
9
- /** The session's previous request on a model, as its usage reported it: none prices the input uncached. */
10
- previousOf?(model: string): Previous | undefined;
9
+ /** The session's recent requests on a model (price.ts recentAfter), by the id the cap prices it under (CapModel.id,
10
+ * which a CLI's request may name otherwise), as their usage reported them: none prices the input uncached. */
11
+ recentOf?(model: string): readonly RecentRequest[];
11
12
  /** What the run spent beside the session's model requests, which the runner's booking does not hold: its priced tools'
12
13
  * charges (null: unknown). The run's spend is the runner's plus this. A figure that is not finite and 0 or more is
13
14
  * unknown too. */
@@ -15,8 +16,18 @@ export interface BeforeRequestOptions {
15
16
  /** What the run's priced tools under way hold, beside the session's requests in flight (null: unknown). A figure that is
16
17
  * not finite and 0 or more is unknown too: the request is refused, never judged as $0 held. */
17
18
  heldUsd?(): number | null;
19
+ /** What the host keeps back beside model request `request` (priced as `asked`) for the steps it may still ask for while
20
+ * it streams (the rule's JudgeState.keepUsd): serve's wrap-up reserve for the session's own requests. Undefined: none. */
21
+ keepBackUsd?(request: Parameters<BeforeRequest>[0], asked: ModelCapRequest): number | undefined;
18
22
  mode?: CapMode;
19
23
  now?: () => number;
20
24
  }
25
+ /** What prices a model request: its model and route, how its input was measured, the output it asks and needs at least,
26
+ * its fee, and whether it is the session's own answer (no side call, no host's request, no unanswered one). */
27
+ export type PricedRequest = Pick<Parameters<BeforeRequest>[0], "model" | "route" | "inputTokensMax" | "inputTokensCounted" | "outputTokensAsked" | "outputTokensLeast" | "feeUsd" | "side" | "host" | "unanswered">;
28
+ /** `request` as the rule prices it: the one place a request's model and the session's recent requests are chosen for it,
29
+ * so its admission, the wrap-up's note and what the run keeps back to answer (requestFigures) price it alike: its input
30
+ * read from the cache a recent request left warm (price.ts warmFrom), else uncached. */
31
+ export declare function capRequestOf(id: string, request: PricedRequest, options: Pick<BeforeRequestOptions, "modelOf" | "recentOf">): ModelCapRequest;
21
32
  /** The host's beforeRequest for a CLI harness's session: the runner's spend and holds, judged by the one rule. */
22
33
  export declare function beforeRequestOf(options: BeforeRequestOptions): BeforeRequest;
@@ -7,6 +7,31 @@ import { SPEND_CAP_REACHED, unmeasured } from "./words.js";
7
7
  const refusalOf = (error) => ({ refuse: error.message, code: error.code, forGood: error.forGood, ...(error.figures ? { figures: error.figures } : {}) });
8
8
  /** A model the host has no price for: refused under a cap, by the rule. */
9
9
  const unpriced = (id) => ({ id, api: "unknown", price: null, outputCeiling: null });
10
+ /** `request` as the rule prices it: the one place a request's model and the session's recent requests are chosen for it,
11
+ * so its admission, the wrap-up's note and what the run keeps back to answer (requestFigures) price it alike: its input
12
+ * read from the cache a recent request left warm (price.ts warmFrom), else uncached. */
13
+ export function capRequestOf(id, request, options) {
14
+ const model = options.modelOf(request.model, request.route) ?? unpriced(request.model);
15
+ // A request the host sends beside the harness's own (its host label: a learned workflow's node), a side call, or one
16
+ // that is no answer of the turn (a title, a summary, a child's) is another conversation's prompt: nothing of the
17
+ // session's cache is read for it, so it is priced as a cache miss.
18
+ // Its bound must be measured as the next request's is (a provider's count, or bytes): their difference is no growth.
19
+ // Asked by the model the cap prices it as: a CLI's request names its model as its provider does (openai/gpt-6.1-sol
20
+ // for gpt-6.1-sol), and its recent requests are the same model's whatever the name.
21
+ const mine = request.host === undefined && !request.side && !request.unanswered ? options.recentOf?.(model.id) : undefined;
22
+ const recent = mine?.filter((one) => (one.counted === true) === (request.inputTokensCounted === true));
23
+ return {
24
+ kind: "model",
25
+ id,
26
+ model,
27
+ inputTokens: request.inputTokensMax,
28
+ ...(request.outputTokensAsked === undefined ? {} : { outputAsked: request.outputTokensAsked }),
29
+ ...(request.outputTokensLeast === undefined ? {} : { outputTokensLeast: request.outputTokensLeast }),
30
+ ...(recent?.length ? { recent } : {}),
31
+ ...(isFigure(request.feeUsd) && request.feeUsd > 0 ? { feeUsd: request.feeUsd } : {}),
32
+ ...(request.side ? { side: true } : {}),
33
+ };
34
+ }
10
35
  /** The host's beforeRequest for a CLI harness's session: the runner's spend and holds, judged by the one rule. */
11
36
  export function beforeRequestOf(options) {
12
37
  const mode = options.mode ?? "expected";
@@ -20,21 +45,7 @@ export function beforeRequestOf(options) {
20
45
  // any paid step, so every refusable step after it sees it. Only a figure is money: one that is not goes to the rule.
21
46
  if (request.paid?.owed && isFigure(request.feeUsd ?? 0))
22
47
  return { holdUsd: request.feeUsd ?? 0 };
23
- const model = options.modelOf(request.model, request.route) ?? unpriced(request.model);
24
- // A request the host sends beside the harness's own (its host label: a learned workflow's node) is another
25
- // conversation's prompt: nothing of the session's cache is read for it, so it is priced as a cache miss.
26
- const previous = request.host === undefined ? options.previousOf?.(request.model) : undefined;
27
- const asked = {
28
- kind: "model",
29
- id: `turn-${request.turn}`,
30
- model,
31
- inputTokens: request.inputTokensMax,
32
- ...(request.outputTokensAsked === undefined ? {} : { outputAsked: request.outputTokensAsked }),
33
- ...(request.outputTokensLeast === undefined ? {} : { outputTokensLeast: request.outputTokensLeast }),
34
- ...(previous ? { previous } : {}),
35
- ...(isFigure(request.feeUsd) && request.feeUsd > 0 ? { feeUsd: request.feeUsd } : {}),
36
- ...(request.side ? { side: true } : {}),
37
- };
48
+ const asked = capRequestOf(`turn-${request.turn}`, request, options);
38
49
  // Each request in flight at what the host held for it, else its worst case at the limit it was admitted with; one with
39
50
  // neither (no hold, no price or no measure) cannot be kept within the cap: refused for good, as an unmeasured input.
40
51
  let inFlight = 0;
@@ -67,7 +78,9 @@ export function beforeRequestOf(options) {
67
78
  }
68
79
  const judge = (input) => {
69
80
  try {
70
- const judged = capRule.judge({ ...asked, inputTokens: input }, { capUsd, spentUsd, heldUsd, mode, now: now() });
81
+ const sized = { ...asked, inputTokens: input };
82
+ const keepUsd = options.keepBackUsd?.(request, sized);
83
+ const judged = capRule.judge(sized, { capUsd, spentUsd, heldUsd, mode, now: now(), ...(keepUsd === undefined ? {} : { keepUsd }) });
71
84
  return { holdUsd: judged.heldUsd, boundUsd: judged.boundUsd, ...(judged.outputTokensMax === undefined ? {} : { outputTokensMax: judged.outputTokensMax }), stoppedUsd: judged.stoppedUsd };
72
85
  }
73
86
  catch (error) {
@@ -1,4 +1,4 @@
1
- import type { CapMode, ModelCapRequest, ModelPrice, PriceRates, Previous } from "./types.js";
1
+ import type { CapMode, ModelCapRequest, ModelPrice, PriceRates, RecentRequest } from "./types.js";
2
2
  /** How long after a request ended the next one in its conversation is expected to read its cache: 4 minutes, inside
3
3
  * Anthropic's 5. */
4
4
  export declare const CACHE_WARM_MS: number;
@@ -27,13 +27,38 @@ export declare function ratesFor(price: ModelPrice, inputTokens: number): PriceR
27
27
  * the input and cache-write rates, and its output at the output rate, each at the rates of the tier its whole input
28
28
  * passes (ratesFor). A hold, a worst case and a booking the cap prices are so never under what the provider bills. */
29
29
  export declare function pricingOf(price: ModelPrice): Pricing;
30
- /** The input of a request of `bound` tokens on `model` expected after `previous`, at `now`: its cache read, and its input
31
- * after the cache plus what the body grew by at full price. Undefined (all of it uncached) with no previous request, one
32
- * on another model, one that ended CACHE_WARM_MS or more ago, or a clock that reads before its end. */
33
- export declare function expectedInput(bound: number, previous: Previous | undefined, now: number, model: string): InputParts | undefined;
30
+ /** How many of a session's recent requests it keeps (recentAfter), the newest: enough for a conversation's last request
31
+ * to outlast the smaller requests a CLI sends between two of its own. Fewer only prices a request colder, never under. */
32
+ export declare const RECENT_REQUESTS_KEPT = 16;
33
+ /** The recent request whose cache a request of `bound` tokens on `model` is expected to read at `now`: of `recent`, those
34
+ * on its model that ended under CACHE_WARM_MS ago (by a clock that does not read before their end) with a bound no bigger
35
+ * than its own (a conversation only grows between its own requests), the biggest, the newest of equal ones. So a smaller
36
+ * request between two of a conversation's own (a CLI's side request while a tool runs, a child's, a summary) leaves the
37
+ * conversation's next request warm from its last, and a conversation that compacted is warm again from its first request
38
+ * after the compaction. None: priced uncached. */
39
+ export declare function warmFrom(bound: number, recent: readonly RecentRequest[] | undefined, now: number, model: string): RecentRequest | undefined;
40
+ /** The input of a request of `bound` tokens on `model` expected at `now` after `recent`: the cache of the request warmFrom
41
+ * picks at the cache-read price, and that request's input after the cache plus what the body grew by since at full
42
+ * price. Undefined (all of it uncached) when it picks none.
43
+ *
44
+ * Why a warm price opens no way past the cap. It is a guess: the request picked may be another conversation's whose
45
+ * bound happened to fit, or its cache may be gone. The guess lowers only what the request is held at (requestPrice's
46
+ * cost, never above its worst), never its worst: the whole bound uncached at the dearer of the input and cache-write
47
+ * prices whichever request was picked, the output limited to what it was admitted at. So a request's real cost is at
48
+ * most its hold plus its bound (Judged.boundUsd): a guess too low adds that much at most, the cache miss "expected" has
49
+ * always allowed and serve reports as the run's overshoot bound. The bound is counted wherever the run's room is read
50
+ * while the request is out (the wrap-up's gate and note count it at hold + bound, sessionSpendOf; a claim lost with it
51
+ * open books it cut at both); a CLI's own request admitted with its host's keep-back is limited so its worst leaves the
52
+ * keep-back free (rule.ts judgeModel), so even a miss stays under the cap; and once a request answers, its real cost
53
+ * is booked and the next admission reads it. "strict" reads no cache: every request held at its worst. */
54
+ export declare function expectedInput(bound: number, recent: readonly RecentRequest[] | undefined, now: number, model: string): InputParts | undefined;
55
+ /** The session's recent requests once `ended` has answered: `ended`, and those that ended under CACHE_WARM_MS before it
56
+ * but one on its model, measured its way and of its bound (`ended` is the newer of the two); the newest
57
+ * RECENT_REQUESTS_KEPT. None is dropped for being smaller or bigger than `ended`: warmFrom picks for each request. */
58
+ export declare function recentAfter(recent: readonly RecentRequest[], ended: RecentRequest): RecentRequest[];
34
59
  /** A request priced under `mode`: `cost(output)`, what it is held at (its expected input, never more than uncached), and
35
60
  * `worst(output)`, its input uncached; each with its hosted tools' most fee. */
36
- export declare function requestPrice(pricing: Pricing, bound: number, previous: Previous | undefined, now: number, mode: CapMode, model: string, feeUsd?: number): {
61
+ export declare function requestPrice(pricing: Pricing, bound: number, recent: readonly RecentRequest[] | undefined, now: number, mode: CapMode, model: string, feeUsd?: number): {
37
62
  cost(output: number): number;
38
63
  worst(output: number): number;
39
64
  };
@@ -1,8 +1,8 @@
1
1
  // The kernel cap's one pricing rule, the same for every harness. A request's input bound (its measured bytes, what its
2
2
  // provider adds, what its hosted tools read) is priced at the dearer of the input and cache-write prices; under "expected"
3
- // the previous request's cache counts at the cache-read price when it ended under CACHE_WARM_MS ago on the same model, so
4
- // only a cache miss can pass the cap, by at most the request's bound; under "strict" every token uncached. Its output is
5
- // held at what it is sent with, its thinking budget included.
3
+ // the cache of one of the session's recent requests (warmFrom) counts at the cache-read price, so only a cache miss can
4
+ // pass the cap, by at most the request's bound; under "strict" every token uncached. Its output is held at what it is
5
+ // sent with, its thinking budget included.
6
6
  import { providerInputOverhead } from "../../host/overhead.js";
7
7
  /** How long after a request ended the next one in its conversation is expected to read its cache: 4 minutes, inside
8
8
  * Anthropic's 5. */
@@ -44,22 +44,56 @@ export function pricingOf(price) {
44
44
  return (parts.cached * read + parts.fresh * fresh + output * rates.output) / 1e6;
45
45
  };
46
46
  }
47
- /** The input of a request of `bound` tokens on `model` expected after `previous`, at `now`: its cache read, and its input
48
- * after the cache plus what the body grew by at full price. Undefined (all of it uncached) with no previous request, one
49
- * on another model, one that ended CACHE_WARM_MS or more ago, or a clock that reads before its end. */
50
- export function expectedInput(bound, previous, now, model) {
51
- if (!previous || previous.model !== model)
52
- return undefined;
53
- const gap = now - previous.endedAt;
54
- if (!(gap >= 0 && gap < CACHE_WARM_MS))
55
- return undefined;
56
- return { cached: previous.cachedTokens, fresh: previous.inputTokens + Math.max(0, bound - previous.boundTokens) };
47
+ /** How many of a session's recent requests it keeps (recentAfter), the newest: enough for a conversation's last request
48
+ * to outlast the smaller requests a CLI sends between two of its own. Fewer only prices a request colder, never under. */
49
+ export const RECENT_REQUESTS_KEPT = 16;
50
+ /** The recent request whose cache a request of `bound` tokens on `model` is expected to read at `now`: of `recent`, those
51
+ * on its model that ended under CACHE_WARM_MS ago (by a clock that does not read before their end) with a bound no bigger
52
+ * than its own (a conversation only grows between its own requests), the biggest, the newest of equal ones. So a smaller
53
+ * request between two of a conversation's own (a CLI's side request while a tool runs, a child's, a summary) leaves the
54
+ * conversation's next request warm from its last, and a conversation that compacted is warm again from its first request
55
+ * after the compaction. None: priced uncached. */
56
+ export function warmFrom(bound, recent, now, model) {
57
+ let best;
58
+ for (const one of recent ?? []) {
59
+ const gap = now - one.endedAt;
60
+ if (one.model !== model || !(gap >= 0 && gap < CACHE_WARM_MS) || !(one.boundTokens <= bound))
61
+ continue;
62
+ if (!best || one.boundTokens > best.boundTokens || (one.boundTokens === best.boundTokens && one.endedAt >= best.endedAt))
63
+ best = one;
64
+ }
65
+ return best;
66
+ }
67
+ /** The input of a request of `bound` tokens on `model` expected at `now` after `recent`: the cache of the request warmFrom
68
+ * picks at the cache-read price, and that request's input after the cache plus what the body grew by since at full
69
+ * price. Undefined (all of it uncached) when it picks none.
70
+ *
71
+ * Why a warm price opens no way past the cap. It is a guess: the request picked may be another conversation's whose
72
+ * bound happened to fit, or its cache may be gone. The guess lowers only what the request is held at (requestPrice's
73
+ * cost, never above its worst), never its worst: the whole bound uncached at the dearer of the input and cache-write
74
+ * prices whichever request was picked, the output limited to what it was admitted at. So a request's real cost is at
75
+ * most its hold plus its bound (Judged.boundUsd): a guess too low adds that much at most, the cache miss "expected" has
76
+ * always allowed and serve reports as the run's overshoot bound. The bound is counted wherever the run's room is read
77
+ * while the request is out (the wrap-up's gate and note count it at hold + bound, sessionSpendOf; a claim lost with it
78
+ * open books it cut at both); a CLI's own request admitted with its host's keep-back is limited so its worst leaves the
79
+ * keep-back free (rule.ts judgeModel), so even a miss stays under the cap; and once a request answers, its real cost
80
+ * is booked and the next admission reads it. "strict" reads no cache: every request held at its worst. */
81
+ export function expectedInput(bound, recent, now, model) {
82
+ const from = warmFrom(bound, recent, now, model);
83
+ return from && { cached: from.cachedTokens, fresh: from.inputTokens + (bound - from.boundTokens) };
84
+ }
85
+ /** The session's recent requests once `ended` has answered: `ended`, and those that ended under CACHE_WARM_MS before it
86
+ * but one on its model, measured its way and of its bound (`ended` is the newer of the two); the newest
87
+ * RECENT_REQUESTS_KEPT. None is dropped for being smaller or bigger than `ended`: warmFrom picks for each request. */
88
+ export function recentAfter(recent, ended) {
89
+ const same = (one) => one.model === ended.model && (one.counted === true) === (ended.counted === true) && one.boundTokens === ended.boundTokens;
90
+ return [...recent.filter((one) => ended.endedAt - one.endedAt < CACHE_WARM_MS && !same(one)), ended].slice(-RECENT_REQUESTS_KEPT);
57
91
  }
58
92
  /** A request priced under `mode`: `cost(output)`, what it is held at (its expected input, never more than uncached), and
59
93
  * `worst(output)`, its input uncached; each with its hosted tools' most fee. */
60
- export function requestPrice(pricing, bound, previous, now, mode, model, feeUsd = 0) {
94
+ export function requestPrice(pricing, bound, recent, now, mode, model, feeUsd = 0) {
61
95
  const worst = (output) => pricing({ cached: 0, fresh: bound }, output) + feeUsd;
62
- const parts = mode === "strict" ? undefined : expectedInput(bound, previous, now, model);
96
+ const parts = mode === "strict" ? undefined : expectedInput(bound, recent, now, model);
63
97
  if (!parts)
64
98
  return { cost: worst, worst };
65
99
  return { cost: (output) => Math.min(pricing(parts, output) + feeUsd, worst(output)), worst };
@@ -1,12 +1,14 @@
1
1
  import type { CapMode, ModelCapRequest, ToolCapRequest } from "./types.js";
2
2
  /** What a judgement reads: the cap (read before this check), the run's spend (null: unknown) and its holds (null:
3
- * unknown). */
3
+ * unknown). `keepUsd`: what the host keeps back beside a model request for the steps it may still ask for while it
4
+ * streams (serve's wrap-up reserve: one typical step and one least answer); judgeModel says how it limits the output. */
4
5
  export type JudgeState = {
5
6
  capUsd: number;
6
7
  spentUsd: number | null;
7
8
  heldUsd: number | null;
8
9
  mode: CapMode;
9
10
  now: number;
11
+ keepUsd?: number;
10
12
  };
11
13
  /** A money figure the cap can count: a finite number of 0 or more. Anything else (null, NaN, Infinity, below 0) is
12
14
  * unknown: it never reads as $0 and never frees room. */
@@ -34,6 +36,14 @@ declare function judge(request: ModelCapRequest | ToolCapRequest, state: JudgeSt
34
36
  export declare const capRule: {
35
37
  judge: typeof judge;
36
38
  };
39
+ /** A main-model request's figures as the cap prices it, for what a run keeps back to answer: its least (an answer at the
40
+ * fewest output tokens the cap admits it at), its step-0 typical cost (its input and a WRAP_UP_STEP0_ANSWER_TOKENS answer,
41
+ * the wrap-up's own) and its worst (its full asked output, its bound included). Undefined when it cannot be priced. */
42
+ export declare function requestFigures(request: ModelCapRequest, mode: CapMode, now: number): {
43
+ leastUsd: number;
44
+ step0Usd: number;
45
+ worstUsd: number;
46
+ } | undefined;
37
47
  /** What the wrap-up reads: the cap, spend and holds as admission counts them, the run's own priced answers on the
38
48
  * request's model, and whether it was told. */
39
49
  export type NoteState = {
@@ -17,10 +17,10 @@ export function priced(request, mode, now) {
17
17
  if (bound === undefined || price === null)
18
18
  return undefined;
19
19
  const asked = outputAsked(request);
20
- const { cost, worst } = requestPrice(pricingOf(price), bound, request.previous, now, mode, request.model.id, request.feeUsd ?? 0);
20
+ const { cost, worst } = requestPrice(pricingOf(price), bound, request.recent, now, mode, request.model.id, request.feeUsd ?? 0);
21
21
  return { asked, cost, worst, least: asked === undefined ? 0 : outputLeast(request, asked) };
22
22
  }
23
- function judgeModel(request, { capUsd, spentUsd: spent, heldUsd: held, mode, now }) {
23
+ function judgeModel(request, { capUsd, spentUsd: spent, heldUsd: held, mode, now, keepUsd }) {
24
24
  if (inputBound(request) === undefined)
25
25
  throw new CapRefused(unmeasured(capUsd), { forGood: true, spentUsd: spent });
26
26
  const price = request.model.price;
@@ -29,7 +29,25 @@ function judgeModel(request, { capUsd, spentUsd: spent, heldUsd: held, mode, now
29
29
  if (request.model.outputCeiling === null && price.output > 0)
30
30
  throw new CapRefused(noCeiling(capUsd), { forGood: true, spentUsd: spent });
31
31
  const p = priced(request, mode, now);
32
- const output = mostOutput(p.cost, p.least, p.asked ?? 0, capUsd - spent - held);
32
+ const left = capUsd - spent - held;
33
+ // The output it is sent with. With a keep-back from its host, first the most whose WORST case (its hold and the cache
34
+ // miss its bound covers, as a request in flight counts in the run's records) leaves `keepUsd` free: a tool call the
35
+ // request makes while it streams then finds room for the steps after it (serve's wrap-up, which counts the request
36
+ // at its worst until it is booked). When even its least and the keep-back do not fit, the run is wrapping up and this
37
+ // request may be its answer: it gets the most what is left buys, as with no keep-back.
38
+ // Why the cap still holds: the first branch only lowers the output, never below the least: cost(out) <= worst(out) <=
39
+ // left - keepUsd <= left. The second is the rule as it was. So every hold is at most what is left, as before; the
40
+ // hold, its bound, what a stop counts and what is booked are priced by the same p at the output sent, unchanged.
41
+ // (The keep-back is kept with a float's tail to spare, so the host's sum of the same figures never reads it as passed.)
42
+ // When the warm guess is wrong (expected mode prices the bound's head as cached from a recent request, and the cache
43
+ // is gone): the hold is too low, and three things still bound the spend. The output is limited to what is sent
44
+ // here, so the request's real cost is at most its worst: its whole bound uncached at the dearer input price plus
45
+ // that output. The first branch admits only a worst that leaves the keep-back free, so a full miss still lands under
46
+ // the cap. Its real cost is then booked at the turn, so the next request is judged on what this one cost, never on
47
+ // its hold. Only the second branch (no keep-back, or a run wrapping up) admits on the hold, and there a miss passes
48
+ // the cap by at most its bound, the overshoot expected mode states; strict mode reads no cache and has none.
49
+ const kept = isFigure(keepUsd) && keepUsd > 0 ? mostOutput(p.worst, p.least, p.asked ?? 0, left - keepUsd - 2 * FIT_TOLERANCE) : undefined;
50
+ const output = kept ?? mostOutput(p.cost, p.least, p.asked ?? 0, left);
33
51
  if (output === undefined) {
34
52
  const { text, figures } = roomRefusal(capUsd, spent, held, p.cost(p.least), p.worst(p.least) - p.cost(p.least));
35
53
  throw new CapRefused(text, { forGood: false, spentUsd: spent, figures });
@@ -71,6 +89,15 @@ function judge(request, state) {
71
89
  }
72
90
  /** The rule's entry, called through this object by every path. */
73
91
  export const capRule = { judge };
92
+ /** A main-model request's figures as the cap prices it, for what a run keeps back to answer: its least (an answer at the
93
+ * fewest output tokens the cap admits it at), its step-0 typical cost (its input and a WRAP_UP_STEP0_ANSWER_TOKENS answer,
94
+ * the wrap-up's own) and its worst (its full asked output, its bound included). Undefined when it cannot be priced. */
95
+ export function requestFigures(request, mode, now) {
96
+ const p = priced(request, mode, now);
97
+ if (!p)
98
+ return undefined;
99
+ return { leastUsd: p.cost(p.least), step0Usd: p.cost(Math.min(p.asked ?? 0, WRAP_UP_STEP0_ANSWER_TOKENS)), worstUsd: p.worst(p.asked ?? p.least) };
100
+ }
74
101
  /** The wrap-up for `request`, the run's next main-model request measured before the note is placed: due under three times
75
102
  * the typical cost (step 0: its input and a 4,096-token answer) or twice its least, not yet told, never for a side call,
76
103
  * and never when the request fits what is left only without the note's bytes. */