@parcha/agentrun-kernel 0.1.0-beta.42 → 0.1.0-beta.44

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,18 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.44 (2026-11-17)
6
+
7
+ - A Codex run under a small spend cap no longer stops as early on a hold that overstated its next request.
8
+
9
+ A request that only adds items to the session's last billed request is now held at that bill plus the bytes of the items it adds, with the local count's margin. The bill is all of that request's `input_tokens`, cached tokens included. Any other difference falls back to the local count, as before: changed instructions, tools, reasoning or model, or an earlier item edited, removed or moved.
10
+
11
+ Once the run has seen its model reason, a request's least output is 1,024 tokens plus twice the most reasoning one answer reported, within its effort's allowance. Before that it is the whole allowance, as before.
12
+
13
+ The request is still sent with all the output the cap fits, and the hold is still its worst case, so the cap is never passed. When the provider cuts an answer at the output the cap limited it to, the turn says so. A final answer cut that way ends the run with "the run's $0.50 cap stopped the model at N tokens before it finished its answer: raise the cap to at least $X to let it finish", where $X is the cap that sends that request whole with the run's wrap-up reserve still kept beside it.
14
+
15
+ An image in a custom tool call's output (Codex code mode's exec) is now counted at its billed tokens, as one in a function call's output already was.
16
+
5
17
  ## 0.1.0-beta.41 (2026-11-16)
6
18
 
7
19
  - A message sent to a working `claude-agent` run now steers it mid-turn. Before, it waited for the turn's end, and a run whose whole job is one turn read it only after the work was done. The model now reads it at its next step, after the tool calls in flight finish, in the same turn. `POST /v2/runs/{id}/messages` answers mode `steer` for a working claude-agent run (it answered `follow_up`), and `GET /v2/capabilities` lists `claude-agent` with `steer: true`.
@@ -1,8 +1,8 @@
1
- export { ANTHROPIC_IMAGE_TOKENS_MAX, ANTHROPIC_TOOL_USE_SYSTEM_PROMPT_TOKENS, ASSUMED_TOOL_PROMPT_TOKENS, anthropicImageTokens, GEMINI_HIGH_RESOLUTION_TOKENS, geminiImageTokens, imageInputOf, imageProviderOf, imageSizeOf, imageTokens, INPUT_OVERHEAD_APIS, LOCAL_COUNT_MARGIN, messagesImagesIn, messagesInputAfter, messagesLocalInputTokens, OPENAI_IMAGE_TOKENS_MAX, openaiImageTokens, openaiPatchMultiplier, providerInputOverhead, responsesEscapedBytes, responsesImagesIn, responsesInputOverhead, responsesLocalInputTokens, type BilledRequest, type ImageInput, type InputShape } from "./overhead.js";
1
+ export { ANTHROPIC_IMAGE_TOKENS_MAX, ANTHROPIC_TOOL_USE_SYSTEM_PROMPT_TOKENS, ASSUMED_TOOL_PROMPT_TOKENS, anthropicImageTokens, GEMINI_HIGH_RESOLUTION_TOKENS, geminiImageTokens, imageInputOf, imageProviderOf, imageSizeOf, imageTokens, INPUT_OVERHEAD_APIS, LOCAL_COUNT_MARGIN, messagesImagesIn, messagesInputAfter, messagesLocalInputTokens, OPENAI_IMAGE_TOKENS_MAX, openaiImageTokens, openaiPatchMultiplier, providerInputOverhead, responsesEscapedBytes, responsesImagesIn, responsesInputAfter, responsesInputOverhead, responsesLocalInputTokens, type BilledRequest, type ImageInput, type InputShape } from "./overhead.js";
2
2
  export { O200K_SHA256, O200K_VOCABULARY, o200kModel, o200kTokens } from "./o200k.js";
3
3
  export { COUNT_TIMEOUT_MS, countedInputOf, CredentialUnavailable, localInputOf, hostHeaderProblems, lastObjectOf, NATIVE_SEARCH_USD, ProxyRefusal, ROUTE_ORIGIN, sameKey, startModelProxy, statesUsageCost, streamErrorOf, usageCostOf } from "./proxy.js";
4
4
  export { OPENROUTER_APP, OPENROUTER_ATTRIBUTION_ENV, onOpenRouter, openRouterApp, openRouterAttribution } from "./openrouter-attribution.js";
5
- export type { InputCounter, ModelProxy, ModelProxyHooks, ModelProxyOptions, ModelUsageReport, ProviderPolicy, ProxyRequest, ProxyRequestContext, ProxyRoute, ProxyUsage, StreamError } from "./proxy.js";
5
+ export type { InputCounter, ModelProxy, ModelProxyHooks, ModelProxyOptions, ModelUsageReport, ProviderPolicy, ProxyRequest, ProxyRequestContext, ProxyRoute, ProxyUsage, ReasoningSeen, StreamError } from "./proxy.js";
6
6
  export { processAlive } from "./alive.js";
7
7
  export { serialWriter } from "./serial.js";
