@parcha/agentrun-kernel 0.1.0-beta.30 → 0.1.0-beta.32

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 (102) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/README.md +5 -0
  3. package/dist/errors.d.ts +7 -0
  4. package/dist/errors.js +10 -0
  5. package/dist/host/box.d.ts +0 -58
  6. package/dist/host/box.js +7 -0
  7. package/dist/host/index.d.ts +5 -9
  8. package/dist/host/index.js +2 -4
  9. package/dist/host/mcp-route.d.ts +14 -0
  10. package/dist/host/mcp-route.js +125 -0
  11. package/dist/host/proxy.d.ts +96 -2
  12. package/dist/host/proxy.js +533 -41
  13. package/dist/host/serial.js +2 -1
  14. package/dist/index.d.ts +5 -4
  15. package/dist/index.js +3 -2
  16. package/dist/kernel/cap/admit.d.ts +35 -0
  17. package/dist/kernel/cap/admit.js +186 -0
  18. package/dist/kernel/cap/errors.d.ts +20 -0
  19. package/dist/kernel/cap/errors.js +25 -0
  20. package/dist/kernel/cap/index.d.ts +14 -0
  21. package/dist/kernel/cap/index.js +15 -0
  22. package/dist/kernel/cap/ledger.d.ts +37 -0
  23. package/dist/kernel/cap/ledger.js +83 -0
  24. package/dist/kernel/cap/marks.d.ts +50 -0
  25. package/dist/kernel/cap/marks.js +28 -0
  26. package/dist/kernel/cap/park.d.ts +80 -0
  27. package/dist/kernel/cap/park.js +57 -0
  28. package/dist/kernel/cap/port.d.ts +21 -0
  29. package/dist/kernel/cap/port.js +95 -0
  30. package/dist/kernel/cap/price.d.ts +54 -0
  31. package/dist/kernel/cap/price.js +117 -0
  32. package/dist/kernel/cap/recover.d.ts +18 -0
  33. package/dist/kernel/cap/recover.js +71 -0
  34. package/dist/kernel/cap/rule.d.ts +55 -0
  35. package/dist/kernel/cap/rule.js +93 -0
  36. package/dist/kernel/cap/run-cap.d.ts +80 -0
  37. package/dist/kernel/cap/run-cap.js +132 -0
  38. package/dist/kernel/cap/steps.d.ts +36 -0
  39. package/dist/kernel/cap/steps.js +64 -0
  40. package/dist/kernel/cap/stopped.d.ts +17 -0
  41. package/dist/kernel/cap/stopped.js +34 -0
  42. package/dist/kernel/cap/types.d.ts +151 -0
  43. package/dist/kernel/cap/types.js +1 -0
  44. package/dist/kernel/cap/words.d.ts +39 -0
  45. package/dist/kernel/cap/words.js +75 -0
  46. package/dist/kernel/cap/wrap-up.d.ts +17 -0
  47. package/dist/kernel/cap/wrap-up.js +37 -0
  48. package/dist/kernel/drive.d.ts +0 -1
  49. package/dist/kernel/drive.js +9 -2
  50. package/dist/kernel/index.d.ts +1 -0
  51. package/dist/kernel/index.js +1 -0
  52. package/dist/kernel/registry/background.d.ts +12 -0
  53. package/dist/kernel/registry/background.js +342 -0
  54. package/dist/kernel/registry/bash.d.ts +3 -0
  55. package/dist/kernel/registry/bash.js +23 -0
  56. package/dist/kernel/registry/browser.d.ts +11 -0
  57. package/dist/kernel/registry/browser.js +14 -0
  58. package/dist/kernel/registry/defs.d.ts +42 -0
  59. package/dist/kernel/registry/defs.js +153 -0
  60. package/dist/kernel/registry/desktop.d.ts +11 -0
  61. package/dist/kernel/registry/desktop.js +90 -0
  62. package/dist/kernel/registry/gate.d.ts +20 -0
  63. package/dist/kernel/registry/gate.js +32 -0
  64. package/dist/kernel/registry/handoff.d.ts +11 -0
  65. package/dist/kernel/registry/handoff.js +51 -0
  66. package/dist/kernel/registry/hands.d.ts +280 -0
  67. package/dist/kernel/registry/hands.js +28 -0
  68. package/dist/kernel/registry/index.d.ts +17 -0
  69. package/dist/kernel/registry/index.js +14 -0
  70. package/dist/kernel/registry/limits.d.ts +27 -0
  71. package/dist/kernel/registry/limits.js +29 -0
  72. package/dist/kernel/registry/phone.d.ts +15 -0
  73. package/dist/kernel/registry/phone.js +135 -0
  74. package/dist/kernel/registry/registry.d.ts +22 -0
  75. package/dist/kernel/registry/registry.js +75 -0
  76. package/dist/kernel/types.d.ts +0 -7
  77. package/dist/process/builtins.js +1 -1
  78. package/dist/process/index.d.ts +1 -0
  79. package/dist/process/index.js +1 -0
  80. package/dist/process/journal.js +1 -1
  81. package/dist/process/recovery.js +1 -1
  82. package/dist/process/resume.d.ts +20 -0
  83. package/dist/process/resume.js +16 -0
  84. package/dist/process/tail.js +1 -1
  85. package/dist/process/tools.d.ts +8 -1
  86. package/dist/process/tools.js +20 -3
  87. package/dist/process/zod.js +1 -1
  88. package/dist/run-booking.d.ts +9 -0
  89. package/dist/run-booking.js +50 -0
  90. package/dist/runner.d.ts +91 -17
  91. package/dist/runner.js +132 -41
  92. package/dist/testing.d.ts +79 -12
  93. package/dist/testing.js +106 -13
  94. package/dist/types.d.ts +235 -10
  95. package/package.json +8 -4
  96. package/vendor/durable-harness/UPSTREAM.json +0 -9
  97. package/dist/host/box-slot.d.ts +0 -26
  98. package/dist/host/box-slot.js +0 -112
  99. package/dist/host/egress-proxy.d.ts +0 -45
  100. package/dist/host/egress-proxy.js +0 -416
  101. package/dist/host/egress-table.d.ts +0 -24
  102. package/dist/host/egress-table.js +0 -165
