Refactor OpenCode lifecycle and structured output handling #2218
Mergedjuliusmarmingemerged 9 commits into
main fromrefs/pull/2218/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/provider/opencodeRuntime.ts line 560OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -570,0 +540,21 @@540+ // const [providerListResult, agentsResult] = await Promise.all([541+ // client.provider.list(),542+ // client.app.agents(),543+ // ]);544+ // console.log(JSON.stringify(providerListResult, null, 4));545+ // console.log(JSON.stringify(agentsResult, null, 4));546+ // if (!providerListResult.data) {547+ // throw new Error("OpenCode provider inventory was empty.");548+ // }549+ // return {550+ // providerList: providerListResult.data,551+ // agents: agentsResult.data ?? [],552+ // } satisfies OpenCodeInventory;553+ // },554+ // catch: (cause) =>555+ // new OpenCodeRuntimeError({556+ // operation: "loadOpenCodeInventory",557+ // detail: `Failed to load OpenCode inventory: ${openCodeRuntimeErrorDetail(cause)}`,558+ // cause: cause,559+ // }),560+ // });
- apps/server/src/provider/opencodeRuntime.ts lines 485 to 496OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -567,4 +479,18 @@479+ new OpenCodeRuntimeError({480+ operation: "loadOpenCodeInventory",481+ detail: `Failed to load OpenCode providers: ${openCodeRuntimeErrorDetail(cause)}`,482+ cause: cause,567483 }),568- });569- }570- }484+ }).pipe(485+ Effect.filterMapOrFail((list) =>486+ list.data487+ ? Result.succeed(list.data)488+ : Result.fail(489+ new OpenCodeRuntimeError({490+ operation: "loadOpenCodeInventory",491+ detail: "OpenCode provider list was empty.",492+ cause: new Error("OpenCode provider list was empty."),493+ }),494+ ),495+ ),496+ );apps/server/src/provider/Layers/OpenCodeAdapter.ts line 503Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -405,18 +460,15 @@405460 threadId: ThreadId,406461 event: {407462 readonly observedAt: string;408463 readonly event: Record<string, unknown>;409464 },410- ) =>411- (nativeEventLogger ? nativeEventLogger.write(event, threadId) : Effect.void).pipe(412- Effect.runPromiseWith(services),413- );465+ ) => (nativeEventLogger ? nativeEventLogger.write(event, threadId) : Effect.void);414466 const writeNativeEventBestEffort = (415467 threadId: ThreadId,416468 event: {417469 readonly observedAt: string;418470 readonly event: Record<string, unknown>;419471 },420- ) => writeNativeEventPromise(threadId, event).catch(() => undefined);472+ ) => writeNativeEvent(threadId, event).pipe(Effect.catchCause(() => Effect.void));421473422- const emitUnexpectedExit = (context: OpenCodeSessionContext, message: string) => {474+ const emitUnexpectedExit = Effect.fn("emitUnexpectedExit")(function* (
- @@ -912,0 +999,21 @@999+ }1000+ return { sessionScope, server, client, openCodeSession: openCodeSession.data };1001+ }).pipe(Effect.provideService(Scope.Scope, sessionScope)),1002+ );1003+ if (startedExit._tag === "Failure") {1004+ yield* Scope.close(sessionScope, Exit.void).pipe(Effect.ignore);1005+ const failure = Cause.squash(startedExit.cause);1006+ return yield* Effect.fail(1007+ failure instanceof Error ? failure : new Error("Failed to start OpenCode session."),1008+ );1009+ }1010+ return startedExit.value;1011+ }).pipe(1012+ Effect.mapError((cause) =>1013+ isProviderAdapterProcessError(cause)1014+ ? cause1015+ : new ProviderAdapterProcessError({1016+ provider: PROVIDER,1017+ threadId: input.threadId,1018+ detail:1019+ cause instanceof Error ? cause.message : "Failed to start OpenCode session.",apps/server/src/provider/Layers/OpenCodeProvider.ts line 130OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -127,3 +124,7 @@127124 };128125 }129126127+export interface OpenCodeInventory {128+ readonly providerList: ProviderListResponse;129+ readonly agents: ReadonlyArray<Agent>;130+}
- apps/server/src/git/Layers/OpenCodeTextGeneration.ts line 187OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -170,12 +181,7 @@170181 }171182 }172183173- const server = yield* Effect.tryPromise({174- try: () => startOpenCodeServerProcess({ binaryPath: input.binaryPath }),175- catch: (cause) =>176- new TextGenerationError({177- operation: input.operation,178- detail: cause instanceof Error ? cause.message : "Failed to start OpenCode server.",179- cause,180- }),181- });184+ // Create a fresh scope that owns this shared server. The runtime185+ // will attach its child-process and fiber finalizers to this scope;186+ // closing it kills the server and interrupts those fibers.187+ const serverScope = yield* Scope.make();
- apps/server/src/server.ts line 230OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -225,3 +227,4 @@225227226228 const RuntimeDependenciesLive = ReactorLayerLive.pipe(227229 // Core Services230+ Layer.provideMerge(OpenCodeRuntimeLive),
- apps/server/src/provider/Layers/OpenCodeAdapter.ts line 536Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -431,17 +477,17 @@477+ yield* emit({431478 ...buildEventBase({ threadId: context.session.threadId, turnId }),432479 type: "runtime.error",433480 payload: {434481 message,435482 class: "transport_error",436483 },437- }).catch(() => undefined);438- void emitPromise({484+ }).pipe(Effect.ignore);485+ yield* emit({439486 ...buildEventBase({ threadId: context.session.threadId, turnId }),440487 type: "session.exited",441488 payload: {442489 reason: message,443490 recoverable: false,444491 exitKind: "error",445492 },446- }).catch(() => undefined);447- };493+ }).pipe(Effect.ignore);apps/server/src/provider/Layers/OpenCodeAdapter.ts line 98OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -74,11 +94,5 @@7494 return new Date().toISOString();7595 }769677-function isProviderAdapterRequestError(cause: unknown): cause is ProviderAdapterRequestError {78- return (79- typeof cause === "object" &&80- cause !== null &&81- "_tag" in cause &&82- cause._tag === "ProviderAdapterRequestError"83- );84-}97+const isProviderAdapterRequestError = Schema.is(ProviderAdapterRequestError);98+const isProviderAdapterProcessError = Schema.is(ProviderAdapterProcessError);
- apps/server/src/provider/Layers/OpenCodeAdapter.ts lines 437 to 484Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -399 +453,21 @@399453454+ // Layer-level finalizer: when the adapter layer shuts down, stop every455+ // session. Each session's `Scope.close` tears down its spawned OpenCode456+ // server (via the `ChildProcessSpawner` finalizer installed in457+ // `startOpenCodeServerProcess`) and interrupts the forked event/exit458+ // fibers. Consumers that can't reason about Effect scopes therefore459+ // cannot leak OpenCode child processes by forgetting to call `stopAll`.460+ yield* Effect.addFinalizer(() =>461+ Effect.gen(function* () {462+ const contexts = [...sessions.values()];463+ sessions.clear();464+ // `ignoreCause` swallows both typed failures (none here) and defects465+ // from throwing scope finalizers so a sibling's death can't interrupt466+ // the remaining cleanups.467+ yield* Effect.forEach(468+ contexts,469+ (context) => Effect.ignoreCause(stopOpenCodeContext(context)),470+ { concurrency: "unbounded", discard: true },471+ );472+ }),473+ );
- @@ -129,0 +153,21 @@153+}154+155+function inferDefaultAgent(agents: ReadonlyArray<Agent>): string | undefined {156+ return agents.find((agent) => agent.name === "build")?.name ?? agents[0]?.name ?? undefined;157+}158+159+const DEFAULT_OPENCODE_MODEL_CAPABILITIES: ModelCapabilities = {160+ reasoningEffortLevels: [],161+ supportsFastMode: false,162+ supportsThinkingToggle: false,163+ contextWindowOptions: [],164+ promptInjectedEffortLevels: [],165+};166+167+function openCodeCapabilitiesForModel(input: {168+ readonly providerID: string;169+ readonly model: ProviderListResponse["all"][number]["models"][string];170+ readonly agents: ReadonlyArray<Agent>;171+}): ModelCapabilities {172+ const variantValues = Object.keys(input.model.variants ?? {});173+ const defaultVariant = inferDefaultVariant(input.providerID, variantValues);@@ -437,11 +527,17 @@437- }).catch(() => undefined);438- void emitPromise({527+ }).pipe(Effect.ignore);528+ yield* emit({439529 ...buildEventBase({ threadId: context.session.threadId, turnId }),440530 type: "session.exited",441531 payload: {442532 reason: message,443533 recoverable: false,444534 exitKind: "error",445535 },446- }).catch(() => undefined);447- };536+ }).pipe(Effect.ignore);537+ // Inline the teardown that `stopOpenCodeContext` would do; we can't538+ // delegate to it because our `getAndSet` above already flipped the539+ // one-shot guard, so the call would no-op.540+ yield* runOpenCodeSdk("session.abort", () =>541+ context.client.session.abort({ sessionID: context.openCodeSessionId }),542+ ).pipe(Effect.ignore({ log: true }));543+ yield* Scope.close(context.sessionScope, Exit.void);
juliusmarminge merged this306ec4b
juliusmarminge closed this
Sign in to join this conversation.



Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID:
d9fa9780-25b4-410e-a892-4ac0b3547ac5You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands and usage tips.