@parcha/agentrun-kernel 0.1.0-beta.37 → 0.1.0-beta.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/NOTICE +2 -0
  3. package/dist/booking.d.ts +25 -6
  4. package/dist/booking.js +15 -4
  5. package/dist/host/index.d.ts +4 -5
  6. package/dist/host/index.js +3 -3
  7. package/dist/host/o200k.d.ts +11 -0
  8. package/dist/host/o200k.js +185 -0
  9. package/dist/host/overhead.d.ts +105 -3
  10. package/dist/host/overhead.js +276 -20
  11. package/dist/host/proxy.d.ts +97 -16
  12. package/dist/host/proxy.js +420 -108
  13. package/dist/index.d.ts +6 -5
  14. package/dist/index.js +4 -3
  15. package/dist/kernel/cap/admit.d.ts +5 -8
  16. package/dist/kernel/cap/admit.js +13 -19
  17. package/dist/kernel/cap/free.d.ts +43 -0
  18. package/dist/kernel/cap/free.js +71 -0
  19. package/dist/kernel/cap/index.d.ts +7 -6
  20. package/dist/kernel/cap/index.js +6 -5
  21. package/dist/kernel/cap/marks.d.ts +2 -3
  22. package/dist/kernel/cap/park.d.ts +3 -4
  23. package/dist/kernel/cap/park.js +4 -5
  24. package/dist/kernel/cap/port.d.ts +11 -5
  25. package/dist/kernel/cap/port.js +26 -24
  26. package/dist/kernel/cap/price.d.ts +10 -30
  27. package/dist/kernel/cap/price.js +15 -48
  28. package/dist/kernel/cap/recover.d.ts +1 -2
  29. package/dist/kernel/cap/recover.js +2 -4
  30. package/dist/kernel/cap/rule.d.ts +11 -17
  31. package/dist/kernel/cap/rule.js +37 -19
  32. package/dist/kernel/cap/run-cap.d.ts +25 -10
  33. package/dist/kernel/cap/run-cap.js +78 -35
  34. package/dist/kernel/cap/types.d.ts +11 -27
  35. package/dist/kernel/cap/words.d.ts +13 -8
  36. package/dist/kernel/cap/words.js +23 -14
  37. package/dist/kernel/cap/wrap-up.d.ts +4 -0
  38. package/dist/kernel/cap/wrap-up.js +5 -1
  39. package/dist/kernel/registry/computer-surface.generated.d.ts +1 -1
  40. package/dist/kernel/registry/computer-surface.generated.js +18 -27
  41. package/dist/kernel/registry/computer.d.ts +14 -7
  42. package/dist/kernel/registry/computer.js +64 -16
  43. package/dist/kernel/registry/gate.d.ts +2 -2
  44. package/dist/kernel/registry/gate.js +4 -7
  45. package/dist/kernel/registry/hands.d.ts +4 -5
  46. package/dist/kernel/registry/index.d.ts +1 -1
  47. package/dist/kernel/registry/index.js +1 -1
  48. package/dist/kernel/registry/registry.js +6 -9
  49. package/dist/kernel/types.d.ts +8 -1
  50. package/dist/process/recovery.d.ts +4 -1
  51. package/dist/process/recovery.js +15 -3
  52. package/dist/process/resume.d.ts +5 -2
  53. package/dist/process/resume.js +15 -3
  54. package/dist/process/tools.d.ts +28 -1
  55. package/dist/process/tools.js +102 -5
  56. package/dist/run-booking.d.ts +21 -2
  57. package/dist/run-booking.js +215 -18
  58. package/dist/runner.d.ts +82 -21
  59. package/dist/runner.js +271 -56
  60. package/dist/testing.d.ts +10 -4
  61. package/dist/testing.js +7 -5
  62. package/dist/tool-deferral.d.ts +12 -0
  63. package/dist/tool-deferral.js +17 -0
  64. package/dist/types.d.ts +133 -48
  65. package/dist/types.js +8 -0
  66. package/package.json +5 -3
  67. package/vendor/o200k/LICENSE +61 -0
  68. package/vendor/o200k/o200k_base.tiktoken +199998 -0
  69. package/dist/host/mcp-route.d.ts +0 -14
  70. package/dist/host/mcp-route.js +0 -125
package/dist/index.d.ts CHANGED
@@ -1,12 +1,13 @@
1
- export { answeredUnpriced, createHarnessRunner, modelPortFor, sessionSpendOf, SUBMIT_TOOL, RUNNER_RECORDS } from "./runner.js";
2
- export { runBooking, type RunSessions } from "./run-booking.js";
3
- export type { Admission, BeforeRequest, Refusal, HarnessRunner, HarnessRunnerOptions, InFlight, ModelBooking, ModelPortEvent, ModelPortOptions, SessionCost } from "./runner.js";
1
+ export { answeredUnpriced, costOfParts, createHarnessRunner, CUT_AT_HOLD, modelPortFor, rebooked, sessionSpendOf, SUBMIT_TOOL, RUNNER_RECORDS, turnCostOf } from "./runner.js";
2
+ export { RECORD_WAIT_MS, runBooking, type RunBookingOptions, type RunSessions, WAIT_POLL_FIRST_MS, WAIT_POLL_MOST_MS, WAIT_STALL_MS } from "./run-booking.js";
3
+ export type { Admission, BeforeRequest, Refusal, HarnessRunner, HarnessRunnerOptions, InFlight, ModelBooking, ModelPortEvent, ModelPortOptions, CostParts, SessionCost } from "./runner.js";
4
4
  export { HarnessRunError, SessionFenced, TurnParked } from "./errors.js";
