effect-codex-app-server (#1942)

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex authored and GitHub committed 2026-04-19 21:46:40 -07:00
1 parent 66c326b8c4
commit 3b98fe3548
35 files changed
+38195 -5470

No files matched your search

+1
View File
@@ -44,6 +44,7 @@
"@types/bun": "catalog:",
"@types/node": "catalog:",
"effect-acp": "workspace:*",
"effect-codex-app-server": "workspace:*",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -29,9 +29,7 @@ import {
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { normalizeCodexModelOptionsWithCapabilities } from "@t3tools/shared/model";
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
@@ -156,10 +154,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {
).pipe(Effect.catch(() => Effect.undefined));
const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
getCodexModelCapabilities(modelSelection.model),
modelSelection.options,
);
const reasoningEffort =
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
const command = ChildProcess.make(
@@ -174,7 +168,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
modelSelection.model,
"--config",
`model_reasoning_effort="${reasoningEffort}"`,
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
...(modelSelection.options?.fastMode ? ["--config", `service_tier="fast"`] : []),
"--output-schema",
schemaPath,
"--output-last-message",
@@ -0,0 +1,134 @@
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
## Mode rules (strict)
You are in **Plan Mode** until a developer message explicitly ends it.
Plan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it.
## Plan Mode vs update_plan tool
Plan Mode is a collaboration mode that can involve requesting user input and eventually issuing a \`<proposed_plan>\` block.
Separately, \`update_plan\` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use \`update_plan\` in Plan mode, it will return an error.
## Execution vs. mutation in Plan Mode
You may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions.
### Allowed (non-mutating, plan-improving)
Actions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples:
* Reading or searching files, configs, schemas, types, manifests, and docs
* Static analysis, inspection, and repo exploration
* Dry-run style commands when they do not edit repo-tracked files
* Tests, builds, or checks that may write to caches or build artifacts (for example, \`target/\`, \`.cache/\`, or snapshots) so long as they do not edit repo-tracked files
### Not allowed (mutating, plan-executing)
Actions that implement the plan or change repo-tracked state. Examples:
* Editing or writing files
* Running formatters or linters that rewrite files
* Applying patches, migrations, or codegen that updates repo-tracked files
* Side-effectful commands whose purpose is to carry out the plan rather than refine it
When in doubt: if the action would reasonably be described as "doing the work" rather than "planning the work," do not do it.
## PHASE 1 - Ground in the environment (explore first, ask second)
Begin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged.
Before asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available.
Exception: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first.
Do not ask questions that can be answered from the repo or system (for example, "where is this struct?" or "which UI component should we use?" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration.
## PHASE 2 - Intent chat (what they actually want)
* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs.
* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask.
## PHASE 3 - Implementation chat (what/how we'll build)
* Once intent is stable, keep asking until the spec is decision complete: approach, interfaces (APIs/schemas/I/O), data flow, edge cases/failure modes, testing + acceptance criteria, rollout/monitoring, and any migrations/compat constraints.
## Asking questions
Critical rules:
* Strongly prefer using the \`request_user_input\` tool to ask any questions.
* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant.
* In rare cases where an unavoidable, important question can't be expressed with reasonable multiple-choice options (due to extreme ambiguity), you may ask it directly without the tool.
You SHOULD ask many questions, but each question must:
* materially change the spec/plan, OR
* confirm/lock an assumption, OR
* choose between meaningful tradeoffs.
* not be answerable by non-mutating commands.
Use the \`request_user_input\` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration.
## Two kinds of unknowns (treat differently)
1. **Discoverable facts** (repo/system truth): explore first.
* Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants).
* Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent.
* If asking, present concrete candidates (paths/service names) + recommend one.
* Never ask questions you can answer from your environment (e.g., "where is this struct").
2. **Preferences/tradeoffs** (not discoverable): ask early.
* These are intent or implementation preferences that cannot be derived from exploration.
* Provide 2-4 mutually exclusive options + a recommended default.
* If unanswered, proceed with the recommended option and record it as an assumption in the final plan.
## Finalization rule
Only output the final plan when it is decision complete and leaves no decisions to the implementer.
When you present the official plan, wrap it in a \`<proposed_plan>\` block so the client can render it specially:
1) The opening tag must be on its own line.
2) Start the plan content on the next line (no text on the same line as the tag).
3) The closing tag must be on its own line.
4) Use Markdown inside the block.
5) Keep the tags exactly as \`<proposed_plan>\` and \`</proposed_plan>\` (do not translate or rename them), even if the plan content is in another language.
Example:
<proposed_plan>
plan content
</proposed_plan>
plan content should be human and agent digestible. The final plan must be plan-only and include:
* A clear title
* A brief summary section
* Important changes or additions to public APIs/interfaces/types
* Test cases and scenarios
* Explicit assumptions and defaults chosen where needed
Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a \`<proposed_plan>\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.
Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
</collaboration_mode>`;
export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Collaboration Mode: Default
You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.
Your active mode changes only when new developer instructions with a different \`<collaboration_mode>...</collaboration_mode>\` change it; user requests or tool descriptions do not change mode by themselves. Known mode names are Default and Plan.
## request_user_input availability
The \`request_user_input\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error.
In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.
</collaboration_mode>`;
@@ -1,4 +1,7 @@
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import {
ApprovalRequestId,
EventId,
@@ -12,20 +15,22 @@ import {
TurnId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { afterAll, it, vi } from "@effect/vitest";
import { it, vi } from "@effect/vitest";
import { Effect, Fiber, Layer, Option, Stream } from "effect";
import { Effect, Exit, Fiber, Layer, Option, Queue, Scope, Stream } from "effect";
import * as CodexErrors from "effect-codex-app-server/errors";
import {
CodexAppServerManager,
type CodexAppServerStartSessionInput,
type CodexAppServerSendTurnInput,
} from "../../codexAppServerManager.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderAdapterValidationError } from "../Errors.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import {
type CodexSessionRuntimeOptions,
type CodexSessionRuntimeSendTurnInput,
type CodexSessionRuntimeShape,
type CodexThreadSnapshot,
} from "./CodexSessionRuntime.ts";
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
@@ -33,110 +38,157 @@ const asTurnId = (value: string): TurnId => TurnId.make(value);
const asEventId = (value: string): EventId => EventId.make(value);
const asItemId = (value: string): ProviderItemId => ProviderItemId.make(value);
class FakeCodexManager extends CodexAppServerManager {
public startSessionImpl = vi.fn(
async (input: CodexAppServerStartSessionInput): Promise<ProviderSession> => {
const now = new Date().toISOString();
return {
provider: "codex",
status: "ready",
runtimeMode: input.runtimeMode,
threadId: input.threadId,
cwd: input.cwd,
createdAt: now,
updatedAt: now,
};
},
class FakeCodexRuntime implements CodexSessionRuntimeShape {
private readonly eventQueue = Effect.runSync(Queue.unbounded<ProviderEvent>());
private readonly now = new Date().toISOString();
public readonly startImpl = vi.fn(() =>
Promise.resolve({
provider: "codex" as const,
status: "ready" as const,
runtimeMode: this.options.runtimeMode,
threadId: this.options.threadId,
cwd: this.options.cwd,
...(this.options.model ? { model: this.options.model } : {}),
createdAt: this.now,
updatedAt: this.now,
} satisfies ProviderSession),
);
public sendTurnImpl = vi.fn(
async (_input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> => ({
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-1"),
public readonly sendTurnImpl = vi.fn(
(_input: CodexSessionRuntimeSendTurnInput): Promise<ProviderTurnStartResult> =>
Promise.resolve({
threadId: this.options.threadId,
turnId: asTurnId("turn-1"),
}),
);
public readonly interruptTurnImpl = vi.fn(
(_turnId?: TurnId): Promise<void> => Promise.resolve(undefined),
);
public readonly readThreadImpl = vi.fn(
(): Promise<CodexThreadSnapshot> =>
Promise.resolve({
threadId: "provider-thread-1",
turns: [],
}),
);
public readonly rollbackThreadImpl = vi.fn(
(_numTurns: number): Promise<CodexThreadSnapshot> =>
Promise.resolve({
threadId: "provider-thread-1",
turns: [],
}),
);
public readonly respondToRequestImpl = vi.fn(
(_requestId: ApprovalRequestId, _decision: ProviderApprovalDecision): Promise<void> =>
Promise.resolve(undefined),
);
public readonly respondToUserInputImpl = vi.fn(
(_requestId: ApprovalRequestId, _answers: ProviderUserInputAnswers): Promise<void> =>
Promise.resolve(undefined),
);
public readonly closeImpl = vi.fn(() => Promise.resolve(undefined));
readonly options: CodexSessionRuntimeOptions;
constructor(options: CodexSessionRuntimeOptions) {
this.options = options;
}
start() {
return Effect.promise(() => this.startImpl());
}
getSession = Effect.promise(() => this.startImpl());
sendTurn(input: CodexSessionRuntimeSendTurnInput) {
return Effect.promise(() => this.sendTurnImpl(input));
}
interruptTurn(turnId?: TurnId) {
return Effect.promise(() => this.interruptTurnImpl(turnId));
}
readThread = Effect.promise(() => this.readThreadImpl());
rollbackThread(numTurns: number) {
return Effect.promise(() => this.rollbackThreadImpl(numTurns));
}
respondToRequest(requestId: ApprovalRequestId, decision: ProviderApprovalDecision) {
return Effect.promise(() => this.respondToRequestImpl(requestId, decision));
}
respondToUserInput(requestId: ApprovalRequestId, answers: ProviderUserInputAnswers) {
return Effect.promise(() => this.respondToUserInputImpl(requestId, answers));
}
get events() {
return Stream.fromQueue(this.eventQueue);
}
close = Effect.promise(() => this.closeImpl());
emit(event: ProviderEvent) {
return Queue.offer(this.eventQueue, event).pipe(Effect.asVoid);
}
}
function makeRuntimeFactory() {
const runtimes: Array<FakeCodexRuntime> = [];
const factory = vi.fn((options: CodexSessionRuntimeOptions) => {
const runtime = new FakeCodexRuntime(options);
runtimes.push(runtime);
return Effect.succeed(runtime);
});
return {
factory,
get lastRuntime(): FakeCodexRuntime | undefined {
return runtimes.at(-1);
},
};
}
function makeScopedRuntimeFactory(options?: { readonly failConstruction?: boolean }) {
const runtimes: Array<FakeCodexRuntime> = [];
const releasedThreadIds: Array<ThreadId> = [];
const factory = vi.fn((runtimeOptions: CodexSessionRuntimeOptions) =>
Effect.gen(function* () {
yield* Scope.Scope;
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
releasedThreadIds.push(runtimeOptions.threadId);
}),
);
if (options?.failConstruction) {
return yield* new CodexErrors.CodexAppServerSpawnError({
command: `${runtimeOptions.binaryPath} app-server`,
cause: new Error("runtime construction failed"),
});
}
const runtime = new FakeCodexRuntime(runtimeOptions);
runtimes.push(runtime);
return runtime;
}),
);
public interruptTurnImpl = vi.fn(
async (_threadId: ThreadId, _turnId?: TurnId): Promise<void> => undefined,
);
public readThreadImpl = vi.fn(async (_threadId: ThreadId) => ({
threadId: asThreadId("thread-1"),
turns: [],
}));
public rollbackThreadImpl = vi.fn(async (_threadId: ThreadId, _numTurns: number) => ({
threadId: asThreadId("thread-1"),
turns: [],
}));
public respondToRequestImpl = vi.fn(
async (
_threadId: ThreadId,
_requestId: ApprovalRequestId,
_decision: ProviderApprovalDecision,
): Promise<void> => undefined,
);
public respondToUserInputImpl = vi.fn(
async (
_threadId: ThreadId,
_requestId: ApprovalRequestId,
_answers: ProviderUserInputAnswers,
): Promise<void> => undefined,
);
public stopAllImpl = vi.fn(() => undefined);
override startSession(input: CodexAppServerStartSessionInput): Promise<ProviderSession> {
return this.startSessionImpl(input);
}
override sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
return this.sendTurnImpl(input);
}
override interruptTurn(threadId: ThreadId, turnId?: TurnId): Promise<void> {
return this.interruptTurnImpl(threadId, turnId);
}
override readThread(threadId: ThreadId) {
return this.readThreadImpl(threadId);
}
override rollbackThread(threadId: ThreadId, numTurns: number) {
return this.rollbackThreadImpl(threadId, numTurns);
}
override respondToRequest(
threadId: ThreadId,
requestId: ApprovalRequestId,
decision: ProviderApprovalDecision,
): Promise<void> {
return this.respondToRequestImpl(threadId, requestId, decision);
}
override respondToUserInput(
threadId: ThreadId,
requestId: ApprovalRequestId,
answers: ProviderUserInputAnswers,
): Promise<void> {
return this.respondToUserInputImpl(threadId, requestId, answers);
}
override stopSession(_threadId: ThreadId): void {}
override listSessions(): ProviderSession[] {
return [];
}
override hasSession(_threadId: ThreadId): boolean {
return false;
}
override stopAll(): void {
this.stopAllImpl();
}
return {
factory,
releasedThreadIds,
get lastRuntime(): FakeCodexRuntime | undefined {
return runtimes.at(-1);
},
};
}
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
@@ -148,9 +200,9 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory
listBindings: () => Effect.succeed([]),
});
const validationManager = new FakeCodexManager();
const validationRuntimeFactory = makeRuntimeFactory();
const validationLayer = it.layer(
makeCodexAdapterLive({ manager: validationManager }).pipe(
makeCodexAdapterLive({ makeRuntime: validationRuntimeFactory.factory }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -179,12 +231,12 @@ validationLayer("CodexAdapterLive validation", (it) => {
issue: "Expected provider 'codex' but received 'claudeAgent'.",
}),
);
assert.equal(validationManager.startSessionImpl.mock.calls.length, 0);
assert.equal(validationRuntimeFactory.factory.mock.calls.length, 0);
}),
);
it.effect("maps codex model options before starting a session", () =>
Effect.gen(function* () {
validationManager.startSessionImpl.mockClear();
validationRuntimeFactory.factory.mockClear();
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
@@ -200,24 +252,21 @@ validationLayer("CodexAdapterLive validation", (it) => {
runtimeMode: "full-access",
});
assert.deepStrictEqual(validationManager.startSessionImpl.mock.calls[0]?.[0], {
provider: "codex",
threadId: asThreadId("thread-1"),
assert.deepStrictEqual(validationRuntimeFactory.factory.mock.calls[0]?.[0], {
binaryPath: "codex",
cwd: process.cwd(),
model: "gpt-5.3-codex",
serviceTier: "fast",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
});
}),
);
});
const sessionErrorManager = new FakeCodexManager();
sessionErrorManager.sendTurnImpl.mockImplementation(async () => {
throw new Error("Unknown session: sess-missing");
});
const sessionRuntimeFactory = makeRuntimeFactory();
const sessionErrorLayer = it.layer(
makeCodexAdapterLive({ manager: sessionErrorManager }).pipe(
makeCodexAdapterLive({ makeRuntime: sessionRuntimeFactory.factory }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -226,7 +275,7 @@ const sessionErrorLayer = it.layer(
);
sessionErrorLayer("CodexAdapterLive session errors", (it) => {
it.effect("maps unknown-session sendTurn errors to ProviderAdapterSessionNotFoundError", () =>
it.effect("maps missing adapter sessions to ProviderAdapterSessionNotFoundError", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const result = yield* adapter
@@ -241,14 +290,20 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
assert.equal(result.failure._tag, "ProviderAdapterSessionNotFoundError");
assert.equal(result.failure.provider, "codex");
assert.equal(result.failure.threadId, "sess-missing");
assert.equal(result.failure.cause instanceof Error, true);
}),
);
it.effect("maps codex model options before sending a turn", () =>
Effect.gen(function* () {
sessionErrorManager.sendTurnImpl.mockClear();
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
provider: "codex",
threadId: asThreadId("sess-missing"),
runtimeMode: "full-access",
});
const runtime = sessionRuntimeFactory.lastRuntime;
assert.ok(runtime);
runtime.sendTurnImpl.mockClear();
yield* Effect.ignore(
adapter.sendTurn({
@@ -266,8 +321,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
}),
);
assert.deepStrictEqual(sessionErrorManager.sendTurnImpl.mock.calls[0]?.[0], {
threadId: asThreadId("sess-missing"),
assert.deepStrictEqual(runtime.sendTurnImpl.mock.calls[0]?.[0], {
input: "hello",
model: "gpt-5.3-codex",
effort: "high",
@@ -277,9 +331,9 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
);
});
const lifecycleManager = new FakeCodexManager();
const lifecycleRuntimeFactory = makeRuntimeFactory();
const lifecycleLayer = it.layer(
makeCodexAdapterLive({ manager: lifecycleManager }).pipe(
makeCodexAdapterLive({ makeRuntime: lifecycleRuntimeFactory.factory }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -287,10 +341,24 @@ const lifecycleLayer = it.layer(
),
);
function startLifecycleRuntime() {
return Effect.gen(function* () {
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
provider: "codex",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
});
const runtime = lifecycleRuntimeFactory.lastRuntime;
assert.ok(runtime);
return { adapter, runtime };
});
}
lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("maps completed agent message items to canonical item.completed events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
const event: ProviderEvent = {
@@ -303,14 +371,17 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
turnId: asTurnId("turn-1"),
itemId: asItemId("msg_1"),
payload: {
threadId: "thread-1",
turnId: "turn-1",
item: {
type: "agentMessage",
id: "msg_1",
text: "done",
},
},
};
lifecycleManager.emit("event", event);
yield* runtime.emit(event);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
@@ -329,7 +400,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("maps completed plan items to canonical proposed-plan completion events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
const event: ProviderEvent = {
@@ -342,15 +413,17 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
turnId: asTurnId("turn-1"),
itemId: asItemId("plan_1"),
payload: {
threadId: "thread-1",
turnId: "turn-1",
item: {
type: "Plan",
type: "plan",
id: "plan_1",
text: "## Final plan\n\n- one\n- two",
},
},
};
lifecycleManager.emit("event", event);
yield* runtime.emit(event);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
@@ -368,10 +441,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("maps plan deltas to canonical proposed-plan delta events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
lifecycleManager.emit("event", {
yield* runtime.emit({
id: asEventId("evt-plan-delta"),
kind: "notification",
provider: "codex",
@@ -381,6 +454,9 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
turnId: asTurnId("turn-1"),
itemId: asItemId("plan_1"),
payload: {
threadId: "thread-1",
turnId: "turn-1",
itemId: "plan_1",
delta: "## Final plan",
},
} satisfies ProviderEvent);
@@ -402,7 +478,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("maps session/closed lifecycle events to canonical session.exited runtime events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
const event: ProviderEvent = {
@@ -415,7 +491,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
message: "Session stopped",
};
lifecycleManager.emit("event", event);
yield* runtime.emit(event);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
@@ -433,10 +509,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("maps retryable Codex error notifications to runtime.warning", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
lifecycleManager.emit("event", {
yield* runtime.emit({
id: asEventId("evt-retryable-error"),
kind: "notification",
provider: "codex",
@@ -445,6 +521,8 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
method: "error",
turnId: asTurnId("turn-1"),
payload: {
threadId: "thread-1",
turnId: "turn-1",
error: {
message: "Reconnecting... 2/5",
},
@@ -469,10 +547,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("maps process stderr notifications to runtime.warning", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
lifecycleManager.emit("event", {
yield* runtime.emit({
id: asEventId("evt-process-stderr"),
kind: "notification",
provider: "codex",
@@ -503,10 +581,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("maps fatal websocket stderr notifications to runtime.error", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
lifecycleManager.emit("event", {
yield* runtime.emit({
id: asEventId("evt-process-stderr-websocket"),
kind: "notification",
provider: "codex",
@@ -539,7 +617,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("preserves request type when mapping serverRequest/resolved", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
const event: ProviderEvent = {
@@ -549,16 +627,15 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "serverRequest/resolved",
requestKind: "command",
requestId: ApprovalRequestId.make("req-1"),
payload: {
request: {
method: "item/commandExecution/requestApproval",
},
decision: "accept",
threadId: "thread-1",
requestId: "req-1",
},
};
lifecycleManager.emit("event", event);
yield* runtime.emit(event);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
@@ -575,7 +652,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("preserves file-read request type when mapping serverRequest/resolved", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
const event: ProviderEvent = {
@@ -585,16 +662,15 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "serverRequest/resolved",
requestKind: "file-read",
requestId: ApprovalRequestId.make("req-file-read-1"),
payload: {
request: {
method: "item/fileRead/requestApproval",
},
decision: "accept",
threadId: "thread-1",
requestId: "req-file-read-1",
},
};
lifecycleManager.emit("event", event);
yield* runtime.emit(event);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
@@ -611,7 +687,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("preserves explicit empty multi-select user-input answers", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
const event: ProviderEvent = {
@@ -623,12 +699,14 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
method: "item/tool/requestUserInput/answered",
payload: {
answers: {
scope: [],
scope: {
answers: [],
},
},
},
};
lifecycleManager.emit("event", event);
yield* runtime.emit(event);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
@@ -647,7 +725,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("maps windowsSandbox/setupCompleted to session state and warning on failure", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 2)).pipe(
Effect.forkChild,
);
@@ -661,12 +739,13 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
method: "windowsSandbox/setupCompleted",
message: "Sandbox setup failed",
payload: {
mode: "unelevated",
success: false,
detail: "unsupported environment",
error: "unsupported environment",
},
};
lifecycleManager.emit("event", event);
yield* runtime.emit(event);
const events = Array.from(yield* Fiber.join(eventsFiber));
assert.equal(events.length, 2);
@@ -691,12 +770,12 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
"maps requestUserInput requests and answered notifications to canonical user-input events",
() =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 2)).pipe(
Effect.forkChild,
);
lifecycleManager.emit("event", {
yield* runtime.emit({
id: asEventId("evt-user-input-requested"),
kind: "request",
provider: "codex",
@@ -705,6 +784,9 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
method: "item/tool/requestUserInput",
requestId: ApprovalRequestId.make("req-user-input-1"),
payload: {
itemId: "item-user-input-1",
threadId: "thread-1",
turnId: "turn-1",
questions: [
{
id: "sandbox_mode",
@@ -716,12 +798,11 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
description: "Allow workspace writes only",
},
],
multiSelect: true,
},
],
},
} satisfies ProviderEvent);
lifecycleManager.emit("event", {
yield* runtime.emit({
id: asEventId("evt-user-input-resolved"),
kind: "notification",
provider: "codex",
@@ -743,7 +824,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
if (events[0]?.type === "user-input.requested") {
assert.equal(events[0].requestId, "req-user-input-1");
assert.equal(events[0].payload.questions[0]?.id, "sandbox_mode");
assert.equal(events[0].payload.questions[0]?.multiSelect, true);
assert.equal(events[0].payload.questions[0]?.multiSelect, false);
}
assert.equal(events[1]?.type, "user-input.resolved");
@@ -756,168 +837,12 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
}),
);
it.effect("maps Codex task and reasoning event chunks into canonical runtime events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 5)).pipe(
Effect.forkChild,
);
lifecycleManager.emit("event", {
id: asEventId("evt-codex-task-started"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "codex/event/task_started",
payload: {
id: "turn-structured-1",
msg: {
type: "task_started",
turn_id: "turn-structured-1",
collaboration_mode_kind: "plan",
},
},
} satisfies ProviderEvent);
lifecycleManager.emit("event", {
id: asEventId("evt-codex-agent-reasoning"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "codex/event/agent_reasoning",
payload: {
id: "turn-structured-1",
msg: {
type: "agent_reasoning",
text: "Need to compare both transport layers before finalizing the plan.",
},
},
} satisfies ProviderEvent);
lifecycleManager.emit("event", {
id: asEventId("evt-codex-reasoning-delta"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "codex/event/reasoning_content_delta",
payload: {
id: "turn-structured-1",
msg: {
type: "reasoning_content_delta",
turn_id: "turn-structured-1",
item_id: "rs_reasoning_1",
delta: "**Compare** transport boundaries",
summary_index: 0,
},
},
} satisfies ProviderEvent);
lifecycleManager.emit("event", {
id: asEventId("evt-codex-task-complete"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "codex/event/task_complete",
payload: {
id: "turn-structured-1",
msg: {
type: "task_complete",
turn_id: "turn-structured-1",
last_agent_message: "<proposed_plan>\n# Ship it\n</proposed_plan>",
},
},
} satisfies ProviderEvent);
const events = Array.from(yield* Fiber.join(eventsFiber));
assert.equal(events[0]?.type, "task.started");
if (events[0]?.type === "task.started") {
assert.equal(events[0].turnId, "turn-structured-1");
assert.equal(events[0].payload.taskId, "turn-structured-1");
assert.equal(events[0].payload.taskType, "plan");
}
assert.equal(events[1]?.type, "task.progress");
if (events[1]?.type === "task.progress") {
assert.equal(events[1].payload.taskId, "turn-structured-1");
assert.equal(
events[1].payload.description,
"Need to compare both transport layers before finalizing the plan.",
);
}
assert.equal(events[2]?.type, "content.delta");
if (events[2]?.type === "content.delta") {
assert.equal(events[2].turnId, "turn-structured-1");
assert.equal(events[2].itemId, "rs_reasoning_1");
assert.equal(events[2].payload.streamKind, "reasoning_summary_text");
assert.equal(events[2].payload.summaryIndex, 0);
}
assert.equal(events[3]?.type, "task.completed");
if (events[3]?.type === "task.completed") {
assert.equal(events[3].turnId, "turn-structured-1");
assert.equal(events[3].payload.taskId, "turn-structured-1");
assert.equal(events[3].payload.summary, "<proposed_plan>\n# Ship it\n</proposed_plan>");
}
assert.equal(events[4]?.type, "turn.proposed.completed");
if (events[4]?.type === "turn.proposed.completed") {
assert.equal(events[4].turnId, "turn-structured-1");
assert.equal(events[4].payload.planMarkdown, "# Ship it");
}
}),
);
it.effect("prefers manager-assigned turn ids for Codex task events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
lifecycleManager.emit("event", {
id: asEventId("evt-codex-task-started-parent-turn"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-parent"),
createdAt: new Date().toISOString(),
method: "codex/event/task_started",
payload: {
id: "turn-child",
msg: {
type: "task_started",
turn_id: "turn-child",
collaboration_mode_kind: "default",
},
conversationId: "child-provider-thread",
},
} satisfies ProviderEvent);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
if (firstEvent._tag !== "Some") {
return;
}
assert.equal(firstEvent.value.type, "task.started");
if (firstEvent.value.type !== "task.started") {
return;
}
assert.equal(firstEvent.value.turnId, "turn-parent");
assert.equal(firstEvent.value.providerRefs?.providerTurnId, "turn-parent");
assert.equal(firstEvent.value.payload.taskId, "turn-child");
}),
);
it.effect("unwraps Codex token usage payloads for context window events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
lifecycleManager.emit("event", {
yield* runtime.emit({
id: asEventId("evt-codex-thread-token-usage-updated"),
kind: "notification",
provider: "codex",
@@ -977,9 +902,130 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
);
});
afterAll(() => {
if (lifecycleManager.stopAllImpl.mock.calls.length === 0) {
lifecycleManager.stopAll();
}
assert.ok(lifecycleManager.stopAllImpl.mock.calls.length >= 1);
const scopedLifecycleRuntimeFactory = makeScopedRuntimeFactory();
const scopedLifecycleLayer = it.layer(
makeCodexAdapterLive({ makeRuntime: scopedLifecycleRuntimeFactory.factory }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
);
scopedLifecycleLayer("CodexAdapterLive scoped lifecycle", (it) => {
it.effect("closes the externally owned session scope on stopSession", () =>
Effect.gen(function* () {
scopedLifecycleRuntimeFactory.releasedThreadIds.length = 0;
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
provider: "codex",
threadId: asThreadId("thread-stop"),
runtimeMode: "full-access",
});
const runtime = scopedLifecycleRuntimeFactory.lastRuntime;
assert.ok(runtime);
yield* adapter.stopSession(asThreadId("thread-stop"));
assert.equal(runtime.closeImpl.mock.calls.length, 1);
assert.deepStrictEqual(scopedLifecycleRuntimeFactory.releasedThreadIds, [
asThreadId("thread-stop"),
]);
assert.equal(yield* adapter.hasSession(asThreadId("thread-stop")), false);
}),
);
});
const scopedFailureRuntimeFactory = makeScopedRuntimeFactory({ failConstruction: true });
const scopedFailureLayer = it.layer(
makeCodexAdapterLive({ makeRuntime: scopedFailureRuntimeFactory.factory }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
);
scopedFailureLayer("CodexAdapterLive scoped startup failure", (it) => {
it.effect("closes the externally owned session scope when startSession fails", () =>
Effect.gen(function* () {
scopedFailureRuntimeFactory.releasedThreadIds.length = 0;
const adapter = yield* CodexAdapter;
const result = yield* adapter
.startSession({
provider: "codex",
threadId: asThreadId("thread-fail"),
runtimeMode: "full-access",
})
.pipe(Effect.result);
assert.equal(result._tag, "Failure");
assert.equal(result.failure._tag, "ProviderAdapterProcessError");
assert.deepStrictEqual(scopedFailureRuntimeFactory.releasedThreadIds, [
asThreadId("thread-fail"),
]);
assert.equal(yield* adapter.hasSession(asThreadId("thread-fail")), false);
}),
);
});
it.effect("flushes managed native logs when the adapter layer shuts down", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-codex-adapter-native-log-"));
const basePath = path.join(tempDir, "provider-native.ndjson");
const runtimeFactory = makeRuntimeFactory();
const scope = yield* Scope.make("sequential");
let scopeClosed = false;
try {
const layer = makeCodexAdapterLive({
makeRuntime: runtimeFactory.factory,
nativeEventLogPath: basePath,
}).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
);
const context = yield* Layer.buildWithScope(layer, scope);
const adapter = yield* Effect.service(CodexAdapter).pipe(Effect.provide(context));
yield* adapter.startSession({
provider: "codex",
threadId: asThreadId("thread-logger"),
runtimeMode: "full-access",
});
const runtime = runtimeFactory.lastRuntime;
assert.ok(runtime);
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
yield* runtime.emit({
id: asEventId("evt-native-log"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-logger"),
createdAt: new Date().toISOString(),
method: "process/stderr",
message: "native flush test",
} satisfies ProviderEvent);
yield* Fiber.join(firstEventFiber);
yield* Scope.close(scope, Exit.void);
scopeClosed = true;
const threadLogPath = path.join(tempDir, "thread-logger.log");
assert.equal(fs.existsSync(threadLogPath), true);
const contents = fs.readFileSync(threadLogPath, "utf8");
assert.match(contents, /NTIVE: .*"message":"native flush test"/);
} finally {
if (!scopeClosed) {
yield* Scope.close(scope, Exit.void);
}
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,275 @@
import assert from "node:assert/strict";
import { Effect, Schema } from "effect";
import { describe, it } from "vitest";
import { ThreadId } from "@t3tools/contracts";
import * as CodexErrors from "effect-codex-app-server/errors";
import * as CodexRpc from "effect-codex-app-server/rpc";
import {
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
} from "../CodexDeveloperInstructions.ts";
import {
buildTurnStartParams,
isRecoverableThreadResumeError,
openCodexThread,
} from "./CodexSessionRuntime.ts";
function makeThreadOpenResponse(
threadId: string,
): CodexRpc.ClientRequestResponsesByMethod["thread/start"] {
return {
cwd: "/tmp/project",
model: "gpt-5.3-codex",
modelProvider: "openai",
approvalPolicy: "never",
approvalsReviewer: "user",
sandbox: { type: "danger-full-access" },
thread: {
id: threadId,
createdAt: "2026-04-18T00:00:00.000Z",
source: { session: "cli" },
turns: [],
status: {
state: "idle",
activeFlags: [],
},
},
} as unknown as CodexRpc.ClientRequestResponsesByMethod["thread/start"];
}
describe("buildTurnStartParams", () => {
it("includes plan collaboration mode when requested", () => {
const params = Effect.runSync(
buildTurnStartParams({
threadId: "provider-thread-1",
runtimeMode: "full-access",
prompt: "Make a plan",
model: "gpt-5.3-codex",
effort: "medium",
interactionMode: "plan",
}),
);
assert.deepStrictEqual(params, {
threadId: "provider-thread-1",
approvalPolicy: "never",
sandboxPolicy: {
type: "dangerFullAccess",
},
input: [
{
type: "text",
text: "Make a plan",
},
],
model: "gpt-5.3-codex",
effort: "medium",
collaborationMode: {
mode: "plan",
settings: {
model: "gpt-5.3-codex",
reasoning_effort: "medium",
developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
},
},
});
});
it("includes default collaboration mode and image attachments", () => {
const params = Effect.runSync(
buildTurnStartParams({
threadId: "provider-thread-1",
runtimeMode: "auto-accept-edits",
prompt: "Implement it",
model: "gpt-5.3-codex",
interactionMode: "default",
attachments: [
{
type: "image",
url: "data:image/png;base64,abc",
},
],
}),
);
assert.deepStrictEqual(params, {
threadId: "provider-thread-1",
approvalPolicy: "on-request",
sandboxPolicy: {
type: "workspaceWrite",
},
input: [
{
type: "text",
text: "Implement it",
},
{
type: "image",
url: "data:image/png;base64,abc",
},
],
model: "gpt-5.3-codex",
collaborationMode: {
mode: "default",
settings: {
model: "gpt-5.3-codex",
reasoning_effort: "medium",
developer_instructions: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
},
},
});
});
it("omits collaboration mode when interaction mode is absent", () => {
const params = Effect.runSync(
buildTurnStartParams({
threadId: "provider-thread-1",
runtimeMode: "approval-required",
prompt: "Review",
}),
);
assert.deepStrictEqual(params, {
threadId: "provider-thread-1",
approvalPolicy: "untrusted",
sandboxPolicy: {
type: "readOnly",
},
input: [
{
type: "text",
text: "Review",
},
],
});
});
});
describe("isRecoverableThreadResumeError", () => {
it("matches missing thread errors", () => {
assert.equal(
isRecoverableThreadResumeError(
new CodexErrors.CodexAppServerRequestError({
code: -32603,
errorMessage: "Thread does not exist",
}),
),
true,
);
});
it("ignores non-recoverable resume errors", () => {
assert.equal(
isRecoverableThreadResumeError(
new CodexErrors.CodexAppServerRequestError({
code: -32603,
errorMessage: "Permission denied",
}),
),
false,
);
});
it("ignores unrelated missing-resource errors that do not mention threads", () => {
assert.equal(
isRecoverableThreadResumeError(
new CodexErrors.CodexAppServerRequestError({
code: -32603,
errorMessage: "Config file not found",
}),
),
false,
);
assert.equal(
isRecoverableThreadResumeError(
new CodexErrors.CodexAppServerRequestError({
code: -32603,
errorMessage: "Model does not exist",
}),
),
false,
);
});
});
describe("openCodexThread", () => {
it("falls back to thread/start when resume fails recoverably", async () => {
const calls: Array<{ method: "thread/start" | "thread/resume"; payload: unknown }> = [];
const started = makeThreadOpenResponse("fresh-thread");
const client = {
request: <M extends "thread/start" | "thread/resume">(
method: M,
payload: CodexRpc.ClientRequestParamsByMethod[M],
) => {
calls.push({ method, payload });
if (method === "thread/resume") {
return Effect.fail(
new CodexErrors.CodexAppServerRequestError({
code: -32603,
errorMessage: "thread not found",
}),
);
}
return Effect.succeed(started as CodexRpc.ClientRequestResponsesByMethod[M]);
},
};
const opened = await Effect.runPromise(
openCodexThread({
client,
threadId: ThreadId.make("thread-1"),
runtimeMode: "full-access",
cwd: "/tmp/project",
requestedModel: "gpt-5.3-codex",
serviceTier: undefined,
resumeThreadId: "stale-thread",
}),
);
assert.equal(opened.thread.id, "fresh-thread");
assert.deepStrictEqual(
calls.map((call) => call.method),
["thread/resume", "thread/start"],
);
});
it("propagates non-recoverable resume failures", async () => {
const client = {
request: <M extends "thread/start" | "thread/resume">(
method: M,
_payload: CodexRpc.ClientRequestParamsByMethod[M],
) => {
if (method === "thread/resume") {
return Effect.fail(
new CodexErrors.CodexAppServerRequestError({
code: -32603,
errorMessage: "timed out waiting for server",
}),
);
}
return Effect.succeed(
makeThreadOpenResponse("fresh-thread") as CodexRpc.ClientRequestResponsesByMethod[M],
);
},
};
await assert.rejects(
Effect.runPromise(
openCodexThread({
client,
threadId: ThreadId.make("thread-1"),
runtimeMode: "full-access",
cwd: "/tmp/project",
requestedModel: "gpt-5.3-codex",
serviceTier: undefined,
resumeThreadId: "stale-thread",
}),
),
(error: unknown) =>
Schema.is(CodexErrors.CodexAppServerRequestError)(error) &&
error.errorMessage === "timed out waiting for server",
);
});
});
File diff suppressed because it is too large. Load diff
@@ -1,18 +1,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, it, assert } from "@effect/vitest";
import {
Effect,
Exit,
FileSystem,
Layer,
Path,
PubSub,
Ref,
Schema,
Scope,
Sink,
Stream,
} from "effect";
import { Effect, Exit, Layer, PubSub, Ref, Schema, Scope, Sink, Stream } from "effect";
import * as CodexErrors from "effect-codex-app-server/errors";
import {
DEFAULT_SERVER_SETTINGS,
ServerSettings,
@@ -23,19 +12,13 @@ import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import { deepMerge } from "@t3tools/shared/Struct";
import {
checkCodexProviderStatus,
hasCustomModelProvider,
parseAuthStatusFromOutput,
readCodexConfigModelProvider,
} from "./CodexProvider.ts";
import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts";
import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider.ts";
import {
haveProvidersChanged,
mergeProviderSnapshot,
ProviderRegistryLive,
} from "./ProviderRegistry.ts";
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";
import { ProviderRegistry } from "../Services/ProviderRegistry.ts";
@@ -45,19 +28,6 @@ process.env.T3CODE_CURSOR_ENABLED = "1";
// ── Test helpers ────────────────────────────────────────────────────
const encoder = new TextEncoder();
const fakeOpenCodeSnapshot: ServerProvider = {
provider: "opencode",
status: "warning",
enabled: true,
installed: false,
auth: { status: "unknown" },
checkedAt: "2026-03-25T00:00:00.000Z",
version: null,
models: [],
slashCommands: [],
skills: [],
message: "OpenCode test stub",
};
function mockHandle(result: { stdout: string; stderr: string; code: number }) {
return ChildProcessSpawner.makeHandle({
@@ -118,6 +88,43 @@ function failingSpawnerLayer(description: string) {
);
}
const codexModelCapabilities = {
reasoningEffortLevels: [
{ value: "high", label: "High", isDefault: true },
{ value: "low", label: "Low" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
} satisfies NonNullable<ServerProvider["models"][number]["capabilities"]>;
function makeCodexProbeSnapshot(
input: Partial<CodexAppServerProviderSnapshot> = {},
): CodexAppServerProviderSnapshot {
return {
version: "1.0.0",
account: {
account: {
type: "chatgpt",
email: "[email protected]",
planType: "pro",
},
requiresOpenaiAuth: false,
},
models: [
{
slug: "gpt-live-codex",
name: "GPT Live Codex",
isCustom: false,
capabilities: codexModelCapabilities,
},
],
skills: [],
...input,
};
}
function makeMutableServerSettingsService(
initial: ContractServerSettings = DEFAULT_SERVER_SETTINGS,
) {
@@ -144,126 +151,43 @@ function makeMutableServerSettingsService(
});
}
/**
* Create a temporary CODEX_HOME scoped to the current Effect test.
* Cleanup is registered in the test scope rather than via Vitest hooks.
*/
function withTempCodexHome(configContent?: string) {
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tmpDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-test-codex-" });
yield* Effect.acquireRelease(
Effect.sync(() => {
const originalCodexHome = process.env.CODEX_HOME;
process.env.CODEX_HOME = tmpDir;
return originalCodexHome;
}),
(originalCodexHome) =>
Effect.sync(() => {
if (originalCodexHome !== undefined) {
process.env.CODEX_HOME = originalCodexHome;
} else {
delete process.env.CODEX_HOME;
}
}),
);
if (configContent !== undefined) {
yield* fileSystem.writeFileString(path.join(tmpDir, "config.toml"), configContent);
}
return { tmpDir } as const;
});
}
it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
"ProviderRegistry",
(it) => {
// ── checkCodexProviderStatus tests ────────────────────────────────
//
// These tests control CODEX_HOME to ensure the custom-provider detection
// in hasCustomModelProvider() does not interfere with the auth-probe
// path being tested.
describe("checkCodexProviderStatus", () => {
it.effect("returns ready when codex is installed and authenticated", () =>
it.effect("uses the app-server account and model list for provider status", () =>
Effect.gen(function* () {
// Point CODEX_HOME at an empty tmp dir (no config.toml) so the
// default code path (OpenAI provider, auth probe runs) is exercised.
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus();
const status = yield* checkCodexProviderStatus(() =>
Effect.succeed(
makeCodexProbeSnapshot({
skills: [
{
name: "github:gh-fix-ci",
path: "/Users/test/.codex/skills/gh-fix-ci/SKILL.md",
enabled: true,
displayName: "CI Debug",
shortDescription: "Debug failing GitHub Actions checks",
},
],
}),
),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.version, "1.0.0");
assert.strictEqual(status.auth.status, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns the codex plan type in auth and keeps spark for supported plans", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus(() =>
Effect.succeed({
type: "chatgpt" as const,
planType: "pro" as const,
sparkEnabled: true,
}),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.auth.type, "pro");
assert.strictEqual(status.auth.type, "chatgpt");
assert.strictEqual(status.auth.label, "ChatGPT Pro Subscription");
assert.deepStrictEqual(
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
true,
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("includes probed codex skills in the provider snapshot", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus(
() =>
Effect.succeed({
type: "chatgpt" as const,
planType: "pro" as const,
sparkEnabled: true,
}),
() =>
Effect.succeed([
{
name: "github:gh-fix-ci",
path: "/Users/test/.codex/skills/gh-fix-ci/SKILL.md",
enabled: true,
displayName: "CI Debug",
shortDescription: "Debug failing GitHub Actions checks",
},
]),
);
assert.deepStrictEqual(status.models, [
{
slug: "gpt-live-codex",
name: "GPT Live Codex",
isCustom: false,
capabilities: codexModelCapabilities,
},
]);
assert.deepStrictEqual(status.skills, [
{
name: "github:gh-fix-ci",
@@ -273,172 +197,81 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
shortDescription: "Debug failing GitHub Actions checks",
},
]);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
}),
);
it.effect("hides spark from codex models for unsupported chatgpt plans", () =>
it.effect("returns unauthenticated when app-server requires OpenAI auth", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus(() =>
Effect.succeed({
type: "chatgpt" as const,
planType: "plus" as const,
sparkEnabled: false,
}),
Effect.succeed(
makeCodexProbeSnapshot({
account: {
account: null,
requiresOpenaiAuth: true,
},
}),
),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.auth.type, "plus");
assert.strictEqual(status.auth.label, "ChatGPT Plus Subscription");
assert.deepStrictEqual(
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
false,
assert.strictEqual(status.status, "error");
assert.strictEqual(status.auth.status, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
}),
);
it.effect("hides spark from codex models for non-pro chatgpt subscriptions", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus(() =>
Effect.succeed({
type: "chatgpt" as const,
planType: "team" as const,
sparkEnabled: false,
}),
);
it.effect(
"returns ready with unknown auth when app-server does not require OpenAI auth",
() =>
Effect.gen(function* () {
const status = yield* checkCodexProviderStatus(() =>
Effect.succeed(
makeCodexProbeSnapshot({
account: {
account: null,
requiresOpenaiAuth: false,
},
}),
),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.auth.type, "team");
assert.strictEqual(status.auth.label, "ChatGPT Team Subscription");
assert.deepStrictEqual(
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
false,
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "unknown");
}),
);
it.effect("returns an api key label for codex api key auth", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus(() =>
Effect.succeed({
type: "apiKey" as const,
planType: null,
sparkEnabled: false,
}),
Effect.succeed(
makeCodexProbeSnapshot({
account: {
account: { type: "apiKey" },
requiresOpenaiAuth: false,
},
}),
),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "authenticated");
assert.strictEqual(status.auth.type, "apiKey");
assert.strictEqual(status.auth.label, "OpenAI API Key");
assert.deepStrictEqual(
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
false,
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect.skipIf(process.platform === "win32")(
"inherits PATH when launching the codex probe with a CODEX_HOME override",
() =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-test-codex-bin-",
});
const codexPath = path.join(binDir, "codex");
yield* fileSystem.writeFileString(
codexPath,
[
"#!/bin/sh",
'if [ "$1" = "--version" ]; then',
' echo "codex-cli 1.0.0"',
" exit 0",
"fi",
'if [ "$1" = "login" ] && [ "$2" = "status" ]; then',
' echo "Logged in using ChatGPT"',
" exit 0",
"fi",
'echo "unexpected args: $*" >&2',
"exit 1",
"",
].join("\n"),
);
yield* fileSystem.chmod(codexPath, 0o755);
const customCodexHome = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-test-codex-home-",
});
const previousPath = process.env.PATH;
process.env.PATH = binDir;
try {
const serverSettingsLayer = ServerSettingsService.layerTest({
providers: {
codex: {
homePath: customCodexHome,
},
},
});
const status = yield* checkCodexProviderStatus().pipe(
Effect.provide(serverSettingsLayer),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.auth.status, "authenticated");
} finally {
process.env.PATH = previousPath;
}
}),
}),
);
it.effect("returns unavailable when codex is missing", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus();
const status = yield* checkCodexProviderStatus(() =>
Effect.fail(
new CodexErrors.CodexAppServerSpawnError({
command: "codex app-server",
cause: new Error("spawn codex ENOENT"),
}),
),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, false);
@@ -447,107 +280,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
status.message,
"Codex CLI (`codex`) is not installed or not on PATH.",
);
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
);
it.effect("returns unavailable when codex is below the minimum supported version", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus();
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(
status.message,
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 0.36.0\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unauthenticated when auth probe reports login required", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus();
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.auth.status, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unauthenticated when login status output includes 'not logged in'", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus();
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.auth.status, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status")
return { stdout: "Not logged in\n", stderr: "", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns warning when login status command is unsupported", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus();
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(
status.message,
"Codex CLI authentication status command is unavailable in this Codex version.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
}),
);
});
@@ -677,7 +410,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
Schema.decodeSync(ServerSettings)(
deepMerge(DEFAULT_SERVER_SETTINGS, {
providers: {
claudeAgent: { enabled: false },
codex: { enabled: false },
cursor: { enabled: false },
},
}),
@@ -697,14 +430,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
spawnCount += 1;
const joined = args.join(" ");
if (joined === "--version") {
if (command === "codex") {
return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
}
return { stdout: "claude 1.0.0\n", stderr: "", code: 0 };
}
if (joined === "login status") {
return { stdout: "Logged in\n", stderr: "", code: 0 };
}
if (joined === "auth status") {
return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 };
}
@@ -722,8 +449,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
const refreshed = yield* Effect.gen(function* () {
for (let remainingAttempts = 50; remainingAttempts > 0; remainingAttempts -= 1) {
const providers = yield* registry.getProviders;
const codexProvider = providers.find((provider) => provider.provider === "codex");
if (codexProvider?.status === "ready") {
const claudeProvider = providers.find(
(provider) => provider.provider === "claudeAgent",
);
if (claudeProvider?.status === "ready") {
return providers;
}
yield* Effect.sleep("10 millis");
@@ -731,99 +460,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
return yield* registry.getProviders;
});
assert.strictEqual(
refreshed.find((provider) => provider.provider === "codex")?.status,
refreshed.find((provider) => provider.provider === "claudeAgent")?.status,
"ready",
);
}).pipe(Effect.provide(runtimeServices));
}),
);
it.effect("reruns codex health when codex provider settings change", () =>
Effect.gen(function* () {
const serverSettings = yield* makeMutableServerSettingsService();
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const providerRegistryLayer = ProviderRegistryLive.pipe(
Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-provider-registry-",
}),
),
Layer.provideMerge(
Layer.succeed(OpenCodeProvider, {
getSnapshot: Effect.succeed(fakeOpenCodeSnapshot),
refresh: Effect.succeed(fakeOpenCodeSnapshot),
streamChanges: Stream.empty,
}),
),
Layer.provideMerge(
mockCommandSpawnerLayer((command, args) => {
const joined = args.join(" ");
if (joined === "--version") {
if (command === "codex") {
return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
}
return { stdout: "", stderr: "spawn ENOENT", code: 1 };
}
if (joined === "about --format json") {
return {
stdout: JSON.stringify({
cliVersion: "2026.04.09-f2b0fcd",
userEmail: null,
}),
stderr: "",
code: 0,
};
}
if (joined === "about") {
return { stdout: "", stderr: "spawn ENOENT", code: 1 };
}
if (joined === "login status") {
return { stdout: "Logged in\n", stderr: "", code: 0 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
);
const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
Scope.provide(scope),
);
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry;
const refreshed = yield* registry.refresh("codex");
assert.strictEqual(
refreshed.find((status) => status.provider === "codex")?.status,
"ready",
);
yield* serverSettings.updateSettings({
providers: {
codex: {
binaryPath: "/custom/codex",
},
},
});
for (let attempt = 0; attempt < 20; attempt += 1) {
const updated = yield* registry.getProviders;
if (updated.find((status) => status.provider === "codex")?.status === "error") {
return;
}
yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 0)));
}
const updated = yield* registry.getProviders;
assert.strictEqual(
updated.find((status) => status.provider === "codex")?.status,
"error",
);
}).pipe(Effect.provide(runtimeServices));
}),
);
it.effect(
"keeps cursor disabled and skips probing when the provider setting is disabled",
() =>
@@ -832,6 +475,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
Schema.decodeSync(ServerSettings)(
deepMerge(DEFAULT_SERVER_SETTINGS, {
providers: {
codex: {
enabled: false,
},
cursor: {
enabled: false,
},
@@ -858,9 +504,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
if (joined === "--version") {
return { stdout: `${command} 1.0.0\n`, stderr: "", code: 0 };
}
if (joined === "login status") {
return { stdout: "Logged in\n", stderr: "", code: 0 };
}
if (joined === "auth status") {
return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 };
}
@@ -919,238 +562,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
);
});
// ── Custom model provider: checkCodexProviderStatus integration ───
describe("checkCodexProviderStatus with custom model provider", () => {
it.effect(
"skips auth probe and returns ready when a custom model provider is configured",
() =>
Effect.gen(function* () {
yield* withTempCodexHome(
[
'model_provider = "portkey"',
"",
"[model_providers.portkey]",
'base_url = "https://api.portkey.ai/v1"',
'env_key = "PORTKEY_API_KEY"',
].join("\n"),
);
const status = yield* checkCodexProviderStatus();
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.auth.status, "unknown");
assert.strictEqual(
status.message,
"Using a custom Codex model provider; OpenAI login check skipped.",
);
}).pipe(
Effect.provide(
// The spawner only handles --version; if the test attempts
// "login status" the throw proves the auth probe was NOT skipped.
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
throw new Error(`Auth probe should have been skipped but got args: ${joined}`);
}),
),
),
);
it.effect("still reports error when codex CLI is missing even with custom provider", () =>
Effect.gen(function* () {
yield* withTempCodexHome(
[
'model_provider = "portkey"',
"",
"[model_providers.portkey]",
'base_url = "https://api.portkey.ai/v1"',
'env_key = "PORTKEY_API_KEY"',
].join("\n"),
);
const status = yield* checkCodexProviderStatus();
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, false);
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
);
});
describe("checkCodexProviderStatus with openai model provider", () => {
it.effect("still runs auth probe when model_provider is openai", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "openai"\n');
const status = yield* checkCodexProviderStatus();
// The auth probe runs and sees "not logged in" → error
assert.strictEqual(status.status, "error");
assert.strictEqual(status.auth.status, "unauthenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status")
return { stdout: "Not logged in\n", stderr: "", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
});
// ── parseAuthStatusFromOutput pure tests ──────────────────────────
describe("parseAuthStatusFromOutput", () => {
it("exit code 0 with no auth markers is ready", () => {
const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.auth.status, "authenticated");
});
it("JSON with authenticated=false is unauthenticated", () => {
const parsed = parseAuthStatusFromOutput({
stdout: '[{"authenticated":false}]\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.auth.status, "unauthenticated");
});
it("JSON without auth marker is warning", () => {
const parsed = parseAuthStatusFromOutput({
stdout: '[{"ok":true}]\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.auth.status, "unknown");
});
});
// ── readCodexConfigModelProvider tests ─────────────────────────────
describe("readCodexConfigModelProvider", () => {
it.effect("returns undefined when config file does not exist", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
assert.strictEqual(yield* readCodexConfigModelProvider(), undefined);
}),
);
it.effect("returns undefined when config has no model_provider key", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model = "gpt-5-codex"\n');
assert.strictEqual(yield* readCodexConfigModelProvider(), undefined);
}),
);
it.effect("returns the provider when model_provider is set at top level", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model = "gpt-5-codex"\nmodel_provider = "portkey"\n');
assert.strictEqual(yield* readCodexConfigModelProvider(), "portkey");
}),
);
it.effect("returns openai when model_provider is openai", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "openai"\n');
assert.strictEqual(yield* readCodexConfigModelProvider(), "openai");
}),
);
it.effect("ignores model_provider inside section headers", () =>
Effect.gen(function* () {
yield* withTempCodexHome(
[
'model = "gpt-5-codex"',
"",
"[model_providers.portkey]",
'base_url = "https://api.portkey.ai/v1"',
'model_provider = "should-be-ignored"',
"",
].join("\n"),
);
assert.strictEqual(yield* readCodexConfigModelProvider(), undefined);
}),
);
it.effect("handles comments and whitespace", () =>
Effect.gen(function* () {
yield* withTempCodexHome(
[
"# This is a comment",
"",
' model_provider = "azure" ',
"",
"[profiles.deep-review]",
'model = "gpt-5-pro"',
].join("\n"),
);
assert.strictEqual(yield* readCodexConfigModelProvider(), "azure");
}),
);
it.effect("handles single-quoted values in TOML", () =>
Effect.gen(function* () {
yield* withTempCodexHome("model_provider = 'mistral'\n");
assert.strictEqual(yield* readCodexConfigModelProvider(), "mistral");
}),
);
});
// ── hasCustomModelProvider tests ───────────────────────────────────
describe("hasCustomModelProvider", () => {
it.effect("returns false when no config file exists", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
assert.strictEqual(yield* hasCustomModelProvider, false);
}),
);
it.effect("returns false when model_provider is not set", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model = "gpt-5-codex"\n');
assert.strictEqual(yield* hasCustomModelProvider, false);
}),
);
it.effect("returns false when model_provider is openai", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "openai"\n');
assert.strictEqual(yield* hasCustomModelProvider, false);
}),
);
it.effect("returns true when model_provider is portkey", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "portkey"\n');
assert.strictEqual(yield* hasCustomModelProvider, true);
}),
);
it.effect("returns true when model_provider is azure", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "azure"\n');
assert.strictEqual(yield* hasCustomModelProvider, true);
}),
);
it.effect("returns true when model_provider is ollama", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "ollama"\n');
assert.strictEqual(yield* hasCustomModelProvider, true);
}),
);
it.effect("returns true when model_provider is a custom proxy", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "my-company-proxy"\n');
assert.strictEqual(yield* hasCustomModelProvider, true);
}),
);
});
// ── checkClaudeProviderStatus tests ──────────────────────────
describe("checkClaudeProviderStatus", () => {
-123
View File
@@ -1,123 +0,0 @@
import type { ServerProviderModel } from "@t3tools/contracts";
export type CodexPlanType =
| "free"
| "go"
| "plus"
| "pro"
| "team"
| "business"
| "enterprise"
| "edu"
| "unknown";
export interface CodexAccountSnapshot {
readonly type: "apiKey" | "chatgpt" | "unknown";
readonly planType: CodexPlanType | null;
readonly sparkEnabled: boolean;
}
export const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
export const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
const CODEX_SPARK_ENABLED_PLAN_TYPES = new Set<CodexPlanType>(["pro"]);
function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
return value as Record<string, unknown>;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
const record = asObject(response);
const account = asObject(record?.account) ?? record;
const accountType = asString(account?.type);
if (accountType === "apiKey") {
return {
type: "apiKey",
planType: null,
sparkEnabled: false,
};
}
if (accountType === "chatgpt") {
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
return {
type: "chatgpt",
planType,
sparkEnabled: CODEX_SPARK_ENABLED_PLAN_TYPES.has(planType),
};
}
return {
type: "unknown",
planType: null,
sparkEnabled: false,
};
}
export function codexAuthSubType(account: CodexAccountSnapshot | undefined): string | undefined {
if (account?.type === "apiKey") {
return "apiKey";
}
if (account?.type !== "chatgpt") {
return undefined;
}
return account.planType && account.planType !== "unknown" ? account.planType : "chatgpt";
}
export function codexAuthSubLabel(account: CodexAccountSnapshot | undefined): string | undefined {
switch (codexAuthSubType(account)) {
case "apiKey":
return "OpenAI API Key";
case "chatgpt":
return "ChatGPT Subscription";
case "free":
return "ChatGPT Free Subscription";
case "go":
return "ChatGPT Go Subscription";
case "plus":
return "ChatGPT Plus Subscription";
case "pro":
return "ChatGPT Pro Subscription";
case "team":
return "ChatGPT Team Subscription";
case "business":
return "ChatGPT Business Subscription";
case "enterprise":
return "ChatGPT Enterprise Subscription";
case "edu":
return "ChatGPT Edu Subscription";
default:
return undefined;
}
}
export function adjustCodexModelsForAccount(
baseModels: ReadonlyArray<ServerProviderModel>,
account: CodexAccountSnapshot | undefined,
): ReadonlyArray<ServerProviderModel> {
if (account?.sparkEnabled !== false) {
return baseModels;
}
return baseModels.filter((model) => model.isCustom || model.slug !== CODEX_SPARK_MODEL);
}
export function resolveCodexModelForAccount(
model: string | undefined,
account: CodexAccountSnapshot,
): string | undefined {
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
return model;
}
return CODEX_DEFAULT_MODEL;
}
-242
View File
@@ -1,242 +0,0 @@
import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
import readline from "node:readline";
import type { ServerProviderSkill } from "@t3tools/contracts";
import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount.ts";
import { expandHomePath } from "../pathExpansion.ts";
interface JsonRpcProbeResponse {
readonly id?: unknown;
readonly result?: unknown;
readonly error?: {
readonly message?: unknown;
};
}
export interface CodexDiscoverySnapshot {
readonly account: CodexAccountSnapshot;
readonly skills: ReadonlyArray<ServerProviderSkill>;
}
function readErrorMessage(response: JsonRpcProbeResponse): string | undefined {
return typeof response.error?.message === "string" ? response.error.message : undefined;
}
function readObject(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
}
function readArray(value: unknown): ReadonlyArray<unknown> | undefined {
return Array.isArray(value) ? value : undefined;
}
function readString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function nonEmptyTrimmed(value: unknown): string | undefined {
const candidate = readString(value)?.trim();
return candidate ? candidate : undefined;
}
function parseCodexSkillsResult(result: unknown, cwd: string): ReadonlyArray<ServerProviderSkill> {
const resultRecord = readObject(result);
const dataBuckets = readArray(resultRecord?.data) ?? [];
const matchingBucket = dataBuckets.find(
(value) => nonEmptyTrimmed(readObject(value)?.cwd) === cwd,
);
const rawSkills =
readArray(readObject(matchingBucket)?.skills) ?? readArray(resultRecord?.skills) ?? [];
return rawSkills.flatMap((value) => {
const skill = readObject(value);
const display = readObject(skill?.interface);
const name = nonEmptyTrimmed(skill?.name);
const path = nonEmptyTrimmed(skill?.path);
if (!name || !path) {
return [];
}
return [
{
name,
path,
enabled: skill?.enabled !== false,
...(nonEmptyTrimmed(skill?.description)
? { description: nonEmptyTrimmed(skill?.description) }
: {}),
...(nonEmptyTrimmed(skill?.scope) ? { scope: nonEmptyTrimmed(skill?.scope) } : {}),
...(nonEmptyTrimmed(display?.displayName)
? { displayName: nonEmptyTrimmed(display?.displayName) }
: {}),
...(nonEmptyTrimmed(skill?.shortDescription) || nonEmptyTrimmed(display?.shortDescription)
? {
shortDescription:
nonEmptyTrimmed(skill?.shortDescription) ??
nonEmptyTrimmed(display?.shortDescription),
}
: {}),
} satisfies ServerProviderSkill,
];
});
}
export function buildCodexInitializeParams() {
return {
clientInfo: {
name: "t3code_desktop",
title: "T3 Code Desktop",
version: "0.1.0",
},
capabilities: {
experimentalApi: true,
},
} as const;
}
export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): void {
if (process.platform === "win32" && child.pid !== undefined) {
try {
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
return;
} catch {
// Fall through to direct kill when taskkill is unavailable.
}
}
child.kill();
}
export async function probeCodexDiscovery(input: {
readonly binaryPath: string;
readonly homePath?: string;
readonly cwd: string;
readonly signal?: AbortSignal;
}): Promise<CodexDiscoverySnapshot> {
return await new Promise((resolve, reject) => {
const child = spawn(input.binaryPath, ["app-server"], {
env: {
...process.env,
...(input.homePath ? { CODEX_HOME: expandHomePath(input.homePath) } : {}),
},
stdio: ["pipe", "pipe", "pipe"],
shell: process.platform === "win32",
});
const output = readline.createInterface({ input: child.stdout });
let completed = false;
let account: CodexAccountSnapshot | undefined;
let skills: ReadonlyArray<ServerProviderSkill> | undefined;
const cleanup = () => {
output.removeAllListeners();
output.close();
child.removeAllListeners();
if (!child.killed) {
killCodexChildProcess(child);
}
};
const finish = (callback: () => void) => {
if (completed) return;
completed = true;
cleanup();
callback();
};
const fail = (error: unknown) =>
finish(() =>
reject(
error instanceof Error
? error
: new Error(`Codex discovery probe failed: ${String(error)}.`),
),
);
const maybeResolve = () => {
if (account && skills !== undefined) {
const resolvedAccount = account;
const resolvedSkills = skills;
finish(() => resolve({ account: resolvedAccount, skills: resolvedSkills }));
}
};
if (input.signal?.aborted) {
fail(new Error("Codex discovery probe aborted."));
return;
}
input.signal?.addEventListener("abort", () =>
fail(new Error("Codex discovery probe aborted.")),
);
const writeMessage = (message: unknown) => {
if (!child.stdin.writable) {
fail(new Error("Cannot write to codex app-server stdin."));
return;
}
child.stdin.write(`${JSON.stringify(message)}\n`);
};
output.on("line", (line) => {
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
fail(new Error("Received invalid JSON from codex app-server during discovery probe."));
return;
}
if (!parsed || typeof parsed !== "object") {
return;
}
const response = parsed as JsonRpcProbeResponse;
if (response.id === 1) {
const errorMessage = readErrorMessage(response);
if (errorMessage) {
fail(new Error(`initialize failed: ${errorMessage}`));
return;
}
writeMessage({ method: "initialized" });
writeMessage({ id: 2, method: "skills/list", params: { cwds: [input.cwd] } });
writeMessage({ id: 3, method: "account/read", params: {} });
return;
}
if (response.id === 2) {
const errorMessage = readErrorMessage(response);
skills = errorMessage ? [] : parseCodexSkillsResult(response.result, input.cwd);
maybeResolve();
return;
}
if (response.id === 3) {
const errorMessage = readErrorMessage(response);
if (errorMessage) {
fail(new Error(`account/read failed: ${errorMessage}`));
return;
}
account = readCodexAccountSnapshot(response.result);
maybeResolve();
}
});
child.once("error", fail);
child.once("exit", (code, signal) => {
if (completed) return;
fail(
new Error(
`codex app-server exited before probe completed (code=${code ?? "null"}, signal=${signal ?? "null"}).`,
),
);
});
writeMessage({
id: 1,
method: "initialize",
params: buildCodexInitializeParams(),
});
});
}
@@ -1,25 +0,0 @@
import { compareCliVersions, normalizeCliVersion } from "./cliVersion.ts";
const CODEX_VERSION_PATTERN = /\bv?(\d+\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?)\b/;
export const MINIMUM_CODEX_CLI_VERSION = "0.37.0";
export const compareCodexCliVersions = compareCliVersions;
export function parseCodexCliVersion(output: string): string | null {
const match = CODEX_VERSION_PATTERN.exec(output);
if (!match?.[1]) {
return null;
}
return normalizeCliVersion(match[1]);
}
export function isCodexCliVersionSupported(version: string): boolean {
return compareCodexCliVersions(version, MINIMUM_CODEX_CLI_VERSION) >= 0;
}
export function formatCodexCliUpgradeMessage(version: string | null): string {
const versionLabel = version ? `v${version}` : "the installed version";
return `Codex CLI ${versionLabel} is too old for T3 Code. Upgrade to v${MINIMUM_CODEX_CLI_VERSION} or newer and restart T3 Code.`;
}
-1
View File
@@ -11,7 +11,6 @@ import {
deriveCompletionDividerBeforeEntryId,
deriveActiveWorkStartedAt,
deriveActivePlanState,
PROVIDER_OPTIONS,
derivePendingApprovals,
derivePendingUserInputs,
deriveTimelineEntries,
+18
View File
@@ -67,6 +67,7 @@
"@types/bun": "catalog:",
"@types/node": "catalog:",
"effect-acp": "workspace:*",
"effect-codex-app-server": "workspace:*",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
@@ -166,6 +167,21 @@
"vitest": "catalog:",
},
},
"packages/effect-codex-app-server": {
"name": "effect-codex-app-server",
"dependencies": {
"effect": "catalog:",
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/openapi-generator": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/vitest": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
},
},
"packages/shared": {
"name": "@t3tools/shared",
"version": "0.0.0-alpha.1",
@@ -1083,6 +1099,8 @@
"effect-acp": ["effect-acp@workspace:packages/effect-acp"],
"effect-codex-app-server": ["effect-codex-app-server@workspace:packages/effect-codex-app-server"],
"electron": ["[email protected]", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-ett8W+yOFGDuM0vhJMamYSkrbV3LoaffzJd9GfjI96zRAxyrNqUSKqBpf/WGbQCweDxX2pkUCUfrv4wwKpsFZA=="],
"electron-to-chromium": ["[email protected]", "", {}, "sha512-QBMrTWEf00GXZmJyx2lbYD45jpI3TUFnNIzJ5BBc8piGUDwMPa1GV6HJWTZVvY/eiN3fSopl7NRbgGp9sZ9LTA=="],
+5 -2
View File
@@ -9,7 +9,6 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import * as AcpError from "../errors.ts";
const encoder = new TextEncoder();
const decoder = new TextDecoder();
export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =>
Stdio.make({
@@ -25,6 +24,7 @@ export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =
export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {
const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();
const output = yield* Queue.unbounded<string>();
const decoder = new TextDecoder();
return {
stdio: Stdio.make({
@@ -32,7 +32,10 @@ export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {
stdin: Stream.fromQueue(input),
stdout: () =>
Sink.forEach((chunk: string | Uint8Array) =>
Queue.offer(output, typeof chunk === "string" ? chunk : decoder.decode(chunk)),
Queue.offer(
output,
typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true }),
),
),
stderr: () => Sink.drain,
}),
@@ -0,0 +1,48 @@
{
"name": "effect-codex-app-server",
"private": true,
"type": "module",
"exports": {
"./client": {
"types": "./src/client.ts",
"import": "./src/client.ts"
},
"./schema": {
"types": "./src/schema.ts",
"import": "./src/schema.ts"
},
"./rpc": {
"types": "./src/rpc.ts",
"import": "./src/rpc.ts"
},
"./protocol": {
"types": "./src/protocol.ts",
"import": "./src/protocol.ts"
},
"./errors": {
"types": "./src/errors.ts",
"import": "./src/errors.ts"
}
},
"scripts": {
"dev": "tsdown src/client.ts src/rpc.ts src/protocol.ts src/schema.ts --format esm,cjs --dts --watch --clean",
"build": "tsdown src/client.ts src/rpc.ts src/protocol.ts src/schema.ts --format esm,cjs --dts --clean",
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"generate": "bun run scripts/generate.ts",
"probe": "bun run test/examples/codex-app-server-probe.ts"
},
"dependencies": {
"effect": "catalog:"
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/openapi-generator": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/vitest": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
}
}
@@ -0,0 +1,772 @@
#!/usr/bin/env node
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { make as makeJsonSchemaGenerator } from "@effect/openapi-generator/JsonSchemaGenerator";
import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
const UPSTREAM_REF = "dbfe855f4fd0f5dcdf079882652a8efe622b0595";
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";
const GithubContentEntries = Schema.Array(
Schema.Struct({
name: Schema.String,
path: Schema.String,
download_url: Schema.NullOr(Schema.String),
type: Schema.String,
}),
);
type GithubContentEntry = (typeof GithubContentEntries.Type)[number];
interface GeneratedPaths {
readonly generatedDir: string;
readonly schemaOutputPath: string;
readonly metaOutputPath: string;
readonly namespacesOutputPath: string;
}
interface MethodEntry {
readonly method: string;
readonly paramsType?: string;
}
interface JsonSchemaFile {
readonly namespace?: string;
readonly exportName: string;
readonly fileName: string;
readonly downloadUrl: string;
readonly qualifiedName: string;
}
class GeneratorError extends Schema.TaggedErrorClass<GeneratorError>()("GeneratorError", {
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message() {
return this.detail;
}
}
const ManualSchemas: Record<string, typeof Schema.Json.Type> = {
GetAuthStatusParams: {
type: "object",
title: "GetAuthStatusParams",
properties: {
includeToken: {
anyOf: [{ type: "boolean" }, { type: "null" }],
},
refreshToken: {
anyOf: [{ type: "boolean" }, { type: "null" }],
},
},
},
GetConversationSummaryParams: {
title: "GetConversationSummaryParams",
oneOf: [
{
type: "object",
properties: {
rolloutPath: { type: "string" },
},
required: ["rolloutPath"],
},
{
type: "object",
properties: {
conversationId: { type: "string" },
},
required: ["conversationId"],
},
],
},
GetConversationSummaryResponse: {
type: "object",
title: "GetConversationSummaryResponse",
properties: {
summary: {},
},
required: ["summary"],
},
GitDiffToRemoteParams: {
type: "object",
title: "GitDiffToRemoteParams",
properties: {
cwd: { type: "string" },
},
required: ["cwd"],
},
GitDiffToRemoteResponse: {
type: "object",
title: "GitDiffToRemoteResponse",
properties: {
sha: { type: "string" },
diff: { type: "string" },
},
required: ["sha", "diff"],
},
GetAuthStatusResponse: {
type: "object",
title: "GetAuthStatusResponse",
properties: {
authMethod: {
anyOf: [{}, { type: "null" }],
},
authToken: {
anyOf: [{ type: "string" }, { type: "null" }],
},
requiresOpenaiAuth: {
anyOf: [{ type: "boolean" }, { type: "null" }],
},
},
required: ["authMethod", "authToken", "requiresOpenaiAuth"],
},
};
const getGeneratedPaths = Effect.fn("getGeneratedPaths")(function* () {
const path = yield* Path.Path;
const generatedDir = path.join(import.meta.dirname, "..", "src", "_generated");
return {
generatedDir,
schemaOutputPath: path.join(generatedDir, "schema.gen.ts"),
metaOutputPath: path.join(generatedDir, "meta.gen.ts"),
namespacesOutputPath: path.join(generatedDir, "namespaces.gen.ts"),
} satisfies GeneratedPaths;
});
const ensureGeneratedDir = Effect.fn("ensureGeneratedDir")(function* () {
const fs = yield* FileSystem.FileSystem;
const { generatedDir } = yield* getGeneratedPaths();
yield* fs.makeDirectory(generatedDir, { recursive: true });
});
const fetchText = Effect.fn("fetchText")(function* (url: string) {
const response = yield* Effect.tryPromise({
try: () =>
fetch(url, {
headers: {
"user-agent": USER_AGENT,
},
}),
catch: (cause) =>
new GeneratorError({
detail: `Failed to fetch ${url}`,
cause,
}),
});
if (!response.ok) {
const detail = yield* Effect.tryPromise({
try: () => response.text(),
catch: () => "",
});
return yield* Effect.fail(
new GeneratorError({
detail: `Failed to download ${url}: ${response.status} ${detail}`,
}),
);
}
return yield* Effect.tryPromise({
try: () => response.text(),
catch: (cause) =>
new GeneratorError({
detail: `Failed to read response body for ${url}`,
cause,
}),
});
});
const fetchDirectoryEntries = Effect.fn("fetchDirectoryEntries")(function* (path: string) {
const raw = yield* fetchText(`${GITHUB_API_BASE}/${path}?ref=${UPSTREAM_REF}`);
return yield* Schema.decodeEffect(Schema.fromJsonString(GithubContentEntries))(raw);
});
function collectSchemaEntries(
chunk: string,
): ReadonlyArray<{ readonly name: string; readonly code: string }> {
const lines = chunk
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0 && !line.startsWith("//"));
const entries: Array<{ name: string; code: string }> = [];
for (let index = 0; index < lines.length; index += 1) {
const typeLine = lines[index];
if (!typeLine?.startsWith("export type ")) {
continue;
}
const constLine = lines[index + 1];
if (!constLine?.startsWith("export const ")) {
throw new Error(`Malformed generator output near: ${typeLine}`);
}
const match = /^export type ([A-Za-z0-9_]+)/.exec(typeLine);
if (!match?.[1]) {
throw new Error(`Could not extract schema name from: ${typeLine}`);
}
entries.push({
name: match[1],
code: `${typeLine}\n${constLine}`,
});
index += 1;
}
return entries;
}
function normalizeNullableTypes(value: typeof Schema.Json.Type): typeof Schema.Json.Type {
if (Array.isArray(value)) {
return value.map(normalizeNullableTypes);
}
if (value === null || typeof value !== "object") {
return value;
}
const normalizedEntries = Object.entries(value).map(([key, child]) => [
key,
normalizeNullableTypes(child),
]);
const normalizedObject = Object.fromEntries(normalizedEntries) as Record<
string,
typeof Schema.Json.Type
>;
const typeValue = normalizedObject.type;
if (!Array.isArray(typeValue)) {
return normalizedObject;
}
const normalizedTypes = typeValue.filter((entry): entry is string => typeof entry === "string");
if (normalizedTypes.length !== typeValue.length || !normalizedTypes.includes("null")) {
return normalizedObject;
}
const nonNullTypes = normalizedTypes.filter((entry) => entry !== "null");
if (nonNullTypes.length !== 1) {
return normalizedObject;
}
const nonNullType = nonNullTypes[0]!;
const nextObject: Record<string, typeof Schema.Json.Type> = {};
for (const [key, child] of Object.entries(normalizedObject)) {
if (key !== "type") {
nextObject[key] = child;
}
}
return {
anyOf: [
{
...nextObject,
type: nonNullType,
},
{ type: "null" },
],
};
}
function stripNullDefaults(value: typeof Schema.Json.Type): typeof Schema.Json.Type {
if (Array.isArray(value)) {
return value.map(stripNullDefaults);
}
if (value === null || typeof value !== "object") {
return value;
}
return Object.fromEntries(
Object.entries(value)
.filter(([key, child]) => !(key === "default" && child === null))
.map(([key, child]) => [key, stripNullDefaults(child)]),
) as typeof Schema.Json.Type;
}
function toPascalCaseMethod(method: string) {
return method
.split("/")
.flatMap((segment) => segment.split(/(?=[A-Z])/))
.flatMap((segment) => segment.split(/[-_]/))
.filter(Boolean)
.map((segment) => segment[0]!.toUpperCase() + segment.slice(1))
.join("");
}
function parseRequestEntries(fileContents: string): ReadonlyArray<MethodEntry> {
const entryPattern = /\{\s*"method":\s*"([^"]+)",\s*id:\s*RequestId,\s*params:\s*([^,}]+)/g;
const entries: Array<MethodEntry> = [];
let match: RegExpExecArray | null;
while ((match = entryPattern.exec(fileContents)) !== null) {
entries.push({
method: match[1]!,
paramsType: match[2]!.trim(),
});
}
return entries;
}
function parseNotificationEntries(fileContents: string): ReadonlyArray<MethodEntry> {
const entryPattern = /\{\s*"method":\s*"([^"]+)"(?:,\s*"params":\s*([^ }]+))?\s*\}/g;
const entries: Array<MethodEntry> = [];
let match: RegExpExecArray | null;
while ((match = entryPattern.exec(fileContents)) !== null) {
entries.push({
method: match[1]!,
...(match[2] ? { paramsType: match[2].trim() } : {}),
});
}
return entries;
}
function resolveSchemaTypeName(
rawTypeName: string,
generatedSchemaNames: ReadonlySet<string>,
): string {
if (rawTypeName === "undefined") {
return "undefined";
}
const candidates = [
rawTypeName,
`V2${rawTypeName}`,
`V1${rawTypeName}`,
`SerdeJson${rawTypeName}`,
];
for (const candidate of candidates) {
if (generatedSchemaNames.has(candidate)) {
return candidate;
}
}
throw new Error(`Unable to resolve schema type name: ${rawTypeName}`);
}
function resolveResponseTypeName(
method: string,
paramsType: string | undefined,
generatedSchemaNames: ReadonlySet<string>,
): string {
const overrides: Record<string, string> = {
"account/logout": "LogoutAccountResponse",
"account/rateLimits/read": "GetAccountRateLimitsResponse",
"config/batchWrite": "ConfigWriteResponse",
"config/mcpServer/reload": "McpServerRefreshResponse",
"config/value/write": "ConfigWriteResponse",
"configRequirements/read": "ConfigRequirementsReadResponse",
};
const override = overrides[method];
if (override) {
return resolveSchemaTypeName(override, generatedSchemaNames);
}
if (paramsType && paramsType !== "undefined") {
const fromParams = paramsType.replace(/Params$/, "Response");
try {
return resolveSchemaTypeName(fromParams, generatedSchemaNames);
} catch {
// Fall through to method-based lookup.
}
}
return resolveSchemaTypeName(`${toPascalCaseMethod(method)}Response`, generatedSchemaNames);
}
function renderMethodConstants(constantName: string, entries: ReadonlyArray<MethodEntry>) {
return [
`export const ${constantName} = {`,
...entries.map(
(entry) => ` ${JSON.stringify(entry.method)}: ${JSON.stringify(entry.method)},`,
),
"} as const;",
"",
].join("\n");
}
function renderTypeInterface(
interfaceName: string,
entries: ReadonlyArray<MethodEntry>,
typeName: (entry: MethodEntry) => string,
) {
return [
`export interface ${interfaceName} {`,
...entries.map((entry) => ` readonly ${JSON.stringify(entry.method)}: ${typeName(entry)};`),
"}",
"",
].join("\n");
}
function renderSchemaMap(
constantName: string,
entries: ReadonlyArray<MethodEntry>,
typeName: (entry: MethodEntry) => string,
) {
return [
`export const ${constantName} = {`,
...entries.map((entry) => {
const schemaName = typeName(entry);
return ` ${JSON.stringify(entry.method)}: ${
schemaName === "undefined" ? "undefined" : `CodexSchema.${schemaName}`
},`;
}),
"} as const;",
"",
].join("\n");
}
function renderSchemaTypeReference(schemaName: string) {
return schemaName === "undefined" ? "undefined" : `typeof CodexSchema.${schemaName}.Type`;
}
function exportNameForPath(filePath: string): string {
const relative = filePath.replace(/^schema\/json\//, "").replace(/\.json$/, "");
if (!relative.includes("/")) {
return relative;
}
const [namespace, name] = relative.split("/", 2) as [string, string];
const namespacePrefix = namespace
.split(/[^A-Za-z0-9]+/)
.filter(Boolean)
.map((segment) => segment[0]!.toUpperCase() + segment.slice(1))
.join("");
return `${namespacePrefix}${name}`;
}
function buildJsonSchemaFiles(
entries: ReadonlyArray<GithubContentEntry>,
): ReadonlyArray<JsonSchemaFile> {
return entries
.filter(
(entry) =>
entry.type === "file" &&
entry.name.endsWith(".json") &&
entry.download_url !== null &&
!entry.name.startsWith("codex_app_server_protocol."),
)
.map((entry) => {
const relative = entry.path.replace(/^codex-rs\/app-server-protocol\/schema\/json\//, "");
const parts = relative.split("/");
if (parts.length > 1) {
return {
namespace: parts[0]!,
exportName: exportNameForPath(relative),
fileName: entry.name,
downloadUrl: entry.download_url!,
qualifiedName: relative.replace(/\.json$/, ""),
} satisfies JsonSchemaFile;
}
return {
exportName: exportNameForPath(relative),
fileName: entry.name,
downloadUrl: entry.download_url!,
qualifiedName: relative.replace(/\.json$/, ""),
} satisfies JsonSchemaFile;
});
}
function rewriteExternalRefs(
value: typeof Schema.Json.Type,
localDefinitionNames: ReadonlyMap<string, string>,
currentNamespace: string | undefined,
exportNameByQualifiedName: ReadonlyMap<string, string>,
): typeof Schema.Json.Type {
if (Array.isArray(value)) {
return value.map((entry) =>
rewriteExternalRefs(entry, localDefinitionNames, currentNamespace, exportNameByQualifiedName),
);
}
if (value === null || typeof value !== "object") {
return value;
}
return Object.fromEntries(
Object.entries(value).map(([key, child]) => {
if (key === "$ref" && typeof child === "string" && child.startsWith("#/definitions/")) {
const definitionName = child.slice("#/definitions/".length);
const localRewrite = localDefinitionNames.get(definitionName);
if (localRewrite) {
return [key, `#/definitions/${localRewrite}`];
}
const candidates = [
...(currentNamespace ? [`${currentNamespace}/${definitionName}`] : []),
definitionName,
definitionName.replace(/^v[12]\//, ""),
definitionName.replace(/^serde_json\//, ""),
`v2/${definitionName}`,
`v1/${definitionName}`,
`serde_json/${definitionName}`,
];
const rewritten = candidates
.map((candidate) => exportNameByQualifiedName.get(candidate))
.find((candidate) => candidate !== undefined);
if (!rewritten) {
throw new Error(`Missing rewritten definition for ref: ${child}`);
}
return [key, `#/definitions/${rewritten}`];
}
return [
key,
rewriteExternalRefs(
child,
localDefinitionNames,
currentNamespace,
exportNameByQualifiedName,
),
];
}),
) as typeof Schema.Json.Type;
}
const generateFiles = Effect.fn("generateFiles")(function* () {
yield* ensureGeneratedDir();
const [rootJsonEntries, v1JsonEntries, v2JsonEntries] = yield* Effect.all([
fetchDirectoryEntries("schema/json"),
fetchDirectoryEntries("schema/json/v1"),
fetchDirectoryEntries("schema/json/v2"),
]);
const jsonSchemaFiles = [
...buildJsonSchemaFiles(rootJsonEntries),
...buildJsonSchemaFiles(v1JsonEntries),
...buildJsonSchemaFiles(v2JsonEntries),
].toSorted((left, right) => left.exportName.localeCompare(right.exportName));
const exportNameByQualifiedName = new Map(
jsonSchemaFiles.map((file) => [file.qualifiedName, file.exportName]),
);
const aggregateSchemas: Record<string, typeof Schema.Json.Type> = {};
for (const file of jsonSchemaFiles) {
const raw = yield* fetchText(file.downloadUrl);
const parsed = JSON.parse(raw) as {
readonly definitions?: Record<string, typeof Schema.Json.Type>;
} & Record<string, typeof Schema.Json.Type>;
const localDefinitionNames = new Map(
Object.keys(parsed.definitions ?? {}).map((definitionName) => [
definitionName,
`${file.exportName}__${definitionName.replace(/[^A-Za-z0-9]/g, "")}`,
]),
);
for (const [definitionName, definitionSchema] of Object.entries(parsed.definitions ?? {})) {
aggregateSchemas[localDefinitionNames.get(definitionName)!] = stripNullDefaults(
normalizeNullableTypes(
rewriteExternalRefs(
definitionSchema,
localDefinitionNames,
file.namespace,
exportNameByQualifiedName,
),
),
);
}
const topLevelSchema: Record<string, typeof Schema.Json.Type> = {};
for (const [key, value] of Object.entries(parsed)) {
if (key !== "definitions") {
topLevelSchema[key] = value;
}
}
aggregateSchemas[file.exportName] = stripNullDefaults(
normalizeNullableTypes(
rewriteExternalRefs(
topLevelSchema,
localDefinitionNames,
file.namespace,
exportNameByQualifiedName,
),
),
);
}
for (const [name, schema] of Object.entries(ManualSchemas)) {
if (!(name in aggregateSchemas)) {
aggregateSchemas[name] = stripNullDefaults(normalizeNullableTypes(schema));
}
}
const generator = makeJsonSchemaGenerator();
for (const [name, schema] of Object.entries(aggregateSchemas).toSorted(([left], [right]) =>
left.localeCompare(right),
)) {
generator.addSchema(name, schema as never);
}
const generatedEntries = new Map<string, string>();
const output = generator.generate("openapi-3.1", aggregateSchemas as never, false).trim();
if (output.length > 0) {
for (const entry of collectSchemaEntries(output)) {
if (!generatedEntries.has(entry.name)) {
generatedEntries.set(entry.name, entry.code);
}
}
}
const generatedSchemaNames = new Set(generatedEntries.keys());
const clientRequestRaw = yield* fetchText(
`https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts`,
);
const clientNotificationRaw = yield* fetchText(
`https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientNotification.ts`,
);
const serverRequestRaw = yield* fetchText(
`https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerRequest.ts`,
);
const serverNotificationRaw = yield* fetchText(
`https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts`,
);
const clientRequestEntries = parseRequestEntries(clientRequestRaw);
const clientNotificationEntries = parseNotificationEntries(clientNotificationRaw);
const serverRequestEntries = parseRequestEntries(serverRequestRaw);
const serverNotificationEntries = parseNotificationEntries(serverNotificationRaw);
const prelude = [
"// This file is generated by the effect-codex-app-server package. Do not edit manually.",
`// Upstream protocol ref: ${UPSTREAM_REF}`,
"",
];
const schemaOutput = [
...prelude,
'import * as Schema from "effect/Schema";',
"",
[...generatedEntries.values()].join("\n\n"),
"",
].join("\n");
const metaOutput = [
...prelude,
'import * as CodexSchema from "./schema.gen.ts";',
"",
renderMethodConstants("CLIENT_REQUEST_METHODS", clientRequestEntries),
renderMethodConstants("CLIENT_NOTIFICATION_METHODS", clientNotificationEntries),
renderMethodConstants("SERVER_REQUEST_METHODS", serverRequestEntries),
renderMethodConstants("SERVER_NOTIFICATION_METHODS", serverNotificationEntries),
"export type ClientRequestMethod = keyof typeof CLIENT_REQUEST_METHODS;",
"export type ClientNotificationMethod = keyof typeof CLIENT_NOTIFICATION_METHODS;",
"export type ServerRequestMethod = keyof typeof SERVER_REQUEST_METHODS;",
"export type ServerNotificationMethod = keyof typeof SERVER_NOTIFICATION_METHODS;",
"",
renderTypeInterface("ClientRequestParamsByMethod", clientRequestEntries, (entry) =>
renderSchemaTypeReference(
resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
),
),
renderTypeInterface("ClientRequestResponsesByMethod", clientRequestEntries, (entry) =>
renderSchemaTypeReference(
resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
),
),
renderTypeInterface("ClientNotificationParamsByMethod", clientNotificationEntries, (entry) =>
renderSchemaTypeReference(
resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
),
),
renderTypeInterface("ServerRequestParamsByMethod", serverRequestEntries, (entry) =>
renderSchemaTypeReference(
resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
),
),
renderTypeInterface("ServerRequestResponsesByMethod", serverRequestEntries, (entry) =>
renderSchemaTypeReference(
resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
),
),
renderTypeInterface("ServerNotificationParamsByMethod", serverNotificationEntries, (entry) =>
renderSchemaTypeReference(
resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
),
),
renderSchemaMap("CLIENT_REQUEST_PARAMS", clientRequestEntries, (entry) =>
resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
),
renderSchemaMap("CLIENT_REQUEST_RESPONSES", clientRequestEntries, (entry) =>
resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
),
renderSchemaMap("CLIENT_NOTIFICATION_PARAMS", clientNotificationEntries, (entry) =>
resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
),
renderSchemaMap("SERVER_REQUEST_PARAMS", serverRequestEntries, (entry) =>
resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
),
renderSchemaMap("SERVER_REQUEST_RESPONSES", serverRequestEntries, (entry) =>
resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
),
renderSchemaMap("SERVER_NOTIFICATION_PARAMS", serverNotificationEntries, (entry) =>
resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
),
].join("\n");
const namespaceGroups = new Map<string, Array<JsonSchemaFile>>();
for (const file of jsonSchemaFiles) {
if (!file.namespace) {
continue;
}
const current = namespaceGroups.get(file.namespace) ?? [];
current.push(file);
namespaceGroups.set(file.namespace, current);
}
const namespacesOutput = [
...prelude,
'import * as CodexSchema from "./schema.gen.ts";',
"",
...[...namespaceGroups.entries()]
.toSorted(([left], [right]) => left.localeCompare(right))
.map(([namespace, files]) => {
const constantName = namespace.replace(/[^A-Za-z0-9]/g, "");
return [
`export const ${constantName} = {`,
...files
.toSorted((left, right) => left.fileName.localeCompare(right.fileName))
.map(
(file) =>
` ${JSON.stringify(file.fileName.replace(/\.json$/, ""))}: CodexSchema.${file.exportName},`,
),
"} as const;",
"",
].join("\n");
}),
].join("\n");
const fs = yield* FileSystem.FileSystem;
const { generatedDir, metaOutputPath, namespacesOutputPath, schemaOutputPath } =
yield* getGeneratedPaths();
yield* fs.writeFileString(schemaOutputPath, schemaOutput);
yield* fs.writeFileString(metaOutputPath, metaOutput);
yield* fs.writeFileString(namespacesOutputPath, namespacesOutput);
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((child) => child.exitCode),
Effect.tap((code) =>
code === 0
? Effect.void
: Effect.fail(
new GeneratorError({
detail: `oxfmt failed with exit code ${code}`,
}),
),
),
);
});
generateFiles().pipe(
Effect.scoped,
Effect.provide(Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer)),
NodeRuntime.runMain,
);
@@ -0,0 +1,585 @@
// This file is generated by the effect-codex-app-server package. Do not edit manually.
// Upstream protocol ref: dbfe855f4fd0f5dcdf079882652a8efe622b0595
import * as CodexSchema from "./schema.gen.ts";
export const CLIENT_REQUEST_METHODS = {
initialize: "initialize",
"thread/start": "thread/start",
"thread/resume": "thread/resume",
"thread/fork": "thread/fork",
"thread/archive": "thread/archive",
"thread/unsubscribe": "thread/unsubscribe",
"thread/name/set": "thread/name/set",
"thread/metadata/update": "thread/metadata/update",
"thread/unarchive": "thread/unarchive",
"thread/compact/start": "thread/compact/start",
"thread/shellCommand": "thread/shellCommand",
"thread/rollback": "thread/rollback",
"thread/list": "thread/list",
"thread/loaded/list": "thread/loaded/list",
"thread/read": "thread/read",
"skills/list": "skills/list",
"plugin/list": "plugin/list",
"plugin/read": "plugin/read",
"app/list": "app/list",
"fs/readFile": "fs/readFile",
"fs/writeFile": "fs/writeFile",
"fs/createDirectory": "fs/createDirectory",
"fs/getMetadata": "fs/getMetadata",
"fs/readDirectory": "fs/readDirectory",
"fs/remove": "fs/remove",
"fs/copy": "fs/copy",
"fs/watch": "fs/watch",
"fs/unwatch": "fs/unwatch",
"skills/config/write": "skills/config/write",
"plugin/install": "plugin/install",
"plugin/uninstall": "plugin/uninstall",
"turn/start": "turn/start",
"turn/steer": "turn/steer",
"turn/interrupt": "turn/interrupt",
"review/start": "review/start",
"model/list": "model/list",
"experimentalFeature/list": "experimentalFeature/list",
"experimentalFeature/enablement/set": "experimentalFeature/enablement/set",
"mcpServer/oauth/login": "mcpServer/oauth/login",
"config/mcpServer/reload": "config/mcpServer/reload",
"mcpServerStatus/list": "mcpServerStatus/list",
"mcpServer/resource/read": "mcpServer/resource/read",
"mcpServer/tool/call": "mcpServer/tool/call",
"windowsSandbox/setupStart": "windowsSandbox/setupStart",
"account/login/start": "account/login/start",
"account/login/cancel": "account/login/cancel",
"account/logout": "account/logout",
"account/rateLimits/read": "account/rateLimits/read",
"feedback/upload": "feedback/upload",
"command/exec": "command/exec",
"command/exec/write": "command/exec/write",
"command/exec/terminate": "command/exec/terminate",
"command/exec/resize": "command/exec/resize",
"config/read": "config/read",
"externalAgentConfig/detect": "externalAgentConfig/detect",
"externalAgentConfig/import": "externalAgentConfig/import",
"config/value/write": "config/value/write",
"config/batchWrite": "config/batchWrite",
"configRequirements/read": "configRequirements/read",
"account/read": "account/read",
getConversationSummary: "getConversationSummary",
gitDiffToRemote: "gitDiffToRemote",
getAuthStatus: "getAuthStatus",
fuzzyFileSearch: "fuzzyFileSearch",
} as const;
export const CLIENT_NOTIFICATION_METHODS = {
initialized: "initialized",
} as const;
export const SERVER_REQUEST_METHODS = {
"item/commandExecution/requestApproval": "item/commandExecution/requestApproval",
"item/fileChange/requestApproval": "item/fileChange/requestApproval",
"item/tool/requestUserInput": "item/tool/requestUserInput",
"mcpServer/elicitation/request": "mcpServer/elicitation/request",
"item/permissions/requestApproval": "item/permissions/requestApproval",
"item/tool/call": "item/tool/call",
"account/chatgptAuthTokens/refresh": "account/chatgptAuthTokens/refresh",
applyPatchApproval: "applyPatchApproval",
execCommandApproval: "execCommandApproval",
} as const;
export const SERVER_NOTIFICATION_METHODS = {
error: "error",
"thread/started": "thread/started",
"thread/status/changed": "thread/status/changed",
"thread/archived": "thread/archived",
"thread/unarchived": "thread/unarchived",
"thread/closed": "thread/closed",
"skills/changed": "skills/changed",
"thread/name/updated": "thread/name/updated",
"thread/tokenUsage/updated": "thread/tokenUsage/updated",
"turn/started": "turn/started",
"hook/started": "hook/started",
"turn/completed": "turn/completed",
"hook/completed": "hook/completed",
"turn/diff/updated": "turn/diff/updated",
"turn/plan/updated": "turn/plan/updated",
"item/started": "item/started",
"item/autoApprovalReview/started": "item/autoApprovalReview/started",
"item/autoApprovalReview/completed": "item/autoApprovalReview/completed",
"item/completed": "item/completed",
"rawResponseItem/completed": "rawResponseItem/completed",
"item/agentMessage/delta": "item/agentMessage/delta",
"item/plan/delta": "item/plan/delta",
"command/exec/outputDelta": "command/exec/outputDelta",
"item/commandExecution/outputDelta": "item/commandExecution/outputDelta",
"item/commandExecution/terminalInteraction": "item/commandExecution/terminalInteraction",
"item/fileChange/outputDelta": "item/fileChange/outputDelta",
"serverRequest/resolved": "serverRequest/resolved",
"item/mcpToolCall/progress": "item/mcpToolCall/progress",
"mcpServer/oauthLogin/completed": "mcpServer/oauthLogin/completed",
"mcpServer/startupStatus/updated": "mcpServer/startupStatus/updated",
"account/updated": "account/updated",
"account/rateLimits/updated": "account/rateLimits/updated",
"app/list/updated": "app/list/updated",
"fs/changed": "fs/changed",
"item/reasoning/summaryTextDelta": "item/reasoning/summaryTextDelta",
"item/reasoning/summaryPartAdded": "item/reasoning/summaryPartAdded",
"item/reasoning/textDelta": "item/reasoning/textDelta",
"thread/compacted": "thread/compacted",
"model/rerouted": "model/rerouted",
deprecationNotice: "deprecationNotice",
configWarning: "configWarning",
"fuzzyFileSearch/sessionUpdated": "fuzzyFileSearch/sessionUpdated",
"fuzzyFileSearch/sessionCompleted": "fuzzyFileSearch/sessionCompleted",
"thread/realtime/started": "thread/realtime/started",
"thread/realtime/itemAdded": "thread/realtime/itemAdded",
"thread/realtime/transcriptUpdated": "thread/realtime/transcriptUpdated",
"thread/realtime/outputAudio/delta": "thread/realtime/outputAudio/delta",
"thread/realtime/sdp": "thread/realtime/sdp",
"thread/realtime/error": "thread/realtime/error",
"thread/realtime/closed": "thread/realtime/closed",
"windows/worldWritableWarning": "windows/worldWritableWarning",
"windowsSandbox/setupCompleted": "windowsSandbox/setupCompleted",
"account/login/completed": "account/login/completed",
} as const;
export type ClientRequestMethod = keyof typeof CLIENT_REQUEST_METHODS;
export type ClientNotificationMethod = keyof typeof CLIENT_NOTIFICATION_METHODS;
export type ServerRequestMethod = keyof typeof SERVER_REQUEST_METHODS;
export type ServerNotificationMethod = keyof typeof SERVER_NOTIFICATION_METHODS;
export interface ClientRequestParamsByMethod {
readonly initialize: typeof CodexSchema.V1InitializeParams.Type;
readonly "thread/start": typeof CodexSchema.V2ThreadStartParams.Type;
readonly "thread/resume": typeof CodexSchema.V2ThreadResumeParams.Type;
readonly "thread/fork": typeof CodexSchema.V2ThreadForkParams.Type;
readonly "thread/archive": typeof CodexSchema.V2ThreadArchiveParams.Type;
readonly "thread/unsubscribe": typeof CodexSchema.V2ThreadUnsubscribeParams.Type;
readonly "thread/name/set": typeof CodexSchema.V2ThreadSetNameParams.Type;
readonly "thread/metadata/update": typeof CodexSchema.V2ThreadMetadataUpdateParams.Type;
readonly "thread/unarchive": typeof CodexSchema.V2ThreadUnarchiveParams.Type;
readonly "thread/compact/start": typeof CodexSchema.V2ThreadCompactStartParams.Type;
readonly "thread/shellCommand": typeof CodexSchema.V2ThreadShellCommandParams.Type;
readonly "thread/rollback": typeof CodexSchema.V2ThreadRollbackParams.Type;
readonly "thread/list": typeof CodexSchema.V2ThreadListParams.Type;
readonly "thread/loaded/list": typeof CodexSchema.V2ThreadLoadedListParams.Type;
readonly "thread/read": typeof CodexSchema.V2ThreadReadParams.Type;
readonly "skills/list": typeof CodexSchema.V2SkillsListParams.Type;
readonly "plugin/list": typeof CodexSchema.V2PluginListParams.Type;
readonly "plugin/read": typeof CodexSchema.V2PluginReadParams.Type;
readonly "app/list": typeof CodexSchema.V2AppsListParams.Type;
readonly "fs/readFile": typeof CodexSchema.V2FsReadFileParams.Type;
readonly "fs/writeFile": typeof CodexSchema.V2FsWriteFileParams.Type;
readonly "fs/createDirectory": typeof CodexSchema.V2FsCreateDirectoryParams.Type;
readonly "fs/getMetadata": typeof CodexSchema.V2FsGetMetadataParams.Type;
readonly "fs/readDirectory": typeof CodexSchema.V2FsReadDirectoryParams.Type;
readonly "fs/remove": typeof CodexSchema.V2FsRemoveParams.Type;
readonly "fs/copy": typeof CodexSchema.V2FsCopyParams.Type;
readonly "fs/watch": typeof CodexSchema.V2FsWatchParams.Type;
readonly "fs/unwatch": typeof CodexSchema.V2FsUnwatchParams.Type;
readonly "skills/config/write": typeof CodexSchema.V2SkillsConfigWriteParams.Type;
readonly "plugin/install": typeof CodexSchema.V2PluginInstallParams.Type;
readonly "plugin/uninstall": typeof CodexSchema.V2PluginUninstallParams.Type;
readonly "turn/start": typeof CodexSchema.V2TurnStartParams.Type;
readonly "turn/steer": typeof CodexSchema.V2TurnSteerParams.Type;
readonly "turn/interrupt": typeof CodexSchema.V2TurnInterruptParams.Type;
readonly "review/start": typeof CodexSchema.V2ReviewStartParams.Type;
readonly "model/list": typeof CodexSchema.V2ModelListParams.Type;
readonly "experimentalFeature/list": typeof CodexSchema.V2ExperimentalFeatureListParams.Type;
readonly "experimentalFeature/enablement/set": typeof CodexSchema.V2ExperimentalFeatureEnablementSetParams.Type;
readonly "mcpServer/oauth/login": typeof CodexSchema.V2McpServerOauthLoginParams.Type;
readonly "config/mcpServer/reload": undefined;
readonly "mcpServerStatus/list": typeof CodexSchema.V2ListMcpServerStatusParams.Type;
readonly "mcpServer/resource/read": typeof CodexSchema.V2McpResourceReadParams.Type;
readonly "mcpServer/tool/call": typeof CodexSchema.V2McpServerToolCallParams.Type;
readonly "windowsSandbox/setupStart": typeof CodexSchema.V2WindowsSandboxSetupStartParams.Type;
readonly "account/login/start": typeof CodexSchema.V2LoginAccountParams.Type;
readonly "account/login/cancel": typeof CodexSchema.V2CancelLoginAccountParams.Type;
readonly "account/logout": undefined;
readonly "account/rateLimits/read": undefined;
readonly "feedback/upload": typeof CodexSchema.V2FeedbackUploadParams.Type;
readonly "command/exec": typeof CodexSchema.V2CommandExecParams.Type;
readonly "command/exec/write": typeof CodexSchema.V2CommandExecWriteParams.Type;
readonly "command/exec/terminate": typeof CodexSchema.V2CommandExecTerminateParams.Type;
readonly "command/exec/resize": typeof CodexSchema.V2CommandExecResizeParams.Type;
readonly "config/read": typeof CodexSchema.V2ConfigReadParams.Type;
readonly "externalAgentConfig/detect": typeof CodexSchema.V2ExternalAgentConfigDetectParams.Type;
readonly "externalAgentConfig/import": typeof CodexSchema.V2ExternalAgentConfigImportParams.Type;
readonly "config/value/write": typeof CodexSchema.V2ConfigValueWriteParams.Type;
readonly "config/batchWrite": typeof CodexSchema.V2ConfigBatchWriteParams.Type;
readonly "configRequirements/read": undefined;
readonly "account/read": typeof CodexSchema.V2GetAccountParams.Type;
readonly getConversationSummary: typeof CodexSchema.GetConversationSummaryParams.Type;
readonly gitDiffToRemote: typeof CodexSchema.GitDiffToRemoteParams.Type;
readonly getAuthStatus: typeof CodexSchema.GetAuthStatusParams.Type;
readonly fuzzyFileSearch: typeof CodexSchema.FuzzyFileSearchParams.Type;
}
export interface ClientRequestResponsesByMethod {
readonly initialize: typeof CodexSchema.V1InitializeResponse.Type;
readonly "thread/start": typeof CodexSchema.V2ThreadStartResponse.Type;
readonly "thread/resume": typeof CodexSchema.V2ThreadResumeResponse.Type;
readonly "thread/fork": typeof CodexSchema.V2ThreadForkResponse.Type;
readonly "thread/archive": typeof CodexSchema.V2ThreadArchiveResponse.Type;
readonly "thread/unsubscribe": typeof CodexSchema.V2ThreadUnsubscribeResponse.Type;
readonly "thread/name/set": typeof CodexSchema.V2ThreadSetNameResponse.Type;
readonly "thread/metadata/update": typeof CodexSchema.V2ThreadMetadataUpdateResponse.Type;
readonly "thread/unarchive": typeof CodexSchema.V2ThreadUnarchiveResponse.Type;
readonly "thread/compact/start": typeof CodexSchema.V2ThreadCompactStartResponse.Type;
readonly "thread/shellCommand": typeof CodexSchema.V2ThreadShellCommandResponse.Type;
readonly "thread/rollback": typeof CodexSchema.V2ThreadRollbackResponse.Type;
readonly "thread/list": typeof CodexSchema.V2ThreadListResponse.Type;
readonly "thread/loaded/list": typeof CodexSchema.V2ThreadLoadedListResponse.Type;
readonly "thread/read": typeof CodexSchema.V2ThreadReadResponse.Type;
readonly "skills/list": typeof CodexSchema.V2SkillsListResponse.Type;
readonly "plugin/list": typeof CodexSchema.V2PluginListResponse.Type;
readonly "plugin/read": typeof CodexSchema.V2PluginReadResponse.Type;
readonly "app/list": typeof CodexSchema.V2AppsListResponse.Type;
readonly "fs/readFile": typeof CodexSchema.V2FsReadFileResponse.Type;
readonly "fs/writeFile": typeof CodexSchema.V2FsWriteFileResponse.Type;
readonly "fs/createDirectory": typeof CodexSchema.V2FsCreateDirectoryResponse.Type;
readonly "fs/getMetadata": typeof CodexSchema.V2FsGetMetadataResponse.Type;
readonly "fs/readDirectory": typeof CodexSchema.V2FsReadDirectoryResponse.Type;
readonly "fs/remove": typeof CodexSchema.V2FsRemoveResponse.Type;
readonly "fs/copy": typeof CodexSchema.V2FsCopyResponse.Type;
readonly "fs/watch": typeof CodexSchema.V2FsWatchResponse.Type;
readonly "fs/unwatch": typeof CodexSchema.V2FsUnwatchResponse.Type;
readonly "skills/config/write": typeof CodexSchema.V2SkillsConfigWriteResponse.Type;
readonly "plugin/install": typeof CodexSchema.V2PluginInstallResponse.Type;
readonly "plugin/uninstall": typeof CodexSchema.V2PluginUninstallResponse.Type;
readonly "turn/start": typeof CodexSchema.V2TurnStartResponse.Type;
readonly "turn/steer": typeof CodexSchema.V2TurnSteerResponse.Type;
readonly "turn/interrupt": typeof CodexSchema.V2TurnInterruptResponse.Type;
readonly "review/start": typeof CodexSchema.V2ReviewStartResponse.Type;
readonly "model/list": typeof CodexSchema.V2ModelListResponse.Type;
readonly "experimentalFeature/list": typeof CodexSchema.V2ExperimentalFeatureListResponse.Type;
readonly "experimentalFeature/enablement/set": typeof CodexSchema.V2ExperimentalFeatureEnablementSetResponse.Type;
readonly "mcpServer/oauth/login": typeof CodexSchema.V2McpServerOauthLoginResponse.Type;
readonly "config/mcpServer/reload": typeof CodexSchema.V2McpServerRefreshResponse.Type;
readonly "mcpServerStatus/list": typeof CodexSchema.V2ListMcpServerStatusResponse.Type;
readonly "mcpServer/resource/read": typeof CodexSchema.V2McpResourceReadResponse.Type;
readonly "mcpServer/tool/call": typeof CodexSchema.V2McpServerToolCallResponse.Type;
readonly "windowsSandbox/setupStart": typeof CodexSchema.V2WindowsSandboxSetupStartResponse.Type;
readonly "account/login/start": typeof CodexSchema.V2LoginAccountResponse.Type;
readonly "account/login/cancel": typeof CodexSchema.V2CancelLoginAccountResponse.Type;
readonly "account/logout": typeof CodexSchema.V2LogoutAccountResponse.Type;
readonly "account/rateLimits/read": typeof CodexSchema.V2GetAccountRateLimitsResponse.Type;
readonly "feedback/upload": typeof CodexSchema.V2FeedbackUploadResponse.Type;
readonly "command/exec": typeof CodexSchema.V2CommandExecResponse.Type;
readonly "command/exec/write": typeof CodexSchema.V2CommandExecWriteResponse.Type;
readonly "command/exec/terminate": typeof CodexSchema.V2CommandExecTerminateResponse.Type;
readonly "command/exec/resize": typeof CodexSchema.V2CommandExecResizeResponse.Type;
readonly "config/read": typeof CodexSchema.V2ConfigReadResponse.Type;
readonly "externalAgentConfig/detect": typeof CodexSchema.V2ExternalAgentConfigDetectResponse.Type;
readonly "externalAgentConfig/import": typeof CodexSchema.V2ExternalAgentConfigImportResponse.Type;
readonly "config/value/write": typeof CodexSchema.V2ConfigWriteResponse.Type;
readonly "config/batchWrite": typeof CodexSchema.V2ConfigWriteResponse.Type;
readonly "configRequirements/read": typeof CodexSchema.V2ConfigRequirementsReadResponse.Type;
readonly "account/read": typeof CodexSchema.V2GetAccountResponse.Type;
readonly getConversationSummary: typeof CodexSchema.GetConversationSummaryResponse.Type;
readonly gitDiffToRemote: typeof CodexSchema.GitDiffToRemoteResponse.Type;
readonly getAuthStatus: typeof CodexSchema.GetAuthStatusResponse.Type;
readonly fuzzyFileSearch: typeof CodexSchema.FuzzyFileSearchResponse.Type;
}
export interface ClientNotificationParamsByMethod {
readonly initialized: undefined;
}
export interface ServerRequestParamsByMethod {
readonly "item/commandExecution/requestApproval": typeof CodexSchema.CommandExecutionRequestApprovalParams.Type;
readonly "item/fileChange/requestApproval": typeof CodexSchema.FileChangeRequestApprovalParams.Type;
readonly "item/tool/requestUserInput": typeof CodexSchema.ToolRequestUserInputParams.Type;
readonly "mcpServer/elicitation/request": typeof CodexSchema.McpServerElicitationRequestParams.Type;
readonly "item/permissions/requestApproval": typeof CodexSchema.PermissionsRequestApprovalParams.Type;
readonly "item/tool/call": typeof CodexSchema.DynamicToolCallParams.Type;
readonly "account/chatgptAuthTokens/refresh": typeof CodexSchema.ChatgptAuthTokensRefreshParams.Type;
readonly applyPatchApproval: typeof CodexSchema.ApplyPatchApprovalParams.Type;
readonly execCommandApproval: typeof CodexSchema.ExecCommandApprovalParams.Type;
}
export interface ServerRequestResponsesByMethod {
readonly "item/commandExecution/requestApproval": typeof CodexSchema.CommandExecutionRequestApprovalResponse.Type;
readonly "item/fileChange/requestApproval": typeof CodexSchema.FileChangeRequestApprovalResponse.Type;
readonly "item/tool/requestUserInput": typeof CodexSchema.ToolRequestUserInputResponse.Type;
readonly "mcpServer/elicitation/request": typeof CodexSchema.McpServerElicitationRequestResponse.Type;
readonly "item/permissions/requestApproval": typeof CodexSchema.PermissionsRequestApprovalResponse.Type;
readonly "item/tool/call": typeof CodexSchema.DynamicToolCallResponse.Type;
readonly "account/chatgptAuthTokens/refresh": typeof CodexSchema.ChatgptAuthTokensRefreshResponse.Type;
readonly applyPatchApproval: typeof CodexSchema.ApplyPatchApprovalResponse.Type;
readonly execCommandApproval: typeof CodexSchema.ExecCommandApprovalResponse.Type;
}
export interface ServerNotificationParamsByMethod {
readonly error: typeof CodexSchema.V2ErrorNotification.Type;
readonly "thread/started": typeof CodexSchema.V2ThreadStartedNotification.Type;
readonly "thread/status/changed": typeof CodexSchema.V2ThreadStatusChangedNotification.Type;
readonly "thread/archived": typeof CodexSchema.V2ThreadArchivedNotification.Type;
readonly "thread/unarchived": typeof CodexSchema.V2ThreadUnarchivedNotification.Type;
readonly "thread/closed": typeof CodexSchema.V2ThreadClosedNotification.Type;
readonly "skills/changed": typeof CodexSchema.V2SkillsChangedNotification.Type;
readonly "thread/name/updated": typeof CodexSchema.V2ThreadNameUpdatedNotification.Type;
readonly "thread/tokenUsage/updated": typeof CodexSchema.V2ThreadTokenUsageUpdatedNotification.Type;
readonly "turn/started": typeof CodexSchema.V2TurnStartedNotification.Type;
readonly "hook/started": typeof CodexSchema.V2HookStartedNotification.Type;
readonly "turn/completed": typeof CodexSchema.V2TurnCompletedNotification.Type;
readonly "hook/completed": typeof CodexSchema.V2HookCompletedNotification.Type;
readonly "turn/diff/updated": typeof CodexSchema.V2TurnDiffUpdatedNotification.Type;
readonly "turn/plan/updated": typeof CodexSchema.V2TurnPlanUpdatedNotification.Type;
readonly "item/started": typeof CodexSchema.V2ItemStartedNotification.Type;
readonly "item/autoApprovalReview/started": typeof CodexSchema.V2ItemGuardianApprovalReviewStartedNotification.Type;
readonly "item/autoApprovalReview/completed": typeof CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification.Type;
readonly "item/completed": typeof CodexSchema.V2ItemCompletedNotification.Type;
readonly "rawResponseItem/completed": typeof CodexSchema.V2RawResponseItemCompletedNotification.Type;
readonly "item/agentMessage/delta": typeof CodexSchema.V2AgentMessageDeltaNotification.Type;
readonly "item/plan/delta": typeof CodexSchema.V2PlanDeltaNotification.Type;
readonly "command/exec/outputDelta": typeof CodexSchema.V2CommandExecOutputDeltaNotification.Type;
readonly "item/commandExecution/outputDelta": typeof CodexSchema.V2CommandExecutionOutputDeltaNotification.Type;
readonly "item/commandExecution/terminalInteraction": typeof CodexSchema.V2TerminalInteractionNotification.Type;
readonly "item/fileChange/outputDelta": typeof CodexSchema.V2FileChangeOutputDeltaNotification.Type;
readonly "serverRequest/resolved": typeof CodexSchema.V2ServerRequestResolvedNotification.Type;
readonly "item/mcpToolCall/progress": typeof CodexSchema.V2McpToolCallProgressNotification.Type;
readonly "mcpServer/oauthLogin/completed": typeof CodexSchema.V2McpServerOauthLoginCompletedNotification.Type;
readonly "mcpServer/startupStatus/updated": typeof CodexSchema.V2McpServerStatusUpdatedNotification.Type;
readonly "account/updated": typeof CodexSchema.V2AccountUpdatedNotification.Type;
readonly "account/rateLimits/updated": typeof CodexSchema.V2AccountRateLimitsUpdatedNotification.Type;
readonly "app/list/updated": typeof CodexSchema.V2AppListUpdatedNotification.Type;
readonly "fs/changed": typeof CodexSchema.V2FsChangedNotification.Type;
readonly "item/reasoning/summaryTextDelta": typeof CodexSchema.V2ReasoningSummaryTextDeltaNotification.Type;
readonly "item/reasoning/summaryPartAdded": typeof CodexSchema.V2ReasoningSummaryPartAddedNotification.Type;
readonly "item/reasoning/textDelta": typeof CodexSchema.V2ReasoningTextDeltaNotification.Type;
readonly "thread/compacted": typeof CodexSchema.V2ContextCompactedNotification.Type;
readonly "model/rerouted": typeof CodexSchema.V2ModelReroutedNotification.Type;
readonly deprecationNotice: typeof CodexSchema.V2DeprecationNoticeNotification.Type;
readonly configWarning: typeof CodexSchema.V2ConfigWarningNotification.Type;
readonly "fuzzyFileSearch/sessionUpdated": typeof CodexSchema.FuzzyFileSearchSessionUpdatedNotification.Type;
readonly "fuzzyFileSearch/sessionCompleted": typeof CodexSchema.FuzzyFileSearchSessionCompletedNotification.Type;
readonly "thread/realtime/started": typeof CodexSchema.V2ThreadRealtimeStartedNotification.Type;
readonly "thread/realtime/itemAdded": typeof CodexSchema.V2ThreadRealtimeItemAddedNotification.Type;
readonly "thread/realtime/transcriptUpdated": typeof CodexSchema.V2ThreadRealtimeTranscriptUpdatedNotification.Type;
readonly "thread/realtime/outputAudio/delta": typeof CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification.Type;
readonly "thread/realtime/sdp": typeof CodexSchema.V2ThreadRealtimeSdpNotification.Type;
readonly "thread/realtime/error": typeof CodexSchema.V2ThreadRealtimeErrorNotification.Type;
readonly "thread/realtime/closed": typeof CodexSchema.V2ThreadRealtimeClosedNotification.Type;
readonly "windows/worldWritableWarning": typeof CodexSchema.V2WindowsWorldWritableWarningNotification.Type;
readonly "windowsSandbox/setupCompleted": typeof CodexSchema.V2WindowsSandboxSetupCompletedNotification.Type;
readonly "account/login/completed": typeof CodexSchema.V2AccountLoginCompletedNotification.Type;
}
export const CLIENT_REQUEST_PARAMS = {
initialize: CodexSchema.V1InitializeParams,
"thread/start": CodexSchema.V2ThreadStartParams,
"thread/resume": CodexSchema.V2ThreadResumeParams,
"thread/fork": CodexSchema.V2ThreadForkParams,
"thread/archive": CodexSchema.V2ThreadArchiveParams,
"thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeParams,
"thread/name/set": CodexSchema.V2ThreadSetNameParams,
"thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateParams,
"thread/unarchive": CodexSchema.V2ThreadUnarchiveParams,
"thread/compact/start": CodexSchema.V2ThreadCompactStartParams,
"thread/shellCommand": CodexSchema.V2ThreadShellCommandParams,
"thread/rollback": CodexSchema.V2ThreadRollbackParams,
"thread/list": CodexSchema.V2ThreadListParams,
"thread/loaded/list": CodexSchema.V2ThreadLoadedListParams,
"thread/read": CodexSchema.V2ThreadReadParams,
"skills/list": CodexSchema.V2SkillsListParams,
"plugin/list": CodexSchema.V2PluginListParams,
"plugin/read": CodexSchema.V2PluginReadParams,
"app/list": CodexSchema.V2AppsListParams,
"fs/readFile": CodexSchema.V2FsReadFileParams,
"fs/writeFile": CodexSchema.V2FsWriteFileParams,
"fs/createDirectory": CodexSchema.V2FsCreateDirectoryParams,
"fs/getMetadata": CodexSchema.V2FsGetMetadataParams,
"fs/readDirectory": CodexSchema.V2FsReadDirectoryParams,
"fs/remove": CodexSchema.V2FsRemoveParams,
"fs/copy": CodexSchema.V2FsCopyParams,
"fs/watch": CodexSchema.V2FsWatchParams,
"fs/unwatch": CodexSchema.V2FsUnwatchParams,
"skills/config/write": CodexSchema.V2SkillsConfigWriteParams,
"plugin/install": CodexSchema.V2PluginInstallParams,
"plugin/uninstall": CodexSchema.V2PluginUninstallParams,
"turn/start": CodexSchema.V2TurnStartParams,
"turn/steer": CodexSchema.V2TurnSteerParams,
"turn/interrupt": CodexSchema.V2TurnInterruptParams,
"review/start": CodexSchema.V2ReviewStartParams,
"model/list": CodexSchema.V2ModelListParams,
"experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListParams,
"experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetParams,
"mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginParams,
"config/mcpServer/reload": undefined,
"mcpServerStatus/list": CodexSchema.V2ListMcpServerStatusParams,
"mcpServer/resource/read": CodexSchema.V2McpResourceReadParams,
"mcpServer/tool/call": CodexSchema.V2McpServerToolCallParams,
"windowsSandbox/setupStart": CodexSchema.V2WindowsSandboxSetupStartParams,
"account/login/start": CodexSchema.V2LoginAccountParams,
"account/login/cancel": CodexSchema.V2CancelLoginAccountParams,
"account/logout": undefined,
"account/rateLimits/read": undefined,
"feedback/upload": CodexSchema.V2FeedbackUploadParams,
"command/exec": CodexSchema.V2CommandExecParams,
"command/exec/write": CodexSchema.V2CommandExecWriteParams,
"command/exec/terminate": CodexSchema.V2CommandExecTerminateParams,
"command/exec/resize": CodexSchema.V2CommandExecResizeParams,
"config/read": CodexSchema.V2ConfigReadParams,
"externalAgentConfig/detect": CodexSchema.V2ExternalAgentConfigDetectParams,
"externalAgentConfig/import": CodexSchema.V2ExternalAgentConfigImportParams,
"config/value/write": CodexSchema.V2ConfigValueWriteParams,
"config/batchWrite": CodexSchema.V2ConfigBatchWriteParams,
"configRequirements/read": undefined,
"account/read": CodexSchema.V2GetAccountParams,
getConversationSummary: CodexSchema.GetConversationSummaryParams,
gitDiffToRemote: CodexSchema.GitDiffToRemoteParams,
getAuthStatus: CodexSchema.GetAuthStatusParams,
fuzzyFileSearch: CodexSchema.FuzzyFileSearchParams,
} as const;
export const CLIENT_REQUEST_RESPONSES = {
initialize: CodexSchema.V1InitializeResponse,
"thread/start": CodexSchema.V2ThreadStartResponse,
"thread/resume": CodexSchema.V2ThreadResumeResponse,
"thread/fork": CodexSchema.V2ThreadForkResponse,
"thread/archive": CodexSchema.V2ThreadArchiveResponse,
"thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeResponse,
"thread/name/set": CodexSchema.V2ThreadSetNameResponse,
"thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateResponse,
"thread/unarchive": CodexSchema.V2ThreadUnarchiveResponse,
"thread/compact/start": CodexSchema.V2ThreadCompactStartResponse,
"thread/shellCommand": CodexSchema.V2ThreadShellCommandResponse,
"thread/rollback": CodexSchema.V2ThreadRollbackResponse,
"thread/list": CodexSchema.V2ThreadListResponse,
"thread/loaded/list": CodexSchema.V2ThreadLoadedListResponse,
"thread/read": CodexSchema.V2ThreadReadResponse,
"skills/list": CodexSchema.V2SkillsListResponse,
"plugin/list": CodexSchema.V2PluginListResponse,
"plugin/read": CodexSchema.V2PluginReadResponse,
"app/list": CodexSchema.V2AppsListResponse,
"fs/readFile": CodexSchema.V2FsReadFileResponse,
"fs/writeFile": CodexSchema.V2FsWriteFileResponse,
"fs/createDirectory": CodexSchema.V2FsCreateDirectoryResponse,
"fs/getMetadata": CodexSchema.V2FsGetMetadataResponse,
"fs/readDirectory": CodexSchema.V2FsReadDirectoryResponse,
"fs/remove": CodexSchema.V2FsRemoveResponse,
"fs/copy": CodexSchema.V2FsCopyResponse,
"fs/watch": CodexSchema.V2FsWatchResponse,
"fs/unwatch": CodexSchema.V2FsUnwatchResponse,
"skills/config/write": CodexSchema.V2SkillsConfigWriteResponse,
"plugin/install": CodexSchema.V2PluginInstallResponse,
"plugin/uninstall": CodexSchema.V2PluginUninstallResponse,
"turn/start": CodexSchema.V2TurnStartResponse,
"turn/steer": CodexSchema.V2TurnSteerResponse,
"turn/interrupt": CodexSchema.V2TurnInterruptResponse,
"review/start": CodexSchema.V2ReviewStartResponse,
"model/list": CodexSchema.V2ModelListResponse,
"experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListResponse,
"experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetResponse,
"mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginResponse,
"config/mcpServer/reload": CodexSchema.V2McpServerRefreshResponse,
"mcpServerStatus/list": CodexSchema.V2ListMcpServerStatusResponse,
"mcpServer/resource/read": CodexSchema.V2McpResourceReadResponse,
"mcpServer/tool/call": CodexSchema.V2McpServerToolCallResponse,
"windowsSandbox/setupStart": CodexSchema.V2WindowsSandboxSetupStartResponse,
"account/login/start": CodexSchema.V2LoginAccountResponse,
"account/login/cancel": CodexSchema.V2CancelLoginAccountResponse,
"account/logout": CodexSchema.V2LogoutAccountResponse,
"account/rateLimits/read": CodexSchema.V2GetAccountRateLimitsResponse,
"feedback/upload": CodexSchema.V2FeedbackUploadResponse,
"command/exec": CodexSchema.V2CommandExecResponse,
"command/exec/write": CodexSchema.V2CommandExecWriteResponse,
"command/exec/terminate": CodexSchema.V2CommandExecTerminateResponse,
"command/exec/resize": CodexSchema.V2CommandExecResizeResponse,
"config/read": CodexSchema.V2ConfigReadResponse,
"externalAgentConfig/detect": CodexSchema.V2ExternalAgentConfigDetectResponse,
"externalAgentConfig/import": CodexSchema.V2ExternalAgentConfigImportResponse,
"config/value/write": CodexSchema.V2ConfigWriteResponse,
"config/batchWrite": CodexSchema.V2ConfigWriteResponse,
"configRequirements/read": CodexSchema.V2ConfigRequirementsReadResponse,
"account/read": CodexSchema.V2GetAccountResponse,
getConversationSummary: CodexSchema.GetConversationSummaryResponse,
gitDiffToRemote: CodexSchema.GitDiffToRemoteResponse,
getAuthStatus: CodexSchema.GetAuthStatusResponse,
fuzzyFileSearch: CodexSchema.FuzzyFileSearchResponse,
} as const;
export const CLIENT_NOTIFICATION_PARAMS = {
initialized: undefined,
} as const;
export const SERVER_REQUEST_PARAMS = {
"item/commandExecution/requestApproval": CodexSchema.CommandExecutionRequestApprovalParams,
"item/fileChange/requestApproval": CodexSchema.FileChangeRequestApprovalParams,
"item/tool/requestUserInput": CodexSchema.ToolRequestUserInputParams,
"mcpServer/elicitation/request": CodexSchema.McpServerElicitationRequestParams,
"item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalParams,
"item/tool/call": CodexSchema.DynamicToolCallParams,
"account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshParams,
applyPatchApproval: CodexSchema.ApplyPatchApprovalParams,
execCommandApproval: CodexSchema.ExecCommandApprovalParams,
} as const;
export const SERVER_REQUEST_RESPONSES = {
"item/commandExecution/requestApproval": CodexSchema.CommandExecutionRequestApprovalResponse,
"item/fileChange/requestApproval": CodexSchema.FileChangeRequestApprovalResponse,
"item/tool/requestUserInput": CodexSchema.ToolRequestUserInputResponse,
"mcpServer/elicitation/request": CodexSchema.McpServerElicitationRequestResponse,
"item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalResponse,
"item/tool/call": CodexSchema.DynamicToolCallResponse,
"account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshResponse,
applyPatchApproval: CodexSchema.ApplyPatchApprovalResponse,
execCommandApproval: CodexSchema.ExecCommandApprovalResponse,
} as const;
export const SERVER_NOTIFICATION_PARAMS = {
error: CodexSchema.V2ErrorNotification,
"thread/started": CodexSchema.V2ThreadStartedNotification,
"thread/status/changed": CodexSchema.V2ThreadStatusChangedNotification,
"thread/archived": CodexSchema.V2ThreadArchivedNotification,
"thread/unarchived": CodexSchema.V2ThreadUnarchivedNotification,
"thread/closed": CodexSchema.V2ThreadClosedNotification,
"skills/changed": CodexSchema.V2SkillsChangedNotification,
"thread/name/updated": CodexSchema.V2ThreadNameUpdatedNotification,
"thread/tokenUsage/updated": CodexSchema.V2ThreadTokenUsageUpdatedNotification,
"turn/started": CodexSchema.V2TurnStartedNotification,
"hook/started": CodexSchema.V2HookStartedNotification,
"turn/completed": CodexSchema.V2TurnCompletedNotification,
"hook/completed": CodexSchema.V2HookCompletedNotification,
"turn/diff/updated": CodexSchema.V2TurnDiffUpdatedNotification,
"turn/plan/updated": CodexSchema.V2TurnPlanUpdatedNotification,
"item/started": CodexSchema.V2ItemStartedNotification,
"item/autoApprovalReview/started": CodexSchema.V2ItemGuardianApprovalReviewStartedNotification,
"item/autoApprovalReview/completed":
CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification,
"item/completed": CodexSchema.V2ItemCompletedNotification,
"rawResponseItem/completed": CodexSchema.V2RawResponseItemCompletedNotification,
"item/agentMessage/delta": CodexSchema.V2AgentMessageDeltaNotification,
"item/plan/delta": CodexSchema.V2PlanDeltaNotification,
"command/exec/outputDelta": CodexSchema.V2CommandExecOutputDeltaNotification,
"item/commandExecution/outputDelta": CodexSchema.V2CommandExecutionOutputDeltaNotification,
"item/commandExecution/terminalInteraction": CodexSchema.V2TerminalInteractionNotification,
"item/fileChange/outputDelta": CodexSchema.V2FileChangeOutputDeltaNotification,
"serverRequest/resolved": CodexSchema.V2ServerRequestResolvedNotification,
"item/mcpToolCall/progress": CodexSchema.V2McpToolCallProgressNotification,
"mcpServer/oauthLogin/completed": CodexSchema.V2McpServerOauthLoginCompletedNotification,
"mcpServer/startupStatus/updated": CodexSchema.V2McpServerStatusUpdatedNotification,
"account/updated": CodexSchema.V2AccountUpdatedNotification,
"account/rateLimits/updated": CodexSchema.V2AccountRateLimitsUpdatedNotification,
"app/list/updated": CodexSchema.V2AppListUpdatedNotification,
"fs/changed": CodexSchema.V2FsChangedNotification,
"item/reasoning/summaryTextDelta": CodexSchema.V2ReasoningSummaryTextDeltaNotification,
"item/reasoning/summaryPartAdded": CodexSchema.V2ReasoningSummaryPartAddedNotification,
"item/reasoning/textDelta": CodexSchema.V2ReasoningTextDeltaNotification,
"thread/compacted": CodexSchema.V2ContextCompactedNotification,
"model/rerouted": CodexSchema.V2ModelReroutedNotification,
deprecationNotice: CodexSchema.V2DeprecationNoticeNotification,
configWarning: CodexSchema.V2ConfigWarningNotification,
"fuzzyFileSearch/sessionUpdated": CodexSchema.FuzzyFileSearchSessionUpdatedNotification,
"fuzzyFileSearch/sessionCompleted": CodexSchema.FuzzyFileSearchSessionCompletedNotification,
"thread/realtime/started": CodexSchema.V2ThreadRealtimeStartedNotification,
"thread/realtime/itemAdded": CodexSchema.V2ThreadRealtimeItemAddedNotification,
"thread/realtime/transcriptUpdated": CodexSchema.V2ThreadRealtimeTranscriptUpdatedNotification,
"thread/realtime/outputAudio/delta": CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification,
"thread/realtime/sdp": CodexSchema.V2ThreadRealtimeSdpNotification,
"thread/realtime/error": CodexSchema.V2ThreadRealtimeErrorNotification,
"thread/realtime/closed": CodexSchema.V2ThreadRealtimeClosedNotification,
"windows/worldWritableWarning": CodexSchema.V2WindowsWorldWritableWarningNotification,
"windowsSandbox/setupCompleted": CodexSchema.V2WindowsSandboxSetupCompletedNotification,
"account/login/completed": CodexSchema.V2AccountLoginCompletedNotification,
} as const;
@@ -0,0 +1,180 @@
// This file is generated by the effect-codex-app-server package. Do not edit manually.
// Upstream protocol ref: dbfe855f4fd0f5dcdf079882652a8efe622b0595
import * as CodexSchema from "./schema.gen.ts";
export const v1 = {
InitializeParams: CodexSchema.V1InitializeParams,
InitializeResponse: CodexSchema.V1InitializeResponse,
} as const;
export const v2 = {
AccountLoginCompletedNotification: CodexSchema.V2AccountLoginCompletedNotification,
AccountRateLimitsUpdatedNotification: CodexSchema.V2AccountRateLimitsUpdatedNotification,
AccountUpdatedNotification: CodexSchema.V2AccountUpdatedNotification,
AgentMessageDeltaNotification: CodexSchema.V2AgentMessageDeltaNotification,
AppListUpdatedNotification: CodexSchema.V2AppListUpdatedNotification,
AppsListParams: CodexSchema.V2AppsListParams,
AppsListResponse: CodexSchema.V2AppsListResponse,
CancelLoginAccountParams: CodexSchema.V2CancelLoginAccountParams,
CancelLoginAccountResponse: CodexSchema.V2CancelLoginAccountResponse,
CommandExecOutputDeltaNotification: CodexSchema.V2CommandExecOutputDeltaNotification,
CommandExecParams: CodexSchema.V2CommandExecParams,
CommandExecResizeParams: CodexSchema.V2CommandExecResizeParams,
CommandExecResizeResponse: CodexSchema.V2CommandExecResizeResponse,
CommandExecResponse: CodexSchema.V2CommandExecResponse,
CommandExecTerminateParams: CodexSchema.V2CommandExecTerminateParams,
CommandExecTerminateResponse: CodexSchema.V2CommandExecTerminateResponse,
CommandExecutionOutputDeltaNotification: CodexSchema.V2CommandExecutionOutputDeltaNotification,
CommandExecWriteParams: CodexSchema.V2CommandExecWriteParams,
CommandExecWriteResponse: CodexSchema.V2CommandExecWriteResponse,
ConfigBatchWriteParams: CodexSchema.V2ConfigBatchWriteParams,
ConfigReadParams: CodexSchema.V2ConfigReadParams,
ConfigReadResponse: CodexSchema.V2ConfigReadResponse,
ConfigRequirementsReadResponse: CodexSchema.V2ConfigRequirementsReadResponse,
ConfigValueWriteParams: CodexSchema.V2ConfigValueWriteParams,
ConfigWarningNotification: CodexSchema.V2ConfigWarningNotification,
ConfigWriteResponse: CodexSchema.V2ConfigWriteResponse,
ContextCompactedNotification: CodexSchema.V2ContextCompactedNotification,
DeprecationNoticeNotification: CodexSchema.V2DeprecationNoticeNotification,
ErrorNotification: CodexSchema.V2ErrorNotification,
ExperimentalFeatureEnablementSetParams: CodexSchema.V2ExperimentalFeatureEnablementSetParams,
ExperimentalFeatureEnablementSetResponse: CodexSchema.V2ExperimentalFeatureEnablementSetResponse,
ExperimentalFeatureListParams: CodexSchema.V2ExperimentalFeatureListParams,
ExperimentalFeatureListResponse: CodexSchema.V2ExperimentalFeatureListResponse,
ExternalAgentConfigDetectParams: CodexSchema.V2ExternalAgentConfigDetectParams,
ExternalAgentConfigDetectResponse: CodexSchema.V2ExternalAgentConfigDetectResponse,
ExternalAgentConfigImportParams: CodexSchema.V2ExternalAgentConfigImportParams,
ExternalAgentConfigImportResponse: CodexSchema.V2ExternalAgentConfigImportResponse,
FeedbackUploadParams: CodexSchema.V2FeedbackUploadParams,
FeedbackUploadResponse: CodexSchema.V2FeedbackUploadResponse,
FileChangeOutputDeltaNotification: CodexSchema.V2FileChangeOutputDeltaNotification,
FsChangedNotification: CodexSchema.V2FsChangedNotification,
FsCopyParams: CodexSchema.V2FsCopyParams,
FsCopyResponse: CodexSchema.V2FsCopyResponse,
FsCreateDirectoryParams: CodexSchema.V2FsCreateDirectoryParams,
FsCreateDirectoryResponse: CodexSchema.V2FsCreateDirectoryResponse,
FsGetMetadataParams: CodexSchema.V2FsGetMetadataParams,
FsGetMetadataResponse: CodexSchema.V2FsGetMetadataResponse,
FsReadDirectoryParams: CodexSchema.V2FsReadDirectoryParams,
FsReadDirectoryResponse: CodexSchema.V2FsReadDirectoryResponse,
FsReadFileParams: CodexSchema.V2FsReadFileParams,
FsReadFileResponse: CodexSchema.V2FsReadFileResponse,
FsRemoveParams: CodexSchema.V2FsRemoveParams,
FsRemoveResponse: CodexSchema.V2FsRemoveResponse,
FsUnwatchParams: CodexSchema.V2FsUnwatchParams,
FsUnwatchResponse: CodexSchema.V2FsUnwatchResponse,
FsWatchParams: CodexSchema.V2FsWatchParams,
FsWatchResponse: CodexSchema.V2FsWatchResponse,
FsWriteFileParams: CodexSchema.V2FsWriteFileParams,
FsWriteFileResponse: CodexSchema.V2FsWriteFileResponse,
GetAccountParams: CodexSchema.V2GetAccountParams,
GetAccountRateLimitsResponse: CodexSchema.V2GetAccountRateLimitsResponse,
GetAccountResponse: CodexSchema.V2GetAccountResponse,
HookCompletedNotification: CodexSchema.V2HookCompletedNotification,
HookStartedNotification: CodexSchema.V2HookStartedNotification,
ItemCompletedNotification: CodexSchema.V2ItemCompletedNotification,
ItemGuardianApprovalReviewCompletedNotification:
CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification,
ItemGuardianApprovalReviewStartedNotification:
CodexSchema.V2ItemGuardianApprovalReviewStartedNotification,
ItemStartedNotification: CodexSchema.V2ItemStartedNotification,
ListMcpServerStatusParams: CodexSchema.V2ListMcpServerStatusParams,
ListMcpServerStatusResponse: CodexSchema.V2ListMcpServerStatusResponse,
LoginAccountParams: CodexSchema.V2LoginAccountParams,
LoginAccountResponse: CodexSchema.V2LoginAccountResponse,
LogoutAccountResponse: CodexSchema.V2LogoutAccountResponse,
McpResourceReadParams: CodexSchema.V2McpResourceReadParams,
McpResourceReadResponse: CodexSchema.V2McpResourceReadResponse,
McpServerOauthLoginCompletedNotification: CodexSchema.V2McpServerOauthLoginCompletedNotification,
McpServerOauthLoginParams: CodexSchema.V2McpServerOauthLoginParams,
McpServerOauthLoginResponse: CodexSchema.V2McpServerOauthLoginResponse,
McpServerRefreshResponse: CodexSchema.V2McpServerRefreshResponse,
McpServerStatusUpdatedNotification: CodexSchema.V2McpServerStatusUpdatedNotification,
McpServerToolCallParams: CodexSchema.V2McpServerToolCallParams,
McpServerToolCallResponse: CodexSchema.V2McpServerToolCallResponse,
McpToolCallProgressNotification: CodexSchema.V2McpToolCallProgressNotification,
ModelListParams: CodexSchema.V2ModelListParams,
ModelListResponse: CodexSchema.V2ModelListResponse,
ModelReroutedNotification: CodexSchema.V2ModelReroutedNotification,
PlanDeltaNotification: CodexSchema.V2PlanDeltaNotification,
PluginInstallParams: CodexSchema.V2PluginInstallParams,
PluginInstallResponse: CodexSchema.V2PluginInstallResponse,
PluginListParams: CodexSchema.V2PluginListParams,
PluginListResponse: CodexSchema.V2PluginListResponse,
PluginReadParams: CodexSchema.V2PluginReadParams,
PluginReadResponse: CodexSchema.V2PluginReadResponse,
PluginUninstallParams: CodexSchema.V2PluginUninstallParams,
PluginUninstallResponse: CodexSchema.V2PluginUninstallResponse,
RawResponseItemCompletedNotification: CodexSchema.V2RawResponseItemCompletedNotification,
ReasoningSummaryPartAddedNotification: CodexSchema.V2ReasoningSummaryPartAddedNotification,
ReasoningSummaryTextDeltaNotification: CodexSchema.V2ReasoningSummaryTextDeltaNotification,
ReasoningTextDeltaNotification: CodexSchema.V2ReasoningTextDeltaNotification,
ReviewStartParams: CodexSchema.V2ReviewStartParams,
ReviewStartResponse: CodexSchema.V2ReviewStartResponse,
ServerRequestResolvedNotification: CodexSchema.V2ServerRequestResolvedNotification,
SkillsChangedNotification: CodexSchema.V2SkillsChangedNotification,
SkillsConfigWriteParams: CodexSchema.V2SkillsConfigWriteParams,
SkillsConfigWriteResponse: CodexSchema.V2SkillsConfigWriteResponse,
SkillsListParams: CodexSchema.V2SkillsListParams,
SkillsListResponse: CodexSchema.V2SkillsListResponse,
TerminalInteractionNotification: CodexSchema.V2TerminalInteractionNotification,
ThreadArchivedNotification: CodexSchema.V2ThreadArchivedNotification,
ThreadArchiveParams: CodexSchema.V2ThreadArchiveParams,
ThreadArchiveResponse: CodexSchema.V2ThreadArchiveResponse,
ThreadClosedNotification: CodexSchema.V2ThreadClosedNotification,
ThreadCompactStartParams: CodexSchema.V2ThreadCompactStartParams,
ThreadCompactStartResponse: CodexSchema.V2ThreadCompactStartResponse,
ThreadForkParams: CodexSchema.V2ThreadForkParams,
ThreadForkResponse: CodexSchema.V2ThreadForkResponse,
ThreadListParams: CodexSchema.V2ThreadListParams,
ThreadListResponse: CodexSchema.V2ThreadListResponse,
ThreadLoadedListParams: CodexSchema.V2ThreadLoadedListParams,
ThreadLoadedListResponse: CodexSchema.V2ThreadLoadedListResponse,
ThreadMetadataUpdateParams: CodexSchema.V2ThreadMetadataUpdateParams,
ThreadMetadataUpdateResponse: CodexSchema.V2ThreadMetadataUpdateResponse,
ThreadNameUpdatedNotification: CodexSchema.V2ThreadNameUpdatedNotification,
ThreadReadParams: CodexSchema.V2ThreadReadParams,
ThreadReadResponse: CodexSchema.V2ThreadReadResponse,
ThreadRealtimeClosedNotification: CodexSchema.V2ThreadRealtimeClosedNotification,
ThreadRealtimeErrorNotification: CodexSchema.V2ThreadRealtimeErrorNotification,
ThreadRealtimeItemAddedNotification: CodexSchema.V2ThreadRealtimeItemAddedNotification,
ThreadRealtimeOutputAudioDeltaNotification:
CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification,
ThreadRealtimeSdpNotification: CodexSchema.V2ThreadRealtimeSdpNotification,
ThreadRealtimeStartedNotification: CodexSchema.V2ThreadRealtimeStartedNotification,
ThreadRealtimeTranscriptUpdatedNotification:
CodexSchema.V2ThreadRealtimeTranscriptUpdatedNotification,
ThreadResumeParams: CodexSchema.V2ThreadResumeParams,
ThreadResumeResponse: CodexSchema.V2ThreadResumeResponse,
ThreadRollbackParams: CodexSchema.V2ThreadRollbackParams,
ThreadRollbackResponse: CodexSchema.V2ThreadRollbackResponse,
ThreadSetNameParams: CodexSchema.V2ThreadSetNameParams,
ThreadSetNameResponse: CodexSchema.V2ThreadSetNameResponse,
ThreadShellCommandParams: CodexSchema.V2ThreadShellCommandParams,
ThreadShellCommandResponse: CodexSchema.V2ThreadShellCommandResponse,
ThreadStartedNotification: CodexSchema.V2ThreadStartedNotification,
ThreadStartParams: CodexSchema.V2ThreadStartParams,
ThreadStartResponse: CodexSchema.V2ThreadStartResponse,
ThreadStatusChangedNotification: CodexSchema.V2ThreadStatusChangedNotification,
ThreadTokenUsageUpdatedNotification: CodexSchema.V2ThreadTokenUsageUpdatedNotification,
ThreadUnarchivedNotification: CodexSchema.V2ThreadUnarchivedNotification,
ThreadUnarchiveParams: CodexSchema.V2ThreadUnarchiveParams,
ThreadUnarchiveResponse: CodexSchema.V2ThreadUnarchiveResponse,
ThreadUnsubscribeParams: CodexSchema.V2ThreadUnsubscribeParams,
ThreadUnsubscribeResponse: CodexSchema.V2ThreadUnsubscribeResponse,
TurnCompletedNotification: CodexSchema.V2TurnCompletedNotification,
TurnDiffUpdatedNotification: CodexSchema.V2TurnDiffUpdatedNotification,
TurnInterruptParams: CodexSchema.V2TurnInterruptParams,
TurnInterruptResponse: CodexSchema.V2TurnInterruptResponse,
TurnPlanUpdatedNotification: CodexSchema.V2TurnPlanUpdatedNotification,
TurnStartedNotification: CodexSchema.V2TurnStartedNotification,
TurnStartParams: CodexSchema.V2TurnStartParams,
TurnStartResponse: CodexSchema.V2TurnStartResponse,
TurnSteerParams: CodexSchema.V2TurnSteerParams,
TurnSteerResponse: CodexSchema.V2TurnSteerResponse,
WindowsSandboxSetupCompletedNotification: CodexSchema.V2WindowsSandboxSetupCompletedNotification,
WindowsSandboxSetupStartParams: CodexSchema.V2WindowsSandboxSetupStartParams,
WindowsSandboxSetupStartResponse: CodexSchema.V2WindowsSandboxSetupStartResponse,
WindowsWorldWritableWarningNotification: CodexSchema.V2WindowsWorldWritableWarningNotification,
} as const;
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,101 @@
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as SchemaIssue from "effect/SchemaIssue";
import * as CodexError from "../errors.ts";
const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
export const JsonRpcId = Schema.Union([Schema.Number, Schema.String]);
export const JsonRpcError = Schema.Struct({
code: Schema.Number,
message: Schema.String,
data: Schema.optional(Schema.Unknown),
});
export const JsonRpcResponseEnvelope = Schema.Struct({
id: JsonRpcId,
result: Schema.optional(Schema.Unknown),
error: Schema.optional(JsonRpcError),
});
export const decodeOptionalPayload = <A, I>(
method: string,
schema: Schema.Codec<A, I> | undefined,
raw: unknown,
): Effect.Effect<A, CodexError.CodexAppServerRequestError> => {
if (!schema) {
if (raw === undefined) {
return Effect.sync(() => undefined as A);
}
return Effect.fail(
CodexError.CodexAppServerRequestError.invalidParams(`${method} does not accept params`, raw),
);
}
return Schema.decodeUnknownEffect(schema)(raw).pipe(
Effect.mapError((error) =>
CodexError.CodexAppServerRequestError.invalidParams(
`Invalid ${method} payload: ${formatSchemaIssue(error.issue)}`,
{ issue: error.issue },
),
),
);
};
export const encodeOptionalPayload = <A, I>(
method: string,
schema: Schema.Codec<A, I> | undefined,
payload: A,
): Effect.Effect<I | undefined, CodexError.CodexAppServerRequestError> => {
if (!schema) {
if (payload === undefined) {
return Effect.sync(() => undefined);
}
return Effect.fail(
CodexError.CodexAppServerRequestError.invalidParams(
`${method} does not accept params`,
payload,
),
);
}
return Schema.encodeEffect(schema)(payload).pipe(
Effect.mapError((error) =>
CodexError.CodexAppServerRequestError.invalidParams(
`Invalid ${method} payload: ${formatSchemaIssue(error.issue)}`,
{ issue: error.issue },
),
),
);
};
export const decodeNotificationPayload = <A, I>(
method: string,
schema: Schema.Codec<A, I> | undefined,
raw: unknown,
): Effect.Effect<A, CodexError.CodexAppServerProtocolParseError> =>
decodeOptionalPayload(method, schema, raw).pipe(
Effect.mapError(
(error) =>
new CodexError.CodexAppServerProtocolParseError({
detail: error.message,
cause: error,
}),
),
);
export const runHandler = Effect.fnUntraced(function* <A, B>(
handler: ((payload: A) => Effect.Effect<B, CodexError.CodexAppServerError>) | undefined,
payload: A,
method: string,
) {
if (!handler) {
return yield* CodexError.CodexAppServerRequestError.methodNotFound(method);
}
return yield* handler(payload).pipe(
Effect.mapError((error) => CodexError.normalizeToRequestError(error)),
);
});
@@ -0,0 +1,57 @@
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Queue from "effect/Queue";
import * as Sink from "effect/Sink";
import * as Stdio from "effect/Stdio";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as CodexError from "../errors.ts";
const encoder = new TextEncoder();
export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =>
Stdio.make({
args: Effect.succeed([]),
stdin: handle.stdout,
stdout: () =>
Sink.mapInput(handle.stdin, (chunk: string | Uint8Array) =>
typeof chunk === "string" ? encoder.encode(chunk) : chunk,
),
stderr: () => Sink.drain,
});
export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {
const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();
const output = yield* Queue.unbounded<string>();
const decoder = new TextDecoder();
return {
stdio: Stdio.make({
args: Effect.succeed([]),
stdin: Stream.fromQueue(input),
stdout: () =>
Sink.forEach((chunk: string | Uint8Array) =>
Queue.offer(
output,
typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true }),
),
),
stderr: () => Sink.drain,
}),
input,
output,
};
});
export const makeTerminationError = (
handle: ChildProcessSpawner.ChildProcessHandle,
): Effect.Effect<CodexError.CodexAppServerError> =>
Effect.match(handle.exitCode, {
onFailure: (cause) =>
new CodexError.CodexAppServerTransportError({
detail: "Failed to determine Codex App Server process exit status",
cause,
}),
onSuccess: (code) => new CodexError.CodexAppServerProcessExitedError({ code }),
});
@@ -0,0 +1,154 @@
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Effect from "effect/Effect";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as CodexClient from "./client.ts";
const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
path.join(import.meta.dirname, "../test/fixtures/codex-app-server-mock-peer.ts"),
);
it.layer(NodeServices.layer)("effect-codex-app-server client", (it) => {
const makeHandle = () =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const path = yield* Path.Path;
const command = ChildProcess.make("bun", ["run", yield* mockPeerPath], {
cwd: path.join(import.meta.dirname, ".."),
shell: process.platform === "win32",
});
return yield* spawner.spawn(command);
});
it.effect("initializes, handles typed server requests, and reads account and skills data", () =>
Effect.gen(function* () {
const userInputRequests = yield* Ref.make<Array<unknown>>([]);
const messageDeltas = yield* Ref.make<Array<unknown>>([]);
const handle = yield* makeHandle();
const scope = yield* Scope.make();
const clientLayer = CodexClient.layerChildProcess(handle);
const context = yield* Layer.buildWithScope(clientLayer, scope);
const result = yield* Effect.gen(function* () {
const client = yield* CodexClient.CodexAppServerClient;
yield* client.handleServerRequest("item/tool/requestUserInput", (payload) =>
Ref.update(userInputRequests, (current) => [...current, payload]).pipe(
Effect.as({
answers: {
approved: {
answers: ["yes"],
},
},
}),
),
);
yield* client.handleServerNotification("item/agentMessage/delta", (payload) =>
Ref.update(messageDeltas, (current) => [...current, payload]),
);
const initialized = 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,
},
});
assert.equal(initialized.userAgent, "mock-codex-app-server");
yield* client.notify("initialized", undefined);
const account = yield* client.request("account/read", {});
assert.equal(account.requiresOpenaiAuth, false);
assert.deepEqual(account.account, {
type: "chatgpt",
email: "[email protected]",
planType: "plus",
});
const skills = yield* client.request("skills/list", {
cwds: [process.cwd()],
});
assert.equal(skills.data.length, 1);
assert.equal(skills.data[0]?.cwd, process.cwd());
return {
account,
skills,
};
}).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
assert.equal(result.skills.data[0]?.skills.length, 0);
assert.deepEqual(yield* Ref.get(userInputRequests), [
{
itemId: "item-approval-1",
threadId: "thread-1",
turnId: "turn-1",
questions: [
{
id: "approved",
header: "Approve",
question: "Continue with the mock skills request?",
options: [
{
label: "yes",
description: "Approve the request",
},
],
},
],
},
]);
assert.deepEqual(yield* Ref.get(messageDeltas), [
{
delta: "Mock server is ready.",
itemId: "item-1",
threadId: "thread-1",
turnId: "turn-1",
},
]);
}),
);
it.effect("initializes a command-backed app-server client", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const scope = yield* Scope.make();
const clientLayer = CodexClient.layerCommand({
command: "bun",
args: ["run", yield* mockPeerPath],
cwd: path.join(import.meta.dirname, ".."),
});
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.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
assert.equal(initialized.userAgent, "mock-codex-app-server");
}),
);
});
@@ -0,0 +1,300 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
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 { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as CodexRpc from "./_generated/meta.gen.ts";
import * as CodexError from "./errors.ts";
import * as CodexProtocol from "./protocol.ts";
import {
decodeNotificationPayload,
decodeOptionalPayload,
encodeOptionalPayload,
runHandler,
} from "./_internal/shared.ts";
import { makeChildStdio, makeTerminationError } from "./_internal/stdio.ts";
export interface CodexAppServerClientOptions {
readonly logIncoming?: boolean;
readonly logOutgoing?: boolean;
readonly logger?: (
event: CodexProtocol.CodexAppServerProtocolLogEvent,
) => Effect.Effect<void, never>;
}
interface CodexAppServerClientRaw {
readonly notifications: CodexProtocol.CodexAppServerPatchedProtocol["incomingNotifications"];
readonly requests: CodexProtocol.CodexAppServerPatchedProtocol["incomingRequests"];
readonly request: CodexProtocol.CodexAppServerPatchedProtocol["request"];
readonly notify: CodexProtocol.CodexAppServerPatchedProtocol["notify"];
readonly respond: CodexProtocol.CodexAppServerPatchedProtocol["respond"];
readonly respondError: CodexProtocol.CodexAppServerPatchedProtocol["respondError"];
}
export interface CodexAppServerClientShape {
readonly raw: CodexAppServerClientRaw;
readonly request: <M extends CodexRpc.ClientRequestMethod>(
method: M,
payload: CodexRpc.ClientRequestParamsByMethod[M],
) => Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError>;
readonly notify: <M extends CodexRpc.ClientNotificationMethod>(
method: M,
payload: CodexRpc.ClientNotificationParamsByMethod[M],
) => Effect.Effect<void, CodexError.CodexAppServerError>;
readonly handleServerRequest: <M extends CodexRpc.ServerRequestMethod>(
method: M,
handler: (
payload: CodexRpc.ServerRequestParamsByMethod[M],
) => Effect.Effect<CodexRpc.ServerRequestResponsesByMethod[M], CodexError.CodexAppServerError>,
) => Effect.Effect<void>;
readonly handleServerNotification: <M extends CodexRpc.ServerNotificationMethod>(
method: M,
handler: (
payload: CodexRpc.ServerNotificationParamsByMethod[M],
) => Effect.Effect<void, CodexError.CodexAppServerError>,
) => Effect.Effect<void>;
readonly handleUnknownServerRequest: (
handler: (
method: string,
params: unknown,
) => Effect.Effect<unknown, CodexError.CodexAppServerError>,
) => Effect.Effect<void>;
readonly handleUnknownServerNotification: (
handler: (
method: string,
params: unknown,
) => Effect.Effect<void, CodexError.CodexAppServerError>,
) => Effect.Effect<void>;
}
export class CodexAppServerClient extends Context.Service<
CodexAppServerClient,
CodexAppServerClientShape
>()("effect-codex-app-server/CodexAppServerClient") {}
type ServerRequestHandler = (
payload: unknown,
) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
type ServerNotificationHandler = (
payload: unknown,
) => Effect.Effect<void, CodexError.CodexAppServerError>;
export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make")(function* (
stdio: Stdio.Stdio,
options: CodexAppServerClientOptions = {},
terminationError?: Effect.Effect<CodexError.CodexAppServerError>,
): Effect.fn.Return<CodexAppServerClientShape, never, Scope.Scope> {
const requestHandlers = new Map<string, ServerRequestHandler>();
const notificationHandlers = new Map<string, Array<ServerNotificationHandler>>();
let unknownRequestHandler:
| ((method: string, params: unknown) => Effect.Effect<unknown, CodexError.CodexAppServerError>)
| undefined;
let unknownNotificationHandler:
| ((method: string, params: unknown) => Effect.Effect<void, CodexError.CodexAppServerError>)
| undefined;
const getServerRequestParamSchema = <M extends CodexRpc.ServerRequestMethod>(
method: M,
):
| Schema.Codec<CodexRpc.ServerRequestParamsByMethod[M], CodexRpc.ServerRequestParamsByMethod[M]>
| undefined => CodexRpc.SERVER_REQUEST_PARAMS[method] as never;
const getServerRequestResponseSchema = <M extends CodexRpc.ServerRequestMethod>(
method: M,
):
| Schema.Codec<
CodexRpc.ServerRequestResponsesByMethod[M],
CodexRpc.ServerRequestResponsesByMethod[M]
>
| undefined => CodexRpc.SERVER_REQUEST_RESPONSES[method] as never;
const getClientRequestParamSchema = <M extends CodexRpc.ClientRequestMethod>(
method: M,
):
| Schema.Codec<CodexRpc.ClientRequestParamsByMethod[M], CodexRpc.ClientRequestParamsByMethod[M]>
| undefined => CodexRpc.CLIENT_REQUEST_PARAMS[method] as never;
const getClientRequestResponseSchema = <M extends CodexRpc.ClientRequestMethod>(
method: M,
):
| Schema.Codec<
CodexRpc.ClientRequestResponsesByMethod[M],
CodexRpc.ClientRequestResponsesByMethod[M]
>
| undefined => CodexRpc.CLIENT_REQUEST_RESPONSES[method] as never;
const getClientNotificationParamSchema = <M extends CodexRpc.ClientNotificationMethod>(
method: M,
):
| Schema.Codec<
CodexRpc.ClientNotificationParamsByMethod[M],
CodexRpc.ClientNotificationParamsByMethod[M]
>
| undefined => CodexRpc.CLIENT_NOTIFICATION_PARAMS[method] as never;
const dispatchNotification = (
notification: CodexProtocol.CodexAppServerIncomingNotification,
): Effect.Effect<void, never> => {
const schema =
notification.method in CodexRpc.SERVER_NOTIFICATION_PARAMS
? CodexRpc.SERVER_NOTIFICATION_PARAMS[
notification.method as CodexRpc.ServerNotificationMethod
]
: undefined;
const handlers = notificationHandlers.get(notification.method) ?? [];
if (schema) {
return decodeNotificationPayload(notification.method, schema, notification.params).pipe(
Effect.flatMap((decoded) =>
Effect.forEach(handlers, (handler) => handler(decoded), { discard: true }),
),
Effect.catch(() => Effect.void),
);
}
return unknownNotificationHandler
? unknownNotificationHandler(notification.method, notification.params).pipe(
Effect.catch(() => Effect.void),
)
: Effect.void;
};
const dispatchRequest = (
request: CodexProtocol.CodexAppServerIncomingRequest,
): Effect.Effect<unknown, CodexError.CodexAppServerError> => {
if (request.method in CodexRpc.SERVER_REQUEST_PARAMS) {
const method = request.method as CodexRpc.ServerRequestMethod;
const payloadSchema = getServerRequestParamSchema(method);
const responseSchema = getServerRequestResponseSchema(method);
const handler = requestHandlers.get(method);
return decodeOptionalPayload(method, payloadSchema, request.params).pipe(
Effect.flatMap((decoded) => runHandler(handler, decoded, method)),
Effect.flatMap((result) => encodeOptionalPayload(method, responseSchema, result)),
);
}
return unknownRequestHandler
? unknownRequestHandler(request.method, request.params)
: Effect.fail(CodexError.CodexAppServerRequestError.methodNotFound(request.method));
};
const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
stdio,
...(terminationError ? { terminationError } : {}),
...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),
...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),
...(options.logger ? { logger: options.logger } : {}),
onNotification: dispatchNotification,
onRequest: dispatchRequest,
});
const request = <M extends CodexRpc.ClientRequestMethod>(
method: M,
payload: CodexRpc.ClientRequestParamsByMethod[M],
): Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError> =>
encodeOptionalPayload(method, getClientRequestParamSchema(method), payload).pipe(
Effect.flatMap((encoded) => transport.request(method, encoded)),
Effect.flatMap(
(
raw,
): Effect.Effect<
CodexRpc.ClientRequestResponsesByMethod[M],
CodexError.CodexAppServerError
> => decodeOptionalPayload(method, getClientRequestResponseSchema(method), raw),
),
);
const notify = <M extends CodexRpc.ClientNotificationMethod>(
method: M,
payload: CodexRpc.ClientNotificationParamsByMethod[M],
) =>
encodeOptionalPayload(method, getClientNotificationParamSchema(method), payload).pipe(
Effect.flatMap((encoded) => transport.notify(method, encoded)),
);
return CodexAppServerClient.of({
raw: {
notifications: transport.incomingNotifications,
requests: transport.incomingRequests,
request: transport.request,
notify: transport.notify,
respond: transport.respond,
respondError: transport.respondError,
},
request,
notify,
handleServerRequest: (method, handler) =>
Effect.sync(() => {
requestHandlers.set(method, handler as ServerRequestHandler);
}),
handleServerNotification: (method, handler) =>
Effect.sync(() => {
const current = notificationHandlers.get(method) ?? [];
current.push(handler as ServerNotificationHandler);
notificationHandlers.set(method, current);
}),
handleUnknownServerRequest: (handler) =>
Effect.sync(() => {
unknownRequestHandler = handler;
}),
handleUnknownServerNotification: (handler) =>
Effect.sync(() => {
unknownNotificationHandler = handler;
}),
});
});
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));
};
export interface CodexAppServerCommandLayerOptions extends CodexAppServerClientOptions {
readonly command: string;
readonly args?: ReadonlyArray<string>;
readonly cwd?: string;
readonly env?: Record<string, string>;
}
export const layerCommand = (
options: CodexAppServerCommandLayerOptions,
): Layer.Layer<
CodexAppServerClient,
CodexError.CodexAppServerSpawnError,
ChildProcessSpawner.ChildProcessSpawner
> =>
Layer.effect(
CodexAppServerClient,
Effect.acquireRelease(
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const command = ChildProcess.make(options.command, [...(options.args ?? [])], {
...(options.cwd ? { cwd: options.cwd } : {}),
...(options.env ? { env: { ...process.env, ...options.env } } : {}),
shell: process.platform === "win32",
});
return yield* spawner.spawn(command).pipe(
Effect.mapError(
(cause) =>
new CodexError.CodexAppServerSpawnError({
command: [options.command, ...(options.args ?? [])].join(" "),
cause,
}),
),
);
}),
(handle) => handle.kill().pipe(Effect.orDie),
).pipe(
Effect.flatMap((handle) =>
make(makeChildStdio(handle), options, makeTerminationError(handle)),
),
),
);
@@ -0,0 +1,151 @@
import * as Schema from "effect/Schema";
export interface CodexAppServerProtocolErrorShape {
readonly code: number;
readonly message: string;
readonly data?: unknown;
}
export class CodexAppServerSpawnError extends Schema.TaggedErrorClass<CodexAppServerSpawnError>()(
"CodexAppServerSpawnError",
{
command: Schema.optional(Schema.String),
cause: Schema.Defect,
},
) {
override get message() {
return this.command
? `Failed to spawn Codex App Server process for command: ${this.command}`
: "Failed to spawn Codex App Server process";
}
}
export class CodexAppServerProcessExitedError extends Schema.TaggedErrorClass<CodexAppServerProcessExitedError>()(
"CodexAppServerProcessExitedError",
{
code: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect),
},
) {
override get message() {
return this.code === undefined
? "Codex App Server process exited"
: `Codex App Server process exited with code ${this.code}`;
}
}
export class CodexAppServerProtocolParseError extends Schema.TaggedErrorClass<CodexAppServerProtocolParseError>()(
"CodexAppServerProtocolParseError",
{
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message() {
return `Failed to parse Codex App Server protocol message: ${this.detail}`;
}
}
export class CodexAppServerTransportError extends Schema.TaggedErrorClass<CodexAppServerTransportError>()(
"CodexAppServerTransportError",
{
detail: Schema.String,
cause: Schema.Defect,
},
) {
override get message() {
return this.detail;
}
}
export class CodexAppServerRequestError extends Schema.TaggedErrorClass<CodexAppServerRequestError>()(
"CodexAppServerRequestError",
{
code: Schema.Number,
errorMessage: Schema.String,
data: Schema.optional(Schema.Unknown),
},
) {
override get message() {
return this.errorMessage;
}
static fromProtocolError(error: CodexAppServerProtocolErrorShape) {
return new CodexAppServerRequestError({
code: error.code,
errorMessage: error.message,
...(error.data !== undefined ? { data: error.data } : {}),
});
}
static parseError(message = "Parse error", data?: unknown) {
return new CodexAppServerRequestError({
code: -32700,
errorMessage: message,
...(data !== undefined ? { data } : {}),
});
}
static invalidRequest(message = "Invalid request", data?: unknown) {
return new CodexAppServerRequestError({
code: -32600,
errorMessage: message,
...(data !== undefined ? { data } : {}),
});
}
static methodNotFound(method: string) {
return new CodexAppServerRequestError({
code: -32601,
errorMessage: `Method not found: ${method}`,
});
}
static invalidParams(message = "Invalid params", data?: unknown) {
return new CodexAppServerRequestError({
code: -32602,
errorMessage: message,
...(data !== undefined ? { data } : {}),
});
}
static internalError(message = "Internal error", data?: unknown) {
return new CodexAppServerRequestError({
code: -32603,
errorMessage: message,
...(data !== undefined ? { data } : {}),
});
}
static overloaded(message = "Server overloaded; retry later.", data?: unknown) {
return new CodexAppServerRequestError({
code: -32001,
errorMessage: message,
...(data !== undefined ? { data } : {}),
});
}
toProtocolError(): CodexAppServerProtocolErrorShape {
return {
code: this.code,
message: this.errorMessage,
...(this.data !== undefined ? { data: this.data } : {}),
};
}
}
export const CodexAppServerError = Schema.Union([
CodexAppServerRequestError,
CodexAppServerSpawnError,
CodexAppServerProcessExitedError,
CodexAppServerProtocolParseError,
CodexAppServerTransportError,
]);
export type CodexAppServerError = typeof CodexAppServerError.Type;
export function normalizeToRequestError(error: CodexAppServerError): CodexAppServerRequestError {
return Schema.is(CodexAppServerRequestError)(error)
? error
: CodexAppServerRequestError.internalError(error.message);
}
@@ -0,0 +1,197 @@
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as CodexError from "./errors.ts";
import * as CodexProtocol from "./protocol.ts";
import { makeInMemoryStdio } from "./_internal/stdio.ts";
const encoder = new TextEncoder();
const encodeJsonl = (value: unknown) => encoder.encode(`${JSON.stringify(value)}\n`);
it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
it.effect(
"encodes requests without a jsonrpc field and routes inbound requests and notifications",
() =>
Effect.gen(function* () {
const { stdio, input, output } = yield* makeInMemoryStdio();
const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
const notificationDeferred =
yield* Deferred.make<ReadonlyArray<CodexProtocol.CodexAppServerIncomingNotification>>();
const requestDeferred =
yield* Deferred.make<ReadonlyArray<CodexProtocol.CodexAppServerIncomingRequest>>();
yield* transport.incomingNotifications.pipe(
Stream.take(1),
Stream.runCollect,
Effect.flatMap((notifications) => Deferred.succeed(notificationDeferred, notifications)),
Effect.forkScoped,
);
yield* transport.incomingRequests.pipe(
Stream.take(1),
Stream.runCollect,
Effect.flatMap((requests) => Deferred.succeed(requestDeferred, requests)),
Effect.forkScoped,
);
yield* transport.notify("initialized");
assert.equal(yield* Queue.take(output), '{"method":"initialized"}\n');
const initializeParams = {
clientInfo: {
name: "effect-codex-app-server-test",
title: "Effect Codex App Server Test",
version: "0.0.0",
},
capabilities: {
experimentalApi: true,
optOutNotificationMethods: null,
},
};
const pendingInitialize = yield* transport
.request("initialize", initializeParams)
.pipe(Effect.forkScoped);
assert.deepEqual(JSON.parse(yield* Queue.take(output)), {
id: 1,
method: "initialize",
params: initializeParams,
});
yield* Queue.offer(
input,
encodeJsonl({
method: "item/agentMessage/delta",
params: {
delta: "Hello from the mock peer.",
itemId: "item-1",
threadId: "thread-1",
turnId: "turn-1",
},
}),
);
yield* Queue.offer(
input,
encodeJsonl({
id: 77,
method: "item/tool/requestUserInput",
params: {
itemId: "item-approval-1",
threadId: "thread-1",
turnId: "turn-1",
questions: [
{
id: "approved",
header: "Approve",
question: "Continue?",
},
],
},
}),
);
yield* Queue.offer(
input,
encodeJsonl({
id: 1,
result: {
userAgent: "mock-codex-app-server",
codexHome: "/tmp/codex-home",
platformFamily: "unix",
platformOs: "macos",
},
}),
);
assert.deepEqual(yield* Fiber.join(pendingInitialize), {
userAgent: "mock-codex-app-server",
codexHome: "/tmp/codex-home",
platformFamily: "unix",
platformOs: "macos",
});
assert.deepEqual(yield* Deferred.await(notificationDeferred), [
{
method: "item/agentMessage/delta",
params: {
delta: "Hello from the mock peer.",
itemId: "item-1",
threadId: "thread-1",
turnId: "turn-1",
},
},
]);
assert.deepEqual(yield* Deferred.await(requestDeferred), [
{
id: 77,
method: "item/tool/requestUserInput",
params: {
itemId: "item-approval-1",
threadId: "thread-1",
turnId: "turn-1",
questions: [
{
id: "approved",
header: "Approve",
question: "Continue?",
},
],
},
},
]);
yield* transport.respond(77, {
answers: {
approved: {
answers: ["yes"],
},
},
});
assert.deepEqual(JSON.parse(yield* Queue.take(output)), {
id: 77,
result: {
answers: {
approved: {
answers: ["yes"],
},
},
},
});
yield* transport.respondError(
78,
CodexError.CodexAppServerRequestError.methodNotFound("x/test"),
);
assert.deepEqual(JSON.parse(yield* Queue.take(output)), {
id: 78,
error: {
code: -32601,
message: "Method not found: x/test",
},
});
}),
);
it.effect("surfaces JSON encoding failures as protocol parse errors", () =>
Effect.gen(function* () {
const { stdio } = yield* makeInMemoryStdio();
const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
assert.instanceOf(bigintError, CodexError.CodexAppServerProtocolParseError);
assert.equal(bigintError.detail, "Failed to encode Codex App Server message");
const circular: Record<string, unknown> = {};
circular.self = circular;
const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
assert.instanceOf(circularError, CodexError.CodexAppServerProtocolParseError);
assert.equal(circularError.detail, "Failed to encode Codex App Server message");
}),
);
});
@@ -0,0 +1,394 @@
import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
import * as Schema from "effect/Schema";
import * as Stdio from "effect/Stdio";
import * as Stream from "effect/Stream";
import * as CodexError from "./errors.ts";
import { JsonRpcId, JsonRpcResponseEnvelope } from "./_internal/shared.ts";
export interface CodexAppServerProtocolLogEvent {
readonly direction: "incoming" | "outgoing";
readonly stage: "raw" | "decoded" | "decode_failed";
readonly payload: unknown;
}
export interface CodexAppServerIncomingNotification {
readonly method: string;
readonly params?: unknown;
}
export interface CodexAppServerIncomingRequest {
readonly id: string | number;
readonly method: string;
readonly params?: unknown;
}
export interface CodexAppServerPatchedProtocolOptions {
readonly stdio: Stdio.Stdio;
readonly terminationError?: Effect.Effect<CodexError.CodexAppServerError>;
readonly logIncoming?: boolean;
readonly logOutgoing?: boolean;
readonly logger?: (event: CodexAppServerProtocolLogEvent) => Effect.Effect<void, never>;
readonly onNotification?: (
notification: CodexAppServerIncomingNotification,
) => Effect.Effect<void, never>;
readonly onRequest?: (
request: CodexAppServerIncomingRequest,
) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
readonly onTermination?: (error: CodexError.CodexAppServerError) => Effect.Effect<void, never>;
}
export interface CodexAppServerPatchedProtocol {
readonly incomingNotifications: Stream.Stream<CodexAppServerIncomingNotification>;
readonly incomingRequests: Stream.Stream<CodexAppServerIncomingRequest>;
readonly request: (
method: string,
payload?: unknown,
) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
readonly notify: (
method: string,
payload?: unknown,
) => Effect.Effect<void, CodexError.CodexAppServerError>;
readonly respond: (
requestId: string | number,
result: unknown,
) => Effect.Effect<void, CodexError.CodexAppServerError>;
readonly respondError: (
requestId: string | number,
error: CodexError.CodexAppServerRequestError,
) => Effect.Effect<void, CodexError.CodexAppServerError>;
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function isIncomingRequest(value: unknown): value is CodexAppServerIncomingRequest {
if (!isObject(value) || typeof value.method !== "string") {
return false;
}
return Schema.is(JsonRpcId)(value.id);
}
function isIncomingNotification(value: unknown): value is CodexAppServerIncomingNotification {
return isObject(value) && typeof value.method === "string" && !("id" in value);
}
function isIncomingResponse(value: unknown): value is typeof JsonRpcResponseEnvelope.Type {
return Schema.is(JsonRpcResponseEnvelope)(value);
}
const encodeWireMessage = (
message: Record<string, unknown>,
): Effect.Effect<string, CodexError.CodexAppServerProtocolParseError> =>
Effect.try({
try: () => `${JSON.stringify(message)}\n`,
catch: (cause) =>
new CodexError.CodexAppServerProtocolParseError({
detail: "Failed to encode Codex App Server message",
cause,
}),
});
const normalizeIncomingError = (error: unknown, detail: string): CodexError.CodexAppServerError =>
Schema.is(CodexError.CodexAppServerError)(error)
? error
: new CodexError.CodexAppServerTransportError({
detail,
cause: error,
});
const toProtocolMessage = (
requestId: string | number,
fields: {
readonly result?: unknown;
readonly error?: CodexError.CodexAppServerProtocolErrorShape;
},
): { readonly [key: string]: unknown } => ({
id: requestId,
...(fields.result !== undefined ? { result: fields.result } : {}),
...(fields.error !== undefined ? { error: fields.error } : {}),
});
export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPatchedProtocol")(
function* (
options: CodexAppServerPatchedProtocolOptions,
): Effect.fn.Return<CodexAppServerPatchedProtocol, never, Scope.Scope> {
const outgoing = yield* Queue.unbounded<string, Cause.Done<void>>();
const incomingNotifications = yield* Queue.unbounded<CodexAppServerIncomingNotification>();
const incomingRequests = yield* Queue.unbounded<CodexAppServerIncomingRequest>();
const pending = yield* Ref.make(
new Map<string, Deferred.Deferred<unknown, CodexError.CodexAppServerError>>(),
);
const nextRequestId = yield* Ref.make(1);
const remainder = yield* Ref.make("");
const terminationHandled = yield* Ref.make(false);
const logProtocol = (event: CodexAppServerProtocolLogEvent) => {
if (event.direction === "incoming" && !options.logIncoming) {
return Effect.void;
}
if (event.direction === "outgoing" && !options.logOutgoing) {
return Effect.void;
}
return (
options.logger?.(event) ??
Effect.logDebug("Codex App Server protocol event").pipe(Effect.annotateLogs({ event }))
);
};
const failAllPending = (error: CodexError.CodexAppServerError) =>
Ref.get(pending).pipe(
Effect.flatMap((current) =>
Effect.forEach([...current.values()], (deferred) => Deferred.fail(deferred, error), {
discard: true,
}),
),
Effect.andThen(Ref.set(pending, new Map())),
);
const handleTermination = (classify: () => Effect.Effect<CodexError.CodexAppServerError>) =>
Ref.modify(terminationHandled, (handled) => {
if (handled) {
return [Effect.void, true] as const;
}
return [
Effect.gen(function* () {
const error = yield* classify();
yield* failAllPending(error);
yield* Queue.end(outgoing);
if (options.onTermination) {
yield* options.onTermination(error);
}
}),
true,
] as const;
}).pipe(Effect.flatten);
const offerOutgoing = (message: Record<string, unknown>) =>
Effect.gen(function* () {
yield* logProtocol({
direction: "outgoing",
stage: "decoded",
payload: message,
});
const encoded = yield* encodeWireMessage(message);
yield* logProtocol({
direction: "outgoing",
stage: "raw",
payload: encoded,
});
yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid);
});
const removePending = (requestId: string) =>
Ref.update(pending, (current) => {
if (!current.has(requestId)) {
return current;
}
const next = new Map(current);
next.delete(requestId);
return next;
});
const resolvePending = (
requestId: string,
handler: (
deferred: Deferred.Deferred<unknown, CodexError.CodexAppServerError>,
) => Effect.Effect<void>,
) =>
Ref.modify(pending, (current) => {
const deferred = current.get(requestId);
if (!deferred) {
return [Effect.void, current] as const;
}
const next = new Map(current);
next.delete(requestId);
return [handler(deferred), next] as const;
}).pipe(Effect.flatten);
const respond = (requestId: string | number, result: unknown) =>
offerOutgoing(toProtocolMessage(requestId, { result }));
const respondError = (
requestId: string | number,
error: CodexError.CodexAppServerRequestError,
) => offerOutgoing(toProtocolMessage(requestId, { error: error.toProtocolError() }));
const handleResponse = (response: typeof JsonRpcResponseEnvelope.Type) => {
const requestId = String(response.id);
const protocolError = response.error;
if (protocolError !== undefined) {
return resolvePending(requestId, (deferred) =>
Deferred.fail(
deferred,
CodexError.CodexAppServerRequestError.fromProtocolError(protocolError),
),
);
}
return resolvePending(requestId, (deferred) => Deferred.succeed(deferred, response.result));
};
const handleRequest = (request: CodexAppServerIncomingRequest) =>
Queue.offer(incomingRequests, request).pipe(
Effect.andThen(
options.onRequest
? options.onRequest(request).pipe(
Effect.matchEffect({
onFailure: (error) =>
respondError(request.id, CodexError.normalizeToRequestError(error)),
onSuccess: (result) => respond(request.id, result),
}),
)
: Effect.void,
),
Effect.asVoid,
);
const handleNotification = (notification: CodexAppServerIncomingNotification) =>
Queue.offer(incomingNotifications, notification).pipe(
Effect.andThen(options.onNotification ? options.onNotification(notification) : Effect.void),
Effect.asVoid,
);
const routeMessage = (
message: unknown,
): Effect.Effect<void, CodexError.CodexAppServerError> => {
if (isIncomingRequest(message)) {
return handleRequest(message);
}
if (isIncomingNotification(message)) {
return handleNotification(message);
}
if (isIncomingResponse(message)) {
return handleResponse(message);
}
return Effect.fail(
new CodexError.CodexAppServerProtocolParseError({
detail: "Received protocol message in an unknown shape",
}),
);
};
const handleLine = (line: string): Effect.Effect<void, CodexError.CodexAppServerError> => {
if (line.trim().length === 0) {
return Effect.void;
}
return logProtocol({
direction: "incoming",
stage: "raw",
payload: line,
}).pipe(
Effect.flatMap(() =>
Effect.try({
try: () => JSON.parse(line),
catch: (cause) =>
new CodexError.CodexAppServerProtocolParseError({
detail: "Failed to decode Codex App Server wire message",
cause,
}),
}),
),
Effect.tap((decoded) =>
logProtocol({
direction: "incoming",
stage: "decoded",
payload: decoded,
}),
),
Effect.tapErrorTag("CodexAppServerProtocolParseError", (error) =>
logProtocol({
direction: "incoming",
stage: "decode_failed",
payload: {
detail: error.detail,
cause: error.cause,
},
}),
),
Effect.flatMap(routeMessage),
);
};
yield* options.stdio.stdin.pipe(
Stream.decodeText(),
Stream.runForEach((chunk) =>
Ref.modify(remainder, (current) => {
const combined = current + chunk;
const lines = combined.split("\n");
const nextRemainder = lines.pop() ?? "";
return [lines.map((line) => line.replace(/\r$/, "")), nextRemainder] as const;
}).pipe(Effect.flatMap((lines) => Effect.forEach(lines, handleLine, { discard: true }))),
),
Effect.matchEffect({
onFailure: (error) =>
handleTermination(() =>
Effect.succeed(normalizeIncomingError(error, "Codex App Server input stream failed")),
),
onSuccess: () =>
Ref.get(remainder).pipe(
Effect.flatMap((line) => (line.trim().length === 0 ? Effect.void : handleLine(line))),
Effect.matchEffect({
onFailure: (error) => handleTermination(() => Effect.succeed(error)),
onSuccess: () =>
handleTermination(
() =>
options.terminationError ??
Effect.succeed(
new CodexError.CodexAppServerTransportError({
detail: "Codex App Server input stream ended",
cause: new Error("Codex App Server input stream ended"),
}),
),
),
}),
),
}),
Effect.forkScoped,
);
yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);
const request = (method: string, payload?: unknown) =>
Effect.gen(function* () {
const requestId = yield* Ref.modify(
nextRequestId,
(current) => [current, current + 1] as const,
);
const deferred = yield* Deferred.make<unknown, CodexError.CodexAppServerError>();
yield* Ref.update(pending, (current) => new Map(current).set(String(requestId), deferred));
yield* offerOutgoing({
id: requestId,
method,
...(payload !== undefined ? { params: payload } : {}),
}).pipe(
Effect.catch((error) =>
removePending(String(requestId)).pipe(Effect.andThen(Effect.fail(error))),
),
);
return yield* Deferred.await(deferred).pipe(
Effect.onInterrupt(() => removePending(String(requestId))),
);
});
const notify = (method: string, payload?: unknown) =>
offerOutgoing({
method,
...(payload !== undefined ? { params: payload } : {}),
});
return {
incomingNotifications: Stream.fromQueue(incomingNotifications),
incomingRequests: Stream.fromQueue(incomingRequests),
request,
notify,
respond,
respondError,
} satisfies CodexAppServerPatchedProtocol;
},
);
@@ -0,0 +1 @@
export * from "./_generated/meta.gen.ts";
@@ -0,0 +1,3 @@
export * from "./_generated/schema.gen.ts";
export * from "./_generated/meta.gen.ts";
export * from "./_generated/namespaces.gen.ts";
@@ -0,0 +1,62 @@
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as CodexClient from "../../src/client.ts";
const program = Effect.gen(function* () {
const codexLayer = CodexClient.layerCommand({
command: process.env.CODEX_BIN ?? "codex",
args: ["app-server"],
cwd: process.cwd(),
logIncoming: true,
logOutgoing: true,
});
yield* Effect.gen(function* () {
const client = yield* CodexClient.CodexAppServerClient;
yield* client.handleServerRequest("item/tool/requestUserInput", (payload) =>
Effect.succeed({
answers: Object.fromEntries(
payload.questions.map((question) => [
question.id,
{
answers:
question.options && question.options.length > 0
? [question.options[0]!.label]
: ["ok"],
},
]),
),
}),
);
const initialized = yield* client.request("initialize", {
clientInfo: {
name: "effect-codex-app-server-probe",
title: "Effect Codex App Server Probe",
version: "0.0.0",
},
capabilities: {
experimentalApi: true,
optOutNotificationMethods: null,
},
});
yield* Console.log("initialize", JSON.stringify(initialized, null, 2));
yield* client.notify("initialized", undefined);
const account = yield* client.request("account/read", {});
yield* Console.log("account/read", JSON.stringify(account, null, 2));
const skills = yield* client.request("skills/list", {
cwds: [process.cwd()],
});
yield* Console.log("skills/list", JSON.stringify(skills, null, 2));
}).pipe(Effect.provide(codexLayer));
});
program.pipe(Effect.scoped, Effect.provide(NodeServices.layer), NodeRuntime.runMain);
@@ -0,0 +1,144 @@
let nextServerRequestId = 10_000;
let pendingSkillsListRequestId: number | string | null = null;
let pendingUserInputRequestId: number | null = null;
const writeMessage = (message: unknown) => {
process.stdout.write(`${JSON.stringify(message)}\n`);
};
const respond = (id: number | string, result: unknown) => {
writeMessage({ id, result });
};
const respondError = (id: number | string, code: number, message: string) => {
writeMessage({
id,
error: {
code,
message,
},
});
};
const sendRequest = (method: string, params: unknown) => {
const id = nextServerRequestId++;
writeMessage({ id, method, params });
return id;
};
const handleMethod = (message: Record<string, unknown>) => {
const method = message.method;
if (typeof method !== "string") {
return;
}
switch (method) {
case "initialize": {
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;
}
case "initialized": {
writeMessage({
method: "item/agentMessage/delta",
params: {
delta: "Mock server is ready.",
itemId: "item-1",
threadId: "thread-1",
turnId: "turn-1",
},
});
return;
}
case "account/read": {
respond(message.id as number | string, {
account: {
type: "chatgpt",
email: "[email protected]",
planType: "plus",
},
requiresOpenaiAuth: false,
});
return;
}
case "skills/list": {
pendingSkillsListRequestId = message.id as number | string;
pendingUserInputRequestId = sendRequest("item/tool/requestUserInput", {
itemId: "item-approval-1",
threadId: "thread-1",
turnId: "turn-1",
questions: [
{
id: "approved",
header: "Approve",
question: "Continue with the mock skills request?",
options: [
{
label: "yes",
description: "Approve the request",
},
],
},
],
});
return;
}
default: {
if (message.id !== undefined) {
respondError(message.id as number | string, -32601, `Unhandled request: ${method}`);
}
}
}
};
const handleResponse = (message: Record<string, unknown>) => {
if (message.id !== pendingUserInputRequestId) {
return;
}
pendingUserInputRequestId = null;
respond(pendingSkillsListRequestId!, {
data: [
{
cwd: process.cwd(),
errors: [],
skills: [],
},
],
});
pendingSkillsListRequestId = null;
};
let remainder = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
remainder += chunk;
const lines = remainder.split("\n");
remainder = lines.pop() ?? "";
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.length === 0) {
continue;
}
const message = JSON.parse(trimmed) as Record<string, unknown>;
if ("method" in message) {
handleMethod(message);
continue;
}
if ("id" in message) {
handleResponse(message);
}
}
});
process.stdin.on("end", () => {
process.exit(0);
});
@@ -0,0 +1,18 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"plugins": [
{
"name": "@effect/language-service",
"namespaceImportPackages": ["@effect/platform-node"],
"diagnosticSeverity": {
"importFromBarrel": "error",
"anyUnknownInErrorContext": "warning",
"instanceOfSchema": "warning",
"deterministicKeys": "warning"
}
}
]
},
"include": ["src", "scripts", "test"]
}
+1
View File
@@ -25,6 +25,7 @@ const workspaceFiles = [
"packages/contracts/package.json",
"packages/shared/package.json",
"packages/effect-acp/package.json",
"packages/effect-codex-app-server/package.json",
"scripts/package.json",
] as const;