@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
@@ -1,12 +1,8 @@
1
- // The kernel cap's one pricing rule, the same for every harness. A request's input bound (its measured bytes, what its
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.
1
+ // The kernel cap's one pricing rule, the same for every harness: a request at its worst case. Its input bound (its
2
+ // measured bytes, what its provider adds, what its hosted tools read) is priced uncached, every token at the dearer of the
3
+ // input and cache-write prices, so a cache miss costs no more than it was held at; its output at what it is sent with,
4
+ // its thinking budget included. No request can pass the cap.
6
5
  import { providerInputOverhead } from "../../host/overhead.js";
7
- /** How long after a request ended the next one in its conversation is expected to read its cache: 4 minutes, inside
8
- * Anthropic's 5. */
9
- export const CACHE_WARM_MS = 4 * 60_000;
10
6
  /** The tokens a limited request keeps for its answer. */
11
7
  export const ANSWER_TOKENS_LEAST = 1_024;
12
8
  /** The least thinking budget Anthropic takes. */
@@ -33,50 +29,21 @@ export function ratesFor(price, inputTokens) {
33
29
  }
34
30
  return rates;
35
31
  }
36
- /** `price` as the cap prices with it: a request's cached input at the cache-read rate, its fresh input at the dearer of
37
- * the input and cache-write rates, and its output at the output rate, each at the rates of the tier its whole input
38
- * passes (ratesFor). A hold, a worst case and a booking the cap prices are so never under what the provider bills. */
32
+ /** `price` as the cap prices with it: every input token uncached, at the dearer of the input and cache-write rates (a
33
+ * cache read is cheaper and a cache write is the dearest an input token bills at), and its output at the output rate,
34
+ * each at the rates of the tier its whole input passes (ratesFor). A hold the cap prices is so never under what the
35
+ * provider bills for the same tokens, whatever the cache did. */
39
36
  export function pricingOf(price) {
40
- return (parts, output) => {
41
- const rates = ratesFor(price, parts.cached + parts.fresh);
42
- const read = rates.cacheRead ?? rates.input;
37
+ return (inputTokens, output) => {
38
+ const rates = ratesFor(price, inputTokens);
43
39
  const fresh = Math.max(rates.input, rates.cacheWrite ?? rates.input);
44
- return (parts.cached * read + parts.fresh * fresh + output * rates.output) / 1e6;
40
+ return (inputTokens * fresh + output * rates.output) / 1e6;
45
41
  };
46
42
  }
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
- // A conversation only grows between its own requests: a smaller body is not one (a compaction, or another conversation's),
57
- // so none of the previous request's cache is known to be read by it. Priced uncached, never under what it can cost.
58
- if (bound < previous.boundTokens)
59
- return undefined;
60
- return { cached: previous.cachedTokens, fresh: previous.inputTokens + Math.max(0, bound - previous.boundTokens) };
61
- }
62
- /** The session's previous request once `ended` has answered: `ended` itself when it continues the conversation (the first
63
- * request, another model's, one measured another way, or one at least as big as the previous), none when it is smaller.
64
- * A smaller body is a compaction or another conversation's (a child's, which the proxy cannot tell from the root's):
65
- * history resets, so it never sticks on a request the conversation has left and never prices the next from another's
66
- * cache. The next request is priced uncached (one miss window), then warm from its own predecessor. */
67
- export function previousAfter(previous, ended) {
68
- if (previous && previous.model === ended.model && previous.counted === ended.counted && ended.boundTokens < previous.boundTokens)
69
- return undefined;
70
- return ended;
71
- }
72
- /** A request priced under `mode`: `cost(output)`, what it is held at (its expected input, never more than uncached), and
73
- * `worst(output)`, its input uncached; each with its hosted tools' most fee. */
74
- export function requestPrice(pricing, bound, previous, now, mode, model, feeUsd = 0) {
75
- const worst = (output) => pricing({ cached: 0, fresh: bound }, output) + feeUsd;
76
- const parts = mode === "strict" ? undefined : expectedInput(bound, previous, now, model);
77
- if (!parts)
78
- return { cost: worst, worst };
79
- return { cost: (output) => Math.min(pricing(parts, output) + feeUsd, worst(output)), worst };
43
+ /** A request of `bound` input tokens at its worst case: what it costs at `output` tokens, its hosted tools' most fee
44
+ * included. It is held at this, so it is booked at no more, answered, missed or cut. */
45
+ export function requestPrice(pricing, bound, feeUsd = 0) {
46
+ return (output) => pricing(bound, output) + feeUsd;
80
47
  }
81
48
  /** A request's whole input bound: its measured bytes, what its provider adds for what it carries, and what its hosted tools
82
49
  * read. Undefined when its bytes were not measured. */
@@ -1,10 +1,9 @@
1
1
  import type { CapMark } from "./marks.js";
2
2
  /** What the marks say: the cap's spend (null: unknown), the run's reported cost (null once any step's own cost is unknown,
3
- * as a step a crash cut), the bound of the steps still open, and how many requests were sent (a refused one is none). */
3
+ * as a step a crash cut), and how many requests were sent (a refused one is none). */
4
4
  export type Spend = {
5
5
  spentUsd: number | null;
6
6
  reportedUsd: number | null;
7
- boundUsd: number;
8
7
  requests: number;
9
8
  };
