diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx
index 84de2bf777cfb..e4d4ce53376c1 100644
--- a/apps/mobile/src/App.tsx
+++ b/apps/mobile/src/App.tsx
@@ -1,4 +1,5 @@
import { installPermissionUpdateNotice } from "./features/connection/permissionUpdateNotice";
+import { InferenceFleetCoordinator } from "./features/settings/InferenceFleetCoordinator";
import { installComposerAttachmentUploads } from "./state/composer-attachment-uploads";
import { installThreadOutboxDelivery } from "./state/threadOutboxDelivery";
import * as Linking from "expo-linking";
@@ -283,6 +284,7 @@ function AppContent() {
+
diff --git a/apps/mobile/src/features/settings/InferenceAccounts.tsx b/apps/mobile/src/features/settings/InferenceAccounts.tsx
index 59ed556613c2c..e1a900f36d4ce 100644
--- a/apps/mobile/src/features/settings/InferenceAccounts.tsx
+++ b/apps/mobile/src/features/settings/InferenceAccounts.tsx
@@ -5,6 +5,10 @@ import {
} from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import {
+ inferenceAccountRetryAfter,
+ inferenceAccountStatus,
+} from "@t3tools/client-runtime/state/inference-proxy";
import {
INFERENCE_DRIVERS,
INFERENCE_HARNESSES,
@@ -201,15 +205,18 @@ function InferenceControls({ environment }: { environment: SettingsTarget }) {
onPress={() => void run({ operation: "revoke", environmentId: c.environmentId })}
/>
))}
- {host.accounts.map((account) => (
- void run({ operation: "removeAccount", name: account.name })}
- />
- ))}
+ {host.accounts.map((account) => {
+ const retryAfter = inferenceAccountRetryAfter(account);
+ return (
+ void run({ operation: "removeAccount", name: account.name })}
+ />
+ );
+ })}
{login ? (
<>
;
+}) {
+ const canGrant = useAtomValue(inferenceProxy.canGrant(host.environmentId));
+ const status = useEnvironmentQuery(
+ canGrant
+ ? inferenceProxy.inferenceStatus({ environmentId: host.environmentId, input: {} })
+ : null,
+ );
+ const route = useAtomCommand(inferenceProxy.routeInference, { reportFailure: false });
+ const providers = useAtomValue(serverEnvironment.providersValueAtom(host.environmentId));
+ const providerStatusKey = JSON.stringify(
+ providers
+ ?.filter((provider) => INFERENCE_DRIVERS.some((driver) => driver === provider.driver))
+ .map((provider) => [
+ provider.instanceId,
+ provider.status,
+ provider.auth.status,
+ provider.availability,
+ provider.limitedUntil,
+ provider.checkedAt,
+ ]),
+ );
+ const attempts = useRef(new Map());
+ const lastProviderStatus = useRef(null);
+ const candidates = status.data ? planInferenceFallbacks(host, status.data, consumers) : [];
+ const keyedCandidates = candidates.map((input) => {
+ const consumer = consumers.find(
+ (entry) => entry.environmentId === input.consumer.environmentId,
+ );
+ return {
+ input,
+ id: `${input.consumer.environmentId}:${input.driver}`,
+ key:
+ consumer && status.data
+ ? inferenceFallbackKey(input.host, consumer, input.driver, status.data)
+ : "",
+ };
+ });
+ const key = JSON.stringify([keyedCandidates, status.successResult?.timestamp]);
+ const run = useEffectEvent(() => {
+ const active = new Set(keyedCandidates.map((candidate) => candidate.id));
+ for (const id of attempts.current.keys()) if (!active.has(id)) attempts.current.delete(id);
+ for (const { input, id, key: candidateKey } of keyedCandidates) {
+ const previous = attempts.current.get(id);
+ if (previous?.key === candidateKey) {
+ if (previous.state !== "failed" || Date.now() < previous.retryAt) continue;
+ }
+ const attempt: Attempt = {
+ key: candidateKey,
+ failures: previous?.key === candidateKey ? previous.failures : 0,
+ retryAt: 0,
+ state: "pending",
+ };
+ attempts.current.set(id, attempt);
+ void route(input).then((result) => {
+ if (attempts.current.get(id) !== attempt) return;
+ if (result._tag === "Success") {
+ attempt.state = "succeeded";
+ return;
+ }
+ attempt.state = "failed";
+ attempt.failures += 1;
+ attempt.retryAt = Date.now() + inferenceFallbackRetryDelay(attempt.failures);
+ });
+ }
+ });
+ const refreshStatus = useEffectEvent(() => {
+ if (canGrant && !status.isPending) status.refresh();
+ });
+
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reconciles grants when a connected host or routed consumer changes
+ useEffect(() => {
+ run();
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- a refreshed status wakes bounded fallback retries
+ }, [key]);
+
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- provider auth changes can make a host newly available for fallback
+ useEffect(() => {
+ if (lastProviderStatus.current !== null && lastProviderStatus.current !== providerStatusKey)
+ refreshStatus();
+ lastProviderStatus.current = providerStatusKey;
+ }, [providerStatusKey]);
+
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- hosts can recover without a provider event or connection change
+ useEffect(() => {
+ if (!canGrant) return;
+ const interval = setInterval(refreshStatus, STATUS_REFRESH_INTERVAL_MS);
+ return () => clearInterval(interval);
+ }, [canGrant]);
+ return null;
+}
+
+export function InferenceFleetCoordinator() {
+ const { environments } = useEnvironments();
+ const connected = environments.filter(
+ (environment) =>
+ environment.connection.phase === "connected" &&
+ environment.serverConfig?.environment.capabilities.inferenceProxy === true,
+ );
+ return connected.map((host) => (
+
+ ));
+}
diff --git a/apps/server/src/inference/InferenceProxy.test.ts b/apps/server/src/inference/InferenceProxy.test.ts
index 069700b6aeacd..e4561534e2962 100644
--- a/apps/server/src/inference/InferenceProxy.test.ts
+++ b/apps/server/src/inference/InferenceProxy.test.ts
@@ -7,10 +7,12 @@ import {
EnvironmentId,
ProviderInstanceId,
ProviderDriverKind,
+ isInferenceProviderConfig,
} from "@t3tools/contracts";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as NetService from "@t3tools/shared/Net";
import * as Deferred from "effect/Deferred";
+import * as Clock from "effect/Clock";
import * as DateTime from "effect/DateTime";
import * as PeerLinks from "../peer/PeerLinks.ts";
import * as Fiber from "effect/Fiber";
@@ -93,6 +95,21 @@ it.effect(
};
let serving = false;
let poolUnavailable = false;
+ let keepRuntimeAvailable = false;
+ let runtimeOnlyUnavailable = false;
+ let listedAccountRuntimeOnly = false;
+ let poolStatusMessage: string | undefined;
+ let poolRetryAfter: string | undefined;
+ let poolCooldowns: Array> | undefined;
+ let managedClaude = false;
+ let managedClaudeStatus = "active";
+ let managedClaudeDisabled = false;
+ let claudeUsageStatus = 200;
+ let claudeUsageCalls = 0;
+ let claudeUsage: Record = {};
+ let blockClaudeUsage = false;
+ const claudeUsageStarted = yield* Deferred.make();
+ const releaseClaudeUsage = yield* Deferred.make();
let lan = false;
let rejectNextLaunch = false;
let currentExit: Deferred.Deferred | undefined;
@@ -161,6 +178,40 @@ it.effect(
let activeCodexConfig: unknown;
const remoteCatalogKeys: (string | undefined)[] = [];
const http = HttpClient.make((request) => {
+ if (request.url.endsWith("/v0/management/api-call")) {
+ const body = request.body;
+ if (body._tag !== "Uint8Array" || !body.text) throw new Error("Missing usage request");
+ const call = JSON.parse(body.text) as Record;
+ expect(call).toMatchObject({
+ auth_index: "claude-auth",
+ method: "GET",
+ url: "https://api.anthropic.com/api/oauth/usage",
+ header: { Authorization: "Bearer $TOKEN$" },
+ });
+ claudeUsageCalls++;
+ return Effect.gen(function* () {
+ if (blockClaudeUsage) {
+ yield* Deferred.succeed(claudeUsageStarted, undefined);
+ yield* Deferred.await(releaseClaudeUsage);
+ }
+ return HttpClientResponse.fromWeb(
+ request,
+ Response.json({
+ status_code: claudeUsageStatus,
+ body: JSON.stringify(claudeUsage),
+ }),
+ );
+ });
+ }
+ if (new URL(request.url).pathname.endsWith("/v0/management/auth-files/models")) {
+ const name = new URL(request.url).searchParams.get("name");
+ const models = catalog.filter((model) =>
+ name === "claude.json"
+ ? model.owned_by === "anthropic"
+ : model.owned_by !== "anthropic",
+ );
+ return Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ models })));
+ }
if (request.method === "POST" && request.url.includes("/v0/management/auth-files?")) {
const body = request.body;
if (body._tag !== "Uint8Array" || !body.text) throw new Error("Missing auth JSON");
@@ -225,10 +276,18 @@ it.effect(
if (request.url.endsWith("/.well-known/t3/environment")) {
expect(request.headers.authorization).toBeUndefined();
return Effect.succeed(
- HttpClientResponse.fromWeb(request, Response.json({ environmentId: peerId })),
+ HttpClientResponse.fromWeb(
+ request,
+ Response.json({
+ environmentId: request.url.startsWith("https://fallback.example.ts.net/")
+ ? EnvironmentId.make("other-host")
+ : peerId,
+ }),
+ ),
);
}
- remoteCatalogKeys.push(request.headers.authorization);
+ if (!request.url.endsWith("/health"))
+ remoteCatalogKeys.push(request.headers.authorization);
if (staleLinkedCatalog && request.url.startsWith("http://127.0.0.1:34567/"))
return Effect.succeed(
HttpClientResponse.fromWeb(request, new Response(null, { status: 502 })),
@@ -242,26 +301,50 @@ it.effect(
HttpClientResponse.fromWeb(
request,
Response.json(
- request.url.endsWith("auth-files")
- ? {
- files: [
- {
- name: "codex:api-key:fixture",
- provider: "codex",
- status: "active",
- unavailable: poolUnavailable,
- runtime_only: true,
- },
- {
- name: "one.json",
- provider: "codex",
- status: "active",
- unavailable: poolUnavailable,
- refresh_token: "must stay local",
- },
- ],
- }
- : { data: catalog },
+ request.url.endsWith("/health")
+ ? new URL(request.url).pathname === "/health"
+ ? { status: "ok" }
+ : {
+ availableDrivers: poolUnavailable ? [] : ["codex", "opencode", "pi"],
+ models: catalog.map((model) => model.id),
+ }
+ : request.url.endsWith("auth-files")
+ ? {
+ files: [
+ ...(managedClaude
+ ? [
+ {
+ id: "claude.json",
+ name: "claude.json",
+ auth_index: "claude-auth",
+ provider: "claude",
+ status: managedClaudeStatus,
+ disabled: managedClaudeDisabled,
+ },
+ ]
+ : []),
+ {
+ name: "codex:api-key:fixture",
+ provider: "codex",
+ status: "active",
+ unavailable:
+ runtimeOnlyUnavailable || (poolUnavailable && !keepRuntimeAvailable),
+ runtime_only: true,
+ },
+ {
+ name: "one.json",
+ provider: "codex",
+ status: "active",
+ unavailable: poolUnavailable,
+ runtime_only: listedAccountRuntimeOnly,
+ status_message: poolStatusMessage,
+ next_retry_after: poolRetryAfter,
+ cooldowns: poolCooldowns,
+ refresh_token: "must stay local",
+ },
+ ],
+ }
+ : { data: catalog },
),
),
);
@@ -323,6 +406,38 @@ it.effect(
Layer.fresh,
);
const settings = yield* ServerSettings.ServerSettingsService;
+ const legacyRoutes = [
+ {
+ driver: "codex" as const,
+ hostId,
+ baseUrl: "http://127.0.0.1:23456",
+ key: "legacy-local-key",
+ },
+ {
+ driver: "claudeAgent" as const,
+ hostId: EnvironmentId.make("offline-host"),
+ baseUrl: "http://192.168.1.44:12345/api/inference",
+ key: "legacy-lan-key",
+ },
+ ];
+ for (const route of legacyRoutes)
+ yield* settings.updateProviderInstance({
+ operation: "upsert",
+ instanceId: ProviderInstanceId.make(route.driver),
+ instance: {
+ driver: ProviderDriverKind.make(route.driver),
+ enabled: false,
+ config: {
+ inferenceEnabled: true,
+ inferenceHostId: route.hostId,
+ inferenceHostLabel: "",
+ inferenceBaseUrl: route.baseUrl,
+ inferenceKey: route.key,
+ inferenceModels: [route.driver === "codex" ? "gpt-legacy" : "claude-legacy"],
+ inferenceHomePath: home,
+ },
+ },
+ });
const cliHome = home + "/.codex";
const claudeHome = home + "/.claude";
const claudeAuthFile = claudeHome + "/.credentials.json";
@@ -401,6 +516,36 @@ it.effect(
Effect.gen(function* () {
const proxy = yield* InferenceProxy.InferenceProxy;
expect((yield* proxy.status).enabled).toBe(false);
+ yield* proxy.bindRoutes(45678);
+ expect(remoteCatalogKeys).toEqual([]);
+ for (const route of legacyRoutes) {
+ const current = (yield* settings.getSettings).providerInstances[
+ ProviderInstanceId.make(route.driver)
+ ];
+ expect(current?.config).toMatchObject({
+ inferenceBaseUrl: `http://127.0.0.1:45678/api/inference/linked/${route.driver}/${route.hostId}`,
+ inferenceKey: route.key,
+ });
+ }
+ const migrated = yield* state.get("inference-proxy-state");
+ expect(Option.isSome(migrated)).toBe(true);
+ if (Option.isSome(migrated)) {
+ const saved = JSON.parse(new TextDecoder().decode(migrated.value)) as {
+ routePools: { driver: string; primary: { baseUrl: string; key: string } }[];
+ };
+ for (const route of legacyRoutes)
+ expect(
+ saved.routePools.find((pool) => pool.driver === route.driver)?.primary,
+ ).toMatchObject({
+ baseUrl: route.baseUrl,
+ key: route.key,
+ });
+ }
+ for (const route of legacyRoutes)
+ yield* proxy.manage({
+ operation: "removeRoute",
+ instanceId: ProviderInstanceId.make(route.driver),
+ });
const startSharing = proxy.manage({
operation: "configure",
enabled: true,
@@ -652,7 +797,164 @@ it.effect(
serving = true;
yield* startSharing;
const { accounts } = yield* proxy.status;
- expect(accounts).toEqual([{ name: "one.json", provider: "codex", status: "active" }]);
+ expect(accounts).toEqual([
+ { name: "one.json", provider: "codex", status: "active", availability: "available" },
+ ]);
+ listedAccountRuntimeOnly = true;
+ expect((yield* proxy.status).accounts).toEqual([]);
+ expect((yield* proxy.status).availableDrivers).toContain("codex");
+ listedAccountRuntimeOnly = false;
+ poolUnavailable = true;
+ poolStatusMessage = "HTTP 429 quota exhausted";
+ poolRetryAfter = "2026-11-17T20:00:00Z";
+ expect((yield* proxy.status).accounts[0]).toMatchObject({
+ availability: "rateLimited",
+ retryAfter: poolRetryAfter,
+ });
+ poolStatusMessage = "Failed to authenticate. API Error: 403 status code (no body)";
+ poolRetryAfter = undefined;
+ expect((yield* proxy.status).accounts[0]).toMatchObject({
+ availability: "authenticationError",
+ });
+ poolStatusMessage = "service_overloaded (HTTP 529)";
+ expect((yield* proxy.status).accounts[0]).toMatchObject({
+ availability: "unavailable",
+ });
+ expect((yield* proxy.status).accounts[0]).not.toHaveProperty("retryAfter");
+ poolStatusMessage = undefined;
+ poolRetryAfter = "1960-01-01T00:00:00Z";
+ expect((yield* proxy.status).accounts[0]).toMatchObject({
+ availability: "unavailable",
+ });
+ expect((yield* proxy.status).accounts[0]).not.toHaveProperty("retryAfter");
+ poolUnavailable = false;
+ poolStatusMessage = undefined;
+ poolRetryAfter = undefined;
+ catalog = [
+ { id: "gpt-quota-fixture", owned_by: "openai" },
+ { id: "claude-quota-fixture", owned_by: "anthropic" },
+ ];
+ const claudeResetAt = DateTime.formatIso(
+ DateTime.makeUnsafe((yield* Clock.currentTimeMillis) + 30 * 60_000),
+ );
+ managedClaude = true;
+ claudeUsage = {
+ five_hour: { utilization: 100, resets_at: claudeResetAt },
+ seven_day: { utilization: 84, resets_at: claudeResetAt },
+ extra_usage: {
+ is_enabled: false,
+ monthly_limit: null,
+ used_credits: null,
+ utilization: null,
+ },
+ };
+ expect(
+ (yield* proxy.status).accounts.find((account) => account.name === "claude.json"),
+ ).toMatchObject({ availability: "rateLimited", retryAfter: claudeResetAt });
+ expect((yield* proxy.status).availableDrivers).not.toContain("claudeAgent");
+ const hosted = yield* proxy.grant(peer);
+ expect((yield* proxy.health(hosted.key))?.availableDrivers).not.toContain(
+ "claudeAgent",
+ );
+ expect((yield* proxy.health(hosted.key))?.models).toEqual(["gpt-quota-fixture"]);
+ expect(claudeUsageCalls).toBe(1);
+ yield* TestClock.adjust("31 seconds");
+ claudeUsage = {
+ five_hour: { utilization: 50, resets_at: claudeResetAt },
+ seven_day: { utilization: 100, resets_at: claudeResetAt },
+ limits: [
+ {
+ kind: "weekly_scoped",
+ percent: 100,
+ resets_at: claudeResetAt,
+ scope: { model: { display_name: "Fable" } },
+ },
+ ],
+ };
+ expect(
+ (yield* proxy.status).accounts.find((account) => account.name === "claude.json"),
+ ).toMatchObject({ availability: "rateLimited", retryAfter: claudeResetAt });
+ expect(claudeUsageCalls).toBe(2);
+ yield* TestClock.adjust("31 seconds");
+ claudeUsage = {
+ five_hour: { utilization: 50, resets_at: claudeResetAt },
+ seven_day: { utilization: 70, resets_at: claudeResetAt },
+ limits: [
+ {
+ kind: "weekly_scoped",
+ percent: 100,
+ resets_at: claudeResetAt,
+ scope: { model: { display_name: "Fable" } },
+ },
+ ],
+ extra_usage: {
+ is_enabled: true,
+ monthly_limit: 10,
+ used_credits: 10,
+ utilization: 100,
+ },
+ };
+ expect(
+ (yield* proxy.status).accounts.find((account) => account.name === "claude.json"),
+ ).toMatchObject({ availability: "available" });
+ expect((yield* proxy.health(hosted.key))?.availableDrivers).toContain("claudeAgent");
+ expect((yield* proxy.health(hosted.key))?.models).toEqual([
+ "gpt-quota-fixture",
+ "claude-quota-fixture",
+ ]);
+ poolCooldowns = [
+ {
+ scope: "model",
+ model_key: "gpt-quota-fixture",
+ reason: "quota",
+ retry_at: claudeResetAt,
+ remaining_seconds: 1_800,
+ },
+ ];
+ runtimeOnlyUnavailable = true;
+ expect((yield* proxy.health(hosted.key))?.models).toEqual(["claude-quota-fixture"]);
+ poolCooldowns = undefined;
+ runtimeOnlyUnavailable = false;
+ yield* TestClock.adjust("31 seconds");
+ claudeUsage = {
+ five_hour: { utilization: 100, resets_at: claudeResetAt },
+ seven_day: { utilization: 100, resets_at: claudeResetAt },
+ extra_usage: {
+ is_enabled: true,
+ monthly_limit: 10,
+ used_credits: 1,
+ utilization: 10,
+ },
+ };
+ expect(
+ (yield* proxy.status).accounts.find((account) => account.name === "claude.json"),
+ ).toMatchObject({ availability: "available" });
+ yield* TestClock.adjust("31 seconds");
+ claudeUsageStatus = 403;
+ expect(
+ (yield* proxy.status).accounts.find((account) => account.name === "claude.json"),
+ ).toMatchObject({ availability: "available" });
+ yield* TestClock.adjust("31 seconds");
+ managedClaudeStatus = "error";
+ expect(
+ (yield* proxy.status).accounts.find((account) => account.name === "claude.json"),
+ ).toMatchObject({ availability: "unavailable" });
+ expect(claudeUsageCalls).toBe(5);
+ managedClaudeStatus = "active";
+ managedClaudeDisabled = true;
+ expect(
+ (yield* proxy.status).accounts.find((account) => account.name === "claude.json"),
+ ).toMatchObject({ availability: "disabled" });
+ expect(claudeUsageCalls).toBe(5);
+ managedClaudeDisabled = false;
+ claudeUsageStatus = 200;
+ blockClaudeUsage = true;
+ expect((yield* proxy.health(hosted.key))?.availableDrivers).toContain("claudeAgent");
+ yield* Deferred.await(claudeUsageStarted);
+ yield* Deferred.succeed(releaseClaudeUsage, undefined);
+ blockClaudeUsage = false;
+ managedClaude = false;
+ catalog = [];
yield* proxy.manage({ operation: "setRouting", strategy: "fill-first" });
yield* proxy.manage({ operation: "setRouting", sessionAffinity: false });
const readConfig = fs
@@ -675,6 +977,9 @@ it.effect(
]);
poolUnavailable = true;
expect((yield* proxy.health(issued.key))?.availableDrivers).toEqual([]);
+ keepRuntimeAvailable = true;
+ expect((yield* proxy.health(issued.key))?.availableDrivers).toContain("codex");
+ keepRuntimeAvailable = false;
poolUnavailable = false;
expect((yield* proxy.health(issued.key))?.availableDrivers).toContain("codex");
const connect = { grant: local, driver: "codex" as const, hostLabel: "Host" };
@@ -690,6 +995,11 @@ it.effect(
{ id: "codex-pool-work", owned_by: "openai" },
{ id: "claude-pool-sonnet", owned_by: "anthropic" },
];
+ poolUnavailable = true;
+ expect((yield* proxy.connect(connect).pipe(Effect.flip)).message).toContain(
+ "no available accounts",
+ );
+ poolUnavailable = false;
expect(
(yield* proxy
.connect({ ...connect, grant: { ...local, key: "expired-local-key" } })
@@ -768,7 +1078,7 @@ it.effect(
instance: native,
});
yield* proxy.connect(connect);
- const configured = (yield* settings.getSettings).providerInstances[
+ let configured = (yield* settings.getSettings).providerInstances[
ProviderInstanceId.make("codex")
];
expect(configured).toMatchObject({
@@ -783,17 +1093,36 @@ it.effect(
],
inferenceHostLabel: "",
inferenceEnabled: true,
+ inferenceBaseUrl: "http://127.0.0.1:12345/api/inference/linked/codex/host",
},
});
expect((yield* proxy.status).routes).toEqual([{ instanceId: "codex", label: "Codex" }]);
expect(activeCodexConfig).toMatchObject({
setupMode: "inference",
homePath: expect.stringContaining("/providers/inference/codex"),
+ inferenceBaseUrl: "http://127.0.0.1:12345/api/inference/linked/codex/host",
+ });
+ if (!isInferenceProviderConfig(configured?.config))
+ throw new Error("Expected a local inference route");
+ expect(yield* proxy.health(local.key, hostId, "codex")).toMatchObject({
+ availableDrivers: ["codex"],
+ models: expect.arrayContaining(["codex-auto-review"]),
+ });
+ expect(yield* proxy.routeHealth(configured.config, local.key, "codex")).toMatchObject({
+ availableDrivers: expect.arrayContaining(["codex"]),
});
yield* proxy.bindRoutes(45678);
- expect(
- (yield* settings.getSettings).providerInstances[ProviderInstanceId.make("codex")],
- ).toEqual(configured);
+ configured = (yield* settings.getSettings).providerInstances[
+ ProviderInstanceId.make("codex")
+ ];
+ expect(configured?.config).toMatchObject({
+ inferenceBaseUrl: "http://127.0.0.1:45678/api/inference/linked/codex/host",
+ });
+ if (!isInferenceProviderConfig(configured?.config))
+ throw new Error("Expected a rebound inference route");
+ expect(yield* proxy.routeHealth(configured.config, local.key, "codex")).toMatchObject({
+ availableDrivers: expect.arrayContaining(["codex"]),
+ });
yield* settings.updateProviderInstance({
operation: "upsert",
instanceId: ProviderInstanceId.make("codex"),
@@ -839,7 +1168,38 @@ it.effect(
expect(
(yield* settings.getSettings).providerInstances[ProviderInstanceId.make("codex")]
?.config,
- ).toMatchObject({ inferenceBaseUrl: expect.stringContaining("192.168.1.12") });
+ ).toMatchObject({
+ inferenceBaseUrl: expect.stringContaining("/api/inference/linked/codex/host"),
+ });
+ expect((yield* proxy.authorize(issued.key, hostId, "codex"))?.baseUrl).toContain(
+ "192.168.1.12",
+ );
+ const directConfig = (yield* settings.getSettings).providerInstances[
+ ProviderInstanceId.make("codex")
+ ]?.config;
+ if (!isInferenceProviderConfig(directConfig))
+ throw new Error("Expected a direct inference route");
+ expect(yield* proxy.routeHealth(directConfig, issued.key, "codex")).toMatchObject({
+ availableDrivers: expect.arrayContaining(["codex"]),
+ });
+ tailnetCatalogDown = false;
+ connectionDown = true;
+ tailnetCatalogDown = true;
+ yield* proxy.connect({
+ ...connect,
+ grant: issued,
+ connection: { url: "https://pool.example.ts.net" },
+ });
+ expect(
+ (yield* settings.getSettings).providerInstances[ProviderInstanceId.make("codex")]
+ ?.config,
+ ).toMatchObject({
+ inferenceBaseUrl: expect.stringContaining("/api/inference/linked/codex/host"),
+ });
+ expect((yield* proxy.authorize(issued.key, hostId, "codex"))?.baseUrl).toContain(
+ "192.168.1.12",
+ );
+ connectionDown = false;
tailnetCatalogDown = false;
const linkedGrant = { ...issued, baseUrl: "t3-environment:host", alternates: [] };
expect(
@@ -851,10 +1211,10 @@ it.effect(
(yield* settings.getSettings).providerInstances[ProviderInstanceId.make("codex")]
?.config,
).toMatchObject({
- inferenceBaseUrl: expect.stringContaining("/api/inference/linked/host"),
+ inferenceBaseUrl: expect.stringContaining("/api/inference/linked/codex/host"),
});
expect(activeCodexConfig).toMatchObject({
- inferenceBaseUrl: expect.stringContaining("/api/inference/linked/host"),
+ inferenceBaseUrl: expect.stringContaining("/api/inference/linked/codex/host"),
});
yield* proxy.bindRoutes(45678);
expect(
@@ -862,10 +1222,11 @@ it.effect(
?.config,
).toMatchObject({
inferenceBaseUrl: expect.stringContaining(
- "127.0.0.1:45678/api/inference/linked/host",
+ "127.0.0.1:45678/api/inference/linked/codex/host",
),
});
expect(yield* proxy.authorize("wrong-key", hostId)).toBeNull();
+ expect(yield* proxy.authorize(issued.key, hostId, "claudeAgent")).toBeNull();
expect(yield* proxy.authorize(issued.key, hostId)).toEqual({
baseUrl: "http://127.0.0.1:23456/api/inference",
key: issued.key,
@@ -911,7 +1272,15 @@ it.effect(
.connect({
...connect,
grant: issued,
- connection: { url: "http://127.0.0.1:23456" },
+ connection: {
+ url: "http://127.0.0.1:23456",
+ ssh: {
+ alias: "host",
+ hostname: "host.local",
+ username: "user",
+ port: 22,
+ },
+ },
})
.pipe(Effect.flip)).message,
).toBe("SSH connection unavailable");
@@ -919,6 +1288,154 @@ it.effect(
const routes = (yield* proxy.status).routes;
expect(routes).toHaveLength(1);
peerId = EnvironmentId.make("other-host");
+ connectionDown = true;
+ const primaryCatalog = catalog;
+ catalog = [
+ { id: "codex-auto-review", owned_by: "openai" },
+ { id: "fallback-only", owned_by: "openai" },
+ ];
+ yield* proxy.registerFallback({
+ ...connect,
+ grant: {
+ ...issued,
+ hostId: peerId,
+ baseUrl: "https://fallback.example.ts.net/api/inference",
+ alternates: [],
+ },
+ });
+ catalog = primaryCatalog;
+ expect(
+ (yield* proxy.routeCandidates(issued.key, hostId, "codex", "codex-auto-review"))?.map(
+ (candidate) => candidate.hostId,
+ ),
+ ).toEqual([peerId]);
+ connectionDown = false;
+ yield* TestClock.adjust("15 seconds");
+ expect(
+ (yield* settings.getSettings).providerInstances[ProviderInstanceId.make("codex")]
+ ?.config,
+ ).toMatchObject({
+ inferenceHostId: hostId,
+ inferenceBaseUrl: expect.stringContaining("/api/inference/linked/codex/host"),
+ });
+ expect(
+ yield* proxy.routeCandidates(issued.key, hostId, "codex", "codex-auto-review"),
+ ).toHaveLength(2);
+ peerId = hostId;
+ yield* proxy.connect({ ...connect, grant: issued });
+ expect(yield* proxy.hasFallback(issued.key, hostId, "codex")).toBe(true);
+ expect(
+ (yield* settings.getSettings).providerInstances[ProviderInstanceId.make("codex")]
+ ?.config,
+ ).toMatchObject({
+ inferenceBaseUrl: expect.stringContaining("/api/inference/linked/codex/host"),
+ inferenceModels: expect.arrayContaining(["codex-auto-review", "fallback-only"]),
+ });
+ expect(
+ yield* proxy.routeCandidates(issued.key, hostId, "codex", "codex-auto-review"),
+ ).toHaveLength(2);
+ yield* proxy.recordRouteOutcome({
+ driver: "codex",
+ hostId,
+ model: "codex-auto-review",
+ status: 403,
+ });
+ expect(
+ (yield* proxy.routeCandidates(issued.key, hostId, "codex", "codex-auto-review"))?.map(
+ (candidate) => candidate.hostId,
+ ),
+ ).toEqual([EnvironmentId.make("other-host")]);
+ yield* proxy.recordRouteOutcome({
+ driver: "codex",
+ hostId,
+ model: "codex-auto-review",
+ status: 200,
+ });
+ expect(
+ yield* proxy.routeCandidates(issued.key, hostId, "codex", "codex-auto-review"),
+ ).toHaveLength(2);
+ yield* proxy.recordRouteOutcome({
+ driver: "codex",
+ hostId,
+ model: "codex-auto-review",
+ status: 429,
+ retryAfterMs: "1200000",
+ retryAfter: "60",
+ });
+ yield* TestClock.adjust("11 minutes");
+ expect(
+ (yield* proxy.routeCandidates(issued.key, hostId, "codex", "codex-auto-review"))?.map(
+ (candidate) => candidate.hostId,
+ ),
+ ).toEqual([EnvironmentId.make("other-host")]);
+ yield* proxy.recordRouteOutcome({
+ driver: "codex",
+ hostId,
+ model: "codex-auto-review",
+ status: 200,
+ });
+ const date = DateTime.toDateUtc(
+ DateTime.makeUnsafe((yield* Clock.currentTimeMillis) + 30 * 60_000),
+ ).toUTCString();
+ yield* proxy.recordRouteOutcome({
+ driver: "codex",
+ hostId,
+ model: "codex-auto-review",
+ status: 429,
+ retryAfterMs: " ",
+ retryAfter: date,
+ });
+ yield* TestClock.adjust("11 minutes");
+ expect(
+ (yield* proxy.routeCandidates(issued.key, hostId, "codex", "codex-auto-review"))?.map(
+ (candidate) => candidate.hostId,
+ ),
+ ).toEqual([EnvironmentId.make("other-host")]);
+ yield* proxy.recordRouteOutcome({
+ driver: "codex",
+ hostId,
+ model: "codex-auto-review",
+ status: 200,
+ });
+ yield* proxy.recordRouteOutcome({
+ driver: "codex",
+ hostId,
+ model: "codex-auto-review",
+ status: 429,
+ retryAfterMs: "-100",
+ retryAfter: "1200",
+ });
+ yield* TestClock.adjust("11 minutes");
+ expect(
+ (yield* proxy.routeCandidates(issued.key, hostId, "codex", "codex-auto-review"))?.map(
+ (candidate) => candidate.hostId,
+ ),
+ ).toEqual([EnvironmentId.make("other-host")]);
+ yield* proxy.recordRouteOutcome({
+ driver: "codex",
+ hostId,
+ model: "codex-auto-review",
+ status: 200,
+ });
+ yield* proxy.recordRouteOutcome({
+ driver: "codex",
+ hostId,
+ model: "codex-auto-review",
+ status: 429,
+ retryAfterMs: "-100",
+ retryAfter: "-1",
+ });
+ yield* TestClock.adjust("29 seconds");
+ expect(
+ (yield* proxy.routeCandidates(issued.key, hostId, "codex", "codex-auto-review"))?.map(
+ (candidate) => candidate.hostId,
+ ),
+ ).toEqual([EnvironmentId.make("other-host")]);
+ yield* TestClock.adjust("1 second");
+ expect(
+ yield* proxy.routeCandidates(issued.key, hostId, "codex", "codex-auto-review"),
+ ).toHaveLength(2);
+ peerId = EnvironmentId.make("other-host");
yield* proxy.connect({
...connect,
hostLabel: "Second",
@@ -989,7 +1506,12 @@ it.effect(
yield* proxy.manage({ operation: "revoke", environmentId: peer.environmentId });
expect(yield* proxy.authorize(grant.key)).toBeNull();
expect(yield* proxy.health(grant.key)).toBeNull();
- expect((yield* proxy.grant(peer)).key).not.toBe(grant.key);
+ expect(
+ yield* proxy.grant({ ...peer, automatic: true }).pipe(Effect.result),
+ ).toMatchObject({ _tag: "Failure" });
+ const restored = yield* proxy.grant(peer);
+ expect(restored.key).not.toBe(grant.key);
+ expect((yield* proxy.grant({ ...peer, automatic: true })).key).toBe(restored.key);
expectRecovery = true;
yield* Deferred.succeed(currentExit!, undefined);
yield* TestClock.adjust("1 second");
diff --git a/apps/server/src/inference/InferenceProxy.ts b/apps/server/src/inference/InferenceProxy.ts
index aa9c10156a8c4..da4b4c0007b9a 100644
--- a/apps/server/src/inference/InferenceProxy.ts
+++ b/apps/server/src/inference/InferenceProxy.ts
@@ -8,7 +8,9 @@ import {
INFERENCE_HARNESSES,
inferenceHarness,
InferenceConsumer,
+ type InferenceGrantInput,
InferenceRouteHealth,
+ InferenceDriver,
type InferenceProviderConfig,
InferenceHostConnection,
isInferenceProviderConfig,
@@ -29,6 +31,7 @@ import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
import { NetService } from "@t3tools/shared/Net";
import { readTailscaleServeRoutesTo } from "@t3tools/tailscale";
import * as SecureRandom from "effect/crypto/SecureRandom";
+import * as Cache from "effect/Cache";
import * as Digest from "effect/crypto/Digest";
import * as Schedule from "effect/Schedule";
import * as Duration from "effect/Duration";
@@ -64,15 +67,39 @@ import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
import { claudeKeychainEntry } from "./claudeKeychain.ts";
import { install, proxyVersion, resolveRelease, Release } from "./install.ts";
import * as PeerLinks from "../peer/PeerLinks.ts";
-import { modelsForDriver, openCodeRouteProblem, validateRouteUrl } from "./routes.ts";
+import {
+ modelsForDriver,
+ needsAccountModelLookup,
+ openCodeRouteProblem,
+ validateRouteUrl,
+} from "./routes.ts";
+import { makeCliproxyApi } from "../usage/cliproxyApi.ts";
+const SavedRouteCandidate = Schema.Struct({
+ hostId: EnvironmentId,
+ baseUrl: Schema.String,
+ key: Schema.String,
+ models: Schema.Array(Schema.String),
+ connection: Schema.optionalKey(InferenceHostConnection),
+});
+type SavedRouteCandidate = typeof SavedRouteCandidate.Type;
const Saved = Schema.Struct({
enabled: Schema.Boolean,
sharing: Schema.Boolean,
port: Schema.Int,
routing: Schema.optionalKey(InferenceRouting),
release: Schema.optionalKey(Release),
+ revokedConsumers: Schema.optionalKey(Schema.Array(EnvironmentId)),
grants: Schema.Array(Schema.Struct({ ...InferenceConsumer.fields, key: Schema.String })),
+ routePools: Schema.optionalKey(
+ Schema.Array(
+ Schema.Struct({
+ driver: InferenceDriver,
+ primary: SavedRouteCandidate,
+ alternates: Schema.Array(SavedRouteCandidate),
+ }),
+ ),
+ ),
// Local CLI sign-ins the user removed from the pool; the sync must not bring them back.
removedLocalAccounts: Schema.optionalKey(Schema.Array(Schema.String)),
});
@@ -82,12 +109,27 @@ const empty: Saved = { enabled: false, sharing: false, port: 0, grants: [] };
const Files = Schema.Struct({
files: Schema.Array(
Schema.Struct({
+ id: Schema.optionalKey(Schema.String),
+ auth_index: Schema.optionalKey(Schema.String),
name: Schema.String,
provider: Schema.String,
status: Schema.String,
disabled: Schema.optionalKey(Schema.Boolean),
unavailable: Schema.optionalKey(Schema.Boolean),
+ status_message: Schema.optionalKey(Schema.NullOr(Schema.String)),
+ next_retry_after: Schema.optionalKey(Schema.NullOr(Schema.String)),
runtime_only: Schema.optionalKey(Schema.Boolean),
+ cooldowns: Schema.optionalKey(
+ Schema.NullOr(
+ Schema.Array(
+ Schema.Struct({
+ scope: Schema.String,
+ model_key: Schema.optionalKey(Schema.String),
+ retry_at: Schema.String,
+ }),
+ ),
+ ),
+ ),
}),
),
});
@@ -97,6 +139,7 @@ const Models = Schema.Struct({
Schema.Struct({ id: Schema.String, owned_by: Schema.optional(Schema.String) }),
),
});
+const AccountModels = Schema.Struct({ models: Schema.Array(Schema.Struct({ id: Schema.String })) });
// Local CLI sign-ins T3 mirrors into the pool, keyed the way `removedLocalAccounts` records them.
const LOCAL_ACCOUNT_PREFIX: Partial> = {
codex: "codex:",
@@ -156,6 +199,45 @@ const isProxyClaudeAuth = Schema.is(ProxyClaudeAuth);
const isRecord = Schema.is(Schema.Record(Schema.String, Schema.Unknown));
const decodeUnknownJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
+function accountAvailability(account: (typeof Files.Type)["files"][number]) {
+ if (account.disabled) return "disabled" as const;
+ if (account.status === "active" && !account.unavailable) return "available" as const;
+ const reason = account.status_message ?? "";
+ if (
+ /\b(?:401|403)\b|auth(?:entication)?[_ -]?fail|invalid[_ -]?grant|invalid[_ -]?credential/i.test(
+ reason,
+ )
+ )
+ return "authenticationError" as const;
+ if (/\b(?:408|5\d\d)\b|service[_ -]?overloaded|overload|transient/i.test(reason))
+ return "unavailable" as const;
+ if (/\b429\b|rate[_ -]?limit|quota|exhausted/i.test(reason)) return "rateLimited" as const;
+ return "unavailable" as const;
+}
+
+interface ClaudeUsageCacheKey {
+ readonly baseUrl: string;
+ readonly management: string;
+ readonly id: string;
+ readonly authIndex: string;
+}
+interface AccountModelsCacheKey {
+ readonly baseUrl: string;
+ readonly management: string;
+ readonly id: string;
+}
+
+function availableDrivers(files: (typeof Files.Type)["files"]) {
+ const available = files.filter(
+ (account) => account.status === "active" && !account.disabled && !account.unavailable,
+ );
+ return INFERENCE_DRIVERS.filter((driver) =>
+ available.some(
+ (account) => INFERENCE_HARNESSES[driver].accounts?.includes(account.provider) ?? true,
+ ),
+ );
+}
+
function jwtClaims(token: string): Record | null {
const payload = token.split(".")[1];
if (!payload) return null;
@@ -238,6 +320,55 @@ const make = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serviceScope = yield* Scope.Scope;
+ const cliproxy = yield* makeCliproxyApi;
+ const quotaSemaphore = yield* Semaphore.make(4);
+ const claudeUsageCache = yield* Cache.make({
+ capacity: 128,
+ timeToLive: "30 seconds",
+ lookup: Effect.fn("InferenceProxy.readClaudeUsage")(function* (key: ClaudeUsageCacheKey) {
+ return yield* cliproxy
+ .readClaudeUsage(
+ { url: key.baseUrl, managementKey: key.management },
+ { id: key.id, auth_index: key.authIndex },
+ )
+ .pipe(
+ quotaSemaphore.withPermits(1),
+ Effect.orElseSucceed(() => undefined),
+ );
+ }),
+ });
+ const modelLookupSemaphore = yield* Semaphore.make(4);
+ const accountModelsCache = yield* Cache.make({
+ capacity: 128,
+ timeToLive: "30 seconds",
+ lookup: Effect.fn("InferenceProxy.readAccountModels")(function* (key: AccountModelsCacheKey) {
+ return yield* jsonRequest(
+ key.baseUrl + "/v0/management/auth-files/models?name=" + encodeURIComponent(key.id),
+ key.management,
+ AccountModels,
+ ).pipe(
+ modelLookupSemaphore.withPermits(1),
+ Effect.orElseSucceed(() => undefined),
+ );
+ }),
+ });
+ const cachedResults = Effect.fn("InferenceProxy.cachedResults")(function* (
+ cache: Cache.Cache,
+ keys: readonly K[],
+ wait?: Duration.Input,
+ ) {
+ yield* Effect.forEach(keys, (key) =>
+ Effect.gen(function* () {
+ if (!(yield* Cache.has(cache, key)))
+ yield* Cache.get(cache, key).pipe(Effect.ignore, Effect.forkIn(serviceScope));
+ }),
+ );
+ if (wait !== undefined && keys.length)
+ yield* Effect.forEach(keys, (key) => Cache.get(cache, key), {
+ concurrency: "unbounded",
+ }).pipe(Effect.timeout(wait), Effect.ignore);
+ return yield* Effect.forEach(keys, (key) => Cache.getSuccess(cache, key));
+ });
const net = yield* NetService;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const store = yield* ServerSecretStore.ServerSecretStore;
@@ -276,6 +407,7 @@ const make = Effect.gen(function* () {
let cached: Saved | undefined;
let proxyAccountWatch: Fiber.Fiber | undefined;
let lastRequestSync = Number.NEGATIVE_INFINITY;
+ const routeFailures = new Map();
let running:
| {
child: ChildProcessSpawner.ChildProcessHandle;
@@ -285,6 +417,59 @@ const make = Effect.gen(function* () {
management: string;
}
| undefined;
+ const claudeUsageEvidence = Effect.fn("InferenceProxy.claudeUsageEvidence")(function* (
+ runtime: NonNullable,
+ files: (typeof Files.Type)["files"],
+ waitForUsage: boolean,
+ ) {
+ const eligible = files
+ .filter(
+ (file) =>
+ file.provider === "claude" &&
+ file.status === "active" &&
+ !file.disabled &&
+ !file.unavailable &&
+ !file.runtime_only &&
+ !!file.id &&
+ !!file.auth_index,
+ )
+ .slice(0, 128);
+ const keys: ClaudeUsageCacheKey[] = eligible.map((file) => ({
+ baseUrl: runtime.baseUrl,
+ management: runtime.management,
+ id: file.id!,
+ authIndex: file.auth_index!,
+ }));
+ const results = yield* cachedResults(
+ claudeUsageCache,
+ keys,
+ waitForUsage ? "2 seconds" : undefined,
+ );
+ const now = yield* Clock.currentTimeMillis;
+ const evidence = new Map();
+ for (const [index, file] of eligible.entries()) {
+ const cached = results[index]!;
+ if (Option.isNone(cached) || !cached.value || cached.value.unavailable) continue;
+ if (
+ cached.value.windows.some(
+ (window) => window.id === "monthly_spend" && window.usedPercent < 100,
+ )
+ )
+ continue;
+ const resets = cached.value.windows
+ .filter(
+ (window) =>
+ (window.id === "five_hour" || window.id === "seven_day") &&
+ window.usedPercent >= 100 &&
+ window.resetsAt &&
+ Date.parse(window.resetsAt) > now,
+ )
+ .map((window) => Date.parse(window.resetsAt!));
+ if (resets.length)
+ evidence.set(file.name, DateTime.formatIso(DateTime.makeUnsafe(Math.max(...resets))));
+ }
+ return evidence;
+ });
const read = Effect.gen(function* () {
if (cached) return cached;
const raw = yield* store.get("inference-proxy-state");
@@ -816,13 +1001,14 @@ const make = Effect.gen(function* () {
];
}),
routing: state.routing ?? defaultInferenceRouting,
+ availableDrivers: [],
version: state.release?.version ?? proxyVersion,
enabled: state.enabled,
sharing: state.sharing,
consumers: state.grants.map(({ environmentId, label }) => ({ environmentId, label })),
};
if (!state.enabled)
- return { ...summary, running: false, accounts: [], problem: routeProblem };
+ return { status: { ...summary, running: false, accounts: [], problem: routeProblem } };
return yield* Effect.gen(function* () {
const runtime = yield* ensureWatched(state);
const sync = yield* syncLocalAuth(runtime);
@@ -832,25 +1018,60 @@ const make = Effect.gen(function* () {
Files,
);
return {
- ...summary,
- running: true,
- accounts: files
- .filter((file) => !file.runtime_only)
- .map(({ name, provider, status }) => ({ name, provider, status })),
- problem: routeProblem ?? sync.problem,
+ status: { ...summary, running: true, problem: routeProblem ?? sync.problem },
+ runtime,
+ files,
};
}).pipe(
Effect.orElseSucceed((e) => ({
- ...summary,
- running: false,
- accounts: [],
- problem: safeFailure("CLIProxyAPI failed to start. Check its port or retry hosting.")(e)
- .message,
+ status: {
+ ...summary,
+ running: false,
+ accounts: [],
+ problem: safeFailure("CLIProxyAPI failed to start. Check its port or retry hosting.")(
+ e,
+ ).message,
+ },
})),
);
}),
)
- .pipe(Effect.mapError(safeFailure("Could not read inference host settings.")));
+ .pipe(
+ Effect.flatMap((snapshot) =>
+ Effect.gen(function* () {
+ if (!("files" in snapshot)) return snapshot.status;
+ const evidence = yield* claudeUsageEvidence(snapshot.runtime, snapshot.files, true);
+ const now = yield* Clock.currentTimeMillis;
+ return {
+ ...snapshot.status,
+ availableDrivers: availableDrivers(
+ snapshot.files.filter((file) => !evidence.has(file.name)),
+ ),
+ accounts: snapshot.files
+ .filter((file) => !file.runtime_only)
+ .map((file) => {
+ const availability = accountAvailability(file);
+ const retryAfter =
+ availability === "available" ? evidence.get(file.name) : undefined;
+ return {
+ name: file.name,
+ provider: file.provider,
+ status: file.status,
+ availability: retryAfter ? ("rateLimited" as const) : availability,
+ ...(retryAfter
+ ? { retryAfter }
+ : availability === "rateLimited" &&
+ file.next_retry_after &&
+ Date.parse(file.next_retry_after) > now
+ ? { retryAfter: file.next_retry_after }
+ : {}),
+ };
+ }),
+ };
+ }),
+ ),
+ Effect.mapError(safeFailure("Could not read inference host settings.")),
+ );
const sharingUrls = Effect.gen(function* () {
const active = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath).pipe(
@@ -1004,12 +1225,20 @@ const make = Effect.gen(function* () {
yield* registry.reconcile(
deriveProviderInstanceConfigMap(revised.settings, providerEnvironment),
);
+ yield* save({
+ ...state,
+ routePools: (state.routePools ?? []).filter(
+ (entry) =>
+ defaultInstanceIdForDriver(ProviderDriverKind.make(entry.driver)) !== input.instanceId,
+ ),
+ });
return {};
}
if (input.operation === "revoke") {
yield* save({
...state,
grants: state.grants.filter((g) => g.environmentId !== input.environmentId),
+ revokedConsumers: [...new Set([...(state.revokedConsumers ?? []), input.environmentId])],
});
return {};
}
@@ -1112,7 +1341,7 @@ const make = Effect.gen(function* () {
);
const grant = Effect.fn("InferenceProxy.grant")(
- function* (consumer: InferenceConsumer) {
+ function* ({ automatic, ...consumer }: InferenceGrantInput) {
const state = yield* read;
const runtime = yield* ensureWatched(state);
const hostId = yield* environment.getEnvironmentId;
@@ -1121,12 +1350,19 @@ const make = Effect.gen(function* () {
return { ...identity, baseUrl: runtime.baseUrl, key: runtime.key };
if (sharingDenial) return yield* failure(sharingDenial);
if (!state.sharing) return yield* failure("Enable sharing on the inference host first.");
+ if (automatic && state.revokedConsumers?.includes(consumer.environmentId))
+ return yield* failure(
+ "Sharing with this environment was revoked. Choose the host again to restore it.",
+ );
const [baseUrl, ...alternates] = (yield* sharingUrls).slice(0, 33);
const existing = state.grants.find((g) => g.environmentId === consumer.environmentId);
const key = existing?.key ?? (yield* newKey);
if (!existing || existing.label !== consumer.label)
yield* save({
...state,
+ revokedConsumers: (state.revokedConsumers ?? []).filter(
+ (id) => id !== consumer.environmentId,
+ ),
grants: [
...state.grants.filter((g) => g.environmentId !== consumer.environmentId),
{ ...consumer, key },
@@ -1141,15 +1377,66 @@ const make = Effect.gen(function* () {
const bindRoutes = Effect.fn("InferenceProxy.bindRoutes")(
function* (port: number) {
const { providerInstances } = yield* settings.getSettings;
+ const state = yield* read;
+ const routePools = [...(state.routePools ?? [])];
+ const bindings: {
+ id: string;
+ driver: InferenceDriver;
+ hostId: EnvironmentId;
+ key: string;
+ baseUrl: string;
+ }[] = [];
+ let poolsChanged = false;
for (const [id, instance] of Object.entries(providerInstances)) {
if (!isInferenceProviderConfig(instance.config)) continue;
- yield* settings.reviseProviderInstance(ProviderInstanceId.make(id), (current) => {
- if (!current || !isInferenceProviderConfig(current.config))
+ const driver = INFERENCE_DRIVERS.find(
+ (candidate) => ProviderDriverKind.make(candidate) === instance.driver,
+ );
+ if (!driver || id !== defaultInstanceIdForDriver(ProviderDriverKind.make(driver))) continue;
+ const config = instance.config;
+ if (typeof config.inferenceKey !== "string") continue;
+ bindings.push({
+ id,
+ driver,
+ hostId: config.inferenceHostId,
+ key: config.inferenceKey,
+ baseUrl: config.inferenceBaseUrl,
+ });
+ const index = routePools.findIndex((entry) => entry.driver === driver);
+ if (
+ index < 0 ||
+ routePools[index]!.primary.hostId !== config.inferenceHostId ||
+ routePools[index]!.primary.key !== config.inferenceKey
+ ) {
+ const pool = {
+ driver,
+ primary: {
+ hostId: config.inferenceHostId,
+ baseUrl: config.inferenceBaseUrl,
+ key: config.inferenceKey,
+ models: [...config.inferenceModels],
+ ...(config.inferenceConnection ? { connection: config.inferenceConnection } : {}),
+ },
+ alternates: [],
+ };
+ if (index < 0) routePools.push(pool);
+ else routePools[index] = pool;
+ poolsChanged = true;
+ }
+ }
+ if (poolsChanged) yield* save({ ...state, routePools });
+ for (const binding of bindings) {
+ const url = `http://127.0.0.1:${port}/api/inference/linked/${binding.driver}/${encodeURIComponent(binding.hostId)}`;
+ if (binding.baseUrl === url) continue;
+ yield* settings.reviseProviderInstance(ProviderInstanceId.make(binding.id), (current) => {
+ if (
+ !current ||
+ current.driver !== ProviderDriverKind.make(binding.driver) ||
+ !isInferenceProviderConfig(current.config) ||
+ current.config.inferenceHostId !== binding.hostId ||
+ current.config.inferenceKey !== binding.key
+ )
return failure("The inference route changed.");
- const url = current.config.inferenceBaseUrl.replace(
- /^http:\/\/127\.0\.0\.1:\d+(\/api\/inference\/linked\/)/,
- `http://127.0.0.1:${port}$1`,
- );
return Effect.succeed({
instance: { ...current, config: { ...current.config, inferenceBaseUrl: url } },
result: undefined,
@@ -1184,14 +1471,181 @@ const make = Effect.gen(function* () {
);
});
+ const candidateAddress = Effect.fn("InferenceProxy.candidateAddress")(function* (
+ candidate: SavedRouteCandidate,
+ ownId: EnvironmentId,
+ ) {
+ if (candidate.hostId === ownId)
+ return (yield* mutex.withPermit(read.pipe(Effect.flatMap(ensureWatched)))).baseUrl;
+ if (candidate.connection || !validateRouteUrl(candidate.baseUrl, false))
+ return new URL("/api/inference", yield* peerAddress(candidate.hostId, candidate.connection))
+ .href;
+ const peer = yield* jsonRequest(
+ new URL("/.well-known/t3/environment", candidate.baseUrl).href,
+ undefined,
+ Peer,
+ );
+ if (peer.environmentId !== candidate.hostId)
+ return yield* failure("The inference address belongs to another environment.");
+ return candidate.baseUrl;
+ });
+
+ const routeProbes = yield* Cache.make({
+ capacity: 64,
+ timeToLive: "15 seconds",
+ lookup: Effect.fn("InferenceProxy.probeRoute")(
+ function* (input: { candidate: SavedRouteCandidate; driver: InferenceDriver }) {
+ const ownId = yield* environment.getEnvironmentId;
+ const baseUrl = yield* candidateAddress(input.candidate, ownId);
+ const health =
+ input.candidate.hostId === ownId
+ ? yield* mutex.withPermit(localHealth())
+ : yield* jsonRequest(baseUrl + "/health", input.candidate.key, InferenceRouteHealth);
+ const models = input.candidate.models.filter((model) => health.models.includes(model));
+ return health.availableDrivers.includes(input.driver) && models.length
+ ? { baseUrl, key: input.candidate.key, models }
+ : undefined;
+ },
+ Effect.timeout("3 seconds"),
+ Effect.orElseSucceed(() => undefined),
+ ),
+ });
+
+ const hasFallback = Effect.fn("InferenceProxy.hasFallback")(
+ function* (key: string, hostId: EnvironmentId | undefined, driver: string | undefined) {
+ if (!hostId || !driver) return false;
+ const instanceId = defaultInstanceIdForDriver(ProviderDriverKind.make(driver));
+ const instance = (yield* settings.getSettings).providerInstances[instanceId];
+ if (
+ !instance ||
+ !isInferenceProviderConfig(instance.config) ||
+ !instance.config.inferenceEnabled ||
+ instance.config.inferenceHostId !== hostId ||
+ instance.config.inferenceKey !== key
+ )
+ return false;
+ return (
+ (yield* read).routePools?.some(
+ (entry) =>
+ entry.driver === driver &&
+ entry.primary.hostId === hostId &&
+ entry.primary.key === key &&
+ entry.alternates.length > 0,
+ ) ?? false
+ );
+ },
+ Effect.mapError(safeFailure("Could not inspect inference routes.")),
+ );
+
+ const routeCandidates = Effect.fn("InferenceProxy.routeCandidates")(
+ function* (
+ key: string,
+ hostId?: EnvironmentId,
+ driver?: string,
+ model?: string,
+ includeAll = false,
+ ) {
+ if (hostId === undefined) {
+ const target = yield* authorize(key);
+ return target ? [{ ...target, models: [] }] : null;
+ }
+ const { providerInstances } = yield* settings.getSettings;
+ const active = INFERENCE_DRIVERS.map((candidateDriver) => ({
+ driver: candidateDriver,
+ instance:
+ providerInstances[defaultInstanceIdForDriver(ProviderDriverKind.make(candidateDriver))],
+ })).find(
+ ({ driver: candidateDriver, instance }) =>
+ (driver === undefined || candidateDriver === driver) &&
+ instance?.enabled !== false &&
+ isInferenceProviderConfig(instance?.config) &&
+ instance.config.inferenceEnabled &&
+ instance.config.inferenceHostId === hostId &&
+ instance.config.inferenceKey === key,
+ );
+ if (!active || !isInferenceProviderConfig(active.instance?.config)) return null;
+ const route = active.instance.config;
+ const pool = (yield* read).routePools?.find((entry) => entry.driver === active.driver);
+ if (!pool || pool.primary.hostId !== hostId || pool.primary.key !== key) {
+ const target = yield* authorize(key, hostId, driver);
+ return target ? [{ ...target, models: route.inferenceModels }] : null;
+ }
+ const matching = model
+ ? [pool.primary, ...pool.alternates].filter((candidate) => candidate.models.includes(model))
+ : includeAll
+ ? [pool.primary, ...pool.alternates]
+ : [pool.primary];
+ const candidates = yield* Effect.forEach(
+ matching.length ? matching : [pool.primary],
+ (candidate) => Cache.get(routeProbes, { candidate, driver: active.driver }),
+ { concurrency: "unbounded" },
+ );
+ const now = yield* Clock.currentTimeMillis;
+ const available = candidates.flatMap((candidate, index) => {
+ if (!candidate) return [];
+ const host = (matching.length ? matching : [pool.primary])[index]!;
+ const models = candidate.models.filter(
+ (slug) => (routeFailures.get(`${active.driver}\0${host.hostId}\0${slug}`) ?? 0) <= now,
+ );
+ return models.length && (model === undefined || models.includes(model))
+ ? [{ ...candidate, hostId: host.hostId, models }]
+ : [];
+ });
+ return available;
+ },
+ Effect.mapError(safeFailure("Could not resolve inference hosts.")),
+ );
+
+ const recordRouteOutcome = Effect.fn("InferenceProxy.recordRouteOutcome")(function* (input: {
+ driver: string;
+ hostId: EnvironmentId;
+ model: string;
+ status: number;
+ retryAfter?: string;
+ retryAfterMs?: string;
+ }) {
+ const key = `${input.driver}\0${input.hostId}\0${input.model}`;
+ if (input.status >= 200 && input.status < 300) {
+ routeFailures.delete(key);
+ return;
+ }
+ if (![401, 403, 429, 502, 503].includes(input.status)) return;
+ const now = yield* Clock.currentTimeMillis;
+ const numericDelay = (value: string | undefined, scale: number) => {
+ if (!value?.trim()) return undefined;
+ const amount = Number(value);
+ if (!Number.isFinite(amount) || amount < 0) return undefined;
+ const delay = amount * scale;
+ return Number.isSafeInteger(Math.ceil(delay)) ? Math.ceil(delay) : undefined;
+ };
+ const millis = numericDelay(input.retryAfterMs, 1);
+ const seconds = input.retryAfter?.trim() ? Number(input.retryAfter) : Number.NaN;
+ const standard = Number.isFinite(seconds)
+ ? numericDelay(input.retryAfter, 1000)
+ : input.retryAfter
+ ? Date.parse(input.retryAfter) - now
+ : undefined;
+ const retryDelay =
+ millis ??
+ (standard !== undefined && Number.isFinite(standard) && standard >= 0 ? standard : undefined);
+ const duration =
+ input.status === 429 && retryDelay !== undefined
+ ? Math.max(5_000, Math.min(retryDelay, Number.MAX_SAFE_INTEGER - now))
+ : input.status === 502 || input.status === 503
+ ? 5_000
+ : 30_000;
+ routeFailures.set(key, now + duration);
+ });
+
const authorize = Effect.fn("InferenceProxy.authorize")(
- function* (key: string, hostId?: EnvironmentId) {
+ function* (key: string, hostId?: EnvironmentId, driver?: string) {
if (hostId !== undefined) {
const { providerInstances } = yield* settings.getSettings;
- const allowed = INFERENCE_DRIVERS.map((driver) => {
+ const allowed = INFERENCE_DRIVERS.map((candidateDriver) => {
const instance =
- providerInstances[defaultInstanceIdForDriver(ProviderDriverKind.make(driver))];
- return instance?.enabled &&
+ providerInstances[defaultInstanceIdForDriver(ProviderDriverKind.make(candidateDriver))];
+ return (driver === undefined || candidateDriver === driver) &&
+ instance?.enabled &&
isInferenceProviderConfig(instance.config) &&
instance.config.inferenceEnabled &&
instance.config.inferenceHostId === hostId &&
@@ -1200,6 +1654,17 @@ const make = Effect.gen(function* () {
: undefined;
}).find((config) => config !== undefined);
if (!allowed) return null;
+ const pool = (yield* read).routePools?.find(
+ (entry) =>
+ (driver === undefined || entry.driver === driver) &&
+ entry.primary.hostId === hostId &&
+ entry.primary.key === key,
+ );
+ if (pool)
+ return {
+ baseUrl: yield* candidateAddress(pool.primary, yield* environment.getEnvironmentId),
+ key,
+ };
const address = yield* peerAddress(hostId, allowed.inferenceConnection);
return { baseUrl: new URL("/api/inference", address).href, key };
}
@@ -1238,22 +1703,65 @@ const make = Effect.gen(function* () {
],
{ concurrency: "unbounded" },
);
- const available = files.filter(
- (account) => account.status === "active" && !account.disabled && !account.unavailable,
- );
+ const evidence = yield* claudeUsageEvidence(runtime, files, false);
+ const now = yield* Clock.currentTimeMillis;
+ const excludedNames = new Set(evidence.keys());
+ const registeredModels = new Map();
+ if (needsAccountModelLookup(files, excludedNames, now)) {
+ const eligible = files
+ .filter(
+ (file) =>
+ file.status === "active" &&
+ !file.disabled &&
+ !file.unavailable &&
+ !excludedNames.has(file.name),
+ )
+ .slice(0, 128);
+ const keys: AccountModelsCacheKey[] = eligible.map((file) => ({
+ baseUrl: runtime.baseUrl,
+ management: runtime.management,
+ id: file.id || file.name,
+ }));
+ const results = yield* cachedResults(accountModelsCache, keys, "500 millis");
+ for (const [index, file] of eligible.entries()) {
+ const cached = results[index]!;
+ if (Option.isSome(cached) && cached.value)
+ registeredModels.set(
+ file.id || file.name,
+ cached.value.models.map((model) => model.id),
+ );
+ }
+ }
return {
- availableDrivers: INFERENCE_DRIVERS.filter((driver) =>
- available.some(
- (account) => INFERENCE_HARNESSES[driver].accounts?.includes(account.provider) ?? true,
- ),
- ),
- models: data.map((model) => model.id),
+ availableDrivers: availableDrivers(files.filter((file) => !evidence.has(file.name))),
+ models: modelsForDriver(data, "opencode", {
+ accounts: files,
+ excludedNames,
+ registeredModels,
+ now,
+ }),
};
});
const health = Effect.fn("InferenceProxy.health")(
- function* (key: string, hostId?: EnvironmentId) {
- const target = yield* authorize(key, hostId);
+ function* (key: string, hostId?: EnvironmentId, driver?: string) {
+ const pool = hostId
+ ? (yield* read).routePools?.find(
+ (entry) =>
+ (driver === undefined || entry.driver === driver) &&
+ entry.primary.hostId === hostId &&
+ entry.primary.key === key,
+ )
+ : undefined;
+ if (pool) {
+ const candidates = yield* routeCandidates(key, hostId, pool.driver, undefined, true);
+ if (candidates === null) return null;
+ return {
+ availableDrivers: candidates.length ? [pool.driver] : [],
+ models: [...new Set(candidates.flatMap((candidate) => candidate.models))],
+ };
+ }
+ const target = yield* authorize(key, hostId, driver);
if (!target) return null;
return hostId === undefined
? yield* mutex.withPermit(localHealth())
@@ -1263,7 +1771,28 @@ const make = Effect.gen(function* () {
);
const routeHealth = Effect.fn("InferenceProxy.routeHealth")(
- function* (route: InferenceProviderConfig, key: string) {
+ function* (route: InferenceProviderConfig, key: string, driver?: string) {
+ const pool = (yield* read).routePools?.find(
+ (entry) =>
+ (driver === undefined || entry.driver === driver) &&
+ entry.primary.hostId === route.inferenceHostId &&
+ entry.primary.key === key,
+ );
+ if (pool?.alternates.length) {
+ const candidates = yield* routeCandidates(
+ key,
+ route.inferenceHostId,
+ pool.driver,
+ undefined,
+ true,
+ );
+ if (!candidates?.length)
+ return yield* failure("No authorized inference host is available.");
+ return {
+ availableDrivers: [pool.driver],
+ models: [...new Set(candidates.flatMap((candidate) => candidate.models))],
+ };
+ }
const ownId = yield* environment.getEnvironmentId;
if (route.inferenceHostId === ownId) {
return yield* mutex.withPermit(
@@ -1271,7 +1800,7 @@ const make = Effect.gen(function* () {
const state = yield* read;
if (!state.enabled) return yield* failure("Inference hosting is disabled.");
const runtime = yield* ensureWatched(state);
- if (runtime.baseUrl !== route.inferenceBaseUrl || runtime.key !== key)
+ if (runtime.key !== key)
return yield* failure(
"Inference route credentials have changed. Connect the route again.",
);
@@ -1279,8 +1808,9 @@ const make = Effect.gen(function* () {
}),
);
}
- const address =
- route.inferenceConnection || route.inferenceBaseUrl.includes("/api/inference/linked/")
+ const address = pool
+ ? yield* candidateAddress(pool.primary, ownId)
+ : route.inferenceConnection || route.inferenceBaseUrl.includes("/api/inference/linked/")
? new URL(
"/api/inference",
yield* peerAddress(route.inferenceHostId, route.inferenceConnection),
@@ -1292,7 +1822,7 @@ const make = Effect.gen(function* () {
);
const connect = Effect.fn("InferenceProxy.connect")(
- function* ({ grant, driver, hostLabel, connection }: InferenceRouteInput) {
+ function* ({ grant, driver, hostLabel, connection }: InferenceRouteInput, fallback = false) {
const id = yield* environment.getEnvironmentId;
if (id !== grant.consumerId)
return yield* failure("Invalid inference route for this environment.");
@@ -1306,11 +1836,16 @@ const make = Effect.gen(function* () {
const resolved = local
? Result.succeed(undefined)
: yield* peerAddress(grant.hostId, connection).pipe(Effect.result);
- if ((environmentRoute || connection) && Result.isFailure(resolved))
+ if ((environmentRoute || connection?.ssh) && Result.isFailure(resolved))
return yield* resolved.failure;
const peer = Result.isSuccess(resolved) ? resolved.success : undefined;
- const linked = peer !== undefined;
- const addresses = peer ? [new URL("/api/inference", peer).href] : candidates;
+ const peerUrl = peer ? new URL("/api/inference", peer).href : undefined;
+ const addresses = [
+ ...new Set([
+ ...(peerUrl ? [peerUrl] : []),
+ ...(environmentRoute || connection?.ssh ? [] : candidates),
+ ]),
+ ];
if (local) {
const runtime = yield* mutex.withPermit(read.pipe(Effect.flatMap(ensure)));
if (runtime.baseUrl !== grant.baseUrl || runtime.key !== grant.key)
@@ -1319,7 +1854,7 @@ const make = Effect.gen(function* () {
const { baseUrl, data } = yield* Effect.firstSuccessOf(
addresses.map((url) =>
Effect.gen(function* () {
- if (!local && !peer) {
+ if (!local && url !== peerUrl) {
const peer = yield* jsonRequest(
new URL("/.well-known/t3/environment", url).href,
undefined,
@@ -1333,61 +1868,178 @@ const make = Effect.gen(function* () {
}),
),
);
+ const health = local
+ ? yield* mutex.withPermit(localHealth())
+ : yield* jsonRequest(baseUrl + "/health", grant.key, InferenceRouteHealth);
+ if (!health.availableDrivers.includes(driver))
+ return yield* failure("The inference host has no available accounts for this provider.");
const models = modelsForDriver(data, driver);
if (!models.length)
return yield* failure("Sign in to an account for this provider on the host, then retry.");
const instanceId = defaultInstanceIdForDriver(ProviderDriverKind.make(driver));
- const active = linked
- ? yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath).pipe(
- Effect.provideService(FileSystem.FileSystem, fs),
- )
- : Option.none();
+ const linked = baseUrl === peerUrl;
+ const active = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath).pipe(
+ Effect.provideService(FileSystem.FileSystem, fs),
+ );
const port = Option.isSome(active) ? active.value.port : config.port;
- const routeUrl = linked
- ? `http://127.0.0.1:${port}/api/inference/linked/${encodeURIComponent(grant.hostId)}`
- : baseUrl;
+ const loopbackUrl = (host: EnvironmentId) =>
+ `http://127.0.0.1:${port}/api/inference/linked/${driver}/${encodeURIComponent(host)}`;
+ const candidate: SavedRouteCandidate = {
+ hostId: grant.hostId,
+ baseUrl,
+ key: grant.key,
+ models,
+ ...(linked && connection ? { connection } : {}),
+ };
+ if (fallback) {
+ const revised = yield* mutex.withPermit(
+ Effect.gen(function* () {
+ const configured = (yield* settings.getSettings).providerInstances[instanceId];
+ if (
+ !configured ||
+ configured.enabled === false ||
+ !isInferenceProviderConfig(configured.config) ||
+ !configured.config.inferenceEnabled
+ )
+ return undefined;
+ const primaryRoute = configured.config;
+ if (primaryRoute.inferenceHostId === grant.hostId) return undefined;
+ if (typeof primaryRoute.inferenceKey !== "string")
+ return yield* failure("The primary inference credential is unavailable.");
+ const primaryKey = primaryRoute.inferenceKey;
+ const state = yield* read;
+ const existing = state.routePools?.find((entry) => entry.driver === driver);
+ const primary: SavedRouteCandidate =
+ existing?.primary.hostId === primaryRoute.inferenceHostId &&
+ existing.primary.key === primaryKey
+ ? existing.primary
+ : {
+ hostId: primaryRoute.inferenceHostId,
+ baseUrl: primaryRoute.inferenceBaseUrl,
+ key: primaryKey,
+ models: [...primaryRoute.inferenceModels],
+ ...(primaryRoute.inferenceConnection
+ ? { connection: primaryRoute.inferenceConnection }
+ : {}),
+ };
+ const alternates = [
+ ...(existing?.alternates ?? []).filter((entry) => entry.hostId !== grant.hostId),
+ candidate,
+ ];
+ yield* save({
+ ...state,
+ routePools: [
+ ...(state.routePools ?? []).filter((entry) => entry.driver !== driver),
+ { driver, primary, alternates },
+ ],
+ });
+ return yield* settings
+ .reviseProviderInstance(instanceId, (current) => {
+ if (
+ !current ||
+ current.enabled === false ||
+ !isInferenceProviderConfig(current.config) ||
+ !current.config.inferenceEnabled ||
+ current.config.inferenceHostId !== primaryRoute.inferenceHostId ||
+ current.config.inferenceKey !== primaryKey
+ )
+ return failure("The inference route changed.");
+ return Effect.succeed({
+ instance: {
+ ...current,
+ config: {
+ ...current.config,
+ inferenceBaseUrl: loopbackUrl(primary.hostId),
+ inferenceModels: [
+ ...new Set([primary, ...alternates].flatMap((entry) => entry.models)),
+ ],
+ },
+ },
+ result: undefined,
+ });
+ })
+ .pipe(Effect.onError(() => save(state).pipe(Effect.orDie)));
+ }),
+ );
+ if (!revised) return;
+ yield* registry.reconcile(
+ deriveProviderInstanceConfigMap(revised.settings, providerEnvironment),
+ );
+ return;
+ }
const home = path.join(config.stateDir, "providers", "inference", instanceId);
yield* fs.makeDirectory(home, { recursive: true, mode: 0o700 });
- const revised = yield* settings.reviseProviderInstance(instanceId, (current) => {
- const problem =
- driver === "opencode"
- ? openCodeRouteProblem(
- current?.environment,
- providerEnvironment.OPENCODE_CONFIG_CONTENT,
- )
- : null;
- if (problem) return failure(problem);
- const native = current ?? { driver: ProviderDriverKind.make(driver), config: {} };
- const { inferenceConnection: _previousConnection, ...nativeConfig } = providerConfig(
- native.config,
- )
- ? native.config
- : {};
- return Effect.succeed({
- instance: {
- ...native,
- enabled: true,
- config: {
- ...nativeConfig,
- inferenceEnabled: true,
- inferenceHostId: grant.hostId,
- inferenceHostLabel: local ? "" : hostLabel,
- inferenceBaseUrl: routeUrl,
- inferenceKey: grant.key,
- inferenceModels: models,
- inferenceHomePath: home,
- ...(linked && connection ? { inferenceConnection: connection } : {}),
- },
- },
- result: undefined,
- });
- });
+ const revised = yield* mutex.withPermit(
+ Effect.gen(function* () {
+ const state = yield* read;
+ const existing = state.routePools?.find((entry) => entry.driver === driver);
+ const updated = yield* settings.reviseProviderInstance(instanceId, (current) => {
+ const problem =
+ driver === "opencode"
+ ? openCodeRouteProblem(
+ current?.environment,
+ providerEnvironment.OPENCODE_CONFIG_CONTENT,
+ )
+ : null;
+ if (problem) return failure(problem);
+ const native = current ?? { driver: ProviderDriverKind.make(driver), config: {} };
+ const { inferenceConnection: _previousConnection, ...nativeConfig } = providerConfig(
+ native.config,
+ )
+ ? native.config
+ : {};
+ const preserve =
+ existing?.primary.hostId === grant.hostId &&
+ current?.enabled !== false &&
+ isInferenceProviderConfig(current?.config) &&
+ current.config.inferenceEnabled &&
+ current.config.inferenceHostId === grant.hostId &&
+ current.config.inferenceKey === existing.primary.key;
+ const alternates = preserve ? existing.alternates : [];
+ return Effect.succeed({
+ instance: {
+ ...native,
+ enabled: true,
+ config: {
+ ...nativeConfig,
+ inferenceEnabled: true,
+ inferenceHostId: grant.hostId,
+ inferenceHostLabel: local ? "" : hostLabel,
+ inferenceBaseUrl: loopbackUrl(grant.hostId),
+ inferenceKey: grant.key,
+ inferenceModels: [
+ ...new Set([...models, ...alternates.flatMap((entry) => entry.models)]),
+ ],
+ inferenceHomePath: home,
+ ...(linked && connection ? { inferenceConnection: connection } : {}),
+ },
+ },
+ result: preserve,
+ });
+ });
+ yield* save({
+ ...state,
+ routePools: [
+ ...(state.routePools ?? []).filter((entry) => entry.driver !== driver),
+ {
+ driver,
+ primary: candidate,
+ alternates: updated.result ? (existing?.alternates ?? []) : [],
+ },
+ ],
+ });
+ return updated;
+ }),
+ );
yield* registry.reconcile(
deriveProviderInstanceConfigMap(revised.settings, providerEnvironment),
);
},
Effect.mapError(safeFailure("Could not configure the routed provider.")),
);
+ const registerFallback = Effect.fn("InferenceProxy.registerFallback")(
+ (input: InferenceRouteInput) => connect(input, true),
+ );
const refreshLocalProviders = Effect.fn("InferenceProxy.refreshLocalProviders")(function* () {
const state = yield* read;
if (!state.enabled) return;
@@ -1405,7 +2057,28 @@ const make = Effect.gen(function* () {
existing.config.inferenceHostId !== hostId
)
continue;
- const models = modelsForDriver(data, driver);
+ const localModels = modelsForDriver(data, driver);
+ const pool = (yield* read).routePools?.find(
+ (entry) => entry.driver === driver && entry.primary.hostId === hostId,
+ );
+ const models = pool
+ ? [...new Set([...localModels, ...pool.alternates.flatMap((entry) => entry.models)])]
+ : localModels;
+ if (pool && pool.primary.models.join("\0") !== localModels.join("\0"))
+ yield* mutex.withPermit(
+ read.pipe(
+ Effect.flatMap((state) =>
+ save({
+ ...state,
+ routePools: (state.routePools ?? []).map((entry) =>
+ entry.driver === driver
+ ? { ...entry, primary: { ...entry.primary, models: localModels } }
+ : entry,
+ ),
+ }),
+ ),
+ ),
+ );
const revised = yield* settings.reviseProviderInstance(instanceId, (current) => {
if (!current) return failure("The local inference provider was removed.");
return Effect.succeed({
@@ -1436,7 +2109,20 @@ const make = Effect.gen(function* () {
Effect.ignore,
Effect.forkScoped,
);
- return { status, manage, authorize, health, routeHealth, grant, connect, bindRoutes };
+ return {
+ status,
+ manage,
+ authorize,
+ hasFallback,
+ routeCandidates,
+ recordRouteOutcome,
+ health,
+ routeHealth,
+ grant,
+ connect,
+ registerFallback,
+ bindRoutes,
+ };
});
export class InferenceProxy extends Context.Service<
@@ -1446,23 +2132,57 @@ export class InferenceProxy extends Context.Service<
readonly health: (
key: string,
hostId?: EnvironmentId,
+ driver?: string,
) => Effect.Effect;
readonly routeHealth: (
route: InferenceProviderConfig,
key: string,
+ driver?: string,
) => Effect.Effect;
readonly manage: (
input: InferenceProxyAction,
) => Effect.Effect;
readonly grant: (
- input: InferenceConsumer,
+ input: InferenceGrantInput,
) => Effect.Effect;
readonly connect: (input: InferenceRouteInput) => Effect.Effect;
+ readonly registerFallback: (
+ input: InferenceRouteInput,
+ ) => Effect.Effect;
readonly bindRoutes: (port: number) => Effect.Effect;
readonly authorize: (
key: string,
hostId?: EnvironmentId,
+ driver?: string,
) => Effect.Effect<{ baseUrl: string; key: string } | null, InferenceProxyError>;
+ readonly routeCandidates: (
+ key: string,
+ hostId?: EnvironmentId,
+ driver?: string,
+ model?: string,
+ includeAll?: boolean,
+ ) => Effect.Effect<
+ ReadonlyArray<{
+ baseUrl: string;
+ key: string;
+ models: ReadonlyArray;
+ hostId?: EnvironmentId;
+ }> | null,
+ InferenceProxyError
+ >;
+ readonly hasFallback: (
+ key: string,
+ hostId: EnvironmentId | undefined,
+ driver: string | undefined,
+ ) => Effect.Effect;
+ readonly recordRouteOutcome: (input: {
+ driver: string;
+ hostId: EnvironmentId;
+ model: string;
+ status: number;
+ retryAfter?: string;
+ retryAfterMs?: string;
+ }) => Effect.Effect;
}
>()("t3/inference/InferenceProxy") {}
export const layer = Layer.effect(InferenceProxy, make);
diff --git a/apps/server/src/inference/http.test.ts b/apps/server/src/inference/http.test.ts
index a6044971fb98e..efa6719a018a9 100644
--- a/apps/server/src/inference/http.test.ts
+++ b/apps/server/src/inference/http.test.ts
@@ -1,7 +1,9 @@
import * as NodeZlib from "node:zlib";
import { expect, it } from "@effect/vitest";
+import { EnvironmentId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
+import * as Stream from "effect/Stream";
import { HttpClient, HttpClientResponse, HttpRouter } from "effect/http";
import { InferenceProxy } from "./InferenceProxy.ts";
import * as InferenceHttp from "./http.ts";
@@ -30,7 +32,10 @@ it("streams an authorized request with a host key, then denies the revoked consu
if (throttled)
return HttpClientResponse.fromWeb(
request,
- new Response("quota", { status: 429, headers: { "retry-after": "60" } }),
+ new Response("quota", {
+ status: 429,
+ headers: { "retry-after": "60", "retry-after-ms": "1200000" },
+ }),
);
const stream = new ReadableStream({
start(controller) {
@@ -70,6 +75,16 @@ it("streams an authorized request with a host key, then denies the revoked consu
: null,
);
},
+ routeCandidates: (key, hostId) => {
+ linkedHost = hostId;
+ return Effect.succeed(
+ active && key === "consumer"
+ ? [{ baseUrl: "http://127.0.0.1:43210", key: "private-host-key", models: [] }]
+ : null,
+ );
+ },
+ hasFallback: () => Effect.succeed(false),
+ recordRouteOutcome: () => Effect.void,
}),
),
Layer.provideMerge(Layer.succeed(HttpClient.HttpClient, client)),
@@ -101,7 +116,7 @@ it("streams an authorized request with a host key, then denies the revoked consu
finish!();
expect((await reader.read()).done).toBe(true);
expect(closed).toBe(true);
- const linked = await handler(request("linked/host/v1/messages?beta=true", "consumer"));
+ const linked = await handler(request("linked/codex/host/v1/messages?beta=true", "consumer"));
expect(linkedHost).toBe("host");
const linkedReader = linked.body!.getReader();
expect(new TextDecoder().decode((await linkedReader.read()).value)).toBe("data: first\n\n");
@@ -117,9 +132,10 @@ it("streams an authorized request with a host key, then denies the revoked consu
const limited = await handler(request("v1/messages?beta=true", "consumer"));
expect(limited.status).toBe(429);
expect(limited.headers.get("retry-after")).toBe("60");
+ expect(limited.headers.get("retry-after-ms")).toBe("1200000");
expect(await limited.text()).toBe("quota");
const health = await handler(
- new Request("http://t3.test/api/inference/linked/host/health", {
+ new Request("http://t3.test/api/inference/linked/codex/host/health", {
headers: { authorization: "Bearer consumer" },
}),
);
@@ -128,7 +144,11 @@ it("streams an authorized request with a host key, then denies the revoked consu
expect(await health.json()).toEqual({ availableDrivers: ["codex"], models: ["gpt-fixture"] });
expect(linkedHost).toBe("host");
active = false;
- expect((await handler(request("v1/messages", "consumer"))).status).toBe(403);
+ const denied = await handler(request("v1/messages", "consumer"));
+ expect(denied.status).toBe(403);
+ expect(await denied.json()).toMatchObject({
+ error: { type: "permission_error", message: expect.stringContaining("T3 inference") },
+ });
expect(
(
await handler(
@@ -143,3 +163,216 @@ it("streams an authorized request with a host key, then denies the revoked consu
await dispose();
}
});
+
+it("tries another authorized host for the same model after an upstream auth failure", async () => {
+ const calls: string[] = [];
+ let recordedRetry: unknown;
+ let primaryStatus = 403;
+ let backupStatus = 200;
+ const client = HttpClient.make((request) =>
+ Effect.sync(() => {
+ calls.push(request.url);
+ if (request.url.endsWith("/v1/messages"))
+ expect(request.headers["x-session-affinity"]).toBe("thread-fixture");
+ return HttpClientResponse.fromWeb(
+ request,
+ request.url.startsWith("http://primary.test") && primaryStatus !== 200
+ ? new Response(null, { status: primaryStatus })
+ : request.url.startsWith("http://backup.test") && backupStatus !== 200
+ ? new Response(null, {
+ status: backupStatus,
+ headers:
+ backupStatus === 429 ? { "retry-after": "60", "retry-after-ms": "1200000" } : {},
+ })
+ : request.url.endsWith("/v1/models")
+ ? Response.json({
+ object: "list",
+ data: request.url.startsWith("http://primary.test")
+ ? [
+ { id: "claude-fable-5-2", owned_by: "primary" },
+ { id: "claude-alpha", owned_by: "primary" },
+ ]
+ : [
+ { id: "claude-fable-5-2", owned_by: "backup" },
+ { id: "claude-beta", owned_by: "backup" },
+ ],
+ })
+ : Response.json({ type: "message", model: "claude-fable-5-2" }),
+ );
+ }),
+ );
+ const { handler, dispose } = HttpRouter.toWebHandler(
+ InferenceHttp.layer.pipe(
+ Layer.provide(
+ Layer.mock(InferenceProxy)({
+ authorize: () => Effect.succeed({ baseUrl: "http://primary.test", key: "primary-key" }),
+ routeCandidates: () =>
+ Effect.succeed([
+ {
+ baseUrl: "http://primary.test",
+ key: "primary-key",
+ models: ["claude-fable-5-2", "claude-alpha"],
+ hostId: EnvironmentId.make("primary"),
+ },
+ {
+ baseUrl: "http://backup.test",
+ key: "backup-key",
+ models: ["claude-fable-5-2", "claude-beta"],
+ hostId: EnvironmentId.make("backup"),
+ },
+ ]),
+ hasFallback: () => Effect.succeed(true),
+ recordRouteOutcome: (input) =>
+ Effect.sync(() => {
+ if (input.status === 429) recordedRetry = input;
+ }),
+ }),
+ ),
+ Layer.provideMerge(Layer.succeed(HttpClient.HttpClient, client)),
+ ),
+ { disableLogger: true },
+ );
+ try {
+ const body = JSON.stringify({ model: "claude-fable-5-2", messages: [] });
+ const response = await handler(
+ new Request("http://t3.test/api/inference/linked/claudeAgent/host/v1/messages", {
+ method: "POST",
+ headers: {
+ authorization: "Bearer consumer",
+ "content-type": "application/json",
+ "x-session-id": "thread-fixture",
+ "x-session-affinity": "thread-fixture",
+ },
+ body,
+ }),
+ );
+ expect(response.status).toBe(200);
+ expect(await response.json()).toMatchObject({ model: "claude-fable-5-2" });
+ expect(calls).toEqual(["http://primary.test/v1/messages", "http://backup.test/v1/messages"]);
+ const catalog = await handler(
+ new Request("http://t3.test/api/inference/linked/claudeAgent/host/v1/models", {
+ headers: { authorization: "Bearer consumer" },
+ }),
+ );
+ expect(catalog.status).toBe(200);
+ expect(await catalog.json()).toEqual({
+ object: "list",
+ data: [
+ { id: "claude-fable-5-2", owned_by: "backup" },
+ { id: "claude-beta", owned_by: "backup" },
+ ],
+ });
+ expect(calls.slice(2)).toEqual([
+ "http://primary.test/v1/models",
+ "http://backup.test/v1/models",
+ ]);
+ const send = () =>
+ handler(
+ new Request("http://t3.test/api/inference/linked/claudeAgent/host/v1/messages", {
+ method: "POST",
+ headers: {
+ authorization: "Bearer consumer",
+ "content-type": "application/json",
+ "x-session-id": "thread-fixture",
+ "x-session-affinity": "thread-fixture",
+ },
+ body,
+ }),
+ );
+ const sticky = await send();
+ expect(sticky.status).toBe(200);
+ expect(calls.slice(4)).toEqual(["http://backup.test/v1/messages"]);
+ backupStatus = 429;
+ primaryStatus = 200;
+ const rebinding = await send();
+ expect(rebinding.status).toBe(200);
+ expect(calls.slice(5)).toEqual([
+ "http://backup.test/v1/messages",
+ "http://primary.test/v1/messages",
+ ]);
+ expect(recordedRetry).toMatchObject({
+ retryAfter: "60",
+ retryAfterMs: "1200000",
+ });
+ const rebound = await send();
+ expect(rebound.status).toBe(200);
+ expect(calls.slice(7)).toEqual(["http://primary.test/v1/messages"]);
+ backupStatus = 200;
+ const union = await handler(
+ new Request("http://t3.test/api/inference/linked/claudeAgent/host/v1/models", {
+ headers: { authorization: "Bearer consumer" },
+ }),
+ );
+ expect(union.status).toBe(200);
+ expect(await union.json()).toEqual({
+ object: "list",
+ data: [
+ { id: "claude-fable-5-2", owned_by: "primary" },
+ { id: "claude-alpha", owned_by: "primary" },
+ { id: "claude-beta", owned_by: "backup" },
+ ],
+ });
+ expect(calls.slice(8)).toEqual([
+ "http://primary.test/v1/models",
+ "http://backup.test/v1/models",
+ ]);
+ } finally {
+ await dispose();
+ }
+});
+
+it("streams an oversized chunked request once without losing its buffered prefix", async () => {
+ const calls: string[] = [];
+ let received = 0;
+ const client = HttpClient.make((request) =>
+ Effect.gen(function* () {
+ calls.push(request.url);
+ if (request.body._tag !== "Stream") throw new Error("Expected a streaming request body");
+ received = yield* Stream.runFold(
+ request.body.stream.pipe(Stream.orDie),
+ () => 0,
+ (total, chunk) => total + chunk.byteLength,
+ );
+ return HttpClientResponse.fromWeb(request, new Response(null, { status: 403 }));
+ }),
+ );
+ const { handler, dispose } = HttpRouter.toWebHandler(
+ InferenceHttp.layer.pipe(
+ Layer.provide(
+ Layer.mock(InferenceProxy)({
+ routeCandidates: () =>
+ Effect.succeed([
+ { baseUrl: "http://primary.test", key: "primary-key", models: ["claude-fable-5-2"] },
+ { baseUrl: "http://backup.test", key: "backup-key", models: ["claude-fable-5-2"] },
+ ]),
+ hasFallback: () => Effect.succeed(true),
+ recordRouteOutcome: () => Effect.void,
+ }),
+ ),
+ Layer.provideMerge(Layer.succeed(HttpClient.HttpClient, client)),
+ ),
+ { disableLogger: true },
+ );
+ const chunk = new Uint8Array(1024 * 1024);
+ const body = new ReadableStream({
+ start(controller) {
+ for (let index = 0; index < 9; index++) controller.enqueue(chunk);
+ controller.close();
+ },
+ });
+ try {
+ const response = await handler(
+ new Request("http://t3.test/api/inference/linked/claudeAgent/host/v1/messages", {
+ method: "POST",
+ headers: { authorization: "Bearer consumer", "content-type": "application/json" },
+ body,
+ duplex: "half",
+ } as RequestInit & { duplex: "half" }),
+ );
+ expect(response.status).toBe(403);
+ expect(received).toBe(9 * 1024 * 1024);
+ expect(calls).toEqual(["http://primary.test/v1/messages"]);
+ } finally {
+ await dispose();
+ }
+});
diff --git a/apps/server/src/inference/http.ts b/apps/server/src/inference/http.ts
index db3135fd749a6..13905a9b712ea 100644
--- a/apps/server/src/inference/http.ts
+++ b/apps/server/src/inference/http.ts
@@ -1,6 +1,12 @@
import * as Layer from "effect/Layer";
import * as Effect from "effect/Effect";
+import * as Clock from "effect/Clock";
+import * as Schema from "effect/Schema";
+import * as Result from "effect/Result";
+import * as Cause from "effect/Cause";
+import * as Stream from "effect/Stream";
import * as FetchHttpClient from "effect/http/FetchHttpClient";
+import * as NodeZlib from "node:zlib";
import {
HttpClient,
HttpClientRequest,
@@ -11,6 +17,117 @@ import {
import { InferenceProxy } from "./InferenceProxy.ts";
import { inferenceTarget } from "./routes.ts";
+const MAX_REPLAY_BODY_BYTES = 8 * 1024 * 1024;
+const MAX_CATALOG_BODY_BYTES = 1024 * 1024;
+const MAX_CATALOG_UNION_BYTES = 8 * 1024 * 1024;
+const MAX_CATALOG_MODELS = 4096;
+const MAX_SESSION_ROUTES = 1024;
+const SESSION_ROUTE_TTL_MS = 30 * 60 * 1000;
+const sessionRoutes = new Map();
+
+class InferenceStreamError extends Schema.TaggedError()(
+ "InferenceStreamError",
+ { cause: Schema.Unknown },
+) {}
+
+function sessionRouteKey(
+ key: string,
+ driver: string | undefined,
+ model: string | undefined,
+ session: string | undefined,
+): string | undefined {
+ if (!driver || !model || !session || session.length > 256) return undefined;
+ return JSON.stringify([key, driver, model, session]);
+}
+
+function rememberSessionRoute(key: string, hostId: string, now: number): void {
+ sessionRoutes.delete(key);
+ sessionRoutes.set(key, { hostId, expiresAt: now + SESSION_ROUTE_TTL_MS });
+ if (sessionRoutes.size > MAX_SESSION_ROUTES)
+ sessionRoutes.delete(sessionRoutes.keys().next().value!);
+}
+
+const replayBody = Effect.fn("InferenceHttp.replayBody")(function* (
+ stream: Stream.Stream,
+ maxBytes = MAX_REPLAY_BODY_BYTES,
+) {
+ const pull = yield* Stream.toPull(stream);
+ const prefix: Uint8Array[] = [];
+ let size = 0;
+ while (true) {
+ const next = yield* pull.pipe(Effect.result);
+ if (Result.isFailure(next)) {
+ if (!Cause.isDone(next.failure)) return yield* Effect.fail(next.failure);
+ const body = new Uint8Array(size);
+ let offset = 0;
+ for (const chunk of prefix) {
+ body.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return { body, stream: Stream.fromIterable(prefix) };
+ }
+ const batchSize = next.success.reduce((total, chunk) => total + chunk.byteLength, 0);
+ if (size + batchSize > maxBytes)
+ return {
+ body: undefined,
+ stream: Stream.fromIterable([...prefix, ...next.success]).pipe(
+ Stream.concat(Stream.fromPull(Effect.succeed(pull))),
+ ),
+ };
+ prefix.push(...next.success);
+ size += batchSize;
+ }
+});
+
+function parseCatalog(body: Uint8Array): Record | undefined {
+ try {
+ const value: unknown = JSON.parse(new TextDecoder().decode(body));
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
+ if (!("data" in value) || !Array.isArray(value.data)) return undefined;
+ return value as Record;
+ } catch {
+ return undefined;
+ }
+}
+
+function requestMetadata(body: Uint8Array, encoding: string | undefined) {
+ try {
+ const decoded =
+ encoding === "zstd"
+ ? NodeZlib.zstdDecompressSync(body, { maxOutputLength: MAX_REPLAY_BODY_BYTES })
+ : encoding === "gzip"
+ ? NodeZlib.gunzipSync(body, { maxOutputLength: MAX_REPLAY_BODY_BYTES })
+ : encoding === undefined || encoding === "identity"
+ ? body
+ : undefined;
+ if (!decoded) return {};
+ const value: unknown = JSON.parse(new TextDecoder().decode(decoded));
+ if (value === null || typeof value !== "object") return {};
+ return {
+ model: "model" in value && typeof value.model === "string" ? value.model : undefined,
+ promptCacheKey:
+ "prompt_cache_key" in value && typeof value.prompt_cache_key === "string"
+ ? value.prompt_cache_key
+ : undefined,
+ };
+ } catch {
+ return {};
+ }
+}
+
+const grantDenied = () =>
+ HttpServerResponse.jsonUnsafe(
+ {
+ type: "error",
+ error: {
+ type: "permission_error",
+ message:
+ "T3 inference access was denied. Check sharing and reconnect the route in Inference accounts.",
+ },
+ },
+ { status: 403, headers: { "cache-control": "no-store" } },
+ );
+
const handler = Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const targetPath = inferenceTarget(request.method, request.url);
@@ -20,45 +137,176 @@ const handler = Effect.gen(function* () {
if (!key) return HttpServerResponse.empty({ status: 401 });
const host = yield* InferenceProxy;
if (targetPath.path === "/health") {
- const health = yield* host.health(key, targetPath.environmentId);
+ const health = yield* host.health(key, targetPath.environmentId, targetPath.driver);
return health === null
- ? HttpServerResponse.empty({ status: 403 })
+ ? grantDenied()
: HttpServerResponse.jsonUnsafe(health, { headers: { "cache-control": "no-store" } });
}
- const target = yield* host.authorize(key, targetPath.environmentId);
- if (!target) return HttpServerResponse.empty({ status: 403 });
+ const canReplay = yield* host.hasFallback(key, targetPath.environmentId, targetPath.driver);
+ const declaredLength = request.headers["content-length"];
+ const length = Number(declaredLength);
+ const buffered =
+ request.method === "POST" &&
+ canReplay &&
+ (declaredLength === undefined ||
+ (Number.isSafeInteger(length) && length <= MAX_REPLAY_BODY_BYTES))
+ ? yield* replayBody(
+ request.stream.pipe(Stream.mapError((cause) => new InferenceStreamError({ cause }))),
+ )
+ : { body: undefined, stream: request.stream };
+ const { body } = buffered;
+ const metadata = body ? requestMetadata(body, request.headers["content-encoding"]) : {};
+ const model = metadata.model;
+ const session =
+ request.headers["x-session-id"] ??
+ request.headers["session_id"] ??
+ request.headers["session-id"] ??
+ request.headers["x-claude-code-session-id"] ??
+ request.headers["x-session-affinity"] ??
+ metadata.promptCacheKey;
+ const affinityKey = sessionRouteKey(key, targetPath.driver, model, session);
+ const candidates = yield* host.routeCandidates(
+ key,
+ targetPath.environmentId,
+ targetPath.driver,
+ model,
+ targetPath.path === "/v1/models",
+ );
+ if (candidates === null) return grantDenied();
+ if (!candidates.length) return HttpServerResponse.empty({ status: 503 });
+ const eligible = model
+ ? candidates.filter((candidate) => candidate.models.includes(model))
+ : candidates.slice(0, 1);
+ let targets =
+ targetPath.path === "/v1/models"
+ ? candidates
+ : eligible.length
+ ? eligible
+ : candidates.slice(0, 1);
+ if (affinityKey) {
+ const preferred = sessionRoutes.get(affinityKey);
+ if (preferred && preferred.expiresAt <= (yield* Clock.currentTimeMillis))
+ sessionRoutes.delete(affinityKey);
+ else if (preferred) {
+ const index = targets.findIndex((target) => target.hostId === preferred.hostId);
+ if (index > 0)
+ targets = [targets[index]!, ...targets.slice(0, index), ...targets.slice(index + 1)];
+ else if (index < 0) sessionRoutes.delete(affinityKey);
+ }
+ }
const client = HttpClient.withScope(yield* HttpClient.HttpClient);
- const headers: Record = { authorization: "Bearer " + target.key };
- for (const name of [
- "accept",
- "content-encoding",
- "anthropic-version",
- "anthropic-beta",
- "session_id",
- "session-id",
- "x-session-id",
- "x-client-request-id",
- "x-codex-beta-features",
- "x-codex-turn-metadata",
- "x-codex-turn-state",
- "x-codex-window-id",
- "thread-id",
- "x-claude-code-session-id",
- ]) {
- const value = request.headers[name];
- if (value) headers[name] = value;
+ let result;
+ let catalogBase: Record | undefined;
+ const catalogModels = new Map>();
+ let catalogBytes = 0;
+ const catalogResponse = () =>
+ HttpServerResponse.jsonUnsafe(
+ { ...catalogBase, data: [...catalogModels.values()] },
+ { headers: { "cache-control": "no-store, no-transform" } },
+ );
+ for (const [index, target] of targets.entries()) {
+ const headers: Record = { authorization: "Bearer " + target.key };
+ for (const name of [
+ "accept",
+ "content-encoding",
+ "anthropic-version",
+ "anthropic-beta",
+ "session_id",
+ "session-id",
+ "x-session-id",
+ "x-session-affinity",
+ "x-client-request-id",
+ "x-codex-beta-features",
+ "x-codex-turn-metadata",
+ "x-codex-turn-state",
+ "x-codex-window-id",
+ "thread-id",
+ "x-claude-code-session-id",
+ ]) {
+ const value = request.headers[name];
+ if (value) headers[name] = value;
+ }
+ const outgoing = HttpClientRequest.make(request.method === "GET" ? "GET" : "POST")(
+ target.baseUrl + targetPath.path,
+ ).pipe(
+ HttpClientRequest.setHeaders(headers),
+ request.method === "POST"
+ ? body
+ ? HttpClientRequest.bodyUint8Array(body, "application/json")
+ : HttpClientRequest.bodyStream(buffered.stream, { contentType: "application/json" })
+ : (req) => req,
+ );
+ const attempt = yield* client
+ .execute(outgoing)
+ .pipe(
+ Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }),
+ Effect.result,
+ );
+ if (Result.isFailure(attempt)) {
+ if (affinityKey && target.hostId) sessionRoutes.delete(affinityKey);
+ if (target.hostId && targetPath.driver && model)
+ yield* host.recordRouteOutcome({
+ driver: targetPath.driver,
+ hostId: target.hostId,
+ model,
+ status: 502,
+ });
+ if (index < targets.length - 1) continue;
+ if (catalogBase) return catalogResponse();
+ return yield* attempt.failure;
+ }
+ result = attempt.success;
+ if (affinityKey && target.hostId) {
+ if (result.status < 400)
+ rememberSessionRoute(affinityKey, target.hostId, yield* Clock.currentTimeMillis);
+ else if ([401, 403, 429, 502, 503].includes(result.status)) sessionRoutes.delete(affinityKey);
+ }
+ if (target.hostId && targetPath.driver && model)
+ yield* host.recordRouteOutcome({
+ driver: targetPath.driver,
+ hostId: target.hostId,
+ model,
+ status: result.status,
+ ...(result.headers["retry-after"] ? { retryAfter: result.headers["retry-after"] } : {}),
+ ...(result.headers["retry-after-ms"]
+ ? { retryAfterMs: result.headers["retry-after-ms"] }
+ : {}),
+ });
+ if (targetPath.path === "/v1/models") {
+ if (result.status >= 200 && result.status < 300) {
+ const read = yield* replayBody(
+ result.stream.pipe(Stream.mapError((cause) => new InferenceStreamError({ cause }))),
+ MAX_CATALOG_BODY_BYTES,
+ ).pipe(Effect.result);
+ if (Result.isSuccess(read) && read.success.body) {
+ const catalog = parseCatalog(read.success.body);
+ if (catalog) {
+ if (catalogBytes + read.success.body.byteLength > MAX_CATALOG_UNION_BYTES)
+ return HttpServerResponse.empty({ status: 502 });
+ catalogBytes += read.success.body.byteLength;
+ catalogBase ??= catalog;
+ for (const item of catalog.data as unknown[]) {
+ if (!item || typeof item !== "object" || Array.isArray(item) || !("id" in item))
+ continue;
+ if (typeof item.id !== "string") continue;
+ if (target.models.length && !target.models.includes(item.id)) continue;
+ if (!catalogModels.has(item.id))
+ catalogModels.set(item.id, item as Record);
+ if (catalogModels.size > MAX_CATALOG_MODELS)
+ return HttpServerResponse.empty({ status: 502 });
+ }
+ }
+ }
+ }
+ if (index < targets.length - 1) continue;
+ if (catalogBase) return catalogResponse();
+ if (result.status >= 200 && result.status < 300)
+ return HttpServerResponse.empty({ status: 502 });
+ }
+ if (index < targets.length - 1 && [401, 403, 429, 502, 503].includes(result.status)) continue;
+ break;
}
- const outgoing = HttpClientRequest.make(request.method === "GET" ? "GET" : "POST")(
- target.baseUrl + targetPath.path,
- ).pipe(
- HttpClientRequest.setHeaders(headers),
- request.method === "POST"
- ? HttpClientRequest.bodyStream(request.stream, { contentType: "application/json" })
- : (req) => req,
- );
- const result = yield* client
- .execute(outgoing)
- .pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }));
+ if (!result) return HttpServerResponse.empty({ status: 502 });
return HttpServerResponse.stream(result.stream, {
status: result.status,
contentType: result.headers["content-type"] ?? "application/json",
@@ -68,6 +316,9 @@ const handler = Effect.gen(function* () {
? { "x-codex-turn-state": result.headers["x-codex-turn-state"] }
: {}),
...(result.headers["retry-after"] ? { "retry-after": result.headers["retry-after"] } : {}),
+ ...(result.headers["retry-after-ms"]
+ ? { "retry-after-ms": result.headers["retry-after-ms"] }
+ : {}),
},
});
}).pipe(
diff --git a/apps/server/src/inference/providerHealth.ts b/apps/server/src/inference/providerHealth.ts
index 15eb8e0fa4e38..f0226ae920da3 100644
--- a/apps/server/src/inference/providerHealth.ts
+++ b/apps/server/src/inference/providerHealth.ts
@@ -10,6 +10,24 @@ import { InferenceProxy } from "./InferenceProxy.ts";
import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
import * as ServerSettings from "../serverSettings.ts";
+export function filterInferenceWorkspaceModels(
+ provider: ServerProvider,
+ snapshots: NonNullable,
+): NonNullable {
+ if (provider.driver !== "pi" && provider.driver !== "opencode") return snapshots;
+ const routedModels = new Set(
+ provider.models.filter((model) => model.slug.startsWith("t3proxy/")).map((model) => model.slug),
+ );
+ const filtered = snapshots.map((snapshot) => {
+ if (snapshot.models === undefined) return snapshot;
+ const models = snapshot.models.filter(
+ (model) => !model.slug.startsWith("t3proxy/") || routedModels.has(model.slug),
+ );
+ return models.length === snapshot.models.length ? snapshot : { ...snapshot, models };
+ });
+ return filtered.every((snapshot, index) => snapshot === snapshots[index]) ? snapshots : filtered;
+}
+
export const makeInferenceProviderHealth = Effect.fn("makeInferenceProviderHealth")(function* () {
const proxy = yield* InferenceProxy;
const settings = yield* ServerSettings.ServerSettingsService;
@@ -18,9 +36,13 @@ export const makeInferenceProviderHealth = Effect.fn("makeInferenceProviderHealt
capacity: 32,
timeToLive: "15 seconds",
lookup: Effect.fn("InferenceProviderHealth.probe")(
- function* (input: { readonly route: InferenceProviderConfig; readonly key: string }) {
+ function* (input: {
+ readonly route: InferenceProviderConfig;
+ readonly key: string;
+ readonly driver: string;
+ }) {
return yield* proxy
- .routeHealth(input.route, input.key)
+ .routeHealth(input.route, input.key, input.driver)
.pipe(Effect.map((health) => ({ health })));
},
Effect.timeout("5 seconds"),
@@ -39,17 +61,49 @@ export const makeInferenceProviderHealth = Effect.fn("makeInferenceProviderHealt
? route.inferenceKey
: (yield* secrets.read([route.inferenceKey]))[0];
const catalog = key
- ? yield* Cache.get(catalogs, { route, key })
+ ? yield* Cache.get(catalogs, { route, key, driver: provider.driver })
: { problem: "Inference host credential is unavailable." };
+ const mixedCatalog = provider.driver === "pi" || provider.driver === "opencode";
+ const servedModels =
+ "health" in catalog &&
+ catalog.health.availableDrivers.some((driver) => driver === provider.driver)
+ ? new Set(catalog.health.models)
+ : new Set();
+ const models = provider.models.filter((model) => {
+ if (!mixedCatalog) return servedModels.has(model.slug);
+ if (!model.slug.startsWith("t3proxy/")) return true;
+ const id = model.slug.slice("t3proxy/".length);
+ return route.inferenceModels.includes(id) && servedModels.has(id);
+ });
const problem =
"problem" in catalog
? catalog.problem
- : catalog.health.availableDrivers.some((driver) => driver === provider.driver) &&
- route.inferenceModels.some((model) => catalog.health.models.includes(model))
+ : route.inferenceModels.some((model) => servedModels.has(model))
? undefined
: "Inference host has no available models for this provider.";
+ if (mixedCatalog) {
+ const availableProvider = {
+ ...provider,
+ models,
+ ...(provider.workspaceSnapshots === undefined
+ ? {}
+ : {
+ workspaceSnapshots: filterInferenceWorkspaceModels(
+ { ...provider, models },
+ provider.workspaceSnapshots,
+ ),
+ }),
+ };
+ return models.length > 0 || problem === undefined
+ ? availableProvider
+ : {
+ ...availableProvider,
+ status: provider.status === "ready" ? ("warning" as const) : provider.status,
+ message: problem,
+ };
+ }
return problem === undefined
- ? provider
+ ? { ...provider, models }
: {
...provider,
availability: "unavailable" as const,
diff --git a/apps/server/src/inference/routes.test.ts b/apps/server/src/inference/routes.test.ts
index 6d4d47857571b..90e99ddf1045d 100644
--- a/apps/server/src/inference/routes.test.ts
+++ b/apps/server/src/inference/routes.test.ts
@@ -3,6 +3,7 @@ import {
inferencePath,
inferenceTarget,
modelsForDriver,
+ needsAccountModelLookup,
routeProvider,
validateRouteUrl,
} from "./routes.ts";
@@ -13,9 +14,10 @@ describe("inference routes", () => {
"/v1/messages?beta=true",
);
expect(inferencePath("GET", "/api/inference/v1/models")).toBe("/v1/models");
- expect(inferenceTarget("GET", "/api/inference/linked/host/health")).toEqual({
+ expect(inferenceTarget("GET", "/api/inference/linked/codex/host/health")).toEqual({
path: "/health",
environmentId: "host",
+ driver: "codex",
});
expect(inferencePath("POST", "/api/inference/health")).toBeNull();
expect(inferencePath("POST", "/api/inference/v1/chat/completions")).toBe(
@@ -30,14 +32,21 @@ describe("inference routes", () => {
expect(inferencePath("POST", "/api/inference" + path)).toBeNull();
}
expect(inferencePath("GET", "/api/inference/v1/messages")).toBeNull();
- expect(inferenceTarget("POST", "/api/inference/linked/host/v1/responses")).toEqual({
+ expect(inferenceTarget("POST", "/api/inference/linked/codex/host/v1/responses")).toEqual({
path: "/v1/responses",
environmentId: "host",
+ driver: "codex",
+ });
+ expect(inferenceTarget("POST", "/api/inference/linked/claudeAgent/host/v1/messages")).toEqual({
+ path: "/v1/messages",
+ environmentId: "host",
+ driver: "claudeAgent",
});
expect(
inferenceTarget("GET", "/api/inference/linked/host/v0/management/auth-files"),
).toBeNull();
expect(inferenceTarget("POST", "/api/inference/linked/%ZZ/v1/messages")).toBeNull();
+ expect(inferenceTarget("POST", "/api/inference/linked/host/v1/messages")).toBeNull();
});
it("accepts private LAN addresses and HTTPS tailnet routes and confines local keys to loopback", () => {
@@ -159,4 +168,92 @@ describe("inference routes", () => {
]);
expect(modelsForDriver(models, "pi")).toEqual(models.map((model) => model.id));
});
+
+ it("excludes an exhausted Claude account's models when only Codex remains available", () => {
+ const now = Date.parse("2026-11-17T00:00:00.000Z");
+ const models = [
+ { id: "claude-sonnet", owned_by: "anthropic" },
+ { id: "gpt-luna", owned_by: "openai" },
+ ];
+ const accounts = [
+ { id: "claude", name: "claude.json", provider: "claude", status: "active" },
+ { id: "codex", name: "codex.json", provider: "codex", status: "active" },
+ ];
+ expect(needsAccountModelLookup(accounts, new Set(), now)).toBe(false);
+ expect(needsAccountModelLookup(accounts, new Set(["claude.json"]), now)).toBe(true);
+ expect(
+ modelsForDriver(models, "opencode", {
+ accounts,
+ excludedNames: new Set(["claude.json"]),
+ registeredModels: new Map([["codex", ["gpt-luna"]]]),
+ now,
+ }),
+ ).toEqual(["gpt-luna"]);
+ expect(
+ modelsForDriver(models, "opencode", {
+ accounts,
+ excludedNames: new Set(["claude.json"]),
+ registeredModels: new Map(),
+ now,
+ }),
+ ).toEqual(["gpt-luna"]);
+ expect(
+ modelsForDriver(models, "opencode", {
+ accounts: [
+ ...accounts,
+ { id: "other-codex", name: "other-codex.json", provider: "codex", status: "error" },
+ ],
+ excludedNames: new Set(["claude.json"]),
+ registeredModels: new Map(),
+ now,
+ }),
+ ).toEqual([]);
+ expect(
+ modelsForDriver(models, "pi", {
+ accounts,
+ excludedNames: new Set(["claude.json"]),
+ registeredModels: new Map([["codex", ["gpt-luna"]]]),
+ now,
+ }),
+ ).toEqual(["gpt-luna"]);
+ });
+
+ it("keeps shared and aliased models when another account can serve them", () => {
+ const now = Date.parse("2026-11-17T00:00:00.000Z");
+ const catalog = [
+ { id: "claude-sonnet", owned_by: "anthropic" },
+ { id: "claude-alias", owned_by: "anthropic" },
+ ];
+ const accounts = [
+ {
+ id: "limited",
+ name: "limited.json",
+ status: "active",
+ cooldowns: [
+ { scope: "model", model_key: "claude-sonnet", retry_at: "2026-11-17T00:01:00Z" },
+ ],
+ },
+ { id: "healthy", name: "healthy.json", status: "active", runtime_only: true },
+ ];
+ expect(needsAccountModelLookup(accounts, new Set(), now)).toBe(true);
+ expect(
+ modelsForDriver(catalog, "opencode", {
+ accounts,
+ excludedNames: new Set(),
+ registeredModels: new Map([
+ ["limited", ["claude-sonnet"]],
+ ["healthy", ["claude-sonnet", "claude-alias"]],
+ ]),
+ now,
+ }),
+ ).toEqual(["claude-sonnet", "claude-alias"]);
+ expect(
+ modelsForDriver(catalog, "opencode", {
+ accounts: [accounts[0]!],
+ excludedNames: new Set(),
+ registeredModels: new Map([["limited", ["claude-sonnet"]]]),
+ now,
+ }),
+ ).toEqual([]);
+ });
});
diff --git a/apps/server/src/inference/routes.ts b/apps/server/src/inference/routes.ts
index 60312355c362c..af861457da850 100644
--- a/apps/server/src/inference/routes.ts
+++ b/apps/server/src/inference/routes.ts
@@ -1,10 +1,10 @@
import {
EnvironmentId,
+ InferenceDriver,
INFERENCE_HARNESSES,
ProviderDriverKind,
type CustomModelSetting,
type SettingsSecretValue,
- type InferenceDriver,
type ProviderInstanceConfig,
} from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
@@ -12,6 +12,7 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
const PREFIX = "/api/inference";
+const isInferenceDriver = Schema.is(InferenceDriver);
export function inferencePath(method: string, rawUrl: string): string | null {
if (!rawUrl.startsWith(PREFIX)) return null;
@@ -32,12 +33,18 @@ export function inferencePath(method: string, rawUrl: string): string | null {
}
export function inferenceTarget(method: string, rawUrl: string) {
- const linked = /^\/api\/inference\/linked\/([^/]+)(\/.*)$/.exec(rawUrl);
- const path = inferencePath(method, linked ? PREFIX + linked[2] : rawUrl);
+ const linked = /^\/api\/inference\/linked\/([^/]+)\/([^/]+)(\/.*)$/.exec(rawUrl);
+ const driver = linked && isInferenceDriver(linked[1]) ? linked[1] : undefined;
+ if (rawUrl.startsWith(PREFIX + "/linked/") && !driver) return null;
+ const path = inferencePath(method, linked ? PREFIX + linked[3] : rawUrl);
if (!path) return null;
if (!linked) return { path, environmentId: undefined };
try {
- return { path, environmentId: EnvironmentId.make(decodeURIComponent(linked[1]!)) };
+ return {
+ path,
+ environmentId: EnvironmentId.make(decodeURIComponent(linked[2]!)),
+ driver,
+ };
} catch {
return null;
}
@@ -59,6 +66,50 @@ export interface ProxyModel {
readonly owned_by?: string | undefined;
}
+export interface ProxyAccount {
+ readonly id?: string | undefined;
+ readonly name: string;
+ readonly provider?: string | undefined;
+ readonly status: string;
+ readonly disabled?: boolean | undefined;
+ readonly unavailable?: boolean | undefined;
+ readonly runtime_only?: boolean | undefined;
+ readonly cooldowns?:
+ | ReadonlyArray<{
+ readonly scope: string;
+ readonly model_key?: string | undefined;
+ readonly retry_at: string;
+ }>
+ | null
+ | undefined;
+}
+
+export interface AccountModelAvailability {
+ readonly accounts: ReadonlyArray;
+ readonly excludedNames: ReadonlySet;
+ readonly registeredModels: ReadonlyMap;
+ readonly now: number;
+}
+
+const usableAccount = (account: ProxyAccount, excludedNames: ReadonlySet) =>
+ account.status === "active" &&
+ !account.disabled &&
+ !account.unavailable &&
+ !excludedNames.has(account.name);
+
+const activeCooldowns = (account: ProxyAccount, now: number) =>
+ account.cooldowns?.filter((cooldown) => Date.parse(cooldown.retry_at) > now) ?? [];
+
+export function needsAccountModelLookup(
+ accounts: ReadonlyArray,
+ excludedNames: ReadonlySet,
+ now: number,
+) {
+ return accounts.some(
+ (account) => !usableAccount(account, excludedNames) || activeCooldowns(account, now).length > 0,
+ );
+}
+
interface Route {
readonly baseUrl: string;
readonly key: SettingsSecretValue;
@@ -193,8 +244,50 @@ const harnesses: Record<
},
};
-export function modelsForDriver(data: readonly ProxyModel[], driver: InferenceDriver) {
- return data.filter((model) => harnesses[driver].serves(model)).map((model) => model.id);
+export function modelsForDriver(
+ data: readonly ProxyModel[],
+ driver: InferenceDriver,
+ availability?: AccountModelAvailability,
+) {
+ const models = data.filter((model) => harnesses[driver].serves(model));
+ if (
+ !availability ||
+ !needsAccountModelLookup(availability.accounts, availability.excludedNames, availability.now)
+ )
+ return models.map((model) => model.id);
+ const available = new Set();
+ for (const account of availability.accounts) {
+ if (!usableAccount(account, availability.excludedNames)) continue;
+ const cooldowns = activeCooldowns(account, availability.now);
+ if (cooldowns.some((cooldown) => cooldown.scope === "credential")) continue;
+ const blocked = new Set(
+ cooldowns
+ .filter((cooldown) => cooldown.scope === "model" && cooldown.model_key)
+ .map((cooldown) => cooldown.model_key),
+ );
+ const registered = availability.registeredModels.get(account.id || account.name);
+ if (registered === undefined) {
+ const owner =
+ account.provider === "codex"
+ ? "openai"
+ : account.provider === "claude"
+ ? "anthropic"
+ : null;
+ if (
+ owner &&
+ availability.accounts.filter((other) => other.provider === account.provider).length === 1
+ ) {
+ for (const model of models) {
+ if (model.owned_by === owner && !blocked.has(model.id)) available.add(model.id);
+ }
+ }
+ continue;
+ }
+ for (const model of registered) {
+ if (!blocked.has(model)) available.add(model);
+ }
+ }
+ return models.filter((model) => available.has(model.id)).map((model) => model.id);
}
export function routeProvider(driver: InferenceDriver, label: string | null, route: Route) {
diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts
index 9c4e00a11ec14..1d5e3fd51dbe0 100644
--- a/apps/server/src/observability/RpcInstrumentation.ts
+++ b/apps/server/src/observability/RpcInstrumentation.ts
@@ -71,6 +71,7 @@ const RPC_AGGREGATES = {
[WS_METHODS.inferenceManage]: "provider",
[WS_METHODS.inferenceGrant]: "provider",
[WS_METHODS.inferenceConnect]: "provider",
+ [WS_METHODS.inferenceRegisterFallback]: "provider",
[WS_METHODS.providerAccountExport]: "provider",
[WS_METHODS.providerAccountImport]: "provider",
[WS_METHODS.providerAuthRespond]: "provider",
@@ -278,6 +279,7 @@ const RPC_METHODS_WITH_TRACING_DISABLED: ReadonlySet = new Set([
WS_METHODS.inferenceManage,
WS_METHODS.inferenceGrant,
WS_METHODS.inferenceConnect,
+ WS_METHODS.inferenceRegisterFallback,
WS_METHODS.providerAccountExport,
WS_METHODS.providerAccountImport,
]);
diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
index aaa813b2802fe..980741feb252d 100644
--- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
@@ -77,13 +77,14 @@ const event = (
data: Record,
label?: string,
version = 1,
+ created = 1,
): ProviderReplayEntry => ({
type: "emit_inbound",
frame: {
type: "sdk.event",
event: {
id: `evt_${type.replaceAll(".", "")}0000`,
- created: 1,
+ created,
type,
...(type.startsWith("rpc.") ? { location: { directory: WORK } } : {}),
data,
@@ -733,6 +734,144 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}),
);
+ it.effect.each([
+ {
+ name: "a quota 429 with a retry hint",
+ error: {
+ type: "provider.quota",
+ status: 429,
+ message: "Quota reached",
+ retryAfterMs: 90_000,
+ },
+ failureClass: "usage_limit",
+ resetAt: "2026-11-17T12:01:30.000Z",
+ },
+ {
+ name: "an otherwise unknown 429 with a retry hint",
+ error: {
+ type: "provider.unknown",
+ status: 429,
+ message: "Rate limited",
+ retryAfterMs: 90_000,
+ },
+ failureClass: "usage_limit",
+ resetAt: "2026-11-17T12:01:30.000Z",
+ },
+ {
+ name: "OpenCode's temporary overloaded 429",
+ error: {
+ type: "provider.rate-limit",
+ status: 429,
+ message: "Service temporarily overloaded",
+ retryAfterMs: 2_000,
+ response: {
+ body: JSON.stringify({
+ error: { code: "service_overloaded", message: "Service temporarily overloaded" },
+ }),
+ },
+ },
+ failureClass: "provider_error",
+ resetAt: null,
+ },
+ {
+ name: "an overloaded 429 identified by its response body",
+ error: {
+ type: "provider.rate-limit",
+ status: 429,
+ message: "Request failed",
+ retryAfterMs: 2_000,
+ response: { body: JSON.stringify({ error: { code: "service_overloaded" } }) },
+ },
+ failureClass: "provider_error",
+ resetAt: null,
+ },
+ {
+ name: "an overloaded 429 identified by its native message",
+ error: {
+ type: "provider.rate-limit",
+ status: 429,
+ message: "Service temporarily overloaded",
+ retryAfterMs: 2_000,
+ },
+ failureClass: "provider_error",
+ resetAt: null,
+ },
+ {
+ name: "a real token rate limit with a retry hint",
+ error: {
+ type: "provider.rate-limit",
+ status: 429,
+ message: "Token rate limit reached",
+ retryAfterMs: 2_000,
+ response: {
+ body: JSON.stringify({
+ error: { code: "rate_limit_exceeded", message: "Token rate limit reached" },
+ }),
+ },
+ },
+ failureClass: "usage_limit",
+ resetAt: "2026-11-17T12:00:02.000Z",
+ },
+ {
+ name: "an overloaded 429 with a retry hint",
+ error: {
+ type: "provider.overloaded",
+ status: 429,
+ message: "Server overloaded",
+ retryAfterMs: 90_000,
+ },
+ failureClass: "provider_error",
+ resetAt: null,
+ },
+ {
+ name: "a generic overloaded 503",
+ error: {
+ type: "provider.overloaded",
+ status: 503,
+ message: "Server overloaded",
+ retryAfterMs: 2_000,
+ },
+ failureClass: "provider_error",
+ resetAt: null,
+ },
+ {
+ name: "an empty-balance 402 with a retry hint",
+ error: {
+ type: "provider.quota",
+ status: 402,
+ message: "Insufficient funds",
+ retryAfterMs: 90_000,
+ },
+ failureClass: "provider_error",
+ resetAt: null,
+ },
+ {
+ name: "a quota 429 with an unusable retry hint",
+ error: { type: "provider.quota", status: 429, message: "Quota reached", retryAfterMs: -1 },
+ failureClass: "usage_limit",
+ resetAt: null,
+ },
+ ] as const)("uses the terminal event time for $name", ({ error, failureClass, resetAt }) =>
+ Effect.gen(function* () {
+ const { runtime, thread } = yield* resumed([
+ out("session.prompt", { sessionID: SESSION, text: "" }),
+ promptAccepted,
+ event(
+ "session.execution.failed",
+ { sessionID: SESSION, error },
+ undefined,
+ 1,
+ Date.parse("2026-11-17T12:00:00.000Z"),
+ ),
+ ]);
+ const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
+ yield* runtime.startTurn(turnInput(thread));
+ const ended = yield* Fiber.join(terminal);
+ assert.equal(ended?.failure?.class, failureClass);
+ assert.equal(ended?.failure?.resetAt, resetAt);
+ }),
+ );
+
// regression: #29289 Claude weekly limits through claude-agent lost their usage-limit reset
it.effect(
"classifies a Claude weekly limit as a usage limit that resets at its reported time",
diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts
index 9f00354c1f7cb..e1a8f1a022f4c 100644
--- a/apps/server/src/provider/ProviderRegistry.test.ts
+++ b/apps/server/src/provider/ProviderRegistry.test.ts
@@ -1119,6 +1119,9 @@ it.layer(
Effect.gen(function* () {
let proxyStatus = 503;
let poolAvailable = true;
+ const mixedCatalog = driver === "pi" || driver === "opencode";
+ const routedSlug = mixedCatalog ? "t3proxy/claude-fixture" : "claude-fixture";
+ const offlineSlug = mixedCatalog ? "t3proxy/claude-offline" : "claude-offline";
const instanceId = ProviderInstanceId.make(driver);
const driverKind = ProviderDriverKind.make(driver);
const provider = decodeServerProvider({
@@ -1131,8 +1134,34 @@ it.layer(
auth: { status: "authenticated" },
checkedAt: "2026-06-10T00:00:00.000Z",
models: [
- { slug: "claude-fixture", name: "Fixture", capabilities: null, isCustom: false },
+ { slug: routedSlug, name: "Fixture", capabilities: null, isCustom: false },
+ { slug: offlineSlug, name: "Offline", capabilities: null, isCustom: false },
+ ...(mixedCatalog
+ ? [{ slug: "morph/native", name: "Native", capabilities: null, isCustom: false }]
+ : []),
],
+ ...(mixedCatalog
+ ? {
+ workspaceSnapshots: [
+ {
+ cwd: "/project",
+ checkedAt: "2026-06-10T00:00:00.000Z",
+ slashCommands: [],
+ skills: [],
+ models: [
+ { slug: routedSlug, name: "Fixture", capabilities: null, isCustom: false },
+ { slug: offlineSlug, name: "Offline", capabilities: null, isCustom: false },
+ {
+ slug: "morph/project",
+ name: "Project",
+ capabilities: null,
+ isCustom: false,
+ },
+ ],
+ },
+ ],
+ }
+ : {}),
supportsTextGeneration: true,
textGenerationOperations: ["generateReviewGuide"],
});
@@ -1170,15 +1199,63 @@ it.layer(
for (const status of [503, 429, 200]) {
proxyStatus = status;
const providers = yield* registry.refresh();
- expect(providers[0]?.availability).toBe(status === 200 ? undefined : "unavailable");
- expect(providers[0]?.status).toBe(status === 200 ? "ready" : "error");
+ const usable = status === 200 || mixedCatalog;
+ expect(providers[0]?.availability).toBe(usable ? undefined : "unavailable");
+ expect(providers[0]?.status).toBe(usable ? "ready" : "error");
+ expect(providers[0]?.models.map((model) => model.slug)).toEqual(
+ status === 200
+ ? [routedSlug, ...(mixedCatalog ? ["morph/native"] : [])]
+ : mixedCatalog
+ ? ["morph/native"]
+ : [routedSlug, offlineSlug],
+ );
+ if (mixedCatalog) {
+ expect(
+ providers[0]?.workspaceSnapshots?.[0]?.models?.map((model) => model.slug),
+ ).toEqual(status === 200 ? [routedSlug, "morph/project"] : ["morph/project"]);
+ const merged = ProviderRegistry.mergeProviderSnapshot(
+ provider,
+ (({ workspaceSnapshots: _workspaceSnapshots, ...rest }) => rest)(providers[0]!),
+ true,
+ );
+ expect(merged.workspaceSnapshots?.[0]?.models?.map((model) => model.slug)).toEqual(
+ status === 200 ? [routedSlug, "morph/project"] : ["morph/project"],
+ );
+ const rescanned = ProviderRegistry.upsertProviderWorkspaceSnapshot(
+ providers[0]!,
+ "/project",
+ {
+ ...providers[0]!,
+ workspaceModels: [
+ { slug: routedSlug, name: "Fixture", capabilities: null, isCustom: false },
+ {
+ slug: "morph/project",
+ name: "Project",
+ capabilities: null,
+ isCustom: false,
+ },
+ ],
+ },
+ true,
+ );
+ expect(
+ rescanned.workspaceSnapshots?.[0]?.models?.map((model) => model.slug),
+ ).toEqual(status === 200 ? [routedSlug, "morph/project"] : ["morph/project"]);
+ }
}
poolAvailable = false;
yield* TestClock.adjust("16 seconds");
- expect((yield* registry.getProviders)[0]?.availability).toBe("unavailable");
+ expect((yield* registry.getProviders)[0]?.availability).toBe(
+ mixedCatalog ? undefined : "unavailable",
+ );
poolAvailable = true;
yield* TestClock.adjust("16 seconds");
expect((yield* registry.getProviders)[0]?.availability).toBeUndefined();
+ if (mixedCatalog)
+ expect((yield* registry.getProviders)[0]?.models.map((model) => model.slug)).toEqual([
+ routedSlug,
+ "morph/native",
+ ]);
}).pipe(
Effect.provide(
ProviderRegistry.layer.pipe(
@@ -1217,7 +1294,7 @@ it.layer(
inferenceHostLabel: "Host",
inferenceBaseUrl: "http://127.0.0.1:9876",
inferenceKey: "fixture-key",
- inferenceModels: ["claude-fixture"],
+ inferenceModels: ["claude-fixture", "claude-offline"],
inferenceHomePath: "/fixture",
},
},
diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.ts
index b7107764de411..4041daaeaa396 100644
--- a/apps/server/src/provider/ProviderRegistry.ts
+++ b/apps/server/src/provider/ProviderRegistry.ts
@@ -1,4 +1,7 @@
-import { makeInferenceProviderHealth } from "../inference/providerHealth.ts";
+import {
+ filterInferenceWorkspaceModels,
+ makeInferenceProviderHealth,
+} from "../inference/providerHealth.ts";
import * as SecretResolver from "../secrets/SecretResolver.ts";
import {
defaultInstanceIdForDriver,
@@ -176,6 +179,7 @@ export function upsertProviderWorkspaceSnapshot(
provider: ServerProvider,
cwd: string,
scopedSnapshot: ProviderWorkspaceSnapshot,
+ routed = false,
): ServerProvider {
const previousSnapshot = provider.workspaceSnapshots?.find((snapshot) => snapshot.cwd === cwd);
const optionDescriptors = scopedSnapshot.optionDescriptors ?? previousSnapshot?.optionDescriptors;
@@ -194,12 +198,15 @@ export function upsertProviderWorkspaceSnapshot(
...(models === undefined ? {} : { models }),
...(scopedSnapshot.workspaceModelsPending ? { modelsPending: true } : {}),
} satisfies NonNullable[number];
+ const workspaceSnapshots = [
+ ...(provider.workspaceSnapshots ?? []).filter((snapshot) => snapshot.cwd !== cwd),
+ workspaceSnapshot,
+ ].slice(-MAX_WORKSPACE_SNAPSHOTS_PER_PROVIDER);
return {
...provider,
- workspaceSnapshots: [
- ...(provider.workspaceSnapshots ?? []).filter((snapshot) => snapshot.cwd !== cwd),
- workspaceSnapshot,
- ].slice(-MAX_WORKSPACE_SNAPSHOTS_PER_PROVIDER),
+ workspaceSnapshots: routed
+ ? filterInferenceWorkspaceModels(provider, workspaceSnapshots)
+ : workspaceSnapshots,
};
}
@@ -265,8 +272,10 @@ const mergeProviderModels = (
provider: ServerProvider,
previousModels: ReadonlyArray,
nextModels: ReadonlyArray,
+ authoritativeModels = false,
): ReadonlyArray => {
- const shouldRetainMissingModels = shouldRetainMissingProviderModels(provider);
+ const shouldRetainMissingModels =
+ !authoritativeModels && shouldRetainMissingProviderModels(provider);
const updateRequiredSlugs = new Set(provider.updateRequiredModels?.map((model) => model.slug));
const retainablePreviousModels = previousModels.filter(
(model) => !model.isCustom && !updateRequiredSlugs.has(model.slug),
@@ -319,13 +328,19 @@ const carrySavedAntigravityAccount = (
export const mergeProviderSnapshot = (
previousProvider: ServerProvider | undefined,
nextProvider: ServerProvider,
+ authoritativeModels = false,
): ServerProvider => {
if (!previousProvider) {
return nextProvider;
}
const savedAccount = carrySavedAntigravityAccount(previousProvider, nextProvider);
const { message: _uncheckedMessage, ...nextWithoutMessage } = nextProvider;
- const models = mergeProviderModels(nextProvider, previousProvider.models, nextProvider.models);
+ const models = mergeProviderModels(
+ nextProvider,
+ previousProvider.models,
+ nextProvider.models,
+ authoritativeModels,
+ );
// Folder catalogs were compared with the old machine catalog, so every folder rescans.
const previousWorkspaceSnapshots = Equal.equals(models, previousProvider.models)
? previousProvider.workspaceSnapshots
@@ -333,15 +348,18 @@ export const mergeProviderSnapshot = (
...snapshot,
modelsPending: true,
}));
+ const workspaceSnapshots = nextProvider.workspaceSnapshots ?? previousWorkspaceSnapshots;
return {
...(savedAccount?.status === "ready" ? nextWithoutMessage : nextProvider),
...savedAccount,
models,
- ...(nextProvider.workspaceSnapshots !== undefined
- ? { workspaceSnapshots: nextProvider.workspaceSnapshots }
- : previousWorkspaceSnapshots !== undefined
- ? { workspaceSnapshots: previousWorkspaceSnapshots }
- : {}),
+ ...(workspaceSnapshots !== undefined
+ ? {
+ workspaceSnapshots: authoritativeModels
+ ? filterInferenceWorkspaceModels({ ...nextProvider, models }, workspaceSnapshots)
+ : workspaceSnapshots,
+ }
+ : {}),
...(nextProvider.workspaceRescannedAt === undefined &&
previousProvider.workspaceRescannedAt !== undefined
? { workspaceRescannedAt: previousProvider.workspaceRescannedAt }
@@ -592,6 +610,7 @@ export const layer = Layer.effect(
concurrency: "unbounded",
},
);
+ const routedInstanceIds = new Set(yield* inferenceHealth.instanceIds);
const [previousProviders, providers, providersToPersist] = yield* Ref.modify(
providersRef,
(previousProviders) => {
@@ -607,7 +626,11 @@ export const layer = Layer.effect(
key,
options?.replace === true
? provider
- : mergeProviderSnapshot(mergedProviders.get(key), provider),
+ : mergeProviderSnapshot(
+ mergedProviders.get(key),
+ provider,
+ routedInstanceIds.has(key),
+ ),
);
}
@@ -1153,6 +1176,9 @@ export const layer = Layer.effect(
if (input.rescan && (input.rescan !== instance || (!runningScan && !scannedFrom))) {
return providers;
}
+ const routed = new Set(yield* inferenceHealth.instanceIds).has(
+ input.instanceId,
+ );
const token = yield* Deferred.make();
// A machine refresh can change this cwd's snapshot, so the scan publishes against the result.
const refreshMachineSnapshot = input.fresh
@@ -1190,13 +1216,18 @@ export const layer = Layer.effect(
) {
return candidate;
}
- const scanned = upsertProviderWorkspaceSnapshot(candidate, input.cwd, {
- ...scopedSnapshot,
- checkedAt: scannedAt,
- // Without driver command discovery, retain previous commands after failed health checks and retry.
- slashCommandsPending:
- scopedSnapshot.slashCommandsPending ?? scopedSnapshot.status === "error",
- });
+ const scanned = upsertProviderWorkspaceSnapshot(
+ candidate,
+ input.cwd,
+ {
+ ...scopedSnapshot,
+ checkedAt: scannedAt,
+ // Without driver command discovery, retain previous commands after failed health checks and retry.
+ slashCommandsPending:
+ scopedSnapshot.slashCommandsPending ?? scopedSnapshot.status === "error",
+ },
+ routed,
+ );
// Clients keep fetched snapshots, so a changed rescan must tell them to fetch again.
const rescanned = workspaceSnapshotOf(scanned);
const held = heldBeforeWait ?? scanBase;
diff --git a/apps/server/src/usage/cliproxyApi.ts b/apps/server/src/usage/cliproxyApi.ts
index 537a2b436f4a4..d050e047da4b8 100644
--- a/apps/server/src/usage/cliproxyApi.ts
+++ b/apps/server/src/usage/cliproxyApi.ts
@@ -484,6 +484,15 @@ export const makeCliproxyApi = Effect.gen(function* () {
return { id: account.id, driver: provider.driver, ...reading };
});
+ const readClaudeUsage = Effect.fn("CliproxyApi.readClaudeUsage")(function* (
+ hub: CliproxyHub,
+ account: Pick,
+ ) {
+ const provider = HUB_PROVIDERS.get("claude")!;
+ const reading = yield* readAccount(hub, { ...account, provider: "claude" }, provider);
+ return reading.usageLimits;
+ });
+
const readAccounts = Effect.fn("CliproxyApi.readAccounts")(function* (
hub: CliproxyHub,
): Effect.fn.Return, UsageLimitSourceError> {
@@ -562,5 +571,5 @@ export const makeCliproxyApi = Effect.gen(function* () {
),
);
});
- return { readAccounts, consume };
+ return { readAccounts, readClaudeUsage, consume };
});
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index d7cdd2ad692b0..94994cdcb9832 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -2848,6 +2848,7 @@ export const layerWsRpc = (
[WS_METHODS.inferenceManage]: (input) => inference.manage(input),
[WS_METHODS.inferenceGrant]: (input) => inference.grant(input),
[WS_METHODS.inferenceConnect]: (input) => inference.connect(input),
+ [WS_METHODS.inferenceRegisterFallback]: (input) => inference.registerFallback(input),
[WS_METHODS.serverReclaimDatabaseSpace]: () => databaseStorage.requestReclaim,
[WS_METHODS.peerLinksList]: (_input) =>
peerLinks.list.pipe(Effect.map((links) => ({ links }))),
diff --git a/apps/web/src/components/InferenceFleetCoordinator.browser.test.tsx b/apps/web/src/components/InferenceFleetCoordinator.browser.test.tsx
new file mode 100644
index 0000000000000..a8fda97672673
--- /dev/null
+++ b/apps/web/src/components/InferenceFleetCoordinator.browser.test.tsx
@@ -0,0 +1,184 @@
+import { EnvironmentId, type InferenceProxyStatus } from "@t3tools/contracts";
+import { expect, it, vi } from "vite-plus/test";
+
+import { act, render } from "../../test/render";
+import type { EnvironmentPresentation } from "../state/environments";
+
+const state = vi.hoisted(() => ({
+ environments: [] as EnvironmentPresentation[],
+ statuses: new Map(),
+ version: 0,
+ listeners: new Set<() => void>(),
+ route: vi.fn(),
+ subscribe(listener: () => void) {
+ this.listeners.add(listener);
+ return () => this.listeners.delete(listener);
+ },
+ snapshot() {
+ return this.version;
+ },
+ publish() {
+ this.version += 1;
+ for (const listener of this.listeners) listener();
+ },
+}));
+
+vi.mock("../state/environments", async () => {
+ const { useSyncExternalStore } = await import("react");
+ return {
+ useEnvironments: () => {
+ useSyncExternalStore(state.subscribe.bind(state), state.snapshot.bind(state));
+ return { environments: state.environments };
+ },
+ };
+});
+vi.mock("../state/query", async () => {
+ const { useSyncExternalStore } = await import("react");
+ return {
+ useEnvironmentQuery: (environmentId: string) => {
+ useSyncExternalStore(state.subscribe.bind(state), state.snapshot.bind(state));
+ const status = state.statuses.get(environmentId);
+ return {
+ data: status?.data ?? null,
+ dataUpdatedAt: status?.dataUpdatedAt ?? 0,
+ isPending: false,
+ refresh: () => {},
+ };
+ },
+ };
+});
+vi.mock("../state/server", async () => {
+ const { Atom } = await import("effect/reactivity");
+ return {
+ serverEnvironment: {
+ inferenceProxy: {
+ canGrant: () => Atom.make(true),
+ inferenceStatus: ({ environmentId }: { environmentId: string }) => environmentId,
+ routeInference: {},
+ },
+ providersValueAtom: () => Atom.make([]),
+ },
+ };
+});
+vi.mock(import("../state/use-atom-command"), () => ({ useAtomCommand: () => state.route }));
+
+import { InferenceFleetCoordinator } from "./InferenceFleetCoordinator";
+
+const primaryId = EnvironmentId.make("primary");
+const alternateId = EnvironmentId.make("alternate");
+const consumerId = EnvironmentId.make("consumer");
+
+function environment(
+ id: typeof primaryId,
+ phase: "connected" | "disconnected",
+ routeHost?: typeof primaryId,
+): EnvironmentPresentation {
+ return {
+ environmentId: id,
+ label: id,
+ connection: { phase },
+ serverConfig: {
+ environment: { capabilities: { inferenceProxy: true } },
+ settings: {
+ providerInstances: routeHost
+ ? {
+ codex: {
+ driver: "codex",
+ enabled: true,
+ config: {
+ inferenceEnabled: true,
+ inferenceHostId: routeHost,
+ inferenceHostLabel: routeHost,
+ inferenceBaseUrl: `https://${routeHost}.example/api/inference`,
+ inferenceKey: "fixture-key",
+ inferenceModels: ["gpt-fixture"],
+ inferenceHomePath: "/fixture",
+ },
+ },
+ }
+ : {},
+ },
+ },
+ } as unknown as EnvironmentPresentation;
+}
+
+function status(available: boolean): InferenceProxyStatus {
+ return {
+ enabled: true,
+ sharing: true,
+ running: true,
+ version: "8.0.60",
+ problem: null,
+ accounts: [],
+ availableDrivers: available ? ["codex"] : [],
+ consumers: [],
+ routes: [],
+ };
+}
+
+it("registers connected fallback hosts once and reconsiders them when the primary route changes", async () => {
+ state.listeners.clear();
+ state.route.mockReset().mockResolvedValue({ _tag: "Success" });
+ state.environments = [
+ environment(primaryId, "connected"),
+ environment(alternateId, "connected"),
+ environment(consumerId, "connected", primaryId),
+ ];
+ state.statuses = new Map([
+ [primaryId, { data: status(true), dataUpdatedAt: 1 }],
+ [alternateId, { data: status(false), dataUpdatedAt: 1 }],
+ ]);
+ state.version = 0;
+
+ await using _screen = await render();
+ expect(state.route).not.toHaveBeenCalled();
+
+ await act(() => {
+ state.environments = [
+ environment(primaryId, "disconnected"),
+ environment(alternateId, "connected"),
+ environment(consumerId, "connected", primaryId),
+ ];
+ state.statuses.set(alternateId, { data: status(true), dataUpdatedAt: 2 });
+ state.publish();
+ });
+ await vi.waitFor(() => expect(state.route).toHaveBeenCalledTimes(1));
+ expect(state.route).toHaveBeenLastCalledWith({
+ host: { environmentId: alternateId, label: alternateId },
+ consumer: { environmentId: consumerId, label: consumerId },
+ driver: "codex",
+ fallback: true,
+ });
+
+ await act(() => {
+ state.statuses.set(alternateId, { data: status(true), dataUpdatedAt: 3 });
+ state.publish();
+ });
+ expect(state.route).toHaveBeenCalledTimes(1);
+
+ await act(() => {
+ state.environments = [
+ environment(primaryId, "connected"),
+ environment(alternateId, "connected"),
+ environment(consumerId, "connected", primaryId),
+ ];
+ state.publish();
+ });
+ expect(state.route).toHaveBeenCalledTimes(1);
+
+ await act(() => {
+ state.environments = [
+ environment(primaryId, "connected"),
+ environment(alternateId, "connected"),
+ environment(consumerId, "connected", alternateId),
+ ];
+ state.publish();
+ });
+ await vi.waitFor(() => expect(state.route).toHaveBeenCalledTimes(2));
+ expect(state.route).toHaveBeenLastCalledWith({
+ host: { environmentId: primaryId, label: primaryId },
+ consumer: { environmentId: consumerId, label: consumerId },
+ driver: "codex",
+ fallback: true,
+ });
+});
diff --git a/apps/web/src/components/InferenceFleetCoordinator.tsx b/apps/web/src/components/InferenceFleetCoordinator.tsx
new file mode 100644
index 0000000000000..40ad01d4ac17d
--- /dev/null
+++ b/apps/web/src/components/InferenceFleetCoordinator.tsx
@@ -0,0 +1,132 @@
+import { useAtomValue } from "@effect/atom-react";
+import {
+ inferenceFallbackKey,
+ inferenceFallbackRetryDelay,
+ planInferenceFallbacks,
+} from "@t3tools/client-runtime/state/inference-proxy";
+import { INFERENCE_DRIVERS } from "@t3tools/contracts";
+import { useEffect, useEffectEvent, useRef } from "react";
+
+import { useEnvironments, type EnvironmentPresentation } from "../state/environments";
+import { serverEnvironment } from "../state/server";
+import { useEnvironmentQuery } from "../state/query";
+import { useAtomCommand } from "../state/use-atom-command";
+
+const { inferenceProxy } = serverEnvironment;
+const STATUS_REFRESH_INTERVAL_MS = 60_000;
+
+interface Attempt {
+ readonly key: string;
+ failures: number;
+ retryAt: number;
+ state: "pending" | "failed" | "succeeded";
+}
+
+function Host({
+ host,
+ consumers,
+}: {
+ host: EnvironmentPresentation;
+ consumers: ReadonlyArray;
+}) {
+ const canGrant = useAtomValue(inferenceProxy.canGrant(host.environmentId));
+ const status = useEnvironmentQuery(
+ canGrant
+ ? inferenceProxy.inferenceStatus({ environmentId: host.environmentId, input: {} })
+ : null,
+ );
+ const route = useAtomCommand(inferenceProxy.routeInference, { reportFailure: false });
+ const providers = useAtomValue(serverEnvironment.providersValueAtom(host.environmentId));
+ const providerStatusKey = JSON.stringify(
+ providers
+ ?.filter((provider) => INFERENCE_DRIVERS.some((driver) => driver === provider.driver))
+ .map((provider) => [
+ provider.instanceId,
+ provider.status,
+ provider.auth.status,
+ provider.availability,
+ provider.limitedUntil,
+ provider.checkedAt,
+ ]),
+ );
+ const attempts = useRef(new Map());
+ const lastProviderStatus = useRef(null);
+ const candidates = status.data ? planInferenceFallbacks(host, status.data, consumers) : [];
+ const keyedCandidates = candidates.map((input) => {
+ const consumer = consumers.find(
+ (entry) => entry.environmentId === input.consumer.environmentId,
+ );
+ return {
+ input,
+ id: `${input.consumer.environmentId}:${input.driver}`,
+ key:
+ consumer && status.data
+ ? inferenceFallbackKey(input.host, consumer, input.driver, status.data)
+ : "",
+ };
+ });
+ const key = JSON.stringify([keyedCandidates, status.dataUpdatedAt]);
+ const run = useEffectEvent(() => {
+ const active = new Set(keyedCandidates.map((candidate) => candidate.id));
+ for (const id of attempts.current.keys()) if (!active.has(id)) attempts.current.delete(id);
+ for (const { input, id, key: candidateKey } of keyedCandidates) {
+ const previous = attempts.current.get(id);
+ if (previous?.key === candidateKey) {
+ if (previous.state !== "failed" || Date.now() < previous.retryAt) continue;
+ }
+ const attempt: Attempt = {
+ key: candidateKey,
+ failures: previous?.key === candidateKey ? previous.failures : 0,
+ retryAt: 0,
+ state: "pending",
+ };
+ attempts.current.set(id, attempt);
+ void route(input).then((result) => {
+ if (attempts.current.get(id) !== attempt) return;
+ if (result._tag === "Success") {
+ attempt.state = "succeeded";
+ return;
+ }
+ attempt.state = "failed";
+ attempt.failures += 1;
+ attempt.retryAt = Date.now() + inferenceFallbackRetryDelay(attempt.failures);
+ });
+ }
+ });
+ const refreshStatus = useEffectEvent(() => {
+ if (canGrant && !status.isPending) status.refresh();
+ });
+
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reconciles grants when a connected host or routed consumer changes
+ useEffect(() => {
+ run();
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- a refreshed status wakes bounded fallback retries
+ }, [key]);
+
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- provider auth changes can make a host newly available for fallback
+ useEffect(() => {
+ if (lastProviderStatus.current !== null && lastProviderStatus.current !== providerStatusKey)
+ refreshStatus();
+ lastProviderStatus.current = providerStatusKey;
+ }, [providerStatusKey]);
+
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- hosts can recover without a provider event or connection change
+ useEffect(() => {
+ if (!canGrant) return;
+ const interval = setInterval(refreshStatus, STATUS_REFRESH_INTERVAL_MS);
+ return () => clearInterval(interval);
+ }, [canGrant]);
+ return null;
+}
+
+export function InferenceFleetCoordinator() {
+ const { environments } = useEnvironments();
+ const connected = environments.filter(
+ (environment) =>
+ environment.connection.phase === "connected" &&
+ environment.serverConfig?.environment.capabilities.inferenceProxy === true,
+ );
+ return connected.map((host) => (
+
+ ));
+}
diff --git a/apps/web/src/components/settings/InferenceProviderAccounts.browser.test.tsx b/apps/web/src/components/settings/InferenceProviderAccounts.browser.test.tsx
index 5108b64b0dfaa..8feb0cde6ebab 100644
--- a/apps/web/src/components/settings/InferenceProviderAccounts.browser.test.tsx
+++ b/apps/web/src/components/settings/InferenceProviderAccounts.browser.test.tsx
@@ -22,8 +22,20 @@ function setup() {
data: {
enabled: true,
accounts: [
- { name: "work.json", provider: "codex", status: "active" },
- { name: "personal.json", provider: "claude", status: "active" },
+ {
+ name: "work.json",
+ provider: "codex",
+ status: "error",
+ availability: "rateLimited",
+ retryAfter: "2099-01-01T00:00:00Z",
+ },
+ {
+ name: "expired.json",
+ provider: "codex",
+ status: "error",
+ availability: "authenticationError",
+ },
+ { name: "personal.json", provider: "claude", status: "active", availability: "available" },
],
},
});
@@ -44,6 +56,11 @@ describe("inference provider accounts", () => {
,
);
await expect.element(screen.getByText("work.json")).toBeVisible();
+ await expect.element(screen.getByText("codex · Rate limited")).toBeVisible();
+ await expect
+ .element(screen.getByText("codex · Authentication or access rejected"))
+ .toBeVisible();
+ await expect.element(screen.getByText(/Retry after/)).toBeVisible();
await expect.element(screen.getByText("personal.json")).not.toBeInTheDocument();
await userEvent.click(screen.getByRole("button", { name: "Codex", exact: true }));
expect(state.run).toHaveBeenLastCalledWith({
diff --git a/apps/web/src/components/settings/InferenceProviderAccounts.tsx b/apps/web/src/components/settings/InferenceProviderAccounts.tsx
index 86d5d1c0854e6..11b377c9a77f8 100644
--- a/apps/web/src/components/settings/InferenceProviderAccounts.tsx
+++ b/apps/web/src/components/settings/InferenceProviderAccounts.tsx
@@ -1,5 +1,9 @@
import { useAtomValue } from "@effect/atom-react";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
+import {
+ inferenceAccountRetryAfter,
+ inferenceAccountStatus,
+} from "@t3tools/client-runtime/state/inference-proxy";
import {
type EnvironmentId,
INFERENCE_HARNESSES,
@@ -103,23 +107,33 @@ export function InferenceProviderAccounts({
<>
{host.accounts
.filter((account) => harness?.accounts?.includes(account.provider) ?? true)
- .map((account) => (
- void run({ operation: "removeAccount", name: account.name })}
- >
- Remove
-
- }
- />
- ))}
+ .map((account) => {
+ const retryAfter = inferenceAccountRetryAfter(account);
+ return (
+
+ Retry after {new Date(retryAfter).toLocaleString()}
+
+ ) : undefined
+ }
+ control={
+
+ }
+ />
+ );
+ })}
{login ? (
<>
+ status.data?.availableDrivers.includes(driver) ?? false;
const route = useAtomCommand(inferenceProxy.routeInference, { reportFailure: false });
const [busy, setBusy] = useState(false);
const [notice, setNotice] = useState("");
@@ -68,7 +70,7 @@ function InferenceRoute({
key={driver}
size="sm"
variant="outline"
- disabled={!canGrant || !canConnect || busy || !!issue}
+ disabled={!canGrant || !canConnect || busy || !!issue || !hasAccount(driver)}
onClick={() => void add(driver)}
>
{INFERENCE_HARNESSES[driver].label}
diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx
index 19c69c8c07088..0740e1d7ecac3 100644
--- a/apps/web/src/routes/__root.tsx
+++ b/apps/web/src/routes/__root.tsx
@@ -34,6 +34,7 @@ import { ReopenClosedViewShortcut } from "../components/ReopenClosedViewShortcut
import { ProjectCloneToastCoordinator } from "../components/ProjectCloneToastCoordinator";
import { ConnectDeviceApprovalCoordinator } from "../components/ConnectDeviceApprovalCoordinator";
import { ChatGptWelcomeCoordinator } from "../components/settings/ChatGptWelcomeCoordinator";
+import { InferenceFleetCoordinator } from "../components/InferenceFleetCoordinator";
import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";
import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
import { Button } from "../components/ui/button";
@@ -194,6 +195,7 @@ function RootRouteBranch() {
+
{import.meta.env.DEV && primaryEnvironmentAuthenticated ? : null}
diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md
index 8b1ed422a9267..244228628a719 100644
--- a/docs/user/providers-claude.md
+++ b/docs/user/providers-claude.md
@@ -54,6 +54,19 @@ The host receives the model request, including its prompt and tool results.
The agent runs tools and stores files and thread history on its executing environment.
Choosing another host in Settings changes the same provider. Local inference is labeled **Claude** or **Codex**.
Choose the route again in Settings to refresh its model list after changing accounts.
+While a client is connected to the executing environment and other shared inference hosts,
+T3 discovers hosts that serve the same provider and saves them as fallback routes. If the
+selected host is unreachable, rejects authentication, or reaches a temporary limit, a new
+request can use another healthy host that serves the requested model. The agent and its
+workspace stay on the executing environment. Keep at least one client connected to each
+host when adding new fallback routes; saved routes remain available afterward.
+T3 keeps a thread on the host that successfully handles its request after a switch. Each
+host selects accounts independently, so a switch between hosts with multiple eligible
+accounts may use a different account even when the same login is present on both.
+
+In **Inference accounts**, a rate-limited Claude account shows its retry time when known.
+If two hosts share that login, its subscription limit applies on both. Another host can
+serve the request if it has an eligible account for the model.
Configure account pooling on the host. Turn on round-robin routing to distribute
requests across eligible accounts, or leave it off to use the first available account.
diff --git a/docs/user/providers-opencode.md b/docs/user/providers-opencode.md
index 978de0fbd49d6..bb86a0f625e9d 100644
--- a/docs/user/providers-opencode.md
+++ b/docs/user/providers-opencode.md
@@ -70,6 +70,11 @@ You can stop the turn while it reconnects. If the server exits or an external
connection cannot be restored, send another prompt to resume the same OpenCode
session.
+OpenCode handles retries while a turn is running. If its retries run out on a rate limit
+and the provider reports when to try again, choose **Resume at reset** on the failed
+thread. T3 will continue that thread at or after the reported time. A service overload
+can also return HTTP 429. OpenCode handles those retries itself.
+
## Shared inference accounts
OpenCode can use the accounts on an [inference host](./providers-claude.md), next to
diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json
index 9c33a07c685e5..b7f39e1859976 100644
--- a/packages/client-runtime/package.json
+++ b/packages/client-runtime/package.json
@@ -299,6 +299,10 @@
"types": "./src/state/providerAccountSync.ts",
"default": "./src/state/providerAccountSync.ts"
},
+ "./state/inference-proxy": {
+ "types": "./src/state/inferenceProxy.ts",
+ "default": "./src/state/inferenceProxy.ts"
+ },
"./state/provider-instance-display": {
"types": "./src/state/providerInstanceDisplay.ts",
"default": "./src/state/providerInstanceDisplay.ts"
diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts
index a2e0b091a8fd6..fb8615d34955a 100644
--- a/packages/client-runtime/src/state/commandPermissions.test.ts
+++ b/packages/client-runtime/src/state/commandPermissions.test.ts
@@ -41,7 +41,13 @@ import {
SshConnectionTarget,
type NetworkStatus,
} from "../connection/model.ts";
-import { createInferenceProxyAtoms } from "./inferenceProxy.ts";
+import {
+ createInferenceProxyAtoms,
+ inferenceFallbackKey,
+ inferenceFallbackRetryDelay,
+ planInferenceFallbacks,
+ type InferenceFleetEnvironment,
+} from "./inferenceProxy.ts";
import { createPeerLinkEnvironmentAtoms } from "./peerLinks.ts";
vi.mock("./session.ts", () => ({
@@ -112,9 +118,14 @@ describe("command permissions", () => {
}),
);
it.effect.each([
- { via: "the connected SSH host", ssh: true },
- { via: "the grant when this client reaches the host over loopback", ssh: false },
- ])("routes through $via without forwarding the client's bearer credential", ({ ssh }) =>
+ { via: "the connected SSH host", ssh: true, fallback: false },
+ {
+ via: "the grant when this client reaches the host over loopback",
+ ssh: false,
+ fallback: false,
+ },
+ { via: "a connected SSH fallback", ssh: true, fallback: true },
+ ])("routes through $via without forwarding the client's bearer credential", ({ ssh, fallback }) =>
Effect.gen(function* () {
const registry = yield* setup;
registry.mount(sessions(other));
@@ -145,6 +156,8 @@ describe("command permissions", () => {
key: "scoped-inference-key",
};
let selected: InferenceRouteInput | undefined;
+ let automaticGrant: boolean | undefined;
+ let selectedMethod: string | undefined;
const host = {
target,
prepared: yield* SubscriptionRef.make(
@@ -160,7 +173,10 @@ describe("command permissions", () => {
session: yield* SubscriptionRef.make(
Option.some({
client: {
- [WS_METHODS.inferenceGrant]: () => Effect.succeed(issued),
+ [WS_METHODS.inferenceGrant]: (input: { automatic?: boolean }) => {
+ automaticGrant = input.automatic;
+ return Effect.succeed(issued);
+ },
},
} as unknown as RpcSession),
),
@@ -177,6 +193,12 @@ describe("command permissions", () => {
[WS_METHODS.inferenceConnect]: (input: InferenceRouteInput) =>
Effect.sync(() => {
selected = input;
+ selectedMethod = WS_METHODS.inferenceConnect;
+ }),
+ [WS_METHODS.inferenceRegisterFallback]: (input: InferenceRouteInput) =>
+ Effect.sync(() => {
+ selected = input;
+ selectedMethod = WS_METHODS.inferenceRegisterFallback;
}),
},
} as unknown as RpcSession),
@@ -207,9 +229,14 @@ describe("command permissions", () => {
host: { environmentId: env, label: "Host" },
consumer: { environmentId: other, label: "Consumer" },
driver: "codex",
+ fallback,
}),
);
expect(result._tag).toBe("Success");
+ expect(automaticGrant).toBe(fallback || undefined);
+ expect(selectedMethod).toBe(
+ fallback ? WS_METHODS.inferenceRegisterFallback : WS_METHODS.inferenceConnect,
+ );
expect(selected).toEqual({
grant: issued,
driver: "codex",
@@ -218,6 +245,95 @@ describe("command permissions", () => {
});
}),
);
+ it("discovers only connected sharing hosts for a routed provider on another host", () => {
+ const host: InferenceFleetEnvironment = {
+ environmentId: env,
+ label: "Studio",
+ connection: { phase: "connected" },
+ serverConfig: null,
+ };
+ const consumer: InferenceFleetEnvironment = {
+ environmentId: other,
+ label: "Spark",
+ connection: { phase: "connected" },
+ serverConfig: {
+ settings: {
+ providerInstances: {
+ claudeAgent: {
+ driver: "claudeAgent",
+ config: {
+ inferenceEnabled: true,
+ inferenceHostId: EnvironmentId.make("m5"),
+ inferenceHostLabel: "M5",
+ inferenceBaseUrl: "http://192.168.0.55:3773/api/inference",
+ inferenceKey: "saved-key",
+ inferenceModels: ["claude-fable-5-2"],
+ inferenceHomePath: "/state/claude",
+ },
+ },
+ },
+ },
+ } as unknown as InferenceFleetEnvironment["serverConfig"],
+ };
+ const status = {
+ enabled: true,
+ sharing: true,
+ running: true,
+ version: "8.0.76",
+ problem: null,
+ accounts: [],
+ availableDrivers: ["claudeAgent"],
+ consumers: [],
+ routes: [],
+ } as const;
+ expect(planInferenceFallbacks(host, status, [consumer])).toEqual([
+ {
+ host: { environmentId: env, label: "Studio" },
+ consumer: { environmentId: other, label: "Spark" },
+ driver: "claudeAgent",
+ fallback: true,
+ },
+ ]);
+ expect(planInferenceFallbacks(host, { ...status, sharing: false }, [consumer])).toEqual([]);
+ expect(
+ planInferenceFallbacks({ ...host, connection: { phase: "offline" } }, status, [consumer]),
+ ).toEqual([]);
+ const original = inferenceFallbackKey(host, consumer, "claudeAgent", status);
+ const reroutedConsumer: InferenceFleetEnvironment = {
+ ...consumer,
+ serverConfig: {
+ settings: {
+ providerInstances: {
+ claudeAgent: {
+ driver: "claudeAgent",
+ config: {
+ inferenceEnabled: true,
+ inferenceHostId: EnvironmentId.make("another-host"),
+ inferenceHostLabel: "Another host",
+ inferenceBaseUrl: "http://192.168.0.56:3773/api/inference",
+ inferenceKey: "saved-key",
+ inferenceModels: ["claude-fable-5-2"],
+ inferenceHomePath: "/state/claude",
+ },
+ },
+ },
+ },
+ } as unknown as InferenceFleetEnvironment["serverConfig"],
+ };
+ const rerouted = inferenceFallbackKey(host, reroutedConsumer, "claudeAgent", status);
+ expect(rerouted).not.toBe(original);
+ expect(
+ inferenceFallbackKey(host, consumer, "claudeAgent", {
+ ...status,
+ accounts: [
+ { name: "Claude", provider: "claudeAgent", status: "ready", availability: "available" },
+ ],
+ }),
+ ).not.toBe(original);
+ expect([1, 2, 3, 4, 5].map(inferenceFallbackRetryDelay)).toEqual([
+ 60_000, 120_000, 240_000, 300_000, 300_000,
+ ]);
+ });
it.effect("requires the destination orchestration grant to mutate project knowledge", () =>
Effect.gen(function* () {
const registry = yield* setup;
diff --git a/packages/client-runtime/src/state/inferenceProxy.ts b/packages/client-runtime/src/state/inferenceProxy.ts
index f5ef6e45b982e..18f1df840b5c8 100644
--- a/packages/client-runtime/src/state/inferenceProxy.ts
+++ b/packages/client-runtime/src/state/inferenceProxy.ts
@@ -1,4 +1,13 @@
-import { type InferenceConsumer, type InferenceDriver, WS_METHODS } from "@t3tools/contracts";
+import {
+ defaultInstanceIdForDriver,
+ INFERENCE_DRIVERS,
+ isInferenceProviderConfig,
+ ProviderDriverKind,
+ type InferenceConsumer,
+ type InferenceDriver,
+ type InferenceProxyStatus,
+ WS_METHODS,
+} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as SubscriptionRef from "effect/SubscriptionRef";
@@ -9,6 +18,7 @@ import type { Atom } from "effect/reactivity";
import { EnvironmentRegistry } from "../connection/registry.ts";
import { requestGuarded } from "../rpc/client.ts";
import { createCommandPermissions } from "./commandPermissions.ts";
+import type { EnvironmentServerConfig } from "../connection/presentation.ts";
import {
createEnvironmentRpcCommand,
createEnvironmentGuardedRpcQueryAtomFamily,
@@ -16,6 +26,103 @@ import {
withEnvironmentRpcPermissions,
} from "./runtime.ts";
+export interface InferenceFleetEnvironment extends InferenceConsumer {
+ readonly connection: { readonly phase: string };
+ readonly serverConfig: EnvironmentServerConfig | null;
+}
+
+type InferenceAccount = InferenceProxyStatus["accounts"][number];
+
+const accountAvailabilityLabels = {
+ available: "Active",
+ authenticationError: "Authentication or access rejected",
+ rateLimited: "Rate limited",
+ unavailable: "Unavailable",
+ disabled: "Disabled",
+} as const;
+
+export function inferenceAccountStatus(account: InferenceAccount): string {
+ return accountAvailabilityLabels[account.availability];
+}
+
+export function inferenceAccountRetryAfter(account: InferenceAccount): string | null {
+ return account.availability === "rateLimited" ? (account.retryAfter ?? null) : null;
+}
+
+export function planInferenceFallbacks(
+ host: InferenceFleetEnvironment,
+ status: InferenceProxyStatus,
+ consumers: ReadonlyArray,
+): ReadonlyArray<{
+ host: InferenceConsumer;
+ consumer: InferenceConsumer;
+ driver: InferenceDriver;
+ fallback: true;
+}> {
+ if (!status.enabled || !status.running || host.connection.phase !== "connected") return [];
+ return consumers.flatMap((consumer) => {
+ const config = consumer.serverConfig;
+ if (consumer.connection.phase !== "connected" || !config) return [];
+ if (host.environmentId !== consumer.environmentId && !status.sharing) return [];
+ return INFERENCE_DRIVERS.flatMap((driver) => {
+ if (!status.availableDrivers.includes(driver)) return [];
+ const instance =
+ config.settings.providerInstances[
+ defaultInstanceIdForDriver(ProviderDriverKind.make(driver))
+ ];
+ const route = instance?.config;
+ return instance?.enabled !== false &&
+ isInferenceProviderConfig(route) &&
+ route.inferenceEnabled &&
+ route.inferenceHostId !== host.environmentId
+ ? [
+ {
+ host: { environmentId: host.environmentId, label: host.label },
+ consumer: { environmentId: consumer.environmentId, label: consumer.label },
+ driver,
+ fallback: true as const,
+ },
+ ]
+ : [];
+ });
+ });
+}
+
+export function inferenceFallbackKey(
+ host: InferenceConsumer,
+ consumer: InferenceFleetEnvironment,
+ driver: InferenceDriver,
+ status: InferenceProxyStatus,
+): string {
+ const instance =
+ consumer.serverConfig?.settings.providerInstances[
+ defaultInstanceIdForDriver(ProviderDriverKind.make(driver))
+ ];
+ const route = instance?.config;
+ return JSON.stringify([
+ host.environmentId,
+ consumer.environmentId,
+ driver,
+ isInferenceProviderConfig(route) ? route.inferenceHostId : null,
+ isInferenceProviderConfig(route) ? route.inferenceBaseUrl : null,
+ status.enabled,
+ status.sharing,
+ status.running,
+ status.availableDrivers,
+ status.accounts.map((account) => [
+ account.name,
+ account.provider,
+ account.status,
+ account.availability,
+ account.retryAfter,
+ ]),
+ ]);
+}
+
+export function inferenceFallbackRetryDelay(failures: number): number {
+ return Math.min(60_000 * 2 ** Math.min(failures - 1, 3), 300_000);
+}
+
export function createInferenceProxyAtoms(
runtime: Atom.AtomRuntime,
) {
@@ -41,14 +148,26 @@ export function createInferenceProxyAtoms(
});
const hostPermission = createCommandPermissions(runtime, WS_METHODS.inferenceGrant);
const consumerPermission = createCommandPermissions(runtime, WS_METHODS.inferenceConnect);
+ const fallbackPermission = createCommandPermissions(
+ runtime,
+ WS_METHODS.inferenceRegisterFallback,
+ );
const routeInference = createRuntimeCommand(runtime, {
label: "inference:route",
execute: Effect.fn("InferenceProxy.route")(
function* (
- input: { host: InferenceConsumer; consumer: InferenceConsumer; driver: InferenceDriver },
+ input: {
+ host: InferenceConsumer;
+ consumer: InferenceConsumer;
+ driver: InferenceDriver;
+ fallback?: boolean;
+ },
registry: AtomRegistry.AtomRegistry,
) {
- yield* consumerPermission.authorize(registry, input.consumer.environmentId);
+ yield* (input.fallback ? fallbackPermission : consumerPermission).authorize(
+ registry,
+ input.consumer.environmentId,
+ );
const connections = yield* EnvironmentRegistry;
const { grant, prepared } = yield* connections.run(
input.host.environmentId,
@@ -56,6 +175,7 @@ export function createInferenceProxyAtoms(
const grant = yield* requestGuarded(WS_METHODS.inferenceGrant, {
environmentId: input.consumer.environmentId,
label: input.consumer.label,
+ ...(input.fallback ? { automatic: true } : {}),
});
const supervisor = yield* EnvironmentSupervisor;
return { grant, prepared: yield* SubscriptionRef.get(supervisor.prepared) };
@@ -85,19 +205,24 @@ export function createInferenceProxyAtoms(
);
const connection =
active && reachable ? { url: active.httpBaseUrl, ...(ssh ? { ssh } : {}) } : undefined;
- registry.refresh(inferenceStatus({ environmentId: input.host.environmentId, input: {} }));
+ if (!input.fallback)
+ registry.refresh(inferenceStatus({ environmentId: input.host.environmentId, input: {} }));
yield* connections.run(
input.consumer.environmentId,
- requestGuarded(WS_METHODS.inferenceConnect, {
- grant,
- driver: input.driver,
- hostLabel: input.host.label,
- ...(connection ? { connection } : {}),
- }),
- );
- registry.refresh(
- inferenceStatus({ environmentId: input.consumer.environmentId, input: {} }),
+ requestGuarded(
+ input.fallback ? WS_METHODS.inferenceRegisterFallback : WS_METHODS.inferenceConnect,
+ {
+ grant,
+ driver: input.driver,
+ hostLabel: input.host.label,
+ ...(connection ? { connection } : {}),
+ },
+ ),
);
+ if (!input.fallback)
+ registry.refresh(
+ inferenceStatus({ environmentId: input.consumer.environmentId, input: {} }),
+ );
},
(effect, _input, registry) =>
effect.pipe(
@@ -113,5 +238,6 @@ export function createInferenceProxyAtoms(
routeInference,
canGrant: hostPermission.permissionAtom,
canConnect: consumerPermission.permissionAtom,
+ canRegisterFallback: fallbackPermission.permissionAtom,
};
}
diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts
index 06b7855f445c7..b105956f9b5d9 100644
--- a/packages/contracts/src/clientRpcPermissions.ts
+++ b/packages/contracts/src/clientRpcPermissions.ts
@@ -77,6 +77,7 @@ export const CLIENT_GUARDED_RPC_SCOPES = {
[WS_METHODS.inferenceManage]: AuthProvidersManageScope,
[WS_METHODS.inferenceGrant]: AuthProvidersManageScope,
[WS_METHODS.inferenceConnect]: AuthProvidersManageScope,
+ [WS_METHODS.inferenceRegisterFallback]: AuthProvidersManageScope,
[WS_METHODS.providerAccountExport]: AuthProvidersManageScope,
[WS_METHODS.providerAccountImport]: AuthProvidersManageScope,
diff --git a/packages/contracts/src/inferenceProxy.ts b/packages/contracts/src/inferenceProxy.ts
index 4bb876e2238a4..30db397365c52 100644
--- a/packages/contracts/src/inferenceProxy.ts
+++ b/packages/contracts/src/inferenceProxy.ts
@@ -65,6 +65,12 @@ export const inferenceHarness = (driver: string): InferenceHarness | undefined =
export const InferenceConsumer = Schema.Struct({ environmentId: EnvironmentId, label: Label });
export type InferenceConsumer = typeof InferenceConsumer.Type;
+export const InferenceGrantInput = Schema.Struct({
+ ...InferenceConsumer.fields,
+ automatic: Schema.optionalKey(Schema.Boolean),
+});
+export type InferenceGrantInput = typeof InferenceGrantInput.Type;
+
const Strategy = Schema.Literals(["round-robin", "fill-first"]);
export const InferenceRouting = Schema.Struct({
strategy: Strategy,
@@ -84,8 +90,21 @@ export const InferenceProxyStatus = Schema.Struct({
routing: Schema.optionalKey(InferenceRouting),
problem: Schema.NullOr(Schema.String),
accounts: Schema.Array(
- Schema.Struct({ name: Schema.String, provider: Schema.String, status: Schema.String }),
+ Schema.Struct({
+ name: Schema.String,
+ provider: Schema.String,
+ status: Schema.String,
+ availability: Schema.Literals([
+ "available",
+ "authenticationError",
+ "rateLimited",
+ "unavailable",
+ "disabled",
+ ]),
+ retryAfter: Schema.optionalKey(Schema.String),
+ }),
),
+ availableDrivers: Schema.Array(InferenceDriver),
consumers: Schema.Array(InferenceConsumer),
routes: Schema.Array(Schema.Struct({ instanceId: ProviderInstanceId, label: Schema.String })),
});
@@ -96,7 +115,9 @@ export function inferenceRouteIssue(host: InferenceProxyStatus | null, local: bo
if (!host.enabled) return "Enable inference hosting on this environment first.";
if (!host.running) return host.problem ?? "The inference host is stopped.";
if (!local && !host.sharing) return "Enable sharing on the host first.";
- if (!host.accounts.length) return "Add a provider account on the host first.";
+ if (!host.accounts.length && !host.availableDrivers.length)
+ return "Add a provider account on the host first.";
+ if (host.availableDrivers.length === 0) return "All hosted accounts are unavailable.";
return null;
}
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index 197f6c151daef..2abbb7050d3e7 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -1,5 +1,5 @@
import {
- InferenceConsumer,
+ InferenceGrantInput,
InferenceProxyStatus,
InferenceProxyAction,
InferenceProxyActionResult,
@@ -613,6 +613,7 @@ export const WS_METHODS = {
inferenceManage: "inference.manage",
inferenceGrant: "inference.grant",
inferenceConnect: "inference.connect",
+ inferenceRegisterFallback: "inference.registerFallback",
serverReclaimDatabaseSpace: "server.reclaimDatabaseSpace",
peerLinksList: "peerLinks.list",
peerLinksLink: "peerLinks.link",
@@ -961,7 +962,7 @@ const WsInferenceManageRpc = Rpc.make(WS_METHODS.inferenceManage, {
error: Schema.Union([InferenceProxyError, EnvironmentAuthorizationError]),
});
const WsInferenceGrantRpc = Rpc.make(WS_METHODS.inferenceGrant, {
- payload: InferenceConsumer,
+ payload: InferenceGrantInput,
success: InferenceRouteGrant,
error: Schema.Union([InferenceProxyError, EnvironmentAuthorizationError]),
});
@@ -970,6 +971,11 @@ const WsInferenceConnectRpc = Rpc.make(WS_METHODS.inferenceConnect, {
success: Schema.Void,
error: Schema.Union([InferenceProxyError, EnvironmentAuthorizationError]),
});
+const WsInferenceRegisterFallbackRpc = Rpc.make(WS_METHODS.inferenceRegisterFallback, {
+ payload: InferenceRouteInput,
+ success: Schema.Void,
+ error: Schema.Union([InferenceProxyError, EnvironmentAuthorizationError]),
+});
const WsServerReclaimDatabaseSpaceRpc = Rpc.make(WS_METHODS.serverReclaimDatabaseSpace, {
payload: Schema.Struct({}),
error: Schema.Union([DatabaseReclaimError, EnvironmentAuthorizationError]),
@@ -2454,6 +2460,7 @@ export const WsRpcGroup = RpcGroup.make(
WsInferenceManageRpc,
WsInferenceGrantRpc,
WsInferenceConnectRpc,
+ WsInferenceRegisterFallbackRpc,
WsPeerLinksListRpc,
WsPeerLinksLinkRpc,
WsPeerLinksUnlinkRpc,
diff --git a/packages/provider-opencode/src/server/adapter.test.ts b/packages/provider-opencode/src/server/adapter.test.ts
index 387c71afe0992..891a14adbc428 100644
--- a/packages/provider-opencode/src/server/adapter.test.ts
+++ b/packages/provider-opencode/src/server/adapter.test.ts
@@ -635,46 +635,86 @@ describe("OpenCodeAdapterV2", () => {
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
);
- it.effect("classifies APIError 429 as a usage limit", () =>
- Effect.gen(function* () {
- const nativeEvents = asyncEventStream();
- const harness = yield* makeOpenCodeRuntimeHarness("usage-limit", "root", {
- event: { subscribe: async () => ({ stream: nativeEvents.stream }) },
- session: {
- create: async () => ({ data: { id: "root", time: { created: 1, updated: 1 } } }),
- promptAsync: async () => ({ data: true }),
- abort: async () => ({ data: true }),
- children: async () => ({ data: [] }),
- },
- });
- yield* harness.startTurn();
- const received = yield* harness.runtime.events.pipe(
- Stream.takeUntil((event) => event.type === "turn.terminal"),
- Stream.runCollect,
- Effect.forkScoped,
- );
- yield* Effect.promise(() =>
- nativeEvents.push({
- type: "session.error",
- properties: {
- sessionID: "root",
- error: {
- name: "APIError",
- data: {
- message: "Provider rejected request",
- statusCode: 429,
- isRetryable: true,
+ it.effect.each([
+ {
+ name: "a token rate limit",
+ message: "Token rate limit reached",
+ responseBody: JSON.stringify({ error: { code: "rate_limit_exceeded" } }),
+ failureClass: "usage_limit",
+ reset: true,
+ },
+ {
+ name: "a temporary service overload",
+ message: "Service temporarily overloaded",
+ responseBody: JSON.stringify({
+ error: { code: "service_overloaded", message: "Service temporarily overloaded" },
+ }),
+ failureClass: "provider_error",
+ reset: false,
+ },
+ {
+ name: "an overload identified by its response body",
+ message: "Request failed",
+ responseBody: JSON.stringify({ error: { code: "service_overloaded" } }),
+ failureClass: "provider_error",
+ reset: false,
+ },
+ {
+ name: "an overload identified by its native message",
+ message: "Service temporarily overloaded",
+ responseBody: "",
+ failureClass: "provider_error",
+ reset: false,
+ },
+ ] as const)(
+ "classifies APIError 429 for $name",
+ ({ message, responseBody, failureClass, reset }) =>
+ Effect.gen(function* () {
+ const observedAt = yield* DateTime.now;
+ const nativeEvents = asyncEventStream();
+ const harness = yield* makeOpenCodeRuntimeHarness("usage-limit", "root", {
+ event: { subscribe: async () => ({ stream: nativeEvents.stream }) },
+ session: {
+ create: async () => ({ data: { id: "root", time: { created: 1, updated: 1 } } }),
+ promptAsync: async () => ({ data: true }),
+ abort: async () => ({ data: true }),
+ children: async () => ({ data: [] }),
+ },
+ });
+ yield* harness.startTurn();
+ const received = yield* harness.runtime.events.pipe(
+ Stream.takeUntil((event) => event.type === "turn.terminal"),
+ Stream.runCollect,
+ Effect.forkScoped,
+ );
+ yield* Effect.promise(() =>
+ nativeEvents.push({
+ type: "session.error",
+ properties: {
+ sessionID: "root",
+ error: {
+ name: "APIError",
+ data: {
+ message,
+ statusCode: 429,
+ isRetryable: true,
+ responseHeaders: { "Retry-After": "2" },
+ responseBody,
+ },
},
},
- },
- }),
- );
- const terminal = (yield* Fiber.join(received)).find(
- (event) => event.type === "turn.terminal",
- );
- assert.equal(terminal?.status, "failed");
- assert.equal(terminal?.failure?.class, "usage_limit");
- }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
+ }),
+ );
+ const terminal = (yield* Fiber.join(received)).find(
+ (event) => event.type === "turn.terminal",
+ );
+ assert.equal(terminal?.status, "failed");
+ assert.equal(terminal?.failure?.class, failureClass);
+ assert.equal(
+ terminal?.failure?.resetAt,
+ reset ? DateTime.formatIso(DateTime.add(observedAt, { seconds: 2 })) : undefined,
+ );
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
);
it.effect("applies a changed runtime policy to the session on resume and turn start", () =>
diff --git a/packages/provider-opencode/src/server/adapter.ts b/packages/provider-opencode/src/server/adapter.ts
index 05819e5619d79..adb4f95a10b18 100644
--- a/packages/provider-opencode/src/server/adapter.ts
+++ b/packages/provider-opencode/src/server/adapter.ts
@@ -69,7 +69,10 @@ import {
} from "@t3tools/provider-core/server/orchestrationInstructions";
import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
import * as OpenCodeRuntime from "./OpenCodeRuntime.ts";
-import { readableProviderErrorMessage } from "./providerErrorMessage.ts";
+import {
+ isExplicitProviderOverload,
+ readableProviderErrorMessage,
+} from "./providerErrorMessage.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
@@ -94,6 +97,21 @@ export const OPENCODE_NATIVE_CHILD_INSTRUCTIONS =
"Use `delegate_task` for child work using project memory, conversation summaries, or code graph; native OpenCode subagents do not inherit T3's session instructions.";
const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({});
+const retryAfterResetAt = (
+ headers: Readonly> | undefined,
+ observedAt: DateTime.Utc,
+): string | null => {
+ const value = Object.entries(headers ?? {})
+ .find(([name]) => name.toLowerCase() === "retry-after")?.[1]
+ ?.trim();
+ if (!value) return null;
+ const nowMs = DateTime.toEpochMillis(observedAt);
+ const resetMs = /^\d+$/.test(value) ? nowMs + Number(value) * 1_000 : Date.parse(value);
+ if (!Number.isSafeInteger(resetMs) || resetMs <= nowMs) return null;
+ const reset = DateTime.make(resetMs);
+ return Option.isSome(reset) ? DateTime.formatIso(reset.value) : null;
+};
+
const makeOpenCodeMessageId = Effect.fnUntraced(function* (
clock: Ref.Ref<{ readonly epochMillis: number; readonly counter: number }>,
) {
@@ -3205,11 +3223,25 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
(state): state is OpenCodeThreadState => state !== undefined,
);
const error = event.properties.error;
- const usageLimit = error?.name === "APIError" && error.data.statusCode === 429;
+ const usageLimit =
+ error?.name === "APIError" &&
+ error.data.statusCode === 429 &&
+ !isExplicitProviderOverload({
+ message: error.data.message,
+ responseBody: error.data.responseBody,
+ });
const failure = makeProviderFailure({
message: openCodeErrorMessage(event),
code: error?.name ?? null,
class: usageLimit ? "usage_limit" : "provider_error",
+ ...(usageLimit
+ ? {
+ resetAt: retryAfterResetAt(
+ error?.name === "APIError" ? error.data.responseHeaders : undefined,
+ yield* DateTime.now,
+ ),
+ }
+ : {}),
});
if (
!isMessageAbortedError(event) &&
diff --git a/packages/provider-opencode/src/server/providerErrorMessage.ts b/packages/provider-opencode/src/server/providerErrorMessage.ts
index 5a7328da4bd96..cffd343f89273 100644
--- a/packages/provider-opencode/src/server/providerErrorMessage.ts
+++ b/packages/provider-opencode/src/server/providerErrorMessage.ts
@@ -16,3 +16,35 @@ export function readableProviderErrorMessage(
? "The model provider failed the request and did not include an error message."
: undefined;
}
+
+export function isExplicitProviderOverload(error: {
+ readonly code?: string | undefined;
+ readonly message?: string | undefined;
+ readonly responseBody?: string | undefined;
+}): boolean {
+ const isOverloadCode = (value: unknown) =>
+ typeof value === "string" &&
+ /^(?:service[._-]overloaded|server[._-]overloaded|provider[._-]overloaded|overloaded[._-]error|overload[._-]error)$/.test(
+ value.toLowerCase(),
+ );
+ if (isOverloadCode(error.code)) return true;
+ if (
+ /\b(?:service|server|provider|upstream)\s+(?:(?:is|was)\s+)?(?:temporarily\s+)?overloaded\b/i.test(
+ error.message ?? "",
+ )
+ )
+ return true;
+ if (!error.responseBody) return false;
+ try {
+ const body: unknown = JSON.parse(error.responseBody);
+ if (isOverloadCode(body)) return true;
+ if (typeof body !== "object" || body === null) return false;
+ const record = body as Record;
+ if (isOverloadCode(record.code) || isOverloadCode(record.type)) return true;
+ if (typeof record.error !== "object" || record.error === null) return false;
+ const nested = record.error as Record;
+ return isOverloadCode(nested.code) || isOverloadCode(nested.type);
+ } catch {
+ return false;
+ }
+}
diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts
index 1cede7712d6d3..681c216087acf 100644
--- a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts
+++ b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts
@@ -6,6 +6,7 @@ import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Exit from "effect/Exit";
import * as Scope from "effect/Scope";
+import * as Stream from "effect/Stream";
import * as Layer from "effect/Layer";
import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
@@ -83,6 +84,50 @@ describe("OpenCode2Client event subscription", () => {
assert.isTrue(Cause.isTimeoutError(error.cause));
}),
);
+
+ it.effect("retains a terminal retry hint that the pinned protocol schema does not include", () =>
+ Effect.gen(function* () {
+ const native = {
+ id: "evt_failed0000",
+ created: Date.parse("2026-11-17T12:00:00.000Z"),
+ type: "session.execution.failed",
+ durable: { aggregateID: "ses_test", seq: 1, version: 1 },
+ data: {
+ sessionID: "ses_test",
+ error: {
+ type: "provider.quota",
+ message: "Quota reached",
+ status: 429,
+ retryAfterMs: 90_000,
+ },
+ },
+ };
+ const transport = Layer.succeed(
+ HttpClient.HttpClient,
+ HttpClient.make((request) =>
+ Effect.succeed(
+ HttpClientResponse.fromWeb(
+ request,
+ new Response(`data: ${JSON.stringify(native)}\n\n`, {
+ headers: { "content-type": "text/event-stream" },
+ }),
+ ),
+ ),
+ ),
+ );
+ const opencode = yield* OpenCode2Client.OpenCode2Client.pipe(
+ Effect.provide(OpenCode2Client.layer.pipe(Layer.provide(transport))),
+ );
+ const { events } = yield* opencode.connect({
+ baseUrl: "http://127.0.0.1:4096",
+ password: "test-password",
+ });
+ const first = yield* events.pipe(Effect.flatMap(Stream.runHead));
+ assert.equal(first._tag, "Some");
+ if (first._tag === "Some" && first.value.type === "session.execution.failed")
+ assert.equal(Reflect.get(first.value.data.error, "retryAfterMs"), 90_000);
+ }),
+ );
});
const previous = {
diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Client.ts b/packages/provider-opencode/src/server/v2/OpenCode2Client.ts
index 1cc1190de00dc..e3fb9c14561ca 100644
--- a/packages/provider-opencode/src/server/v2/OpenCode2Client.ts
+++ b/packages/provider-opencode/src/server/v2/OpenCode2Client.ts
@@ -50,8 +50,17 @@ export class OpenCode2SilentStreamError extends Schema.TaggedError;
+
export type OpenCode2StreamEvent =
- | OpenCodeEvent
+ | Exclude
+ | (TerminalFailure & {
+ readonly data: TerminalFailure["data"] & {
+ readonly error: TerminalFailure["data"]["error"] & {
+ readonly retryAfterMs?: number;
+ };
+ };
+ })
| OpenCode2UnreadableTerminal
| OpenCode2UnreadableStart;
@@ -134,6 +143,14 @@ const SILENT_STREAM_TIMEOUT = "45 seconds";
const SUBSCRIPTION_TIMEOUT = "10 seconds";
const decodeEvent = Schema.decodeUnknownResult(Schema.fromJsonString(OpenCodeEvent));
+const decodeRetryHint = Schema.decodeUnknownOption(
+ Schema.fromJsonString(
+ Schema.Struct({
+ type: Schema.Literal("session.execution.failed"),
+ data: Schema.Struct({ error: Schema.Struct({ retryAfterMs: Schema.Finite }) }),
+ }),
+ ),
+);
const decodeEnvelope = Schema.decodeUnknownOption(
Schema.fromJsonString(
Schema.Struct({
@@ -190,9 +207,26 @@ const readEvents = HttpClient.HttpClient.pipe(
Stream.pipeThroughChannel(Sse.decode()),
Stream.filterMapEffect((frame) => {
const decoded = decodeEvent(frame.data);
- return Result.isSuccess(decoded)
- ? Effect.succeed(Result.succeed(decoded.success))
- : undecodable(frame.data);
+ if (Result.isFailure(decoded)) return undecodable(frame.data);
+ const event = decoded.success;
+ const hint =
+ event.type === "session.execution.failed" ? decodeRetryHint(frame.data) : Option.none();
+ return Effect.succeed(
+ Result.succeed(
+ event.type === "session.execution.failed" && Option.isSome(hint)
+ ? {
+ ...event,
+ data: {
+ ...event.data,
+ error: {
+ ...event.data.error,
+ retryAfterMs: hint.value.data.error.retryAfterMs,
+ },
+ },
+ }
+ : event,
+ ),
+ );
}),
),
),
diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts
index b43eeb0f7ff80..8f65f01365fcc 100644
--- a/packages/provider-opencode/src/server/v2/adapter.ts
+++ b/packages/provider-opencode/src/server/v2/adapter.ts
@@ -65,7 +65,10 @@ import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import * as OpenCode2Client from "./OpenCode2Client.ts";
import * as OpenCode2Server from "./OpenCode2Server.ts";
import * as OpenCodeRuntime from "../OpenCodeRuntime.ts";
-import { readableProviderErrorMessage } from "../providerErrorMessage.ts";
+import {
+ isExplicitProviderOverload,
+ readableProviderErrorMessage,
+} from "../providerErrorMessage.ts";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
import {
@@ -673,10 +676,25 @@ const isUsageLimit = (error: {
readonly type: string;
readonly status?: number | undefined;
readonly message: string;
+ readonly response?: { readonly body: string } | undefined;
}) =>
- (error.type === "provider.quota" && error.status !== 402) ||
- error.type === "provider.rate-limit" ||
- claudeUsageLimit(error.message) !== undefined;
+ isExplicitProviderOverload({
+ code: error.type,
+ message: error.message,
+ responseBody: error.response?.body,
+ })
+ ? false
+ : (error.type === "provider.quota" && error.status !== 402) ||
+ error.type === "provider.rate-limit" ||
+ error.status === 429 ||
+ claudeUsageLimit(error.message) !== undefined;
+
+const retryResetAt = (created: number, retryAfterMs: number | undefined): string | null => {
+ if (retryAfterMs === undefined || !Number.isSafeInteger(retryAfterMs) || retryAfterMs <= 0)
+ return null;
+ const reset = DateTime.make(created + retryAfterMs);
+ return Option.isSome(reset) ? DateTime.formatIso(reset.value) : null;
+};
const INTERRUPT_TIMEOUT = 10_000;
const INSTRUCTIONS_KEY = "t3-code";
@@ -2952,13 +2970,17 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
return yield* endExecution(state, turn, { status: "interrupted" });
case "session.execution.failed": {
const { type, message, status, response } = event.data.error;
+ const usageLimit = isUsageLimit(event.data.error);
return yield* endExecution(state, turn, {
status: "failed",
failure: makeProviderFailure({
message: readableProviderErrorMessage(message, status, response?.body),
code: type,
- class: isUsageLimit(event.data.error) ? "usage_limit" : "provider_error",
- resetAt: claudeUsageLimit(message)?.resetAt ?? null,
+ class: usageLimit ? "usage_limit" : "provider_error",
+ resetAt: usageLimit
+ ? (claudeUsageLimit(message)?.resetAt ??
+ retryResetAt(event.created, event.data.error.retryAfterMs))
+ : null,
}),
});
}