5
+ export { CODEMODE, DEFER_CATALOG_OVER, defersCatalog, isCatalogWire, 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";
8
9
  export type { HarnessRunReason } from "./errors.js";
9
- export { CONTENT_FILTERED, HOST_RESULT_MAX_CHARS, hostedTool } from "./types.js";
10
+ export { CONTENT_FILTERED, HOST_RESULT_MAX_CHARS, hostedTool, PLAN_LIMIT_CODE, PLAN_LIMIT_WORDS } 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, ToolPermission, 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, OwnCalls, SessionIO, SessionRecord, SessionSpec, SessionState, SessionStore, SessionWriter, ToolPermission, TurnStatus, } from "./types.js";
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
- export { answeredUnpriced, createHarnessRunner, modelPortFor, sessionSpendOf, SUBMIT_TOOL, RUNNER_RECORDS } from "./runner.js";
2
- export { runBooking } from "./run-booking.js";
1
+ export { answeredUnpriced, costOfParts, createHarnessRunner, CUT_AT_HOLD, modelPortFor, rebooked, sessionSpendOf, SUBMIT_TOOL, RUNNER_RECORDS, turnCostOf } from "./runner.js";
2
+ export { RECORD_WAIT_MS, runBooking, WAIT_POLL_FIRST_MS, WAIT_POLL_MOST_MS, WAIT_STALL_MS } from "./run-booking.js";
3
3
  export { HarnessRunError, SessionFenced, TurnParked } from "./errors.js";
