From e03c7c798e377c7ae514f5c323bf5de05faea845 Mon Sep 17 00:00:00 2001 From: Souleymane Sidibe <936370+soulesidibe@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:07:10 +0000 Subject: [PATCH] bl-240: omit error data from the echo of JSON-RPC error responses in the acp and codex-app-server runners --- docs/plugins/runner-acp.md | 4 +- docs/plugins/runner-codex-app-server.md | 2 +- docs/spec-decisions.md | 15 +++++- .../main/kotlin/loop/runner/acp/AcpFraming.kt | 33 ++++++++++++ .../main/kotlin/loop/runner/acp/AcpRunner.kt | 17 +++++-- .../kotlin/loop/runner/acp/AcpFramingTest.kt | 42 ++++++++++++++++ .../loop/runner/acp/AcpQuotaResetTest.kt | 50 ++++++++++++++++++- .../loop/runner/codex/CodexAppServerRunner.kt | 23 ++++++--- .../loop/runner/codex/ProtocolFraming.kt | 37 ++++++++++++++ .../runner/codex/CodexAppServerRunnerTest.kt | 34 +++++++++++++ .../loop/runner/codex/ProtocolFramingTest.kt | 27 ++++++++++ 11 files changed, 270 insertions(+), 14 deletions(-) diff --git a/docs/plugins/runner-acp.md b/docs/plugins/runner-acp.md index bc245363..7c9a16df 100644 --- a/docs/plugins/runner-acp.md +++ b/docs/plugins/runner-acp.md @@ -72,7 +72,7 @@ Loop checks `runners.acp` against the profile and `AcpRunnerProvider.validate` o - **Launch:** argv words run in the workspace working directory inside an isolated process group (`ProcessGroupLauncher`) with no shell. Under `preset: agy`, Loop sweeps stale isolated folders and appends `--disable-telemetry`, `--sandbox`, and `--gemini-dir ` pointing to an isolated folder containing `antigravity-cli/settings.json` (`{"toolPermission": "strict", "allowNonWorkspaceAccess": false}`). The folder is `$LOOP_HOME/agy/-` when `LOOP_HOME` lies under `$HOME`, else `$HOME/.loop-agy/-`, never in the attempt folder, which Loop deletes when the attempt ends. See [Isolated folder lifetime](#isolated-folder-lifetime). Loop never passes `--dangerously-skip-permissions`, `--effort`, `--remote-agent`, or `--remote-control`. - **Loop MCP server:** when the attempt environment provides `LOOP_LAUNCHER` and `LOOP_TOOL_CONFIG`, `session/new` and `session/load` pass Loop's stdio MCP server (`name: "loop"`, `command: `, `args: ["tool", "mcp"]`) with only the 8 Loop environment variables (`LOOP_TOOL_CONFIG`, `LOOP_ATTEMPT_ID`, `LOOP_ISSUE_ID`, `LOOP_ISSUE_IDENTIFIER`, `LOOP_TRACKER_ID`, `LOOP_HOME`, `LOOP_SESSION_ID`, `LOOP_TURN_ID`). `LOOP_SESSION_ID` and `LOOP_TURN_ID` stay fixed at the values of the turn that opened the session. A respawn or a resume under `preset: agy` passes the `mcpServers` again in `session/load`. -- **Stdout:** newline delimited JSON-RPC 2.0 messages, bounded to 10 MB per line (`ProcessGroupLauncher.MAX_LINE_BYTES`). Malformed lines are logged on stderr with a fixed reason (never quoting the line) and skipped. +- **Stdout:** newline delimited JSON-RPC 2.0 messages, bounded to 10 MB per line (`ProcessGroupLauncher.MAX_LINE_BYTES`). Malformed lines are logged on stderr with a fixed reason (never quoting the line) and skipped. Each line is kept as runner output as read, except an error response, echoed with its `jsonrpc`, `id`, `code` and `message` and a `[error data omitted, N chars]` marker in place of its data, which can hold account fields (bl-240). The runner still reads the whole error. - **Stderr:** kept apart from the protocol stream as diagnostic output. - **Stop:** closing a session closes stdin and waits up to 5 seconds (`STOP_GRACE`) for the process to exit. When the grace expires, Loop kills the process group and reports `stop_grace_expired` through `AgentSession.stop(report)`. Under `preset: agy`, the isolated `--gemini-dir` folder of a session that reported its runtime session id is kept after the process exits, since it holds `agy`'s session store, and the folders earlier sessions of the same issue kept are removed; any other folder, and the folder of a session a guard ended, is removed (logging any removal failure). @@ -141,7 +141,7 @@ Loop ships default context windows of `1048576` tokens in `ContextConfig.DEFAULT - **Hard-limit interrupt:** `AgentSession.interrupt()` sends a `session/cancel` notification, answers any pending `session/request_permission` with `cancelled`, preserves `result.usage` on `stopReason: "cancelled"`, and ends the turn cleanly so Loop rotates onto a fresh session. - **Error mapping:** structured JSON-RPC errors reporting authentication or eligibility failure (401, 403, expired login, `IneligibleTierError`), rate limit or overload (429, 503, 529), model refusal (`-32602 Unknown model ID` or `modelNotFound`), or runtime-reported network transport failure with no HTTP status map to `runner_unavailable`, as does an `agy` of another major or older than the minimum at `initialize` under `preset: agy`. All other errors, exits, and malformed lines are ordinary failures. A Google error object anywhere in the error data, nested in a string field included, maps to `runner_unavailable` when its `status` is `RESOURCE_EXHAUSTED` or an `ErrorInfo` `reason` is `QUOTA_EXHAUSTED`. The quota message text alone is free text and maps nothing. - **Retry time and quota reset (bl-215):** a `runner_unavailable` with a status or a rate limit code sets `retryAfter`, which the run level hold uses as its period when it is longer than the backoff, so one probe runs at the reset instead of one every 1 to 15 minutes. An explicit `retryAfterMs`, `retry_after_ms`, `retryAfterSeconds`, `retry_after_seconds`, `retryAfter` or `retry_after` key of the error data comes first. Else the wait is the first valid positive value of, in order: `quotaResetTimeStamp` (RFC 3339) minus now, `quotaResetDelay`, a `RetryInfo` `retryDelay`, each searched at any depth of the error data, a JSON body inside a string field included, then `Your quota will reset after ` in the error message or a string of the data. Durations use Google's format (`4h23m27.716645894s`, `27s`, `850ms`). A past timestamp or an unparsable value is skipped, never a failure, and nothing found leaves `retryAfter` empty as before. -- **`rate_limit` event:** with a quota reset found, the turn emits `rate_limit` before `turn_failed`, with `limit_id` `gemini`, the error's `metadata.model` as `limit_name` (else `runners.acp.model`), and `reached` `quota_exhausted`. It carries no window, since a window needs a used percent that `agy` never reports, so the reset time is in the `turn_failed` reason instead: `turn_failed: (code ); the quota resets at `. `loop trace` prints it as `rate_limit limit=gemini name= reached=quota_exhausted`. Only the reset time and a plain model id are read from the error: no account id, email or token reaches the event or the reason. The JSON-RPC line itself is still echoed as runner output, like every protocol line. The decisions are in [The acp runner holds until an exhausted Gemini quota resets](../spec-decisions.md#the-acp-runner-holds-until-an-exhausted-gemini-quota-resets-extension-bl-215). +- **`rate_limit` event:** with a quota reset found, the turn emits `rate_limit` before `turn_failed`, with `limit_id` `gemini`, the error's `metadata.model` as `limit_name` (else `runners.acp.model`), and `reached` `quota_exhausted`. It carries no window, since a window needs a used percent that `agy` never reports, so the reset time is in the `turn_failed` reason instead: `turn_failed: (code ); the quota resets at `. `loop trace` prints it as `rate_limit limit=gemini name= reached=quota_exhausted`. Only the reset time and a plain model id are read from the error: no account id, email or token reaches the event or the reason. The JSON-RPC line is echoed as runner output without its error data (bl-240), see [error responses in runner output](../spec-decisions.md#error-responses-in-runner-output-extension-bl-240). The decisions are in [The acp runner holds until an exhausted Gemini quota resets](../spec-decisions.md#the-acp-runner-holds-until-an-exhausted-gemini-quota-resets-extension-bl-215). - **Startup preflight (`preset: agy`):** verifies the `agy` binary is reachable, on pinned major version `1` and no older than `1.5.18`, reading the version from the line of `agy --version` that is only a version, else its last version token, so a banner such as `new version 1.6.0 available` printed before it never decides it (errors stop startup; 1.5.18 is the first version that applies permission prompts to files read or edited through `file:///` URIs, which the guards above rely on), and runs `agy models` to warn on login problems, offline failures, or a configured model not listed. ## Capabilities diff --git a/docs/plugins/runner-codex-app-server.md b/docs/plugins/runner-codex-app-server.md index 8287929a..b8adf730 100644 --- a/docs/plugins/runner-codex-app-server.md +++ b/docs/plugins/runner-codex-app-server.md @@ -78,7 +78,7 @@ The merge risk reviewer follows the model of `kinds.code.delivery.risk.reviewer` - **Launch:** the words of `command` as the argv, with the workspace as its working directory, in its own process group, with the agent env of the shared policy (`agent.env` added, removed names taken out). Cancelling the attempt kills the group. No shell runs it, unlike the spec's `bash -lc`: a login shell reads the user's profile after the env policy built the env, and a profile export would bring back a name the policy removed, such as `GH_TOKEN` or `LOOP_HOLDOUT` (m3-20). - **The agent's commands:** every `thread/start` sets `allow_login_shell` to false in its `config`, so Codex runs each command of the agent with `zsh -c` or `bash -c`, not `-lc`, and the same profile export does not reach them either. A command the model asks to run in a login shell is refused by Codex. Not covered: `zsh` reads `~/.zshenv` for every shell, login or not, so an export there still reaches the agent's commands when the user's shell is zsh. -- **Stdout** is the protocol stream: one JSON object per line, the framing of the pinned app server. Each line is kept as output. A line split across reads is read whole once its line break arrives. A line that is not a protocol message is logged as `loop: an app server stdout line is not a protocol message (), skipped`, the reason a fixed phrase such as `not JSON`, never the line, and reading goes on. A line longer than 10 MB, the max line size of spec 10.1, is dropped by the launcher, never held whole in memory, and a `loop: a stdout line of bytes was dropped, longer than the maximum of 10485760 bytes` line on stderr takes its place (bl-128). +- **Stdout** is the protocol stream: one JSON object per line, the framing of the pinned app server. Each line is kept as output as read, except an error response, echoed with its `id`, `code` and `message` and a `[error data omitted, N chars]` marker in place of its data (bl-240), see [error responses in runner output](../spec-decisions.md#error-responses-in-runner-output-extension-bl-240). A line split across reads is read whole once its line break arrives. A line that is not a protocol message is logged as `loop: an app server stdout line is not a protocol message (), skipped`, the reason a fixed phrase such as `not JSON`, never the line, and reading goes on. A line longer than 10 MB, the max line size of spec 10.1, is dropped by the launcher, never held whole in memory, and a `loop: a stdout line of bytes was dropped, longer than the maximum of 10485760 bytes` line on stderr takes its place (bl-128). - **Stderr** is kept apart, as diagnostics: each line is kept as stderr output and never read as protocol. - **Stdin** carries the client's messages, one JSON object per line. It stays open across the turns of a session and is closed when the session stops. - **Failures:** `invalid_workspace_cwd` (the workspace is not a directory, nothing starts), `agent_not_found` (the process cannot be spawned, or the launcher exits 127 because it could not run the command, before any stdout line), `response_error` (the start or a `turn/start` failed, see below), `response_timeout` and `turn_timeout` (see [timeouts](#turns-timeouts-and-continuation)), `turn_failed` and `turn_cancelled` (the turn's own end), `port_exit: exit code N, before the response` (the server exited while a request waited for its answer), `port_exit: exit code N, no turn result` (it exited during the turn) and `port_exit: the app server of this session is gone, turn N cannot start on thread `. diff --git a/docs/spec-decisions.md b/docs/spec-decisions.md index 4f53e2df..5b68e197 100644 --- a/docs/spec-decisions.md +++ b/docs/spec-decisions.md @@ -3143,10 +3143,23 @@ A `runner_unavailable` from an exhausted Gemini quota carried no retry key Loop - **Classified on structured fields.** A Google error object anywhere in the error data, a JSON body inside a string field included, maps to `runner_unavailable` when its `status` is `RESOURCE_EXHAUSTED` or an `ErrorInfo` reason is `QUOTA_EXHAUSTED`. The quota message alone is free text and classifies nothing, as since `m4-08`. - **Wait.** An explicit retry key of the error data comes first, as before. Else the first valid positive value of `quotaResetTimeStamp` minus now, `quotaResetDelay`, `retryDelay` (any depth), then the message text, becomes `TurnFailed.retryAfter`, in Google's duration format. A past timestamp or an unparsable value is skipped. `RunnerHold` is unchanged: it already takes a `retryAfter` longer than its backoff as the period, so one probe runs at the reset. - **Telemetry.** The turn emits the `rate_limit` event of the Codex runner with `limit_id` `gemini`, the model as `limit_name` and `reached` `quota_exhausted`. `RunnerEvent.RateLimit.Window` needs a used percent that `agy` never reports, so the event carries no window and the reset instant goes in the `turn_failed` reason, `...; the quota resets at `, rather than a `plugin-api` change. -- **Redaction.** Only the reset time and a plain model id are read from the error, so no account id, email or token reaches the event or the reason. The raw JSON-RPC line is still echoed as runner output, like every protocol line. +- **Redaction.** Only the reset time and a plain model id are read from the error, so no account id, email or token reaches the event or the reason. The JSON-RPC line is echoed as runner output without its error data since [bl-240](#error-responses-in-runner-output-extension-bl-240). Tests: `plugins/runner-acp/src/test/kotlin/loop/runner/acp/AcpQuotaResetTest.kt` (from the logged 429 body: details in the error data, the body nested in a string, an array body in a string, the message text only, a past timestamp, an unparsable value, no reset at all, an explicit retry key first, the duration format, and through the fake server the `rate_limit` event and `retryAfter` of a prompt error), `spec-core/src/test/kotlin/loop/core/orchestrator/RunnerHoldTest.kt` (`bl-215 an exhausted Gemini quota holds until its reset time, not the 1 minute backoff`). +### Error responses in runner output (extension, bl-240) + +The acp and codex-app-server runners echoed every stdout line as runner output before decoding it, and the orchestrator's `SecretRedactor` knows only learned env secrets and token patterns. So the `data` of a JSON-RPC error response, such as the Google body of an exhausted Gemini quota with its `consumer` account id and an email, reached the event store, the attempt record file, `loop show` and the run observer. The decisions (`AcpFraming.echo` in `plugins/runner-acp`, `ProtocolFraming.echo` in `plugins/runner-codex-app-server`): + +- **Rule.** A stdout line that decodes as an error response is echoed as its `jsonrpc` and `id` members (each only when the line has it), its `code` and `message`, and `"data":"[error data omitted, N chars]"`, N the length of the omitted values as compact JSON. Omitted means the error's `data` and any other member of the error besides `code` and `message`, and any member of the envelope besides `jsonrpc`, `id` and `error`, since a provider body can sit there too. An error with nothing else, or only null members, is echoed as read. +- **The frame keeps the data.** Only the echo is rewritten: the decoded frame the runner reads keeps the whole error, so bl-215's `rate_limit` event, `retryAfter` and `turn_failed` reason are read as before. The `turn_failed` reason already names only the code and the message. +- **Every other line is echoed as read,** byte for byte: requests, notifications, success responses, a line that is not a protocol message and every stderr line. A line drained after a kill follows the same rule. +- **One function per runner.** The two runners share only `plugins/runner-process`, which has no JSON dependency, so each framing has its own small `echo` with the same rule rather than a JSON dependency on the process launcher. +- **Not the claude-code runner.** Claude Code's stream-json carries no JSON-RPC frames. A failed API call is a `result` line with `is_error` whose `result` text quotes the Anthropic error body, `{"type":"error","error":{"type":...,"message":...}}`, and its `rate_limit_event` lines carry windows, statuses and reset times: neither has an account id or an email field, so its lines stay echoed as read and it has no test of its own. A runner whose provider bodies gain account fields takes the same rule. +- **Not the redactor.** A general email or account id pattern in `SecretRedactor` would touch every writer, git output included, so the runners leave the data out instead. + +Tests: `plugins/runner-acp/src/test/kotlin/loop/runner/acp/AcpFramingTest.kt` and `plugins/runner-codex-app-server/src/test/kotlin/loop/runner/codex/ProtocolFramingTest.kt` (the `bl-240` tests: the data and the extra members omitted, every other line echoed byte for byte), `AcpQuotaResetTest.kt` (`bl-240 the echo of the quota error omits its data, the frame still gives rate_limit and the reason`), `CodexAppServerRunnerTest.kt` (`bl-240 the echo of an error answer omits its data, other lines are echoed as read`). + ### Claude Code rate limits (extension, bl-209) Conformance 17.5 item 13 asks a runner to extract rate limit telemetry; the Codex runner did since [m3-21](#codex-runner-usage-rate-limits-and-cost-m3-21), the Claude Code runner dropped its rate limit lines. Claude Code writes `{"type":"rate_limit_event","rate_limit_info":{...}}` lines in its stream: a `status` (`allowed`, `allowed_warning`, `rejected`), the `rateLimitType` and `resetsAt` of the window that status is about, the overage fields, and `unifiedWindows`, each window by name with its `utilization` (0 to 1), `resetsAt` (Unix seconds) and `status`. The recorded lines of `real_two_turns_one_process.jsonl` and `wake_turns_10c2f759.jsonl` name only `seven_day`. The decisions (`ClaudeRateLimits` in `plugins/runner-claude-code`): diff --git a/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpFraming.kt b/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpFraming.kt index 909596a7..c71fd599 100644 --- a/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpFraming.kt +++ b/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpFraming.kt @@ -144,6 +144,36 @@ object AcpFraming { return AcpFrame.Malformed(line, "not a JSON-RPC message") } + /** + * The text runner output echoes for the stdout line of [frame] (bl-240). An error response's `data`, and any member + * besides `code` and `message` in its error or besides `jsonrpc`, `id` and `error` in its envelope, can hold a + * provider's error body with account fields, so it is echoed as `jsonrpc` and `id` (as the line had them), `code`, + * `message` and a `data` marker, `[error data omitted, N chars]`, N the length of the omitted values as compact JSON. + * Every other line, an undecodable one included, is echoed as read. The frame itself keeps the data. + */ + fun echo(frame: AcpFrame): String { + if (frame !is AcpFrame.Error) return frame.line + val envelope = json.parseToJsonElement(frame.line) as JsonObject + val error = envelope.getValue("error") as JsonObject + // A null member carries nothing to omit. + val omitted = + (envelope.filterKeys { it !in ENVELOPE_KEPT }.values + error.filterKeys { it !in ERROR_KEPT }.values) + .filterNot { it is JsonNull } + if (omitted.isEmpty()) return frame.line + return buildJsonObject { + envelope["jsonrpc"]?.let { put("jsonrpc", it) } + envelope["id"]?.let { put("id", it) } + put( + "error", + buildJsonObject { + put("code", error.getValue("code")) + put("message", error.getValue("message")) + put("data", "[error data omitted, ${omitted.sumOf { it.toString().length }} chars]") + }, + ) + }.toString() + } + /** Encodes a JSON-RPC 2.0 request line, terminated with `\n`. */ fun request( id: Long, @@ -197,6 +227,9 @@ object AcpFraming { ) }.toString() + "\n" + private val ENVELOPE_KEPT = setOf("jsonrpc", "id", "error") + private val ERROR_KEPT = setOf("code", "message") + private fun isValidId(id: JsonElement): Boolean { val primitive = id as? JsonPrimitive ?: return false return primitive.isString || primitive.longOrNull != null diff --git a/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpRunner.kt b/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpRunner.kt index db0c0e1b..a73cbd14 100644 --- a/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpRunner.kt +++ b/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpRunner.kt @@ -594,10 +594,14 @@ class AcpRunner internal constructor( return fail(event.exitCode, reason) } is ProcessEvent.Line -> { - out(RunnerEvent.Output(event.stream, event.text)) - if (event.stream != Stream.Stdout) continue + if (event.stream != Stream.Stdout) { + out(RunnerEvent.Output(event.stream, event.text)) + continue + } process.stdoutLines++ val frame = decodeFrame(event.text) + // bl-240: an error response's data stays in the frame, out of the echo. + out(RunnerEvent.Output(event.stream, AcpFraming.echo(frame))) if (frame is AcpFrame.Malformed) { out(malformed(frame)) continue @@ -842,7 +846,7 @@ class AcpRunner internal constructor( kill(process) while (true) { val queued = process.events.tryReceive().getOrNull() ?: break - if (queued is ProcessEvent.Line) out(RunnerEvent.Output(queued.stream, queued.text)) + if (queued is ProcessEvent.Line) out(echoed(queued)) } } } @@ -850,6 +854,13 @@ class AcpRunner internal constructor( private fun decodeFrame(line: String): AcpFrame = AcpFraming.decode(line).also(onFrame) + /** The runner output of a [line] drained after the kill, a stdout line echoed as [AcpFraming.echo] gives it (bl-240). */ + private fun echoed(line: ProcessEvent.Line): RunnerEvent.Output = + RunnerEvent.Output( + line.stream, + if (line.stream == Stream.Stdout) AcpFraming.echo(AcpFraming.decode(line.text)) else line.text, + ) + private fun malformed(frame: AcpFrame.Malformed): RunnerEvent.Output = loopNote("an ACP server stdout line is not a protocol message (${frame.reason}), skipped") diff --git a/plugins/runner-acp/src/test/kotlin/loop/runner/acp/AcpFramingTest.kt b/plugins/runner-acp/src/test/kotlin/loop/runner/acp/AcpFramingTest.kt index 0b8b5ebf..23ced307 100644 --- a/plugins/runner-acp/src/test/kotlin/loop/runner/acp/AcpFramingTest.kt +++ b/plugins/runner-acp/src/test/kotlin/loop/runner/acp/AcpFramingTest.kt @@ -87,4 +87,46 @@ class AcpFramingTest { assertEquals(-32601L, decodedErr.code) assertEquals("method not found", decodedErr.message) } + + @Test + fun `bl-240 the echo of an error response omits its data and keeps jsonrpc, id, code and message`() { + val data = """{"metadata":{"email":"someone@example.com","consumer":"projects/735190462281"}}""" + val line = """{"jsonrpc":"2.0","id":4,"error":{"code":-32000,"message":"Resource exhausted","data":$data}}""" + + val echo = AcpFraming.echo(AcpFraming.decode(line)) + + assertEquals( + """{"jsonrpc":"2.0","id":4,"error":{"code":-32000,"message":"Resource exhausted","data":"[error data omitted, ${data.length} chars]"}}""", + echo, + ) + } + + @Test + fun `bl-240 members of an error response besides code and message are omitted too`() { + val line = + """{"jsonrpc":"2.0","id":null,"account":"735190462281","error":{"code":429,"message":"quota","status":"someone@example.com"}}""" + + val echo = AcpFraming.echo(AcpFraming.decode(line)) + + assertEquals( + """{"jsonrpc":"2.0","id":null,"error":{"code":429,"message":"quota","data":"[error data omitted, 35 chars]"}}""", + echo, + ) + } + + @Test + fun `bl-240 every other line is echoed as read, byte for byte`() { + val lines = + listOf( + """{ "jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "s1"} }""", + """{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1}}""", + """{"jsonrpc":"2.0","id":2, "error":{"code":-32601,"message":"method not found"}}""", + """{"jsonrpc":"2.0","id":3,"error":{"code":-32000,"message":"no data","data":null}}""", + """not json {"error":{"data":"someone@example.com"}}""", + """{"jsonrpc":"2.0","id":5,"error":{"code":"bad","message":"x","data":{"email":"e"}}}""", + "", + ) + + lines.forEach { line -> assertEquals(line, AcpFraming.echo(AcpFraming.decode(line))) } + } } diff --git a/plugins/runner-acp/src/test/kotlin/loop/runner/acp/AcpQuotaResetTest.kt b/plugins/runner-acp/src/test/kotlin/loop/runner/acp/AcpQuotaResetTest.kt index e6893b58..41e7fc2b 100644 --- a/plugins/runner-acp/src/test/kotlin/loop/runner/acp/AcpQuotaResetTest.kt +++ b/plugins/runner-acp/src/test/kotlin/loop/runner/acp/AcpQuotaResetTest.kt @@ -251,13 +251,61 @@ class AcpQuotaResetTest { assertNull(rateLimit.secondary) assertEquals(failed.turnId, rateLimit.turnId) assertTrue(events.indexOf(rateLimit) < events.indexOf(failed)) - // The raw protocol line echo is runner output as for every frame; what the quota adds names no account. + // What the quota adds names no account; the echo of the line is bl-240's test below. listOf(rateLimit, failed).forEach { event -> val text = event.toString() assertFalse(EMAIL in text || ACCOUNT_ID in text, text) } } + @Test + fun `bl-240 the echo of the quota error omits its data, the frame still gives rate_limit and the reason`() { + val errorLine = + buildJsonObject { + put("jsonrpc", "2.0") + put("id", 4) + put( + "error", + buildJsonObject { + put("code", -32000) + put("message", "Resource exhausted") + put("data", parse(logged429(model = null))) + }, + ) + }.toString() + val notification = """{ "jsonrpc": "2.0", "method": "loop/unknown", "params": {"note": "kept as read"} }""" + val undecodable = """not json {"error":{"data":"kept as read"}}""" + val server = + FakeAcpServer.write(dir) { + initialize(id = 1) + sessionNew(id = 2, sessionId = "s-quota") + sessionSetModel(id = 3, configUpdateModelId = FakeAcpServer.DEFAULT_MODEL, sessionId = "s-quota") + awaitClient() + raw(notification) + raw(undecodable) + raw(errorLine) + } + + val events = runBlocking { withTimeout(20.seconds) { agyRunner(server).run(context(), "Work").toList() } } + + val outputs = events.filterIsInstance() + outputs.forEach { output -> assertFalse(EMAIL in output.line || ACCOUNT_ID in output.line, output.line) } + val echoed = outputs.single { "Resource exhausted" in it.line } + assertEquals(RunnerEvent.Output.Stream.Stdout, echoed.stream) + assertTrue("\"code\":-32000" in echoed.line, echoed.line) + assertTrue("[error data omitted, " in echoed.line, echoed.line) + assertTrue(outputs.any { it.stream == RunnerEvent.Output.Stream.Stdout && it.line == notification }) + assertTrue(outputs.any { it.stream == RunnerEvent.Output.Stream.Stdout && it.line == undecodable }) + // The decoded frame keeps the data, so bl-215's telemetry reads the reset and the model as before. + val failed = assertIs(events.last()) + assertEquals(RunnerEvent.TurnFailed.Category.RunnerUnavailable, failed.category) + assertEquals(RESET_DELAY, failed.retryAfter) + assertTrue("the quota resets at $RESET_AT" in failed.reason, failed.reason) + val rateLimit = events.filterIsInstance().single() + assertEquals("gemini", rateLimit.limitId) + assertEquals("quota_exhausted", rateLimit.reached) + } + @Test fun `a rate limit error with no reset emits no rate_limit event`() { val server = diff --git a/plugins/runner-codex-app-server/src/main/kotlin/loop/runner/codex/CodexAppServerRunner.kt b/plugins/runner-codex-app-server/src/main/kotlin/loop/runner/codex/CodexAppServerRunner.kt index c1b4e8b4..cca831af 100644 --- a/plugins/runner-codex-app-server/src/main/kotlin/loop/runner/codex/CodexAppServerRunner.kt +++ b/plugins/runner-codex-app-server/src/main/kotlin/loop/runner/codex/CodexAppServerRunner.kt @@ -190,9 +190,9 @@ data class CodexAppServerSettings( * `thread/resume` fails the turn with `response_error` and never starts a new thread in its place. Usage Codex replays * on a resumed thread for the earlier attempt's turns is left out, see [Telemetry]. * - * Streams: stdout is the protocol stream. Each stdout line is kept as raw [RunnerEvent.Output] and read with - * [ProtocolFraming], one JSON-RPC message per line; a line split across reads is whole once its line break arrives, - * since the launcher reads lines. A line longer than [ProtocolFraming.MAX_LINE_BYTES] is dropped by the launcher, which + * Streams: stdout is the protocol stream. Each stdout line is read with [ProtocolFraming], one JSON-RPC message per + * line, and kept as [RunnerEvent.Output] as read, except an error response, whose data is left out (bl-240); a line + * split across reads is whole once its line break arrives, since the launcher reads lines. A line longer than [ProtocolFraming.MAX_LINE_BYTES] is dropped by the launcher, which * writes a `loop:` line on stderr in its place (bl-128). A line that is not a protocol message is logged as a `loop:` * line on stderr naming the framing's fixed reason, never the line, and reading goes on: a bad line never ends the * turn. Stderr is kept apart, as diagnostics: each stderr line is a raw `Output` on stderr and never reaches the @@ -631,10 +631,14 @@ class CodexAppServerRunner internal constructor( return fail(event.exitCode, reason) } is ProcessEvent.Line -> { - out(RunnerEvent.Output(event.stream, event.text)) - if (event.stream != Stream.Stdout) continue + if (event.stream != Stream.Stdout) { + out(RunnerEvent.Output(event.stream, event.text)) + continue + } process.stdoutLines++ val frame = frame(event.text) + // bl-240: an error response's data stays in the frame, out of the echo. + out(RunnerEvent.Output(event.stream, ProtocolFraming.echo(frame))) if (frame is Frame.Malformed) { out(malformed(frame)) continue @@ -780,7 +784,7 @@ class CodexAppServerRunner internal constructor( kill(process) while (true) { val queued = process.events.tryReceive().getOrNull() ?: break - if (queued is ProcessEvent.Line) out(RunnerEvent.Output(queued.stream, queued.text)) + if (queued is ProcessEvent.Line) out(echoed(queued)) } end(event) } @@ -818,6 +822,13 @@ class CodexAppServerRunner internal constructor( /** Frames one stdout [line] and hands the frame to [onFrame]. */ private fun frame(line: String): Frame = ProtocolFraming.decode(line).also(onFrame) + /** The runner output of a [line] drained after the kill, a stdout line echoed as [ProtocolFraming.echo] gives it (bl-240). */ + private fun echoed(line: ProcessEvent.Line): RunnerEvent.Output = + RunnerEvent.Output( + line.stream, + if (line.stream == Stream.Stdout) ProtocolFraming.echo(ProtocolFraming.decode(line.text)) else line.text, + ) + /** The log line of a stdout line that is not a protocol message: its reason, never the line. */ private fun malformed(frame: Frame.Malformed): RunnerEvent.Output = RunnerEvent.Output(Stream.Stderr, "${LOOP_PREFIX}an app server stdout line is not a protocol message (${frame.reason}), skipped") diff --git a/plugins/runner-codex-app-server/src/main/kotlin/loop/runner/codex/ProtocolFraming.kt b/plugins/runner-codex-app-server/src/main/kotlin/loop/runner/codex/ProtocolFraming.kt index ed1ad02b..35afcfaa 100644 --- a/plugins/runner-codex-app-server/src/main/kotlin/loop/runner/codex/ProtocolFraming.kt +++ b/plugins/runner-codex-app-server/src/main/kotlin/loop/runner/codex/ProtocolFraming.kt @@ -3,7 +3,10 @@ package loop.runner.codex import kotlinx.serialization.KSerializer import kotlinx.serialization.SerializationException import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put import loop.runner.codex.protocol.CodexJson import loop.runner.codex.protocol.JSONRPCError import loop.runner.codex.protocol.JSONRPCNotification @@ -89,6 +92,40 @@ object ProtocolFraming { } } + /** + * The text runner output echoes for the stdout line of [frame] (bl-240), by the rule of the acp runner's + * `AcpFraming.echo`: an error response's `data`, and any member besides `code` and `message` in its error or besides + * `jsonrpc`, `id` and `error` in its envelope, can hold a provider's error body with account fields, so it is echoed + * as `id` (and `jsonrpc` when the line had one), `code`, `message` and a `data` marker, `[error data omitted, N + * chars]`, N the length of the omitted values as compact JSON. Every other line, an undecodable one included, is + * echoed as read. The frame itself keeps the data. + */ + fun echo(frame: Frame): String { + if (frame !is Frame.Error) return frame.line + val envelope = CodexJson.format.parseToJsonElement(frame.line) as JsonObject + val error = envelope["error"] as? JsonObject ?: return frame.line + // A null member carries nothing to omit. + val omitted = + (envelope.filterKeys { it !in ENVELOPE_KEPT }.values + error.filterKeys { it !in ERROR_KEPT }.values) + .filterNot { it is JsonNull } + if (omitted.isEmpty()) return frame.line + return buildJsonObject { + envelope["jsonrpc"]?.let { put("jsonrpc", it) } + envelope["id"]?.let { put("id", it) } + put( + "error", + buildJsonObject { + error["code"]?.let { put("code", it) } + error["message"]?.let { put("message", it) } + put("data", "[error data omitted, ${omitted.sumOf { it.toString().length }} chars]") + }, + ) + }.toString() + } + + private val ENVELOPE_KEPT = setOf("jsonrpc", "id", "error") + private val ERROR_KEPT = setOf("code", "message") + /** The UTF-8 length of [line], counted only when it can pass the maximum: a UTF-16 unit takes at most 3 bytes. */ private fun utf8Length(line: String): Int = when { diff --git a/plugins/runner-codex-app-server/src/test/kotlin/loop/runner/codex/CodexAppServerRunnerTest.kt b/plugins/runner-codex-app-server/src/test/kotlin/loop/runner/codex/CodexAppServerRunnerTest.kt index af486450..d3fe8dba 100644 --- a/plugins/runner-codex-app-server/src/test/kotlin/loop/runner/codex/CodexAppServerRunnerTest.kt +++ b/plugins/runner-codex-app-server/src/test/kotlin/loop/runner/codex/CodexAppServerRunnerTest.kt @@ -295,6 +295,38 @@ class CodexAppServerRunnerTest { assertEquals(started.sessionId to started.turnId, failed.sessionId to failed.turnId) } + @Test + fun `bl-240 the echo of an error answer omits its data, other lines are echoed as read`() { + val notification = """{ "method": "loop/unknown", "params": {"note": "kept as read"} }""" + val undecodable = """not json {"error":{"data":"kept as read"}}""" + val errorLine = + """{"id":2,"error":{"code":-32603,"message":"thread/start is not available",""" + + """"data":{"email":"$EMAIL","account_id":"$ACCOUNT_ID"}}}""" + val server = + FakeAppServer.write(dir) { + awaitClient() + response(1, FakeAppServer.initializeResult()) + awaitClient() + awaitClient() + raw(notification) + raw(undecodable) + raw(errorLine) + shell("sleep 1000") + } + + val events = runAll(runner(server.command)) + + val outputs = events.filterIsInstance() + outputs.forEach { output -> assertFalse(EMAIL in output.line || ACCOUNT_ID in output.line, output.line) } + val echoed = outputs.single { it.stream == Stream.Stdout && "thread/start is not available" in it.line } + assertTrue("\"code\":-32603" in echoed.line, echoed.line) + assertTrue("[error data omitted, " in echoed.line, echoed.line) + assertTrue(outputs.any { it.stream == Stream.Stdout && it.line == notification }) + assertTrue(outputs.any { it.stream == Stream.Stdout && it.line == undecodable }) + val failed = assertIs(events.last()) + assertEquals("response_error: thread/start failed with code -32603: thread/start is not available", failed.reason) + } + @Test fun `17_5 item 2 an answer out of order fails the start with response_error naming both requests`() { val server = @@ -1074,5 +1106,7 @@ class CodexAppServerRunnerTest { /** The responses to `initialize`, `thread/start` and `turn/start` a handshake reads before the turn. */ const val STARTUP_RESPONSES = 3 const val POLL_MS = 50L + const val EMAIL = "someone@example.com" + const val ACCOUNT_ID = "735190462281" } } diff --git a/plugins/runner-codex-app-server/src/test/kotlin/loop/runner/codex/ProtocolFramingTest.kt b/plugins/runner-codex-app-server/src/test/kotlin/loop/runner/codex/ProtocolFramingTest.kt index 221ee9f0..6f5a12c3 100644 --- a/plugins/runner-codex-app-server/src/test/kotlin/loop/runner/codex/ProtocolFramingTest.kt +++ b/plugins/runner-codex-app-server/src/test/kotlin/loop/runner/codex/ProtocolFramingTest.kt @@ -95,4 +95,31 @@ class ProtocolFramingTest { assertEquals("line longer than 10 MB", malformed.reason) assertEquals("line longer than 10 MB", assertIs(ProtocolFraming.decode(atLimit + " ")).reason) } + + @Test + fun `bl-240 the echo of an error response omits its data and keeps id, code and message`() { + val data = """{"email":"someone@example.com","account_id":"735190462281"}""" + val line = """{"id":2,"error":{"code":-32603,"message":"usage limit reached","data":$data}}""" + + val echo = ProtocolFraming.echo(ProtocolFraming.decode(line)) + + assertEquals( + """{"id":2,"error":{"code":-32603,"message":"usage limit reached","data":"[error data omitted, ${data.length} chars]"}}""", + echo, + ) + } + + @Test + fun `bl-240 every other line is echoed as read, byte for byte`() { + val lines = + listOf( + """{ "method": "thread/started", "params": {"thread": {"id": "t1"}} }""", + """{"id":1,"result":{}}""", + """{"id":"a", "error":{"code":-32601,"message":"no such method"}}""", + """not json {"error":{"data":"someone@example.com"}}""", + "", + ) + + lines.forEach { line -> assertEquals(line, ProtocolFraming.echo(ProtocolFraming.decode(line))) } + } }