Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions cli/src/test/kotlin/loop/cli/TranscriptReplay.kt
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,18 @@ fun main(args: Array<String>) {
val transcript = Path.of(args[0])
val record = Path.of(args[1])
val argv = args.drop(2)
record.resolve("argv").writeText(argv.joinToString("\n"))
// Two attempts of one run may replay at once into the same record folder: each file is replaced atomically, since
// concurrent `Files.copy` with REPLACE_EXISTING deletes then creates the target and one of them can fail.
TranscriptReplay.replaceAtomically(record.resolve("argv")) { it.writeText(argv.joinToString("\n")) }
val mcpConfig =
argv
.zipWithNext()
.firstOrNull { it.first == "--mcp-config" }
?.second
?.let { Path.of(it) }
mcpConfig?.let { Files.copy(it, record.resolve("mcp.json"), StandardCopyOption.REPLACE_EXISTING) }
mcpConfig?.let { config ->
TranscriptReplay.replaceAtomically(record.resolve("mcp.json")) { Files.copy(config, it, StandardCopyOption.REPLACE_EXISTING) }
}
// The first user message line; Claude Code with `--input-format stream-json` keeps stdin open (m3-07).
readlnOrNull()
val servers =
Expand Down Expand Up @@ -77,6 +81,20 @@ fun main(args: Array<String>) {
}

object TranscriptReplay {
/** Writes [target] through [write] into a temporary file of its own folder, then moves it over [target] atomically. */
fun replaceAtomically(
target: Path,
write: (Path) -> Unit,
) {
val temp = Files.createTempFile(target.parent, ".${target.fileName}", ".tmp")
try {
write(temp)
Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
} finally {
Files.deleteIfExists(temp)
}
}

data class ToolUse(
val id: String,
val name: String,
Expand Down
4 changes: 3 additions & 1 deletion docs/plugins/runner-acp.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,9 @@ Loop ships default context windows of `1048576` tokens in `ContextConfig.DEFAULT
- **Occupancy:** every `usage_update` notification with `used > 0` emits `context_usage` with `google/<model>`, deduplicated when occupancy and model are unchanged.
- **Usage:** every `session/prompt` response carrying `usage` adds its turn counts into the session's running absolute totals with `totalCostUsd = null`.
- **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.
- **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 <duration>` 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: <message> (code <code>); the quota resets at <instant>`. `loop trace` prints it as `rate_limit limit=gemini name=<model> 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).
- **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
Expand Down
11 changes: 11 additions & 0 deletions docs/spec-decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -3120,6 +3120,17 @@ Under `preset: agy` each session ran with a fresh isolated `--gemini-dir` folder

Tests: `plugins/runner-acp/src/test/kotlin/loop/runner/acp/AgyResumeTest.kt` (a hold keeps the folder and a resume loads it in a new process with the same folder, a respawn after a dead process, a respawn that dies fails the turn without a second one, no kept folder, a tampered `settings.json` rewritten before the load, an unexpected root entry refused, an agent without `loadSession` and a `session/load` error each giving a fresh session, a session without an id deleting its folder, and since bl-230 a kept folder surviving a new session of the issue until that one is kept, the sweep at the runner's start, a protected roots failure ending the session), `plugins/runner-acp/src/test/kotlin/loop/runner/acp/AgyIsolationDirLifetimeTest.kt` (the lookup and claim, the removal of an issue's kept folders, the sweep of a gone workspace and of a dead owner under both roots, the checks before a load, and since bl-230 the allow lists of `config/` and `antigravity-cli/`, the folder `removeKept` spares, and the pid file claim against a concurrent sweep) and `AcpRunnerContractTest` (the contract's resume cases under `preset: agy`).

### The acp runner holds until an exhausted Gemini quota resets (extension, bl-215)

A `runner_unavailable` from an exhausted Gemini quota carried no retry key Loop read, so the run level hold probed after 1 minute, then 2, 4 and up to 15 minutes for hours until the quota reset. Google's 429 carries the reset: `agy`'s own CLI logged three, each `RESOURCE_EXHAUSTED` with an `ErrorInfo` of reason `QUOTA_EXHAUSTED` whose `metadata` holds `model`, `quotaResetDelay` and `quotaResetTimeStamp`, a `RetryInfo` `retryDelay`, and the message `Your quota will reset after <duration>`. Which of these `agy acp` passes through its JSON-RPC error is not confirmed yet, so every form is read (`AcpQuotaReset` in `plugins/runner-acp`).

- **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 <instant>`, 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.

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`).

### 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`):
Expand Down
6 changes: 4 additions & 2 deletions mcp/src/main/kotlin/loop/mcp/LoopMcpServer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -406,8 +406,10 @@ object LoopMcpServer {
val server = create(version, submitResult, move, comment, trimmer, resources, ask, followup)
val transport = StdioServerTransport(input.asSource().buffered(), output.asSink().buffered())
val closed = CompletableDeferred<Unit>()
val session = server.createSession(transport)
session.onClose { closed.complete(Unit) }
// Listened to before createSession, which starts the transport: an input that ends at once can close it
// before createSession returns, and a listener added to the session after that would never hear the close.
transport.onClose { closed.complete(Unit) }
server.createSession(transport)
closed.await()
}

Expand Down
30 changes: 30 additions & 0 deletions mcp/src/test/kotlin/loop/mcp/LoopMcpServerTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.OutputStream
import java.nio.channels.Channels
import java.nio.channels.Pipe
import kotlin.test.Test
Expand Down Expand Up @@ -693,4 +695,32 @@ class LoopMcpServerTest {
}
assertTrue(!client.serving.isAlive, "the server still runs after the end of its input")
}

/**
* The transport starts reading inside `createSession`, so an input that ends at once can close the session before
* `serve` returns from it. The end is still seen: every one of these servers returns.
*/
@Test
fun `the server returns when its input ends before the session is set up`() {
repeat(200) { round ->
val serving =
Thread {
runBlocking {
LoopMcpServer.serve(
ByteArrayInputStream(ByteArray(0)),
OutputStream.nullOutputStream(),
"test",
SubmitResultHandler { ToolReply("ok") },
MoveHandler { ToolReply("moved") },
CommentHandler { ToolReply("commented") },
)
}
}.apply {
isDaemon = true
start()
}
serving.join(10_000)
assertTrue(!serving.isAlive, "server $round still runs after its input ended")
}
}
}
40 changes: 26 additions & 14 deletions plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpErrors.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.longOrNull
import loop.api.RunnerEvent
import java.util.Locale
import kotlin.time.Clock
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
import kotlin.time.Instant