4
+ export { CODEMODE, DEFER_CATALOG_OVER, defersCatalog, isCatalogWire, 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
- export { CONTENT_FILTERED, HOST_RESULT_MAX_CHARS, hostedTool } from "./types.js";
7
+ export { CONTENT_FILTERED, HOST_RESULT_MAX_CHARS, hostedTool, PLAN_LIMIT_CODE, PLAN_LIMIT_WORDS } from "./types.js";
7
8
  export { bookRequest, isConnectCode, isGatewayTimeout, rejectionCode } from "./booking.js";
@@ -1,6 +1,6 @@
1
1
  import type { CapMarks } from "./marks.js";
2
2
  import { CapRefused, DecisionPriceUnreadable } from "./errors.js";
3
- import type { Cap, CapMode, CapModel, CapOptions, DecisionCapRequest } from "./types.js";
3
+ import type { Cap, CapModel, CapOptions, DecisionCapRequest } from "./types.js";
4
4
  export { CapRefused, DecisionPriceUnreadable };
5
5
  /** A step whose start mark could not be written is not sent. */
6
6
  export declare const MARK_NOT_WRITTEN = "the model request was not sent: its mark could not be written";
@@ -12,15 +12,12 @@ export declare const END_MARK_WAIT_MS = 10000;
12
12
  export declare function openCap(options: CapOptions & {
13
13
  marks: CapMarks;
14
14
  }): Promise<Cap>;
15
- /** The output a decision is expected to take, a question (main's DECISION_OUTPUT_TOKENS). */
16
- export declare const DECISION_OUTPUT_TOKENS = 256;
17
15
  /** An image's input allowance, in tokens (main's DECISION_IMAGE_TOKENS: a 1568 px square at 750 pixels a token). */
18
16
  export declare const DECISION_IMAGE_TOKENS = 3300;
19
- /** A decision held as a model request is, at its fixed output (all of it or refused, never clamped), as main holds it:
20
- * DECISION_OUTPUT_TOKENS a question under "expected", whatever its model's most output (so a model with none is admitted
21
- * so); its model's most completion tokens under "strict" (none, and its output priced: no bound, refused); its images'
22
- * tokens in its input; its fees (per request, per image) beside its tokens. */
23
- export declare function decisionAsk(request: DecisionCapRequest, mode: CapMode): {
17
+ /** A decision held as a model request is, at its worst case, its fixed output all of it or refused, never clamped (its
18
+ * request names no output limit): its model's most completion tokens (none, and its output priced: no bound, refused);
19
+ * its images' tokens in its input; its fees (per request, per image) beside its tokens. */
20
+ export declare function decisionAsk(request: DecisionCapRequest): {
24
21
  model: CapModel;
25
22
  inputTokens: number;
26
23
  output: number | null;
@@ -8,7 +8,7 @@ import { ownCostsOf, spendOf, toldIn } from "./recover.js";
8
8
  import { capRule, noteFor, priced } from "./rule.js";
9
9
  import { CapRefused, DecisionPriceUnreadable } from "./errors.js";
10
10
  export { CapRefused, DecisionPriceUnreadable };
11
- const NO_HOLD = (id) => ({ id, heldUsd: 0, boundUsd: 0, worstUsd: 0, stoppedUsd: () => 0 });
11
+ const NO_HOLD = (id) => ({ id, heldUsd: 0, stoppedUsd: () => 0 });
12
12
  /** A step whose start mark could not be written is not sent. */
13
13
  export const MARK_NOT_WRITTEN = "the model request was not sent: its mark could not be written";
14
14
  /** A step whose end mark did not land within its wait. */
@@ -21,25 +21,20 @@ export async function openCap(options) {
21
21
  const spent = spendOf(read).spentUsd;
22
22
  return createCap({ ...options, spentUsd: options.spentUsd === undefined ? spent : options.spentUsd }, { costs: ownCostsOf(read), told: toldIn(read) });
23
23
  }
24
- /** The output a decision is expected to take, a question (main's DECISION_OUTPUT_TOKENS). */
25
- export const DECISION_OUTPUT_TOKENS = 256;
26
24
  /** An image's input allowance, in tokens (main's DECISION_IMAGE_TOKENS: a 1568 px square at 750 pixels a token). */
27
25
  export const DECISION_IMAGE_TOKENS = 3_300;
28
- /** A decision held as a model request is, at its fixed output (all of it or refused, never clamped), as main holds it:
29
- * DECISION_OUTPUT_TOKENS a question under "expected", whatever its model's most output (so a model with none is admitted
30
- * so); its model's most completion tokens under "strict" (none, and its output priced: no bound, refused); its images'
31
- * tokens in its input; its fees (per request, per image) beside its tokens. */
32
- export function decisionAsk(request, mode) {
26
+ /** A decision held as a model request is, at its worst case, its fixed output all of it or refused, never clamped (its
27
+ * request names no output limit): its model's most completion tokens (none, and its output priced: no bound, refused);
28
+ * its images' tokens in its input; its fees (per request, per image) beside its tokens. */
29
+ export function decisionAsk(request) {
33
30
  if (request.model === "unreadable")
34
31
  throw new DecisionPriceUnreadable();
35
32
  const images = request.images ?? 0;
36
- const output = mode === "strict" ? request.model.outputCeiling : request.questions * DECISION_OUTPUT_TOKENS;
37
- const model = mode === "strict" ? request.model : { ...request.model, outputCeiling: output };
38
33
  const feeUsd = (request.requestUsd ?? 0) + (request.imageUsd ?? 0) * images;
39
- return { model, inputTokens: request.inputTokens + images * DECISION_IMAGE_TOKENS, output, feeUsd };
34
+ return { model: request.model, inputTokens: request.inputTokens + images * DECISION_IMAGE_TOKENS, output: request.model.outputCeiling, feeUsd };
40
35
  }
41
- const asModel = (request, mode) => {
42
- const { model, inputTokens, output, feeUsd } = decisionAsk(request, mode);
36
+ const asModel = (request) => {
37
+ const { model, inputTokens, output, feeUsd } = decisionAsk(request);
43
38
  return {
44
39
  kind: "model",
45
40
  id: request.id,
@@ -57,7 +52,6 @@ const unpriced = (request) => ({
57
52
  inputTokens: request.inputTokens,
58
53
  });
59
54
  export function createCap(options, seed = {}) {
60
- const mode = options.mode ?? "expected";
61
55
  const now = options.now ?? Date.now;
62
56
  const ledger = new Ledger(options.spentUsd === undefined ? 0 : options.spentUsd);
63
57
  const marks = options.marks;
@@ -80,7 +74,7 @@ export function createCap(options, seed = {}) {
80
74
  if (!marks)
81
75
  return admission;
82
76
  try {
83
- await marks.write({ kind: "start", id: admission.id, at: now(), heldUsd, ...(admission.boundUsd > 0 ? { boundUsd: admission.boundUsd } : {}), ...extra });
77
+ await marks.write({ kind: "start", id: admission.id, at: now(), heldUsd, ...extra });
84
78
  }
85
79
  catch {
86
80
  ledger.release(admission.id);
@@ -106,7 +100,7 @@ export function createCap(options, seed = {}) {
106
100
  async admit(input) {
107
101
  // Read before every check: a raise holds from the next paid step. A decision under no cap is not priced.
108
102
  const capUsd = options.capUsd();
109
- const request = input.kind !== "decision" ? input : capUsd === undefined ? unpriced(input) : asModel(input, mode);
103
+ const request = input.kind !== "decision" ? input : capUsd === undefined ? unpriced(input) : asModel(input);
110
104
  // An id whose last step's marks are not all written is not used again until its settle is retried: else that retry
111
105
  // finds the new step's hold and settles it at the old step's figure.
112
106
  const last = settlements.get(request.id);
@@ -121,7 +115,7 @@ export function createCap(options, seed = {}) {
121
115
  }
122
116
  else {
123
117
  try {
124
- const judged = capRule.judge(request, { capUsd, spentUsd: ledger.spent(), heldUsd: ledger.held(), mode, now: now() });
118
+ const judged = capRule.judge(request, { capUsd, spentUsd: ledger.spent(), heldUsd: ledger.held() });
125
119
  admission = { id: request.id, ...judged };
126
120
  }
127
121
  catch (error) {
@@ -170,11 +164,11 @@ export function createCap(options, seed = {}) {
170
164
  return settled.usd;
171
165
  },
172
166
  leastUsd(request) {
173
- const p = priced(request, mode, now());
167
+ const p = priced(request);
174
168
  return p ? p.cost(p.least) : Number.NaN;
175
169
  },
176
170
  note(request) {
177
- const note = noteFor(request, { capUsd: options.capUsd(), spentUsd: ledger.spent(), heldUsd: ledger.held(), costs: ownCosts(request.model.id), told, mode, now: now() });
171
+ const note = noteFor(request, { capUsd: options.capUsd(), spentUsd: ledger.spent(), heldUsd: ledger.held(), costs: ownCosts(request.model.id), told });
178
172
  if (note)
179
173
  offered = note;
180
174
  return note;
@@ -0,0 +1,43 @@
1
+ import { type BeforeRequest } from "../../runner.js";
2
+ import type { SessionRecord } from "../../types.js";
3
+ import type { CapModel } from "./types.js";
4
+ /** The requests on a free model a run may make by default. */
5
+ export declare const FREE_MODEL_REQUESTS = 60;
6
+ /** OpenRouter's routers, each of which picks a model per request: OpenRouter prices them at the routed model's price,
7
+ * which pi-ai's catalog writes as $0, so their zeros are no price and none is free. The one list: serve's
8
+ * local-models.ts isRouter reads it. */
9
+ export declare const ROUTERS: ReadonlySet<string>;
10
+ /** Whether `model` is a free model: one whose known price is $0 for every token, each tier's included. A model with no
11
+ * price (null), or none at all, is no free model: unknown, the dollar cap's to refuse; nor is an OpenRouter router
12
+ * (ROUTERS), whatever its catalog price; nor a ChatGPT plan's (CapModel.plan), whatever its listing. The one rule: serve's
13
+ * local-models.ts isFree, the model picker's free mark, reads it on the catalog entry's price. */
14
+ export declare function freeModel(model: CapModel | undefined): boolean;
15
+ /** Whether `request` is on a free model (freeModel, as `modelOf` prices it): never one with a fee beside it (a native
16
+ * web search's) or a paid step's charge, which cost dollars, nor one named by a router. The one rule for both what the
17
+ * runner books at a known $0 (Admitted.free) and what the run's limit counts. */
18
+ export declare function freeRequest(request: Parameters<BeforeRequest>[0], modelOf: (id: string, route?: string) => CapModel | undefined): boolean;
19
+ /** A ChatGPT plan's model as the cap prices it, on every harness alike (pi's route and a CLI's model proxy): billed to the
20
+ * plan, so no price here (never its $0 listing, never an unknown price) and the plan's mark (CapModel.plan). */
21
+ export declare function planCapModel(id: string, api: string, outputCeiling: number | null): CapModel;
22
+ /** The requests before its limit at which a run on a free model is told to finish (told on the request that has this many
23
+ * left, itself included). 3: enough for the model to read the note, answer and tidy up once, few enough that a normal
24
+ * run never sees it. */
25
+ export declare const FREE_WRAP_UP_MARGIN = 3;
26
+ /** Whether a run that has made `made` counted requests, under `limit`, is due its wrap-up on its next one: at most
27
+ * FREE_WRAP_UP_MARGIN requests left, that next one included. Returns how many are left. */
28
+ export declare function freeWrapUpDue(limit: number, made: number): {
29
+ left: number;
30
+ } | undefined;
31
+ /** The note's words, once per run and limit (the dollar cap's wrap-up note carries them, the same mechanism). */
32
+ export declare const freeWrapUpWords: (left: number) => string;
33
+ /** The requests counted toward the free limit that `records` (a session's runner records) hold: each runner.request marked
34
+ * `freeRequest`, answered, in flight or cut. The one count, runBooking's and the wrap-up's. */
35
+ export declare const freeRequestsIn: (records: readonly SessionRecord[]) => number;
36
+ /** The words a run ends in once it has made `limit` requests on free models: the dollar cap's code, then why. */
37
+ export declare const freeCeilingEnd: (limit: number) => string;
38
+ /** The message of a run's end in freeCeilingEnd's words: what follows its code; undefined for any other summary. */
39
+ export declare const freeCeilingMessage: (summary: string | null | undefined) => string | undefined;
40
+ /** The limit an environment sets (`AGENTRUN_FREE_MODEL_REQUESTS`, a whole number above 0), else FREE_MODEL_REQUESTS. A value
41
+ * that is no such number is refused, loudly: a limit read as none would let a free run loop for ever. */
42
+ export declare const FREE_MODEL_REQUESTS_ENV = "AGENTRUN_FREE_MODEL_REQUESTS";
43
+ export declare function freeModelRequestsOf(env: Record<string, string | undefined>): number;
@@ -0,0 +1,71 @@
1
+ // The request ceiling for free models. The dollar cap cannot stop a run whose requests cost nothing: a free model's (its
2
+ // catalog price all zeros, an OpenRouter `:free` model and the like, whose shared daily quota one looping run can burn).
3
+ // So such requests are counted across the run, and once it has made the server's limit of them (FREE_MODEL_REQUESTS,
4
+ // else the operator's), its next one is refused for good and the run ends as the dollar cap ends one it can never fit:
5
+ // failed, in the cap's code and these words. A paid request never counts toward it, and is never refused by it; nor is a
6
+ // ChatGPT plan's request (ChatGPT-plan requests don't count).
7
+ import { RUNNER_RECORDS } from "../../runner.js";
8
+ import { SPEND_CAP_REACHED } from "./words.js";
9
+ import { SERVER_NOTE_LABEL } from "./wrap-up.js";
10
+ /** The requests on a free model a run may make by default. */
11
+ export const FREE_MODEL_REQUESTS = 60;
12
+ /** OpenRouter's routers, each of which picks a model per request: OpenRouter prices them at the routed model's price,
13
+ * which pi-ai's catalog writes as $0, so their zeros are no price and none is free. The one list: serve's
14
+ * local-models.ts isRouter reads it. */
15
+ export const ROUTERS = new Set(["auto", "openrouter/auto", "openrouter/auto-beta", "openrouter/auto-code", "openrouter/free", "openrouter/fusion", "openrouter/pareto-code", "typesafe/jev-router"]);
16
+ const zero = (rates) => rates.input === 0 && rates.output === 0 && (rates.cacheRead ?? 0) === 0 && (rates.cacheWrite ?? 0) === 0;
17
+ /** Whether `model` is a free model: one whose known price is $0 for every token, each tier's included. A model with no
18
+ * price (null), or none at all, is no free model: unknown, the dollar cap's to refuse; nor is an OpenRouter router
19
+ * (ROUTERS), whatever its catalog price; nor a ChatGPT plan's (CapModel.plan), whatever its listing. The one rule: serve's
20
+ * local-models.ts isFree, the model picker's free mark, reads it on the catalog entry's price. */
21
+ export function freeModel(model) {
22
+ if (!model || model.plan || ROUTERS.has(model.id))
23
+ return false;
24
+ const price = model.price;
25
+ return !!price && zero(price) && (price.tiers ?? []).every(zero);
26
+ }
27
+ /** Whether `request` is on a free model (freeModel, as `modelOf` prices it): never one with a fee beside it (a native
28
+ * web search's) or a paid step's charge, which cost dollars, nor one named by a router. The one rule for both what the
29
+ * runner books at a known $0 (Admitted.free) and what the run's limit counts. */
30
+ export function freeRequest(request, modelOf) {
31
+ if (request.paid || (request.feeUsd ?? 0) !== 0 || ROUTERS.has(request.model))
32
+ return false;
33
+ return freeModel(modelOf(request.model, request.route));
34
+ }
35
+ /** A ChatGPT plan's model as the cap prices it, on every harness alike (pi's route and a CLI's model proxy): billed to the
36
+ * plan, so no price here (never its $0 listing, never an unknown price) and the plan's mark (CapModel.plan). */
37
+ export function planCapModel(id, api, outputCeiling) {
38
+ return { id, api, price: null, outputCeiling, plan: true };
39
+ }
40
+ /** The requests before its limit at which a run on a free model is told to finish (told on the request that has this many
41
+ * left, itself included). 3: enough for the model to read the note, answer and tidy up once, few enough that a normal
42
+ * run never sees it. */
43
+ export const FREE_WRAP_UP_MARGIN = 3;
44
+ /** Whether a run that has made `made` counted requests, under `limit`, is due its wrap-up on its next one: at most
45
+ * FREE_WRAP_UP_MARGIN requests left, that next one included. Returns how many are left. */
46
+ export function freeWrapUpDue(limit, made) {
47
+ const left = limit - made;
48
+ return left >= 1 && left <= FREE_WRAP_UP_MARGIN ? { left } : undefined;
49
+ }
50
+ /** The note's words, once per run and limit (the dollar cap's wrap-up note carries them, the same mechanism). */
51
+ export const freeWrapUpWords = (left) => `${SERVER_NOTE_LABEL}${left} free-model request${left === 1 ? "" : "s"} left in this run, this one included: finish now with your answer.`;
52
+ /** The requests counted toward the free limit that `records` (a session's runner records) hold: each runner.request marked
53
+ * `freeRequest`, answered, in flight or cut. The one count, runBooking's and the wrap-up's. */
54
+ export const freeRequestsIn = (records) => records.filter((r) => r.kind === RUNNER_RECORDS.request && r.data?.freeRequest === true).length;
55
+ /** The words a run ends in once it has made `limit` requests on free models: the dollar cap's code, then why. */
56
+ export const freeCeilingEnd = (limit) => `${SPEND_CAP_REACHED}: Not sent: this run reached its ${limit}-request limit for free models.`;
57
+ const FREE_CEILING = new RegExp(`^${SPEND_CAP_REACHED}: (Not sent: this run reached its \\d+-request limit for free models\\.)$`);
58
+ /** The message of a run's end in freeCeilingEnd's words: what follows its code; undefined for any other summary. */
59
+ export const freeCeilingMessage = (summary) => typeof summary === "string" ? FREE_CEILING.exec(summary)?.[1] : undefined;
60
+ /** The limit an environment sets (`AGENTRUN_FREE_MODEL_REQUESTS`, a whole number above 0), else FREE_MODEL_REQUESTS. A value
61
+ * that is no such number is refused, loudly: a limit read as none would let a free run loop for ever. */
62
+ export const FREE_MODEL_REQUESTS_ENV = "AGENTRUN_FREE_MODEL_REQUESTS";
63
+ export function freeModelRequestsOf(env) {
64
+ const given = env[FREE_MODEL_REQUESTS_ENV];
65
+ if (given === undefined || given.trim() === "")
66
+ return FREE_MODEL_REQUESTS;
67
+ const value = Number(given);
68
+ if (!Number.isSafeInteger(value) || value < 1)
69
+ throw new Error(`${FREE_MODEL_REQUESTS_ENV} is a whole number of requests above 0, not ${given}`);
70
+ return value;
71
+ }
@@ -1,14 +1,15 @@
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";
1
+ export { CapRefused, createCap, DECISION_IMAGE_TOKENS, DecisionPriceUnreadable, END_MARK_WAIT_MS, END_NOT_WRITTEN, MARK_NOT_WRITTEN, openCap } from "./admit.js";
2
2
  export { capRule, noteFor, requestFigures, type Judged, type JudgeState, type NoteState } from "./rule.js";
3
- export { beforeRequestOf, type BeforeRequestOptions } from "./port.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, previousAfter, pricingOf, ratesFor, requestPrice } from "./price.js";
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";
5
+ export { ANSWER_TOKENS_LEAST, CAP_TOLERANCE, FIT_TOLERANCE, STOP_ALLOWANCE_TOKENS, THINKING_BUDGET_LEAST, inputBound, mostOutput, pricingOf, ratesFor, requestPrice, type Pricing } from "./price.js";
6
+ export { aloneRefusal, 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
+ export { FREE_MODEL_REQUESTS, FREE_MODEL_REQUESTS_ENV, FREE_WRAP_UP_MARGIN, freeCeilingEnd, freeCeilingMessage, freeModel, freeModelRequestsOf, freeRequest, freeRequestsIn, freeWrapUpDue, freeWrapUpWords, planCapModel, ROUTERS } from "./free.js";
7
8
  export { checkRaise, followUpOf, parkOf, takeRaises, type BudgetPending, type Park, type RaiseCheck, type RaiseState } from "./park.js";
8
- export { WRAP_UP_FACTOR, WRAP_UP_LEAST_FACTOR, WRAP_UP_STEP0_ANSWER_TOKENS, typicalCost, wrapUpDue, wrapUpWords } from "./wrap-up.js";
9
+ export { SERVER_NOTE_LABEL, WRAP_UP_FACTOR, WRAP_UP_LEAST_FACTOR, WRAP_UP_STEP0_ANSWER_TOKENS, typicalCost, wrapUpDue, wrapUpWords } from "./wrap-up.js";
9
10
  export { CapStop, createStepWaits, type StepWaits } from "./steps.js";
10
11
  export { memoryMarks, type CapMark, type CapMarks, type EndMark, type StartMark, type ToldMark, type WaitMark } from "./marks.js";
11
12
  export { ownCostsOf, spendOf, toldIn, type Spend } from "./recover.js";
12
13
  export { StepNotHeld, StepNotSettled } from "./ledger.js";
13
14
  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";
15
+ export type { Admission, Cap, CapModel, CapOptions, CapRequest, DecisionCapRequest, ModelCapRequest, ModelPrice, PriceRates, PriceTier, RefusalFigures, Settled, ToolCapRequest } from "./types.js";
@@ -1,13 +1,14 @@
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
- export { CapRefused, createCap, DECISION_IMAGE_TOKENS, DECISION_OUTPUT_TOKENS, DecisionPriceUnreadable, END_MARK_WAIT_MS, END_NOT_WRITTEN, MARK_NOT_WRITTEN, openCap } from "./admit.js";
3
+ export { CapRefused, createCap, DECISION_IMAGE_TOKENS, DecisionPriceUnreadable, END_MARK_WAIT_MS, END_NOT_WRITTEN, MARK_NOT_WRITTEN, openCap } from "./admit.js";
4
4
  export { capRule, noteFor, requestFigures } from "./rule.js";
5
- export { beforeRequestOf } from "./port.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, previousAfter, pricingOf, ratesFor, requestPrice } from "./price.js";
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";
7
+ export { ANSWER_TOKENS_LEAST, CAP_TOLERANCE, FIT_TOLERANCE, STOP_ALLOWANCE_TOKENS, THINKING_BUDGET_LEAST, inputBound, mostOutput, pricingOf, ratesFor, requestPrice } from "./price.js";
8
+ export { aloneRefusal, 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
+ export { FREE_MODEL_REQUESTS, FREE_MODEL_REQUESTS_ENV, FREE_WRAP_UP_MARGIN, freeCeilingEnd, freeCeilingMessage, freeModel, freeModelRequestsOf, freeRequest, freeRequestsIn, freeWrapUpDue, freeWrapUpWords, planCapModel, ROUTERS } from "./free.js";
9
10
  export { checkRaise, followUpOf, parkOf, takeRaises } from "./park.js";
10
- export { WRAP_UP_FACTOR, WRAP_UP_LEAST_FACTOR, WRAP_UP_STEP0_ANSWER_TOKENS, typicalCost, wrapUpDue, wrapUpWords } from "./wrap-up.js";
11
+ export { SERVER_NOTE_LABEL, WRAP_UP_FACTOR, WRAP_UP_LEAST_FACTOR, WRAP_UP_STEP0_ANSWER_TOKENS, typicalCost, wrapUpDue, wrapUpWords } from "./wrap-up.js";
11
12
  export { CapStop, createStepWaits } from "./steps.js";
12
13
  export { memoryMarks } from "./marks.js";
13
14
  export { ownCostsOf, spendOf, toldIn } from "./recover.js";
@@ -1,11 +1,10 @@
1
- /** A step's start: what it is held at (null: no figure, as an older store kept none), and its bound (what a cache miss
2
- * can add). `refused`: the cap refused it, and it never left. `tool`: a paid call's name. */
1
+ /** A step's start: what it is held at (null: no figure, as an older store kept none). `refused`: the cap refused it, and
2
+ * it never left. `tool`: a paid call's name. */
3
3
  export type StartMark = {
4
4
  readonly kind: "start";
5
5
  readonly id: string;
6
6
  readonly at: number;
7
7
  readonly heldUsd: number | null;
8
- readonly boundUsd?: number;
9
8
  /** A model request's model: the wrap-up's typical cost counts the run's own model's answers only. */
10
9
  readonly model?: string;
11
10
  readonly side?: true;
@@ -1,15 +1,14 @@
1
1
  import type { CapRefused } from "./admit.js";
2
- /** A run parked at its cap waits on a raise: its cap, what the cap counted as taken, the least the refused step needs, the
3
- * least cap that sends it, the raise it is offered, and the most a cache miss could have added to the refused step
4
- * (`bound_usd`, the refusal's boundUsd; 0 when it named none), which the budget card shows as main's overshoot bound. */
2
+ /** A run parked at its cap waits on a raise: its cap, what it had spent (never a hold), what it held for steps still
3
+ * running when it was refused, the least the refused step needs, the least cap that sends it, and the raise it is offered. */
5
4
  export type BudgetPending = {
6
5
  kind: "budget";
7
6
  cap_usd: number;
8
7
  spent_usd: number;
8
+ held_usd: number;
9
9
  needs_usd: number;
10
10
  least_cap_usd: number;
11
11
  suggested_cap_usd: number;
12
- bound_usd: number;
13
12
  };
14
13
  export type Park = {
15
14
  outcome: "parked";
@@ -1,20 +1,19 @@
1
1
  import { CAP_TOLERANCE } from "./price.js";
2
2
  import { CAP_REFUSAL_CODE, money, SPEND_CAP_REACHED, suggestedRaise } from "./words.js";
3
3
  const micro = (usd) => Math.round(usd * 1e6) / 1e6;
4
- /** A bound to a millionth, rounded up (never under what it bounds), as main's overshoot bound is (run-view.ts microUp);
5
- * no bound is 0, never -0 (the ceiling of a hair under 0 is -0, which a card would print as "-0"). */
6
- const microUp = (usd) => Math.ceil(usd * 1e6 - 1e-9) / 1e6 + 0;
7
4
  /** The run's end for `refusal` under `capUsd`. */
8
5
  export function parkOf(refusal, capUsd) {
9
6
  if (refusal.forGood || !refusal.figures)
10
7
  return { outcome: "failed", error: refusal.message };
11
- const { spentUsd, needsUsd, leastCapUsd, boundUsd } = refusal.figures;
8
+ const { spentUsd, heldUsd = 0, needsUsd, leastCapUsd } = refusal.figures;
12
9
  // Its words without the refusal's code: a model request's ("spend_cap_reached (out of budget): ") or a paid step's
13
10
  // ("spend_cap_reached: "), so a pause reads its sentence alone, whichever step was refused.
14
11
  const words = [CAP_REFUSAL_CODE, `${SPEND_CAP_REACHED}: `].reduce((said, code) => (said.startsWith(code) ? said.slice(code.length) : said), refusal.message);
15
12
  return {
16
13
  outcome: "parked",
17
- pending: { kind: "budget", cap_usd: capUsd, spent_usd: micro(spentUsd), needs_usd: micro(needsUsd), least_cap_usd: leastCapUsd, suggested_cap_usd: suggestedRaise(capUsd, spentUsd, needsUsd), bound_usd: microUp(boundUsd ?? 0) },
14
+ // What it spent is what it spent, never a hold of a step still running (those settle at what they cost); the raise it
15
+ // is offered counts the holds too, so it covers them whatever they settle at.
16
+ pending: { kind: "budget", cap_usd: capUsd, spent_usd: micro(spentUsd), held_usd: micro(heldUsd), needs_usd: micro(needsUsd), least_cap_usd: leastCapUsd, suggested_cap_usd: suggestedRaise(capUsd, spentUsd + heldUsd, needsUsd) },
18
17
  words,
19
18
  event: { kind: "pause", text: words },
20
19
  };
@@ -1,13 +1,11 @@
1
1
  import type { BeforeRequest } from "../../runner.js";
2
- import type { CapMode, CapModel, Previous } from "./types.js";
2
+ import type { CapModel, ModelCapRequest } 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;
11
9
  /** What the run spent beside the session's model requests, which the runner's booking does not hold: its priced tools'
12
10
  * 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
11
  * unknown too. */
@@ -15,8 +13,16 @@ export interface BeforeRequestOptions {
15
13
  /** What the run's priced tools under way hold, beside the session's requests in flight (null: unknown). A figure that is
16
14
  * not finite and 0 or more is unknown too: the request is refused, never judged as $0 held. */
17
15
  heldUsd?(): number | null;
18
- mode?: CapMode;
19
- now?: () => number;
16
+ /** What the host keeps back beside model request `request` (priced as `asked`) for the steps it may still ask for while
17
+ * it streams (the rule's JudgeState.keepUsd): serve's wrap-up reserve for the session's own requests. Undefined: none. */
18
+ keepBackUsd?(request: Parameters<BeforeRequest>[0], asked: ModelCapRequest): number | undefined;
20
19
  }
20
+ /** What prices a model request: its model and route, its input bound, the output it asks and needs at least, its fee,
21
+ * and whether it is a side call. */
22
+ export type PricedRequest = Pick<Parameters<BeforeRequest>[0], "model" | "route" | "inputTokensMax" | "outputTokensAsked" | "outputTokensLeast" | "feeUsd" | "side">;
23
+ /** `request` as the rule prices it: the one place a request's model is chosen for it (a CLI's request names its model as
24
+ * its provider does, openai/gpt-6.1-sol for gpt-6.1-sol), so its admission, the wrap-up's note and what the run keeps
25
+ * back to answer (requestFigures) price it alike: its whole input bound uncached. */
26
+ export declare function capRequestOf(id: string, request: PricedRequest, options: Pick<BeforeRequestOptions, "modelOf">): ModelCapRequest;
21
27
  /** The host's beforeRequest for a CLI harness's session: the runner's spend and holds, judged by the one rule. */
22
28
  export declare function beforeRequestOf(options: BeforeRequestOptions): BeforeRequest;
@@ -7,10 +7,24 @@ 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 is chosen for it (a CLI's request names its model as
11
+ * its provider does, openai/gpt-6.1-sol for gpt-6.1-sol), so its admission, the wrap-up's note and what the run keeps
12
+ * back to answer (requestFigures) price it alike: its whole input bound uncached. */
13
+ export function capRequestOf(id, request, options) {
14
+ const model = options.modelOf(request.model, request.route) ?? unpriced(request.model);
15
+ return {
16
+ kind: "model",
17
+ id,
18
+ model,
19
+ inputTokens: request.inputTokensMax,
20
+ ...(request.outputTokensAsked === undefined ? {} : { outputAsked: request.outputTokensAsked }),
21
+ ...(request.outputTokensLeast === undefined ? {} : { outputTokensLeast: request.outputTokensLeast }),
22
+ ...(isFigure(request.feeUsd) && request.feeUsd > 0 ? { feeUsd: request.feeUsd } : {}),
23
+ ...(request.side ? { side: true } : {}),
24
+ };
25
+ }
10
26
  /** The host's beforeRequest for a CLI harness's session: the runner's spend and holds, judged by the one rule. */
11
27
  export function beforeRequestOf(options) {
12
- const mode = options.mode ?? "expected";
13
- const now = options.now ?? Date.now;
14
28
  return (request) => {
15
29
  const capUsd = options.capUsd();
16
30
  if (capUsd === undefined)
@@ -20,24 +34,7 @@ export function beforeRequestOf(options) {
20
34
  // 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
35
  if (request.paid?.owed && isFigure(request.feeUsd ?? 0))
22
36
  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), a side call, or one
25
- // that is no answer of the turn (a title, a summary, a child's) is another conversation's prompt: nothing of the
26
- // session's cache is read for it, so it is priced as a cache miss.
27
- // Its bound must be measured as the next request's is (a provider's count, or bytes): their difference is no growth.
28
- const before = request.host === undefined && !request.side && !request.unanswered ? options.previousOf?.(request.model) : undefined;
29
- const previous = before && (before.counted === true) === (request.inputTokensCounted === true) ? before : undefined;
30
- const asked = {
31
- kind: "model",
32
- id: `turn-${request.turn}`,
33
- model,
34
- inputTokens: request.inputTokensMax,
35
- ...(request.outputTokensAsked === undefined ? {} : { outputAsked: request.outputTokensAsked }),
36
- ...(request.outputTokensLeast === undefined ? {} : { outputTokensLeast: request.outputTokensLeast }),
37
- ...(previous ? { previous } : {}),
38
- ...(isFigure(request.feeUsd) && request.feeUsd > 0 ? { feeUsd: request.feeUsd } : {}),
39
- ...(request.side ? { side: true } : {}),
40
- };
37
+ const asked = capRequestOf(`turn-${request.turn}`, request, options);
41
38
  // Each request in flight at what the host held for it, else its worst case at the limit it was admitted with; one with
42
39
  // neither (no hold, no price or no measure) cannot be kept within the cap: refused for good, as an unmeasured input.
43
40
  let inFlight = 0;
@@ -59,7 +56,7 @@ export function beforeRequestOf(options) {
59
56
  // paidCall), its words naming it, beside the run's spend and holds.
60
57
  if (request.paid) {
61
58
  try {
62
- const judged = capRule.judge({ kind: "tool", id: `turn-${request.turn}`, name: request.paid.name, holdUsd: request.feeUsd ?? 0, basis: request.paid.basis }, { capUsd, spentUsd, heldUsd, mode, now: now() });
59
+ const judged = capRule.judge({ kind: "tool", id: `turn-${request.turn}`, name: request.paid.name, holdUsd: request.feeUsd ?? 0, basis: request.paid.basis }, { capUsd, spentUsd, heldUsd });
63
60
  return { holdUsd: judged.heldUsd };
64
61
  }
65
62
  catch (error) {
@@ -70,8 +67,10 @@ export function beforeRequestOf(options) {
70
67
  }
71
68
  const judge = (input) => {
72
69
  try {
73
- const judged = capRule.judge({ ...asked, inputTokens: input }, { capUsd, spentUsd, heldUsd, mode, now: now() });
74
- return { holdUsd: judged.heldUsd, boundUsd: judged.boundUsd, ...(judged.outputTokensMax === undefined ? {} : { outputTokensMax: judged.outputTokensMax }), stoppedUsd: judged.stoppedUsd };
70
+ const sized = { ...asked, inputTokens: input };
71
+ const keepUsd = options.keepBackUsd?.(request, sized);
72
+ const judged = capRule.judge(sized, { capUsd, spentUsd, heldUsd, ...(keepUsd === undefined ? {} : { keepUsd }) });
73
+ return { holdUsd: judged.heldUsd, ...(judged.outputTokensMax === undefined ? {} : { outputTokensMax: judged.outputTokensMax }), stoppedUsd: judged.stoppedUsd };
75
74
  }
76
75
  catch (error) {
77
76
  // Its words, and what the run's end is decided from (parkOf): for good, or for room with its figures.
@@ -97,10 +96,13 @@ export function beforeRequestOf(options) {
97
96
  * no measure, or priced output with neither a limit nor a ceiling (as the rule's noCeiling): undefined (it cannot be
98
97
  * counted), never 0 and never Infinity. */
99
98
  function worstOf(model, inputTokens, outputTokens) {
99
+ // A plan's request costs the run nothing (CapModel.plan).
100
+ if (model?.plan)
101
+ return 0;
100
102
  if (!model?.price || inputTokens === undefined)
101
103
  return undefined;
102
104
  if (outputTokens === undefined && model.outputCeiling === null && model.price.output > 0)
103
105
  return undefined;
104
106
  const bound = inputBound({ kind: "model", id: "", model, inputTokens });
105
- return pricingOf(model.price)({ cached: 0, fresh: bound ?? inputTokens }, outputTokens ?? model.outputCeiling ?? 0);
107
+ return pricingOf(model.price)(bound ?? inputTokens, outputTokens ?? model.outputCeiling ?? 0);
106
108
  }
@@ -1,7 +1,4 @@
1
- import type { CapMode, ModelCapRequest, ModelPrice, PriceRates, Previous } from "./types.js";
2
- /** How long after a request ended the next one in its conversation is expected to read its cache: 4 minutes, inside
3
- * Anthropic's 5. */
4
- export declare const CACHE_WARM_MS: number;
1
+ import type { ModelCapRequest, ModelPrice, PriceRates } from "./types.js";
5
2
  /** The tokens a limited request keeps for its answer. */
6
3
  export declare const ANSWER_TOKENS_LEAST = 1024;
7
4
  /** The least thinking budget Anthropic takes. */
@@ -12,37 +9,20 @@ export declare const STOP_ALLOWANCE_TOKENS = 1024;
12
9
  export declare const FIT_TOLERANCE = 1e-12;
13
10
  /** How near two caps are the same cap: a raise must be above a run's cap by more. */
14
11
  export declare const CAP_TOLERANCE = 1e-9;
15
- /** A request's input as it is priced: `cached` tokens at the cache-read price, `fresh` at the dearer of input and cache write. */
16
- export type InputParts = {
17
- cached: number;
18
- fresh: number;
19
- };
20
- /** A price as a function of its input parts and its output tokens, in USD. */
21
- export type Pricing = (input: InputParts, output: number) => number;
12
+ /** A price as a function of its input tokens (all uncached) and its output tokens, in USD. */
13
+ export type Pricing = (inputTokens: number, output: number) => number;
22
14
  /** The rates of `price` for a request of `inputTokens` in all (fresh and cached): its tier with the highest threshold
23
15
  * that input is above, else its base rates. pi-ai's calculateCost picks them so, on the same table (the catalog's), and
24
16
  * then prices the whole request at them; serve's kernel-cap-tiers-parity test holds the two together. */
25
17
  export declare function ratesFor(price: ModelPrice, inputTokens: number): PriceRates;
26
- /** `price` as the cap prices with it: a request's cached input at the cache-read rate, its fresh input at the dearer of
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
- * passes (ratesFor). A hold, a worst case and a booking the cap prices are so never under what the provider bills. */
18
+ /** `price` as the cap prices with it: every input token uncached, at the dearer of the input and cache-write rates (a
19
+ * cache read is cheaper and a cache write is the dearest an input token bills at), and its output at the output rate,
20
+ * each at the rates of the tier its whole input passes (ratesFor). A hold the cap prices is so never under what the
21
+ * provider bills for the same tokens, whatever the cache did. */
29
22
  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;
34
- /** The session's previous request once `ended` has answered: `ended` itself when it continues the conversation (the first
35
- * request, another model's, one measured another way, or one at least as big as the previous), none when it is smaller.
36
- * A smaller body is a compaction or another conversation's (a child's, which the proxy cannot tell from the root's):
37
- * history resets, so it never sticks on a request the conversation has left and never prices the next from another's
38
- * cache. The next request is priced uncached (one miss window), then warm from its own predecessor. */
39
- export declare function previousAfter(previous: Previous | undefined, ended: Previous): Previous | undefined;
40
- /** A request priced under `mode`: `cost(output)`, what it is held at (its expected input, never more than uncached), and
41
- * `worst(output)`, its input uncached; each with its hosted tools' most fee. */
42
- export declare function requestPrice(pricing: Pricing, bound: number, previous: Previous | undefined, now: number, mode: CapMode, model: string, feeUsd?: number): {
43
- cost(output: number): number;
44
- worst(output: number): number;
45
- };
23
+ /** A request of `bound` input tokens at its worst case: what it costs at `output` tokens, its hosted tools' most fee
24
+ * included. It is held at this, so it is booked at no more, answered, missed or cut. */
25
+ export declare function requestPrice(pricing: Pricing, bound: number, feeUsd?: number): (output: number) => number;
46
26
  /** A request's whole input bound: its measured bytes, what its provider adds for what it carries, and what its hosted tools
47
27
  * read. Undefined when its bytes were not measured. */
48
28
  export declare function inputBound(request: ModelCapRequest): number | undefined;