TypeScript
refactor(server): trace provider operations and keep streamed events untraced (#21993)
Julius Marminge509e0e054905
diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.tsindex 62b2ec6eac1..fb7130ed163 100644--- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts@@ -120,8 +120,8 @@ export function makeAntigravityAcpAdapterFlavor(): AcpAdapterV2Flavor {const antigravityClientFileRoots = (cwd: string | null) =>cwd === null ? [options.host.paths.attachmentsDir] : [cwd, options.host.paths.attachmentsDir];- const makeRuntime = (input: AcpAdapterV2RuntimeInput) =>- Effect.gen(function* () {+ const makeRuntime = Effect.fn("AntigravityAdapterV2.makeRuntime")(+ function* (input: AcpAdapterV2RuntimeInput) {const scope = yield* Scope.fork(yield* Effect.scope);const runtime = yield* options.withProcess(@@ -144,14 +144,14 @@ export function makeAntigravityAcpAdapterFlavor(),),};- }).pipe(- Effect.provideService(Crypto.Crypto, options.crypto),- Effect.mapError((cause): EffectAcpErrors.AcpError =>- cause._tag === "ProviderSetupError"- ? new EffectAcpErrors.AcpTransportError({ detail: cause.detail, cause })- : cause,- ),- );+ },+ Effect.provideService(Crypto.Crypto, options.crypto),+ Effect.mapError((cause): EffectAcpErrors.AcpError =>+ cause._tag === "ProviderSetupError"+ ? new EffectAcpErrors.AcpTransportError({ detail: cause.detail, cause })+ : cause,+ ),+ );return {driver: ANTIGRAVITY_PROVIDER,@@ -163,17 +163,19 @@ export function makeAntigravityAcpAdapterFlavor(preferResumeSession: true,subagentsIdleOnTurnCompletion: true,...(options.onSessionEvent === undefined ? {} : { onSessionEvent: options.onSessionEvent }),- applyModelSelection: ({ runtime, modelSelection }) =>- Effect.gen(function* () {- const defaultModel = yield* options.defaultModel;- return yield* applyAntigravityAcpModelSelection({- runtime,- model:- modelSelection.model === ANTIGRAVITY_DEFAULT_MODEL ? undefined : modelSelection.model,- defaultModel,- mapError: (cause) => cause,- });- }),+ applyModelSelection: Effect.fn("AntigravityAdapterV2.applyModelSelection")(function* ({+ runtime,+ modelSelection,+ }) {+ const defaultModel = yield* options.defaultModel;+ return yield* applyAntigravityAcpModelSelection({+ runtime,+ model:+ modelSelection.model === ANTIGRAVITY_DEFAULT_MODEL ? undefined : modelSelection.model,+ defaultModel,+ mapError: (cause) => cause,+ });+ }),sessionModeForPolicy: (policy) => antigravityPermissionMode(policy.runtimeMode),clientFileSystem: {readTextFile: (request, cwd) =>diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.tsindex b5f585ddbfa..1e0b25eec2a 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts@@ -3967,8 +3967,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (});});- const rememberProviderThread = (providerThread: OrchestrationV2ProviderThread) =>- Effect.gen(function* () {+ const rememberProviderThread =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (providerThread: OrchestrationV2ProviderThread) {const nativeThreadId = providerThread.nativeThreadRef?.nativeId;if (nativeThreadId === undefined || nativeThreadId === null) {return;@@ -4064,11 +4065,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (Effect.map((all) => taskIdSetForNativeThread(all, nativeThreadId).has(taskId)),);- const isKnownOpaqueBackgroundTaskOnNativeThread = (- nativeThreadId: string,- taskId: string,- ) =>- Effect.gen(function* () {+ const isKnownOpaqueBackgroundTaskOnNativeThread =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (nativeThreadId: string, taskId: string) {if (yield* hasPendingBackgroundTaskOnNativeThread(nativeThreadId, taskId)) {return true;}@@ -4091,11 +4090,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (taskIds,);- const consumeWakeEligibilityForBufferedNotification = (- nativeThreadId: string,- taskId: string,- ) =>- Effect.gen(function* () {+ const consumeWakeEligibilityForBufferedNotification =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (nativeThreadId: string, taskId: string) {yield* clearTaskIdFromNativeThreadSet(wakeEligibleBackgroundTasksByNativeThread,nativeThreadId,@@ -4186,11 +4183,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (return updated;});- const replacePendingBackgroundTasks = (- nativeThreadId: string,- tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>,- ) =>- Effect.gen(function* () {+ const replacePendingBackgroundTasks =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (+ nativeThreadId: string,+ tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>,+ ) {yield* Ref.update(pendingBackgroundTasksByNativeThread, (current) => {const updated = new Map(current);if (tasks.length === 0) {@@ -4212,11 +4210,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (}});- const upsertPendingBackgroundTask = (- nativeThreadId: string,- task: OrchestrationV2PendingBackgroundTask,- ) =>- Effect.gen(function* () {+ const upsertPendingBackgroundTask =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (+ nativeThreadId: string,+ task: OrchestrationV2PendingBackgroundTask,+ ) {yield* Ref.update(pendingBackgroundTasksByNativeThread, (current) => {const roster = new Map(rosterForNativeThread(current, nativeThreadId));roster.set(task.taskId, task);@@ -4243,8 +4242,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (return [true, updated] as const;});- const clearPendingBackgroundTasksForNativeThread = (nativeThreadId: string) =>- Effect.gen(function* () {+ const clearPendingBackgroundTasksForNativeThread =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (nativeThreadId: string) {yield* Ref.update(pendingBackgroundTasksByNativeThread, (current) => {if (!current.has(nativeThreadId)) {return current;@@ -4256,8 +4256,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (yield* endClaudeMonitorTasks((_taskId, task) => task.nativeThreadId === nativeThreadId);});- const clearWakeStateForNativeThread = (nativeThreadId: string) =>- Effect.gen(function* () {+ const clearWakeStateForNativeThread =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (nativeThreadId: string) {yield* clearWakeReports(nativeThreadId);yield* Ref.update(wakeBuffers, (current) => {if (!current.has(nativeThreadId)) {@@ -6083,8 +6084,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (});const reasoningDeltas = yield* makeProviderTextDeltaCoalescer({flushIntervalMs: 50,- emit: (update) =>- Effect.gen(function* () {+ emit:+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (update) {const context = yield* Ref.get(activeTurn);if (context === null || context.nativeTurnId !== update.turnId) return;const block = context.reasoning.blocks.get(update.itemId);@@ -9467,19 +9469,20 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (}return false;}),- hasPendingBackgroundWorkForThread: (providerThread) =>- Effect.gen(function* () {- const nativeThreadId = providerThread.nativeThreadRef?.nativeId;- if (nativeThreadId === undefined || nativeThreadId === null) {- return false;- }- return (- rosterForNativeThread(- yield* Ref.get(pendingBackgroundTasksByNativeThread),- nativeThreadId,- ).size > 0- );- }),+ hasPendingBackgroundWorkForThread: Effect.fn(+ "ClaudeAdapterV2.hasPendingBackgroundWorkForThread",+ )(function* (providerThread) {+ const nativeThreadId = providerThread.nativeThreadRef?.nativeId;+ if (nativeThreadId === undefined || nativeThreadId === null) {+ return false;+ }+ return (+ rosterForNativeThread(+ yield* Ref.get(pendingBackgroundTasksByNativeThread),+ nativeThreadId,+ ).size > 0+ );+ }),ensureThread: Effect.fn("ClaudeAdapterV2.ensureThread")(function* (threadInput: ProviderAdapter.ProviderAdapterV2EnsureThreadInput) {const createdAt = yield* DateTime.now;@@ -9551,36 +9554,35 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (message: { ...turnInput.message, text: "/compact" },}),steerTurn,- stopTask: ({ providerThread, taskId }) =>- Effect.gen(function* () {- const liveQuery = yield* Ref.get(queryContext);- const task = (yield* Ref.get(sessionSubagentsByTaskId)).get(taskId);- if (- liveQuery === null ||- liveQuery.stopping ||- liveQuery.nativeThreadId !== providerThread.nativeThreadRef?.nativeId ||- task === undefined ||- task.task.threadId !== providerThread.appThreadId ||- task.task.workflow === undefined ||- task.task.status !== "running" ||- liveQuery.subagentsFromEarlierProcesses.has(task)- ) {- return yield* new ProviderAdapter.ProviderAdapterProtocolError({- driver: CLAUDE_PROVIDER,- detail: "No running workflow task belongs to this provider thread",- });- }- yield* liveQuery.query.stopTask(taskId).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterProtocolError({- driver: CLAUDE_PROVIDER,- detail: "Workflow stop request failed",- cause,- }),- ),- );- }),+ stopTask: Effect.fn("ClaudeAdapterV2.stopTask")(function* ({ providerThread, taskId }) {+ const liveQuery = yield* Ref.get(queryContext);+ const task = (yield* Ref.get(sessionSubagentsByTaskId)).get(taskId);+ if (+ liveQuery === null ||+ liveQuery.stopping ||+ liveQuery.nativeThreadId !== providerThread.nativeThreadRef?.nativeId ||+ task === undefined ||+ task.task.threadId !== providerThread.appThreadId ||+ task.task.workflow === undefined ||+ task.task.status !== "running" ||+ liveQuery.subagentsFromEarlierProcesses.has(task)+ ) {+ return yield* new ProviderAdapter.ProviderAdapterProtocolError({+ driver: CLAUDE_PROVIDER,+ detail: "No running workflow task belongs to this provider thread",+ });+ }+ yield* liveQuery.query.stopTask(taskId).pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterProtocolError({+ driver: CLAUDE_PROVIDER,+ detail: "Workflow stop request failed",+ cause,+ }),+ ),+ );+ }),interruptTurn,stopSubagent: Effect.fn("ClaudeAdapterV2.stopSubagent")(function* (input) {const existing = yield* Ref.get(queryContext);diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.tsindex d26273081b2..4750aad5326 100644--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts@@ -717,19 +717,19 @@ function codexRuntimeModeTurnDefaults(runtimeMode: RuntimeMode): {}}-export function buildCodexTurnStartParams(input: {- readonly nativeThreadId: string;- readonly codexInput: ReadonlyArray<CodexSchema.V2TurnStartParams__UserInput>;- readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;- readonly modelSelection: ModelSelection;- readonly hasT3Mcp?: boolean;- readonly browserToolsAvailable?: boolean;- readonly deviceToolsAvailable?: boolean;- /** ChatGPT token sharing does not accept service tiers. */- readonly omitServiceTier?: boolean;- readonly appContext?: ProviderAdapter.ProviderAdapterV2TurnInput["appContext"];-}) {- return Effect.gen(function* () {+export const buildCodexTurnStartParams = Effect.fn("CodexAdapterV2.buildCodexTurnStartParams")(+ function* (input: {+ readonly nativeThreadId: string;+ readonly codexInput: ReadonlyArray<CodexSchema.V2TurnStartParams__UserInput>;+ readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;+ readonly modelSelection: ModelSelection;+ readonly hasT3Mcp?: boolean;+ readonly browserToolsAvailable?: boolean;+ readonly deviceToolsAvailable?: boolean;+ /** ChatGPT token sharing does not accept service tiers. */+ readonly omitServiceTier?: boolean;+ readonly appContext?: ProviderAdapter.ProviderAdapterV2TurnInput["appContext"];+ }) {const runtimeModeDefaults = codexRuntimeModeTurnDefaults(input.runtimePolicy.runtimeMode);const approvalPolicy =input.runtimePolicy.approvalPolicy === undefined@@ -808,8 +808,8 @@ export function buildCodexTurnStartParams(input: {...(serviceTier === undefined ? {} : { serviceTier }),...(collaborationMode === undefined ? {} : { collaborationMode }),});- });-}+ },+);function providerSession(input: {readonly providerSessionId: OrchestrationV2ProviderSession["id"];@@ -832,17 +832,17 @@ function providerSession(input: {};}-function getNativeThreadId(providerThread: OrchestrationV2ProviderThread) {- return Effect.gen(function* () {- const nativeThreadId = providerThread.nativeThreadRef?.nativeId;- if (nativeThreadId === undefined || nativeThreadId === null) {- return yield* toProtocolError(- `Provider thread ${providerThread.id} is missing a native Codex thread id.`,- );- }- return nativeThreadId;- });-}+const getNativeThreadId = Effect.fn("CodexAdapterV2.getNativeThreadId")(function* (+ providerThread: OrchestrationV2ProviderThread,+) {+ const nativeThreadId = providerThread.nativeThreadRef?.nativeId;+ if (nativeThreadId === undefined || nativeThreadId === null) {+ return yield* toProtocolError(+ `Provider thread ${providerThread.id} is missing a native Codex thread id.`,+ );+ }+ return nativeThreadId;+});function providerThreadFromCodexThread(input: {readonly appThreadId: ThreadId | null;@@ -1399,31 +1399,30 @@ const layerCodexAppServerClientFactoryCommand = (Effect.gen(function* () {const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;return CodexAppServerClientFactory.of({- open: (input) =>- Effect.gen(function* () {- const scope = yield* Scope.Scope;- const command = yield* makeCodexAppServerSpawnCommand({- command: options.command,- args: [...(options.args ?? [])],- ...(options.cwd === undefined ? {} : { cwd: options.cwd }),- ...(options.env === undefined ? {} : { env: options.env, extendEnv: true }),- });- const handle = yield* spawner.spawn(command).pipe(- Effect.provideService(Scope.Scope, scope),- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterOpenSessionError({- driver: CODEX_PROVIDER,- providerSessionId: input.providerSessionId,- cause,- }),- ),- );- const context = yield* Layer.build(CodexClient.layerChildProcess(handle, options));- return yield* Effect.service(CodexClient.CodexAppServerClient).pipe(- Effect.provide(context),- );- }),+ open: Effect.fn("CodexAdapterV2.open")(function* (input) {+ const scope = yield* Scope.Scope;+ const command = yield* makeCodexAppServerSpawnCommand({+ command: options.command,+ args: [...(options.args ?? [])],+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),+ ...(options.env === undefined ? {} : { env: options.env, extendEnv: true }),+ });+ const handle = yield* spawner.spawn(command).pipe(+ Effect.provideService(Scope.Scope, scope),+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterOpenSessionError({+ driver: CODEX_PROVIDER,+ providerSessionId: input.providerSessionId,+ cause,+ }),+ ),+ );+ const context = yield* Layer.build(CodexClient.layerChildProcess(handle, options));+ return yield* Effect.service(CodexClient.CodexAppServerClient).pipe(+ Effect.provide(context),+ );+ }),});}),);@@ -1514,50 +1513,49 @@ export const layerAppServerClientFactory: Layer.Layer<const agentScope = yield* AgentScope;return CodexAppServerClientFactory.of({- open: (input) =>- Effect.gen(function* () {- const scope = yield* Scope.Scope;- const environment = {- ...codexAppServerEnvironment(input.environment),- ...(input.settings.homePath ? { CODEX_HOME: input.settings.homePath } : {}),- };- const command = yield* makeCodexAppServerSpawnCommand({- command: input.settings.binaryPath || "codex",- args: codexAppServerArgs(- resolveCodexLaunchArgs(input.settings.launchArgs, input.environment),- ),- env: environment,- threadId: input.threadId,- }).pipe(Effect.provideService(AgentScope, agentScope));- const handle = yield* spawner.spawn(command).pipe(- Effect.provideService(Scope.Scope, scope),- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterOpenSessionError({- driver: CODEX_PROVIDER,- providerSessionId: input.providerSessionId,- cause,- }),- ),- );- const protocolLogger = makeCodexAppServerProtocolLogger({- nativeEventLogger,- threadId: input.threadId,- providerSessionId: input.providerSessionId,- });- const clientOptions: CodexClient.CodexAppServerClientOptions =- protocolLogger === undefined- ? {}- : {- logIncoming: true,- logOutgoing: true,- logger: protocolLogger,- };- const context = yield* Layer.build(CodexClient.layerChildProcess(handle, clientOptions));- return yield* Effect.service(CodexClient.CodexAppServerClient).pipe(- Effect.provide(context),- );- }),+ open: Effect.fn("CodexAdapterV2.open")(function* (input) {+ const scope = yield* Scope.Scope;+ const environment = {+ ...codexAppServerEnvironment(input.environment),+ ...(input.settings.homePath ? { CODEX_HOME: input.settings.homePath } : {}),+ };+ const command = yield* makeCodexAppServerSpawnCommand({+ command: input.settings.binaryPath || "codex",+ args: codexAppServerArgs(+ resolveCodexLaunchArgs(input.settings.launchArgs, input.environment),+ ),+ env: environment,+ threadId: input.threadId,+ }).pipe(Effect.provideService(AgentScope, agentScope));+ const handle = yield* spawner.spawn(command).pipe(+ Effect.provideService(Scope.Scope, scope),+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterOpenSessionError({+ driver: CODEX_PROVIDER,+ providerSessionId: input.providerSessionId,+ cause,+ }),+ ),+ );+ const protocolLogger = makeCodexAppServerProtocolLogger({+ nativeEventLogger,+ threadId: input.threadId,+ providerSessionId: input.providerSessionId,+ });+ const clientOptions: CodexClient.CodexAppServerClientOptions =+ protocolLogger === undefined+ ? {}+ : {+ logIncoming: true,+ logOutgoing: true,+ logger: protocolLogger,+ };+ const context = yield* Layer.build(CodexClient.layerChildProcess(handle, clientOptions));+ return yield* Effect.service(CodexClient.CodexAppServerClient).pipe(+ Effect.provide(context),+ );+ }),});}),);@@ -1571,52 +1569,51 @@ export type CodexAdapterV2DriverEnv =| Path.Path| ServerConfig;-export const createCodexAdapterV2 = (+export const createCodexAdapterV2 = Effect.fn("CodexAdapterV2.createCodexAdapterV2")(function* ({ instanceId, environment, enabled, config }: ProviderAdapterDriverCreateInput<CodexSettings>,hooks: Pick<CodexAdapterV2Options, "onUsageLimits" | "resolveRuntime"> = {},-) =>- Effect.gen(function* () {- const clientFactory = yield* CodexAppServerClientFactory;- const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;- const crypto = yield* Crypto.Crypto;- const fileSystem = yield* FileSystem.FileSystem;- const hostEnvironment = yield* HostProcess.Environment;- const idAllocator = yield* IdAllocator.IdAllocatorV2;- const serverConfig = yield* ServerConfig;- const homeLayout = yield* resolveCodexHomeLayout(config);-- yield* materializeCodexShadowHome(homeLayout).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapterDriverCreateError({- driver: CODEX_DRIVER_KIND,- instanceId,- detail: "Failed to materialize the Codex shadow home.",- cause,- }),- ),- );-- const settings = {- ...config,- enabled,- binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),- homePath: homeLayout.effectiveHomePath ?? "",- } satisfies CodexSettings;+) {+ const clientFactory = yield* CodexAppServerClientFactory;+ const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;+ const crypto = yield* Crypto.Crypto;+ const fileSystem = yield* FileSystem.FileSystem;+ const hostEnvironment = yield* HostProcess.Environment;+ const idAllocator = yield* IdAllocator.IdAllocatorV2;+ const serverConfig = yield* ServerConfig;+ const homeLayout = yield* resolveCodexHomeLayout(config);++ yield* materializeCodexShadowHome(homeLayout).pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapterDriverCreateError({+ driver: CODEX_DRIVER_KIND,+ instanceId,+ detail: "Failed to materialize the Codex shadow home.",+ cause,+ }),+ ),+ );- return yield* makeCodexAdapterV2({- instanceId,- settings,- environment: yield* mergeProviderInstanceEnvironment(environment, hostEnvironment),- clientFactory,- crypto,- fileSystem,- idAllocator,- serverConfig,- continuationRequests,- ...hooks,- });+ const settings = {+ ...config,+ enabled,+ binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),+ homePath: homeLayout.effectiveHomePath ?? "",+ } satisfies CodexSettings;++ return yield* makeCodexAdapterV2({+ instanceId,+ settings,+ environment: yield* mergeProviderInstanceEnvironment(environment, hostEnvironment),+ clientFactory,+ crypto,+ fileSystem,+ idAllocator,+ serverConfig,+ continuationRequests,+ ...hooks,});+});export const CodexAdapterV2Driver: ProviderAdapterDriver<CodexSettings, CodexAdapterV2DriverEnv> = {driverKind: CODEX_DRIVER_KIND,@@ -1695,8 +1692,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (driver: CODEX_PROVIDER,getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()),- openSession: (input) =>- Effect.gen(function* () {+ openSession: Effect.fn("CodexAdapterV2.openSession")(+ function* (input) {const scope = yield* Scope.Scope;const resolvedRuntime =adapterOptions.resolveRuntime === undefined@@ -1727,8 +1724,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ();// Codex drops client developer messages during compaction but only// resends additionalContext when it changes.- const restoreAdditionalContext = (threadId: string) =>- Effect.gen(function* () {+ const restoreAdditionalContext = Effect.fn("CodexAdapterV2.restoreAdditionalContext")(+ function* (threadId: string) {const context = (yield* Ref.get(additionalContextByThread)).get(threadId);if (!context) return;yield* client.request("thread/inject_items", {@@ -1752,14 +1749,14 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (},),});- }).pipe(- Effect.timeout("10 seconds"),- Effect.catch((cause) =>- Effect.logWarning("Failed to restore Codex additional context after compaction.", {- cause,- }),- ),- );+ },+ Effect.timeout("10 seconds"),+ Effect.catch((cause) =>+ Effect.logWarning("Failed to restore Codex additional context after compaction.", {+ cause,+ }),+ ),+ );const initialized = yield* Ref.make(false);// Threads share this app-server, and Codex rejects a second// `initialize`.@@ -1981,102 +1978,101 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (});});- const registerRootTurn = (input: {+ const registerRootTurn = Effect.fn("CodexAdapterV2.registerRootTurn")(function* (input: {readonly turnInput: ProviderAdapter.ProviderAdapterV2TurnInput;readonly nativeTurnId: string;readonly startedAt: DateTime.Utc;readonly waitForNativeStart?: boolean;- }) =>- Effect.gen(function* () {- const existing = (yield* Ref.get(activeTurns)).get(input.nativeTurnId);- if (existing !== undefined) {- return existing;- }- const providerTurnId = idAllocator.derive.providerTurn({- driver: CODEX_PROVIDER,- nativeTurnId: input.nativeTurnId,- });- const context: ActiveCodexTurnContext = {- ...(input.waitForNativeStart- ? { nativeStartReady: yield* Deferred.make<void>() }- : {}),- input: input.turnInput,- projectionAppThread: input.turnInput.appThread,- projectionThreadId: input.turnInput.threadId,- projectionRunId: input.turnInput.runId,- nativeTurnId: input.nativeTurnId,- providerThread: input.turnInput.providerThread,- providerTurnId,- providerTurnOrdinal: input.turnInput.providerTurnOrdinal,- providerNodeId: input.turnInput.rootNodeId,- providerNodeKind: "root_turn",- providerNodeStartedAt: input.startedAt,- itemParentNodeId: input.turnInput.rootNodeId,- rootNodeId: input.turnInput.rootNodeId,- subagent: null,- startedAt: input.startedAt,- itemPositions: new Map(),- fileChangeKindsByItem: new Map(),- };- yield* Ref.update(limitedTurnItems, (current) => {- const next = new Map(current);- next.delete(context.providerThread.id);- return next;- });- beginTurnTokenUsage(context);- endSessionApprovalsOnModeChange(context);- yield* Ref.update(activeTurns, (current) => {- const updated = new Map(current);- updated.set(input.nativeTurnId, context);- return updated;- });- yield* emitProviderEvent({- type: "provider_turn.updated",- driver: CODEX_PROVIDER,- threadId: input.turnInput.threadId,- providerTurn: {- id: providerTurnId,- providerThreadId: input.turnInput.providerThread.id,- nodeId: input.turnInput.rootNodeId,- runAttemptId: input.turnInput.attemptId,- nativeTurnRef: {- driver: CODEX_PROVIDER,- nativeId: input.nativeTurnId,- strength: "strong",- },- ordinal: input.turnInput.providerTurnOrdinal,- status: "running",- startedAt: input.startedAt,- completedAt: null,+ }) {+ const existing = (yield* Ref.get(activeTurns)).get(input.nativeTurnId);+ if (existing !== undefined) {+ return existing;+ }+ const providerTurnId = idAllocator.derive.providerTurn({+ driver: CODEX_PROVIDER,+ nativeTurnId: input.nativeTurnId,+ });+ const context: ActiveCodexTurnContext = {+ ...(input.waitForNativeStart ? { nativeStartReady: yield* Deferred.make<void>() } : {}),+ input: input.turnInput,+ projectionAppThread: input.turnInput.appThread,+ projectionThreadId: input.turnInput.threadId,+ projectionRunId: input.turnInput.runId,+ nativeTurnId: input.nativeTurnId,+ providerThread: input.turnInput.providerThread,+ providerTurnId,+ providerTurnOrdinal: input.turnInput.providerTurnOrdinal,+ providerNodeId: input.turnInput.rootNodeId,+ providerNodeKind: "root_turn",+ providerNodeStartedAt: input.startedAt,+ itemParentNodeId: input.turnInput.rootNodeId,+ rootNodeId: input.turnInput.rootNodeId,+ subagent: null,+ startedAt: input.startedAt,+ itemPositions: new Map(),+ fileChangeKindsByItem: new Map(),+ };+ yield* Ref.update(limitedTurnItems, (current) => {+ const next = new Map(current);+ next.delete(context.providerThread.id);+ return next;+ });+ beginTurnTokenUsage(context);+ endSessionApprovalsOnModeChange(context);+ yield* Ref.update(activeTurns, (current) => {+ const updated = new Map(current);+ updated.set(input.nativeTurnId, context);+ return updated;+ });+ yield* emitProviderEvent({+ type: "provider_turn.updated",+ driver: CODEX_PROVIDER,+ threadId: input.turnInput.threadId,+ providerTurn: {+ id: providerTurnId,+ providerThreadId: input.turnInput.providerThread.id,+ nodeId: input.turnInput.rootNodeId,+ runAttemptId: input.turnInput.attemptId,+ nativeTurnRef: {+ driver: CODEX_PROVIDER,+ nativeId: input.nativeTurnId,+ strength: "strong",},- });- yield* rememberRootProviderThread(input.turnInput.providerThread);- return context;+ ordinal: input.turnInput.providerTurnOrdinal,+ status: "running",+ startedAt: input.startedAt,+ completedAt: null,+ },});+ yield* rememberRootProviderThread(input.turnInput.providerThread);+ return context;+ });- const findActiveTurnByNativeThreadId = (nativeThreadId: string) =>- Effect.gen(function* () {+ const findActiveTurnByNativeThreadId =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (nativeThreadId: string) {const turns = Array.from((yield* Ref.get(activeTurns)).values());return turns.find((context) => context.providerThread.nativeThreadRef?.nativeId === nativeThreadId,);});- const awaitActiveTurn = (+ // Streaming updates repeatedly await this context, including retries before registration.+ const awaitActiveTurn = Effect.fnUntraced(function* (nativeTurnId: string,attemptsRemaining = 1_000,- ): Effect.Effect<ActiveCodexTurnContext | undefined> =>- Effect.gen(function* () {- const context = (yield* Ref.get(activeTurns)).get(nativeTurnId);- if (context !== undefined || attemptsRemaining <= 0) {- return context;- }- yield* Effect.yieldNow;- return yield* awaitActiveTurn(nativeTurnId, attemptsRemaining - 1);- });+ ): Effect.fn.Return<ActiveCodexTurnContext | undefined> {+ const context = (yield* Ref.get(activeTurns)).get(nativeTurnId);+ if (context !== undefined || attemptsRemaining <= 0) {+ return context;+ }+ yield* Effect.yieldNow;+ return yield* awaitActiveTurn(nativeTurnId, attemptsRemaining - 1);+ });- const resolveItemEventContext = (nativeTurnId: string) =>- Effect.gen(function* () {+ const resolveItemEventContext =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (nativeTurnId: string) {const settled = (yield* Ref.get(settledTurns)).get(nativeTurnId);if (settled !== undefined) {return { context: settled, settled: true } as const;@@ -2158,8 +2154,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (return updated;});- const turnHasRetainedBackgroundWork = (nativeTurnId: string) =>- Effect.gen(function* () {+ const turnHasRetainedBackgroundWork =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (nativeTurnId: string) {const commands = (yield* Ref.get(runningCommandItemsByTurn)).get(nativeTurnId);if (commands !== undefined && commands.size > 0) {return true;@@ -2179,8 +2176,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (return false;});- const releaseSettledTurnIfIdle = (nativeTurnId: string) =>- Effect.gen(function* () {+ const releaseSettledTurnIfIdle =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (nativeTurnId: string) {if (yield* turnHasRetainedBackgroundWork(nativeTurnId)) {return;}@@ -2223,105 +2221,106 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (* items mid-flight (no item/completed). Emit terminal turn items before* turn.terminal so the projection never keeps a forever-running command card.*/- const terminalizeRunningCommandItems = (+ const terminalizeRunningCommandItems = Effect.fn(+ "CodexAdapterV2.terminalizeRunningCommandItems",+ )(function* (context: ActiveCodexTurnContext,nativeTurnId: string,status: "interrupted" | "failed",completedAt: DateTime.Utc,- ) =>- Effect.gen(function* () {- const items = (yield* Ref.get(runningCommandItemsByTurn)).get(nativeTurnId);- if (items === undefined || items.size === 0) {- return;- }- for (const tracked of items.values()) {- const nodeId = idAllocator.derive.nodeFromProviderItem({- driver: CODEX_PROVIDER,- nativeItemId: tracked.id,- });- const turnItemId = idAllocator.derive.turnItemFromProviderItem({- driver: CODEX_PROVIDER,- nativeItemId: tracked.id,- });- const { ordinal, startedAt } = yield* resolveItemPosition(context, tracked.id);- const node: OrchestrationV2ExecutionNode = {- id: nodeId,- threadId: context.projectionThreadId,- runId: context.projectionRunId,- parentNodeId: context.itemParentNodeId,- rootNodeId: context.rootNodeId,- kind: "tool_call",- status,- countsForRun: false,- providerThreadId: context.providerThread.id,- providerTurnId: context.providerTurnId,- nativeItemRef: codexNativeItemRef(tracked.id),- runtimeRequestId: null,- checkpointScopeId: null,- startedAt,- completedAt,- };- const turnItem: OrchestrationV2TurnItem = {- id: turnItemId,- threadId: context.projectionThreadId,- runId: context.projectionRunId,- nodeId,- providerThreadId: context.providerThread.id,- providerTurnId: context.providerTurnId,- nativeItemRef: codexNativeItemRef(tracked.id),- parentItemId: null,- ordinal,- status,- title: null,- startedAt,- completedAt,- updatedAt: completedAt,- type: "command_execution",- input: tracked.command,- ...(tracked.aggregatedOutput === undefined- ? {}- : { output: tracked.aggregatedOutput }),- };- yield* emitProviderEvent({- type: "node.updated",- driver: CODEX_PROVIDER,- node,- });- yield* emitProviderEvent({- type: "turn_item.updated",- driver: CODEX_PROVIDER,- turnItem,- });- }- });-- const terminateBackgroundTerminal = Effect.fn("CodexAdapterV2.terminateBackgroundTerminal")(- function* (nativeThreadId: string, processId: string) {- const response = yield* client.raw- .request("thread/backgroundTerminals/terminate", {- threadId: nativeThreadId,- processId,- })- .pipe(- Effect.catchTags({- CodexAppServerProcessExitedError: () => Effect.succeed({ terminated: true }),- CodexAppServerInputStreamEndedError: () => Effect.succeed({ terminated: true }),- // The thread is unloaded, as Codex does a minute after a- // settle or archive unsubscribes it. Unloading kills the- // thread's terminals, so nothing is left to stop.- CodexAppServerRequestError: (error) =>- error.code === -32600 && error.errorMessage.startsWith("thread not found:")- ? Effect.succeed({ terminated: true })- : Effect.fail(error),- }),- );- const result = yield* decodeCodexBackgroundTerminalTerminateResponse(response);- if (result.terminated) return;- let cursor: string | null = null;- while (true) {- const response: unknown = yield* client.raw.request(- "thread/backgroundTerminals/list",- {+ ) {+ const items = (yield* Ref.get(runningCommandItemsByTurn)).get(nativeTurnId);+ if (items === undefined || items.size === 0) {+ return;+ }+ for (const tracked of items.values()) {+ const nodeId = idAllocator.derive.nodeFromProviderItem({+ driver: CODEX_PROVIDER,+ nativeItemId: tracked.id,+ });+ const turnItemId = idAllocator.derive.turnItemFromProviderItem({+ driver: CODEX_PROVIDER,+ nativeItemId: tracked.id,+ });+ const { ordinal, startedAt } = yield* resolveItemPosition(context, tracked.id);+ const node: OrchestrationV2ExecutionNode = {+ id: nodeId,+ threadId: context.projectionThreadId,+ runId: context.projectionRunId,+ parentNodeId: context.itemParentNodeId,+ rootNodeId: context.rootNodeId,+ kind: "tool_call",+ status,+ countsForRun: false,+ providerThreadId: context.providerThread.id,+ providerTurnId: context.providerTurnId,+ nativeItemRef: codexNativeItemRef(tracked.id),+ runtimeRequestId: null,+ checkpointScopeId: null,+ startedAt,+ completedAt,+ };+ const turnItem: OrchestrationV2TurnItem = {+ id: turnItemId,+ threadId: context.projectionThreadId,+ runId: context.projectionRunId,+ nodeId,+ providerThreadId: context.providerThread.id,+ providerTurnId: context.providerTurnId,+ nativeItemRef: codexNativeItemRef(tracked.id),+ parentItemId: null,+ ordinal,+ status,+ title: null,+ startedAt,+ completedAt,+ updatedAt: completedAt,+ type: "command_execution",+ input: tracked.command,+ ...(tracked.aggregatedOutput === undefined+ ? {}+ : { output: tracked.aggregatedOutput }),+ };+ yield* emitProviderEvent({+ type: "node.updated",+ driver: CODEX_PROVIDER,+ node,+ });+ yield* emitProviderEvent({+ type: "turn_item.updated",+ driver: CODEX_PROVIDER,+ turnItem,+ });+ }+ });++ const terminateBackgroundTerminal = Effect.fn("CodexAdapterV2.terminateBackgroundTerminal")(+ function* (nativeThreadId: string, processId: string) {+ const response = yield* client.raw+ .request("thread/backgroundTerminals/terminate", {+ threadId: nativeThreadId,+ processId,+ })+ .pipe(+ Effect.catchTags({+ CodexAppServerProcessExitedError: () => Effect.succeed({ terminated: true }),+ CodexAppServerInputStreamEndedError: () => Effect.succeed({ terminated: true }),+ // The thread is unloaded, as Codex does a minute after a+ // settle or archive unsubscribes it. Unloading kills the+ // thread's terminals, so nothing is left to stop.+ CodexAppServerRequestError: (error) =>+ error.code === -32600 && error.errorMessage.startsWith("thread not found:")+ ? Effect.succeed({ terminated: true })+ : Effect.fail(error),+ }),+ );+ const result = yield* decodeCodexBackgroundTerminalTerminateResponse(response);+ if (result.terminated) return;+ let cursor: string | null = null;+ while (true) {+ const response: unknown = yield* client.raw.request(+ "thread/backgroundTerminals/list",+ {threadId: nativeThreadId,...(cursor === null ? {} : { cursor }),},@@ -2345,69 +2344,71 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (* item/completed when functions.wait terminates the cell. Persistent tools* can outlive the root turn and must stay running.*/- const terminalizeRunningDynamicTools = (+ const terminalizeRunningDynamicTools = Effect.fn(+ "CodexAdapterV2.terminalizeRunningDynamicTools",+ )(function* (context: ActiveCodexTurnContext,nativeTurnId: string,status: "cancelled" | "interrupted" | "failed",completedAt: DateTime.Utc,includePersistent: boolean,- ) =>- Effect.gen(function* () {- const items = (yield* Ref.get(runningDynamicToolsByTurn)).get(nativeTurnId);- if (items === undefined || items.size === 0) {- return;+ ) {+ const items = (yield* Ref.get(runningDynamicToolsByTurn)).get(nativeTurnId);+ if (items === undefined || items.size === 0) {+ return;+ }+ for (const tracked of items.values()) {+ if (!includePersistent && isPersistentCodexDynamicTool(tracked)) {+ continue;}- for (const tracked of items.values()) {- if (!includePersistent && isPersistentCodexDynamicTool(tracked)) {- continue;- }- const artifacts = yield* buildDynamicToolArtifacts(context, tracked);- yield* emitProviderEvent({- type: "node.updated",- driver: CODEX_PROVIDER,- node: {- ...artifacts.node,- status,- completedAt,- },- });- yield* emitProviderEvent({- type: "turn_item.updated",- driver: CODEX_PROVIDER,- turnItem: {- ...artifacts.turnItem,- status,- completedAt,- updatedAt: completedAt,- },- });+ const artifacts = yield* buildDynamicToolArtifacts(context, tracked);+ yield* emitProviderEvent({+ type: "node.updated",+ driver: CODEX_PROVIDER,+ node: {+ ...artifacts.node,+ status,+ completedAt,+ },+ });+ yield* emitProviderEvent({+ type: "turn_item.updated",+ driver: CODEX_PROVIDER,+ turnItem: {+ ...artifacts.turnItem,+ status,+ completedAt,+ updatedAt: completedAt,+ },+ });+ }+ yield* Ref.update(runningDynamicToolsByTurn, (current) => {+ if (!current.has(nativeTurnId)) {+ return current;}- yield* Ref.update(runningDynamicToolsByTurn, (current) => {- if (!current.has(nativeTurnId)) {- return current;+ const remaining = new Map(current.get(nativeTurnId) ?? []);+ for (const tracked of remaining.values()) {+ if (includePersistent || !isPersistentCodexDynamicTool(tracked)) {+ remaining.delete(tracked.id);}- const remaining = new Map(current.get(nativeTurnId) ?? []);- for (const tracked of remaining.values()) {- if (includePersistent || !isPersistentCodexDynamicTool(tracked)) {- remaining.delete(tracked.id);- }- }- const updated = new Map(current);- if (remaining.size === 0) {- updated.delete(nativeTurnId);- } else {- updated.set(nativeTurnId, remaining);- }- return updated;- });+ }+ const updated = new Map(current);+ if (remaining.size === 0) {+ updated.delete(nativeTurnId);+ } else {+ updated.set(nativeTurnId, remaining);+ }+ return updated;});+ });- const resolveItemPosition = (- context: ActiveCodexTurnContext,- nativeItemId: string,- startedAt?: DateTime.Utc,- ) =>- Effect.gen(function* () {+ const resolveItemPosition =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (+ context: ActiveCodexTurnContext,+ nativeItemId: string,+ startedAt?: DateTime.Utc,+ ) {// Read the clock first so the lookup and the insert run without yielding.const now = startedAt ?? (yield* DateTime.now);const existing = context.itemPositions.get(nativeItemId);@@ -2439,15 +2440,16 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (return [next, updated];});- const emitSubagentTaskUpdate = (input: {- readonly subagent: CodexSubagentThreadContext;- readonly status: OrchestrationV2Subagent["status"];- readonly result?: string | null;- readonly completedAt?: DateTime.Utc | null;- readonly startedAt?: DateTime.Utc;- readonly reopen?: boolean;- }) =>- Effect.gen(function* () {+ const emitSubagentTaskUpdate =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (input: {+ readonly subagent: CodexSubagentThreadContext;+ readonly status: OrchestrationV2Subagent["status"];+ readonly result?: string | null;+ readonly completedAt?: DateTime.Utc | null;+ readonly startedAt?: DateTime.Utc;+ readonly reopen?: boolean;+ }) {const now = yield* DateTime.now;const prior = input.subagent.task;const settled = !isOrchestrationV2WorkActive(prior.status);@@ -2510,11 +2512,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (});});- const emitSubagentProviderTurnStarted = (- subagent: CodexSubagentThreadContext,- turn: PendingCodexSubagentTurnStarted,- ) =>- Effect.gen(function* () {+ const emitSubagentProviderTurnStarted =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (+ subagent: CodexSubagentThreadContext,+ turn: PendingCodexSubagentTurnStarted,+ ) {if (subagent.nativeTurnIds.has(turn.nativeTurnId)) return;subagent.nativeTurnIds.add(turn.nativeTurnId);const parentNativeThreadId = yield* getNativeThreadId(@@ -2656,12 +2659,13 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (});});- const rememberSubagentTurnStarted = (input: {- readonly nativeThreadId: string;- readonly nativeTurnId: string;- readonly startedAt: DateTime.Utc;- }) =>- Effect.gen(function* () {+ const rememberSubagentTurnStarted =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (input: {+ readonly nativeThreadId: string;+ readonly nativeTurnId: string;+ readonly startedAt: DateTime.Utc;+ }) {const subagent = (yield* Ref.get(subagentThreads)).get(input.nativeThreadId);if (subagent !== undefined) {yield* emitSubagentProviderTurnStarted(subagent, input);@@ -2729,19 +2733,20 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (});});- const registerSubagentThread = (input: {- readonly context: ActiveCodexTurnContext;- readonly nativeThreadId: string;- readonly nativeItemId: string;- readonly nativeToolCallId: string;- readonly prompt: string;- readonly title: string | null;- readonly model: string | null;- readonly reasoningEffort?: string | null | undefined;- readonly ordinal: number;- readonly emitInitialPrompt: boolean;- }) =>- Effect.gen(function* () {+ const registerSubagentThread =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (input: {+ readonly context: ActiveCodexTurnContext;+ readonly nativeThreadId: string;+ readonly nativeItemId: string;+ readonly nativeToolCallId: string;+ readonly prompt: string;+ readonly title: string | null;+ readonly model: string | null;+ readonly reasoningEffort?: string | null | undefined;+ readonly ordinal: number;+ readonly emitInitialPrompt: boolean;+ }) {const registeredSubagents = yield* Ref.get(subagentThreads);if (registeredSubagents.has(input.nativeThreadId)) {return;@@ -3009,11 +3014,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (}});- const registerSubagentThreads = (input: {- readonly context: ActiveCodexTurnContext;- readonly item: CodexCollabAgentToolCallItem;- }) =>- Effect.gen(function* () {+ const registerSubagentThreads =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (input: {+ readonly context: ActiveCodexTurnContext;+ readonly item: CodexCollabAgentToolCallItem;+ }) {if (input.item.tool !== "spawnAgent" || input.item.receiverThreadIds.length === 0) {return;}@@ -3038,11 +3044,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (}});- const registerSubagentActivity = (input: {- readonly context?: ActiveCodexTurnContext;- readonly item: CodexSubAgentActivityItem;- }) =>- Effect.gen(function* () {+ const registerSubagentActivity =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (input: {+ readonly context?: ActiveCodexTurnContext;+ readonly item: CodexSubAgentActivityItem;+ }) {if (input.item.kind === "started") {const context = input.context;if (context === undefined) return;@@ -3078,8 +3085,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (}});- const updateSubagentStates = (input: { readonly item: CodexCollabAgentToolCallItem }) =>- Effect.gen(function* () {+ const updateSubagentStates =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (input: { readonly item: CodexCollabAgentToolCallItem }) {const subagents = yield* Ref.get(subagentThreads);for (const [nativeThreadId, state] of Object.entries(input.item.agentsStates)) {const subagent = subagents.get(nativeThreadId);@@ -3107,8 +3115,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (}});- const resolvePlanId = (context: ActiveCodexTurnContext, planKey: string) =>- Effect.gen(function* () {+ const resolvePlanId =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (context: ActiveCodexTurnContext, planKey: string) {const existing = (yield* Ref.get(planIds)).get(planKey);if (existing !== undefined) {return existing;@@ -3126,8 +3135,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (return planId;});- const resolveCodexAttachment = (attachment: ChatAttachment) =>- Effect.gen(function* () {+ const resolveCodexAttachment = Effect.fn("CodexAdapterV2.resolveCodexAttachment")(+ function* (attachment: ChatAttachment) {const attachmentPath = resolveAttachmentPath({attachmentsDir: serverConfig.attachmentsDir,attachment,@@ -3150,115 +3159,115 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (type: "image" as const,url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`,} satisfies CodexSchema.V2TurnStartParams__UserInput;- });+ },+ );- const toCodexInput = (+ const toCodexInput = Effect.fn("CodexAdapterV2.toCodexInput")(function* (turnInput: Pick<| ProviderAdapter.ProviderAdapterV2TurnInput| ProviderAdapter.ProviderAdapterV2SteerInput,"message">,- ) =>- Effect.gen(function* () {- const inputItems: Array<CodexSchema.V2TurnStartParams__UserInput> = [];- const text = providerMessageTextWithAttachmentPaths({- text: codexSkillMentionText(turnInput.message.text),- attachments: turnInput.message.attachments,- resolveAttachmentPath: (attachment) =>- resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, attachment }),- });- if (text.length > 0) {- inputItems.push({- type: "text",- text,- });- }- const attachmentItems = yield* Effect.forEach(- turnInput.message.attachments.filter(isProviderNativeImageAttachment),- resolveCodexAttachment,- { concurrency: 1 },- );- inputItems.push(...attachmentItems);- if (inputItems.length === 0) {- return yield* toProtocolError("Turn requires non-empty text or attachments.");- }- return inputItems;+ ) {+ const inputItems: Array<CodexSchema.V2TurnStartParams__UserInput> = [];+ const text = providerMessageTextWithAttachmentPaths({+ text: codexSkillMentionText(turnInput.message.text),+ attachments: turnInput.message.attachments,+ resolveAttachmentPath: (attachment) =>+ resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, attachment }),});+ if (text.length > 0) {+ inputItems.push({+ type: "text",+ text,+ });+ }+ const attachmentItems = yield* Effect.forEach(+ turnInput.message.attachments.filter(isProviderNativeImageAttachment),+ resolveCodexAttachment,+ { concurrency: 1 },+ );+ inputItems.push(...attachmentItems);+ if (inputItems.length === 0) {+ return yield* toProtocolError("Turn requires non-empty text or attachments.");+ }+ return inputItems;+ });- const buildAgentMessageArtifacts = (+ // Reasoning and assistant-text coalescers build these artifacts on every streamed update.+ const buildAgentMessageArtifacts = Effect.fnUntraced(function* (context: ActiveCodexTurnContext,item: { readonly id: string; readonly text: string },completed: boolean,- ) =>- Effect.gen(function* () {- const updatedAt = yield* DateTime.now;- const completedAt = completed ? updatedAt : null;- const nodeId = idAllocator.derive.nodeFromProviderItem({- driver: CODEX_PROVIDER,- nativeItemId: item.id,- });- const { ordinal, startedAt } = yield* resolveItemPosition(context, item.id);- const messageId = idAllocator.derive.messageFromProviderItem({- driver: CODEX_PROVIDER,- nativeItemId: item.id,- });- const turnItemId = idAllocator.derive.turnItemFromProviderItem({- driver: CODEX_PROVIDER,- nativeItemId: item.id,- });- const node: OrchestrationV2ExecutionNode = {- id: nodeId,- threadId: context.projectionThreadId,- runId: context.projectionRunId,- parentNodeId: context.itemParentNodeId,- rootNodeId: context.rootNodeId,- kind: "assistant_message",- status: completed ? "completed" : "running",- countsForRun: false,- providerThreadId: context.providerThread.id,- providerTurnId: context.providerTurnId,- nativeItemRef: codexNativeItemRef(item.id),- runtimeRequestId: null,- checkpointScopeId: null,- startedAt,- completedAt,- };- const message: OrchestrationV2ConversationMessage = {- createdBy: "agent",- creationSource: "provider",- id: messageId,- threadId: context.projectionThreadId,- runId: context.projectionRunId,- nodeId,- role: "assistant",- text: item.text,- attachments: [],- streaming: !completed,- createdAt: startedAt,- updatedAt,- };- const turnItem: OrchestrationV2TurnItem = {- id: turnItemId,- threadId: context.projectionThreadId,- runId: context.projectionRunId,- nodeId,- providerThreadId: context.providerThread.id,- providerTurnId: context.providerTurnId,- nativeItemRef: codexNativeItemRef(item.id),- parentItemId: null,- ordinal,- status: completed ? "completed" : "running",- title: null,- startedAt,- completedAt,- updatedAt,- type: "assistant_message",- messageId,- text: item.text,- streaming: !completed,- };- return { node, message, turnItem };+ ) {+ const updatedAt = yield* DateTime.now;+ const completedAt = completed ? updatedAt : null;+ const nodeId = idAllocator.derive.nodeFromProviderItem({+ driver: CODEX_PROVIDER,+ nativeItemId: item.id,});+ const { ordinal, startedAt } = yield* resolveItemPosition(context, item.id);+ const messageId = idAllocator.derive.messageFromProviderItem({+ driver: CODEX_PROVIDER,+ nativeItemId: item.id,+ });+ const turnItemId = idAllocator.derive.turnItemFromProviderItem({+ driver: CODEX_PROVIDER,+ nativeItemId: item.id,+ });+ const node: OrchestrationV2ExecutionNode = {+ id: nodeId,+ threadId: context.projectionThreadId,+ runId: context.projectionRunId,+ parentNodeId: context.itemParentNodeId,+ rootNodeId: context.rootNodeId,+ kind: "assistant_message",+ status: completed ? "completed" : "running",+ countsForRun: false,+ providerThreadId: context.providerThread.id,+ providerTurnId: context.providerTurnId,+ nativeItemRef: codexNativeItemRef(item.id),+ runtimeRequestId: null,+ checkpointScopeId: null,+ startedAt,+ completedAt,+ };+ const message: OrchestrationV2ConversationMessage = {+ createdBy: "agent",+ creationSource: "provider",+ id: messageId,+ threadId: context.projectionThreadId,+ runId: context.projectionRunId,+ nodeId,+ role: "assistant",+ text: item.text,+ attachments: [],+ streaming: !completed,+ createdAt: startedAt,+ updatedAt,+ };+ const turnItem: OrchestrationV2TurnItem = {+ id: turnItemId,+ threadId: context.projectionThreadId,+ runId: context.projectionRunId,+ nodeId,+ providerThreadId: context.providerThread.id,+ providerTurnId: context.providerTurnId,+ nativeItemRef: codexNativeItemRef(item.id),+ parentItemId: null,+ ordinal,+ status: completed ? "completed" : "running",+ title: null,+ startedAt,+ completedAt,+ updatedAt,+ type: "assistant_message",+ messageId,+ text: item.text,+ streaming: !completed,+ };+ return { node, message, turnItem };+ });// Reuse the text coalescer so token bursts do not create one database write per token.const reasoningParts = new Map<@@ -3267,8 +3276,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (>();const reasoningDeltas = yield* makeProviderTextDeltaCoalescer({flushIntervalMs: CODEX_ASSISTANT_DELTA_FLUSH_INTERVAL_MS,- emit: (update) =>- Effect.gen(function* () {+ emit:+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (update) {const part = reasoningParts.get(update.itemId);if (part === undefined) return;const context = yield* awaitActiveTurn(update.turnId);@@ -3352,8 +3362,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (const agentMessageDeltas = yield* makeProviderTextDeltaCoalescer({flushIntervalMs: CODEX_ASSISTANT_DELTA_FLUSH_INTERVAL_MS,- emit: (update) =>- Effect.gen(function* () {+ emit:+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (update) {const context = yield* awaitActiveTurn(update.turnId);if (context === undefined) {return;@@ -3414,16 +3425,17 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (}),});- const emitSubagentUserMessage = (- context: ActiveCodexTurnContext,- item: Extract<- | CodexSchema.V2ItemStartedNotification__ThreadItem- | CodexSchema.V2ItemCompletedNotification__ThreadItem,- { type: "userMessage" }- >,- nativeStartedAt?: DateTime.Utc,- ) =>- Effect.gen(function* () {+ const emitSubagentUserMessage =+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (+ context: ActiveCodexTurnContext,+ item: Extract<+ | CodexSchema.V2ItemStartedNotification__ThreadItem+ | CodexSchema.V2ItemCompletedNotification__ThreadItem,+ { type: "userMessage" }+ >,+ nativeStartedAt?: DateTime.Utc,+ ) {if (context.subagent === null || context.providerTurnOrdinal === 1) {return false;}@@ -3466,82 +3478,83 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (driver: CODEX_PROVIDER,turnItem: artifacts.turnItem,});- return true;- });-- const buildCommandExecutionArtifacts = (- context: ActiveCodexTurnContext,- item: Extract<- | CodexSchema.V2ItemStartedNotification__ThreadItem- | CodexSchema.V2ItemCompletedNotification__ThreadItem,- { type: "commandExecution" }- >,- ) =>- Effect.gen(function* () {- const updatedAt = yield* DateTime.now;- const status = codexItemStatus(item.status);- const completedAt = status.completed ? updatedAt : null;- const nodeId = idAllocator.derive.nodeFromProviderItem({- driver: CODEX_PROVIDER,- nativeItemId: item.id,- });- const turnItemId = idAllocator.derive.turnItemFromProviderItem({- driver: CODEX_PROVIDER,- nativeItemId: item.id,- });- const { ordinal, startedAt } = yield* resolveItemPosition(context, item.id);- const node: OrchestrationV2ExecutionNode = {- id: nodeId,- threadId: context.projectionThreadId,- runId: context.projectionRunId,- parentNodeId: context.itemParentNodeId,- rootNodeId: context.rootNodeId,- kind: "tool_call",- status: status.node,- countsForRun: false,- providerThreadId: context.providerThread.id,- providerTurnId: context.providerTurnId,- nativeItemRef: codexNativeItemRef(item.id),- runtimeRequestId: null,- checkpointScopeId: null,- startedAt,- completedAt,- };- const turnItem: OrchestrationV2TurnItem = {- id: turnItemId,- threadId: context.projectionThreadId,- runId: context.projectionRunId,- nodeId,- providerThreadId: context.providerThread.id,- providerTurnId: context.providerTurnId,- nativeItemRef: codexNativeItemRef(item.id),- parentItemId: null,- ordinal,- status: status.turnItem,- title: null,- startedAt,- completedAt,- updatedAt,- type: "command_execution",- input: item.command,- ...(item.aggregatedOutput === null || item.aggregatedOutput === undefined- ? {}- : { output: item.aggregatedOutput }),- ...(item.exitCode === null || item.exitCode === undefined- ? {}- : { exitCode: item.exitCode }),- };- return { node, turnItem };+ return true;});- const buildFileChangeArtifacts = (+ const buildCommandExecutionArtifacts = Effect.fn(+ "CodexAdapterV2.buildCommandExecutionArtifacts",+ )(function* (context: ActiveCodexTurnContext,item: Extract<- CodexSchema.V2ItemCompletedNotification__ThreadItem,- { type: "fileChange" }+ | CodexSchema.V2ItemStartedNotification__ThreadItem+ | CodexSchema.V2ItemCompletedNotification__ThreadItem,+ { type: "commandExecution" }>,- ) =>- Effect.gen(function* () {+ ) {+ const updatedAt = yield* DateTime.now;+ const status = codexItemStatus(item.status);+ const completedAt = status.completed ? updatedAt : null;+ const nodeId = idAllocator.derive.nodeFromProviderItem({+ driver: CODEX_PROVIDER,+ nativeItemId: item.id,+ });+ const turnItemId = idAllocator.derive.turnItemFromProviderItem({+ driver: CODEX_PROVIDER,+ nativeItemId: item.id,+ });+ const { ordinal, startedAt } = yield* resolveItemPosition(context, item.id);+ const node: OrchestrationV2ExecutionNode = {+ id: nodeId,+ threadId: context.projectionThreadId,+ runId: context.projectionRunId,+ parentNodeId: context.itemParentNodeId,+ rootNodeId: context.rootNodeId,+ kind: "tool_call",+ status: status.node,+ countsForRun: false,+ providerThreadId: context.providerThread.id,+ providerTurnId: context.providerTurnId,+ nativeItemRef: codexNativeItemRef(item.id),+ runtimeRequestId: null,+ checkpointScopeId: null,+ startedAt,+ completedAt,+ };+ const turnItem: OrchestrationV2TurnItem = {+ id: turnItemId,+ threadId: context.projectionThreadId,+ runId: context.projectionRunId,+ nodeId,+ providerThreadId: context.providerThread.id,+ providerTurnId: context.providerTurnId,+ nativeItemRef: codexNativeItemRef(item.id),+ parentItemId: null,+ ordinal,+ status: status.turnItem,+ title: null,+ startedAt,+ completedAt,+ updatedAt,+ type: "command_execution",+ input: item.command,+ ...(item.aggregatedOutput === null || item.aggregatedOutput === undefined+ ? {}+ : { output: item.aggregatedOutput }),+ ...(item.exitCode === null || item.exitCode === undefined+ ? {}+ : { exitCode: item.exitCode }),+ };+ return { node, turnItem };+ });++ const buildFileChangeArtifacts = Effect.fn("CodexAdapterV2.buildFileChangeArtifacts")(+ function* (+ context: ActiveCodexTurnContext,+ item: Extract<+ CodexSchema.V2ItemCompletedNotification__ThreadItem,+ { type: "fileChange" }+ >,+ ) {const firstChange = item.changes[0];if (firstChange === undefined) {return null;@@ -3596,14 +3609,15 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (diffStr: firstChange.diff,};return { node, turnItem };- });+ },+ );- const buildWebSearchArtifacts = (input: {- readonly context: ActiveCodexTurnContext;- readonly item: CodexWebSearchItem;- readonly completed: boolean;- }) =>- Effect.gen(function* () {+ const buildWebSearchArtifacts = Effect.fn("CodexAdapterV2.buildWebSearchArtifacts")(+ function* (input: {+ readonly context: ActiveCodexTurnContext;+ readonly item: CodexWebSearchItem;+ readonly completed: boolean;+ }) {const updatedAt = yield* DateTime.now;const completedAt = input.completed ? updatedAt : null;const nodeId = idAllocator.derive.nodeFromProviderItem({@@ -3653,13 +3667,11 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (...(patterns.length === 0 ? {} : { patterns: [...patterns] }),};return { node, turnItem };- });+ },+ );- const buildDynamicToolArtifacts = (- context: ActiveCodexTurnContext,- item: CodexDynamicToolItem,- ) =>- Effect.gen(function* () {+ const buildDynamicToolArtifacts = Effect.fn("CodexAdapterV2.buildDynamicToolArtifacts")(+ function* (context: ActiveCodexTurnContext, item: CodexDynamicToolItem) {const updatedAt = yield* DateTime.now;const status = codexItemStatus(item.status);const completedAt = status.completed ? updatedAt : null;@@ -3710,36 +3722,36 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (...projection,};return { node, turnItem };- });+ },+ );/*** The item stays running until then, which keeps the run's event* ingestion open past turn/completed; it runs off the notification* reader so a slow server cannot stall other events.*/- const captureMcpApp = (+ const captureMcpApp = Effect.fn("CodexAdapterV2.captureMcpApp")(function* (context: ActiveCodexTurnContext,nativeTurnId: string,item: Extract<CodexDynamicToolItem, { readonly type: "mcpToolCall" }>,resourceUri: string,- ) =>- Effect.gen(function* () {- // Registered before it can run, so a turn ending right away sees it.- const started = yield* Deferred.make<void>();- const fiber = yield* Deferred.await(started).pipe(- Effect.andThen(captureMcpAppItem(context, nativeTurnId, item, resourceUri)),- Effect.forkIn(scope, { startImmediately: true }),+ ) {+ // Registered before it can run, so a turn ending right away sees it.+ const started = yield* Deferred.make<void>();+ const fiber = yield* Deferred.await(started).pipe(+ Effect.andThen(captureMcpAppItem(context, nativeTurnId, item, resourceUri)),+ Effect.forkIn(scope, { startImmediately: true }),+ );+ yield* Ref.update(pendingMcpAppCaptures, (current) => {+ const updated = new Map(current);+ updated.set(+ nativeTurnId,+ new Map(current.get(nativeTurnId) ?? []).set(item.id, { item, fiber }),);- yield* Ref.update(pendingMcpAppCaptures, (current) => {- const updated = new Map(current);- updated.set(- nativeTurnId,- new Map(current.get(nativeTurnId) ?? []).set(item.id, { item, fiber }),- );- return updated;- });- yield* Deferred.succeed(started, undefined);+ return updated;});+ yield* Deferred.succeed(started, undefined);+ });const captureMcpAppItem = (context: ActiveCodexTurnContext,@@ -3830,8 +3842,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (}),);- const terminalizeMcpAppCaptures = (context: ActiveCodexTurnContext, nativeTurnId: string) =>- Effect.gen(function* () {+ const terminalizeMcpAppCaptures = Effect.fn("CodexAdapterV2.terminalizeMcpAppCaptures")(+ function* (context: ActiveCodexTurnContext, nativeTurnId: string) {const captures = (yield* Ref.get(pendingMcpAppCaptures)).get(nativeTurnId);if (captures === undefined) return;for (const { item, fiber } of captures.values()) {@@ -3849,84 +3861,86 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (turnItem: artifacts.turnItem,});}- });+ },+ );- const buildProposedPlanArtifacts = (input: {+ // The plan coalescer builds these artifacts on every streamed update.+ const buildProposedPlanArtifacts = Effect.fnUntraced(function* (input: {readonly context: ActiveCodexTurnContext;readonly nativeItemId: string;readonly status: OrchestrationV2PlanArtifact["status"];readonly markdown: string;readonly completed?: boolean;- }) =>- Effect.gen(function* () {- const updatedAt = yield* DateTime.now;- const completedAt = input.completed === true ? updatedAt : null;- const planId = yield* resolvePlanId(input.context, input.nativeItemId);- const nodeId = idAllocator.derive.nodeFromProviderItem({- driver: CODEX_PROVIDER,- nativeItemId: input.nativeItemId,- });- const turnItemId = idAllocator.derive.turnItemFromProviderItem({- driver: CODEX_PROVIDER,- nativeItemId: input.nativeItemId,- });- const { ordinal, startedAt } = yield* resolveItemPosition(- input.context,- input.nativeItemId,- );- const plan: OrchestrationV2PlanArtifact = {- id: planId,- threadId: input.context.projectionThreadId,- runId: input.context.projectionRunId,- nodeId,- kind: "proposed_plan",- status: input.status,- markdown: input.markdown,- };- const node: OrchestrationV2ExecutionNode = {- id: nodeId,- threadId: input.context.projectionThreadId,- runId: input.context.projectionRunId,- parentNodeId: input.context.itemParentNodeId,- rootNodeId: input.context.rootNodeId,- kind: "plan",- status: input.completed === true ? "completed" : "running",- countsForRun: false,- providerThreadId: input.context.providerThread.id,- providerTurnId: input.context.providerTurnId,- nativeItemRef: codexNativeItemRef(input.nativeItemId),- runtimeRequestId: null,- checkpointScopeId: null,- startedAt,- completedAt,- };- const turnItem: OrchestrationV2TurnItem = {- id: turnItemId,- threadId: input.context.projectionThreadId,- runId: input.context.projectionRunId,- nodeId,- providerThreadId: input.context.providerThread.id,- providerTurnId: input.context.providerTurnId,- nativeItemRef: codexNativeItemRef(input.nativeItemId),- parentItemId: null,- ordinal,- status: input.completed === true ? "completed" : "running",- title: null,- startedAt,- completedAt,- updatedAt,- type: "proposed_plan",- planId,- markdown: input.markdown,- streaming: input.completed !== true,- };- return { node, plan, turnItem };+ }) {+ const updatedAt = yield* DateTime.now;+ const completedAt = input.completed === true ? updatedAt : null;+ const planId = yield* resolvePlanId(input.context, input.nativeItemId);+ const nodeId = idAllocator.derive.nodeFromProviderItem({+ driver: CODEX_PROVIDER,+ nativeItemId: input.nativeItemId,});+ const turnItemId = idAllocator.derive.turnItemFromProviderItem({+ driver: CODEX_PROVIDER,+ nativeItemId: input.nativeItemId,+ });+ const { ordinal, startedAt } = yield* resolveItemPosition(+ input.context,+ input.nativeItemId,+ );+ const plan: OrchestrationV2PlanArtifact = {+ id: planId,+ threadId: input.context.projectionThreadId,+ runId: input.context.projectionRunId,+ nodeId,+ kind: "proposed_plan",+ status: input.status,+ markdown: input.markdown,+ };+ const node: OrchestrationV2ExecutionNode = {+ id: nodeId,+ threadId: input.context.projectionThreadId,+ runId: input.context.projectionRunId,+ parentNodeId: input.context.itemParentNodeId,+ rootNodeId: input.context.rootNodeId,+ kind: "plan",+ status: input.completed === true ? "completed" : "running",+ countsForRun: false,+ providerThreadId: input.context.providerThread.id,+ providerTurnId: input.context.providerTurnId,+ nativeItemRef: codexNativeItemRef(input.nativeItemId),+ runtimeRequestId: null,+ checkpointScopeId: null,+ startedAt,+ completedAt,+ };+ const turnItem: OrchestrationV2TurnItem = {+ id: turnItemId,+ threadId: input.context.projectionThreadId,+ runId: input.context.projectionRunId,+ nodeId,+ providerThreadId: input.context.providerThread.id,+ providerTurnId: input.context.providerTurnId,+ nativeItemRef: codexNativeItemRef(input.nativeItemId),+ parentItemId: null,+ ordinal,+ status: input.completed === true ? "completed" : "running",+ title: null,+ startedAt,+ completedAt,+ updatedAt,+ type: "proposed_plan",+ planId,+ markdown: input.markdown,+ streaming: input.completed !== true,+ };+ return { node, plan, turnItem };+ });const planDeltas = yield* makeProviderTextDeltaCoalescer({flushIntervalMs: CODEX_PLAN_DELTA_FLUSH_INTERVAL_MS,- emit: (update) =>- Effect.gen(function* () {+ emit:+ /* Provider events include streaming deltas; avoid a span for each update. */+ Effect.fnUntraced(function* (update) {const resolved = yield* resolveItemEventContext(update.turnId);if (resolved === undefined) return;const interrupted = (yield* Ref.get(terminalizedNonCompletedNativeTurns)).has(@@ -3955,18 +3969,18 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (driver: CODEX_PROVIDER,turnItem: artifacts.turnItem,});- }).pipe(Effect.orDie),+ }, Effect.orDie),});- const buildTodoListArtifacts = (input: {- readonly context: ActiveCodexTurnContext;- readonly nativeItemId: string;- readonly status: OrchestrationV2PlanArtifact["status"];- readonly steps: ReadonlyArray<OrchestrationV2PlanStep>;- readonly explanation?: string;- readonly completed?: boolean;- }) =>- Effect.gen(function* () {+ const buildTodoListArtifacts = Effect.fn("CodexAdapterV2.buildTodoListArtifacts")(+ function* (input: {+ readonly context: ActiveCodexTurnContext;+ readonly nativeItemId: string;+ readonly status: OrchestrationV2PlanArtifact["status"];+ readonly steps: ReadonlyArray<OrchestrationV2PlanStep>;+ readonly explanation?: string;+ readonly completed?: boolean;+ }) {const updatedAt = yield* DateTime.now;const completedAt = input.completed === true ? updatedAt : null;const planId = yield* resolvePlanId(input.context, input.nativeItemId);@@ -4030,9 +4044,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (...(input.explanation === undefined ? {} : { explanation: input.explanation }),};return { node, plan, turnItem };- });+ },+ );- const buildApprovalRequestArtifacts = (input: {+ const buildApprovalRequestArtifacts = Effect.fn(+ "CodexAdapterV2.buildApprovalRequestArtifacts",+ )(function* (input: {readonly context: ActiveCodexTurnContext;readonly nativeItemId: string;readonly nativeRequestId: string;@@ -4040,190 +4057,190 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (readonly prompt?: string | null;readonly appName?: string;readonly options?: ReadonlyArray<ProviderApprovalOption>;- }) =>- Effect.gen(function* () {- const createdAt = yield* DateTime.now;- const { owner, subagent } = approvalOwnerCodexTurn(input.context);- const parentNodeId =- subagent?.subagentNodeId ??- idAllocator.derive.nodeFromProviderItem({- driver: CODEX_PROVIDER,- nativeItemId: input.nativeItemId,- });- const ordinal = yield* resolveItemOrdinal(- owner,- `${input.nativeItemId}:approval:${input.nativeRequestId}`,- );- const requestId = yield* idAllocator.allocate.runtimeRequest({+ }) {+ const createdAt = yield* DateTime.now;+ const { owner, subagent } = approvalOwnerCodexTurn(input.context);+ const parentNodeId =+ subagent?.subagentNodeId ??+ idAllocator.derive.nodeFromProviderItem({driver: CODEX_PROVIDER,- providerTurnId: owner.providerTurnId,- nativeRequestId: input.nativeRequestId,+ nativeItemId: input.nativeItemId,});- const nodeId = idAllocator.derive.approvalNode({ requestId });- const providerSessionId = owner.input.providerThread.providerSessionId;- if (providerSessionId === null) {- return yield* toProtocolError(- `Provider thread ${owner.providerThread.id} is missing a provider session id.`,- );- }- const node: OrchestrationV2ExecutionNode = {- id: nodeId,- threadId: owner.projectionThreadId,- runId: owner.projectionRunId,- parentNodeId,- rootNodeId: owner.rootNodeId,- kind: "approval_request",- status: "waiting",- countsForRun: false,- providerThreadId: owner.providerThread.id,- providerTurnId: owner.providerTurnId,- nativeItemRef: codexNativeItemRef(input.nativeItemId),- runtimeRequestId: requestId,- checkpointScopeId: null,- startedAt: createdAt,- completedAt: null,- };- const request: OrchestrationV2RuntimeRequest = {- id: requestId,- nodeId,- providerTurnId: owner.providerTurnId,- nativeRequestRef: {- driver: CODEX_PROVIDER,- nativeId: input.nativeRequestId,- strength: "strong",- },- kind: input.requestKind,- status: "pending",- responseCapability: {- type: "live",- providerSessionId,- },- createdAt,- resolvedAt: null,- };- const turnItem: OrchestrationV2TurnItem = {- id: idAllocator.derive.approvalTurnItem({ requestId }),- threadId: owner.projectionThreadId,- runId: owner.projectionRunId,- nodeId,- providerThreadId: owner.providerThread.id,- providerTurnId: owner.providerTurnId,- nativeItemRef: codexNativeItemRef(input.nativeItemId),- parentItemId: null,- ordinal,- status: "waiting",- title: null,- startedAt: createdAt,- completedAt: null,- updatedAt: createdAt,- type: "approval_request",- requestId,- requestKind: input.requestKind,- ...(input.prompt === null || input.prompt === undefined- ? {}- : { prompt: input.prompt }),- ...(input.appName === undefined ? {} : { appName: input.appName }),- ...(input.options === undefined ? {} : { options: input.options }),- };- return { node, request, turnItem };+ const ordinal = yield* resolveItemOrdinal(+ owner,+ `${input.nativeItemId}:approval:${input.nativeRequestId}`,+ );+ const requestId = yield* idAllocator.allocate.runtimeRequest({+ driver: CODEX_PROVIDER,+ providerTurnId: owner.providerTurnId,+ nativeRequestId: input.nativeRequestId,});+ const nodeId = idAllocator.derive.approvalNode({ requestId });+ const providerSessionId = owner.input.providerThread.providerSessionId;+ if (providerSessionId === null) {+ return yield* toProtocolError(+ `Provider thread ${owner.providerThread.id} is missing a provider session id.`,+ );+ }+ const node: OrchestrationV2ExecutionNode = {+ id: nodeId,+ threadId: owner.projectionThreadId,+ runId: owner.projectionRunId,+ parentNodeId,+ rootNodeId: owner.rootNodeId,+ kind: "approval_request",+ status: "waiting",+ countsForRun: false,+ providerThreadId: owner.providerThread.id,+ providerTurnId: owner.providerTurnId,+ nativeItemRef: codexNativeItemRef(input.nativeItemId),+ runtimeRequestId: requestId,+ checkpointScopeId: null,+ startedAt: createdAt,+ completedAt: null,+ };+ const request: OrchestrationV2RuntimeRequest = {+ id: requestId,+ nodeId,+ providerTurnId: owner.providerTurnId,+ nativeRequestRef: {+ driver: CODEX_PROVIDER,+ nativeId: input.nativeRequestId,+ strength: "strong",+ },+ kind: input.requestKind,+ status: "pending",+ responseCapability: {+ type: "live",+ providerSessionId,+ },+ createdAt,+ resolvedAt: null,+ };+ const turnItem: OrchestrationV2TurnItem = {+ id: idAllocator.derive.approvalTurnItem({ requestId }),+ threadId: owner.projectionThreadId,+ runId: owner.projectionRunId,+ nodeId,+ providerThreadId: owner.providerThread.id,+ providerTurnId: owner.providerTurnId,+ nativeItemRef: codexNativeItemRef(input.nativeItemId),+ parentItemId: null,+ ordinal,+ status: "waiting",+ title: null,+ startedAt: createdAt,+ completedAt: null,+ updatedAt: createdAt,+ type: "approval_request",+ requestId,+ requestKind: input.requestKind,+ ...(input.prompt === null || input.prompt === undefined+ ? {}+ : { prompt: input.prompt }),+ ...(input.appName === undefined ? {} : { appName: input.appName }),+ ...(input.options === undefined ? {} : { options: input.options }),+ };+ return { node, request, turnItem };+ });- const buildUserInputRequestArtifacts = (input: {+ const buildUserInputRequestArtifacts = Effect.fn(+ "CodexAdapterV2.buildUserInputRequestArtifacts",+ )(function* (input: {readonly context: ActiveCodexTurnContext;readonly nativeItemId: string;readonly nativeRequestId: string;readonly questions: ReadonlyArray<CodexSchema.ToolRequestUserInputParams__ToolRequestUserInputQuestion>;readonly responseMode?: "message";- }) =>- Effect.gen(function* () {- const createdAt = yield* DateTime.now;- const requestId = yield* idAllocator.allocate.runtimeRequest({- driver: CODEX_PROVIDER,- providerTurnId: input.context.providerTurnId,- nativeRequestId: input.nativeRequestId,- });- const providerSessionId = input.context.input.providerThread.providerSessionId;- if (providerSessionId === null) {- return yield* toProtocolError(- `Provider thread ${input.context.providerThread.id} is missing a provider session id.`,- );- }- const questions = input.questions.map((question, index) => ({- id: nonEmptyText(question.id, `question-${index + 1}`),- header: nonEmptyText(question.header, "Question"),- question: nonEmptyText(question.question, "Choose an answer."),- options:- question.options?.map((option, optionIndex) => ({- label: nonEmptyText(option.label, `Option ${optionIndex + 1}`),- description: nonEmptyText(option.description, option.label),- })) ?? [],- }));- const nodeId = idAllocator.derive.nodeFromProviderItem({- driver: CODEX_PROVIDER,- nativeItemId: input.nativeItemId,- });- const turnItemId = idAllocator.derive.turnItemFromProviderItem({- driver: CODEX_PROVIDER,- nativeItemId: input.nativeItemId,- });- const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId);- const node: OrchestrationV2ExecutionNode = {- id: nodeId,- threadId: input.context.projectionThreadId,- runId: input.context.projectionRunId,- parentNodeId: input.context.itemParentNodeId,- rootNodeId: input.context.rootNodeId,- kind: "user_input_request",- status: "waiting",- countsForRun: false,- providerThreadId: input.context.providerThread.id,- providerTurnId: input.context.providerTurnId,- nativeItemRef: codexNativeItemRef(input.nativeItemId),- runtimeRequestId: requestId,- checkpointScopeId: null,- startedAt: createdAt,- completedAt: null,- };- const request: OrchestrationV2RuntimeRequest = {- id: requestId,- nodeId,- providerTurnId: input.context.providerTurnId,- nativeRequestRef: {- driver: CODEX_PROVIDER,- nativeId: input.nativeRequestId,- strength: "strong",- },- kind: "user_input",- status: "pending",- responseCapability:- input.responseMode === "message"- ? { type: "message" }- : { type: "live", providerSessionId },- createdAt,- resolvedAt: null,- };- const turnItem: OrchestrationV2TurnItem = {- id: turnItemId,- threadId: input.context.projectionThreadId,- runId: input.context.projectionRunId,- nodeId,- providerThreadId: input.context.providerThread.id,- providerTurnId: input.context.providerTurnId,- nativeItemRef: codexNativeItemRef(input.nativeItemId),- parentItemId: null,- ordinal,- status: "waiting",- title: null,- startedAt: createdAt,- completedAt: null,- updatedAt: createdAt,- type: "user_input_request",- requestId,- questions,- ...(input.responseMode === undefined ? {} : { responseMode: input.responseMode }),- };- return { node, request, turnItem };+ }) {+ const createdAt = yield* DateTime.now;+ const requestId = yield* idAllocator.allocate.runtimeRequest({+ driver: CODEX_PROVIDER,+ providerTurnId: input.context.providerTurnId,+ nativeRequestId: input.nativeRequestId,+ });+ const providerSessionId = input.context.input.providerThread.providerSessionId;+ if (providerSessionId === null) {+ return yield* toProtocolError(+ `Provider thread ${input.context.providerThread.id} is missing a provider session id.`,+ );+ }+ const questions = input.questions.map((question, index) => ({+ id: nonEmptyText(question.id, `question-${index + 1}`),+ header: nonEmptyText(question.header, "Question"),+ question: nonEmptyText(question.question, "Choose an answer."),+ options:+ question.options?.map((option, optionIndex) => ({+ label: nonEmptyText(option.label, `Option ${optionIndex + 1}`),+ description: nonEmptyText(option.description, option.label),+ })) ?? [],+ }));+ const nodeId = idAllocator.derive.nodeFromProviderItem({+ driver: CODEX_PROVIDER,+ nativeItemId: input.nativeItemId,+ });+ const turnItemId = idAllocator.derive.turnItemFromProviderItem({+ driver: CODEX_PROVIDER,+ nativeItemId: input.nativeItemId,});+ const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId);+ const node: OrchestrationV2ExecutionNode = {+ id: nodeId,+ threadId: input.context.projectionThreadId,+ runId: input.context.projectionRunId,+ parentNodeId: input.context.itemParentNodeId,+ rootNodeId: input.context.rootNodeId,+ kind: "user_input_request",+ status: "waiting",+ countsForRun: false,+ providerThreadId: input.context.providerThread.id,+ providerTurnId: input.context.providerTurnId,+ nativeItemRef: codexNativeItemRef(input.nativeItemId),+ runtimeRequestId: requestId,+ checkpointScopeId: null,+ startedAt: createdAt,+ completedAt: null,+ };+ const request: OrchestrationV2RuntimeRequest = {+ id: requestId,+ nodeId,+ providerTurnId: input.context.providerTurnId,+ nativeRequestRef: {+ driver: CODEX_PROVIDER,+ nativeId: input.nativeRequestId,+ strength: "strong",+ },+ kind: "user_input",+ status: "pending",+ responseCapability:+ input.responseMode === "message"+ ? { type: "message" }+ : { type: "live", providerSessionId },+ createdAt,+ resolvedAt: null,+ };+ const turnItem: OrchestrationV2TurnItem = {+ id: turnItemId,+ threadId: input.context.projectionThreadId,+ runId: input.context.projectionRunId,+ nodeId,+ providerThreadId: input.context.providerThread.id,+ providerTurnId: input.context.providerTurnId,+ nativeItemRef: codexNativeItemRef(input.nativeItemId),+ parentItemId: null,+ ordinal,+ status: "waiting",+ title: null,+ startedAt: createdAt,+ completedAt: null,+ updatedAt: createdAt,+ type: "user_input_request",+ requestId,+ questions,+ ...(input.responseMode === undefined ? {} : { responseMode: input.responseMode }),+ };+ return { node, request, turnItem };+ });yield* client.handleServerNotification("item/agentMessage/delta", (payload) =>Effect.gen(function* () {@@ -6214,11 +6231,11 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ();});- const startNativeTurn = (- turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,- codexInput: ReadonlyArray<CodexSchema.V2TurnStartParams__UserInput>,- ) =>- Effect.gen(function* () {+ const startNativeTurn = Effect.fn("CodexAdapterV2.startNativeTurn")(+ function* (+ turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,+ codexInput: ReadonlyArray<CodexSchema.V2TurnStartParams__UserInput>,+ ) {const threadId = yield* getNativeThreadId(turnInput.providerThread);const mcpSession = yield* mcpSessions.read(turnInput.threadId);const turnStartParams = yield* buildCodexTurnStartParams({@@ -6247,32 +6264,35 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (const started = yield* client.request("turn/start", turnStartParams);yield* registerRootTurn({turnInput,- nativeTurnId: started.turn.id,- startedAt: codexTimestamp(started.turn.startedAt),- waitForNativeStart: started.turn.startedAt === null,- });- }).pipe(- Effect.ensuring(- Effect.flatMap(getNativeThreadId(turnInput.providerThread), (threadId) =>- Ref.update(pendingRootTurns, (current) => {- const updated = new Map(current);- updated.delete(threadId);- return updated;- }),- ).pipe(Effect.ignore),+ nativeTurnId: started.turn.id,+ startedAt: codexTimestamp(started.turn.startedAt),+ waitForNativeStart: started.turn.startedAt === null,+ });+ },+ (effect, turnInput) =>+ effect.pipe(+ Effect.ensuring(+ Effect.flatMap(getNativeThreadId(turnInput.providerThread), (threadId) =>+ Ref.update(pendingRootTurns, (current) => {+ const updated = new Map(current);+ updated.delete(threadId);+ return updated;+ }),+ ).pipe(Effect.ignore),+ ),),- );+ );/*** Setting or resuming a goal starts the first goal turn with this run's* turn configuration (approvals, sandbox, model, plan mode), since a* turn Codex starts on its own reuses the last turn's settings.*/- const runGoalCommand = (- turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,- command: CodexGoalCommand,- ) =>- Effect.gen(function* () {+ const runGoalCommand = Effect.fn("CodexAdapterV2.runGoalCommand")(+ function* (+ turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,+ command: CodexGoalCommand,+ ) {const threadId = yield* getNativeThreadId(turnInput.providerThread);rootProviderThreads.set(threadId, turnInput.providerThread);const readGoal = client@@ -6363,18 +6383,21 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (),),);- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterTurnStartError({- driver: CODEX_PROVIDER,- threadId: turnInput.threadId,- providerThreadId: turnInput.providerThread.id,- runId: turnInput.runId,- cause,- }),+ },+ (effect, turnInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterTurnStartError({+ driver: CODEX_PROVIDER,+ threadId: turnInput.threadId,+ providerThreadId: turnInput.providerThread.id,+ runId: turnInput.runId,+ cause,+ }),+ ),),- );+ );const mcpAppsError = (detail: string) => (cause: unknown) =>new ProviderAdapter.ProviderAdapterProtocolError({@@ -6383,8 +6406,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (payload: cause,});const mcpApps: ProviderAdapter.ProviderAdapterV2McpApps = {- listTools: (toolsInput) =>- Effect.gen(function* () {+ listTools: Effect.fn("CodexAdapterV2.listTools")(+ function* (toolsInput) {const threadId = yield* getNativeThreadId(toolsInput.providerThread);const response = yield* ensureInitialized.pipe(Effect.andThen(@@ -6397,9 +6420,11 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ();const server = response.data.find((entry) => entry.name === toolsInput.server);return Object.values(server?.tools ?? {});- }).pipe(Effect.mapError(mcpAppsError("Failed to list Codex MCP tools."))),- callTool: (callInput) =>- Effect.gen(function* () {+ },+ Effect.mapError(mcpAppsError("Failed to list Codex MCP tools.")),+ ),+ callTool: Effect.fn("CodexAdapterV2.callTool")(+ function* (callInput) {const threadId = yield* getNativeThreadId(callInput.providerThread);const response = yield* ensureInitialized.pipe(Effect.andThen(@@ -6419,9 +6444,11 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (...(response.isError === true ? { isError: true } : {}),...(response._meta === undefined ? {} : { _meta: response._meta }),};- }).pipe(Effect.mapError(mcpAppsError("Codex MCP tool call failed."))),- readResource: (readInput) =>- Effect.gen(function* () {+ },+ Effect.mapError(mcpAppsError("Codex MCP tool call failed.")),+ ),+ readResource: Effect.fn("CodexAdapterV2.readResource")(+ function* (readInput) {const threadId = yield* getNativeThreadId(readInput.providerThread);const response = yield* ensureInitialized.pipe(Effect.andThen(@@ -6433,7 +6460,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (),);return { contents: response.contents };- }).pipe(Effect.mapError(mcpAppsError("Codex MCP resource read failed."))),+ },+ Effect.mapError(mcpAppsError("Codex MCP resource read failed.")),+ ),};const runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime = {@@ -6468,27 +6497,28 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (}return false;}),- hasPendingBackgroundWorkForThread: (providerThread) =>- Effect.gen(function* () {- const contexts = [- ...(yield* Ref.get(activeTurns)).values(),- ...(yield* Ref.get(settledTurns)).values(),- ];- const roots = contexts.filter(- (context) => context.providerThread.id === providerThread.id,- );- for (const context of contexts) {- if (!roots.some((root) => context === root || isDescendantCodexTurn(context, root)))- continue;- if (yield* turnHasRetainedBackgroundWork(context.nativeTurnId)) return true;- if (- context.subagent !== null &&- (yield* Ref.get(activeTurns)).has(context.nativeTurnId)- )- return true;- }- return false;- }),+ hasPendingBackgroundWorkForThread: Effect.fn(+ "CodexAdapterV2.hasPendingBackgroundWorkForThread",+ )(function* (providerThread) {+ const contexts = [+ ...(yield* Ref.get(activeTurns)).values(),+ ...(yield* Ref.get(settledTurns)).values(),+ ];+ const roots = contexts.filter(+ (context) => context.providerThread.id === providerThread.id,+ );+ for (const context of contexts) {+ if (!roots.some((root) => context === root || isDescendantCodexTurn(context, root)))+ continue;+ if (yield* turnHasRetainedBackgroundWork(context.nativeTurnId)) return true;+ if (+ context.subagent !== null &&+ (yield* Ref.get(activeTurns)).has(context.nativeTurnId)+ )+ return true;+ }+ return false;+ }),ensureThread: (threadInput) =>ensureInitialized.pipe(Effect.andThen(mcpSessions.read(threadInput.threadId)),@@ -6521,8 +6551,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (}),),),- resumeThread: (threadInput) =>- Effect.gen(function* () {+ resumeThread: Effect.fn("CodexAdapterV2.resumeThread")(+ function* (threadInput) {const nativeThreadId = yield* getNativeThreadId(threadInput.providerThread);// excludeTurns is not in the generated request schema yet.const resume = client.raw.request("thread/resume", {@@ -6574,19 +6604,22 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (nativeConversationHeadRef: threadInput.providerThread.nativeConversationHeadRef,updatedAt: codexTimestamp(response.thread.updatedAt),} satisfies OrchestrationV2ProviderThread;- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterResumeThreadError({- driver: CODEX_PROVIDER,- providerSessionId: input.providerSessionId,- providerThreadId: threadInput.providerThread.id,- cause: normalizeCodexCause(cause),- }),+ },+ (effect, threadInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterResumeThreadError({+ driver: CODEX_PROVIDER,+ providerSessionId: input.providerSessionId,+ providerThreadId: threadInput.providerThread.id,+ cause: normalizeCodexCause(cause),+ }),+ ),),- ),- compactThread: (turnInput) =>- Effect.gen(function* () {+ ),+ compactThread: Effect.fn("CodexAdapterV2.compactThread")(+ function* (turnInput) {const threadId = yield* getNativeThreadId(turnInput.providerThread);yield* Ref.update(pendingRootTurns, (current) =>new Map(current).set(threadId, turnInput),@@ -6602,20 +6635,23 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (}),),);- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterTurnStartError({- driver: CODEX_PROVIDER,- threadId: turnInput.threadId,- providerThreadId: turnInput.providerThread.id,- runId: turnInput.runId,- cause,- }),+ },+ (effect, turnInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterTurnStartError({+ driver: CODEX_PROVIDER,+ threadId: turnInput.threadId,+ providerThreadId: turnInput.providerThread.id,+ runId: turnInput.runId,+ cause,+ }),+ ),),- ),- injectHistory: (input) =>- Effect.gen(function* () {+ ),+ injectHistory: Effect.fn("CodexAdapterV2.injectHistory")(+ function* (input) {const threadId = yield* getNativeThreadId(input.providerThread);return yield* client.request("thread/inject_items", {@@ -6632,16 +6668,16 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (error.code === -32601 ? Effect.succeed(false) : Effect.fail(error),}),);- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterProtocolError({- driver: CODEX_PROVIDER,- detail: "Failed to inject historical context",- cause,- }),- ),+ },+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterProtocolError({+ driver: CODEX_PROVIDER,+ detail: "Failed to inject historical context",+ cause,+ }),),+ ),startTurn: (turnInput) => {const goalCommand =turnInput.message.attachments.length === 0 &&@@ -6669,8 +6705,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (),);},- steerTurn: (turnInput) =>- Effect.gen(function* () {+ steerTurn: Effect.fn("CodexAdapterV2.steerTurn")(+ function* (turnInput) {const threadId = yield* getNativeThreadId(turnInput.providerThread);const latestTurnId = latestGoalTurnId(turnInput.providerTurnId);const held = heldGoalTurn(turnInput.providerThread, latestTurnId);@@ -6693,37 +6729,43 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (input: codexInput,threadId,});- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterSteerRunError({- driver: CODEX_PROVIDER,- providerThreadId: turnInput.providerThread.id,- providerTurnId: turnInput.providerTurnId,- cause,- }),+ },+ (effect, turnInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterSteerRunError({+ driver: CODEX_PROVIDER,+ providerThreadId: turnInput.providerThread.id,+ providerTurnId: turnInput.providerTurnId,+ cause,+ }),+ ),),- ),+ ),// Dropping this connection's subscription lets the shared app-server// shut the native thread (and its MCP servers) down once it is idle.- unloadThread: (unloadInput) =>- Effect.gen(function* () {+ unloadThread: Effect.fn("CodexAdapterV2.unloadThread")(+ function* (unloadInput) {const nativeThreadId = yield* getNativeThreadId(unloadInput.providerThread);sessionApprovals.delete(nativeThreadId);yield* client.request("thread/unsubscribe", { threadId: nativeThreadId });- }).pipe(- Effect.mapError((cause) =>- cause._tag === "ProviderAdapterProtocolError"- ? cause- : new ProviderAdapter.ProviderAdapterProtocolError({- driver: CODEX_PROVIDER,- detail: `Failed to unload Codex thread for provider thread ${unloadInput.providerThread.id}`,- cause: normalizeCodexCause(cause),- }),+ },+ (effect, unloadInput) =>+ effect.pipe(+ Effect.mapError((cause) =>+ cause._tag === "ProviderAdapterProtocolError"+ ? cause+ : new ProviderAdapter.ProviderAdapterProtocolError({+ driver: CODEX_PROVIDER,+ detail: `Failed to unload Codex thread for provider thread ${unloadInput.providerThread.id}`,+ cause: normalizeCodexCause(cause),+ }),+ ),),- ),- interruptTurn: (requestedInput) =>- Effect.gen(function* () {+ ),+ interruptTurn: Effect.fn("CodexAdapterV2.interruptTurn")(+ function* (requestedInput) {const { turnInput, goalTurns } = yield* resolveGoalStopTarget(requestedInput);const [activeTurnContexts, settledTurnContexts] =yield* turnTerminalizationPermit.withPermits(1)(@@ -6977,8 +7019,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (}const containedTerminalKeys = new Set<string>();const attemptedTerminalKeys = new Set<string>();- const collectTrackedTerminals = (targets: typeof interruptTargets) =>- Effect.gen(function* () {+ const collectTrackedTerminals = Effect.fn("CodexAdapterV2.collectTrackedTerminals")(+ function* (targets: typeof interruptTargets) {const trackedTerminals = new Map<string,{ readonly nativeThreadId: string; readonly processId: string }@@ -6999,32 +7041,32 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (}}return trackedTerminals;- });- const terminateTrackedTerminals = (targets: typeof interruptTargets) =>- Effect.gen(function* () {- const trackedTerminals = yield* collectTrackedTerminals(targets);- const pendingTerminals = Array.from(trackedTerminals.entries())- .filter(([key]) => !containedTerminalKeys.has(key))- .sort(- ([leftKey], [rightKey]) =>- Number(attemptedTerminalKeys.has(leftKey)) -- Number(attemptedTerminalKeys.has(rightKey)),- );- return yield* Effect.forEach(- pendingTerminals,- ([key, { nativeThreadId, processId }]) =>- Effect.gen(function* () {- attemptedTerminalKeys.add(key);- yield* terminateBackgroundTerminal(nativeThreadId, processId);- containedTerminalKeys.add(key);- }).pipe(- Effect.as({ success: true as const }),- Effect.catch((error) =>- Effect.succeed({ success: false as const, error }),- ),- ),+ },+ );+ const terminateTrackedTerminals = Effect.fn(+ "CodexAdapterV2.terminateTrackedTerminals",+ )(function* (targets: typeof interruptTargets) {+ const trackedTerminals = yield* collectTrackedTerminals(targets);+ const pendingTerminals = Array.from(trackedTerminals.entries())+ .filter(([key]) => !containedTerminalKeys.has(key))+ .sort(+ ([leftKey], [rightKey]) =>+ Number(attemptedTerminalKeys.has(leftKey)) -+ Number(attemptedTerminalKeys.has(rightKey)),);- });+ return yield* Effect.forEach(+ pendingTerminals,+ ([key, { nativeThreadId, processId }]) =>+ Effect.gen(function* () {+ attemptedTerminalKeys.add(key);+ yield* terminateBackgroundTerminal(nativeThreadId, processId);+ containedTerminalKeys.add(key);+ }).pipe(+ Effect.as({ success: true as const }),+ Effect.catch((error) => Effect.succeed({ success: false as const, error })),+ ),+ );+ });const [, completed] = yield* Effect.all([@@ -7094,19 +7136,22 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (Effect.onError(() => finalizeRemainingInterruptLineage),Effect.ensuring(cleanupInterruptState),);- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterInterruptError({- driver: CODEX_PROVIDER,- providerThreadId: requestedInput.providerThread.id,- providerTurnId: requestedInput.providerTurnId,- cause,- }),+ },+ (effect, requestedInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterInterruptError({+ driver: CODEX_PROVIDER,+ providerThreadId: requestedInput.providerThread.id,+ providerTurnId: requestedInput.providerTurnId,+ cause,+ }),+ ),),- ),- respondToRuntimeRequest: (requestInput) =>- Effect.gen(function* () {+ ),+ respondToRuntimeRequest: Effect.fn("CodexAdapterV2.respondToRuntimeRequest")(+ function* (requestInput) {const pending = (yield* Ref.get(pendingRuntimeRequests)).get(String(requestInput.requestId),);@@ -7142,19 +7187,22 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (});}yield* Deferred.succeed(pending.decision, requestInput.decision);- }).pipe(- Effect.mapError((cause) =>- isProviderAdapterRuntimeRequestResponseError(cause)- ? cause- : new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({- driver: CODEX_PROVIDER,- requestId: requestInput.requestId,- cause,- }),+ },+ (effect, requestInput) =>+ effect.pipe(+ Effect.mapError((cause) =>+ isProviderAdapterRuntimeRequestResponseError(cause)+ ? cause+ : new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({+ driver: CODEX_PROVIDER,+ requestId: requestInput.requestId,+ cause,+ }),+ ),),- ),- uploadFeedback: (feedbackInput) =>- Effect.gen(function* () {+ ),+ uploadFeedback: Effect.fn("CodexAdapterV2.uploadFeedback")(+ function* (feedbackInput) {const threadId = yield* getNativeThreadId(feedbackInput.providerThread);const response = yield* ensureInitialized.pipe(Effect.andThen(@@ -7167,19 +7215,19 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (),);return { feedbackId: response.threadId };- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterProtocolError({- driver: CODEX_PROVIDER,- detail: "Failed to upload Codex thread feedback.",- payload: cause,- }),- ),+ },+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterProtocolError({+ driver: CODEX_PROVIDER,+ detail: "Failed to upload Codex thread feedback.",+ payload: cause,+ }),),+ ),mcpApps,- readThreadSnapshot: (threadInput) =>- Effect.gen(function* () {+ readThreadSnapshot: Effect.fn("CodexAdapterV2.readThreadSnapshot")(+ function* (threadInput) {const threadId = yield* getNativeThreadId(threadInput.providerThread);const response = yield* ensureInitialized.pipe(Effect.andThen(client.request("thread/read", { threadId, includeTurns: true })),@@ -7200,18 +7248,21 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (runtimeRequests: [],providerPayload: response.thread,};- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({- driver: CODEX_PROVIDER,- providerThreadId: threadInput.providerThread.id,- cause,- }),+ },+ (effect, threadInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({+ driver: CODEX_PROVIDER,+ providerThreadId: threadInput.providerThread.id,+ cause,+ }),+ ),),- ),- rollbackThread: (threadInput) =>- Effect.gen(function* () {+ ),+ rollbackThread: Effect.fn("CodexAdapterV2.rollbackThread")(+ function* (threadInput) {const threadId = yield* getNativeThreadId(threadInput.providerThread);const numTurns = yield* resolveCodexRollbackTurnCount(threadInput);const nativeConversationHeadRef =@@ -7275,18 +7326,21 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (runtimeRequests: [],providerPayload: response.thread,};- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterRollbackThreadError({- driver: CODEX_PROVIDER,- providerThreadId: threadInput.providerThread.id,- cause: normalizeCodexCause(cause),- }),+ },+ (effect, threadInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterRollbackThreadError({+ driver: CODEX_PROVIDER,+ providerThreadId: threadInput.providerThread.id,+ cause: normalizeCodexCause(cause),+ }),+ ),),- ),- forkThread: (threadInput) =>- Effect.gen(function* () {+ ),+ forkThread: Effect.fn("CodexAdapterV2.forkThread")(+ function* (threadInput) {const threadId = yield* getNativeThreadId(threadInput.sourceProviderThread);const boundary = yield* resolveCodexForkBoundary(threadInput);const response = yield* ensureInitialized.pipe(@@ -7356,27 +7410,33 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (: { providerTurnId: threadInput.providerTurnId }),},});- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterForkThreadError({- driver: CODEX_PROVIDER,- providerThreadId: threadInput.sourceProviderThread.id,- cause: normalizeCodexCause(cause),- }),+ },+ (effect, threadInput) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterForkThreadError({+ driver: CODEX_PROVIDER,+ providerThreadId: threadInput.sourceProviderThread.id,+ cause: normalizeCodexCause(cause),+ }),+ ),),- ),+ ),};return runtime;- }).pipe(- Effect.mapError(- (cause) =>- new ProviderAdapter.ProviderAdapterOpenSessionError({- driver: CODEX_PROVIDER,- providerSessionId: input.providerSessionId,- cause,- }),+ },+ (effect, input) =>+ effect.pipe(+ Effect.mapError(+ (cause) =>+ new ProviderAdapter.ProviderAdapterOpenSessionError({+ driver: CODEX_PROVIDER,+ providerSessionId: input.providerSessionId,+ cause,+ }),+ ),),- ),+ ),});});diff --git a/apps/server/src/provider/AntigravityAuth.ts b/apps/server/src/provider/AntigravityAuth.tsindex ea1c8f7448c..c97aa949aab 100644--- a/apps/server/src/provider/AntigravityAuth.ts+++ b/apps/server/src/provider/AntigravityAuth.ts@@ -261,8 +261,8 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* <),);- const runSignIn = (flow: AuthFlow, stopSessions: Effect.Effect<void, ProviderSetupError>) =>- Effect.gen(function* () {+ const runSignIn = Effect.fn("AntigravityAuth.runSignIn")(+ function* (flow: AuthFlow, stopSessions: Effect.Effect<void, ProviderSetupError>) {yield* stopSessions.pipe(Effect.ensuring(stopOwnedProcesses));const runtime = yield* options.makeRuntime({onAuthorizationUrl: (url) => receiveAuthorizationUrl(flow, url),@@ -281,16 +281,19 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* <}),);yield* options.onAuthenticated(started, runtime);- }).pipe(- Effect.scoped,- Effect.timeoutOrElse({- duration: AUTH_TIMEOUT_MS,- orElse: () =>- Effect.fail(setupError("start", "Google sign-in expired. Start sign-in again.")),- }),- Effect.exit,- Effect.flatMap((result) => finishFlow(flow, result)),- );+ },+ (effect, flow, stopSessions) =>+ effect.pipe(+ Effect.scoped,+ Effect.timeoutOrElse({+ duration: AUTH_TIMEOUT_MS,+ orElse: () =>+ Effect.fail(setupError("start", "Google sign-in expired. Start sign-in again.")),+ }),+ Effect.exit,+ Effect.flatMap((result) => finishFlow(flow, result)),+ ),+ );const stopFlow = (flow: AuthFlow, phase: "cancelled" | "failed", message: string) =>Effect.uninterruptible(@@ -322,18 +325,21 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* <}),);- const requireFlow = (ownerSessionId: string, flowId: string, name: string) =>- Effect.gen(function* () {- const flow = activeFlow;- if (!flow || flow.id !== flowId || flow.ownerSessionId !== ownerSessionId) {- return yield* setupError(name, "This sign-in is no longer active in this client.");- }- const now = yield* Clock.currentTimeMillis;- if (now >= flow.expiresAtMillis) {- return yield* setupError(name, "Google sign-in expired. Start sign-in again.");- }- return flow;- });+ const requireFlow = Effect.fn("AntigravityAuth.requireFlow")(function* (+ ownerSessionId: string,+ flowId: string,+ name: string,+ ) {+ const flow = activeFlow;+ if (!flow || flow.id !== flowId || flow.ownerSessionId !== ownerSessionId) {+ return yield* setupError(name, "This sign-in is no longer active in this client.");+ }+ const now = yield* Clock.currentTimeMillis;+ if (now >= flow.expiresAtMillis) {+ return yield* setupError(name, "Google sign-in expired. Start sign-in again.");+ }+ return flow;+ });const controller: ProviderAuthController = {start: (ownerSessionId, stopSessions = Effect.void) =>diff --git a/apps/server/src/provider/ClaudeProvider.ts b/apps/server/src/provider/ClaudeProvider.tsindex a30e58f177c..89a13d81c8a 100644--- a/apps/server/src/provider/ClaudeProvider.ts+++ b/apps/server/src/provider/ClaudeProvider.ts@@ -684,11 +684,11 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(const nowIso = Effect.map(DateTime.now, DateTime.formatIso);-export const makePendingClaudeProvider = (- claudeSettings: ClaudeSettings,- modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG,-): Effect.Effect<ServerProviderDraft> =>- Effect.gen(function* () {+export const makePendingClaudeProvider = Effect.fn("ClaudeProvider.makePendingClaudeProvider")(+ function* (+ claudeSettings: ClaudeSettings,+ modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG,+ ): Effect.fn.Return<ServerProviderDraft> {const checkedAt = yield* nowIso;const models = providerModelsFromSettings(modelCatalog.models.map((entry) => entry.model),@@ -725,6 +725,7 @@ export const makePendingClaudeProvider = (message: "Claude provider status has not been checked in this session yet.",},});- });+ },+);export { probeClaudeCapabilities };diff --git a/apps/server/src/provider/CodexChatGptAuth.ts b/apps/server/src/provider/CodexChatGptAuth.tsindex 6a393ace4c6..a9bf5dbac74 100644--- a/apps/server/src/provider/CodexChatGptAuth.ts+++ b/apps/server/src/provider/CodexChatGptAuth.ts@@ -109,49 +109,48 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*}) {const analytics = yield* Effect.serviceOption(AnalyticsService.AnalyticsService);const settings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService);- const track = <A, E extends ProviderSetupError, R>(+ const track = Effect.fn("CodexChatGptAuth.track")(function* <A, E extends ProviderSetupError, R>(event: "auth" | "transfer",properties: Readonly<Record<string, string>>,task: Effect.Effect<A, E, R>,expiresAt?: number,- ) =>- Effect.gen(function* () {- if (Option.isNone(analytics)) return yield* task;- const record = (name: string, properties: Readonly<Record<string, unknown>>) =>- analytics.value.record(name, properties).pipe(Effect.ignoreCause);- const startedAt = yield* Clock.currentTimeMillis;- yield* record(`chatgpt.${event}.started`, properties);- return yield* task.pipe(- Effect.onExit((result) =>- Effect.gen(function* () {- const endedAt = yield* Clock.currentTimeMillis;- const error = Exit.isFailure(result)- ? Cause.findErrorOption(result.cause)- : Option.none();- const counts =- Exit.isSuccess(result) &&- (event === "transfer" || options.telemetryFlow !== "primary_handoff")- ? yield* accountCounts.pipe(Effect.catchCause(() => Effect.succeed({})))- : {};- yield* record(`chatgpt.${event}.completed`, {- ...counts,- ...properties,- outcome: Exit.isSuccess(result)- ? "succeeded"- : Cause.hasInterruptsOnly(result.cause)- ? expiresAt !== undefined && endedAt >= expiresAt- ? "expired"- : "cancelled"- : "failed",- durationMs: Math.max(0, endedAt - startedAt),- ...(Option.isSome(error) && isSetupError(error.value)- ? { failureStage: error.value.operation }- : {}),- });- }),- ),- );- });+ ) {+ if (Option.isNone(analytics)) return yield* task;+ const record = (name: string, properties: Readonly<Record<string, unknown>>) =>+ analytics.value.record(name, properties).pipe(Effect.ignoreCause);+ const startedAt = yield* Clock.currentTimeMillis;+ yield* record(`chatgpt.${event}.started`, properties);+ return yield* task.pipe(+ Effect.onExit((result) =>+ Effect.gen(function* () {+ const endedAt = yield* Clock.currentTimeMillis;+ const error = Exit.isFailure(result)+ ? Cause.findErrorOption(result.cause)+ : Option.none();+ const counts =+ Exit.isSuccess(result) &&+ (event === "transfer" || options.telemetryFlow !== "primary_handoff")+ ? yield* accountCounts.pipe(Effect.catchCause(() => Effect.succeed({})))+ : {};+ yield* record(`chatgpt.${event}.completed`, {+ ...counts,+ ...properties,+ outcome: Exit.isSuccess(result)+ ? "succeeded"+ : Cause.hasInterruptsOnly(result.cause)+ ? expiresAt !== undefined && endedAt >= expiresAt+ ? "expired"+ : "cancelled"+ : "failed",+ durationMs: Math.max(0, endedAt - startedAt),+ ...(Option.isSome(error) && isSetupError(error.value)+ ? { failureStage: error.value.operation }+ : {}),+ });+ }),+ ),+ );+ });const http = yield* HttpClient.HttpClient;const store = yield* ProviderCredentialStore.make("codex-chatgpt", options.instanceId);const registrationStore = yield* ProviderCredentialStore.make(diff --git a/apps/server/src/provider/CodexProvider.ts b/apps/server/src/provider/CodexProvider.tsindex 33a0ce8edad..1cdec303ebf 100644--- a/apps/server/src/provider/CodexProvider.ts+++ b/apps/server/src/provider/CodexProvider.ts@@ -543,33 +543,16 @@ export const probeCodexSkillsForCwd = Effect.fn("probeCodexSkillsForCwd")(functiconst emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>appendCustomCodexModels([], codexSettings.customModels);-const makePendingCodexProvider = (+const makePendingCodexProvider = Effect.fn("CodexProvider.makePendingCodexProvider")(function* (codexSettings: CodexSettings,-): Effect.Effect<ServerProviderDraft> =>- Effect.gen(function* () {- const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);- const models = emptyCodexModelsFromSettings(codexSettings);-- if (!codexSettings.enabled) {- return buildServerProvider({- presentation: CODEX_PRESENTATION,- enabled: false,- checkedAt,- models,- skills: [],- probe: {- installed: false,- version: null,- status: "warning",- auth: { status: "unknown" },- message: "Codex is disabled in T3 Code settings.",- },- });- }+): Effect.fn.Return<ServerProviderDraft> {+ const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);+ const models = emptyCodexModelsFromSettings(codexSettings);+ if (!codexSettings.enabled) {return buildServerProvider({presentation: CODEX_PRESENTATION,- enabled: true,+ enabled: false,checkedAt,models,skills: [],@@ -578,10 +561,26 @@ const makePendingCodexProvider = (version: null,status: "warning",auth: { status: "unknown" },- message: "Codex provider status has not been checked in this session yet.",+ message: "Codex is disabled in T3 Code settings.",},});+ }++ return buildServerProvider({+ presentation: CODEX_PRESENTATION,+ enabled: true,+ checkedAt,+ models,+ skills: [],+ probe: {+ installed: false,+ version: null,+ status: "warning",+ auth: { status: "unknown" },+ message: "Codex provider status has not been checked in this session yet.",+ },});+});function accountProbeStatus({ account, rateLimits }: CodexAppServerProviderSnapshot): {readonly status: Exclude<ServerProviderState, "disabled">;diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.tsindex 7a77aa6beb1..0f42271c62d 100644--- a/apps/server/src/provider/Drivers/AntigravityDriver.ts+++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts@@ -93,435 +93,436 @@ export const AntigravityDriver: ProviderDriver<configSchema: AntigravitySettings,defaultConfig: () => decodeSettings({}),usage: AntigravityUsage.antigravityUsageReader,- create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>- Effect.gen(function* () {- const crypto = yield* Crypto.Crypto;- const fileSystem = yield* FileSystem.FileSystem;- const httpClient = yield* HttpClient.HttpClient;- const path = yield* Path.Path;- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;- const host = yield* ProviderHost.ProviderHost;- const selfInvocation = yield* resolveSelfInvocation();- const installation = yield* AntigravityInstallation.AntigravityInstallation;- const loggers = yield* ProviderEventLoggers.ProviderEventLoggers;- const modelCatalog = yield* ModelCatalog.ModelCatalog;- const currentCatalog = modelCatalog.current(DRIVER);- const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;- const makeNativeLogger = yield* makeAcpNativeLoggerFactory();- const settings = { ...config, enabled } satisfies AntigravitySettings;- const auth: AntigravityAuthConfig = {- authMethod: settings.authMethod,- apiKey: settings.apiKey,- gcpProject: settings.gcpProject,- gcpLocation: settings.gcpLocation,- };- const authConfigIssue = antigravityAuthConfigIssue(auth);- const processEnvironment = yield* mergeProviderInstanceEnvironment(environment);- const userHome = resolveAntigravityUserHome(- yield* HostProcess.Platform,- processEnvironment,- yield* HostProcess.HomeDirectory,+ create: Effect.fn("AntigravityDriver.create")(function* ({+ instanceId,+ displayName,+ accentColor,+ environment,+ enabled,+ config,+ }) {+ const crypto = yield* Crypto.Crypto;+ const fileSystem = yield* FileSystem.FileSystem;+ const httpClient = yield* HttpClient.HttpClient;+ const path = yield* Path.Path;+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const host = yield* ProviderHost.ProviderHost;+ const selfInvocation = yield* resolveSelfInvocation();+ const installation = yield* AntigravityInstallation.AntigravityInstallation;+ const loggers = yield* ProviderEventLoggers.ProviderEventLoggers;+ const modelCatalog = yield* ModelCatalog.ModelCatalog;+ const currentCatalog = modelCatalog.current(DRIVER);+ const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;+ const makeNativeLogger = yield* makeAcpNativeLoggerFactory();+ const settings = { ...config, enabled } satisfies AntigravitySettings;+ const auth: AntigravityAuthConfig = {+ authMethod: settings.authMethod,+ apiKey: settings.apiKey,+ gcpProject: settings.gcpProject,+ gcpLocation: settings.gcpLocation,+ };+ const authConfigIssue = antigravityAuthConfigIssue(auth);+ const processEnvironment = yield* mergeProviderInstanceEnvironment(environment);+ const userHome = resolveAntigravityUserHome(+ yield* HostProcess.Platform,+ processEnvironment,+ yield* HostProcess.HomeDirectory,+ );+ const directories = yield* resolveAntigravityInstanceDirectories(+ host.paths.stateDir,+ instanceId,+ ).pipe(+ Effect.provideService(Crypto.Crypto, crypto),+ Effect.provideService(Path.Path, path),+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER,+ instanceId,+ detail: "Could not resolve the Antigravity profile directory.",+ cause,+ }),+ ),+ );+ const profileDirectory = directories.profile;+ for (const directory of [+ directories.runtimeTemp,+ path.join(profileDirectory, "antigravity-acp", "tmp"),+ ]) {+ yield* removeAntigravityRuntimeTempDirs(directory).pipe(+ Effect.provideService(FileSystem.FileSystem, fileSystem),);- const directories = yield* resolveAntigravityInstanceDirectories(- host.paths.stateDir,- instanceId,- ).pipe(- Effect.provideService(Crypto.Crypto, crypto),- Effect.provideService(Path.Path, path),+ }+ const continuationIdentity = defaultProviderContinuationIdentity({+ driverKind: DRIVER,+ instanceId,+ });+ const stampIdentity = withInstanceIdentity({+ instanceId,+ driverKind: DRIVER,+ displayName,+ accentColor,+ continuationGroupKey: continuationIdentity.continuationKey,+ });+ const classifyModels = (draft: ServerProviderDraft) =>+ currentCatalog.pipe(+ Effect.map((catalog) => stampIdentity(ModelCatalog.applyModelCatalog(draft, catalog))),+ );++ const makeRuntime = Effect.fn("AntigravityDriver.makeRuntime")(function* (+ input: Omit<AntigravityAcpRuntimeInput, "spawn" | "childProcessSpawner">,+ ): Effect.fn.Return<+ AcpSessionRuntime.AcpSessionRuntime["Service"],+ AcpError | ProviderSetupError,+ Scope.Scope+ > {+ if (authConfigIssue !== null) {+ return yield* new ProviderSetupError({+ instanceId,+ operation: "configure",+ detail: authConfigIssue,+ });+ }+ const executable = yield* installation.acquire(settings.binaryPath, processEnvironment).pipe(Effect.mapError((cause) =>- new ProviderDriverError({- driver: DRIVER,+ new ProviderSetupError({instanceId,- detail: "Could not resolve the Antigravity profile directory.",+ operation: "resolve",+ detail: cause.detail,cause,}),),);- const profileDirectory = directories.profile;- for (const directory of [- directories.runtimeTemp,- path.join(profileDirectory, "antigravity-acp", "tmp"),- ]) {- yield* removeAntigravityRuntimeTempDirs(directory).pipe(- Effect.provideService(FileSystem.FileSystem, fileSystem),- );- }- const continuationIdentity = defaultProviderContinuationIdentity({- driverKind: DRIVER,- instanceId,- });- const stampIdentity = withInstanceIdentity({- instanceId,- driverKind: DRIVER,- displayName,- accentColor,- continuationGroupKey: continuationIdentity.continuationKey,- });- const classifyModels = (draft: ServerProviderDraft) =>- currentCatalog.pipe(- Effect.map((catalog) => stampIdentity(ModelCatalog.applyModelCatalog(draft, catalog))),- );-- const makeRuntime = Effect.fn("AntigravityDriver.makeRuntime")(function* (- input: Omit<AntigravityAcpRuntimeInput, "spawn" | "childProcessSpawner">,- ): Effect.fn.Return<- AcpSessionRuntime.AcpSessionRuntime["Service"],- AcpError | ProviderSetupError,- Scope.Scope- > {- if (authConfigIssue !== null) {- return yield* new ProviderSetupError({- instanceId,- operation: "configure",- detail: authConfigIssue,- });- }- const executable = yield* installation- .acquire(settings.binaryPath, processEnvironment)- .pipe(- Effect.mapError(- (cause) =>- new ProviderSetupError({- instanceId,- operation: "resolve",- detail: cause.detail,- cause,- }),- ),- );- const profile = yield* prepareAntigravityProfile({- profileDirectory,- baseEnv: processEnvironment,- auth,- userHome,- tempDirectory: directories.runtimeTemp,- }).pipe(- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, path),- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- Effect.mapError((cause) =>- isNodeRuntimeUnavailableError(cause.cause)- ? new ProviderSetupError({- instanceId,- operation: "start",- detail: nodeRuntimeUnavailableMessage("Antigravity sign-in"),- cause,- })- : cause,- ),- );- // Each process unpacks into its own directory that dies with the- // runtime scope, after the child is killed. A shared directory would- // let one session's teardown delete files a sibling still reads.- // Removal is best effort: a handle can outlive the kill on Windows,- // and the sweep on the next driver start reclaims what is left.- const runtimeTempDirectory = yield* Effect.acquireRelease(- fileSystem.makeTempDirectory({ directory: profile.tempDirectory, prefix: "run-" }).pipe(- Effect.mapError(- (cause) =>- new ProviderSetupError({- instanceId,- operation: "start",- detail: "Could not create an Antigravity runtime temp directory.",- cause,- }),- ),+ const profile = yield* prepareAntigravityProfile({+ profileDirectory,+ baseEnv: processEnvironment,+ auth,+ userHome,+ tempDirectory: directories.runtimeTemp,+ }).pipe(+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.mapError((cause) =>+ isNodeRuntimeUnavailableError(cause.cause)+ ? new ProviderSetupError({+ instanceId,+ operation: "start",+ detail: nodeRuntimeUnavailableMessage("Antigravity sign-in"),+ cause,+ })+ : cause,+ ),+ );+ // Each process unpacks into its own directory that dies with the+ // runtime scope, after the child is killed. A shared directory would+ // let one session's teardown delete files a sibling still reads.+ // Removal is best effort: a handle can outlive the kill on Windows,+ // and the sweep on the next driver start reclaims what is left.+ const runtimeTempDirectory = yield* Effect.acquireRelease(+ fileSystem.makeTempDirectory({ directory: profile.tempDirectory, prefix: "run-" }).pipe(+ Effect.mapError(+ (cause) =>+ new ProviderSetupError({+ instanceId,+ operation: "start",+ detail: "Could not create an Antigravity runtime temp directory.",+ cause,+ }),),- (directory) =>- fileSystem- .remove(directory, { recursive: true, force: true })- .pipe(- Effect.catch(() =>- Effect.logWarning("Could not remove an Antigravity runtime temp directory."),- ),+ ),+ (directory) =>+ fileSystem+ .remove(directory, { recursive: true, force: true })+ .pipe(+ Effect.catch(() =>+ Effect.logWarning("Could not remove an Antigravity runtime temp directory."),),- );- const runtime = yield* makeAntigravityAcpRuntime({- ...input,- authMethod: auth.authMethod,- childProcessSpawner: spawner,- spawn: buildAntigravityAcpSpawnInput({- installation: executable,- profile,- cwd: input.cwd,- baseEnv: withAgentDeviceEnvironment(processEnvironment, input),- auth,- runtimeTempDirectory,- }),- }).pipe(Effect.provideService(Crypto.Crypto, crypto));- return {- ...runtime,- start: () =>- runtime- .start()- .pipe(- Effect.tapError((cause): Effect.Effect<void> =>- input.onAuthorizationUrl === undefined && isAntigravitySignInRequiredError(cause)- ? provider.onAuthRequired- : Effect.void,- ),+ ),+ );+ const runtime = yield* makeAntigravityAcpRuntime({+ ...input,+ authMethod: auth.authMethod,+ childProcessSpawner: spawner,+ spawn: buildAntigravityAcpSpawnInput({+ installation: executable,+ profile,+ cwd: input.cwd,+ baseEnv: withAgentDeviceEnvironment(processEnvironment, input),+ auth,+ runtimeTempDirectory,+ }),+ }).pipe(Effect.provideService(Crypto.Crypto, crypto));+ return {+ ...runtime,+ start: () =>+ runtime+ .start()+ .pipe(+ Effect.tapError((cause): Effect.Effect<void> =>+ input.onAuthorizationUrl === undefined && isAntigravitySignInRequiredError(cause)+ ? provider.onAuthRequired+ : Effect.void,),- };- });-- const makeDisposableRuntime = Effect.fn("AntigravityDriver.makeDisposableRuntime")(function* (- input: Pick<AntigravityAcpRuntimeInput, "onAuthorizationUrl">,- ) {- const cwd = yield* fileSystem- .makeTempDirectoryScoped({ prefix: "t3-antigravity-setup-" })- .pipe(- Effect.mapError(- () =>- new ProviderSetupError({- instanceId,- operation: "start",- detail: "Could not create an Antigravity setup workspace.",- }),),- );- let sessionId: string | undefined;- yield* Effect.addFinalizer(() =>- removeAntigravitySessionFiles({- profileDirectory,- sessionId,- cwd,- }).pipe(- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, path),+ };+ });++ const makeDisposableRuntime = Effect.fn("AntigravityDriver.makeDisposableRuntime")(function* (+ input: Pick<AntigravityAcpRuntimeInput, "onAuthorizationUrl">,+ ) {+ const cwd = yield* fileSystem+ .makeTempDirectoryScoped({ prefix: "t3-antigravity-setup-" })+ .pipe(+ Effect.mapError(+ () =>+ new ProviderSetupError({+ instanceId,+ operation: "start",+ detail: "Could not create an Antigravity setup workspace.",+ }),),);- const runtime = yield* makeRuntime({+ let sessionId: string | undefined;+ yield* Effect.addFinalizer(() =>+ removeAntigravitySessionFiles({+ profileDirectory,+ sessionId,cwd,- clientInfo: { name: "t3-code-provider-setup", version: "0.0.0" },- mcpServers: [],- ...(input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {}),- });- return {- ...runtime,- start: () =>- runtime.start().pipe(- Effect.tap((started) =>- Effect.sync(() => {- sessionId = started.sessionId;- }),- ),- ),- };- });-- const publishCatalog = (- started: AcpSessionRuntime.AcpSessionRuntimeStartResult,- runtime: Pick<AcpSessionRuntime.AcpSessionRuntime["Service"], "getEvents" | "drainEvents">,- ): Effect.Effect<void> =>- Effect.gen(function* () {- yield* provider.onSessionStarted(started);- yield* Stream.runForEach(runtime.getEvents(), (event) => {- if (event._tag === "EventStreamBarrier") {- return Deferred.succeed(event.acknowledge, undefined).pipe(Effect.asVoid);- }- if (event._tag === "ConfigOptionsUpdated") {- return provider.onConfigOptionsUpdated(event.configOptions);- }- return event._tag === "AvailableCommandsUpdated"- ? provider.onAvailableCommands(event.availableCommands)- : Effect.void;- }).pipe(Effect.forkScoped);- yield* runtime.drainEvents;- }).pipe(Effect.scoped);-- const authFlow: AntigravityAuth = yield* makeAntigravityAuth({- instanceId,- makeRuntime: makeDisposableRuntime,- onAuthenticated: publishCatalog,- onSignedOut: Effect.suspend(() => provider.onSignedOut),- usesBrowser: antigravityAuthUsesBrowser(auth.authMethod),+ }).pipe(+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ ),+ );+ const runtime = yield* makeRuntime({+ cwd,+ clientInfo: { name: "t3-code-provider-setup", version: "0.0.0" },+ mcpServers: [],+ ...(input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {}),});+ return {+ ...runtime,+ start: () =>+ runtime.start().pipe(+ Effect.tap((started) =>+ Effect.sync(() => {+ sessionId = started.sessionId;+ }),+ ),+ ),+ };+ });- // The probe must not spawn. The agent is a PyInstaller one-file bundle- // that unpacks about 1 GB per launch, and the health check runs every- // minute.- const probe = Effect.gen(function* () {- yield* modelCatalog.refreshInBackground;- if (authConfigIssue !== null) {- return yield* new ProviderSetupError({- instanceId,- operation: "configure",- detail: authConfigIssue,- });+ const publishCatalog = Effect.fn("AntigravityDriver.publishCatalog")(function* (+ started: AcpSessionRuntime.AcpSessionRuntimeStartResult,+ runtime: Pick<AcpSessionRuntime.AcpSessionRuntime["Service"], "getEvents" | "drainEvents">,+ ) {+ yield* provider.onSessionStarted(started);+ yield* Stream.runForEach(runtime.getEvents(), (event) => {+ if (event._tag === "EventStreamBarrier") {+ return Deferred.succeed(event.acknowledge, undefined).pipe(Effect.asVoid);}- const executable = yield* installation- .resolve(settings.binaryPath, processEnvironment)- .pipe(- Effect.mapError(- (cause) =>- new ProviderSetupError({- instanceId,- operation: "resolve",- detail: cause.detail,- cause,- }),- ),- );- return {- protocolVersion: 1,- agentCapabilities: {- loadSession: true,- promptCapabilities: { image: true, audio: true, embeddedContext: true },- sessionCapabilities: { list: {}, resume: {} },- },- authMethods: [{ id: "oauth-personal", name: "Log in with Google" }],- agentInfo: {- name: "antigravity-acp",- title: "Google Antigravity",- version: executable.version ?? "unknown",- },- };- });+ if (event._tag === "ConfigOptionsUpdated") {+ return provider.onConfigOptionsUpdated(event.configOptions);+ }+ return event._tag === "AvailableCommandsUpdated"+ ? provider.onAvailableCommands(event.availableCommands)+ : Effect.void;+ }).pipe(Effect.forkScoped);+ yield* runtime.drainEvents;+ }, Effect.scoped);- const usage = yield* makeAntigravityUsageProbe({- profileDirectory,- authMethod: auth.authMethod,- }).pipe(- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, path),- Effect.provideService(Crypto.Crypto, crypto),- Effect.provideService(HttpClient.HttpClient, httpClient),- );- const provider = yield* makeAntigravityProvider(settings, {- stampIdentity: classifyModels,- probe,- probeUsage: usage.probe,- clearUsage: usage.clear,- auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) },- supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe(- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, path),- Effect.orElseSucceed(() => false),- ),- }).pipe(+ const authFlow: AntigravityAuth = yield* makeAntigravityAuth({+ instanceId,+ makeRuntime: makeDisposableRuntime,+ onAuthenticated: publishCatalog,+ onSignedOut: Effect.suspend(() => provider.onSignedOut),+ usesBrowser: antigravityAuthUsesBrowser(auth.authMethod),+ });++ // The probe must not spawn. The agent is a PyInstaller one-file bundle+ // that unpacks about 1 GB per launch, and the health check runs every+ // minute.+ const probe = Effect.gen(function* () {+ yield* modelCatalog.refreshInBackground;+ if (authConfigIssue !== null) {+ return yield* new ProviderSetupError({+ instanceId,+ operation: "configure",+ detail: authConfigIssue,+ });+ }+ const executable = yield* installation.resolve(settings.binaryPath, processEnvironment).pipe(Effect.mapError((cause) =>- new ProviderDriverError({- driver: DRIVER,+ new ProviderSetupError({instanceId,- detail: "Could not prepare the Antigravity provider status.",+ operation: "resolve",+ detail: cause.detail,cause,}),),);- const defaultModel = currentCatalog.pipe(Effect.map((catalog) => catalog?.defaultChatModel));- const orchestrationAdapter = yield* makeAntigravityAdapterV2({- instanceId,- selfInvocation,- makeRuntime,- withProcess: authFlow.withProcess,- defaultModel,- onSessionStarted: provider.onSessionStarted,- onSessionEvent: (event) => {- if (event._tag === "ConfigOptionsUpdated") {- return provider.onConfigOptionsUpdated(event.configOptions);- }- return event._tag === "AvailableCommandsUpdated"- ? provider.onAvailableCommands(event.availableCommands)- : Effect.void;+ return {+ protocolVersion: 1,+ agentCapabilities: {+ loadSession: true,+ promptCapabilities: { image: true, audio: true, embeddedContext: true },+ sessionCapabilities: { list: {}, resume: {} },},- continuationRequests,- nativeLogging: (threadId) =>- makeNativeLogger({- nativeEventLogger: loggers.native,- provider: DRIVER,- threadId,- }),- });- const textGeneration = yield* makeAntigravityTextGeneration({- profileDirectory,- defaultModel,- withProcess: authFlow.withProcess,- makeRuntime: (cwd) =>- makeRuntime({- cwd,- clientInfo: { name: "t3-code-text", version: "0.0.0" },- mcpServers: [],- }),- });-- const refreshModels = Effect.fn("AntigravityDriver.refreshModels")(- function* () {- const processScope = yield* Scope.make();- yield* Effect.addFinalizer((exit) => Scope.close(processScope, exit));- yield* authFlow- .withProcess(- Scope.close(processScope, Exit.void),- Effect.gen(function* () {- const runtime = yield* makeDisposableRuntime({});- const started = yield* runtime.start();- yield* publishCatalog(started, runtime);- }),- )- .pipe(Effect.provideService(Scope.Scope, processScope));+ authMethods: [{ id: "oauth-personal", name: "Log in with Google" }],+ agentInfo: {+ name: "antigravity-acp",+ title: "Google Antigravity",+ version: executable.version ?? "unknown",},- Effect.scoped,- Effect.timeoutOrElse({- duration: "90 seconds",- orElse: () =>- Effect.fail(- new ProviderDriverError({- driver: DRIVER,- instanceId,- detail: "Antigravity model refresh timed out. Try again or check Google sign-in.",- }),- ),+ };+ });++ const usage = yield* makeAntigravityUsageProbe({+ profileDirectory,+ authMethod: auth.authMethod,+ }).pipe(+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ Effect.provideService(Crypto.Crypto, crypto),+ Effect.provideService(HttpClient.HttpClient, httpClient),+ );+ const provider = yield* makeAntigravityProvider(settings, {+ stampIdentity: classifyModels,+ probe,+ probeUsage: usage.probe,+ clearUsage: usage.clear,+ auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) },+ supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe(+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ Effect.orElseSucceed(() => false),+ ),+ }).pipe(+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER,+ instanceId,+ detail: "Could not prepare the Antigravity provider status.",+ cause,+ }),+ ),+ );+ const defaultModel = currentCatalog.pipe(Effect.map((catalog) => catalog?.defaultChatModel));+ const orchestrationAdapter = yield* makeAntigravityAdapterV2({+ instanceId,+ selfInvocation,+ makeRuntime,+ withProcess: authFlow.withProcess,+ defaultModel,+ onSessionStarted: provider.onSessionStarted,+ onSessionEvent: (event) => {+ if (event._tag === "ConfigOptionsUpdated") {+ return provider.onConfigOptionsUpdated(event.configOptions);+ }+ return event._tag === "AvailableCommandsUpdated"+ ? provider.onAvailableCommands(event.availableCommands)+ : Effect.void;+ },+ continuationRequests,+ nativeLogging: (threadId) =>+ makeNativeLogger({+ nativeEventLogger: loggers.native,+ provider: DRIVER,+ threadId,}),- Effect.tapError((cause) =>- isAntigravitySignInRequiredError(cause) ? provider.onAuthRequired : Effect.void,- ),- Effect.mapError((cause) =>- cause._tag === "ProviderDriverError"- ? cause- : new ProviderDriverError({- driver: DRIVER,- instanceId,- detail: isAntigravitySignInRequiredError(cause)- ? "Sign in to Antigravity in provider settings before refreshing models."- : cause._tag === "ProviderSetupError" &&- (cause.operation === "configure" || cause.operation === "start")- ? cause.detail- : "Could not refresh Antigravity models. The previous model list is unchanged.",- cause,- }),- ),- );+ });+ const textGeneration = yield* makeAntigravityTextGeneration({+ profileDirectory,+ defaultModel,+ withProcess: authFlow.withProcess,+ makeRuntime: (cwd) =>+ makeRuntime({+ cwd,+ clientInfo: { name: "t3-code-text", version: "0.0.0" },+ mcpServers: [],+ }),+ });- return {- instanceId,- driverKind: DRIVER,- continuationIdentity,- displayName,- accentColor,- enabled,- snapshot: provider.snapshot,- snapshotForCwd: (cwd) =>- !enabled- ? provider.snapshot.getSnapshot- : discoverAntigravitySkills({ cwd, userHome }).pipe(- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, path),- Effect.flatMap((skills) => provider.snapshotForCwd(cwd, skills)),- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER,- instanceId,- detail: "Could not read Antigravity workspace skills.",- cause,- }),- ),+ const refreshModels = Effect.fn("AntigravityDriver.refreshModels")(+ function* () {+ const processScope = yield* Scope.make();+ yield* Effect.addFinalizer((exit) => Scope.close(processScope, exit));+ yield* authFlow+ .withProcess(+ Scope.close(processScope, Exit.void),+ Effect.gen(function* () {+ const runtime = yield* makeDisposableRuntime({});+ const started = yield* runtime.start();+ yield* publishCatalog(started, runtime);+ }),+ )+ .pipe(Effect.provideService(Scope.Scope, processScope));+ },+ Effect.scoped,+ Effect.timeoutOrElse({+ duration: "90 seconds",+ orElse: () =>+ Effect.fail(+ new ProviderDriverError({+ driver: DRIVER,+ instanceId,+ detail: "Antigravity model refresh timed out. Try again or check Google sign-in.",+ }),+ ),+ }),+ Effect.tapError((cause) =>+ isAntigravitySignInRequiredError(cause) ? provider.onAuthRequired : Effect.void,+ ),+ Effect.mapError((cause) =>+ cause._tag === "ProviderDriverError"+ ? cause+ : new ProviderDriverError({+ driver: DRIVER,+ instanceId,+ detail: isAntigravitySignInRequiredError(cause)+ ? "Sign in to Antigravity in provider settings before refreshing models."+ : cause._tag === "ProviderSetupError" &&+ (cause.operation === "configure" || cause.operation === "start")+ ? cause.detail+ : "Could not refresh Antigravity models. The previous model list is unchanged.",+ cause,+ }),+ ),+ );++ return {+ instanceId,+ driverKind: DRIVER,+ continuationIdentity,+ displayName,+ accentColor,+ enabled,+ snapshot: provider.snapshot,+ snapshotForCwd: (cwd) =>+ !enabled+ ? provider.snapshot.getSnapshot+ : discoverAntigravitySkills({ cwd, userHome }).pipe(+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ Effect.flatMap((skills) => provider.snapshotForCwd(cwd, skills)),+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER,+ instanceId,+ detail: "Could not read Antigravity workspace skills.",+ cause,+ }),),- orchestrationAdapter,- textGeneration,- auth: authFlow.controller,- refreshModels,- } satisfies ProviderInstance;- }),+ ),+ orchestrationAdapter,+ textGeneration,+ auth: authFlow.controller,+ refreshModels,+ } satisfies ProviderInstance;+ }),};diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.tsindex 4e5fe8e1048..176c7332fb4 100644--- a/apps/server/src/provider/Drivers/ClaudeDriver.ts+++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts@@ -113,288 +113,293 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.configSchema: ClaudeSettings,defaultConfig: (): ClaudeSettings => decodeClaudeSettings({}),usage: claudeUsageReader,- create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>- Effect.gen(function* () {- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;- const fileSystem = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- // The server cwd is $HOME in packaged desktop builds, and `claude`- // wrappers that scope themselves to their cwd refuse to run there.- const { stateDir } = yield* ServerConfig.ServerConfig;- const httpClient = yield* HttpClient.HttpClient;- const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;- const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator;- const catalogService = yield* ModelCatalog.ModelCatalog;- const modelCatalog = catalogService- .current(DRIVER_KIND)- .pipe(Effect.map(resolveClaudeModelCatalog));- const processEnv = yield* mergeProviderInstanceEnvironment(environment);- const fallbackContinuationIdentity = defaultProviderContinuationIdentity({- driverKind: DRIVER_KIND,- instanceId,- });- const effectiveConfig = {- ...config,- enabled,- binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),- } satisfies ClaudeSettings;- const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(- resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {- binaryPath: effectiveConfig.binaryPath,- env: processEnv,- }).pipe(- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, path),- ),- );- const continuationGroupKey = yield* makeClaudeContinuationGroupKey(- effectiveConfig,- processEnv,- );- const configDir = yield* resolveClaudeHomePath(effectiveConfig, processEnv);- const accountConfigPath = yield* ClaudeResetCredits.claudeAccountConfigPath(- effectiveConfig.homePath.trim() || processEnv.CLAUDE_CONFIG_DIR?.trim()- ? configDir- : undefined,- );- const stampIdentity = withInstanceIdentity({+ create: Effect.fn("ClaudeDriver.create")(function* ({+ instanceId,+ displayName,+ accentColor,+ environment,+ enabled,+ config,+ }) {+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const fileSystem = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ // The server cwd is $HOME in packaged desktop builds, and `claude`+ // wrappers that scope themselves to their cwd refuse to run there.+ const { stateDir } = yield* ServerConfig.ServerConfig;+ const httpClient = yield* HttpClient.HttpClient;+ const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;+ const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator;+ const catalogService = yield* ModelCatalog.ModelCatalog;+ const modelCatalog = catalogService+ .current(DRIVER_KIND)+ .pipe(Effect.map(resolveClaudeModelCatalog));+ const processEnv = yield* mergeProviderInstanceEnvironment(environment);+ const fallbackContinuationIdentity = defaultProviderContinuationIdentity({+ driverKind: DRIVER_KIND,+ instanceId,+ });+ const effectiveConfig = {+ ...config,+ enabled,+ binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),+ } satisfies ClaudeSettings;+ const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(+ resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {+ binaryPath: effectiveConfig.binaryPath,+ env: processEnv,+ }).pipe(+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ ),+ );+ const continuationGroupKey = yield* makeClaudeContinuationGroupKey(effectiveConfig, processEnv);+ const configDir = yield* resolveClaudeHomePath(effectiveConfig, processEnv);+ const accountConfigPath = yield* ClaudeResetCredits.claudeAccountConfigPath(+ effectiveConfig.homePath.trim() || processEnv.CLAUDE_CONFIG_DIR?.trim()+ ? configDir+ : undefined,+ );+ const stampIdentity = withInstanceIdentity({+ instanceId,+ driverKind: DRIVER_KIND,+ displayName,+ accentColor,+ continuationGroupKey,+ });++ const scopedLimitNames = yield* makeClaudeScopedLimitNames;+ const orchestrationAdapter = yield* createClaudeAdapterV2(+ {instanceId,- driverKind: DRIVER_KIND,displayName,accentColor,- continuationGroupKey,- });-- const scopedLimitNames = yield* makeClaudeScopedLimitNames;- const orchestrationAdapter = yield* createClaudeAdapterV2(- {- instanceId,- displayName,- accentColor,- environment,- enabled,- config,- },- { scopedLimitNames, onUsageLimits: (update) => snapshot.applyUsageLimits(update) },- ).pipe(- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: "Failed to build Claude orchestration adapter.",- cause,- }),- ),- );- const textGeneration = yield* makeClaudeTextGeneration(- effectiveConfig,- processEnv,- modelCatalog,- );+ environment,+ enabled,+ config,+ },+ { scopedLimitNames, onUsageLimits: (update) => snapshot.applyUsageLimits(update) },+ ).pipe(+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: "Failed to build Claude orchestration adapter.",+ cause,+ }),+ ),+ );+ const textGeneration = yield* makeClaudeTextGeneration(+ effectiveConfig,+ processEnv,+ modelCatalog,+ );- // Per-instance capabilities cache: keyed on binary + resolved HOME so- // account-specific probes never share auth metadata across instances.- // A transient miss may reuse the last account once, but its usage windows keep their age.- const lastGoodCapabilities = yield* Ref.make<ClaudeCapabilitiesProbe | undefined>(undefined);- const capabilitiesProbeCache = yield* Cache.makeWith(- () =>- probeClaudeCapabilities(effectiveConfig, processEnv, stateDir).pipe(- Effect.flatMap((capabilities) =>- ClaudeResetCredits.readClaudeOrganizationId(accountConfigPath).pipe(- Effect.map((workspaceId) => ({- _tag: "fresh" as const,- capabilities:- workspaceId === undefined ? capabilities : { ...capabilities, workspaceId },- })),- ),+ // Per-instance capabilities cache: keyed on binary + resolved HOME so+ // account-specific probes never share auth metadata across instances.+ // A transient miss may reuse the last account once, but its usage windows keep their age.+ const lastGoodCapabilities = yield* Ref.make<ClaudeCapabilitiesProbe | undefined>(undefined);+ const capabilitiesProbeCache = yield* Cache.makeWith(+ () =>+ probeClaudeCapabilities(effectiveConfig, processEnv, stateDir).pipe(+ Effect.flatMap((capabilities) =>+ ClaudeResetCredits.readClaudeOrganizationId(accountConfigPath).pipe(+ Effect.map((workspaceId) => ({+ _tag: "fresh" as const,+ capabilities:+ workspaceId === undefined ? capabilities : { ...capabilities, workspaceId },+ })),),- Effect.tap(({ capabilities }) => Ref.set(lastGoodCapabilities, capabilities)),- Effect.catch((error) =>- Ref.getAndSet(lastGoodCapabilities, undefined).pipe(- Effect.flatMap((capabilities) =>- capabilities === undefined- ? Effect.fail(error)- : ClaudeResetCredits.readClaudeOrganizationId(accountConfigPath).pipe(- Effect.flatMap((workspaceId) =>- workspaceId === capabilities.workspaceId- ? Effect.succeed({- _tag: "fallback" as const,- capabilities: withoutUsage(capabilities),- })- : Effect.fail(error),- ),+ ),+ Effect.tap(({ capabilities }) => Ref.set(lastGoodCapabilities, capabilities)),+ Effect.catch((error) =>+ Ref.getAndSet(lastGoodCapabilities, undefined).pipe(+ Effect.flatMap((capabilities) =>+ capabilities === undefined+ ? Effect.fail(error)+ : ClaudeResetCredits.readClaudeOrganizationId(accountConfigPath).pipe(+ Effect.flatMap((workspaceId) =>+ workspaceId === capabilities.workspaceId+ ? Effect.succeed({+ _tag: "fallback" as const,+ capabilities: withoutUsage(capabilities),+ })+ : Effect.fail(error),),- ),+ ),),),- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, path),),- {- capacity: 1,- timeToLive: (exit) =>- // Only a fresh probe earns the TTL; a failure or its fallback retries on the next check.- Exit.isSuccess(exit) && exit.value._tag === "fresh"- ? CAPABILITIES_PROBE_TTL- : Duration.zero,- },- );- const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(- effectiveConfig,- stateDir,- processEnv,- );- const resolveCapabilities = Cache.get(capabilitiesProbeCache, capabilitiesCacheKey).pipe(- Effect.map((result) => result.capabilities),- );+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ ),+ {+ capacity: 1,+ timeToLive: (exit) =>+ // Only a fresh probe earns the TTL; a failure or its fallback retries on the next check.+ Exit.isSuccess(exit) && exit.value._tag === "fresh"+ ? CAPABILITIES_PROBE_TTL+ : Duration.zero,+ },+ );+ const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(+ effectiveConfig,+ stateDir,+ processEnv,+ );+ const resolveCapabilities = Cache.get(capabilitiesProbeCache, capabilitiesCacheKey).pipe(+ Effect.map((result) => result.capabilities),+ );- const checkProvider = catalogService.refreshInBackground.pipe(- Effect.andThen(- modelCatalog.pipe(- Effect.flatMap((catalog) =>- checkClaudeProviderStatus(- effectiveConfig,- () => resolveCapabilities,- processEnv,- stateDir,- catalog,- scopedLimitNames,- (version) =>- ClaudeResetCredits.readClaudeResetCredits(configDir, version).pipe(- Effect.provideService(HttpClient.HttpClient, httpClient),- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, path),- ),- ),+ const checkProvider = catalogService.refreshInBackground.pipe(+ Effect.andThen(+ modelCatalog.pipe(+ Effect.flatMap((catalog) =>+ checkClaudeProviderStatus(+ effectiveConfig,+ () => resolveCapabilities,+ processEnv,+ stateDir,+ catalog,+ scopedLimitNames,+ (version) =>+ ClaudeResetCredits.readClaudeResetCredits(configDir, version).pipe(+ Effect.provideService(HttpClient.HttpClient, httpClient),+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ ),),- Effect.map(stampIdentity),),+ Effect.map(stampIdentity),),- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, path),- );+ ),+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ );- const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);- const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<ClaudeSettings>>({- resolveMaintenance,- getSettings: snapshotSettings.getSettings,- streamSettings: snapshotSettings.streamSettings,- haveSettingsChanged: haveProviderSnapshotSettingsChanged,- initialSnapshot: (settings) =>- modelCatalog.pipe(- Effect.flatMap((catalog) => makePendingClaudeProvider(settings.provider, catalog)),- Effect.map(stampIdentity),- ),- checkProvider,- enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>- resolveMaintenance().pipe(- Effect.flatMap((maintenanceCapabilities) =>- enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {- enableProviderUpdateChecks: settings.enableProviderUpdateChecks,- }),- ),- Effect.provideService(HttpClient.HttpClient, httpClient),- Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),- Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),- ),- }).pipe(- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,- cause,+ const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);+ const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<ClaudeSettings>>({+ resolveMaintenance,+ getSettings: snapshotSettings.getSettings,+ streamSettings: snapshotSettings.streamSettings,+ haveSettingsChanged: haveProviderSnapshotSettingsChanged,+ initialSnapshot: (settings) =>+ modelCatalog.pipe(+ Effect.flatMap((catalog) => makePendingClaudeProvider(settings.provider, catalog)),+ Effect.map(stampIdentity),+ ),+ checkProvider,+ enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>+ resolveMaintenance().pipe(+ Effect.flatMap((maintenanceCapabilities) =>+ enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {+ enableProviderUpdateChecks: settings.enableProviderUpdateChecks,}),+ ),+ Effect.provideService(HttpClient.HttpClient, httpClient),+ Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),+ Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),),- );+ }).pipe(+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,+ cause,+ }),+ ),+ );- // Same rules as Codex: serialised on the config directory that holds the- // login, one request id kept until Claude answers (a cooldown or rate- // limit is an answer), then a re-probe.- const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = () =>- Effect.gen(function* () {- const current = yield* snapshot.getSnapshot;- const grantId = current.usageLimits?.resetCredits?.nextCreditId;- if (!grantId || !current.version) return "noCredit" as const;- const version = current.version;- return yield* resetCreditCoordinator.redeem(- configDir,- (requestId) =>- ClaudeResetCredits.consumeClaudeResetCredit({- configDir,- accountConfigPath,- version,- grantId,- requestId,- }),- ClaudeResetCredits.isSettledClaudeResetCreditFailure,- );- }).pipe(- Effect.provideService(HttpClient.HttpClient, httpClient),- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, path),- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail:- cause._tag === "ClaudeResetCreditError"- ? cause.message- : "Claude could not redeem the reset.",- cause,- }),- ),- Effect.tap((outcome) =>- Effect.gen(function* () {- const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;- yield* Cache.invalidateAll(capabilitiesProbeCache);- const refreshed = yield* snapshot.refresh;- const after = refreshed.usageLimits?.checkedAt;- if (- outcome === "reset" &&- (after === undefined ||- after === before ||- refreshed.usageLimits?.unavailable?.reason === "probeFailed")- ) {- return yield* new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail:- "The reset was applied, but Claude could not confirm the new limits. Refresh to check.",- });- }+ // Same rules as Codex: serialised on the config directory that holds the+ // login, one request id kept until Claude answers (a cooldown or rate+ // limit is an answer), then a re-probe.+ const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = Effect.fn(+ "ClaudeDriver.consumeResetCredit",+ )(+ function* () {+ const current = yield* snapshot.getSnapshot;+ const grantId = current.usageLimits?.resetCredits?.nextCreditId;+ if (!grantId || !current.version) return "noCredit" as const;+ const version = current.version;+ return yield* resetCreditCoordinator.redeem(+ configDir,+ (requestId) =>+ ClaudeResetCredits.consumeClaudeResetCredit({+ configDir,+ accountConfigPath,+ version,+ grantId,+ requestId,}),- ),+ ClaudeResetCredits.isSettledClaudeResetCreditFailure,);+ },+ Effect.provideService(HttpClient.HttpClient, httpClient),+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail:+ cause._tag === "ClaudeResetCreditError"+ ? cause.message+ : "Claude could not redeem the reset.",+ cause,+ }),+ ),+ Effect.tap((outcome) =>+ Effect.gen(function* () {+ const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;+ yield* Cache.invalidateAll(capabilitiesProbeCache);+ const refreshed = yield* snapshot.refresh;+ const after = refreshed.usageLimits?.checkedAt;+ if (+ outcome === "reset" &&+ (after === undefined ||+ after === before ||+ refreshed.usageLimits?.unavailable?.reason === "probeFailed")+ ) {+ return yield* new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail:+ "The reset was applied, but Claude could not confirm the new limits. Refresh to check.",+ });+ }+ }),+ ),+ );- return {- instanceId,- driverKind: DRIVER_KIND,- continuationIdentity: {- ...fallbackContinuationIdentity,- continuationKey: continuationGroupKey,- },- displayName,- accentColor,- enabled,- snapshot,- invalidateCaches: Cache.invalidateAll(capabilitiesProbeCache),- snapshotForCwd: (cwd: string) =>- snapshot.getSnapshot.pipe(- Effect.flatMap((machineSnapshot) =>- probeClaudeWorkspaceSnapshot(effectiveConfig, machineSnapshot, cwd, processEnv),- ),- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, path),+ return {+ instanceId,+ driverKind: DRIVER_KIND,+ continuationIdentity: {+ ...fallbackContinuationIdentity,+ continuationKey: continuationGroupKey,+ },+ displayName,+ accentColor,+ enabled,+ snapshot,+ invalidateCaches: Cache.invalidateAll(capabilitiesProbeCache),+ snapshotForCwd: (cwd: string) =>+ snapshot.getSnapshot.pipe(+ Effect.flatMap((machineSnapshot) =>+ probeClaudeWorkspaceSnapshot(effectiveConfig, machineSnapshot, cwd, processEnv),),- orchestrationAdapter,- textGeneration,- consumeResetCredit,- } satisfies ProviderInstance;- }),+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ ),+ orchestrationAdapter,+ textGeneration,+ consumeResetCredit,+ } satisfies ProviderInstance;+ }),};diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.tsindex 2388213eed3..28e23b2f7e9 100644--- a/apps/server/src/provider/Drivers/CodexDriver.ts+++ b/apps/server/src/provider/Drivers/CodexDriver.ts@@ -106,246 +106,252 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv, Path.PatconfigSchema: CodexSettings,defaultConfig: (): CodexSettings => decodeCodexSettings({}),usage: codexUsageReader,- create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>- Effect.gen(function* () {- if (config.setupMode === "managed")- return yield* makeManagedCodexProvider({- instanceId,- displayName,- accentColor,- environment,- enabled,- config,- });- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;- const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator;- const fileSystem = yield* FileSystem.FileSystem;- const pathService = yield* Path.Path;- const httpClient = yield* HttpClient.HttpClient;- const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;- const modelCatalog = yield* ModelCatalog.ModelCatalog;- const currentCatalog = modelCatalog.current(DRIVER_KIND);- const processEnv = yield* mergeProviderInstanceEnvironment(environment);- const homeLayout = yield* resolveCodexHomeLayout(config);- const continuationIdentity = codexContinuationIdentity(homeLayout);- const stampIdentity = withInstanceIdentity({+ create: Effect.fn("CodexDriver.create")(function* ({+ instanceId,+ displayName,+ accentColor,+ environment,+ enabled,+ config,+ }) {+ if (config.setupMode === "managed")+ return yield* makeManagedCodexProvider({instanceId,- driverKind: DRIVER_KIND,displayName,accentColor,- continuationGroupKey: continuationIdentity.continuationKey,- });- yield* materializeCodexShadowHome(homeLayout).pipe(- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: cause.message,- cause,- }),- ),- );- const effectiveConfig = {- ...config,+ environment,enabled,- binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),- homePath: homeLayout.effectiveHomePath ?? "",- } satisfies CodexSettings;- const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(- resolveProviderMaintenanceCapabilitiesEffect(- makeCodexMaintenanceResolver(homeLayout.sharedHomePath),- {- binaryPath: effectiveConfig.binaryPath,- env: processEnv,- },- ).pipe(- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, pathService),- ),- );-- const orchestrationAdapter = yield* createCodexAdapterV2(+ config,+ });+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator;+ const fileSystem = yield* FileSystem.FileSystem;+ const pathService = yield* Path.Path;+ const httpClient = yield* HttpClient.HttpClient;+ const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;+ const modelCatalog = yield* ModelCatalog.ModelCatalog;+ const currentCatalog = modelCatalog.current(DRIVER_KIND);+ const processEnv = yield* mergeProviderInstanceEnvironment(environment);+ const homeLayout = yield* resolveCodexHomeLayout(config);+ const continuationIdentity = codexContinuationIdentity(homeLayout);+ const stampIdentity = withInstanceIdentity({+ instanceId,+ driverKind: DRIVER_KIND,+ displayName,+ accentColor,+ continuationGroupKey: continuationIdentity.continuationKey,+ });+ yield* materializeCodexShadowHome(homeLayout).pipe(+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: cause.message,+ cause,+ }),+ ),+ );+ const effectiveConfig = {+ ...config,+ enabled,+ binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),+ homePath: homeLayout.effectiveHomePath ?? "",+ } satisfies CodexSettings;+ const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(+ resolveProviderMaintenanceCapabilitiesEffect(+ makeCodexMaintenanceResolver(homeLayout.sharedHomePath),{- instanceId,- displayName,- accentColor,- environment,- enabled,- config,+ binaryPath: effectiveConfig.binaryPath,+ env: processEnv,},- { onUsageLimits: (update) => snapshot.applyUsageLimits(update) },).pipe(- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: "Failed to build Codex orchestration adapter.",- cause,- }),- ),- );-- // Kick the TTL-gated manifest refresh in the background and classify with the in-memory- // manifest, so a slow or hung fetch never delays the provider check.- const checkProvider = modelCatalog.refreshInBackground.pipe(- Effect.andThen(- Effect.zipWith(- checkCodexProviderStatus(effectiveConfig, undefined, processEnv),- currentCatalog,- (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),- { concurrent: true },- ),- ),Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),Effect.provideService(FileSystem.FileSystem, fileSystem),Effect.provideService(Path.Path, pathService),- );- const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);- const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({- resolveMaintenance,- getSettings: snapshotSettings.getSettings,- streamSettings: snapshotSettings.streamSettings,- haveSettingsChanged: haveProviderSnapshotSettingsChanged,- initialSnapshot: (settings) =>- Effect.zipWith(- makePendingCodexProvider(settings.provider),- currentCatalog,- (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),- ),- checkProvider,- enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>- resolveMaintenance().pipe(- Effect.flatMap((maintenanceCapabilities) =>- enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {- enableProviderUpdateChecks: settings.enableProviderUpdateChecks,- }),- ),- Effect.provideService(HttpClient.HttpClient, httpClient),- Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),- Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),- ),- }).pipe(- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,- cause,+ ),+ );++ const orchestrationAdapter = yield* createCodexAdapterV2(+ {+ instanceId,+ displayName,+ accentColor,+ environment,+ enabled,+ config,+ },+ { onUsageLimits: (update) => snapshot.applyUsageLimits(update) },+ ).pipe(+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: "Failed to build Codex orchestration adapter.",+ cause,+ }),+ ),+ );++ // Kick the TTL-gated manifest refresh in the background and classify with the in-memory+ // manifest, so a slow or hung fetch never delays the provider check.+ const checkProvider = modelCatalog.refreshInBackground.pipe(+ Effect.andThen(+ Effect.zipWith(+ checkCodexProviderStatus(effectiveConfig, undefined, processEnv),+ currentCatalog,+ (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),+ { concurrent: true },+ ),+ ),+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, pathService),+ );+ const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);+ const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({+ resolveMaintenance,+ getSettings: snapshotSettings.getSettings,+ streamSettings: snapshotSettings.streamSettings,+ haveSettingsChanged: haveProviderSnapshotSettingsChanged,+ initialSnapshot: (settings) =>+ Effect.zipWith(+ makePendingCodexProvider(settings.provider),+ currentCatalog,+ (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),+ ),+ checkProvider,+ enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>+ resolveMaintenance().pipe(+ Effect.flatMap((maintenanceCapabilities) =>+ enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {+ enableProviderUpdateChecks: settings.enableProviderUpdateChecks,}),+ ),+ Effect.provideService(HttpClient.HttpClient, httpClient),+ Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),+ Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),),- );- const textGeneration = yield* makeCodexTextGeneration(- effectiveConfig,- processEnv,- snapshot.getSnapshot.pipe(Effect.map((value) => value.models)),- );- const snapshotForCwd = (cwd: string) =>- !effectiveConfig.enabled- ? snapshot.getSnapshot- : Effect.all([- snapshot.getSnapshot,- probeCodexSkillsForCwd({- binaryPath: effectiveConfig.binaryPath,- homePath: effectiveConfig.homePath,- launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),- cwd,- environment: processEnv,- }).pipe(- Effect.scoped,- Effect.timeout("20 seconds"),- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- ),- ]).pipe(- Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })),- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: `Failed to probe Codex skills for '${cwd}'`,- cause,- }),- ),- );-- // Redemption spends something on the user's account. It serialises on- // the account (instances sharing a Codex home share the credit), keeps- // one idempotency key until Codex reports an outcome, and is bounded so- // a hung app-server cannot hold the account lock.- // Keyed on the directory holding auth.json: an auth-overlay instance has- // its own account under `effectiveHomePath`, while plain instances share- // the common home. The continuation key would conflate the two.- const accountKey = homeLayout.effectiveHomePath ?? homeLayout.sharedHomePath;- const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = () =>- resetCreditCoordinator- .redeem(accountKey, (idempotencyKey) =>- Effect.gen(function* () {- const { client } = yield* withCodexAppServerClient({- binaryPath: effectiveConfig.binaryPath,- homePath: effectiveConfig.homePath,- launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),- cwd: process.cwd(),- environment: processEnv,- });- const response = yield* client.request("account/rateLimitResetCredit/consume", {- idempotencyKey,- });- return response.outcome;- }).pipe(Effect.scoped, Effect.timeout("20 seconds")),- )- .pipe(- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ }).pipe(+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,+ cause,+ }),+ ),+ );+ const textGeneration = yield* makeCodexTextGeneration(+ effectiveConfig,+ processEnv,+ snapshot.getSnapshot.pipe(Effect.map((value) => value.models)),+ );+ const snapshotForCwd = (cwd: string) =>+ !effectiveConfig.enabled+ ? snapshot.getSnapshot+ : Effect.all([+ snapshot.getSnapshot,+ probeCodexSkillsForCwd({+ binaryPath: effectiveConfig.binaryPath,+ homePath: effectiveConfig.homePath,+ launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),+ cwd,+ environment: processEnv,+ }).pipe(+ Effect.scoped,+ Effect.timeout("20 seconds"),+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ ),+ ]).pipe(+ Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })),Effect.mapError((cause) =>new ProviderDriverError({driver: DRIVER_KIND,instanceId,- detail: "Codex could not redeem the reset credit.",+ detail: `Failed to probe Codex skills for '${cwd}'`,cause,}),),- // The windows just changed; re-probe so the snapshot says so. A- // failed probe republishes the pre-redemption limits rather than- // marking them failed, so "confirmed" means `checkedAt` moved past- // what was published before the redemption started.- Effect.tap((outcome) =>- Effect.gen(function* () {- const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;- const refreshed = yield* snapshot.refresh;- const after = refreshed.usageLimits?.checkedAt;- if (- outcome === "reset" &&- (after === undefined ||- after === before ||- refreshed.usageLimits?.unavailable?.reason === "probeFailed")- ) {- return yield* new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail:- "The reset was applied, but Codex could not confirm the new limits. Refresh to check.",- });- }- }),- ),);- return {- instanceId,- driverKind: DRIVER_KIND,- continuationIdentity,- displayName,- accentColor,- enabled,- snapshot,- snapshotForCwd,- consumeResetCredit,- orchestrationAdapter,- textGeneration,- } satisfies ProviderInstance;- }),+ // Redemption spends something on the user's account. It serialises on+ // the account (instances sharing a Codex home share the credit), keeps+ // one idempotency key until Codex reports an outcome, and is bounded so+ // a hung app-server cannot hold the account lock.+ // Keyed on the directory holding auth.json: an auth-overlay instance has+ // its own account under `effectiveHomePath`, while plain instances share+ // the common home. The continuation key would conflate the two.+ const accountKey = homeLayout.effectiveHomePath ?? homeLayout.sharedHomePath;+ const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = () =>+ resetCreditCoordinator+ .redeem(accountKey, (idempotencyKey) =>+ Effect.gen(function* () {+ const { client } = yield* withCodexAppServerClient({+ binaryPath: effectiveConfig.binaryPath,+ homePath: effectiveConfig.homePath,+ launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),+ cwd: process.cwd(),+ environment: processEnv,+ });+ const response = yield* client.request("account/rateLimitResetCredit/consume", {+ idempotencyKey,+ });+ return response.outcome;+ }).pipe(Effect.scoped, Effect.timeout("20 seconds")),+ )+ .pipe(+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: "Codex could not redeem the reset credit.",+ cause,+ }),+ ),+ // The windows just changed; re-probe so the snapshot says so. A+ // failed probe republishes the pre-redemption limits rather than+ // marking them failed, so "confirmed" means `checkedAt` moved past+ // what was published before the redemption started.+ Effect.tap((outcome) =>+ Effect.gen(function* () {+ const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;+ const refreshed = yield* snapshot.refresh;+ const after = refreshed.usageLimits?.checkedAt;+ if (+ outcome === "reset" &&+ (after === undefined ||+ after === before ||+ refreshed.usageLimits?.unavailable?.reason === "probeFailed")+ ) {+ return yield* new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail:+ "The reset was applied, but Codex could not confirm the new limits. Refresh to check.",+ });+ }+ }),+ ),+ );++ return {+ instanceId,+ driverKind: DRIVER_KIND,+ continuationIdentity,+ displayName,+ accentColor,+ enabled,+ snapshot,+ snapshotForCwd,+ consumeResetCredit,+ orchestrationAdapter,+ textGeneration,+ } satisfies ProviderInstance;+ }),};diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.tsindex 1493c283c2a..26db5d8d46f 100644--- a/apps/server/src/provider/Drivers/antigravityUsageReader.ts+++ b/apps/server/src/provider/Drivers/antigravityUsageReader.ts@@ -433,47 +433,49 @@ export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function*cache?.set(canonical, { fingerprint, candidates });return candidates;});- const walk = (directory: string, root: string): Effect.Effect<void> =>- Effect.gen(function* () {- const names = yield* fileSystem.readDirectory(directory).pipe(- Effect.catchTags({- PlatformError: (cause) => {- if (cause.reason._tag !== "NotFound") errors.push(directory);- return Effect.succeed(null);- },- }),- );- if (names === null) return;- names.sort((a, b) => a.localeCompare(b));- for (const name of names) {- const path = pathService.join(directory, name);- // Like a directory listing's entry types: symlinks are neither files nor directories.- const isLink = Exit.isSuccess(yield* Effect.exit(fileSystem.readLink(path)));- const type = isLink- ? "SymbolicLink"- : yield* fileSystem.stat(path).pipe(- Effect.map((info) => info.type),- Effect.orElseSucceed(() => null),- );- if (type === "Directory") {- yield* walk(path, root);- } else if ((type === "File" || type === null) && name.endsWith(".db")) {- const candidates = yield* readFile(path).pipe(- Effect.catch(() => {- errors.push(path);- return Effect.succeed(null);- }),+ const walk = Effect.fn("antigravityUsageReader.walk")(function* (+ directory: string,+ root: string,+ ): Effect.fn.Return<void> {+ const names = yield* fileSystem.readDirectory(directory).pipe(+ Effect.catchTags({+ PlatformError: (cause) => {+ if (cause.reason._tag !== "NotFound") errors.push(directory);+ return Effect.succeed(null);+ },+ }),+ );+ if (names === null) return;+ names.sort((a, b) => a.localeCompare(b));+ for (const name of names) {+ const path = pathService.join(directory, name);+ // Like a directory listing's entry types: symlinks are neither files nor directories.+ const isLink = Exit.isSuccess(yield* Effect.exit(fileSystem.readLink(path)));+ const type = isLink+ ? "SymbolicLink"+ : yield* fileSystem.stat(path).pipe(+ Effect.map((info) => info.type),+ Effect.orElseSucceed(() => null),);- if (candidates === null) continue;- const fileIndex = files.length;- files.push({ root, path, records: [] });- for (const [index, candidate] of candidates.entries()) {- append(candidate, fileIndex);- if (index % 256 === 255) yield* Effect.yieldNow;- }+ if (type === "Directory") {+ yield* walk(path, root);+ } else if ((type === "File" || type === null) && name.endsWith(".db")) {+ const candidates = yield* readFile(path).pipe(+ Effect.catch(() => {+ errors.push(path);+ return Effect.succeed(null);+ }),+ );+ if (candidates === null) continue;+ const fileIndex = files.length;+ files.push({ root, path, records: [] });+ for (const [index, candidate] of candidates.entries()) {+ append(candidate, fileIndex);+ if (index % 256 === 255) yield* Effect.yieldNow;}}- });+ }+ });for (const root of roots) yield* walk(root, root);if (cache !== undefined) {for (const key of cache.keys()) if (!visited.has(key)) cache.delete(key);diff --git a/apps/server/src/provider/ProviderAuthService.ts b/apps/server/src/provider/ProviderAuthService.tsindex 24f176dd709..5a730c5baf8 100644--- a/apps/server/src/provider/ProviderAuthService.ts+++ b/apps/server/src/provider/ProviderAuthService.ts@@ -10,6 +10,7 @@ import {} from "@t3tools/contracts";import * as Context from "effect/Context";import * as Effect from "effect/Effect";+import * as Function from "effect/Function";import * as Layer from "effect/Layer";import type * as Scope from "effect/Scope";import * as Stream from "effect/Stream";@@ -267,8 +268,8 @@ export const makeProviderAuthService = Effect.gen(function* () {}),);}),- subscribe: (input, ownerSessionId) =>- Effect.gen(function* () {+ subscribe: Function.flow(+ Effect.fn("ProviderAuthService.subscribe")(function* (input, ownerSessionId) {const changes = yield* registry.subscribeChanges;const initial = yield* getController(input.instanceId, "subscribe");return Stream.concat(@@ -280,7 +281,9 @@ export const makeProviderAuthService = Effect.gen(function* () {Stream.changesWith((previous, next) => previous === next),Stream.switchMap((auth) => auth.subscribe(ownerSessionId)),);- }).pipe(Stream.unwrap),+ }),+ Stream.unwrap,+ ),tryHandlePromptCommand: Effect.fn("ProviderAuthService.tryHandlePromptCommand")(function* (input) {const instance = yield* registry.getInstance(input.instanceId);diff --git a/apps/server/src/provider/ProviderInstanceRegistry.ts b/apps/server/src/provider/ProviderInstanceRegistry.tsindex e5bf808faa7..1659e8f8fa1 100644--- a/apps/server/src/provider/ProviderInstanceRegistry.ts+++ b/apps/server/src/provider/ProviderInstanceRegistry.ts@@ -70,98 +70,97 @@ const resolveEntryEnabled = (entry: ProviderInstanceConfig, typedConfig: unknownreturn entry.enabled ?? providerInstanceConfigEnabledFlag(typedConfig) ?? true;};-const buildEntry = <R>(input: {+const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* <R>(input: {readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;readonly parentScope: Scope.Scope;readonly instanceId: ProviderInstanceId;readonly rawInstanceId: string;readonly entry: ProviderInstanceConfig;-}): Effect.Effect<+}): Effect.fn.Return<| { readonly kind: "live"; readonly live: LiveEntry }| { readonly kind: "unavailable"; readonly snapshot: ServerProvider },never,R-> =>- Effect.gen(function* () {- const { driversById, parentScope, instanceId, rawInstanceId, entry } = input;- const driver = driversById.get(entry.driver);- if (!driver) {- return {- kind: "unavailable" as const,- snapshot: yield* buildUnavailableProviderSnapshot({- driverKind: entry.driver,- instanceId,- displayName: entry.displayName,- accentColor: entry.accentColor,- reason: `Driver '${entry.driver}' is not registered in this build.`,- }),- };- }-- const decoder = Schema.decodeUnknownEffect(driver.configSchema);- const decodeResult = yield* decoder(entry.config ?? driver.defaultConfig()).pipe(Effect.result);- if (decodeResult._tag === "Failure") {- const issue = decodeResult.failure;- const detail = issue.message ?? String(issue);- yield* Effect.logError("Failed to decode provider instance config", {- instanceId: rawInstanceId,- driver: entry.driver,- detail,- });- return {- kind: "unavailable" as const,- snapshot: yield* buildUnavailableProviderSnapshot({- driverKind: entry.driver,- instanceId,- displayName: entry.displayName,- accentColor: entry.accentColor,- reason: `Invalid config for instance '${rawInstanceId}': ${detail}`,- }),- };- }-- const typedConfig = decodeResult.success;- const childScope = yield* Scope.make();- yield* Scope.addFinalizer(parentScope, Scope.close(childScope, Exit.void).pipe(Effect.ignore));+> {+ const { driversById, parentScope, instanceId, rawInstanceId, entry } = input;+ const driver = driversById.get(entry.driver);+ if (!driver) {+ return {+ kind: "unavailable" as const,+ snapshot: yield* buildUnavailableProviderSnapshot({+ driverKind: entry.driver,+ instanceId,+ displayName: entry.displayName,+ accentColor: entry.accentColor,+ reason: `Driver '${entry.driver}' is not registered in this build.`,+ }),+ };+ }- const createResult = yield* driver- .create({+ const decoder = Schema.decodeUnknownEffect(driver.configSchema);+ const decodeResult = yield* decoder(entry.config ?? driver.defaultConfig()).pipe(Effect.result);+ if (decodeResult._tag === "Failure") {+ const issue = decodeResult.failure;+ const detail = issue.message ?? String(issue);+ yield* Effect.logError("Failed to decode provider instance config", {+ instanceId: rawInstanceId,+ driver: entry.driver,+ detail,+ });+ return {+ kind: "unavailable" as const,+ snapshot: yield* buildUnavailableProviderSnapshot({+ driverKind: entry.driver,instanceId,displayName: entry.displayName,accentColor: entry.accentColor,- environment: entry.environment ?? [],- enabled: resolveEntryEnabled(entry, typedConfig),- config: typedConfig,- })- .pipe(Effect.provideService(Scope.Scope, childScope), Effect.result);- if (createResult._tag === "Failure") {- yield* Effect.logError("Failed to create provider instance", {- instanceId: rawInstanceId,- driver: entry.driver,- detail: createResult.failure.detail,- });- yield* Scope.close(childScope, Exit.void).pipe(Effect.ignore);- return {- kind: "unavailable" as const,- snapshot: yield* buildUnavailableProviderSnapshot({- driverKind: entry.driver,- instanceId,- displayName: entry.displayName,- accentColor: entry.accentColor,- reason: `Driver '${entry.driver}' failed to create instance: ${createResult.failure.detail}`,- }),- };- }+ reason: `Invalid config for instance '${rawInstanceId}': ${detail}`,+ }),+ };+ }++ const typedConfig = decodeResult.success;+ const childScope = yield* Scope.make();+ yield* Scope.addFinalizer(parentScope, Scope.close(childScope, Exit.void).pipe(Effect.ignore));+ const createResult = yield* driver+ .create({+ instanceId,+ displayName: entry.displayName,+ accentColor: entry.accentColor,+ environment: entry.environment ?? [],+ enabled: resolveEntryEnabled(entry, typedConfig),+ config: typedConfig,+ })+ .pipe(Effect.provideService(Scope.Scope, childScope), Effect.result);+ if (createResult._tag === "Failure") {+ yield* Effect.logError("Failed to create provider instance", {+ instanceId: rawInstanceId,+ driver: entry.driver,+ detail: createResult.failure.detail,+ });+ yield* Scope.close(childScope, Exit.void).pipe(Effect.ignore);return {- kind: "live" as const,- live: {- instance: createResult.success,- scope: childScope,- entry,- },+ kind: "unavailable" as const,+ snapshot: yield* buildUnavailableProviderSnapshot({+ driverKind: entry.driver,+ instanceId,+ displayName: entry.displayName,+ accentColor: entry.accentColor,+ reason: `Driver '${entry.driver}' failed to create instance: ${createResult.failure.detail}`,+ }),};- });+ }++ return {+ kind: "live" as const,+ live: {+ instance: createResult.success,+ scope: childScope,+ entry,+ },+ };+});const makeReconcile = <R>(input: {readonly state: RegistryState;@@ -263,67 +262,68 @@ const makeReconcile = <R>(input: {});};-export const makeProviderInstanceRegistry = <R>(input: {+export const makeProviderInstanceRegistry = Effect.fn(+ "ProviderInstanceRegistry.makeProviderInstanceRegistry",+)(function* <R>(input: {readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;readonly configMap: ProviderInstanceConfigMap;-}): Effect.Effect<+}): Effect.fn.Return<{readonly registry: ProviderInstanceRegistry["Service"];readonly mutator: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape;},never,R | Scope.Scope-> =>- Effect.gen(function* () {- const driversById = new Map<ProviderDriverKind, AnyProviderDriver<R>>(- input.drivers.map((driver) => [driver.driverKind, driver]),- );+> {+ const driversById = new Map<ProviderDriverKind, AnyProviderDriver<R>>(+ input.drivers.map((driver) => [driver.driverKind, driver]),+ );- // Capture the enclosing scope so per-instance child scopes can be- // attached to it at `reconcile` time. Without this, `reconcile`- // called later (e.g. from the hydration layer) would attach child- // scopes to the *caller's* scope instead of the registry's.- const parentScope = yield* Scope.Scope;+ // Capture the enclosing scope so per-instance child scopes can be+ // attached to it at `reconcile` time. Without this, `reconcile`+ // called later (e.g. from the hydration layer) would attach child+ // scopes to the *caller's* scope instead of the registry's.+ const parentScope = yield* Scope.Scope;- const driverContext = yield* Effect.context<R>();+ const driverContext = yield* Effect.context<R>();- const entries = yield* Ref.make<ReadonlyMap<ProviderInstanceId, LiveEntry>>(new Map());- const unavailable = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ServerProvider>>(new Map());- const changes = yield* PubSub.unbounded<void>();- yield* Effect.addFinalizer(() => PubSub.shutdown(changes));+ const entries = yield* Ref.make<ReadonlyMap<ProviderInstanceId, LiveEntry>>(new Map());+ const unavailable = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ServerProvider>>(new Map());+ const changes = yield* PubSub.unbounded<void>();+ yield* Effect.addFinalizer(() => PubSub.shutdown(changes));- const state: RegistryState = { entries, unavailable, changes };- const reconcileWithR = makeReconcile({ state, driversById, parentScope });- const reconcile: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape["reconcile"] =- (configMap) => reconcileWithR(configMap).pipe(Effect.provideContext(driverContext));+ const state: RegistryState = { entries, unavailable, changes };+ const reconcileWithR = makeReconcile({ state, driversById, parentScope });+ const reconcile: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape["reconcile"] =+ (configMap) => reconcileWithR(configMap).pipe(Effect.provideContext(driverContext));- yield* reconcile(input.configMap);+ yield* reconcile(input.configMap);- const registry: ProviderInstanceRegistry["Service"] = {- getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)),- listInstances: Ref.get(entries).pipe(- Effect.map(- (map) =>- Array.from(map.values(), (live) => live.instance) as ReadonlyArray<ProviderInstance>,- ),+ const registry: ProviderInstanceRegistry["Service"] = {+ getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)),+ listInstances: Ref.get(entries).pipe(+ Effect.map(+ (map) =>+ Array.from(map.values(), (live) => live.instance) as ReadonlyArray<ProviderInstance>,),- listUnavailable: Ref.get(unavailable).pipe(- Effect.map((map) => Array.from(map.values()) as ReadonlyArray<ServerProvider>),- ),- get streamChanges() {- return Stream.fromPubSub(changes);- },- get subscribeChanges() {- return PubSub.subscribe(changes);- },- };+ ),+ listUnavailable: Ref.get(unavailable).pipe(+ Effect.map((map) => Array.from(map.values()) as ReadonlyArray<ServerProvider>),+ ),+ get streamChanges() {+ return Stream.fromPubSub(changes);+ },+ get subscribeChanges() {+ return PubSub.subscribe(changes);+ },+ };- const mutator: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape = {- reconcile,- };+ const mutator: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape = {+ reconcile,+ };- return { registry, mutator };- });+ return { registry, mutator };+});export const layer = <R>(input: {readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.tsindex 0a3b4e60917..c459f670fca 100644--- a/apps/server/src/provider/ProviderRegistry.ts+++ b/apps/server/src/provider/ProviderRegistry.ts@@ -454,21 +454,22 @@ export const layer = Layer.effect(liveSubsRef,).pipe(Effect.map((map) => Array.from(map.values(), buildSnapshotSource)));- const persistProvider = (provider: ServerProvider) =>- Effect.gen(function* () {- const key = snapshotInstanceKey(provider);- const filePath = yield* resolveProviderStatusCachePath({- cacheDir: config.providerStatusCacheDir,- instanceId: key,- }).pipe(Effect.provideService(Path.Path, path));- const { workspaceSnapshots: _workspaceSnapshots, ...machineProvider } = provider;- yield* writeProviderStatusCache({ filePath, provider: machineProvider }).pipe(- Effect.provideService(FileSystem.FileSystem, fileSystem),- Effect.provideService(Path.Path, path),- Effect.tapError(Effect.logError),- Effect.ignore,- );- });+ const persistProvider = Effect.fn("ProviderRegistry.persistProvider")(function* (+ provider: ServerProvider,+ ) {+ const key = snapshotInstanceKey(provider);+ const filePath = yield* resolveProviderStatusCachePath({+ cacheDir: config.providerStatusCacheDir,+ instanceId: key,+ }).pipe(Effect.provideService(Path.Path, path));+ const { workspaceSnapshots: _workspaceSnapshots, ...machineProvider } = provider;+ yield* writeProviderStatusCache({ filePath, provider: machineProvider }).pipe(+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ Effect.provideService(Path.Path, path),+ Effect.tapError(Effect.logError),+ Effect.ignore,+ );+ });const applyProviderUpdateState = Effect.fn("applyProviderUpdateState")(function* (provider: ServerProvider,diff --git a/apps/server/src/provider/claudeResetCredits.ts b/apps/server/src/provider/claudeResetCredits.tsindex 4736fbe4970..fbc3efa2e5d 100644--- a/apps/server/src/provider/claudeResetCredits.ts+++ b/apps/server/src/provider/claudeResetCredits.ts@@ -122,25 +122,28 @@ export function claudeResetCreditsToContract(};}-const readJson = <S extends Schema.Top>(schema: S, file: string) =>- Effect.gen(function* () {- const fs = yield* FileSystem.FileSystem;- return yield* fs.readFileString(file).pipe(- Effect.catchTags({- PlatformError: (error) =>- error.reason._tag === "NotFound" ? Effect.succeed("{}") : Effect.fail(error),- }),- Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(schema))),- );- });+const readJson = Effect.fn("claudeResetCredits.readJson")(function* <S extends Schema.Top>(+ schema: S,+ file: string,+) {+ const fs = yield* FileSystem.FileSystem;+ return yield* fs.readFileString(file).pipe(+ Effect.catchTags({+ PlatformError: (error) =>+ error.reason._tag === "NotFound" ? Effect.succeed("{}") : Effect.fail(error),+ }),+ Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(schema))),+ );+});-const readAccessToken = (configDir: string) =>- Effect.gen(function* () {- if ((yield* HostProcess.Platform) === "darwin") return undefined;- const path = yield* Path.Path;- const credentials = yield* readJson(Credentials, path.join(configDir, ".credentials.json"));- return credentials.claudeAiOauth?.accessToken?.trim() || undefined;- });+const readAccessToken = Effect.fn("claudeResetCredits.readAccessToken")(function* (+ configDir: string,+) {+ if ((yield* HostProcess.Platform) === "darwin") return undefined;+ const path = yield* Path.Path;+ const credentials = yield* readJson(Credentials, path.join(configDir, ".credentials.json"));+ return credentials.claudeAiOauth?.accessToken?.trim() || undefined;+});const withClaudeHeaders = (token: string, version: string) =>HttpClientRequest.setHeaders({diff --git a/apps/server/src/provider/providerMaintenanceCommandCoordinator.ts b/apps/server/src/provider/providerMaintenanceCommandCoordinator.tsindex f2fc03659be..c7db6bdf76a 100644--- a/apps/server/src/provider/providerMaintenanceCommandCoordinator.ts+++ b/apps/server/src/provider/providerMaintenanceCommandCoordinator.ts@@ -35,13 +35,13 @@ export const makeProviderMaintenanceCommandCoordinator = Effect.fn(return next;});- const withCommandLock: ProviderMaintenanceCommandCoordinatorShape<E>["withCommandLock"] = ({- targetKey,- lockKey,- onQueued,- run,- }) =>- Effect.gen(function* () {+ const withCommandLock: ProviderMaintenanceCommandCoordinatorShape<E>["withCommandLock"] =+ Effect.fn("providerMaintenanceCommandCoordinator.withCommandLock")(function* ({+ targetKey,+ lockKey,+ onQueued,+ run,+ }) {const acquired = yield* acquireTarget(targetKey);if (!acquired) {return yield* Effect.fail(input.makeAlreadyRunningError(targetKey));diff --git a/apps/server/src/provider/providerStatusCache.ts b/apps/server/src/provider/providerStatusCache.tsindex d2e5a70084d..486b7fd4104 100644--- a/apps/server/src/provider/providerStatusCache.ts+++ b/apps/server/src/provider/providerStatusCache.ts@@ -108,8 +108,8 @@ export const resolveProviderStatusCachePath = Effect.fn("resolveProviderStatusCa},);-export const readProviderStatusCache = (filePath: string) =>- Effect.gen(function* () {+export const readProviderStatusCache = Effect.fn("providerStatusCache.readProviderStatusCache")(+ function* (filePath: string) {const fs = yield* FileSystem.FileSystem;const exists = yield* fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));if (!exists) {@@ -132,7 +132,8 @@ export const readProviderStatusCache = (filePath: string) =>onSuccess: Effect.succeed,}),);- });+ },+);export const writeProviderStatusCache = (input: {readonly filePath: string;diff --git a/apps/server/src/provider/resetCreditCoordinator.ts b/apps/server/src/provider/resetCreditCoordinator.tsindex 95e24cbdc65..45532eeb055 100644--- a/apps/server/src/provider/resetCreditCoordinator.ts+++ b/apps/server/src/provider/resetCreditCoordinator.ts@@ -58,24 +58,25 @@ export const make = Effect.gen(function* () {});});- const redeem: ResetCreditCoordinator["Service"]["redeem"] = (accountKey, consume, isSettled) =>- Effect.gen(function* () {- const state = yield* stateFor(accountKey);- return yield* state.lock.withPermits(1)(- Effect.gen(function* () {- const existing = yield* Ref.get(state.pendingKey);- const idempotencyKey = existing ?? (yield* crypto.randomUUIDv4());- yield* Ref.set(state.pendingKey, idempotencyKey);- const outcome = yield* consume(idempotencyKey).pipe(- Effect.tapError((error) =>- isSettled?.(error) ? Ref.set(state.pendingKey, null) : Effect.void,- ),- );- yield* Ref.set(state.pendingKey, null);- return outcome;- }),- );- });+ const redeem: ResetCreditCoordinator["Service"]["redeem"] = Effect.fn(+ "resetCreditCoordinator.redeem",+ )(function* (accountKey, consume, isSettled) {+ const state = yield* stateFor(accountKey);+ return yield* state.lock.withPermits(1)(+ Effect.gen(function* () {+ const existing = yield* Ref.get(state.pendingKey);+ const idempotencyKey = existing ?? (yield* crypto.randomUUIDv4());+ yield* Ref.set(state.pendingKey, idempotencyKey);+ const outcome = yield* consume(idempotencyKey).pipe(+ Effect.tapError((error) =>+ isSettled?.(error) ? Ref.set(state.pendingKey, null) : Effect.void,+ ),+ );+ yield* Ref.set(state.pendingKey, null);+ return outcome;+ }),+ );+ });return { redeem } satisfies ResetCreditCoordinator["Service"];});diff --git a/apps/server/src/provider/unavailableProviderSnapshot.ts b/apps/server/src/provider/unavailableProviderSnapshot.tsindex 368c7e86d46..d1888278ab3 100644--- a/apps/server/src/provider/unavailableProviderSnapshot.ts+++ b/apps/server/src/provider/unavailableProviderSnapshot.ts@@ -19,38 +19,36 @@ export interface UnavailableProviderSnapshotInput {const nowIso = Effect.map(DateTime.now, DateTime.formatIso);-export function buildUnavailableProviderSnapshot(- input: UnavailableProviderSnapshotInput,-): Effect.Effect<ServerProvider> {- return Effect.gen(function* () {- const checkedAt = input.checkedAt ?? (yield* nowIso);- const displayName = input.displayName?.trim() || (input.driverKind as string);+export const buildUnavailableProviderSnapshot = Effect.fn(+ "unavailableProviderSnapshot.buildUnavailableProviderSnapshot",+)(function* (input: UnavailableProviderSnapshotInput): Effect.fn.Return<ServerProvider> {+ const checkedAt = input.checkedAt ?? (yield* nowIso);+ const displayName = input.displayName?.trim() || (input.driverKind as string);- const base = buildServerProvider({- presentation: { displayName },- enabled: false,- checkedAt,- models: [],- skills: [],- probe: {- installed: false,- version: null,- status: "error",- auth: { status: "unknown" },- message: input.reason,- },- });-- return {- ...base,- instanceId: input.instanceId,- ...(input.accentColor ? { accentColor: input.accentColor } : {}),- driver:- typeof input.driverKind === "string"- ? ProviderDriverKind.make(input.driverKind)- : input.driverKind,- availability: "unavailable",- unavailableReason: input.reason,- };+ const base = buildServerProvider({+ presentation: { displayName },+ enabled: false,+ checkedAt,+ models: [],+ skills: [],+ probe: {+ installed: false,+ version: null,+ status: "error",+ auth: { status: "unknown" },+ message: input.reason,+ },});-}++ return {+ ...base,+ instanceId: input.instanceId,+ ...(input.accentColor ? { accentColor: input.accentColor } : {}),+ driver:+ typeof input.driverKind === "string"+ ? ProviderDriverKind.make(input.driverKind)+ : input.driverKind,+ availability: "unavailable",+ unavailableReason: input.reason,+ };+});