10
9
  export declare function spendOf(marks: readonly CapMark[]): Spend;
@@ -1,7 +1,6 @@
1
1
  export function spendOf(marks) {
2
2
  let spent = 0;
3
3
  let reported = 0;
4
- let bound = 0;
5
4
  let requests = 0;
6
5
  const add = (usd, known) => {
7
6
  spent = spent === null || usd === null ? null : spent + usd;
@@ -14,9 +13,8 @@ export function spendOf(marks) {
14
13
  /** Ends read before any start of their id (marks that fall out of order): each closes the start that comes after it. */
15
14
  const early = new Set();
16
15
  const cut = (start) => {
17
- // A crash cut it: it counts at what it was held at, and no one knows what it cost.
16
+ // A crash cut it: it counts at what it was held at (its worst case), and no one knows what it cost.
18
17
  add(start.heldUsd, false);
19
- bound += start.boundUsd ?? 0;
20
18
  };
21
19
  for (const mark of marks) {
22
20
  if (mark.kind === "start") {
@@ -49,7 +47,7 @@ export function spendOf(marks) {
49
47
  }
50
48
  for (const start of open.values())
51
49
  cut(start);
52
- return { spentUsd: spent, reportedUsd: reported, boundUsd: bound, requests };
50
+ return { spentUsd: spent, reportedUsd: reported, requests };
53
51
  }
54
52
  /** A run's own priced answers from its marks, as the live cap counts them: each main-model request (never a side call or
55
53
  * a paid call) whose end is an answer with a cost above 0, with its model. */
@@ -1,31 +1,28 @@
1
- import type { CapMode, ModelCapRequest, ToolCapRequest } from "./types.js";
1
+ import type { 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
- mode: CapMode;
9
- now: number;
9
+ keepUsd?: number;
10
10
  };
11
11
  /** A money figure the cap can count: a finite number of 0 or more. Anything else (null, NaN, Infinity, below 0) is
12
12
  * unknown: it never reads as $0 and never frees room. */
13
13
  export declare const isFigure: (usd: unknown) => usd is number;
14
- /** A step admitted: what it is held at, the most a cache miss adds, its worst case, the output it may be sent with and its
15
- * thinking budget, and what it counts at if stopped having streamed that many tokens (within its hold). */
14
+ /** A step admitted: what it is held at (its worst case: no answer, miss or cut books it past this), the output it may be
15
+ * sent with and its thinking budget, and what it counts at if stopped having streamed that many tokens (within its hold). */
16
16
  export type Judged = {
17
17
  heldUsd: number;
18
- boundUsd: number;
19
- worstUsd: number;
20
18
  outputTokensMax?: number;
21
19
  thinkingBudget?: number;
22
20
  stoppedUsd(streamedTokens: number): number;
23
21
  };
24
- /** A model request priced: its output asked and least, and its cost and worst case at an output. */
25
- export declare function priced(request: ModelCapRequest, mode: CapMode, now: number): {
22
+ /** A model request priced: its output asked and least, and its worst case at an output (price.ts requestPrice). */
23
+ export declare function priced(request: ModelCapRequest): {
26
24
  asked: number | undefined;
27
- cost: (output: number) => number;
28
- worst: (output: number) => number;
25
+ cost: (_output: number) => number;
29
26
  least: number;
30
27
  } | undefined;
31
28
  /** The one rule: admits `request` under `state`, or throws CapRefused. */
@@ -36,11 +33,10 @@ export declare const capRule: {
36
33
  };
37
34
  /** 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
38
35
  * fewest output tokens the cap admits it at), its step-0 typical cost (its input and a WRAP_UP_STEP0_ANSWER_TOKENS answer,
39
- * the wrap-up's own) and its worst (its full asked output, its bound included). Undefined when it cannot be priced. */
40
- export declare function requestFigures(request: ModelCapRequest, mode: CapMode, now: number): {
36
+ * the wrap-up's own). Undefined when it cannot be priced. */
37
+ export declare function requestFigures(request: ModelCapRequest): {
41
38
  leastUsd: number;
42
39
  step0Usd: number;
43
- worstUsd: number;
44
40
  } | undefined;
45
41
  /** What the wrap-up reads: the cap, spend and holds as admission counts them, the run's own priced answers on the
46
42
  * request's model, and whether it was told. */
@@ -50,8 +46,6 @@ export type NoteState = {
50
46
  heldUsd: number;
51
47
  costs: readonly number[];
52
48
  told: boolean;
53
- mode: CapMode;
54
- now: number;
55
49
  };
56
50
  /** The wrap-up for `request`, the run's next main-model request measured before the note is placed: due under three times
57
51
  * 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,
@@ -10,17 +10,25 @@ import { noCeiling, noPrice, noToolPrice, paidRefusal, roomRefusal, unknownHeld,
10
10
  /** A money figure the cap can count: a finite number of 0 or more. Anything else (null, NaN, Infinity, below 0) is
11
11
  * unknown: it never reads as $0 and never frees room. */
12
12
  export const isFigure = (usd) => typeof usd === "number" && Number.isFinite(usd) && usd >= 0;
13
- /** A model request priced: its output asked and least, and its cost and worst case at an output. */
14
- export function priced(request, mode, now) {
13
+ /** A model request priced: its output asked and least, and its worst case at an output (price.ts requestPrice). */
14
+ export function priced(request) {
15
+ // A plan's request costs the run nothing at any output: its least, its step-0 figure and its worst are $0.
16
+ if (request.model.plan)
17
+ return { asked: outputAsked(request), cost: (_output) => 0, least: 0 };
15
18
  const bound = inputBound(request);
16
19
  const price = request.model.price;
17
20
  if (bound === undefined || price === null)
18
21
  return undefined;
19
22
  const asked = outputAsked(request);
20
- const { cost, worst } = requestPrice(pricingOf(price), bound, request.previous, now, mode, request.model.id, request.feeUsd ?? 0);
21
- return { asked, cost, worst, least: asked === undefined ? 0 : outputLeast(request, asked) };
23
+ const cost = requestPrice(pricingOf(price), bound, request.feeUsd ?? 0);
24
+ return { asked, cost, least: asked === undefined ? 0 : outputLeast(request, asked) };
22
25
  }
23
- function judgeModel(request, { capUsd, spentUsd: spent, heldUsd: held, mode, now }) {
26
+ function judgeModel(request, { capUsd, spentUsd: spent, heldUsd: held, keepUsd }) {
27
+ // A request on a person's subscription plan (CapModel.plan) is billed to the plan, never in dollars: held at $0, its
28
+ // output never limited (the plan's own limits apply), and admitted at any known spend, even one at the cap. Whatever else the run pays for (a
29
+ // paid tool, a model on a key) is judged as ever, so the cap still holds every dollar.
30
+ if (request.model.plan)
31
+ return { heldUsd: 0, stoppedUsd: () => 0 };
24
32
  if (inputBound(request) === undefined)
25
33
  throw new CapRefused(unmeasured(capUsd), { forGood: true, spentUsd: spent });
26
34
  const price = request.model.price;
@@ -28,20 +36,29 @@ function judgeModel(request, { capUsd, spentUsd: spent, heldUsd: held, mode, now
28
36
  throw new CapRefused(noPrice(capUsd), { forGood: true, spentUsd: spent });
29
37
  if (request.model.outputCeiling === null && price.output > 0)
30
38
  throw new CapRefused(noCeiling(capUsd), { forGood: true, spentUsd: spent });
31
- const p = priced(request, mode, now);
32
- const output = mostOutput(p.cost, p.least, p.asked ?? 0, capUsd - spent - held);
39
+ const p = priced(request);
40
+ const left = capUsd - spent - held;
41
+ // The output it is sent with, clamped so its worst case fits: its whole input bound uncached and that output. With a
42
+ // keep-back from its host, first the most that leaves `keepUsd` free: a tool call the request makes while it streams
43
+ // then finds room for the steps after it (serve's wrap-up, which counts the request at its hold until it is booked).
44
+ // When even its least and the keep-back do not fit, the run is wrapping up and this request may be its answer: it gets
45
+ // the most what is left buys, as with no keep-back. Below its least, it is refused and the run parks for a raise.
46
+ // Why no request can pass the cap: every branch admits only an output whose worst case is at most what is left (the
47
+ // first at most what is left less the keep-back). The output is limited to that when sent, so whatever the cache did,
48
+ // and if it is cut with no usage, the request is booked at no more than its hold, which counts in the run's records
49
+ // while it is out; a stop counts what streamed, within the hold. (The keep-back is kept with a float's tail to spare,
50
+ // so the host's sum of the same figures never reads it as passed.)
51
+ const kept = isFigure(keepUsd) && keepUsd > 0 ? mostOutput(p.cost, p.least, p.asked ?? 0, left - keepUsd - 2 * FIT_TOLERANCE) : undefined;
52
+ const output = kept ?? mostOutput(p.cost, p.least, p.asked ?? 0, left);
33
53
  if (output === undefined) {
34
- const { text, figures } = roomRefusal(capUsd, spent, held, p.cost(p.least), p.worst(p.least) - p.cost(p.least));
54
+ const { text, figures } = roomRefusal(capUsd, spent, held, p.cost(p.least));
35
55
  throw new CapRefused(text, { forGood: false, spentUsd: spent, figures });
36
56
  }
37
57
  const heldUsd = p.cost(output);
38
- const worstUsd = p.worst(output);
39
58
  const stoppedPrice = (streamed) => p.cost(Math.min(output, streamed + STOP_ALLOWANCE_TOKENS));
40
59
  const thinking = thinkingWithin(request, output);
41
60
  return {
42
61
  heldUsd,
43
- boundUsd: Math.max(0, worstUsd - heldUsd),
44
- worstUsd,
45
62
  ...(p.asked === undefined ? {} : { outputTokensMax: output }),
46
63
  ...(thinking === undefined ? {} : { thinkingBudget: thinking }),
47
64
  stoppedUsd: (streamed) => Math.min(heldUsd, stoppedPrice(streamed)),
@@ -57,7 +74,7 @@ function judgeTool(request, { capUsd, spentUsd: spent, heldUsd: held }) {
57
74
  const { text, figures } = paidRefusal(capUsd, spent, held, request.name, request.holdUsd, request.basis);
58
75
  throw new CapRefused(text, { forGood: false, spentUsd: spent, figures });
59
76
  }
60
- return { heldUsd: request.holdUsd, boundUsd: 0, worstUsd: request.holdUsd, stoppedUsd: () => request.holdUsd };
77
+ return { heldUsd: request.holdUsd, stoppedUsd: () => request.holdUsd };
61
78
  }
62
79
  /** The one rule: admits `request` under `state`, or throws CapRefused. */
63
80
  function judge(request, state) {
@@ -73,20 +90,21 @@ function judge(request, state) {
73
90
  export const capRule = { judge };
74
91
  /** 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
75
92
  * fewest output tokens the cap admits it at), its step-0 typical cost (its input and a WRAP_UP_STEP0_ANSWER_TOKENS answer,
76
- * the wrap-up's own) and its worst (its full asked output, its bound included). Undefined when it cannot be priced. */
77
- export function requestFigures(request, mode, now) {
78
- const p = priced(request, mode, now);
93
+ * the wrap-up's own). Undefined when it cannot be priced. */
94
+ export function requestFigures(request) {
95
+ const p = priced(request);
79
96
  if (!p)
80
97
  return undefined;
81
- 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) };
98
+ return { leastUsd: p.cost(p.least), step0Usd: p.cost(Math.min(p.asked ?? 0, WRAP_UP_STEP0_ANSWER_TOKENS)) };
82
99
  }
83
100
  /** The wrap-up for `request`, the run's next main-model request measured before the note is placed: due under three times
84
101
  * 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,
85
102
  * and never when the request fits what is left only without the note's bytes. */
86
103
  export function noteFor(request, state) {
87
- if (request.side || state.told || state.capUsd === undefined || state.spentUsd === null)
104
+ // A plan's request is never stopped by the cap, so the model on it has nothing to wrap up for.
105
+ if (request.side || request.model.plan || state.told || state.capUsd === undefined || state.spentUsd === null)
88
106
  return undefined;
89
- const p = priced(request, state.mode, state.now);
107
+ const p = priced(request);
90
108
  if (!p)
91
109
  return undefined;
92
110
  const least = p.cost(p.least);
@@ -95,7 +113,7 @@ export function noteFor(request, state) {
95
113
  if (!due)
96
114
  return undefined;
97
115
  const words = wrapUpWords(due.leftUsd, state.costs.length === 0);
98
- const noted = priced({ ...request, inputTokens: (request.inputTokens ?? 0) + Buffer.byteLength(words, "utf8") }, state.mode, state.now);
116
+ const noted = priced({ ...request, inputTokens: (request.inputTokens ?? 0) + Buffer.byteLength(words, "utf8") });
99
117
  if (noted && noted.cost(noted.least) > due.leftUsd + FIT_TOLERANCE && least <= due.leftUsd + FIT_TOLERANCE)
100
118
  return undefined;
101
119
  return { words, leftUsd: due.leftUsd };
@@ -1,7 +1,8 @@
1
1
  import { type RunSessions } from "../../run-booking.js";
2
2
  import { type BeforeRequest } from "../../runner.js";
3
3
  import type { SessionRecord, SessionWriter } from "../../types.js";
4
- import type { Admission, CapMode, CapModel, DecisionCapRequest, Previous, Settled } from "./types.js";
4
+ import { type PricedRequest } from "./port.js";
5
+ import type { Admission, CapModel, DecisionCapRequest, ModelCapRequest, Settled } from "./types.js";
5
6
  /** The session a run's workflow decisions book under. */
6
7
  export declare const DECISION_SESSION = "decisions";
7
8
  export interface RunCapOptions {
@@ -9,17 +10,27 @@ export interface RunCapOptions {
9
10
  readonly sessions: RunSessions;
10
11
  /** The run's cap, read before every check, so a raise holds from the next one. Undefined: no cap. */
11
12
  capUsd(): number | undefined;
12
- readonly mode?: CapMode;
13
- readonly now?: () => number;
14
13
  /** The run's model requests' models, by id and route (BeforeRequestOptions.modelOf; its decisions' are the cap's own). */
15
14
  modelOf(id: string, route?: string): CapModel | undefined;
16
- previousOf?(model: string): Previous | undefined;
17
15
  /** The run's priced tools' charges and holds beside its requests (beforeRequestOf's), when it has any. */
18
16
  spentUsd?(): number | null;
19
17
  heldUsd?(): number | null;
18
+ /** What the host keeps back beside a model request while it streams (BeforeRequestOptions.keepBackUsd). */
19
+ keepBackUsd?(request: Parameters<BeforeRequest>[0], asked: ModelCapRequest): number | undefined;
20
20
  /** Told each request the rule judged, with the run's totals it was asked with, and its answer (an observer: a live
21
21
  * view of the cap, a test's record). */
22
22
  judged?(request: Parameters<BeforeRequest>[0], answer: Awaited<ReturnType<BeforeRequest>>): void;
23
+ /** The most model requests on free models (free.ts freeModel) the run makes, capped or not: the next one past it is
24
+ * refused for good, in freeCeilingEnd's words. Its paid tool calls, its decisions and ChatGPT-plan requests never
25
+ * count. Undefined: no such limit. */
26
+ freeRequests?: number;
27
+ /** Whether the run has parked (its host's pause): a model request waiting for room (runBooking) leaves the line then,
28
+ * refused in its own words, so nothing more is sent until a raise. */
29
+ parked?(): boolean;
30
+ /** How long a request waits for room with nothing it waits on settling (runBooking's WAIT_STALL_MS by default). */
31
+ waitStallMs?: number;
32
+ /** The run's stop: a step waiting for room (a paid call's or a decision's as a model request's) leaves at it, unsent. */
33
+ stopped?: AbortSignal;
23
34
  }
24
35
  /** A run's decisions on its one cap: each admitted before it is sent and settled once it answered. */
25
36
  export interface RunDecisions {
@@ -35,6 +46,9 @@ export interface RunDecisions {
35
46
  export interface RunCap {
36
47
  /** The run's one rule for every model request (a model booking's beforeRequest), its decisions' models known to it. */
37
48
  readonly before: BeforeRequest;
49
+ /** A model request as `before` prices it (port.ts capRequestOf, with the same models): what the wrap-up's note and the
50
+ * reserve (requestFigures) price, so they price it as admission does. */
51
+ asked(request: PricedRequest): ModelCapRequest;
38
52
  /** The run's decisions, booked on `writer` (the run's DECISION_SESSION) under the same rule. `flush`: makes what the
39
53
  * journal holds survive a lost box, awaited once a decision's hold is written and before it is sent, as a model
40
54
  * request's is (request_start), so a decision sent and then lost with its box still counts after the next claim. */
@@ -55,7 +69,9 @@ export interface RunTools {
55
69
  * for it, named there as `charged_by`; `tool` and `tag`, the tool whose charge it is and its session (ModelRequest.paid);
56
70
  * `owed`, money its provider is already owed: held and booked, never refused. `hold`: a hold-only step: money
57
71
  * reserved, not spent; given back on a lost claim, never booked as cut. `ref`: the one booking it names: a ref already
58
- * booked (on the run's records, or on this claim) books nothing again, and the answer says `booked`. */
72
+ * booked (on the run's records, or on this claim) books nothing again, and the answer says `booked`. `under`: the key
73
+ * of the model session whose tool call it runs in (ModelRequest.paid.under): it is judged beside that session's
74
+ * requests in flight and never waits on them, since one of them may be the request that asked for it. */
59
75
  admit(request: {
60
76
  readonly id: string;
61
77
  readonly name: string;
@@ -68,6 +84,7 @@ export interface RunTools {
68
84
  readonly owed?: true;
69
85
  readonly hold?: true;
70
86
  readonly ref?: string;
87
+ readonly under?: string;
71
88
  }): Promise<Admission & {
72
89
  readonly booked?: true;
73
90
  }>;
@@ -81,11 +98,9 @@ export interface RunTools {
81
98
  }
82
99
  /** The session a run's paid tool calls book under. */
83
100
  export declare const TOOL_SESSION = "paid-tools";
84
- /** How a run ends once its booked spend passed its cap (overCapEnd), read from its model session's `records` and what
85
- * its other sessions spent (`othersUsd`): each request at the figure the cap counts it at (sessionSpendOf's figures: one
86
- * cut by a crash at its hold plus its bound), and the bound of the requests since the spend last fit, so a cache miss
87
- * within that bound (a cut request's possible one included) pauses the run instead. Undefined while it fits, by such a
88
- * miss, or with a spend unknown. */
101
+ /** How a run ends once its booked spend passed its cap (overCapEnd), read from its model session's `records` (each
102
+ * request at the figure the cap counts it at, sessionSpendOf's: one cut by a crash at its hold) and what its other
103
+ * sessions spent (`othersUsd`). Undefined while it fits, or with a spend unknown. */
89
104
  export declare function overCapOf(records: readonly SessionRecord[], othersUsd: number, capUsd: number): string | undefined;
90
105
  export declare function runCap(options: RunCapOptions): RunCap;
91
106
  /** A run's paid tool calls booked on `writer` (its TOOL_SESSION) under `before`, the run's one rule (runCap's, or the
@@ -3,56 +3,94 @@
3
3
  // (modelPortFor: runner.request with what it holds before it leaves, runner.turn with what it cost once it answers). So
4
4
  // a decision is judged on the run's model spend beside its own and a model request on the run's decisions, a refusal's
5
5
  // figures are the run's (main's holdPaid reads the whole run), and a claim taken again after a lost one rebuilds the
6
- // spend of both from the journal: a decision held and never answered counts at its hold and its bound, as any request.
7
- // Decisions book under their own session (DECISION_SESSION), priced as main holds them (decisionAsk).
6
+ // spend of both from the journal: a decision held and never answered counts at its hold, as any request.
7
+ // Decisions book under their own session (DECISION_SESSION), held at their worst case (decisionAsk).
8
8
  import { runBooking } from "../../run-booking.js";
9
9
  import { modelPortFor, RUNNER_RECORDS, sessionSpendOf } from "../../runner.js";
10
- import { overCapEnd } from "./words.js";
10
+ import { aloneRefusal, overCapEnd, SPEND_CAP_REACHED } from "./words.js";
11
+ import { freeCeilingEnd, freeRequest } from "./free.js";
11
12
  import { decisionAsk } from "./admit.js";
12
13
  import { CapRefused, DecisionPriceUnreadable } from "./errors.js";
13
- import { beforeRequestOf } from "./port.js";
14
+ import { beforeRequestOf, capRequestOf } from "./port.js";
14
15
  /** The session a run's workflow decisions book under. */
15
16
  export const DECISION_SESSION = "decisions";
16
17
  /** The session a run's paid tool calls book under. */
17
18
  export const TOOL_SESSION = "paid-tools";
18
- /** How a run ends once its booked spend passed its cap (overCapEnd), read from its model session's `records` and what
19
- * its other sessions spent (`othersUsd`): each request at the figure the cap counts it at (sessionSpendOf's figures: one
20
- * cut by a crash at its hold plus its bound), and the bound of the requests since the spend last fit, so a cache miss
21
- * within that bound (a cut request's possible one included) pauses the run instead. Undefined while it fits, by such a
22
- * miss, or with a spend unknown. */
19
+ /** How a run ends once its booked spend passed its cap (overCapEnd), read from its model session's `records` (each
20
+ * request at the figure the cap counts it at, sessionSpendOf's: one cut by a crash at its hold) and what its other
21
+ * sessions spent (`othersUsd`). Undefined while it fits, or with a spend unknown. */
23
22
  export function overCapOf(records, othersUsd, capUsd) {
24
23
  const read = sessionSpendOf(records);
25
24
  if (read.spentUsd === null)
26
25
  return undefined;
27
- let running = othersUsd;
28
- let bound = 0;
29
- for (const { turn, usd } of read.figures) {
30
- running += usd ?? 0;
31
- bound = running <= capUsd ? 0 : bound + (read.bounds.get(turn) ?? 0);
32
- }
33
- return overCapEnd(othersUsd + read.spentUsd, capUsd, bound);
26
+ return overCapEnd(othersUsd + read.spentUsd, capUsd);
34
27
  }
35
28
  export function runCap(options) {
36
- const mode = options.mode ?? "expected";
37
29
  /** Each decision under way's model, as the rule prices it (decisionAsk), by the model key its request books under. */
38
30
  const deciding = new Map();
31
+ const pricing = { modelOf: (id, route) => deciding.get(id) ?? options.modelOf(id, route) };
39
32
  const rule = beforeRequestOf({
40
33
  capUsd: options.capUsd,
41
- mode,
42
- ...(options.now ? { now: options.now } : {}),
43
- modelOf: (id, route) => deciding.get(id) ?? options.modelOf(id, route),
44
- ...(options.previousOf ? { previousOf: (model) => (deciding.has(model) ? undefined : options.previousOf(model)) } : {}),
34
+ ...pricing,
45
35
  ...(options.spentUsd ? { spentUsd: options.spentUsd } : {}),
46
36
  ...(options.heldUsd ? { heldUsd: options.heldUsd } : {}),
37
+ ...(options.keepBackUsd ? { keepBackUsd: options.keepBackUsd } : {}),
47
38
  });
48
- const before = runBooking(options.sessions, options.judged ? async (request) => {
39
+ // A request on a free model (freeRequest), under a cap or none. The dollar cap cannot stop such requests, so a model
40
+ // request of the run's own sessions past the run's limit of them (`freeRequests`) is refused for good, before the
41
+ // dollar rule; one within it goes to the rule, and its admission says it counts (`freeRequest`, written on its
42
+ // runner.request, so the next count holds it in any process). A paid tool call and a decision book under their own
43
+ // sessions and never count; nor does a ChatGPT plan's request (no free model). A free model's request is also admitted
44
+ // `free`: the runner books it a known $0 however it ends (runner.ts Admitted), never unknown. One on a person's plan
45
+ // (CapModel.plan) is admitted `plan`: $0 to the run however it ends, cut by a crash included. A request is never both:
46
+ // freeModel refuses a plan model (its listing's price is no price), so `free` is false for every plan request, and the
47
+ // plan mark is returned before the free one is looked at. One the rule refused stays refused.
48
+ const limit = options.freeRequests;
49
+ const judge = async (request) => {
50
+ const free = freeRequest(request, pricing.modelOf);
51
+ const counted = free && request.key !== DECISION_SESSION && request.key !== TOOL_SESSION;
52
+ if (counted && limit !== undefined && (request.freeRequestsMade ?? 0) >= limit)
53
+ return { refuse: freeCeilingEnd(limit), forGood: true, code: SPEND_CAP_REACHED };
49
54
  const answer = await rule(request);
50
- options.judged(request, answer);
55
+ if (answer && "refuse" in answer)
56
+ return await roomOf(request, answer);
57
+ if (!request.paid && pricing.modelOf(request.model, request.route)?.plan)
58
+ return { ...answer, plan: true };
59
+ if (!free)
60
+ return answer;
61
+ return { ...(answer ?? {}), ...(counted ? { freeRequest: true } : {}), free: true };
62
+ };
63
+ // A step (a model request, a decision, a paid tool call) refused for room while steps in flight hold some of it: judged
64
+ // again by the same rule as if none of the steps that settle on their own were out (a hold-only step, one the booking
65
+ // no longer waits on, and a paid call's own session's requests in flight, one of which may have asked for it, still
66
+ // count: runBooking marks them `stays`). Fits so: it `waits` (runBooking asks again once they settle, and never passes the
67
+ // cap: every admission is the rule's over the holds as they are then). Refused even so: refused now, its figures that
68
+ // refusal's (the least cap that sends it once they settle), its words saying what is spent and what is held apart
69
+ // (aloneRefusal), never holds as spent. A step in flight that holds $0 (a free model's request) frees no room when it
70
+ // settles, so with only such steps beside the ones that stay, the refusal is the rule's own.
71
+ const roomOf = async (request, refused) => {
72
+ if (refused.forGood !== false || !refused.figures || !request.inFlight.some((flight) => !flight.stays && flight.holdUsd !== 0))
73
+ return refused;
74
+ const alone = await rule({ ...request, inFlight: request.inFlight.filter((flight) => flight.stays) });
75
+ if (!(alone && "refuse" in alone))
76
+ return { ...refused, waits: true };
77
+ const capUsd = options.capUsd();
78
+ if (alone.forGood !== false || !alone.figures || capUsd === undefined)
79
+ return alone;
80
+ const figures = { ...alone.figures, heldUsd: refused.figures.heldUsd ?? 0 };
81
+ return { ...alone, refuse: aloneRefusal(capUsd, figures), figures };
82
+ };
83
+ const before = runBooking(options.sessions, options.judged ? async (request) => {
84
+ const answer = await judge(request);
85
+ // An observer sees each verdict the run goes by: a refusal that waits is asked again, its verdict told then.
86
+ if (!(answer && "refuse" in answer && answer.waits))
87
+ options.judged(request, answer);
51
88
  return answer;
52
- } : rule);
89
+ } : judge, { ...(options.parked ? { parked: options.parked } : {}), ...(options.waitStallMs === undefined ? {} : { stallMs: options.waitStallMs }), ...(options.stopped ? { stopped: options.stopped } : {}) });
53
90
  const forget = (key) => void deciding.delete(key);
54
91
  return {
55
92
  before,
93
+ asked: (request) => capRequestOf("asked", request, pricing),
56
94
  async decisions(writer, decisionOptions = {}) {
57
95
  const steps = await stepsOn(writer, before, decisionOptions.flush, "decision", forget);
58
96
  return {
@@ -61,7 +99,7 @@ export function runCap(options) {
61
99
  // Under no cap a decision is not priced: nothing is read, nothing refused (its model may be "unreadable").
62
100
  if (capUsd !== undefined && request.model === "unreadable")
63
101
  throw new DecisionPriceUnreadable();
64
- const asked = capUsd === undefined || request.model === "unreadable" ? undefined : decisionAsk(request, mode);
102
+ const asked = capUsd === undefined || request.model === "unreadable" ? undefined : decisionAsk(request);
65
103
  const key = `decision:${request.id}`;
66
104
  if (asked)
67
105
  deciding.set(key, { ...asked.model, id: key });
@@ -86,14 +124,14 @@ export async function paidCalls(writer, before, options = {}) {
86
124
  const refsOf = () => (refs ??= writer.read().then((records) => new Set(records.filter((r) => r.kind === RUNNER_RECORDS.request).map((r) => r.data?.ref).filter((ref) => typeof ref === "string"))));
87
125
  const book = (request) =>
88
126
  // A hold that is no figure (an unpriced browser provider's) goes to the rule as given, which refuses it for good.
89
- steps.book(request.id, { model: `paid:${request.name}`, inputTokensMax: 0, ...(request.holdUsd !== 0 ? { feeUsd: request.holdUsd } : {}), paid: { name: request.name, basis: request.basis, ...(request.call === undefined ? {} : { call: request.call }), ...(request.chargedBy === undefined ? {} : { charged_by: request.chargedBy }), ...(request.tool === undefined ? {} : { tool: request.tool }), ...(request.tag === undefined ? {} : { tag: request.tag }), ...(request.owed ? { owed: true } : {}), ...(request.hold ? { hold: true } : {}), ...(request.ref === undefined ? {} : { ref: request.ref }) } });
127
+ steps.book(request.id, { model: `paid:${request.name}`, inputTokensMax: 0, ...(request.holdUsd !== 0 ? { feeUsd: request.holdUsd } : {}), paid: { name: request.name, basis: request.basis, ...(request.call === undefined ? {} : { call: request.call }), ...(request.chargedBy === undefined ? {} : { charged_by: request.chargedBy }), ...(request.tool === undefined ? {} : { tool: request.tool }), ...(request.tag === undefined ? {} : { tag: request.tag }), ...(request.owed ? { owed: true } : {}), ...(request.hold ? { hold: true } : {}), ...(request.ref === undefined ? {} : { ref: request.ref }), ...(request.under === undefined ? {} : { under: request.under }) } });
90
128
  return {
91
129
  admit: async (request) => {
92
130
  if (request.ref === undefined)
93
131
  return book(request);
94
132
  const booked = await refsOf();
95
133
  if (booked.has(request.ref))
96
- return { id: request.id, heldUsd: 0, boundUsd: 0, worstUsd: 0, stoppedUsd: () => 0, booked: true };
134
+ return { id: request.id, heldUsd: 0, stoppedUsd: () => 0, booked: true };
97
135
  booked.add(request.ref);
98
136
  try {
99
137
  return await book(request);
@@ -112,13 +150,20 @@ export async function paidCalls(writer, before, options = {}) {
112
150
  * each a runner.request before it is sent (flushed when `flush` is given) and a runner.turn once settled. */
113
151
  async function stepsOn(writer, before, flush, what, forget) {
114
152
  {
115
- /** The verdict of the step being admitted (admissions run one at a time on the booking), for its refusal. */
153
+ /** The verdict of the step being admitted (admissions run one at a time on the booking), for its hold or refusal: set
154
+ * as its check begins and ends, and taken by its book once its admission ends, before the next one's check begins. A
155
+ * step booked while another waits for room sets nothing, so it never wipes the verdict of the one before it. */
116
156
  let verdict;
117
- const lastVerdict = () => verdict;
157
+ const takeVerdict = () => {
158
+ const taken = verdict;
159
+ verdict = undefined;
160
+ return taken;
161
+ };
118
162
  const booking = await modelPortFor(writer, {
119
163
  key: writer.key,
120
164
  label: writer.key,
121
165
  beforeRequest: async (request) => {
166
+ verdict = undefined;
122
167
  const answer = await before(request);
123
168
  verdict = (answer ?? undefined);
124
169
  return answer;
@@ -127,32 +172,30 @@ async function stepsOn(writer, before, flush, what, forget) {
127
172
  ...(flush ? { onEvent: async (event) => { if (event.type === "request_start")
128
173
  await flush(); } } : {}),
129
174
  });
130
- // A step an earlier claim admitted and that never answered: booked cut, counted at its hold and its bound.
175
+ // A step an earlier claim admitted and that never answered: booked cut, counted at its hold.
131
176
  await booking.bookCut();
132
177
  const open = new Map();
133
178
  return {
134
179
  /** Books step `id`, asked as `asked` (its model key a decision's priced model, or a paid call's name). */
135
180
  async book(id, asked) {
136
181
  const key = asked.model;
137
- verdict = undefined;
138
182
  let ticket;
139
183
  try {
140
184
  ticket = await booking.models.beforeRequest(asked);
141
185
  }
142
186
  catch (error) {
143
187
  forget(key);
144
- const refused = lastVerdict();
188
+ const refused = takeVerdict();
145
189
  if (refused?.refuse !== undefined)
146
190
  throw new CapRefused(refused.refuse, { forGood: refused.forGood ?? true, spentUsd: refused.figures?.spentUsd ?? null, ...(refused.figures ? { figures: refused.figures } : {}) });
147
191
  throw error;
148
192
  }
149
193
  if (!ticket)
150
194
  throw new Error(`${what} ${id}: its booking gave it no ticket`);
151
- const admitted = lastVerdict();
195
+ const admitted = takeVerdict();
152
196
  const held = typeof admitted?.holdUsd === "number" ? admitted.holdUsd : 0;
153
- const bound = typeof admitted?.boundUsd === "number" ? admitted.boundUsd : 0;
154
197
  open.set(id, { ticket, key, heldUsd: held });
155
- return { id, heldUsd: held, boundUsd: bound, worstUsd: held + bound, stoppedUsd: () => held };
198
+ return { id, heldUsd: held, stoppedUsd: () => held };
156
199
  },
157
200
  async settle(id, usd, options) {
158
201
  const step = open.get(id);