@@ -0,0 +1,80 @@
1
+ import { type RunSessions } from "../../run-booking.js";
2
+ import { type BeforeRequest } from "../../runner.js";
3
+ import type { SessionWriter } from "../../types.js";
4
+ import type { Admission, CapMode, CapModel, DecisionCapRequest, Previous, Settled } from "./types.js";
5
+ /** The session a run's workflow decisions book under. */
6
+ export declare const DECISION_SESSION = "decisions";
7
+ export interface RunCapOptions {
8
+ /** The run's sessions: every key it has and each one's records (the journal's). */
9
+ readonly sessions: RunSessions;
10
+ /** The run's cap, read before every check, so a raise holds from the next one. Undefined: no cap. */
11
+ capUsd(): number | undefined;
12
+ readonly mode?: CapMode;
13
+ readonly now?: () => number;
14
+ /** The run's model requests' models (its decisions' are the cap's own). */
15
+ modelOf(id: string): CapModel | undefined;
16
+ previousOf?(model: string): Previous | undefined;
17
+ /** The run's priced tools' charges and holds beside its requests (beforeRequestOf's), when it has any. */
18
+ spentUsd?(): number | null;
19
+ heldUsd?(): number | null;
20
+ /** Told each request the rule judged, with the run's totals it was asked with, and its answer (an observer: a live
21
+ * view of the cap, a test's record). */
22
+ judged?(request: Parameters<BeforeRequest>[0], answer: Awaited<ReturnType<BeforeRequest>>): void;
23
+ }
24
+ /** A run's decisions on its one cap: each admitted before it is sent and settled once it answered. */
25
+ export interface RunDecisions {
26
+ /** Admits `request`: its hold, or CapRefused (for room, with its figures; or for good), or DecisionPriceUnreadable. */
27
+ admit(request: DecisionCapRequest): Promise<Admission>;
28
+ /** Settles the decision `id` at what it charged (`usd`; null: at its hold, as main books a charge not said). */
29
+ settle(id: string, settled: Settled): Promise<number | null>;
30
+ /** What the run's decisions cost, this claim's and every earlier claim's (null: unknown). */
31
+ spentUsd(): number | null;
32
+ /** What its decisions under way hold. */
33
+ heldUsd(): number;
34
+ }
35
+ export interface RunCap {
36
+ /** The run's one rule for every model request (a model booking's beforeRequest), its decisions' models known to it. */
37
+ readonly before: BeforeRequest;
38
+ /** The run's decisions, booked on `writer` (the run's DECISION_SESSION) under the same rule. `flush`: makes what the
39
+ * journal holds survive a lost box, awaited once a decision's hold is written and before it is sent, as a model
40
+ * request's is (request_start), so a decision sent and then lost with its box still counts after the next claim. */
41
+ decisions(writer: SessionWriter, options?: {
42
+ flush?: () => Promise<void>;
43
+ }): Promise<RunDecisions>;
44
+ /** The run's paid tool calls (a web search's or fetch's request, a monid call), booked on `writer` (the run's
45
+ * TOOL_SESSION) under the same rule: each held at its price before it is sent (flushed when `flush` is given) and
46
+ * settled at what it charged, as main's paidRequest books it. */
47
+ tools(writer: SessionWriter, options?: {
48
+ flush?: () => Promise<void>;
49
+ }): Promise<RunTools>;
50
+ }
51
+ /** A run's paid tool calls on its one cap. */
52
+ export interface RunTools {
53
+ /** Admits the paid request `id` at its price (`holdUsd`): its hold, or CapRefused. `call`: the tool call it runs under,
54
+ * named on its runner.request (none for a step under no call, a person's browser time); `chargedBy`, who charges
55
+ * for it, named there as `charged_by`. */
56
+ admit(request: {
57
+ readonly id: string;
58
+ readonly name: string;
59
+ readonly holdUsd: number;
60
+ readonly basis: string;
61
+ readonly call?: string;
62
+ readonly chargedBy?: string;
63
+ }): Promise<Admission>;
64
+ /** Settles it at what it charged (null: at its hold; 0: nothing was billed). `givenBack`: its hold let go unused,
65
+ * nothing sent (at 0), its record marked so (ModelUsage.givenBack): never read as a $0 charge or an unpriced one. */
66
+ settle(id: string, usd: number | null, options?: {
67
+ readonly givenBack?: true;
68
+ }): Promise<number | null>;
69
+ spentUsd(): number | null;
70
+ heldUsd(): number;
71
+ }
72
+ /** The session a run's paid tool calls book under. */
73
+ export declare const TOOL_SESSION = "paid-tools";
74
+ export declare function runCap(options: RunCapOptions): RunCap;
75
+ /** A run's paid tool calls booked on `writer` (its TOOL_SESSION) under `before`, the run's one rule (runCap's, or the
76
+ * adapter loop's runBooking over its spec's check): each held at its price before it is sent (main's paidCall, by the
77
+ * rule's tool judgement), flushed first when `flush` is given, and settled at what it charged. */
78
+ export declare function paidCalls(writer: SessionWriter, before: BeforeRequest, options?: {
79
+ flush?: () => Promise<void>;
80
+ }): Promise<RunTools>;
@@ -0,0 +1,132 @@
1
+ // A run's one cap: its model requests and its workflow decisions admitted by the one rule (beforeRequestOf), one at a
2
+ // time across the run (runBooking over its sessions), and booked on one ledger, the runner records of its sessions
3
+ // (modelPortFor: runner.request with what it holds before it leaves, runner.turn with what it cost once it answers). So
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
+ // 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).
8
+ import { runBooking } from "../../run-booking.js";
9
+ import { modelPortFor } from "../../runner.js";
10
+ import { decisionAsk } from "./admit.js";
11
+ import { CapRefused, DecisionPriceUnreadable } from "./errors.js";
12
+ import { beforeRequestOf } from "./port.js";
13
+ /** The session a run's workflow decisions book under. */
14
+ export const DECISION_SESSION = "decisions";
15
+ /** The session a run's paid tool calls book under. */
16
+ export const TOOL_SESSION = "paid-tools";
17
+ export function runCap(options) {
18
+ const mode = options.mode ?? "expected";
19
+ /** Each decision under way's model, as the rule prices it (decisionAsk), by the model key its request books under. */
20
+ const deciding = new Map();
21
+ const rule = beforeRequestOf({
22
+ capUsd: options.capUsd,
23
+ mode,
24
+ ...(options.now ? { now: options.now } : {}),
25
+ modelOf: (id) => deciding.get(id) ?? options.modelOf(id),
26
+ ...(options.previousOf ? { previousOf: (model) => (deciding.has(model) ? undefined : options.previousOf(model)) } : {}),
27
+ ...(options.spentUsd ? { spentUsd: options.spentUsd } : {}),
28
+ ...(options.heldUsd ? { heldUsd: options.heldUsd } : {}),
29
+ });
30
+ const before = runBooking(options.sessions, options.judged ? async (request) => {
31
+ const answer = await rule(request);
32
+ options.judged(request, answer);
33
+ return answer;
34
+ } : rule);
35
+ const forget = (key) => void deciding.delete(key);
36
+ return {
37
+ before,
38
+ async decisions(writer, decisionOptions = {}) {
39
+ const steps = await stepsOn(writer, before, decisionOptions.flush, "decision", forget);
40
+ return {
41
+ async admit(request) {
42
+ const capUsd = options.capUsd();
43
+ // Under no cap a decision is not priced: nothing is read, nothing refused (its model may be "unreadable").
44
+ if (capUsd !== undefined && request.model === "unreadable")
45
+ throw new DecisionPriceUnreadable();
46
+ const asked = capUsd === undefined || request.model === "unreadable" ? undefined : decisionAsk(request, mode);
47
+ const key = `decision:${request.id}`;
48
+ if (asked)
49
+ deciding.set(key, { ...asked.model, id: key });
50
+ return steps.book(request.id, { model: key, ...(asked ? { inputTokensMax: asked.inputTokens, ...(asked.output === null ? {} : { outputTokensAsked: asked.output, outputTokensLeast: asked.output }), ...(asked.feeUsd > 0 ? { feeUsd: asked.feeUsd } : {}) } : { inputTokensMax: request.inputTokens }) });
51
+ },
52
+ settle: (id, settled) => steps.settle(id, "usd" in settled ? settled.usd : null),
53
+ spentUsd: steps.spentUsd,
54
+ heldUsd: steps.heldUsd,
55
+ };
56
+ },
57
+ tools: (writer, toolOptions = {}) => paidCalls(writer, before, toolOptions),
58
+ };
59
+ }
60
+ /** A run's paid tool calls booked on `writer` (its TOOL_SESSION) under `before`, the run's one rule (runCap's, or the
61
+ * adapter loop's runBooking over its spec's check): each held at its price before it is sent (main's paidCall, by the
62
+ * rule's tool judgement), flushed first when `flush` is given, and settled at what it charged. */
63
+ export async function paidCalls(writer, before, options = {}) {
64
+ const steps = await stepsOn(writer, before, options.flush, "paid call", () => { });
65
+ return {
66
+ // A hold that is no figure (an unpriced browser provider's) goes to the rule as given, which refuses it for good.
67
+ admit: (request) => 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 }) } }),
68
+ settle: (id, usd, options) => steps.settle(id, options?.givenBack ? 0 : usd, options),
69
+ spentUsd: steps.spentUsd,
70
+ heldUsd: steps.heldUsd,
71
+ };
72
+ }
73
+ /** Steps that are no model request of the run's own (its decisions, its paid tool calls) booked on `writer` under `before`:
74
+ * each a runner.request before it is sent (flushed when `flush` is given) and a runner.turn once settled. */
75
+ async function stepsOn(writer, before, flush, what, forget) {
76
+ {
77
+ /** The verdict of the step being admitted (admissions run one at a time on the booking), for its refusal. */
78
+ let verdict;
79
+ const lastVerdict = () => verdict;
80
+ const booking = await modelPortFor(writer, {
81
+ key: writer.key,
82
+ label: writer.key,
83
+ beforeRequest: async (request) => {
84
+ const answer = await before(request);
85
+ verdict = (answer ?? undefined);
86
+ return answer;
87
+ },
88
+ // Its hold durable before it leaves: the booking awaits request_start once its runner.request is written.
89
+ ...(flush ? { onEvent: async (event) => { if (event.type === "request_start")
90
+ await flush(); } } : {}),
91
+ });
92
+ // A step an earlier claim admitted and that never answered: booked cut, counted at its hold and its bound.
93
+ await booking.bookCut();
94
+ const open = new Map();
95
+ return {
96
+ /** Books step `id`, asked as `asked` (its model key a decision's priced model, or a paid call's name). */
97
+ async book(id, asked) {
98
+ const key = asked.model;
99
+ verdict = undefined;
100
+ let ticket;
101
+ try {
102
+ ticket = await booking.models.beforeRequest(asked);
103
+ }
104
+ catch (error) {
105
+ forget(key);
106
+ const refused = lastVerdict();
107
+ if (refused?.refuse !== undefined)
108
+ throw new CapRefused(refused.refuse, { forGood: refused.forGood ?? true, spentUsd: refused.figures?.spentUsd ?? null, ...(refused.figures ? { figures: refused.figures } : {}) });
109
+ throw error;
110
+ }
111
+ if (!ticket)
112
+ throw new Error(`${what} ${id}: its booking gave it no ticket`);
113
+ const admitted = lastVerdict();
114
+ const held = typeof admitted?.holdUsd === "number" ? admitted.holdUsd : 0;
115
+ const bound = typeof admitted?.boundUsd === "number" ? admitted.boundUsd : 0;
116
+ open.set(id, { ticket, key, heldUsd: held });
117
+ return { id, heldUsd: held, boundUsd: bound, worstUsd: held + bound, stoppedUsd: () => held };
118
+ },
119
+ async settle(id, usd, options) {
120
+ const step = open.get(id);
121
+ if (!step)
122
+ throw new Error(`no ${what} ${id} is under way on this claim`);
123
+ open.delete(id);
124
+ forget(step.key);
125
+ await booking.models.afterRequest({ input: 0, output: 0, cacheRead: 0, usd, ...(options?.givenBack ? { givenBack: true } : {}) }, step.ticket);
126
+ return usd ?? step.heldUsd;
127
+ },
128
+ spentUsd: () => booking.spentUsd(),
129
+ heldUsd: () => [...open.values()].reduce((sum, step) => sum + step.heldUsd, 0),
130
+ };
131
+ }
132
+ }
@@ -0,0 +1,36 @@
1
+ import type { CapRefused } from "./admit.js";
2
+ import type { CapMarks } from "./marks.js";
3
+ /** A step the cap stopped for good: its path and the refusal. */
4
+ export declare class CapStop extends Error {
5
+ readonly path: string;
6
+ readonly refusal: CapRefused;
7
+ constructor(path: string, refusal: CapRefused);
8
+ }
9
+ export interface StepWaits {
10
+ /** A step under way, by its path. */
11
+ working(path: string): void;
12
+ /** A step that ended: it neither works nor waits. */
13
+ done(path: string): void;
14
+ /** The node path a provider session's requests belong to. */
15
+ session(sessionId: string, path: string): void;
16
+ /** A step's path: its own, else its provider session's node. */
17
+ pathOf(at: {
18
+ path?: string;
19
+ session?: string;
20
+ }): string;
21
+ /** The step at `path` waits for a raise; its wait mark is written first, and a mark not written counts no wait. */
22
+ wait(path: string, refusal: CapRefused): Promise<boolean>;
23
+ /** Raised: every waiting step works again. */
24
+ resume(): void;
25
+ /** Whether every step under way waits: the run may park. */
26
+ allWaiting(): boolean;
27
+ /** The steps a pause names. */
28
+ waitingFor(): string[];
29
+ /** Ends the step at `path` for good, kept by path. */
30
+ stop(path: string, refusal: CapRefused): CapStop;
31
+ stopped(path: string): CapStop | undefined;
32
+ }
33
+ export declare function createStepWaits({ marks, now }?: {
34
+ marks?: CapMarks;
35
+ now?: () => number;
36
+ }): StepWaits;
@@ -0,0 +1,64 @@
1
+ /** A step the cap stopped for good: its path and the refusal. */
2
+ export class CapStop extends Error {
3
+ path;
4
+ refusal;
5
+ constructor(path, refusal) {
6
+ super(refusal.message);
7
+ this.name = "CapStop";
8
+ this.path = path;
9
+ this.refusal = refusal;
10
+ }
11
+ }
12
+ export function createStepWaits({ marks, now = Date.now } = {}) {
13
+ const working = new Set();
14
+ const waiting = new Map();
15
+ const sessions = new Map();
16
+ const stops = new Map();
17
+ /** Each step's generation, and the resumes': a resume, done or stop bumps them, and a wait whose generation moved while
18
+ * its mark was written counts no wait (it was answered before it began). */
19
+ const generations = new Map();
20
+ let resumes = 0;
21
+ const bump = (path) => generations.set(path, (generations.get(path) ?? 0) + 1);
22
+ return {
23
+ working: (path) => void working.add(path),
24
+ done: (path) => {
25
+ bump(path);
26
+ working.delete(path);
27
+ waiting.delete(path);
28
+ },
29
+ session: (sessionId, path) => void sessions.set(sessionId, path),
30
+ pathOf: ({ path, session }) => {
31
+ if (path !== undefined)
32
+ return path;
33
+ const known = session === undefined ? undefined : sessions.get(session);
34
+ if (known === undefined)
35
+ throw new Error(`no step is known for provider session ${String(session)}: a request must name its node`);
36
+ return known;
37
+ },
38
+ async wait(path, refusal) {
39
+ const [step, resumed] = [generations.get(path) ?? 0, resumes];
40
+ await marks?.write({ kind: "wait", path, at: now() });
41
+ // Resumed, ended or stopped while the mark was written: the wait is answered already, never left behind; the caller
42
+ // reads false and goes on now, rather than blocking on a raise that has already landed.
43
+ if ((generations.get(path) ?? 0) !== step || resumes !== resumed)
44
+ return false;
45
+ waiting.set(path, refusal);
46
+ return true;
47
+ },
48
+ resume: () => {
49
+ resumes++;
50
+ waiting.clear();
51
+ },
52
+ allWaiting: () => working.size > 0 && [...working].every((path) => waiting.has(path)),
53
+ waitingFor: () => [...waiting.keys()],
54
+ stop(path, refusal) {
55
+ bump(path);
56
+ const stop = new CapStop(path, refusal);
57
+ stops.set(path, stop);
58
+ working.delete(path);
59
+ waiting.delete(path);
60
+ return stop;
61
+ },
62
+ stopped: (path) => stops.get(path),
63
+ };
64
+ }
@@ -0,0 +1,17 @@
1
+ type Blocks = {
2
+ content?: unknown;
3
+ } | undefined;
4
+ /** What a model answer streamed, in bytes: its text, its thinking, and each tool call's name and arguments as JSON. */
5
+ export declare function streamedBytes(message: Blocks): number;
6
+ /** What of a model answer's reasoning streamed, in bytes: its thinking blocks. */
7
+ export declare function reasoningBytes(message: Blocks): number;
8
+ /** The tokens a stopped request counts before the stop's allowance: what it streamed and the unstreamed part of its
9
+ * reasoning budget, within its output limit. A reasoning budget no one knows (a reasoning model sent with no level: its
10
+ * reasoning hidden, its effort unknown) is its whole output limit. */
11
+ export declare function stoppedTokens({ streamedBytes: streamed, reasoningBytes: reasoning, reasoningBudget, outputLimit }: {
12
+ streamedBytes: number;
13
+ reasoningBytes: number;
14
+ reasoningBudget: number | "unknown";
15
+ outputLimit: number;
16
+ }): number;
17
+ export {};
@@ -0,0 +1,34 @@
1
+ // What a stopped request streamed, as the cap counts it: each UTF-8 byte a token (a byte-level tokenizer never makes a
2
+ // token of less than one byte), its text, its thinking, and each tool call's name and arguments; and the part of a hidden
3
+ // reasoning budget it did not stream, which the provider may have spent before the stop. The figure books through
4
+ // booking.ts's `stopped` rule (its input, these tokens and the stop's allowance, within its output limit and its hold).
5
+ const blocksOf = (message) => (Array.isArray(message?.content) ? message.content : []);
6
+ /** What a model answer streamed, in bytes: its text, its thinking, and each tool call's name and arguments as JSON. */
7
+ export function streamedBytes(message) {
8
+ let bytes = 0;
9
+ for (const block of blocksOf(message)) {
10
+ if (typeof block?.text === "string")
11
+ bytes += Buffer.byteLength(block.text, "utf8");
12
+ if (typeof block?.thinking === "string")
13
+ bytes += Buffer.byteLength(block.thinking, "utf8");
14
+ if (block?.type === "toolCall")
15
+ bytes += Buffer.byteLength(`${typeof block.name === "string" ? block.name : ""}${JSON.stringify(block.arguments ?? {})}`, "utf8");
16
+ }
17
+ return bytes;
18
+ }
19
+ /** What of a model answer's reasoning streamed, in bytes: its thinking blocks. */
20
+ export function reasoningBytes(message) {
21
+ let bytes = 0;
22
+ for (const block of blocksOf(message))
23
+ if (typeof block?.thinking === "string")
24
+ bytes += Buffer.byteLength(block.thinking, "utf8");
25
+ return bytes;
26
+ }
27
+ /** The tokens a stopped request counts before the stop's allowance: what it streamed and the unstreamed part of its
28
+ * reasoning budget, within its output limit. A reasoning budget no one knows (a reasoning model sent with no level: its
29
+ * reasoning hidden, its effort unknown) is its whole output limit. */
30
+ export function stoppedTokens({ streamedBytes: streamed, reasoningBytes: reasoning, reasoningBudget, outputLimit }) {
31
+ if (reasoningBudget === "unknown")
32
+ return outputLimit;
33
+ return Math.min(outputLimit, streamed + Math.max(0, reasoningBudget - reasoning));
34
+ }
@@ -0,0 +1,151 @@
1
+ import type { Ended } from "../../booking.js";
2
+ import type { InputShape } from "../../host/overhead.js";
3
+ import type { CapMarks } from "./marks.js";
4
+ /** A model's rates, in USD per million tokens. No cache rates: the input rate. */
5
+ export interface PriceRates {
6
+ readonly input: number;
7
+ readonly output: number;
8
+ readonly cacheRead?: number;
9
+ readonly cacheWrite?: number;
10
+ }
11
+ /** A tier of a model's price, as the catalog gives it (pi-ai's cost tiers): its rates for a request whose whole input
12
+ * (fresh, cached and written to the cache) is above `inputTokensAbove` tokens. */
13
+ export interface PriceTier extends PriceRates {
14
+ readonly inputTokensAbove: number;
15
+ }
16
+ /** A model's list price, in USD per million tokens, as the catalog gives it: its base rates, and its tiers when the
17
+ * catalog has any (the catalog's own table, passed as given). */
18
+ export interface ModelPrice extends PriceRates {
19
+ readonly tiers?: readonly PriceTier[];
20
+ }
21
+ /** A model as the cap prices it: its API (what its provider adds server-side, and whether its thinking takes a budget),
22
+ * its price (null: none known), and its output ceiling (null: none). */
23
+ export interface CapModel {
24
+ readonly id: string;
25
+ readonly api: string;
26
+ readonly price: ModelPrice | null;
27
+ readonly outputCeiling: number | null;
28
+ readonly reasoning?: boolean;
29
+ }
30
+ /** The previous request of the conversation, as its usage reported it: what of its input was read from or written to
31
+ * the cache, the rest, its input bound (the unit this request's is in) and when it ended (ms), on which model. */
32
+ export interface Previous {
33
+ readonly model: string;
34
+ readonly cachedTokens: number;
35
+ readonly inputTokens: number;
36
+ readonly boundTokens: number;
37
+ readonly endedAt: number;
38
+ }
39
+ /** A model request about to be sent, from any harness (pi in process, a CLI's through the model proxy). */
40
+ export interface ModelCapRequest {
41
+ readonly kind: "model";
42
+ /** The request's own id: it holds and settles under it, so requests in flight together never share a hold. */
43
+ readonly id: string;
44
+ readonly model: CapModel;
45
+ /** Its input bound: one token per UTF-8 byte of what is sent. Undefined: not measured. */
46
+ readonly inputTokens: number | undefined;
47
+ /** What its provider adds server-side, by what it carries (tools, images). */
48
+ readonly shape?: InputShape;
49
+ /** What its hosted tools read into its input that its body does not hold (a native search's allowance). */
50
+ readonly extraInputTokens?: number;
51
+ /** The most its hosted tools may charge beside its tokens. */
52
+ readonly feeUsd?: number;
53
+ /** The output it asks for. Undefined: its model's ceiling. */
54
+ readonly outputAsked?: number;
55
+ /** The least output it may be limited to and still answer (the proxy's policy says). Absent: 1,024 for the answer, and
56
+ * its thinking's least. */
57
+ readonly outputTokensLeast?: number;
58
+ /** Its thinking budget, on an API whose thinking takes one beside the answer's output. */
59
+ readonly thinkingBudget?: number;
60
+ readonly previous?: Previous;
61
+ /** A side call (a title, a summary), never its turn's own. */
62
+ readonly side?: boolean;
63
+ /** It carries the cap's wrap-up note (Cap.note) in its body, its bytes in `inputTokens`: told once it is answered. */
64
+ readonly noted?: boolean;
65
+ }
66
+ /** A workflow decision about to be judged, held as main holds it (serve decision-cap.ts holdOf): its model at its
67
+ * catalog's price (`outputCeiling`: the catalog's most completion tokens), "unreadable" when the catalog could not be
68
+ * read for one. Its output is DECISION_OUTPUT_TOKENS a question (expected), or its model's most (strict); its input its
69
+ * state and questions' bytes plus DECISION_IMAGE_TOKENS an image; its fees the catalog's per request and per image. With
70
+ * no cap it is not priced at all. */
71
+ export interface DecisionCapRequest {
72
+ readonly kind: "decision";
73
+ readonly id: string;
74
+ readonly model: CapModel | "unreadable";
75
+ /** The UTF-8 bytes of its state and questions as JSON, one token a byte. */
76
+ readonly inputTokens: number;
77
+ /** How many questions it asks. */
78
+ readonly questions: number;
79
+ /** How many images it sends. */
80
+ readonly images?: number;
81
+ /** The catalog's price per request and per image, in USD. */
82
+ readonly requestUsd?: number;
83
+ readonly imageUsd?: number;
84
+ }
85
+ /** A priced tool call about to be made: held at its quote, or its allowance, until it is charged. */
86
+ export interface ToolCapRequest {
87
+ readonly kind: "tool";
88
+ readonly id: string;
89
+ readonly name: string;
90
+ readonly holdUsd: number;
91
+ /** Why it is held at that: "its quote", "the allowance". */
92
+ readonly basis: string;
93
+ }
94
+ export type CapRequest = ModelCapRequest | ToolCapRequest | DecisionCapRequest;
95
+ /** A step the cap let go: what it is held at until it settles (a model request's expected cost at the output it may be
96
+ * sent with, its worst case under strict), the most a cache miss can add (`boundUsd`), its worst case, and for a model
97
+ * request the output it is limited to and what it counts at if stopped having streamed that many tokens. */
98
+ export interface Admission {
99
+ readonly id: string;
100
+ readonly heldUsd: number;
101
+ readonly boundUsd: number;
102
+ readonly worstUsd: number;
103
+ readonly outputTokensMax?: number;
104
+ readonly thinkingBudget?: number;
105
+ stoppedUsd(streamedTokens: number): number;
106
+ }
107
+ /** A refusal for room's figures, beside its words: what the cap counted as taken, the least the step needs, and the least
108
+ * cap that sends it (the figure its words name). */
109
+ export interface RefusalFigures {
110
+ readonly spentUsd: number;
111
+ readonly needsUsd: number;
112
+ readonly leastCapUsd: number;
113
+ readonly boundUsd?: number;
114
+ }
115
+ /** How a step ended, for settle: a model request's as booking.ts reads it; a paid call's charge (null: it did not say). */
116
+ export type Settled = Ended | {
117
+ end: "charged";
118
+ usd: number | null;
119
+ };
120
+ export interface CapOptions {
121
+ /** The run's cap, read before every paid check, so a raise holds from the next one. Undefined: no cap. */
122
+ capUsd(): number | undefined;
123
+ mode?: CapMode;
124
+ /** What the run has spent when the cap opens (null: unknown). openCap reads it from `marks`. */
125
+ spentUsd?: number | null;
126
+ now?: () => number;
127
+ /** Where each step's start and end marks go (the journal binds it); none: the cap keeps no marks. */
128
+ marks?: CapMarks;
129
+ /** How long settle waits for a step's end mark before it fails loudly. Default 10 s. */
130
+ endMarkWaitMs?: number;
131
+ }
132
+ /** How the cap prices a request's input: "expected" from the previous request's cache; "strict" every token uncached. */
133
+ export type CapMode = "expected" | "strict";
134
+ export interface Cap {
135
+ admit(request: CapRequest): Promise<Admission>;
136
+ /** Books a step that ended, its hold let go: a model request by how it ended, a paid call at its charge (its hold when
137
+ * it said none). Answers its figure. */
138
+ settle(id: string, ended: Settled): Promise<number | null>;
139
+ /** A request's least admission: its input and least output at its price, the figure admit refuses it below. */
140
+ leastUsd(request: ModelCapRequest): number;
141
+ spentUsd(): number | null;
142
+ heldUsd(): number;
143
+ /** The wrap-up note for `request`, the run's next main-model request measured before the note is placed, when it is
144
+ * due and not yet told; none for a side call, or when the request fits what is left only without the note's bytes. */
145
+ note(request: ModelCapRequest): {
146
+ words: string;
147
+ leftUsd: number;
148
+ } | undefined;
149
+ /** The run's own priced answers on `model`, the wrap-up's typical cost's costs. */
150
+ ownCosts(model: string): number[];
151
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,39 @@
1
+ import type { RefusalFigures } from "./types.js";
2
+ /** What every refusal begins with. */
3
+ export declare const SPEND_CAP_REACHED = "spend_cap_reached";
4
+ /** What a refusal for room begins with. */
5
+ export declare const CAP_REFUSAL_CODE = "spend_cap_reached (out of budget): ";
6
+ /** How many of the refused request's least a run parked at its cap is offered on top of what was taken. */
7
+ export declare const SUGGESTED_RAISE_FACTOR = 10;
8
+ /** An amount in words: a whole number of dollars as given ($1), else two decimals or as many as it takes, up to eight. */
9
+ export declare function money(usd: number): string;
10
+ /** An amount to the nearest cent, as money says it. */
11
+ export declare const centsMoney: (usd: number) => string;
12
+ /** A least in words: rounded up to the cent within a float's tail, so that it is enough ($0.1024 is $0.11). */
13
+ export declare const leastMoney: (usd: number) => string;
14
+ /** The cap to raise to for a step past `cap` that needs `total` in all: whole cents, a cent at least, above the cap. */
15
+ export declare const raiseFigure: (cap: number, total: number) => number;
16
+ export declare const raiseTo: (cap: number, total: number) => string;
17
+ /** The raise a run parked at its cap is offered: what was taken plus 10 times the refused step's least, rounded up to a
18
+ * whole dollar (a hair under, so a float just past a dollar stays that dollar), and above the cap past a float's tail. */
19
+ export declare const suggestedRaise: (cap: number, spentUsd: number, needsUsd: number) => number;
20
+ /** A model request what is left cannot buy the least of. */
21
+ export declare function roomRefusal(cap: number, spent: number, held: number, least: number, boundUsd?: number): {
22
+ text: string;
23
+ figures: RefusalFigures;
24
+ };
25
+ /** A paid call what is left cannot hold. */
26
+ export declare function paidRefusal(cap: number, spent: number, held: number, name: string, holdUsd: number, basis: string): {
27
+ text: string;
28
+ figures: RefusalFigures;
29
+ };
30
+ /** The over-cap row's words, after the usage row whose booked cost `spentUsd` passed `capUsd`: by how much; when it passed
31
+ * by no more than `boundUsd` (the bound of the requests since the cost last fit), a cache miss did it, and the most it
32
+ * could have. None at or under the cap, with no cap, or with no known cost. */
33
+ export declare function overCapWords(spentUsd: number | null, capUsd: number | undefined, boundUsd?: number): string | undefined;
34
+ export declare const unmeasured: (cap: number) => string;
35
+ export declare const noPrice: (cap: number) => string;
36
+ export declare const noCeiling: (cap: number) => string;
37
+ export declare const noToolPrice: (cap: number, name: string) => string;
38
+ export declare const unknownSpend: (cap: number) => string;
39
+ export declare const unknownHeld: (cap: number) => string;
@@ -0,0 +1,75 @@
1
+ // The kernel cap's words, as a person who has never seen a model request reads them: what the run spent (and holds for
2
+ // steps still running) of its cap, what the next step needs at the least, and the cap to raise to, to continue. A
3
+ // refusal for room begins CAP_REFUSAL_CODE ("out of budget", which keeps it final to pi-ai's retry whatever digits its
4
+ // words hold); a refusal no cap could fix begins the bare code.
5
+ import { CAP_TOLERANCE, FIT_TOLERANCE } from "./price.js";
6
+ /** What every refusal begins with. */
7
+ export const SPEND_CAP_REACHED = "spend_cap_reached";
8
+ /** What a refusal for room begins with. */
9
+ export const CAP_REFUSAL_CODE = `${SPEND_CAP_REACHED} (out of budget): `;
10
+ /** How many of the refused request's least a run parked at its cap is offered on top of what was taken. */
11
+ export const SUGGESTED_RAISE_FACTOR = 10;
12
+ /** An amount in words: a whole number of dollars as given ($1), else two decimals or as many as it takes, up to eight. */
13
+ export function money(usd) {
14
+ if (Number.isInteger(usd))
15
+ return `$${usd}`;
16
+ for (let digits = 2; digits < 8; digits++)
17
+ if (Number(usd.toFixed(digits)) === Number(usd.toFixed(8)))
18
+ return `$${usd.toFixed(digits)}`;
19
+ return `$${usd.toFixed(8)}`;
20
+ }
21
+ /** An amount to the nearest cent, as money says it. */
22
+ export const centsMoney = (usd) => money(Math.round(usd * 100) / 100);
23
+ /** A least in words: rounded up to the cent within a float's tail, so that it is enough ($0.1024 is $0.11). */
24
+ export const leastMoney = (usd) => `$${(Math.ceil(usd * 100 - FIT_TOLERANCE * 100) / 100).toFixed(2)}`;
25
+ /** The cap to raise to for a step past `cap` that needs `total` in all: whole cents, a cent at least, above the cap. */
26
+ export const raiseFigure = (cap, total) => {
27
+ const cents = Math.ceil(total * 100 - FIT_TOLERANCE * 100);
28
+ return (cents / 100 > cap + CAP_TOLERANCE ? cents : Math.floor((cap + CAP_TOLERANCE) * 100) + 1) / 100;
29
+ };
30
+ export const raiseTo = (cap, total) => `$${raiseFigure(cap, total).toFixed(2)}`;
31
+ /** The raise a run parked at its cap is offered: what was taken plus 10 times the refused step's least, rounded up to a
32
+ * whole dollar (a hair under, so a float just past a dollar stays that dollar), and above the cap past a float's tail. */
33
+ export const suggestedRaise = (cap, spentUsd, needsUsd) => {
34
+ const up = Math.ceil(spentUsd + SUGGESTED_RAISE_FACTOR * needsUsd - 1e-9);
35
+ return up > cap + CAP_TOLERANCE ? up : Math.floor(cap + CAP_TOLERANCE) + 1;
36
+ };
37
+ /** What a run has spent of its cap: and what it holds for steps still running, when that is a cent or more. */
38
+ const spentOf = (spent, held, cap) => {
39
+ const holds = centsMoney(held);
40
+ return holds !== "$0" ? `spent ${centsMoney(spent)} and holds ${holds} for steps still running, of its ${money(cap)} cap` : `spent ${centsMoney(spent)} of its ${money(cap)} cap`;
41
+ };
42
+ /** A model request what is left cannot buy the least of. */
43
+ export function roomRefusal(cap, spent, held, least, boundUsd) {
44
+ const leastCapUsd = raiseFigure(cap, spent + held + least);
45
+ const figures = { spentUsd: spent + held, needsUsd: least, leastCapUsd, ...(boundUsd && boundUsd > 0 ? { boundUsd } : {}) };
46
+ const [need, raise] = [leastMoney(least), `$${leastCapUsd.toFixed(2)}`];
47
+ if (spent === 0 && held === 0)
48
+ return { text: `${CAP_REFUSAL_CODE}Not sent: the next step needs at least ${need}, and this run's cap is ${money(cap)}. Raise the cap to at least ${raise} to continue.`, figures };
49
+ return { text: `${CAP_REFUSAL_CODE}Not sent: this run has ${spentOf(spent, held, cap)}, and the next step needs at least ${need}. Raise the cap to at least ${raise} to continue.`, figures };
50
+ }
51
+ /** A paid call what is left cannot hold. */
52
+ export function paidRefusal(cap, spent, held, name, holdUsd, basis) {
53
+ const leastCapUsd = raiseFigure(cap, spent + held + holdUsd);
54
+ return {
55
+ text: `${SPEND_CAP_REACHED}: Not sent: this run has ${spentOf(spent, held, cap)}, and the next step, ${name}, could cost up to ${money(holdUsd)} (${basis}). Raise the cap to at least $${leastCapUsd.toFixed(2)} to continue.`,
56
+ figures: { spentUsd: spent + held, needsUsd: holdUsd, leastCapUsd },
57
+ };
58
+ }
59
+ /** An amount rounded up to the cent, so "at most" holds. */
60
+ const centsUp = (usd) => money(Math.ceil(usd * 100 - 1e-9) / 100);
61
+ /** The over-cap row's words, after the usage row whose booked cost `spentUsd` passed `capUsd`: by how much; when it passed
62
+ * by no more than `boundUsd` (the bound of the requests since the cost last fit), a cache miss did it, and the most it
63
+ * could have. None at or under the cap, with no cap, or with no known cost. */
64
+ export function overCapWords(spentUsd, capUsd, boundUsd = 0) {
65
+ if (capUsd === undefined || typeof spentUsd !== "number" || spentUsd <= capUsd + FIT_TOLERANCE)
66
+ return undefined;
67
+ const byMiss = boundUsd > 0 && spentUsd - capUsd <= boundUsd + FIT_TOLERANCE;
68
+ return byMiss ? `Went ${centsUp(spentUsd - capUsd)} over its cap on a cache miss (at most ${centsUp(boundUsd)}).` : `Spent ${centsMoney(spentUsd)}, ${centsUp(spentUsd - capUsd)} over the run's cap of ${centsMoney(capUsd)}`;
69
+ }
70
+ export const unmeasured = (cap) => `${SPEND_CAP_REACHED}: Not sent: the size of the next model request's input is unknown, so the run's cap of ${money(cap)} cannot be kept: the run is out of budget.`;
71
+ export const noPrice = (cap) => `${SPEND_CAP_REACHED}: Not sent: the next model request's model has no price here, so the run's cap of ${money(cap)} cannot be kept: the run is out of budget.`;
72
+ export const noCeiling = (cap) => `${SPEND_CAP_REACHED}: Not sent: the next model request's model has no output ceiling here and its output is priced, so what a request may cost has no bound and the run's cap of ${money(cap)} cannot be kept: the run is out of budget.`;
73
+ export const noToolPrice = (cap, name) => `${SPEND_CAP_REACHED}: Not sent: the next step, ${name}, has no price here, so the run's cap of ${money(cap)} cannot be kept: the run is out of budget.`;
74
+ export const unknownSpend = (cap) => `${SPEND_CAP_REACHED}: Not sent: what the run has spent is unknown, so its cap of ${money(cap)} cannot be kept: the run is out of budget.`;
75
+ export const unknownHeld = (cap) => `${SPEND_CAP_REACHED}: Not sent: what the run's steps still running hold is unknown, so its cap of ${money(cap)} cannot be kept: the run is out of budget.`;