Compare commits

...
Author SHA1 Message Date
Cursor Agent cb4e8f4b61 fix: filter synthetic 'default' service tier and close registry sync probe race
Bug 1: getCodexServiceTierOptionValue now returns undefined when the
persisted serviceTier value is the synthetic 'default' id used only as
a UI select option. Previously this forwarded 'default' to the API,
which overrides project-level routing settings. Standard routing should
omit the tier entirely (matching pre-change behavior).

Bug 2: Add a deferred re-read of instance snapshots after the forked
stream consumers have had time to subscribe. The managed provider
updates its snapshot ref before publishing to its PubSub, so re-reading
after a yield captures any probe result that landed between the initial
getSnapshot and the subscriber becoming active.
2026-06-10 23:40:03 +00:00
Julius Marmingeandcodex 34629c2a50 fix codex provider startup probing
Co-authored-by: codex <[email protected]>
2026-06-10 16:12:51 -07:00
Julius Marmingeandcodex d0e9e37a34 Expose Codex service tier options
Map the app-server service tier catalog to a select capability and forward selected tier IDs without translating them through fast mode. Preserve legacy persisted fast-mode selections.

Co-authored-by: codex <[email protected]>
2026-06-10 15:51:59 -07:00
Julius Marmingeandcodex ddae737d6f Refresh Codex app-server protocol bindings
Co-authored-by: codex <[email protected]>
2026-06-10 15:44:18 -07:00
20 changed files with 4045 additions and 1870 deletions

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
import { assert, it } from "@effect/vitest";
import { ProviderInstanceId } from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import { getCodexServiceTierOptionValue } from "./codexModelOptions.ts";
it("returns the selected Codex service tier id", () => {
const selection = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.5", [
{ id: "serviceTier", value: "flex" },
]);
assert.equal(getCodexServiceTierOptionValue(selection), "flex");
});
it("keeps legacy persisted fast mode selections working", () => {
const selection = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
{ id: "fastMode", value: true },
]);
assert.equal(getCodexServiceTierOptionValue(selection), "fast");
});
+15
View File
@@ -0,0 +1,15 @@
import type { ModelSelection } from "@t3tools/contracts";
import {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
} from "@t3tools/shared/model";
export function getCodexServiceTierOptionValue(
modelSelection: ModelSelection | null | undefined,
): string | undefined {
const tier =
getModelSelectionStringOptionValue(modelSelection, "serviceTier") ??
(getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true ? "fast" : undefined);
if (tier === "default") return undefined;
return tier;
}
@@ -271,7 +271,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "fastMode", value: true },
{ id: "serviceTier", value: "priority" },
]),
runtimeMode: "full-access",
});
@@ -281,7 +281,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
cwd: process.cwd(),
model: "gpt-5.3-codex",
providerInstanceId: ProviderInstanceId.make("codex"),
serviceTier: "fast",
serviceTier: "priority",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
});
@@ -344,7 +344,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
input: "hello",
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
{ id: "serviceTier", value: "priority" },
]),
attachments: [],
}),
@@ -354,7 +354,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
input: "hello",
model: "gpt-5.3-codex",
effort: "high",
serviceTier: "fast",
serviceTier: "priority",
});
}),
);
@@ -398,7 +398,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
"gpt-5.3-codex",
[
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
{ id: "serviceTier", value: "flex" },
],
),
attachments: [],
@@ -409,7 +409,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
input: "hello",
model: "gpt-5.3-codex",
effort: "high",
serviceTier: "fast",
serviceTier: "flex",
});
}).pipe(Effect.provide(customLayer));
});
+10 -11
View File
@@ -37,10 +37,8 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import * as CodexErrors from "effect-codex-app-server/errors";
import * as EffectCodexSchema from "effect-codex-app-server/schema";
import {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
} from "@t3tools/shared/model";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { getCodexServiceTierOptionValue } from "../../codexModelOptions.ts";
import {
ProviderAdapterRequestError,
@@ -1380,6 +1378,10 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
yield* Effect.suspend(() => stopSessionInternal(existing));
}
const serviceTier =
input.modelSelection?.instanceId === boundInstanceId
? getCodexServiceTierOptionValue(input.modelSelection)
: undefined;
const runtimeInput: CodexSessionRuntimeOptions = {
threadId: input.threadId,
providerInstanceId: boundInstanceId,
@@ -1394,10 +1396,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
...(input.modelSelection?.instanceId === boundInstanceId
? { model: input.modelSelection.model }
: {}),
...(input.modelSelection?.instanceId === boundInstanceId &&
getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode") === true
? { serviceTier: "fast" }
: {}),
...(serviceTier ? { serviceTier } : {}),
};
const sessionScope = yield* Scope.make("sequential");
let sessionScopeTransferred = false;
@@ -1513,9 +1512,9 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
input.modelSelection?.instanceId === boundInstanceId
? getModelSelectionStringOptionValue(input.modelSelection, "reasoningEffort")
: undefined;
const fastMode =
const serviceTier =
input.modelSelection?.instanceId === boundInstanceId
? getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode")
? getCodexServiceTierOptionValue(input.modelSelection)
: undefined;
return yield* session.runtime
.sendTurn({
@@ -1528,7 +1527,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
effort: reasoningEffort as EffectCodexSchema.V2TurnStartParams__ReasoningEffort,
}
: {}),
...(fastMode === true ? { serviceTier: "fast" } : {}),
...(serviceTier ? { serviceTier } : {}),
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
})
@@ -0,0 +1,104 @@
import { assert, it } from "@effect/vitest";
import { mapCodexModelCapabilities } from "./CodexProvider.ts";
it("maps current Codex model capability fields", () => {
const capabilities = mapCodexModelCapabilities({
additionalSpeedTiers: [],
defaultReasoningEffort: "super-high",
description: "Test model",
displayName: "GPT Test",
hidden: false,
id: "gpt-test",
isDefault: true,
model: "gpt-test",
defaultServiceTier: "flex",
serviceTiers: [
{
id: "priority",
name: "Fast",
description: "Lower latency responses.",
},
{
id: "flex",
name: "Flex",
description: "Lower-cost asynchronous routing.",
},
],
supportedReasoningEfforts: [
{
description: "Maximum reasoning",
reasoningEffort: "super-high",
},
],
});
assert.deepStrictEqual(capabilities.optionDescriptors, [
{
id: "reasoningEffort",
label: "Reasoning",
type: "select",
options: [{ id: "super-high", label: "super-high", isDefault: true }],
currentValue: "super-high",
},
{
id: "serviceTier",
label: "Service Tier",
type: "select",
options: [
{ id: "default", label: "Standard" },
{
id: "priority",
label: "Fast",
description: "Lower latency responses.",
},
{
id: "flex",
label: "Flex",
description: "Lower-cost asynchronous routing.",
isDefault: true,
},
],
currentValue: "flex",
},
]);
});
it("uses standard routing when the catalog has no default service tier", () => {
const capabilities = mapCodexModelCapabilities({
additionalSpeedTiers: ["fast"],
defaultReasoningEffort: "medium",
defaultServiceTier: null,
description: "Test model",
displayName: "GPT Test",
hidden: false,
id: "gpt-test",
isDefault: true,
model: "gpt-test",
serviceTiers: [
{
id: "priority",
name: "Fast",
description: "1.5x speed, increased usage",
},
],
supportedReasoningEfforts: [],
});
assert.deepStrictEqual(capabilities.optionDescriptors, [
{
id: "serviceTier",
label: "Service Tier",
type: "select",
options: [
{ id: "default", label: "Standard", isDefault: true },
{
id: "priority",
label: "Fast",
description: "1.5x speed, increased usage",
},
],
currentValue: "default",
},
]);
});
@@ -17,6 +17,7 @@ import type {
ServerProvider,
ServerProviderState,
ModelCapabilities,
ProviderOptionDescriptor,
ServerProviderModel,
ServerProviderSkill,
} from "@t3tools/contracts";
@@ -44,7 +45,7 @@ export interface CodexAppServerProviderSnapshot {
readonly skills: ReadonlyArray<ServerProviderSkill>;
}
const REASONING_EFFORT_LABELS: Record<CodexSchema.V2ModelListResponse__ReasoningEffort, string> = {
const REASONING_EFFORT_LABELS: Readonly<Record<string, string>> = {
none: "None",
minimal: "Minimal",
low: "Low",
@@ -53,6 +54,12 @@ const REASONING_EFFORT_LABELS: Record<CodexSchema.V2ModelListResponse__Reasoning
xhigh: "Extra High",
};
const DEFAULT_SERVICE_TIER_ID = "default";
function reasoningEffortLabel(reasoningEffort: string): string {
return REASONING_EFFORT_LABELS[reasoningEffort] ?? reasoningEffort;
}
function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["account"]) {
if (!account) return undefined;
if (account.type === "apiKey") return "OpenAI API Key";
@@ -93,46 +100,71 @@ function codexAccountEmail(account: CodexSchema.V2GetAccountResponse["account"])
return account.email;
}
function mapCodexModelCapabilities(
export function mapCodexModelCapabilities(
model: CodexSchema.V2ModelListResponse__Model,
): ModelCapabilities {
const reasoningOptions = model.supportedReasoningEfforts.map(({ reasoningEffort }) =>
reasoningEffort === model.defaultReasoningEffort
? {
id: reasoningEffort,
label: REASONING_EFFORT_LABELS[reasoningEffort],
label: reasoningEffortLabel(reasoningEffort),
isDefault: true,
}
: {
id: reasoningEffort,
label: REASONING_EFFORT_LABELS[reasoningEffort],
label: reasoningEffortLabel(reasoningEffort),
},
);
const defaultReasoning = reasoningOptions.find((option) => option.isDefault)?.id;
const supportsFastMode = (model.additionalSpeedTiers ?? []).includes("fast");
const serviceTiers =
model.serviceTiers && model.serviceTiers.length > 0
? model.serviceTiers
: (model.additionalSpeedTiers ?? []).map((id) => ({
id,
name: id === "fast" ? "Fast" : id,
description: "",
}));
const catalogDefaultServiceTier = serviceTiers.some(
(tier) => tier.id === model.defaultServiceTier,
)
? model.defaultServiceTier
: null;
const defaultServiceTier = catalogDefaultServiceTier ?? DEFAULT_SERVICE_TIER_ID;
const optionDescriptors: ProviderOptionDescriptor[] = [];
if (reasoningOptions.length > 0) {
optionDescriptors.push({
id: "reasoningEffort",
label: "Reasoning",
type: "select",
options: reasoningOptions,
...(defaultReasoning ? { currentValue: defaultReasoning } : {}),
});
}
if (serviceTiers.length > 0) {
optionDescriptors.push({
id: "serviceTier",
label: "Service Tier",
type: "select",
options: [
{
id: DEFAULT_SERVICE_TIER_ID,
label: "Standard",
...(defaultServiceTier === DEFAULT_SERVICE_TIER_ID ? { isDefault: true } : {}),
},
...serviceTiers.map((tier) => ({
id: tier.id,
label: tier.name,
...(tier.description ? { description: tier.description } : {}),
...(defaultServiceTier === tier.id ? { isDefault: true } : {}),
})),
],
currentValue: defaultServiceTier,
});
}
return createModelCapabilities({
optionDescriptors: [
...(reasoningOptions.length > 0
? [
{
id: "reasoningEffort",
label: "Reasoning",
type: "select" as const,
options: reasoningOptions,
...(defaultReasoning ? { currentValue: defaultReasoning } : {}),
},
]
: []),
...(supportsFastMode
? [
{
id: "fastMode",
label: "Fast Mode",
type: "boolean" as const,
},
]
: []),
],
optionDescriptors,
});
}
@@ -594,6 +594,77 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
]);
});
it.effect("does not run provider probes during layer construction", () =>
Effect.gen(function* () {
const codexDriver = ProviderDriverKind.make("codex");
const codexInstanceId = ProviderInstanceId.make("codex");
const initialProvider = {
instanceId: codexInstanceId,
driver: codexDriver,
status: "warning",
enabled: true,
installed: false,
auth: { status: "unknown" },
checkedAt: "2026-06-10T00:00:00.000Z",
version: null,
message: "Checking Codex provider status.",
models: [],
slashCommands: [],
skills: [],
} as const satisfies ServerProvider;
const refreshCalls = yield* Ref.make(0);
const instance = {
instanceId: codexInstanceId,
driverKind: codexDriver,
continuationIdentity: {
driverKind: codexDriver,
continuationKey: "codex:instance:codex",
},
displayName: undefined,
enabled: true,
snapshot: {
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
provider: codexDriver,
packageName: null,
}),
getSnapshot: Effect.succeed(initialProvider),
refresh: Ref.update(refreshCalls, (count) => count + 1).pipe(
Effect.andThen(Effect.never),
),
streamChanges: Stream.empty,
},
adapter: {} as ProviderInstance["adapter"],
textGeneration: {} as ProviderInstance["textGeneration"],
} satisfies ProviderInstance;
const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {
getInstance: (instanceId) =>
Effect.succeed(instanceId === codexInstanceId ? instance : undefined),
listInstances: Effect.succeed([instance]),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), PubSub.subscribe),
});
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const runtimeServices = yield* Layer.build(
ProviderRegistryLive.pipe(
Layer.provideMerge(instanceRegistryLayer),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-background-refresh-",
}),
),
Layer.provideMerge(NodeServices.layer),
),
).pipe(Scope.provide(scope));
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry;
assert.deepStrictEqual(yield* registry.getProviders, [initialProvider]);
assert.strictEqual(yield* Ref.get(refreshCalls), 0);
}).pipe(Effect.provide(runtimeServices));
}),
);
it("persists merged provider snapshots for the providers that were refreshed", () => {
const previousProviders = [
{
@@ -1042,7 +1113,17 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry;
const providers = yield* registry.getProviders;
let providers = yield* registry.getProviders;
for (
let attempts = 0;
attempts < 50 &&
providers.find((provider) => provider.instanceId === "codex_personal")?.status !==
"error";
attempts += 1
) {
yield* Effect.yieldNow;
providers = yield* registry.getProviders;
}
const codexPersonal = providers.find(
(provider) => provider.instanceId === "codex_personal",
);
@@ -1072,9 +1153,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
// instance and rebuild it so a fresh probe runs with the new binary.
// This test drives the real settings stream → registry reconcile →
// aggregator sync pipeline and asserts that `getProviders` reflects
// the new probe's outcome. If `syncLiveSources` stops awaiting the
// rebuilt instance's refresh (previous bug mode), the aggregator
// keeps the old snapshot and this test fails.
// the new background probe's outcome.
//
it.effect("re-probes when settings change the codex binaryPath", () =>
Effect.gen(function* () {
@@ -1124,7 +1203,18 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
// the two probe runs is `checkedAt` — each probe stamps a
// fresh DateTime, so we capture it and assert it advances
// after the settings mutation.
const initialProviders = yield* registry.getProviders;
let initialProviders = yield* registry.getProviders;
for (
let attempts = 0;
attempts < 50 &&
initialProviders.find((provider) => provider.instanceId === "codex")?.status !==
"error";
attempts += 1
) {
yield* TestClock.adjust("10 millis");
yield* Effect.yieldNow;
initialProviders = yield* registry.getProviders;
}
const initialCodex = initialProviders.find(
(provider) => provider.instanceId === "codex",
);
@@ -1144,8 +1234,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
// envelope changed because `binaryPath` differs → `entryEqual`
// is false). The registry's `Stream.runForEach(
// instanceRegistry.streamChanges, () => syncLiveSources)`
// fires `syncLiveSources`, which subscribes + awaits a fresh
// refresh on the rebuilt instance.
// fires `syncLiveSources`, which subscribes and launches a fresh
// background refresh on the rebuilt instance.
yield* serverSettings.updateSettings({
providers: {
codex: { enabled: true, binaryPath: secondMissing },
@@ -1158,7 +1248,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
for (let attempts = 0; attempts < 60; attempts += 1) {
const providers = yield* registry.getProviders;
const codex = providers.find((provider) => provider.instanceId === "codex");
if (codex !== undefined && codex.checkedAt !== initialCheckedAt) {
if (
codex !== undefined &&
codex.status === "error" &&
codex.checkedAt !== initialCheckedAt
) {
return providers;
}
yield* TestClock.adjust("50 millis");
@@ -492,16 +492,15 @@ export const ProviderRegistryLive = Layer.effect(
* - subscribe to each newly-added or rebuilt instance's
* `streamChanges` (so periodic + enrichment refreshes land in
* `providersRef`);
* - force-refresh each newly-added/rebuilt instance and feed the
* result directly into `providersRef`, bypassing the PubSub
* attachment race that otherwise drops the initial probe;
* - read each newly-added/rebuilt instance's current snapshot after
* subscribing, closing the race with its independently-running
* background startup probe;
* - prune `providersRef` of instances that no longer exist.
*
* Initial refreshes are awaited in parallel rather than forked, so
* callers (layer build; `streamChanges` watcher) see fully-probed
* state on return. This matters for layer build in particular:
* consumers reading `getProviders` immediately after layer build
* expect the probe to have already landed.
* Provider refreshes are owned by each managed provider and never run
* on this layer's construction path. Consumers see cached or pending
* snapshots immediately, then receive live probe results through the
* already-attached change stream.
*
* Per-instance subscription fibers are not tracked explicitly. When
* a rebuilt instance's old child scope closes, its PubSub shuts
@@ -543,27 +542,51 @@ export const ProviderRegistryLive = Layer.effect(
}
// Fork long-lived subscriptions to each new/rebuilt instance's
// change stream BEFORE kicking off refreshes — if the driver's
// own initial probe (line 140 in `makeManagedServerProvider`)
// wins the refreshSemaphore race, its PubSub publish must land
// in an active subscriber or the result is dropped.
// change stream before reading its current snapshot. If the
// driver's own initial probe finishes during this sync, either
// the current read or the active subscriber observes the result.
for (const [, instance] of newlyAdded) {
const source = buildSnapshotSource(instance);
yield* Stream.runForEach(source.streamChanges, (provider) =>
correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),
).pipe(Effect.forkScoped);
}
yield* Effect.yieldNow;
// Force-refresh every new/rebuilt instance in parallel and wait
// for them all to complete. The refresh's result is piped
// directly into `syncProvider`, so `providersRef` is populated
// deterministically by the time this block returns — regardless
// of PubSub subscription timing. Failures are logged and
// swallowed so one bad driver can't wedge the whole registry.
// Snapshot current state without starting a probe. Managed providers
// launch their startup refresh independently, so this closes the
// subscription race without putting external work on the registry
// or HTTP server construction path.
yield* Effect.forEach(
newlyAdded,
([, instance]) =>
refreshOneSource(buildSnapshotSource(instance)).pipe(Effect.ignoreCause({ log: true })),
Effect.gen(function* () {
const source = buildSnapshotSource(instance);
const provider = yield* source.getSnapshot;
yield* correlateSnapshotWithSource(source, provider).pipe(
Effect.flatMap(syncProvider),
);
}).pipe(Effect.ignoreCause({ log: true })),
{ concurrency: "unbounded", discard: true },
);
// Re-read snapshots after yielding to close the race between
// subscription establishment and the initial read. The managed
// provider updates its snapshot ref before publishing to the
// PubSub, so this second read captures any probe that landed
// after the first getSnapshot but before the forked subscriber
// became active. The subscriber then handles all future updates.
yield* Effect.yieldNow;
yield* Effect.forEach(
newlyAdded,
([, instance]) =>
Effect.gen(function* () {
const source = buildSnapshotSource(instance);
const provider = yield* source.getSnapshot;
yield* correlateSnapshotWithSource(source, provider).pipe(
Effect.flatMap(syncProvider),
);
}).pipe(Effect.ignoreCause({ log: true })),
{ concurrency: "unbounded", discard: true },
);
yield* upsertProviders(unavailableProviders, {
@@ -654,9 +677,9 @@ export const ProviderRegistryLive = Layer.effect(
// was dropped, which made any settings change that replaced an
// instance never propagate to the aggregator's `providersRef`.)
const instanceChanges = yield* instanceRegistry.subscribeChanges;
// Initial sync: subscribe + kick off refreshes for every instance
// present at boot. Run synchronously so consumers pulling immediately
// after the layer build see the correct aggregator state.
// Initial sync attaches subscriptions and snapshots current state for
// every instance present at boot. Provider probes are already running in
// their managed background fibers and never block this layer.
yield* syncLiveSources;
// React to registry mutations — instance added / removed / rebuilt.
// `Stream.fromSubscription` builds a stream over the pre-acquired
@@ -129,6 +129,7 @@ describe("makeManagedServerProvider", () => {
Effect.forkChild,
);
yield* Effect.yieldNow;
assert.strictEqual(yield* Ref.get(checkCalls), 1);
yield* Deferred.succeed(releaseCheck, undefined);
@@ -152,11 +152,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
return {
maintenanceCapabilities: input.maintenanceCapabilities,
getSnapshot: input.getSettings.pipe(
Effect.flatMap(applySnapshot),
Effect.tapError(Effect.logError),
Effect.orDie,
),
getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
@@ -32,7 +32,7 @@ function makeFakeCodexBinary(
exitCode?: number;
stderr?: string;
requireImage?: boolean;
requireFastServiceTier?: boolean;
requireServiceTier?: string;
requireReasoningEffort?: string;
forbidReasoningEffort?: boolean;
stdinMustContain?: string;
@@ -52,7 +52,7 @@ function makeFakeCodexBinary(
"#!/bin/sh",
'output_path=""',
'seen_image="0"',
'seen_fast_service_tier="0"',
'seen_service_tier=""',
'seen_reasoning_effort=""',
"while [ $# -gt 0 ]; do",
' if [ "$1" = "--image" ]; then',
@@ -65,9 +65,11 @@ function makeFakeCodexBinary(
" fi",
' if [ "$1" = "--config" ]; then',
" shift",
' if [ "$1" = "service_tier=\\"fast\\"" ]; then',
' seen_fast_service_tier="1"',
" fi",
' case "$1" in',
" service_tier=*)",
' seen_service_tier="$1"',
" ;;",
" esac",
' case "$1" in',
" model_reasoning_effort=*)",
' seen_reasoning_effort="$1"',
@@ -93,10 +95,10 @@ function makeFakeCodexBinary(
"fi",
]
: []),
...(input.requireFastServiceTier
...(input.requireServiceTier
? [
'if [ "$seen_fast_service_tier" != "1" ]; then',
' printf "%s\\n" "missing fast service tier config" >&2',
`if [ "$seen_service_tier" != "service_tier=\\"${input.requireServiceTier}\\"" ]; then`,
' printf "%s\\n" "unexpected service tier config: $seen_service_tier" >&2',
` exit 5`,
"fi",
]
@@ -161,7 +163,7 @@ function withFakeCodexEnv<A, E, R>(
exitCode?: number;
stderr?: string;
requireImage?: boolean;
requireFastServiceTier?: boolean;
requireServiceTier?: string;
requireReasoningEffort?: string;
forbidReasoningEffort?: boolean;
stdinMustContain?: string;
@@ -209,7 +211,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
);
it.effect(
"forwards codex fast mode and non-default reasoning effort into codex exec config",
"forwards codex service tier and non-default reasoning effort into codex exec config",
() =>
withFakeCodexEnv(
{
@@ -217,7 +219,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
subject: "Add important change",
body: "",
}),
requireFastServiceTier: true,
requireServiceTier: "priority",
requireReasoningEffort: "xhigh",
stdinMustNotContain: "branch must be a short semantic git branch fragment",
},
@@ -229,7 +231,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
{ id: "reasoningEffort", value: "xhigh" },
{ id: "fastMode", value: true },
{ id: "serviceTier", value: "priority" },
]),
}),
),
@@ -32,10 +32,8 @@ import {
sanitizeThreadTitle,
toJsonSchemaObject,
} from "./TextGenerationUtils.ts";
import {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
} from "@t3tools/shared/model";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { getCodexServiceTierOptionValue } from "../codexModelOptions.ts";
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
@@ -181,6 +179,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
const reasoningEffort =
getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
const serviceTier = getCodexServiceTierOptionValue(modelSelection);
const command = ChildProcess.make(
codexConfig.binaryPath || "codex",
[
@@ -193,9 +192,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
modelSelection.model,
"--config",
`model_reasoning_effort="${reasoningEffort}"`,
...(getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true
? ["--config", `service_tier="fast"`]
: []),
...(serviceTier ? ["--config", `service_tier="${serviceTier}"`] : []),
"--output-schema",
schemaPath,
"--output-last-message",
@@ -17,7 +17,7 @@ import {
} from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
const UPSTREAM_REF = "07b695190f30a450e4921f71f77473e564395c59";
const UPSTREAM_REF = "b39f943a634a6e7ba86c3d6e8cf6d5f35e612566";
const USER_AGENT = "effect-codex-app-server-generator";
const GITHUB_API_BASE =
"https://api.github.com/repos/openai/codex/contents/codex-rs/app-server-protocol";
@@ -348,6 +348,7 @@ function resolveResponseTypeName(
const overrides: Record<string, string> = {
"account/logout": "LogoutAccountResponse",
"account/rateLimits/read": "GetAccountRateLimitsResponse",
"account/usage/read": "GetAccountTokenUsageResponse",
"config/batchWrite": "ConfigWriteResponse",
"config/mcpServer/reload": "McpServerRefreshResponse",
"config/value/write": "ConfigWriteResponse",
@@ -745,14 +746,16 @@ const generateFiles = Effect.fn("generateFiles")(function* () {
yield* Effect.log(`Generated Codex App Server schemas from ${UPSTREAM_REF}`);
yield* Effect.service(ChildProcessSpawner.ChildProcessSpawner).pipe(
Effect.flatMap((spawner) => spawner.spawn(ChildProcess.make("bun", ["oxfmt", generatedDir]))),
Effect.flatMap((spawner) =>
spawner.spawn(ChildProcess.make("vp", ["fmt", generatedDir, "--write"])),
),
Effect.flatMap((child) => child.exitCode),
Effect.tap((code) =>
code === 0
? Effect.void
: Effect.fail(
new GeneratorError({
detail: `oxfmt failed with exit code ${code}`,
detail: `vp fmt failed with exit code ${code}`,
}),
),
),
@@ -1,5 +1,5 @@
// This file is generated by the effect-codex-app-server package. Do not edit manually.
// Upstream protocol ref: 07b695190f30a450e4921f71f77473e564395c59
// Upstream protocol ref: b39f943a634a6e7ba86c3d6e8cf6d5f35e612566
import * as CodexSchema from "./schema.gen.ts";
@@ -9,8 +9,12 @@ export const CLIENT_REQUEST_METHODS = {
"thread/resume": "thread/resume",
"thread/fork": "thread/fork",
"thread/archive": "thread/archive",
"thread/delete": "thread/delete",
"thread/unsubscribe": "thread/unsubscribe",
"thread/name/set": "thread/name/set",
"thread/goal/set": "thread/goal/set",
"thread/goal/get": "thread/goal/get",
"thread/goal/clear": "thread/goal/clear",
"thread/metadata/update": "thread/metadata/update",
"thread/unarchive": "thread/unarchive",
"thread/compact/start": "thread/compact/start",
@@ -22,16 +26,19 @@ export const CLIENT_REQUEST_METHODS = {
"thread/read": "thread/read",
"thread/inject_items": "thread/inject_items",
"skills/list": "skills/list",
"skills/extraRoots/set": "skills/extraRoots/set",
"hooks/list": "hooks/list",
"marketplace/add": "marketplace/add",
"marketplace/remove": "marketplace/remove",
"marketplace/upgrade": "marketplace/upgrade",
"plugin/list": "plugin/list",
"plugin/installed": "plugin/installed",
"plugin/read": "plugin/read",
"plugin/skill/read": "plugin/skill/read",
"plugin/share/save": "plugin/share/save",
"plugin/share/updateTargets": "plugin/share/updateTargets",
"plugin/share/list": "plugin/share/list",
"plugin/share/checkout": "plugin/share/checkout",
"plugin/share/delete": "plugin/share/delete",
"app/list": "app/list",
"fs/readFile": "fs/readFile",
@@ -53,6 +60,7 @@ export const CLIENT_REQUEST_METHODS = {
"model/list": "model/list",
"modelProvider/capabilities/read": "modelProvider/capabilities/read",
"experimentalFeature/list": "experimentalFeature/list",
"permissionProfile/list": "permissionProfile/list",
"experimentalFeature/enablement/set": "experimentalFeature/enablement/set",
"mcpServer/oauth/login": "mcpServer/oauth/login",
"config/mcpServer/reload": "config/mcpServer/reload",
@@ -65,6 +73,7 @@ export const CLIENT_REQUEST_METHODS = {
"account/login/cancel": "account/login/cancel",
"account/logout": "account/logout",
"account/rateLimits/read": "account/rateLimits/read",
"account/usage/read": "account/usage/read",
"account/sendAddCreditsNudgeEmail": "account/sendAddCreditsNudgeEmail",
"feedback/upload": "feedback/upload",
"command/exec": "command/exec",
@@ -96,6 +105,7 @@ export const SERVER_REQUEST_METHODS = {
"item/permissions/requestApproval": "item/permissions/requestApproval",
"item/tool/call": "item/tool/call",
"account/chatgptAuthTokens/refresh": "account/chatgptAuthTokens/refresh",
"attestation/generate": "attestation/generate",
applyPatchApproval: "applyPatchApproval",
execCommandApproval: "execCommandApproval",
} as const;
@@ -105,12 +115,14 @@ export const SERVER_NOTIFICATION_METHODS = {
"thread/started": "thread/started",
"thread/status/changed": "thread/status/changed",
"thread/archived": "thread/archived",
"thread/deleted": "thread/deleted",
"thread/unarchived": "thread/unarchived",
"thread/closed": "thread/closed",
"skills/changed": "skills/changed",
"thread/name/updated": "thread/name/updated",
"thread/goal/updated": "thread/goal/updated",
"thread/goal/cleared": "thread/goal/cleared",
"thread/settings/updated": "thread/settings/updated",
"thread/tokenUsage/updated": "thread/tokenUsage/updated",
"turn/started": "turn/started",
"hook/started": "hook/started",
@@ -148,6 +160,7 @@ export const SERVER_NOTIFICATION_METHODS = {
"thread/compacted": "thread/compacted",
"model/rerouted": "model/rerouted",
"model/verification": "model/verification",
"turn/moderationMetadata": "turn/moderationMetadata",
warning: "warning",
guardianWarning: "guardianWarning",
deprecationNotice: "deprecationNotice",
@@ -178,8 +191,12 @@ export interface ClientRequestParamsByMethod {
readonly "thread/resume": CodexSchema.V2ThreadResumeParams;
readonly "thread/fork": CodexSchema.V2ThreadForkParams;
readonly "thread/archive": CodexSchema.V2ThreadArchiveParams;
readonly "thread/delete": CodexSchema.V2ThreadDeleteParams;
readonly "thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeParams;
readonly "thread/name/set": CodexSchema.V2ThreadSetNameParams;
readonly "thread/goal/set": CodexSchema.V2ThreadGoalSetParams;
readonly "thread/goal/get": CodexSchema.V2ThreadGoalGetParams;
readonly "thread/goal/clear": CodexSchema.V2ThreadGoalClearParams;
readonly "thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateParams;
readonly "thread/unarchive": CodexSchema.V2ThreadUnarchiveParams;
readonly "thread/compact/start": CodexSchema.V2ThreadCompactStartParams;
@@ -191,16 +208,19 @@ export interface ClientRequestParamsByMethod {
readonly "thread/read": CodexSchema.V2ThreadReadParams;
readonly "thread/inject_items": CodexSchema.V2ThreadInjectItemsParams;
readonly "skills/list": CodexSchema.V2SkillsListParams;
readonly "skills/extraRoots/set": CodexSchema.V2SkillsExtraRootsSetParams;
readonly "hooks/list": CodexSchema.V2HooksListParams;
readonly "marketplace/add": CodexSchema.V2MarketplaceAddParams;
readonly "marketplace/remove": CodexSchema.V2MarketplaceRemoveParams;
readonly "marketplace/upgrade": CodexSchema.V2MarketplaceUpgradeParams;
readonly "plugin/list": CodexSchema.V2PluginListParams;
readonly "plugin/installed": CodexSchema.V2PluginInstalledParams;
readonly "plugin/read": CodexSchema.V2PluginReadParams;
readonly "plugin/skill/read": CodexSchema.V2PluginSkillReadParams;
readonly "plugin/share/save": CodexSchema.V2PluginShareSaveParams;
readonly "plugin/share/updateTargets": CodexSchema.V2PluginShareUpdateTargetsParams;
readonly "plugin/share/list": CodexSchema.V2PluginShareListParams;
readonly "plugin/share/checkout": CodexSchema.V2PluginShareCheckoutParams;
readonly "plugin/share/delete": CodexSchema.V2PluginShareDeleteParams;
readonly "app/list": CodexSchema.V2AppsListParams;
readonly "fs/readFile": CodexSchema.V2FsReadFileParams;
@@ -222,6 +242,7 @@ export interface ClientRequestParamsByMethod {
readonly "model/list": CodexSchema.V2ModelListParams;
readonly "modelProvider/capabilities/read": CodexSchema.V2ModelProviderCapabilitiesReadParams;
readonly "experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListParams;
readonly "permissionProfile/list": CodexSchema.V2PermissionProfileListParams;
readonly "experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetParams;
readonly "mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginParams;
readonly "config/mcpServer/reload": undefined;
@@ -234,6 +255,7 @@ export interface ClientRequestParamsByMethod {
readonly "account/login/cancel": CodexSchema.V2CancelLoginAccountParams;
readonly "account/logout": undefined;
readonly "account/rateLimits/read": undefined;
readonly "account/usage/read": undefined;
readonly "account/sendAddCreditsNudgeEmail": CodexSchema.V2SendAddCreditsNudgeEmailParams;
readonly "feedback/upload": CodexSchema.V2FeedbackUploadParams;
readonly "command/exec": CodexSchema.V2CommandExecParams;
@@ -259,8 +281,12 @@ export interface ClientRequestResponsesByMethod {
readonly "thread/resume": CodexSchema.V2ThreadResumeResponse;
readonly "thread/fork": CodexSchema.V2ThreadForkResponse;
readonly "thread/archive": CodexSchema.V2ThreadArchiveResponse;
readonly "thread/delete": CodexSchema.V2ThreadDeleteResponse;
readonly "thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeResponse;
readonly "thread/name/set": CodexSchema.V2ThreadSetNameResponse;
readonly "thread/goal/set": CodexSchema.V2ThreadGoalSetResponse;
readonly "thread/goal/get": CodexSchema.V2ThreadGoalGetResponse;
readonly "thread/goal/clear": CodexSchema.V2ThreadGoalClearResponse;
readonly "thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateResponse;
readonly "thread/unarchive": CodexSchema.V2ThreadUnarchiveResponse;
readonly "thread/compact/start": CodexSchema.V2ThreadCompactStartResponse;
@@ -272,16 +298,19 @@ export interface ClientRequestResponsesByMethod {
readonly "thread/read": CodexSchema.V2ThreadReadResponse;
readonly "thread/inject_items": CodexSchema.V2ThreadInjectItemsResponse;
readonly "skills/list": CodexSchema.V2SkillsListResponse;
readonly "skills/extraRoots/set": CodexSchema.V2SkillsExtraRootsSetResponse;
readonly "hooks/list": CodexSchema.V2HooksListResponse;
readonly "marketplace/add": CodexSchema.V2MarketplaceAddResponse;
readonly "marketplace/remove": CodexSchema.V2MarketplaceRemoveResponse;
readonly "marketplace/upgrade": CodexSchema.V2MarketplaceUpgradeResponse;
readonly "plugin/list": CodexSchema.V2PluginListResponse;
readonly "plugin/installed": CodexSchema.V2PluginInstalledResponse;
readonly "plugin/read": CodexSchema.V2PluginReadResponse;
readonly "plugin/skill/read": CodexSchema.V2PluginSkillReadResponse;
readonly "plugin/share/save": CodexSchema.V2PluginShareSaveResponse;
readonly "plugin/share/updateTargets": CodexSchema.V2PluginShareUpdateTargetsResponse;
readonly "plugin/share/list": CodexSchema.V2PluginShareListResponse;
readonly "plugin/share/checkout": CodexSchema.V2PluginShareCheckoutResponse;
readonly "plugin/share/delete": CodexSchema.V2PluginShareDeleteResponse;
readonly "app/list": CodexSchema.V2AppsListResponse;
readonly "fs/readFile": CodexSchema.V2FsReadFileResponse;
@@ -303,6 +332,7 @@ export interface ClientRequestResponsesByMethod {
readonly "model/list": CodexSchema.V2ModelListResponse;
readonly "modelProvider/capabilities/read": CodexSchema.V2ModelProviderCapabilitiesReadResponse;
readonly "experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListResponse;
readonly "permissionProfile/list": CodexSchema.V2PermissionProfileListResponse;
readonly "experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetResponse;
readonly "mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginResponse;
readonly "config/mcpServer/reload": CodexSchema.V2McpServerRefreshResponse;
@@ -315,6 +345,7 @@ export interface ClientRequestResponsesByMethod {
readonly "account/login/cancel": CodexSchema.V2CancelLoginAccountResponse;
readonly "account/logout": CodexSchema.V2LogoutAccountResponse;
readonly "account/rateLimits/read": CodexSchema.V2GetAccountRateLimitsResponse;
readonly "account/usage/read": CodexSchema.V2GetAccountTokenUsageResponse;
readonly "account/sendAddCreditsNudgeEmail": CodexSchema.V2SendAddCreditsNudgeEmailResponse;
readonly "feedback/upload": CodexSchema.V2FeedbackUploadResponse;
readonly "command/exec": CodexSchema.V2CommandExecResponse;
@@ -346,6 +377,7 @@ export interface ServerRequestParamsByMethod {
readonly "item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalParams;
readonly "item/tool/call": CodexSchema.DynamicToolCallParams;
readonly "account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshParams;
readonly "attestation/generate": CodexSchema.AttestationGenerateParams;
readonly applyPatchApproval: CodexSchema.ApplyPatchApprovalParams;
readonly execCommandApproval: CodexSchema.ExecCommandApprovalParams;
}
@@ -358,6 +390,7 @@ export interface ServerRequestResponsesByMethod {
readonly "item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalResponse;
readonly "item/tool/call": CodexSchema.DynamicToolCallResponse;
readonly "account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshResponse;
readonly "attestation/generate": CodexSchema.AttestationGenerateResponse;
readonly applyPatchApproval: CodexSchema.ApplyPatchApprovalResponse;
readonly execCommandApproval: CodexSchema.ExecCommandApprovalResponse;
}
@@ -367,12 +400,14 @@ export interface ServerNotificationParamsByMethod {
readonly "thread/started": CodexSchema.V2ThreadStartedNotification;
readonly "thread/status/changed": CodexSchema.V2ThreadStatusChangedNotification;
readonly "thread/archived": CodexSchema.V2ThreadArchivedNotification;
readonly "thread/deleted": CodexSchema.V2ThreadDeletedNotification;
readonly "thread/unarchived": CodexSchema.V2ThreadUnarchivedNotification;
readonly "thread/closed": CodexSchema.V2ThreadClosedNotification;
readonly "skills/changed": CodexSchema.V2SkillsChangedNotification;
readonly "thread/name/updated": CodexSchema.V2ThreadNameUpdatedNotification;
readonly "thread/goal/updated": CodexSchema.V2ThreadGoalUpdatedNotification;
readonly "thread/goal/cleared": CodexSchema.V2ThreadGoalClearedNotification;
readonly "thread/settings/updated": CodexSchema.V2ThreadSettingsUpdatedNotification;
readonly "thread/tokenUsage/updated": CodexSchema.V2ThreadTokenUsageUpdatedNotification;
readonly "turn/started": CodexSchema.V2TurnStartedNotification;
readonly "hook/started": CodexSchema.V2HookStartedNotification;
@@ -410,6 +445,7 @@ export interface ServerNotificationParamsByMethod {
readonly "thread/compacted": CodexSchema.V2ContextCompactedNotification;
readonly "model/rerouted": CodexSchema.V2ModelReroutedNotification;
readonly "model/verification": CodexSchema.V2ModelVerificationNotification;
readonly "turn/moderationMetadata": CodexSchema.V2TurnModerationMetadataNotification;
readonly warning: CodexSchema.V2WarningNotification;
readonly guardianWarning: CodexSchema.V2GuardianWarningNotification;
readonly deprecationNotice: CodexSchema.V2DeprecationNoticeNotification;
@@ -435,8 +471,12 @@ export const CLIENT_REQUEST_PARAMS = {
"thread/resume": CodexSchema.V2ThreadResumeParams,
"thread/fork": CodexSchema.V2ThreadForkParams,
"thread/archive": CodexSchema.V2ThreadArchiveParams,
"thread/delete": CodexSchema.V2ThreadDeleteParams,
"thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeParams,
"thread/name/set": CodexSchema.V2ThreadSetNameParams,
"thread/goal/set": CodexSchema.V2ThreadGoalSetParams,
"thread/goal/get": CodexSchema.V2ThreadGoalGetParams,
"thread/goal/clear": CodexSchema.V2ThreadGoalClearParams,
"thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateParams,
"thread/unarchive": CodexSchema.V2ThreadUnarchiveParams,
"thread/compact/start": CodexSchema.V2ThreadCompactStartParams,
@@ -448,16 +488,19 @@ export const CLIENT_REQUEST_PARAMS = {
"thread/read": CodexSchema.V2ThreadReadParams,
"thread/inject_items": CodexSchema.V2ThreadInjectItemsParams,
"skills/list": CodexSchema.V2SkillsListParams,
"skills/extraRoots/set": CodexSchema.V2SkillsExtraRootsSetParams,
"hooks/list": CodexSchema.V2HooksListParams,
"marketplace/add": CodexSchema.V2MarketplaceAddParams,
"marketplace/remove": CodexSchema.V2MarketplaceRemoveParams,
"marketplace/upgrade": CodexSchema.V2MarketplaceUpgradeParams,
"plugin/list": CodexSchema.V2PluginListParams,
"plugin/installed": CodexSchema.V2PluginInstalledParams,
"plugin/read": CodexSchema.V2PluginReadParams,
"plugin/skill/read": CodexSchema.V2PluginSkillReadParams,
"plugin/share/save": CodexSchema.V2PluginShareSaveParams,
"plugin/share/updateTargets": CodexSchema.V2PluginShareUpdateTargetsParams,
"plugin/share/list": CodexSchema.V2PluginShareListParams,
"plugin/share/checkout": CodexSchema.V2PluginShareCheckoutParams,
"plugin/share/delete": CodexSchema.V2PluginShareDeleteParams,
"app/list": CodexSchema.V2AppsListParams,
"fs/readFile": CodexSchema.V2FsReadFileParams,
@@ -479,6 +522,7 @@ export const CLIENT_REQUEST_PARAMS = {
"model/list": CodexSchema.V2ModelListParams,
"modelProvider/capabilities/read": CodexSchema.V2ModelProviderCapabilitiesReadParams,
"experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListParams,
"permissionProfile/list": CodexSchema.V2PermissionProfileListParams,
"experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetParams,
"mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginParams,
"config/mcpServer/reload": undefined,
@@ -491,6 +535,7 @@ export const CLIENT_REQUEST_PARAMS = {
"account/login/cancel": CodexSchema.V2CancelLoginAccountParams,
"account/logout": undefined,
"account/rateLimits/read": undefined,
"account/usage/read": undefined,
"account/sendAddCreditsNudgeEmail": CodexSchema.V2SendAddCreditsNudgeEmailParams,
"feedback/upload": CodexSchema.V2FeedbackUploadParams,
"command/exec": CodexSchema.V2CommandExecParams,
@@ -516,8 +561,12 @@ export const CLIENT_REQUEST_RESPONSES = {
"thread/resume": CodexSchema.V2ThreadResumeResponse,
"thread/fork": CodexSchema.V2ThreadForkResponse,
"thread/archive": CodexSchema.V2ThreadArchiveResponse,
"thread/delete": CodexSchema.V2ThreadDeleteResponse,
"thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeResponse,
"thread/name/set": CodexSchema.V2ThreadSetNameResponse,
"thread/goal/set": CodexSchema.V2ThreadGoalSetResponse,
"thread/goal/get": CodexSchema.V2ThreadGoalGetResponse,
"thread/goal/clear": CodexSchema.V2ThreadGoalClearResponse,
"thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateResponse,
"thread/unarchive": CodexSchema.V2ThreadUnarchiveResponse,
"thread/compact/start": CodexSchema.V2ThreadCompactStartResponse,
@@ -529,16 +578,19 @@ export const CLIENT_REQUEST_RESPONSES = {
"thread/read": CodexSchema.V2ThreadReadResponse,
"thread/inject_items": CodexSchema.V2ThreadInjectItemsResponse,
"skills/list": CodexSchema.V2SkillsListResponse,
"skills/extraRoots/set": CodexSchema.V2SkillsExtraRootsSetResponse,
"hooks/list": CodexSchema.V2HooksListResponse,
"marketplace/add": CodexSchema.V2MarketplaceAddResponse,
"marketplace/remove": CodexSchema.V2MarketplaceRemoveResponse,
"marketplace/upgrade": CodexSchema.V2MarketplaceUpgradeResponse,
"plugin/list": CodexSchema.V2PluginListResponse,
"plugin/installed": CodexSchema.V2PluginInstalledResponse,
"plugin/read": CodexSchema.V2PluginReadResponse,
"plugin/skill/read": CodexSchema.V2PluginSkillReadResponse,
"plugin/share/save": CodexSchema.V2PluginShareSaveResponse,
"plugin/share/updateTargets": CodexSchema.V2PluginShareUpdateTargetsResponse,
"plugin/share/list": CodexSchema.V2PluginShareListResponse,
"plugin/share/checkout": CodexSchema.V2PluginShareCheckoutResponse,
"plugin/share/delete": CodexSchema.V2PluginShareDeleteResponse,
"app/list": CodexSchema.V2AppsListResponse,
"fs/readFile": CodexSchema.V2FsReadFileResponse,
@@ -560,6 +612,7 @@ export const CLIENT_REQUEST_RESPONSES = {
"model/list": CodexSchema.V2ModelListResponse,
"modelProvider/capabilities/read": CodexSchema.V2ModelProviderCapabilitiesReadResponse,
"experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListResponse,
"permissionProfile/list": CodexSchema.V2PermissionProfileListResponse,
"experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetResponse,
"mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginResponse,
"config/mcpServer/reload": CodexSchema.V2McpServerRefreshResponse,
@@ -572,6 +625,7 @@ export const CLIENT_REQUEST_RESPONSES = {
"account/login/cancel": CodexSchema.V2CancelLoginAccountResponse,
"account/logout": CodexSchema.V2LogoutAccountResponse,
"account/rateLimits/read": CodexSchema.V2GetAccountRateLimitsResponse,
"account/usage/read": CodexSchema.V2GetAccountTokenUsageResponse,
"account/sendAddCreditsNudgeEmail": CodexSchema.V2SendAddCreditsNudgeEmailResponse,
"feedback/upload": CodexSchema.V2FeedbackUploadResponse,
"command/exec": CodexSchema.V2CommandExecResponse,
@@ -603,6 +657,7 @@ export const SERVER_REQUEST_PARAMS = {
"item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalParams,
"item/tool/call": CodexSchema.DynamicToolCallParams,
"account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshParams,
"attestation/generate": CodexSchema.AttestationGenerateParams,
applyPatchApproval: CodexSchema.ApplyPatchApprovalParams,
execCommandApproval: CodexSchema.ExecCommandApprovalParams,
} as const;
@@ -615,6 +670,7 @@ export const SERVER_REQUEST_RESPONSES = {
"item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalResponse,
"item/tool/call": CodexSchema.DynamicToolCallResponse,
"account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshResponse,
"attestation/generate": CodexSchema.AttestationGenerateResponse,
applyPatchApproval: CodexSchema.ApplyPatchApprovalResponse,
execCommandApproval: CodexSchema.ExecCommandApprovalResponse,
} as const;
@@ -624,12 +680,14 @@ export const SERVER_NOTIFICATION_PARAMS = {
"thread/started": CodexSchema.V2ThreadStartedNotification,
"thread/status/changed": CodexSchema.V2ThreadStatusChangedNotification,
"thread/archived": CodexSchema.V2ThreadArchivedNotification,
"thread/deleted": CodexSchema.V2ThreadDeletedNotification,
"thread/unarchived": CodexSchema.V2ThreadUnarchivedNotification,
"thread/closed": CodexSchema.V2ThreadClosedNotification,
"skills/changed": CodexSchema.V2SkillsChangedNotification,
"thread/name/updated": CodexSchema.V2ThreadNameUpdatedNotification,
"thread/goal/updated": CodexSchema.V2ThreadGoalUpdatedNotification,
"thread/goal/cleared": CodexSchema.V2ThreadGoalClearedNotification,
"thread/settings/updated": CodexSchema.V2ThreadSettingsUpdatedNotification,
"thread/tokenUsage/updated": CodexSchema.V2ThreadTokenUsageUpdatedNotification,
"turn/started": CodexSchema.V2TurnStartedNotification,
"hook/started": CodexSchema.V2HookStartedNotification,
@@ -669,6 +727,7 @@ export const SERVER_NOTIFICATION_PARAMS = {
"thread/compacted": CodexSchema.V2ContextCompactedNotification,
"model/rerouted": CodexSchema.V2ModelReroutedNotification,
"model/verification": CodexSchema.V2ModelVerificationNotification,
"turn/moderationMetadata": CodexSchema.V2TurnModerationMetadataNotification,
warning: CodexSchema.V2WarningNotification,
guardianWarning: CodexSchema.V2GuardianWarningNotification,
deprecationNotice: CodexSchema.V2DeprecationNoticeNotification,
@@ -1,5 +1,5 @@
// This file is generated by the effect-codex-app-server package. Do not edit manually.
// Upstream protocol ref: 07b695190f30a450e4921f71f77473e564395c59
// Upstream protocol ref: b39f943a634a6e7ba86c3d6e8cf6d5f35e612566
import * as CodexSchema from "./schema.gen.ts";
@@ -74,6 +74,7 @@ export const v2 = {
GetAccountParams: CodexSchema.V2GetAccountParams,
GetAccountRateLimitsResponse: CodexSchema.V2GetAccountRateLimitsResponse,
GetAccountResponse: CodexSchema.V2GetAccountResponse,
GetAccountTokenUsageResponse: CodexSchema.V2GetAccountTokenUsageResponse,
GuardianWarningNotification: CodexSchema.V2GuardianWarningNotification,
HookCompletedNotification: CodexSchema.V2HookCompletedNotification,
HooksListParams: CodexSchema.V2HooksListParams,
@@ -112,13 +113,19 @@ export const v2 = {
ModelProviderCapabilitiesReadResponse: CodexSchema.V2ModelProviderCapabilitiesReadResponse,
ModelReroutedNotification: CodexSchema.V2ModelReroutedNotification,
ModelVerificationNotification: CodexSchema.V2ModelVerificationNotification,
PermissionProfileListParams: CodexSchema.V2PermissionProfileListParams,
PermissionProfileListResponse: CodexSchema.V2PermissionProfileListResponse,
PlanDeltaNotification: CodexSchema.V2PlanDeltaNotification,
PluginInstalledParams: CodexSchema.V2PluginInstalledParams,
PluginInstalledResponse: CodexSchema.V2PluginInstalledResponse,
PluginInstallParams: CodexSchema.V2PluginInstallParams,
PluginInstallResponse: CodexSchema.V2PluginInstallResponse,
PluginListParams: CodexSchema.V2PluginListParams,
PluginListResponse: CodexSchema.V2PluginListResponse,
PluginReadParams: CodexSchema.V2PluginReadParams,
PluginReadResponse: CodexSchema.V2PluginReadResponse,
PluginShareCheckoutParams: CodexSchema.V2PluginShareCheckoutParams,
PluginShareCheckoutResponse: CodexSchema.V2PluginShareCheckoutResponse,
PluginShareDeleteParams: CodexSchema.V2PluginShareDeleteParams,
PluginShareDeleteResponse: CodexSchema.V2PluginShareDeleteResponse,
PluginShareListParams: CodexSchema.V2PluginShareListParams,
@@ -146,6 +153,8 @@ export const v2 = {
SkillsChangedNotification: CodexSchema.V2SkillsChangedNotification,
SkillsConfigWriteParams: CodexSchema.V2SkillsConfigWriteParams,
SkillsConfigWriteResponse: CodexSchema.V2SkillsConfigWriteResponse,
SkillsExtraRootsSetParams: CodexSchema.V2SkillsExtraRootsSetParams,
SkillsExtraRootsSetResponse: CodexSchema.V2SkillsExtraRootsSetResponse,
SkillsListParams: CodexSchema.V2SkillsListParams,
SkillsListResponse: CodexSchema.V2SkillsListResponse,
TerminalInteractionNotification: CodexSchema.V2TerminalInteractionNotification,
@@ -158,9 +167,18 @@ export const v2 = {
ThreadClosedNotification: CodexSchema.V2ThreadClosedNotification,
ThreadCompactStartParams: CodexSchema.V2ThreadCompactStartParams,
ThreadCompactStartResponse: CodexSchema.V2ThreadCompactStartResponse,
ThreadDeletedNotification: CodexSchema.V2ThreadDeletedNotification,
ThreadDeleteParams: CodexSchema.V2ThreadDeleteParams,
ThreadDeleteResponse: CodexSchema.V2ThreadDeleteResponse,
ThreadForkParams: CodexSchema.V2ThreadForkParams,
ThreadForkResponse: CodexSchema.V2ThreadForkResponse,
ThreadGoalClearedNotification: CodexSchema.V2ThreadGoalClearedNotification,
ThreadGoalClearParams: CodexSchema.V2ThreadGoalClearParams,
ThreadGoalClearResponse: CodexSchema.V2ThreadGoalClearResponse,
ThreadGoalGetParams: CodexSchema.V2ThreadGoalGetParams,
ThreadGoalGetResponse: CodexSchema.V2ThreadGoalGetResponse,
ThreadGoalSetParams: CodexSchema.V2ThreadGoalSetParams,
ThreadGoalSetResponse: CodexSchema.V2ThreadGoalSetResponse,
ThreadGoalUpdatedNotification: CodexSchema.V2ThreadGoalUpdatedNotification,
ThreadInjectItemsParams: CodexSchema.V2ThreadInjectItemsParams,
ThreadInjectItemsResponse: CodexSchema.V2ThreadInjectItemsResponse,
@@ -189,6 +207,7 @@ export const v2 = {
ThreadRollbackResponse: CodexSchema.V2ThreadRollbackResponse,
ThreadSetNameParams: CodexSchema.V2ThreadSetNameParams,
ThreadSetNameResponse: CodexSchema.V2ThreadSetNameResponse,
ThreadSettingsUpdatedNotification: CodexSchema.V2ThreadSettingsUpdatedNotification,
ThreadShellCommandParams: CodexSchema.V2ThreadShellCommandParams,
ThreadShellCommandResponse: CodexSchema.V2ThreadShellCommandResponse,
ThreadStartedNotification: CodexSchema.V2ThreadStartedNotification,
@@ -205,6 +224,7 @@ export const v2 = {
TurnDiffUpdatedNotification: CodexSchema.V2TurnDiffUpdatedNotification,
TurnInterruptParams: CodexSchema.V2TurnInterruptParams,
TurnInterruptResponse: CodexSchema.V2TurnInterruptResponse,
TurnModerationMetadataNotification: CodexSchema.V2TurnModerationMetadataNotification,
TurnPlanUpdatedNotification: CodexSchema.V2TurnPlanUpdatedNotification,
TurnStartedNotification: CodexSchema.V2TurnStartedNotification,
TurnStartParams: CodexSchema.V2TurnStartParams,
File diff suppressed because it is too large. Load diff
@@ -152,4 +152,41 @@ it.layer(NodeServices.layer)("effect-codex-app-server client", (it) => {
assert.equal(initialized.userAgent, "mock-codex-app-server");
}),
);
it.effect("drains command stderr so large diagnostics cannot block protocol responses", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const scope = yield* Scope.make();
const clientLayer = CodexClient.layerCommand({
command: "node",
args: mockPeerArgs(yield* mockPeerPath),
cwd: path.join(import.meta.dirname, ".."),
env: {
CODEX_APP_SERVER_TEST_STDERR_BYTES: String(512 * 1024),
},
});
const context = yield* Layer.buildWithScope(clientLayer, scope);
const initialized = yield* Effect.gen(function* () {
const client = yield* CodexClient.CodexAppServerClient;
return yield* client.request("initialize", {
clientInfo: {
name: "effect-codex-app-server-test",
title: "Effect Codex App Server Test",
version: "0.0.0",
},
capabilities: {
experimentalApi: true,
optOutNotificationMethods: null,
},
});
}).pipe(
Effect.timeout("5 seconds"),
Effect.provide(context),
Effect.ensuring(Scope.close(scope, Exit.void)),
);
assert.equal(initialized.userAgent, "mock-codex-app-server");
}),
);
});
+11 -10
View File
@@ -4,6 +4,7 @@ import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stdio from "effect/Stdio";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as CodexRpc from "./_generated/meta.gen.ts";
@@ -253,11 +254,15 @@ export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make
export const layerChildProcess = (
handle: ChildProcessSpawner.ChildProcessHandle,
options: CodexAppServerClientOptions = {},
): Layer.Layer<CodexAppServerClient> => {
const stdio = makeChildStdio(handle);
const terminationError = makeTerminationError(handle);
return Layer.effect(CodexAppServerClient, make(stdio, options, terminationError));
};
): Layer.Layer<CodexAppServerClient> =>
Layer.effect(CodexAppServerClient, makeChildProcessClient(handle, options));
const makeChildProcessClient = Effect.fn(
"effect-codex-app-server/CodexAppServerClient.makeChildProcessClient",
)(function* (handle: ChildProcessSpawner.ChildProcessHandle, options: CodexAppServerClientOptions) {
yield* Stream.runDrain(handle.stderr).pipe(Effect.ignore, Effect.forkScoped);
return yield* make(makeChildStdio(handle), options, makeTerminationError(handle));
});
export interface CodexAppServerCommandLayerOptions extends CodexAppServerClientOptions {
readonly command: string;
@@ -292,9 +297,5 @@ export const layerCommand = (
}),
),
);
}).pipe(
Effect.flatMap((handle) =>
make(makeChildStdio(handle), options, makeTerminationError(handle)),
),
),
}).pipe(Effect.flatMap((handle) => makeChildProcessClient(handle, options))),
);
@@ -10,6 +10,8 @@ import { assert, it } from "@effect/vitest";
import * as CodexError from "./errors.ts";
import * as CodexProtocol from "./protocol.ts";
import * as CodexRpc from "./rpc.ts";
import * as CodexSchema from "./schema.ts";
import { makeInMemoryStdio } from "./_internal/stdio.ts";
const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
@@ -18,8 +20,28 @@ const encoder = new TextEncoder();
const encodeJsonl = (value: unknown) => encoder.encode(`${encodeUnknownJsonString(value)}\n`);
const decodeJson = Schema.decodeEffect(Schema.UnknownFromJsonString);
const decodeAccountTokenUsageResponse = Schema.decodeUnknownEffect(
CodexRpc.CLIENT_REQUEST_RESPONSES["account/usage/read"],
);
it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
it.effect("maps account usage responses to the upstream token usage schema", () =>
Effect.gen(function* () {
assert.strictEqual(
CodexRpc.CLIENT_REQUEST_RESPONSES["account/usage/read"],
CodexSchema.V2GetAccountTokenUsageResponse,
);
const decoded = yield* decodeAccountTokenUsageResponse({
dailyUsageBuckets: [{ startDate: "2026-06-10", tokens: 42 }],
summary: { lifetimeTokens: 42 },
});
assert.deepEqual(decoded, {
dailyUsageBuckets: [{ startDate: "2026-06-10", tokens: 42 }],
summary: { lifetimeTokens: 42 },
});
}),
);
it.effect(
"encodes requests without a jsonrpc field and routes inbound requests and notifications",
() =>
@@ -34,6 +34,18 @@ const handleMethod = (message: Record<string, unknown>) => {
switch (method) {
case "initialize": {
const stderrBytes = Number(process.env.CODEX_APP_SERVER_TEST_STDERR_BYTES ?? 0);
if (Number.isFinite(stderrBytes) && stderrBytes > 0) {
process.stderr.write("x".repeat(stderrBytes), () => {
respond(message.id as number | string, {
userAgent: "mock-codex-app-server",
codexHome: process.cwd(),
platformFamily: process.platform === "win32" ? "windows" : "unix",
platformOs: process.platform === "darwin" ? "macos" : process.platform,
});
});
return;
}
respond(message.id as number | string, {
userAgent: "mock-codex-app-server",
codexHome: process.cwd(),