Integrate Codex app-server support

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-08-14 11:22:49 +02:00
1 parent 038560e580
commit 90d0f40790
68 files changed
+17389 -19730

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -0,0 +1,417 @@
import { randomUUID } from "node:crypto";
import { Effect, FileSystem, Layer, Option, Path, Schema, Scope, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { CodexModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { TextGenerationError } from "@t3tools/contracts";
import {
type BranchNameGenerationInput,
type ThreadTitleGenerationResult,
type TextGenerationShape,
TextGeneration,
} from "../Services/TextGeneration.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "../Prompts.ts";
import {
normalizeCliError,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { getCodexModelCapabilities } from "../../provider/codexModels.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;
const makeCodexTextGeneration = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverConfig = yield* Effect.service(ServerConfig);
const serverSettingsService = yield* Effect.service(ServerSettingsService);
type MaterializedImageAttachments = {
readonly imagePaths: ReadonlyArray<string>;
};
const readStreamAsString = <E>(
operation: string,
stream: Stream.Stream<Uint8Array, E>,
): Effect.Effect<string, TextGenerationError> =>
stream.pipe(
Stream.decodeText(),
Stream.runFold(
() => "",
(acc, chunk) => acc + chunk,
),
Effect.mapError((cause) =>
normalizeCliError("codex", operation, cause, "Failed to collect process output"),
),
);
const writeTempFile = (
operation: string,
prefix: string,
content: string,
): Effect.Effect<string, TextGenerationError, Scope.Scope> => {
return fileSystem
.makeTempFileScoped({
prefix: `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`,
})
.pipe(
Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)),
Effect.mapError(
(cause) =>
new TextGenerationError({
operation,
detail: `Failed to write temp file`,
cause,
}),
),
);
};
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
_operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle",
attachments: BranchNameGenerationInput["attachments"],
): Effect.fn.Return<MaterializedImageAttachments, TextGenerationError> {
if (!attachments || attachments.length === 0) {
return { imagePaths: [] };
}
const imagePaths: string[] = [];
for (const attachment of attachments) {
if (attachment.type !== "image") {
continue;
}
const resolvedPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
continue;
}
const fileInfo = yield* fileSystem
.stat(resolvedPath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
continue;
}
imagePaths.push(resolvedPath);
}
return { imagePaths };
});
const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
operation,
cwd,
prompt,
outputSchemaJson,
imagePaths = [],
cleanupPaths = [],
modelSelection,
}: {
operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
cwd: string;
prompt: string;
outputSchemaJson: S;
imagePaths?: ReadonlyArray<string>;
cleanupPaths?: ReadonlyArray<string>;
modelSelection: CodexModelSelection;
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
const schemaPath = yield* writeTempFile(
operation,
"codex-schema",
JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
);
const outputPath = yield* writeTempFile(operation, "codex-output", "");
const codexSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.codex,
).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(
codexSettings?.binaryPath || "codex",
[
"exec",
"--ephemeral",
"--skip-git-repo-check",
"-s",
"read-only",
"--model",
modelSelection.model,
"--config",
`model_reasoning_effort="${reasoningEffort}"`,
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
"--output-schema",
schemaPath,
"--output-last-message",
outputPath,
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
"-",
],
{
env: {
...process.env,
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
},
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.encodeText(Stream.make(prompt)),
},
},
);
const child = yield* commandSpawner
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
),
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
readStreamAsString(operation, child.stdout),
readStreamAsString(operation, child.stderr),
child.exitCode.pipe(
Effect.mapError((cause) =>
normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
),
),
],
{ concurrency: "unbounded" },
);
if (exitCode !== 0) {
const stderrDetail = stderr.trim();
const stdoutDetail = stdout.trim();
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
return yield* new TextGenerationError({
operation,
detail:
detail.length > 0
? `Codex CLI command failed: ${detail}`
: `Codex CLI command failed with code ${exitCode}.`,
});
}
});
const cleanup = Effect.all(
[schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
{
concurrency: "unbounded",
},
).pipe(Effect.asVoid);
return yield* Effect.gen(function* () {
yield* runCodexCommand().pipe(
Effect.scoped,
Effect.timeoutOption(CODEX_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
),
onSome: () => Effect.void,
}),
),
);
return yield* fileSystem.readFileString(outputPath).pipe(
Effect.mapError(
(cause) =>
new TextGenerationError({
operation,
detail: "Failed to read Codex output file.",
cause,
}),
),
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Codex returned invalid structured output.",
cause,
}),
),
),
);
}).pipe(Effect.ensuring(cleanup));
});
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
"CodexTextGeneration.generateCommitMessage",
)(function* (input) {
const { prompt, outputSchema } = buildCommitMessagePrompt({
branch: input.branch,
stagedSummary: input.stagedSummary,
stagedPatch: input.stagedPatch,
includeBranch: input.includeBranch === true,
});
if (input.modelSelection.provider !== "codex") {
return yield* new TextGenerationError({
operation: "generateCommitMessage",
detail: "Invalid model selection.",
});
}
const generated = yield* runCodexJson({
operation: "generateCommitMessage",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
subject: sanitizeCommitSubject(generated.subject),
body: generated.body.trim(),
...("branch" in generated && typeof generated.branch === "string"
? { branch: sanitizeFeatureBranchName(generated.branch) }
: {}),
};
});
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
"CodexTextGeneration.generatePrContent",
)(function* (input) {
const { prompt, outputSchema } = buildPrContentPrompt({
baseBranch: input.baseBranch,
headBranch: input.headBranch,
commitSummary: input.commitSummary,
diffSummary: input.diffSummary,
diffPatch: input.diffPatch,
});
if (input.modelSelection.provider !== "codex") {
return yield* new TextGenerationError({
operation: "generatePrContent",
detail: "Invalid model selection.",
});
}
const generated = yield* runCodexJson({
operation: "generatePrContent",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
title: sanitizePrTitle(generated.title),
body: generated.body.trim(),
};
});
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
"CodexTextGeneration.generateBranchName",
)(function* (input) {
const { imagePaths } = yield* materializeImageAttachments(
"generateBranchName",
input.attachments,
);
const { prompt, outputSchema } = buildBranchNamePrompt({
message: input.message,
attachments: input.attachments,
});
if (input.modelSelection.provider !== "codex") {
return yield* new TextGenerationError({
operation: "generateBranchName",
detail: "Invalid model selection.",
});
}
const generated = yield* runCodexJson({
operation: "generateBranchName",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
imagePaths,
modelSelection: input.modelSelection,
});
return {
branch: sanitizeBranchFragment(generated.branch),
};
});
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
"CodexTextGeneration.generateThreadTitle",
)(function* (input) {
const { imagePaths } = yield* materializeImageAttachments(
"generateThreadTitle",
input.attachments,
);
const { prompt, outputSchema } = buildThreadTitlePrompt({
message: input.message,
attachments: input.attachments,
});
if (input.modelSelection.provider !== "codex") {
return yield* new TextGenerationError({
operation: "generateThreadTitle",
detail: "Invalid model selection.",
});
}
const generated = yield* runCodexJson({
operation: "generateThreadTitle",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
imagePaths,
modelSelection: input.modelSelection,
});
return {
title: sanitizeThreadTitle(generated.title),
} satisfies ThreadTitleGenerationResult;
});
return {
generateCommitMessage,
generatePrContent,
generateBranchName,
generateThreadTitle,
} satisfies TextGenerationShape;
});
export const CodexTextGenerationLive = Layer.effect(TextGeneration, makeCodexTextGeneration);
@@ -0,0 +1,253 @@
import * as path from "node:path";
import * as os from "node:os";
import { fileURLToPath } from "node:url";
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { expect } from "vitest";
import { ServerSettingsError } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
function shellSingleQuote(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
}
const CursorTextGenerationTestLayer = CursorTextGenerationLive.pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-cursor-text-generation-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
function makeAcpAgentWrapper(dir: string, env: Record<string, string>): string {
const binDir = path.join(dir, "bin");
const agentPath = path.join(binDir, "agent");
mkdirSync(binDir, { recursive: true });
writeFileSync(
agentPath,
[
"#!/bin/sh",
...Object.entries(env).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}`),
'if [ "$1" != "acp" ]; then',
' printf "%s\\n" "unexpected args: $*" >&2',
" exit 11",
"fi",
`exec bun ${JSON.stringify(mockAgentPath)}`,
"",
].join("\n"),
"utf8",
);
chmodSync(agentPath, 0o755);
return agentPath;
}
function withFakeAcpAgent<A, E, R>(
env: Record<string, string>,
effect: Effect.Effect<A, E, R>,
): Effect.Effect<A, E | ServerSettingsError, R | ServerSettingsService> {
return Effect.gen(function* () {
const tempDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-acp-"));
const agentPath = makeAcpAgentWrapper(tempDir, env);
const serverSettings = yield* ServerSettingsService;
const previousSettings = yield* serverSettings.getSettings;
yield* serverSettings.updateSettings({
providers: {
cursor: {
binaryPath: agentPath,
},
},
});
return yield* effect.pipe(
Effect.ensuring(
serverSettings
.updateSettings({
providers: {
cursor: {
binaryPath: previousSettings.providers.cursor.binaryPath,
},
},
})
.pipe(
Effect.catch(() => Effect.void),
Effect.ensuring(
Effect.sync(() => {
rmSync(tempDir, { recursive: true, force: true });
}),
),
Effect.asVoid,
),
),
);
});
}
it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
it.effect("uses ACP model config options instead of raw CLI model ids", () => {
const requestLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-log-"));
const requestLogPath = path.join(requestLogDir, "requests.ndjson");
return withFakeAcpAgent(
{
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
subject: "Add generated commit message",
body: "- verify cursor acp model config path",
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-text-generation",
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
stagedPatch:
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
modelSelection: {
provider: "cursor",
model: "gpt-5.4",
options: {
reasoning: "xhigh",
fastMode: true,
contextWindow: "1m",
},
},
});
expect(generated.subject).toBe("Add generated commit message");
expect(generated.body).toBe("- verify cursor acp model config path");
const requests = readFileSync(requestLogPath, "utf8")
.trim()
.split("\n")
.filter((line) => line.length > 0)
.map((line) => JSON.parse(line) as { method?: string; params?: Record<string, unknown> });
expect(
requests.find((request) => request.method === "initialize")?.params?.clientCapabilities,
).toMatchObject({
_meta: {
parameterizedModelPicker: true,
},
});
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "mode" &&
request.params?.value === "ask",
),
).toBe(true);
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "model" &&
request.params?.value === "gpt-5.4",
),
).toBe(true);
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "reasoning" &&
request.params?.value === "extra-high",
),
).toBe(true);
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "context" &&
request.params?.value === "1m",
),
).toBe(true);
expect(
requests.some(
(request) =>
request.method === "session/set_config_option" &&
request.params?.configId === "fast" &&
request.params?.value === "true",
),
).toBe(true);
expect(
requests.find((request) => request.method === "session/prompt")?.params?.prompt,
).toEqual(
expect.arrayContaining([
expect.objectContaining({
type: "text",
text: expect.stringContaining("Staged patch:"),
}),
]),
);
rmSync(requestLogDir, { recursive: true, force: true });
}),
);
});
it.effect("accepts json objects with extra assistant text around them", () =>
withFakeAcpAgent(
{
T3_ACP_PROMPT_RESPONSE_TEXT:
'Sure, here is the JSON:\n```json\n{\n "subject": "Update README dummy comment with attribution and date",\n "body": ""\n}\n```\nDone.',
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-noisy-json",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: {
provider: "cursor",
model: "composer-2",
},
});
expect(generated.subject).toBe("Update README dummy comment with attribution and date");
expect(generated.body).toBe("");
}),
),
);
it.effect("generates thread titles through Cursor ACP text generation", () =>
withFakeAcpAgent(
{
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
title: '"Trim reconnect spinner status after resume."',
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Fix the reconnect spinner after a resumed session.",
modelSelection: {
provider: "cursor",
model: "composer-2",
},
});
expect(generated.title).toBe("Trim reconnect spinner status after resume.");
}),
),
);
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,112 @@
/**
* RoutingTextGeneration – Dispatches text generation requests to either the
* Codex CLI or Claude CLI implementation based on the provider in each
* request input.
*
* When `modelSelection.provider` is `"claudeAgent"` the request is forwarded to
* the Claude layer; for any other value (including the default `undefined`) it
* falls through to the Codex layer.
*
* @module RoutingTextGeneration
*/
import { Effect, Layer, Context } from "effect";
import {
TextGeneration,
type TextGenerationProvider,
type TextGenerationShape,
} from "../Services/TextGeneration.ts";
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";
// ---------------------------------------------------------------------------
// Internal service tags so both concrete layers can coexist.
// ---------------------------------------------------------------------------
class CodexTextGen extends Context.Service<CodexTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/CodexTextGen",
) {}
class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
) {}
class CursorTextGen extends Context.Service<CursorTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/CursorTextGen",
) {}
class OpenCodeTextGen extends Context.Service<OpenCodeTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/OpenCodeTextGen",
) {}
// ---------------------------------------------------------------------------
// Routing implementation
// ---------------------------------------------------------------------------
const makeRoutingTextGeneration = Effect.gen(function* () {
const codex = yield* CodexTextGen;
const claude = yield* ClaudeTextGen;
const cursor = yield* CursorTextGen;
const opencode = yield* OpenCodeTextGen;
const providerToService = {
codex,
claudeAgent: claude,
cursor,
opencode,
};
const route = (provider: TextGenerationProvider | "opencode") => providerToService[provider];
return {
generateCommitMessage: (input) =>
route(input.modelSelection.provider).generateCommitMessage(input),
generatePrContent: (input) => route(input.modelSelection.provider).generatePrContent(input),
generateBranchName: (input) => route(input.modelSelection.provider).generateBranchName(input),
generateThreadTitle: (input) => route(input.modelSelection.provider).generateThreadTitle(input),
} satisfies TextGenerationShape;
});
const InternalCodexLayer = Layer.effect(
CodexTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(CodexTextGenerationLive));
const InternalClaudeLayer = Layer.effect(
ClaudeTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(ClaudeTextGenerationLive));
const InternalCursorLayer = Layer.effect(
CursorTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(CursorTextGenerationLive));
const InternalOpenCodeLayer = Layer.effect(
OpenCodeTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(OpenCodeTextGenerationLive));
export const RoutingTextGenerationLive = Layer.effect(
TextGeneration,
makeRoutingTextGeneration,
).pipe(
Layer.provide(InternalCodexLayer),
Layer.provide(InternalClaudeLayer),
Layer.provide(InternalCursorLayer),
Layer.provide(InternalOpenCodeLayer),
);
@@ -0,0 +1,123 @@
/**
* TextGeneration - Effect service contract for AI-generated Git content.
*
* Generates commit messages and pull request titles/bodies from repository
* context prepared by Git services.
*
* @module TextGeneration
*/
import { Context } from "effect";
import type { Effect } from "effect";
import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
import type { TextGenerationError } from "@t3tools/contracts";
/** Providers that support git text generation (commit messages, PR content, branch names). */
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor";
export interface CommitMessageGenerationInput {
cwd: string;
branch: string | null;
stagedSummary: string;
stagedPatch: string;
/** When true, the model also returns a semantic branch name for the change. */
includeBranch?: boolean;
/** What model and provider to use for generation. */
modelSelection: ModelSelection;
}
export interface CommitMessageGenerationResult {
subject: string;
body: string;
/** Only present when `includeBranch` was set on the input. */
branch?: string | undefined;
}
export interface PrContentGenerationInput {
cwd: string;
baseBranch: string;
headBranch: string;
commitSummary: string;
diffSummary: string;
diffPatch: string;
/** What model and provider to use for generation. */
modelSelection: ModelSelection;
}
export interface PrContentGenerationResult {
title: string;
body: string;
}
export interface BranchNameGenerationInput {
cwd: string;
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
/** What model and provider to use for generation. */
modelSelection: ModelSelection;
}
export interface BranchNameGenerationResult {
branch: string;
}
export interface ThreadTitleGenerationInput {
cwd: string;
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
/** What model and provider to use for generation. */
modelSelection: ModelSelection;
}
export interface ThreadTitleGenerationResult {
title: string;
}
export interface TextGenerationService {
generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult>;
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
generateBranchName(input: BranchNameGenerationInput): Promise<BranchNameGenerationResult>;
generateThreadTitle(input: ThreadTitleGenerationInput): Promise<ThreadTitleGenerationResult>;
}
/**
* TextGenerationShape - Service API for commit/PR text generation.
*/
export interface TextGenerationShape {
/**
* Generate a commit message from staged change context.
*/
readonly generateCommitMessage: (
input: CommitMessageGenerationInput,
) => Effect.Effect<CommitMessageGenerationResult, TextGenerationError>;
/**
* Generate pull request title/body from branch and diff context.
*/
readonly generatePrContent: (
input: PrContentGenerationInput,
) => Effect.Effect<PrContentGenerationResult, TextGenerationError>;
/**
* Generate a concise branch name from a user message.
*/
readonly generateBranchName: (
input: BranchNameGenerationInput,
) => Effect.Effect<BranchNameGenerationResult, TextGenerationError>;
/**
* Generate a concise thread title from a user's first message.
*/
readonly generateThreadTitle: (
input: ThreadTitleGenerationInput,
) => Effect.Effect<ThreadTitleGenerationResult, TextGenerationError>;
}
/**
* TextGeneration - Service tag for commit and PR text generation.
*/
export class TextGeneration extends Context.Service<TextGeneration, TextGenerationShape>()(
"t3/git/Services/TextGeneration",
) {}
@@ -155,7 +155,7 @@ async function waitForThread(
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
activities: ReadonlyArray<{ kind: string }>;
}) => boolean,
timeoutMs = 15_000,
timeoutMs = 30_000,
) {
const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
const poll = async (): Promise<{
@@ -180,7 +180,7 @@ async function waitForThread(
async function waitForEvent(
engine: OrchestrationEngineShape,
predicate: (event: { type: string }) => boolean,
timeoutMs = 15_000,
timeoutMs = 30_000,
) {
const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
const poll = async () => {
@@ -231,8 +231,8 @@ function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string {
return runGit(cwd, ["show", `${ref}:${filePath}`]);
}
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 15_000) {
const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 30_000) {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<void> => {
if (gitRefExists(cwd, ref)) {
return;
@@ -247,6 +247,9 @@ async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 15_000)
}
describe("CheckpointReactor", () => {
const LONG_TEST_TIMEOUT_MS = 30_000;
const test = (name: string, run: () => Promise<void>, timeout = LONG_TEST_TIMEOUT_MS) =>
it(name, run, timeout);
let runtime: ManagedRuntime.ManagedRuntime<
| OrchestrationEngineService
| CheckpointReactor
@@ -453,7 +456,7 @@ describe("CheckpointReactor", () => {
};
}
it("captures pre-turn baseline on turn.started and post-turn checkpoint on turn.completed", async () => {
test("captures pre-turn baseline on turn.started and post-turn checkpoint on turn.completed", async () => {
const harness = await createHarness({ seedFilesystemCheckpoints: false });
const createdAt = "2026-01-01T00:00:00.000Z";
@@ -703,7 +706,7 @@ describe("CheckpointReactor", () => {
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
});
it("captures pre-turn and completion checkpoints for claude runtime events", async () => {
test("captures pre-turn and completion checkpoints for claude runtime events", async () => {
const harness = await createHarness({
seedFilesystemCheckpoints: false,
providerName: ProviderDriverKind.make("claudeAgent"),
@@ -764,7 +767,7 @@ describe("CheckpointReactor", () => {
).toBe(true);
});
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
test("appends capture failure activity when turn diff summary cannot be derived", async () => {
const harness = await createHarness({ seedFilesystemCheckpoints: false });
const createdAt = "2026-01-01T00:00:00.000Z";
@@ -811,7 +814,7 @@ describe("CheckpointReactor", () => {
).toBe(true);
});
it("captures pre-turn baseline from project workspace root when thread worktree is unset", async () => {
test("captures pre-turn baseline from project workspace root when thread worktree is unset", async () => {
const harness = await createHarness({
hasSession: false,
seedFilesystemCheckpoints: false,
@@ -848,7 +851,7 @@ describe("CheckpointReactor", () => {
).toBe("v1\n");
});
it("captures turn completion checkpoint from project workspace root when provider session cwd is unavailable", async () => {
test("captures turn completion checkpoint from project workspace root when provider session cwd is unavailable", async () => {
const harness = await createHarness({
hasSession: false,
seedFilesystemCheckpoints: false,
@@ -899,7 +902,7 @@ describe("CheckpointReactor", () => {
).toBe("v2\n");
});
it("ignores non-v2 checkpoint.captured runtime events", async () => {
test("ignores non-v2 checkpoint.captured runtime events", async () => {
const harness = await createHarness();
const createdAt = "2026-01-01T00:00:00.000Z";
@@ -941,9 +944,9 @@ describe("CheckpointReactor", () => {
);
});
it("continues processing runtime events after a single checkpoint runtime failure", async () => {
const nonRepositorySessionCwd = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-checkpoint-runtime-non-repo-"),
test("continues processing runtime events after a single checkpoint runtime failure", async () => {
const nonRepositorySessionCwd = fs.mkdtempSync(
path.join(os.tmpdir(), "t3-checkpoint-runtime-non-repo-"),
);
tempDirs.push(nonRepositorySessionCwd);
@@ -1001,7 +1004,7 @@ describe("CheckpointReactor", () => {
).toBe(true);
});
it("executes provider revert and emits thread.reverted for checkpoint revert requests", async () => {
test("executes provider revert and emits thread.reverted for checkpoint revert requests", async () => {
const harness = await createHarness();
const createdAt = "2026-01-01T00:00:00.000Z";
@@ -1082,9 +1085,9 @@ describe("CheckpointReactor", () => {
).toBe(false);
});
it("executes provider revert and emits thread.reverted for claude sessions", async () => {
const harness = await createHarness({ providerName: ProviderDriverKind.make("claudeAgent") });
const createdAt = "2026-01-01T00:00:00.000Z";
test("executes provider revert and emits thread.reverted for claude sessions", async () => {
const harness = await createHarness({ providerName: "claudeAgent" });
const createdAt = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
@@ -1151,7 +1154,7 @@ describe("CheckpointReactor", () => {
});
});
it("processes consecutive revert requests with deterministic rollback sequencing", async () => {
test("processes consecutive revert requests with deterministic rollback sequencing", async () => {
const harness = await createHarness();
const createdAt = "2026-01-01T00:00:00.000Z";
@@ -1234,7 +1237,7 @@ describe("CheckpointReactor", () => {
});
});
it("appends an error activity when revert is requested without an active session", async () => {
test("appends an error activity when revert is requested without an active session", async () => {
const harness = await createHarness({ hasSession: false });
const createdAt = "2026-01-01T00:00:00.000Z";
@@ -21,16 +21,8 @@ import {
ThreadId,
TurnId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
import * as PubSub from "effect/PubSub";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { it as effectIt } from "@effect/vitest";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { Deferred, Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
import { afterEach, describe, expect, it, vi } from "vitest";
import { deriveServerPaths, ServerConfig } from "../../config.ts";
import { TextGenerationError } from "@t3tools/contracts";
@@ -552,115 +544,58 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
effectIt.effect("projects starting before a slow provider session finishes", () =>
Effect.gen(function* () {
const releaseStart = yield* Deferred.make<void>();
const harness = yield* Effect.promise(() =>
createHarness({
startSessionEffect: (session) => Deferred.await(releaseStart).pipe(Effect.as(session)),
}),
);
const now = "2026-01-01T00:00:00.000Z";
it("records session lastError and clears active turn when provider turn start fails", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
yield* harness.engine.dispatch({
harness.sendTurn.mockImplementation(
() =>
Effect.fail(
new ProviderAdapterRequestError({
provider: "cursor",
method: "session/set_config_option",
detail: 'Invalid value for session config option "model"',
}),
) as never,
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-slow-provider"),
commandId: CommandId.make("cmd-turn-start-session-error"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-slow-provider"),
messageId: asMessageId("user-message-session-error"),
role: "user",
text: "start slowly",
text: "hello",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
});
}),
);
yield* Effect.promise(() => waitFor(() => harness.startSession.mock.calls.length === 1));
const duringStartup = yield* Effect.promise(() => harness.readModel());
expect(
duringStartup.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.session
?.status,
).toBe("starting");
expect(harness.sendTurn).not.toHaveBeenCalled();
yield* Deferred.succeed(releaseStart, undefined);
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
}),
);
effectIt.effect("settles a failed provider startup and allows a clean retry", () =>
Effect.gen(function* () {
let failStartup = true;
const harness = yield* Effect.promise(() =>
createHarness({
startSessionEffect: (session) =>
failStartup
? Effect.fail(
new ProviderAdapterRequestError({
provider: "codex",
method: "thread.start",
detail: "deterministic startup failure",
}),
)
: Effect.succeed(session),
}),
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return (
thread?.session?.lastError ===
'Provider adapter request failed (cursor) for session/set_config_option: Invalid value for session config option "model"' &&
thread?.session?.status === "ready" &&
thread?.session?.activeTurnId === null
);
const now = "2026-01-01T00:00:00.000Z";
});
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-provider-failure"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-provider-failure"),
role: "user",
text: "fail once",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
});
yield* Effect.promise(() =>
waitFor(async () => {
const readModel = await harness.readModel();
return (
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.session
?.status === "error"
);
}),
);
let readModel = yield* Effect.promise(() => harness.readModel());
let thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session?.lastError).toContain("deterministic startup failure");
expect(harness.sendTurn).not.toHaveBeenCalled();
failStartup = false;
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-provider-retry"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-provider-retry"),
role: "user",
text: "retry",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: "2026-01-01T00:00:01.000Z",
});
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
readModel = yield* Effect.promise(() => harness.readModel());
thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session?.status).toBe("starting");
expect(thread?.session?.lastError).toBeNull();
}),
);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session).toMatchObject({
status: "ready",
activeTurnId: null,
lastError:
'Provider adapter request failed (cursor) for session/set_config_option: Invalid value for session config option "model"',
});
});
it("generates a thread title on the first turn", async () => {
const harness = await createHarness();
@@ -2112,6 +2047,63 @@ describe("ProviderCommandReactor", () => {
});
});
it("switches cursor model in-session without restarting", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "cursor", model: "composer-2" },
});
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-cursor-model-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-cursor-model-1"),
role: "user",
text: "first cursor turn",
attachments: [],
},
modelSelection: { provider: "cursor", model: "composer-2" },
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-cursor-model-2"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-cursor-model-2"),
role: "user",
text: "second cursor turn",
attachments: [],
},
modelSelection: {
provider: "cursor",
model: "composer-2",
options: { fastMode: true },
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.startSession.mock.calls.length).toBe(1);
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
modelSelection: { provider: "cursor", model: "composer-2", options: { fastMode: true } },
});
});
it("restarts the provider session when runtime mode is updated on the thread", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -2486,37 +2478,30 @@ describe("ProviderCommandReactor", () => {
});
});
it("starts a fresh session when only projected session state exists", async () => {
it("preserves provider method context when turn start fails", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-stale"),
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
createdAt: now,
}),
harness.sendTurn.mockImplementation(
() =>
Effect.fail(
new ProviderAdapterRequestError({
provider: "cursor",
method: "session/set_config_option",
detail: "Invalid cursor/set_config_option payload: Expected string, got null",
}),
) as never,
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-stale"),
commandId: CommandId.make("cmd-turn-start-provider-error"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-stale"),
messageId: asMessageId("user-message-provider-error"),
role: "user",
text: "resume codex",
text: "hello",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -2525,19 +2510,73 @@ describe("ProviderCommandReactor", () => {
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "approval-required",
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining(
"Provider adapter request failed (cursor) for session/set_config_option",
),
},
});
});
it("keeps the full rendered cause for non-adapter turn start failures", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.sendTurn.mockImplementation(
() =>
Effect.fail(
new Error("Invalid params", { cause: new Error("session/prompt failed") }),
) as never,
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-raw-error"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-raw-error"),
role: "user",
text: "hello",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining("session/prompt failed"),
},
});
});
@@ -2653,6 +2692,60 @@ describe("ProviderCommandReactor", () => {
});
});
it("processes approval responses while a provider turn is still in flight", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
const unblockSendTurn = Effect.runSync(Deferred.make<void>());
harness.sendTurn.mockImplementation(() =>
Deferred.await(unblockSendTurn).pipe(
Effect.as({
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-1"),
}),
),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-blocked-approval"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-blocked-approval"),
role: "user",
text: "need approval while turn is running",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.approval.respond",
commandId: CommandId.make("cmd-approval-respond-during-send-turn"),
threadId: ThreadId.make("thread-1"),
requestId: asApprovalRequestId("approval-request-while-send-turn-blocked"),
decision: "acceptForSession",
createdAt: now,
}),
);
await waitFor(() => harness.respondToRequest.mock.calls.length === 1);
expect(harness.respondToRequest.mock.calls[0]?.[0]).toEqual({
threadId: "thread-1",
requestId: "approval-request-while-send-turn-blocked",
decision: "acceptForSession",
});
await Effect.runPromise(Deferred.succeed(unblockSendTurn, undefined));
});
it("reacts to thread.user-input.respond by forwarding structured user input answers", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -248,7 +248,7 @@ function findProviderAdapterRequestError(
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = findProviderAdapterRequestError(cause);
if (error) {
if (Schema.is(ProviderAdapterRequestError)(error)) {
const detail = error.detail.toLowerCase();
return (
detail.includes("unknown pending approval request") ||
@@ -264,13 +264,8 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = findProviderAdapterRequestError(cause);
if (error) {
const detail = error.detail.toLowerCase();
return (
detail.includes("unknown pending user-input request") ||
detail.includes("unknown pending user input request") ||
detail.includes("unknown pending codex user input request")
);
if (Schema.is(ProviderAdapterRequestError)(error)) {
return error.detail.toLowerCase().includes("unknown pending user-input request");
}
const message = Cause.pretty(cause).toLowerCase();
return (
@@ -384,7 +379,7 @@ const make = Effect.gen(function* () {
? failReason.error
: undefined;
if (providerError) {
return providerError.detail;
return providerError.message;
}
return Cause.pretty(cause);
};
@@ -664,9 +659,13 @@ const make = Effect.gen(function* () {
thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null;
if (existingSessionThreadId) {
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
const cwdChanged = effectiveCwd !== activeSession?.cwd;
const sessionModelSwitch = (yield* providerService.getCapabilities(desiredInstanceId))
.sessionModelSwitch;
const providerChanged =
requestedModelSelection !== undefined &&
requestedModelSelection.provider !== currentProvider;
const sessionModelSwitch =
currentProvider === undefined
? "in-session"
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
const modelChanged =
requestedModelSelection !== undefined &&
requestedModelSelection.model !== activeSession?.model;
@@ -682,17 +681,14 @@ const make = Effect.gen(function* () {
if (
!runtimeModeChanged &&
!cwdChanged &&
!instanceChanged &&
!providerChanged &&
!shouldRestartForModelChange &&
!shouldRestartForModelSelectionChange
) {
return existingSessionThreadId;
}
const resumeCursor = shouldRestartForModelChange
? undefined
: (activeSession?.resumeCursor ?? undefined);
const resumeCursor = providerChanged ? undefined : (activeSession?.resumeCursor ?? undefined);
yield* Effect.logInfo("provider command reactor restarting provider session", {
threadId,
existingSessionThreadId,
@@ -703,9 +699,7 @@ const make = Effect.gen(function* () {
currentRuntimeMode: thread.session?.runtimeMode,
desiredRuntimeMode: thread.runtimeMode,
runtimeModeChanged,
previousCwd: activeSession?.cwd,
desiredCwd: effectiveCwd,
cwdChanged,
providerChanged,
modelChanged,
instanceChanged,
shouldRestartForModelChange,
@@ -1126,9 +1120,6 @@ const make = Effect.gen(function* () {
}
const handleTurnStartFailure = (cause: Cause.Cause<unknown>) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const detail = formatFailureDetail(cause);
return setThreadSessionErrorOnTurnStartFailure({
threadId: event.payload.threadId,
@@ -1145,22 +1136,9 @@ const make = Effect.gen(function* () {
createdAt: event.payload.createdAt,
}),
),
Effect.asVoid,
);
};
const recoverTurnStartFailure = (cause: Cause.Cause<unknown>) =>
handleTurnStartFailure(cause).pipe(
Effect.catchCause((recoveryCause) =>
Effect.logWarning("provider command reactor failed to recover turn start failure", {
eventType: event.type,
threadId: event.payload.threadId,
cause: Cause.pretty(recoveryCause),
originalCause: Cause.pretty(cause),
}),
),
);
const sendTurnRequest = yield* buildSendTurnRequestForThread({
threadId: event.payload.threadId,
messageText: message.text,
@@ -1181,7 +1159,7 @@ const make = Effect.gen(function* () {
yield* providerService
.sendTurn(sendTurnRequest.value)
.pipe(Effect.catchCause(recoverTurnStartFailure), Effect.forkScoped);
.pipe(Effect.catchCause(handleTurnStartFailure), Effect.forkScoped);
});
const processTurnInterruptRequested = Effect.fn("processTurnInterruptRequested")(function* (
@@ -12,14 +12,8 @@ import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Result from "effect/Result";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
createModelCapabilities,
getModelSelectionStringOptionValue,
getProviderOptionCurrentValue,
getProviderOptionDescriptors,
} from "@t3tools/shared/model";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import { compareSemverVersions } from "@t3tools/shared/semver";
import { resolveApiModelId } from "@t3tools/shared/model";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import {
query as claudeQuery,
type Options as ClaudeQueryOptions,
@@ -383,79 +377,50 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo
);
}
export function resolveClaudeEffort(
caps: ModelCapabilities,
raw: string | null | undefined,
): string | undefined {
const descriptors = getProviderOptionDescriptors({
caps,
...(raw ? { selections: [{ id: "effort", value: raw }] } : {}),
function buildInitialClaudeProviderSnapshot(claudeSettings: ClaudeSettings): ServerProvider {
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
claudeSettings.customModels,
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
);
if (!claudeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
slashCommands: [],
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Claude is disabled in T3 Code settings.",
},
});
}
return buildServerProvider({
provider: PROVIDER,
enabled: true,
checkedAt,
models,
slashCommands: [],
probe: {
installed: true,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Checking Claude availability...",
},
});
const effortDescriptor = descriptors.find((descriptor) => descriptor.id === "effort");
const value = getProviderOptionCurrentValue(effortDescriptor);
return typeof value === "string" ? value : undefined;
}
/**
* Normalize a resolved Claude effort value into one suitable for the Claude
* CLI's `--effort` flag.
*
* Mirrors the mapping used when invoking the Claude Agent SDK
* ({@link getEffectiveClaudeAgentEffort} in ClaudeAdapter): `ultracode` is a
* Claude Code setting that pairs with `xhigh`, `ultrathink` is filtered out
* because it is a prompt-prefix mode, and older model compatibility mappings
* are preserved for current Claude Code behavior.
*/
export function normalizeClaudeCliEffort(
effort: string | null | undefined,
model: string | null | undefined,
): string | undefined {
if (!effort || effort === "ultrathink") {
return undefined;
}
if (effort === "ultracode") {
return "xhigh";
}
if (
effort === "xhigh" &&
model !== "claude-fable-5" &&
model !== "claude-opus-5" &&
model !== "claude-opus-4-8" &&
model !== "claude-sonnet-5"
) {
return "max";
}
if (effort === "max" && model === "claude-sonnet-4-6") {
return "high";
}
return effort;
}
export function isClaudeUltracodeEffort(effort: string | null | undefined): boolean {
return effort === "ultracode";
}
export function resolveClaudeContextWindow(
modelSelection: ModelSelection | undefined,
): string | undefined {
const caps = getClaudeModelCapabilities(modelSelection?.model);
const raw = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
const descriptors = getProviderOptionDescriptors({
caps,
...(raw ? { selections: [{ id: "contextWindow", value: raw }] } : {}),
});
const descriptor = descriptors.find((candidate) => candidate.id === "contextWindow");
const value = getProviderOptionCurrentValue(descriptor);
return typeof value === "string" ? value : undefined;
}
export function resolveClaudeApiModelId(modelSelection: ModelSelection): string {
switch (resolveClaudeContextWindow(modelSelection)) {
case "1m":
return `${modelSelection.model}[1m]`;
default:
return modelSelection.model;
}
export function resolveClaudeApiModelId(modelSelection: ClaudeModelSelection): string {
return resolveApiModelId(modelSelection);
}
function toTitleCaseWords(value: string): string {
@@ -1002,4 +967,43 @@ export const makePendingClaudeProvider = (
});
});
export { probeClaudeCapabilities };
export const ClaudeProviderLive = Layer.effect(
ClaudeProvider,
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const subscriptionProbeCache = yield* Cache.make({
capacity: 1,
timeToLive: Duration.minutes(5),
lookup: (binaryPath: string) => probeClaudeCapabilities(binaryPath),
});
const checkProvider = checkClaudeProviderStatus(
(binaryPath) =>
Cache.get(subscriptionProbeCache, binaryPath).pipe(
Effect.map((probe) => probe?.subscriptionType),
),
(binaryPath) =>
Cache.get(subscriptionProbeCache, binaryPath).pipe(
Effect.map((probe) => probe?.slashCommands),
),
).pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
return yield* makeManagedServerProvider<ClaudeSettings>({
getSettings: serverSettings.getSettings.pipe(
Effect.map((settings) => settings.providers.claudeAgent),
Effect.orDie,
),
streamSettings: serverSettings.streamChanges.pipe(
Stream.map((settings) => settings.providers.claudeAgent),
),
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
buildInitialSnapshot: buildInitialClaudeProviderSnapshot,
checkProvider,
});
}),
);
@@ -22,17 +22,7 @@ import { createModelSelection } from "@t3tools/shared/model";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, vi } from "@effect/vitest";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as CodexErrors from "effect-codex-app-server/errors";
import { Effect, Fiber, Layer, Option, Queue, Stream } from "effect";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
@@ -44,14 +34,8 @@ import {
type CodexSessionRuntimeSendTurnInput,
type CodexSessionRuntimeShape,
type CodexThreadSnapshot,
} from "./CodexSessionRuntime.ts";
import { makeCodexAdapter } from "./CodexAdapter.ts";
const decodeCodexSettings = Schema.decodeSync(CodexSettings);
// Test-local service tag so the rest of the file can keep using `yield* CodexAdapter`.
class CodexAdapter extends Context.Service<CodexAdapter, CodexAdapterShape>()(
"t3/provider/Layers/CodexAdapter.test/CodexAdapter",
) {}
} from "../codex/CodexSessionRuntime.ts";
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
const asTurnId = (value: string): TurnId => TurnId.make(value);
@@ -60,11 +44,11 @@ const asItemId = (value: string): ProviderItemId => ProviderItemId.make(value);
class FakeCodexRuntime implements CodexSessionRuntimeShape {
private readonly eventQueue = Effect.runSync(Queue.unbounded<ProviderEvent>());
private readonly now = "2026-01-01T00:00:00.000Z";
private readonly now = new Date().toISOString();
public readonly startImpl = vi.fn(() =>
Promise.resolve({
provider: ProviderDriverKind.make("codex"),
provider: "codex" as const,
status: "ready" as const,
runtimeMode: this.options.runtimeMode,
threadId: this.options.threadId,
@@ -176,41 +160,6 @@ function makeRuntimeFactory() {
};
}
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;
}),
);
return {
factory,
releasedThreadIds,
get lastRuntime(): FakeCodexRuntime | undefined {
return runtimes.at(-1);
},
};
}
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
upsert: () => Effect.void,
getProvider: () =>
@@ -222,15 +171,7 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory
const validationRuntimeFactory = makeRuntimeFactory();
const validationLayer = it.layer(
Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = decodeCodexSettings({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: validationRuntimeFactory.factory,
});
}),
).pipe(
makeCodexAdapterLive({ makeRuntime: validationRuntimeFactory.factory }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -259,7 +200,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
issue: "Expected provider 'codex' but received 'claudeAgent'.",
}),
);
NodeAssert.equal(validationRuntimeFactory.factory.mock.calls.length, 0);
assert.equal(validationRuntimeFactory.factory.mock.calls.length, 0);
}),
);
it.effect("maps codex model options before starting a session", () =>
@@ -276,13 +217,11 @@ validationLayer("CodexAdapterLive validation", (it) => {
runtimeMode: "full-access",
});
NodeAssert.deepStrictEqual(validationRuntimeFactory.factory.mock.calls[0]?.[0], {
assert.deepStrictEqual(validationRuntimeFactory.factory.mock.calls[0]?.[0], {
binaryPath: "codex",
cwd: process.cwd(),
launchArgs: "",
model: "gpt-5.3-codex",
providerInstanceId: ProviderInstanceId.make("codex"),
serviceTier: "priority",
serviceTier: "fast",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
});
@@ -292,15 +231,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
const sessionRuntimeFactory = makeRuntimeFactory();
const sessionErrorLayer = it.layer(
Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = decodeCodexSettings({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: sessionRuntimeFactory.factory,
});
}),
).pipe(
makeCodexAdapterLive({ makeRuntime: sessionRuntimeFactory.factory }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -320,10 +251,10 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
})
.pipe(Effect.result);
NodeAssert.equal(result._tag, "Failure");
NodeAssert.equal(result.failure._tag, "ProviderAdapterSessionNotFoundError");
NodeAssert.equal(result.failure.provider, "codex");
NodeAssert.equal(result.failure.threadId, "sess-missing");
assert.equal(result._tag, "Failure");
assert.equal(result.failure._tag, "ProviderAdapterSessionNotFoundError");
assert.equal(result.failure.provider, "codex");
assert.equal(result.failure.threadId, "sess-missing");
}),
);
@@ -331,12 +262,12 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("sess-missing"),
runtimeMode: "full-access",
});
const runtime = sessionRuntimeFactory.lastRuntime;
NodeAssert.ok(runtime);
assert.ok(runtime);
runtime.sendTurnImpl.mockClear();
yield* Effect.ignore(
@@ -351,7 +282,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
}),
);
NodeAssert.deepStrictEqual(runtime.sendTurnImpl.mock.calls[0]?.[0], {
assert.deepStrictEqual(runtime.sendTurnImpl.mock.calls[0]?.[0], {
input: "hello",
model: "gpt-5.3-codex",
effort: "high",
@@ -481,15 +412,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
const lifecycleRuntimeFactory = makeRuntimeFactory();
const lifecycleLayer = it.layer(
Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = decodeCodexSettings({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: lifecycleRuntimeFactory.factory,
});
}),
).pipe(
makeCodexAdapterLive({ makeRuntime: lifecycleRuntimeFactory.factory }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -501,12 +424,12 @@ function startLifecycleRuntime() {
return Effect.gen(function* () {
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
provider: ProviderDriverKind.make("codex"),
provider: "codex",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
});
const runtime = lifecycleRuntimeFactory.lastRuntime;
NodeAssert.ok(runtime);
assert.ok(runtime);
return { adapter, runtime };
});
}
@@ -527,7 +450,6 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
turnId: asTurnId("turn-1"),
itemId: asItemId("msg_1"),
payload: {
completedAtMs: 1_778_000_000_000,
threadId: "thread-1",
turnId: "turn-1",
item: {
@@ -628,7 +550,6 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
turnId: asTurnId("turn-1"),
itemId: asItemId("plan_1"),
payload: {
completedAtMs: 1_778_000_000_000,
threadId: "thread-1",
turnId: "turn-1",
item: {
@@ -796,40 +717,6 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
);
it.effect("maps realtime started notifications with upstream realtime session ids", () =>
Effect.gen(function* () {
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
yield* runtime.emit({
id: asEventId("evt-realtime-started"),
kind: "notification",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-1"),
createdAt: "2026-01-01T00:00:00.000Z",
method: "thread/realtime/started",
payload: {
threadId: "thread-1",
realtimeSessionId: "realtime-session-1",
version: "v2",
},
} satisfies ProviderEvent);
const firstEvent = yield* Fiber.join(firstEventFiber);
NodeAssert.equal(firstEvent._tag, "Some");
if (firstEvent._tag !== "Some") {
return;
}
NodeAssert.equal(firstEvent.value.type, "thread.realtime.started");
if (firstEvent.value.type !== "thread.realtime.started") {
return;
}
NodeAssert.equal(firstEvent.value.threadId, "thread-1");
NodeAssert.equal(firstEvent.value.payload.realtimeSessionId, "realtime-session-1");
}),
);
it.effect("maps fatal websocket stderr notifications to runtime.error", () =>
Effect.gen(function* () {
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
@@ -1072,9 +959,9 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
const events = Array.from(yield* Fiber.join(eventsFiber));
NodeAssert.equal(events[0]?.type, "user-input.requested");
if (events[0]?.type === "user-input.requested") {
NodeAssert.equal(events[0].requestId, "req-user-input-1");
NodeAssert.equal(events[0].payload.questions[0]?.id, "sandbox_mode");
NodeAssert.equal(events[0].payload.questions[0]?.multiSelect, false);
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, false);
}
NodeAssert.equal(events[1]?.type, "user-input.resolved");
@@ -1151,155 +1038,3 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
}),
);
});
const scopedLifecycleRuntimeFactory = makeScopedRuntimeFactory();
const scopedLifecycleLayer = it.layer(
Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = decodeCodexSettings({});
return yield* makeCodexAdapter(codexConfig, {
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: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-stop"),
runtimeMode: "full-access",
});
const runtime = scopedLifecycleRuntimeFactory.lastRuntime;
NodeAssert.ok(runtime);
yield* adapter.stopSession(asThreadId("thread-stop"));
NodeAssert.equal(runtime.closeImpl.mock.calls.length, 1);
NodeAssert.deepStrictEqual(scopedLifecycleRuntimeFactory.releasedThreadIds, [
asThreadId("thread-stop"),
]);
NodeAssert.equal(yield* adapter.hasSession(asThreadId("thread-stop")), false);
}),
);
});
const scopedFailureRuntimeFactory = makeScopedRuntimeFactory({ failConstruction: true });
const scopedFailureLayer = it.layer(
Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = decodeCodexSettings({});
return yield* makeCodexAdapter(codexConfig, {
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: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-fail"),
runtimeMode: "full-access",
})
.pipe(Effect.result);
NodeAssert.equal(result._tag, "Failure");
NodeAssert.equal(result.failure._tag, "ProviderAdapterProcessError");
NodeAssert.deepStrictEqual(scopedFailureRuntimeFactory.releasedThreadIds, [
asThreadId("thread-fail"),
]);
NodeAssert.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 = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-codex-adapter-native-log-"),
);
const basePath = NodePath.join(tempDir, "provider-native.ndjson");
const runtimeFactory = makeRuntimeFactory();
const scope = yield* Scope.make("sequential");
let scopeClosed = false;
try {
const layer = Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = decodeCodexSettings({});
return yield* makeCodexAdapter(codexConfig, {
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: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-logger"),
runtimeMode: "full-access",
});
const runtime = runtimeFactory.lastRuntime;
NodeAssert.ok(runtime);
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
yield* runtime.emit({
id: asEventId("evt-native-log"),
kind: "notification",
provider: ProviderDriverKind.make("codex"),
threadId: asThreadId("thread-logger"),
createdAt: "2026-01-01T00:00:00.000Z",
method: "process/stderr",
message: "native flush test",
} satisfies ProviderEvent);
yield* Fiber.join(firstEventFiber);
yield* Scope.close(scope, Exit.void);
scopeClosed = true;
const threadLogPath = NodePath.join(tempDir, "provider-native.thread-logger.log");
NodeAssert.equal(NodeFS.existsSync(threadLogPath), true);
const contents = NodeFS.readFileSync(threadLogPath, "utf8");
NodeAssert.match(contents, /NTIVE: .*"message":"native flush test"/);
} finally {
if (!scopeClosed) {
yield* Scope.close(scope, Exit.void);
}
NodeFS.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
+123 -178
View File
@@ -26,23 +26,11 @@ import {
ThreadId,
ProviderSendTurnInput,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Crypto from "effect/Crypto";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { Effect, Fiber, FileSystem, Layer, Queue, Schema, Stream } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as CodexErrors from "effect-codex-app-server/errors";
import * as EffectCodexSchema from "effect-codex-app-server/schema";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { getCodexServiceTierOptionValue } from "../../codexModelOptions.ts";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import {
ProviderAdapterRequestError,
ProviderAdapterProcessError,
@@ -51,9 +39,10 @@ import {
ProviderAdapterValidationError,
type ProviderAdapterError,
} from "../Errors.ts";
import { type CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import {
CodexResumeCursorSchema,
CodexSessionRuntimeThreadIdMissingError,
@@ -61,7 +50,7 @@ import {
type CodexSessionRuntimeError,
type CodexSessionRuntimeOptions,
type CodexSessionRuntimeShape,
} from "./CodexSessionRuntime.ts";
} from "../codex/CodexSessionRuntime.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import { resolveCodexLaunchArgs } from "./codexLaunchArgs.ts";
const isCodexAppServerProcessExitedError = Schema.is(CodexErrors.CodexAppServerProcessExitedError);
@@ -74,14 +63,12 @@ const isCodexResumeCursorSchema = Schema.is(CodexResumeCursorSchema);
const PROVIDER = ProviderDriverKind.make("codex");
export interface CodexAdapterLiveOptions {
readonly instanceId?: ProviderInstanceId;
readonly environment?: NodeJS.ProcessEnv;
readonly makeRuntime?: (
options: CodexSessionRuntimeOptions,
) => Effect.Effect<
CodexSessionRuntimeShape,
CodexSessionRuntimeError,
ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
ChildProcessSpawner.ChildProcessSpawner
>;
readonly nativeEventLogPath?: string;
readonly nativeEventLogger?: EventNdjsonLogger;
@@ -89,7 +76,6 @@ export interface CodexAdapterLiveOptions {
interface CodexAdapterSessionContext {
readonly threadId: ThreadId;
readonly scope: Scope.Closeable;
readonly runtime: CodexSessionRuntimeShape;
readonly eventFiber: Fiber.Fiber<void, never>;
stopped: boolean;
@@ -100,7 +86,10 @@ function mapCodexRuntimeError(
method: string,
error: CodexSessionRuntimeError,
): ProviderAdapterError {
if (isCodexAppServerProcessExitedError(error) || isCodexAppServerTransportError(error)) {
if (
Schema.is(CodexErrors.CodexAppServerProcessExitedError)(error) ||
Schema.is(CodexErrors.CodexAppServerTransportError)(error)
) {
return new ProviderAdapterSessionClosedError({
provider: PROVIDER,
threadId,
@@ -108,7 +97,7 @@ function mapCodexRuntimeError(
});
}
if (isCodexSessionRuntimeThreadIdMissingError(error)) {
if (Schema.is(CodexSessionRuntimeThreadIdMissingError)(error)) {
return new ProviderAdapterSessionNotFoundError({
provider: PROVIDER,
threadId,
@@ -140,8 +129,7 @@ function readPayload<A>(
schema: Schema.Schema<A>,
payload: ProviderEvent["payload"],
): A | undefined {
const isPayload = Schema.is(schema);
return isPayload(payload) ? payload : undefined;
return Schema.is(schema)(payload) ? payload : undefined;
}
function trimText(value: string | undefined | null): string | undefined {
@@ -193,12 +181,11 @@ function normalizeCodexTokenUsage(
}
function toTurnStatus(
value: EffectCodexSchema.V2TurnCompletedNotification["turn"]["status"] | "cancelled",
value: EffectCodexSchema.V2TurnCompletedNotification["turn"]["status"],
): "completed" | "failed" | "cancelled" | "interrupted" {
switch (value) {
case "completed":
case "failed":
case "cancelled":
case "interrupted":
return value;
default:
@@ -270,14 +257,8 @@ function itemTitle(itemType: CanonicalItemType, item?: CodexLifecycleItem): stri
}
}
function itemDetail(itemType: CanonicalItemType, item: CodexLifecycleItem): string | undefined {
const itemRecord = item as Record<string, unknown>;
const action = itemRecord.action as Record<string, unknown> | undefined;
const actionQueries = Array.isArray(action?.queries) ? action.queries : [];
function itemDetail(item: CodexLifecycleItem): string | undefined {
const candidates = [
...(itemType === "web_search"
? [itemRecord.query, action?.query, ...actionQueries, action?.pattern, action?.url]
: []),
"command" in item ? item.command : undefined,
"title" in item ? item.title : undefined,
"summary" in item ? item.summary : undefined,
@@ -475,7 +456,7 @@ function mapItemLifecycle(
return undefined;
}
const detail = itemDetail(itemType, item);
const detail = itemDetail(item);
const status =
lifecycle === "item.started"
? "inProgress"
@@ -1115,7 +1096,7 @@ function mapToRuntimeEvents(
}
const itemType = toCanonicalItemType(item.type);
if (itemType === "plan") {
const detail = itemDetail(itemType, item);
const detail = itemDetail(item);
if (!detail) {
return [];
}
@@ -1441,7 +1422,7 @@ function mapToRuntimeEvents(
type: "thread.realtime.started",
...runtimeEventBase(event, canonicalThreadId),
payload: {
realtimeSessionId: payload.realtimeSessionId ?? undefined,
realtimeSessionId: payload.sessionId ?? undefined,
},
},
];
@@ -1628,7 +1609,6 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("codex");
const fileSystem = yield* FileSystem.FileSystem;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const crypto = yield* Crypto.Crypto;
const serverConfig = yield* Effect.service(ServerConfig);
const nativeEventLogger =
options?.nativeEventLogger ??
@@ -1637,132 +1617,109 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
stream: "native",
})
: undefined);
const managedNativeEventLogger =
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
const serverSettingsService = yield* ServerSettingsService;
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
const sessions = new Map<ThreadId, CodexAdapterSessionContext>();
const startSession: CodexAdapterShape["startSession"] = (input) =>
Effect.scoped(
Effect.gen(function* () {
if (input.provider !== undefined && input.provider !== PROVIDER) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "startSession",
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
});
}
const existing = sessions.get(input.threadId);
if (existing && !existing.stopped) {
yield* Effect.suspend(() => stopSessionInternal(existing));
}
const serviceTier =
input.modelSelection?.instanceId === boundInstanceId
? getCodexServiceTierOptionValue(input.modelSelection)
: undefined;
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
const runtimeInput: CodexSessionRuntimeOptions = {
threadId: input.threadId,
providerInstanceId: boundInstanceId,
cwd: input.cwd ?? process.cwd(),
binaryPath: codexConfig.binaryPath,
launchArgs: resolveCodexLaunchArgs(codexConfig.launchArgs, options?.environment),
...(options?.environment ? { environment: options.environment } : {}),
...(codexConfig.homePath ? { homePath: codexConfig.homePath } : {}),
...(isCodexResumeCursorSchema(input.resumeCursor)
? { resumeCursor: input.resumeCursor }
: {}),
runtimeMode: input.runtimeMode,
...(input.modelSelection?.instanceId === boundInstanceId
? { model: input.modelSelection.model }
: {}),
...(serviceTier ? { serviceTier } : {}),
...(mcpSession
? {
environment: {
...(options?.environment ?? process.env),
T3_MCP_BEARER_TOKEN: mcpSession.authorizationHeader.replace(/^Bearer\s+/, ""),
},
appServerArgs: [
"-c",
`mcp_servers.t3-code.url=${mcpSession.endpoint}`,
"-c",
'mcp_servers.t3-code.bearer_token_env_var="T3_MCP_BEARER_TOKEN"',
],
}
: {}),
};
const sessionScope = yield* Scope.make("sequential");
let sessionScopeTransferred = false;
yield* Effect.addFinalizer(() =>
sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void),
);
const createRuntime = options?.makeRuntime ?? makeCodexSessionRuntime;
const runtime = yield* createRuntime(runtimeInput).pipe(
Effect.provideService(Scope.Scope, sessionScope),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
Effect.provideService(Crypto.Crypto, crypto),
Effect.mapError(
(cause) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: cause.message,
cause,
}),
),
);
const eventFiber = yield* Stream.runForEach(runtime.events, (event) =>
Effect.gen(function* () {
yield* writeNativeEvent(event);
const runtimeEvents = mapToRuntimeEvents(event, event.threadId);
if (runtimeEvents.length === 0) {
yield* Effect.logDebug("ignoring unhandled Codex provider event", {
method: event.method,
threadId: event.threadId,
turnId: event.turnId,
itemId: event.itemId,
});
return;
}
yield* Queue.offerAll(runtimeEventQueue, runtimeEvents);
}),
).pipe(Effect.forkChild);
const started = yield* runtime.start().pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: cause.message,
cause,
}),
),
Effect.onError(() =>
runtime.close.pipe(
Effect.andThen(Effect.ignore(Scope.close(sessionScope, Exit.void))),
Effect.andThen(Fiber.interrupt(eventFiber)),
Effect.ignore,
),
),
);
sessions.set(input.threadId, {
threadId: input.threadId,
scope: sessionScope,
runtime,
eventFiber,
stopped: false,
const startSession: CodexAdapterShape["startSession"] = Effect.fn("startSession")(
function* (input) {
if (input.provider !== undefined && input.provider !== PROVIDER) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "startSession",
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
});
sessionScopeTransferred = true;
}
return started;
}),
);
const existing = sessions.get(input.threadId);
if (existing && !existing.stopped) {
yield* Effect.suspend(() => stopSessionInternal(existing));
}
const codexSettings = yield* serverSettingsService.getSettings.pipe(
Effect.map((settings) => settings.providers.codex),
Effect.mapError(
(error) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: error.message,
cause: error,
}),
),
);
const runtimeInput: CodexSessionRuntimeOptions = {
threadId: input.threadId,
cwd: input.cwd ?? process.cwd(),
binaryPath: codexSettings.binaryPath,
...(codexSettings.homePath ? { homePath: codexSettings.homePath } : {}),
...(Schema.is(CodexResumeCursorSchema)(input.resumeCursor)
? { resumeCursor: input.resumeCursor }
: {}),
runtimeMode: input.runtimeMode,
...(input.modelSelection?.provider === "codex"
? { model: input.modelSelection.model }
: {}),
...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode
? { serviceTier: "fast" }
: {}),
};
const createRuntime = options?.makeRuntime ?? makeCodexSessionRuntime;
const runtime = yield* createRuntime(runtimeInput).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
Effect.mapError(
(cause) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: cause.message,
cause,
}),
),
);
const eventFiber = yield* Stream.runForEach(runtime.events, (event) =>
Effect.gen(function* () {
yield* writeNativeEvent(event);
const runtimeEvents = mapToRuntimeEvents(event, event.threadId);
if (runtimeEvents.length === 0) {
yield* Effect.logDebug("ignoring unhandled Codex provider event", {
method: event.method,
threadId: event.threadId,
turnId: event.turnId,
itemId: event.itemId,
});
return;
}
yield* Queue.offerAll(runtimeEventQueue, runtimeEvents);
}),
).pipe(Effect.forkChild);
const started = yield* runtime.start().pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: cause.message,
cause,
}),
),
Effect.onError(() =>
runtime.close.pipe(Effect.andThen(Fiber.interrupt(eventFiber)), Effect.ignore),
),
);
sessions.set(input.threadId, {
threadId: input.threadId,
runtime,
eventFiber,
stopped: false,
});
return started;
},
);
const resolveAttachment = Effect.fn("resolveAttachment")(function* (
input: ProviderSendTurnInput,
@@ -1804,26 +1761,19 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
);
const session = yield* requireSession(input.threadId);
const reasoningEffort =
input.modelSelection?.instanceId === boundInstanceId
? getModelSelectionStringOptionValue(input.modelSelection, "reasoningEffort")
: undefined;
const serviceTier =
input.modelSelection?.instanceId === boundInstanceId
? getCodexServiceTierOptionValue(input.modelSelection)
: undefined;
return yield* session.runtime
.sendTurn({
...(input.input !== undefined ? { input: input.input } : {}),
...(input.modelSelection?.instanceId === boundInstanceId
...(input.modelSelection?.provider === "codex"
? { model: input.modelSelection.model }
: {}),
...(reasoningEffort
? {
effort: reasoningEffort as EffectCodexSchema.V2TurnStartParams__ReasoningEffort,
}
...(input.modelSelection?.provider === "codex" &&
input.modelSelection.options?.reasoningEffort !== undefined
? { effort: input.modelSelection.options.reasoningEffort }
: {}),
...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode
? { serviceTier: "fast" }
: {}),
...(serviceTier ? { serviceTier } : {}),
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
})
@@ -1914,7 +1864,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
),
);
const writeNativeEvent = Effect.fnUntraced(function* (event: ProviderEvent) {
const writeNativeEvent = Effect.fn("writeNativeEvent")(function* (event: ProviderEvent) {
if (!nativeEventLogger) {
return;
}
@@ -1930,7 +1880,6 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
session.stopped = true;
sessions.delete(session.threadId);
yield* session.runtime.close.pipe(Effect.ignore);
yield* Effect.ignore(Scope.close(session.scope, Exit.void));
yield* Fiber.interrupt(session.eventFiber).pipe(Effect.ignore);
});
@@ -1960,11 +1909,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
}).pipe(Effect.asVoid);
yield* Effect.acquireRelease(Effect.void, () =>
stopAll().pipe(
Effect.andThen(Queue.shutdown(runtimeEventQueue)),
Effect.andThen(managedNativeEventLogger?.close() ?? Effect.void),
Effect.ignore,
),
stopAll().pipe(Effect.andThen(Queue.shutdown(runtimeEventQueue)), Effect.ignore),
);
return {
+388 -161
View File
@@ -16,13 +16,28 @@ import * as CodexErrors from "effect-codex-app-server/errors";
import type {
CodexSettings,
ServerProvider,
ServerProviderAuth,
ServerProviderSkill,
ServerProviderState,
ModelCapabilities,
ProviderOptionDescriptor,
ServerProviderModel,
ServerProviderSkill,
} from "@t3tools/contracts";
import { PREFERRED_DEFAULT_CODEX_MODELS, ServerSettingsError } from "@t3tools/contracts";
import {
Cache,
Data,
Duration,
Effect,
Equal,
FileSystem,
Layer,
Option,
Path,
Result,
Stream,
} from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { createModelCapabilities } from "@t3tools/shared/model";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
@@ -32,22 +47,73 @@ import {
buildServerProvider,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import { expandHomePath } from "../../pathExpansion.ts";
import packageJson from "../../../package.json" with { type: "json" };
const isCodexAppServerSpawnError = Schema.is(CodexErrors.CodexAppServerSpawnError);
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
import {
formatCodexCliUpgradeMessage,
isCodexCliVersionSupported,
parseCodexCliVersion,
} from "../codexCliVersion.ts";
import {
adjustCodexModelsForAccount,
codexAuthSubLabel,
codexAuthSubType,
type CodexAccountSnapshot,
} from "../codexAccount.ts";
import { type CodexDiscoverySnapshot, probeCodexDiscovery } from "../codexAppServer.ts";
import { BUILT_IN_CODEX_MODELS, DEFAULT_CODEX_MODEL_CAPABILITIES } from "../codexModels.ts";
import { CodexProvider } from "../Services/CodexProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ServerSettingsError } from "@t3tools/contracts";
const CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER = "2 seconds" as const;
const PROVIDER = "codex" as const;
const OPENAI_AUTH_PROVIDERS = new Set(["openai"]);
const CODEX_PRESENTATION = {
displayName: "Codex",
showInteractionModeToggle: true,
} as const;
class CodexDiscoveryCacheKey extends Data.Class<{
readonly binaryPath: string;
readonly homePath?: string;
readonly cwd: string;
}> {}
export interface CodexAppServerProviderSnapshot {
readonly account: CodexSchema.V2GetAccountResponse;
readonly version: string | undefined;
readonly models: ReadonlyArray<ServerProviderModel>;
readonly skills: ReadonlyArray<ServerProviderSkill>;
function buildInitialCodexProviderSnapshot(codexSettings: CodexSettings): ServerProvider {
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
BUILT_IN_CODEX_MODELS,
PROVIDER,
codexSettings.customModels,
DEFAULT_CODEX_MODEL_CAPABILITIES,
);
if (!codexSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
skills: [],
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Codex is disabled in T3 Code settings.",
},
});
}
return buildServerProvider({
provider: PROVIDER,
enabled: true,
checkedAt,
models,
skills: [],
probe: {
installed: true,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Checking Codex CLI availability...",
},
});
}
const REASONING_EFFORT_LABELS: Readonly<Record<string, string>> = {
@@ -324,49 +390,14 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
readonly homePath?: string;
readonly launchArgs?: string;
readonly cwd: string;
readonly customModels?: ReadonlyArray<string>;
readonly environment?: NodeJS.ProcessEnv;
}) {
// `~` is not shell-expanded when env vars are set via `child_process.spawn`,
// so `CODEX_HOME=~/.codex_work` would reach codex verbatim and trip
// "CODEX_HOME points to '~/.codex_work', but that path does not exist".
// Expand here for parity with `CodexTextGeneration`/`CodexSessionRuntime`.
const resolvedHomePath = input.homePath ? expandHomePath(input.homePath) : undefined;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const environment = {
...input.environment,
...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),
};
const spawnCommand = yield* resolveSpawnCommand(
input.binaryPath,
codexAppServerArgs(input.launchArgs),
{
env: environment,
extendEnv: true,
},
);
const child = yield* spawner
.spawn(
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
cwd: input.cwd,
env: environment,
extendEnv: true,
forceKillAfter: CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER,
shell: spawnCommand.shell,
}),
)
.pipe(
Effect.mapError(
(cause) =>
new CodexErrors.CodexAppServerSpawnError({
command: `${input.binaryPath} app-server`,
cause,
}),
),
);
const clientContext = yield* Layer.build(CodexClient.layerChildProcess(child));
const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
Effect.provide(clientContext),
}) =>
probeCodexDiscovery(input).pipe(
Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
Effect.result,
Effect.map((result) => {
if (Result.isFailure(result)) return undefined;
return Option.isSome(result.success) ? result.success.value : undefined;
}),
);
const initialize = yield* client.request("initialize", {
@@ -415,122 +446,42 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
} satisfies CodexAppServerProviderSnapshot;
});
const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] => {
const models = new Set<string>();
for (const model of codexSettings.customModels) {
const trimmed = model.trim();
if (trimmed.length > 0) {
models.add(trimmed);
}
}
return Array.from(models, (model) => ({
slug: model,
name: model,
isCustom: true,
capabilities: null,
}));
};
const makePendingCodexProvider = (
codexSettings: CodexSettings,
): Effect.Effect<ServerProviderDraft> =>
Effect.gen(function* () {
const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
const models = emptyCodexModelsFromSettings(codexSettings);
if (!codexSettings.enabled) {
return buildServerProvider({
presentation: CODEX_PRESENTATION,
enabled: false,
checkedAt,
models,
skills: [],
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Codex is disabled in T3 Code settings.",
},
});
}
return buildServerProvider({
presentation: CODEX_PRESENTATION,
enabled: true,
checkedAt,
models,
skills: [],
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Codex provider status has not been checked in this session yet.",
},
});
});
function accountProbeStatus(account: CodexAppServerProviderSnapshot["account"]): {
readonly status: Exclude<ServerProviderState, "disabled">;
readonly auth: ServerProvider["auth"];
readonly message?: string;
} {
const authLabel = codexAccountAuthLabel(account.account);
const authEmail = codexAccountEmail(account.account);
const auth = {
status: account.account ? ("authenticated" as const) : ("unknown" as const),
...(account.account?.type ? { type: account.account?.type } : {}),
...(authLabel ? { label: authLabel } : {}),
...(authEmail ? { email: authEmail } : {}),
} satisfies ServerProvider["auth"];
if (account.account) {
return { status: "ready", auth };
}
if (account.requiresOpenaiAuth) {
return {
status: "error",
auth: { status: "unauthenticated" },
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
return { status: "ready", auth };
}
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
codexSettings: CodexSettings,
probe: (input: {
resolveAccount?: (input: {
readonly binaryPath: string;
readonly homePath?: string;
}) => Effect.Effect<CodexAccountSnapshot | undefined>,
resolveSkills?: (input: {
readonly binaryPath: string;
readonly homePath?: string;
readonly launchArgs?: string;
readonly cwd: string;
readonly customModels: ReadonlyArray<string>;
readonly environment?: NodeJS.ProcessEnv;
}) => Effect.Effect<
CodexAppServerProviderSnapshot,
CodexErrors.CodexAppServerError,
ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
> = probeCodexAppServerProvider,
environment?: NodeJS.ProcessEnv,
}) => Effect.Effect<ReadonlyArray<ServerProviderSkill> | undefined>,
): Effect.fn.Return<
ServerProviderDraft,
ServerProvider,
ServerSettingsError,
ChildProcessSpawner.ChildProcessSpawner
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
| Path.Path
| ServerSettingsService
> {
const resolvedEnvironment = environment ?? process.env;
const checkedAt = DateTime.formatIso(yield* DateTime.now);
const emptyModels = emptyCodexModelsFromSettings(codexSettings);
const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.codex),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
BUILT_IN_CODEX_MODELS,
PROVIDER,
codexSettings.customModels,
DEFAULT_CODEX_MODEL_CAPABILITIES,
);
if (!codexSettings.enabled) {
return buildServerProvider({
presentation: CODEX_PRESENTATION,
provider: PROVIDER,
enabled: false,
checkedAt,
models: emptyModels,
skills: [],
models,
probe: {
installed: false,
version: null,
@@ -541,6 +492,282 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
});
}
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Codex CLI (`codex`) is not installed or not on PATH."
: `Failed to execute Codex CLI health check: ${error.message}.`,
},
});
}
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
auth: { status: "unknown" },
message: "Codex CLI is installed but failed to run. Timed out while running command.",
},
});
}
const version = versionProbe.success.value;
const parsedVersion =
parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ??
parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
auth: { status: "unknown" },
message: detail
? `Codex CLI is installed but failed to run. ${detail}`
: "Codex CLI is installed but failed to run.",
},
});
}
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
auth: { status: "unknown" },
message: formatCodexCliUpgradeMessage(parsedVersion),
},
});
}
const skills =
(resolveSkills
? yield* resolveSkills({
binaryPath: codexSettings.binaryPath,
homePath: codexSettings.homePath,
cwd: process.cwd(),
}).pipe(Effect.orElseSucceed(() => undefined))
: undefined) ?? [];
if (yield* hasCustomModelProvider) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
skills,
probe: {
installed: true,
version: parsedVersion,
status: "ready",
auth: { status: "unknown" },
message: "Using a custom Codex model provider; OpenAI login check skipped.",
},
});
}
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
const account = resolveAccount
? yield* resolveAccount({
binaryPath: codexSettings.binaryPath,
homePath: codexSettings.homePath,
})
: undefined;
const resolvedModels = adjustCodexModelsForAccount(models, account);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models: resolvedModels,
skills,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message: `Could not verify Codex authentication status: ${error.message}.`,
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models: resolvedModels,
skills,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message: "Could not verify Codex authentication status. Timed out while running command.",
},
});
}
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
const authType = codexAuthSubType(account);
const authLabel = codexAuthSubLabel(account);
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models: resolvedModels,
skills,
probe: {
installed: true,
version: parsedVersion,
status: parsed.status,
auth: {
...parsed.auth,
...(authType ? { type: authType } : {}),
...(authLabel ? { label: authLabel } : {}),
},
...(parsed.message ? { message: parsed.message } : {}),
},
});
});
const applyCodexDiscoverySnapshot = (
snapshot: ServerProvider,
discovery: CodexDiscoverySnapshot,
): ServerProvider => {
const authType = codexAuthSubType(discovery.account);
const authLabel = codexAuthSubLabel(discovery.account);
return {
...snapshot,
auth: {
...snapshot.auth,
...(authType ? { type: authType } : {}),
...(authLabel ? { label: authLabel } : {}),
},
models: adjustCodexModelsForAccount(snapshot.models, discovery.account),
skills: discovery.skills,
};
};
const enrichCodexSnapshotViaDiscovery = (input: {
readonly settings: CodexSettings;
readonly snapshot: ServerProvider;
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
readonly getDiscovery: (input: {
readonly binaryPath: string;
readonly homePath?: string;
readonly cwd: string;
}) => Effect.Effect<CodexDiscoverySnapshot | undefined>;
}) =>
(input.settings.enabled && input.snapshot.installed
? input
.getDiscovery({
binaryPath: input.settings.binaryPath,
homePath: input.settings.homePath,
cwd: process.cwd(),
})
.pipe(
Effect.flatMap((discovery) =>
discovery
? input.publishSnapshot(applyCodexDiscoverySnapshot(input.snapshot, discovery))
: Effect.void,
),
)
: Effect.void
).pipe(Effect.catchCause((cause) => Effect.logError(cause)));
export const CodexProviderLive = Layer.effect(
CodexProvider,
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const accountProbeCache = yield* Cache.make({
capacity: 4,
timeToLive: Duration.minutes(5),
lookup: (key: CodexDiscoveryCacheKey) => {
const { binaryPath, homePath, cwd } = key;
return probeCodexCapabilities({
binaryPath,
cwd,
...(homePath ? { homePath } : {}),
});
},
});
});
const getDiscovery = (input: {
readonly binaryPath: string;
readonly homePath?: string;
readonly cwd: string;
}) => Cache.get(accountProbeCache, new CodexDiscoveryCacheKey(input));
const checkProvider = checkCodexProviderStatus().pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
return yield* makeManagedServerProvider<CodexSettings>({
getSettings: serverSettings.getSettings.pipe(
Effect.map((settings) => settings.providers.codex),
Effect.orDie,
),
streamSettings: serverSettings.streamChanges.pipe(
Stream.map((settings) => settings.providers.codex),
),
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
buildInitialSnapshot: buildInitialCodexProviderSnapshot,
checkProvider,
enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
enrichCodexSnapshotViaDiscovery({
settings,
snapshot,
publishSnapshot,
getDiscovery,
}),
});
}
const probeResult = yield* probe({
binaryPath: codexSettings.binaryPath,
homePath: codexSettings.homePath,
@@ -41,19 +41,15 @@ const mockAgentPath = NodePath.join(__dirname, "../../../scripts/acp-mock-agent.
const mockAgentCommand = "node";
const mockAgentArgs = [mockAgentPath] as const;
async function makeMockAgentWrapper(
extraEnv?: Record<string, string>,
options?: { initialDelaySeconds?: number },
) {
const dir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "cursor-acp-mock-"));
const wrapperPath = NodePath.join(dir, "fake-agent.sh");
async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {
const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-acp-mock-"));
const wrapperPath = path.join(dir, "fake-agent.sh");
const envExports = Object.entries(extraEnv ?? {})
.map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
.join("\n");
const script = `#!/bin/sh
${envExports}
${options?.initialDelaySeconds ? `sleep ${JSON.stringify(String(options.initialDelaySeconds))}` : ""}
exec ${JSON.stringify(mockAgentCommand)} ${mockAgentArgs.map((arg) => JSON.stringify(arg)).join(" ")} "$@"
exec ${JSON.stringify(bunExe)} ${JSON.stringify(mockAgentPath)} "$@"
`;
await NodeFSP.writeFile(wrapperPath, script, "utf8");
await NodeFSP.chmod(wrapperPath, 0o755);
@@ -100,54 +96,6 @@ async function readJsonLines(filePath: string) {
.map((line) => JSON.parse(line) as Record<string, unknown>);
}
async function waitForFileContent(filePath: string, attempts = 40) {
for (let attempt = 0; attempt < attempts; attempt += 1) {
try {
const raw = await NodeFSP.readFile(filePath, "utf8");
if (raw.trim().length > 0) {
return raw;
}
} catch {}
await Effect.runPromise(Effect.yieldNow);
}
throw new Error(`Timed out waiting for file content at ${filePath}`);
}
function waitForJsonLogMatch(
filePath: string,
predicate: (entry: Record<string, unknown>) => boolean,
attempts = 40,
) {
return Effect.gen(function* () {
for (let attempt = 0; attempt < attempts; attempt += 1) {
const requests = yield* Effect.promise(() => readJsonLines(filePath));
if (requests.some(predicate)) {
return requests;
}
yield* Effect.yieldNow;
}
return yield* Effect.promise(() => readJsonLines(filePath));
});
}
// Tests mutate `ServerSettingsService` mid-flight (e.g. setting
// `providers.cursor.binaryPath` to a mock ACP wrapper). The adapter
// captures `cursorSettings` once at construction, so without a resolver
// the mutation is invisible — sessions would spawn the constructor's
// (empty) binary path. Wiring `resolveSettings` through
// `ServerSettingsService.getSettings` makes each session read the latest
// snapshot, matching the old "always read live" behavior that these
// tests assumed.
const makeResolveCursorSettings = Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
return yield* Effect.succeed(
serverSettings.getSettings.pipe(
Effect.map((snapshot) => snapshot.providers.cursor),
Effect.orDie,
),
);
});
const cursorAdapterTestLayer = it.layer(
Layer.effect(
CursorAdapter,
@@ -250,166 +198,6 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
}),
);
it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const settings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-steer-thread");
// Keep the first prompt in flight long enough for the steer to land.
const wrapperPath = yield* Effect.promise(() =>
makeMockAgentWrapper({ T3_ACP_PROMPT_DELAY_MS: "1500" }),
);
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
const runtimeEventsFiber = yield* adapter.streamEvents.pipe(
Stream.filter((event) => event.threadId === threadId),
Stream.takeUntil((event) => event.type === "turn.completed"),
Stream.runCollect,
Effect.forkChild,
);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
});
const firstTurnFiber = yield* adapter
.sendTurn({
threadId,
input: "run 5 commands",
attachments: [],
})
.pipe(Effect.forkChild);
// Poll until the first prompt is in flight — sendTurn binds the active
// turn id before prompting. The mock agent runs on the real clock, so
// each TestClock.adjust just provides the scheduler hops for its stdio
// responses to land.
yield* Effect.gen(function* () {
for (let attempt = 0; attempt < 200; attempt += 1) {
const sessions = yield* adapter.listSessions();
const session = sessions.find((entry) => entry.threadId === threadId);
if (session?.activeTurnId !== undefined) {
return;
}
yield* TestClock.adjust("10 millis");
}
throw new Error("Timed out waiting for the first prompt to be in flight.");
});
// Steer: a second sendTurn while the first prompt is still in flight
// continues the same turn.
const steeredTurn = yield* adapter.sendTurn({
threadId,
input: "actually run 15",
attachments: [],
});
const firstTurn = yield* Fiber.join(firstTurnFiber);
assert.equal(String(steeredTurn.turnId), String(firstTurn.turnId));
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
const turnStartedEvents = runtimeEvents.filter((event) => event.type === "turn.started");
const turnCompletedEvents = runtimeEvents.filter((event) => event.type === "turn.completed");
// One turn boundary for the whole run: the superseded first prompt
// resolving must not settle the merged turn.
assert.equal(turnStartedEvents.length, 1);
assert.equal(String(turnStartedEvents[0]?.turnId), String(firstTurn.turnId));
assert.equal(turnCompletedEvents.length, 1);
assert.equal(String(turnCompletedEvents[0]?.turnId), String(firstTurn.turnId));
yield* adapter.stopSession(threadId);
}),
);
it.effect("closes the ACP child process when a session stops", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const settings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-stop-session-close");
const tempDir = yield* Effect.promise(() =>
NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "cursor-adapter-exit-log-")),
);
const exitLogPath = NodePath.join(tempDir, "exit.log");
const wrapperPath = yield* Effect.promise(() =>
makeMockAgentWrapper({
T3_ACP_EXIT_LOG_PATH: exitLogPath,
}),
);
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
});
yield* adapter.stopSession(threadId);
const exitLog = yield* Effect.promise(() => waitForFileContent(exitLogPath));
assert.include(exitLog, "SIGTERM");
}),
);
it.effect(
"serializes concurrent startSession calls for the same thread and closes the replaced ACP session",
() =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const settings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-concurrent-start-session");
const tempDir = yield* Effect.promise(() =>
NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "cursor-adapter-concurrent-exit-log-")),
);
const exitLogPath = NodePath.join(tempDir, "exit.log");
const wrapperPath = yield* Effect.promise(() =>
makeMockAgentWrapper(
{
T3_ACP_EXIT_LOG_PATH: exitLogPath,
},
{ initialDelaySeconds: 0.2 },
),
);
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
const [firstSession, secondSession] = yield* Effect.all(
[
adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
}),
adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
}),
],
{ concurrency: "unbounded" },
);
assert.equal(firstSession.threadId, threadId);
assert.equal(secondSession.threadId, threadId);
yield* adapter.stopSession(threadId);
const exitLog = yield* Effect.promise(() => waitForFileContent(exitLogPath));
assert.equal(exitLog.match(/SIGTERM/g)?.length ?? 0, 2);
}),
);
it.effect("rejects startSession when provider mismatches", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
@@ -459,14 +247,12 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
yield* adapter.stopSession(threadId);
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
const modeRequest = requests
.toReversed()
.find(
(entry) =>
entry.method === "session/set_mode" ||
(entry.method === "session/set_config_option" &&
(entry.params as Record<string, unknown> | undefined)?.configId === "mode"),
);
const modeRequest = requests.find(
(entry) =>
entry.method === "session/set_mode" ||
(entry.method === "session/set_config_option" &&
(entry.params as Record<string, unknown> | undefined)?.configId === "mode"),
);
assert.isDefined(modeRequest);
assert.equal(
(modeRequest?.params as Record<string, unknown> | undefined)?.sessionId,
@@ -482,78 +268,6 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
}),
);
it.effect(
"applies initial model and mode configuration during startSession and skips repeating it on first send",
() =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const serverSettings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-initial-config-probe");
const tempDir = yield* Effect.promise(() =>
NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "cursor-acp-")),
);
const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
const argvLogPath = NodePath.join(tempDir, "argv.txt");
yield* Effect.promise(() => NodeFSP.writeFile(requestLogPath, "", "utf8"));
const wrapperPath = yield* Effect.promise(() =>
makeProbeWrapper(requestLogPath, argvLogPath),
);
yield* serverSettings.updateSettings({
providers: { cursor: { binaryPath: wrapperPath } },
});
const modelSelection = createModelSelection(ProviderInstanceId.make("cursor"), "gpt-5.4", [
{ id: "reasoning", value: "xhigh" },
{ id: "contextWindow", value: "1m" },
{ id: "fastMode", value: true },
]);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection,
});
yield* Effect.promise(() => waitForFileContent(requestLogPath));
const requestsAfterStart = yield* Effect.promise(() => readJsonLines(requestLogPath));
const configIdsAfterStart = requestsAfterStart.flatMap((entry) =>
entry.method === "session/set_config_option" &&
typeof (entry.params as Record<string, unknown> | undefined)?.configId === "string"
? [String((entry.params as Record<string, unknown>).configId)]
: [],
);
assert.deepStrictEqual(configIdsAfterStart, [
"model",
"reasoning",
"context",
"fast",
"mode",
]);
yield* adapter.sendTurn({
threadId,
input: "hello mock",
attachments: [],
modelSelection,
interactionMode: "default",
});
yield* adapter.stopSession(threadId);
const finalRequests = yield* Effect.promise(() => readJsonLines(requestLogPath));
const finalConfigIds = finalRequests.flatMap((entry) =>
entry.method === "session/set_config_option" &&
typeof (entry.params as Record<string, unknown> | undefined)?.configId === "string"
? [String((entry.params as Record<string, unknown>).configId)]
: [],
);
assert.deepStrictEqual(finalConfigIds, ["model", "reasoning", "context", "fast", "mode"]);
assert.equal(finalRequests.filter((entry) => entry.method === "session/prompt").length, 1);
}),
);
it.effect(
"streams ACP tool calls and approvals on the active turn in approval-required mode",
() =>
@@ -1133,92 +847,6 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
}),
);
it.effect("interrupting a session settles pending user-input waits", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const serverSettings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-interrupt-pending-user-input");
const userInputRequested = yield* Deferred.make<void>();
const wrapperPath = yield* Effect.promise(() =>
makeMockAgentWrapper({ T3_ACP_EMIT_ASK_QUESTION: "1" }),
);
yield* serverSettings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
yield* Stream.runForEach(adapter.streamEvents, (event) => {
if (String(event.threadId) !== String(threadId) || event.type !== "user-input.requested") {
return Effect.void;
}
return Deferred.succeed(userInputRequested, undefined).pipe(Effect.ignore);
}).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
});
const sendTurnFiber = yield* adapter
.sendTurn({
threadId,
input: "ask me a question and then interrupt",
attachments: [],
})
.pipe(Effect.forkChild);
yield* Deferred.await(userInputRequested);
yield* adapter.interruptTurn(threadId);
yield* Fiber.await(sendTurnFiber);
assert.equal(yield* adapter.hasSession(threadId), true);
yield* adapter.stopSession(threadId);
}),
);
it.effect("broadcasts runtime events to multiple stream consumers", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
const settings = yield* ServerSettingsService;
const threadId = ThreadId.make("cursor-runtime-event-broadcast");
const wrapperPath = yield* Effect.promise(() => makeMockAgentWrapper());
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
const firstConsumer = yield* Stream.take(adapter.streamEvents, 3).pipe(
Stream.runCollect,
Effect.forkChild,
);
const secondConsumer = yield* Stream.take(adapter.streamEvents, 3).pipe(
Stream.runCollect,
Effect.forkChild,
);
yield* adapter.startSession({
threadId,
provider: ProviderDriverKind.make("cursor"),
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
});
const firstEvents = Array.from(yield* Fiber.join(firstConsumer));
const secondEvents = Array.from(yield* Fiber.join(secondConsumer));
assert.deepStrictEqual(
firstEvents.map((event) => event.type),
["session.started", "session.state.changed", "thread.started"],
);
assert.deepStrictEqual(
secondEvents.map((event) => event.type),
["session.started", "session.state.changed", "thread.started"],
);
yield* adapter.stopSession(threadId);
}),
);
it.effect("switches model in-session via session/set_config_option", () =>
Effect.gen(function* () {
const adapter = yield* CursorAdapter;
File diff suppressed because it is too large. Load diff
@@ -1,21 +1,9 @@
import * as NodeOS from "node:os";
import * as NodeServices from "@effect/platform-node/NodeServices";
import type * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import type * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import type * as EffectAcpSchema from "effect-acp/schema";
import type { CursorSettings } from "@t3tools/contracts";
import { createModelCapabilities } from "@t3tools/shared/model";
import {
buildCursorProviderSnapshot,
buildCursorCapabilitiesFromConfigOptions,
checkCursorProviderStatus,
discoverCursorModelsViaAcp,
buildCursorDiscoveredModelsFromConfigOptions,
getCursorFallbackModels,
getCursorParameterizedModelPickerUnsupportedMessage,
parseCursorAboutOutput,
@@ -25,139 +13,6 @@ import {
resolveCursorAcpConfigUpdates,
} from "./CursorProvider.ts";
const runNode = <A, E>(
effect: Effect.Effect<
A,
E,
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem | Path.Path
>,
): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
const resolveMockAgentPath = Effect.fn("resolveMockAgentPath")(function* () {
const path = yield* Path.Path;
return yield* path.fromFileUrl(new URL("../../../scripts/acp-mock-agent.ts", import.meta.url));
});
function selectDescriptor(
id: string,
label: string,
options: ReadonlyArray<{ id: string; label: string; isDefault?: boolean }>,
) {
return {
id,
label,
type: "select" as const,
options: [...options],
...(options.find((option) => option.isDefault)?.id
? { currentValue: options.find((option) => option.isDefault)?.id }
: {}),
};
}
function booleanDescriptor(id: string, label: string, currentValue?: boolean) {
return {
id,
label,
type: "boolean" as const,
...(typeof currentValue === "boolean" ? { currentValue } : {}),
};
}
const makeMockAgentWrapper = Effect.fn("makeMockAgentWrapper")(function* (
extraEnv?: Record<string, string>,
) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const mockAgentPath = yield* resolveMockAgentPath();
const dir = yield* fileSystem.makeTempDirectory({
directory: NodeOS.tmpdir(),
prefix: "cursor-provider-mock-",
});
const wrapperPath = path.join(dir, "fake-agent.sh");
const mockAgentCommand = ["node", mockAgentPath].map((arg) => JSON.stringify(arg)).join(" ");
const envExports = Object.entries(extraEnv ?? {})
.map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
.join("\n");
const script = `#!/bin/sh
${envExports}
exec ${mockAgentCommand} "$@"
`;
yield* fileSystem.writeFileString(wrapperPath, script);
yield* fileSystem.chmod(wrapperPath, 0o755);
return wrapperPath;
});
const makeMockAgentWithAboutWrapper = Effect.fn("makeMockAgentWithAboutWrapper")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const mockAgentPath = yield* resolveMockAgentPath();
const dir = yield* fileSystem.makeTempDirectory({
directory: NodeOS.tmpdir(),
prefix: "cursor-provider-about-mock-",
});
const wrapperPath = path.join(dir, "fake-agent.sh");
const mockAgentCommand = ["node", mockAgentPath].map((arg) => JSON.stringify(arg)).join(" ");
const script = `#!/bin/sh
if [ "$1" = "about" ]; then
printf 'CLI Version 2026.04.09-f2b0fcd\\n'
printf 'User Email [email protected]\\n'
exit 0
fi
exec ${mockAgentCommand} "$@"
`;
yield* fileSystem.writeFileString(wrapperPath, script);
yield* fileSystem.chmod(wrapperPath, 0o755);
return wrapperPath;
});
const waitForFileContent = Effect.fn("waitForFileContent")(function* (
filePath: string,
attempts = 40,
) {
const fileSystem = yield* FileSystem.FileSystem;
for (let attempt = 0; attempt < attempts; attempt += 1) {
const content = yield* fileSystem
.readFileString(filePath)
.pipe(Effect.catch(() => Effect.void));
if (content !== undefined) {
if (content.trim().length > 0) {
return content;
}
}
yield* Effect.sleep("50 millis");
}
return yield* Effect.die(`Timed out waiting for file content at ${filePath}`);
});
const makeProviderStatusEnvFixture = Effect.fn("makeProviderStatusEnvFixture")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fileSystem.makeTempDirectory({
directory: NodeOS.tmpdir(),
prefix: "cursor-provider-status-env-",
});
return {
requestLogPath: path.join(tempDir, "requests.ndjson"),
wrapperPath: yield* makeMockAgentWithAboutWrapper(),
};
});
const makeExitLogFixture = Effect.fn("makeExitLogFixture")(function* (prefix: string) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fileSystem.makeTempDirectory({
directory: NodeOS.tmpdir(),
prefix,
});
const exitLogPath = path.join(tempDir, "exit.log");
return {
exitLogPath,
wrapperPath: yield* makeMockAgentWrapper({
T3_ACP_EXIT_LOG_PATH: exitLogPath,
}),
};
});
const parameterizedGpt54ConfigOptions = [
{
type: "select",
@@ -235,39 +90,33 @@ const parameterizedClaudeConfigOptions = [
},
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
const parameterizedClaudeModelOptionConfigOptions = [
const sessionNewCursorConfigOptions = [
{
type: "select",
currentValue: "claude-opus-4-6",
options: [{ name: "Opus 4.6", value: "claude-opus-4-6" }],
currentValue: "agent",
options: [
{ name: "Agent", value: "agent", description: "Full agent capabilities with tool access" },
],
category: "mode",
id: "mode",
name: "Mode",
description: "Controls how the agent executes tasks",
},
{
type: "select",
currentValue: "composer-2",
options: [
{ name: "Auto", value: "default" },
{ name: "Composer 2", value: "composer-2" },
{ name: "GPT-5.4", value: "gpt-5.4" },
{ name: "Sonnet 4.6", value: "claude-sonnet-4-6" },
{ name: "Opus 4.6", value: "claude-opus-4-6" },
{ name: "Codex 5.3 Spark", value: "gpt-5.3-codex-spark" },
],
category: "model",
id: "model",
name: "Model",
},
{
type: "select",
currentValue: "high",
options: [
{ name: "Low", value: "low" },
{ name: "Medium", value: "medium" },
{ name: "High", value: "high" },
],
category: "thought_level",
id: "reasoning",
name: "Reasoning",
},
{
type: "select",
currentValue: "max",
options: [
{ name: "Low", value: "low" },
{ name: "Medium", value: "medium" },
{ name: "High", value: "high" },
{ name: "Max", value: "max" },
],
category: "model_option",
id: "effort",
name: "Effort",
description: "Controls which model is used for responses",
},
{
type: "select",
@@ -279,39 +128,10 @@ const parameterizedClaudeModelOptionConfigOptions = [
category: "model_config",
id: "fast",
name: "Fast",
},
{
type: "select",
currentValue: "true",
options: [
{ name: "Off", value: "false" },
{ name: ":icon-brain:", value: "true" },
],
category: "model_config",
id: "thinking",
name: "Thinking",
description: "Faster speeds.",
},
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
const baseCursorSettings: CursorSettings = {
enabled: true,
binaryPath: "cursor-agent",
apiEndpoint: "",
customModels: [],
};
const cursorAcpDiscoveryFailedMessage = [
"Cursor ACP model discovery failed.",
"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart T3 Code, and try again.",
"See https://cursor.com/docs/cli/installation.",
"Check server logs for ACP details.",
].join(" ");
const missingCursorBinaryPath = "/definitely/not/installed/t3-cursor-agent";
const cursorCliCommandMissingMessage = [
`Cursor CLI command \`${missingCursorBinaryPath}\` was not found.`,
`Install or enable the Cursor CLI, make sure \`${missingCursorBinaryPath}\` is on PATH, then restart T3 Code.`,
"See https://cursor.com/docs/cli/installation.",
].join(" ");
describe("getCursorFallbackModels", () => {
it("does not publish any built-in cursor models before ACP discovery", () => {
expect(
@@ -322,55 +142,6 @@ describe("getCursorFallbackModels", () => {
});
});
describe("buildCursorProviderSnapshot", () => {
it("downgrades ready status to warning when ACP model discovery times out", () => {
expect(
buildCursorProviderSnapshot({
checkedAt: "2026-01-01T00:00:00.000Z",
cursorSettings: baseCursorSettings,
parsed: {
version: "2026.04.09-f2b0fcd",
status: "ready",
auth: { status: "authenticated", type: "Team", label: "Cursor Team Subscription" },
},
discoveryWarning: "Cursor ACP model discovery timed out after 15000ms.",
}),
).toMatchObject({
status: "warning",
message: "Cursor ACP model discovery timed out after 15000ms.",
models: [],
});
});
it("preserves provider error state while appending discovery warnings", () => {
expect(
buildCursorProviderSnapshot({
checkedAt: "2026-01-01T00:00:00.000Z",
cursorSettings: {
...baseCursorSettings,
customModels: ["claude-sonnet-4-6"],
},
parsed: {
version: "2026.04.09-f2b0fcd",
status: "error",
auth: { status: "unauthenticated" },
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
},
discoveryWarning: cursorAcpDiscoveryFailedMessage,
}),
).toMatchObject({
status: "error",
message: `Cursor Agent is not authenticated. Run \`agent login\` and try again. ${cursorAcpDiscoveryFailedMessage}`,
models: [
{
slug: "claude-sonnet-4-6",
isCustom: true,
},
],
});
});
});
describe("buildCursorCapabilitiesFromConfigOptions", () => {
it("derives model capabilities from parameterized Cursor ACP config options", () => {
expect(buildCursorCapabilitiesFromConfigOptions(parameterizedGpt54ConfigOptions)).toEqual(
@@ -406,25 +177,6 @@ describe("buildCursorCapabilitiesFromConfigOptions", () => {
}),
);
});
it("prefers the newer model_option effort control over legacy thought_level", () => {
expect(
buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeModelOptionConfigOptions),
).toEqual(
createModelCapabilities({
optionDescriptors: [
selectDescriptor("reasoning", "Effort", [
{ id: "low", label: "Low" },
{ id: "medium", label: "Medium" },
{ id: "high", label: "High" },
{ id: "max", label: "Max", isDefault: true },
]),
booleanDescriptor("fastMode", "Fast", true),
booleanDescriptor("thinking", "Thinking", true),
],
}),
);
});
});
describe("checkCursorProviderStatus", () => {
@@ -474,46 +226,6 @@ describe("checkCursorProviderStatus", () => {
});
});
describe("discoverCursorModelsViaAcp", () => {
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
const wrapperPath = await runNode(makeMockAgentWrapper());
const models = await runNode(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}).pipe(Effect.scoped),
);
expect(models.map((model) => model.slug)).toEqual([
"default",
"composer-2",
"gpt-5.4",
"claude-opus-4-6",
]);
});
it("closes the ACP probe runtime after discovery completes", async () => {
const { exitLogPath, wrapperPath } = await runNode(
makeExitLogFixture("cursor-provider-exit-log-"),
);
await runNode(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}),
);
const exitLog = await runNode(waitForFileContent(exitLogPath));
expect(exitLog).toContain("SIGTERM");
});
});
describe("parseCursorAboutOutput", () => {
it("parses json about output and forwards subscription metadata", () => {
expect(
@@ -665,16 +377,4 @@ describe("resolveCursorAcpConfigUpdates", () => {
]),
).toEqual([{ configId: "fast", value: "false" }]);
});
it("writes Cursor effort changes through the newer model_option config when available", () => {
expect(
resolveCursorAcpConfigUpdates(parameterizedClaudeModelOptionConfigOptions, [
{ id: "reasoning", value: "max" },
{ id: "thinking", value: false },
]),
).toEqual([
{ configId: "effort", value: "max" },
{ configId: "thinking", value: "false" },
]);
});
});
@@ -281,7 +281,28 @@ type EventBaseInput = {
readonly requestId?: string | undefined;
readonly createdAt?: string | undefined;
readonly raw?: unknown;
};
}): Pick<
ProviderRuntimeEvent,
"eventId" | "provider" | "threadId" | "createdAt" | "turnId" | "itemId" | "requestId" | "raw"
> {
return {
eventId: EventId.make(randomUUID()),
provider: PROVIDER,
threadId: input.threadId,
createdAt: input.createdAt ?? nowIso(),
...(input.turnId ? { turnId: input.turnId } : {}),
...(input.itemId ? { itemId: RuntimeItemId.make(input.itemId) } : {}),
...(input.requestId ? { requestId: RuntimeRequestId.make(input.requestId) } : {}),
...(input.raw !== undefined
? {
raw: {
source: "opencode.sdk.event",
payload: input.raw,
} as unknown as ProviderRuntimeEvent["raw"],
}
: {}),
};
}
function toToolLifecycleItemType(toolName: string): ToolLifecycleItemType {
const normalized = toolName.toLowerCase();
@@ -10,16 +10,12 @@ import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Stream from "effect/Stream";
import type * as ClaudeAdapter from "../Services/ClaudeAdapter.ts";
import type * as CodexAdapter from "../Services/CodexAdapter.ts";
import type * as CursorAdapter from "../Services/CursorAdapter.ts";
import type * as OpenCodeAdapter from "../Services/OpenCodeAdapter.ts";
import * as ProviderAdapterRegistry from "../Services/ProviderAdapterRegistry.ts";
import * as ProviderInstanceRegistry from "../Services/ProviderInstanceRegistry.ts";
import type { ProviderInstance } from "../ProviderDriver.ts";
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
import type * as TextGeneration from "../../textGeneration/TextGeneration.ts";
import * as ProviderAdapterRegistryLayer from "./ProviderAdapterRegistry.ts";
import { ClaudeAdapter, type ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter, type CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { CursorAdapter, type CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
import { ProviderUnsupportedError } from "../Errors.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
const CODEX_DRIVER = ProviderDriverKind.make("codex");
@@ -61,8 +57,8 @@ const fakeClaudeAdapter: ClaudeAdapter.ClaudeAdapterShape = {
streamEvents: Stream.empty,
};
const fakeOpenCodeAdapter: OpenCodeAdapter.OpenCodeAdapterShape = {
provider: OPENCODE_DRIVER,
const fakeCursorAdapter: CursorAdapterShape = {
provider: "cursor",
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
sendTurn: vi.fn(),
@@ -78,78 +74,17 @@ const fakeOpenCodeAdapter: OpenCodeAdapter.OpenCodeAdapterShape = {
streamEvents: Stream.empty,
};
const fakeCursorAdapter: CursorAdapter.CursorAdapterShape = {
provider: CURSOR_DRIVER,
capabilities: { sessionModelSwitch: "in-session" },
startSession: vi.fn(),
sendTurn: vi.fn(),
interruptTurn: vi.fn(),
respondToRequest: vi.fn(),
respondToUserInput: vi.fn(),
stopSession: vi.fn(),
listSessions: vi.fn(),
hasSession: vi.fn(),
readThread: vi.fn(),
rollbackThread: vi.fn(),
stopAll: vi.fn(),
streamEvents: Stream.empty,
};
// ProviderAdapterRegistryLive is now a facade over ProviderInstanceRegistry —
// it walks `listInstances` once at boot and surfaces the default-instance
// adapter keyed by its driver kind. To test the facade we supply four fake
// instances whose `instanceId === defaultInstanceIdForDriver(driverKind)` so
// they pass the default-instance filter.
const makeFakeInstance = (
driverKindString: "codex" | "claudeAgent" | "cursor" | "opencode",
adapter: ProviderInstance["adapter"],
): ProviderInstance => {
const driverKind = ProviderDriverKind.make(driverKindString);
return {
instanceId: defaultInstanceIdForDriver(driverKind),
driverKind,
continuationIdentity: {
driverKind,
continuationKey: `${driverKind}:instance:${defaultInstanceIdForDriver(driverKind)}`,
},
displayName: undefined,
enabled: true,
snapshot: {
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
provider: driverKind,
packageName: null,
}),
getSnapshot: Effect.succeed({} as unknown as ServerProvider),
refresh: Effect.succeed({} as unknown as ServerProvider),
streamChanges: Stream.empty,
},
adapter,
textGeneration: {} as unknown as TextGeneration.TextGeneration["Service"],
};
};
const fakeInstances: ReadonlyArray<ProviderInstance> = [
makeFakeInstance("codex", fakeCodexAdapter),
makeFakeInstance("claudeAgent", fakeClaudeAdapter),
makeFakeInstance("opencode", fakeOpenCodeAdapter),
makeFakeInstance("cursor", fakeCursorAdapter),
];
const fakeInstanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, {
getInstance: (instanceId) =>
Effect.succeed(fakeInstances.find((instance) => instance.instanceId === instanceId)),
listInstances: Effect.succeed(fakeInstances),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
// Tests never drive changes through this fake; acquire a throwaway
// subscription on an unused PubSub so the shape is satisfied.
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) => PubSub.subscribe(pubsub)),
});
const layer = Layer.mergeAll(
Layer.provide(
ProviderAdapterRegistryLayer.ProviderAdapterRegistryLive,
fakeInstanceRegistryLayer,
const layer = it.layer(
Layer.mergeAll(
Layer.provide(
ProviderAdapterRegistryLive,
Layer.mergeAll(
Layer.succeed(CodexAdapter, fakeCodexAdapter),
Layer.succeed(ClaudeAdapter, fakeClaudeAdapter),
Layer.succeed(CursorAdapter, fakeCursorAdapter),
),
),
NodeServices.layer,
),
NodeServices.layer,
);
@@ -157,39 +92,24 @@ const layer = Layer.mergeAll(
it.layer(layer)("ProviderAdapterRegistryLive", (it) => {
it("resolves adapters and routing metadata from provider instances", () =>
Effect.gen(function* () {
const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistry;
const claudeInstanceId = defaultInstanceIdForDriver(CLAUDE_AGENT_DRIVER);
const adapter = yield* registry.getByInstance(claudeInstanceId);
assert.strictEqual(adapter, fakeClaudeAdapter);
const info = yield* registry.getInstanceInfo(claudeInstanceId);
assert.deepStrictEqual(info, {
instanceId: claudeInstanceId,
driverKind: CLAUDE_AGENT_DRIVER,
displayName: undefined,
accentColor: undefined,
enabled: true,
continuationIdentity: {
driverKind: CLAUDE_AGENT_DRIVER,
continuationKey: "claudeAgent:instance:claudeAgent",
},
});
const instances = yield* registry.listInstances();
assert.deepStrictEqual(instances, [
defaultInstanceIdForDriver(CODEX_DRIVER),
claudeInstanceId,
defaultInstanceIdForDriver(OPENCODE_DRIVER),
defaultInstanceIdForDriver(CURSOR_DRIVER),
]);
const registry = yield* ProviderAdapterRegistry;
const codex = yield* registry.getByProvider("codex");
const claude = yield* registry.getByProvider("claudeAgent");
const cursor = yield* registry.getByProvider("cursor");
assert.equal(codex, fakeCodexAdapter);
assert.equal(claude, fakeClaudeAdapter);
assert.equal(cursor, fakeCursorAdapter);
const providers = yield* registry.listProviders();
assert.deepStrictEqual(providers, [
CODEX_DRIVER,
CLAUDE_AGENT_DRIVER,
OPENCODE_DRIVER,
CURSOR_DRIVER,
]);
}));
assert.deepEqual(providers, ["codex", "claudeAgent", "cursor"]);
}),
);
it.effect("fails with ProviderUnsupportedError for unknown providers", () =>
Effect.gen(function* () {
const registry = yield* ProviderAdapterRegistry;
const adapter = yield* registry.getByProvider("unknown" as ProviderKind).pipe(Effect.result);
assertFailure(adapter, new ProviderUnsupportedError({ provider: "unknown" }));
}),
);
});
@@ -29,22 +29,22 @@ import {
ProviderAdapterRegistry,
type ProviderAdapterRegistryShape,
} from "../Services/ProviderAdapterRegistry.ts";
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import { CursorAdapter } from "../Services/CursorAdapter.ts";
const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* () {
const registry = yield* ProviderInstanceRegistry;
const getByInstance: ProviderAdapterRegistryShape["getByInstance"] = (instanceId) =>
registry.getInstance(instanceId).pipe(
Effect.flatMap((instance) =>
instance === undefined
? Effect.fail(
new ProviderUnsupportedError({
provider: instanceId,
}),
)
: Effect.succeed(instance.adapter),
),
);
const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* (
options?: ProviderAdapterRegistryLiveOptions,
) {
const cursorAdapterOption = yield* Effect.serviceOption(CursorAdapter);
const adapters =
options?.adapters !== undefined
? options.adapters
: [yield* CodexAdapter, yield* ClaudeAdapter, yield* CursorAdapter];
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
const getInstanceInfo: ProviderAdapterRegistryShape["getInstanceInfo"] = (instanceId) =>
registry.getInstance(instanceId).pipe(
@@ -1498,20 +1498,23 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
);
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry.ProviderRegistry;
let providers = yield* registry.getProviders;
for (
let attempts = 0;
attempts < 50 &&
providers.find((provider) => provider.instanceId === "codex_personal")?.status !==
"error";
attempts += 1
) {
yield* Effect.yieldNow;
providers = yield* registry.getProviders;
const registry = yield* ProviderRegistry;
const initial = yield* registry.getProviders;
assert.deepStrictEqual(Array.isArray(initial), true);
for (let attempt = 0; attempt < 100; attempt += 1) {
const refreshed = yield* registry.getProviders;
if (refreshed.find((status) => status.provider === "codex")?.status === "ready") {
break;
}
yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 5)));
}
const codexPersonal = providers.find(
(provider) => provider.instanceId === "codex_personal",
const ready = yield* registry.getProviders;
assert.strictEqual(
ready.find((status) => status.provider === "codex")?.status,
"ready",
);
assert.notStrictEqual(
codexPersonal,
@@ -39,6 +39,8 @@ describe("AcpSessionRuntime", () => {
_meta: { parameterizedModelPicker: true },
},
});
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -78,7 +80,7 @@ describe("AcpSessionRuntime", () => {
});
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.events, 4)));
expect(notes).toHaveLength(4);
expect(notes.map((note) => note._tag)).toEqual([
"PlanUpdated",
@@ -99,6 +101,8 @@ describe("AcpSessionRuntime", () => {
) {
expect(assistantDelta.itemId).toBe(assistantStart.itemId);
}
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -279,7 +283,7 @@ describe("AcpSessionRuntime", () => {
});
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 7)));
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.events, 7)));
expect(notes.map((note) => note._tag)).toEqual([
"AssistantItemStarted",
"ContentDelta",
@@ -310,6 +314,8 @@ describe("AcpSessionRuntime", () => {
expect(secondStarted.itemId).not.toBe(firstStarted.itemId);
expect(secondDelta.itemId).toBe(secondStarted.itemId);
}
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -340,7 +346,7 @@ describe("AcpSessionRuntime", () => {
});
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 1)));
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.events, 1)));
expect(notes.map((note) => note._tag)).toEqual(["ToolCallUpdated"]);
const toolCall = notes[0];
expect(toolCall?._tag).toBe("ToolCallUpdated");
@@ -348,6 +354,8 @@ describe("AcpSessionRuntime", () => {
expect(toolCall.toolCall.status).toBe("completed");
expect(toolCall.toolCall.title).toBe("Read file");
}
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -399,41 +407,8 @@ describe("AcpSessionRuntime", () => {
(event) => event.method === "session/prompt" && event.status === "succeeded",
),
).toBe(true);
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
requestLogger: (event) =>
Effect.sync(() => {
requestEvents.push(event);
}),
}),
),
Effect.scoped,
Effect.provide(NodeServices.layer),
);
});
it.effect("skips no-op session config writes when the requested value is already active", () => {
const requestEvents: Array<AcpSessionRuntime.AcpSessionRequestLogEvent> = [];
return Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
yield* runtime.start();
yield* runtime.setConfigOption("model", "default");
yield* runtime.setMode("ask");
expect(
requestEvents.some(
(event) => event.method === "session/set_config_option" && event.status === "started",
),
).toBe(false);
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -477,6 +452,8 @@ describe("AcpSessionRuntime", () => {
expect(
protocolEvents.some((event) => event.direction === "incoming" && event.stage === "decoded"),
).toBe(true);
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -622,7 +599,9 @@ describe("AcpSessionRuntime", () => {
expect(error.message).toContain("composer-2[fast=true]");
}
const recordedRequests = NodeFS.readFileSync(requestLogPath, "utf8")
yield* runtime.close;
const recordedRequests = readFileSync(requestLogPath, "utf8")
.trim()
.split("\n")
.filter((line) => line.length > 0)
@@ -634,6 +613,8 @@ describe("AcpSessionRuntime", () => {
message.params?.value === "composer-2[fast=false]",
),
).toBe(false);
rmSync(tempDir, { recursive: true, force: true });
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -651,7 +632,6 @@ describe("AcpSessionRuntime", () => {
),
Effect.scoped,
Effect.provide(NodeServices.layer),
Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
);
});
});
@@ -255,24 +255,6 @@ describe("AcpRuntimeModel", () => {
}
});
it("trims padded current mode updates before emitting a mode change", () => {
const result = parseSessionUpdateEvent({
sessionId: "session-1",
update: {
sessionUpdate: "current_mode_update",
currentModeId: " code ",
},
} satisfies EffectAcpSchema.SessionNotification);
expect(result.modeId).toBe("code");
expect(result.events).toEqual([
{
_tag: "ModeChanged",
modeId: "code",
},
]);
});
it("projects typed ACP plan and content updates", () => {
const planResult = parseSessionUpdateEvent({
sessionId: "session-1",
@@ -515,13 +515,11 @@ export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotificat
switch (upd.sessionUpdate) {
case "current_mode_update": {
modeId = upd.currentModeId.trim();
if (modeId) {
events.push({
_tag: "ModeChanged",
modeId,
});
}
modeId = upd.currentModeId;
events.push({
_tag: "ModeChanged",
modeId,
});
break;
}
case "plan": {
+71 -222
View File
@@ -96,155 +96,48 @@ export interface AcpSessionRuntimeStartResult {
readonly modelConfigId: string | undefined;
}
export class AcpSessionRuntime extends Context.Service<
AcpSessionRuntime,
{
/**
* Registers a handler for `session/request_permission`.
* @see https://agentclientprotocol.com/protocol/schema#session/request_permission
*/
readonly handleRequestPermission: EffectAcpClient.AcpClient["Service"]["handleRequestPermission"];
/**
* Registers a handler for `session/elicitation`.
* @see https://agentclientprotocol.com/protocol/schema#session/elicitation
*/
readonly handleElicitation: EffectAcpClient.AcpClient["Service"]["handleElicitation"];
/**
* Registers a handler for `fs/read_text_file`.
* @see https://agentclientprotocol.com/protocol/schema#fs/read_text_file
*/
readonly handleReadTextFile: EffectAcpClient.AcpClient["Service"]["handleReadTextFile"];
/**
* Registers a handler for `fs/write_text_file`.
* @see https://agentclientprotocol.com/protocol/schema#fs/write_text_file
*/
readonly handleWriteTextFile: EffectAcpClient.AcpClient["Service"]["handleWriteTextFile"];
/**
* Registers a handler for `terminal/create`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/create
*/
readonly handleCreateTerminal: EffectAcpClient.AcpClient["Service"]["handleCreateTerminal"];
/**
* Registers a handler for `terminal/output`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/output
*/
readonly handleTerminalOutput: EffectAcpClient.AcpClient["Service"]["handleTerminalOutput"];
/**
* Registers a handler for `terminal/wait_for_exit`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/wait_for_exit
*/
readonly handleTerminalWaitForExit: EffectAcpClient.AcpClient["Service"]["handleTerminalWaitForExit"];
/**
* Registers a handler for `terminal/kill`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/kill
*/
readonly handleTerminalKill: EffectAcpClient.AcpClient["Service"]["handleTerminalKill"];
/**
* Registers a handler for `terminal/release`.
* @see https://agentclientprotocol.com/protocol/schema#terminal/release
*/
readonly handleTerminalRelease: EffectAcpClient.AcpClient["Service"]["handleTerminalRelease"];
/**
* Registers a handler for `session/update`.
* @see https://agentclientprotocol.com/protocol/schema#session/update
*/
readonly handleSessionUpdate: EffectAcpClient.AcpClient["Service"]["handleSessionUpdate"];
/**
* Registers a handler for `session/elicitation/complete`.
* @see https://agentclientprotocol.com/protocol/schema#session/elicitation/complete
*/
readonly handleElicitationComplete: EffectAcpClient.AcpClient["Service"]["handleElicitationComplete"];
/**
* Registers a fallback extension request handler.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly handleUnknownExtRequest: EffectAcpClient.AcpClient["Service"]["handleUnknownExtRequest"];
/**
* Registers a fallback extension notification handler.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly handleUnknownExtNotification: EffectAcpClient.AcpClient["Service"]["handleUnknownExtNotification"];
/**
* Registers a typed extension request handler.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly handleExtRequest: EffectAcpClient.AcpClient["Service"]["handleExtRequest"];
/**
* Registers a typed extension notification handler.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly handleExtNotification: EffectAcpClient.AcpClient["Service"]["handleExtNotification"];
/**
* Initializes the ACP connection, authenticates, and loads, resumes, or creates the session.
* Concurrent calls share the same in-flight startup and a failed startup may be retried.
*/
readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
/** Stream of parsed ACP session events emitted after startup. */
readonly getEvents: () => Stream.Stream<AcpSessionRuntimeEvent, never>;
/** Waits until the current event consumer has processed every queued event. */
readonly drainEvents: Effect.Effect<void>;
/** Latest mode state observed from session setup and `session/update` notifications. */
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
/** Latest configuration options observed from session setup and configuration writes. */
readonly getConfigOptions: Effect.Effect<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
/**
* Sends a prompt turn to the active session.
* @see https://agentclientprotocol.com/protocol/schema#session/prompt
*/
readonly prompt: (
payload: Omit<EffectAcpSchema.PromptRequest, "sessionId">,
) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;
/**
* Sends a real ACP `session/cancel` notification for the active session.
* @see https://agentclientprotocol.com/protocol/schema#session/cancel
*/
readonly cancel: Effect.Effect<void, EffectAcpErrors.AcpError>;
/**
* Selects the active mode through the negotiated `mode` configuration option.
* This is a no-op when the requested mode is already active.
* @see https://agentclientprotocol.com/protocol/schema#session/set_config_option
*/
readonly setMode: (
modeId: string,
) => Effect.Effect<EffectAcpSchema.SetSessionModeResponse, EffectAcpErrors.AcpError>;
/**
* Updates a session configuration option and the runtime configuration snapshot.
* @see https://agentclientprotocol.com/protocol/schema#session/set_config_option
*/
readonly setConfigOption: (
configId: string,
value: string | boolean,
) => Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError>;
/**
* Selects the base model through the negotiated model configuration option.
* @see https://agentclientprotocol.com/protocol/schema#session/set_config_option
*/
readonly setModel: (model: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;
/**
* Selects the active model through the unstable ACP `session/set_model` capability.
* @see https://agentclientprotocol.com/protocol/schema#session/set_model
*/
readonly setSessionModel: (
modelId: string,
) => Effect.Effect<EffectAcpSchema.SetSessionModelResponse, EffectAcpErrors.AcpError>;
/**
* Sends a generic ACP extension request and records it through the request logger.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly request: (
method: string,
payload: unknown,
) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;
/**
* Sends a generic ACP extension notification.
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly notify: (
method: string,
payload: unknown,
) => Effect.Effect<void, EffectAcpErrors.AcpError>;
}
>()("t3/provider/acp/AcpSessionRuntime") {}
export interface AcpSessionRuntimeShape {
readonly handleRequestPermission: EffectAcpClient.AcpClientShape["handleRequestPermission"];
readonly handleElicitation: EffectAcpClient.AcpClientShape["handleElicitation"];
readonly handleReadTextFile: EffectAcpClient.AcpClientShape["handleReadTextFile"];
readonly handleWriteTextFile: EffectAcpClient.AcpClientShape["handleWriteTextFile"];
readonly handleCreateTerminal: EffectAcpClient.AcpClientShape["handleCreateTerminal"];
readonly handleTerminalOutput: EffectAcpClient.AcpClientShape["handleTerminalOutput"];
readonly handleTerminalWaitForExit: EffectAcpClient.AcpClientShape["handleTerminalWaitForExit"];
readonly handleTerminalKill: EffectAcpClient.AcpClientShape["handleTerminalKill"];
readonly handleTerminalRelease: EffectAcpClient.AcpClientShape["handleTerminalRelease"];
readonly handleSessionUpdate: EffectAcpClient.AcpClientShape["handleSessionUpdate"];
readonly handleElicitationComplete: EffectAcpClient.AcpClientShape["handleElicitationComplete"];
readonly handleUnknownExtRequest: EffectAcpClient.AcpClientShape["handleUnknownExtRequest"];
readonly handleUnknownExtNotification: EffectAcpClient.AcpClientShape["handleUnknownExtNotification"];
readonly handleExtRequest: EffectAcpClient.AcpClientShape["handleExtRequest"];
readonly handleExtNotification: EffectAcpClient.AcpClientShape["handleExtNotification"];
readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
readonly events: Stream.Stream<AcpParsedSessionEvent, never>;
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
readonly getConfigOptions: Effect.Effect<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
readonly prompt: (
payload: Omit<EffectAcpSchema.PromptRequest, "sessionId">,
) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;
readonly cancel: Effect.Effect<void, EffectAcpErrors.AcpError>;
readonly setMode: (
modeId: string,
) => Effect.Effect<EffectAcpSchema.SetSessionModeResponse, EffectAcpErrors.AcpError>;
readonly setConfigOption: (
configId: string,
value: string | boolean,
) => Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError>;
readonly setModel: (model: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;
readonly request: (
method: string,
payload: unknown,
) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;
readonly notify: (
method: string,
payload: unknown,
) => Effect.Effect<void, EffectAcpErrors.AcpError>;
readonly close: Effect.Effect<void>;
}
interface AcpStartedState extends AcpSessionRuntimeStartResult {}
@@ -271,13 +164,13 @@ export const make = (
): Effect.Effect<
AcpSessionRuntime["Service"],
EffectAcpErrors.AcpError,
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope
ChildProcessSpawner.ChildProcessSpawner
> =>
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const runtimeScope = yield* Scope.Scope;
const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>();
const runtimeScope = yield* Scope.make("sequential");
const eventQueue = yield* Queue.unbounded<AcpParsedSessionEvent>();
const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());
const assistantItemRuntimeId = yield* crypto.randomUUIDv4.pipe(
@@ -403,6 +296,8 @@ export const make = (
});
}),
);
const close = Scope.close(runtimeScope, Exit.void).pipe(Effect.asVoid);
const initializeClientCapabilities = {
fs: {
readTextFile: false,
@@ -485,47 +380,32 @@ export const make = (
| EffectAcpSchema.ResumeSessionResponse,
): Effect.Effect<void> => Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(response));
const updateCurrentModeId = (modeId: string): Effect.Effect<void> =>
Ref.update(modeStateRef, (current) =>
current ? { ...current, currentModeId: modeId } : current,
);
const setConfigOption = (
configId: string,
value: string | boolean,
): Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError> =>
validateConfigOptionValue(configId, value).pipe(
Effect.flatMap(() => getStartedState),
Effect.flatMap((started) =>
Ref.get(configOptionsRef).pipe(
Effect.flatMap((configOptions) => {
const existing = findSessionConfigOption(configOptions, configId);
if (existing && configOptionCurrentValueMatches(existing, value)) {
return Effect.succeed({
configOptions,
} satisfies EffectAcpSchema.SetSessionConfigOptionResponse);
}
const requestPayload =
typeof value === "boolean"
? ({
sessionId: started.sessionId,
configId,
type: "boolean",
value,
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest)
: ({
sessionId: started.sessionId,
configId,
value: String(value),
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest);
return runLoggedRequest(
"session/set_config_option",
requestPayload,
acp.agent.setSessionConfigOption(requestPayload),
).pipe(Effect.tap((response) => updateConfigOptions(response)));
}),
),
),
Effect.flatMap((started) => {
const requestPayload =
typeof value === "boolean"
? ({
sessionId: started.sessionId,
configId,
type: "boolean",
value,
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest)
: ({
sessionId: started.sessionId,
configId,
value: String(value),
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest);
return runLoggedRequest(
"session/set_config_option",
requestPayload,
acp.agent.setSessionConfigOption(requestPayload),
).pipe(Effect.tap((response) => updateConfigOptions(response)));
}),
);
const startOnce = Effect.gen(function* () {
@@ -705,15 +585,7 @@ export const make = (
handleExtRequest: acp.handleExtRequest,
handleExtNotification: acp.handleExtNotification,
start: () => start,
getEvents: () => Stream.fromQueue(eventQueue),
drainEvents: Effect.gen(function* () {
const acknowledge = yield* Deferred.make<void>();
yield* Queue.offer(eventQueue, {
_tag: "EventStreamBarrier",
acknowledge,
});
yield* Deferred.await(acknowledge);
}),
events: Stream.fromQueue(eventQueue),
getModeState: Ref.get(modeStateRef),
getConfigOptions: Ref.get(configOptionsRef),
prompt: (payload) =>
@@ -772,17 +644,7 @@ export const make = (
),
),
setMode: (modeId) =>
Ref.get(modeStateRef).pipe(
Effect.flatMap((modeState) => {
if (modeState?.currentModeId === modeId) {
return Effect.succeed({} satisfies EffectAcpSchema.SetSessionModeResponse);
}
return setConfigOption("mode", modeId).pipe(
Effect.tap(() => updateCurrentModeId(modeId)),
Effect.as({} satisfies EffectAcpSchema.SetSessionModeResponse),
);
}),
),
getStartedState.pipe(Effect.flatMap(() => setConfigOption("mode", modeId))),
setConfigOption,
setModel: (model) =>
getStartedState.pipe(
@@ -806,7 +668,8 @@ export const make = (
request: (method, payload) =>
runLoggedRequest(method, payload, acp.raw.request(method, payload)),
notify: acp.raw.notify,
} satisfies AcpSessionRuntime["Service"];
close,
} satisfies AcpSessionRuntimeShape;
});
export const layer = (
@@ -827,20 +690,6 @@ function sessionConfigOptionsFromSetup(
return response?.configOptions ?? [];
}
function configOptionCurrentValueMatches(
configOption: EffectAcpSchema.SessionConfigOption,
value: string | boolean,
): boolean {
const currentValue = configOption.currentValue;
if (configOption.type === "boolean") {
return currentValue === value;
}
if (typeof currentValue !== "string") {
return false;
}
return currentValue.trim() === String(value).trim();
}
const handleSessionUpdate = ({
queue,
modeStateRef,
@@ -17,6 +17,7 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
const started = yield* runtime.start();
expect(started.initializeResult).toBeDefined();
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -57,10 +58,7 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
if (Array.isArray(configOptions)) {
const modelConfig = configOptions.find((opt) => opt.category === "model");
const parameterizedOptions = configOptions.filter(
(opt) =>
opt.category === "thought_level" ||
opt.category === "model_option" ||
opt.category === "model_config",
(opt) => opt.category === "thought_level" || opt.category === "model_config",
);
// @effect-diagnostics-next-line preferSchemaOverJson:off
yield* Console.log("Model config option:", JSON.stringify(modelConfig, null, 2));
@@ -72,6 +70,7 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
expect(modelConfig).toBeDefined();
expect(typeof modelConfig?.id).toBe("string");
}
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -118,16 +117,14 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
if (Array.isArray(setResult.configOptions)) {
const modelConfig = setResult.configOptions.find((opt) => opt.category === "model");
const parameterizedOptions = setResult.configOptions.filter(
(opt) =>
opt.category === "thought_level" ||
opt.category === "model_option" ||
opt.category === "model_config",
(opt) => opt.category === "thought_level" || opt.category === "model_config",
);
if (modelConfig?.type === "select") {
expect(modelConfig.currentValue).toBe("gpt-5.4");
}
expect(parameterizedOptions.length).toBeGreaterThan(0);
}
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -1,9 +1,6 @@
import { type CursorSettings, type ProviderOptionSelection } from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Scope from "effect/Scope";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { type CursorModelOptions, type CursorSettings } from "@t3tools/contracts";
import { Effect, Layer } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import type * as EffectAcpErrors from "effect-acp/errors";
import {
@@ -48,11 +45,7 @@ export function buildCursorAcpSpawnInput(
export const makeCursorAcpRuntime = (
input: CursorAcpRuntimeInput,
): Effect.Effect<
AcpSessionRuntime.AcpSessionRuntime["Service"],
EffectAcpErrors.AcpError,
Crypto.Crypto | Scope.Scope
> =>
): Effect.Effect<AcpSessionRuntimeShape, EffectAcpErrors.AcpError> =>
Effect.gen(function* () {
const acpContext = yield* Layer.build(
AcpSessionRuntime.layer({
@@ -66,10 +59,8 @@ export const makeCursorAcpRuntime = (
),
),
);
return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
Effect.provide(acpContext),
);
});
return yield* Effect.service(AcpSessionRuntime).pipe(Effect.provide(acpContext));
}).pipe(Effect.scoped);
interface CursorAcpModelSelectionRuntime {
readonly getConfigOptions: AcpSessionRuntime.AcpSessionRuntime["Service"]["getConfigOptions"];
@@ -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>`;
@@ -0,0 +1,118 @@
import assert from "node:assert/strict";
import { Effect } from "effect";
import { describe, it } from "vitest";
import {
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
} from "./CodexDeveloperInstructions.ts";
import { buildTurnStartParams } from "./CodexSessionRuntime.ts";
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",
},
],
});
});
});
File diff suppressed because it is too large. Load diff
+111
View File
@@ -0,0 +1,111 @@
import type * as EffectCodexSchema from "effect-codex-app-server/schema";
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"]);
export function readCodexAccountSnapshotResponse(
response: EffectCodexSchema.V2GetAccountResponse,
): CodexAccountSnapshot {
const account = response.account;
if (!account) {
return {
type: "unknown",
planType: null,
sparkEnabled: false,
};
}
if (account.type === "apiKey") {
return {
type: "apiKey",
planType: null,
sparkEnabled: false,
};
}
return {
type: "chatgpt",
planType: account.planType as CodexPlanType,
sparkEnabled: CODEX_SPARK_ENABLED_PLAN_TYPES.has(account.planType as CodexPlanType),
};
}
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;
}
@@ -0,0 +1,91 @@
import { describe, expect, it } from "vitest";
import type * as EffectCodexSchema from "effect-codex-app-server/schema";
import { readCodexAccountSnapshotResponse } from "./codexAccount.ts";
import { buildCodexInitializeParams, parseCodexSkillsListResponse } from "./codexAppServer.ts";
describe("buildCodexInitializeParams", () => {
it("returns the typed Codex initialize payload", () => {
expect(buildCodexInitializeParams()).toEqual({
clientInfo: {
name: "t3code_desktop",
title: "T3 Code Desktop",
version: "0.1.0",
},
capabilities: {
experimentalApi: true,
},
});
});
});
describe("readCodexAccountSnapshotResponse", () => {
it("maps chatgpt responses without lossy unknown parsing", () => {
const response = {
account: {
type: "chatgpt",
email: "[email protected]",
planType: "pro",
},
requiresOpenaiAuth: false,
} satisfies EffectCodexSchema.V2GetAccountResponse;
expect(readCodexAccountSnapshotResponse(response)).toEqual({
type: "chatgpt",
planType: "pro",
sparkEnabled: true,
});
});
});
describe("parseCodexSkillsListResponse", () => {
it("prefers the matching cwd bucket and keeps typed skill metadata", () => {
const response = {
data: [
{
cwd: "/tmp/other",
errors: [],
skills: [
{
name: "other",
path: "/tmp/other/SKILL.md",
description: "Other skill",
enabled: true,
scope: "repo",
},
],
},
{
cwd: "/work/project",
errors: [],
skills: [
{
name: "planner",
path: "/work/project/.skills/planner/SKILL.md",
description: "Plans work",
enabled: true,
scope: "repo",
shortDescription: "Plan steps",
interface: {
displayName: "Planner",
shortDescription: "Plan work",
},
},
],
},
],
} satisfies EffectCodexSchema.V2SkillsListResponse;
expect(parseCodexSkillsListResponse(response, "/work/project")).toEqual([
{
name: "planner",
path: "/work/project/.skills/planner/SKILL.md",
enabled: true,
description: "Plans work",
scope: "repo",
displayName: "Planner",
shortDescription: "Plan steps",
},
]);
});
});
+155
View File
@@ -0,0 +1,155 @@
import { spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
import type { ServerProviderSkill } from "@t3tools/contracts";
import { Effect, Layer, Schema } from "effect";
import * as CodexClient from "effect-codex-app-server/client";
import type * as EffectCodexSchema from "effect-codex-app-server/schema";
import type { Mutable } from "effect/Types";
import { readCodexAccountSnapshotResponse, type CodexAccountSnapshot } from "./codexAccount.ts";
export interface CodexDiscoverySnapshot {
readonly account: CodexAccountSnapshot;
readonly skills: ReadonlyArray<ServerProviderSkill>;
}
export class CodexDiscoveryProbeError extends Schema.TaggedErrorClass<CodexDiscoveryProbeError>()(
"CodexDiscoveryProbeError",
{
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return this.detail;
}
}
export function parseCodexSkillsListResponse(
response: EffectCodexSchema.V2SkillsListResponse,
cwd: string,
): ReadonlyArray<ServerProviderSkill> {
const matchingEntry = response.data.find((entry) => entry.cwd === cwd);
const skills = matchingEntry
? matchingEntry.skills
: response.data.flatMap((entry) => entry.skills);
return skills.map((skill) => {
const shortDescription =
skill.shortDescription ?? skill.interface?.shortDescription ?? undefined;
const parsedSkill: Mutable<ServerProviderSkill> = {
name: skill.name,
path: skill.path,
enabled: skill.enabled,
};
if (skill.description) {
parsedSkill.description = skill.description;
}
if (skill.scope) {
parsedSkill.scope = skill.scope;
}
if (skill.interface?.displayName) {
parsedSkill.displayName = skill.interface.displayName;
}
if (shortDescription) {
parsedSkill.shortDescription = shortDescription;
}
return parsedSkill;
});
}
export function buildCodexInitializeParams(): EffectCodexSchema.V1InitializeParams {
return {
clientInfo: {
name: "t3code_desktop",
title: "T3 Code Desktop",
version: "0.1.0",
},
capabilities: {
experimentalApi: true,
},
};
}
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 const probeCodexDiscovery = Effect.fn("probeCodexDiscovery")(function* (input: {
readonly binaryPath: string;
readonly homePath?: string;
readonly cwd: string;
}) {
const clientContext = yield* Layer.build(
CodexClient.layerCommand({
command: input.binaryPath,
args: ["app-server"],
...(input.homePath ? { env: { CODEX_HOME: input.homePath } } : {}),
}),
).pipe(
Effect.mapError(
(cause) =>
new CodexDiscoveryProbeError({
detail: `Codex discovery probe spawn failed: ${cause.message}`,
cause,
}),
),
);
const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(
Effect.provide(clientContext),
);
yield* client.request("initialize", buildCodexInitializeParams()).pipe(
Effect.mapError(
(cause) =>
new CodexDiscoveryProbeError({
detail: `Codex discovery probe initialize failed: ${cause.message}`,
cause,
}),
),
);
yield* client.notify("initialized", undefined).pipe(
Effect.mapError(
(cause) =>
new CodexDiscoveryProbeError({
detail: `Codex discovery probe initialized notification failed: ${cause.message}`,
cause,
}),
),
);
const [skillsResponse, accountResponse] = yield* Effect.all(
[
client.request("skills/list", {
cwds: [input.cwd],
}),
client.request("account/read", {}),
],
{ concurrency: "unbounded" },
).pipe(
Effect.mapError(
(cause) =>
new CodexDiscoveryProbeError({
detail: `Codex discovery probe request failed: ${cause.message}`,
cause,
}),
),
);
return {
account: readCodexAccountSnapshotResponse(accountResponse),
skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
} satisfies CodexDiscoverySnapshot;
}, Effect.scoped);
+127
View File
@@ -0,0 +1,127 @@
import type { ModelCapabilities, ServerProviderModel } from "@t3tools/contracts";
export const DEFAULT_CODEX_MODEL_CAPABILITIES: ModelCapabilities = {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
{ value: "medium", label: "Medium" },
{ value: "low", label: "Low" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
};
export const BUILT_IN_CODEX_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
{ value: "medium", label: "Medium" },
{ value: "low", label: "Low" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "gpt-5.4-mini",
name: "GPT-5.4 Mini",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
{ value: "medium", label: "Medium" },
{ value: "low", label: "Low" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "gpt-5.3-codex",
name: "GPT-5.3 Codex",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
{ value: "medium", label: "Medium" },
{ value: "low", label: "Low" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "gpt-5.3-codex-spark",
name: "GPT-5.3 Codex Spark",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
{ value: "medium", label: "Medium" },
{ value: "low", label: "Low" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "gpt-5.2-codex",
name: "GPT-5.2 Codex",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
{ value: "medium", label: "Medium" },
{ value: "low", label: "Low" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "gpt-5.2",
name: "GPT-5.2",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
{ value: "medium", label: "Medium" },
{ value: "low", label: "Low" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
];
export function getCodexModelCapabilities(model: string | null | undefined): ModelCapabilities {
const slug = model?.trim();
return (
BUILT_IN_CODEX_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ??
DEFAULT_CODEX_MODEL_CAPABILITIES
);
}
@@ -31,7 +31,8 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
readonly getSettings: Effect.Effect<Settings, ServerSettingsError>;
readonly streamSettings: Stream.Stream<Settings>;
readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
readonly initialSnapshot: (settings: Settings) => Effect.Effect<ServerProvider>;
readonly buildInitialSnapshot?: ((settings: Settings) => ServerProvider) | undefined;
readonly initialSnapshot?: ((settings: Settings) => ServerProvider) | undefined;
readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;
readonly enrichSnapshot?: (input: {
readonly settings: Settings;
@@ -40,25 +41,27 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
}) => Effect.Effect<void>;
readonly refreshInterval?: Duration.Input;
}): Effect.fn.Return<
ServerProviderShape,
ServerSettingsError,
Scope.Scope | BackgroundPolicy.BackgroundPolicy | ServerSettingsService
> {
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
const serverSettings = yield* ServerSettingsService;
}): Effect.fn.Return<ServerProviderShape, ServerSettingsError, Scope.Scope> {
type InitialRefreshState = "idle" | "running" | "done";
const refreshSemaphore = yield* Semaphore.make(1);
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<ServerProvider>(),
PubSub.shutdown,
);
const initialSettings = yield* input.getSettings;
const initialSnapshot = yield* input.initialSnapshot(initialSettings);
const initialSnapshotFactory = input.buildInitialSnapshot ?? input.initialSnapshot;
if (!initialSnapshotFactory) {
return yield* Effect.die(
new Error("makeManagedServerProvider requires an initial snapshot factory."),
);
}
const initialSnapshot = initialSnapshotFactory(initialSettings);
const snapshotStateRef = yield* Ref.make<ProviderSnapshotState>({
snapshot: initialSnapshot,
enrichmentGeneration: 0,
});
const settingsRef = yield* Ref.make(initialSettings);
const initialRefreshStateRef = yield* Ref.make<InitialRefreshState>("idle");
const enrichmentFiberRef = yield* Ref.make<Fiber.Fiber<void, unknown> | null>(null);
const scope = yield* Effect.scope;
@@ -70,6 +73,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
if (state.enrichmentGeneration !== generation || Equal.equals(state.snapshot, nextSnapshot)) {
return [null, state] as const;
}
return [
nextSnapshot,
{
@@ -135,6 +139,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
] as const;
});
yield* Ref.set(settingsRef, nextSettings);
yield* Ref.set(initialRefreshStateRef, "done");
yield* PubSub.publish(changesPubSub, nextSnapshot);
yield* restartSnapshotEnrichment(nextSettings, nextSnapshot, nextGeneration);
return nextSnapshot;
@@ -147,41 +152,27 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
return yield* applySnapshot(nextSettings, { forceRefresh: true });
});
const hasProviderStatusDemand = Effect.gen(function* () {
const state = yield* Ref.get(snapshotStateRef);
const instanceId = state.snapshot.instanceId;
const [genericDemand, instanceDemand] = yield* Effect.all([
backgroundPolicy.shouldRunScopeWork({ type: "provider-status" }),
backgroundPolicy.shouldRunScopeWork({ type: "provider-status", instanceId }),
]);
return genericDemand || instanceDemand;
});
const getRefreshInterval =
input.refreshInterval !== undefined
? Effect.succeed(input.refreshInterval)
: serverSettings.getSettings.pipe(
Effect.map(
(settings) =>
resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
),
Effect.orElseSucceed(() => DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL),
);
const refreshIntervalChanges = yield* Queue.sliding<void>(1);
if (input.refreshInterval === undefined) {
const serverSettingsChanges = yield* serverSettings.subscribeChanges;
yield* serverSettingsChanges.pipe(
Stream.map((settings) =>
Duration.toMillis(
resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,
),
),
Stream.changes,
Stream.runForEach(() => Queue.offer(refreshIntervalChanges, undefined).pipe(Effect.asVoid)),
Effect.forkScoped,
const startInitialRefreshIfNeeded = Effect.fn("startInitialRefreshIfNeeded")(function* () {
const shouldStart = yield* Ref.modify(
initialRefreshStateRef,
(state): readonly [boolean, InitialRefreshState] =>
state === "idle" ? [true, "running"] : [false, state],
);
}
if (!shouldStart) {
return;
}
yield* refreshSnapshot().pipe(
Effect.onExit((exit) =>
exit._tag === "Failure"
? Ref.update(initialRefreshStateRef, (state) => (state === "running" ? "idle" : state))
: Effect.void,
),
Effect.ignoreCause({ log: true }),
Effect.forkIn(scope),
);
});
yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
Effect.asVoid(applySnapshot(nextSettings)),
@@ -212,15 +203,18 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
Effect.ignoreCause({ log: true }),
),
).pipe(Effect.forkScoped);
yield* applySnapshot(initialSettings, { forceRefresh: true }).pipe(
Effect.ignoreCause({ log: true }),
Effect.forkScoped,
);
yield* startInitialRefreshIfNeeded();
return {
maintenanceCapabilities: input.maintenanceCapabilities,
getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
getSnapshot: startInitialRefreshIfNeeded().pipe(
Effect.flatMap(() =>
input.getSettings.pipe(
Effect.flatMap(applySnapshot),
Effect.tapError(Effect.logError),
Effect.orDie,
),
),
),
refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
+8
View File
@@ -182,6 +182,14 @@ export const layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>
const ServerSettingsJson = fromLenientJson(ServerSettings);
const decodeServerSettingsJsonExit = Schema.decodeUnknownExit(ServerSettingsJson);
const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent", "cursor"];
/**
* Ensure the `textGenerationModelSelection` points to an enabled provider.
* If the selected provider is disabled, fall back to the first enabled
* provider with its default model. This is applied at read-time so the
* persisted preference is preserved for when a provider is re-enabled.
*/
function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings {
return isModelSelectionProviderEnabled(settings, settings.textGenerationModelSelection)
? settings