8
8
  export { PARENT_WATCH_SHIM, parentWatched, parentWatchHere, SETPRIV } from "./parent-death.js";
@@ -1,6 +1,6 @@
1
1
  // What a harness adapter runs beside its harness on the host: the session's model proxy, provider-neutral, with each
2
2
  // provider's rules in a `ProviderPolicy`. Written for AgentRun.
3
- export { ANTHROPIC_IMAGE_TOKENS_MAX, ANTHROPIC_TOOL_USE_SYSTEM_PROMPT_TOKENS, ASSUMED_TOOL_PROMPT_TOKENS, anthropicImageTokens, GEMINI_HIGH_RESOLUTION_TOKENS, geminiImageTokens, imageInputOf, imageProviderOf, imageSizeOf, imageTokens, INPUT_OVERHEAD_APIS, LOCAL_COUNT_MARGIN, messagesImagesIn, messagesInputAfter, messagesLocalInputTokens, OPENAI_IMAGE_TOKENS_MAX, openaiImageTokens, openaiPatchMultiplier, providerInputOverhead, responsesEscapedBytes, responsesImagesIn, responsesInputOverhead, responsesLocalInputTokens } from "./overhead.js";
3
+ export { ANTHROPIC_IMAGE_TOKENS_MAX, ANTHROPIC_TOOL_USE_SYSTEM_PROMPT_TOKENS, ASSUMED_TOOL_PROMPT_TOKENS, anthropicImageTokens, GEMINI_HIGH_RESOLUTION_TOKENS, geminiImageTokens, imageInputOf, imageProviderOf, imageSizeOf, imageTokens, INPUT_OVERHEAD_APIS, LOCAL_COUNT_MARGIN, messagesImagesIn, messagesInputAfter, messagesLocalInputTokens, OPENAI_IMAGE_TOKENS_MAX, openaiImageTokens, openaiPatchMultiplier, providerInputOverhead, responsesEscapedBytes, responsesImagesIn, responsesInputAfter, responsesInputOverhead, responsesLocalInputTokens } from "./overhead.js";
4
4
  export { O200K_SHA256, O200K_VOCABULARY, o200kModel, o200kTokens } from "./o200k.js";
5
5
  export { COUNT_TIMEOUT_MS, countedInputOf, CredentialUnavailable, localInputOf, hostHeaderProblems, lastObjectOf, NATIVE_SEARCH_USD, ProxyRefusal, ROUTE_ORIGIN, sameKey, startModelProxy, statesUsageCost, streamErrorOf, usageCostOf } from "./proxy.js";
6
6
  export { OPENROUTER_APP, OPENROUTER_ATTRIBUTION_ENV, onOpenRouter, openRouterApp, openRouterAttribution } from "./openrouter-attribution.js";
