@parcha/agentrun-harness-codex 0.1.0-beta.29 → 0.1.0-beta.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,37 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.30 (2026-11-05)
6
+
7
+ - On codex, a content-filter stop whose final Responses event is longer than the model proxy keeps of it now ends the turn
8
+ through a gateway that sends each event as its data alone (LiteLLM sends no `event:` lines). Before, only a stream that
9
+ named its events was read, and Codex asked for the refused answer again until its turn limit. The policy reads the
10
+ event's type from its data, whatever the JSON's spacing.
11
+ - 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.
12
+ - A run whose model provider stops the answer on its content filter now ends `failed` with `error.code` `moderated` and
13
+ says so in plain words: "The model provider stopped this answer (its content filter). Rephrase the request, or try
14
+ another model." Before, it ended `run_failed` with the provider's jargon ("Response incomplete: content_filter"). The
15
+ 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
16
+ claude-agent and codex the session's model proxy reads the provider's stop (Anthropic's `refusal`, an OpenAI answer
17
+ `incomplete` for `content_filter`) and the harness ends the turn at once: the CLI no longer asks for the refused answer
18
+ again, turn after turn. Only the turn's own answer request ends it: a side call the CLI makes beside the turn (one
19
+ without the session's tools) that the provider stops is logged and left to the CLI. The refused request is booked at
20
+ the usage its end reports. The kernel exports `CONTENT_FILTERED`, the text such a turn ends with; a provider policy may
21
+ say a stop through `filtered` and a side call through `answers`, and the model proxy tells its machine through
22
+ `onFiltered`.
23
+ - 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.
24
+ - **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.
25
+ - **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.
26
+ - **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.
27
+ - **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.
28
+ - **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.
29
+ - **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.
30
+ - **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`).
31
+ - **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.
32
+ - 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.
33
+ - **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.
34
+ - **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.
35
+
5
36
  ## 0.1.0-beta.29 (2026-11-04)
6
37
 
7
38
  - **The Codex adapter takes the host's skills, and its sessions no longer see Codex's bundled ones**
package/dist/adapter.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type HostSkill } from "@parcha/agentrun-kernel";
2
2
  import type { AgentAdapter } from "@parcha/agentrun-kernel";
3
+ import { NativeJournal } from "@parcha/agentrun-kernel/process";
3
4
  import { type ConfineChild } from "./host/machine.js";
4
5
  import { type ModelProxyOptions } from "@parcha/agentrun-kernel/host";
5
6
  /**
@@ -56,4 +57,11 @@ export interface CodexAdapterOptions {
56
57
  /** For tests: the fetch the model proxy forwards with. */
57
58
  fetch?: typeof fetch;
58
59
  }
60
+ /**
61
+ * The mirrored rollout the next drive resumes Codex from, by the harness's own rule (harness.ts, `resume`: the last
62
+ * thread, its first line `session_meta`, its path the one the harness derives); none when it would start a new thread.
63
+ * The settle reads only this, so it and the next Codex agree on what Codex has. The copied harness keeps its own copy
64
+ * of the rule: its own patch budget has no room for a call here.
65
+ */
66
+ export declare function resumedRollout(journal: NativeJournal): Promise<string[]>;
59
67
  export declare function codexAdapter(options: CodexAdapterOptions): AgentAdapter;
package/dist/adapter.js CHANGED
@@ -14,12 +14,13 @@ import { join } from "node:path";
14
14
  import { HOST_RESULT_MAX_CHARS, READ_SKILL_FILE, readSkillFileTool, skillProblems, toolSchemaProblems } from "@parcha/agentrun-kernel";
15
15
  import { abortedOutcome, openDrive, SessionHalt } from "@parcha/agentrun-kernel/kernel";
16
16
  import { pendingSubmissions } from "@parcha/agentrun-kernel/kernel";
17
- import { recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
17
+ import { NativeJournal, recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
18
18
  import { CODEX_VERSION } from "./binary.js";
19
19
  import { codexSchemaProblems, describedDescription } from "./schema.js";
20
20
  import { withCheckedBinary } from "./host/sandbox.js";
21
21
  import { verifyCodex } from "./verify.js";
22
- import { codexHarness } from "./harness.js";
22
+ import { codexHarness, owedSubmissions } from "./harness.js";
23
+ import { isRolloutPath, isSessionMeta, rolloutStream, summarizeRollout, THREAD_STREAM } from "./rollout.js";
23
24
  import { localMachine, sessionDir } from "./host/machine.js";
24
25
  import { serialWriter } from "@parcha/agentrun-kernel/host";
25
26
  /** A name app-server accepts for a dynamic tool. */
@@ -73,6 +74,17 @@ const SKILLS_DIR = "skills";
73
74
  function skillsSeed(skills) {
74
75
  return { dir: "codex-home", files: Object.fromEntries(skills.flatMap((skill) => Object.entries(skill.files).map(([path, text]) => [`${SKILLS_DIR}/${skill.name}/${path}`, text]))) };
75
76
  }
77
+ /**
78
+ * The mirrored rollout the next drive resumes Codex from, by the harness's own rule (harness.ts, `resume`: the last
79
+ * thread, its first line `session_meta`, its path the one the harness derives); none when it would start a new thread.
80
+ * The settle reads only this, so it and the next Codex agree on what Codex has. The copied harness keeps its own copy
81
+ * of the rule: its own patch budget has no room for a call here.
82
+ */
83
+ export async function resumedRollout(journal) {
84
+ const thread = journal.records(THREAD_STREAM).at(-1)?.data;
85
+ const restored = thread ? (await journal.read(rolloutStream(thread.threadId))).map((r) => r.data) : [];
86
+ return thread && isSessionMeta(restored[0]) && isRolloutPath(thread.path, thread.threadId) ? restored : [];
87
+ }
76
88
  export function codexAdapter(options) {
77
89
  if (options.webSearch !== undefined && options.webSearch !== "live")
78
90
  throw new TypeError("agentrun-harness-codex: webSearch is \"live\" or absent");
@@ -241,13 +253,20 @@ export function codexAdapter(options) {
241
253
  await ready();
242
254
  void run();
243
255
  },
244
- async settleOpenTurn() {
256
+ async settleOpenTurn(options = {}) {
245
257
  if (state !== "open_turn")
246
258
  throw new Error("agentrun-harness-codex: there is no turn to settle");
247
259
  await ready();
248
260
  // The turn's end in the session's own transcript, as a turn that ends writes it: the next open finds no open turn,
249
- // and the next turn carries no recovery of this one. Nothing is sent.
250
- await settleTurn(drive);
261
+ // and the next turn carries no recovery of this one. Nothing is sent. A prompt the turn placed that Codex never
262
+ // recorded (the stop came before its rollout held it: Codex answers turn/start first) is carried into the next
263
+ // message, as an unplaced one is; a follow-up's own is not. The record is the rollout as the session keeps it (its
264
+ // mirror, which a stopped drive adds nothing to), the rollout the next Codex is resumed from: a prompt it lacks the
265
+ // next turn's model never saw, so carrying it never sends it twice.
266
+ const folded = drive.state();
267
+ const rollout = await resumedRollout(new NativeJournal(drive));
268
+ const unsent = owedSubmissions(folded, recoveryNote(folded)?.turn.placed ?? [], summarizeRollout(rollout).clientIds).map((s) => s.id);
269
+ await settleTurn(drive, { unsent, ...(options.opening === undefined ? {} : { host: options.opening }) });
251
270
  state = "idle";
252
271
  },
253
272
  async turnEnd() {
@@ -1,4 +1,4 @@
1
- import type { AcquireMachine, CacheDir } from "./process.js";
1
+ import type { AcquireMachine, CacheDir, SessionProcess } from "./process.js";
2
2
  import { type ModelProxyHooks, type ModelProxyOptions, type ParentWatch } from "@parcha/agentrun-kernel/host";
3
3
  /** The variables a child takes from this process, when they are set. */
4
4
  export declare const INHERITED_ENV: readonly ["PATH", "LANG", "TZ"];
@@ -54,5 +54,12 @@ export type ConfineChild = (child: Readonly<ChildCommand>) => ChildCommand;
54
54
  export declare function confined(child: ChildCommand, confine: ConfineChild | undefined): ChildCommand;
55
55
  /** The child's environment: the allowlist from `from`, then what the caller names. */
56
56
  export declare function childEnv(from: Readonly<Record<string, string | undefined>>, extra?: Readonly<Record<string, string>>): Record<string, string>;
57
+ /**
58
+ * A child's sends with no `turn/start` once the drive is stopped: no turn starts after a stop. Whether a placed prompt
59
+ * reached Codex is its rollout's to say (the settle reads it as the session keeps it): Codex answers turn/start before it
60
+ * writes the user message, so a stop just after the send can kill it with the prompt unrecorded. Every other line goes
61
+ * unchanged, in order, at once (the stop's own `turn/interrupt` too).
62
+ */
63
+ export declare function withoutTurnsAfterStop<P extends Pick<SessionProcess, "send">>(proc: P, signal: AbortSignal): P;
57
64
  /** A machine factory for sessions under `options.dir`: each acquire makes the directories fresh and starts a proxy. */
58
65
  export declare function localMachine(options: LocalMachineOptions): AcquireMachine;
@@ -139,6 +139,23 @@ function start(options, from, cwd, ceiling, confine, watch) {
139
139
  kill,
140
140
  };
141
141
  }
142
+ /**
143
+ * A child's sends with no `turn/start` once the drive is stopped: no turn starts after a stop. Whether a placed prompt
144
+ * reached Codex is its rollout's to say (the settle reads it as the session keeps it): Codex answers turn/start before it
145
+ * writes the user message, so a stop just after the send can kill it with the prompt unrecorded. Every other line goes
146
+ * unchanged, in order, at once (the stop's own `turn/interrupt` too).
147
+ */
148
+ export function withoutTurnsAfterStop(proc, signal) {
149
+ const send = proc.send.bind(proc);
150
+ return {
151
+ ...proc,
152
+ send(line) {
153
+ if (signal.aborted && line?.method === "turn/start")
154
+ return true;
155
+ return send(line);
156
+ },
157
+ };
158
+ }
142
159
  /** A machine factory for sessions under `options.dir`: each acquire makes the directories fresh and starts a proxy. */
143
160
  export function localMachine(options) {
144
161
  const from = options.env ?? process.env;
@@ -206,6 +223,8 @@ export function localMachine(options) {
206
223
  ...(price ? { price } : {}),
207
224
  ...(options.proxy.log ? { log: options.proxy.log } : {}),
208
225
  ...(options.proxy.fetch ? { fetch: options.proxy.fetch } : {}),
226
+ // The provider stopped the turn's answer on its content filter: no retry of it can pass, so the turn ends at once.
227
+ onFiltered: (message) => ctx.halt?.(new Error(message)),
209
228
  }, key);
210
229
  const lost = new AbortController();
211
230
  const children = new Set();
@@ -224,7 +243,7 @@ export function localMachine(options) {
224
243
  spawn: async (spawnOptions) => {
225
244
  if (closed)
226
245
  throw new Error("agentrun-harness-codex: the session machine is closed");
227
- const proc = start(spawnOptions, from, root, ceiling, options.confine, options.parentWatch);
246
+ const proc = withoutTurnsAfterStop(start(spawnOptions, from, root, ceiling, options.confine, options.parentWatch), ctx.signal);
228
247
  children.add(proc);
229
248
  void proc.exited.then(() => children.delete(proc));
230
249
  return proc;
@@ -30,6 +30,21 @@ export interface CodexPolicyOptions {
30
30
  end(): void;
31
31
  };
32
32
  }
33
+ /**
34
+ * Whether the provider stopped the answer on its content filter: the stream's terminal event (or a whole body) is an
35
+ * `incomplete` response whose `incomplete_details.reason` is `content_filter`. Read by parsing each `data:` line on its
36
+ * own, as endValue reads the usage, never by matching text; an answer cut at its output limit (`max_output_tokens`) is not one.
37
+ *
38
+ * The terminal event carries the whole response (its output, encrypted reasoning included), so its line can be longer
39
+ * than the proxy keeps of an answer; then the proxy's start of that line is read. The response's fields come in a fixed
40
+ * order, `id`, `object`, `created_at`, `status`, `background`, `error`, `incomplete_details`, then `instructions`, the
41
+ * tools and the output (OpenAI's; a LiteLLM gateway's, `id`, `created_at`, `incomplete_details`, ..., `output`, keeps it
42
+ * ahead of the output too), so `incomplete_details` is near the line's start. It is read only on a line that is the event's
43
+ * own: one the SSE `event: response.incomplete` names (OpenAI's API), or whose data says `"type":"response.incomplete"`
44
+ * before its `"response":{` (a gateway that sends each event as its data alone: LiteLLM), as the first
45
+ * `"incomplete_details":{` after `"response":{` (one JSON object), whatever the JSON's spacing.
46
+ */
47
+ export declare function filtered(text: string, lineStarts?: readonly string[]): boolean;
33
48
  /** The usage a Responses answer reports at its end (`endValue`), or undefined, an unknown cost, when it reports none. */
34
49
  export declare function usageOf(text: string): ProxyUsage | undefined;
35
50
  /** The web searches a Responses answer ran, as its terminal event reports them (`tool_usage.web_search.num_requests`,
@@ -55,6 +70,18 @@ export declare function responsesOutputAsked(body: Record<string, unknown>): num
55
70
  /** The least output a Responses body may be limited to and still answer: 1,024 tokens, plus its reasoning effort's
56
71
  * allowance when it reasons. */
57
72
  export declare function responsesOutputLeast(body: Record<string, unknown>): number;
73
+ /** The reasoning tokens a Responses request may bill that its stream never shows (only a summary of its reasoning
74
+ * streams): its effort's budget; none at effort `none`; and with no effort the body says (the model then reasons at its
75
+ * own default, or not at all), its output limit, `fallback` when the body names none: the conservative side. An
76
+ * estimate, as the efforts' budgets are not limits the provider keeps: a stopped request counts the part of it that
77
+ * did not stream (less `responsesReasoningBytes` of what it sent), never past its hold. */
78
+ export declare function responsesReasoningHidden(body: Record<string, unknown>, fallback: number): number;
79
+ /** The bytes of reasoning one Responses stream event carries: a reasoning delta's text, UTF-8; 0 for answer text, a
80
+ * function call's arguments and every other event. */
81
+ export declare function responsesReasoningBytes(event: string): number;
82
+ /** The bytes of content one Responses stream event carries: a content delta's text, UTF-8, never the framing around it
83
+ * (its sequence number, item id, indexes, logprobs, obfuscation); 0 for every other event. */
84
+ export declare function responsesContentBytes(event: string): number;
58
85
  /** A Responses body with its output limited to `max` tokens, reasoning included: never raised, and never longer. */
59
86
  export declare function limitResponsesOutput(body: Record<string, unknown>, max: number): Record<string, unknown>;
60
87
  export declare function codexPolicy(options: CodexPolicyOptions): ProviderPolicy;
@@ -218,6 +218,96 @@ function endValue(text, key) {
218
218
  return undefined;
219
219
  }
220
220
  }
221
+ /**
222
+ * Whether the provider stopped the answer on its content filter: the stream's terminal event (or a whole body) is an
223
+ * `incomplete` response whose `incomplete_details.reason` is `content_filter`. Read by parsing each `data:` line on its
224
+ * own, as endValue reads the usage, never by matching text; an answer cut at its output limit (`max_output_tokens`) is not one.
225
+ *
226
+ * The terminal event carries the whole response (its output, encrypted reasoning included), so its line can be longer
227
+ * than the proxy keeps of an answer; then the proxy's start of that line is read. The response's fields come in a fixed
228
+ * order, `id`, `object`, `created_at`, `status`, `background`, `error`, `incomplete_details`, then `instructions`, the
229
+ * tools and the output (OpenAI's; a LiteLLM gateway's, `id`, `created_at`, `incomplete_details`, ..., `output`, keeps it
230
+ * ahead of the output too), so `incomplete_details` is near the line's start. It is read only on a line that is the event's
231
+ * own: one the SSE `event: response.incomplete` names (OpenAI's API), or whose data says `"type":"response.incomplete"`
232
+ * before its `"response":{` (a gateway that sends each event as its data alone: LiteLLM), as the first
233
+ * `"incomplete_details":{` after `"response":{` (one JSON object), whatever the JSON's spacing.
234
+ */
235
+ export function filtered(text, lineStarts = []) {
236
+ let end = terminalResponse(text.split("\n"), false);
237
+ if (end === undefined) {
238
+ const whole = text.trimStart();
239
+ if (whole.startsWith("{")) {
240
+ try {
241
+ const body = JSON.parse(whole);
242
+ if (isPlain(body) && body.object === "response")
243
+ end = body;
244
+ }
245
+ catch { }
246
+ }
247
+ }
248
+ end ??= terminalResponse(lineStarts, true);
249
+ return isPlain(end) && end.status === "incomplete" && isPlain(end.incomplete_details) && end.incomplete_details.reason === "content_filter";
250
+ }
251
+ /** The response of the last terminal event in `lines` (`filtered`), each `data:` line parsed on its own; with `starts`,
252
+ * the lines are kept starts, and one that is a `response.incomplete` event's (by its name, or its data's type ahead of
253
+ * its response) is read from its start. */
254
+ function terminalResponse(lines, starts) {
255
+ let end;
256
+ let named = false;
257
+ for (const line of lines) {
258
+ if (line.startsWith("event:")) {
259
+ named = line.slice(6).trim() === "response.incomplete";
260
+ continue;
261
+ }
262
+ if (!line.startsWith("data:"))
263
+ continue;
264
+ const data = line.slice(5).trim();
265
+ const incomplete = named || ownIncomplete(data);
266
+ named = false;
267
+ if (!data.startsWith("{"))
268
+ continue;
269
+ try {
270
+ const event = JSON.parse(data);
271
+ if (isPlain(event) && typeof event.type === "string" && PAID_END.has(event.type))
272
+ end = event.response;
273
+ }
274
+ catch {
275
+ // A line the window cut (skipped), or a kept start the event's name says is the stop's.
276
+ if (starts && incomplete)
277
+ end = startOfResponse(data) ?? end;
278
+ }
279
+ }
280
+ return end;
281
+ }
282
+ const RESPONSE_KEY = /"response"\s*:\s*\{/;
283
+ const INCOMPLETE_TYPE = /"type"\s*:\s*"response\.incomplete"/;
284
+ const DETAILS_KEY = /"incomplete_details"\s*:\s*\{/;
285
+ /** Whether a kept start's data is a `response.incomplete` event's own: its `type` says so ahead of its `response` (a
286
+ * quote of it in an answer's text is escaped, so it never reads as one). */
287
+ function ownIncomplete(data) {
288
+ const type = data.search(INCOMPLETE_TYPE);
289
+ const response = data.search(RESPONSE_KEY);
290
+ return type >= 0 && (response < 0 || type < response);
291
+ }
292
+ /** The status and `incomplete_details` of the response a `response.incomplete` event's line starts with (`filtered`), or
293
+ * undefined when the line's kept start does not hold them. */
294
+ function startOfResponse(data) {
295
+ const response = data.search(RESPONSE_KEY);
296
+ if (response < 0)
297
+ return undefined;
298
+ const found = DETAILS_KEY.exec(data.slice(response));
299
+ if (!found)
300
+ return undefined;
301
+ const json = objectAt(data, response + found.index + found[0].length - 1);
302
+ if (json === undefined)
303
+ return undefined;
304
+ try {
305
+ return { status: "incomplete", incomplete_details: JSON.parse(json) };
306
+ }
307
+ catch {
308
+ return undefined;
309
+ }
310
+ }
221
311
  /** The usage a Responses answer reports at its end (`endValue`), or undefined, an unknown cost, when it reports none. */
222
312
  export function usageOf(text) {
223
313
  return usageFrom(endValue(text, "usage"));
@@ -401,6 +491,43 @@ export function responsesOutputLeast(body) {
401
491
  const effort = isPlain(body.reasoning) && typeof body.reasoning.effort === "string" ? body.reasoning.effort : undefined;
402
492
  return ANSWER_TOKENS_LEAST + (effort === undefined ? 0 : REASONING_TOKENS_ALLOWED[effort] ?? 0);
403
493
  }
494
+ /** The reasoning tokens a Responses request may bill that its stream never shows (only a summary of its reasoning
495
+ * streams): its effort's budget; none at effort `none`; and with no effort the body says (the model then reasons at its
496
+ * own default, or not at all), its output limit, `fallback` when the body names none: the conservative side. An
497
+ * estimate, as the efforts' budgets are not limits the provider keeps: a stopped request counts the part of it that
498
+ * did not stream (less `responsesReasoningBytes` of what it sent), never past its hold. */
499
+ export function responsesReasoningHidden(body, fallback) {
500
+ const effort = isPlain(body.reasoning) && typeof body.reasoning.effort === "string" ? body.reasoning.effort : undefined;
501
+ if (effort === "none")
502
+ return 0;
503
+ const budget = effort === undefined ? undefined : REASONING_TOKENS_ALLOWED[effort];
504
+ return budget ?? responsesOutputAsked(body) ?? fallback;
505
+ }
506
+ /** The Responses stream's events whose deltas are reasoning: its summary, and its reasoning text where a model sends it. */
507
+ const REASONING_DELTAS = new Set(["response.reasoning_summary_text.delta", "response.reasoning_text.delta"]);
508
+ /** The bytes of reasoning one Responses stream event carries: a reasoning delta's text, UTF-8; 0 for answer text, a
509
+ * function call's arguments and every other event. */
510
+ export function responsesReasoningBytes(event) {
511
+ const data = event.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
512
+ if (!data.startsWith("{"))
513
+ return 0;
514
+ const parsed = JSON.parse(data);
515
+ return typeof parsed.type === "string" && REASONING_DELTAS.has(parsed.type) && typeof parsed.delta === "string" ? Buffer.byteLength(parsed.delta, "utf8") : 0;
516
+ }
517
+ /** The Responses stream's events whose deltas are content: answer text, reasoning, and a tool call's input. */
518
+ const CONTENT_DELTAS = new Set([
519
+ "response.output_text.delta", "response.reasoning_summary_text.delta", "response.reasoning_text.delta",
520
+ "response.function_call_arguments.delta", "response.custom_tool_call_input.delta",
521
+ ]);
522
+ /** The bytes of content one Responses stream event carries: a content delta's text, UTF-8, never the framing around it
523
+ * (its sequence number, item id, indexes, logprobs, obfuscation); 0 for every other event. */
524
+ export function responsesContentBytes(event) {
525
+ const data = event.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
526
+ if (!data.startsWith("{"))
527
+ return 0;
528
+ const parsed = JSON.parse(data);
529
+ return typeof parsed.type === "string" && CONTENT_DELTAS.has(parsed.type) && typeof parsed.delta === "string" ? Buffer.byteLength(parsed.delta, "utf8") : 0;
530
+ }
404
531
  /** A Responses body with its output limited to `max` tokens, reasoning included: never raised, and never longer. */
405
532
  export function limitResponsesOutput(body, max) {
406
533
  const asked = responsesOutputAsked(body);
@@ -461,6 +588,7 @@ export function codexPolicy(options) {
461
588
  const usage = usageOf(text);
462
589
  return usage && { ...usage, webSearches: webSearchesOf(text) ?? null };
463
590
  } : usageOf,
591
+ filtered,
464
592
  watch: options.announce ? () => watchResponse(options.announce) : undefined,
465
593
  unwatched: options.announce ? () => options.announce.failed() : undefined,
466
594
  modelOf: (body) => (typeof body.model === "string" ? body.model : undefined),
@@ -468,6 +596,9 @@ export function codexPolicy(options) {
468
596
  // stated bound: a body that offers web search has no input bound (undefined), so its input is unmeasured.
469
597
  outputAsked: responsesOutputAsked,
470
598
  outputLeast: responsesOutputLeast,
599
+ reasoningHidden: (body) => responsesReasoningHidden(body, maxOutputTokens),
600
+ reasoningBytesOf: responsesReasoningBytes,
601
+ contentBytesOf: responsesContentBytes,
471
602
  limitOutput: limitResponsesOutput,
472
603
  serverInputOverhead: search ? (body) => {
473
604
  if (Array.isArray(body.tools) && body.tools.some((tool) => isPlain(tool) && tool.type === "web_search"))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-harness-codex",
3
- "version": "0.1.0-beta.29",
3
+ "version": "0.1.0-beta.31",
4
4
  "description": "Codex as an AgentRun harness: a tool-less Codex app-server behind a loopback model proxy, durable in AgentRun's own store, with the host's tools as its only tools.",
5
5
  "keywords": [
6
6
  "agentrun",
@@ -40,8 +40,8 @@
40
40
  "test": "node --test --test-concurrency=8 'test/*.test.mjs'"
41
41
  },
42
42
  "dependencies": {
43
- "@parcha/agentrun-dsl": "0.1.0-beta.29",
44
- "@parcha/agentrun-kernel": "0.1.0-beta.29"
43
+ "@parcha/agentrun-dsl": "0.1.0-beta.31",
44
+ "@parcha/agentrun-kernel": "0.1.0-beta.31"
45
45
  },
46
46
  "peerDependencies": {
47
47
  "@openai/codex": "0.164.0"