@devries-cameron20 / t3code Mirror · read-only / commits / 6843eff7c4
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 08:15 UTC

fix(opencode): recover Go limits after a startup timeout (#27757)

Co-authored-by: maria-rcks <maria@kuuro.net>

Lakshmi Tanmay committed Nov 1, 2026 at 08:11 UTC 6843eff7c46b157c901be8d3e54083a0528fb586
3 files changed +222 -13
packages/provider-core/src/server/managedProvider.ts
+37 -3
@@ -44,6 +44,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
44 readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
45 readonly initialSnapshot: (settings: Settings) => Effect.Effect<ServerProvider>;
46 readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;
47 + readonly checkUsageLimits?: Effect.Effect<ServerProvider["usageLimits"]>;
48 readonly invalidateUsageCache?: Effect.Effect<void>;
49 readonly enrichSnapshot?: (input: {
50 readonly settings: Settings;
@@ -250,14 +251,45 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
251 );
252 });
253
254 + const needsUsageRecovery = (snapshot: ServerProvider) =>
255 + input.checkUsageLimits !== undefined &&
256 + snapshot.installed &&
257 + snapshot.status === "ready" &&
258 + snapshot.auth.status === "authenticated" &&
259 + snapshot.usageLimits?.unavailable?.reason === "probeFailed";
260 +
261 + const needsProviderRefresh = (snapshot: ServerProvider) =>
262 + input.refreshOnInterval !== false &&
263 + (typeof input.refreshOnInterval !== "function" || input.refreshOnInterval(snapshot));
264 +
265 + const refreshOnInterval = Effect.fn("ManagedServerProvider.refreshOnInterval")(function* () {
266 + const { snapshot } = yield* Ref.get(snapshotStateRef);
267 + if (!snapshot.enabled) return;
268 + if (!needsUsageRecovery(snapshot) || !input.checkUsageLimits) {
269 + if (needsProviderRefresh(snapshot)) {
270 + yield* applySnapshotBase(yield* input.getSettings, { forceRefresh: true });
271 + }
272 + return;
273 + }
274 + const probed = yield* input.checkUsageLimits;
275 + const next = yield* Ref.modify(snapshotStateRef, (state) => {
276 + const usageLimits = resolveUsageLimitsAfterProbe({
277 + published: state.snapshot.usageLimits,
278 + probed,
279 + });
280 + const snapshot = withUsageLimits(state.snapshot, usageLimits);
281 + return [snapshot, { ...state, snapshot }] as const;
282 + });
283 + yield* PubSub.publish(changesPubSub, next);
284 + });
285 +
286 const shouldRefreshOnInterval = Effect.gen(function* () {
287 const state = yield* Ref.get(snapshotStateRef);
288 // A disabled instance has nothing to probe; a periodic check would only
289 // republish a snapshot that differs in checkedAt.
290 if (
291 !state.snapshot.enabled ||
259 - input.refreshOnInterval === false ||
260 - (typeof input.refreshOnInterval === "function" && !input.refreshOnInterval(state.snapshot))
292 + (!needsUsageRecovery(state.snapshot) && !needsProviderRefresh(state.snapshot))
293 ) {
294 return false;
295 }
@@ -317,7 +349,9 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
349 intervalElapsed && Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) > 0
350 ? shouldRefreshOnInterval.pipe(
351 Effect.flatMap((shouldRefresh) =>
320 - shouldRefresh ? refreshSnapshot().pipe(Effect.asVoid) : Effect.void,
352 + shouldRefresh
353 + ? refreshSemaphore.withPermits(1)(refreshOnInterval())
354 + : Effect.void,
355 ),
356 )
357 : Effect.void,
packages/provider-opencode/src/server/driver.test.ts
+173 -1
@@ -5,11 +5,12 @@ import * as NodePath from "node:path";
5
6 import * as NodeServices from "@effect/platform-node/NodeServices";
7 import { assert, it } from "@effect/vitest";
8 -import { ProviderInstanceId } from "@t3tools/contracts";
8 +import { DEFAULT_SERVER_SETTINGS, ProviderInstanceId } from "@t3tools/contracts";
9 import type { OpenCodeSettings } from "../settings.ts";
10 import * as HostProcess from "@t3tools/shared/HostProcess";
11 import * as Deferred from "effect/Deferred";
12 import * as Effect from "effect/Effect";
13 +import * as Duration from "effect/Duration";
14 import * as Fiber from "effect/Fiber";
15 import * as Layer from "effect/Layer";
16 import * as Logger from "effect/Logger";
@@ -264,6 +265,177 @@ it.layer(layer)("OpenCodeDriver runtime selection", (it) => {
265 assert.strictEqual(requested.length, readsAfterRejection);
266 }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
267 );
268 +
269 + it.effect.each(
270 + [
271 + { name: "recovers" },
272 + { name: "skips without demand", demand: false },
273 + { name: "respects a disabled interval", intervalOff: true },
274 + { name: "skips disabled instances", enabled: false },
275 + { name: "skips unsupported usage", unsupported: true },
276 + ].map((scenario) => ({
277 + enabled: true,
278 + demand: true,
279 + intervalOff: false,
280 + unsupported: false,
281 + ...scenario,
282 + })),
283 + )("Go usage recovery $name without restarting a ready catalog", (scenario) =>
284 + Effect.gen(function* () {
285 + const usageStarted = yield* Deferred.make<void>();
286 + let usageReads = 0;
287 + let serverStarts = 0;
288 + let modelReads = 0;
289 + const server = HttpClient.make((request) => {
290 + if (request.url === "https://opencode.ai/zen/go/v1/usage") {
291 + usageReads += 1;
292 + assert.strictEqual(request.headers.authorization, "Bearer test-go-key");
293 + if (scenario.unsupported)
294 + return Effect.succeed(
295 + HttpClientResponse.fromWeb(request, new Response(null, { status: 403 })),
296 + );
297 + if (usageReads === 1)
298 + return Deferred.succeed(usageStarted, undefined).pipe(Effect.andThen(Effect.never));
299 + const window = { percent: 10, resetsAt: "2026-11-01T00:00:00.000Z" };
300 + return Effect.succeed(
301 + HttpClientResponse.fromWeb(
302 + request,
303 + Response.json({ usage: { rolling: window, weekly: window, monthly: window } }),
304 + ),
305 + );
306 + }
307 + const path = new URL(request.url).pathname;
308 + if (path === "/api/model") modelReads += 1;
309 + const body =
310 + path === "/api/info"
311 + ? JSON.parse(OPENCODE_2_RESPONSES["/api/info"].body)
312 + : {
313 + location: { directory: "/work" },
314 + data:
315 + path === "/api/model"
316 + ? [
317 + {
318 + id: "big-pickle",
319 + modelID: "big-pickle",
320 + providerID: "opencode",
321 + name: "Big Pickle",
322 + package: "@opencode/ai/providers/openai-compatible",
323 + settings: {},
324 + compatibility: {},
325 + capabilities: { tools: true, input: ["text"], output: ["text"] },
326 + variants: [],
327 + time: { released: 1789516800000 },
328 + cost: [],
329 + status: "active",
330 + enabled: true,
331 + limit: { context: 1000000, output: 65536 },
332 + },
333 + ]
334 + : [],
335 + };
336 + return Effect.succeed(HttpClientResponse.fromWeb(request, Response.json(body)));
337 + });
338 + const runtime = {
339 + ...openCode2Runtime,
340 + startOpenCodeServerProcess: ({
341 + verify,
342 + }: Parameters<
343 + OpenCodeRuntime.OpenCodeRuntime["Service"]["startOpenCodeServerProcess"]
344 + >[0]) =>
345 + Effect.gen(function* () {
346 + serverStarts += 1;
347 + const url = "http://127.0.0.1:4096";
348 + const version = verify ? yield* verify(url) : "2.0.18";
349 + return { url, version, isRunning: Effect.succeed(true), exitCode: Effect.never };
350 + }),
351 + };
352 + const instance = yield* OpenCodeDriver.create({
353 + instanceId: ProviderInstanceId.make("opencode-usage-recovery"),
354 + displayName: undefined,
355 + environment: [
356 + {
357 + name: "OPENCODE_AUTH_CONTENT",
358 + sensitive: true,
359 + value: JSON.stringify({
360 + "opencode-go": { type: "api", key: "test-go-key" },
361 + }),
362 + },
363 + ],
364 + enabled: scenario.enabled,
365 + config: OpenCodeDriver.defaultConfig(),
366 + }).pipe(
367 + Effect.provide(
368 + TestProviderHost.layer({
369 + runBackgroundWork: scenario.demand,
370 + settings: scenario.intervalOff
371 + ? {
372 + ...DEFAULT_SERVER_SETTINGS,
373 + backgroundActivity: {
374 + ...DEFAULT_SERVER_SETTINGS.backgroundActivity,
375 + profile: "custom",
376 + overrides: { providerHealthRefreshInterval: Duration.zero },
377 + },
378 + }
379 + : DEFAULT_SERVER_SETTINGS,
380 + }),
381 + ),
382 + Effect.provideService(HttpClient.HttpClient, server),
383 + Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, runtime),
384 + );
385 + const initial = scenario.enabled
386 + ? yield* instance.snapshot.streamChanges.pipe(
387 + Stream.filter((snapshot) => snapshot.usageLimits !== undefined),
388 + Stream.take(1),
389 + Stream.runCollect,
390 + Effect.forkChild,
391 + )
392 + : undefined;
393 + if (scenario.enabled && !scenario.unsupported) yield* Deferred.await(usageStarted);
394 + yield* TestClock.adjust("5 seconds");
395 + const failed = initial
396 + ? Array.from(yield* Fiber.join(initial))[0]
397 + : yield* instance.snapshot.getSnapshot;
398 + if (scenario.enabled) {
399 + assert.strictEqual(failed?.status, "ready");
400 + assert.strictEqual(failed?.auth.status, "authenticated");
401 + }
402 + const initialReason =
403 + scenario.enabled && !scenario.unsupported ? "probeFailed" : "unsupported";
404 + assert.strictEqual(failed?.usageLimits?.unavailable?.reason, initialReason);
405 + const catalogReads = modelReads;
406 + const starts = serverStarts;
407 +
408 + const shouldRecover =
409 + scenario.enabled && scenario.demand && !scenario.intervalOff && !scenario.unsupported;
410 + const recovery = shouldRecover
411 + ? yield* instance.snapshot.streamChanges.pipe(
412 + Stream.filter((snapshot) => snapshot.usageLimits?.windows.length === 3),
413 + Stream.take(1),
414 + Stream.runCollect,
415 + Effect.forkChild,
416 + )
417 + : undefined;
418 + yield* TestClock.adjust("5 minutes");
419 + const recovered = yield* instance.snapshot.getSnapshot;
420 + const expectedReads = !scenario.enabled ? 0 : shouldRecover ? 2 : 1;
421 + assert.strictEqual(usageReads, expectedReads);
422 + if (recovery) assert.deepStrictEqual(Array.from(yield* Fiber.join(recovery)), [recovered]);
423 + assert.strictEqual(
424 + recovered.usageLimits?.unavailable?.reason,
425 + shouldRecover ? undefined : initialReason,
426 + );
427 + assert.deepStrictEqual(
428 + recovered.usageLimits?.windows.map((window) => window.kind),
429 + shouldRecover ? ["session", "weekly", "monthly"] : [],
430 + );
431 + assert.strictEqual(modelReads, catalogReads);
432 + assert.strictEqual(serverStarts, starts);
433 + yield* TestClock.adjust("15 minutes");
434 + assert.strictEqual(usageReads, expectedReads);
435 + assert.strictEqual(modelReads, catalogReads);
436 + assert.strictEqual(serverStarts, starts);
437 + }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
438 + );
439 });
440
441 // npm links into opencode-ai for 1.x and @opencode/cli for 2.x.
packages/provider-opencode/src/server/driver.ts
+12 -9
@@ -335,6 +335,16 @@ export const OpenCodeDriver: ProviderDriver<
335 ),
336 );
337
338 + const checkUsageLimits = readOpenCodeGoUsageLimits({
339 + enabled: effectiveConfig.enabled,
340 + serverUrl: effectiveConfig.serverUrl,
341 + environment: processEnv,
342 + }).pipe(
343 + Effect.provideService(FileSystem.FileSystem, fileSystem),
344 + Effect.provideService(Path.Path, pathService),
345 + Effect.provideService(HttpClient.HttpClient, httpClient),
346 + Effect.provideService(Crypto.Crypto, crypto),
347 + );
348 const checkProvider = Effect.all(
349 {
350 provider: checkOpenCodeProviderStatus(
@@ -346,20 +356,12 @@ export const OpenCodeDriver: ProviderDriver<
356 Effect.annotateLogs({ providerInstanceId: instanceId }),
357 Effect.annotateSpans({ providerInstanceId: instanceId }),
358 ),
349 - usageLimits: readOpenCodeGoUsageLimits({
350 - enabled: effectiveConfig.enabled,
351 - serverUrl: effectiveConfig.serverUrl,
352 - environment: processEnv,
353 - }),
359 + usageLimits: checkUsageLimits,
360 },
361 { concurrency: "unbounded" },
362 ).pipe(
363 Effect.map(({ provider, usageLimits }) => ({ ...provider, usageLimits })),
364 Effect.map(stampIdentity),
359 - Effect.provideService(FileSystem.FileSystem, fileSystem),
360 - Effect.provideService(Path.Path, pathService),
361 - Effect.provideService(HttpClient.HttpClient, httpClient),
362 - Effect.provideService(Crypto.Crypto, crypto),
365 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
366 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
367 );
@@ -445,6 +447,7 @@ export const OpenCodeDriver: ProviderDriver<
447 initialSnapshot: (settings) =>
448 makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),
449 checkProvider,
450 + checkUsageLimits,
451 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
452 resolveMaintenance().pipe(
453 Effect.flatMap((maintenanceCapabilities) =>