@parcha/agentrun-kernel 0.1.0-beta.43 → 0.1.0-beta.45
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 +26 -0
- package/README.md +2 -2
- package/dist/host/index.d.ts +2 -2
- package/dist/host/index.js +1 -1
- package/dist/host/overhead.d.ts +24 -0
- package/dist/host/overhead.js +51 -2
- package/dist/host/proxy.d.ts +21 -5
- package/dist/host/proxy.js +43 -9
- package/dist/index.d.ts +2 -2
- package/dist/kernel/cap/port.js +5 -2
- package/dist/kernel/cap/rule.d.ts +6 -1
- package/dist/kernel/cap/rule.js +3 -1
- package/dist/runner.d.ts +17 -3
- package/dist/runner.js +26 -4
- package/dist/types.d.ts +12 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,32 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## 0.1.0-beta.45 (2026-11-18)
|
|
6
|
+
|
|
7
|
+
- Goose 1.59.2 runs as an AgentRun harness on the ACP adapter: `gooseAdapter({ binary, model, provider, price })` checks the binary's sha256 against its pin, starts `goose acp` from the shipped recipe (`recipes/goose.json`, loaded by `recipeFile` and `gooseRecipe`), and points each Goose process at a model proxy of its own (`gooseProxy`) on the session's booking, so the run's cap and books hold as they do for Claude Code. <!-- changes/acp-goose-harness.md -->
|
|
8
|
+
- The recipe turns every bundled Goose extension off, blocks Goose's model catalog download with a dead egress proxy, mirrors its sessions so another runner's Goose loads them, and leaves the model our MCP tools (`agentrun__<name>`) and Goose's `load_skill`.
|
|
9
|
+
- Goose's proxy forwards only `POST /v1/messages`, with the API's version and the one `anthropic-beta` value the pinned Goose sends (`GOOSE_BETAS`), never Goose's `agent-session-id`. It answers `GET /v1/models` itself with the run's model, and refuses any other model, tool, hosted tool or beta before the provider is asked.
|
|
10
|
+
- `GOOSE_PIN` records the release as the ACP registry listed it, with where and when it was read. `verifyPinnedBinary` refuses a binary whose sha256 differs (`ACP_BINARY_MISMATCH`), reading it and never running it. `gooseAdapter` checks it when the adapter is made and again before every Goose process starts (the adapter's new `beforeStart` option), so a binary replaced in between never runs unchecked. `verifyFirstSeen` records the first verified digest of an agent the registry lists without one, and refuses later drift (`ACP_BINARY_DRIFT`).
|
|
11
|
+
- The adapter's `proxy` option is now called with the session's booking, its tools' names and a halt of its drive (`AcpProxySession`).
|
|
12
|
+
- The kernel's model proxy can answer a local route with a fixed JSON body (`ProxyRoute.localJson`), only to the session's key or a side key.
|
|
13
|
+
- The runner now writes a warn line when a paid model request bills more input than the bound its spend-cap hold was priced on: the one way a cap can be passed, a hold that was too small. <!-- changes/cap-bound-warn.md -->
|
|
14
|
+
|
|
15
|
+
The line is `event=cap_hold_short`, in the same logfmt shape as the server's other log lines, written to stderr once for each such request as its answer is booked: by an agent's run, by a workflow run's model nodes (harness `workflow`), and for a request that answered after its run's claim was lost, by the booking that writes it later. It carries the run id, the request's session and turn, the harness, the model, the bound and the billed input in tokens (input, cache reads and cache writes together), and in USD what was held, what the answer billed and the shortfall (billed less held) when the answer was priced.
|
|
16
|
+
|
|
17
|
+
No line is written for a request billed at or under its bound, for one whose answer reported no usage, for one billed to a ChatGPT plan or on a free model (held at $0 whatever its input), or for one with no hold (no cap). The line carries ids and figures only: never any prompt or answer text, header, key or token. Billing, holds and refusals are unchanged.
|
|
18
|
+
|
|
19
|
+
## 0.1.0-beta.44 (2026-11-17)
|
|
20
|
+
|
|
21
|
+
- A Codex run under a small spend cap no longer stops as early on a hold that overstated its next request. <!-- changes/codex-cap-hold-billed-after.md -->
|
|
22
|
+
|
|
23
|
+
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.
|
|
24
|
+
|
|
25
|
+
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.
|
|
26
|
+
|
|
27
|
+
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.
|
|
28
|
+
|
|
29
|
+
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.
|
|
30
|
+
|
|
5
31
|
## 0.1.0-beta.41 (2026-11-16)
|
|
6
32
|
|
|
7
33
|
- 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`.
|
package/README.md
CHANGED
|
@@ -49,8 +49,8 @@ harness adapter the way they run on Pi, durable in AgentRun's own store.
|
|
|
49
49
|
`parkOf`, `checkRaise` and `followUpOf` decide what a refusal and a raise do to the run.
|
|
50
50
|
- `./host` is the session's model proxy, provider-neutral: on the loopback interface, it admits only the session's key,
|
|
51
51
|
only the routes a `ProviderPolicy` lists (by exact path text, with no query or one the route lists exactly; a route
|
|
52
|
-
may also be answered by the proxy, or be free, like a token count), and strict JSON
|
|
53
|
-
body, asks the runner's `beforeRequest` before each paid request, adds the provider's credential (which never reaches
|
|
52
|
+
may also be answered by the proxy, or be free, like a token count), and strict JSON that has the policy shape (it refuses any
|
|
53
|
+
other body), asks the runner's `beforeRequest` before each paid request, adds the provider's credential (which never reaches
|
|
54
54
|
the harness), and reports each response's usage to `afterRequest`. Model spend is accounted only there, by the runner.
|
|
55
55
|
|
|
56
56
|
The runner's own bounds (a turn limit, no progress, an unknown tool, a refused fork, the host's refusal) fail a node
|
package/dist/host/index.d.ts
CHANGED
|
@@ -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";
|
package/dist/host/index.js
CHANGED
|
@@ -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";
|
package/dist/host/overhead.d.ts
CHANGED
|
@@ -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;
|
package/dist/host/overhead.js
CHANGED
|
@@ -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) {
|
package/dist/host/proxy.d.ts
CHANGED
|
@@ -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. */
|
|
@@ -11,6 +11,10 @@ export interface ProxyRoute {
|
|
|
11
11
|
readonly headers?: readonly string[];
|
|
12
12
|
/** Answered here with this status and an empty body, never forwarded (a client's connectivity check). */
|
|
13
13
|
readonly local?: number;
|
|
14
|
+
/** With `local`: the JSON text it is answered with in place of an empty body (a client's list of models, answered
|
|
15
|
+
* with the session's own so the provider's list is never asked for), and then only to the session's key or a side
|
|
16
|
+
* key. */
|
|
17
|
+
readonly localJson?: string;
|
|
14
18
|
/** Not a paid request (a token count): forwarded without asking the runner, and no usage is reported. */
|
|
15
19
|
readonly free?: boolean;
|
|
16
20
|
}
|
|
@@ -20,6 +24,9 @@ export interface ProxyUsage {
|
|
|
20
24
|
output: number;
|
|
21
25
|
cacheRead: number;
|
|
22
26
|
cacheWrite?: number;
|
|
27
|
+
/** The reasoning tokens of its output, when the response reports them (Responses' output_tokens_details): what the
|
|
28
|
+
* run has seen its model reason (ReasoningSeen, `ProviderPolicy.outputLeast`). Never booked: `output` has them. */
|
|
29
|
+
reasoning?: number;
|
|
23
30
|
/** `plan`: the policy's route bills a person's subscription plan, not the tokens (ModelUsage.billing). */
|
|
24
31
|
billing?: "plan";
|
|
25
32
|
}
|
|
@@ -31,6 +38,11 @@ export declare class CredentialUnavailable extends Error {
|
|
|
31
38
|
* and OpenAI's "Web search (all models)" list the same price). The one figure every fee reads: the proxy policies of the
|
|
32
39
|
* Claude and Codex harnesses and the runner's hosted search. */
|
|
33
40
|
export declare const NATIVE_SEARCH_USD = 0.01;
|
|
41
|
+
/** What a session's model proxy has seen its model reason in this run: the most reasoning tokens one of its answers
|
|
42
|
+
* reported (ProxyUsage.reasoning), undefined before any answer reported its own. */
|
|
43
|
+
export interface ReasoningSeen {
|
|
44
|
+
readonly most?: number;
|
|
45
|
+
}
|
|
34
46
|
/** What one provider's API may carry through the proxy. */
|
|
35
47
|
export interface ProviderPolicy {
|
|
36
48
|
/** A name for messages. */
|
|
@@ -109,13 +121,14 @@ export interface ProviderPolicy {
|
|
|
109
121
|
* no local count (a model whose tokenizer the policy does not have), and keeps its byte bound. Absent: never counted. */
|
|
110
122
|
countInputLocally?(body: Record<string, unknown>): Promise<number | undefined> | number | undefined;
|
|
111
123
|
/** 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
|
|
124
|
+
* the same model whose answer reported what its whole input billed (`messagesInputAfter`, `responsesInputAfter`): for a request the provider
|
|
113
125
|
* did not count, its input bound when it is below its other bounds. Undefined: the earlier request says nothing of this
|
|
114
126
|
* one (they differ in more than what this one adds). Absent: never used. */
|
|
115
127
|
inputAfter?(earlier: BilledRequest, body: Record<string, unknown>): number | undefined;
|
|
116
128
|
/** 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
|
-
|
|
129
|
+
* its provider takes when it thinks. Absent: 1,024. `seen`: what the session's model has reasoned in this run, given for
|
|
130
|
+
* a request on it (ReasoningSeen.most). */
|
|
131
|
+
outputLeast?(body: Record<string, unknown>, seen?: ReasoningSeen): number;
|
|
119
132
|
/** The reasoning effort the body asks its model at, as its provider names it (Responses' `reasoning.effort`,
|
|
120
133
|
* Messages' `output_config.effort`): what `outputLeast` read it at, handed to the host beside it (ProxyRequest.effort).
|
|
121
134
|
* Absent, or undefined for a body: it names none. */
|
|
@@ -297,9 +310,12 @@ export interface ModelProxyOptions {
|
|
|
297
310
|
onFiltered?: (message: string) => void;
|
|
298
311
|
/** Told, once an answer request's answer, once its stop says the provider cut it at its output limit
|
|
299
312
|
* (`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").
|
|
313
|
+
* the answer again (Codex retries an incomplete stream) ends the turn there, the answer cut ("length"). `capCut`: the
|
|
314
|
+
* request went with less output than it asked, limited to what the run's cap left (ModelTicket.capCut), so the cut is
|
|
315
|
+
* the cap's, never a normal answer: the cap, and the least cap that sends it whole. */
|
|
301
316
|
onCut?: (stop: {
|
|
302
317
|
outputTokens?: number;
|
|
318
|
+
capCut?: CapCut;
|
|
303
319
|
}) => void;
|
|
304
320
|
/** Told, with its words and code, once the provider's error answer is one no retry mends (`ProviderPolicy.finalError`:
|
|
305
321
|
* a plan's limit reached), as its client is answered those words: the harness ends the turn in them. */
|
package/dist/host/proxy.js
CHANGED
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
// forward, where a response reports its usage). The core:
|
|
5
5
|
// - admits a request only with the session's key (compared in constant time), on a route the policy lists, by exact
|
|
6
6
|
// path text, with no query or one the route lists exactly: an absolute URL, `..`, `//` or `%` escapes never match. A
|
|
7
|
-
// route may be answered here with a status alone, with no key (a client's connectivity check), or
|
|
8
|
-
// count, which the runner never pays);
|
|
7
|
+
// route may be answered here with a status alone, with no key (a client's connectivity check), or with a body the
|
|
8
|
+
// policy fixed, with the key (a client's list of models), or be free (a token count, which the runner never pays);
|
|
9
9
|
// - parses the body strictly (one JSON value, no duplicate key at any depth, so a check on one `model` cannot pass while
|
|
10
10
|
// the provider reads another), then has the policy shape it (or refuse it);
|
|
11
11
|
// - asks the runner before every paid request (`beforeRequest`, where a turn cap or the host's budget refuses it) and
|
|
@@ -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. */
|
|
@@ -934,11 +946,19 @@ export async function startModelProxy(options, key) {
|
|
|
934
946
|
const e = error;
|
|
935
947
|
return refuse(res, e.status ?? 403, e.message, req);
|
|
936
948
|
}
|
|
937
|
-
// A local route forwards nothing
|
|
938
|
-
//
|
|
949
|
+
// A local route forwards nothing. One that answers only a status needs no key: a client's connectivity check (the
|
|
950
|
+
// Claude Agent CLI's `HEAD /api/hello`) is sent without one. One that answers a body says something of the session
|
|
951
|
+
// (its model, to Goose's `GET /v1/models`), so it takes a key as every other route does.
|
|
939
952
|
if (route.local !== undefined) {
|
|
940
|
-
|
|
941
|
-
|
|
953
|
+
if (route.localJson === undefined) {
|
|
954
|
+
res.writeHead(route.local, { "content-length": "0" });
|
|
955
|
+
return res.end();
|
|
956
|
+
}
|
|
957
|
+
const sent = policy.keyOf(req.headers);
|
|
958
|
+
if (!sameKey(sent, key) && sideOf(sent) === undefined)
|
|
959
|
+
return refuse(res, 401, "this session's key is required", req);
|
|
960
|
+
res.writeHead(route.local, { "content-type": "application/json", "content-length": String(Buffer.byteLength(route.localJson)) });
|
|
961
|
+
return res.end(route.localJson);
|
|
942
962
|
}
|
|
943
963
|
// The session's key (the harness's requests), or a side key the host holds (its own, labelled).
|
|
944
964
|
const sentKey = policy.keyOf(req.headers);
|
|
@@ -1013,9 +1033,12 @@ export async function startModelProxy(options, key) {
|
|
|
1013
1033
|
/** The content and the reasoning the client was sent, by the policy's reading of each event (content: text,
|
|
1014
1034
|
* reasoning and tool arguments; reasoning: what of its reasoning streamed). */
|
|
1015
1035
|
const sentOf = eventCounter({ content: policy.contentBytesOf?.bind(policy), reasoning: policy.reasoningBytesOf?.bind(policy) });
|
|
1036
|
+
/** Whether this request is on the session's model, its own (not the host's): what the run has seen its model reason
|
|
1037
|
+
* is read for it (ReasoningSeen), and its answer's reasoning counts toward it. */
|
|
1038
|
+
const ownModel = asked === model && host === undefined;
|
|
1016
1039
|
try {
|
|
1017
1040
|
outputTokensAsked = figure(policy.outputAsked?.(body));
|
|
1018
|
-
outputTokensLeast = figure(policy.outputLeast?.(body));
|
|
1041
|
+
outputTokensLeast = figure(ownModel ? policy.outputLeast?.(body, { most: reasoningMost }) : policy.outputLeast?.(body));
|
|
1019
1042
|
hiddenTokens = figure(policy.reasoningHidden?.(body)) ?? 0;
|
|
1020
1043
|
}
|
|
1021
1044
|
catch (error) {
|
|
@@ -1369,7 +1392,11 @@ export async function startModelProxy(options, key) {
|
|
|
1369
1392
|
if (!stop)
|
|
1370
1393
|
return;
|
|
1371
1394
|
cutTold = true;
|
|
1372
|
-
|
|
1395
|
+
// Sent with less output than it asked, limited to what the run's cap left: the cut is the cap's.
|
|
1396
|
+
const capCut = limit !== undefined && typeof ticket === "object" && ticket !== null ? capCutOf(ticket.capCut) : undefined;
|
|
1397
|
+
if (capCut)
|
|
1398
|
+
stop = { ...stop, capCut };
|
|
1399
|
+
say(`model proxy (${policy.id}): the provider cut the answer at its output limit${capCut ? " the run's cap limited it to" : ""}`);
|
|
1373
1400
|
// The harness ends the turn: until it opens its next, the session's answer requests are refused.
|
|
1374
1401
|
stopTold = "cut at the model's output limit";
|
|
1375
1402
|
try {
|
|
@@ -1677,6 +1704,11 @@ export async function startModelProxy(options, key) {
|
|
|
1677
1704
|
const billedInput = usage.input + usage.cacheRead + (usage.cacheWrite ?? 0);
|
|
1678
1705
|
if (answered?.ok && !stoppedByClient && !unread && failed === undefined && translated === undefined && refusedIn === undefined && host === undefined && Number.isSafeInteger(billedInput) && billedInput > 0)
|
|
1679
1706
|
billed.set(asked, { body, inputTokens: billedInput });
|
|
1707
|
+
// The reasoning an answer of the session's model reported: the most one answer reasoned is what a later request's
|
|
1708
|
+
// least output is read from.
|
|
1709
|
+
const reasoned = usage.reasoning;
|
|
1710
|
+
if (ownModel && !unread && typeof reasoned === "number" && Number.isSafeInteger(reasoned) && reasoned >= 0)
|
|
1711
|
+
reasoningMost = Math.max(reasoningMost ?? 0, reasoned);
|
|
1680
1712
|
try {
|
|
1681
1713
|
usd = refusedIn !== undefined ? 0 : unread ? null : options.price?.(asked, usage) ?? null;
|
|
1682
1714
|
if (refusedIn !== undefined)
|
|
@@ -1707,7 +1739,9 @@ export async function startModelProxy(options, key) {
|
|
|
1707
1739
|
: !seen.ok ? (isGatewayTimeout(began?.status ?? 0) ? { end: "lost", label: "gateway_timeout" } : { end: "nothing", label: "status" })
|
|
1708
1740
|
: !answered && usd === null ? { end: "lost", label: "error_after", began: true }
|
|
1709
1741
|
: { end: "answered", usd, ...(erredIn !== undefined ? { label: "error", reason: erredIn } : filteredTold ? { label: "filtered" } : {}), ...(tableUsd === undefined ? {} : { tableUsd }) };
|
|
1710
|
-
|
|
1742
|
+
// The reasoning it reported is the proxy's own reading (reasoningMost), never a booked figure: its output has it.
|
|
1743
|
+
const { reasoning: _reasoning, ...tokens } = usage;
|
|
1744
|
+
await hooks.afterRequest({ ...tokens, usd, ...(own ? {} : { estimated: true }), ...(tableUsd === undefined ? {} : { tableUsd }), ...(ids ? { providerIds: ids } : {}), ...stopped }, ticket, ended);
|
|
1711
1745
|
}
|
|
1712
1746
|
catch (error) {
|
|
1713
1747
|
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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { answeredUnpriced, costOfParts, createHarnessRunner, CUT_AT_HOLD, modelPortFor, rebooked, sessionSpendOf, SUBMIT_TOOL, RUNNER_RECORDS, turnCostOf } from "./runner.js";
|
|
2
2
|
export { RECORD_WAIT_MS, runBooking, type RunBookingOptions, type RunSessions, WAIT_POLL_FIRST_MS, WAIT_POLL_MOST_MS, WAIT_STALL_MS } from "./run-booking.js";
|
|
3
|
-
export type { Admission, BeforeRequest, Refusal, HarnessRunner, HarnessRunnerOptions, InFlight, ModelBooking, ModelPortEvent, ModelPortOptions, CostParts, SessionCost } from "./runner.js";
|
|
3
|
+
export type { Admission, BeforeRequest, Refusal, HarnessRunner, HarnessRunnerOptions, HoldShort, InFlight, ModelBooking, ModelPortEvent, ModelPortOptions, CostParts, SessionCost } from "./runner.js";
|
|
4
4
|
export { HarnessRunError, SessionFenced, TurnParked } from "./errors.js";
|
|
5
5
|
export { CODEMODE, DEFER_CATALOG_OVER, defersCatalog, isCatalogWire, META_TOOLS, TOOLS_CALL, TOOLS_SEARCH } from "./tool-deferral.js";
|
|
6
6
|
export { toolSchemaProblems } from "./schema-check.js";
|
|
@@ -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";
|
package/dist/kernel/cap/port.js
CHANGED
|
@@ -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
|
-
|
|
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): {
|
package/dist/kernel/cap/rule.js
CHANGED
|
@@ -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
|
|
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
|
|
@@ -186,8 +188,19 @@ export interface HarnessRunnerOptions {
|
|
|
186
188
|
* turn limit counts paid requests only, so without this bound a harness whose turns never reach its model (a cached or
|
|
187
189
|
* refused answer, a misconfigured model) would be sent turns forever, on microtasks no timer can interrupt. */
|
|
188
190
|
export declare const NO_PROGRESS_TURNS = 3;
|
|
191
|
+
/** A request whose answer billed more input than the bound its hold was priced on (InFlight.inputTokensMax): the cap's
|
|
192
|
+
* one failure that matters, a hold too small. Its model; that bound and what it billed (input, cache reads and cache
|
|
193
|
+
* writes together, as `inputAfter` reads a bill), in tokens; what was held for it and, when its answer was priced, what
|
|
194
|
+
* it billed, in USD. */
|
|
195
|
+
export type HoldShort = {
|
|
196
|
+
model: string;
|
|
197
|
+
boundTokens: number;
|
|
198
|
+
billedTokens: number;
|
|
199
|
+
heldUsd: number;
|
|
200
|
+
billedUsd?: number;
|
|
201
|
+
};
|
|
189
202
|
/** What a paid request tells a host, beside its session's key and label. A `request_end` carries how its path saw the
|
|
190
|
-
* request end (`ended`, booking.ts), when the path said. */
|
|
203
|
+
* request end (`ended`, booking.ts), when the path said, and `holdShort` when it billed past its hold's bound. */
|
|
191
204
|
export type ModelPortEvent = {
|
|
192
205
|
type: "request_start";
|
|
193
206
|
turn: number;
|
|
@@ -199,6 +212,7 @@ export type ModelPortEvent = {
|
|
|
199
212
|
usage: ModelUsage;
|
|
200
213
|
host?: string;
|
|
201
214
|
ended?: Ended;
|
|
215
|
+
holdShort?: HoldShort;
|
|
202
216
|
};
|
|
203
217
|
export interface ModelPortOptions {
|
|
204
218
|
/** The session's key: what `beforeRequest` and every event carry. */
|
package/dist/runner.js
CHANGED
|
@@ -36,6 +36,21 @@ const positive = (value, name) => {
|
|
|
36
36
|
* turn limit counts paid requests only, so without this bound a harness whose turns never reach its model (a cached or
|
|
37
37
|
* refused answer, a misconfigured model) would be sent turns forever, on microtasks no timer can interrupt. */
|
|
38
38
|
export const NO_PROGRESS_TURNS = 3;
|
|
39
|
+
/** `usage` against the bound its request's hold was priced on (`flight`'s inputTokensMax; `hold`, what was held): a
|
|
40
|
+
* HoldShort when it billed more input than that bound. Undefined when it billed at or under it, or when there is nothing
|
|
41
|
+
* to compare: no bound, no hold (no cap priced it), a request held at $0 whatever its input (billed to a plan or on a
|
|
42
|
+
* free model, `unpriced`), or a usage with no input count (one cut, or one whose answer reported none). */
|
|
43
|
+
const holdShortOf = (usage, flight, hold, unpriced) => {
|
|
44
|
+
const count = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
|
|
45
|
+
const input = count(usage.input);
|
|
46
|
+
const bound = count(flight?.inputTokensMax);
|
|
47
|
+
if (!flight || bound === undefined || hold === undefined || unpriced || usage.billing === "plan" || usage.cut || usage.givenBack || input === undefined)
|
|
48
|
+
return undefined;
|
|
49
|
+
const billed = input + (count(usage.cacheRead) ?? 0) + (count(usage.cacheWrite) ?? 0);
|
|
50
|
+
if (billed <= bound)
|
|
51
|
+
return undefined;
|
|
52
|
+
return { model: flight.model, boundTokens: bound, billedTokens: billed, heldUsd: hold, ...(typeof usage.usd === "number" && Number.isFinite(usage.usd) ? { billedUsd: usage.usd } : {}) };
|
|
53
|
+
};
|
|
39
54
|
/** The runner's booking of paid model requests, for a host that drives an adapter session itself (a chat run): the same
|
|
40
55
|
* records (`runner.request` before a request leaves, `runner.turn` with its cost when it answers), the same turn limit
|
|
41
56
|
* and `beforeRequest`, the same events. `createHarnessRunner` is built on it. */
|
|
@@ -368,7 +383,9 @@ function bookingFor(writer, options) {
|
|
|
368
383
|
}
|
|
369
384
|
open.push({ turn, model, inputTokensMax, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(hold === undefined ? {} : { holdUsd: hold }), ...(host === undefined ? {} : { host }), ...(route === undefined ? {} : { route }), ...(paid?.hold ? { stays: true } : {}) });
|
|
370
385
|
fly(turn);
|
|
371
|
-
|
|
386
|
+
// The cap's figures for a cut of its answer, only with the limit they are about.
|
|
387
|
+
const capCut = limited !== undefined && verdict && "capCut" in verdict && verdict.capCut ? verdict.capCut : undefined;
|
|
388
|
+
return { turn, ...(limited === undefined ? {} : { outputTokensMax: limited }), ...(withoutNote ? { noteDropped: true } : {}), ...(capCut ? { capCut } : {}) };
|
|
372
389
|
};
|
|
373
390
|
const models = {
|
|
374
391
|
...(options.note ? { note: options.note } : {}),
|
|
@@ -393,6 +410,8 @@ function bookingFor(writer, options) {
|
|
|
393
410
|
// The turn this request was admitted as (its ticket; without one, the earliest still in flight).
|
|
394
411
|
const turn = ticket?.turn ?? open[0]?.turn ?? turns;
|
|
395
412
|
const at = open.findIndex((f) => f.turn === turn);
|
|
413
|
+
// As it was admitted: the bound its hold was priced on (holdShortOf).
|
|
414
|
+
const flight = at >= 0 ? open[at] : undefined;
|
|
396
415
|
if (at >= 0)
|
|
397
416
|
open.splice(at, 1);
|
|
398
417
|
// A cost that never came in (a response cut short): at what the host held for the request, else unknown. One its
|
|
@@ -430,6 +449,9 @@ function bookingFor(writer, options) {
|
|
|
430
449
|
// Marked so, for a reader to say why it cost nothing (a run on free models: "$0 · free model").
|
|
431
450
|
if (free)
|
|
432
451
|
data.free = true;
|
|
452
|
+
// Billed past the bound its hold was priced on: told with its end, for the host's warn line, here or, its write
|
|
453
|
+
// refused, by the next booking that writes it (handoffs). Its booking is as above.
|
|
454
|
+
const holdShort = holdShortOf(usage, flight, hold, plan || free);
|
|
433
455
|
try {
|
|
434
456
|
// A runner.turn with the ids holds what a carried response record of this turn would: that one is dropped. A
|
|
435
457
|
// stopped one keeps the figure it counts at (`heldUsd`), so a later process counts it the same.
|
|
@@ -441,7 +463,7 @@ function bookingFor(writer, options) {
|
|
|
441
463
|
// Refused (its claim lost as it answered, say): the booking is handed to the session's next booking in this
|
|
442
464
|
// process, which writes it at its bookCut, never cutting a request that answered (handoffs).
|
|
443
465
|
if (scope !== undefined)
|
|
444
|
-
handoffOf(scope).refused.set(turn, { data, usage, ...(ended ? { ended } : {}) });
|
|
466
|
+
handoffOf(scope).refused.set(turn, { data, usage, ...(ended ? { ended } : {}), ...(holdShort ? { holdShort } : {}) });
|
|
445
467
|
settle?.();
|
|
446
468
|
// A paid request whose cost can't be kept: the attempt stops, saying so, rather than spend on uncounted. Asked
|
|
447
469
|
// with the request's own host label, as its admission was: a stop that holds only the harness's own requests (a
|
|
@@ -457,7 +479,7 @@ function bookingFor(writer, options) {
|
|
|
457
479
|
const hosted = hosts.get(turn);
|
|
458
480
|
// Awaited: a host that marks the request's end on its record writes it before the booking counts as settled, so a
|
|
459
481
|
// run's end never lands ahead of the mark that says its request was cut.
|
|
460
|
-
await emit({ type: "request_end", turn, usage, ...(hosted === undefined ? {} : { host: hosted }), ...(ended ? { ended } : {}) });
|
|
482
|
+
await emit({ type: "request_end", turn, usage, ...(hosted === undefined ? {} : { host: hosted }), ...(ended ? { ended } : {}), ...(holdShort ? { holdShort } : {}) });
|
|
461
483
|
},
|
|
462
484
|
};
|
|
463
485
|
// One booking of the cut requests at a time: a call made while one is writing waits for it, never books them again.
|
|
@@ -515,7 +537,7 @@ function bookingFor(writer, options) {
|
|
|
515
537
|
spentUsd = sessionSpendOf([...now, ...booked]).spentUsd;
|
|
516
538
|
for (const one of taken) {
|
|
517
539
|
const hosted = hosts.get(one.turn);
|
|
518
|
-
await emit({ type: "request_end", turn: one.turn, usage: one.usage, ...(hosted === undefined ? {} : { host: hosted }), ...(one.ended ? { ended: one.ended } : {}) });
|
|
540
|
+
await emit({ type: "request_end", turn: one.turn, usage: one.usage, ...(hosted === undefined ? {} : { host: hosted }), ...(one.ended ? { ended: one.ended } : {}), ...(one.holdShort ? { holdShort: one.holdShort } : {}) });
|
|
519
541
|
}
|
|
520
542
|
}
|
|
521
543
|
handoffDone(scope);
|
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.
|
|
3
|
+
"version": "0.1.0-beta.45",
|
|
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.
|
|
65
|
+
"@parcha/agentrun-dsl": "0.1.0-beta.45",
|
|
66
66
|
"ajv": "8.18.0",
|
|
67
67
|
"typebox": "1.3.27"
|
|
68
68
|
},
|