@@ -221,6 +221,30 @@ export interface BilledRequest {
221
221
  * tokenizer is not o200k_base: the CLI's second request, read at its bytes, is four times what it bills.
222
222
  */
223
223
  export declare function messagesInputAfter(earlier: BilledRequest, body: Record<string, unknown>): number | undefined;
224
+ /**
225
+ * The most input tokens a Responses `body` can be billed for, from an earlier request of its session that the provider
226
+ * billed (`earlier`): that request's billed input (all of its `input_tokens`, the cached ones among them), plus the items
227
+ * `body` appends after the earlier request's whole `input` (the earlier answer's own output items it carries back, a
228
+ * reasoning item, a message, a function or custom tool call, and the tools' outputs) at their bytes, each image among them
229
+ * at the most it is billed as in place of its data's bytes, with the local count's per-item and per-request margin
230
+ * (`LOCAL_COUNT_MARGIN`). Undefined (no figure: the body keeps its other bounds, its local count or its bytes) when the
231
+ * two differ in any field but their input and the fields that bill no input (`max_output_tokens`, `stream`, `metadata`):
232
+ * its instructions, tools, tool choice, reasoning, include, model or any other; when the later input is not the earlier
233
+ * one, item for item, with items appended (an edit, a reorder or a removal of any earlier item); when either input is not
234
+ * a list of items; when the earlier request's figure is not a count; or when the items it appends hold a file (billed by
235
+ * its pages, with no stated bound).
236
+ *
237
+ * Why it never undercounts: the provider renders a request as its instructions and tools, then each input item in turn,
238
+ * and bills each item's tokens whatever follows it, as `messagesInputAfter` argues for a Messages body. The later request
239
+ * is the earlier one with items after its last, so all the earlier request was billed for, it is billed for again, and
240
+ * no more. What it appends is bounded as the byte bound bounds any body (`inputTokensMaxOf`): a byte-level BPE token
241
+ * covers at least one byte, the JSON keys each item spends cover its framing, and the margin adds 16 tokens an item and
242
+ * 256 beside. Nothing is read through a tokenizer, so the figure rests on no count's accuracy, and a reasoning item's
243
+ * encrypted content is counted at its bytes, as the byte bound counts it. The Responses API's own context rule (a
244
+ * reasoning model's reasoning items from turns before the latest user message are dropped) only takes from a later
245
+ * request what the earlier one may still have been billed for: it adds to the figure's slack, never to the bill.
246
+ */
247
+ export declare function responsesInputAfter(earlier: BilledRequest, body: Record<string, unknown>): number | undefined;
224
248
  /** The image a body's `data` (base64, or a data URL) carries: the bytes it takes, and its size when its header says it.
225
249
  * Anything else (an http URL, a file id): no bytes, no size. */
226
250
  export declare function imageInputOf(data: unknown): ImageInput;
@@ -264,7 +264,7 @@ export function messagesImagesIn(messages) {
264
264
  return messagesBlocks(messages).filter((block) => block.type === "image").map((block) => (plain(block.source) && block.source.type === "base64" ? imageInputOf(block.source.data) : { bytes: 0 }));
265
265
  }
266
266
  /** The parts of a Responses body the API reads as images, in order: an `input_image` item, a part of an item's content,
267
- * a part of a function call's output. */
267
+ * a part of a function call's or a custom tool call's output. */
268
268
  function responsesImageParts(input) {
269
269
  const out = [];
270
270
  const image = (part) => { if (plain(part) && part.type === "input_image")
@@ -275,7 +275,7 @@ function responsesImageParts(input) {
275
275
  image(item);
276
276
  for (const part of list(item.content))
277
277
  image(part);
278
- if (item.type === "function_call_output")
278
+ if (item.type === "function_call_output" || item.type === "custom_tool_call_output")
279
279
  for (const part of list(item.output))
280
280
  image(part);
281
281
  }
@@ -523,6 +523,55 @@ export function messagesInputAfter(earlier, body) {
523
523
  const images = messagesImagesIn(added).reduce((sum, image) => sum + imageTokens(model, image) - image.bytes, 0);
524
524
  return earlier.inputTokens + Buffer.byteLength(JSON.stringify(added), "utf8") + images;
525
525
  }
526
+ /** The fields of a Responses body that bill no input, as `UNBILLED_FIELDS` for a Messages body: how much it may answer,
527
+ * whether it streams, and who asks. Its `input` is compared item by item (`responsesInputAfter`). */
528
+ const RESPONSES_UNBILLED_FIELDS = new Set(["input", "max_output_tokens", "stream", "metadata"]);
529
+ /**
530
+ * The most input tokens a Responses `body` can be billed for, from an earlier request of its session that the provider
531
+ * billed (`earlier`): that request's billed input (all of its `input_tokens`, the cached ones among them), plus the items
532
+ * `body` appends after the earlier request's whole `input` (the earlier answer's own output items it carries back, a
533
+ * reasoning item, a message, a function or custom tool call, and the tools' outputs) at their bytes, each image among them
534
+ * at the most it is billed as in place of its data's bytes, with the local count's per-item and per-request margin
535
+ * (`LOCAL_COUNT_MARGIN`). Undefined (no figure: the body keeps its other bounds, its local count or its bytes) when the
536
+ * two differ in any field but their input and the fields that bill no input (`max_output_tokens`, `stream`, `metadata`):
537
+ * its instructions, tools, tool choice, reasoning, include, model or any other; when the later input is not the earlier
538
+ * one, item for item, with items appended (an edit, a reorder or a removal of any earlier item); when either input is not
539
+ * a list of items; when the earlier request's figure is not a count; or when the items it appends hold a file (billed by
540
+ * its pages, with no stated bound).
541
+ *
542
+ * Why it never undercounts: the provider renders a request as its instructions and tools, then each input item in turn,
543
+ * and bills each item's tokens whatever follows it, as `messagesInputAfter` argues for a Messages body. The later request
544
+ * is the earlier one with items after its last, so all the earlier request was billed for, it is billed for again, and
545
+ * no more. What it appends is bounded as the byte bound bounds any body (`inputTokensMaxOf`): a byte-level BPE token
546
+ * covers at least one byte, the JSON keys each item spends cover its framing, and the margin adds 16 tokens an item and
547
+ * 256 beside. Nothing is read through a tokenizer, so the figure rests on no count's accuracy, and a reasoning item's
548
+ * encrypted content is counted at its bytes, as the byte bound counts it. The Responses API's own context rule (a
549
+ * reasoning model's reasoning items from turns before the latest user message are dropped) only takes from a later
550
+ * request what the earlier one may still have been billed for: it adds to the figure's slack, never to the bill.
551
+ */
552
+ export function responsesInputAfter(earlier, body) {
553
+ if (!plain(earlier?.body) || !plain(body) || !Number.isSafeInteger(earlier.inputTokens) || earlier.inputTokens <= 0)
554
+ return undefined;
555
+ const fields = new Set([...Object.keys(earlier.body), ...Object.keys(body)].filter((name) => !RESPONSES_UNBILLED_FIELDS.has(name)));
556
+ for (const name of fields)
557
+ if (JSON.stringify(earlier.body[name]) !== JSON.stringify(body[name]))
558
+ return undefined;
559
+ const before = earlier.body.input;
560
+ const after = body.input;
561
+ if (!Array.isArray(before) || !Array.isArray(after) || after.length < before.length)
562
+ return undefined;
563
+ for (let i = 0; i < before.length; i++)
564
+ if (JSON.stringify(before[i]) !== JSON.stringify(after[i]))
565
+ return undefined;
566
+ const added = after.slice(before.length);
567
+ if (itemsIn(added, "input_file") > 0)
568
+ return undefined;
569
+ const model = typeof body.model === "string" ? body.model : undefined;
570
+ // Each image's data is part of the added bytes, so the sum is never below the earlier figure.
571
+ const images = responsesImagesIn(added).reduce((sum, image) => sum + imageTokens(model, image) - image.bytes, 0);
572
+ const items = added.length + added.reduce((sum, item) => sum + (plain(item) && item.type === "function_call_output" ? list(item.output).filter(plain).length : 0), 0);
573
+ return earlier.inputTokens + Buffer.byteLength(JSON.stringify(added), "utf8") + images + LOCAL_COUNT_MARGIN.perItem * items + LOCAL_COUNT_MARGIN.perRequest;
574
+ }
526
575
  /** The image a body's `data` (base64, or a data URL) carries: the bytes it takes, and its size when its header says it.
527
576
  * Anything else (an http URL, a file id): no bytes, no size. */
528
577
  export function imageInputOf(data) {
@@ -1,5 +1,5 @@
1
1
  import { type IncomingHttpHeaders } from "node:http";
2
- import { type NoteRequest } from "../types.js";
2
+ import { type CapCut, type NoteRequest } from "../types.js";
3
3
  import { type Ended } from "../booking.js";
4
4
  import type { BilledRequest } from "./overhead.js";
5
5
  /** A route a policy admits: its method, its exact path, and the request headers forwarded with it. */
@@ -20,6 +20,9 @@ export interface ProxyUsage {
20
20
  output: number;
21
21
  cacheRead: number;
22
22
  cacheWrite?: number;
23
+ /** The reasoning tokens of its output, when the response reports them (Responses' output_tokens_details): what the
24
+ * run has seen its model reason (ReasoningSeen, `ProviderPolicy.outputLeast`). Never booked: `output` has them. */
25
+ reasoning?: number;
23
26
  /** `plan`: the policy's route bills a person's subscription plan, not the tokens (ModelUsage.billing). */
24
27
  billing?: "plan";
25
28
  }
@@ -31,6 +34,11 @@ export declare class CredentialUnavailable extends Error {
31
34
  * and OpenAI's "Web search (all models)" list the same price). The one figure every fee reads: the proxy policies of the
32
35
  * Claude and Codex harnesses and the runner's hosted search. */
33
36
  export declare const NATIVE_SEARCH_USD = 0.01;
37
+ /** What a session's model proxy has seen its model reason in this run: the most reasoning tokens one of its answers
38
+ * reported (ProxyUsage.reasoning), undefined before any answer reported its own. */
39
+ export interface ReasoningSeen {
40
+ readonly most?: number;
41
+ }
34
42
  /** What one provider's API may carry through the proxy. */
35
43
  export interface ProviderPolicy {
36
44
  /** A name for messages. */
@@ -109,13 +117,14 @@ export interface ProviderPolicy {
109
117
  * no local count (a model whose tokenizer the policy does not have), and keeps its byte bound. Absent: never counted. */
110
118
  countInputLocally?(body: Record<string, unknown>): Promise<number | undefined> | number | undefined;
111
119
  /** The most input tokens the body `apply` returned can be billed for, from `earlier`, the session's last request on
112
- * the same model whose answer reported what its whole input billed (`messagesInputAfter`): for a request the provider
120
+ * the same model whose answer reported what its whole input billed (`messagesInputAfter`, `responsesInputAfter`): for a request the provider
113
121
  * did not count, its input bound when it is below its other bounds. Undefined: the earlier request says nothing of this
114
122
  * one (they differ in more than what this one adds). Absent: never used. */
115
123
  inputAfter?(earlier: BilledRequest, body: Record<string, unknown>): number | undefined;
116
124
  /** The least output the body may be limited to and still answer: 1,024 tokens for the answer, plus the least thinking
117
- * its provider takes when it thinks. Absent: 1,024. */
118
- outputLeast?(body: Record<string, unknown>): number;
125
+ * its provider takes when it thinks. Absent: 1,024. `seen`: what the session's model has reasoned in this run, given for
126
+ * a request on it (ReasoningSeen.most). */
127
+ outputLeast?(body: Record<string, unknown>, seen?: ReasoningSeen): number;
119
128
  /** The reasoning effort the body asks its model at, as its provider names it (Responses' `reasoning.effort`,
120
129
  * Messages' `output_config.effort`): what `outputLeast` read it at, handed to the host beside it (ProxyRequest.effort).
121
130
  * Absent, or undefined for a body: it names none. */
@@ -297,9 +306,12 @@ export interface ModelProxyOptions {
297
306
  onFiltered?: (message: string) => void;
298
307
  /** Told, once an answer request's answer, once its stop says the provider cut it at its output limit
299
308
  * (`ProviderPolicy.cut`), before its client has the piece that carries the stop: a harness whose client would ask for
300
- * the answer again (Codex retries an incomplete stream) ends the turn there, the answer cut ("length"). */
309
+ * the answer again (Codex retries an incomplete stream) ends the turn there, the answer cut ("length"). `capCut`: the
310
+ * request went with less output than it asked, limited to what the run's cap left (ModelTicket.capCut), so the cut is
311
+ * the cap's, never a normal answer: the cap, and the least cap that sends it whole. */
301
312
  onCut?: (stop: {
302
313
  outputTokens?: number;
314
+ capCut?: CapCut;
303
315
  }) => void;
304
316
  /** Told, with its words and code, once the provider's error answer is one no retry mends (`ProviderPolicy.finalError`:
305
317
  * a plan's limit reached), as its client is answered those words: the harness ends the turn in them. */
@@ -807,6 +807,14 @@ export async function localInputOf(policy, body, say = () => { }) {
807
807
  return undefined;
808
808
  }
809
809
  }
810
+ /** A ticket's `capCut` (ModelTicket.capCut) when it is one: two money figures of 0 or more. */
811
+ function capCutOf(value) {
812
+ if (typeof value !== "object" || value === null)
813
+ return undefined;
814
+ const { capUsd, raiseToUsd } = value;
815
+ const money = (usd) => typeof usd === "number" && Number.isFinite(usd) && usd >= 0;
816
+ return money(capUsd) && money(raiseToUsd) ? { capUsd, raiseToUsd } : undefined;
817
+ }
810
818
  /** Start a session's model proxy on the loopback interface, admitting `key`. */
811
819
  /**
812
820
  * The most input tokens a request with body `sent` (the body `apply` returned, as it is sent) can be billed for: its UTF-8
@@ -861,6 +869,10 @@ export async function startModelProxy(options, key) {
861
869
  /** By model, the last request whose answer reported what its whole input billed: the body it was sent with and that
862
870
  * count (`policy.inputAfter` bounds a later request by it). */
863
871
  const billed = new Map();
872
+ /** The most reasoning tokens one answer of the session's model reported in this run (ProxyUsage.reasoning): a later
873
+ * request's least output is read from it (`policy.outputLeast`). Only the session's own answers, never a side call's or
874
+ * the host's. */
875
+ let reasoningMost;
864
876
  /** The requests whose answer the provider stopped on its content filter, read on for their usage, each until booked. */
865
877
  const draining = new Map();
866
878
  /** Set by close(): nothing is admitted or sent after it. */
@@ -1013,9 +1025,12 @@ export async function startModelProxy(options, key) {
1013
1025
  /** The content and the reasoning the client was sent, by the policy's reading of each event (content: text,
1014
1026
  * reasoning and tool arguments; reasoning: what of its reasoning streamed). */
1015
1027
  const sentOf = eventCounter({ content: policy.contentBytesOf?.bind(policy), reasoning: policy.reasoningBytesOf?.bind(policy) });
1028
+ /** Whether this request is on the session's model, its own (not the host's): what the run has seen its model reason
1029
+ * is read for it (ReasoningSeen), and its answer's reasoning counts toward it. */
1030
+ const ownModel = asked === model && host === undefined;
1016
1031
  try {
1017
1032
  outputTokensAsked = figure(policy.outputAsked?.(body));
1018
- outputTokensLeast = figure(policy.outputLeast?.(body));
1033
+ outputTokensLeast = figure(ownModel ? policy.outputLeast?.(body, { most: reasoningMost }) : policy.outputLeast?.(body));
1019
1034
  hiddenTokens = figure(policy.reasoningHidden?.(body)) ?? 0;
1020
1035
  }
1021
1036
  catch (error) {
@@ -1369,7 +1384,11 @@ export async function startModelProxy(options, key) {
1369
1384
  if (!stop)
1370
1385
  return;
1371
1386
  cutTold = true;
1372
- say(`model proxy (${policy.id}): the provider cut the answer at its output limit`);
1387
+ // Sent with less output than it asked, limited to what the run's cap left: the cut is the cap's.
1388
+ const capCut = limit !== undefined && typeof ticket === "object" && ticket !== null ? capCutOf(ticket.capCut) : undefined;
1389
+ if (capCut)
1390
+ stop = { ...stop, capCut };
1391
+ say(`model proxy (${policy.id}): the provider cut the answer at its output limit${capCut ? " the run's cap limited it to" : ""}`);
1373
1392
  // The harness ends the turn: until it opens its next, the session's answer requests are refused.
1374
1393
  stopTold = "cut at the model's output limit";
1375
1394
  try {
@@ -1677,6 +1696,11 @@ export async function startModelProxy(options, key) {
1677
1696
  const billedInput = usage.input + usage.cacheRead + (usage.cacheWrite ?? 0);
1678
1697
  if (answered?.ok && !stoppedByClient && !unread && failed === undefined && translated === undefined && refusedIn === undefined && host === undefined && Number.isSafeInteger(billedInput) && billedInput > 0)
1679
1698
  billed.set(asked, { body, inputTokens: billedInput });
1699
+ // The reasoning an answer of the session's model reported: the most one answer reasoned is what a later request's
1700
+ // least output is read from.
1701
+ const reasoned = usage.reasoning;
1702
+ if (ownModel && !unread && typeof reasoned === "number" && Number.isSafeInteger(reasoned) && reasoned >= 0)
1703
+ reasoningMost = Math.max(reasoningMost ?? 0, reasoned);
1680
1704
  try {
1681
1705
  usd = refusedIn !== undefined ? 0 : unread ? null : options.price?.(asked, usage) ?? null;
1682
1706
  if (refusedIn !== undefined)
@@ -1707,7 +1731,9 @@ export async function startModelProxy(options, key) {
1707
1731
  : !seen.ok ? (isGatewayTimeout(began?.status ?? 0) ? { end: "lost", label: "gateway_timeout" } : { end: "nothing", label: "status" })
1708
1732
  : !answered && usd === null ? { end: "lost", label: "error_after", began: true }
1709
1733
  : { end: "answered", usd, ...(erredIn !== undefined ? { label: "error", reason: erredIn } : filteredTold ? { label: "filtered" } : {}), ...(tableUsd === undefined ? {} : { tableUsd }) };
1710
- await hooks.afterRequest({ ...usage, usd, ...(own ? {} : { estimated: true }), ...(tableUsd === undefined ? {} : { tableUsd }), ...(ids ? { providerIds: ids } : {}), ...stopped }, ticket, ended);
1734
+ // The reasoning it reported is the proxy's own reading (reasoningMost), never a booked figure: its output has it.
1735
+ const { reasoning: _reasoning, ...tokens } = usage;
1736
+ await hooks.afterRequest({ ...tokens, usd, ...(own ? {} : { estimated: true }), ...(tableUsd === undefined ? {} : { tableUsd }), ...(ids ? { providerIds: ids } : {}), ...stopped }, ticket, ended);
1711
1737
  }
1712
1738
  catch (error) {
1713
1739
  say(`model proxy (${policy.id}): afterRequest threw; the request was answered and not booked`, { error: String(error?.message ?? error).slice(0, 200) });
package/dist/index.d.ts CHANGED
@@ -10,4 +10,4 @@ export type { HarnessRunReason } from "./errors.js";
10
10
  export { CONTENT_FILTERED, HOST_RESULT_MAX_CHARS, hostedTool, PLAN_LIMIT_CODE, PLAN_LIMIT_WORDS } from "./types.js";
11
11
  export { bookRequest, isConnectCode, isGatewayTimeout, rejectionCode } from "./booking.js";
12
12
  export type { Booked, Ended, Priced } from "./booking.js";
13
- export type { AdapterEvent, AdapterSession, AgentAdapter, AdapterFacts, GateAnswer, GateCall, SessionPort, Wire, HarnessEvent, HostTool, McpCallResult, McpTool, NestedCalls, NestedResult, ToolImage, JsonValue, ModelPort, ModelTicket, ModelRequest, ModelUsage, NoteRequest, NodeRequest, OwnCalls, SessionIO, SessionRecord, SessionSpec, SessionState, SessionStore, SessionWriter, ToolPermission, TurnStatus, } from "./types.js";
13
+ export type { AdapterEvent, AdapterSession, AgentAdapter, AdapterFacts, GateAnswer, GateCall, SessionPort, Wire, HarnessEvent, HostTool, McpCallResult, McpTool, NestedCalls, NestedResult, ToolImage, JsonValue, ModelPort, ModelTicket, CapCut, ModelRequest, ModelUsage, NoteRequest, NodeRequest, OwnCalls, SessionIO, SessionRecord, SessionSpec, SessionState, SessionStore, SessionWriter, ToolPermission, TurnStatus, } from "./types.js";
@@ -1,7 +1,7 @@
1
1
  import { CapRefused } from "./errors.js";
2
2
  import { inputBound, pricingOf } from "./price.js";
3
3
  import { capRule, isFigure } from "./rule.js";
4
- import { SPEND_CAP_REACHED, unmeasured } from "./words.js";
4
+ import { raiseFigure, SPEND_CAP_REACHED, unmeasured } from "./words.js";
5
5
  /** The cap's refusal as the runner takes it: its words, its code, and what the run's end is decided from (parkOf): for
6
6
  * good, or for room with its figures. */
7
7
  const refusalOf = (error) => ({ refuse: error.message, code: error.code, forGood: error.forGood, ...(error.figures ? { figures: error.figures } : {}) });
@@ -70,7 +70,10 @@ export function beforeRequestOf(options) {
70
70
  const sized = { ...asked, inputTokens: input };
71
71
  const keepUsd = options.keepBackUsd?.(request, sized);
72
72
  const judged = capRule.judge(sized, { capUsd, spentUsd, heldUsd, ...(keepUsd === undefined ? {} : { keepUsd }) });
73
- return { holdUsd: judged.heldUsd, ...(judged.outputTokensMax === undefined ? {} : { outputTokensMax: judged.outputTokensMax }), stoppedUsd: judged.stoppedUsd };
73
+ // Sent with less output than it asks: a cut at that limit is the cap's, said with the cap and the least cap that
74
+ // sends it whole (beside what the run had spent and held as it was admitted).
75
+ const capCut = judged.outputTokensMax !== undefined && judged.uncutUsd !== undefined && spentUsd !== null && heldUsd !== null ? { capUsd, raiseToUsd: raiseFigure(capUsd, spentUsd + heldUsd + judged.uncutUsd) } : undefined;
76
+ return { holdUsd: judged.heldUsd, ...(judged.outputTokensMax === undefined ? {} : { outputTokensMax: judged.outputTokensMax }), stoppedUsd: judged.stoppedUsd, ...(capCut ? { capCut } : {}) };
74
77
  }
75
78
  catch (error) {
76
79
  // Its words, and what the run's end is decided from (parkOf): for good, or for room with its figures.
@@ -12,12 +12,17 @@ export type JudgeState = {
12
12
  * unknown: it never reads as $0 and never frees room. */
13
13
  export declare const isFigure: (usd: unknown) => usd is number;
14
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). */
15
+ * sent with and its thinking budget, and what it counts at if stopped having streamed that many tokens (within its hold).
16
+ * `uncutUsd`: sent with less output than it asks, what a cap must leave room for beside the run's spend and holds to send
17
+ * it whole (the figure a cut of its answer names): its worst case at all it asks, and the keep-back beside it when one
18
+ * was asked (with the float's tail judgeModel keeps it with), so at that cap the same request is sent whole and the
19
+ * keep-back stays free. */
16
20
  export type Judged = {
17
21
  heldUsd: number;
18
22
  outputTokensMax?: number;
19
23
  thinkingBudget?: number;
20
24
  stoppedUsd(streamedTokens: number): number;
25
+ uncutUsd?: number;
21
26
  };
22
27
  /** A model request priced: its output asked and least, and its worst case at an output (price.ts requestPrice). */
23
28
  export declare function priced(request: ModelCapRequest): {
@@ -48,7 +48,8 @@ function judgeModel(request, { capUsd, spentUsd: spent, heldUsd: held, keepUsd }
48
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
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
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;
51
+ const keepBack = isFigure(keepUsd) && keepUsd > 0 ? keepUsd + 2 * FIT_TOLERANCE : undefined;
52
+ const kept = keepBack === undefined ? undefined : mostOutput(p.cost, p.least, p.asked ?? 0, left - keepBack);
52
53
  const output = kept ?? mostOutput(p.cost, p.least, p.asked ?? 0, left);
53
54
  if (output === undefined) {
54
55
  const { text, figures } = roomRefusal(capUsd, spent, held, p.cost(p.least));
@@ -61,6 +62,7 @@ function judgeModel(request, { capUsd, spentUsd: spent, heldUsd: held, keepUsd }
61
62
  heldUsd,
62
63
  ...(p.asked === undefined ? {} : { outputTokensMax: output }),
63
64
  ...(thinking === undefined ? {} : { thinkingBudget: thinking }),
65
+ ...(p.asked !== undefined && output < p.asked ? { uncutUsd: p.cost(p.asked) + (keepBack ?? 0) } : {}),
64
66
  stoppedUsd: (streamed) => Math.min(heldUsd, stoppedPrice(streamed)),
65
67
  };
66
68
  }
package/dist/runner.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type Ended } from "./booking.js";
2
- import type { AgentAdapter, HarnessEvent, HostTool, JsonValue, ModelPort, ModelUsage, NodeRequest, NoteRequest, SessionRecord, SessionStore, SessionWriter } from "./types.js";
2
+ import type { AgentAdapter, CapCut, HarnessEvent, HostTool, JsonValue, ModelPort, ModelUsage, NodeRequest, NoteRequest, SessionRecord, SessionStore, SessionWriter } from "./types.js";
3
3
  /** Exactly the interpreter's `runNode`, plus `stop`: a pause of every node it is running. With `drainMs`, each node
4
4
  * starts no new turn, call or paid request, its calls in flight run on until their outcomes are recorded (for at most
5
5
  * `drainMs`, on an adapter that can drain), and then it stops, failing `aborted`; its session resumes from its records
@@ -139,7 +139,8 @@ export type InFlight = {
139
139
  * `note`: the host's record of the note this request carries, written on the request's `runner.turn` record once it
140
140
  * ends, beside how it was booked, so a later process reads whether the note reached an answer. `freeRequest`: one of
141
141
  * the run's requests on a free model, which its ceiling on such requests counts: written on its runner.request (as
142
- * `freeRequest`), so the count holds it in every process, and a cut one books at $0 (bookCut). */
142
+ * `freeRequest`), so the count holds it in every process, and a cut one books at $0 (bookCut). `capCut`: its output
143
+ * limited below what it asked by what is left of the cap, the figures an answer cut at that limit says (ModelTicket). */
143
144
  export type Admission = {
144
145
  holdUsd?: number;
145
146
  outputTokensMax?: number;
@@ -149,6 +150,7 @@ export type Admission = {
149
150
  [key: string]: JsonValue;
150
151
  };
151
152
  freeRequest?: true;
153
+ capCut?: CapCut;
152
154
  };
153
155
  /** An admission as a host gives it: with `free` when the request is on a free model (its known price is $0 for every
154
156
  * token, with no fee beside), so it costs nothing however it ends: booked a known $0 (booking.ts), its own cost 0, its
package/dist/runner.js CHANGED
@@ -368,7 +368,9 @@ function bookingFor(writer, options) {
368
368
  }
369
369
  open.push({ turn, model, inputTokensMax, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(hold === undefined ? {} : { holdUsd: hold }), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }), ...(paid?.hold ? { stays: true } : {}) });
370
370
  fly(turn);
371
- return { turn, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(withoutNote ? { noteDropped: true } : {}) };
371
+ // The cap's figures for a cut of its answer, only with the limit they are about.
372
+ const capCut = limited !== undefined && verdict && "capCut" in verdict && verdict.capCut ? verdict.capCut : undefined;
373
+ return { turn, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(withoutNote ? { noteDropped: true } : {}), ...(capCut ? { capCut } : {}) };
372
374
  };
373
375
  const models = {
374
376
  ...(options.note ? { note: options.note } : {}),
package/dist/types.d.ts CHANGED
@@ -311,6 +311,12 @@ export type NoteRequest = {
311
311
  outputTokensAsked?: number;
312
312
  outputTokensLeast?: number;
313
313
  };
314
+ /** What a cut answer says when the run's cap limited its output: the cap, and the least cap that sends its request with
315
+ * all the output it asked (its whole input uncached and that output, beside what the run had spent and held), in USD. */
316
+ export type CapCut = {
317
+ capUsd: number;
318
+ raiseToUsd: number;
319
+ };
314
320
  /** A paid request's admission: the turn it was admitted as, which its answer is booked under. */
315
321
  export interface ModelTicket {
316
322
  turn: number;
@@ -320,6 +326,9 @@ export interface ModelTicket {
320
326
  /** Admitted only without its host's note (ModelRequest.noted): its bytes did not fit what is left of the cap. The
321
327
  * request goes as its client sent it, and the note waits for another request. */
322
328
  noteDropped?: true;
329
+ /** Limited below the output it asked (`outputTokensMax`) by what is left of its host's spend cap: an answer the provider
330
+ * cuts at that limit is the cap's cut, said with these figures (turn_end's capCut), never a normal answer. */
331
+ capCut?: CapCut;
323
332
  }
324
333
  /** What the host lends a session. */
325
334
  export interface SessionIO {
@@ -419,12 +428,14 @@ export type AdapterEvent = {
419
428
  truncated?: true;
420
429
  }
421
430
  /** `stopReason: "length"` only when the turn's final answer was cut at the model's output limit (unfinished), with that
422
- * answer's output tokens when the adapter knows them: a host reads the answer as cut, never as the run's end. */
431
+ * answer's output tokens when the adapter knows them: a host reads the answer as cut, never as the run's end. `capCut`:
432
+ * the limit it was cut at was the run's cap's (ModelTicket.capCut), with the cap and the least cap that finishes it. */
423
433
  | {
424
434
  type: "turn_end";
425
435
  status: TurnStatus;
426
436
  stopReason?: "length";
427
437
  outputTokens?: number;
438
+ capCut?: CapCut;
428
439
  }
429
440
  /** The model was given these submissions (the ids `send` or `steer` placed them under): a steer placed mid-turn reaches
430
441
  * it at the turn's next step, after the tool calls in flight. An adapter that records nothing of its own says it, so
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-kernel",
3
- "version": "0.1.0-beta.42",
3
+ "version": "0.1.0-beta.44",
4
4
  "description": "Agent harnesses other than Pi, starting with Codex, behind one seam: a DSL node's runNode and an AgentRun run on a harness adapter, durable in AgentRun's own store.",
5
5
  "keywords": [
6
6
  "agentrun",
@@ -62,7 +62,7 @@
62
62
  "test": "node --test --test-concurrency=8 'test/*.test.mjs'"
63
63
  },
64
64
  "dependencies": {
65
- "@parcha/agentrun-dsl": "0.1.0-beta.42",
65
+ "@parcha/agentrun-dsl": "0.1.0-beta.44",
66
66
  "ajv": "8.18.0",
67
67
  "typebox": "1.3.27"
68
68
  },