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
3 changes: 3 additions & 0 deletions bridge/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,9 @@ const main = async () => {
case "rpc.clientGone":
void run(Providers.clientGone(fields)).catch(() => undefined);
return;
case "providers.refreshUsage":
void run(Providers.refreshUsage(fields)).catch(() => undefined);
return;
// What became of an offer (`ProviderContinuationService`): dropped, its run ended
// before it started, or done with.
case "continuation.clear":
Expand Down
13 changes: 13 additions & 0 deletions bridge/src/providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -463,3 +463,16 @@ export const clientGone = (fields: Record<string, unknown>) =>
const caller = decodeCaller(fields);
return policy.removeRpcClient(caller.authSessionId, caller.rpcClientId);
});

/**
* `providers.refreshUsage`: a turn of the instance failed on its usage limit, so it reads its
* limits again, as `ProviderEventIngestor` does once it stored that terminal.
*/
export const refreshUsage = (fields: Record<string, unknown>) =>
Effect.gen(function* () {
const instances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
const instanceId = ProviderInstanceId.make(String(fields.instanceId ?? ""));
const instance = yield* instances.getInstance(instanceId);
if (!instance?.snapshot.refreshUsage) return;
yield* instance.snapshot.refreshUsage.pipe(Effect.ignoreCause({ log: true }));
});
23 changes: 23 additions & 0 deletions crates/server-threads/src/turns/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,9 @@ struct State {
runtime_lost: bool,
/// The provider turn the terminal of a turn that failed to start names.
failed_turn_id: String,
/// A terminal that failed on the usage limit was stored, so the instance reads its limits
/// again.
refresh_usage: bool,
}

fn lock(state: &Mutex<State>) -> MutexGuard<'_, State> {
Expand Down Expand Up @@ -222,6 +225,7 @@ async fn consume(
children: Children::default(),
runtime_lost: false,
failed_turn_id: ids::failed_provider_turn(&session.driver, &run.attempt),
refresh_usage: false,
}));
let stream = turns.batcher.stream(Some(Priority {
thread_id: run.thread_id.clone(),
Expand Down Expand Up @@ -304,6 +308,19 @@ async fn consume(
if let Err(error) = written {
break Some(error);
}
// Once the terminal is stored, as upstream's `ProviderEventIngestor` does, so the limits
// show without waiting for the next provider check.
if std::mem::take(&mut lock(&state).refresh_usage) {
let (turns, instance) = (turns.clone(), run.instance_id.clone());
tokio::spawn(async move {
turns
.notify_running_bridge(
"providers.refreshUsage",
json!({ "instanceId": instance }),
)
.await;
});
}
if let Some(attempt) = started_attempt {
turns.deliver_parked_steers(&run.thread_id, &attempt);
}
Expand Down Expand Up @@ -593,6 +610,12 @@ fn ingest_delivered(
};
let writers = vec![writer; events.len()];
write_events(transaction, batch, &mut events, &writers)?;
if delivered["type"] == "turn.terminal"
&& delivered["status"] == "failed"
&& delivered["failure"]["class"] == "usage_limit"
{
state.refresh_usage = true;
}
let mut followed = ingest::follow_up(transaction, &run.input(), delivered, &events)?;
if !followed.is_empty() {
let writers = vec![writer; followed.len()];
Expand Down
36 changes: 35 additions & 1 deletion crates/server/tests/fixtures/fake-claude.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,17 @@
// - `BG-TIMER`: the same with `sleep 3600`, a timer upstream's adapter marks the agent waits on.
// - `LIMIT`: fails the turn on Claude's usage limit (an API error with status 429).
// - `SLOW`: starts answering and ends only when interrupted, as a long turn Stop ends.
// - `RATE <percent>`: reports the session window's use in a `rate_limit_event`, as the CLI does
// before it answers, then answers OK.
//
// `LIMIT` and `RATE` record when they reported, in milliseconds since the epoch.
// - an empty prompt, which the SDK sends to resume a turn the CLI was told to pick up
// (`CLAUDE_CODE_RESUME_INTERRUPTED_TURN`): answers RESUMED.
// - anything else: answers OK.
//
// Every prompt and tool answer is a line of JSON in the file `FAKE_CLAUDE_LOG` names, which the
// command that runs it sets.
// command that runs it sets. With `FAKE_CLAUDE_USAGE` set, `get_usage` (the usage probe) answers
// with the session window's use the JSON file it names holds (`{ "fiveHour": 10 }`).

import * as Fs from "node:fs";
import * as Readline from "node:readline";
Expand All @@ -29,6 +34,9 @@ if (args.includes("--version") || args.includes("-v")) {
}

const LOG = process.env.FAKE_CLAUDE_LOG;
const USAGE = process.env.FAKE_CLAUDE_USAGE;
/** When the session window resets: fixed, so every report of it agrees. */
const RESETS_AT = "2099-01-01T00:00:00.000Z";
const record = (entry) => {
if (LOG !== undefined) Fs.appendFileSync(LOG, `${JSON.stringify(entry)}\n`);
};
Expand Down Expand Up @@ -309,6 +317,7 @@ const turn = async (message) => {
record({ event: "prompt", text });
init();
if (text.includes("LIMIT")) {
record({ event: "limit", at: Date.now() });
result("API Error: 429 Rate limit reached.", {
is_error: true,
api_error_status: 429,
Expand All @@ -317,6 +326,23 @@ const turn = async (message) => {
});
return;
}
const rate = /RATE (\d+)/.exec(text);
if (rate !== null) {
record({ event: "rate", at: Date.now() });
send({
type: "rate_limit_event",
rate_limit_info: {
status: "allowed",
rateLimitType: "five_hour",
utilization: Number(rate[1]) / 100,
resetsAt: Date.parse(RESETS_AT) / 1000,
},
...base(),
});
assistant([{ type: "text", text: "OK" }]);
result("OK");
return;
}
if (text.includes("SLOW")) {
assistant([{ type: "text", text: "WORKING" }]);
slow = () =>
Expand Down Expand Up @@ -372,6 +398,14 @@ const control = (request) => {
});
case "mcp_status":
return respond(request, { mcpServers: [] });
case "get_usage": {
if (USAGE === undefined) return respond(request);
const { fiveHour } = JSON.parse(Fs.readFileSync(USAGE, "utf8"));
return respond(request, {
rate_limits_available: true,
rate_limits: { five_hour: { utilization: fiveHour, resets_at: RESETS_AT } },
});
}
case "interrupt": {
respond(request);
const end = slow;
Expand Down
Loading
Loading