@devries-cameron20 / t3code-1 / commits / 509e0e0549
Fork 0

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

refactor(server): trace provider operations and keep streamed events untraced (#21993)

Julius Marminge committed Oct 19, 2026 at 18:30 UTC 509e0e054905442c7933cf1ca25c67b7982581a7
19 files changed +2541 -2451
apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts
+23 -21
@@ -120,8 +120,8 @@ export function makeAntigravityAcpAdapterFlavor(
120 ): AcpAdapterV2Flavor {
121 const antigravityClientFileRoots = (cwd: string | null) =>
122 cwd === null ? [options.host.paths.attachmentsDir] : [cwd, options.host.paths.attachmentsDir];
123 - const makeRuntime = (input: AcpAdapterV2RuntimeInput) =>
124 - Effect.gen(function* () {
123 + const makeRuntime = Effect.fn("AntigravityAdapterV2.makeRuntime")(
124 + function* (input: AcpAdapterV2RuntimeInput) {
125 const scope = yield* Scope.fork(yield* Effect.scope);
126 const runtime = yield* options
127 .withProcess(
@@ -144,14 +144,14 @@ export function makeAntigravityAcpAdapterFlavor(
144 ),
145 ),
146 };
147 - }).pipe(
148 - Effect.provideService(Crypto.Crypto, options.crypto),
149 - Effect.mapError((cause): EffectAcpErrors.AcpError =>
150 - cause._tag === "ProviderSetupError"
151 - ? new EffectAcpErrors.AcpTransportError({ detail: cause.detail, cause })
152 - : cause,
153 - ),
154 - );
147 + },
148 + Effect.provideService(Crypto.Crypto, options.crypto),
149 + Effect.mapError((cause): EffectAcpErrors.AcpError =>
150 + cause._tag === "ProviderSetupError"
151 + ? new EffectAcpErrors.AcpTransportError({ detail: cause.detail, cause })
152 + : cause,
153 + ),
154 + );
155
156 return {
157 driver: ANTIGRAVITY_PROVIDER,
@@ -163,17 +163,19 @@ export function makeAntigravityAcpAdapterFlavor(
163 preferResumeSession: true,
164 subagentsIdleOnTurnCompletion: true,
165 ...(options.onSessionEvent === undefined ? {} : { onSessionEvent: options.onSessionEvent }),
166 - applyModelSelection: ({ runtime, modelSelection }) =>
167 - Effect.gen(function* () {
168 - const defaultModel = yield* options.defaultModel;
169 - return yield* applyAntigravityAcpModelSelection({
170 - runtime,
171 - model:
172 - modelSelection.model === ANTIGRAVITY_DEFAULT_MODEL ? undefined : modelSelection.model,
173 - defaultModel,
174 - mapError: (cause) => cause,
175 - });
176 - }),
166 + applyModelSelection: Effect.fn("AntigravityAdapterV2.applyModelSelection")(function* ({
167 + runtime,
168 + modelSelection,
169 + }) {
170 + const defaultModel = yield* options.defaultModel;
171 + return yield* applyAntigravityAcpModelSelection({
172 + runtime,
173 + model:
174 + modelSelection.model === ANTIGRAVITY_DEFAULT_MODEL ? undefined : modelSelection.model,
175 + defaultModel,
176 + mapError: (cause) => cause,
177 + });
178 + }),
179 sessionModeForPolicy: (policy) => antigravityPermissionMode(policy.runtimeMode),
180 clientFileSystem: {
181 readTextFile: (request, cwd) =>
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+73 -71
@@ -3967,8 +3967,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
3967 });
3968 });
3969
3970 - const rememberProviderThread = (providerThread: OrchestrationV2ProviderThread) =>
3971 - Effect.gen(function* () {
3970 + const rememberProviderThread =
3971 + /* Provider events include streaming deltas; avoid a span for each update. */
3972 + Effect.fnUntraced(function* (providerThread: OrchestrationV2ProviderThread) {
3973 const nativeThreadId = providerThread.nativeThreadRef?.nativeId;
3974 if (nativeThreadId === undefined || nativeThreadId === null) {
3975 return;
@@ -4064,11 +4065,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4065 Effect.map((all) => taskIdSetForNativeThread(all, nativeThreadId).has(taskId)),
4066 );
4067
4067 - const isKnownOpaqueBackgroundTaskOnNativeThread = (
4068 - nativeThreadId: string,
4069 - taskId: string,
4070 - ) =>
4071 - Effect.gen(function* () {
4068 + const isKnownOpaqueBackgroundTaskOnNativeThread =
4069 + /* Provider events include streaming deltas; avoid a span for each update. */
4070 + Effect.fnUntraced(function* (nativeThreadId: string, taskId: string) {
4071 if (yield* hasPendingBackgroundTaskOnNativeThread(nativeThreadId, taskId)) {
4072 return true;
4073 }
@@ -4091,11 +4090,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4090 taskIds,
4091 );
4092
4094 - const consumeWakeEligibilityForBufferedNotification = (
4095 - nativeThreadId: string,
4096 - taskId: string,
4097 - ) =>
4098 - Effect.gen(function* () {
4093 + const consumeWakeEligibilityForBufferedNotification =
4094 + /* Provider events include streaming deltas; avoid a span for each update. */
4095 + Effect.fnUntraced(function* (nativeThreadId: string, taskId: string) {
4096 yield* clearTaskIdFromNativeThreadSet(
4097 wakeEligibleBackgroundTasksByNativeThread,
4098 nativeThreadId,
@@ -4186,11 +4183,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4183 return updated;
4184 });
4185
4189 - const replacePendingBackgroundTasks = (
4190 - nativeThreadId: string,
4191 - tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>,
4192 - ) =>
4193 - Effect.gen(function* () {
4186 + const replacePendingBackgroundTasks =
4187 + /* Provider events include streaming deltas; avoid a span for each update. */
4188 + Effect.fnUntraced(function* (
4189 + nativeThreadId: string,
4190 + tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>,
4191 + ) {
4192 yield* Ref.update(pendingBackgroundTasksByNativeThread, (current) => {
4193 const updated = new Map(current);
4194 if (tasks.length === 0) {
@@ -4212,11 +4210,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4210 }
4211 });
4212
4215 - const upsertPendingBackgroundTask = (
4216 - nativeThreadId: string,
4217 - task: OrchestrationV2PendingBackgroundTask,
4218 - ) =>
4219 - Effect.gen(function* () {
4213 + const upsertPendingBackgroundTask =
4214 + /* Provider events include streaming deltas; avoid a span for each update. */
4215 + Effect.fnUntraced(function* (
4216 + nativeThreadId: string,
4217 + task: OrchestrationV2PendingBackgroundTask,
4218 + ) {
4219 yield* Ref.update(pendingBackgroundTasksByNativeThread, (current) => {
4220 const roster = new Map(rosterForNativeThread(current, nativeThreadId));
4221 roster.set(task.taskId, task);
@@ -4243,8 +4242,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4242 return [true, updated] as const;
4243 });
4244
4246 - const clearPendingBackgroundTasksForNativeThread = (nativeThreadId: string) =>
4247 - Effect.gen(function* () {
4245 + const clearPendingBackgroundTasksForNativeThread =
4246 + /* Provider events include streaming deltas; avoid a span for each update. */
4247 + Effect.fnUntraced(function* (nativeThreadId: string) {
4248 yield* Ref.update(pendingBackgroundTasksByNativeThread, (current) => {
4249 if (!current.has(nativeThreadId)) {
4250 return current;
@@ -4256,8 +4256,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4256 yield* endClaudeMonitorTasks((_taskId, task) => task.nativeThreadId === nativeThreadId);
4257 });
4258
4259 - const clearWakeStateForNativeThread = (nativeThreadId: string) =>
4260 - Effect.gen(function* () {
4259 + const clearWakeStateForNativeThread =
4260 + /* Provider events include streaming deltas; avoid a span for each update. */
4261 + Effect.fnUntraced(function* (nativeThreadId: string) {
4262 yield* clearWakeReports(nativeThreadId);
4263 yield* Ref.update(wakeBuffers, (current) => {
4264 if (!current.has(nativeThreadId)) {
@@ -6083,8 +6084,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
6084 });
6085 const reasoningDeltas = yield* makeProviderTextDeltaCoalescer({
6086 flushIntervalMs: 50,
6086 - emit: (update) =>
6087 - Effect.gen(function* () {
6087 + emit:
6088 + /* Provider events include streaming deltas; avoid a span for each update. */
6089 + Effect.fnUntraced(function* (update) {
6090 const context = yield* Ref.get(activeTurn);
6091 if (context === null || context.nativeTurnId !== update.turnId) return;
6092 const block = context.reasoning.blocks.get(update.itemId);
@@ -9467,19 +9469,20 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9469 }
9470 return false;
9471 }),
9470 - hasPendingBackgroundWorkForThread: (providerThread) =>
9471 - Effect.gen(function* () {
9472 - const nativeThreadId = providerThread.nativeThreadRef?.nativeId;
9473 - if (nativeThreadId === undefined || nativeThreadId === null) {
9474 - return false;
9475 - }
9476 - return (
9477 - rosterForNativeThread(
9478 - yield* Ref.get(pendingBackgroundTasksByNativeThread),
9479 - nativeThreadId,
9480 - ).size > 0
9481 - );
9482 - }),
9472 + hasPendingBackgroundWorkForThread: Effect.fn(
9473 + "ClaudeAdapterV2.hasPendingBackgroundWorkForThread",
9474 + )(function* (providerThread) {
9475 + const nativeThreadId = providerThread.nativeThreadRef?.nativeId;
9476 + if (nativeThreadId === undefined || nativeThreadId === null) {
9477 + return false;
9478 + }
9479 + return (
9480 + rosterForNativeThread(
9481 + yield* Ref.get(pendingBackgroundTasksByNativeThread),
9482 + nativeThreadId,
9483 + ).size > 0
9484 + );
9485 + }),
9486 ensureThread: Effect.fn("ClaudeAdapterV2.ensureThread")(
9487 function* (threadInput: ProviderAdapter.ProviderAdapterV2EnsureThreadInput) {
9488 const createdAt = yield* DateTime.now;
@@ -9551,36 +9554,35 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9554 message: { ...turnInput.message, text: "/compact" },
9555 }),
9556 steerTurn,
9554 - stopTask: ({ providerThread, taskId }) =>
9555 - Effect.gen(function* () {
9556 - const liveQuery = yield* Ref.get(queryContext);
9557 - const task = (yield* Ref.get(sessionSubagentsByTaskId)).get(taskId);
9558 - if (
9559 - liveQuery === null ||
9560 - liveQuery.stopping ||
9561 - liveQuery.nativeThreadId !== providerThread.nativeThreadRef?.nativeId ||
9562 - task === undefined ||
9563 - task.task.threadId !== providerThread.appThreadId ||
9564 - task.task.workflow === undefined ||
9565 - task.task.status !== "running" ||
9566 - liveQuery.subagentsFromEarlierProcesses.has(task)
9567 - ) {
9568 - return yield* new ProviderAdapter.ProviderAdapterProtocolError({
9569 - driver: CLAUDE_PROVIDER,
9570 - detail: "No running workflow task belongs to this provider thread",
9571 - });
9572 - }
9573 - yield* liveQuery.query.stopTask(taskId).pipe(
9574 - Effect.mapError(
9575 - (cause) =>
9576 - new ProviderAdapter.ProviderAdapterProtocolError({
9577 - driver: CLAUDE_PROVIDER,
9578 - detail: "Workflow stop request failed",
9579 - cause,
9580 - }),
9581 - ),
9582 - );
9583 - }),
9557 + stopTask: Effect.fn("ClaudeAdapterV2.stopTask")(function* ({ providerThread, taskId }) {
9558 + const liveQuery = yield* Ref.get(queryContext);
9559 + const task = (yield* Ref.get(sessionSubagentsByTaskId)).get(taskId);
9560 + if (
9561 + liveQuery === null ||
9562 + liveQuery.stopping ||
9563 + liveQuery.nativeThreadId !== providerThread.nativeThreadRef?.nativeId ||
9564 + task === undefined ||
9565 + task.task.threadId !== providerThread.appThreadId ||
9566 + task.task.workflow === undefined ||
9567 + task.task.status !== "running" ||
9568 + liveQuery.subagentsFromEarlierProcesses.has(task)
9569 + ) {
9570 + return yield* new ProviderAdapter.ProviderAdapterProtocolError({
9571 + driver: CLAUDE_PROVIDER,
9572 + detail: "No running workflow task belongs to this provider thread",
9573 + });
9574 + }
9575 + yield* liveQuery.query.stopTask(taskId).pipe(
9576 + Effect.mapError(
9577 + (cause) =>
9578 + new ProviderAdapter.ProviderAdapterProtocolError({
9579 + driver: CLAUDE_PROVIDER,
9580 + detail: "Workflow stop request failed",
9581 + cause,
9582 + }),
9583 + ),
9584 + );
9585 + }),
9586 interruptTurn,
9587 stopSubagent: Effect.fn("ClaudeAdapterV2.stopSubagent")(function* (input) {
9588 const existing = yield* Ref.get(queryContext);
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+1188 -1128
@@ -717,19 +717,19 @@ function codexRuntimeModeTurnDefaults(runtimeMode: RuntimeMode): {
717 }
718 }
719
720 -export function buildCodexTurnStartParams(input: {
721 - readonly nativeThreadId: string;
722 - readonly codexInput: ReadonlyArray<CodexSchema.V2TurnStartParams__UserInput>;
723 - readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
724 - readonly modelSelection: ModelSelection;
725 - readonly hasT3Mcp?: boolean;
726 - readonly browserToolsAvailable?: boolean;
727 - readonly deviceToolsAvailable?: boolean;
728 - /** ChatGPT token sharing does not accept service tiers. */
729 - readonly omitServiceTier?: boolean;
730 - readonly appContext?: ProviderAdapter.ProviderAdapterV2TurnInput["appContext"];
731 -}) {
732 - return Effect.gen(function* () {
720 +export const buildCodexTurnStartParams = Effect.fn("CodexAdapterV2.buildCodexTurnStartParams")(
721 + function* (input: {
722 + readonly nativeThreadId: string;
723 + readonly codexInput: ReadonlyArray<CodexSchema.V2TurnStartParams__UserInput>;
724 + readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
725 + readonly modelSelection: ModelSelection;
726 + readonly hasT3Mcp?: boolean;
727 + readonly browserToolsAvailable?: boolean;
728 + readonly deviceToolsAvailable?: boolean;
729 + /** ChatGPT token sharing does not accept service tiers. */
730 + readonly omitServiceTier?: boolean;
731 + readonly appContext?: ProviderAdapter.ProviderAdapterV2TurnInput["appContext"];
732 + }) {
733 const runtimeModeDefaults = codexRuntimeModeTurnDefaults(input.runtimePolicy.runtimeMode);
734 const approvalPolicy =
735 input.runtimePolicy.approvalPolicy === undefined
@@ -808,8 +808,8 @@ export function buildCodexTurnStartParams(input: {
808 ...(serviceTier === undefined ? {} : { serviceTier }),
809 ...(collaborationMode === undefined ? {} : { collaborationMode }),
810 });
811 - });
812 -}
811 + },
812 +);
813
814 function providerSession(input: {
815 readonly providerSessionId: OrchestrationV2ProviderSession["id"];
@@ -832,17 +832,17 @@ function providerSession(input: {
832 };
833 }
834
835 -function getNativeThreadId(providerThread: OrchestrationV2ProviderThread) {
836 - return Effect.gen(function* () {
837 - const nativeThreadId = providerThread.nativeThreadRef?.nativeId;
838 - if (nativeThreadId === undefined || nativeThreadId === null) {
839 - return yield* toProtocolError(
840 - `Provider thread ${providerThread.id} is missing a native Codex thread id.`,
841 - );
842 - }
843 - return nativeThreadId;
844 - });
845 -}
835 +const getNativeThreadId = Effect.fn("CodexAdapterV2.getNativeThreadId")(function* (
836 + providerThread: OrchestrationV2ProviderThread,
837 +) {
838 + const nativeThreadId = providerThread.nativeThreadRef?.nativeId;
839 + if (nativeThreadId === undefined || nativeThreadId === null) {
840 + return yield* toProtocolError(
841 + `Provider thread ${providerThread.id} is missing a native Codex thread id.`,
842 + );
843 + }
844 + return nativeThreadId;
845 +});
846
847 function providerThreadFromCodexThread(input: {
848 readonly appThreadId: ThreadId | null;
@@ -1399,31 +1399,30 @@ const layerCodexAppServerClientFactoryCommand = (
1399 Effect.gen(function* () {
1400 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1401 return CodexAppServerClientFactory.of({
1402 - open: (input) =>
1403 - Effect.gen(function* () {
1404 - const scope = yield* Scope.Scope;
1405 - const command = yield* makeCodexAppServerSpawnCommand({
1406 - command: options.command,
1407 - args: [...(options.args ?? [])],
1408 - ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
1409 - ...(options.env === undefined ? {} : { env: options.env, extendEnv: true }),
1410 - });
1411 - const handle = yield* spawner.spawn(command).pipe(
1412 - Effect.provideService(Scope.Scope, scope),
1413 - Effect.mapError(
1414 - (cause) =>
1415 - new ProviderAdapter.ProviderAdapterOpenSessionError({
1416 - driver: CODEX_PROVIDER,
1417 - providerSessionId: input.providerSessionId,
1418 - cause,
1419 - }),
1420 - ),
1421 - );
1422 - const context = yield* Layer.build(CodexClient.layerChildProcess(handle, options));
1423 - return yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
1424 - Effect.provide(context),
1425 - );
1426 - }),
1402 + open: Effect.fn("CodexAdapterV2.open")(function* (input) {
1403 + const scope = yield* Scope.Scope;
1404 + const command = yield* makeCodexAppServerSpawnCommand({
1405 + command: options.command,
1406 + args: [...(options.args ?? [])],
1407 + ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
1408 + ...(options.env === undefined ? {} : { env: options.env, extendEnv: true }),
1409 + });
1410 + const handle = yield* spawner.spawn(command).pipe(
1411 + Effect.provideService(Scope.Scope, scope),
1412 + Effect.mapError(
1413 + (cause) =>
1414 + new ProviderAdapter.ProviderAdapterOpenSessionError({
1415 + driver: CODEX_PROVIDER,
1416 + providerSessionId: input.providerSessionId,
1417 + cause,
1418 + }),
1419 + ),
1420 + );
1421 + const context = yield* Layer.build(CodexClient.layerChildProcess(handle, options));
1422 + return yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
1423 + Effect.provide(context),
1424 + );
1425 + }),
1426 });
1427 }),
1428 );
@@ -1514,50 +1513,49 @@ export const layerAppServerClientFactory: Layer.Layer<
1513 const agentScope = yield* AgentScope;
1514
1515 return CodexAppServerClientFactory.of({
1517 - open: (input) =>
1518 - Effect.gen(function* () {
1519 - const scope = yield* Scope.Scope;
1520 - const environment = {
1521 - ...codexAppServerEnvironment(input.environment),
1522 - ...(input.settings.homePath ? { CODEX_HOME: input.settings.homePath } : {}),
1523 - };
1524 - const command = yield* makeCodexAppServerSpawnCommand({
1525 - command: input.settings.binaryPath || "codex",
1526 - args: codexAppServerArgs(
1527 - resolveCodexLaunchArgs(input.settings.launchArgs, input.environment),
1528 - ),
1529 - env: environment,
1530 - threadId: input.threadId,
1531 - }).pipe(Effect.provideService(AgentScope, agentScope));
1532 - const handle = yield* spawner.spawn(command).pipe(
1533 - Effect.provideService(Scope.Scope, scope),
1534 - Effect.mapError(
1535 - (cause) =>
1536 - new ProviderAdapter.ProviderAdapterOpenSessionError({
1537 - driver: CODEX_PROVIDER,
1538 - providerSessionId: input.providerSessionId,
1539 - cause,
1540 - }),
1541 - ),
1542 - );
1543 - const protocolLogger = makeCodexAppServerProtocolLogger({
1544 - nativeEventLogger,
1545 - threadId: input.threadId,
1546 - providerSessionId: input.providerSessionId,
1547 - });
1548 - const clientOptions: CodexClient.CodexAppServerClientOptions =
1549 - protocolLogger === undefined
1550 - ? {}
1551 - : {
1552 - logIncoming: true,
1553 - logOutgoing: true,
1554 - logger: protocolLogger,
1555 - };
1556 - const context = yield* Layer.build(CodexClient.layerChildProcess(handle, clientOptions));
1557 - return yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
1558 - Effect.provide(context),
1559 - );
1560 - }),
1516 + open: Effect.fn("CodexAdapterV2.open")(function* (input) {
1517 + const scope = yield* Scope.Scope;
1518 + const environment = {
1519 + ...codexAppServerEnvironment(input.environment),
1520 + ...(input.settings.homePath ? { CODEX_HOME: input.settings.homePath } : {}),
1521 + };
1522 + const command = yield* makeCodexAppServerSpawnCommand({
1523 + command: input.settings.binaryPath || "codex",
1524 + args: codexAppServerArgs(
1525 + resolveCodexLaunchArgs(input.settings.launchArgs, input.environment),
1526 + ),
1527 + env: environment,
1528 + threadId: input.threadId,
1529 + }).pipe(Effect.provideService(AgentScope, agentScope));
1530 + const handle = yield* spawner.spawn(command).pipe(
1531 + Effect.provideService(Scope.Scope, scope),
1532 + Effect.mapError(
1533 + (cause) =>
1534 + new ProviderAdapter.ProviderAdapterOpenSessionError({
1535 + driver: CODEX_PROVIDER,
1536 + providerSessionId: input.providerSessionId,
1537 + cause,
1538 + }),
1539 + ),
1540 + );
1541 + const protocolLogger = makeCodexAppServerProtocolLogger({
1542 + nativeEventLogger,
1543 + threadId: input.threadId,
1544 + providerSessionId: input.providerSessionId,
1545 + });
1546 + const clientOptions: CodexClient.CodexAppServerClientOptions =
1547 + protocolLogger === undefined
1548 + ? {}
1549 + : {
1550 + logIncoming: true,
1551 + logOutgoing: true,
1552 + logger: protocolLogger,
1553 + };
1554 + const context = yield* Layer.build(CodexClient.layerChildProcess(handle, clientOptions));
1555 + return yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
1556 + Effect.provide(context),
1557 + );
1558 + }),
1559 });
1560 }),
1561 );
@@ -1571,52 +1569,51 @@ export type CodexAdapterV2DriverEnv =
1569 | Path.Path
1570 | ServerConfig;
1571
1574 -export const createCodexAdapterV2 = (
1572 +export const createCodexAdapterV2 = Effect.fn("CodexAdapterV2.createCodexAdapterV2")(function* (
1573 { instanceId, environment, enabled, config }: ProviderAdapterDriverCreateInput<CodexSettings>,
1574 hooks: Pick<CodexAdapterV2Options, "onUsageLimits" | "resolveRuntime"> = {},
1577 -) =>
1578 - Effect.gen(function* () {
1579 - const clientFactory = yield* CodexAppServerClientFactory;
1580 - const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
1581 - const crypto = yield* Crypto.Crypto;
1582 - const fileSystem = yield* FileSystem.FileSystem;
1583 - const hostEnvironment = yield* HostProcess.Environment;
1584 - const idAllocator = yield* IdAllocator.IdAllocatorV2;
1585 - const serverConfig = yield* ServerConfig;
1586 - const homeLayout = yield* resolveCodexHomeLayout(config);
1587 -
1588 - yield* materializeCodexShadowHome(homeLayout).pipe(
1589 - Effect.mapError(
1590 - (cause) =>
1591 - new ProviderAdapterDriverCreateError({
1592 - driver: CODEX_DRIVER_KIND,
1593 - instanceId,
1594 - detail: "Failed to materialize the Codex shadow home.",
1595 - cause,
1596 - }),
1597 - ),
1598 - );
1599 -
1600 - const settings = {
1601 - ...config,
1602 - enabled,
1603 - binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),
1604 - homePath: homeLayout.effectiveHomePath ?? "",
1605 - } satisfies CodexSettings;
1575 +) {
1576 + const clientFactory = yield* CodexAppServerClientFactory;
1577 + const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
1578 + const crypto = yield* Crypto.Crypto;
1579 + const fileSystem = yield* FileSystem.FileSystem;
1580 + const hostEnvironment = yield* HostProcess.Environment;
1581 + const idAllocator = yield* IdAllocator.IdAllocatorV2;
1582 + const serverConfig = yield* ServerConfig;
1583 + const homeLayout = yield* resolveCodexHomeLayout(config);
1584 +
1585 + yield* materializeCodexShadowHome(homeLayout).pipe(
1586 + Effect.mapError(
1587 + (cause) =>
1588 + new ProviderAdapterDriverCreateError({
1589 + driver: CODEX_DRIVER_KIND,
1590 + instanceId,
1591 + detail: "Failed to materialize the Codex shadow home.",
1592 + cause,
1593 + }),
1594 + ),
1595 + );
1596
1607 - return yield* makeCodexAdapterV2({
1608 - instanceId,
1609 - settings,
1610 - environment: yield* mergeProviderInstanceEnvironment(environment, hostEnvironment),
1611 - clientFactory,
1612 - crypto,
1613 - fileSystem,
1614 - idAllocator,
1615 - serverConfig,
1616 - continuationRequests,
1617 - ...hooks,
1618 - });
1597 + const settings = {
1598 + ...config,
1599 + enabled,
1600 + binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),
1601 + homePath: homeLayout.effectiveHomePath ?? "",
1602 + } satisfies CodexSettings;
1603 +
1604 + return yield* makeCodexAdapterV2({
1605 + instanceId,
1606 + settings,
1607 + environment: yield* mergeProviderInstanceEnvironment(environment, hostEnvironment),
1608 + clientFactory,
1609 + crypto,
1610 + fileSystem,
1611 + idAllocator,
1612 + serverConfig,
1613 + continuationRequests,
1614 + ...hooks,
1615 });
1616 +});
1617
1618 export const CodexAdapterV2Driver: ProviderAdapterDriver<CodexSettings, CodexAdapterV2DriverEnv> = {
1619 driverKind: CODEX_DRIVER_KIND,
@@ -1695,8 +1692,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
1692 driver: CODEX_PROVIDER,
1693 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
1694 planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()),
1698 - openSession: (input) =>
1699 - Effect.gen(function* () {
1695 + openSession: Effect.fn("CodexAdapterV2.openSession")(
1696 + function* (input) {
1697 const scope = yield* Scope.Scope;
1698 const resolvedRuntime =
1699 adapterOptions.resolveRuntime === undefined
@@ -1727,8 +1724,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
1724 );
1725 // Codex drops client developer messages during compaction but only
1726 // resends additionalContext when it changes.
1730 - const restoreAdditionalContext = (threadId: string) =>
1731 - Effect.gen(function* () {
1727 + const restoreAdditionalContext = Effect.fn("CodexAdapterV2.restoreAdditionalContext")(
1728 + function* (threadId: string) {
1729 const context = (yield* Ref.get(additionalContextByThread)).get(threadId);
1730 if (!context) return;
1731 yield* client.request("thread/inject_items", {
@@ -1752,14 +1749,14 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
1749 },
1750 ),
1751 });
1755 - }).pipe(
1756 - Effect.timeout("10 seconds"),
1757 - Effect.catch((cause) =>
1758 - Effect.logWarning("Failed to restore Codex additional context after compaction.", {
1759 - cause,
1760 - }),
1761 - ),
1762 - );
1752 + },
1753 + Effect.timeout("10 seconds"),
1754 + Effect.catch((cause) =>
1755 + Effect.logWarning("Failed to restore Codex additional context after compaction.", {
1756 + cause,
1757 + }),
1758 + ),
1759 + );
1760 const initialized = yield* Ref.make(false);
1761 // Threads share this app-server, and Codex rejects a second
1762 // `initialize`.
@@ -1981,102 +1978,101 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
1978 });
1979 });
1980
1984 - const registerRootTurn = (input: {
1981 + const registerRootTurn = Effect.fn("CodexAdapterV2.registerRootTurn")(function* (input: {
1982 readonly turnInput: ProviderAdapter.ProviderAdapterV2TurnInput;
1983 readonly nativeTurnId: string;
1984 readonly startedAt: DateTime.Utc;
1985 readonly waitForNativeStart?: boolean;
1989 - }) =>
1990 - Effect.gen(function* () {
1991 - const existing = (yield* Ref.get(activeTurns)).get(input.nativeTurnId);
1992 - if (existing !== undefined) {
1993 - return existing;
1994 - }
1995 - const providerTurnId = idAllocator.derive.providerTurn({
1996 - driver: CODEX_PROVIDER,
1997 - nativeTurnId: input.nativeTurnId,
1998 - });
1999 - const context: ActiveCodexTurnContext = {
2000 - ...(input.waitForNativeStart
2001 - ? { nativeStartReady: yield* Deferred.make<void>() }
2002 - : {}),
2003 - input: input.turnInput,
2004 - projectionAppThread: input.turnInput.appThread,
2005 - projectionThreadId: input.turnInput.threadId,
2006 - projectionRunId: input.turnInput.runId,
2007 - nativeTurnId: input.nativeTurnId,
2008 - providerThread: input.turnInput.providerThread,
2009 - providerTurnId,
2010 - providerTurnOrdinal: input.turnInput.providerTurnOrdinal,
2011 - providerNodeId: input.turnInput.rootNodeId,
2012 - providerNodeKind: "root_turn",
2013 - providerNodeStartedAt: input.startedAt,
2014 - itemParentNodeId: input.turnInput.rootNodeId,
2015 - rootNodeId: input.turnInput.rootNodeId,
2016 - subagent: null,
2017 - startedAt: input.startedAt,
2018 - itemPositions: new Map(),
2019 - fileChangeKindsByItem: new Map(),
2020 - };
2021 - yield* Ref.update(limitedTurnItems, (current) => {
2022 - const next = new Map(current);
2023 - next.delete(context.providerThread.id);
2024 - return next;
2025 - });
2026 - beginTurnTokenUsage(context);
2027 - endSessionApprovalsOnModeChange(context);
2028 - yield* Ref.update(activeTurns, (current) => {
2029 - const updated = new Map(current);
2030 - updated.set(input.nativeTurnId, context);
2031 - return updated;
2032 - });
2033 - yield* emitProviderEvent({
2034 - type: "provider_turn.updated",
2035 - driver: CODEX_PROVIDER,
2036 - threadId: input.turnInput.threadId,
2037 - providerTurn: {
2038 - id: providerTurnId,
2039 - providerThreadId: input.turnInput.providerThread.id,
2040 - nodeId: input.turnInput.rootNodeId,
2041 - runAttemptId: input.turnInput.attemptId,
2042 - nativeTurnRef: {
2043 - driver: CODEX_PROVIDER,
2044 - nativeId: input.nativeTurnId,
2045 - strength: "strong",
2046 - },
2047 - ordinal: input.turnInput.providerTurnOrdinal,
2048 - status: "running",
2049 - startedAt: input.startedAt,
2050 - completedAt: null,
1986 + }) {
1987 + const existing = (yield* Ref.get(activeTurns)).get(input.nativeTurnId);
1988 + if (existing !== undefined) {
1989 + return existing;
1990 + }
1991 + const providerTurnId = idAllocator.derive.providerTurn({
1992 + driver: CODEX_PROVIDER,
1993 + nativeTurnId: input.nativeTurnId,
1994 + });
1995 + const context: ActiveCodexTurnContext = {
1996 + ...(input.waitForNativeStart ? { nativeStartReady: yield* Deferred.make<void>() } : {}),
1997 + input: input.turnInput,
1998 + projectionAppThread: input.turnInput.appThread,
1999 + projectionThreadId: input.turnInput.threadId,
2000 + projectionRunId: input.turnInput.runId,
2001 + nativeTurnId: input.nativeTurnId,
2002 + providerThread: input.turnInput.providerThread,
2003 + providerTurnId,
2004 + providerTurnOrdinal: input.turnInput.providerTurnOrdinal,
2005 + providerNodeId: input.turnInput.rootNodeId,
2006 + providerNodeKind: "root_turn",
2007 + providerNodeStartedAt: input.startedAt,
2008 + itemParentNodeId: input.turnInput.rootNodeId,
2009 + rootNodeId: input.turnInput.rootNodeId,
2010 + subagent: null,
2011 + startedAt: input.startedAt,
2012 + itemPositions: new Map(),
2013 + fileChangeKindsByItem: new Map(),
2014 + };
2015 + yield* Ref.update(limitedTurnItems, (current) => {
2016 + const next = new Map(current);
2017 + next.delete(context.providerThread.id);
2018 + return next;
2019 + });
2020 + beginTurnTokenUsage(context);
2021 + endSessionApprovalsOnModeChange(context);
2022 + yield* Ref.update(activeTurns, (current) => {
2023 + const updated = new Map(current);
2024 + updated.set(input.nativeTurnId, context);
2025 + return updated;
2026 + });
2027 + yield* emitProviderEvent({
2028 + type: "provider_turn.updated",
2029 + driver: CODEX_PROVIDER,
2030 + threadId: input.turnInput.threadId,
2031 + providerTurn: {
2032 + id: providerTurnId,
2033 + providerThreadId: input.turnInput.providerThread.id,
2034 + nodeId: input.turnInput.rootNodeId,
2035 + runAttemptId: input.turnInput.attemptId,
2036 + nativeTurnRef: {
2037 + driver: CODEX_PROVIDER,
2038 + nativeId: input.nativeTurnId,
2039 + strength: "strong",
2040 },
2052 - });
2053 - yield* rememberRootProviderThread(input.turnInput.providerThread);
2054 - return context;
2041 + ordinal: input.turnInput.providerTurnOrdinal,
2042 + status: "running",
2043 + startedAt: input.startedAt,
2044 + completedAt: null,
2045 + },
2046 });
2047 + yield* rememberRootProviderThread(input.turnInput.providerThread);
2048 + return context;
2049 + });
2050
2057 - const findActiveTurnByNativeThreadId = (nativeThreadId: string) =>
2058 - Effect.gen(function* () {
2051 + const findActiveTurnByNativeThreadId =
2052 + /* Provider events include streaming deltas; avoid a span for each update. */
2053 + Effect.fnUntraced(function* (nativeThreadId: string) {
2054 const turns = Array.from((yield* Ref.get(activeTurns)).values());
2055 return turns.find(
2056 (context) => context.providerThread.nativeThreadRef?.nativeId === nativeThreadId,
2057 );
2058 });
2059
2065 - const awaitActiveTurn = (
2060 + // Streaming updates repeatedly await this context, including retries before registration.
2061 + const awaitActiveTurn = Effect.fnUntraced(function* (
2062 nativeTurnId: string,
2063 attemptsRemaining = 1_000,
2068 - ): Effect.Effect<ActiveCodexTurnContext | undefined> =>
2069 - Effect.gen(function* () {
2070 - const context = (yield* Ref.get(activeTurns)).get(nativeTurnId);
2071 - if (context !== undefined || attemptsRemaining <= 0) {
2072 - return context;
2073 - }
2074 - yield* Effect.yieldNow;
2075 - return yield* awaitActiveTurn(nativeTurnId, attemptsRemaining - 1);
2076 - });
2064 + ): Effect.fn.Return<ActiveCodexTurnContext | undefined> {
2065 + const context = (yield* Ref.get(activeTurns)).get(nativeTurnId);
2066 + if (context !== undefined || attemptsRemaining <= 0) {
2067 + return context;
2068 + }
2069 + yield* Effect.yieldNow;
2070 + return yield* awaitActiveTurn(nativeTurnId, attemptsRemaining - 1);
2071 + });
2072
2078 - const resolveItemEventContext = (nativeTurnId: string) =>
2079 - Effect.gen(function* () {
2073 + const resolveItemEventContext =
2074 + /* Provider events include streaming deltas; avoid a span for each update. */
2075 + Effect.fnUntraced(function* (nativeTurnId: string) {
2076 const settled = (yield* Ref.get(settledTurns)).get(nativeTurnId);
2077 if (settled !== undefined) {
2078 return { context: settled, settled: true } as const;
@@ -2158,8 +2154,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
2154 return updated;
2155 });
2156
2161 - const turnHasRetainedBackgroundWork = (nativeTurnId: string) =>
2162 - Effect.gen(function* () {
2157 + const turnHasRetainedBackgroundWork =
2158 + /* Provider events include streaming deltas; avoid a span for each update. */
2159 + Effect.fnUntraced(function* (nativeTurnId: string) {
2160 const commands = (yield* Ref.get(runningCommandItemsByTurn)).get(nativeTurnId);
2161 if (commands !== undefined && commands.size > 0) {
2162 return true;
@@ -2179,8 +2176,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
2176 return false;
2177 });
2178
2182 - const releaseSettledTurnIfIdle = (nativeTurnId: string) =>
2183 - Effect.gen(function* () {
2179 + const releaseSettledTurnIfIdle =
2180 + /* Provider events include streaming deltas; avoid a span for each update. */
2181 + Effect.fnUntraced(function* (nativeTurnId: string) {
2182 if (yield* turnHasRetainedBackgroundWork(nativeTurnId)) {
2183 return;
2184 }
@@ -2223,105 +2221,106 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
2221 * items mid-flight (no item/completed). Emit terminal turn items before
2222 * turn.terminal so the projection never keeps a forever-running command card.
2223 */
2226 - const terminalizeRunningCommandItems = (
2224 + const terminalizeRunningCommandItems = Effect.fn(
2225 + "CodexAdapterV2.terminalizeRunningCommandItems",
2226 + )(function* (
2227 context: ActiveCodexTurnContext,
2228 nativeTurnId: string,
2229 status: "interrupted" | "failed",
2230 completedAt: DateTime.Utc,
2231 - ) =>
2232 - Effect.gen(function* () {
2233 - const items = (yield* Ref.get(runningCommandItemsByTurn)).get(nativeTurnId);
2234 - if (items === undefined || items.size === 0) {
2235 - return;
2236 - }
2237 - for (const tracked of items.values()) {
2238 - const nodeId = idAllocator.derive.nodeFromProviderItem({
2239 - driver: CODEX_PROVIDER,
2240 - nativeItemId: tracked.id,
2241 - });
2242 - const turnItemId = idAllocator.derive.turnItemFromProviderItem({
2243 - driver: CODEX_PROVIDER,
2244 - nativeItemId: tracked.id,
2245 - });
2246 - const { ordinal, startedAt } = yield* resolveItemPosition(context, tracked.id);
2247 - const node: OrchestrationV2ExecutionNode = {
2248 - id: nodeId,
2249 - threadId: context.projectionThreadId,
2250 - runId: context.projectionRunId,
2251 - parentNodeId: context.itemParentNodeId,
2252 - rootNodeId: context.rootNodeId,
2253 - kind: "tool_call",
2254 - status,
2255 - countsForRun: false,
2256 - providerThreadId: context.providerThread.id,
2257 - providerTurnId: context.providerTurnId,
2258 - nativeItemRef: codexNativeItemRef(tracked.id),
2259 - runtimeRequestId: null,
2260 - checkpointScopeId: null,
2261 - startedAt,
2262 - completedAt,
2263 - };
2264 - const turnItem: OrchestrationV2TurnItem = {
2265 - id: turnItemId,
2266 - threadId: context.projectionThreadId,
2267 - runId: context.projectionRunId,
2268 - nodeId,
2269 - providerThreadId: context.providerThread.id,
2270 - providerTurnId: context.providerTurnId,
2271 - nativeItemRef: codexNativeItemRef(tracked.id),
2272 - parentItemId: null,
2273 - ordinal,
2274 - status,
2275 - title: null,
2276 - startedAt,
2277 - completedAt,
2278 - updatedAt: completedAt,
2279 - type: "command_execution",
2280 - input: tracked.command,
2281 - ...(tracked.aggregatedOutput === undefined
2282 - ? {}
2283 - : { output: tracked.aggregatedOutput }),
2284 - };
2285 - yield* emitProviderEvent({
2286 - type: "node.updated",
2287 - driver: CODEX_PROVIDER,
2288 - node,
2289 - });
2290 - yield* emitProviderEvent({
2291 - type: "turn_item.updated",
2292 - driver: CODEX_PROVIDER,
2293 - turnItem,
2294 - });
2295 - }
2296 - });
2297 -
2298 - const terminateBackgroundTerminal = Effect.fn("CodexAdapterV2.terminateBackgroundTerminal")(
2299 - function* (nativeThreadId: string, processId: string) {
2300 - const response = yield* client.raw
2301 - .request("thread/backgroundTerminals/terminate", {
2302 - threadId: nativeThreadId,
2303 - processId,
2304 - })
2305 - .pipe(
2306 - Effect.catchTags({
2307 - CodexAppServerProcessExitedError: () => Effect.succeed({ terminated: true }),
2308 - CodexAppServerInputStreamEndedError: () => Effect.succeed({ terminated: true }),
2309 - // The thread is unloaded, as Codex does a minute after a
2310 - // settle or archive unsubscribes it. Unloading kills the
2311 - // thread's terminals, so nothing is left to stop.
2312 - CodexAppServerRequestError: (error) =>
2313 - error.code === -32600 && error.errorMessage.startsWith("thread not found:")
2314 - ? Effect.succeed({ terminated: true })
2315 - : Effect.fail(error),
2316 - }),
2317 - );
2318 - const result = yield* decodeCodexBackgroundTerminalTerminateResponse(response);
2319 - if (result.terminated) return;
2320 - let cursor: string | null = null;
2321 - while (true) {
2322 - const response: unknown = yield* client.raw.request(
2323 - "thread/backgroundTerminals/list",
2324 - {
2231 + ) {
2232 + const items = (yield* Ref.get(runningCommandItemsByTurn)).get(nativeTurnId);
2233 + if (items === undefined || items.size === 0) {
2234 + return;
2235 + }
2236 + for (const tracked of items.values()) {
2237 + const nodeId = idAllocator.derive.nodeFromProviderItem({
2238 + driver: CODEX_PROVIDER,
2239 + nativeItemId: tracked.id,
2240 + });
2241 + const turnItemId = idAllocator.derive.turnItemFromProviderItem({
2242 + driver: CODEX_PROVIDER,
2243 + nativeItemId: tracked.id,
2244 + });
2245 + const { ordinal, startedAt } = yield* resolveItemPosition(context, tracked.id);
2246 + const node: OrchestrationV2ExecutionNode = {
2247 + id: nodeId,
2248 + threadId: context.projectionThreadId,
2249 + runId: context.projectionRunId,
2250 + parentNodeId: context.itemParentNodeId,
2251 + rootNodeId: context.rootNodeId,
2252 + kind: "tool_call",
2253 + status,
2254 + countsForRun: false,
2255 + providerThreadId: context.providerThread.id,
2256 + providerTurnId: context.providerTurnId,
2257 + nativeItemRef: codexNativeItemRef(tracked.id),
2258 + runtimeRequestId: null,
2259 + checkpointScopeId: null,
2260 + startedAt,
2261 + completedAt,
2262 + };
2263 + const turnItem: OrchestrationV2TurnItem = {
2264 + id: turnItemId,
2265 + threadId: context.projectionThreadId,
2266 + runId: context.projectionRunId,
2267 + nodeId,
2268 + providerThreadId: context.providerThread.id,
2269 + providerTurnId: context.providerTurnId,
2270 + nativeItemRef: codexNativeItemRef(tracked.id),
2271 + parentItemId: null,
2272 + ordinal,
2273 + status,
2274 + title: null,
2275 + startedAt,
2276 + completedAt,
2277 + updatedAt: completedAt,
2278 + type: "command_execution",
2279 + input: tracked.command,
2280 + ...(tracked.aggregatedOutput === undefined
2281 + ? {}
2282 + : { output: tracked.aggregatedOutput }),
2283 + };
2284 + yield* emitProviderEvent({
2285 + type: "node.updated",
2286 + driver: CODEX_PROVIDER,
2287 + node,
2288 + });
2289 + yield* emitProviderEvent({
2290 + type: "turn_item.updated",
2291 + driver: CODEX_PROVIDER,
2292 + turnItem,
2293 + });
2294 + }
2295 + });
2296 +
2297 + const terminateBackgroundTerminal = Effect.fn("CodexAdapterV2.terminateBackgroundTerminal")(
2298 + function* (nativeThreadId: string, processId: string) {
2299 + const response = yield* client.raw
2300 + .request("thread/backgroundTerminals/terminate", {
2301 + threadId: nativeThreadId,
2302 + processId,
2303 + })
2304 + .pipe(
2305 + Effect.catchTags({
2306 + CodexAppServerProcessExitedError: () => Effect.succeed({ terminated: true }),
2307 + CodexAppServerInputStreamEndedError: () => Effect.succeed({ terminated: true }),
2308 + // The thread is unloaded, as Codex does a minute after a
2309 + // settle or archive unsubscribes it. Unloading kills the
2310 + // thread's terminals, so nothing is left to stop.
2311 + CodexAppServerRequestError: (error) =>
2312 + error.code === -32600 && error.errorMessage.startsWith("thread not found:")
2313 + ? Effect.succeed({ terminated: true })
2314 + : Effect.fail(error),
2315 + }),
2316 + );
2317 + const result = yield* decodeCodexBackgroundTerminalTerminateResponse(response);
2318 + if (result.terminated) return;
2319 + let cursor: string | null = null;
2320 + while (true) {
2321 + const response: unknown = yield* client.raw.request(
2322 + "thread/backgroundTerminals/list",
2323 + {
2324 threadId: nativeThreadId,
2325 ...(cursor === null ? {} : { cursor }),
2326 },
@@ -2345,69 +2344,71 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
2344 * item/completed when functions.wait terminates the cell. Persistent tools
2345 * can outlive the root turn and must stay running.
2346 */
2348 - const terminalizeRunningDynamicTools = (
2347 + const terminalizeRunningDynamicTools = Effect.fn(
2348 + "CodexAdapterV2.terminalizeRunningDynamicTools",
2349 + )(function* (
2350 context: ActiveCodexTurnContext,
2351 nativeTurnId: string,
2352 status: "cancelled" | "interrupted" | "failed",
2353 completedAt: DateTime.Utc,
2354 includePersistent: boolean,
2354 - ) =>
2355 - Effect.gen(function* () {
2356 - const items = (yield* Ref.get(runningDynamicToolsByTurn)).get(nativeTurnId);
2357 - if (items === undefined || items.size === 0) {
2358 - return;
2355 + ) {
2356 + const items = (yield* Ref.get(runningDynamicToolsByTurn)).get(nativeTurnId);
2357 + if (items === undefined || items.size === 0) {
2358 + return;
2359 + }
2360 + for (const tracked of items.values()) {
2361 + if (!includePersistent && isPersistentCodexDynamicTool(tracked)) {
2362 + continue;
2363 }
2360 - for (const tracked of items.values()) {
2361 - if (!includePersistent && isPersistentCodexDynamicTool(tracked)) {
2362 - continue;
2363 - }
2364 - const artifacts = yield* buildDynamicToolArtifacts(context, tracked);
2365 - yield* emitProviderEvent({
2366 - type: "node.updated",
2367 - driver: CODEX_PROVIDER,
2368 - node: {
2369 - ...artifacts.node,
2370 - status,
2371 - completedAt,
2372 - },
2373 - });
2374 - yield* emitProviderEvent({
2375 - type: "turn_item.updated",
2376 - driver: CODEX_PROVIDER,
2377 - turnItem: {
2378 - ...artifacts.turnItem,
2379 - status,
2380 - completedAt,
2381 - updatedAt: completedAt,
2382 - },
2383 - });
2364 + const artifacts = yield* buildDynamicToolArtifacts(context, tracked);
2365 + yield* emitProviderEvent({
2366 + type: "node.updated",
2367 + driver: CODEX_PROVIDER,
2368 + node: {
2369 + ...artifacts.node,
2370 + status,
2371 + completedAt,
2372 + },
2373 + });
2374 + yield* emitProviderEvent({
2375 + type: "turn_item.updated",
2376 + driver: CODEX_PROVIDER,
2377 + turnItem: {
2378 + ...artifacts.turnItem,
2379 + status,
2380 + completedAt,
2381 + updatedAt: completedAt,
2382 + },
2383 + });
2384 + }
2385 + yield* Ref.update(runningDynamicToolsByTurn, (current) => {
2386 + if (!current.has(nativeTurnId)) {
2387 + return current;
2388 }
2385 - yield* Ref.update(runningDynamicToolsByTurn, (current) => {
2386 - if (!current.has(nativeTurnId)) {
2387 - return current;
2389 + const remaining = new Map(current.get(nativeTurnId) ?? []);
2390 + for (const tracked of remaining.values()) {
2391 + if (includePersistent || !isPersistentCodexDynamicTool(tracked)) {
2392 + remaining.delete(tracked.id);
2393 }
2389 - const remaining = new Map(current.get(nativeTurnId) ?? []);
2390 - for (const tracked of remaining.values()) {
2391 - if (includePersistent || !isPersistentCodexDynamicTool(tracked)) {
2392 - remaining.delete(tracked.id);
2393 - }
2394 - }
2395 - const updated = new Map(current);
2396 - if (remaining.size === 0) {
2397 - updated.delete(nativeTurnId);
2398 - } else {
2399 - updated.set(nativeTurnId, remaining);
2400 - }
2401 - return updated;
2402 - });
2394 + }
2395 + const updated = new Map(current);
2396 + if (remaining.size === 0) {
2397 + updated.delete(nativeTurnId);
2398 + } else {
2399 + updated.set(nativeTurnId, remaining);
2400 + }
2401 + return updated;
2402 });
2403 + });
2404
2405 - const resolveItemPosition = (
2406 - context: ActiveCodexTurnContext,
2407 - nativeItemId: string,
2408 - startedAt?: DateTime.Utc,
2409 - ) =>
2410 - Effect.gen(function* () {
2405 + const resolveItemPosition =
2406 + /* Provider events include streaming deltas; avoid a span for each update. */
2407 + Effect.fnUntraced(function* (
2408 + context: ActiveCodexTurnContext,
2409 + nativeItemId: string,
2410 + startedAt?: DateTime.Utc,
2411 + ) {
2412 // Read the clock first so the lookup and the insert run without yielding.
2413 const now = startedAt ?? (yield* DateTime.now);
2414 const existing = context.itemPositions.get(nativeItemId);
@@ -2439,15 +2440,16 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
2440 return [next, updated];
2441 });
2442
2442 - const emitSubagentTaskUpdate = (input: {
2443 - readonly subagent: CodexSubagentThreadContext;
2444 - readonly status: OrchestrationV2Subagent["status"];
2445 - readonly result?: string | null;
2446 - readonly completedAt?: DateTime.Utc | null;
2447 - readonly startedAt?: DateTime.Utc;
2448 - readonly reopen?: boolean;
2449 - }) =>
2450 - Effect.gen(function* () {
2443 + const emitSubagentTaskUpdate =
2444 + /* Provider events include streaming deltas; avoid a span for each update. */
2445 + Effect.fnUntraced(function* (input: {
2446 + readonly subagent: CodexSubagentThreadContext;
2447 + readonly status: OrchestrationV2Subagent["status"];
2448 + readonly result?: string | null;
2449 + readonly completedAt?: DateTime.Utc | null;
2450 + readonly startedAt?: DateTime.Utc;
2451 + readonly reopen?: boolean;
2452 + }) {
2453 const now = yield* DateTime.now;
2454 const prior = input.subagent.task;
2455 const settled = !isOrchestrationV2WorkActive(prior.status);
@@ -2510,11 +2512,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
2512 });
2513 });
2514
2513 - const emitSubagentProviderTurnStarted = (
2514 - subagent: CodexSubagentThreadContext,
2515 - turn: PendingCodexSubagentTurnStarted,
2516 - ) =>
2517 - Effect.gen(function* () {
2515 + const emitSubagentProviderTurnStarted =
2516 + /* Provider events include streaming deltas; avoid a span for each update. */
2517 + Effect.fnUntraced(function* (
2518 + subagent: CodexSubagentThreadContext,
2519 + turn: PendingCodexSubagentTurnStarted,
2520 + ) {
2521 if (subagent.nativeTurnIds.has(turn.nativeTurnId)) return;
2522 subagent.nativeTurnIds.add(turn.nativeTurnId);
2523 const parentNativeThreadId = yield* getNativeThreadId(
@@ -2656,12 +2659,13 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
2659 });
2660 });
2661
2659 - const rememberSubagentTurnStarted = (input: {
2660 - readonly nativeThreadId: string;
2661 - readonly nativeTurnId: string;
2662 - readonly startedAt: DateTime.Utc;
2663 - }) =>
2664 - Effect.gen(function* () {
2662 + const rememberSubagentTurnStarted =
2663 + /* Provider events include streaming deltas; avoid a span for each update. */
2664 + Effect.fnUntraced(function* (input: {
2665 + readonly nativeThreadId: string;
2666 + readonly nativeTurnId: string;
2667 + readonly startedAt: DateTime.Utc;
2668 + }) {
2669 const subagent = (yield* Ref.get(subagentThreads)).get(input.nativeThreadId);
2670 if (subagent !== undefined) {
2671 yield* emitSubagentProviderTurnStarted(subagent, input);
@@ -2729,19 +2733,20 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
2733 });
2734 });
2735
2732 - const registerSubagentThread = (input: {
2733 - readonly context: ActiveCodexTurnContext;
2734 - readonly nativeThreadId: string;
2735 - readonly nativeItemId: string;
2736 - readonly nativeToolCallId: string;
2737 - readonly prompt: string;
2738 - readonly title: string | null;
2739 - readonly model: string | null;
2740 - readonly reasoningEffort?: string | null | undefined;
2741 - readonly ordinal: number;
2742 - readonly emitInitialPrompt: boolean;
2743 - }) =>
2744 - Effect.gen(function* () {
2736 + const registerSubagentThread =
2737 + /* Provider events include streaming deltas; avoid a span for each update. */
2738 + Effect.fnUntraced(function* (input: {
2739 + readonly context: ActiveCodexTurnContext;
2740 + readonly nativeThreadId: string;
2741 + readonly nativeItemId: string;
2742 + readonly nativeToolCallId: string;
2743 + readonly prompt: string;
2744 + readonly title: string | null;
2745 + readonly model: string | null;
2746 + readonly reasoningEffort?: string | null | undefined;
2747 + readonly ordinal: number;
2748 + readonly emitInitialPrompt: boolean;
2749 + }) {
2750 const registeredSubagents = yield* Ref.get(subagentThreads);
2751 if (registeredSubagents.has(input.nativeThreadId)) {
2752 return;
@@ -3009,11 +3014,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
3014 }
3015 });
3016
3012 - const registerSubagentThreads = (input: {
3013 - readonly context: ActiveCodexTurnContext;
3014 - readonly item: CodexCollabAgentToolCallItem;
3015 - }) =>
3016 - Effect.gen(function* () {
3017 + const registerSubagentThreads =
3018 + /* Provider events include streaming deltas; avoid a span for each update. */
3019 + Effect.fnUntraced(function* (input: {
3020 + readonly context: ActiveCodexTurnContext;
3021 + readonly item: CodexCollabAgentToolCallItem;
3022 + }) {
3023 if (input.item.tool !== "spawnAgent" || input.item.receiverThreadIds.length === 0) {
3024 return;
3025 }
@@ -3038,11 +3044,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
3044 }
3045 });
3046
3041 - const registerSubagentActivity = (input: {
3042 - readonly context?: ActiveCodexTurnContext;
3043 - readonly item: CodexSubAgentActivityItem;
3044 - }) =>
3045 - Effect.gen(function* () {
3047 + const registerSubagentActivity =
3048 + /* Provider events include streaming deltas; avoid a span for each update. */
3049 + Effect.fnUntraced(function* (input: {
3050 + readonly context?: ActiveCodexTurnContext;
3051 + readonly item: CodexSubAgentActivityItem;
3052 + }) {
3053 if (input.item.kind === "started") {
3054 const context = input.context;
3055 if (context === undefined) return;
@@ -3078,8 +3085,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
3085 }
3086 });
3087
3081 - const updateSubagentStates = (input: { readonly item: CodexCollabAgentToolCallItem }) =>
3082 - Effect.gen(function* () {
3088 + const updateSubagentStates =
3089 + /* Provider events include streaming deltas; avoid a span for each update. */
3090 + Effect.fnUntraced(function* (input: { readonly item: CodexCollabAgentToolCallItem }) {
3091 const subagents = yield* Ref.get(subagentThreads);
3092 for (const [nativeThreadId, state] of Object.entries(input.item.agentsStates)) {
3093 const subagent = subagents.get(nativeThreadId);
@@ -3107,8 +3115,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
3115 }
3116 });
3117
3110 - const resolvePlanId = (context: ActiveCodexTurnContext, planKey: string) =>
3111 - Effect.gen(function* () {
3118 + const resolvePlanId =
3119 + /* Provider events include streaming deltas; avoid a span for each update. */
3120 + Effect.fnUntraced(function* (context: ActiveCodexTurnContext, planKey: string) {
3121 const existing = (yield* Ref.get(planIds)).get(planKey);
3122 if (existing !== undefined) {
3123 return existing;
@@ -3126,8 +3135,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
3135 return planId;
3136 });
3137
3129 - const resolveCodexAttachment = (attachment: ChatAttachment) =>
3130 - Effect.gen(function* () {
3138 + const resolveCodexAttachment = Effect.fn("CodexAdapterV2.resolveCodexAttachment")(
3139 + function* (attachment: ChatAttachment) {
3140 const attachmentPath = resolveAttachmentPath({
3141 attachmentsDir: serverConfig.attachmentsDir,
3142 attachment,
@@ -3150,115 +3159,115 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
3159 type: "image" as const,
3160 url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`,
3161 } satisfies CodexSchema.V2TurnStartParams__UserInput;
3153 - });
3162 + },
3163 + );
3164
3155 - const toCodexInput = (
3165 + const toCodexInput = Effect.fn("CodexAdapterV2.toCodexInput")(function* (
3166 turnInput: Pick<
3167 | ProviderAdapter.ProviderAdapterV2TurnInput
3168 | ProviderAdapter.ProviderAdapterV2SteerInput,
3169 "message"
3170 >,
3161 - ) =>
3162 - Effect.gen(function* () {
3163 - const inputItems: Array<CodexSchema.V2TurnStartParams__UserInput> = [];
3164 - const text = providerMessageTextWithAttachmentPaths({
3165 - text: codexSkillMentionText(turnInput.message.text),
3166 - attachments: turnInput.message.attachments,
3167 - resolveAttachmentPath: (attachment) =>
3168 - resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, attachment }),
3169 - });
3170 - if (text.length > 0) {
3171 - inputItems.push({
3172 - type: "text",
3173 - text,
3174 - });
3175 - }
3176 - const attachmentItems = yield* Effect.forEach(
3177 - turnInput.message.attachments.filter(isProviderNativeImageAttachment),
3178 - resolveCodexAttachment,
3179 - { concurrency: 1 },
3180 - );
3181 - inputItems.push(...attachmentItems);
3182 - if (inputItems.length === 0) {
3183 - return yield* toProtocolError("Turn requires non-empty text or attachments.");
3184 - }
3185 - return inputItems;
3171 + ) {
3172 + const inputItems: Array<CodexSchema.V2TurnStartParams__UserInput> = [];
3173 + const text = providerMessageTextWithAttachmentPaths({
3174 + text: codexSkillMentionText(turnInput.message.text),
3175 + attachments: turnInput.message.attachments,
3176 + resolveAttachmentPath: (attachment) =>
3177 + resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, attachment }),
3178 });
3179 + if (text.length > 0) {
3180 + inputItems.push({
3181 + type: "text",
3182 + text,
3183 + });
3184 + }
3185 + const attachmentItems = yield* Effect.forEach(
3186 + turnInput.message.attachments.filter(isProviderNativeImageAttachment),
3187 + resolveCodexAttachment,
3188 + { concurrency: 1 },
3189 + );
3190 + inputItems.push(...attachmentItems);
3191 + if (inputItems.length === 0) {
3192 + return yield* toProtocolError("Turn requires non-empty text or attachments.");
3193 + }
3194 + return inputItems;
3195 + });
3196
3188 - const buildAgentMessageArtifacts = (
3197 + // Reasoning and assistant-text coalescers build these artifacts on every streamed update.
3198 + const buildAgentMessageArtifacts = Effect.fnUntraced(function* (
3199 context: ActiveCodexTurnContext,
3200 item: { readonly id: string; readonly text: string },
3201 completed: boolean,
3192 - ) =>
3193 - Effect.gen(function* () {
3194 - const updatedAt = yield* DateTime.now;
3195 - const completedAt = completed ? updatedAt : null;
3196 - const nodeId = idAllocator.derive.nodeFromProviderItem({
3197 - driver: CODEX_PROVIDER,
3198 - nativeItemId: item.id,
3199 - });
3200 - const { ordinal, startedAt } = yield* resolveItemPosition(context, item.id);
3201 - const messageId = idAllocator.derive.messageFromProviderItem({
3202 - driver: CODEX_PROVIDER,
3203 - nativeItemId: item.id,
3204 - });
3205 - const turnItemId = idAllocator.derive.turnItemFromProviderItem({
3206 - driver: CODEX_PROVIDER,
3207 - nativeItemId: item.id,
3208 - });
3209 - const node: OrchestrationV2ExecutionNode = {
3210 - id: nodeId,
3211 - threadId: context.projectionThreadId,
3212 - runId: context.projectionRunId,
3213 - parentNodeId: context.itemParentNodeId,
3214 - rootNodeId: context.rootNodeId,
3215 - kind: "assistant_message",
3216 - status: completed ? "completed" : "running",
3217 - countsForRun: false,
3218 - providerThreadId: context.providerThread.id,
3219 - providerTurnId: context.providerTurnId,
3220 - nativeItemRef: codexNativeItemRef(item.id),
3221 - runtimeRequestId: null,
3222 - checkpointScopeId: null,
3223 - startedAt,
3224 - completedAt,
3225 - };
3226 - const message: OrchestrationV2ConversationMessage = {
3227 - createdBy: "agent",
3228 - creationSource: "provider",
3229 - id: messageId,
3230 - threadId: context.projectionThreadId,
3231 - runId: context.projectionRunId,
3232 - nodeId,
3233 - role: "assistant",
3234 - text: item.text,
3235 - attachments: [],
3236 - streaming: !completed,
3237 - createdAt: startedAt,
3238 - updatedAt,
3239 - };
3240 - const turnItem: OrchestrationV2TurnItem = {
3241 - id: turnItemId,
3242 - threadId: context.projectionThreadId,
3243 - runId: context.projectionRunId,
3244 - nodeId,
3245 - providerThreadId: context.providerThread.id,
3246 - providerTurnId: context.providerTurnId,
3247 - nativeItemRef: codexNativeItemRef(item.id),
3248 - parentItemId: null,
3249 - ordinal,
3250 - status: completed ? "completed" : "running",
3251 - title: null,
3252 - startedAt,
3253 - completedAt,
3254 - updatedAt,
3255 - type: "assistant_message",
3256 - messageId,
3257 - text: item.text,
3258 - streaming: !completed,
3259 - };
3260 - return { node, message, turnItem };
3202 + ) {
3203 + const updatedAt = yield* DateTime.now;
3204 + const completedAt = completed ? updatedAt : null;
3205 + const nodeId = idAllocator.derive.nodeFromProviderItem({
3206 + driver: CODEX_PROVIDER,
3207 + nativeItemId: item.id,
3208 });
3209 + const { ordinal, startedAt } = yield* resolveItemPosition(context, item.id);
3210 + const messageId = idAllocator.derive.messageFromProviderItem({
3211 + driver: CODEX_PROVIDER,
3212 + nativeItemId: item.id,
3213 + });
3214 + const turnItemId = idAllocator.derive.turnItemFromProviderItem({
3215 + driver: CODEX_PROVIDER,
3216 + nativeItemId: item.id,
3217 + });
3218 + const node: OrchestrationV2ExecutionNode = {
3219 + id: nodeId,
3220 + threadId: context.projectionThreadId,
3221 + runId: context.projectionRunId,
3222 + parentNodeId: context.itemParentNodeId,
3223 + rootNodeId: context.rootNodeId,
3224 + kind: "assistant_message",
3225 + status: completed ? "completed" : "running",
3226 + countsForRun: false,
3227 + providerThreadId: context.providerThread.id,
3228 + providerTurnId: context.providerTurnId,
3229 + nativeItemRef: codexNativeItemRef(item.id),
3230 + runtimeRequestId: null,
3231 + checkpointScopeId: null,
3232 + startedAt,
3233 + completedAt,
3234 + };
3235 + const message: OrchestrationV2ConversationMessage = {
3236 + createdBy: "agent",
3237 + creationSource: "provider",
3238 + id: messageId,
3239 + threadId: context.projectionThreadId,
3240 + runId: context.projectionRunId,
3241 + nodeId,
3242 + role: "assistant",
3243 + text: item.text,
3244 + attachments: [],
3245 + streaming: !completed,
3246 + createdAt: startedAt,
3247 + updatedAt,
3248 + };
3249 + const turnItem: OrchestrationV2TurnItem = {
3250 + id: turnItemId,
3251 + threadId: context.projectionThreadId,
3252 + runId: context.projectionRunId,
3253 + nodeId,
3254 + providerThreadId: context.providerThread.id,
3255 + providerTurnId: context.providerTurnId,
3256 + nativeItemRef: codexNativeItemRef(item.id),
3257 + parentItemId: null,
3258 + ordinal,
3259 + status: completed ? "completed" : "running",
3260 + title: null,
3261 + startedAt,
3262 + completedAt,
3263 + updatedAt,
3264 + type: "assistant_message",
3265 + messageId,
3266 + text: item.text,
3267 + streaming: !completed,
3268 + };
3269 + return { node, message, turnItem };
3270 + });
3271
3272 // Reuse the text coalescer so token bursts do not create one database write per token.
3273 const reasoningParts = new Map<
@@ -3267,8 +3276,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
3276 >();
3277 const reasoningDeltas = yield* makeProviderTextDeltaCoalescer({
3278 flushIntervalMs: CODEX_ASSISTANT_DELTA_FLUSH_INTERVAL_MS,
3270 - emit: (update) =>
3271 - Effect.gen(function* () {
3279 + emit:
3280 + /* Provider events include streaming deltas; avoid a span for each update. */
3281 + Effect.fnUntraced(function* (update) {
3282 const part = reasoningParts.get(update.itemId);
3283 if (part === undefined) return;
3284 const context = yield* awaitActiveTurn(update.turnId);
@@ -3352,8 +3362,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
3362
3363 const agentMessageDeltas = yield* makeProviderTextDeltaCoalescer({
3364 flushIntervalMs: CODEX_ASSISTANT_DELTA_FLUSH_INTERVAL_MS,
3355 - emit: (update) =>
3356 - Effect.gen(function* () {
3365 + emit:
3366 + /* Provider events include streaming deltas; avoid a span for each update. */
3367 + Effect.fnUntraced(function* (update) {
3368 const context = yield* awaitActiveTurn(update.turnId);
3369 if (context === undefined) {
3370 return;
@@ -3414,16 +3425,17 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
3425 }),
3426 });
3427
3417 - const emitSubagentUserMessage = (
3418 - context: ActiveCodexTurnContext,
3419 - item: Extract<
3420 - | CodexSchema.V2ItemStartedNotification__ThreadItem
3421 - | CodexSchema.V2ItemCompletedNotification__ThreadItem,
3422 - { type: "userMessage" }
3423 - >,
3424 - nativeStartedAt?: DateTime.Utc,
3425 - ) =>
3426 - Effect.gen(function* () {
3428 + const emitSubagentUserMessage =
3429 + /* Provider events include streaming deltas; avoid a span for each update. */
3430 + Effect.fnUntraced(function* (
3431 + context: ActiveCodexTurnContext,
3432 + item: Extract<
3433 + | CodexSchema.V2ItemStartedNotification__ThreadItem
3434 + | CodexSchema.V2ItemCompletedNotification__ThreadItem,
3435 + { type: "userMessage" }
3436 + >,
3437 + nativeStartedAt?: DateTime.Utc,
3438 + ) {
3439 if (context.subagent === null || context.providerTurnOrdinal === 1) {
3440 return false;
3441 }
@@ -3466,82 +3478,83 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
3478 driver: CODEX_PROVIDER,
3479 turnItem: artifacts.turnItem,
3480 });
3469 - return true;
3470 - });
3471 -
3472 - const buildCommandExecutionArtifacts = (
3473 - context: ActiveCodexTurnContext,
3474 - item: Extract<
3475 - | CodexSchema.V2ItemStartedNotification__ThreadItem
3476 - | CodexSchema.V2ItemCompletedNotification__ThreadItem,
3477 - { type: "commandExecution" }
3478 - >,
3479 - ) =>
3480 - Effect.gen(function* () {
3481 - const updatedAt = yield* DateTime.now;
3482 - const status = codexItemStatus(item.status);
3483 - const completedAt = status.completed ? updatedAt : null;
3484 - const nodeId = idAllocator.derive.nodeFromProviderItem({
3485 - driver: CODEX_PROVIDER,
3486 - nativeItemId: item.id,
3487 - });
3488 - const turnItemId = idAllocator.derive.turnItemFromProviderItem({
3489 - driver: CODEX_PROVIDER,
3490 - nativeItemId: item.id,
3491 - });
3492 - const { ordinal, startedAt } = yield* resolveItemPosition(context, item.id);
3493 - const node: OrchestrationV2ExecutionNode = {
3494 - id: nodeId,
3495 - threadId: context.projectionThreadId,
3496 - runId: context.projectionRunId,
3497 - parentNodeId: context.itemParentNodeId,
3498 - rootNodeId: context.rootNodeId,
3499 - kind: "tool_call",
3500 - status: status.node,
3501 - countsForRun: false,
3502 - providerThreadId: context.providerThread.id,
3503 - providerTurnId: context.providerTurnId,
3504 - nativeItemRef: codexNativeItemRef(item.id),
3505 - runtimeRequestId: null,
3506 - checkpointScopeId: null,
3507 - startedAt,
3508 - completedAt,
3509 - };
3510 - const turnItem: OrchestrationV2TurnItem = {
3511 - id: turnItemId,
3512 - threadId: context.projectionThreadId,
3513 - runId: context.projectionRunId,
3514 - nodeId,
3515 - providerThreadId: context.providerThread.id,
3516 - providerTurnId: context.providerTurnId,
3517 - nativeItemRef: codexNativeItemRef(item.id),
3518 - parentItemId: null,
3519 - ordinal,
3520 - status: status.turnItem,
3521 - title: null,
3522 - startedAt,
3523 - completedAt,
3524 - updatedAt,
3525 - type: "command_execution",
3526 - input: item.command,
3527 - ...(item.aggregatedOutput === null || item.aggregatedOutput === undefined
3528 - ? {}
3529 - : { output: item.aggregatedOutput }),
3530 - ...(item.exitCode === null || item.exitCode === undefined
3531 - ? {}
3532 - : { exitCode: item.exitCode }),
3533 - };
3534 - return { node, turnItem };
3481 + return true;
3482 });
3483
3537 - const buildFileChangeArtifacts = (
3484 + const buildCommandExecutionArtifacts = Effect.fn(
3485 + "CodexAdapterV2.buildCommandExecutionArtifacts",
3486 + )(function* (
3487 context: ActiveCodexTurnContext,
3488 item: Extract<
3540 - CodexSchema.V2ItemCompletedNotification__ThreadItem,
3541 - { type: "fileChange" }
3489 + | CodexSchema.V2ItemStartedNotification__ThreadItem
3490 + | CodexSchema.V2ItemCompletedNotification__ThreadItem,
3491 + { type: "commandExecution" }
3492 >,
3543 - ) =>
3544 - Effect.gen(function* () {
3493 + ) {
3494 + const updatedAt = yield* DateTime.now;
3495 + const status = codexItemStatus(item.status);
3496 + const completedAt = status.completed ? updatedAt : null;
3497 + const nodeId = idAllocator.derive.nodeFromProviderItem({
3498 + driver: CODEX_PROVIDER,
3499 + nativeItemId: item.id,
3500 + });
3501 + const turnItemId = idAllocator.derive.turnItemFromProviderItem({
3502 + driver: CODEX_PROVIDER,
3503 + nativeItemId: item.id,
3504 + });
3505 + const { ordinal, startedAt } = yield* resolveItemPosition(context, item.id);
3506 + const node: OrchestrationV2ExecutionNode = {
3507 + id: nodeId,
3508 + threadId: context.projectionThreadId,
3509 + runId: context.projectionRunId,
3510 + parentNodeId: context.itemParentNodeId,
3511 + rootNodeId: context.rootNodeId,
3512 + kind: "tool_call",
3513 + status: status.node,
3514 + countsForRun: false,
3515 + providerThreadId: context.providerThread.id,
3516 + providerTurnId: context.providerTurnId,
3517 + nativeItemRef: codexNativeItemRef(item.id),
3518 + runtimeRequestId: null,
3519 + checkpointScopeId: null,
3520 + startedAt,
3521 + completedAt,
3522 + };
3523 + const turnItem: OrchestrationV2TurnItem = {
3524 + id: turnItemId,
3525 + threadId: context.projectionThreadId,
3526 + runId: context.projectionRunId,
3527 + nodeId,
3528 + providerThreadId: context.providerThread.id,
3529 + providerTurnId: context.providerTurnId,
3530 + nativeItemRef: codexNativeItemRef(item.id),
3531 + parentItemId: null,
3532 + ordinal,
3533 + status: status.turnItem,
3534 + title: null,
3535 + startedAt,
3536 + completedAt,
3537 + updatedAt,
3538 + type: "command_execution",
3539 + input: item.command,
3540 + ...(item.aggregatedOutput === null || item.aggregatedOutput === undefined
3541 + ? {}
3542 + : { output: item.aggregatedOutput }),
3543 + ...(item.exitCode === null || item.exitCode === undefined
3544 + ? {}
3545 + : { exitCode: item.exitCode }),
3546 + };
3547 + return { node, turnItem };
3548 + });
3549 +
3550 + const buildFileChangeArtifacts = Effect.fn("CodexAdapterV2.buildFileChangeArtifacts")(
3551 + function* (
3552 + context: ActiveCodexTurnContext,
3553 + item: Extract<
3554 + CodexSchema.V2ItemCompletedNotification__ThreadItem,
3555 + { type: "fileChange" }
3556 + >,
3557 + ) {
3558 const firstChange = item.changes[0];
3559 if (firstChange === undefined) {
3560 return null;
@@ -3596,14 +3609,15 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
3609 diffStr: firstChange.diff,
3610 };
3611 return { node, turnItem };
3599 - });
3612 + },
3613 + );
3614
3601 - const buildWebSearchArtifacts = (input: {
3602 - readonly context: ActiveCodexTurnContext;
3603 - readonly item: CodexWebSearchItem;
3604 - readonly completed: boolean;
3605 - }) =>
3606 - Effect.gen(function* () {
3615 + const buildWebSearchArtifacts = Effect.fn("CodexAdapterV2.buildWebSearchArtifacts")(
3616 + function* (input: {
3617 + readonly context: ActiveCodexTurnContext;
3618 + readonly item: CodexWebSearchItem;
3619 + readonly completed: boolean;
3620 + }) {
3621 const updatedAt = yield* DateTime.now;
3622 const completedAt = input.completed ? updatedAt : null;
3623 const nodeId = idAllocator.derive.nodeFromProviderItem({
@@ -3653,13 +3667,11 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
3667 ...(patterns.length === 0 ? {} : { patterns: [...patterns] }),
3668 };
3669 return { node, turnItem };
3656 - });
3670 + },
3671 + );
3672
3658 - const buildDynamicToolArtifacts = (
3659 - context: ActiveCodexTurnContext,
3660 - item: CodexDynamicToolItem,
3661 - ) =>
3662 - Effect.gen(function* () {
3673 + const buildDynamicToolArtifacts = Effect.fn("CodexAdapterV2.buildDynamicToolArtifacts")(
3674 + function* (context: ActiveCodexTurnContext, item: CodexDynamicToolItem) {
3675 const updatedAt = yield* DateTime.now;
3676 const status = codexItemStatus(item.status);
3677 const completedAt = status.completed ? updatedAt : null;
@@ -3710,36 +3722,36 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
3722 ...projection,
3723 };
3724 return { node, turnItem };
3713 - });
3725 + },
3726 + );
3727
3728 /**
3729 * The item stays running until then, which keeps the run's event
3730 * ingestion open past turn/completed; it runs off the notification
3731 * reader so a slow server cannot stall other events.
3732 */
3720 - const captureMcpApp = (
3733 + const captureMcpApp = Effect.fn("CodexAdapterV2.captureMcpApp")(function* (
3734 context: ActiveCodexTurnContext,
3735 nativeTurnId: string,
3736 item: Extract<CodexDynamicToolItem, { readonly type: "mcpToolCall" }>,
3737 resourceUri: string,
3725 - ) =>
3726 - Effect.gen(function* () {
3727 - // Registered before it can run, so a turn ending right away sees it.
3728 - const started = yield* Deferred.make<void>();
3729 - const fiber = yield* Deferred.await(started).pipe(
3730 - Effect.andThen(captureMcpAppItem(context, nativeTurnId, item, resourceUri)),
3731 - Effect.forkIn(scope, { startImmediately: true }),
3738 + ) {
3739 + // Registered before it can run, so a turn ending right away sees it.
3740 + const started = yield* Deferred.make<void>();
3741 + const fiber = yield* Deferred.await(started).pipe(
3742 + Effect.andThen(captureMcpAppItem(context, nativeTurnId, item, resourceUri)),
3743 + Effect.forkIn(scope, { startImmediately: true }),
3744 + );
3745 + yield* Ref.update(pendingMcpAppCaptures, (current) => {
3746 + const updated = new Map(current);
3747 + updated.set(
3748 + nativeTurnId,
3749 + new Map(current.get(nativeTurnId) ?? []).set(item.id, { item, fiber }),
3750 );
3733 - yield* Ref.update(pendingMcpAppCaptures, (current) => {
3734 - const updated = new Map(current);
3735 - updated.set(
3736 - nativeTurnId,
3737 - new Map(current.get(nativeTurnId) ?? []).set(item.id, { item, fiber }),
3738 - );
3739 - return updated;
3740 - });
3741 - yield* Deferred.succeed(started, undefined);
3751 + return updated;
3752 });
3753 + yield* Deferred.succeed(started, undefined);
3754 + });
3755
3756 const captureMcpAppItem = (
3757 context: ActiveCodexTurnContext,
@@ -3830,8 +3842,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
3842 }),
3843 );
3844
3833 - const terminalizeMcpAppCaptures = (context: ActiveCodexTurnContext, nativeTurnId: string) =>
3834 - Effect.gen(function* () {
3845 + const terminalizeMcpAppCaptures = Effect.fn("CodexAdapterV2.terminalizeMcpAppCaptures")(
3846 + function* (context: ActiveCodexTurnContext, nativeTurnId: string) {
3847 const captures = (yield* Ref.get(pendingMcpAppCaptures)).get(nativeTurnId);
3848 if (captures === undefined) return;
3849 for (const { item, fiber } of captures.values()) {
@@ -3849,84 +3861,86 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
3861 turnItem: artifacts.turnItem,
3862 });
3863 }
3852 - });
3864 + },
3865 + );
3866
3854 - const buildProposedPlanArtifacts = (input: {
3867 + // The plan coalescer builds these artifacts on every streamed update.
3868 + const buildProposedPlanArtifacts = Effect.fnUntraced(function* (input: {
3869 readonly context: ActiveCodexTurnContext;
3870 readonly nativeItemId: string;
3871 readonly status: OrchestrationV2PlanArtifact["status"];
3872 readonly markdown: string;
3873 readonly completed?: boolean;
3860 - }) =>
3861 - Effect.gen(function* () {
3862 - const updatedAt = yield* DateTime.now;
3863 - const completedAt = input.completed === true ? updatedAt : null;
3864 - const planId = yield* resolvePlanId(input.context, input.nativeItemId);
3865 - const nodeId = idAllocator.derive.nodeFromProviderItem({
3866 - driver: CODEX_PROVIDER,
3867 - nativeItemId: input.nativeItemId,
3868 - });
3869 - const turnItemId = idAllocator.derive.turnItemFromProviderItem({
3870 - driver: CODEX_PROVIDER,
3871 - nativeItemId: input.nativeItemId,
3872 - });
3873 - const { ordinal, startedAt } = yield* resolveItemPosition(
3874 - input.context,
3875 - input.nativeItemId,
3876 - );
3877 - const plan: OrchestrationV2PlanArtifact = {
3878 - id: planId,
3879 - threadId: input.context.projectionThreadId,
3880 - runId: input.context.projectionRunId,
3881 - nodeId,
3882 - kind: "proposed_plan",
3883 - status: input.status,
3884 - markdown: input.markdown,
3885 - };
3886 - const node: OrchestrationV2ExecutionNode = {
3887 - id: nodeId,
3888 - threadId: input.context.projectionThreadId,
3889 - runId: input.context.projectionRunId,
3890 - parentNodeId: input.context.itemParentNodeId,
3891 - rootNodeId: input.context.rootNodeId,
3892 - kind: "plan",
3893 - status: input.completed === true ? "completed" : "running",
3894 - countsForRun: false,
3895 - providerThreadId: input.context.providerThread.id,
3896 - providerTurnId: input.context.providerTurnId,
3897 - nativeItemRef: codexNativeItemRef(input.nativeItemId),
3898 - runtimeRequestId: null,
3899 - checkpointScopeId: null,
3900 - startedAt,
3901 - completedAt,
3902 - };
3903 - const turnItem: OrchestrationV2TurnItem = {
3904 - id: turnItemId,
3905 - threadId: input.context.projectionThreadId,
3906 - runId: input.context.projectionRunId,
3907 - nodeId,
3908 - providerThreadId: input.context.providerThread.id,
3909 - providerTurnId: input.context.providerTurnId,
3910 - nativeItemRef: codexNativeItemRef(input.nativeItemId),
3911 - parentItemId: null,
3912 - ordinal,
3913 - status: input.completed === true ? "completed" : "running",
3914 - title: null,
3915 - startedAt,
3916 - completedAt,
3917 - updatedAt,
3918 - type: "proposed_plan",
3919 - planId,
3920 - markdown: input.markdown,
3921 - streaming: input.completed !== true,
3922 - };
3923 - return { node, plan, turnItem };
3874 + }) {
3875 + const updatedAt = yield* DateTime.now;
3876 + const completedAt = input.completed === true ? updatedAt : null;
3877 + const planId = yield* resolvePlanId(input.context, input.nativeItemId);
3878 + const nodeId = idAllocator.derive.nodeFromProviderItem({
3879 + driver: CODEX_PROVIDER,
3880 + nativeItemId: input.nativeItemId,
3881 });
3882 + const turnItemId = idAllocator.derive.turnItemFromProviderItem({
3883 + driver: CODEX_PROVIDER,
3884 + nativeItemId: input.nativeItemId,
3885 + });
3886 + const { ordinal, startedAt } = yield* resolveItemPosition(
3887 + input.context,
3888 + input.nativeItemId,
3889 + );
3890 + const plan: OrchestrationV2PlanArtifact = {
3891 + id: planId,
3892 + threadId: input.context.projectionThreadId,
3893 + runId: input.context.projectionRunId,
3894 + nodeId,
3895 + kind: "proposed_plan",
3896 + status: input.status,
3897 + markdown: input.markdown,
3898 + };
3899 + const node: OrchestrationV2ExecutionNode = {
3900 + id: nodeId,
3901 + threadId: input.context.projectionThreadId,
3902 + runId: input.context.projectionRunId,
3903 + parentNodeId: input.context.itemParentNodeId,
3904 + rootNodeId: input.context.rootNodeId,
3905 + kind: "plan",
3906 + status: input.completed === true ? "completed" : "running",
3907 + countsForRun: false,
3908 + providerThreadId: input.context.providerThread.id,
3909 + providerTurnId: input.context.providerTurnId,
3910 + nativeItemRef: codexNativeItemRef(input.nativeItemId),
3911 + runtimeRequestId: null,
3912 + checkpointScopeId: null,
3913 + startedAt,
3914 + completedAt,
3915 + };
3916 + const turnItem: OrchestrationV2TurnItem = {
3917 + id: turnItemId,
3918 + threadId: input.context.projectionThreadId,
3919 + runId: input.context.projectionRunId,
3920 + nodeId,
3921 + providerThreadId: input.context.providerThread.id,
3922 + providerTurnId: input.context.providerTurnId,
3923 + nativeItemRef: codexNativeItemRef(input.nativeItemId),
3924 + parentItemId: null,
3925 + ordinal,
3926 + status: input.completed === true ? "completed" : "running",
3927 + title: null,
3928 + startedAt,
3929 + completedAt,
3930 + updatedAt,
3931 + type: "proposed_plan",
3932 + planId,
3933 + markdown: input.markdown,
3934 + streaming: input.completed !== true,
3935 + };
3936 + return { node, plan, turnItem };
3937 + });
3938
3939 const planDeltas = yield* makeProviderTextDeltaCoalescer({
3940 flushIntervalMs: CODEX_PLAN_DELTA_FLUSH_INTERVAL_MS,
3928 - emit: (update) =>
3929 - Effect.gen(function* () {
3941 + emit:
3942 + /* Provider events include streaming deltas; avoid a span for each update. */
3943 + Effect.fnUntraced(function* (update) {
3944 const resolved = yield* resolveItemEventContext(update.turnId);
3945 if (resolved === undefined) return;
3946 const interrupted = (yield* Ref.get(terminalizedNonCompletedNativeTurns)).has(
@@ -3955,18 +3969,18 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
3969 driver: CODEX_PROVIDER,
3970 turnItem: artifacts.turnItem,
3971 });
3958 - }).pipe(Effect.orDie),
3972 + }, Effect.orDie),
3973 });
3974
3961 - const buildTodoListArtifacts = (input: {
3962 - readonly context: ActiveCodexTurnContext;
3963 - readonly nativeItemId: string;
3964 - readonly status: OrchestrationV2PlanArtifact["status"];
3965 - readonly steps: ReadonlyArray<OrchestrationV2PlanStep>;
3966 - readonly explanation?: string;
3967 - readonly completed?: boolean;
3968 - }) =>
3969 - Effect.gen(function* () {
3975 + const buildTodoListArtifacts = Effect.fn("CodexAdapterV2.buildTodoListArtifacts")(
3976 + function* (input: {
3977 + readonly context: ActiveCodexTurnContext;
3978 + readonly nativeItemId: string;
3979 + readonly status: OrchestrationV2PlanArtifact["status"];
3980 + readonly steps: ReadonlyArray<OrchestrationV2PlanStep>;
3981 + readonly explanation?: string;
3982 + readonly completed?: boolean;
3983 + }) {
3984 const updatedAt = yield* DateTime.now;
3985 const completedAt = input.completed === true ? updatedAt : null;
3986 const planId = yield* resolvePlanId(input.context, input.nativeItemId);
@@ -4030,9 +4044,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
4044 ...(input.explanation === undefined ? {} : { explanation: input.explanation }),
4045 };
4046 return { node, plan, turnItem };
4033 - });
4047 + },
4048 + );
4049
4035 - const buildApprovalRequestArtifacts = (input: {
4050 + const buildApprovalRequestArtifacts = Effect.fn(
4051 + "CodexAdapterV2.buildApprovalRequestArtifacts",
4052 + )(function* (input: {
4053 readonly context: ActiveCodexTurnContext;
4054 readonly nativeItemId: string;
4055 readonly nativeRequestId: string;
@@ -4040,190 +4057,190 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
4057 readonly prompt?: string | null;
4058 readonly appName?: string;
4059 readonly options?: ReadonlyArray<ProviderApprovalOption>;
4043 - }) =>
4044 - Effect.gen(function* () {
4045 - const createdAt = yield* DateTime.now;
4046 - const { owner, subagent } = approvalOwnerCodexTurn(input.context);
4047 - const parentNodeId =
4048 - subagent?.subagentNodeId ??
4049 - idAllocator.derive.nodeFromProviderItem({
4050 - driver: CODEX_PROVIDER,
4051 - nativeItemId: input.nativeItemId,
4052 - });
4053 - const ordinal = yield* resolveItemOrdinal(
4054 - owner,
4055 - `${input.nativeItemId}:approval:${input.nativeRequestId}`,
4056 - );
4057 - const requestId = yield* idAllocator.allocate.runtimeRequest({
4060 + }) {
4061 + const createdAt = yield* DateTime.now;
4062 + const { owner, subagent } = approvalOwnerCodexTurn(input.context);
4063 + const parentNodeId =
4064 + subagent?.subagentNodeId ??
4065 + idAllocator.derive.nodeFromProviderItem({
4066 driver: CODEX_PROVIDER,
4059 - providerTurnId: owner.providerTurnId,
4060 - nativeRequestId: input.nativeRequestId,
4067 + nativeItemId: input.nativeItemId,
4068 });
4062 - const nodeId = idAllocator.derive.approvalNode({ requestId });
4063 - const providerSessionId = owner.input.providerThread.providerSessionId;
4064 - if (providerSessionId === null) {
4065 - return yield* toProtocolError(
4066 - `Provider thread ${owner.providerThread.id} is missing a provider session id.`,
4067 - );
4068 - }
4069 - const node: OrchestrationV2ExecutionNode = {
4070 - id: nodeId,
4071 - threadId: owner.projectionThreadId,
4072 - runId: owner.projectionRunId,
4073 - parentNodeId,
4074 - rootNodeId: owner.rootNodeId,
4075 - kind: "approval_request",
4076 - status: "waiting",
4077 - countsForRun: false,
4078 - providerThreadId: owner.providerThread.id,
4079 - providerTurnId: owner.providerTurnId,
4080 - nativeItemRef: codexNativeItemRef(input.nativeItemId),
4081 - runtimeRequestId: requestId,
4082 - checkpointScopeId: null,
4083 - startedAt: createdAt,
4084 - completedAt: null,
4085 - };
4086 - const request: OrchestrationV2RuntimeRequest = {
4087 - id: requestId,
4088 - nodeId,
4089 - providerTurnId: owner.providerTurnId,
4090 - nativeRequestRef: {
4091 - driver: CODEX_PROVIDER,
4092 - nativeId: input.nativeRequestId,
4093 - strength: "strong",
4094 - },
4095 - kind: input.requestKind,
4096 - status: "pending",
4097 - responseCapability: {
4098 - type: "live",
4099 - providerSessionId,
4100 - },
4101 - createdAt,
4102 - resolvedAt: null,
4103 - };
4104 - const turnItem: OrchestrationV2TurnItem = {
4105 - id: idAllocator.derive.approvalTurnItem({ requestId }),
4106 - threadId: owner.projectionThreadId,
4107 - runId: owner.projectionRunId,
4108 - nodeId,
4109 - providerThreadId: owner.providerThread.id,
4110 - providerTurnId: owner.providerTurnId,
4111 - nativeItemRef: codexNativeItemRef(input.nativeItemId),
4112 - parentItemId: null,
4113 - ordinal,
4114 - status: "waiting",
4115 - title: null,
4116 - startedAt: createdAt,
4117 - completedAt: null,
4118 - updatedAt: createdAt,
4119 - type: "approval_request",
4120 - requestId,
4121 - requestKind: input.requestKind,
4122 - ...(input.prompt === null || input.prompt === undefined
4123 - ? {}
4124 - : { prompt: input.prompt }),
4125 - ...(input.appName === undefined ? {} : { appName: input.appName }),
4126 - ...(input.options === undefined ? {} : { options: input.options }),
4127 - };
4128 - return { node, request, turnItem };
4069 + const ordinal = yield* resolveItemOrdinal(
4070 + owner,
4071 + `${input.nativeItemId}:approval:${input.nativeRequestId}`,
4072 + );
4073 + const requestId = yield* idAllocator.allocate.runtimeRequest({
4074 + driver: CODEX_PROVIDER,
4075 + providerTurnId: owner.providerTurnId,
4076 + nativeRequestId: input.nativeRequestId,
4077 });
4078 + const nodeId = idAllocator.derive.approvalNode({ requestId });
4079 + const providerSessionId = owner.input.providerThread.providerSessionId;
4080 + if (providerSessionId === null) {
4081 + return yield* toProtocolError(
4082 + `Provider thread ${owner.providerThread.id} is missing a provider session id.`,
4083 + );
4084 + }
4085 + const node: OrchestrationV2ExecutionNode = {
4086 + id: nodeId,
4087 + threadId: owner.projectionThreadId,
4088 + runId: owner.projectionRunId,
4089 + parentNodeId,
4090 + rootNodeId: owner.rootNodeId,
4091 + kind: "approval_request",
4092 + status: "waiting",
4093 + countsForRun: false,
4094 + providerThreadId: owner.providerThread.id,
4095 + providerTurnId: owner.providerTurnId,
4096 + nativeItemRef: codexNativeItemRef(input.nativeItemId),
4097 + runtimeRequestId: requestId,
4098 + checkpointScopeId: null,
4099 + startedAt: createdAt,
4100 + completedAt: null,
4101 + };
4102 + const request: OrchestrationV2RuntimeRequest = {
4103 + id: requestId,
4104 + nodeId,
4105 + providerTurnId: owner.providerTurnId,
4106 + nativeRequestRef: {
4107 + driver: CODEX_PROVIDER,
4108 + nativeId: input.nativeRequestId,
4109 + strength: "strong",
4110 + },
4111 + kind: input.requestKind,
4112 + status: "pending",
4113 + responseCapability: {
4114 + type: "live",
4115 + providerSessionId,
4116 + },
4117 + createdAt,
4118 + resolvedAt: null,
4119 + };
4120 + const turnItem: OrchestrationV2TurnItem = {
4121 + id: idAllocator.derive.approvalTurnItem({ requestId }),
4122 + threadId: owner.projectionThreadId,
4123 + runId: owner.projectionRunId,
4124 + nodeId,
4125 + providerThreadId: owner.providerThread.id,
4126 + providerTurnId: owner.providerTurnId,
4127 + nativeItemRef: codexNativeItemRef(input.nativeItemId),
4128 + parentItemId: null,
4129 + ordinal,
4130 + status: "waiting",
4131 + title: null,
4132 + startedAt: createdAt,
4133 + completedAt: null,
4134 + updatedAt: createdAt,
4135 + type: "approval_request",
4136 + requestId,
4137 + requestKind: input.requestKind,
4138 + ...(input.prompt === null || input.prompt === undefined
4139 + ? {}
4140 + : { prompt: input.prompt }),
4141 + ...(input.appName === undefined ? {} : { appName: input.appName }),
4142 + ...(input.options === undefined ? {} : { options: input.options }),
4143 + };
4144 + return { node, request, turnItem };
4145 + });
4146
4131 - const buildUserInputRequestArtifacts = (input: {
4147 + const buildUserInputRequestArtifacts = Effect.fn(
4148 + "CodexAdapterV2.buildUserInputRequestArtifacts",
4149 + )(function* (input: {
4150 readonly context: ActiveCodexTurnContext;
4151 readonly nativeItemId: string;
4152 readonly nativeRequestId: string;
4153 readonly questions: ReadonlyArray<CodexSchema.ToolRequestUserInputParams__ToolRequestUserInputQuestion>;
4154 readonly responseMode?: "message";
4137 - }) =>
4138 - Effect.gen(function* () {
4139 - const createdAt = yield* DateTime.now;
4140 - const requestId = yield* idAllocator.allocate.runtimeRequest({
4141 - driver: CODEX_PROVIDER,
4142 - providerTurnId: input.context.providerTurnId,
4143 - nativeRequestId: input.nativeRequestId,
4144 - });
4145 - const providerSessionId = input.context.input.providerThread.providerSessionId;
4146 - if (providerSessionId === null) {
4147 - return yield* toProtocolError(
4148 - `Provider thread ${input.context.providerThread.id} is missing a provider session id.`,
4149 - );
4150 - }
4151 - const questions = input.questions.map((question, index) => ({
4152 - id: nonEmptyText(question.id, `question-${index + 1}`),
4153 - header: nonEmptyText(question.header, "Question"),
4154 - question: nonEmptyText(question.question, "Choose an answer."),
4155 - options:
4156 - question.options?.map((option, optionIndex) => ({
4157 - label: nonEmptyText(option.label, `Option ${optionIndex + 1}`),
4158 - description: nonEmptyText(option.description, option.label),
4159 - })) ?? [],
4160 - }));
4161 - const nodeId = idAllocator.derive.nodeFromProviderItem({
4162 - driver: CODEX_PROVIDER,
4163 - nativeItemId: input.nativeItemId,
4164 - });
4165 - const turnItemId = idAllocator.derive.turnItemFromProviderItem({
4166 - driver: CODEX_PROVIDER,
4167 - nativeItemId: input.nativeItemId,
4168 - });
4169 - const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId);
4170 - const node: OrchestrationV2ExecutionNode = {
4171 - id: nodeId,
4172 - threadId: input.context.projectionThreadId,
4173 - runId: input.context.projectionRunId,
4174 - parentNodeId: input.context.itemParentNodeId,
4175 - rootNodeId: input.context.rootNodeId,
4176 - kind: "user_input_request",
4177 - status: "waiting",
4178 - countsForRun: false,
4179 - providerThreadId: input.context.providerThread.id,
4180 - providerTurnId: input.context.providerTurnId,
4181 - nativeItemRef: codexNativeItemRef(input.nativeItemId),
4182 - runtimeRequestId: requestId,
4183 - checkpointScopeId: null,
4184 - startedAt: createdAt,
4185 - completedAt: null,
4186 - };
4187 - const request: OrchestrationV2RuntimeRequest = {
4188 - id: requestId,
4189 - nodeId,
4190 - providerTurnId: input.context.providerTurnId,
4191 - nativeRequestRef: {
4192 - driver: CODEX_PROVIDER,
4193 - nativeId: input.nativeRequestId,
4194 - strength: "strong",
4195 - },
4196 - kind: "user_input",
4197 - status: "pending",
4198 - responseCapability:
4199 - input.responseMode === "message"
4200 - ? { type: "message" }
4201 - : { type: "live", providerSessionId },
4202 - createdAt,
4203 - resolvedAt: null,
4204 - };
4205 - const turnItem: OrchestrationV2TurnItem = {
4206 - id: turnItemId,
4207 - threadId: input.context.projectionThreadId,
4208 - runId: input.context.projectionRunId,
4209 - nodeId,
4210 - providerThreadId: input.context.providerThread.id,
4211 - providerTurnId: input.context.providerTurnId,
4212 - nativeItemRef: codexNativeItemRef(input.nativeItemId),
4213 - parentItemId: null,
4214 - ordinal,
4215 - status: "waiting",
4216 - title: null,
4217 - startedAt: createdAt,
4218 - completedAt: null,
4219 - updatedAt: createdAt,
4220 - type: "user_input_request",
4221 - requestId,
4222 - questions,
4223 - ...(input.responseMode === undefined ? {} : { responseMode: input.responseMode }),
4224 - };
4225 - return { node, request, turnItem };
4155 + }) {
4156 + const createdAt = yield* DateTime.now;
4157 + const requestId = yield* idAllocator.allocate.runtimeRequest({
4158 + driver: CODEX_PROVIDER,
4159 + providerTurnId: input.context.providerTurnId,
4160 + nativeRequestId: input.nativeRequestId,
4161 + });
4162 + const providerSessionId = input.context.input.providerThread.providerSessionId;
4163 + if (providerSessionId === null) {
4164 + return yield* toProtocolError(
4165 + `Provider thread ${input.context.providerThread.id} is missing a provider session id.`,
4166 + );
4167 + }
4168 + const questions = input.questions.map((question, index) => ({
4169 + id: nonEmptyText(question.id, `question-${index + 1}`),
4170 + header: nonEmptyText(question.header, "Question"),
4171 + question: nonEmptyText(question.question, "Choose an answer."),
4172 + options:
4173 + question.options?.map((option, optionIndex) => ({
4174 + label: nonEmptyText(option.label, `Option ${optionIndex + 1}`),
4175 + description: nonEmptyText(option.description, option.label),
4176 + })) ?? [],
4177 + }));
4178 + const nodeId = idAllocator.derive.nodeFromProviderItem({
4179 + driver: CODEX_PROVIDER,
4180 + nativeItemId: input.nativeItemId,
4181 + });
4182 + const turnItemId = idAllocator.derive.turnItemFromProviderItem({
4183 + driver: CODEX_PROVIDER,
4184 + nativeItemId: input.nativeItemId,
4185 });
4186 + const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId);
4187 + const node: OrchestrationV2ExecutionNode = {
4188 + id: nodeId,
4189 + threadId: input.context.projectionThreadId,
4190 + runId: input.context.projectionRunId,
4191 + parentNodeId: input.context.itemParentNodeId,
4192 + rootNodeId: input.context.rootNodeId,
4193 + kind: "user_input_request",
4194 + status: "waiting",
4195 + countsForRun: false,
4196 + providerThreadId: input.context.providerThread.id,
4197 + providerTurnId: input.context.providerTurnId,
4198 + nativeItemRef: codexNativeItemRef(input.nativeItemId),
4199 + runtimeRequestId: requestId,
4200 + checkpointScopeId: null,
4201 + startedAt: createdAt,
4202 + completedAt: null,
4203 + };
4204 + const request: OrchestrationV2RuntimeRequest = {
4205 + id: requestId,
4206 + nodeId,
4207 + providerTurnId: input.context.providerTurnId,
4208 + nativeRequestRef: {
4209 + driver: CODEX_PROVIDER,
4210 + nativeId: input.nativeRequestId,
4211 + strength: "strong",
4212 + },
4213 + kind: "user_input",
4214 + status: "pending",
4215 + responseCapability:
4216 + input.responseMode === "message"
4217 + ? { type: "message" }
4218 + : { type: "live", providerSessionId },
4219 + createdAt,
4220 + resolvedAt: null,
4221 + };
4222 + const turnItem: OrchestrationV2TurnItem = {
4223 + id: turnItemId,
4224 + threadId: input.context.projectionThreadId,
4225 + runId: input.context.projectionRunId,
4226 + nodeId,
4227 + providerThreadId: input.context.providerThread.id,
4228 + providerTurnId: input.context.providerTurnId,
4229 + nativeItemRef: codexNativeItemRef(input.nativeItemId),
4230 + parentItemId: null,
4231 + ordinal,
4232 + status: "waiting",
4233 + title: null,
4234 + startedAt: createdAt,
4235 + completedAt: null,
4236 + updatedAt: createdAt,
4237 + type: "user_input_request",
4238 + requestId,
4239 + questions,
4240 + ...(input.responseMode === undefined ? {} : { responseMode: input.responseMode }),
4241 + };
4242 + return { node, request, turnItem };
4243 + });
4244
4245 yield* client.handleServerNotification("item/agentMessage/delta", (payload) =>
4246 Effect.gen(function* () {
@@ -6214,11 +6231,11 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6231 );
6232 });
6233
6217 - const startNativeTurn = (
6218 - turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
6219 - codexInput: ReadonlyArray<CodexSchema.V2TurnStartParams__UserInput>,
6220 - ) =>
6221 - Effect.gen(function* () {
6234 + const startNativeTurn = Effect.fn("CodexAdapterV2.startNativeTurn")(
6235 + function* (
6236 + turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
6237 + codexInput: ReadonlyArray<CodexSchema.V2TurnStartParams__UserInput>,
6238 + ) {
6239 const threadId = yield* getNativeThreadId(turnInput.providerThread);
6240 const mcpSession = yield* mcpSessions.read(turnInput.threadId);
6241 const turnStartParams = yield* buildCodexTurnStartParams({
@@ -6247,32 +6264,35 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6264 const started = yield* client.request("turn/start", turnStartParams);
6265 yield* registerRootTurn({
6266 turnInput,
6250 - nativeTurnId: started.turn.id,
6251 - startedAt: codexTimestamp(started.turn.startedAt),
6252 - waitForNativeStart: started.turn.startedAt === null,
6253 - });
6254 - }).pipe(
6255 - Effect.ensuring(
6256 - Effect.flatMap(getNativeThreadId(turnInput.providerThread), (threadId) =>
6257 - Ref.update(pendingRootTurns, (current) => {
6258 - const updated = new Map(current);
6259 - updated.delete(threadId);
6260 - return updated;
6261 - }),
6262 - ).pipe(Effect.ignore),
6267 + nativeTurnId: started.turn.id,
6268 + startedAt: codexTimestamp(started.turn.startedAt),
6269 + waitForNativeStart: started.turn.startedAt === null,
6270 + });
6271 + },
6272 + (effect, turnInput) =>
6273 + effect.pipe(
6274 + Effect.ensuring(
6275 + Effect.flatMap(getNativeThreadId(turnInput.providerThread), (threadId) =>
6276 + Ref.update(pendingRootTurns, (current) => {
6277 + const updated = new Map(current);
6278 + updated.delete(threadId);
6279 + return updated;
6280 + }),
6281 + ).pipe(Effect.ignore),
6282 + ),
6283 ),
6264 - );
6284 + );
6285
6286 /**
6287 * Setting or resuming a goal starts the first goal turn with this run's
6288 * turn configuration (approvals, sandbox, model, plan mode), since a
6289 * turn Codex starts on its own reuses the last turn's settings.
6290 */
6271 - const runGoalCommand = (
6272 - turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
6273 - command: CodexGoalCommand,
6274 - ) =>
6275 - Effect.gen(function* () {
6291 + const runGoalCommand = Effect.fn("CodexAdapterV2.runGoalCommand")(
6292 + function* (
6293 + turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
6294 + command: CodexGoalCommand,
6295 + ) {
6296 const threadId = yield* getNativeThreadId(turnInput.providerThread);
6297 rootProviderThreads.set(threadId, turnInput.providerThread);
6298 const readGoal = client
@@ -6363,18 +6383,21 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6383 ),
6384 ),
6385 );
6366 - }).pipe(
6367 - Effect.mapError(
6368 - (cause) =>
6369 - new ProviderAdapter.ProviderAdapterTurnStartError({
6370 - driver: CODEX_PROVIDER,
6371 - threadId: turnInput.threadId,
6372 - providerThreadId: turnInput.providerThread.id,
6373 - runId: turnInput.runId,
6374 - cause,
6375 - }),
6386 + },
6387 + (effect, turnInput) =>
6388 + effect.pipe(
6389 + Effect.mapError(
6390 + (cause) =>
6391 + new ProviderAdapter.ProviderAdapterTurnStartError({
6392 + driver: CODEX_PROVIDER,
6393 + threadId: turnInput.threadId,
6394 + providerThreadId: turnInput.providerThread.id,
6395 + runId: turnInput.runId,
6396 + cause,
6397 + }),
6398 + ),
6399 ),
6377 - );
6400 + );
6401
6402 const mcpAppsError = (detail: string) => (cause: unknown) =>
6403 new ProviderAdapter.ProviderAdapterProtocolError({
@@ -6383,8 +6406,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6406 payload: cause,
6407 });
6408 const mcpApps: ProviderAdapter.ProviderAdapterV2McpApps = {
6386 - listTools: (toolsInput) =>
6387 - Effect.gen(function* () {
6409 + listTools: Effect.fn("CodexAdapterV2.listTools")(
6410 + function* (toolsInput) {
6411 const threadId = yield* getNativeThreadId(toolsInput.providerThread);
6412 const response = yield* ensureInitialized.pipe(
6413 Effect.andThen(
@@ -6397,9 +6420,11 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6420 );
6421 const server = response.data.find((entry) => entry.name === toolsInput.server);
6422 return Object.values(server?.tools ?? {});
6400 - }).pipe(Effect.mapError(mcpAppsError("Failed to list Codex MCP tools."))),
6401 - callTool: (callInput) =>
6402 - Effect.gen(function* () {
6423 + },
6424 + Effect.mapError(mcpAppsError("Failed to list Codex MCP tools.")),
6425 + ),
6426 + callTool: Effect.fn("CodexAdapterV2.callTool")(
6427 + function* (callInput) {
6428 const threadId = yield* getNativeThreadId(callInput.providerThread);
6429 const response = yield* ensureInitialized.pipe(
6430 Effect.andThen(
@@ -6419,9 +6444,11 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6444 ...(response.isError === true ? { isError: true } : {}),
6445 ...(response._meta === undefined ? {} : { _meta: response._meta }),
6446 };
6422 - }).pipe(Effect.mapError(mcpAppsError("Codex MCP tool call failed."))),
6423 - readResource: (readInput) =>
6424 - Effect.gen(function* () {
6447 + },
6448 + Effect.mapError(mcpAppsError("Codex MCP tool call failed.")),
6449 + ),
6450 + readResource: Effect.fn("CodexAdapterV2.readResource")(
6451 + function* (readInput) {
6452 const threadId = yield* getNativeThreadId(readInput.providerThread);
6453 const response = yield* ensureInitialized.pipe(
6454 Effect.andThen(
@@ -6433,7 +6460,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6460 ),
6461 );
6462 return { contents: response.contents };
6436 - }).pipe(Effect.mapError(mcpAppsError("Codex MCP resource read failed."))),
6463 + },
6464 + Effect.mapError(mcpAppsError("Codex MCP resource read failed.")),
6465 + ),
6466 };
6467
6468 const runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime = {
@@ -6468,27 +6497,28 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6497 }
6498 return false;
6499 }),
6471 - hasPendingBackgroundWorkForThread: (providerThread) =>
6472 - Effect.gen(function* () {
6473 - const contexts = [
6474 - ...(yield* Ref.get(activeTurns)).values(),
6475 - ...(yield* Ref.get(settledTurns)).values(),
6476 - ];
6477 - const roots = contexts.filter(
6478 - (context) => context.providerThread.id === providerThread.id,
6479 - );
6480 - for (const context of contexts) {
6481 - if (!roots.some((root) => context === root || isDescendantCodexTurn(context, root)))
6482 - continue;
6483 - if (yield* turnHasRetainedBackgroundWork(context.nativeTurnId)) return true;
6484 - if (
6485 - context.subagent !== null &&
6486 - (yield* Ref.get(activeTurns)).has(context.nativeTurnId)
6487 - )
6488 - return true;
6489 - }
6490 - return false;
6491 - }),
6500 + hasPendingBackgroundWorkForThread: Effect.fn(
6501 + "CodexAdapterV2.hasPendingBackgroundWorkForThread",
6502 + )(function* (providerThread) {
6503 + const contexts = [
6504 + ...(yield* Ref.get(activeTurns)).values(),
6505 + ...(yield* Ref.get(settledTurns)).values(),
6506 + ];
6507 + const roots = contexts.filter(
6508 + (context) => context.providerThread.id === providerThread.id,
6509 + );
6510 + for (const context of contexts) {
6511 + if (!roots.some((root) => context === root || isDescendantCodexTurn(context, root)))
6512 + continue;
6513 + if (yield* turnHasRetainedBackgroundWork(context.nativeTurnId)) return true;
6514 + if (
6515 + context.subagent !== null &&
6516 + (yield* Ref.get(activeTurns)).has(context.nativeTurnId)
6517 + )
6518 + return true;
6519 + }
6520 + return false;
6521 + }),
6522 ensureThread: (threadInput) =>
6523 ensureInitialized.pipe(
6524 Effect.andThen(mcpSessions.read(threadInput.threadId)),
@@ -6521,8 +6551,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6551 }),
6552 ),
6553 ),
6524 - resumeThread: (threadInput) =>
6525 - Effect.gen(function* () {
6554 + resumeThread: Effect.fn("CodexAdapterV2.resumeThread")(
6555 + function* (threadInput) {
6556 const nativeThreadId = yield* getNativeThreadId(threadInput.providerThread);
6557 // excludeTurns is not in the generated request schema yet.
6558 const resume = client.raw.request("thread/resume", {
@@ -6574,19 +6604,22 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6604 nativeConversationHeadRef: threadInput.providerThread.nativeConversationHeadRef,
6605 updatedAt: codexTimestamp(response.thread.updatedAt),
6606 } satisfies OrchestrationV2ProviderThread;
6577 - }).pipe(
6578 - Effect.mapError(
6579 - (cause) =>
6580 - new ProviderAdapter.ProviderAdapterResumeThreadError({
6581 - driver: CODEX_PROVIDER,
6582 - providerSessionId: input.providerSessionId,
6583 - providerThreadId: threadInput.providerThread.id,
6584 - cause: normalizeCodexCause(cause),
6585 - }),
6607 + },
6608 + (effect, threadInput) =>
6609 + effect.pipe(
6610 + Effect.mapError(
6611 + (cause) =>
6612 + new ProviderAdapter.ProviderAdapterResumeThreadError({
6613 + driver: CODEX_PROVIDER,
6614 + providerSessionId: input.providerSessionId,
6615 + providerThreadId: threadInput.providerThread.id,
6616 + cause: normalizeCodexCause(cause),
6617 + }),
6618 + ),
6619 ),
6587 - ),
6588 - compactThread: (turnInput) =>
6589 - Effect.gen(function* () {
6620 + ),
6621 + compactThread: Effect.fn("CodexAdapterV2.compactThread")(
6622 + function* (turnInput) {
6623 const threadId = yield* getNativeThreadId(turnInput.providerThread);
6624 yield* Ref.update(pendingRootTurns, (current) =>
6625 new Map(current).set(threadId, turnInput),
@@ -6602,20 +6635,23 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6635 }),
6636 ),
6637 );
6605 - }).pipe(
6606 - Effect.mapError(
6607 - (cause) =>
6608 - new ProviderAdapter.ProviderAdapterTurnStartError({
6609 - driver: CODEX_PROVIDER,
6610 - threadId: turnInput.threadId,
6611 - providerThreadId: turnInput.providerThread.id,
6612 - runId: turnInput.runId,
6613 - cause,
6614 - }),
6638 + },
6639 + (effect, turnInput) =>
6640 + effect.pipe(
6641 + Effect.mapError(
6642 + (cause) =>
6643 + new ProviderAdapter.ProviderAdapterTurnStartError({
6644 + driver: CODEX_PROVIDER,
6645 + threadId: turnInput.threadId,
6646 + providerThreadId: turnInput.providerThread.id,
6647 + runId: turnInput.runId,
6648 + cause,
6649 + }),
6650 + ),
6651 ),
6616 - ),
6617 - injectHistory: (input) =>
6618 - Effect.gen(function* () {
6652 + ),
6653 + injectHistory: Effect.fn("CodexAdapterV2.injectHistory")(
6654 + function* (input) {
6655 const threadId = yield* getNativeThreadId(input.providerThread);
6656 return yield* client
6657 .request("thread/inject_items", {
@@ -6632,16 +6668,16 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6668 error.code === -32601 ? Effect.succeed(false) : Effect.fail(error),
6669 }),
6670 );
6635 - }).pipe(
6636 - Effect.mapError(
6637 - (cause) =>
6638 - new ProviderAdapter.ProviderAdapterProtocolError({
6639 - driver: CODEX_PROVIDER,
6640 - detail: "Failed to inject historical context",
6641 - cause,
6642 - }),
6643 - ),
6671 + },
6672 + Effect.mapError(
6673 + (cause) =>
6674 + new ProviderAdapter.ProviderAdapterProtocolError({
6675 + driver: CODEX_PROVIDER,
6676 + detail: "Failed to inject historical context",
6677 + cause,
6678 + }),
6679 ),
6680 + ),
6681 startTurn: (turnInput) => {
6682 const goalCommand =
6683 turnInput.message.attachments.length === 0 &&
@@ -6669,8 +6705,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6705 ),
6706 );
6707 },
6672 - steerTurn: (turnInput) =>
6673 - Effect.gen(function* () {
6708 + steerTurn: Effect.fn("CodexAdapterV2.steerTurn")(
6709 + function* (turnInput) {
6710 const threadId = yield* getNativeThreadId(turnInput.providerThread);
6711 const latestTurnId = latestGoalTurnId(turnInput.providerTurnId);
6712 const held = heldGoalTurn(turnInput.providerThread, latestTurnId);
@@ -6693,37 +6729,43 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
6729 input: codexInput,
6730 threadId,
6731 });
6696 - }).pipe(
6697 - Effect.mapError(
6698 - (cause) =>
6699 - new ProviderAdapter.ProviderAdapterSteerRunError({
6700 - driver: CODEX_PROVIDER,
6701 - providerThreadId: turnInput.providerThread.id,
6702 - providerTurnId: turnInput.providerTurnId,
6703 - cause,
6704 - }),
6732 + },
6733 + (effect, turnInput) =>
6734 + effect.pipe(
6735 + Effect.mapError(
6736 + (cause) =>
6737 + new ProviderAdapter.ProviderAdapterSteerRunError({
6738 + driver: CODEX_PROVIDER,
6739 + providerThreadId: turnInput.providerThread.id,
6740 + providerTurnId: turnInput.providerTurnId,
6741 + cause,
6742 + }),
6743 + ),
6744 ),
6706 - ),
6745 + ),
6746 // Dropping this connection's subscription lets the shared app-server
6747 // shut the native thread (and its MCP servers) down once it is idle.
6709 - unloadThread: (unloadInput) =>
6710 - Effect.gen(function* () {
6748 + unloadThread: Effect.fn("CodexAdapterV2.unloadThread")(
6749 + function* (unloadInput) {
6750 const nativeThreadId = yield* getNativeThreadId(unloadInput.providerThread);
6751 sessionApprovals.delete(nativeThreadId);
6752 yield* client.request("thread/unsubscribe", { threadId: nativeThreadId });
6714 - }).pipe(
6715 - Effect.mapError((cause) =>
6716 - cause._tag === "ProviderAdapterProtocolError"
6717 - ? cause
6718 - : new ProviderAdapter.ProviderAdapterProtocolError({
6719 - driver: CODEX_PROVIDER,
6720 - detail: `Failed to unload Codex thread for provider thread ${unloadInput.providerThread.id}`,
6721 - cause: normalizeCodexCause(cause),
6722 - }),
6753 + },
6754 + (effect, unloadInput) =>
6755 + effect.pipe(
6756 + Effect.mapError((cause) =>
6757 + cause._tag === "ProviderAdapterProtocolError"
6758 + ? cause
6759 + : new ProviderAdapter.ProviderAdapterProtocolError({
6760 + driver: CODEX_PROVIDER,
6761 + detail: `Failed to unload Codex thread for provider thread ${unloadInput.providerThread.id}`,
6762 + cause: normalizeCodexCause(cause),
6763 + }),
6764 + ),
6765 ),
6724 - ),
6725 - interruptTurn: (requestedInput) =>
6726 - Effect.gen(function* () {
6766 + ),
6767 + interruptTurn: Effect.fn("CodexAdapterV2.interruptTurn")(
6768 + function* (requestedInput) {
6769 const { turnInput, goalTurns } = yield* resolveGoalStopTarget(requestedInput);
6770 const [activeTurnContexts, settledTurnContexts] =
6771 yield* turnTerminalizationPermit.withPermits(1)(
@@ -6977,8 +7019,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
7019 }
7020 const containedTerminalKeys = new Set<string>();
7021 const attemptedTerminalKeys = new Set<string>();
6980 - const collectTrackedTerminals = (targets: typeof interruptTargets) =>
6981 - Effect.gen(function* () {
7022 + const collectTrackedTerminals = Effect.fn("CodexAdapterV2.collectTrackedTerminals")(
7023 + function* (targets: typeof interruptTargets) {
7024 const trackedTerminals = new Map<
7025 string,
7026 { readonly nativeThreadId: string; readonly processId: string }
@@ -6999,32 +7041,32 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
7041 }
7042 }
7043 return trackedTerminals;
7002 - });
7003 - const terminateTrackedTerminals = (targets: typeof interruptTargets) =>
7004 - Effect.gen(function* () {
7005 - const trackedTerminals = yield* collectTrackedTerminals(targets);
7006 - const pendingTerminals = Array.from(trackedTerminals.entries())
7007 - .filter(([key]) => !containedTerminalKeys.has(key))
7008 - .sort(
7009 - ([leftKey], [rightKey]) =>
7010 - Number(attemptedTerminalKeys.has(leftKey)) -
7011 - Number(attemptedTerminalKeys.has(rightKey)),
7012 - );
7013 - return yield* Effect.forEach(
7014 - pendingTerminals,
7015 - ([key, { nativeThreadId, processId }]) =>
7016 - Effect.gen(function* () {
7017 - attemptedTerminalKeys.add(key);
7018 - yield* terminateBackgroundTerminal(nativeThreadId, processId);
7019 - containedTerminalKeys.add(key);
7020 - }).pipe(
7021 - Effect.as({ success: true as const }),
7022 - Effect.catch((error) =>
7023 - Effect.succeed({ success: false as const, error }),
7024 - ),
7025 - ),
7044 + },
7045 + );
7046 + const terminateTrackedTerminals = Effect.fn(
7047 + "CodexAdapterV2.terminateTrackedTerminals",
7048 + )(function* (targets: typeof interruptTargets) {
7049 + const trackedTerminals = yield* collectTrackedTerminals(targets);
7050 + const pendingTerminals = Array.from(trackedTerminals.entries())
7051 + .filter(([key]) => !containedTerminalKeys.has(key))
7052 + .sort(
7053 + ([leftKey], [rightKey]) =>
7054 + Number(attemptedTerminalKeys.has(leftKey)) -
7055 + Number(attemptedTerminalKeys.has(rightKey)),
7056 );
7027 - });
7057 + return yield* Effect.forEach(
7058 + pendingTerminals,
7059 + ([key, { nativeThreadId, processId }]) =>
7060 + Effect.gen(function* () {
7061 + attemptedTerminalKeys.add(key);
7062 + yield* terminateBackgroundTerminal(nativeThreadId, processId);
7063 + containedTerminalKeys.add(key);
7064 + }).pipe(
7065 + Effect.as({ success: true as const }),
7066 + Effect.catch((error) => Effect.succeed({ success: false as const, error })),
7067 + ),
7068 + );
7069 + });
7070
7071 const [, completed] = yield* Effect.all(
7072 [
@@ -7094,19 +7136,22 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
7136 Effect.onError(() => finalizeRemainingInterruptLineage),
7137 Effect.ensuring(cleanupInterruptState),
7138 );
7097 - }).pipe(
7098 - Effect.mapError(
7099 - (cause) =>
7100 - new ProviderAdapter.ProviderAdapterInterruptError({
7101 - driver: CODEX_PROVIDER,
7102 - providerThreadId: requestedInput.providerThread.id,
7103 - providerTurnId: requestedInput.providerTurnId,
7104 - cause,
7105 - }),
7139 + },
7140 + (effect, requestedInput) =>
7141 + effect.pipe(
7142 + Effect.mapError(
7143 + (cause) =>
7144 + new ProviderAdapter.ProviderAdapterInterruptError({
7145 + driver: CODEX_PROVIDER,
7146 + providerThreadId: requestedInput.providerThread.id,
7147 + providerTurnId: requestedInput.providerTurnId,
7148 + cause,
7149 + }),
7150 + ),
7151 ),
7107 - ),
7108 - respondToRuntimeRequest: (requestInput) =>
7109 - Effect.gen(function* () {
7152 + ),
7153 + respondToRuntimeRequest: Effect.fn("CodexAdapterV2.respondToRuntimeRequest")(
7154 + function* (requestInput) {
7155 const pending = (yield* Ref.get(pendingRuntimeRequests)).get(
7156 String(requestInput.requestId),
7157 );
@@ -7142,19 +7187,22 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
7187 });
7188 }
7189 yield* Deferred.succeed(pending.decision, requestInput.decision);
7145 - }).pipe(
7146 - Effect.mapError((cause) =>
7147 - isProviderAdapterRuntimeRequestResponseError(cause)
7148 - ? cause
7149 - : new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({
7150 - driver: CODEX_PROVIDER,
7151 - requestId: requestInput.requestId,
7152 - cause,
7153 - }),
7190 + },
7191 + (effect, requestInput) =>
7192 + effect.pipe(
7193 + Effect.mapError((cause) =>
7194 + isProviderAdapterRuntimeRequestResponseError(cause)
7195 + ? cause
7196 + : new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({
7197 + driver: CODEX_PROVIDER,
7198 + requestId: requestInput.requestId,
7199 + cause,
7200 + }),
7201 + ),
7202 ),
7155 - ),
7156 - uploadFeedback: (feedbackInput) =>
7157 - Effect.gen(function* () {
7203 + ),
7204 + uploadFeedback: Effect.fn("CodexAdapterV2.uploadFeedback")(
7205 + function* (feedbackInput) {
7206 const threadId = yield* getNativeThreadId(feedbackInput.providerThread);
7207 const response = yield* ensureInitialized.pipe(
7208 Effect.andThen(
@@ -7167,19 +7215,19 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
7215 ),
7216 );
7217 return { feedbackId: response.threadId };
7170 - }).pipe(
7171 - Effect.mapError(
7172 - (cause) =>
7173 - new ProviderAdapter.ProviderAdapterProtocolError({
7174 - driver: CODEX_PROVIDER,
7175 - detail: "Failed to upload Codex thread feedback.",
7176 - payload: cause,
7177 - }),
7178 - ),
7218 + },
7219 + Effect.mapError(
7220 + (cause) =>
7221 + new ProviderAdapter.ProviderAdapterProtocolError({
7222 + driver: CODEX_PROVIDER,
7223 + detail: "Failed to upload Codex thread feedback.",
7224 + payload: cause,
7225 + }),
7226 ),
7227 + ),
7228 mcpApps,
7181 - readThreadSnapshot: (threadInput) =>
7182 - Effect.gen(function* () {
7229 + readThreadSnapshot: Effect.fn("CodexAdapterV2.readThreadSnapshot")(
7230 + function* (threadInput) {
7231 const threadId = yield* getNativeThreadId(threadInput.providerThread);
7232 const response = yield* ensureInitialized.pipe(
7233 Effect.andThen(client.request("thread/read", { threadId, includeTurns: true })),
@@ -7200,18 +7248,21 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
7248 runtimeRequests: [],
7249 providerPayload: response.thread,
7250 };
7203 - }).pipe(
7204 - Effect.mapError(
7205 - (cause) =>
7206 - new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({
7207 - driver: CODEX_PROVIDER,
7208 - providerThreadId: threadInput.providerThread.id,
7209 - cause,
7210 - }),
7251 + },
7252 + (effect, threadInput) =>
7253 + effect.pipe(
7254 + Effect.mapError(
7255 + (cause) =>
7256 + new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({
7257 + driver: CODEX_PROVIDER,
7258 + providerThreadId: threadInput.providerThread.id,
7259 + cause,
7260 + }),
7261 + ),
7262 ),
7212 - ),
7213 - rollbackThread: (threadInput) =>
7214 - Effect.gen(function* () {
7263 + ),
7264 + rollbackThread: Effect.fn("CodexAdapterV2.rollbackThread")(
7265 + function* (threadInput) {
7266 const threadId = yield* getNativeThreadId(threadInput.providerThread);
7267 const numTurns = yield* resolveCodexRollbackTurnCount(threadInput);
7268 const nativeConversationHeadRef =
@@ -7275,18 +7326,21 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
7326 runtimeRequests: [],
7327 providerPayload: response.thread,
7328 };
7278 - }).pipe(
7279 - Effect.mapError(
7280 - (cause) =>
7281 - new ProviderAdapter.ProviderAdapterRollbackThreadError({
7282 - driver: CODEX_PROVIDER,
7283 - providerThreadId: threadInput.providerThread.id,
7284 - cause: normalizeCodexCause(cause),
7285 - }),
7329 + },
7330 + (effect, threadInput) =>
7331 + effect.pipe(
7332 + Effect.mapError(
7333 + (cause) =>
7334 + new ProviderAdapter.ProviderAdapterRollbackThreadError({
7335 + driver: CODEX_PROVIDER,
7336 + providerThreadId: threadInput.providerThread.id,
7337 + cause: normalizeCodexCause(cause),
7338 + }),
7339 + ),
7340 ),
7287 - ),
7288 - forkThread: (threadInput) =>
7289 - Effect.gen(function* () {
7341 + ),
7342 + forkThread: Effect.fn("CodexAdapterV2.forkThread")(
7343 + function* (threadInput) {
7344 const threadId = yield* getNativeThreadId(threadInput.sourceProviderThread);
7345 const boundary = yield* resolveCodexForkBoundary(threadInput);
7346 const response = yield* ensureInitialized.pipe(
@@ -7356,27 +7410,33 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
7410 : { providerTurnId: threadInput.providerTurnId }),
7411 },
7412 });
7359 - }).pipe(
7360 - Effect.mapError(
7361 - (cause) =>
7362 - new ProviderAdapter.ProviderAdapterForkThreadError({
7363 - driver: CODEX_PROVIDER,
7364 - providerThreadId: threadInput.sourceProviderThread.id,
7365 - cause: normalizeCodexCause(cause),
7366 - }),
7413 + },
7414 + (effect, threadInput) =>
7415 + effect.pipe(
7416 + Effect.mapError(
7417 + (cause) =>
7418 + new ProviderAdapter.ProviderAdapterForkThreadError({
7419 + driver: CODEX_PROVIDER,
7420 + providerThreadId: threadInput.sourceProviderThread.id,
7421 + cause: normalizeCodexCause(cause),
7422 + }),
7423 + ),
7424 ),
7368 - ),
7425 + ),
7426 };
7427 return runtime;
7371 - }).pipe(
7372 - Effect.mapError(
7373 - (cause) =>
7374 - new ProviderAdapter.ProviderAdapterOpenSessionError({
7375 - driver: CODEX_PROVIDER,
7376 - providerSessionId: input.providerSessionId,
7377 - cause,
7378 - }),
7428 + },
7429 + (effect, input) =>
7430 + effect.pipe(
7431 + Effect.mapError(
7432 + (cause) =>
7433 + new ProviderAdapter.ProviderAdapterOpenSessionError({
7434 + driver: CODEX_PROVIDER,
7435 + providerSessionId: input.providerSessionId,
7436 + cause,
7437 + }),
7438 + ),
7439 ),
7380 - ),
7440 + ),
7441 });
7442 });
apps/server/src/provider/AntigravityAuth.ts
+30 -24
@@ -261,8 +261,8 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* <
261 ),
262 );
263
264 - const runSignIn = (flow: AuthFlow, stopSessions: Effect.Effect<void, ProviderSetupError>) =>
265 - Effect.gen(function* () {
264 + const runSignIn = Effect.fn("AntigravityAuth.runSignIn")(
265 + function* (flow: AuthFlow, stopSessions: Effect.Effect<void, ProviderSetupError>) {
266 yield* stopSessions.pipe(Effect.ensuring(stopOwnedProcesses));
267 const runtime = yield* options.makeRuntime({
268 onAuthorizationUrl: (url) => receiveAuthorizationUrl(flow, url),
@@ -281,16 +281,19 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* <
281 }),
282 );
283 yield* options.onAuthenticated(started, runtime);
284 - }).pipe(
285 - Effect.scoped,
286 - Effect.timeoutOrElse({
287 - duration: AUTH_TIMEOUT_MS,
288 - orElse: () =>
289 - Effect.fail(setupError("start", "Google sign-in expired. Start sign-in again.")),
290 - }),
291 - Effect.exit,
292 - Effect.flatMap((result) => finishFlow(flow, result)),
293 - );
284 + },
285 + (effect, flow, stopSessions) =>
286 + effect.pipe(
287 + Effect.scoped,
288 + Effect.timeoutOrElse({
289 + duration: AUTH_TIMEOUT_MS,
290 + orElse: () =>
291 + Effect.fail(setupError("start", "Google sign-in expired. Start sign-in again.")),
292 + }),
293 + Effect.exit,
294 + Effect.flatMap((result) => finishFlow(flow, result)),
295 + ),
296 + );
297
298 const stopFlow = (flow: AuthFlow, phase: "cancelled" | "failed", message: string) =>
299 Effect.uninterruptible(
@@ -322,18 +325,21 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* <
325 }),
326 );
327
325 - const requireFlow = (ownerSessionId: string, flowId: string, name: string) =>
326 - Effect.gen(function* () {
327 - const flow = activeFlow;
328 - if (!flow || flow.id !== flowId || flow.ownerSessionId !== ownerSessionId) {
329 - return yield* setupError(name, "This sign-in is no longer active in this client.");
330 - }
331 - const now = yield* Clock.currentTimeMillis;
332 - if (now >= flow.expiresAtMillis) {
333 - return yield* setupError(name, "Google sign-in expired. Start sign-in again.");
334 - }
335 - return flow;
336 - });
328 + const requireFlow = Effect.fn("AntigravityAuth.requireFlow")(function* (
329 + ownerSessionId: string,
330 + flowId: string,
331 + name: string,
332 + ) {
333 + const flow = activeFlow;
334 + if (!flow || flow.id !== flowId || flow.ownerSessionId !== ownerSessionId) {
335 + return yield* setupError(name, "This sign-in is no longer active in this client.");
336 + }
337 + const now = yield* Clock.currentTimeMillis;
338 + if (now >= flow.expiresAtMillis) {
339 + return yield* setupError(name, "Google sign-in expired. Start sign-in again.");
340 + }
341 + return flow;
342 + });
343
344 const controller: ProviderAuthController = {
345 start: (ownerSessionId, stopSessions = Effect.void) =>
apps/server/src/provider/ClaudeProvider.ts
+7 -6
@@ -684,11 +684,11 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
684
685 const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
686
687 -export const makePendingClaudeProvider = (
688 - claudeSettings: ClaudeSettings,
689 - modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG,
690 -): Effect.Effect<ServerProviderDraft> =>
691 - Effect.gen(function* () {
687 +export const makePendingClaudeProvider = Effect.fn("ClaudeProvider.makePendingClaudeProvider")(
688 + function* (
689 + claudeSettings: ClaudeSettings,
690 + modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG,
691 + ): Effect.fn.Return<ServerProviderDraft> {
692 const checkedAt = yield* nowIso;
693 const models = providerModelsFromSettings(
694 modelCatalog.models.map((entry) => entry.model),
@@ -725,6 +725,7 @@ export const makePendingClaudeProvider = (
725 message: "Claude provider status has not been checked in this session yet.",
726 },
727 });
728 - });
728 + },
729 +);
730
731 export { probeClaudeCapabilities };
apps/server/src/provider/CodexChatGptAuth.ts
+38 -39
@@ -109,49 +109,48 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function*
109 }) {
110 const analytics = yield* Effect.serviceOption(AnalyticsService.AnalyticsService);
111 const settings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService);
112 - const track = <A, E extends ProviderSetupError, R>(
112 + const track = Effect.fn("CodexChatGptAuth.track")(function* <A, E extends ProviderSetupError, R>(
113 event: "auth" | "transfer",
114 properties: Readonly<Record<string, string>>,
115 task: Effect.Effect<A, E, R>,
116 expiresAt?: number,
117 - ) =>
118 - Effect.gen(function* () {
119 - if (Option.isNone(analytics)) return yield* task;
120 - const record = (name: string, properties: Readonly<Record<string, unknown>>) =>
121 - analytics.value.record(name, properties).pipe(Effect.ignoreCause);
122 - const startedAt = yield* Clock.currentTimeMillis;
123 - yield* record(`chatgpt.${event}.started`, properties);
124 - return yield* task.pipe(
125 - Effect.onExit((result) =>
126 - Effect.gen(function* () {
127 - const endedAt = yield* Clock.currentTimeMillis;
128 - const error = Exit.isFailure(result)
129 - ? Cause.findErrorOption(result.cause)
130 - : Option.none();
131 - const counts =
132 - Exit.isSuccess(result) &&
133 - (event === "transfer" || options.telemetryFlow !== "primary_handoff")
134 - ? yield* accountCounts.pipe(Effect.catchCause(() => Effect.succeed({})))
135 - : {};
136 - yield* record(`chatgpt.${event}.completed`, {
137 - ...counts,
138 - ...properties,
139 - outcome: Exit.isSuccess(result)
140 - ? "succeeded"
141 - : Cause.hasInterruptsOnly(result.cause)
142 - ? expiresAt !== undefined && endedAt >= expiresAt
143 - ? "expired"
144 - : "cancelled"
145 - : "failed",
146 - durationMs: Math.max(0, endedAt - startedAt),
147 - ...(Option.isSome(error) && isSetupError(error.value)
148 - ? { failureStage: error.value.operation }
149 - : {}),
150 - });
151 - }),
152 - ),
153 - );
154 - });
117 + ) {
118 + if (Option.isNone(analytics)) return yield* task;
119 + const record = (name: string, properties: Readonly<Record<string, unknown>>) =>
120 + analytics.value.record(name, properties).pipe(Effect.ignoreCause);
121 + const startedAt = yield* Clock.currentTimeMillis;
122 + yield* record(`chatgpt.${event}.started`, properties);
123 + return yield* task.pipe(
124 + Effect.onExit((result) =>
125 + Effect.gen(function* () {
126 + const endedAt = yield* Clock.currentTimeMillis;
127 + const error = Exit.isFailure(result)
128 + ? Cause.findErrorOption(result.cause)
129 + : Option.none();
130 + const counts =
131 + Exit.isSuccess(result) &&
132 + (event === "transfer" || options.telemetryFlow !== "primary_handoff")
133 + ? yield* accountCounts.pipe(Effect.catchCause(() => Effect.succeed({})))
134 + : {};
135 + yield* record(`chatgpt.${event}.completed`, {
136 + ...counts,
137 + ...properties,
138 + outcome: Exit.isSuccess(result)
139 + ? "succeeded"
140 + : Cause.hasInterruptsOnly(result.cause)
141 + ? expiresAt !== undefined && endedAt >= expiresAt
142 + ? "expired"
143 + : "cancelled"
144 + : "failed",
145 + durationMs: Math.max(0, endedAt - startedAt),
146 + ...(Option.isSome(error) && isSetupError(error.value)
147 + ? { failureStage: error.value.operation }
148 + : {}),
149 + });
150 + }),
151 + ),
152 + );
153 + });
154 const http = yield* HttpClient.HttpClient;
155 const store = yield* ProviderCredentialStore.make("codex-chatgpt", options.instanceId);
156 const registrationStore = yield* ProviderCredentialStore.make(
apps/server/src/provider/CodexProvider.ts
+23 -24
@@ -543,33 +543,16 @@ export const probeCodexSkillsForCwd = Effect.fn("probeCodexSkillsForCwd")(functi
543 const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>
544 appendCustomCodexModels([], codexSettings.customModels);
545
546 -const makePendingCodexProvider = (
546 +const makePendingCodexProvider = Effect.fn("CodexProvider.makePendingCodexProvider")(function* (
547 codexSettings: CodexSettings,
548 -): Effect.Effect<ServerProviderDraft> =>
549 - Effect.gen(function* () {
550 - const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
551 - const models = emptyCodexModelsFromSettings(codexSettings);
552 -
553 - if (!codexSettings.enabled) {
554 - return buildServerProvider({
555 - presentation: CODEX_PRESENTATION,
556 - enabled: false,
557 - checkedAt,
558 - models,
559 - skills: [],
560 - probe: {
561 - installed: false,
562 - version: null,
563 - status: "warning",
564 - auth: { status: "unknown" },
565 - message: "Codex is disabled in T3 Code settings.",
566 - },
567 - });
568 - }
548 +): Effect.fn.Return<ServerProviderDraft> {
549 + const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
550 + const models = emptyCodexModelsFromSettings(codexSettings);
551
552 + if (!codexSettings.enabled) {
553 return buildServerProvider({
554 presentation: CODEX_PRESENTATION,
572 - enabled: true,
555 + enabled: false,
556 checkedAt,
557 models,
558 skills: [],
@@ -578,10 +561,26 @@ const makePendingCodexProvider = (
561 version: null,
562 status: "warning",
563 auth: { status: "unknown" },
581 - message: "Codex provider status has not been checked in this session yet.",
564 + message: "Codex is disabled in T3 Code settings.",
565 },
566 });
567 + }
568 +
569 + return buildServerProvider({
570 + presentation: CODEX_PRESENTATION,
571 + enabled: true,
572 + checkedAt,
573 + models,
574 + skills: [],
575 + probe: {
576 + installed: false,
577 + version: null,
578 + status: "warning",
579 + auth: { status: "unknown" },
580 + message: "Codex provider status has not been checked in this session yet.",
581 + },
582 });
583 +});
584
585 function accountProbeStatus({ account, rateLimits }: CodexAppServerProviderSnapshot): {
586 readonly status: Exclude<ServerProviderState, "disabled">;
apps/server/src/provider/Drivers/AntigravityDriver.ts
+401 -400
@@ -93,435 +93,436 @@ export const AntigravityDriver: ProviderDriver<
93 configSchema: AntigravitySettings,
94 defaultConfig: () => decodeSettings({}),
95 usage: AntigravityUsage.antigravityUsageReader,
96 - create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
97 - Effect.gen(function* () {
98 - const crypto = yield* Crypto.Crypto;
99 - const fileSystem = yield* FileSystem.FileSystem;
100 - const httpClient = yield* HttpClient.HttpClient;
101 - const path = yield* Path.Path;
102 - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
103 - const host = yield* ProviderHost.ProviderHost;
104 - const selfInvocation = yield* resolveSelfInvocation();
105 - const installation = yield* AntigravityInstallation.AntigravityInstallation;
106 - const loggers = yield* ProviderEventLoggers.ProviderEventLoggers;
107 - const modelCatalog = yield* ModelCatalog.ModelCatalog;
108 - const currentCatalog = modelCatalog.current(DRIVER);
109 - const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
110 - const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
111 - const settings = { ...config, enabled } satisfies AntigravitySettings;
112 - const auth: AntigravityAuthConfig = {
113 - authMethod: settings.authMethod,
114 - apiKey: settings.apiKey,
115 - gcpProject: settings.gcpProject,
116 - gcpLocation: settings.gcpLocation,
117 - };
118 - const authConfigIssue = antigravityAuthConfigIssue(auth);
119 - const processEnvironment = yield* mergeProviderInstanceEnvironment(environment);
120 - const userHome = resolveAntigravityUserHome(
121 - yield* HostProcess.Platform,
122 - processEnvironment,
123 - yield* HostProcess.HomeDirectory,
96 + create: Effect.fn("AntigravityDriver.create")(function* ({
97 + instanceId,
98 + displayName,
99 + accentColor,
100 + environment,
101 + enabled,
102 + config,
103 + }) {
104 + const crypto = yield* Crypto.Crypto;
105 + const fileSystem = yield* FileSystem.FileSystem;
106 + const httpClient = yield* HttpClient.HttpClient;
107 + const path = yield* Path.Path;
108 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
109 + const host = yield* ProviderHost.ProviderHost;
110 + const selfInvocation = yield* resolveSelfInvocation();
111 + const installation = yield* AntigravityInstallation.AntigravityInstallation;
112 + const loggers = yield* ProviderEventLoggers.ProviderEventLoggers;
113 + const modelCatalog = yield* ModelCatalog.ModelCatalog;
114 + const currentCatalog = modelCatalog.current(DRIVER);
115 + const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
116 + const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
117 + const settings = { ...config, enabled } satisfies AntigravitySettings;
118 + const auth: AntigravityAuthConfig = {
119 + authMethod: settings.authMethod,
120 + apiKey: settings.apiKey,
121 + gcpProject: settings.gcpProject,
122 + gcpLocation: settings.gcpLocation,
123 + };
124 + const authConfigIssue = antigravityAuthConfigIssue(auth);
125 + const processEnvironment = yield* mergeProviderInstanceEnvironment(environment);
126 + const userHome = resolveAntigravityUserHome(
127 + yield* HostProcess.Platform,
128 + processEnvironment,
129 + yield* HostProcess.HomeDirectory,
130 + );
131 + const directories = yield* resolveAntigravityInstanceDirectories(
132 + host.paths.stateDir,
133 + instanceId,
134 + ).pipe(
135 + Effect.provideService(Crypto.Crypto, crypto),
136 + Effect.provideService(Path.Path, path),
137 + Effect.mapError(
138 + (cause) =>
139 + new ProviderDriverError({
140 + driver: DRIVER,
141 + instanceId,
142 + detail: "Could not resolve the Antigravity profile directory.",
143 + cause,
144 + }),
145 + ),
146 + );
147 + const profileDirectory = directories.profile;
148 + for (const directory of [
149 + directories.runtimeTemp,
150 + path.join(profileDirectory, "antigravity-acp", "tmp"),
151 + ]) {
152 + yield* removeAntigravityRuntimeTempDirs(directory).pipe(
153 + Effect.provideService(FileSystem.FileSystem, fileSystem),
154 );
125 - const directories = yield* resolveAntigravityInstanceDirectories(
126 - host.paths.stateDir,
127 - instanceId,
128 - ).pipe(
129 - Effect.provideService(Crypto.Crypto, crypto),
130 - Effect.provideService(Path.Path, path),
155 + }
156 + const continuationIdentity = defaultProviderContinuationIdentity({
157 + driverKind: DRIVER,
158 + instanceId,
159 + });
160 + const stampIdentity = withInstanceIdentity({
161 + instanceId,
162 + driverKind: DRIVER,
163 + displayName,
164 + accentColor,
165 + continuationGroupKey: continuationIdentity.continuationKey,
166 + });
167 + const classifyModels = (draft: ServerProviderDraft) =>
168 + currentCatalog.pipe(
169 + Effect.map((catalog) => stampIdentity(ModelCatalog.applyModelCatalog(draft, catalog))),
170 + );
171 +
172 + const makeRuntime = Effect.fn("AntigravityDriver.makeRuntime")(function* (
173 + input: Omit<AntigravityAcpRuntimeInput, "spawn" | "childProcessSpawner">,
174 + ): Effect.fn.Return<
175 + AcpSessionRuntime.AcpSessionRuntime["Service"],
176 + AcpError | ProviderSetupError,
177 + Scope.Scope
178 + > {
179 + if (authConfigIssue !== null) {
180 + return yield* new ProviderSetupError({
181 + instanceId,
182 + operation: "configure",
183 + detail: authConfigIssue,
184 + });
185 + }
186 + const executable = yield* installation.acquire(settings.binaryPath, processEnvironment).pipe(
187 Effect.mapError(
188 (cause) =>
133 - new ProviderDriverError({
134 - driver: DRIVER,
189 + new ProviderSetupError({
190 instanceId,
136 - detail: "Could not resolve the Antigravity profile directory.",
191 + operation: "resolve",
192 + detail: cause.detail,
193 cause,
194 }),
195 ),
196 );
141 - const profileDirectory = directories.profile;
142 - for (const directory of [
143 - directories.runtimeTemp,
144 - path.join(profileDirectory, "antigravity-acp", "tmp"),
145 - ]) {
146 - yield* removeAntigravityRuntimeTempDirs(directory).pipe(
147 - Effect.provideService(FileSystem.FileSystem, fileSystem),
148 - );
149 - }
150 - const continuationIdentity = defaultProviderContinuationIdentity({
151 - driverKind: DRIVER,
152 - instanceId,
153 - });
154 - const stampIdentity = withInstanceIdentity({
155 - instanceId,
156 - driverKind: DRIVER,
157 - displayName,
158 - accentColor,
159 - continuationGroupKey: continuationIdentity.continuationKey,
160 - });
161 - const classifyModels = (draft: ServerProviderDraft) =>
162 - currentCatalog.pipe(
163 - Effect.map((catalog) => stampIdentity(ModelCatalog.applyModelCatalog(draft, catalog))),
164 - );
165 -
166 - const makeRuntime = Effect.fn("AntigravityDriver.makeRuntime")(function* (
167 - input: Omit<AntigravityAcpRuntimeInput, "spawn" | "childProcessSpawner">,
168 - ): Effect.fn.Return<
169 - AcpSessionRuntime.AcpSessionRuntime["Service"],
170 - AcpError | ProviderSetupError,
171 - Scope.Scope
172 - > {
173 - if (authConfigIssue !== null) {
174 - return yield* new ProviderSetupError({
175 - instanceId,
176 - operation: "configure",
177 - detail: authConfigIssue,
178 - });
179 - }
180 - const executable = yield* installation
181 - .acquire(settings.binaryPath, processEnvironment)
182 - .pipe(
183 - Effect.mapError(
184 - (cause) =>
185 - new ProviderSetupError({
186 - instanceId,
187 - operation: "resolve",
188 - detail: cause.detail,
189 - cause,
190 - }),
191 - ),
192 - );
193 - const profile = yield* prepareAntigravityProfile({
194 - profileDirectory,
195 - baseEnv: processEnvironment,
196 - auth,
197 - userHome,
198 - tempDirectory: directories.runtimeTemp,
199 - }).pipe(
200 - Effect.provideService(FileSystem.FileSystem, fileSystem),
201 - Effect.provideService(Path.Path, path),
202 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
203 - Effect.mapError((cause) =>
204 - isNodeRuntimeUnavailableError(cause.cause)
205 - ? new ProviderSetupError({
206 - instanceId,
207 - operation: "start",
208 - detail: nodeRuntimeUnavailableMessage("Antigravity sign-in"),
209 - cause,
210 - })
211 - : cause,
212 - ),
213 - );
214 - // Each process unpacks into its own directory that dies with the
215 - // runtime scope, after the child is killed. A shared directory would
216 - // let one session's teardown delete files a sibling still reads.
217 - // Removal is best effort: a handle can outlive the kill on Windows,
218 - // and the sweep on the next driver start reclaims what is left.
219 - const runtimeTempDirectory = yield* Effect.acquireRelease(
220 - fileSystem.makeTempDirectory({ directory: profile.tempDirectory, prefix: "run-" }).pipe(
221 - Effect.mapError(
222 - (cause) =>
223 - new ProviderSetupError({
224 - instanceId,
225 - operation: "start",
226 - detail: "Could not create an Antigravity runtime temp directory.",
227 - cause,
228 - }),
229 - ),
197 + const profile = yield* prepareAntigravityProfile({
198 + profileDirectory,
199 + baseEnv: processEnvironment,
200 + auth,
201 + userHome,
202 + tempDirectory: directories.runtimeTemp,
203 + }).pipe(
204 + Effect.provideService(FileSystem.FileSystem, fileSystem),
205 + Effect.provideService(Path.Path, path),
206 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
207 + Effect.mapError((cause) =>
208 + isNodeRuntimeUnavailableError(cause.cause)
209 + ? new ProviderSetupError({
210 + instanceId,
211 + operation: "start",
212 + detail: nodeRuntimeUnavailableMessage("Antigravity sign-in"),
213 + cause,
214 + })
215 + : cause,
216 + ),
217 + );
218 + // Each process unpacks into its own directory that dies with the
219 + // runtime scope, after the child is killed. A shared directory would
220 + // let one session's teardown delete files a sibling still reads.
221 + // Removal is best effort: a handle can outlive the kill on Windows,
222 + // and the sweep on the next driver start reclaims what is left.
223 + const runtimeTempDirectory = yield* Effect.acquireRelease(
224 + fileSystem.makeTempDirectory({ directory: profile.tempDirectory, prefix: "run-" }).pipe(
225 + Effect.mapError(
226 + (cause) =>
227 + new ProviderSetupError({
228 + instanceId,
229 + operation: "start",
230 + detail: "Could not create an Antigravity runtime temp directory.",
231 + cause,
232 + }),
233 ),
231 - (directory) =>
232 - fileSystem
233 - .remove(directory, { recursive: true, force: true })
234 - .pipe(
235 - Effect.catch(() =>
236 - Effect.logWarning("Could not remove an Antigravity runtime temp directory."),
237 - ),
234 + ),
235 + (directory) =>
236 + fileSystem
237 + .remove(directory, { recursive: true, force: true })
238 + .pipe(
239 + Effect.catch(() =>
240 + Effect.logWarning("Could not remove an Antigravity runtime temp directory."),
241 ),
239 - );
240 - const runtime = yield* makeAntigravityAcpRuntime({
241 - ...input,
242 - authMethod: auth.authMethod,
243 - childProcessSpawner: spawner,
244 - spawn: buildAntigravityAcpSpawnInput({
245 - installation: executable,
246 - profile,
247 - cwd: input.cwd,
248 - baseEnv: withAgentDeviceEnvironment(processEnvironment, input),
249 - auth,
250 - runtimeTempDirectory,
251 - }),
252 - }).pipe(Effect.provideService(Crypto.Crypto, crypto));
253 - return {
254 - ...runtime,
255 - start: () =>
256 - runtime
257 - .start()
258 - .pipe(
259 - Effect.tapError((cause): Effect.Effect<void> =>
260 - input.onAuthorizationUrl === undefined && isAntigravitySignInRequiredError(cause)
261 - ? provider.onAuthRequired
262 - : Effect.void,
263 - ),
242 + ),
243 + );
244 + const runtime = yield* makeAntigravityAcpRuntime({
245 + ...input,
246 + authMethod: auth.authMethod,
247 + childProcessSpawner: spawner,
248 + spawn: buildAntigravityAcpSpawnInput({
249 + installation: executable,
250 + profile,
251 + cwd: input.cwd,
252 + baseEnv: withAgentDeviceEnvironment(processEnvironment, input),
253 + auth,
254 + runtimeTempDirectory,
255 + }),
256 + }).pipe(Effect.provideService(Crypto.Crypto, crypto));
257 + return {
258 + ...runtime,
259 + start: () =>
260 + runtime
261 + .start()
262 + .pipe(
263 + Effect.tapError((cause): Effect.Effect<void> =>
264 + input.onAuthorizationUrl === undefined && isAntigravitySignInRequiredError(cause)
265 + ? provider.onAuthRequired
266 + : Effect.void,
267 ),
265 - };
266 - });
267 -
268 - const makeDisposableRuntime = Effect.fn("AntigravityDriver.makeDisposableRuntime")(function* (
269 - input: Pick<AntigravityAcpRuntimeInput, "onAuthorizationUrl">,
270 - ) {
271 - const cwd = yield* fileSystem
272 - .makeTempDirectoryScoped({ prefix: "t3-antigravity-setup-" })
273 - .pipe(
274 - Effect.mapError(
275 - () =>
276 - new ProviderSetupError({
277 - instanceId,
278 - operation: "start",
279 - detail: "Could not create an Antigravity setup workspace.",
280 - }),
268 ),
282 - );
283 - let sessionId: string | undefined;
284 - yield* Effect.addFinalizer(() =>
285 - removeAntigravitySessionFiles({
286 - profileDirectory,
287 - sessionId,
288 - cwd,
289 - }).pipe(
290 - Effect.provideService(FileSystem.FileSystem, fileSystem),
291 - Effect.provideService(Path.Path, path),
269 + };
270 + });
271 +
272 + const makeDisposableRuntime = Effect.fn("AntigravityDriver.makeDisposableRuntime")(function* (
273 + input: Pick<AntigravityAcpRuntimeInput, "onAuthorizationUrl">,
274 + ) {
275 + const cwd = yield* fileSystem
276 + .makeTempDirectoryScoped({ prefix: "t3-antigravity-setup-" })
277 + .pipe(
278 + Effect.mapError(
279 + () =>
280 + new ProviderSetupError({
281 + instanceId,
282 + operation: "start",
283 + detail: "Could not create an Antigravity setup workspace.",
284 + }),
285 ),
286 );
294 - const runtime = yield* makeRuntime({
287 + let sessionId: string | undefined;
288 + yield* Effect.addFinalizer(() =>
289 + removeAntigravitySessionFiles({
290 + profileDirectory,
291 + sessionId,
292 cwd,
296 - clientInfo: { name: "t3-code-provider-setup", version: "0.0.0" },
297 - mcpServers: [],
298 - ...(input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {}),
299 - });
300 - return {
301 - ...runtime,
302 - start: () =>
303 - runtime.start().pipe(
304 - Effect.tap((started) =>
305 - Effect.sync(() => {
306 - sessionId = started.sessionId;
307 - }),
308 - ),
309 - ),
310 - };
311 - });
312 -
313 - const publishCatalog = (
314 - started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
315 - runtime: Pick<AcpSessionRuntime.AcpSessionRuntime["Service"], "getEvents" | "drainEvents">,
316 - ): Effect.Effect<void> =>
317 - Effect.gen(function* () {
318 - yield* provider.onSessionStarted(started);
319 - yield* Stream.runForEach(runtime.getEvents(), (event) => {
320 - if (event._tag === "EventStreamBarrier") {
321 - return Deferred.succeed(event.acknowledge, undefined).pipe(Effect.asVoid);
322 - }
323 - if (event._tag === "ConfigOptionsUpdated") {
324 - return provider.onConfigOptionsUpdated(event.configOptions);
325 - }
326 - return event._tag === "AvailableCommandsUpdated"
327 - ? provider.onAvailableCommands(event.availableCommands)
328 - : Effect.void;
329 - }).pipe(Effect.forkScoped);
330 - yield* runtime.drainEvents;
331 - }).pipe(Effect.scoped);
332 -
333 - const authFlow: AntigravityAuth = yield* makeAntigravityAuth({
334 - instanceId,
335 - makeRuntime: makeDisposableRuntime,
336 - onAuthenticated: publishCatalog,
337 - onSignedOut: Effect.suspend(() => provider.onSignedOut),
338 - usesBrowser: antigravityAuthUsesBrowser(auth.authMethod),
293 + }).pipe(
294 + Effect.provideService(FileSystem.FileSystem, fileSystem),
295 + Effect.provideService(Path.Path, path),
296 + ),
297 + );
298 + const runtime = yield* makeRuntime({
299 + cwd,
300 + clientInfo: { name: "t3-code-provider-setup", version: "0.0.0" },
301 + mcpServers: [],
302 + ...(input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {}),
303 });
304 + return {
305 + ...runtime,
306 + start: () =>
307 + runtime.start().pipe(
308 + Effect.tap((started) =>
309 + Effect.sync(() => {
310 + sessionId = started.sessionId;
311 + }),
312 + ),
313 + ),
314 + };
315 + });
316
341 - // The probe must not spawn. The agent is a PyInstaller one-file bundle
342 - // that unpacks about 1 GB per launch, and the health check runs every
343 - // minute.
344 - const probe = Effect.gen(function* () {
345 - yield* modelCatalog.refreshInBackground;
346 - if (authConfigIssue !== null) {
347 - return yield* new ProviderSetupError({
348 - instanceId,
349 - operation: "configure",
350 - detail: authConfigIssue,
351 - });
317 + const publishCatalog = Effect.fn("AntigravityDriver.publishCatalog")(function* (
318 + started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
319 + runtime: Pick<AcpSessionRuntime.AcpSessionRuntime["Service"], "getEvents" | "drainEvents">,
320 + ) {
321 + yield* provider.onSessionStarted(started);
322 + yield* Stream.runForEach(runtime.getEvents(), (event) => {
323 + if (event._tag === "EventStreamBarrier") {
324 + return Deferred.succeed(event.acknowledge, undefined).pipe(Effect.asVoid);
325 }
353 - const executable = yield* installation
354 - .resolve(settings.binaryPath, processEnvironment)
355 - .pipe(
356 - Effect.mapError(
357 - (cause) =>
358 - new ProviderSetupError({
359 - instanceId,
360 - operation: "resolve",
361 - detail: cause.detail,
362 - cause,
363 - }),
364 - ),
365 - );
366 - return {
367 - protocolVersion: 1,
368 - agentCapabilities: {
369 - loadSession: true,
370 - promptCapabilities: { image: true, audio: true, embeddedContext: true },
371 - sessionCapabilities: { list: {}, resume: {} },
372 - },
373 - authMethods: [{ id: "oauth-personal", name: "Log in with Google" }],
374 - agentInfo: {
375 - name: "antigravity-acp",
376 - title: "Google Antigravity",
377 - version: executable.version ?? "unknown",
378 - },
379 - };
380 - });
326 + if (event._tag === "ConfigOptionsUpdated") {
327 + return provider.onConfigOptionsUpdated(event.configOptions);
328 + }
329 + return event._tag === "AvailableCommandsUpdated"
330 + ? provider.onAvailableCommands(event.availableCommands)
331 + : Effect.void;
332 + }).pipe(Effect.forkScoped);
333 + yield* runtime.drainEvents;
334 + }, Effect.scoped);
335
382 - const usage = yield* makeAntigravityUsageProbe({
383 - profileDirectory,
384 - authMethod: auth.authMethod,
385 - }).pipe(
386 - Effect.provideService(FileSystem.FileSystem, fileSystem),
387 - Effect.provideService(Path.Path, path),
388 - Effect.provideService(Crypto.Crypto, crypto),
389 - Effect.provideService(HttpClient.HttpClient, httpClient),
390 - );
391 - const provider = yield* makeAntigravityProvider(settings, {
392 - stampIdentity: classifyModels,
393 - probe,
394 - probeUsage: usage.probe,
395 - clearUsage: usage.clear,
396 - auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) },
397 - supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe(
398 - Effect.provideService(FileSystem.FileSystem, fileSystem),
399 - Effect.provideService(Path.Path, path),
400 - Effect.orElseSucceed(() => false),
401 - ),
402 - }).pipe(
336 + const authFlow: AntigravityAuth = yield* makeAntigravityAuth({
337 + instanceId,
338 + makeRuntime: makeDisposableRuntime,
339 + onAuthenticated: publishCatalog,
340 + onSignedOut: Effect.suspend(() => provider.onSignedOut),
341 + usesBrowser: antigravityAuthUsesBrowser(auth.authMethod),
342 + });
343 +
344 + // The probe must not spawn. The agent is a PyInstaller one-file bundle
345 + // that unpacks about 1 GB per launch, and the health check runs every
346 + // minute.
347 + const probe = Effect.gen(function* () {
348 + yield* modelCatalog.refreshInBackground;
349 + if (authConfigIssue !== null) {
350 + return yield* new ProviderSetupError({
351 + instanceId,
352 + operation: "configure",
353 + detail: authConfigIssue,
354 + });
355 + }
356 + const executable = yield* installation.resolve(settings.binaryPath, processEnvironment).pipe(
357 Effect.mapError(
358 (cause) =>
405 - new ProviderDriverError({
406 - driver: DRIVER,
359 + new ProviderSetupError({
360 instanceId,
408 - detail: "Could not prepare the Antigravity provider status.",
361 + operation: "resolve",
362 + detail: cause.detail,
363 cause,
364 }),
365 ),
366 );
413 - const defaultModel = currentCatalog.pipe(Effect.map((catalog) => catalog?.defaultChatModel));
414 - const orchestrationAdapter = yield* makeAntigravityAdapterV2({
415 - instanceId,
416 - selfInvocation,
417 - makeRuntime,
418 - withProcess: authFlow.withProcess,
419 - defaultModel,
420 - onSessionStarted: provider.onSessionStarted,
421 - onSessionEvent: (event) => {
422 - if (event._tag === "ConfigOptionsUpdated") {
423 - return provider.onConfigOptionsUpdated(event.configOptions);
424 - }
425 - return event._tag === "AvailableCommandsUpdated"
426 - ? provider.onAvailableCommands(event.availableCommands)
427 - : Effect.void;
367 + return {
368 + protocolVersion: 1,
369 + agentCapabilities: {
370 + loadSession: true,
371 + promptCapabilities: { image: true, audio: true, embeddedContext: true },
372 + sessionCapabilities: { list: {}, resume: {} },
373 },
429 - continuationRequests,
430 - nativeLogging: (threadId) =>
431 - makeNativeLogger({
432 - nativeEventLogger: loggers.native,
433 - provider: DRIVER,
434 - threadId,
435 - }),
436 - });
437 - const textGeneration = yield* makeAntigravityTextGeneration({
438 - profileDirectory,
439 - defaultModel,
440 - withProcess: authFlow.withProcess,
441 - makeRuntime: (cwd) =>
442 - makeRuntime({
443 - cwd,
444 - clientInfo: { name: "t3-code-text", version: "0.0.0" },
445 - mcpServers: [],
446 - }),
447 - });
448 -
449 - const refreshModels = Effect.fn("AntigravityDriver.refreshModels")(
450 - function* () {
451 - const processScope = yield* Scope.make();
452 - yield* Effect.addFinalizer((exit) => Scope.close(processScope, exit));
453 - yield* authFlow
454 - .withProcess(
455 - Scope.close(processScope, Exit.void),
456 - Effect.gen(function* () {
457 - const runtime = yield* makeDisposableRuntime({});
458 - const started = yield* runtime.start();
459 - yield* publishCatalog(started, runtime);
460 - }),
461 - )
462 - .pipe(Effect.provideService(Scope.Scope, processScope));
374 + authMethods: [{ id: "oauth-personal", name: "Log in with Google" }],
375 + agentInfo: {
376 + name: "antigravity-acp",
377 + title: "Google Antigravity",
378 + version: executable.version ?? "unknown",
379 },
464 - Effect.scoped,
465 - Effect.timeoutOrElse({
466 - duration: "90 seconds",
467 - orElse: () =>
468 - Effect.fail(
469 - new ProviderDriverError({
470 - driver: DRIVER,
471 - instanceId,
472 - detail: "Antigravity model refresh timed out. Try again or check Google sign-in.",
473 - }),
474 - ),
380 + };
381 + });
382 +
383 + const usage = yield* makeAntigravityUsageProbe({
384 + profileDirectory,
385 + authMethod: auth.authMethod,
386 + }).pipe(
387 + Effect.provideService(FileSystem.FileSystem, fileSystem),
388 + Effect.provideService(Path.Path, path),
389 + Effect.provideService(Crypto.Crypto, crypto),
390 + Effect.provideService(HttpClient.HttpClient, httpClient),
391 + );
392 + const provider = yield* makeAntigravityProvider(settings, {
393 + stampIdentity: classifyModels,
394 + probe,
395 + probeUsage: usage.probe,
396 + clearUsage: usage.clear,
397 + auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) },
398 + supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe(
399 + Effect.provideService(FileSystem.FileSystem, fileSystem),
400 + Effect.provideService(Path.Path, path),
401 + Effect.orElseSucceed(() => false),
402 + ),
403 + }).pipe(
404 + Effect.mapError(
405 + (cause) =>
406 + new ProviderDriverError({
407 + driver: DRIVER,
408 + instanceId,
409 + detail: "Could not prepare the Antigravity provider status.",
410 + cause,
411 + }),
412 + ),
413 + );
414 + const defaultModel = currentCatalog.pipe(Effect.map((catalog) => catalog?.defaultChatModel));
415 + const orchestrationAdapter = yield* makeAntigravityAdapterV2({
416 + instanceId,
417 + selfInvocation,
418 + makeRuntime,
419 + withProcess: authFlow.withProcess,
420 + defaultModel,
421 + onSessionStarted: provider.onSessionStarted,
422 + onSessionEvent: (event) => {
423 + if (event._tag === "ConfigOptionsUpdated") {
424 + return provider.onConfigOptionsUpdated(event.configOptions);
425 + }
426 + return event._tag === "AvailableCommandsUpdated"
427 + ? provider.onAvailableCommands(event.availableCommands)
428 + : Effect.void;
429 + },
430 + continuationRequests,
431 + nativeLogging: (threadId) =>
432 + makeNativeLogger({
433 + nativeEventLogger: loggers.native,
434 + provider: DRIVER,
435 + threadId,
436 }),
476 - Effect.tapError((cause) =>
477 - isAntigravitySignInRequiredError(cause) ? provider.onAuthRequired : Effect.void,
478 - ),
479 - Effect.mapError((cause) =>
480 - cause._tag === "ProviderDriverError"
481 - ? cause
482 - : new ProviderDriverError({
483 - driver: DRIVER,
484 - instanceId,
485 - detail: isAntigravitySignInRequiredError(cause)
486 - ? "Sign in to Antigravity in provider settings before refreshing models."
487 - : cause._tag === "ProviderSetupError" &&
488 - (cause.operation === "configure" || cause.operation === "start")
489 - ? cause.detail
490 - : "Could not refresh Antigravity models. The previous model list is unchanged.",
491 - cause,
492 - }),
493 - ),
494 - );
437 + });
438 + const textGeneration = yield* makeAntigravityTextGeneration({
439 + profileDirectory,
440 + defaultModel,
441 + withProcess: authFlow.withProcess,
442 + makeRuntime: (cwd) =>
443 + makeRuntime({
444 + cwd,
445 + clientInfo: { name: "t3-code-text", version: "0.0.0" },
446 + mcpServers: [],
447 + }),
448 + });
449
496 - return {
497 - instanceId,
498 - driverKind: DRIVER,
499 - continuationIdentity,
500 - displayName,
501 - accentColor,
502 - enabled,
503 - snapshot: provider.snapshot,
504 - snapshotForCwd: (cwd) =>
505 - !enabled
506 - ? provider.snapshot.getSnapshot
507 - : discoverAntigravitySkills({ cwd, userHome }).pipe(
508 - Effect.provideService(FileSystem.FileSystem, fileSystem),
509 - Effect.provideService(Path.Path, path),
510 - Effect.flatMap((skills) => provider.snapshotForCwd(cwd, skills)),
511 - Effect.mapError(
512 - (cause) =>
513 - new ProviderDriverError({
514 - driver: DRIVER,
515 - instanceId,
516 - detail: "Could not read Antigravity workspace skills.",
517 - cause,
518 - }),
519 - ),
450 + const refreshModels = Effect.fn("AntigravityDriver.refreshModels")(
451 + function* () {
452 + const processScope = yield* Scope.make();
453 + yield* Effect.addFinalizer((exit) => Scope.close(processScope, exit));
454 + yield* authFlow
455 + .withProcess(
456 + Scope.close(processScope, Exit.void),
457 + Effect.gen(function* () {
458 + const runtime = yield* makeDisposableRuntime({});
459 + const started = yield* runtime.start();
460 + yield* publishCatalog(started, runtime);
461 + }),
462 + )
463 + .pipe(Effect.provideService(Scope.Scope, processScope));
464 + },
465 + Effect.scoped,
466 + Effect.timeoutOrElse({
467 + duration: "90 seconds",
468 + orElse: () =>
469 + Effect.fail(
470 + new ProviderDriverError({
471 + driver: DRIVER,
472 + instanceId,
473 + detail: "Antigravity model refresh timed out. Try again or check Google sign-in.",
474 + }),
475 + ),
476 + }),
477 + Effect.tapError((cause) =>
478 + isAntigravitySignInRequiredError(cause) ? provider.onAuthRequired : Effect.void,
479 + ),
480 + Effect.mapError((cause) =>
481 + cause._tag === "ProviderDriverError"
482 + ? cause
483 + : new ProviderDriverError({
484 + driver: DRIVER,
485 + instanceId,
486 + detail: isAntigravitySignInRequiredError(cause)
487 + ? "Sign in to Antigravity in provider settings before refreshing models."
488 + : cause._tag === "ProviderSetupError" &&
489 + (cause.operation === "configure" || cause.operation === "start")
490 + ? cause.detail
491 + : "Could not refresh Antigravity models. The previous model list is unchanged.",
492 + cause,
493 + }),
494 + ),
495 + );
496 +
497 + return {
498 + instanceId,
499 + driverKind: DRIVER,
500 + continuationIdentity,
501 + displayName,
502 + accentColor,
503 + enabled,
504 + snapshot: provider.snapshot,
505 + snapshotForCwd: (cwd) =>
506 + !enabled
507 + ? provider.snapshot.getSnapshot
508 + : discoverAntigravitySkills({ cwd, userHome }).pipe(
509 + Effect.provideService(FileSystem.FileSystem, fileSystem),
510 + Effect.provideService(Path.Path, path),
511 + Effect.flatMap((skills) => provider.snapshotForCwd(cwd, skills)),
512 + Effect.mapError(
513 + (cause) =>
514 + new ProviderDriverError({
515 + driver: DRIVER,
516 + instanceId,
517 + detail: "Could not read Antigravity workspace skills.",
518 + cause,
519 + }),
520 ),
521 - orchestrationAdapter,
522 - textGeneration,
523 - auth: authFlow.controller,
524 - refreshModels,
525 - } satisfies ProviderInstance;
526 - }),
521 + ),
522 + orchestrationAdapter,
523 + textGeneration,
524 + auth: authFlow.controller,
525 + refreshModels,
526 + } satisfies ProviderInstance;
527 + }),
528 };
apps/server/src/provider/Drivers/ClaudeDriver.ts
+268 -263
@@ -113,288 +113,293 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.
113 configSchema: ClaudeSettings,
114 defaultConfig: (): ClaudeSettings => decodeClaudeSettings({}),
115 usage: claudeUsageReader,
116 - create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
117 - Effect.gen(function* () {
118 - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
119 - const fileSystem = yield* FileSystem.FileSystem;
120 - const path = yield* Path.Path;
121 - // The server cwd is $HOME in packaged desktop builds, and `claude`
122 - // wrappers that scope themselves to their cwd refuse to run there.
123 - const { stateDir } = yield* ServerConfig.ServerConfig;
124 - const httpClient = yield* HttpClient.HttpClient;
125 - const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
126 - const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator;
127 - const catalogService = yield* ModelCatalog.ModelCatalog;
128 - const modelCatalog = catalogService
129 - .current(DRIVER_KIND)
130 - .pipe(Effect.map(resolveClaudeModelCatalog));
131 - const processEnv = yield* mergeProviderInstanceEnvironment(environment);
132 - const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
133 - driverKind: DRIVER_KIND,
134 - instanceId,
135 - });
136 - const effectiveConfig = {
137 - ...config,
138 - enabled,
139 - binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),
140 - } satisfies ClaudeSettings;
141 - const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
142 - resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
143 - binaryPath: effectiveConfig.binaryPath,
144 - env: processEnv,
145 - }).pipe(
146 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
147 - Effect.provideService(FileSystem.FileSystem, fileSystem),
148 - Effect.provideService(Path.Path, path),
149 - ),
150 - );
151 - const continuationGroupKey = yield* makeClaudeContinuationGroupKey(
152 - effectiveConfig,
153 - processEnv,
154 - );
155 - const configDir = yield* resolveClaudeHomePath(effectiveConfig, processEnv);
156 - const accountConfigPath = yield* ClaudeResetCredits.claudeAccountConfigPath(
157 - effectiveConfig.homePath.trim() || processEnv.CLAUDE_CONFIG_DIR?.trim()
158 - ? configDir
159 - : undefined,
160 - );
161 - const stampIdentity = withInstanceIdentity({
116 + create: Effect.fn("ClaudeDriver.create")(function* ({
117 + instanceId,
118 + displayName,
119 + accentColor,
120 + environment,
121 + enabled,
122 + config,
123 + }) {
124 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
125 + const fileSystem = yield* FileSystem.FileSystem;
126 + const path = yield* Path.Path;
127 + // The server cwd is $HOME in packaged desktop builds, and `claude`
128 + // wrappers that scope themselves to their cwd refuse to run there.
129 + const { stateDir } = yield* ServerConfig.ServerConfig;
130 + const httpClient = yield* HttpClient.HttpClient;
131 + const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
132 + const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator;
133 + const catalogService = yield* ModelCatalog.ModelCatalog;
134 + const modelCatalog = catalogService
135 + .current(DRIVER_KIND)
136 + .pipe(Effect.map(resolveClaudeModelCatalog));
137 + const processEnv = yield* mergeProviderInstanceEnvironment(environment);
138 + const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
139 + driverKind: DRIVER_KIND,
140 + instanceId,
141 + });
142 + const effectiveConfig = {
143 + ...config,
144 + enabled,
145 + binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),
146 + } satisfies ClaudeSettings;
147 + const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
148 + resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
149 + binaryPath: effectiveConfig.binaryPath,
150 + env: processEnv,
151 + }).pipe(
152 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
153 + Effect.provideService(FileSystem.FileSystem, fileSystem),
154 + Effect.provideService(Path.Path, path),
155 + ),
156 + );
157 + const continuationGroupKey = yield* makeClaudeContinuationGroupKey(effectiveConfig, processEnv);
158 + const configDir = yield* resolveClaudeHomePath(effectiveConfig, processEnv);
159 + const accountConfigPath = yield* ClaudeResetCredits.claudeAccountConfigPath(
160 + effectiveConfig.homePath.trim() || processEnv.CLAUDE_CONFIG_DIR?.trim()
161 + ? configDir
162 + : undefined,
163 + );
164 + const stampIdentity = withInstanceIdentity({
165 + instanceId,
166 + driverKind: DRIVER_KIND,
167 + displayName,
168 + accentColor,
169 + continuationGroupKey,
170 + });
171 +
172 + const scopedLimitNames = yield* makeClaudeScopedLimitNames;
173 + const orchestrationAdapter = yield* createClaudeAdapterV2(
174 + {
175 instanceId,
163 - driverKind: DRIVER_KIND,
176 displayName,
177 accentColor,
166 - continuationGroupKey,
167 - });
168 -
169 - const scopedLimitNames = yield* makeClaudeScopedLimitNames;
170 - const orchestrationAdapter = yield* createClaudeAdapterV2(
171 - {
172 - instanceId,
173 - displayName,
174 - accentColor,
175 - environment,
176 - enabled,
177 - config,
178 - },
179 - { scopedLimitNames, onUsageLimits: (update) => snapshot.applyUsageLimits(update) },
180 - ).pipe(
181 - Effect.mapError(
182 - (cause) =>
183 - new ProviderDriverError({
184 - driver: DRIVER_KIND,
185 - instanceId,
186 - detail: "Failed to build Claude orchestration adapter.",
187 - cause,
188 - }),
189 - ),
190 - );
191 - const textGeneration = yield* makeClaudeTextGeneration(
192 - effectiveConfig,
193 - processEnv,
194 - modelCatalog,
195 - );
178 + environment,
179 + enabled,
180 + config,
181 + },
182 + { scopedLimitNames, onUsageLimits: (update) => snapshot.applyUsageLimits(update) },
183 + ).pipe(
184 + Effect.mapError(
185 + (cause) =>
186 + new ProviderDriverError({
187 + driver: DRIVER_KIND,
188 + instanceId,
189 + detail: "Failed to build Claude orchestration adapter.",
190 + cause,
191 + }),
192 + ),
193 + );
194 + const textGeneration = yield* makeClaudeTextGeneration(
195 + effectiveConfig,
196 + processEnv,
197 + modelCatalog,
198 + );
199
197 - // Per-instance capabilities cache: keyed on binary + resolved HOME so
198 - // account-specific probes never share auth metadata across instances.
199 - // A transient miss may reuse the last account once, but its usage windows keep their age.
200 - const lastGoodCapabilities = yield* Ref.make<ClaudeCapabilitiesProbe | undefined>(undefined);
201 - const capabilitiesProbeCache = yield* Cache.makeWith(
202 - () =>
203 - probeClaudeCapabilities(effectiveConfig, processEnv, stateDir).pipe(
204 - Effect.flatMap((capabilities) =>
205 - ClaudeResetCredits.readClaudeOrganizationId(accountConfigPath).pipe(
206 - Effect.map((workspaceId) => ({
207 - _tag: "fresh" as const,
208 - capabilities:
209 - workspaceId === undefined ? capabilities : { ...capabilities, workspaceId },
210 - })),
211 - ),
200 + // Per-instance capabilities cache: keyed on binary + resolved HOME so
201 + // account-specific probes never share auth metadata across instances.
202 + // A transient miss may reuse the last account once, but its usage windows keep their age.
203 + const lastGoodCapabilities = yield* Ref.make<ClaudeCapabilitiesProbe | undefined>(undefined);
204 + const capabilitiesProbeCache = yield* Cache.makeWith(
205 + () =>
206 + probeClaudeCapabilities(effectiveConfig, processEnv, stateDir).pipe(
207 + Effect.flatMap((capabilities) =>
208 + ClaudeResetCredits.readClaudeOrganizationId(accountConfigPath).pipe(
209 + Effect.map((workspaceId) => ({
210 + _tag: "fresh" as const,
211 + capabilities:
212 + workspaceId === undefined ? capabilities : { ...capabilities, workspaceId },
213 + })),
214 ),
213 - Effect.tap(({ capabilities }) => Ref.set(lastGoodCapabilities, capabilities)),
214 - Effect.catch((error) =>
215 - Ref.getAndSet(lastGoodCapabilities, undefined).pipe(
216 - Effect.flatMap((capabilities) =>
217 - capabilities === undefined
218 - ? Effect.fail(error)
219 - : ClaudeResetCredits.readClaudeOrganizationId(accountConfigPath).pipe(
220 - Effect.flatMap((workspaceId) =>
221 - workspaceId === capabilities.workspaceId
222 - ? Effect.succeed({
223 - _tag: "fallback" as const,
224 - capabilities: withoutUsage(capabilities),
225 - })
226 - : Effect.fail(error),
227 - ),
215 + ),
216 + Effect.tap(({ capabilities }) => Ref.set(lastGoodCapabilities, capabilities)),
217 + Effect.catch((error) =>
218 + Ref.getAndSet(lastGoodCapabilities, undefined).pipe(
219 + Effect.flatMap((capabilities) =>
220 + capabilities === undefined
221 + ? Effect.fail(error)
222 + : ClaudeResetCredits.readClaudeOrganizationId(accountConfigPath).pipe(
223 + Effect.flatMap((workspaceId) =>
224 + workspaceId === capabilities.workspaceId
225 + ? Effect.succeed({
226 + _tag: "fallback" as const,
227 + capabilities: withoutUsage(capabilities),
228 + })
229 + : Effect.fail(error),
230 ),
229 - ),
231 + ),
232 ),
233 ),
232 - Effect.provideService(FileSystem.FileSystem, fileSystem),
233 - Effect.provideService(Path.Path, path),
234 ),
235 - {
236 - capacity: 1,
237 - timeToLive: (exit) =>
238 - // Only a fresh probe earns the TTL; a failure or its fallback retries on the next check.
239 - Exit.isSuccess(exit) && exit.value._tag === "fresh"
240 - ? CAPABILITIES_PROBE_TTL
241 - : Duration.zero,
242 - },
243 - );
244 - const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(
245 - effectiveConfig,
246 - stateDir,
247 - processEnv,
248 - );
249 - const resolveCapabilities = Cache.get(capabilitiesProbeCache, capabilitiesCacheKey).pipe(
250 - Effect.map((result) => result.capabilities),
251 - );
235 + Effect.provideService(FileSystem.FileSystem, fileSystem),
236 + Effect.provideService(Path.Path, path),
237 + ),
238 + {
239 + capacity: 1,
240 + timeToLive: (exit) =>
241 + // Only a fresh probe earns the TTL; a failure or its fallback retries on the next check.
242 + Exit.isSuccess(exit) && exit.value._tag === "fresh"
243 + ? CAPABILITIES_PROBE_TTL
244 + : Duration.zero,
245 + },
246 + );
247 + const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(
248 + effectiveConfig,
249 + stateDir,
250 + processEnv,
251 + );
252 + const resolveCapabilities = Cache.get(capabilitiesProbeCache, capabilitiesCacheKey).pipe(
253 + Effect.map((result) => result.capabilities),
254 + );
255
253 - const checkProvider = catalogService.refreshInBackground.pipe(
254 - Effect.andThen(
255 - modelCatalog.pipe(
256 - Effect.flatMap((catalog) =>
257 - checkClaudeProviderStatus(
258 - effectiveConfig,
259 - () => resolveCapabilities,
260 - processEnv,
261 - stateDir,
262 - catalog,
263 - scopedLimitNames,
264 - (version) =>
265 - ClaudeResetCredits.readClaudeResetCredits(configDir, version).pipe(
266 - Effect.provideService(HttpClient.HttpClient, httpClient),
267 - Effect.provideService(FileSystem.FileSystem, fileSystem),
268 - Effect.provideService(Path.Path, path),
269 - ),
270 - ),
256 + const checkProvider = catalogService.refreshInBackground.pipe(
257 + Effect.andThen(
258 + modelCatalog.pipe(
259 + Effect.flatMap((catalog) =>
260 + checkClaudeProviderStatus(
261 + effectiveConfig,
262 + () => resolveCapabilities,
263 + processEnv,
264 + stateDir,
265 + catalog,
266 + scopedLimitNames,
267 + (version) =>
268 + ClaudeResetCredits.readClaudeResetCredits(configDir, version).pipe(
269 + Effect.provideService(HttpClient.HttpClient, httpClient),
270 + Effect.provideService(FileSystem.FileSystem, fileSystem),
271 + Effect.provideService(Path.Path, path),
272 + ),
273 ),
272 - Effect.map(stampIdentity),
274 ),
275 + Effect.map(stampIdentity),
276 ),
275 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
276 - Effect.provideService(FileSystem.FileSystem, fileSystem),
277 - Effect.provideService(Path.Path, path),
278 - );
277 + ),
278 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
279 + Effect.provideService(FileSystem.FileSystem, fileSystem),
280 + Effect.provideService(Path.Path, path),
281 + );
282
280 - const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
281 - const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<ClaudeSettings>>({
282 - resolveMaintenance,
283 - getSettings: snapshotSettings.getSettings,
284 - streamSettings: snapshotSettings.streamSettings,
285 - haveSettingsChanged: haveProviderSnapshotSettingsChanged,
286 - initialSnapshot: (settings) =>
287 - modelCatalog.pipe(
288 - Effect.flatMap((catalog) => makePendingClaudeProvider(settings.provider, catalog)),
289 - Effect.map(stampIdentity),
290 - ),
291 - checkProvider,
292 - enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
293 - resolveMaintenance().pipe(
294 - Effect.flatMap((maintenanceCapabilities) =>
295 - enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
296 - enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
297 - }),
298 - ),
299 - Effect.provideService(HttpClient.HttpClient, httpClient),
300 - Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
301 - Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
302 - ),
303 - }).pipe(
304 - Effect.mapError(
305 - (cause) =>
306 - new ProviderDriverError({
307 - driver: DRIVER_KIND,
308 - instanceId,
309 - detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,
310 - cause,
283 + const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
284 + const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<ClaudeSettings>>({
285 + resolveMaintenance,
286 + getSettings: snapshotSettings.getSettings,
287 + streamSettings: snapshotSettings.streamSettings,
288 + haveSettingsChanged: haveProviderSnapshotSettingsChanged,
289 + initialSnapshot: (settings) =>
290 + modelCatalog.pipe(
291 + Effect.flatMap((catalog) => makePendingClaudeProvider(settings.provider, catalog)),
292 + Effect.map(stampIdentity),
293 + ),
294 + checkProvider,
295 + enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
296 + resolveMaintenance().pipe(
297 + Effect.flatMap((maintenanceCapabilities) =>
298 + enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
299 + enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
300 }),
301 + ),
302 + Effect.provideService(HttpClient.HttpClient, httpClient),
303 + Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
304 + Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
305 ),
313 - );
306 + }).pipe(
307 + Effect.mapError(
308 + (cause) =>
309 + new ProviderDriverError({
310 + driver: DRIVER_KIND,
311 + instanceId,
312 + detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,
313 + cause,
314 + }),
315 + ),
316 + );
317
315 - // Same rules as Codex: serialised on the config directory that holds the
316 - // login, one request id kept until Claude answers (a cooldown or rate
317 - // limit is an answer), then a re-probe.
318 - const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = () =>
319 - Effect.gen(function* () {
320 - const current = yield* snapshot.getSnapshot;
321 - const grantId = current.usageLimits?.resetCredits?.nextCreditId;
322 - if (!grantId || !current.version) return "noCredit" as const;
323 - const version = current.version;
324 - return yield* resetCreditCoordinator.redeem(
325 - configDir,
326 - (requestId) =>
327 - ClaudeResetCredits.consumeClaudeResetCredit({
328 - configDir,
329 - accountConfigPath,
330 - version,
331 - grantId,
332 - requestId,
333 - }),
334 - ClaudeResetCredits.isSettledClaudeResetCreditFailure,
335 - );
336 - }).pipe(
337 - Effect.provideService(HttpClient.HttpClient, httpClient),
338 - Effect.provideService(FileSystem.FileSystem, fileSystem),
339 - Effect.provideService(Path.Path, path),
340 - Effect.mapError(
341 - (cause) =>
342 - new ProviderDriverError({
343 - driver: DRIVER_KIND,
344 - instanceId,
345 - detail:
346 - cause._tag === "ClaudeResetCreditError"
347 - ? cause.message
348 - : "Claude could not redeem the reset.",
349 - cause,
350 - }),
351 - ),
352 - Effect.tap((outcome) =>
353 - Effect.gen(function* () {
354 - const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;
355 - yield* Cache.invalidateAll(capabilitiesProbeCache);
356 - const refreshed = yield* snapshot.refresh;
357 - const after = refreshed.usageLimits?.checkedAt;
358 - if (
359 - outcome === "reset" &&
360 - (after === undefined ||
361 - after === before ||
362 - refreshed.usageLimits?.unavailable?.reason === "probeFailed")
363 - ) {
364 - return yield* new ProviderDriverError({
365 - driver: DRIVER_KIND,
366 - instanceId,
367 - detail:
368 - "The reset was applied, but Claude could not confirm the new limits. Refresh to check.",
369 - });
370 - }
318 + // Same rules as Codex: serialised on the config directory that holds the
319 + // login, one request id kept until Claude answers (a cooldown or rate
320 + // limit is an answer), then a re-probe.
321 + const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = Effect.fn(
322 + "ClaudeDriver.consumeResetCredit",
323 + )(
324 + function* () {
325 + const current = yield* snapshot.getSnapshot;
326 + const grantId = current.usageLimits?.resetCredits?.nextCreditId;
327 + if (!grantId || !current.version) return "noCredit" as const;
328 + const version = current.version;
329 + return yield* resetCreditCoordinator.redeem(
330 + configDir,
331 + (requestId) =>
332 + ClaudeResetCredits.consumeClaudeResetCredit({
333 + configDir,
334 + accountConfigPath,
335 + version,
336 + grantId,
337 + requestId,
338 }),
372 - ),
339 + ClaudeResetCredits.isSettledClaudeResetCreditFailure,
340 );
341 + },
342 + Effect.provideService(HttpClient.HttpClient, httpClient),
343 + Effect.provideService(FileSystem.FileSystem, fileSystem),
344 + Effect.provideService(Path.Path, path),
345 + Effect.mapError(
346 + (cause) =>
347 + new ProviderDriverError({
348 + driver: DRIVER_KIND,
349 + instanceId,
350 + detail:
351 + cause._tag === "ClaudeResetCreditError"
352 + ? cause.message
353 + : "Claude could not redeem the reset.",
354 + cause,
355 + }),
356 + ),
357 + Effect.tap((outcome) =>
358 + Effect.gen(function* () {
359 + const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;
360 + yield* Cache.invalidateAll(capabilitiesProbeCache);
361 + const refreshed = yield* snapshot.refresh;
362 + const after = refreshed.usageLimits?.checkedAt;
363 + if (
364 + outcome === "reset" &&
365 + (after === undefined ||
366 + after === before ||
367 + refreshed.usageLimits?.unavailable?.reason === "probeFailed")
368 + ) {
369 + return yield* new ProviderDriverError({
370 + driver: DRIVER_KIND,
371 + instanceId,
372 + detail:
373 + "The reset was applied, but Claude could not confirm the new limits. Refresh to check.",
374 + });
375 + }
376 + }),
377 + ),
378 + );
379
375 - return {
376 - instanceId,
377 - driverKind: DRIVER_KIND,
378 - continuationIdentity: {
379 - ...fallbackContinuationIdentity,
380 - continuationKey: continuationGroupKey,
381 - },
382 - displayName,
383 - accentColor,
384 - enabled,
385 - snapshot,
386 - invalidateCaches: Cache.invalidateAll(capabilitiesProbeCache),
387 - snapshotForCwd: (cwd: string) =>
388 - snapshot.getSnapshot.pipe(
389 - Effect.flatMap((machineSnapshot) =>
390 - probeClaudeWorkspaceSnapshot(effectiveConfig, machineSnapshot, cwd, processEnv),
391 - ),
392 - Effect.provideService(FileSystem.FileSystem, fileSystem),
393 - Effect.provideService(Path.Path, path),
380 + return {
381 + instanceId,
382 + driverKind: DRIVER_KIND,
383 + continuationIdentity: {
384 + ...fallbackContinuationIdentity,
385 + continuationKey: continuationGroupKey,
386 + },
387 + displayName,
388 + accentColor,
389 + enabled,
390 + snapshot,
391 + invalidateCaches: Cache.invalidateAll(capabilitiesProbeCache),
392 + snapshotForCwd: (cwd: string) =>
393 + snapshot.getSnapshot.pipe(
394 + Effect.flatMap((machineSnapshot) =>
395 + probeClaudeWorkspaceSnapshot(effectiveConfig, machineSnapshot, cwd, processEnv),
396 ),
395 - orchestrationAdapter,
396 - textGeneration,
397 - consumeResetCredit,
398 - } satisfies ProviderInstance;
399 - }),
397 + Effect.provideService(FileSystem.FileSystem, fileSystem),
398 + Effect.provideService(Path.Path, path),
399 + ),
400 + orchestrationAdapter,
401 + textGeneration,
402 + consumeResetCredit,
403 + } satisfies ProviderInstance;
404 + }),
405 };
apps/server/src/provider/Drivers/CodexDriver.ts
+226 -220
@@ -106,246 +106,252 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv, Path.Pat
106 configSchema: CodexSettings,
107 defaultConfig: (): CodexSettings => decodeCodexSettings({}),
108 usage: codexUsageReader,
109 - create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
110 - Effect.gen(function* () {
111 - if (config.setupMode === "managed")
112 - return yield* makeManagedCodexProvider({
113 - instanceId,
114 - displayName,
115 - accentColor,
116 - environment,
117 - enabled,
118 - config,
119 - });
120 - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
121 - const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator;
122 - const fileSystem = yield* FileSystem.FileSystem;
123 - const pathService = yield* Path.Path;
124 - const httpClient = yield* HttpClient.HttpClient;
125 - const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
126 - const modelCatalog = yield* ModelCatalog.ModelCatalog;
127 - const currentCatalog = modelCatalog.current(DRIVER_KIND);
128 - const processEnv = yield* mergeProviderInstanceEnvironment(environment);
129 - const homeLayout = yield* resolveCodexHomeLayout(config);
130 - const continuationIdentity = codexContinuationIdentity(homeLayout);
131 - const stampIdentity = withInstanceIdentity({
109 + create: Effect.fn("CodexDriver.create")(function* ({
110 + instanceId,
111 + displayName,
112 + accentColor,
113 + environment,
114 + enabled,
115 + config,
116 + }) {
117 + if (config.setupMode === "managed")
118 + return yield* makeManagedCodexProvider({
119 instanceId,
133 - driverKind: DRIVER_KIND,
120 displayName,
121 accentColor,
136 - continuationGroupKey: continuationIdentity.continuationKey,
137 - });
138 - yield* materializeCodexShadowHome(homeLayout).pipe(
139 - Effect.mapError(
140 - (cause) =>
141 - new ProviderDriverError({
142 - driver: DRIVER_KIND,
143 - instanceId,
144 - detail: cause.message,
145 - cause,
146 - }),
147 - ),
148 - );
149 - const effectiveConfig = {
150 - ...config,
122 + environment,
123 enabled,
152 - binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),
153 - homePath: homeLayout.effectiveHomePath ?? "",
154 - } satisfies CodexSettings;
155 - const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
156 - resolveProviderMaintenanceCapabilitiesEffect(
157 - makeCodexMaintenanceResolver(homeLayout.sharedHomePath),
158 - {
159 - binaryPath: effectiveConfig.binaryPath,
160 - env: processEnv,
161 - },
162 - ).pipe(
163 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
164 - Effect.provideService(FileSystem.FileSystem, fileSystem),
165 - Effect.provideService(Path.Path, pathService),
166 - ),
167 - );
168 -
169 - const orchestrationAdapter = yield* createCodexAdapterV2(
124 + config,
125 + });
126 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
127 + const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator;
128 + const fileSystem = yield* FileSystem.FileSystem;
129 + const pathService = yield* Path.Path;
130 + const httpClient = yield* HttpClient.HttpClient;
131 + const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
132 + const modelCatalog = yield* ModelCatalog.ModelCatalog;
133 + const currentCatalog = modelCatalog.current(DRIVER_KIND);
134 + const processEnv = yield* mergeProviderInstanceEnvironment(environment);
135 + const homeLayout = yield* resolveCodexHomeLayout(config);
136 + const continuationIdentity = codexContinuationIdentity(homeLayout);
137 + const stampIdentity = withInstanceIdentity({
138 + instanceId,
139 + driverKind: DRIVER_KIND,
140 + displayName,
141 + accentColor,
142 + continuationGroupKey: continuationIdentity.continuationKey,
143 + });
144 + yield* materializeCodexShadowHome(homeLayout).pipe(
145 + Effect.mapError(
146 + (cause) =>
147 + new ProviderDriverError({
148 + driver: DRIVER_KIND,
149 + instanceId,
150 + detail: cause.message,
151 + cause,
152 + }),
153 + ),
154 + );
155 + const effectiveConfig = {
156 + ...config,
157 + enabled,
158 + binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),
159 + homePath: homeLayout.effectiveHomePath ?? "",
160 + } satisfies CodexSettings;
161 + const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
162 + resolveProviderMaintenanceCapabilitiesEffect(
163 + makeCodexMaintenanceResolver(homeLayout.sharedHomePath),
164 {
171 - instanceId,
172 - displayName,
173 - accentColor,
174 - environment,
175 - enabled,
176 - config,
165 + binaryPath: effectiveConfig.binaryPath,
166 + env: processEnv,
167 },
178 - { onUsageLimits: (update) => snapshot.applyUsageLimits(update) },
168 ).pipe(
180 - Effect.mapError(
181 - (cause) =>
182 - new ProviderDriverError({
183 - driver: DRIVER_KIND,
184 - instanceId,
185 - detail: "Failed to build Codex orchestration adapter.",
186 - cause,
187 - }),
188 - ),
189 - );
190 -
191 - // Kick the TTL-gated manifest refresh in the background and classify with the in-memory
192 - // manifest, so a slow or hung fetch never delays the provider check.
193 - const checkProvider = modelCatalog.refreshInBackground.pipe(
194 - Effect.andThen(
195 - Effect.zipWith(
196 - checkCodexProviderStatus(effectiveConfig, undefined, processEnv),
197 - currentCatalog,
198 - (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),
199 - { concurrent: true },
200 - ),
201 - ),
169 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
170 Effect.provideService(FileSystem.FileSystem, fileSystem),
171 Effect.provideService(Path.Path, pathService),
205 - );
206 - const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
207 - const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({
208 - resolveMaintenance,
209 - getSettings: snapshotSettings.getSettings,
210 - streamSettings: snapshotSettings.streamSettings,
211 - haveSettingsChanged: haveProviderSnapshotSettingsChanged,
212 - initialSnapshot: (settings) =>
213 - Effect.zipWith(
214 - makePendingCodexProvider(settings.provider),
215 - currentCatalog,
216 - (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),
217 - ),
218 - checkProvider,
219 - enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
220 - resolveMaintenance().pipe(
221 - Effect.flatMap((maintenanceCapabilities) =>
222 - enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
223 - enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
224 - }),
225 - ),
226 - Effect.provideService(HttpClient.HttpClient, httpClient),
227 - Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
228 - Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
229 - ),
230 - }).pipe(
231 - Effect.mapError(
232 - (cause) =>
233 - new ProviderDriverError({
234 - driver: DRIVER_KIND,
235 - instanceId,
236 - detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,
237 - cause,
172 + ),
173 + );
174 +
175 + const orchestrationAdapter = yield* createCodexAdapterV2(
176 + {
177 + instanceId,
178 + displayName,
179 + accentColor,
180 + environment,
181 + enabled,
182 + config,
183 + },
184 + { onUsageLimits: (update) => snapshot.applyUsageLimits(update) },
185 + ).pipe(
186 + Effect.mapError(
187 + (cause) =>
188 + new ProviderDriverError({
189 + driver: DRIVER_KIND,
190 + instanceId,
191 + detail: "Failed to build Codex orchestration adapter.",
192 + cause,
193 + }),
194 + ),
195 + );
196 +
197 + // Kick the TTL-gated manifest refresh in the background and classify with the in-memory
198 + // manifest, so a slow or hung fetch never delays the provider check.
199 + const checkProvider = modelCatalog.refreshInBackground.pipe(
200 + Effect.andThen(
201 + Effect.zipWith(
202 + checkCodexProviderStatus(effectiveConfig, undefined, processEnv),
203 + currentCatalog,
204 + (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),
205 + { concurrent: true },
206 + ),
207 + ),
208 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
209 + Effect.provideService(FileSystem.FileSystem, fileSystem),
210 + Effect.provideService(Path.Path, pathService),
211 + );
212 + const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
213 + const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({
214 + resolveMaintenance,
215 + getSettings: snapshotSettings.getSettings,
216 + streamSettings: snapshotSettings.streamSettings,
217 + haveSettingsChanged: haveProviderSnapshotSettingsChanged,
218 + initialSnapshot: (settings) =>
219 + Effect.zipWith(
220 + makePendingCodexProvider(settings.provider),
221 + currentCatalog,
222 + (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)),
223 + ),
224 + checkProvider,
225 + enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
226 + resolveMaintenance().pipe(
227 + Effect.flatMap((maintenanceCapabilities) =>
228 + enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
229 + enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
230 }),
231 + ),
232 + Effect.provideService(HttpClient.HttpClient, httpClient),
233 + Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
234 + Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
235 ),
240 - );
241 - const textGeneration = yield* makeCodexTextGeneration(
242 - effectiveConfig,
243 - processEnv,
244 - snapshot.getSnapshot.pipe(Effect.map((value) => value.models)),
245 - );
246 - const snapshotForCwd = (cwd: string) =>
247 - !effectiveConfig.enabled
248 - ? snapshot.getSnapshot
249 - : Effect.all([
250 - snapshot.getSnapshot,
251 - probeCodexSkillsForCwd({
252 - binaryPath: effectiveConfig.binaryPath,
253 - homePath: effectiveConfig.homePath,
254 - launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
255 - cwd,
256 - environment: processEnv,
257 - }).pipe(
258 - Effect.scoped,
259 - Effect.timeout("20 seconds"),
260 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
261 - ),
262 - ]).pipe(
263 - Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })),
264 - Effect.mapError(
265 - (cause) =>
266 - new ProviderDriverError({
267 - driver: DRIVER_KIND,
268 - instanceId,
269 - detail: `Failed to probe Codex skills for '${cwd}'`,
270 - cause,
271 - }),
272 - ),
273 - );
274 -
275 - // Redemption spends something on the user's account. It serialises on
276 - // the account (instances sharing a Codex home share the credit), keeps
277 - // one idempotency key until Codex reports an outcome, and is bounded so
278 - // a hung app-server cannot hold the account lock.
279 - // Keyed on the directory holding auth.json: an auth-overlay instance has
280 - // its own account under `effectiveHomePath`, while plain instances share
281 - // the common home. The continuation key would conflate the two.
282 - const accountKey = homeLayout.effectiveHomePath ?? homeLayout.sharedHomePath;
283 - const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = () =>
284 - resetCreditCoordinator
285 - .redeem(accountKey, (idempotencyKey) =>
286 - Effect.gen(function* () {
287 - const { client } = yield* withCodexAppServerClient({
288 - binaryPath: effectiveConfig.binaryPath,
289 - homePath: effectiveConfig.homePath,
290 - launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
291 - cwd: process.cwd(),
292 - environment: processEnv,
293 - });
294 - const response = yield* client.request("account/rateLimitResetCredit/consume", {
295 - idempotencyKey,
296 - });
297 - return response.outcome;
298 - }).pipe(Effect.scoped, Effect.timeout("20 seconds")),
299 - )
300 - .pipe(
301 - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
236 + }).pipe(
237 + Effect.mapError(
238 + (cause) =>
239 + new ProviderDriverError({
240 + driver: DRIVER_KIND,
241 + instanceId,
242 + detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,
243 + cause,
244 + }),
245 + ),
246 + );
247 + const textGeneration = yield* makeCodexTextGeneration(
248 + effectiveConfig,
249 + processEnv,
250 + snapshot.getSnapshot.pipe(Effect.map((value) => value.models)),
251 + );
252 + const snapshotForCwd = (cwd: string) =>
253 + !effectiveConfig.enabled
254 + ? snapshot.getSnapshot
255 + : Effect.all([
256 + snapshot.getSnapshot,
257 + probeCodexSkillsForCwd({
258 + binaryPath: effectiveConfig.binaryPath,
259 + homePath: effectiveConfig.homePath,
260 + launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
261 + cwd,
262 + environment: processEnv,
263 + }).pipe(
264 + Effect.scoped,
265 + Effect.timeout("20 seconds"),
266 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
267 + ),
268 + ]).pipe(
269 + Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })),
270 Effect.mapError(
271 (cause) =>
272 new ProviderDriverError({
273 driver: DRIVER_KIND,
274 instanceId,
307 - detail: "Codex could not redeem the reset credit.",
275 + detail: `Failed to probe Codex skills for '${cwd}'`,
276 cause,
277 }),
278 ),
311 - // The windows just changed; re-probe so the snapshot says so. A
312 - // failed probe republishes the pre-redemption limits rather than
313 - // marking them failed, so "confirmed" means `checkedAt` moved past
314 - // what was published before the redemption started.
315 - Effect.tap((outcome) =>
316 - Effect.gen(function* () {
317 - const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;
318 - const refreshed = yield* snapshot.refresh;
319 - const after = refreshed.usageLimits?.checkedAt;
320 - if (
321 - outcome === "reset" &&
322 - (after === undefined ||
323 - after === before ||
324 - refreshed.usageLimits?.unavailable?.reason === "probeFailed")
325 - ) {
326 - return yield* new ProviderDriverError({
327 - driver: DRIVER_KIND,
328 - instanceId,
329 - detail:
330 - "The reset was applied, but Codex could not confirm the new limits. Refresh to check.",
331 - });
332 - }
333 - }),
334 - ),
279 );
280
337 - return {
338 - instanceId,
339 - driverKind: DRIVER_KIND,
340 - continuationIdentity,
341 - displayName,
342 - accentColor,
343 - enabled,
344 - snapshot,
345 - snapshotForCwd,
346 - consumeResetCredit,
347 - orchestrationAdapter,
348 - textGeneration,
349 - } satisfies ProviderInstance;
350 - }),
281 + // Redemption spends something on the user's account. It serialises on
282 + // the account (instances sharing a Codex home share the credit), keeps
283 + // one idempotency key until Codex reports an outcome, and is bounded so
284 + // a hung app-server cannot hold the account lock.
285 + // Keyed on the directory holding auth.json: an auth-overlay instance has
286 + // its own account under `effectiveHomePath`, while plain instances share
287 + // the common home. The continuation key would conflate the two.
288 + const accountKey = homeLayout.effectiveHomePath ?? homeLayout.sharedHomePath;
289 + const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = () =>
290 + resetCreditCoordinator
291 + .redeem(accountKey, (idempotencyKey) =>
292 + Effect.gen(function* () {
293 + const { client } = yield* withCodexAppServerClient({
294 + binaryPath: effectiveConfig.binaryPath,
295 + homePath: effectiveConfig.homePath,
296 + launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv),
297 + cwd: process.cwd(),
298 + environment: processEnv,
299 + });
300 + const response = yield* client.request("account/rateLimitResetCredit/consume", {
301 + idempotencyKey,
302 + });
303 + return response.outcome;
304 + }).pipe(Effect.scoped, Effect.timeout("20 seconds")),
305 + )
306 + .pipe(
307 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
308 + Effect.mapError(
309 + (cause) =>
310 + new ProviderDriverError({
311 + driver: DRIVER_KIND,
312 + instanceId,
313 + detail: "Codex could not redeem the reset credit.",
314 + cause,
315 + }),
316 + ),
317 + // The windows just changed; re-probe so the snapshot says so. A
318 + // failed probe republishes the pre-redemption limits rather than
319 + // marking them failed, so "confirmed" means `checkedAt` moved past
320 + // what was published before the redemption started.
321 + Effect.tap((outcome) =>
322 + Effect.gen(function* () {
323 + const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;
324 + const refreshed = yield* snapshot.refresh;
325 + const after = refreshed.usageLimits?.checkedAt;
326 + if (
327 + outcome === "reset" &&
328 + (after === undefined ||
329 + after === before ||
330 + refreshed.usageLimits?.unavailable?.reason === "probeFailed")
331 + ) {
332 + return yield* new ProviderDriverError({
333 + driver: DRIVER_KIND,
334 + instanceId,
335 + detail:
336 + "The reset was applied, but Codex could not confirm the new limits. Refresh to check.",
337 + });
338 + }
339 + }),
340 + ),
341 + );
342 +
343 + return {
344 + instanceId,
345 + driverKind: DRIVER_KIND,
346 + continuationIdentity,
347 + displayName,
348 + accentColor,
349 + enabled,
350 + snapshot,
351 + snapshotForCwd,
352 + consumeResetCredit,
353 + orchestrationAdapter,
354 + textGeneration,
355 + } satisfies ProviderInstance;
356 + }),
357 };
apps/server/src/provider/Drivers/antigravityUsageReader.ts
+40 -38
@@ -433,47 +433,49 @@ export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function*
433 cache?.set(canonical, { fingerprint, candidates });
434 return candidates;
435 });
436 - const walk = (directory: string, root: string): Effect.Effect<void> =>
437 - Effect.gen(function* () {
438 - const names = yield* fileSystem.readDirectory(directory).pipe(
439 - Effect.catchTags({
440 - PlatformError: (cause) => {
441 - if (cause.reason._tag !== "NotFound") errors.push(directory);
442 - return Effect.succeed(null);
443 - },
444 - }),
445 - );
446 - if (names === null) return;
447 - names.sort((a, b) => a.localeCompare(b));
448 - for (const name of names) {
449 - const path = pathService.join(directory, name);
450 - // Like a directory listing's entry types: symlinks are neither files nor directories.
451 - const isLink = Exit.isSuccess(yield* Effect.exit(fileSystem.readLink(path)));
452 - const type = isLink
453 - ? "SymbolicLink"
454 - : yield* fileSystem.stat(path).pipe(
455 - Effect.map((info) => info.type),
456 - Effect.orElseSucceed(() => null),
457 - );
458 - if (type === "Directory") {
459 - yield* walk(path, root);
460 - } else if ((type === "File" || type === null) && name.endsWith(".db")) {
461 - const candidates = yield* readFile(path).pipe(
462 - Effect.catch(() => {
463 - errors.push(path);
464 - return Effect.succeed(null);
465 - }),
436 + const walk = Effect.fn("antigravityUsageReader.walk")(function* (
437 + directory: string,
438 + root: string,
439 + ): Effect.fn.Return<void> {
440 + const names = yield* fileSystem.readDirectory(directory).pipe(
441 + Effect.catchTags({
442 + PlatformError: (cause) => {
443 + if (cause.reason._tag !== "NotFound") errors.push(directory);
444 + return Effect.succeed(null);
445 + },
446 + }),
447 + );
448 + if (names === null) return;
449 + names.sort((a, b) => a.localeCompare(b));
450 + for (const name of names) {
451 + const path = pathService.join(directory, name);
452 + // Like a directory listing's entry types: symlinks are neither files nor directories.
453 + const isLink = Exit.isSuccess(yield* Effect.exit(fileSystem.readLink(path)));
454 + const type = isLink
455 + ? "SymbolicLink"
456 + : yield* fileSystem.stat(path).pipe(
457 + Effect.map((info) => info.type),
458 + Effect.orElseSucceed(() => null),
459 );
467 - if (candidates === null) continue;
468 - const fileIndex = files.length;
469 - files.push({ root, path, records: [] });
470 - for (const [index, candidate] of candidates.entries()) {
471 - append(candidate, fileIndex);
472 - if (index % 256 === 255) yield* Effect.yieldNow;
473 - }
460 + if (type === "Directory") {
461 + yield* walk(path, root);
462 + } else if ((type === "File" || type === null) && name.endsWith(".db")) {
463 + const candidates = yield* readFile(path).pipe(
464 + Effect.catch(() => {
465 + errors.push(path);
466 + return Effect.succeed(null);
467 + }),
468 + );
469 + if (candidates === null) continue;
470 + const fileIndex = files.length;
471 + files.push({ root, path, records: [] });
472 + for (const [index, candidate] of candidates.entries()) {
473 + append(candidate, fileIndex);
474 + if (index % 256 === 255) yield* Effect.yieldNow;
475 }
476 }
476 - });
477 + }
478 + });
479 for (const root of roots) yield* walk(root, root);
480 if (cache !== undefined) {
481 for (const key of cache.keys()) if (!visited.has(key)) cache.delete(key);
apps/server/src/provider/ProviderAuthService.ts
+6 -3
@@ -10,6 +10,7 @@ import {
10 } from "@t3tools/contracts";
11 import * as Context from "effect/Context";
12 import * as Effect from "effect/Effect";
13 +import * as Function from "effect/Function";
14 import * as Layer from "effect/Layer";
15 import type * as Scope from "effect/Scope";
16 import * as Stream from "effect/Stream";
@@ -267,8 +268,8 @@ export const makeProviderAuthService = Effect.gen(function* () {
268 }),
269 );
270 }),
270 - subscribe: (input, ownerSessionId) =>
271 - Effect.gen(function* () {
271 + subscribe: Function.flow(
272 + Effect.fn("ProviderAuthService.subscribe")(function* (input, ownerSessionId) {
273 const changes = yield* registry.subscribeChanges;
274 const initial = yield* getController(input.instanceId, "subscribe");
275 return Stream.concat(
@@ -280,7 +281,9 @@ export const makeProviderAuthService = Effect.gen(function* () {
281 Stream.changesWith((previous, next) => previous === next),
282 Stream.switchMap((auth) => auth.subscribe(ownerSessionId)),
283 );
283 - }).pipe(Stream.unwrap),
284 + }),
285 + Stream.unwrap,
286 + ),
287 tryHandlePromptCommand: Effect.fn("ProviderAuthService.tryHandlePromptCommand")(
288 function* (input) {
289 const instance = yield* registry.getInstance(input.instanceId);
apps/server/src/provider/ProviderInstanceRegistry.ts
+120 -120
@@ -70,98 +70,97 @@ const resolveEntryEnabled = (entry: ProviderInstanceConfig, typedConfig: unknown
70 return entry.enabled ?? providerInstanceConfigEnabledFlag(typedConfig) ?? true;
71 };
72
73 -const buildEntry = <R>(input: {
73 +const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* <R>(input: {
74 readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;
75 readonly parentScope: Scope.Scope;
76 readonly instanceId: ProviderInstanceId;
77 readonly rawInstanceId: string;
78 readonly entry: ProviderInstanceConfig;
79 -}): Effect.Effect<
79 +}): Effect.fn.Return<
80 | { readonly kind: "live"; readonly live: LiveEntry }
81 | { readonly kind: "unavailable"; readonly snapshot: ServerProvider },
82 never,
83 R
84 -> =>
85 - Effect.gen(function* () {
86 - const { driversById, parentScope, instanceId, rawInstanceId, entry } = input;
87 - const driver = driversById.get(entry.driver);
88 - if (!driver) {
89 - return {
90 - kind: "unavailable" as const,
91 - snapshot: yield* buildUnavailableProviderSnapshot({
92 - driverKind: entry.driver,
93 - instanceId,
94 - displayName: entry.displayName,
95 - accentColor: entry.accentColor,
96 - reason: `Driver '${entry.driver}' is not registered in this build.`,
97 - }),
98 - };
99 - }
100 -
101 - const decoder = Schema.decodeUnknownEffect(driver.configSchema);
102 - const decodeResult = yield* decoder(entry.config ?? driver.defaultConfig()).pipe(Effect.result);
103 - if (decodeResult._tag === "Failure") {
104 - const issue = decodeResult.failure;
105 - const detail = issue.message ?? String(issue);
106 - yield* Effect.logError("Failed to decode provider instance config", {
107 - instanceId: rawInstanceId,
108 - driver: entry.driver,
109 - detail,
110 - });
111 - return {
112 - kind: "unavailable" as const,
113 - snapshot: yield* buildUnavailableProviderSnapshot({
114 - driverKind: entry.driver,
115 - instanceId,
116 - displayName: entry.displayName,
117 - accentColor: entry.accentColor,
118 - reason: `Invalid config for instance '${rawInstanceId}': ${detail}`,
119 - }),
120 - };
121 - }
122 -
123 - const typedConfig = decodeResult.success;
124 - const childScope = yield* Scope.make();
125 - yield* Scope.addFinalizer(parentScope, Scope.close(childScope, Exit.void).pipe(Effect.ignore));
84 +> {
85 + const { driversById, parentScope, instanceId, rawInstanceId, entry } = input;
86 + const driver = driversById.get(entry.driver);
87 + if (!driver) {
88 + return {
89 + kind: "unavailable" as const,
90 + snapshot: yield* buildUnavailableProviderSnapshot({
91 + driverKind: entry.driver,
92 + instanceId,
93 + displayName: entry.displayName,
94 + accentColor: entry.accentColor,
95 + reason: `Driver '${entry.driver}' is not registered in this build.`,
96 + }),
97 + };
98 + }
99
127 - const createResult = yield* driver
128 - .create({
100 + const decoder = Schema.decodeUnknownEffect(driver.configSchema);
101 + const decodeResult = yield* decoder(entry.config ?? driver.defaultConfig()).pipe(Effect.result);
102 + if (decodeResult._tag === "Failure") {
103 + const issue = decodeResult.failure;
104 + const detail = issue.message ?? String(issue);
105 + yield* Effect.logError("Failed to decode provider instance config", {
106 + instanceId: rawInstanceId,
107 + driver: entry.driver,
108 + detail,
109 + });
110 + return {
111 + kind: "unavailable" as const,
112 + snapshot: yield* buildUnavailableProviderSnapshot({
113 + driverKind: entry.driver,
114 instanceId,
115 displayName: entry.displayName,
116 accentColor: entry.accentColor,
132 - environment: entry.environment ?? [],
133 - enabled: resolveEntryEnabled(entry, typedConfig),
134 - config: typedConfig,
135 - })
136 - .pipe(Effect.provideService(Scope.Scope, childScope), Effect.result);
137 - if (createResult._tag === "Failure") {
138 - yield* Effect.logError("Failed to create provider instance", {
139 - instanceId: rawInstanceId,
140 - driver: entry.driver,
141 - detail: createResult.failure.detail,
142 - });
143 - yield* Scope.close(childScope, Exit.void).pipe(Effect.ignore);
144 - return {
145 - kind: "unavailable" as const,
146 - snapshot: yield* buildUnavailableProviderSnapshot({
147 - driverKind: entry.driver,
148 - instanceId,
149 - displayName: entry.displayName,
150 - accentColor: entry.accentColor,
151 - reason: `Driver '${entry.driver}' failed to create instance: ${createResult.failure.detail}`,
152 - }),
153 - };
154 - }
117 + reason: `Invalid config for instance '${rawInstanceId}': ${detail}`,
118 + }),
119 + };
120 + }
121 +
122 + const typedConfig = decodeResult.success;
123 + const childScope = yield* Scope.make();
124 + yield* Scope.addFinalizer(parentScope, Scope.close(childScope, Exit.void).pipe(Effect.ignore));
125
126 + const createResult = yield* driver
127 + .create({
128 + instanceId,
129 + displayName: entry.displayName,
130 + accentColor: entry.accentColor,
131 + environment: entry.environment ?? [],
132 + enabled: resolveEntryEnabled(entry, typedConfig),
133 + config: typedConfig,
134 + })
135 + .pipe(Effect.provideService(Scope.Scope, childScope), Effect.result);
136 + if (createResult._tag === "Failure") {
137 + yield* Effect.logError("Failed to create provider instance", {
138 + instanceId: rawInstanceId,
139 + driver: entry.driver,
140 + detail: createResult.failure.detail,
141 + });
142 + yield* Scope.close(childScope, Exit.void).pipe(Effect.ignore);
143 return {
157 - kind: "live" as const,
158 - live: {
159 - instance: createResult.success,
160 - scope: childScope,
161 - entry,
162 - },
144 + kind: "unavailable" as const,
145 + snapshot: yield* buildUnavailableProviderSnapshot({
146 + driverKind: entry.driver,
147 + instanceId,
148 + displayName: entry.displayName,
149 + accentColor: entry.accentColor,
150 + reason: `Driver '${entry.driver}' failed to create instance: ${createResult.failure.detail}`,
151 + }),
152 };
164 - });
153 + }
154 +
155 + return {
156 + kind: "live" as const,
157 + live: {
158 + instance: createResult.success,
159 + scope: childScope,
160 + entry,
161 + },
162 + };
163 +});
164
165 const makeReconcile = <R>(input: {
166 readonly state: RegistryState;
@@ -263,67 +262,68 @@ const makeReconcile = <R>(input: {
262 });
263 };
264
266 -export const makeProviderInstanceRegistry = <R>(input: {
265 +export const makeProviderInstanceRegistry = Effect.fn(
266 + "ProviderInstanceRegistry.makeProviderInstanceRegistry",
267 +)(function* <R>(input: {
268 readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
269 readonly configMap: ProviderInstanceConfigMap;
269 -}): Effect.Effect<
270 +}): Effect.fn.Return<
271 {
272 readonly registry: ProviderInstanceRegistry["Service"];
273 readonly mutator: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape;
274 },
275 never,
276 R | Scope.Scope
276 -> =>
277 - Effect.gen(function* () {
278 - const driversById = new Map<ProviderDriverKind, AnyProviderDriver<R>>(
279 - input.drivers.map((driver) => [driver.driverKind, driver]),
280 - );
277 +> {
278 + const driversById = new Map<ProviderDriverKind, AnyProviderDriver<R>>(
279 + input.drivers.map((driver) => [driver.driverKind, driver]),
280 + );
281
282 - // Capture the enclosing scope so per-instance child scopes can be
283 - // attached to it at `reconcile` time. Without this, `reconcile`
284 - // called later (e.g. from the hydration layer) would attach child
285 - // scopes to the *caller's* scope instead of the registry's.
286 - const parentScope = yield* Scope.Scope;
282 + // Capture the enclosing scope so per-instance child scopes can be
283 + // attached to it at `reconcile` time. Without this, `reconcile`
284 + // called later (e.g. from the hydration layer) would attach child
285 + // scopes to the *caller's* scope instead of the registry's.
286 + const parentScope = yield* Scope.Scope;
287
288 - const driverContext = yield* Effect.context<R>();
288 + const driverContext = yield* Effect.context<R>();
289
290 - const entries = yield* Ref.make<ReadonlyMap<ProviderInstanceId, LiveEntry>>(new Map());
291 - const unavailable = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ServerProvider>>(new Map());
292 - const changes = yield* PubSub.unbounded<void>();
293 - yield* Effect.addFinalizer(() => PubSub.shutdown(changes));
290 + const entries = yield* Ref.make<ReadonlyMap<ProviderInstanceId, LiveEntry>>(new Map());
291 + const unavailable = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ServerProvider>>(new Map());
292 + const changes = yield* PubSub.unbounded<void>();
293 + yield* Effect.addFinalizer(() => PubSub.shutdown(changes));
294
295 - const state: RegistryState = { entries, unavailable, changes };
296 - const reconcileWithR = makeReconcile({ state, driversById, parentScope });
297 - const reconcile: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape["reconcile"] =
298 - (configMap) => reconcileWithR(configMap).pipe(Effect.provideContext(driverContext));
295 + const state: RegistryState = { entries, unavailable, changes };
296 + const reconcileWithR = makeReconcile({ state, driversById, parentScope });
297 + const reconcile: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape["reconcile"] =
298 + (configMap) => reconcileWithR(configMap).pipe(Effect.provideContext(driverContext));
299
300 - yield* reconcile(input.configMap);
300 + yield* reconcile(input.configMap);
301
302 - const registry: ProviderInstanceRegistry["Service"] = {
303 - getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)),
304 - listInstances: Ref.get(entries).pipe(
305 - Effect.map(
306 - (map) =>
307 - Array.from(map.values(), (live) => live.instance) as ReadonlyArray<ProviderInstance>,
308 - ),
302 + const registry: ProviderInstanceRegistry["Service"] = {
303 + getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)),
304 + listInstances: Ref.get(entries).pipe(
305 + Effect.map(
306 + (map) =>
307 + Array.from(map.values(), (live) => live.instance) as ReadonlyArray<ProviderInstance>,
308 ),
310 - listUnavailable: Ref.get(unavailable).pipe(
311 - Effect.map((map) => Array.from(map.values()) as ReadonlyArray<ServerProvider>),
312 - ),
313 - get streamChanges() {
314 - return Stream.fromPubSub(changes);
315 - },
316 - get subscribeChanges() {
317 - return PubSub.subscribe(changes);
318 - },
319 - };
309 + ),
310 + listUnavailable: Ref.get(unavailable).pipe(
311 + Effect.map((map) => Array.from(map.values()) as ReadonlyArray<ServerProvider>),
312 + ),
313 + get streamChanges() {
314 + return Stream.fromPubSub(changes);
315 + },
316 + get subscribeChanges() {
317 + return PubSub.subscribe(changes);
318 + },
319 + };
320
321 - const mutator: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape = {
322 - reconcile,
323 - };
321 + const mutator: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape = {
322 + reconcile,
323 + };
324
325 - return { registry, mutator };
326 - });
325 + return { registry, mutator };
326 +});
327
328 export const layer = <R>(input: {
329 readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
apps/server/src/provider/ProviderRegistry.ts
+16 -15
@@ -454,21 +454,22 @@ export const layer = Layer.effect(
454 liveSubsRef,
455 ).pipe(Effect.map((map) => Array.from(map.values(), buildSnapshotSource)));
456
457 - const persistProvider = (provider: ServerProvider) =>
458 - Effect.gen(function* () {
459 - const key = snapshotInstanceKey(provider);
460 - const filePath = yield* resolveProviderStatusCachePath({
461 - cacheDir: config.providerStatusCacheDir,
462 - instanceId: key,
463 - }).pipe(Effect.provideService(Path.Path, path));
464 - const { workspaceSnapshots: _workspaceSnapshots, ...machineProvider } = provider;
465 - yield* writeProviderStatusCache({ filePath, provider: machineProvider }).pipe(
466 - Effect.provideService(FileSystem.FileSystem, fileSystem),
467 - Effect.provideService(Path.Path, path),
468 - Effect.tapError(Effect.logError),
469 - Effect.ignore,
470 - );
471 - });
457 + const persistProvider = Effect.fn("ProviderRegistry.persistProvider")(function* (
458 + provider: ServerProvider,
459 + ) {
460 + const key = snapshotInstanceKey(provider);
461 + const filePath = yield* resolveProviderStatusCachePath({
462 + cacheDir: config.providerStatusCacheDir,
463 + instanceId: key,
464 + }).pipe(Effect.provideService(Path.Path, path));
465 + const { workspaceSnapshots: _workspaceSnapshots, ...machineProvider } = provider;
466 + yield* writeProviderStatusCache({ filePath, provider: machineProvider }).pipe(
467 + Effect.provideService(FileSystem.FileSystem, fileSystem),
468 + Effect.provideService(Path.Path, path),
469 + Effect.tapError(Effect.logError),
470 + Effect.ignore,
471 + );
472 + });
473
474 const applyProviderUpdateState = Effect.fn("applyProviderUpdateState")(function* (
475 provider: ServerProvider,
apps/server/src/provider/claudeResetCredits.ts
+21 -18
@@ -122,25 +122,28 @@ export function claudeResetCreditsToContract(
122 };
123 }
124
125 -const readJson = <S extends Schema.Top>(schema: S, file: string) =>
126 - Effect.gen(function* () {
127 - const fs = yield* FileSystem.FileSystem;
128 - return yield* fs.readFileString(file).pipe(
129 - Effect.catchTags({
130 - PlatformError: (error) =>
131 - error.reason._tag === "NotFound" ? Effect.succeed("{}") : Effect.fail(error),
132 - }),
133 - Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(schema))),
134 - );
135 - });
125 +const readJson = Effect.fn("claudeResetCredits.readJson")(function* <S extends Schema.Top>(
126 + schema: S,
127 + file: string,
128 +) {
129 + const fs = yield* FileSystem.FileSystem;
130 + return yield* fs.readFileString(file).pipe(
131 + Effect.catchTags({
132 + PlatformError: (error) =>
133 + error.reason._tag === "NotFound" ? Effect.succeed("{}") : Effect.fail(error),
134 + }),
135 + Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(schema))),
136 + );
137 +});
138
137 -const readAccessToken = (configDir: string) =>
138 - Effect.gen(function* () {
139 - if ((yield* HostProcess.Platform) === "darwin") return undefined;
140 - const path = yield* Path.Path;
141 - const credentials = yield* readJson(Credentials, path.join(configDir, ".credentials.json"));
142 - return credentials.claudeAiOauth?.accessToken?.trim() || undefined;
143 - });
139 +const readAccessToken = Effect.fn("claudeResetCredits.readAccessToken")(function* (
140 + configDir: string,
141 +) {
142 + if ((yield* HostProcess.Platform) === "darwin") return undefined;
143 + const path = yield* Path.Path;
144 + const credentials = yield* readJson(Credentials, path.join(configDir, ".credentials.json"));
145 + return credentials.claudeAiOauth?.accessToken?.trim() || undefined;
146 +});
147
148 const withClaudeHeaders = (token: string, version: string) =>
149 HttpClientRequest.setHeaders({
apps/server/src/provider/providerMaintenanceCommandCoordinator.ts
+7 -7
@@ -35,13 +35,13 @@ export const makeProviderMaintenanceCommandCoordinator = Effect.fn(
35 return next;
36 });
37
38 - const withCommandLock: ProviderMaintenanceCommandCoordinatorShape<E>["withCommandLock"] = ({
39 - targetKey,
40 - lockKey,
41 - onQueued,
42 - run,
43 - }) =>
44 - Effect.gen(function* () {
38 + const withCommandLock: ProviderMaintenanceCommandCoordinatorShape<E>["withCommandLock"] =
39 + Effect.fn("providerMaintenanceCommandCoordinator.withCommandLock")(function* ({
40 + targetKey,
41 + lockKey,
42 + onQueued,
43 + run,
44 + }) {
45 const acquired = yield* acquireTarget(targetKey);
46 if (!acquired) {
47 return yield* Effect.fail(input.makeAlreadyRunningError(targetKey));
apps/server/src/provider/providerStatusCache.ts
+4 -3
@@ -108,8 +108,8 @@ export const resolveProviderStatusCachePath = Effect.fn("resolveProviderStatusCa
108 },
109 );
110
111 -export const readProviderStatusCache = (filePath: string) =>
112 - Effect.gen(function* () {
111 +export const readProviderStatusCache = Effect.fn("providerStatusCache.readProviderStatusCache")(
112 + function* (filePath: string) {
113 const fs = yield* FileSystem.FileSystem;
114 const exists = yield* fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));
115 if (!exists) {
@@ -132,7 +132,8 @@ export const readProviderStatusCache = (filePath: string) =>
132 onSuccess: Effect.succeed,
133 }),
134 );
135 - });
135 + },
136 +);
137
138 export const writeProviderStatusCache = (input: {
139 readonly filePath: string;
apps/server/src/provider/resetCreditCoordinator.ts
+19 -18
@@ -58,24 +58,25 @@ export const make = Effect.gen(function* () {
58 });
59 });
60
61 - const redeem: ResetCreditCoordinator["Service"]["redeem"] = (accountKey, consume, isSettled) =>
62 - Effect.gen(function* () {
63 - const state = yield* stateFor(accountKey);
64 - return yield* state.lock.withPermits(1)(
65 - Effect.gen(function* () {
66 - const existing = yield* Ref.get(state.pendingKey);
67 - const idempotencyKey = existing ?? (yield* crypto.randomUUIDv4());
68 - yield* Ref.set(state.pendingKey, idempotencyKey);
69 - const outcome = yield* consume(idempotencyKey).pipe(
70 - Effect.tapError((error) =>
71 - isSettled?.(error) ? Ref.set(state.pendingKey, null) : Effect.void,
72 - ),
73 - );
74 - yield* Ref.set(state.pendingKey, null);
75 - return outcome;
76 - }),
77 - );
78 - });
61 + const redeem: ResetCreditCoordinator["Service"]["redeem"] = Effect.fn(
62 + "resetCreditCoordinator.redeem",
63 + )(function* (accountKey, consume, isSettled) {
64 + const state = yield* stateFor(accountKey);
65 + return yield* state.lock.withPermits(1)(
66 + Effect.gen(function* () {
67 + const existing = yield* Ref.get(state.pendingKey);
68 + const idempotencyKey = existing ?? (yield* crypto.randomUUIDv4());
69 + yield* Ref.set(state.pendingKey, idempotencyKey);
70 + const outcome = yield* consume(idempotencyKey).pipe(
71 + Effect.tapError((error) =>
72 + isSettled?.(error) ? Ref.set(state.pendingKey, null) : Effect.void,
73 + ),
74 + );
75 + yield* Ref.set(state.pendingKey, null);
76 + return outcome;
77 + }),
78 + );
79 + });
80
81 return { redeem } satisfies ResetCreditCoordinator["Service"];
82 });
apps/server/src/provider/unavailableProviderSnapshot.ts
+31 -33
@@ -19,38 +19,36 @@ export interface UnavailableProviderSnapshotInput {
19
20 const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
21
22 -export function buildUnavailableProviderSnapshot(
23 - input: UnavailableProviderSnapshotInput,
24 -): Effect.Effect<ServerProvider> {
25 - return Effect.gen(function* () {
26 - const checkedAt = input.checkedAt ?? (yield* nowIso);
27 - const displayName = input.displayName?.trim() || (input.driverKind as string);
22 +export const buildUnavailableProviderSnapshot = Effect.fn(
23 + "unavailableProviderSnapshot.buildUnavailableProviderSnapshot",
24 +)(function* (input: UnavailableProviderSnapshotInput): Effect.fn.Return<ServerProvider> {
25 + const checkedAt = input.checkedAt ?? (yield* nowIso);
26 + const displayName = input.displayName?.trim() || (input.driverKind as string);
27
29 - const base = buildServerProvider({
30 - presentation: { displayName },
31 - enabled: false,
32 - checkedAt,
33 - models: [],
34 - skills: [],
35 - probe: {
36 - installed: false,
37 - version: null,
38 - status: "error",
39 - auth: { status: "unknown" },
40 - message: input.reason,
41 - },
42 - });
43 -
44 - return {
45 - ...base,
46 - instanceId: input.instanceId,
47 - ...(input.accentColor ? { accentColor: input.accentColor } : {}),
48 - driver:
49 - typeof input.driverKind === "string"
50 - ? ProviderDriverKind.make(input.driverKind)
51 - : input.driverKind,
52 - availability: "unavailable",
53 - unavailableReason: input.reason,
54 - };
28 + const base = buildServerProvider({
29 + presentation: { displayName },
30 + enabled: false,
31 + checkedAt,
32 + models: [],
33 + skills: [],
34 + probe: {
35 + installed: false,
36 + version: null,
37 + status: "error",
38 + auth: { status: "unknown" },
39 + message: input.reason,
40 + },
41 });
56 -}
42 +
43 + return {
44 + ...base,
45 + instanceId: input.instanceId,
46 + ...(input.accentColor ? { accentColor: input.accentColor } : {}),
47 + driver:
48 + typeof input.driverKind === "string"
49 + ? ProviderDriverKind.make(input.driverKind)
50 + : input.driverKind,
51 + availability: "unavailable",
52 + unavailableReason: input.reason,
53 + };
54 +});