/**
* Classifies structured ACP JSON-RPC errors into [RunnerEvent.TurnFailed.Category.RunnerUnavailable]
Expand All @@ -24,6 +26,7 @@ internal object AcpErrors {
data class Classification(
val category: RunnerEvent.TurnFailed.Category?,
val retryAfter: Duration? = null,
val quotaReset: AcpQuotaReset.Reset? = null,
)

private const val INVALID_PARAMS_CODE = -32602L
Expand Down Expand Up @@ -80,13 +83,16 @@ internal object AcpErrors {
/**
* Classifies a structured JSON-RPC error response for [method]. Returns `RunnerUnavailable` only
* for structured model refusals, authentication/eligibility codes or 401/403 statuses, rate limit
* or overload codes or 429/503/529 statuses, or POSIX/Node transport errno codes with no HTTP status.
* or overload codes or 429/503/529 statuses (a Google `RESOURCE_EXHAUSTED` or `QUOTA_EXHAUSTED`
* error at any depth of [data] included), or POSIX/Node transport errno codes with no HTTP status.
* A rate limit or status classification carries its wait, a quota reset measured from [now].
*/
fun classify(
method: String?,
code: Long,
message: String,
data: JsonElement? = null,
now: Instant = Clock.System.now(),
): Classification {
val dataObj = data as? JsonObject
val httpStatus = extractHttpStatus(dataObj)
Expand All @@ -102,28 +108,19 @@ internal object AcpErrors {
}

if (httpStatus != null && httpStatus in UNAVAILABLE_HTTP_STATUSES) {
return Classification(
category = RunnerEvent.TurnFailed.Category.RunnerUnavailable,
retryAfter = extractRetryAfter(dataObj),
)
return unavailableWithWait(message, data, now)
}

if (HTTP_STATUS_LINE_PATTERNS.any { it.containsMatchIn(combined) }) {
return Classification(
category = RunnerEvent.TurnFailed.Category.RunnerUnavailable,
retryAfter = extractRetryAfter(dataObj),
)
return unavailableWithWait(message, data, now)
}

if (tokens.any { it in STRUCTURED_AUTH_CODES }) {
return Classification(RunnerEvent.TurnFailed.Category.RunnerUnavailable)
}

if (tokens.any { it in STRUCTURED_RATE_LIMIT_CODES }) {
return Classification(
category = RunnerEvent.TurnFailed.Category.RunnerUnavailable,
retryAfter = extractRetryAfter(dataObj),
)
if (tokens.any { it in STRUCTURED_RATE_LIMIT_CODES } || AcpQuotaReset.isQuotaExhausted(data)) {
return unavailableWithWait(message, data, now)
}

// m4-08: a transport failure with no HTTP status at all is RunnerUnavailable; one with an HTTP
Expand All @@ -135,6 +132,21 @@ internal object AcpErrors {
return Classification(category = null)
}

/**
* A `RunnerUnavailable` that may carry a wait: an explicit retry key of the error data first, else the quota reset
* [AcpQuotaReset] finds (bl-215), else none.
*/
private fun unavailableWithWait(
message: String,
data: JsonElement?,
now: Instant,
): Classification {
val unavailable = RunnerEvent.TurnFailed.Category.RunnerUnavailable
extractRetryAfter(data as? JsonObject)?.let { return Classification(unavailable, retryAfter = it) }
val reset = AcpQuotaReset.find(message, data, now)
return Classification(unavailable, retryAfter = reset?.retryAfter, quotaReset = reset)
}

private fun extractHttpStatus(data: JsonObject?): Long? {
if (data == null) return null
for (key in listOf("httpStatus", "httpStatusCode", "http_status", "status", "statusCode")) {
Expand Down
Loading