Files
PaperClipAI/server/src/services/native-runtime/native-provider-failure.ts
T
paperclipbugbotandClaude Opus 5.5 64c872e4da fix(opencode): record model traffic when opencode serve is OOM-killed (#23428)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The native Runner starts `opencode serve` for each OpenCode turn and
sends every model request of OpenCode through a local provider proxy.
> - #23372 and #23391 showed that the kernel OOM killer stops `opencode
serve` at the 8 GiB sandbox limit about 50 seconds into light turns, and
that the memory is OpenCode's own resident set (about 7.6 GiB) and
anonymous memory.
> - The retained run log has no raw provider or SSE trace. So we cannot
tell a huge provider response, a loop of model requests, or growth
inside OpenCode on a normal stream from one another.
> - The provider proxy already sees each model request and its response.
It is the cheapest place to measure this.
> - This pull request counts the model traffic in the proxy and reports
the counts when `opencode serve` dies by a signal.
> - The benefit is that the next OOM kill shows which of the three
causes applies, so the fix can target it.

## Linked Issues or Issue Description

Refs #23372 (kernel OOM evidence). Refs #23391 (memory attribution).

**What happened?**
On a cloud sandbox, native OpenCode turns with a fast DeepSeek model
fail with `opencode_server_exited`. The failure record shows
`memoryKill: observed` and `opencodeRssBytes` of about 8.16 GB at the 8
GiB limit. The run log shows no event for about 46 seconds before the
kill. It does not show how much model traffic OpenCode handled in that
time.

**Expected behavior**
When the kernel stops `opencode serve`, the failure record says how many
model requests OpenCode sent, how many bytes the provider returned, and
how large and how old the response was that was still streaming.

**Steps to reproduce**
1. Run a native OpenCode turn through the Runner provider proxy in a
Linux sandbox with a cgroup v2 memory limit.
2. Make the kernel OOM killer stop `opencode serve` while a model
response streams.
3. Read `resultJson.nativeTurnFailure`. Before this change, it has no
model traffic counts.

**Paperclip version or commit**
`master` at fcb8fc5deb.

## What Changed

- New `provider-traffic.ts`: a meter that counts, for one `opencode
serve` launch, model requests, request bytes, completed responses,
response bytes, and the size and age of responses that still stream. It
keeps only numbers. It records no request or response content.
- `startOpenCodeProviderProxy` starts one meter entry for each forwarded
request. It counts response bytes with a pass-through stream in the
existing response pipeline. A request ends as completed only when its
response pipeline finishes. Any other ending counts as interrupted. The
proxy keeps the largest interrupted response's bytes and duration. When
OpenCode dies while it reads a response, its connection closes and that
response ends first, so this keeps the response it was killed on. A
request that the proxy rejects before it calls the provider is not
counted.
- A signal death of `opencode serve` adds these fields to
`opencodeFailure`: `providerRequests`, `providerResponsesCompleted`,
`providerResponsesInterrupted`, `providerRequestBytes`,
`providerResponseBytes`, `providerInflightResponses`,
`providerInflightResponseBytes`, `providerInflightMs`,
`providerInterruptedResponseBytes` and `providerInterruptedMs`.
- `native-provider-failure.ts` keeps the new fields in its closed
vocabulary. Each must be a safe integer that is zero or more. Other
values are dropped.
- `openCodeServerDriverInternals` also exports
`startOpenCodeProviderProxy` for tests.
- This is a diagnostic. It does not change how a turn fails or recovers,
and it does not change any forwarded bytes.

## Verification

- `cd packages/paperclip-runner && npx vitest run
src/drivers/opencode/provider-traffic.test.ts
src/drivers/opencode/provider-traffic-proxy.test.ts`: 6/6 pass.
- The meter tests check completed and in-flight counts, the largest
in-flight response, the oldest in-flight age, and that late bytes, a
repeated end and bad sizes change nothing.
- A meter test checks that a response which ends before it completes
keeps its size and duration.
- The proxy test sends one finished request and one request whose
response still streams through the real proxy to a local fake provider.
It checks the exact request and response byte counts. Then the client
stops reading, as a killed OpenCode does, and the test checks that the
response is reported as interrupted with its byte count. A second test
checks that a rejected request is not counted.
- `cd packages/paperclip-runner && npx vitest run
src/drivers/opencode/opencode-server-driver.test.ts -t "OpenCode stops
mid-turn|classifies a lost event stream"`: 2/2 pass. The SIGKILL test
now expects zero traffic counts, because its fixture does not call the
model.
- `cd server && npx vitest run
src/services/native-runtime/native-provider-failure.test.ts`: 65/65
pass. A new test checks that the counts pass through and that bad values
are dropped.
- A scoped `tsc --noEmit` of the server file shows no errors. `tsc -p
packages/paperclip-runner/tsconfig.json --noEmit` shows no errors in the
changed files.
- These local runs used an older parent commit with the same versions of
the changed code paths. CI runs the full suites on this branch.

## Risks

- Low risk. The counter is a pass-through `Transform` in the existing
response pipeline. It forwards each chunk unchanged and adds its length
to a number.
- The meter keeps one small entry for each in-flight request and removes
it when the request ends.
- Counts are reported only for a signal death of `opencode serve`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code
execution in an agent sandbox.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 01:19:59 +00:00

442 lines
24 KiB
TypeScript

import type { PrpEvent, PrpTerminalState } from "../../vendor/paperclip-runner/index.js";
import { antigravityModelRefusalMessage, readProviderFailure, type AntigravityAuthRoute, type ProviderFailure } from "@paperclipai/shared";
/** The runner driver's provider code for a model Google refused for the connection. */
const ANTIGRAVITY_MODEL_UNAVAILABLE_CODE = "antigravity_model_unavailable";
// Shared by every provider whose selected model is rejected, so it names no specific connection.
export const NATIVE_MODEL_REJECTION_MESSAGE =
"The selected model is not available through the current AI connection. Choose a supported model or a compatible AI connection.";
export const NATIVE_PROVIDER_OVERLOADED_MESSAGE =
"Selected model is at capacity. Please try a different model.";
export const NATIVE_PROVIDER_OVERLOADED_CODE = "native_provider_overloaded";
export const NATIVE_PROVIDER_CAPACITY_MAX_RETRIES = 2;
export const NATIVE_PROVIDER_OVERLOADED_DIAGNOSTIC = {
provider: "codex",
category: "server_overloaded",
} as const;
export const NATIVE_MODEL_REJECTION_DIAGNOSTIC = {
provider: "codex",
category: "model_auth_incompatible",
status: 400,
authMode: "chatgpt",
} as const;
function record(value: unknown): Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value)
? value as Record<string, unknown>
: {};
}
/** Classify only a committed provider terminal, never model prose or tool output. */
export function nativeProviderUsageLimitFromEvent(
event: Pick<PrpEvent, "sourceKind" | "eventType" | "payload">,
): boolean {
const payload = record(event.payload);
if (event.sourceKind !== "runner" || event.eventType !== "turn.failed" || payload.status !== "failed") return false;
const error = record(payload.error);
if (error.codexErrorInfo === "usageLimitExceeded") return true;
// ACP harnesses type the same exhausted allowance as a provider failure.
// Context, turn and configured budget limits stay ordinary terminals.
const category = readProviderFailure(error.providerFailure)?.category;
return category === "quota_exhausted" || category === "rate_limit";
}
/** An API-key Codex turn whose configured model the Responses API answers with 404. */
export const NATIVE_MODEL_NOT_FOUND_DIAGNOSTIC = {
provider: "codex",
category: "model_not_found",
status: 404,
authMode: "api_key",
} as const;
/** Reconstruct only the closed diagnostic vocabulary, never provider text. */
export function readNativeModelRejectionDiagnostic(value: unknown) {
try {
const entry = record(value);
for (const diagnostic of [NATIVE_MODEL_REJECTION_DIAGNOSTIC, NATIVE_MODEL_NOT_FOUND_DIAGNOSTIC]) {
if (Object.entries(diagnostic).every(([key, expected]) => entry[key] === expected)) return { ...diagnostic };
}
return null;
} catch { return null; }
}
/**
* Codex `CodexErrorInfo` variants. Unit variants arrive as strings; HTTP
* variants arrive as one-key objects that can carry `httpStatusCode`.
*/
const CODEX_ERROR_INFO_KINDS: ReadonlySet<string> = new Set([
"contextWindowExceeded", "usageLimitExceeded", "serverOverloaded", "httpConnectionFailed",
"responseStreamConnectionFailed", "internalServerError", "unauthorized", "badRequest",
"threadRollbackFailed", "sandboxError", "responseStreamDisconnected",
"responseTooManyFailedAttempts", "other",
]);
/**
* `error.code` values the runner itself writes on a failed Codex turn: the
* Codex driver's `failProtocol` callers and runnerd's Codex backend. A provider
* error object can also carry `code`, so any other value is `unrecognized`.
*/
const NATIVE_TURN_FAILURE_RUNNER_CODES: ReadonlySet<string> = new Set([
"thread_binding_mismatch", "turn_binding_mismatch", "turn_start_mismatch", "tool_binding_mismatch",
"runtime_request_binding_mismatch", "runtime_request_duplicate", "runtime_request_recovery_failed",
"notification_transport_failed", "provider_event_type_invalid", "invalid_semantic_result",
"conflicting_semantic_result", "conflicting_turn_terminal", "invalid_spawn_lineage",
"provider_descendant_capacity_exhausted", "provider_terminal_error_missing", "provider_turn_lost_on_restore",
]);
/**
* Closed vocabulary for a failed Codex turn that no classifier above claims.
* It explains generic `Native session failed` reports without provider text.
*/
export interface NativeCodexTurnFailureDiagnostic {
provider: "codex";
category: "turn_failed";
/** A known `CodexErrorInfo` kind, `unrecognized`, or `absent`. */
codexErrorInfo: string;
httpStatus?: number;
/** A known runner-issued failure code, or `unrecognized` for any other code. */
runnerFailureCode?: string;
}
/**
* `error.code` values the OpenCode driver writes when it fails a turn itself.
* Other OpenCode failures carry provider error objects and stay `unrecognized`.
*/
const OPENCODE_TURN_FAILURE_RUNNER_CODES: ReadonlySet<string> = new Set([
"opencode_server_exited", "opencode_event_stream_lost", "provider_terminal_error_missing",
"opencode_empty_response", "opencode_output_limit_reached",
]);
const PROVIDER_FAILURE_CATEGORIES: ReadonlySet<string> = new Set<ProviderFailure["category"]>([
"rate_limit", "quota_exhausted", "authentication", "permission", "model_unavailable", "invalid_request",
"overloaded", "timeout", "unknown",
]);
const PROVIDER_FAILURE_RETRYABILITY: ReadonlySet<string> = new Set<ProviderFailure["retryability"]>([
"transient", "requires_action", "unknown",
]);
const OPENCODE_STREAM_FAILURE_KINDS: ReadonlySet<string> = new Set([
"server_exited", "connection_failed", "http_error", "stream_closed", "stream_error",
]);
const OPENCODE_CONNECTION_ERRORS: ReadonlySet<string> = new Set([
"ECONNREFUSED", "ECONNRESET", "EPIPE", "ETIMEDOUT", "EHOSTUNREACH", "ENETUNREACH",
"UND_ERR_SOCKET", "UND_ERR_CLOSED", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT",
"UND_ERR_BODY_TIMEOUT", "unrecognized",
]);
/** POSIX, Linux and macOS signal names; any other `signal` value is dropped. */
const OPENCODE_EXIT_SIGNALS: ReadonlySet<string> = new Set([
"SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", "SIGTRAP", "SIGABRT", "SIGIOT", "SIGBUS", "SIGEMT", "SIGFPE",
"SIGKILL", "SIGUSR1", "SIGSEGV", "SIGUSR2", "SIGPIPE", "SIGALRM", "SIGTERM", "SIGSTKFLT", "SIGCHLD",
"SIGCONT", "SIGSTOP", "SIGTSTP", "SIGTTIN", "SIGTTOU", "SIGURG", "SIGXCPU", "SIGXFSZ", "SIGVTALRM",
"SIGPROF", "SIGWINCH", "SIGIO", "SIGPOLL", "SIGPWR", "SIGINFO", "SIGLOST", "SIGSYS", "SIGUNUSED",
]);
/** Closed vocabulary for a failed OpenCode turn, including a lost `opencode serve`. */
export interface NativeOpenCodeTurnFailureDiagnostic {
provider: "opencode";
category: "turn_failed";
/** A known runner-issued failure code, or `unrecognized` for any other code. */
runnerFailureCode?: string;
/** How the driver lost its event stream, when it failed the turn itself. */
streamFailure?: string;
exitCode?: number;
signal?: string;
connectionError?: string;
/** Whether the kernel recorded an OOM kill in `opencode serve`'s cgroup, for a signal death. */
memoryKill?: "observed" | "not_observed";
/** The nearest cgroup memory limit over `opencode serve`, and that cgroup's peak use. */
memoryLimitBytes?: number;
memoryPeakBytes?: number;
/** `opencode serve`'s resident set at the last memory sample, and its high-water mark. */
opencodeRssBytes?: number;
opencodePeakRssBytes?: number;
/** The limited cgroup's anonymous, shared and file memory at the last sample. */
cgroupAnonBytes?: number;
cgroupShmemBytes?: number;
cgroupFileBytes?: number;
/** The largest other process at the last sample: a kernel task name and its resident set. */
largestProcessName?: string;
largestProcessRssBytes?: number;
memorySampleAgeMs?: number;
/** Model traffic through Runner's provider proxy since `opencode serve` started, for a signal death. */
providerRequests?: number;
providerResponsesCompleted?: number;
providerResponsesInterrupted?: number;
providerRequestBytes?: number;
providerResponseBytes?: number;
providerInflightResponses?: number;
providerInflightResponseBytes?: number;
providerInflightMs?: number;
providerInterruptedResponseBytes?: number;
providerInterruptedMs?: number;
/** The stream failure's HTTP status, or else the provider error's status. */
httpStatus?: number;
/** The provider error's category and retryability, when the turn carried one. */
providerFailureCategory?: ProviderFailure["category"];
providerFailureRetryability?: ProviderFailure["retryability"];
}
export type NativeTurnFailureDiagnostic = NativeCodexTurnFailureDiagnostic | NativeOpenCodeTurnFailureDiagnostic;
function httpStatusField(value: unknown) {
return typeof value === "number" && Number.isInteger(value) && value >= 100 && value <= 599
? { httpStatus: value } : {};
}
function runnerFailureCodeField(value: unknown, codes: ReadonlySet<string> = NATIVE_TURN_FAILURE_RUNNER_CODES) {
if (typeof value !== "string") return {};
return { runnerFailureCode: codes.has(value) ? value : "unrecognized" };
}
type OpenCodeMemoryCountKey =
| "memoryLimitBytes" | "memoryPeakBytes" | "opencodeRssBytes" | "opencodePeakRssBytes"
| "cgroupAnonBytes" | "cgroupShmemBytes" | "cgroupFileBytes" | "largestProcessRssBytes" | "memorySampleAgeMs"
| "providerRequests" | "providerResponsesCompleted" | "providerRequestBytes" | "providerResponseBytes"
| "providerInflightResponses" | "providerInflightResponseBytes" | "providerInflightMs"
| "providerResponsesInterrupted" | "providerInterruptedResponseBytes" | "providerInterruptedMs";
/** A kernel count: a safe integer, positive for a limit, otherwise zero or more. */
function memoryCountField<K extends OpenCodeMemoryCountKey>(key: K, value: unknown, minimum = 0): { [P in K]?: number } {
return typeof value === "number" && Number.isSafeInteger(value) && value >= minimum
? { [key]: value } as { [P in K]?: number } : {};
}
/** Kernel task names are at most 15 bytes; the driver reports any other name as `other`. */
const OPENCODE_PROCESS_NAME = /^[A-Za-z0-9._+:-]{1,15}$/;
function openCodeMemoryFields(
entry: Record<string, unknown>,
): Pick<NativeOpenCodeTurnFailureDiagnostic, OpenCodeMemoryCountKey | "memoryKill" | "largestProcessName"> {
const { memoryKill, largestProcessName } = entry;
return {
...(memoryKill === "observed" || memoryKill === "not_observed"
? { memoryKill: memoryKill as "observed" | "not_observed" } : {}),
...memoryCountField("memoryLimitBytes", entry.memoryLimitBytes, 1),
...memoryCountField("memoryPeakBytes", entry.memoryPeakBytes, 1),
...memoryCountField("opencodeRssBytes", entry.opencodeRssBytes),
...memoryCountField("opencodePeakRssBytes", entry.opencodePeakRssBytes),
...memoryCountField("cgroupAnonBytes", entry.cgroupAnonBytes),
...memoryCountField("cgroupShmemBytes", entry.cgroupShmemBytes),
...memoryCountField("cgroupFileBytes", entry.cgroupFileBytes),
...(typeof largestProcessName === "string" && OPENCODE_PROCESS_NAME.test(largestProcessName)
? { largestProcessName: largestProcessName as string } : {}),
...memoryCountField("largestProcessRssBytes", entry.largestProcessRssBytes),
...memoryCountField("memorySampleAgeMs", entry.memorySampleAgeMs),
...memoryCountField("providerRequests", entry.providerRequests),
...memoryCountField("providerResponsesCompleted", entry.providerResponsesCompleted),
...memoryCountField("providerRequestBytes", entry.providerRequestBytes),
...memoryCountField("providerResponseBytes", entry.providerResponseBytes),
...memoryCountField("providerInflightResponses", entry.providerInflightResponses),
...memoryCountField("providerInflightResponseBytes", entry.providerInflightResponseBytes),
...memoryCountField("providerInflightMs", entry.providerInflightMs),
...memoryCountField("providerResponsesInterrupted", entry.providerResponsesInterrupted),
...memoryCountField("providerInterruptedResponseBytes", entry.providerInterruptedResponseBytes),
...memoryCountField("providerInterruptedMs", entry.providerInterruptedMs),
};
}
function openCodeStreamFailureFields(value: unknown): Omit<NativeOpenCodeTurnFailureDiagnostic, "provider" | "category" | "runnerFailureCode"> {
const entry = record(value);
const kind = entry.kind ?? entry.streamFailure;
if (typeof kind !== "string" || !OPENCODE_STREAM_FAILURE_KINDS.has(kind)) return {};
const { exitCode, signal, connectionError } = entry;
return {
streamFailure: kind,
...(typeof exitCode === "number" && Number.isInteger(exitCode) && exitCode >= 0 && exitCode <= 255 ? { exitCode } : {}),
...(typeof signal === "string" && OPENCODE_EXIT_SIGNALS.has(signal) ? { signal } : {}),
...(typeof connectionError === "string" && OPENCODE_CONNECTION_ERRORS.has(connectionError) ? { connectionError } : {}),
...openCodeMemoryFields(entry),
...httpStatusField(entry.httpStatus),
};
}
/** Only the provider error's closed fields; its message and code stay out of diagnostics. */
function openCodeProviderFailureFields(
category: unknown, retryability: unknown, httpStatus: unknown,
): Pick<NativeOpenCodeTurnFailureDiagnostic, "providerFailureCategory" | "providerFailureRetryability" | "httpStatus"> {
if (typeof category !== "string" || !PROVIDER_FAILURE_CATEGORIES.has(category)) return {};
return {
providerFailureCategory: category as ProviderFailure["category"],
...(typeof retryability === "string" && PROVIDER_FAILURE_RETRYABILITY.has(retryability)
? { providerFailureRetryability: retryability as ProviderFailure["retryability"] } : {}),
...httpStatusField(httpStatus),
};
}
function openCodeTurnFailure(failure: Record<string, unknown>): NativeOpenCodeTurnFailureDiagnostic {
const providerFailure = readProviderFailure(failure.providerFailure);
return {
provider: "opencode",
category: "turn_failed",
...runnerFailureCodeField(failure.code, OPENCODE_TURN_FAILURE_RUNNER_CODES),
...(providerFailure ? openCodeProviderFailureFields(
providerFailure.category, providerFailure.retryability, providerFailure.httpStatus) : {}),
...openCodeStreamFailureFields(failure.opencodeFailure),
};
}
function codexErrorInfoFields(value: unknown): Pick<NativeCodexTurnFailureDiagnostic, "codexErrorInfo" | "httpStatus"> {
if (value === undefined || value === null) return { codexErrorInfo: "absent" };
if (typeof value === "string") return { codexErrorInfo: CODEX_ERROR_INFO_KINDS.has(value) ? value : "unrecognized" };
const entry = record(value);
const keys = Object.keys(entry);
if (keys.length !== 1 || !CODEX_ERROR_INFO_KINDS.has(keys[0]!)) return { codexErrorInfo: "unrecognized" };
return { codexErrorInfo: keys[0]!, ...httpStatusField(record(entry[keys[0]!]).httpStatusCode) };
}
/** Rebuild a persisted turn-failure diagnostic from its closed vocabulary only. */
export function readNativeTurnFailureDiagnostic(value: unknown): NativeTurnFailureDiagnostic | null {
try {
const entry = record(value);
if (entry.provider === "opencode") {
if (entry.category !== "turn_failed") return null;
return {
provider: "opencode",
category: "turn_failed",
...runnerFailureCodeField(entry.runnerFailureCode, OPENCODE_TURN_FAILURE_RUNNER_CODES),
...openCodeProviderFailureFields(entry.providerFailureCategory, entry.providerFailureRetryability, entry.httpStatus),
...openCodeStreamFailureFields(entry),
};
}
const kind = entry.codexErrorInfo;
if (entry.provider !== "codex" || entry.category !== "turn_failed" || typeof kind !== "string" ||
(kind !== "absent" && kind !== "unrecognized" && !CODEX_ERROR_INFO_KINDS.has(kind))) return null;
return {
provider: "codex",
category: "turn_failed",
codexErrorInfo: kind,
...httpStatusField(entry.httpStatus),
...runnerFailureCodeField(entry.runnerFailureCode),
};
} catch { return null; }
}
const TRANSIENT_PROVIDER_REFUSALS: ReadonlySet<string> = new Set<ProviderFailure["category"]>(["overloaded", "rate_limit"]);
/** An accepted done report outlives a later transient provider refusal in the same turn. */
export function nativeAcceptedResultOutlivesProviderFailure(input: {
terminal: Pick<PrpTerminalState, "turnTerminalState" | "runTerminalState" | "reportedWorkDisposition">;
providerFailure: { errorCode: string } | null;
providerExplanation: ProviderFailure | null;
}): boolean {
if (input.terminal.runTerminalState !== "failed" || input.terminal.turnTerminalState !== "failed" ||
input.terminal.reportedWorkDisposition !== "done") return false;
if (input.providerFailure) return input.providerFailure.errorCode === NATIVE_PROVIDER_OVERLOADED_CODE;
const failure = input.providerExplanation;
return failure !== null && failure.retryability === "transient" && TRANSIENT_PROVIDER_REFUSALS.has(failure.category);
}
/** Observe only events accepted by the bound control-plane persistence port. */
export function createNativeProviderFailureObservation(
provider: { kind: string; model?: string | null; agent?: string },
options: {
/** Google Antigravity's connection route, known only where the run's credentials were resolved. */
antigravityRoute?: AntigravityAuthRoute;
} = {},
) {
const antigravity = provider.kind === "acpx" && provider.agent === "antigravity";
let rejectedTurnId: string | null = null;
/** A Codex API-key turn whose configured model the Responses API does not serve (404). */
let missingModelTurnId: string | null = null;
let overloadedTurnId: string | null = null;
const failedTurns = new Map<string, NativeTurnFailureDiagnostic>();
const providerFailures = new Map<string, ProviderFailure>();
/** A driver-classified, action-required model rejection; `forTerminal` classifies it, so it is not "unclassified". */
const modelUnavailableTurn = (turnId: string) => {
const failure = providerFailures.get(turnId);
return failure?.category === "model_unavailable" && failure.retryability === "requires_action";
};
return {
observe(event: PrpEvent) {
if (event.sourceKind === "runner" && event.eventType === "turn.failed" && event.turnId
&& event.payload.status === "failed") {
const failure = readProviderFailure(record(event.payload.error).providerFailure);
if (failure && !providerFailures.has(event.turnId)) providerFailures.set(event.turnId, failure);
// Antigravity's owned patch types Google's 503 as a transient overload:
// it takes the same bounded capacity retry as Codex's serverOverloaded.
if (antigravity && failure?.category === "overloaded" && failure.retryability === "transient") {
overloadedTurnId = event.turnId;
}
}
if ((provider.kind !== "codex" && provider.kind !== "opencode") ||
event.sourceKind !== "runner" || event.eventType !== "turn.failed" || !event.turnId) return;
const payload = record(event.payload);
const failure = record(payload.error);
if (provider.kind === "opencode") {
// OpenCode has no classifier above, so every failed turn is diagnosed.
if (payload.status === "failed") failedTurns.set(event.turnId, openCodeTurnFailure(failure));
return;
}
if (payload.status === "failed") {
failedTurns.set(event.turnId, {
provider: "codex",
category: "turn_failed",
...codexErrorInfoFields(failure.codexErrorInfo),
...runnerFailureCodeField(failure.code),
});
}
if (payload.status === "failed" && failure.codexErrorInfo === "serverOverloaded") {
overloadedTurnId = event.turnId;
return;
}
if (!provider.model || payload.status !== "failed" || payload.recoverable === true || failure.recoverable === true ||
typeof failure.message !== "string" || failure.message.length > 4_096) return;
// With an API key, Codex retries the Responses API 404 and then fails the turn with this
// terminal text (codex 0.160.0). Bind it to the configured model; store neither name nor text.
const info = record(failure.codexErrorInfo);
const infoKinds = Object.keys(info);
// Its retried 404s arrive as responseStreamDisconnected with willRetry; only the terminal kind counts.
if (infoKinds.length === 1 && infoKinds[0] === "httpConnectionFailed" && record(info.httpConnectionFailed).httpStatusCode === 404 &&
failure.message.startsWith(`unexpected status 404 Not Found: The model \`${provider.model}\` does not exist or you do not have access to it.`)) {
missingModelTurnId = event.turnId;
return;
}
let response: Record<string, unknown>;
try { response = record(JSON.parse(failure.message)); } catch { return; }
const error = record(response.error);
// This is a provider terminal envelope, not text emitted by a tool or an
// agent. Bind the exact rejection to the configured model without storing
// its name or the response. Unknown provider errors retain their behavior.
if (response.type !== "error" || response.status !== 400 || error.type !== "invalid_request_error" ||
error.message !== `The '${provider.model}' model is not supported when using Codex with a ChatGPT account.`) return;
rejectedTurnId = event.turnId;
},
providerFailureForTerminal(turnId: string | null | undefined, terminal: PrpTerminalState) {
if (!turnId || terminal.turnTerminalState !== "failed" || terminal.runTerminalState !== "failed") return null;
return providerFailures.get(turnId) ?? null;
},
forTerminal(turnId: string | null | undefined, terminal: PrpTerminalState) {
if (!turnId || terminal.turnTerminalState !== "failed" || terminal.runTerminalState !== "failed") return null;
if (turnId === overloadedTurnId) return {
errorCode: NATIVE_PROVIDER_OVERLOADED_CODE,
errorMessage: NATIVE_PROVIDER_OVERLOADED_MESSAGE,
diagnostic: antigravity ? { provider: "antigravity", category: "server_overloaded" } : { ...NATIVE_PROVIDER_OVERLOADED_DIAGNOSTIC },
};
// Every model rejection shares one result; only its closed diagnostic differs.
const modelRejection = <T>(diagnostic: T, errorMessage: string = NATIVE_MODEL_REJECTION_MESSAGE) => ({
errorCode: "native_provider_model_rejected" as const, errorMessage, diagnostic,
});
if (turnId === missingModelTurnId) return modelRejection({ ...NATIVE_MODEL_NOT_FOUND_DIAGNOSTIC });
if (turnId === rejectedTurnId) return modelRejection({ ...NATIVE_MODEL_REJECTION_DIAGNOSTIC });
// A driver's closed category marks a rejected model for any provider. Only an
// action-required rejection qualifies; a transient one may succeed on retry.
if (!modelUnavailableTurn(turnId)) return null;
const failure = providerFailures.get(turnId)!;
// Antigravity's typed refusal names the configured model and the fix for
// its connection route. Without the route (a run recovered after a
// restart), the shared message stays accurate.
const message = antigravity && failure.providerCode === ANTIGRAVITY_MODEL_UNAVAILABLE_CODE && provider.model && options.antigravityRoute
? antigravityModelRefusalMessage(provider.model, options.antigravityRoute) : undefined;
return modelRejection(failedTurns.get(turnId) ?? { provider: failure.provider, category: failure.category }, message);
},
/** Diagnostics only: the failed turn that `forTerminal` did not classify. */
unclassifiedTurnFailure(turnId: string | null | undefined, terminal: PrpTerminalState) {
if (!turnId || terminal.turnTerminalState !== "failed" || terminal.runTerminalState !== "failed" ||
turnId === overloadedTurnId || turnId === rejectedTurnId || turnId === missingModelTurnId ||
modelUnavailableTurn(turnId)) return null;
const diagnostic = failedTurns.get(turnId);
return diagnostic ? { ...diagnostic } : null;
},
};
}