@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
@@ -6,5 +6,6 @@ export function serialWriter(writer) {
6
6
  chain = run.catch(() => undefined);
7
7
  return run;
8
8
  };
9
- return { key: writer.key, read: () => next(() => writer.read()), append: (records) => next(() => writer.append(records)) };
9
+ // The barrier goes on the same chain: it syncs what the appends before it wrote.
10
+ return { key: writer.key, read: () => next(() => writer.read()), append: (records) => next(() => writer.append(records)), sync: () => next(() => writer.sync()) };
10
11
  }
package/dist/index.d.ts CHANGED
@@ -1,8 +1,9 @@
1
- export { createHarnessRunner, modelPortFor, SUBMIT_TOOL, RUNNER_RECORDS } from "./runner.js";
2
- export type { Admission, BeforeRequest, HarnessRunner, HarnessRunnerOptions, InFlight, ModelBooking, ModelPortEvent, ModelPortOptions } from "./runner.js";
1
+ export { 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";
3
4
  export { DELEGATE_RESULT_SCHEMA, DELEGATE_TOOL, delegateProblems, delegateTool } from "./delegate.js";
4
5
  export type { DelegateAgent, DelegateEvent, DelegateOptions } from "./delegate.js";
5
- export { HarnessRunError, SessionFenced } from "./errors.js";
6
+ export { HarnessRunError, SessionFenced, TurnParked } from "./errors.js";
6
7
  export { toolSchemaProblems } from "./schema-check.js";
7
8
  export { READ_SKILL_FILE, readSkillFileTool, SKILL_BYTES, skillProblems } from "./skill-files.js";
8
9
  export type { HostSkill, SkillFileList } from "./skill-files.js";
@@ -10,4 +11,4 @@ export type { HarnessRunReason } from "./errors.js";
10
11
  export { CONTENT_FILTERED, HOST_RESULT_MAX_CHARS } from "./types.js";
11
12
  export { bookRequest, isConnectCode, isGatewayTimeout, rejectionCode } from "./booking.js";
12
13
  export type { Booked, Ended, Priced } from "./booking.js";
13
- export type { AdapterCapabilities, AdapterEvent, AdapterSession, AgentAdapter, HarnessEvent, HostTool, ToolImage, JsonValue, ModelPort, ModelTicket, ModelRequest, ModelUsage, NodeRequest, SessionIO, SessionRecord, SessionSpec, SessionState, SessionStore, SessionWriter, TurnStatus, } from "./types.js";
14
+ export type { AdapterCapabilities, AdapterEvent, AdapterSession, AgentAdapter, AdapterFacts, GateAnswer, GateCall, SessionPort, Wire, HarnessEvent, HostTool, McpCallResult, McpClient, McpTool, ToolImage, JsonValue, ModelPort, ModelTicket, ModelRequest, ModelUsage, NoteRequest, NodeRequest, SessionIO, SessionMcp, SessionRecord, SessionSpec, SessionState, SessionStore, SessionWriter, TurnStatus, } from "./types.js";
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
- export { createHarnessRunner, modelPortFor, SUBMIT_TOOL, RUNNER_RECORDS } from "./runner.js";
1
+ export { createHarnessRunner, modelPortFor, sessionSpendOf, SUBMIT_TOOL, RUNNER_RECORDS } from "./runner.js";
2
+ export { runBooking } from "./run-booking.js";
2
3
  export { DELEGATE_RESULT_SCHEMA, DELEGATE_TOOL, delegateProblems, delegateTool } from "./delegate.js";
3
- export { HarnessRunError, SessionFenced } from "./errors.js";
4
+ export { HarnessRunError, SessionFenced, TurnParked } from "./errors.js";
4
5
  export { toolSchemaProblems } from "./schema-check.js";
5
6
  export { READ_SKILL_FILE, readSkillFileTool, SKILL_BYTES, skillProblems } from "./skill-files.js";
6
7
  export { CONTENT_FILTERED, HOST_RESULT_MAX_CHARS } from "./types.js";
@@ -0,0 +1,35 @@
1
+ import type { CapMarks } from "./marks.js";
2
+ import { CapRefused, DecisionPriceUnreadable } from "./errors.js";
3
+ import type { Cap, CapMode, CapModel, CapOptions, DecisionCapRequest } from "./types.js";
4
+ export { CapRefused, DecisionPriceUnreadable };
5
+ /** A step whose start mark could not be written is not sent. */
6
+ export declare const MARK_NOT_WRITTEN = "the model request was not sent: its mark could not be written";
7
+ /** A step whose end mark did not land within its wait. */
8
+ export declare const END_NOT_WRITTEN = "the model request's end could not be recorded";
9
+ export declare const END_MARK_WAIT_MS = 10000;
10
+ /** The cap of a run opened again: what it has spent read from its marks (recover.ts), a step a crash cut at its hold, its
11
+ * own priced answers and whether its wrap-up was told. */
12
+ export declare function openCap(options: CapOptions & {
13
+ marks: CapMarks;
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
+ /** An image's input allowance, in tokens (main's DECISION_IMAGE_TOKENS: a 1568 px square at 750 pixels a token). */
18
+ 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): {
24
+ model: CapModel;
25
+ inputTokens: number;
26
+ output: number | null;
27
+ feeUsd: number;
28
+ };
29
+ export declare function createCap(options: CapOptions, seed?: {
30
+ costs?: {
31
+ model: string;
32
+ usd: number;
33
+ }[];
34
+ told?: boolean;
35
+ }): Cap;
@@ -0,0 +1,186 @@
1
+ // createCap: the kernel cap on its own ledger (pi in process, decisions, priced tools), every decision by the one rule
2
+ // (rule.ts capRule.judge) and every note by noteFor. Before each step what the run has spent, plus what its steps under
3
+ // way hold, plus what this step needs at the least, must stay within the cap, read before every check so a raise holds
4
+ // from the next paid step. Each step holds under its own id until it settles; its start mark (with its hold) is written
5
+ // before it leaves, its end mark (with what booking.ts booked) before its result comes back.
6
+ import { Ledger, StepNotSettled } from "./ledger.js";
7
+ import { ownCostsOf, spendOf, toldIn } from "./recover.js";
8
+ import { capRule, noteFor, priced } from "./rule.js";
9
+ import { CapRefused, DecisionPriceUnreadable } from "./errors.js";
10
+ export { CapRefused, DecisionPriceUnreadable };
11
+ const NO_HOLD = (id) => ({ id, heldUsd: 0, boundUsd: 0, worstUsd: 0, stoppedUsd: () => 0 });
12
+ /** A step whose start mark could not be written is not sent. */
13
+ export const MARK_NOT_WRITTEN = "the model request was not sent: its mark could not be written";
14
+ /** A step whose end mark did not land within its wait. */
15
+ export const END_NOT_WRITTEN = "the model request's end could not be recorded";
16
+ export const END_MARK_WAIT_MS = 10_000;
17
+ /** The cap of a run opened again: what it has spent read from its marks (recover.ts), a step a crash cut at its hold, its
18
+ * own priced answers and whether its wrap-up was told. */
19
+ export async function openCap(options) {
20
+ const read = await options.marks.read();
21
+ const spent = spendOf(read).spentUsd;
22
+ return createCap({ ...options, spentUsd: options.spentUsd === undefined ? spent : options.spentUsd }, { costs: ownCostsOf(read), told: toldIn(read) });
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
+ /** An image's input allowance, in tokens (main's DECISION_IMAGE_TOKENS: a 1568 px square at 750 pixels a token). */
27
+ 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) {
33
+ if (request.model === "unreadable")
34
+ throw new DecisionPriceUnreadable();
35
+ 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
+ const feeUsd = (request.requestUsd ?? 0) + (request.imageUsd ?? 0) * images;
39
+ return { model, inputTokens: request.inputTokens + images * DECISION_IMAGE_TOKENS, output, feeUsd };
40
+ }
41
+ const asModel = (request, mode) => {
42
+ const { model, inputTokens, output, feeUsd } = decisionAsk(request, mode);
43
+ return {
44
+ kind: "model",
45
+ id: request.id,
46
+ model,
47
+ inputTokens,
48
+ ...(feeUsd > 0 ? { feeUsd } : {}),
49
+ ...(output === null ? {} : { outputAsked: output, outputTokensLeast: output }),
50
+ };
51
+ };
52
+ /** A decision under no cap: not priced (main lets it go unpriced), so nothing is read and nothing refused. */
53
+ const unpriced = (request) => ({
54
+ kind: "model",
55
+ id: request.id,
56
+ model: { id: request.model === "unreadable" ? "unreadable" : request.model.id, api: "decision", price: null, outputCeiling: null },
57
+ inputTokens: request.inputTokens,
58
+ });
59
+ export function createCap(options, seed = {}) {
60
+ const mode = options.mode ?? "expected";
61
+ const now = options.now ?? Date.now;
62
+ const ledger = new Ledger(options.spentUsd === undefined ? 0 : options.spentUsd);
63
+ const marks = options.marks;
64
+ const costs = [...(seed.costs ?? [])];
65
+ let told = seed.told ?? false;
66
+ /** The note last offered, which the told mark keeps once a request carrying it is answered. */
67
+ let offered;
68
+ /** What each model request under way is, for its settle. */
69
+ const steps = new Map();
70
+ const ownCosts = (model) => costs.filter((cost) => cost.model === model).map((cost) => cost.usd);
71
+ /** Each step's settle, by id: its booking and which of its marks landed, so a retry books nothing twice. */
72
+ const settlements = new Map();
73
+ /** A refused step's own start mark, before its refusal is thrown; a mark that fails still ends it with the refusal. */
74
+ const refusing = async (id, refusal, extra) => {
75
+ await marks?.write({ kind: "start", id, at: now(), heldUsd: 0, refused: true, ...extra }).catch(() => undefined);
76
+ throw refusal;
77
+ };
78
+ /** A step's start mark, before it leaves: one that fails lets its hold go and the step is not sent. */
79
+ const started = async (admission, extra, heldUsd = admission.heldUsd) => {
80
+ if (!marks)
81
+ return admission;
82
+ try {
83
+ await marks.write({ kind: "start", id: admission.id, at: now(), heldUsd, ...(admission.boundUsd > 0 ? { boundUsd: admission.boundUsd } : {}), ...extra });
84
+ }
85
+ catch {
86
+ ledger.release(admission.id);
87
+ throw new Error(MARK_NOT_WRITTEN);
88
+ }
89
+ return admission;
90
+ };
91
+ /** A write of an end's marks within END_MARK_WAIT_MS: past it, or failed, the step's result fails loudly. */
92
+ const withinWait = async (write) => {
93
+ const wait = options.endMarkWaitMs ?? END_MARK_WAIT_MS;
94
+ let timer;
95
+ try {
96
+ await Promise.race([write, new Promise((_, reject) => (timer = setTimeout(() => reject(new Error(`${END_NOT_WRITTEN}: its end mark did not land within ${wait} ms`)), wait)))]);
97
+ }
98
+ catch (error) {
99
+ throw new Error(error instanceof Error && error.message.startsWith(END_NOT_WRITTEN) ? error.message : `${END_NOT_WRITTEN}: ${String(error)}`);
100
+ }
101
+ finally {
102
+ clearTimeout(timer);
103
+ }
104
+ };
105
+ return {
106
+ async admit(input) {
107
+ // Read before every check: a raise holds from the next paid step. A decision under no cap is not priced.
108
+ const capUsd = options.capUsd();
109
+ const request = input.kind !== "decision" ? input : capUsd === undefined ? unpriced(input) : asModel(input, mode);
110
+ // An id whose last step's marks are not all written is not used again until its settle is retried: else that retry
111
+ // finds the new step's hold and settles it at the old step's figure.
112
+ const last = settlements.get(request.id);
113
+ if (marks && last && (!last.endWritten || (last.tells && !last.toldWritten)))
114
+ throw new StepNotSettled(request.id);
115
+ const extra = request.kind === "tool" ? { tool: request.name } : { model: request.model.id, ...(request.side ? { side: true } : {}) };
116
+ let admission;
117
+ if (capUsd === undefined) {
118
+ admission = NO_HOLD(request.id);
119
+ // Nothing held with no cap: a figure its end never says is unknown.
120
+ ledger.hold(request.id, { usd: null });
121
+ }
122
+ else {
123
+ try {
124
+ const judged = capRule.judge(request, { capUsd, spentUsd: ledger.spent(), heldUsd: ledger.held(), mode, now: now() });
125
+ admission = { id: request.id, ...judged };
126
+ }
127
+ catch (error) {
128
+ if (error instanceof CapRefused)
129
+ return refusing(request.id, error, extra);
130
+ throw error;
131
+ }
132
+ // Every step holds, a $0 one too: its settle then books a known figure (its charge, else its $0 hold).
133
+ ledger.hold(request.id, { usd: admission.heldUsd, stoppedPrice: admission.stoppedUsd });
134
+ }
135
+ // A new step under an id whose last step settled: it settles on its own.
136
+ settlements.delete(request.id);
137
+ // With no cap nothing was held: its start mark holds no figure, so a crash before its end reopens as unknown.
138
+ const sent = await started(admission, extra, capUsd === undefined ? null : admission.heldUsd);
139
+ if (request.kind === "model")
140
+ steps.set(request.id, { model: request.model.id, side: request.side === true, noted: request.noted === true });
141
+ return sent;
142
+ },
143
+ async settle(id, ended) {
144
+ // Booked once: a settle retried after its marks failed reuses the first booking, its costs and its note.
145
+ // A step under way under `id` settles afresh; with none, a retry answers the last settle, and an id never held is
146
+ // refused (StepNotHeld), nothing booked.
147
+ let settled = ledger.holds(id) ? undefined : settlements.get(id);
148
+ if (!settled) {
149
+ const { usd, rule } = ledger.settle(id, ended);
150
+ const step = steps.get(id);
151
+ steps.delete(id);
152
+ const answered = rule.startsWith("answered");
153
+ if (step && !step.side && answered && typeof usd === "number" && usd > 0)
154
+ costs.push({ model: step.model, usd });
155
+ // The note is told once the request carrying it is answered, never before.
156
+ const tells = step?.noted === true && answered && !told;
157
+ if (tells)
158
+ told = true;
159
+ settled = { usd, rule, tells, endWritten: false, toldWritten: false };
160
+ settlements.set(id, settled);
161
+ }
162
+ if (marks && !settled.endWritten) {
163
+ await withinWait(marks.write({ kind: "end", id, at: now(), usd: settled.usd, rule: settled.rule }));
164
+ settled.endWritten = true;
165
+ }
166
+ if (marks && settled.tells && !settled.toldWritten) {
167
+ await withinWait(marks.write({ kind: "told", id, at: now(), words: offered?.words ?? "", leftUsd: offered?.leftUsd ?? 0 }));
168
+ settled.toldWritten = true;
169
+ }
170
+ return settled.usd;
171
+ },
172
+ leastUsd(request) {
173
+ const p = priced(request, mode, now());
174
+ return p ? p.cost(p.least) : Number.NaN;
175
+ },
176
+ 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() });
178
+ if (note)
179
+ offered = note;
180
+ return note;
181
+ },
182
+ ownCosts,
183
+ spentUsd: () => ledger.spent(),
184
+ heldUsd: () => ledger.held(),
185
+ };
186
+ }
@@ -0,0 +1,20 @@
1
+ import type { RefusalFigures } from "./types.js";
2
+ /** The cap's refusal: `forGood` when no raise could send the step (the run fails, never parks), else a refusal for room
3
+ * with its figures (the run parks, offered the raise its words name). */
4
+ export declare class CapRefused extends Error {
5
+ readonly code = "spend_cap_reached";
6
+ readonly forGood: boolean;
7
+ readonly spentUsd: number | null;
8
+ readonly figures?: RefusalFigures;
9
+ constructor(message: string, { forGood, spentUsd, figures }: {
10
+ forGood: boolean;
11
+ spentUsd: number | null;
12
+ figures?: RefusalFigures;
13
+ });
14
+ }
15
+ /** A decision whose model's price could not be read: it fails unsent as a connection error (read again next time), never
16
+ * as the cap's stop. */
17
+ export declare class DecisionPriceUnreadable extends Error {
18
+ readonly connection = true;
19
+ constructor();
20
+ }
@@ -0,0 +1,25 @@
1
+ /** The cap's refusal: `forGood` when no raise could send the step (the run fails, never parks), else a refusal for room
2
+ * with its figures (the run parks, offered the raise its words name). */
3
+ export class CapRefused extends Error {
4
+ code = "spend_cap_reached";
5
+ forGood;
6
+ spentUsd;
7
+ figures;
8
+ constructor(message, { forGood, spentUsd, figures }) {
9
+ super(message);
10
+ this.name = "CapRefused";
11
+ this.forGood = forGood;
12
+ this.spentUsd = spentUsd;
13
+ if (figures)
14
+ this.figures = figures;
15
+ }
16
+ }
17
+ /** A decision whose model's price could not be read: it fails unsent as a connection error (read again next time), never
18
+ * as the cap's stop. */
19
+ export class DecisionPriceUnreadable extends Error {
20
+ connection = true;
21
+ constructor() {
22
+ super("the decision was not sent: its model's price could not be read from the catalog");
23
+ this.name = "DecisionPriceUnreadable";
24
+ }
25
+ }
@@ -0,0 +1,14 @@
1
+ export { CapRefused, createCap, DECISION_IMAGE_TOKENS, DECISION_OUTPUT_TOKENS, DecisionPriceUnreadable, END_MARK_WAIT_MS, END_NOT_WRITTEN, MARK_NOT_WRITTEN, openCap } from "./admit.js";
2
+ export { capRule, noteFor, type Judged, type JudgeState, type NoteState } from "./rule.js";
3
+ export { beforeRequestOf, type BeforeRequestOptions } from "./port.js";
4
+ export { DECISION_SESSION, paidCalls, runCap, TOOL_SESSION, type RunCap, type RunCapOptions, type RunDecisions, type RunTools } from "./run-cap.js";
5
+ export { ANSWER_TOKENS_LEAST, CACHE_WARM_MS, CAP_TOLERANCE, FIT_TOLERANCE, STOP_ALLOWANCE_TOKENS, THINKING_BUDGET_LEAST, expectedInput, inputBound, mostOutput, pricingOf, ratesFor, requestPrice } from "./price.js";
6
+ export { CAP_REFUSAL_CODE, SPEND_CAP_REACHED, SUGGESTED_RAISE_FACTOR, centsMoney, leastMoney, money, overCapWords, raiseFigure, raiseTo, suggestedRaise } from "./words.js";
7
+ 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 { CapStop, createStepWaits, type StepWaits } from "./steps.js";
10
+ export { memoryMarks, type CapMark, type CapMarks, type EndMark, type StartMark, type ToldMark, type WaitMark } from "./marks.js";
11
+ export { ownCostsOf, spendOf, toldIn, type Spend } from "./recover.js";
12
+ export { StepNotHeld, StepNotSettled } from "./ledger.js";
13
+ export { reasoningBytes, stoppedTokens, streamedBytes } from "./stopped.js";
14
+ export type { Admission, Cap, CapMode, CapModel, CapOptions, CapRequest, DecisionCapRequest, ModelCapRequest, ModelPrice, PriceRates, PriceTier, Previous, RefusalFigures, Settled, ToolCapRequest } from "./types.js";
@@ -0,0 +1,15 @@
1
+ // The kernel cap (kernel tangle 2: the cap lives in the kernel, the same for every harness). Not exported from the
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";
4
+ export { capRule, noteFor } from "./rule.js";
5
+ export { beforeRequestOf } from "./port.js";
6
+ export { DECISION_SESSION, paidCalls, runCap, TOOL_SESSION } from "./run-cap.js";
7
+ export { ANSWER_TOKENS_LEAST, CACHE_WARM_MS, CAP_TOLERANCE, FIT_TOLERANCE, STOP_ALLOWANCE_TOKENS, THINKING_BUDGET_LEAST, expectedInput, inputBound, mostOutput, pricingOf, ratesFor, requestPrice } from "./price.js";
8
+ export { CAP_REFUSAL_CODE, SPEND_CAP_REACHED, SUGGESTED_RAISE_FACTOR, centsMoney, leastMoney, money, overCapWords, raiseFigure, raiseTo, suggestedRaise } from "./words.js";
9
+ 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 { CapStop, createStepWaits } from "./steps.js";
12
+ export { memoryMarks } from "./marks.js";
13
+ export { ownCostsOf, spendOf, toldIn } from "./recover.js";
14
+ export { StepNotHeld, StepNotSettled } from "./ledger.js";
15
+ export { reasoningBytes, stoppedTokens, streamedBytes } from "./stopped.js";
@@ -0,0 +1,37 @@
1
+ import type { Settled } from "./types.js";
2
+ /** A step under way: what it is held at (null with no cap: nothing held, an unknown figure if it never says its cost),
3
+ * and for a model request what it counts at if stopped having streamed that many. */
4
+ export type Hold = {
5
+ readonly usd: number | null;
6
+ readonly stoppedPrice?: (streamedTokens: number) => number;
7
+ };
8
+ export type Booking = {
9
+ readonly usd: number | null;
10
+ readonly rule: string;
11
+ };
12
+ /** A settle of an id the ledger never held: refused, nothing booked. */
13
+ export declare class StepNotHeld extends Error {
14
+ readonly id: string;
15
+ constructor(id: string);
16
+ }
17
+ /** An admit of an id whose last step's end mark (or told mark) is not written yet: refused, nothing held or marked. Its
18
+ * settle must be retried first, else that retry would settle the new step at the old step's figure. */
19
+ export declare class StepNotSettled extends Error {
20
+ readonly id: string;
21
+ constructor(id: string);
22
+ }
23
+ export declare class Ledger {
24
+ #private;
25
+ constructor(spentUsd: number | null);
26
+ spent(): number | null;
27
+ held(): number;
28
+ /** Whether a step is under way under `id`. */
29
+ holds(id: string): boolean;
30
+ /** Holds a step under `id`: refused while another step holds under it; an id whose step settled is free again. */
31
+ hold(id: string, hold: Hold): void;
32
+ /** Lets `id`'s hold go with nothing booked: a step that never left (its start mark could not be written). */
33
+ release(id: string): void;
34
+ /** Lets `id`'s hold go and books what its step ended at, with the rule that gave it. With no step under way under `id`:
35
+ * the booking of the step that last settled under it (a retried settle), else StepNotHeld. */
36
+ settle(id: string, ended: Settled): Booking;
37
+ }
@@ -0,0 +1,83 @@
1
+ // What the kernel cap counts: what the run has spent (null: unknown, never $0), and what each step under way is held at,
2
+ // by its own id, until it settles. A model request settles by how it ended, through booking.ts's one rule (answered: its
3
+ // cost, else its hold; nothing: 0; lost: its hold; stopped: what streamed, within its hold); a paid call at its charge, or
4
+ // its hold when it said none. A step books once: a settle retried answers the first booking. An id may be used again once
5
+ // its step has settled: each use holds and books on its own. A settle of an id the ledger never held is refused.
6
+ import { bookRequest } from "../../booking.js";
7
+ /** A settle of an id the ledger never held: refused, nothing booked. */
8
+ export class StepNotHeld extends Error {
9
+ id;
10
+ constructor(id) {
11
+ super(`the cap holds no step ${id}: nothing was booked (a step settles under the id it was admitted with)`);
12
+ this.name = "StepNotHeld";
13
+ this.id = id;
14
+ }
15
+ }
16
+ /** An admit of an id whose last step's end mark (or told mark) is not written yet: refused, nothing held or marked. Its
17
+ * settle must be retried first, else that retry would settle the new step at the old step's figure. */
18
+ export class StepNotSettled extends Error {
19
+ id;
20
+ constructor(id) {
21
+ super(`the cap's last step ${id} has not finished settling (its end mark is not written): retry its settle before ${id} is used again`);
22
+ this.name = "StepNotSettled";
23
+ this.id = id;
24
+ }
25
+ }
26
+ export class Ledger {
27
+ #spent;
28
+ #holds = new Map();
29
+ /** Each id's last booking: a settle retried after it (its marks failed) answers it, never books again. */
30
+ #booked = new Map();
31
+ constructor(spentUsd) {
32
+ this.#spent = spentUsd;
33
+ }
34
+ spent() {
35
+ return this.#spent;
36
+ }
37
+ held() {
38
+ let sum = 0;
39
+ for (const hold of this.#holds.values())
40
+ if (hold.usd !== null)
41
+ sum += hold.usd;
42
+ return sum;
43
+ }
44
+ /** Whether a step is under way under `id`. */
45
+ holds(id) {
46
+ return this.#holds.has(id);
47
+ }
48
+ /** Holds a step under `id`: refused while another step holds under it; an id whose step settled is free again. */
49
+ hold(id, hold) {
50
+ if (this.#holds.has(id))
51
+ throw new Error(`the cap already holds a step ${id}: each step under way holds under its own id`);
52
+ this.#holds.set(id, hold);
53
+ this.#booked.delete(id);
54
+ }
55
+ /** Lets `id`'s hold go with nothing booked: a step that never left (its start mark could not be written). */
56
+ release(id) {
57
+ this.#holds.delete(id);
58
+ }
59
+ /** Lets `id`'s hold go and books what its step ended at, with the rule that gave it. With no step under way under `id`:
60
+ * the booking of the step that last settled under it (a retried settle), else StepNotHeld. */
61
+ settle(id, ended) {
62
+ const hold = this.#holds.get(id);
63
+ if (!hold) {
64
+ const last = this.#booked.get(id);
65
+ if (last)
66
+ return last;
67
+ throw new StepNotHeld(id);
68
+ }
69
+ this.#holds.delete(id);
70
+ let booked;
71
+ if (ended.end === "charged") {
72
+ const said = typeof ended.usd === "number" && Number.isFinite(ended.usd) && ended.usd >= 0;
73
+ booked = { usd: said ? ended.usd : hold.usd, rule: said ? "charged" : "charged:held" };
74
+ }
75
+ else {
76
+ booked = bookRequest(ended, { ...(hold.usd === null ? {} : { hold: hold.usd }), ...(hold.stoppedPrice ? { stoppedPrice: hold.stoppedPrice } : {}) });
77
+ }
78
+ const usd = booked.usd;
79
+ this.#spent = this.#spent === null || usd === null ? null : this.#spent + usd;
80
+ this.#booked.set(id, booked);
81
+ return booked;
82
+ }
83
+ }
@@ -0,0 +1,50 @@
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. */
3
+ export type StartMark = {
4
+ readonly kind: "start";
5
+ readonly id: string;
6
+ readonly at: number;
7
+ readonly heldUsd: number | null;
8
+ readonly boundUsd?: number;
9
+ /** A model request's model: the wrap-up's typical cost counts the run's own model's answers only. */
10
+ readonly model?: string;
11
+ readonly side?: true;
12
+ readonly tool?: string;
13
+ readonly refused?: true;
14
+ };
15
+ /** A step's end: what it was booked at (null: unknown), and the booking rule that gave it. */
16
+ export type EndMark = {
17
+ readonly kind: "end";
18
+ readonly id: string;
19
+ readonly at: number;
20
+ readonly usd: number | null;
21
+ readonly rule?: string;
22
+ };
23
+ /** The wrap-up told, in the answered request `id`: once per run. */
24
+ export type ToldMark = {
25
+ readonly kind: "told";
26
+ readonly id: string;
27
+ readonly at: number;
28
+ readonly words: string;
29
+ readonly leftUsd: number;
30
+ };
31
+ /** A step that waits for a raise, by its path. */
32
+ export type WaitMark = {
33
+ readonly kind: "wait";
34
+ readonly path: string;
35
+ readonly at: number;
36
+ };
37
+ export type CapMark = StartMark | EndMark | ToldMark | WaitMark;
38
+ export interface CapMarks {
39
+ /** Writes `mark` durably (the journal: in the step's own commit). Rejects when it could not be written. */
40
+ write(mark: CapMark): Promise<void>;
41
+ /** Every mark of the run, in the order written. */
42
+ read(): Promise<CapMark[]>;
43
+ }
44
+ /** CapMarks in memory, for tests: `failNext()` makes the next write reject, `hang()` makes every write after it wait
45
+ * forever, as a store whose write never settles. */
46
+ export declare function memoryMarks(initial?: readonly CapMark[]): CapMarks & {
47
+ all(): CapMark[];
48
+ failNext(): void;
49
+ hang(): void;
50
+ };
@@ -0,0 +1,28 @@
1
+ // The cap's marks: the port the run's journal binds (each mark written in the step's own commit), and a test double. A
2
+ // paid step's start mark, with what it is held at, is written before the step leaves; its end mark, with what it was
3
+ // booked at, before its result is given back. Every mark is keyed by its step's id, so a reopened run counts an end
4
+ // against its own step, never another (recover.ts).
5
+ /** CapMarks in memory, for tests: `failNext()` makes the next write reject, `hang()` makes every write after it wait
6
+ * forever, as a store whose write never settles. */
7
+ export function memoryMarks(initial = []) {
8
+ const marks = [...initial];
9
+ let fail = false;
10
+ let hung = false;
11
+ return {
12
+ async write(mark) {
13
+ if (hung)
14
+ return new Promise(() => { });
15
+ if (fail) {
16
+ fail = false;
17
+ throw new Error("the mark could not be written");
18
+ }
19
+ marks.push(mark);
20
+ },
21
+ async read() {
22
+ return [...marks];
23
+ },
24
+ all: () => [...marks],
25
+ failNext: () => void (fail = true),
26
+ hang: () => void (hung = true),
27
+ };
28
+ }
@@ -0,0 +1,80 @@
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. */
5
+ export type BudgetPending = {
6
+ kind: "budget";
7
+ cap_usd: number;
8
+ spent_usd: number;
9
+ needs_usd: number;
10
+ least_cap_usd: number;
11
+ suggested_cap_usd: number;
12
+ bound_usd: number;
13
+ };
14
+ export type Park = {
15
+ outcome: "parked";
16
+ pending: BudgetPending;
17
+ words: string;
18
+ event: {
19
+ kind: "pause";
20
+ text: string;
21
+ };
22
+ error?: undefined;
23
+ } | {
24
+ outcome: "failed";
25
+ error: string;
26
+ pending?: undefined;
27
+ };
28
+ /** The run's end for `refusal` under `capUsd`. */
29
+ export declare function parkOf(refusal: CapRefused, capUsd: number): Park;
30
+ /** What a raise meets: the run's cap, whether it is final, the pause it waits at (none while it works), and its last raise
31
+ * (with the pause that one answered). */
32
+ export type RaiseState = {
33
+ capUsd: number | undefined;
34
+ final?: boolean;
35
+ pause?: string | undefined;
36
+ lastRaise?: {
37
+ to: number;
38
+ pause?: string | undefined;
39
+ };
40
+ };
41
+ export type RaiseCheck = {
42
+ raised: true;
43
+ resumes: boolean;
44
+ pause?: string;
45
+ refused?: undefined;
46
+ retry?: undefined;
47
+ } | {
48
+ retry: true;
49
+ resumed: boolean;
50
+ raised?: undefined;
51
+ refused?: undefined;
52
+ } | {
53
+ refused: string;
54
+ raised?: undefined;
55
+ retry?: undefined;
56
+ };
57
+ export declare function checkRaise(state: RaiseState, raiseUsd: number): RaiseCheck;
58
+ /** The follow-up a raised parked run goes on with: the server's words, never the person's. */
59
+ export declare const followUpOf: (capUsd: number) => {
60
+ text: string;
61
+ author: "server";
62
+ reason: "cap_raised";
63
+ };
64
+ /** Raise commands taken together (in id order, by the claim that wakes the run): each checked against the state the ones
65
+ * before it left; the run resumes once, at the latest cap, with one follow-up. */
66
+ export declare function takeRaises(state: RaiseState, raises: readonly {
67
+ id: number;
68
+ usd: number;
69
+ }[]): {
70
+ followUp?: {
71
+ text: string;
72
+ author: "server";
73
+ reason: "cap_raised";
74
+ } | undefined;
75
+ capUsd: number | undefined;
76
+ results: ({
77
+ id: number;
78
+ } & RaiseCheck)[];
79
+ followUps: number;
80
+ };