@parcha/agentrun-kernel 0.1.0-beta.29 → 0.1.0-beta.30
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 +46 -0
- package/README.md +12 -1
- package/dist/booking.d.ts +50 -0
- package/dist/booking.js +52 -0
- package/dist/host/proxy.d.ts +37 -4
- package/dist/host/proxy.js +193 -14
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -1
- package/dist/kernel/drive.d.ts +5 -0
- package/dist/kernel/drive.js +38 -1
- package/dist/kernel/types.d.ts +9 -0
- package/dist/process/settle.d.ts +14 -3
- package/dist/process/settle.js +23 -5
- package/dist/runner.js +19 -7
- package/dist/types.d.ts +24 -5
- package/dist/types.js +7 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,52 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## 0.1.0-beta.30 (2026-11-05)
|
|
6
|
+
|
|
7
|
+
- A Codex run stopped just after its message was sent to Codex no longer loses the message. Codex answers `turn/start` before it writes the message to its rollout: on the real app-server, killed at the answer or 20 ms after it, the rollout held no user message; 100 ms after, it did. A stop in that window kills Codex with the message sent and never recorded, and the next Codex, resumed from the session's rollout, never has it. The stop's settle now reads Codex's rollout as the session keeps it, the rollout the next Codex is resumed from, and carries a placed message it lacks into the next one, as claude-agent's settle reads its CLI's transcript. The `turn/start` send mark is gone (the kernel's `markSent` and `sentMarks` with it); a stopped drive still starts no turn.
|
|
8
|
+
- A run whose model provider stops the answer on its content filter now ends `failed` with `error.code` `moderated` and
|
|
9
|
+
says so in plain words: "The model provider stopped this answer (its content filter). Rephrase the request, or try
|
|
10
|
+
another model." Before, it ended `run_failed` with the provider's jargon ("Response incomplete: content_filter"). The
|
|
11
|
+
Timeline's error row keeps the harness's words for the stop (pi-ai's on pi, the kernel's on claude-agent and codex). On pi the run reads pi-ai's words for the stop on each API. On
|
|
12
|
+
claude-agent and codex the session's model proxy reads the provider's stop (Anthropic's `refusal`, an OpenAI answer
|
|
13
|
+
`incomplete` for `content_filter`) and the harness ends the turn at once: the CLI no longer asks for the refused answer
|
|
14
|
+
again, turn after turn. Only the turn's own answer request ends it: a side call the CLI makes beside the turn (one
|
|
15
|
+
without the session's tools) that the provider stops is logged and left to the CLI. The refused request is booked at
|
|
16
|
+
the usage its end reports. The kernel exports `CONTENT_FILTERED`, the text such a turn ends with; a provider policy may
|
|
17
|
+
say a stop through `filtered` and a side call through `answers`, and the model proxy tells its machine through
|
|
18
|
+
`onFiltered`.
|
|
19
|
+
- A message the person stopped before the harness began it is no longer lost. A Codex or Claude run stopped in its first seconds (Codex still starting), then told "Go on.", answered "I'm missing the earlier task context": the stop withdrew the first message, and the follow-up reached the model alone. Now the stopped message stays in the conversation. The next message carries it first, with a line saying it was stopped before any work on it began, and the stopped turn still never runs on its own. Several stopped messages are carried in order. A stopped steer is not carried. A crash after the next message was taken, before the harness recorded it, still recovers with the stopped words.
|
|
20
|
+
- A model request under a spend cap is booked by one rule on every harness: the kernel's `bookRequest`, from how the
|
|
21
|
+
request ended (`Ended`). The rule is never to under-count.
|
|
22
|
+
- **A whole answer** books its own cost, or its hold when that cost cannot be read. On pi, that used to make what the run
|
|
23
|
+
had spent unknown.
|
|
24
|
+
- **An error status before any event**, or a request refused at connect, books nothing.
|
|
25
|
+
- **A failure once the request left, a gateway's 504 or 524, or an answer after an attempt that was lost** books the
|
|
26
|
+
hold.
|
|
27
|
+
- **A stop** books what streamed: its content, and the part of a hidden reasoning budget that did not stream.
|
|
28
|
+
- **A content-filter end** on pi books the hold: pi-ai ends it as an error after events, which can have been billed. On
|
|
29
|
+
the proxy, a filtered answer is an answer and books its own cost.
|
|
30
|
+
|
|
31
|
+
On pi, the cap now gives pi-ai a fetch that records each attempt pi-ai makes, so a reset before any response books the
|
|
32
|
+
hold where it booked $0, and a 429 then an answer is priced once. An API whose transport that fetch cannot see (Codex's
|
|
33
|
+
WebSocket, Bedrock, Google, Cloudflare) books the hold for a failure before any event. A later process reads the figure
|
|
34
|
+
this one booked: a pi request that failed before any event marks its hold, and the runner writes `bookedUsd` and `rule` on
|
|
35
|
+
its records. The model proxy passes how a request ended as `afterRequest`'s third argument.
|
|
36
|
+
If the store cannot take such a mark within 15 s, the request fails, saying its end could not be recorded, and a later
|
|
37
|
+
process reads it at its hold.
|
|
38
|
+
- A request you stop under a cap counts the reasoning it never streamed. A model whose reasoning streams only as a summary (the Responses API's reasoning, Claude 4-class thinking) is billed for far more than the summary's bytes. A stop after about 10,000 hidden reasoning tokens on a gpt-5-class model with a 20 KB context cost about $0.106 and counted $0.038, so deliberate stops could pass a cap. A stopped request that reasons now also counts the part of its reasoning budget that did not stream: input + streamed + 1,024 + max(0, reasoning budget - reasoning streamed), never more than its hold. Real usage still replaces the figure when it comes.
|
|
39
|
+
- **On pi:** a reasoning model's stopped request counts its thinking level's budget (on Anthropic's API, the `budget_tokens` it was sent with, for a model whose thinking takes one). A Claude model that thinks adaptively (every current one on Anthropic's API) is sent no budget, and its thinking is bounded only by its output limit, so it counts that limit less 1,024 tokens: in practice its hold. A stop after a 300-byte thinking summary on Sonnet 5.5 with a 20 KB context under a $1 cap counted $0.142 at medium and $0.224 at high, against about $0.45 for 40,000 adaptive thinking tokens. The request's output limit is now the one actually sent: the cap had taken a thinking budget out of it that pi-ai never sends (8,192 tokens at medium), so the request was held at more than it was sent with. With no level, on an API whose model reasons at its own default, it counts its whole output limit. With thinking off on Anthropic's API, on a model whose thinking can be off, nothing more.
|
|
40
|
+
- **Adaptive thinking counts up to the hold.** On every current Claude model, on pi and on `claude-agent`, the provider is given no thinking budget, so a stopped request counts up to the hold the cap took for it. Under a cap with little left beside that hold, the request after the stop can be refused.
|
|
41
|
+
- **On `codex`:** the effort's budget (minimal 1,024, low 2,048, medium 8,192, high 16,384), none at effort `none`, and the output limit when the body names no effort.
|
|
42
|
+
- **On `opencode`:** the same as `codex` (the same Responses API): what a stop counts as streamed is the content its deltas carried, not the wire, plus the unstreamed part of its effort's budget. On the walk through OpenCode's proxy (a request at $100 a million output tokens under a $0.50 cap, stopped after 1,146 characters of answer text after the stream's echo of the request) the stop booked 106,831 bytes, its whole $0.50 hold, and refused "Go on."; it now counts $0.217, and "Go on." goes.
|
|
43
|
+
- **On `claude-agent`:** the thinking budget, or `max_tokens` when thinking is adaptive, for every request that thinks; none with thinking off. Thinking that streamed is subtracted, so a stop after a budget's worth of visible thinking counts nothing on top.
|
|
44
|
+
- **Kernel:** a provider policy may read a request's hidden reasoning from its body (`reasoningHidden`). It may also read the reasoning in each streamed event (`reasoningBytesOf`). The model proxy books a stopped response with both (`stoppedHiddenTokens`, `stoppedReasoningBytes`), and the runner counts all it sent plus the part of the budget its reasoning did not cover.
|
|
45
|
+
- **What streamed is the content, not the wire.** On `claude-agent` and `codex` a stop counted the response's bytes as sent, the provider's framing included: about 11.7 bytes a character of text on the Responses API and 24 on the Messages API. A codex request at $100 a million output under a $0.50 cap, stopped after 1,146 characters, booked its whole hold and refused "Go on.". It now counts each text, reasoning and tool-argument delta's UTF-8 bytes, as pi counts its streamed blocks: $0.217, and the next request goes. A provider policy reads them (`contentBytesOf`).
|
|
46
|
+
- **A stop before the provider's first header** on `claude-agent` and `codex` now counts as a stop with nothing streamed (its input and 1,024 tokens, as on pi), not its whole hold. A response the provider answered with an error status still counts at its hold.
|
|
47
|
+
- A message the person stopped the instant it was sent is no longer lost on claude-agent, and the same window is closed on Codex and OpenCode. Asked "Reply with exactly this code and nothing else: CARRY-CLAUDE-7", stopped within its first second, then told "Go on.", a claude-agent run answered "There's nothing earlier in this conversation for me to continue from": Claude takes a message within its first second, so the stop landed after the harness placed it and before the CLI was handed it, and nothing carried it. Now a stop's settle carries a placed message its CLI never took into the next one, as it carries one stopped before it was placed. On claude-agent that is a message the CLI's own transcript, as the session keeps it, does not hold: that transcript is the history a resumed CLI is given, so a carried message is never sent twice. On Codex it is a message Codex's own rollout, as the session keeps it, does not hold. OpenCode marks a message just before it sends it (`prompt_async`), and a marked message is never carried: a crash between the mark and the send loses it rather than sending it twice. After a stop, no new turn is started.
|
|
48
|
+
- **A recovered message is not carried again.** After a crash between a message's placement and its CLI's record, the recovery message carries its words. It now records which messages it carries, before it goes (a kernel effect by its id on claude-agent, its `PROMPT_STREAM` record on OpenCode). Once the CLI holds the recovery message, a stop's settle and a later recovery both count those messages sent, so nothing is sent twice, even after a second crash. Codex's recovery already did this through its client id.
|
|
49
|
+
- **A follow-up's own prompt** (the host's, named to the settle) is withdrawn and never carried into the person's next message, as the follow-up says: a host prompt that never ran is not sent. A person's message waiting beside it is left as it is.
|
|
50
|
+
|
|
5
51
|
## 0.1.0-beta.29 (2026-11-04)
|
|
6
52
|
|
|
7
53
|
- `@parcha/agentrun-adapters/kernel` and `@parcha/agentrun-adapters/process`: the durable kernel a harness adapter runs on, over the run's session store, and the shared layer for harnesses that run as a child process.
|
package/README.md
CHANGED
|
@@ -18,7 +18,18 @@ harness adapter the way they run on Pi, durable in AgentRun's own store.
|
|
|
18
18
|
call that finished during the pause is never run, or paid for, again.
|
|
19
19
|
- `AgentAdapter` is the interface a harness implements: `check` refuses a session before anything is spent (a fork it
|
|
20
20
|
cannot make), and `open` restores a session from its records. A session's `settleOpenTurn()` ends a turn its records
|
|
21
|
-
still hold open (one the person stopped), interrupted, and runs nothing, so the turn is never resumed.
|
|
21
|
+
still hold open (one the person stopped), interrupted, and runs nothing, so the turn is never resumed. A prompt it
|
|
22
|
+
stopped before the harness placed it stays in the conversation: the next prompt or follow-up carries its text first,
|
|
23
|
+
with a line saying it was stopped before any work on it began. The carry is in that message's text in the session's
|
|
24
|
+
state, so a crash's recovery of it, placed but never recorded by the CLI, sends the stopped words too. So does a
|
|
25
|
+
prompt the harness placed and its CLI never took (the stop came between the two), carried by `settleTurn`'s `unsent`.
|
|
26
|
+
Whether the CLI took it is the CLI's own record as the session keeps it, the history a resumed CLI is given:
|
|
27
|
+
claude-agent's transcript, Codex's rollout (Codex answers `turn/start` before it writes the message, and the Claude
|
|
28
|
+
SDK writes a message to the CLI at once, so a stop can kill either before it records it). A prompt that record lacks
|
|
29
|
+
the next turn's model never saw, so carrying it never sends it twice. OpenCode marks a prompt just before it sends it,
|
|
30
|
+
and a marked one is never carried. A recovery message records which placed prompts it carries before it goes, so once
|
|
31
|
+
the CLI holds it they count as recorded, across a chain of recoveries. A follow-up's own prompt, named to the settle
|
|
32
|
+
(`opening`), is withdrawn and never carried.
|
|
22
33
|
- `SessionStore` is the run's store for sessions. A session is written only through a writer, and `open(key)` takes the
|
|
23
34
|
session: every writer opened earlier for that key is fenced from then on, and its appends are refused
|
|
24
35
|
(`SessionFenced`) with nothing written. The runner opens one writer per attempt and hands it to the adapter, so a
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What one model request counts at under a spend cap: one rule for every path (pi's requests in serve's own process, and
|
|
3
|
+
* the claude-agent, codex and opencode requests the kernel's model proxy books through the runner). The rule is never to
|
|
4
|
+
* under-count: a request counts at what it can have cost, never less.
|
|
5
|
+
*
|
|
6
|
+
* A path says how its request ended (`Ended`), and `bookRequest` gives its figure:
|
|
7
|
+
* - `answered`: a whole answer, at the cost its usage (or its gateway) says, else the hold;
|
|
8
|
+
* - `nothing`: the provider answered a status before any event (not a gateway's timeout), or the request provably never
|
|
9
|
+
* left (`isConnectCode`): 0;
|
|
10
|
+
* - `lost`: anything that can have been billed and says no cost (a transport error once it left, a cut answer, a
|
|
11
|
+
* gateway's 504 or 524, an answer after an attempt that was lost, which can have been billed twice, a crash): the hold;
|
|
12
|
+
* - `stopped`: our abort, its client gone part way: what streamed (its content, and the part of a hidden reasoning
|
|
13
|
+
* budget that did not stream), priced by the path (`stoppedPrice`), never past the hold.
|
|
14
|
+
* With no hold (no cap), a figure no one knows is `null`, as it always was.
|
|
15
|
+
*/
|
|
16
|
+
/** How a request ended, as its path saw it. `label` names the case for the record (`rule`); it changes no figure but
|
|
17
|
+
* `answered`'s `filtered` (a content-filter end: its reported usage, else the hold, as any answer). */
|
|
18
|
+
export type Ended = {
|
|
19
|
+
end: "answered";
|
|
20
|
+
usd: number | null;
|
|
21
|
+
label?: "filtered";
|
|
22
|
+
} | {
|
|
23
|
+
end: "nothing";
|
|
24
|
+
label: "status" | "never_left";
|
|
25
|
+
} | {
|
|
26
|
+
end: "lost";
|
|
27
|
+
label: "error_before" | "error_after" | "gateway_timeout" | "retried" | "cut";
|
|
28
|
+
began?: boolean;
|
|
29
|
+
} | {
|
|
30
|
+
end: "stopped";
|
|
31
|
+
streamedTokens: number;
|
|
32
|
+
};
|
|
33
|
+
/** What a path prices a request with: what its cap held for it, and what it counts at when stopped having streamed
|
|
34
|
+
* `tokens` (its input, those tokens and the stop's allowance, at most its output limit, at its price). */
|
|
35
|
+
export type Priced = {
|
|
36
|
+
hold?: number;
|
|
37
|
+
stoppedPrice?: (streamedTokens: number) => number;
|
|
38
|
+
};
|
|
39
|
+
/** A booked request: its figure (null when no one knows it and nothing was held), and the rule that gave it. */
|
|
40
|
+
export type Booked = {
|
|
41
|
+
usd: number | null;
|
|
42
|
+
rule: string;
|
|
43
|
+
};
|
|
44
|
+
/** The one booking of a request: `ended` priced by `priced`. */
|
|
45
|
+
export declare function bookRequest(ended: Ended, priced: Priced): Booked;
|
|
46
|
+
export declare const isConnectCode: (code: unknown) => boolean;
|
|
47
|
+
/** A gateway's answer that the provider was still at work when it gave up (Cloudflare's 524, a 504): billed, not a status. */
|
|
48
|
+
export declare const isGatewayTimeout: (status: number) => boolean;
|
|
49
|
+
/** The code of a fetch's rejection: its cause's (undici), else its own. */
|
|
50
|
+
export declare const rejectionCode: (error: unknown) => string | undefined;
|
package/dist/booking.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What one model request counts at under a spend cap: one rule for every path (pi's requests in serve's own process, and
|
|
3
|
+
* the claude-agent, codex and opencode requests the kernel's model proxy books through the runner). The rule is never to
|
|
4
|
+
* under-count: a request counts at what it can have cost, never less.
|
|
5
|
+
*
|
|
6
|
+
* A path says how its request ended (`Ended`), and `bookRequest` gives its figure:
|
|
7
|
+
* - `answered`: a whole answer, at the cost its usage (or its gateway) says, else the hold;
|
|
8
|
+
* - `nothing`: the provider answered a status before any event (not a gateway's timeout), or the request provably never
|
|
9
|
+
* left (`isConnectCode`): 0;
|
|
10
|
+
* - `lost`: anything that can have been billed and says no cost (a transport error once it left, a cut answer, a
|
|
11
|
+
* gateway's 504 or 524, an answer after an attempt that was lost, which can have been billed twice, a crash): the hold;
|
|
12
|
+
* - `stopped`: our abort, its client gone part way: what streamed (its content, and the part of a hidden reasoning
|
|
13
|
+
* budget that did not stream), priced by the path (`stoppedPrice`), never past the hold.
|
|
14
|
+
* With no hold (no cap), a figure no one knows is `null`, as it always was.
|
|
15
|
+
*/
|
|
16
|
+
const figure = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
|
|
17
|
+
/** The one booking of a request: `ended` priced by `priced`. */
|
|
18
|
+
export function bookRequest(ended, priced) {
|
|
19
|
+
const hold = figure(priced.hold);
|
|
20
|
+
const rule = "label" in ended && ended.label ? `${ended.end}:${ended.label}` : ended.end;
|
|
21
|
+
switch (ended.end) {
|
|
22
|
+
case "answered": {
|
|
23
|
+
// A content filter's end is an answer: its usage when it reported one, else the hold.
|
|
24
|
+
const usd = figure(ended.usd);
|
|
25
|
+
return { usd: usd ?? hold ?? null, rule };
|
|
26
|
+
}
|
|
27
|
+
case "nothing":
|
|
28
|
+
return { usd: 0, rule };
|
|
29
|
+
case "lost":
|
|
30
|
+
return { usd: hold ?? null, rule };
|
|
31
|
+
case "stopped": {
|
|
32
|
+
const streamed = figure(ended.streamedTokens);
|
|
33
|
+
const stopped = hold !== undefined && streamed !== undefined && priced.stoppedPrice ? figure(priced.stoppedPrice(streamed)) : undefined;
|
|
34
|
+
return { usd: stopped === undefined ? hold ?? null : Math.min(hold, stopped), rule };
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** The connect-phase codes of a request that never left: refused, unresolved or unreachable, a connect timeout, or a TLS
|
|
39
|
+
* certificate refused before the request was written. Anything else (a reset, a timeout once connected, no code) left. */
|
|
40
|
+
const CONNECT_CODES = new Set([
|
|
41
|
+
"ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EHOSTUNREACH", "ENETUNREACH", "UND_ERR_CONNECT_TIMEOUT",
|
|
42
|
+
"DEPTH_ZERO_SELF_SIGNED_CERT", "UNABLE_TO_VERIFY_LEAF_SIGNATURE", "SELF_SIGNED_CERT_IN_CHAIN", "ERR_TLS_CERT_ALTNAME_INVALID",
|
|
43
|
+
]);
|
|
44
|
+
export const isConnectCode = (code) => typeof code === "string" && (CONNECT_CODES.has(code) || code.startsWith("CERT_"));
|
|
45
|
+
/** A gateway's answer that the provider was still at work when it gave up (Cloudflare's 524, a 504): billed, not a status. */
|
|
46
|
+
export const isGatewayTimeout = (status) => status === 504 || status === 524;
|
|
47
|
+
/** The code of a fetch's rejection: its cause's (undici), else its own. */
|
|
48
|
+
export const rejectionCode = (error) => {
|
|
49
|
+
const at = error;
|
|
50
|
+
const code = at?.cause?.code ?? at?.code;
|
|
51
|
+
return typeof code === "string" ? code : undefined;
|
|
52
|
+
};
|
package/dist/host/proxy.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type IncomingHttpHeaders } from "node:http";
|
|
2
|
+
import { type Ended } from "../booking.js";
|
|
2
3
|
/** A route a policy admits: its method, its exact path, and the request headers forwarded with it. */
|
|
3
4
|
export interface ProxyRoute {
|
|
4
5
|
readonly method: string;
|
|
@@ -35,6 +36,14 @@ export interface ProviderPolicy {
|
|
|
35
36
|
/** The usage a completed response reports, if it reports one: from its whole text, or, for a long one, its first and
|
|
36
37
|
* last 64 KiB (a provider may report input tokens as a stream starts and output tokens as it ends). */
|
|
37
38
|
usageOf(text: string): ProxyUsage | undefined;
|
|
39
|
+
/** Whether the provider stopped a completed answer on its content filter (a refusal), read from its text as `usageOf`
|
|
40
|
+
* reads it, never by matching its words, and from `lineStarts`, the start of each of its last whole lines (16 KiB of
|
|
41
|
+
* each, for a line longer than the text kept). Absent: the policy cannot tell, and no answer is read as stopped. */
|
|
42
|
+
filtered?(text: string, lineStarts: readonly string[]): boolean;
|
|
43
|
+
/** Whether a request is the turn's answer request (the client's own turn, which offers the model the session's tools),
|
|
44
|
+
* and not a side call its client makes beside the turn (a title, a summary): only an answer request's content-filter
|
|
45
|
+
* stop ends the turn; a side call's is logged and left to the client. Absent: every request is the turn's. */
|
|
46
|
+
answers?(body: Record<string, unknown>): boolean;
|
|
38
47
|
/** Called once for each request the proxy forwards that the provider answers, as the answer starts. Requests overlap (a
|
|
39
48
|
* client's background calls run beside its turn), so what it keeps is for the sink to tell apart: each call returns its own
|
|
40
49
|
* observer. The observer is given each piece of the answer as text, BEFORE that piece is written to the client, so what it
|
|
@@ -64,6 +73,18 @@ export interface ProviderPolicy {
|
|
|
64
73
|
/** The least output the body may be limited to and still answer: 1,024 tokens for the answer, plus the least thinking
|
|
65
74
|
* its provider takes when it thinks. Absent: 1,024. */
|
|
66
75
|
outputLeast?(body: Record<string, unknown>): number;
|
|
76
|
+
/** The reasoning tokens the body's request may bill that its response does not stream (a provider that streams only a
|
|
77
|
+
* summary of its reasoning, or none): its effort's or its thinking's budget, else its output limit when it reasons at
|
|
78
|
+
* an effort the body does not say. A stopped request counts them beside what streamed. Absent or 0: none. */
|
|
79
|
+
reasoningHidden?(body: Record<string, unknown>): number | undefined;
|
|
80
|
+
/** The bytes of reasoning one whole server-sent event of the response carries (a reasoning summary's or a thinking
|
|
81
|
+
* delta's text, UTF-8), 0 for any other event. A stopped request subtracts what reached its client from the budget
|
|
82
|
+
* `reasoningHidden` reads, so reasoning that streamed is not counted twice, and answer text never stands in for it. */
|
|
83
|
+
reasoningBytesOf?(event: string): number;
|
|
84
|
+
/** The bytes of content one whole server-sent event of the response carries: its text, reasoning and tool-call
|
|
85
|
+
* arguments, UTF-8, never the framing around them (ids, indexes, sequence numbers). A stopped request counts what of
|
|
86
|
+
* this reached its client, as pi counts the blocks it streamed. Absent: the bytes as sent. */
|
|
87
|
+
contentBytesOf?(event: string): number;
|
|
67
88
|
/** The body `apply` returned with its output limited to `max` tokens, thinking included (what is left of a spend cap
|
|
68
89
|
* can buy): never more than it asked for, and never longer as sent, since its input bound was measured on it. A host
|
|
69
90
|
* that limits a request's output needs it: without it such a request is refused, never sent unlimited. */
|
|
@@ -80,9 +101,17 @@ export interface ModelUsageReport extends ProxyUsage {
|
|
|
80
101
|
tableUsd?: number | null;
|
|
81
102
|
/** The ids the response's headers gave it (`providerIdsOf`), when they came. */
|
|
82
103
|
providerIds?: Record<string, string>;
|
|
83
|
-
/** A response its client left before its end (a stop), with
|
|
84
|
-
*
|
|
104
|
+
/** A response its client left before its end (a stop), with what of it the client was sent: the content of its events
|
|
105
|
+
* (text, reasoning, tool arguments, UTF-8 bytes) where the policy reads it (`contentBytesOf`), else the bytes as sent.
|
|
106
|
+
* Not set for one the provider ended early (an error part way), nor for one the client read whole. */
|
|
85
107
|
stoppedAfterBytes?: number;
|
|
108
|
+
/** A stopped response's reasoning budget, as the policy reads it from the body (`reasoningHidden`): reasoning that
|
|
109
|
+
* streams only as a summary, or not at all. Set only with `stoppedAfterBytes`, and only when above 0. */
|
|
110
|
+
stoppedHiddenTokens?: number;
|
|
111
|
+
/** The bytes of reasoning the client was sent of a stopped response (its summary or thinking deltas, by the policy's
|
|
112
|
+
* `reasoningBytesOf`), set with `stoppedHiddenTokens`. The host counts the budget less these, max(0, budget - these),
|
|
113
|
+
* beside `stoppedAfterBytes`. */
|
|
114
|
+
stoppedReasoningBytes?: number;
|
|
86
115
|
}
|
|
87
116
|
/** A paid request as the host is asked about it, before it leaves. */
|
|
88
117
|
export interface ProxyRequest {
|
|
@@ -99,8 +128,9 @@ export interface ModelProxyHooks {
|
|
|
99
128
|
* `afterRequest`, since requests may be in flight together. A ticket's `outputTokensMax` limits the request's output
|
|
100
129
|
* (thinking included) to that many tokens, written into its body by the policy's `limitOutput` before it is sent. */
|
|
101
130
|
beforeRequest(request: ProxyRequest): Promise<unknown>;
|
|
102
|
-
/** When a request's response has completed, with its usage
|
|
103
|
-
|
|
131
|
+
/** When a request's response has completed, with its usage, the ticket its `beforeRequest` returned, and how it ended
|
|
132
|
+
* (booking.ts), which the runner books it by: one rule for every path. */
|
|
133
|
+
afterRequest(usage: ModelUsageReport, ticket?: unknown, ended?: Ended): Promise<void>;
|
|
104
134
|
/** When a paid request's response headers arrive, before its body: the ids they give it (`providerIdsOf`), so a
|
|
105
135
|
* request a crash cuts off after this point is known to have reached the provider, under those ids. */
|
|
106
136
|
responded?(ids: Record<string, string>, ticket?: unknown): Promise<void>;
|
|
@@ -133,6 +163,9 @@ export interface ModelProxyOptions {
|
|
|
133
163
|
headers?: Readonly<Record<string, string>>;
|
|
134
164
|
/** For tests: the fetch the proxy forwards with. */
|
|
135
165
|
fetch?: typeof fetch;
|
|
166
|
+
/** Told, with CONTENT_FILTERED, once an answer the provider stopped on its content filter has been passed and booked
|
|
167
|
+
* (`ProviderPolicy.filtered`): the harness halts the turn with it, before its client asks for the answer again. */
|
|
168
|
+
onFiltered?: (message: string) => void;
|
|
136
169
|
}
|
|
137
170
|
/** What is wrong with headers a host would add to forwarded requests: a name that is not a token or is reserved, a value
|
|
138
171
|
* an HTTP header cannot carry (a line break or other control character, or a character beyond Latin-1, which the fetch
|
package/dist/host/proxy.js
CHANGED
|
@@ -16,6 +16,50 @@
|
|
|
16
16
|
// Model spend is accounted only there, by the runner: the proxy keeps no ledger of its own.
|
|
17
17
|
import { createHash, timingSafeEqual } from "node:crypto";
|
|
18
18
|
import { createServer } from "node:http";
|
|
19
|
+
import { CONTENT_FILTERED } from "../types.js";
|
|
20
|
+
import { isConnectCode, isGatewayTimeout, rejectionCode } from "../booking.js";
|
|
21
|
+
/** The longest a response's text may run with no event boundary before the reasoning count lets it go (a body that is
|
|
22
|
+
* not a stream of events, read whole as one). */
|
|
23
|
+
const EVENT_MAX_CHARS = 1 << 22;
|
|
24
|
+
/** What of a response reached its client, event by event: each whole server-sent event (up to a blank line) read by
|
|
25
|
+
* each of `readers`, its bytes added to that reader's sum; a reader the policy does not have counts none. */
|
|
26
|
+
function eventCounter(readers) {
|
|
27
|
+
const keys = Object.keys(readers).filter((key) => readers[key] !== undefined);
|
|
28
|
+
const sums = Object.fromEntries(keys.map((key) => [key, 0]));
|
|
29
|
+
let pending = "";
|
|
30
|
+
/** A "\r" the last piece ended on: the first half of a "\r\n" the next piece ends. */
|
|
31
|
+
let cr = "";
|
|
32
|
+
return {
|
|
33
|
+
push(text) {
|
|
34
|
+
if (!keys.length)
|
|
35
|
+
return;
|
|
36
|
+
// A line end split between pieces ("\r" here, "\n" in the next) is joined before "\r\n" becomes "\n", or the two
|
|
37
|
+
// events around a split blank line would read as one, which no policy can parse.
|
|
38
|
+
let piece = cr + text;
|
|
39
|
+
cr = piece.endsWith("\r") ? "\r" : "";
|
|
40
|
+
if (cr)
|
|
41
|
+
piece = piece.slice(0, -1);
|
|
42
|
+
pending += piece.replace(/\r\n/g, "\n");
|
|
43
|
+
for (let at = pending.indexOf("\n\n"); at >= 0; at = pending.indexOf("\n\n")) {
|
|
44
|
+
const event = pending.slice(0, at);
|
|
45
|
+
pending = pending.slice(at + 2);
|
|
46
|
+
for (const key of keys) {
|
|
47
|
+
try {
|
|
48
|
+
const n = readers[key](event);
|
|
49
|
+
if (typeof n === "number" && Number.isFinite(n) && n > 0)
|
|
50
|
+
sums[key] += n;
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
// An event the policy cannot read carries nothing it counts.
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (pending.length > EVENT_MAX_CHARS)
|
|
58
|
+
pending = "";
|
|
59
|
+
},
|
|
60
|
+
bytes: (of) => sums[of] ?? 0,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
19
63
|
/** A header a host may not set on forwarded requests: the credential's, the transport's, and the provider's protocol. */
|
|
20
64
|
const RESERVED_HEADER = /^(?:authorization|proxy-authorization|x-api-key|host|content-length|content-type|transfer-encoding|connection|cookie|anthropic-.*)$/i;
|
|
21
65
|
const HEADER_NAME = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
|
|
@@ -38,6 +82,13 @@ const UNSAFE_PATH = /[^A-Za-z0-9/_.\-?=&]|\.\.|\/\/|^[^/]|\?.*\?/;
|
|
|
38
82
|
const MAX_BODY = 32 * 1024 * 1024;
|
|
39
83
|
/** How much of a response's start and end the proxy keeps to read its usage from. */
|
|
40
84
|
const USAGE_WINDOW = 64 * 1024;
|
|
85
|
+
/** How long an answer the provider stopped on its content filter is still read after its client left, or the proxy began
|
|
86
|
+
* to close, so the request is booked at the usage its end reports; past it, it is cut off as any other. */
|
|
87
|
+
const FILTERED_DRAIN_MS = 5_000;
|
|
88
|
+
/** How much of the start of each line of an answer the proxy keeps, for its last LINE_STARTS whole lines: an event's name
|
|
89
|
+
* and the first fields of its data, which a stop can be read from when the event's line is longer than either window. */
|
|
90
|
+
const LINE_START = 16 * 1024;
|
|
91
|
+
const LINE_STARTS = 4;
|
|
41
92
|
/** A response header that names the request: the provider's `request-id` (`x-request-id`), or a gateway's own call id
|
|
42
93
|
* (LiteLLM's `x-litellm-call-id`, the id its spend log records; `llm_provider-request-id`, the provider's passed on). */
|
|
43
94
|
const ID_HEADER = /^(?:[a-z0-9]+[-_])*(?:request|call)[-_]id$/;
|
|
@@ -247,6 +298,8 @@ export async function startModelProxy(options, key) {
|
|
|
247
298
|
const origin = baseOf(options.origin);
|
|
248
299
|
const refusedStatus = policy.refusedStatus ?? 400;
|
|
249
300
|
const inflight = new Set();
|
|
301
|
+
/** The requests whose answer the provider stopped on its content filter, read on for their usage, each until booked. */
|
|
302
|
+
const draining = new Map();
|
|
250
303
|
/** Set by close(): nothing is admitted or sent after it. */
|
|
251
304
|
let closing = false;
|
|
252
305
|
/** The host's log, which must never break a request (a throw from it is dropped). */
|
|
@@ -341,9 +394,15 @@ export async function startModelProxy(options, key) {
|
|
|
341
394
|
const figure = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
|
|
342
395
|
let outputTokensAsked;
|
|
343
396
|
let outputTokensLeast;
|
|
397
|
+
/** The reasoning a stop of this request leaves unseen (the policy's `reasoningHidden`), in tokens. */
|
|
398
|
+
let hiddenTokens = 0;
|
|
399
|
+
/** The content and the reasoning the client was sent, by the policy's reading of each event (content: text,
|
|
400
|
+
* reasoning and tool arguments; reasoning: what of its reasoning streamed). */
|
|
401
|
+
const sentOf = eventCounter({ content: policy.contentBytesOf?.bind(policy), reasoning: policy.reasoningBytesOf?.bind(policy) });
|
|
344
402
|
try {
|
|
345
403
|
outputTokensAsked = figure(policy.outputAsked?.(body));
|
|
346
404
|
outputTokensLeast = figure(policy.outputLeast?.(body));
|
|
405
|
+
hiddenTokens = figure(policy.reasoningHidden?.(body)) ?? 0;
|
|
347
406
|
}
|
|
348
407
|
catch (error) {
|
|
349
408
|
say(`model proxy (${policy.id}): the policy could not read the body's output; its worst case is unmeasured`, { error: String(error?.message ?? error).slice(0, 200) });
|
|
@@ -430,16 +489,21 @@ export async function startModelProxy(options, key) {
|
|
|
430
489
|
}
|
|
431
490
|
const controller = new AbortController();
|
|
432
491
|
inflight.add(controller);
|
|
492
|
+
/** Set once the provider's content-filter stop was told: the answer is read on to its end for its usage, though the
|
|
493
|
+
* client (whose turn the harness ends) goes away. */
|
|
494
|
+
let keepReading = false;
|
|
433
495
|
/** That the client left before the answer reached it whole (the harness stopped the request). */
|
|
434
496
|
let clientLeft = false;
|
|
435
|
-
/** The bytes of the answer the client was sent
|
|
497
|
+
/** The bytes of the answer the client was sent (and, for one read on after its content-filter stop, read after its
|
|
498
|
+
* client left: what the provider streamed). */
|
|
436
499
|
let sentBytes = 0;
|
|
437
500
|
/** That the answer ended because its client left part way, not because the provider or this proxy ended it. */
|
|
438
501
|
let stoppedByClient = false;
|
|
439
502
|
res.on("close", () => {
|
|
440
503
|
if (!answered)
|
|
441
504
|
clientLeft = true;
|
|
442
|
-
|
|
505
|
+
if (!keepReading)
|
|
506
|
+
controller.abort();
|
|
443
507
|
});
|
|
444
508
|
let head = "";
|
|
445
509
|
let tail = "";
|
|
@@ -448,10 +512,64 @@ export async function startModelProxy(options, key) {
|
|
|
448
512
|
let answered;
|
|
449
513
|
/** That the provider's answer began, with its status: what a client that left before the end had of it. */
|
|
450
514
|
let began;
|
|
515
|
+
/** The code of the provider's fetch failing before any response (rejectionCode): a connect-phase one never left. */
|
|
516
|
+
let failedCode;
|
|
451
517
|
let watchEnd;
|
|
452
518
|
/** The ids its headers gave it. */
|
|
453
519
|
let ids;
|
|
454
520
|
let reported;
|
|
521
|
+
/** Whether the provider's content-filter stop was read (once an answer). */
|
|
522
|
+
let filteredTold = false;
|
|
523
|
+
/** Whether this request is the turn's answer request (`ProviderPolicy.answers`): a side call's stop ends nothing. */
|
|
524
|
+
let answering = true;
|
|
525
|
+
try {
|
|
526
|
+
answering = policy.answers ? policy.answers(body) : true;
|
|
527
|
+
}
|
|
528
|
+
catch (error) {
|
|
529
|
+
say(`model proxy (${policy.id}): whether the request is the turn's could not be read; taken as the turn's`, { error: String(error?.message ?? error).slice(0, 200) });
|
|
530
|
+
}
|
|
531
|
+
/** Called once the request is booked, when its answer was read on after its stop (the proxy's close waits for it). */
|
|
532
|
+
let drained;
|
|
533
|
+
const settled = () => {
|
|
534
|
+
if (!drained)
|
|
535
|
+
return;
|
|
536
|
+
draining.delete(controller);
|
|
537
|
+
drained();
|
|
538
|
+
};
|
|
539
|
+
/** The start of the line being read (LINE_START) and of the last whole lines (LINE_STARTS). */
|
|
540
|
+
let lineStart = "";
|
|
541
|
+
let lineLength = 0;
|
|
542
|
+
const starts = [];
|
|
543
|
+
/** Tells the harness the provider stopped this answer on its content filter, when `text` (the answer so far, or the
|
|
544
|
+
* kept window of it) says so: once, and never failing the answer. */
|
|
545
|
+
const tellFiltered = (text) => {
|
|
546
|
+
if (filteredTold || !policy.filtered)
|
|
547
|
+
return;
|
|
548
|
+
let stopped = false;
|
|
549
|
+
try {
|
|
550
|
+
stopped = policy.filtered(text, starts);
|
|
551
|
+
}
|
|
552
|
+
catch (error) {
|
|
553
|
+
say(`model proxy (${policy.id}): whether the provider's content filter stopped the answer could not be read`, { error: String(error?.message ?? error).slice(0, 200) });
|
|
554
|
+
}
|
|
555
|
+
if (!stopped)
|
|
556
|
+
return;
|
|
557
|
+
filteredTold = true;
|
|
558
|
+
if (!answering) {
|
|
559
|
+
say(`model proxy (${policy.id}): the provider stopped a side call on its content filter; left to the client`);
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
562
|
+
say(`model proxy (${policy.id}): the provider stopped the answer on its content filter`);
|
|
563
|
+
// Read on to the answer's end for its usage, though the client goes; the proxy's close waits for it, bounded.
|
|
564
|
+
keepReading = true;
|
|
565
|
+
draining.set(controller, new Promise((resolve) => (drained = resolve)));
|
|
566
|
+
try {
|
|
567
|
+
options.onFiltered?.(CONTENT_FILTERED);
|
|
568
|
+
}
|
|
569
|
+
catch (error) {
|
|
570
|
+
say(`model proxy (${policy.id}): onFiltered threw`, { error: String(error?.message ?? error).slice(0, 200) });
|
|
571
|
+
}
|
|
572
|
+
};
|
|
455
573
|
try {
|
|
456
574
|
// From here a paid request may be paid, so every way out below books it exactly once.
|
|
457
575
|
const upstream = await forward(`${origin}${route.path}${query ? `?${query}` : ""}`, { method: route.method, headers, body: sent, signal: controller.signal });
|
|
@@ -474,7 +592,7 @@ export async function startModelProxy(options, key) {
|
|
|
474
592
|
say(`model proxy (${policy.id}): responded threw; the request's ids are kept with its booking only`, { error: String(error?.message ?? error).slice(0, 200) });
|
|
475
593
|
}
|
|
476
594
|
}
|
|
477
|
-
began = { ok: upstream.ok };
|
|
595
|
+
began = { ok: upstream.ok, status: upstream.status };
|
|
478
596
|
res.writeHead(upstream.status, { "content-type": upstream.headers.get("content-type") ?? "application/json" });
|
|
479
597
|
const decoder = new TextDecoder();
|
|
480
598
|
let watcher;
|
|
@@ -506,8 +624,31 @@ export async function startModelProxy(options, key) {
|
|
|
506
624
|
watcher = undefined;
|
|
507
625
|
}
|
|
508
626
|
}
|
|
509
|
-
//
|
|
510
|
-
|
|
627
|
+
// The provider's content-filter stop, read before the client has the piece that carries it: the harness ends the
|
|
628
|
+
// turn before its client acts on the stop (asks for the refused answer again, or ends the turn its own way).
|
|
629
|
+
// A line longer than the window is read as it ends, from its start, while the lines just before it (an event's
|
|
630
|
+
// name) are still the last starts kept: a piece may carry the lines after it too.
|
|
631
|
+
const window = (tail + text).slice(-USAGE_WINDOW);
|
|
632
|
+
const lines = text.split("\n");
|
|
633
|
+
for (let at = 0; at < lines.length; at++) {
|
|
634
|
+
if (lineStart.length < LINE_START)
|
|
635
|
+
lineStart += lines[at].slice(0, LINE_START - lineStart.length);
|
|
636
|
+
lineLength += lines[at].length;
|
|
637
|
+
if (at < lines.length - 1) {
|
|
638
|
+
starts.push(lineStart);
|
|
639
|
+
if (starts.length > LINE_STARTS)
|
|
640
|
+
starts.shift();
|
|
641
|
+
if (upstream.ok && lineLength > USAGE_WINDOW)
|
|
642
|
+
tellFiltered(window);
|
|
643
|
+
lineStart = "";
|
|
644
|
+
lineLength = 0;
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
if (upstream.ok && lines.length > 1)
|
|
648
|
+
tellFiltered(window);
|
|
649
|
+
// A client that reads slowly holds the provider back: nothing more is read until what was written drains. A
|
|
650
|
+
// client gone after the stop was told is written nothing more: the answer is read on for its usage alone.
|
|
651
|
+
if (!res.destroyed && !res.write(chunk)) {
|
|
511
652
|
// One wait, and nothing left behind: whichever comes first takes both listeners off.
|
|
512
653
|
await new Promise((resolve) => {
|
|
513
654
|
const done = () => { res.off("drain", done); res.off("close", done); resolve(); };
|
|
@@ -518,6 +659,7 @@ export async function startModelProxy(options, key) {
|
|
|
518
659
|
// The usage is at the start, the end, or both: keep those, not the whole answer.
|
|
519
660
|
length += text.length;
|
|
520
661
|
sentBytes += chunk.byteLength;
|
|
662
|
+
sentOf.push(text);
|
|
521
663
|
if (head.length < USAGE_WINDOW)
|
|
522
664
|
head += text.slice(0, USAGE_WINDOW - head.length);
|
|
523
665
|
tail = (tail + text).slice(-USAGE_WINDOW);
|
|
@@ -528,7 +670,12 @@ export async function startModelProxy(options, key) {
|
|
|
528
670
|
}
|
|
529
671
|
catch (error) {
|
|
530
672
|
// Its client had left before this (a stop): read now, as the proxy's own end below closes the response too.
|
|
531
|
-
|
|
673
|
+
// Before any header too: the request left, and the provider may have begun it, as a stop part way. Only this proxy's
|
|
674
|
+
// abort ends a stop: an answer read on after its client left (its content-filter stop) that the provider ends with
|
|
675
|
+
// an error is no stop.
|
|
676
|
+
stoppedByClient = clientLeft && (began === undefined || began.ok) && controller.signal.aborted;
|
|
677
|
+
if (!began)
|
|
678
|
+
failedCode = rejectionCode(error);
|
|
532
679
|
say(`model proxy (${policy.id}): the request did not complete`, { error: String(error?.message ?? error).slice(0, 200) });
|
|
533
680
|
if (!res.headersSent)
|
|
534
681
|
refuse(res, 502, "the provider did not answer", req);
|
|
@@ -548,7 +695,7 @@ export async function startModelProxy(options, key) {
|
|
|
548
695
|
// cut short, one that said no usage, or a usage or a price that could not be read. A booking that fails is
|
|
549
696
|
// reported (the runner stops the node on it).
|
|
550
697
|
if (route.free)
|
|
551
|
-
return;
|
|
698
|
+
return settled();
|
|
552
699
|
let usage;
|
|
553
700
|
let usd = null;
|
|
554
701
|
// Whether `usd` is a figure the provider gave (an error answer's nothing included), not one this proxy made up.
|
|
@@ -557,15 +704,24 @@ export async function startModelProxy(options, key) {
|
|
|
557
704
|
// A client may leave once it has read the response's usage (Codex does, at the completion event) while the provider
|
|
558
705
|
// still holds the stream open: what was read of a successful answer is read for its usage as a whole one is. With none
|
|
559
706
|
// in it, the cost is unknown, as for any answer cut short.
|
|
560
|
-
|
|
707
|
+
// An error answer cut part way is still an error answer: its status says it was not paid.
|
|
708
|
+
const seen = answered ?? began;
|
|
561
709
|
if (!seen) {
|
|
562
710
|
usage = { input: 0, output: 0, cacheRead: 0 };
|
|
711
|
+
// A request refused at connect never left: it costs nothing. Anything else may have reached the provider.
|
|
712
|
+
if (isConnectCode(failedCode)) {
|
|
713
|
+
usd = 0;
|
|
714
|
+
own = true;
|
|
715
|
+
}
|
|
563
716
|
}
|
|
564
717
|
else if (!seen.ok) {
|
|
565
|
-
// A provider's error answer was not a paid response: it costs nothing.
|
|
718
|
+
// A provider's error answer was not a paid response: it costs nothing. But a gateway's 504 or 524 says only that
|
|
719
|
+
// the gateway gave up: the provider was still at work, and bills it.
|
|
566
720
|
usage = { input: 0, output: 0, cacheRead: 0 };
|
|
567
|
-
|
|
568
|
-
|
|
721
|
+
if (!isGatewayTimeout(began?.status ?? 0)) {
|
|
722
|
+
usd = 0;
|
|
723
|
+
own = true;
|
|
724
|
+
}
|
|
569
725
|
}
|
|
570
726
|
else {
|
|
571
727
|
let unread = false;
|
|
@@ -597,12 +753,26 @@ export async function startModelProxy(options, key) {
|
|
|
597
753
|
}
|
|
598
754
|
try {
|
|
599
755
|
// A response its client stopped and whose cost is unknown says what streamed of it, for the host to count it by.
|
|
600
|
-
|
|
601
|
-
|
|
756
|
+
// With the reasoning it never streamed, which the provider can have billed too.
|
|
757
|
+
// What it streamed: its content where the policy reads it, never the provider's framing; else the bytes as sent.
|
|
758
|
+
const streamed = policy.contentBytesOf ? sentOf.bytes("content") : sentBytes;
|
|
759
|
+
const stopped = stoppedByClient && usd === null ? { stoppedAfterBytes: streamed, ...(hiddenTokens > 0 ? { stoppedHiddenTokens: hiddenTokens, stoppedReasoningBytes: sentOf.bytes("reasoning") } : {}) } : {};
|
|
760
|
+
// How it ended, for the runner to book it by (booking.ts). A stop counts what the stop fields above say of it: its
|
|
761
|
+
// content, and the part of its hidden reasoning budget that did not stream, max(0, budget - the reasoning sent).
|
|
762
|
+
const ended = stoppedByClient && usd === null ? { end: "stopped", streamedTokens: streamed + Math.max(0, hiddenTokens - sentOf.bytes("reasoning")) }
|
|
763
|
+
: !seen ? (isConnectCode(failedCode) ? { end: "nothing", label: "never_left" } : { end: "lost", label: "error_before" })
|
|
764
|
+
: !seen.ok ? (isGatewayTimeout(began?.status ?? 0) ? { end: "lost", label: "gateway_timeout" } : { end: "nothing", label: "status" })
|
|
765
|
+
: !answered && usd === null ? { end: "lost", label: "error_after", began: true }
|
|
766
|
+
: { end: "answered", usd, ...(filteredTold ? { label: "filtered" } : {}) };
|
|
767
|
+
await hooks.afterRequest({ ...usage, usd, ...(own ? {} : { estimated: true }), ...(tableUsd === undefined ? {} : { tableUsd }), ...(ids ? { providerIds: ids } : {}), ...stopped }, ticket, ended);
|
|
602
768
|
}
|
|
603
769
|
catch (error) {
|
|
604
770
|
say(`model proxy (${policy.id}): afterRequest threw; the request was answered and not booked`, { error: String(error?.message ?? error).slice(0, 200) });
|
|
605
771
|
}
|
|
772
|
+
// An answer whose stop no piece showed before it ended (a whole JSON body): read whole once it is booked.
|
|
773
|
+
if (seen?.ok)
|
|
774
|
+
tellFiltered(length <= USAGE_WINDOW ? tail : `${head}\n${tail}`);
|
|
775
|
+
settled();
|
|
606
776
|
};
|
|
607
777
|
const server = createServer((req, res) => { void serve(req, res).catch(() => { if (!res.headersSent)
|
|
608
778
|
refuse(res, 500, "the proxy failed", req);
|
|
@@ -621,7 +791,16 @@ export async function startModelProxy(options, key) {
|
|
|
621
791
|
close: async () => {
|
|
622
792
|
closing = true;
|
|
623
793
|
for (const c of inflight)
|
|
624
|
-
|
|
794
|
+
if (!draining.has(c))
|
|
795
|
+
c.abort();
|
|
796
|
+
// An answer the provider stopped on its content filter is read on to its end and booked first, for FILTERED_DRAIN_MS.
|
|
797
|
+
if (draining.size) {
|
|
798
|
+
let timer;
|
|
799
|
+
await Promise.race([Promise.all(draining.values()), new Promise((resolve) => (timer = setTimeout(resolve, FILTERED_DRAIN_MS)))]);
|
|
800
|
+
clearTimeout(timer);
|
|
801
|
+
for (const c of inflight)
|
|
802
|
+
c.abort();
|
|
803
|
+
}
|
|
625
804
|
server.closeAllConnections();
|
|
626
805
|
await new Promise((resolve) => server.close(() => resolve()));
|
|
627
806
|
},
|
package/dist/index.d.ts
CHANGED
|
@@ -7,5 +7,7 @@ export { toolSchemaProblems } from "./schema-check.js";
|
|
|
7
7
|
export { READ_SKILL_FILE, readSkillFileTool, SKILL_BYTES, skillProblems } from "./skill-files.js";
|
|
8
8
|
export type { HostSkill, SkillFileList } from "./skill-files.js";
|
|
9
9
|
export type { HarnessRunReason } from "./errors.js";
|
|
10
|
-
export { HOST_RESULT_MAX_CHARS } from "./types.js";
|
|
10
|
+
export { CONTENT_FILTERED, HOST_RESULT_MAX_CHARS } from "./types.js";
|
|
11
|
+
export { bookRequest, isConnectCode, isGatewayTimeout, rejectionCode } from "./booking.js";
|
|
12
|
+
export type { Booked, Ended, Priced } from "./booking.js";
|
|
11
13
|
export type { AdapterCapabilities, AdapterEvent, AdapterSession, AgentAdapter, HarnessEvent, HostTool, ToolImage, JsonValue, ModelPort, ModelTicket, ModelRequest, ModelUsage, NodeRequest, SessionIO, SessionRecord, SessionSpec, SessionState, SessionStore, SessionWriter, TurnStatus, } from "./types.js";
|
package/dist/index.js
CHANGED
|
@@ -3,4 +3,5 @@ export { DELEGATE_RESULT_SCHEMA, DELEGATE_TOOL, delegateProblems, delegateTool }
|
|
|
3
3
|
export { HarnessRunError, SessionFenced } from "./errors.js";
|
|
4
4
|
export { toolSchemaProblems } from "./schema-check.js";
|
|
5
5
|
export { READ_SKILL_FILE, readSkillFileTool, SKILL_BYTES, skillProblems } from "./skill-files.js";
|
|
6
|
-
export { HOST_RESULT_MAX_CHARS } from "./types.js";
|
|
6
|
+
export { CONTENT_FILTERED, HOST_RESULT_MAX_CHARS } from "./types.js";
|
|
7
|
+
export { bookRequest, isConnectCode, isGatewayTimeout, rejectionCode } from "./booking.js";
|
package/dist/kernel/drive.d.ts
CHANGED
|
@@ -10,6 +10,11 @@ export declare const KERNEL_RECORDS: {
|
|
|
10
10
|
export declare const INTERRUPTED_TEXT = "interrupted: the process running it stopped before it reported an outcome; it may or may not have taken effect";
|
|
11
11
|
/** The state a session's records fold to. */
|
|
12
12
|
export declare function foldSession(runId: string, records: readonly SessionRecord[]): SessionState;
|
|
13
|
+
/** What the next prompt or follow-up says of the ones a stop withdrew before any work on them began (`carry`). */
|
|
14
|
+
export declare const stoppedLine: (count: number) => string;
|
|
15
|
+
/** The submissions the harness has yet to place, oldest first, each with its text as the fold made it: a prompt or
|
|
16
|
+
* follow-up after a stop's withdraw carries the stopped text first (`carrying`), so the person's earlier words stay in
|
|
17
|
+
* the conversation, and the stopped turn never runs on its own. */
|
|
13
18
|
export declare function pendingSubmissions(state: SessionState): Submission[];
|
|
14
19
|
export declare function hostToolIO(io: EffectIO, ctx: DriveContext, overrides?: {
|
|
15
20
|
signal?: AbortSignal;
|
package/dist/kernel/drive.js
CHANGED
|
@@ -22,15 +22,17 @@ export const INTERRUPTED_TEXT = "interrupted: the process running it stopped bef
|
|
|
22
22
|
export function foldSession(runId, records) {
|
|
23
23
|
const state = { runId, status: "running", submissions: [], placed: new Set(), withdrawn: new Set(), effects: new Map(), effectOrder: [] };
|
|
24
24
|
const byStep = new Map();
|
|
25
|
+
const carry = carrying();
|
|
25
26
|
for (const record of records) {
|
|
26
27
|
if (record.kind === KERNEL_RECORDS.submission) {
|
|
27
28
|
const data = record.data;
|
|
28
29
|
if (state.submissions.some((s) => s.id === data.id))
|
|
29
30
|
continue;
|
|
30
|
-
state.submissions.push({ ...data, receivedAt: new Date(data.receivedAt) });
|
|
31
31
|
// A withdraw lands only while its target is not placed yet.
|
|
32
32
|
if (data.kind === "withdraw" && data.target && !state.placed.has(data.target))
|
|
33
33
|
state.withdrawn.add(data.target);
|
|
34
|
+
const text = carry(state, data);
|
|
35
|
+
state.submissions.push({ ...data, ...(text === undefined ? {} : { text }), receivedAt: new Date(data.receivedAt) });
|
|
34
36
|
}
|
|
35
37
|
else if (record.kind === KERNEL_RECORDS.start) {
|
|
36
38
|
const data = record.data;
|
|
@@ -72,6 +74,41 @@ export function foldSession(runId, records) {
|
|
|
72
74
|
}
|
|
73
75
|
return state;
|
|
74
76
|
}
|
|
77
|
+
/** What the next prompt or follow-up says of the ones a stop withdrew before any work on them began (`carry`). */
|
|
78
|
+
export const stoppedLine = (count) => count === 1 ? "(The message above was stopped before any work on it began.)" : "(The messages above were stopped before any work on them began.)";
|
|
79
|
+
/** The carry, as the fold meets each submission: a prompt or follow-up after withdraws with `carry` of prompts and
|
|
80
|
+
* follow-ups (those since the one before it, in order, with whatever each of them carried, so several stops before a
|
|
81
|
+
* message all reach it) holds their texts first, then `stoppedLine`, then its own. A steer neither carries nor is
|
|
82
|
+
* carried. It is the submission's text in the session's state, so every reader of it, pending or placed (the
|
|
83
|
+
* harness's send, and a crash's recovery of a placed message its CLI never recorded), has the stopped words. */
|
|
84
|
+
function carrying() {
|
|
85
|
+
// Each prompt's and follow-up's own words, and the words it carried.
|
|
86
|
+
const own = new Map();
|
|
87
|
+
const carried = new Map();
|
|
88
|
+
let waiting = [];
|
|
89
|
+
return (state, data) => {
|
|
90
|
+
if (data.kind === "withdraw") {
|
|
91
|
+
// A withdraw that landed (its target unplaced), or one of a placed target its CLI was never sent (`unsent`).
|
|
92
|
+
const landed = data.target !== undefined && (state.withdrawn.has(data.target) || (data.unsent === true && state.placed.has(data.target)));
|
|
93
|
+
const target = data.carry && landed ? own.get(data.target) : undefined;
|
|
94
|
+
if (target && (target.kind === "prompt" || target.kind === "followUp")) {
|
|
95
|
+
waiting.push(...(carried.get(data.target) ?? []), ...(target.text ? [target.text] : []));
|
|
96
|
+
carried.delete(data.target);
|
|
97
|
+
}
|
|
98
|
+
return data.text;
|
|
99
|
+
}
|
|
100
|
+
own.set(data.id, { kind: data.kind, text: data.text });
|
|
101
|
+
if (data.kind === "steer" || !waiting.length)
|
|
102
|
+
return data.text;
|
|
103
|
+
const before = waiting;
|
|
104
|
+
waiting = [];
|
|
105
|
+
carried.set(data.id, before);
|
|
106
|
+
return `${before.join("\n\n")}\n\n${stoppedLine(before.length)}\n\n${data.text ?? ""}`;
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
/** The submissions the harness has yet to place, oldest first, each with its text as the fold made it: a prompt or
|
|
110
|
+
* follow-up after a stop's withdraw carries the stopped text first (`carrying`), so the person's earlier words stay in
|
|
111
|
+
* the conversation, and the stopped turn never runs on its own. */
|
|
75
112
|
export function pendingSubmissions(state) {
|
|
76
113
|
return state.submissions.filter((s) => s.kind !== "withdraw" && !state.placed.has(s.id) && !state.withdrawn.has(s.id));
|
|
77
114
|
}
|
package/dist/kernel/types.d.ts
CHANGED
|
@@ -5,9 +5,18 @@ export type SubmissionKind = "prompt" | "steer" | "followUp" | "withdraw";
|
|
|
5
5
|
export interface Submission {
|
|
6
6
|
id: string;
|
|
7
7
|
kind: SubmissionKind;
|
|
8
|
+
/** What the person sent. In the session's state (foldSession), a prompt or follow-up after `carry` withdraws holds
|
|
9
|
+
* their words first (drive.ts `carrying`); the record keeps the person's own. */
|
|
8
10
|
text?: string;
|
|
9
11
|
/** For a withdraw: the submission it withdraws. */
|
|
10
12
|
target?: string;
|
|
13
|
+
/** For a withdraw of a prompt or follow-up: its text stays in the conversation, carried into the next prompt or
|
|
14
|
+
* follow-up, whose `text` in the session's state (foldSession) holds it first, pending or placed. A person's stop
|
|
15
|
+
* withdraws this way (settleTurn): what they asked is kept, never run on its own. */
|
|
16
|
+
carry?: true;
|
|
17
|
+
/** For a `carry` withdraw of a placed prompt or follow-up its CLI never recorded (process/settle.ts `unsent`):
|
|
18
|
+
* its text is carried as an unplaced one's is, and it stays placed, so nothing sends it on its own. */
|
|
19
|
+
unsent?: true;
|
|
11
20
|
receivedAt: Date;
|
|
12
21
|
}
|
|
13
22
|
export type EffectStatus = "pending" | "running" | "completed" | "failed";
|
package/dist/process/settle.d.ts
CHANGED
|
@@ -1,11 +1,22 @@
|
|
|
1
1
|
import { type Drive } from "../kernel/index.js";
|
|
2
|
+
/** How a settle treats the open turn's prompts beyond those still pending. */
|
|
3
|
+
export interface SettleOptions {
|
|
4
|
+
/** Placed prompts and follow-ups the harness's CLI never recorded (its own record, as the session keeps it): carried,
|
|
5
|
+
* as a pending one is. */
|
|
6
|
+
readonly unsent?: readonly string[];
|
|
7
|
+
/** The submission of a host's own prompt (a follow-up's, `FollowUpTarget.settleOpenTurn`'s `opening`): withdrawn
|
|
8
|
+
* while pending, never carried, and the only one withdrawn. */
|
|
9
|
+
readonly host?: string;
|
|
10
|
+
}
|
|
2
11
|
/**
|
|
3
12
|
* Records the session's open turn as ended in its transcript, the record a turn that ends writes (so `openTurn` finds
|
|
4
13
|
* none, and the next turn carries no recovery note for it), and runs nothing. Input the turn never placed (a stop that
|
|
5
|
-
* landed before the harness took its prompt) is withdrawn first,
|
|
6
|
-
*
|
|
14
|
+
* landed before the harness took its prompt) is withdrawn first, so no later open finds it pending and nothing of it
|
|
15
|
+
* runs on its own; a prompt or follow-up is withdrawn with `carry`, so its text stays in the conversation, carried into
|
|
16
|
+
* the next one (the kernel's pendingSubmissions). A steer is not carried. So is a placed one its harness never sent
|
|
17
|
+
* (`unsent`: the adapter reads its CLI's own record), and a host's prompt (`host`) is dropped instead. It is the write behind
|
|
7
18
|
* `AdapterSession.settleOpenTurn()` for a turn the person stopped, which is never resumed. The adapter checks that a
|
|
8
19
|
* turn is open. The end is the kernel's for the session's own stop (`abortedOutcome` of its `SessionHalt`), the one
|
|
9
20
|
* path an interrupted turn's end takes, though the turn never ran in this process.
|
|
10
21
|
*/
|
|
11
|
-
export declare function settleTurn(drive: Drive): Promise<void>;
|
|
22
|
+
export declare function settleTurn(drive: Drive, options?: SettleOptions): Promise<void>;
|
package/dist/process/settle.js
CHANGED
|
@@ -4,15 +4,33 @@ import { NativeJournal } from "./journal.js";
|
|
|
4
4
|
/**
|
|
5
5
|
* Records the session's open turn as ended in its transcript, the record a turn that ends writes (so `openTurn` finds
|
|
6
6
|
* none, and the next turn carries no recovery note for it), and runs nothing. Input the turn never placed (a stop that
|
|
7
|
-
* landed before the harness took its prompt) is withdrawn first,
|
|
8
|
-
*
|
|
7
|
+
* landed before the harness took its prompt) is withdrawn first, so no later open finds it pending and nothing of it
|
|
8
|
+
* runs on its own; a prompt or follow-up is withdrawn with `carry`, so its text stays in the conversation, carried into
|
|
9
|
+
* the next one (the kernel's pendingSubmissions). A steer is not carried. So is a placed one its harness never sent
|
|
10
|
+
* (`unsent`: the adapter reads its CLI's own record), and a host's prompt (`host`) is dropped instead. It is the write behind
|
|
9
11
|
* `AdapterSession.settleOpenTurn()` for a turn the person stopped, which is never resumed. The adapter checks that a
|
|
10
12
|
* turn is open. The end is the kernel's for the session's own stop (`abortedOutcome` of its `SessionHalt`), the one
|
|
11
13
|
* path an interrupted turn's end takes, though the turn never ran in this process.
|
|
12
14
|
*/
|
|
13
|
-
export async function settleTurn(drive) {
|
|
14
|
-
|
|
15
|
-
|
|
15
|
+
export async function settleTurn(drive, options = {}) {
|
|
16
|
+
const state = drive.state();
|
|
17
|
+
// A placed prompt or follow-up its CLI never recorded (the stop landed between its placement and the CLI's record of
|
|
18
|
+
// it) is carried too, first, as it came first. It stays placed, so nothing sends it on its own. A host's is not.
|
|
19
|
+
for (const id of options.unsent ?? []) {
|
|
20
|
+
const submission = state.submissions.find((s) => s.id === id);
|
|
21
|
+
if (id === options.host || !state.placed.has(id) || (submission?.kind !== "prompt" && submission?.kind !== "followUp"))
|
|
22
|
+
continue;
|
|
23
|
+
await drive.submit({ id: `withdraw:${id}`, kind: "withdraw", target: id, carry: true, unsent: true });
|
|
24
|
+
}
|
|
25
|
+
// A follow-up's settle names its own prompt (`host`): that one is withdrawn and never carried, and the rest is left
|
|
26
|
+
// as it is (kernel/follow-up.ts). A person's stop withdraws every prompt pending.
|
|
27
|
+
const pending = pendingSubmissions(drive.state()).filter((s) => options.host === undefined || s.id === options.host);
|
|
28
|
+
for (const submission of pending) {
|
|
29
|
+
// A prompt or follow-up the person stopped stays in the conversation: its text is carried into the next one
|
|
30
|
+
// (pendingSubmissions). A stopped steer is dropped, and so is a host's prompt: one that never ran is not sent.
|
|
31
|
+
const carry = submission.kind !== "steer" && submission.id !== options.host;
|
|
32
|
+
await drive.submit({ id: `withdraw:${submission.id}`, kind: "withdraw", target: submission.id, ...(carry ? { carry: true } : {}) });
|
|
33
|
+
}
|
|
16
34
|
const { status, error } = abortedOutcome(AbortSignal.abort(new SessionHalt("interrupted")));
|
|
17
35
|
const journal = new NativeJournal(drive);
|
|
18
36
|
journal.message({ type: "turn", status, ...(error === undefined ? {} : { error }) });
|
package/dist/runner.js
CHANGED
|
@@ -9,6 +9,7 @@ import { randomUUID } from "node:crypto";
|
|
|
9
9
|
import { Compile } from "typebox/compile";
|
|
10
10
|
import { submitParameters } from "@parcha/agentrun-dsl";
|
|
11
11
|
import { HarnessRunError, SessionFenced } from "./errors.js";
|
|
12
|
+
import { bookRequest } from "./booking.js";
|
|
12
13
|
/** The tool the runner injects; a host tool may not take its name. */
|
|
13
14
|
export const SUBMIT_TOOL = "submit";
|
|
14
15
|
/** Why a review rejected a candidate, as the model reads it: its message, or, for none (no message, or a blank one),
|
|
@@ -71,8 +72,10 @@ function bookingFor(writer, options) {
|
|
|
71
72
|
const data = r.data;
|
|
72
73
|
const turn = data.turn ?? inherited.find((t) => !answered.has(t)) ?? 0;
|
|
73
74
|
answered.add(turn);
|
|
74
|
-
//
|
|
75
|
-
|
|
75
|
+
// The figure it was booked at (bookRequest), as written. A record from before that has none: a cost that never came
|
|
76
|
+
// in at the figure its answer was booked at (a stopped request's), else what was held for it.
|
|
77
|
+
const booked = data.bookedUsd === null ? null : heldFigure(data.bookedUsd);
|
|
78
|
+
spentUsd = spent(spentUsd, booked !== undefined ? (booked ?? undefined) : data.usd === null ? (heldFigure(data.heldUsd) ?? held.get(turn)) : (data.usd ?? 0));
|
|
76
79
|
}
|
|
77
80
|
for (const turn of inherited)
|
|
78
81
|
if (!answered.has(turn))
|
|
@@ -176,7 +179,7 @@ function bookingFor(writer, options) {
|
|
|
176
179
|
throw error;
|
|
177
180
|
}
|
|
178
181
|
},
|
|
179
|
-
afterRequest: async (usage, ticket) => {
|
|
182
|
+
afterRequest: async (usage, ticket, ended) => {
|
|
180
183
|
// The turn this request was admitted as (its ticket; without one, the earliest still in flight).
|
|
181
184
|
const turn = ticket?.turn ?? open[0]?.turn ?? turns;
|
|
182
185
|
const at = open.findIndex((f) => f.turn === turn);
|
|
@@ -187,14 +190,23 @@ function bookingFor(writer, options) {
|
|
|
187
190
|
const hold = held.get(turn);
|
|
188
191
|
const stoppedUsd = stoppedAt.get(turn);
|
|
189
192
|
stoppedAt.delete(turn);
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
+
// Its hidden reasoning counts beside all it sent, less the reasoning it sent: max(0, budget - reasoning bytes), so
|
|
194
|
+
// reasoning that streamed is not counted twice and answer text never stands in for it.
|
|
195
|
+
const figure0 = (value) => (typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0);
|
|
196
|
+
const hidden = figure0(usage.stoppedHiddenTokens);
|
|
197
|
+
const reasoned = figure0(usage.stoppedReasoningBytes);
|
|
198
|
+
const sent = typeof usage.stoppedAfterBytes === "number" && usage.stoppedAfterBytes >= 0 ? usage.stoppedAfterBytes : undefined;
|
|
199
|
+
const stopped = usage.usd === null && hold !== undefined && stoppedUsd && sent !== undefined ? heldFigure(stoppedUsd(sent + Math.max(0, hidden - reasoned))) : undefined;
|
|
200
|
+
// How its path saw it end, booked by the one rule (booking.ts); a host from before that says nothing of it: as
|
|
201
|
+
// before, its own cost, else what streamed of a stop, else the hold.
|
|
202
|
+
const booking = ended ? bookRequest(ended, { ...(hold === undefined ? {} : { hold }), ...(stoppedUsd ? { stoppedPrice: stoppedUsd } : {}) }) : undefined;
|
|
203
|
+
const figure = booking ? booking.usd : usage.usd !== null ? usage.usd : stopped === undefined ? hold : Math.min(hold, stopped);
|
|
204
|
+
spentUsd = spent(spentUsd, figure ?? undefined);
|
|
193
205
|
try {
|
|
194
206
|
// A runner.turn with the ids holds what a carried response record of this turn would: that one is dropped. A
|
|
195
207
|
// stopped one keeps the figure it counts at (`heldUsd`), so a later process counts it the same.
|
|
196
208
|
const covers = (r) => usage.providerIds !== undefined && r.data.turn === turn;
|
|
197
|
-
await write([{ kind: RUNNER_RECORDS.turn, data: { turn, usd: usage.usd, ...tokensOf(usage), ...(usage.estimated ? { estimated: true } : {}), ...(usage.tableUsd === undefined ? {} : { tableUsd: usage.tableUsd }), ...(usage.providerIds ? { providerIds: usage.providerIds } : {}), ...(stopped === undefined ? {} : { heldUsd:
|
|
209
|
+
await write([{ kind: RUNNER_RECORDS.turn, data: { turn, usd: usage.usd, ...tokensOf(usage), ...(usage.estimated ? { estimated: true } : {}), ...(usage.tableUsd === undefined ? {} : { tableUsd: usage.tableUsd }), ...(usage.providerIds ? { providerIds: usage.providerIds } : {}), ...(stopped === undefined ? {} : { heldUsd: Math.min(hold, stopped), stopped: true }), ...(booking ? { bookedUsd: booking.usd, rule: booking.rule } : {}) } }], covers);
|
|
198
210
|
}
|
|
199
211
|
catch (error) {
|
|
200
212
|
// A paid request whose cost can't be kept: the attempt stops, saying so, rather than spend on uncounted.
|
package/dist/types.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { WorkflowDeps } from "@parcha/agentrun-dsl";
|
|
2
|
+
import type { Ended } from "./booking.js";
|
|
2
3
|
export type JsonValue = null | boolean | number | string | JsonValue[] | {
|
|
3
4
|
[key: string]: JsonValue;
|
|
4
5
|
};
|
|
@@ -27,6 +28,13 @@ export interface ToolImage {
|
|
|
27
28
|
* takes at most 500,000 here.
|
|
28
29
|
*/
|
|
29
30
|
export declare const HOST_RESULT_MAX_CHARS = 120000;
|
|
31
|
+
/**
|
|
32
|
+
* The error a turn ends with when its provider stopped the answer on its content filter (Anthropic's `refusal` stop, an
|
|
33
|
+
* OpenAI answer `incomplete` for `content_filter`): a harness's model proxy reads the stop in the answer it passes
|
|
34
|
+
* (`ProviderPolicy.filtered`) and the harness halts the turn with this text at once, so its CLI never asks for the refused
|
|
35
|
+
* answer again. A host reads a run's end by it (agentrun-serve's `moderated`).
|
|
36
|
+
*/
|
|
37
|
+
export declare const CONTENT_FILTERED = "content_filter: the model provider stopped this answer";
|
|
30
38
|
/** A tool the host gives a session. */
|
|
31
39
|
export interface HostTool {
|
|
32
40
|
name: string;
|
|
@@ -115,9 +123,15 @@ export interface ModelUsage {
|
|
|
115
123
|
* id such as LiteLLM's `x-litellm-call-id`): what joins this booking to the provider's own log. A cut request has
|
|
116
124
|
* them only if its response had begun. */
|
|
117
125
|
providerIds?: Record<string, string>;
|
|
118
|
-
/** A response its client stopped part way, its cost unknown, with
|
|
119
|
-
*
|
|
126
|
+
/** A response its client stopped part way, its cost unknown, with what of it the client was sent (the model proxy's
|
|
127
|
+
* `stoppedAfterBytes`: its content's UTF-8 bytes where the policy reads it): the host counts it by what streamed
|
|
128
|
+
* (`Admission.stoppedUsd`), never more than its hold. */
|
|
120
129
|
stoppedAfterBytes?: number;
|
|
130
|
+
/** A stopped response's reasoning budget (the proxy's `stoppedHiddenTokens`): the part of it the reasoning it sent
|
|
131
|
+
* did not cover, max(0, budget - `stoppedReasoningBytes`), counts beside `stoppedAfterBytes`, never past the hold. */
|
|
132
|
+
stoppedHiddenTokens?: number;
|
|
133
|
+
/** The bytes of reasoning a stopped response sent (the proxy's `stoppedReasoningBytes`). */
|
|
134
|
+
stoppedReasoningBytes?: number;
|
|
121
135
|
}
|
|
122
136
|
/** The session's model requests, through the runner: every paid request is announced before it is sent, and may be
|
|
123
137
|
* refused there (a turn cap, the host's budget); its usage is reported when it completes. */
|
|
@@ -126,7 +140,9 @@ export interface ModelPort {
|
|
|
126
140
|
beforeRequest(request: ModelRequest): Promise<ModelTicket | void>;
|
|
127
141
|
/** Books a completed request. `ticket` is what its own `beforeRequest` returned: requests may be in flight together, so
|
|
128
142
|
* an answer is booked under the turn it was admitted as, not the latest one. */
|
|
129
|
-
|
|
143
|
+
/** `ended`: how the request ended, as the model proxy saw it (booking.ts), what it is booked by; absent (a host from
|
|
144
|
+
* before it), booked as before, by `usd` and `stoppedAfterBytes`. */
|
|
145
|
+
afterRequest(usage: ModelUsage, ticket?: ModelTicket, ended?: Ended): Promise<void>;
|
|
130
146
|
/** Records the ids a paid request's response gave it, as its headers arrive and before its answer is read. */
|
|
131
147
|
responded?(ids: Record<string, string>, ticket?: ModelTicket): Promise<void>;
|
|
132
148
|
}
|
|
@@ -202,8 +218,11 @@ export interface AdapterSession {
|
|
|
202
218
|
/** Record the open turn as ended, interrupted, and send nothing: the turn is not to be resumed (a person stopped it, and
|
|
203
219
|
* an interrupt writes no end in the session). Only when `state` is `open_turn`; the session is `idle` after, here and
|
|
204
220
|
* when a later process opens it, and the next `send` is a turn of its own. A follow-up closes a cut turn the same way
|
|
205
|
-
* (kernel/follow-up.ts, FollowUpTarget.settleOpenTurn)
|
|
206
|
-
|
|
221
|
+
* (kernel/follow-up.ts, FollowUpTarget.settleOpenTurn), naming its own prompt (`opening`): that one is withdrawn and
|
|
222
|
+
* never carried, and the rest is left as it is. */
|
|
223
|
+
settleOpenTurn(options?: {
|
|
224
|
+
opening?: string;
|
|
225
|
+
}): Promise<void>;
|
|
207
226
|
/** Resolves when the turn in flight ends. */
|
|
208
227
|
turnEnd(): Promise<{
|
|
209
228
|
status: TurnStatus;
|
package/dist/types.js
CHANGED
|
@@ -8,3 +8,10 @@
|
|
|
8
8
|
* takes at most 500,000 here.
|
|
9
9
|
*/
|
|
10
10
|
export const HOST_RESULT_MAX_CHARS = 120_000;
|
|
11
|
+
/**
|
|
12
|
+
* The error a turn ends with when its provider stopped the answer on its content filter (Anthropic's `refusal` stop, an
|
|
13
|
+
* OpenAI answer `incomplete` for `content_filter`): a harness's model proxy reads the stop in the answer it passes
|
|
14
|
+
* (`ProviderPolicy.filtered`) and the harness halts the turn with this text at once, so its CLI never asks for the refused
|
|
15
|
+
* answer again. A host reads a run's end by it (agentrun-serve's `moderated`).
|
|
16
|
+
*/
|
|
17
|
+
export const CONTENT_FILTERED = "content_filter: the model provider stopped this answer";
|
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.30",
|
|
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",
|
|
@@ -56,7 +56,7 @@
|
|
|
56
56
|
"test": "node --test --test-concurrency=8 'test/*.test.mjs'"
|
|
57
57
|
},
|
|
58
58
|
"dependencies": {
|
|
59
|
-
"@parcha/agentrun-dsl": "0.1.0-beta.
|
|
59
|
+
"@parcha/agentrun-dsl": "0.1.0-beta.30",
|
|
60
60
|
"ajv": "8.18.0",
|
|
61
61
|
"typebox": "1.3.7"
|
|
62
62
|
},
|