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

@@ -46,9 +46,13 @@ const PROJECT_ID = asProjectId("project-1");
const THREAD_ID = ThreadId.make("thread-1");
const FIXTURE_TURN_ID = "fixture-turn";
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
type IntegrationProvider = ProviderDriverKind;
const CODEX_PROVIDER = ProviderDriverKind.make("codex");
const CLAUDE_AGENT_PROVIDER = ProviderDriverKind.make("claudeAgent");
const LONG_LIVE_TEST_TIMEOUT_MS = 60_000;
const live = (
name: string,
test: Parameters<typeof it.live>[1],
timeout = LONG_LIVE_TEST_TIMEOUT_MS,
) => it.live(name, test, timeout);
type IntegrationProvider = ProviderKind;
function nowIso() {
return "2026-05-01T00:00:00.000Z";
@@ -182,7 +186,7 @@ const startTurn = (input: {
createdAt: input.createdAt ?? nowIso(),
});
it.live("runs a single turn end-to-end and persists checkpoint state in sqlite + git", () =>
live("runs a single turn end-to-end and persists checkpoint state in sqlite + git", () =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
@@ -361,7 +365,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
),
);
it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
live("runs multi-turn file edits and persists checkpoint diffs", () =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
@@ -544,7 +548,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
),
);
it.live("tracks approval requests and resolves pending approvals on user response", () =>
live("tracks approval requests and resolves pending approvals on user response", () =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
@@ -625,269 +629,273 @@ it.live("tracks approval requests and resolves pending approvals on user respons
),
);
it.live("records failed turn runtime state and checkpoint status as error", () =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
live(
"records failed turn runtime state and checkpoint status as error",
() =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-failure-1", "2026-02-24T10:04:00.000Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "content.delta",
...runtimeBase("evt-failure-2", "2026-02-24T10:04:00.100Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
payload: {
streamKind: "assistant_text",
delta: "Partial output before failure.\n",
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-failure-1", "2026-02-24T10:04:00.000Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
},
{
type: "runtime.error",
...runtimeBase("evt-failure-3", "2026-02-24T10:04:00.200Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
payload: {
message: "Sandbox command failed.",
{
type: "content.delta",
...runtimeBase("evt-failure-2", "2026-02-24T10:04:00.100Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
payload: {
streamKind: "assistant_text",
delta: "Partial output before failure.\n",
},
},
},
{
type: "turn.completed",
...runtimeBase("evt-failure-4", "2026-02-24T10:04:00.300Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
payload: {
state: "failed",
errorMessage: "Sandbox command failed.",
{
type: "runtime.error",
...runtimeBase("evt-failure-3", "2026-02-24T10:04:00.200Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
payload: {
message: "Sandbox command failed.",
},
},
},
],
});
{
type: "turn.completed",
...runtimeBase("evt-failure-4", "2026-02-24T10:04:00.300Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
payload: {
state: "failed",
errorMessage: "Sandbox command failed.",
},
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-failure",
messageId: "msg-user-failure",
text: "Run risky command",
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-failure",
messageId: "msg-user-failure",
text: "Run risky command",
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.status === "error" &&
entry.session?.lastError === "Sandbox command failed." &&
entry.activities.some((activity) => activity.kind === "runtime.error") &&
entry.checkpoints.length === 1,
);
assert.equal(thread.session?.status, "error");
assert.equal(thread.checkpoints[0]?.status, "error");
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.status === "error" &&
entry.session?.lastError === "Sandbox command failed." &&
entry.activities.some((activity) => activity.kind === "runtime.error") &&
entry.checkpoints.length === 1,
30_000,
);
assert.equal(thread.session?.status, "error");
assert.equal(thread.checkpoints[0]?.status, "error");
const checkpointRow = yield* harness.checkpointRepository.getByThreadAndTurnCount({
threadId: THREAD_ID,
checkpointTurnCount: 1,
});
assert.equal(Option.isSome(checkpointRow), true);
if (Option.isSome(checkpointRow)) {
assert.equal(checkpointRow.value.status, "error");
}
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
true,
);
}),
),
const checkpointRow = yield* harness.checkpointRepository.getByThreadAndTurnCount({
threadId: THREAD_ID,
checkpointTurnCount: 1,
});
assert.equal(Option.isSome(checkpointRow), true);
if (Option.isSome(checkpointRow)) {
assert.equal(checkpointRow.value.status, "error");
}
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
true,
);
}),
),
LONG_LIVE_TEST_TIMEOUT_MS,
);
it.live("reverts to an earlier checkpoint and trims checkpoint projections + git refs", () =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
live(
"reverts to an earlier checkpoint and trims checkpoint projections + git refs",
() =>
withHarness((harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-revert-1", "2026-02-24T10:05:00.000Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "tool.started",
...runtimeBase("evt-revert-1-tool-started", "2026-02-24T10:05:00.025Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "tool.completed",
...runtimeBase("evt-revert-1-tool-completed", "2026-02-24T10:05:00.035Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "message.delta",
...runtimeBase("evt-revert-1a", "2026-02-24T10:05:00.050Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Updated README to v2.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-revert-2", "2026-02-24T10:05:00.100Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
NodeFS.writeFileSync(NodePath.join(cwd, "README.md"), "v2\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-revert-1",
messageId: "msg-user-revert-1",
text: "First edit",
createdAt: "2026-02-24T10:04:59.900Z",
});
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-revert-1", "2026-02-24T10:05:00.000Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "tool.started",
...runtimeBase("evt-revert-1-tool-started", "2026-02-24T10:05:00.025Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "tool.completed",
...runtimeBase("evt-revert-1-tool-completed", "2026-02-24T10:05:00.035Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "message.delta",
...runtimeBase("evt-revert-1a", "2026-02-24T10:05:00.050Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Updated README to v2.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-revert-2", "2026-02-24T10:05:00.100Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-revert-1",
messageId: "msg-user-revert-1",
text: "First edit",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) => entry.session?.threadId === "thread-1" && entry.checkpoints.length === 1,
);
yield* harness.waitForThread(
THREAD_ID,
(entry) => entry.session?.threadId === "thread-1" && entry.checkpoints.length === 1,
30_000,
);
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
events: [
{
type: "turn.started",
...runtimeBase("evt-revert-3", "2026-02-24T10:05:01.000Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "tool.started",
...runtimeBase("evt-revert-3-tool-started", "2026-02-24T10:05:01.025Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "tool.completed",
...runtimeBase("evt-revert-3-tool-completed", "2026-02-24T10:05:01.035Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "message.delta",
...runtimeBase("evt-revert-3a", "2026-02-24T10:05:01.050Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Updated README to v3.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-revert-4", "2026-02-24T10:05:01.100Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
NodeFS.writeFileSync(NodePath.join(cwd, "README.md"), "v3\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-revert-2",
messageId: "msg-user-revert-2",
text: "Second edit",
createdAt: "2026-02-24T10:05:00.900Z",
});
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
events: [
{
type: "turn.started",
...runtimeBase("evt-revert-3", "2026-02-24T10:05:01.000Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "tool.started",
...runtimeBase("evt-revert-3-tool-started", "2026-02-24T10:05:01.025Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "tool.completed",
...runtimeBase("evt-revert-3-tool-completed", "2026-02-24T10:05:01.035Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
toolKind: "command",
title: "Edit file",
detail: "README.md",
},
{
type: "message.delta",
...runtimeBase("evt-revert-3a", "2026-02-24T10:05:01.050Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Updated README to v3.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-revert-4", "2026-02-24T10:05:01.100Z"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-revert-2",
messageId: "msg-user-revert-2",
text: "Second edit",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.activities.some((activity) => activity.turnId === "turn-2"),
8000,
);
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.activities.some((activity) => activity.turnId === "turn-2"),
8000,
);
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.make("cmd-checkpoint-revert"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
});
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.make("cmd-checkpoint-revert"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
});
yield* harness.waitForDomainEvent((event) => event.type === "thread.reverted");
const revertedThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
);
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
assert.deepEqual(
revertedThread.messages.map((message) => ({ role: message.role, text: message.text })),
[
{ role: "user", text: "First edit" },
{ role: "assistant", text: "Updated README to v2.\n" },
],
);
assert.equal(
revertedThread.activities.some((activity) => activity.turnId === "turn-2"),
false,
);
assert.equal(
revertedThread.activities.some(
(activity) => activity.turnId === "turn-1" && activity.kind === "tool.started",
),
true,
);
assert.equal(
revertedThread.activities.some(
(activity) => activity.turnId === "turn-1" && activity.kind === "tool.completed",
),
true,
);
assert.equal(
NodeFS.readFileSync(NodePath.join(harness.workspaceDir, "README.md"), "utf8"),
"v2\n",
);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false,
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
yield* harness.waitForDomainEvent((event) => event.type === "thread.reverted");
const revertedThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
30_000,
);
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
assert.deepEqual(
revertedThread.messages.map((message) => ({ role: message.role, text: message.text })),
[
{ role: "user", text: "First edit" },
{ role: "assistant", text: "Updated README to v2.\n" },
],
);
assert.equal(
revertedThread.activities.some((activity) => activity.turnId === "turn-2"),
false,
);
assert.equal(
revertedThread.activities.some(
(activity) => activity.turnId === "turn-1" && activity.kind === "tool.started",
),
true,
);
assert.equal(
revertedThread.activities.some(
(activity) => activity.turnId === "turn-1" && activity.kind === "tool.completed",
),
true,
);
assert.equal(fs.readFileSync(path.join(harness.workspaceDir, "README.md"), "utf8"), "v2\n");
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false,
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
const checkpointRows = yield* harness.checkpointRepository.listByThreadId({
threadId: THREAD_ID,
});
assert.equal(checkpointRows.length, 1);
}),
),
const checkpointRows = yield* harness.checkpointRepository.listByThreadId({
threadId: THREAD_ID,
});
assert.equal(checkpointRows.length, 1);
}),
),
LONG_LIVE_TEST_TIMEOUT_MS,
);
it.live(
live(
"appends checkpoint.revert.failed activity when revert is requested without an active session",
() =>
withHarness((harness) =>
@@ -924,7 +932,7 @@ it.live(
),
);
it.live("starts a claudeAgent session on first turn when provider is requested", () =>
live("starts a claudeAgent session on first turn when provider is requested", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
@@ -993,7 +1001,7 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
),
);
it.live("recovers claudeAgent sessions after provider stopAll using persisted resume state", () =>
live("recovers claudeAgent sessions after provider stopAll using persisted resume state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
@@ -1051,6 +1059,7 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
30_000,
);
yield* harness.adapterHarness!.adapter.stopAll();
@@ -1125,7 +1134,7 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
),
);
it.live("forwards claudeAgent approval responses to the provider session", () =>
live("forwards claudeAgent approval responses to the provider session", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
@@ -1211,7 +1220,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
),
);
it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
@@ -1292,150 +1301,130 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
),
);
it.live("reverts claudeAgent turns and rolls back provider conversation state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
live(
"reverts claudeAgent turns and rolls back provider conversation state",
() =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase(
"evt-claude-revert-1",
"2026-02-24T10:14:00.000Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v2\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-1",
messageId: "msg-user-claude-revert-1",
text: "First Claude edit",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
{
type: "message.delta",
...runtimeBase(
"evt-claude-revert-2",
"2026-02-24T10:14:00.050Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v2\n",
},
{
type: "turn.completed",
...runtimeBase(
"evt-claude-revert-3",
"2026-02-24T10:14:00.100Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
NodeFS.writeFileSync(NodePath.join(cwd, "README.md"), "v2\n", "utf8");
}),
});
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-1",
messageId: "msg-user-claude-revert-1",
text: "First Claude edit",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-sonnet-4-6",
},
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v3\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
}),
});
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
events: [
{
type: "turn.started",
...runtimeBase(
"evt-claude-revert-4",
"2026-02-24T10:14:01.000Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase(
"evt-claude-revert-5",
"2026-02-24T10:14:01.050Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v3\n",
},
{
type: "turn.completed",
...runtimeBase(
"evt-claude-revert-6",
"2026-02-24T10:14:01.100Z",
CLAUDE_AGENT_PROVIDER,
),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
NodeFS.writeFileSync(NodePath.join(cwd, "README.md"), "v3\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-2",
messageId: "msg-user-claude-revert-2",
text: "Second Claude edit",
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-2",
messageId: "msg-user-claude-revert-2",
text: "Second Claude edit",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.session?.providerName === "claudeAgent",
30_000,
);
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.session?.providerName === "claudeAgent",
);
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.make("cmd-checkpoint-revert-claude"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
});
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.make("cmd-checkpoint-revert-claude"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
});
const revertedThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
);
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
true,
);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false,
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
}),
CLAUDE_AGENT_PROVIDER,
),
const revertedThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
);
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
true,
);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false,
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
}),
"claudeAgent",
),
LONG_LIVE_TEST_TIMEOUT_MS,
);
+3 -1
View File
@@ -44,7 +44,9 @@
"@types/node": "catalog:",
"effect-acp": "workspace:*",
"effect-codex-app-server": "workspace:*",
"vite-plus": "catalog:"
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
},
"engines": {
"node": "^22.16 || ^23.11 || >=24.10"
+2 -52
View File
@@ -12,7 +12,6 @@ import * as AcpError from "effect-acp/errors";
import type * as AcpSchema from "effect-acp/schema";
const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
const exitLogPath = process.env.T3_ACP_EXIT_LOG_PATH;
const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
const emitInterleavedAssistantToolCalls =
process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
@@ -57,42 +56,6 @@ let promptCount = 0;
let overlappingFirstPromptId: string | undefined;
const cancelledSessions = new Set<string>();
function promptIdFromRequestMeta(
request: Pick<AcpSchema.PromptRequest, "_meta">,
): string | undefined {
const meta = request._meta;
if (meta === null || typeof meta !== "object") {
return undefined;
}
const promptId = meta.promptId ?? meta.requestId;
return typeof promptId === "string" && promptId.length > 0 ? promptId : undefined;
}
function logExit(reason: string): void {
if (!exitLogPath) {
return;
}
NodeFS.appendFileSync(exitLogPath, `${reason}\n`, "utf8");
}
function writeJsonRpcNotification(method: string, params: unknown): void {
process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`);
}
process.once("SIGTERM", () => {
logExit("SIGTERM");
process.exit(0);
});
process.once("SIGINT", () => {
logExit("SIGINT");
process.exit(0);
});
process.once("exit", (code) => {
logExit(`exit:${code}`);
});
function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
if (parameterizedModelPicker) {
const baseOptions: Array<AcpSchema.SessionConfigOption> = [
@@ -434,21 +397,8 @@ const program = Effect.gen(function* () {
);
yield* agent.handleCancel(({ sessionId }) =>
Effect.gen(function* () {
const cancelledSessionId = String(sessionId ?? "mock-session-1");
cancelledSessions.add(cancelledSessionId);
if (emitLateUpdateAfterCancel) {
yield* Effect.sleep("50 millis");
yield* Effect.sync(() => {
writeJsonRpcNotification("session/update", {
sessionId: cancelledSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "late after cancel" },
},
});
});
}
Effect.sync(() => {
cancelledSessions.add(String(sessionId));
}),
);
@@ -323,10 +323,10 @@ async function setSelectOptionIfAdvertised(
sessionId,
configId: option.id,
value,
})) as SetConfigResult | null | undefined;
})) as SetConfigResult;
logSection(`SET_${label}_RESPONSE`, response);
return response?.configOptions ?? configOptions;
return response.configOptions ?? configOptions;
}
async function main() {
@@ -384,10 +384,10 @@ async function main() {
sessionId,
configId: modelConfig.id,
value: targetModel,
})) as SetConfigResult | null | undefined;
})) as SetConfigResult;
logSection("SET_MODEL_RESPONSE", setModelResponse);
configOptions = setModelResponse?.configOptions ?? configOptions;
configOptions = setModelResponse.configOptions ?? configOptions;
configOptions = await setSelectOptionIfAdvertised(
rpc,
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
@@ -0,0 +1,307 @@
import {
DEFAULT_MODEL_BY_PROVIDER,
EnvironmentId,
ModelSelection,
ThreadId,
} from "@t3tools/contracts";
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime";
import "../../index.css";
import { page } from "vitest/browser";
import { afterEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu";
import { TraitsMenuContent } from "./TraitsPicker";
import { useComposerDraftStore } from "../../composerDraftStore";
const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: string }) {
const threadId = ThreadId.make("thread-compact-menu");
const threadRef = scopeThreadRef(LOCAL_ENVIRONMENT_ID, threadId);
const threadKey = scopedThreadKey(threadRef);
const provider = props?.modelSelection?.provider ?? "claudeAgent";
const model = props?.modelSelection?.model ?? DEFAULT_MODEL_BY_PROVIDER[provider];
useComposerDraftStore.setState({
draftsByThreadKey: {
[threadKey]: {
prompt: props?.prompt ?? "",
images: [],
nonPersistedImageIds: [],
persistedAttachments: [],
terminalContexts: [],
modelSelectionByProvider: {
[provider]: {
provider,
model,
...(props?.modelSelection?.options ? { options: props.modelSelection.options } : {}),
},
},
activeProvider: provider,
runtimeMode: null,
interactionMode: null,
},
},
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
});
const host = document.createElement("div");
document.body.append(host);
const onPromptChange = vi.fn();
const providerOptions = props?.modelSelection?.options;
const models =
provider === "claudeAgent"
? [
{
slug: "claude-opus-4-6",
name: "Claude Opus 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: ["ultrathink"],
},
},
{
slug: "claude-haiku-4-5",
name: "Claude Haiku 4.5",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: true,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "claude-sonnet-4-6",
name: "Claude Sonnet 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "ultrathink", label: "Ultrathink" },
],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: ["ultrathink"],
},
},
]
: provider === "codex"
? [
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
]
: [];
const screen = await render(
<CompactComposerControlsMenu
activePlan={false}
interactionMode="default"
planSidebarLabel="Plan"
planSidebarOpen={false}
runtimeMode="approval-required"
showInteractionModeToggle
traitsMenuContent={
<TraitsMenuContent
provider={provider}
models={models}
threadRef={threadRef}
model={model}
prompt={props?.prompt ?? ""}
modelOptions={providerOptions}
onPromptChange={onPromptChange}
/>
}
onToggleInteractionMode={vi.fn()}
onTogglePlanSidebar={vi.fn()}
onRuntimeModeChange={vi.fn()}
/>,
{ container: host },
);
const cleanup = async () => {
await screen.unmount();
host.remove();
};
return {
[Symbol.asyncDispose]: cleanup,
cleanup,
};
}
describe("CompactComposerControlsMenu", () => {
afterEach(() => {
document.body.innerHTML = "";
useComposerDraftStore.setState({
draftsByThreadKey: {},
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
stickyModelSelectionByProvider: {},
});
});
it("shows fast mode controls for Opus", async () => {
await using _ = await mountMenu({
modelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
});
await page.getByLabelText("More composer controls").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Fast Mode");
expect(text).toContain("off");
expect(text).toContain("on");
});
});
it("hides fast mode controls for non-Opus Claude models", async () => {
await using _ = await mountMenu({
modelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
});
await page.getByLabelText("More composer controls").click();
await vi.waitFor(() => {
expect(document.body.textContent ?? "").not.toContain("Fast Mode");
});
});
it("shows only the provided effort options", async () => {
await using _ = await mountMenu({
modelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
});
await page.getByLabelText("More composer controls").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Low");
expect(text).toContain("Medium");
expect(text).toContain("High");
expect(text).not.toContain("Max");
expect(text).toContain("Ultrathink");
});
});
it("shows a Claude thinking on/off section for Haiku", async () => {
await using _ = await mountMenu({
modelSelection: {
provider: "claudeAgent",
model: "claude-haiku-4-5",
options: { thinking: true },
},
});
await page.getByLabelText("More composer controls").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Thinking");
expect(text).toContain("On (default)");
expect(text).toContain("Off");
});
});
it("shows prompt-controlled Ultrathink state with selectable effort controls", async () => {
await using _ = await mountMenu({
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: { effort: "high" },
},
prompt: "Ultrathink:\nInvestigate this",
});
await page.getByLabelText("More composer controls").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Effort");
expect(text).not.toContain("ultrathink");
});
});
it("warns when ultrathink appears in prompt body text", async () => {
await using _ = await mountMenu({
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: { effort: "high" },
},
prompt: "Ultrathink:\nplease ultrathink about this problem",
});
await page.getByLabelText("More composer controls").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain(
'Your prompt contains "ultrathink" in the text. Remove it to change effort.',
);
});
});
it("can hide the interaction mode section", async () => {
const host = document.createElement("div");
document.body.append(host);
const screen = await render(
<CompactComposerControlsMenu
activePlan={false}
interactionMode="default"
planSidebarLabel="Plan"
planSidebarOpen={false}
runtimeMode="approval-required"
showInteractionModeToggle={false}
onToggleInteractionMode={vi.fn()}
onTogglePlanSidebar={vi.fn()}
onRuntimeModeChange={vi.fn()}
/>,
{ container: host },
);
await page.getByLabelText("More composer controls").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).not.toContain("Mode");
expect(text).not.toContain("Chat");
expect(text).not.toContain("Plan");
expect(text).toContain("Access");
expect(text).toContain("Supervised");
expect(text).toContain("Full access");
});
await screen.unmount();
host.remove();
});
});
@@ -1,3 +1,10 @@
import { type ProviderKind, type ServerProvider } from "@t3tools/contracts";
import { resolveModelSlugForProvider, resolveSelectableModel } from "@t3tools/shared/model";
import { memo, useState } from "react";
import type { VariantProps } from "class-variance-authority";
import { type ProviderPickerKind, PROVIDER_OPTIONS } from "../../session-logic";
import { ChevronDownIcon } from "lucide-react";
import { Button, buttonVariants } from "../ui/button";
import {
type ProviderInstanceId,
type ProviderDriverKind,
@@ -39,97 +46,26 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
open?: boolean;
triggerVariant?: VariantProps<typeof buttonVariants>["variant"];
triggerClassName?: string;
triggerAriaLabel?: string;
onOpenChange?: (open: boolean) => void;
getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null;
onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void;
disabledReason?: string;
onProviderModelChange: (provider: ProviderKind, model: string) => void;
}) {
const [uncontrolledIsMenuOpen, setUncontrolledIsMenuOpen] = useState(false);
const isMenuOpen = props.open ?? uncontrolledIsMenuOpen;
// Resolve the active instance entry by exact routing key. The composer
// resolves fallbacks before rendering this component; if the selected
// instance disappears, do not infer a replacement from its driver kind.
const activeEntry = useMemo(() => {
return (
props.instanceEntries.find((entry) => entry.instanceId === props.activeInstanceId) ?? null
);
}, [props.activeInstanceId, props.instanceEntries]);
const activeInstanceId = props.activeInstanceId;
const selectedInstanceOptions = props.modelOptionsByInstance.get(activeInstanceId) ?? [];
// If the current slug belongs to a different instance (for example after
// a provider switch or disable), prefer the active instance's first
// option so the trigger icon and label stay in sync instead of showing
// a stale foreign slug.
const selectedModel =
selectedInstanceOptions.find((option) => option.slug === props.model) ??
selectedInstanceOptions[0];
const triggerTitle = selectedModel ? getTriggerDisplayModelName(selectedModel) : props.model;
const triggerLabel = selectedModel ? getTriggerDisplayModelLabel(selectedModel) : props.model;
const duplicateDriverCount = props.instanceEntries.filter(
(entry) => activeEntry !== null && entry.driverKind === activeEntry.driverKind,
).length;
const showInstanceBadge = Boolean(activeEntry?.accentColor) || duplicateDriverCount > 1;
const setIsMenuOpen = (open: boolean) => {
props.onOpenChange?.(open);
if (props.open === undefined) {
setUncontrolledIsMenuOpen(open);
}
};
useEffect(() => {
if (!isMenuOpen) {
return;
}
const { documentElement, body } = document;
const previousDocumentOverscrollBehavior = documentElement.style.overscrollBehavior;
const previousBodyOverflow = body.style.overflow;
const previousBodyPaddingRight = body.style.paddingRight;
const scrollbarWidth = window.innerWidth - documentElement.clientWidth;
documentElement.style.overscrollBehavior = "contain";
body.style.overflow = "hidden";
if (scrollbarWidth > 0) {
body.style.paddingRight = `${scrollbarWidth}px`;
}
const shouldAllowOverlayScroll = (target: EventTarget | null) => {
return target instanceof Element && target.closest("[data-model-picker-content]");
};
const preventBackgroundWheel = (event: WheelEvent) => {
if (shouldAllowOverlayScroll(event.target)) {
return;
}
event.preventDefault();
};
const preventBackgroundTouchMove = (event: TouchEvent) => {
if (shouldAllowOverlayScroll(event.target)) {
return;
}
event.preventDefault();
};
document.addEventListener("wheel", preventBackgroundWheel, { capture: true, passive: false });
document.addEventListener("touchmove", preventBackgroundTouchMove, {
capture: true,
passive: false,
});
return () => {
document.removeEventListener("wheel", preventBackgroundWheel, { capture: true });
document.removeEventListener("touchmove", preventBackgroundTouchMove, { capture: true });
documentElement.style.overscrollBehavior = previousDocumentOverscrollBehavior;
body.style.overflow = previousBodyOverflow;
body.style.paddingRight = previousBodyPaddingRight;
};
}, [isMenuOpen]);
const handleInstanceModelChange = (instanceId: ProviderInstanceId, model: string) => {
const [isMenuOpen, setIsMenuOpen] = useState(false);
const activeProvider = props.lockedProvider ?? props.provider;
const selectedProviderOptions = props.modelOptionsByProvider[activeProvider];
const selectedModelValue =
resolveSelectableModel(activeProvider, props.model, selectedProviderOptions) ?? props.model;
const selectedModelLabel =
selectedProviderOptions.find((option) => option.slug === selectedModelValue)?.name ??
props.model;
const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[activeProvider];
const handleModelChange = (provider: ProviderKind, value: string) => {
if (props.disabled) return;
props.onInstanceModelChange(instanceId, model);
if (!value) return;
const resolvedModel =
resolveSelectableModel(provider, value, props.modelOptionsByProvider[provider]) ??
resolveModelSlugForProvider(provider, value);
if (!resolvedModel) return;
props.onProviderModelChange(provider, resolvedModel);
setIsMenuOpen(false);
};
@@ -156,6 +92,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
props.triggerClassName,
)}
disabled={props.disabled}
title={props.disabled ? props.disabledReason : undefined}
/>
}
>
@@ -182,31 +119,127 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
<TooltipPopup side="top">{triggerLabel}</TooltipPopup>
</Tooltip>
</span>
<span aria-hidden="true" className="flex items-center">
<ComposerControlChevron />
</span>
</PopoverTrigger>
<PopoverPopup
align="start"
className="border-0 bg-transparent p-0 shadow-none before:hidden [-webkit-backdrop-filter:none]! [--viewport-inline-padding:0] [backdrop-filter:none]!"
viewportClassName="rounded-lg !overflow-hidden p-0"
>
<ModelPickerContent
activeInstanceId={activeInstanceId}
model={props.model}
lockedProvider={props.lockedProvider}
lockedContinuationGroupKey={props.lockedContinuationGroupKey ?? null}
instanceEntries={props.instanceEntries}
{...(props.keybindings ? { keybindings: props.keybindings } : {})}
modelOptionsByInstance={props.modelOptionsByInstance}
terminalOpen={props.terminalOpen ?? false}
onRequestClose={() => setIsMenuOpen(false)}
{...(props.getModelDisabledReason
? { getModelDisabledReason: props.getModelDisabledReason }
: {})}
onInstanceModelChange={handleInstanceModelChange}
/>
</PopoverPopup>
</Popover>
</MenuTrigger>
<MenuPopup align="start">
{props.lockedProvider !== null ? (
<MenuGroup>
<MenuRadioGroup
value={selectedModelValue}
onValueChange={(value) => handleModelChange(props.lockedProvider!, value)}
>
{props.modelOptionsByProvider[props.lockedProvider].map((modelOption) => (
<MenuRadioItem
key={`${props.lockedProvider}:${modelOption.slug}`}
value={modelOption.slug}
onClick={() => setIsMenuOpen(false)}
>
{modelOption.name}
</MenuRadioItem>
))}
</MenuRadioGroup>
</MenuGroup>
) : (
<>
{AVAILABLE_PROVIDER_OPTIONS.map((option) => {
const OptionIcon = PROVIDER_ICON_BY_PROVIDER[option.value];
const liveProvider = props.providers
? getProviderSnapshot(props.providers, option.value)
: undefined;
if (liveProvider && liveProvider.status !== "ready") {
const unavailableLabel = !liveProvider.enabled
? "Disabled"
: !liveProvider.installed
? "Not installed"
: "Unavailable";
return (
<MenuItem key={option.value} disabled>
<OptionIcon
aria-hidden="true"
className={cn(
"size-4 shrink-0 opacity-80",
providerIconClassName(option.value, "text-muted-foreground/85"),
)}
/>
<span>{option.label}</span>
<span className="ms-auto text-[11px] text-muted-foreground/80 uppercase tracking-[0.08em]">
{unavailableLabel}
</span>
</MenuItem>
);
}
return (
<MenuSub key={option.value}>
<MenuSubTrigger>
<OptionIcon
aria-hidden="true"
className={cn(
"size-4 shrink-0",
providerIconClassName(option.value, "text-muted-foreground/85"),
)}
/>
{option.label}
</MenuSubTrigger>
<MenuSubPopup className="[--available-height:min(24rem,70vh)]" sideOffset={4}>
<MenuGroup>
<MenuRadioGroup
value={
props.provider === option.value
? (resolveSelectableModel(
option.value,
props.model,
props.modelOptionsByProvider[option.value],
) ?? props.model)
: ""
}
onValueChange={(value) => handleModelChange(option.value, value)}
>
{props.modelOptionsByProvider[option.value].map((modelOption) => (
<MenuRadioItem
key={`${option.value}:${modelOption.slug}`}
value={modelOption.slug}
onClick={() => setIsMenuOpen(false)}
>
{modelOption.name}
</MenuRadioItem>
))}
</MenuRadioGroup>
</MenuGroup>
</MenuSubPopup>
</MenuSub>
);
})}
{UNAVAILABLE_PROVIDER_OPTIONS.length > 0 && <MenuDivider />}
{UNAVAILABLE_PROVIDER_OPTIONS.map((option) => {
const OptionIcon = PROVIDER_ICON_BY_PROVIDER[option.value];
return (
<MenuItem key={option.value} disabled>
<OptionIcon
aria-hidden="true"
className="size-4 shrink-0 text-muted-foreground/85 opacity-80"
/>
<span>{option.label}</span>
<span className="ms-auto text-[11px] text-muted-foreground/80 uppercase tracking-[0.08em]">
Coming soon
</span>
</MenuItem>
);
})}
{UNAVAILABLE_PROVIDER_OPTIONS.length === 0 && <MenuDivider />}
{COMING_SOON_PROVIDER_OPTIONS.map((option) => {
const OptionIcon = option.icon;
return (
<MenuItem key={option.id} disabled>
<OptionIcon aria-hidden="true" className="size-4 shrink-0 opacity-80" />
<span>{option.label}</span>
<span className="ms-auto text-[11px] text-muted-foreground/80 uppercase tracking-[0.08em]">
Coming soon
</span>
</MenuItem>
);
})}
</>
)}
</MenuPopup>
</Menu>
);
});
@@ -0,0 +1,696 @@
import "../../index.css";
import {
type ModelSelection,
ClaudeModelOptions,
CodexModelOptions,
CursorModelOptions,
DEFAULT_MODEL_BY_PROVIDER,
DEFAULT_SERVER_SETTINGS,
OpenCodeModelOptions,
EnvironmentId,
type ServerProvider,
ThreadId,
} from "@t3tools/contracts";
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime";
import { page } from "vitest/browser";
import { useCallback } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
import { TraitsPicker } from "./TraitsPicker";
import {
COMPOSER_DRAFT_STORAGE_KEY,
ComposerThreadDraftState,
useComposerDraftStore,
useComposerThreadDraft,
useEffectiveComposerModelState,
} from "../../composerDraftStore";
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
// ── Claude TraitsPicker tests ─────────────────────────────────────────
const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
const CLAUDE_THREAD_ID = ThreadId.make("thread-claude-traits");
const CLAUDE_THREAD_REF = scopeThreadRef(LOCAL_ENVIRONMENT_ID, CLAUDE_THREAD_ID);
const CLAUDE_THREAD_KEY = scopedThreadKey(CLAUDE_THREAD_REF);
const CODEX_THREAD_ID = ThreadId.make("thread-codex-traits");
const CODEX_THREAD_REF = scopeThreadRef(LOCAL_ENVIRONMENT_ID, CODEX_THREAD_ID);
const CODEX_THREAD_KEY = scopedThreadKey(CODEX_THREAD_REF);
const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
{
provider: "codex",
enabled: true,
installed: true,
version: "0.1.0",
status: "ready",
auth: { status: "authenticated" },
checkedAt: "2026-01-01T00:00:00.000Z",
slashCommands: [],
skills: [],
models: [
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
],
},
{
provider: "opencode",
enabled: true,
installed: true,
version: "0.1.0",
status: "ready",
auth: { status: "authenticated" },
checkedAt: "2026-01-01T00:00:00.000Z",
slashCommands: [],
skills: [],
models: [
{
slug: "openai/gpt-5",
name: "GPT-5",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
variantOptions: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium", isDefault: true },
],
agentOptions: [
{ value: "build", label: "Build", isDefault: true },
{ value: "plan", label: "Plan" },
],
},
},
],
},
{
provider: "claudeAgent",
enabled: true,
installed: true,
version: "0.1.0",
status: "ready",
auth: { status: "authenticated" },
checkedAt: "2026-01-01T00:00:00.000Z",
slashCommands: [],
skills: [],
models: [
{
slug: "claude-opus-4-6",
name: "Claude Opus 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: ["ultrathink"],
},
},
{
slug: "claude-sonnet-4-6",
name: "Claude Sonnet 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "ultrathink", label: "Ultrathink" },
],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: ["ultrathink"],
},
},
{
slug: "claude-haiku-4-5",
name: "Claude Haiku 4.5",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: true,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
],
},
];
const findTestProvider = (provider: ServerProvider["provider"]) => {
const testProvider = TEST_PROVIDERS.find((candidate) => candidate.provider === provider);
if (!testProvider) {
throw new Error(`Missing test provider fixture: ${provider}`);
}
return testProvider;
};
function ClaudeTraitsPickerHarness(props: {
model: string;
fallbackModelSelection: ModelSelection | null;
triggerVariant?: "ghost" | "outline";
}) {
const prompt = useComposerThreadDraft(CLAUDE_THREAD_REF).prompt;
const setPrompt = useComposerDraftStore((store) => store.setPrompt);
const { modelOptions, selectedModel } = useEffectiveComposerModelState({
threadRef: CLAUDE_THREAD_REF,
providers: TEST_PROVIDERS,
selectedProvider: "claudeAgent",
threadModelSelection: props.fallbackModelSelection,
projectModelSelection: null,
settings: {
...DEFAULT_SERVER_SETTINGS,
...DEFAULT_CLIENT_SETTINGS,
},
});
const handlePromptChange = useCallback(
(nextPrompt: string) => {
setPrompt(CLAUDE_THREAD_REF, nextPrompt);
},
[setPrompt],
);
return (
<TraitsPicker
provider="claudeAgent"
models={TEST_PROVIDERS[2]!.models}
threadRef={CLAUDE_THREAD_REF}
model={selectedModel ?? props.model}
prompt={prompt}
modelOptions={modelOptions?.claudeAgent}
onPromptChange={handlePromptChange}
triggerVariant={props.triggerVariant}
/>
);
}
async function mountClaudePicker(props?: {
model?: string;
prompt?: string;
options?: ClaudeModelOptions;
fallbackModelOptions?: {
effort?: "low" | "medium" | "high" | "max" | "ultrathink";
thinking?: boolean;
fastMode?: boolean;
} | null;
skipDraftModelOptions?: boolean;
triggerVariant?: "ghost" | "outline";
}) {
const model = props?.model ?? "claude-opus-4-6";
const claudeOptions = !props?.skipDraftModelOptions ? props?.options : undefined;
const draftsByThreadKey: Record<string, ComposerThreadDraftState> = {
[CLAUDE_THREAD_KEY]: {
prompt: props?.prompt ?? "",
images: [],
nonPersistedImageIds: [],
persistedAttachments: [],
terminalContexts: [],
modelSelectionByProvider: props?.skipDraftModelOptions
? {}
: {
claudeAgent: {
provider: "claudeAgent",
model,
...(claudeOptions && Object.keys(claudeOptions).length > 0
? { options: claudeOptions }
: {}),
},
},
activeProvider: "claudeAgent",
runtimeMode: null,
interactionMode: null,
},
};
useComposerDraftStore.setState({
draftsByThreadKey,
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
});
const host = document.createElement("div");
document.body.append(host);
const fallbackModelSelection =
props?.fallbackModelOptions !== undefined
? ({
provider: "claudeAgent",
model,
...(props.fallbackModelOptions ? { options: props.fallbackModelOptions } : {}),
} satisfies ModelSelection)
: null;
const screen = await render(
<ClaudeTraitsPickerHarness
model={model}
fallbackModelSelection={fallbackModelSelection}
{...(props?.triggerVariant ? { triggerVariant: props.triggerVariant } : {})}
/>,
{ container: host },
);
const cleanup = async () => {
await screen.unmount();
host.remove();
};
return {
[Symbol.asyncDispose]: cleanup,
cleanup,
};
}
describe("TraitsPicker (Claude)", () => {
afterEach(() => {
document.body.innerHTML = "";
useComposerDraftStore.setState({
draftsByThreadKey: {},
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
stickyModelSelectionByProvider: {},
});
});
it("shows fast mode controls for Opus", async () => {
await using _ = await mountClaudePicker();
await page.getByRole("button").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Fast Mode");
expect(text).toContain("off");
expect(text).toContain("on");
});
});
it("hides fast mode controls for non-Opus models", async () => {
await using _ = await mountClaudePicker({ model: "claude-sonnet-4-6" });
await page.getByRole("button").click();
await vi.waitFor(() => {
expect(document.body.textContent ?? "").not.toContain("Fast Mode");
});
});
it("shows only the provided effort options", async () => {
await using _ = await mountClaudePicker({
model: "claude-sonnet-4-6",
});
await page.getByRole("button").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Low");
expect(text).toContain("Medium");
expect(text).toContain("High");
expect(text).not.toContain("Max");
expect(text).toContain("Ultrathink");
});
});
it("shows a th inking on/off dropdown for Haiku", async () => {
await using _ = await mountClaudePicker({
model: "claude-haiku-4-5",
options: { thinking: true },
});
await vi.waitFor(() => {
expect(document.body.textContent ?? "").toContain("Thinking On");
});
await page.getByRole("button").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Thinking");
expect(text).toContain("On (default)");
expect(text).toContain("Off");
});
});
it("shows prompt-controlled Ultrathink state with selectable effort controls", async () => {
await using _ = await mountClaudePicker({
model: "claude-opus-4-6",
options: { effort: "high" },
prompt: "Ultrathink:\nInvestigate this",
});
await vi.waitFor(() => {
expect(document.body.textContent ?? "").toContain("Ultrathink");
expect(document.body.textContent ?? "").not.toContain("Ultrathink · Prompt");
});
await page.getByRole("button").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Effort");
expect(text).not.toContain("ultrathink");
});
});
it("warns when ultrathink appears in prompt body text", async () => {
await using _ = await mountClaudePicker({
model: "claude-opus-4-6",
options: { effort: "high" },
prompt: "Ultrathink:\nplease ultrathink about this problem",
});
await page.getByRole("button").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain(
'Your prompt contains "ultrathink" in the text. Remove it to change effort.',
);
});
});
it("persists sticky claude model options when traits change", async () => {
await using _ = await mountClaudePicker({
model: "claude-opus-4-6",
options: { effort: "medium", fastMode: false },
});
await page.getByRole("button").click();
await page.getByRole("menuitemradio", { name: "Max" }).click();
expect(
useComposerDraftStore.getState().stickyModelSelectionByProvider.claudeAgent,
).toMatchObject({
provider: "claudeAgent",
options: {
effort: "max",
},
});
});
it("accepts outline trigger styling", async () => {
await using _ = await mountClaudePicker({
triggerVariant: "outline",
});
const button = document.querySelector("button");
if (!(button instanceof HTMLButtonElement)) {
throw new Error("Expected traits trigger button to be rendered.");
}
expect(button.className).toContain("border-input");
expect(button.className).toContain("bg-popover");
});
});
// ── Codex TraitsPicker tests ──────────────────────────────────────────
async function mountCodexPicker(props: { model?: string; options?: CodexModelOptions }) {
const model = props.model ?? DEFAULT_MODEL_BY_PROVIDER.codex;
const draftsByThreadKey: Record<string, ComposerThreadDraftState> = {
[CODEX_THREAD_KEY]: {
prompt: "",
images: [],
nonPersistedImageIds: [],
persistedAttachments: [],
terminalContexts: [],
modelSelectionByProvider: {
codex: {
provider: "codex",
model,
...(props.options ? { options: props.options } : {}),
},
},
activeProvider: "codex",
runtimeMode: null,
interactionMode: null,
},
};
useComposerDraftStore.setState({
draftsByThreadKey,
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {
"environment-local:project-codex-traits": CODEX_THREAD_KEY,
},
});
const host = document.createElement("div");
document.body.append(host);
const screen = await render(
<TraitsPicker
provider="codex"
models={TEST_PROVIDERS[0]!.models}
threadRef={CODEX_THREAD_REF}
model={props.model ?? DEFAULT_MODEL_BY_PROVIDER.codex}
prompt=""
modelOptions={props.options}
onPromptChange={() => {}}
/>,
{ container: host },
);
const cleanup = async () => {
await screen.unmount();
host.remove();
};
return {
[Symbol.asyncDispose]: cleanup,
cleanup,
};
}
async function mountCursorPicker(props: { model?: string; options?: CursorModelOptions }) {
const model = props.model ?? DEFAULT_MODEL_BY_PROVIDER.cursor;
const cursorThreadId = ThreadId.make("thread-cursor-traits");
const cursorThreadRef = scopeThreadRef(LOCAL_ENVIRONMENT_ID, cursorThreadId);
const cursorThreadKey = scopedThreadKey(cursorThreadRef);
const host = document.createElement("div");
document.body.append(host);
useComposerDraftStore.setState({
draftsByThreadKey: {
[cursorThreadKey]: {
prompt: "",
images: [],
nonPersistedImageIds: [],
persistedAttachments: [],
terminalContexts: [],
modelSelectionByProvider: {
cursor: {
provider: "cursor",
model,
...(props.options ? { options: props.options } : {}),
},
},
activeProvider: "cursor",
runtimeMode: null,
interactionMode: null,
},
},
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
});
const screen = await render(
<TraitsPicker
provider="cursor"
models={[
{
slug: "composer-2",
name: "Composer 2",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "claude-opus-4-6",
name: "Opus 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200K", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: [],
},
},
]}
threadRef={cursorThreadRef}
model={model}
prompt=""
modelOptions={props.options}
onPromptChange={() => {}}
/>,
{ container: host },
);
const cleanup = async () => {
await screen.unmount();
host.remove();
};
return {
[Symbol.asyncDispose]: cleanup,
cleanup,
};
}
describe("TraitsPicker (Codex)", () => {
afterEach(() => {
document.body.innerHTML = "";
localStorage.removeItem(COMPOSER_DRAFT_STORAGE_KEY);
useComposerDraftStore.setState({
draftsByThreadKey: {},
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
stickyModelSelectionByProvider: {},
});
});
it("shows fast mode controls", async () => {
await using _ = await mountCodexPicker({
options: { fastMode: false },
});
await page.getByRole("button").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Fast Mode");
expect(text).toContain("off");
expect(text).toContain("on");
});
});
it("shows Fast in the trigger label when fast mode is active", async () => {
await using _ = await mountCodexPicker({
options: { fastMode: true },
});
await vi.waitFor(() => {
expect(document.body.textContent ?? "").toContain("High · Fast");
});
});
it("shows only the provided effort options", async () => {
await using _ = await mountCodexPicker({
options: { fastMode: false },
});
await page.getByRole("button").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Extra High");
expect(text).toContain("High");
expect(text).not.toContain("Low");
expect(text).not.toContain("Medium");
});
});
it("persists sticky codex model options when traits change", async () => {
await using _ = await mountCodexPicker({
options: { fastMode: false },
});
await page.getByRole("button").click();
await page.getByRole("menuitemradio", { name: "on" }).click();
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.codex).toMatchObject({
provider: "codex",
options: { fastMode: true },
});
});
});
describe("TraitsPicker (Cursor)", () => {
afterEach(() => {
document.body.innerHTML = "";
localStorage.removeItem(COMPOSER_DRAFT_STORAGE_KEY);
useComposerDraftStore.setState({
draftsByThreadKey: {},
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
stickyModelSelectionByProvider: {},
});
});
it("uses the selected fast mode menu label for the trigger in fast-only state", async () => {
await using _ = await mountCursorPicker({
model: "composer-2",
options: { fastMode: false },
});
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Normal");
});
await page.getByRole("button").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Fast Mode");
expect(text).toContain("off");
expect(text).toContain("on");
});
});
it("shows Normal for Cursor Opus 4.6 when fast mode and context window are both at defaults", async () => {
await using _ = await mountCursorPicker({
model: "claude-opus-4-6",
options: { fastMode: false },
});
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Normal");
});
await page.getByRole("button").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Fast Mode");
expect(text).toContain("Context Window");
expect(text).toContain("200K (default)");
expect(text).toContain("1M");
});
});
it("shows Normal · 1M for Cursor Opus 4.6 when fast mode is off and context window is overridden", async () => {
await using _ = await mountCursorPicker({
model: "claude-opus-4-6",
options: { fastMode: false, contextWindow: "1m" },
});
await vi.waitFor(() => {
expect(document.body.textContent ?? "").toContain("Normal · 1M");
});
});
});
@@ -0,0 +1,731 @@
import { describe, expect, it } from "vitest";
import type { ServerProviderModel } from "@t3tools/contracts";
import {
getComposerProviderControls,
getComposerProviderState,
renderProviderTraitsMenuContent,
renderProviderTraitsPicker,
} from "./composerProviderRegistry";
const 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: [],
},
},
];
const CURSOR_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "auto",
name: "Auto",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "composer-2",
name: "Composer 2",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "gpt-5.3-codex",
name: "Codex 5.3",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium", isDefault: true },
{ value: "high", label: "High" },
{ value: "xhigh", label: "Extra high" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium", isDefault: true },
{ value: "high", label: "High" },
{ value: "xhigh", label: "Extra high" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "272k", label: "272k", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: [],
},
},
{
slug: "claude-opus-4-6",
name: "Opus 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
],
supportsFastMode: false,
supportsThinkingToggle: true,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
];
const CLAUDE_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "claude-opus-4-6",
name: "Claude Opus 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: ["ultrathink"],
},
},
{
slug: "claude-sonnet-4-6",
name: "Claude Sonnet 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "ultrathink", label: "Ultrathink" },
],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: ["ultrathink"],
},
},
{
slug: "claude-haiku-4-5",
name: "Claude Haiku 4.5",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: true,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
];
const CLAUDE_MODELS_WITH_CONTEXT_WINDOW: ReadonlyArray<ServerProviderModel> = [
{
slug: "claude-opus-4-6",
name: "Claude Opus 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
promptInjectedEffortLevels: ["ultrathink"],
},
},
{
slug: "claude-haiku-4-5",
name: "Claude Haiku 4.5",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: true,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
},
},
];
const OPENCODE_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "openai/gpt-5",
name: "GPT-5",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
variantOptions: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium", isDefault: true },
],
agentOptions: [
{ value: "build", label: "Build", isDefault: true },
{ value: "plan", label: "Plan" },
],
},
},
];
describe("getComposerProviderState", () => {
it("returns codex defaults when no codex draft options exist", () => {
const state = getComposerProviderState({
provider: "codex",
model: "gpt-5.4",
models: CODEX_MODELS,
prompt: "",
modelOptions: undefined,
});
expect(state).toEqual({
provider: "codex",
promptEffort: "high",
modelOptionsForDispatch: {
reasoningEffort: "high",
},
});
});
it("normalizes codex dispatch options while preserving the selected effort", () => {
const state = getComposerProviderState({
provider: "codex",
model: "gpt-5.4",
models: CODEX_MODELS,
prompt: "",
modelOptions: {
codex: {
reasoningEffort: "low",
fastMode: true,
},
},
});
expect(state).toEqual({
provider: "codex",
promptEffort: "low",
modelOptionsForDispatch: {
reasoningEffort: "low",
fastMode: true,
},
});
});
it("preserves codex fast mode when it is the only active option", () => {
const state = getComposerProviderState({
provider: "codex",
model: "gpt-5.4",
models: CODEX_MODELS,
prompt: "",
modelOptions: {
codex: {
fastMode: true,
},
},
});
expect(state).toEqual({
provider: "codex",
promptEffort: "high",
modelOptionsForDispatch: {
reasoningEffort: "high",
fastMode: true,
},
});
});
it("preserves codex default effort explicitly in dispatch options", () => {
const state = getComposerProviderState({
provider: "codex",
model: "gpt-5.4",
models: CODEX_MODELS,
prompt: "",
modelOptions: {
codex: {
reasoningEffort: "high",
fastMode: false,
},
},
});
expect(state).toEqual({
provider: "codex",
promptEffort: "high",
modelOptionsForDispatch: {
reasoningEffort: "high",
fastMode: false,
},
});
});
it("returns Claude defaults for effort-capable models", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-sonnet-4-6",
models: CLAUDE_MODELS,
prompt: "",
modelOptions: undefined,
});
expect(state).toEqual({
provider: "claudeAgent",
promptEffort: "high",
modelOptionsForDispatch: {
effort: "high",
},
});
});
it("tracks Claude ultrathink from the prompt without changing dispatch effort", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-sonnet-4-6",
models: CLAUDE_MODELS,
prompt: "Ultrathink:\nInvestigate this failure",
modelOptions: {
claudeAgent: {
effort: "medium",
},
},
});
expect(state).toEqual({
provider: "claudeAgent",
promptEffort: "medium",
modelOptionsForDispatch: {
effort: "medium",
},
composerFrameClassName: "ultrathink-frame",
composerSurfaceClassName: "shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]",
modelPickerIconClassName: "ultrathink-chroma",
});
});
it("drops unsupported Claude effort options for models without effort controls", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-haiku-4-5",
models: CLAUDE_MODELS,
prompt: "",
modelOptions: {
claudeAgent: {
effort: "max",
thinking: false,
},
},
});
expect(state).toEqual({
provider: "claudeAgent",
promptEffort: null,
modelOptionsForDispatch: {
thinking: false,
},
});
});
it("preserves Claude fast mode when it is the only active option", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-opus-4-6",
models: CLAUDE_MODELS,
prompt: "",
modelOptions: {
claudeAgent: {
fastMode: true,
},
},
});
expect(state).toEqual({
provider: "claudeAgent",
promptEffort: "high",
modelOptionsForDispatch: {
effort: "high",
fastMode: true,
},
});
});
it("returns minimal state for Cursor without trait controls", () => {
const state = getComposerProviderState({
provider: "cursor",
model: "auto",
models: CURSOR_MODELS,
prompt: "",
modelOptions: undefined,
});
expect(state).toEqual({
provider: "cursor",
promptEffort: null,
modelOptionsForDispatch: undefined,
});
});
it("dispatches Cursor fast traits separately from the family model key", () => {
const state = getComposerProviderState({
provider: "cursor",
model: "composer-2",
models: CURSOR_MODELS,
prompt: "",
modelOptions: {
cursor: { fastMode: true },
},
});
expect(state).toEqual({
provider: "cursor",
promptEffort: null,
modelOptionsForDispatch: { fastMode: true },
});
});
it("resolves Cursor reasoning effort from server-driven capabilities", () => {
const state = getComposerProviderState({
provider: "cursor",
model: "gpt-5.3-codex",
models: CURSOR_MODELS,
prompt: "",
modelOptions: {
cursor: { reasoning: "high" },
},
});
expect(state).toEqual({
provider: "cursor",
promptEffort: "high",
modelOptionsForDispatch: { reasoning: "high" },
});
});
it("preserves default Cursor reasoning in dispatch options so prior overrides can be cleared", () => {
const state = getComposerProviderState({
provider: "cursor",
model: "gpt-5.3-codex",
models: CURSOR_MODELS,
prompt: "",
modelOptions: {
cursor: { reasoning: "medium" },
},
});
expect(state).toEqual({
provider: "cursor",
promptEffort: "medium",
modelOptionsForDispatch: { reasoning: "medium" },
});
});
it("preserves Cursor context window in dispatch options", () => {
const state = getComposerProviderState({
provider: "cursor",
model: "gpt-5.4",
models: CURSOR_MODELS,
prompt: "",
modelOptions: {
cursor: {
contextWindow: "1m",
},
},
});
expect(state).toEqual({
provider: "cursor",
promptEffort: "medium",
modelOptionsForDispatch: {
contextWindow: "1m",
reasoning: "medium",
},
});
});
it("preserves explicit default Cursor reasoning so deepMerge can clear a prior non-default", () => {
const state = getComposerProviderState({
provider: "cursor",
model: "gpt-5.4",
models: CURSOR_MODELS,
prompt: "",
modelOptions: {
cursor: { reasoning: "medium" },
},
});
expect(state.modelOptionsForDispatch).toHaveProperty("reasoning", "medium");
});
it("preserves explicit Cursor fastMode: false so deepMerge can overwrite a prior true", () => {
const state = getComposerProviderState({
provider: "cursor",
model: "composer-2",
models: CURSOR_MODELS,
prompt: "",
modelOptions: {
cursor: { fastMode: false },
},
});
expect(state.modelOptionsForDispatch).toHaveProperty("fastMode", false);
});
it("preserves explicit Cursor thinking: true so deepMerge can overwrite a prior false", () => {
const state = getComposerProviderState({
provider: "cursor",
model: "claude-opus-4-6",
models: CURSOR_MODELS,
prompt: "",
modelOptions: {
cursor: { thinking: true },
},
});
expect(state.modelOptionsForDispatch).toHaveProperty("thinking", true);
});
it("preserves Claude default effort explicitly in dispatch options", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-opus-4-6",
models: CLAUDE_MODELS,
prompt: "",
modelOptions: {
claudeAgent: {
effort: "high",
fastMode: false,
},
},
});
expect(state).toEqual({
provider: "claudeAgent",
promptEffort: "high",
modelOptionsForDispatch: {
effort: "high",
fastMode: false,
},
});
});
it("preserves explicit fastMode: false so deepMerge can overwrite a prior true", () => {
// Regression: normalizeClaudeModelOptionsWithCapabilities used to strip
// fastMode: false, which meant deepMerge could never clear a previous true.
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-opus-4-6",
models: CLAUDE_MODELS,
prompt: "",
modelOptions: {
claudeAgent: {
effort: "high",
fastMode: false,
},
},
});
expect(state.modelOptionsForDispatch).toHaveProperty("fastMode", false);
});
it("preserves explicit thinking: true so deepMerge can overwrite a prior false", () => {
// Regression: thinking: true (the default) used to be stripped, which
// meant deepMerge could never clear a previous thinking: false.
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-haiku-4-5",
models: CLAUDE_MODELS,
prompt: "",
modelOptions: {
claudeAgent: {
thinking: true,
},
},
});
expect(state.modelOptionsForDispatch).toHaveProperty("thinking", true);
});
it("preserves Claude default context window explicitly in dispatch options", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-opus-4-6",
models: CLAUDE_MODELS_WITH_CONTEXT_WINDOW,
prompt: "",
modelOptions: {
claudeAgent: {
effort: "high",
contextWindow: "200k",
},
},
});
expect(state.modelOptionsForDispatch).toMatchObject({
effort: "high",
contextWindow: "200k",
});
});
it("preserves explicit contextWindow default so deepMerge can overwrite a prior 1m", () => {
// Regression: the default contextWindow must survive normalization so
// deepMerge can clear an older non-default 1m selection.
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-opus-4-6",
models: CLAUDE_MODELS_WITH_CONTEXT_WINDOW,
prompt: "",
modelOptions: {
claudeAgent: {
contextWindow: "200k",
},
},
});
expect(state.modelOptionsForDispatch).toHaveProperty("contextWindow", "200k");
});
it("omits contextWindow when the model does not support it", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-haiku-4-5",
models: CLAUDE_MODELS_WITH_CONTEXT_WINDOW,
prompt: "",
modelOptions: {
claudeAgent: {
contextWindow: "1m",
},
},
});
expect(state.modelOptionsForDispatch).toBeUndefined();
});
it("omits fastMode when the model does not support it", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-sonnet-4-6",
models: CLAUDE_MODELS,
prompt: "",
modelOptions: {
claudeAgent: {
effort: "high",
fastMode: true,
},
},
});
expect(state.modelOptionsForDispatch).not.toHaveProperty("fastMode");
});
it("preserves OpenCode variant and agent options for dispatch", () => {
const state = getComposerProviderState({
provider: "opencode",
model: "openai/gpt-5",
models: OPENCODE_MODELS,
prompt: "",
modelOptions: {
opencode: {
variant: "medium",
agent: "plan",
},
},
});
expect(state).toEqual({
provider: "opencode",
promptEffort: "medium",
modelOptionsForDispatch: {
variant: "medium",
agent: "plan",
},
});
});
});
describe("getComposerProviderControls", () => {
it("hides the interaction mode toggle for OpenCode", () => {
expect(getComposerProviderControls("opencode")).toEqual({
showInteractionModeToggle: false,
});
});
it("keeps the interaction mode toggle for Codex and Claude", () => {
expect(getComposerProviderControls("codex")).toEqual({
showInteractionModeToggle: true,
});
expect(getComposerProviderControls("claudeAgent")).toEqual({
showInteractionModeToggle: true,
});
});
});
describe("provider traits render guards", () => {
it("returns null for codex traits picker when no thread target is provided", () => {
const content = renderProviderTraitsPicker({
provider: "codex",
model: "gpt-5.4",
models: CODEX_MODELS,
modelOptions: undefined,
prompt: "",
onPromptChange: () => {},
});
expect(content).toBeNull();
});
it("returns null for claude traits menu content when no thread target is provided", () => {
const content = renderProviderTraitsMenuContent({
provider: "claudeAgent",
model: "claude-sonnet-4-6",
models: CLAUDE_MODELS,
modelOptions: undefined,
prompt: "",
onPromptChange: () => {},
});
expect(content).toBeNull();
});
});
+6 -4
View File
@@ -5,10 +5,12 @@ import type * as React from "react";
import { cn } from "~/lib/utils";
type InputProps = Omit<InputPrimitive.Props & React.RefAttributes<HTMLInputElement>, "size"> & {
size?: "sm" | "default" | "lg" | number;
unstyled?: boolean;
nativeInput?: boolean;
type InputProps = Omit<InputPrimitive.Props, "className" | "size" | "style"> & {
className?: string | undefined;
size?: "sm" | "default" | "lg" | number | undefined;
style?: React.CSSProperties | undefined;
unstyled?: boolean | undefined;
nativeInput?: boolean | undefined;
};
function Input({
-24
View File
@@ -1391,30 +1391,6 @@ describe("composerDraftStore modelSelection", () => {
);
});
it("preserves the selected Cursor model when only traits change", () => {
const store = useComposerDraftStore.getState();
store.setProviderModelOptions(threadRef, CURSOR_DRIVER, toSelections({ reasoning: "high" }), {
model: "gpt-5.4",
persistSticky: true,
});
expect(
draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider[CURSOR_INSTANCE],
).toEqual(
modelSelection(CURSOR_DRIVER, "gpt-5.4", {
reasoning: "high",
}),
);
expect(
useComposerDraftStore.getState().stickyModelSelectionByProvider[CURSOR_INSTANCE],
).toEqual(
modelSelection(CURSOR_DRIVER, "gpt-5.4", {
reasoning: "high",
}),
);
});
it("updates only the draft when sticky persistence is omitted", () => {
const store = useComposerDraftStore.getState();
+29 -35
View File
@@ -1294,41 +1294,6 @@ describe("deriveWorkLogEntries", () => {
});
});
it("does not use command stdout as the detail when Cursor omits the command input", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
id: "cursor-command-complete",
createdAt: "2026-04-16T22:40:42.221Z",
kind: "tool.completed",
summary: "Ran command",
payload: {
itemType: "command_execution",
title: "Ran command",
data: {
toolCallId: "toolu_vrtx_01WypXgRM8PPygBtrVAZwzy5",
kind: "execute",
rawInput: {},
rawOutput: {
exitCode: 0,
stdout: "total 960\napps\npackages\n",
stderr: "",
},
},
},
}),
];
const [entry] = deriveWorkLogEntries(activities);
expect(entry).toMatchObject({
id: "cursor-command-complete",
label: "Ran command",
itemType: "command_execution",
toolTitle: "Ran command",
});
expect(entry?.detail).toBeUndefined();
expect(entry?.command).toBeUndefined();
});
it("collapses legacy completed tool rows that are missing tool metadata", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
@@ -1929,3 +1894,32 @@ describe("rerun workflows", () => {
expect(spawnRows.map((row) => row.turnId)).toEqual(["turn-1", "turn-2"]);
});
});
describe("PROVIDER_OPTIONS", () => {
it("advertises Codex, Claude, OpenCode, and Cursor as available providers", () => {
const claude = PROVIDER_OPTIONS.find((option) => option.value === "claudeAgent");
const opencode = PROVIDER_OPTIONS.find((option) => option.value === "opencode");
const cursor = PROVIDER_OPTIONS.find((option) => option.value === "cursor");
expect(PROVIDER_OPTIONS).toEqual([
{ value: "codex", label: "Codex", available: true },
{ value: "claudeAgent", label: "Claude", available: true },
{ value: "opencode", label: "OpenCode", available: true },
{ value: "cursor", label: "Cursor", available: true },
]);
expect(claude).toEqual({
value: "claudeAgent",
label: "Claude",
available: true,
});
expect(opencode).toEqual({
value: "opencode",
label: "OpenCode",
available: true,
});
expect(cursor).toEqual({
value: "cursor",
label: "Cursor",
available: true,
});
});
});
File diff suppressed because it is too large. Load diff
+2300
View File
File diff suppressed because it is too large. Load diff
+48 -10
View File
@@ -7,8 +7,49 @@ import { ProviderDriverKind } from "./providerInstance.ts";
export const ProviderOptionDescriptorType = Schema.Literals(["select", "boolean"]);
export type ProviderOptionDescriptorType = typeof ProviderOptionDescriptorType.Type;
export const ProviderOptionChoice = Schema.Struct({
id: TrimmedNonEmptyString,
export type ProviderReasoningEffort =
| CodexReasoningEffort
| ClaudeAgentEffort
| CursorReasoningOption;
export const CodexModelOptions = Schema.Struct({
reasoningEffort: Schema.optional(CodexReasoningEffort),
fastMode: Schema.optional(Schema.Boolean),
});
export type CodexModelOptions = typeof CodexModelOptions.Type;
export const ClaudeModelOptions = Schema.Struct({
thinking: Schema.optional(Schema.Boolean),
effort: Schema.optional(ClaudeAgentEffort),
fastMode: Schema.optional(Schema.Boolean),
contextWindow: Schema.optional(Schema.String),
});
export type ClaudeModelOptions = typeof ClaudeModelOptions.Type;
export const CursorModelOptions = Schema.Struct({
reasoning: Schema.optional(CursorReasoningOption),
fastMode: Schema.optional(Schema.Boolean),
thinking: Schema.optional(Schema.Boolean),
contextWindow: Schema.optional(Schema.String),
});
export type CursorModelOptions = typeof CursorModelOptions.Type;
export const OpenCodeModelOptions = Schema.Struct({
variant: Schema.optional(TrimmedNonEmptyString),
agent: Schema.optional(TrimmedNonEmptyString),
});
export type OpenCodeModelOptions = typeof OpenCodeModelOptions.Type;
export const ProviderModelOptions = Schema.Struct({
codex: Schema.optional(CodexModelOptions),
claudeAgent: Schema.optional(ClaudeModelOptions),
cursor: Schema.optional(CursorModelOptions),
opencode: Schema.optional(OpenCodeModelOptions),
});
export type ProviderModelOptions = typeof ProviderModelOptions.Type;
export const EffortOption = Schema.Struct({
value: TrimmedNonEmptyString,
label: TrimmedNonEmptyString,
description: Schema.optional(TrimmedNonEmptyString),
isDefault: Schema.optional(Schema.Boolean),
@@ -214,12 +255,9 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Partial<
[OPENCODE_DRIVER_KIND]: {},
};
// ── Provider display names ────────────────────────────────────────────
export const PROVIDER_DISPLAY_NAMES: Partial<Record<ProviderDriverKind, string>> = {
[CODEX_DRIVER_KIND]: "Codex",
[CLAUDE_DRIVER_KIND]: "Claude",
[CURSOR_DRIVER_KIND]: "Cursor",
[GROK_DRIVER_KIND]: "Grok",
[OPENCODE_DRIVER_KIND]: "OpenCode",
export const PROVIDER_DISPLAY_NAMES: Record<ProviderKind, string> = {
codex: "Codex",
claudeAgent: "Claude",
cursor: "Cursor",
opencode: "OpenCode",
};
+6
View File
@@ -34,6 +34,12 @@ export const ORCHESTRATION_WS_METHODS = {
subscribeThread: "orchestration.subscribeThread",
} as const;
export const ORCHESTRATION_WS_CHANNELS = {
domainEvent: "orchestration.domainEvent",
} as const;
export const ProviderKind = Schema.Literals(["codex", "claudeAgent", "cursor", "opencode"]);
export type ProviderKind = typeof ProviderKind.Type;
export const ProviderApprovalPolicy = Schema.Literals([
"untrusted",
"on-failure",
@@ -25,7 +25,6 @@ const RuntimeEventRawSource = Schema.Union([
Schema.Literal("claude.sdk.message"),
Schema.Literal("claude.sdk.permission"),
Schema.Literal("codex.sdk.thread-event"),
Schema.Literal("opencode.sdk.event"),
Schema.Literal("acp.jsonrpc"),
Schema.TemplateLiteral(["acp.", Schema.String, ".extension"]),
]);
+6 -33
View File
@@ -363,39 +363,12 @@ export const ClaudeSettings = makeProviderSettingsSchema(
);
export type ClaudeSettings = typeof ClaudeSettings.Type;
export const CursorSettings = makeProviderSettingsSchema(
{
enabled: Schema.Boolean.pipe(
Schema.withDecodingDefault(Effect.succeed(false)),
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
),
binaryPath: makeBinaryPathSetting("cursor-agent").pipe(
Schema.annotateKey({
title: "Binary path",
description: "Path to the Cursor agent binary.",
providerSettingsForm: { placeholder: "cursor-agent", clearWhenEmpty: "omit" },
}),
),
apiEndpoint: TrimmedString.pipe(
Schema.withDecodingDefault(Effect.succeed("")),
Schema.annotateKey({
title: "API endpoint",
description: "Override the Cursor API endpoint for this instance.",
providerSettingsForm: {
placeholder: "https://...",
clearWhenEmpty: "omit",
},
}),
),
customModels: Schema.Array(Schema.String).pipe(
Schema.withDecodingDefault(Effect.succeed([])),
Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
),
},
{
order: ["binaryPath", "apiEndpoint"],
},
);
export const CursorSettings = Schema.Struct({
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
binaryPath: makeBinaryPathSetting("agent"),
apiEndpoint: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
});
export type CursorSettings = typeof CursorSettings.Type;
export const GrokSettings = makeProviderSettingsSchema(
+11 -6
View File
@@ -25,19 +25,24 @@
}
},
"scripts": {
"typecheck": "tsgo --noEmit",
"test": "vp test run",
"generate": "node scripts/generate.ts",
"probe": "node test/examples/codex-app-server-probe.ts"
"dev": "tsdown src/client.ts src/rpc.ts src/protocol.ts src/schema.ts --format esm,cjs --dts --watch --clean",
"build": "tsdown src/client.ts src/rpc.ts src/protocol.ts src/schema.ts --format esm,cjs --dts --clean",
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"generate": "bun run scripts/generate.ts",
"probe": "bun run test/examples/codex-app-server-probe.ts"
},
"dependencies": {
"effect": "catalog:"
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/openapi-generator": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"vite-plus": "catalog:"
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
}
}
@@ -3,21 +3,10 @@
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { make as makeJsonSchemaGenerator } from "@effect/openapi-generator/JsonSchemaGenerator";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import {
FetchHttpClient,
HttpClient,
HttpClientRequest,
HttpClientResponse,
} from "effect/unstable/http";
import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
const UPSTREAM_REF = "678157acaa819d5510adfe359abb5d0392cfe461";
const UPSTREAM_REF = "dbfe855f4fd0f5dcdf079882652a8efe622b0595";
const USER_AGENT = "effect-codex-app-server-generator";
const GITHUB_API_BASE =
"https://api.github.com/repos/openai/codex/contents/codex-rs/app-server-protocol";
@@ -32,15 +21,6 @@ const GithubContentEntries = Schema.Array(
);
type GithubContentEntry = (typeof GithubContentEntries.Type)[number];
const JsonSchemaDocument = Schema.StructWithRest(
Schema.Struct({
definitions: Schema.optionalKey(Schema.Record(Schema.String, Schema.Json)),
}),
[Schema.Record(Schema.String, Schema.Json)],
);
const decodeGithubContentEntries = Schema.decodeEffect(Schema.fromJsonString(GithubContentEntries));
const decodeJsonSchemaDocument = Schema.decodeEffect(Schema.fromJsonString(JsonSchemaDocument));
interface GeneratedPaths {
readonly generatedDir: string;
readonly schemaOutputPath: string;
@@ -63,14 +43,14 @@ interface JsonSchemaFile {
class GeneratorError extends Schema.TaggedErrorClass<GeneratorError>()("GeneratorError", {
detail: Schema.String,
cause: Schema.optional(Schema.Defect()),
cause: Schema.optional(Schema.Defect),
}) {
override get message() {
return this.detail;
}
}
const ManualSchemas: Record<string, Schema.Json> = {
const ManualSchemas: Record<string, typeof Schema.Json.Type> = {
GetAuthStatusParams: {
type: "object",
title: "GetAuthStatusParams",
@@ -163,24 +143,45 @@ const ensureGeneratedDir = Effect.fn("ensureGeneratedDir")(function* () {
});
const fetchText = Effect.fn("fetchText")(function* (url: string) {
return yield* HttpClientRequest.get(url).pipe(
HttpClientRequest.setHeader("user-agent", USER_AGENT),
HttpClient.execute,
Effect.flatMap(HttpClientResponse.filterStatusOk),
Effect.flatMap((okResponse) => okResponse.text),
Effect.mapError(
(cause) =>
new GeneratorError({
detail: `Failed to fetch ${url}`,
cause,
}),
),
);
const response = yield* Effect.tryPromise({
try: () =>
fetch(url, {
headers: {
"user-agent": USER_AGENT,
},
}),
catch: (cause) =>
new GeneratorError({
detail: `Failed to fetch ${url}`,
cause,
}),
});
if (!response.ok) {
const detail = yield* Effect.tryPromise({
try: () => response.text(),
catch: () => "",
});
return yield* Effect.fail(
new GeneratorError({
detail: `Failed to download ${url}: ${response.status} ${detail}`,
}),
);
}
return yield* Effect.tryPromise({
try: () => response.text(),
catch: (cause) =>
new GeneratorError({
detail: `Failed to read response body for ${url}`,
cause,
}),
});
});
const fetchDirectoryEntries = Effect.fn("fetchDirectoryEntries")(function* (path: string) {
const raw = yield* fetchText(`${GITHUB_API_BASE}/${path}?ref=${UPSTREAM_REF}`);
return yield* decodeGithubContentEntries(raw);
return yield* Schema.decodeEffect(Schema.fromJsonString(GithubContentEntries))(raw);
});
function collectSchemaEntries(
@@ -218,7 +219,7 @@ function collectSchemaEntries(
return entries;
}
function normalizeNullableTypes(value: Schema.Json): Schema.Json {
function normalizeNullableTypes(value: typeof Schema.Json.Type): typeof Schema.Json.Type {
if (Array.isArray(value)) {
return value.map(normalizeNullableTypes);
}
@@ -230,7 +231,10 @@ function normalizeNullableTypes(value: Schema.Json): Schema.Json {
key,
normalizeNullableTypes(child),
]);
const normalizedObject = Object.fromEntries(normalizedEntries) as Record<string, Schema.Json>;
const normalizedObject = Object.fromEntries(normalizedEntries) as Record<
string,
typeof Schema.Json.Type
>;
const typeValue = normalizedObject.type;
if (!Array.isArray(typeValue)) {
@@ -248,7 +252,7 @@ function normalizeNullableTypes(value: Schema.Json): Schema.Json {
}
const nonNullType = nonNullTypes[0]!;
const nextObject: Record<string, Schema.Json> = {};
const nextObject: Record<string, typeof Schema.Json.Type> = {};
for (const [key, child] of Object.entries(normalizedObject)) {
if (key !== "type") {
nextObject[key] = child;
@@ -266,7 +270,7 @@ function normalizeNullableTypes(value: Schema.Json): Schema.Json {
};
}
function stripNullDefaults(value: Schema.Json): Schema.Json {
function stripNullDefaults(value: typeof Schema.Json.Type): typeof Schema.Json.Type {
if (Array.isArray(value)) {
return value.map(stripNullDefaults);
}
@@ -278,7 +282,7 @@ function stripNullDefaults(value: Schema.Json): Schema.Json {
Object.entries(value)
.filter(([key, child]) => !(key === "default" && child === null))
.map(([key, child]) => [key, stripNullDefaults(child)]),
) as Schema.Json;
) as typeof Schema.Json.Type;
}
function toPascalCaseMethod(method: string) {
@@ -348,13 +352,10 @@ function resolveResponseTypeName(
const overrides: Record<string, string> = {
"account/logout": "LogoutAccountResponse",
"account/rateLimits/read": "GetAccountRateLimitsResponse",
"account/usage/read": "GetAccountTokenUsageResponse",
"account/workspaceMessages/read": "GetWorkspaceMessagesResponse",
"config/batchWrite": "ConfigWriteResponse",
"config/mcpServer/reload": "McpServerRefreshResponse",
"config/value/write": "ConfigWriteResponse",
"configRequirements/read": "ConfigRequirementsReadResponse",
"externalAgentConfig/import/readHistories": "ExternalAgentConfigImportHistoriesReadResponse",
};
const override = overrides[method];
@@ -417,7 +418,7 @@ function renderSchemaMap(
}
function renderSchemaTypeReference(schemaName: string) {
return schemaName === "undefined" ? "undefined" : `CodexSchema.${schemaName}`;
return schemaName === "undefined" ? "undefined" : `typeof CodexSchema.${schemaName}.Type`;
}
function exportNameForPath(filePath: string): string {
@@ -468,11 +469,11 @@ function buildJsonSchemaFiles(
}
function rewriteExternalRefs(
value: Schema.Json,
value: typeof Schema.Json.Type,
localDefinitionNames: ReadonlyMap<string, string>,
currentNamespace: string | undefined,
exportNameByQualifiedName: ReadonlyMap<string, string>,
): Schema.Json {
): typeof Schema.Json.Type {
if (Array.isArray(value)) {
return value.map((entry) =>
rewriteExternalRefs(entry, localDefinitionNames, currentNamespace, exportNameByQualifiedName),
@@ -522,7 +523,7 @@ function rewriteExternalRefs(
),
];
}),
) as Schema.Json;
) as typeof Schema.Json.Type;
}
const generateFiles = Effect.fn("generateFiles")(function* () {
@@ -543,11 +544,13 @@ const generateFiles = Effect.fn("generateFiles")(function* () {
const exportNameByQualifiedName = new Map(
jsonSchemaFiles.map((file) => [file.qualifiedName, file.exportName]),
);
const aggregateSchemas: Record<string, Schema.Json> = {};
const aggregateSchemas: Record<string, typeof Schema.Json.Type> = {};
for (const file of jsonSchemaFiles) {
const raw = yield* fetchText(file.downloadUrl);
const parsed = yield* decodeJsonSchemaDocument(raw);
const parsed = JSON.parse(raw) as {
readonly definitions?: Record<string, typeof Schema.Json.Type>;
} & Record<string, typeof Schema.Json.Type>;
const localDefinitionNames = new Map(
Object.keys(parsed.definitions ?? {}).map((definitionName) => [
definitionName,
@@ -568,7 +571,7 @@ const generateFiles = Effect.fn("generateFiles")(function* () {
);
}
const topLevelSchema: Record<string, Schema.Json> = {};
const topLevelSchema: Record<string, typeof Schema.Json.Type> = {};
for (const [key, value] of Object.entries(parsed)) {
if (key !== "definitions") {
topLevelSchema[key] = value;
@@ -748,16 +751,14 @@ const generateFiles = Effect.fn("generateFiles")(function* () {
yield* Effect.log(`Generated Codex App Server schemas from ${UPSTREAM_REF}`);
yield* Effect.service(ChildProcessSpawner.ChildProcessSpawner).pipe(
Effect.flatMap((spawner) =>
spawner.spawn(ChildProcess.make("vp", ["fmt", generatedDir, "--write"])),
),
Effect.flatMap((spawner) => spawner.spawn(ChildProcess.make("bun", ["oxfmt", generatedDir]))),
Effect.flatMap((child) => child.exitCode),
Effect.tap((code) =>
code === 0
? Effect.void
: Effect.fail(
new GeneratorError({
detail: `vp fmt failed with exit code ${code}`,
detail: `oxfmt failed with exit code ${code}`,
}),
),
),
@@ -766,12 +767,6 @@ const generateFiles = Effect.fn("generateFiles")(function* () {
generateFiles().pipe(
Effect.scoped,
Effect.provide(
Layer.mergeAll(
Logger.layer([Logger.consolePretty()]),
NodeServices.layer,
FetchHttpClient.layer,
),
),
Effect.provide(Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer)),
NodeRuntime.runMain,
);
@@ -1,5 +1,5 @@
// This file is generated by the effect-codex-app-server package. Do not edit manually.
// Upstream protocol ref: 678157acaa819d5510adfe359abb5d0392cfe461
// Upstream protocol ref: dbfe855f4fd0f5dcdf079882652a8efe622b0595
import * as CodexSchema from "./schema.gen.ts";
@@ -9,40 +9,20 @@ export const CLIENT_REQUEST_METHODS = {
"thread/resume": "thread/resume",
"thread/fork": "thread/fork",
"thread/archive": "thread/archive",
"thread/delete": "thread/delete",
"thread/unsubscribe": "thread/unsubscribe",
"thread/name/set": "thread/name/set",
"thread/goal/set": "thread/goal/set",
"thread/goal/get": "thread/goal/get",
"thread/goal/clear": "thread/goal/clear",
"thread/metadata/update": "thread/metadata/update",
"thread/unarchive": "thread/unarchive",
"thread/compact/start": "thread/compact/start",
"thread/shellCommand": "thread/shellCommand",
"thread/approveGuardianDeniedAction": "thread/approveGuardianDeniedAction",
"thread/rollback": "thread/rollback",
"thread/list": "thread/list",
"thread/loaded/list": "thread/loaded/list",
"thread/read": "thread/read",
"thread/inject_items": "thread/inject_items",
"skills/list": "skills/list",
"skills/extraRoots/set": "skills/extraRoots/set",
"hooks/list": "hooks/list",
"marketplace/add": "marketplace/add",
"marketplace/remove": "marketplace/remove",
"marketplace/upgrade": "marketplace/upgrade",
"plugin/list": "plugin/list",
"plugin/installed": "plugin/installed",
"plugin/read": "plugin/read",
"plugin/skill/read": "plugin/skill/read",
"plugin/share/save": "plugin/share/save",
"plugin/share/updateTargets": "plugin/share/updateTargets",
"plugin/share/list": "plugin/share/list",
"plugin/share/checkout": "plugin/share/checkout",
"plugin/share/delete": "plugin/share/delete",
"app/read": "app/read",
"app/list": "app/list",
"app/installed": "app/installed",
"fs/readFile": "fs/readFile",
"fs/writeFile": "fs/writeFile",
"fs/createDirectory": "fs/createDirectory",
@@ -60,9 +40,7 @@ export const CLIENT_REQUEST_METHODS = {
"turn/interrupt": "turn/interrupt",
"review/start": "review/start",
"model/list": "model/list",
"modelProvider/capabilities/read": "modelProvider/capabilities/read",
"experimentalFeature/list": "experimentalFeature/list",
"permissionProfile/list": "permissionProfile/list",
"experimentalFeature/enablement/set": "experimentalFeature/enablement/set",
"mcpServer/oauth/login": "mcpServer/oauth/login",
"config/mcpServer/reload": "config/mcpServer/reload",
@@ -70,15 +48,10 @@ export const CLIENT_REQUEST_METHODS = {
"mcpServer/resource/read": "mcpServer/resource/read",
"mcpServer/tool/call": "mcpServer/tool/call",
"windowsSandbox/setupStart": "windowsSandbox/setupStart",
"windowsSandbox/readiness": "windowsSandbox/readiness",
"account/login/start": "account/login/start",
"account/login/cancel": "account/login/cancel",
"account/logout": "account/logout",
"account/rateLimits/read": "account/rateLimits/read",
"account/rateLimitResetCredit/consume": "account/rateLimitResetCredit/consume",
"account/usage/read": "account/usage/read",
"account/workspaceMessages/read": "account/workspaceMessages/read",
"account/sendAddCreditsNudgeEmail": "account/sendAddCreditsNudgeEmail",
"feedback/upload": "feedback/upload",
"command/exec": "command/exec",
"command/exec/write": "command/exec/write",
@@ -87,7 +60,6 @@ export const CLIENT_REQUEST_METHODS = {
"config/read": "config/read",
"externalAgentConfig/detect": "externalAgentConfig/detect",
"externalAgentConfig/import": "externalAgentConfig/import",
"externalAgentConfig/import/readHistories": "externalAgentConfig/import/readHistories",
"config/value/write": "config/value/write",
"config/batchWrite": "config/batchWrite",
"configRequirements/read": "configRequirements/read",
@@ -110,7 +82,6 @@ export const SERVER_REQUEST_METHODS = {
"item/permissions/requestApproval": "item/permissions/requestApproval",
"item/tool/call": "item/tool/call",
"account/chatgptAuthTokens/refresh": "account/chatgptAuthTokens/refresh",
"attestation/generate": "attestation/generate",
applyPatchApproval: "applyPatchApproval",
execCommandApproval: "execCommandApproval",
} as const;
@@ -120,16 +91,10 @@ export const SERVER_NOTIFICATION_METHODS = {
"thread/started": "thread/started",
"thread/status/changed": "thread/status/changed",
"thread/archived": "thread/archived",
"thread/deleted": "thread/deleted",
"thread/unarchived": "thread/unarchived",
"thread/closed": "thread/closed",
"skills/changed": "skills/changed",
"thread/name/updated": "thread/name/updated",
"thread/goal/updated": "thread/goal/updated",
"thread/goal/cleared": "thread/goal/cleared",
"thread/environment/connected": "thread/environment/connected",
"thread/environment/disconnected": "thread/environment/disconnected",
"thread/settings/updated": "thread/settings/updated",
"thread/tokenUsage/updated": "thread/tokenUsage/updated",
"turn/started": "turn/started",
"hook/started": "hook/started",
@@ -142,16 +107,12 @@ export const SERVER_NOTIFICATION_METHODS = {
"item/autoApprovalReview/completed": "item/autoApprovalReview/completed",
"item/completed": "item/completed",
"rawResponseItem/completed": "rawResponseItem/completed",
"rawResponse/completed": "rawResponse/completed",
"item/agentMessage/delta": "item/agentMessage/delta",
"item/plan/delta": "item/plan/delta",
"command/exec/outputDelta": "command/exec/outputDelta",
"process/outputDelta": "process/outputDelta",
"process/exited": "process/exited",
"item/commandExecution/outputDelta": "item/commandExecution/outputDelta",
"item/commandExecution/terminalInteraction": "item/commandExecution/terminalInteraction",
"item/fileChange/outputDelta": "item/fileChange/outputDelta",
"item/fileChange/patchUpdated": "item/fileChange/patchUpdated",
"serverRequest/resolved": "serverRequest/resolved",
"item/mcpToolCall/progress": "item/mcpToolCall/progress",
"mcpServer/oauthLogin/completed": "mcpServer/oauthLogin/completed",
@@ -159,28 +120,19 @@ export const SERVER_NOTIFICATION_METHODS = {
"account/updated": "account/updated",
"account/rateLimits/updated": "account/rateLimits/updated",
"app/list/updated": "app/list/updated",
"remoteControl/status/changed": "remoteControl/status/changed",
"externalAgentConfig/import/progress": "externalAgentConfig/import/progress",
"externalAgentConfig/import/completed": "externalAgentConfig/import/completed",
"fs/changed": "fs/changed",
"item/reasoning/summaryTextDelta": "item/reasoning/summaryTextDelta",
"item/reasoning/summaryPartAdded": "item/reasoning/summaryPartAdded",
"item/reasoning/textDelta": "item/reasoning/textDelta",
"thread/compacted": "thread/compacted",
"model/rerouted": "model/rerouted",
"model/verification": "model/verification",
"turn/moderationMetadata": "turn/moderationMetadata",
"model/safetyBuffering/updated": "model/safetyBuffering/updated",
warning: "warning",
guardianWarning: "guardianWarning",
deprecationNotice: "deprecationNotice",
configWarning: "configWarning",
"fuzzyFileSearch/sessionUpdated": "fuzzyFileSearch/sessionUpdated",
"fuzzyFileSearch/sessionCompleted": "fuzzyFileSearch/sessionCompleted",
"thread/realtime/started": "thread/realtime/started",
"thread/realtime/itemAdded": "thread/realtime/itemAdded",
"thread/realtime/transcript/delta": "thread/realtime/transcript/delta",
"thread/realtime/transcript/done": "thread/realtime/transcript/done",
"thread/realtime/transcriptUpdated": "thread/realtime/transcriptUpdated",
"thread/realtime/outputAudio/delta": "thread/realtime/outputAudio/delta",
"thread/realtime/sdp": "thread/realtime/sdp",
"thread/realtime/error": "thread/realtime/error",
@@ -196,193 +148,137 @@ export type ServerRequestMethod = keyof typeof SERVER_REQUEST_METHODS;
export type ServerNotificationMethod = keyof typeof SERVER_NOTIFICATION_METHODS;
export interface ClientRequestParamsByMethod {
readonly initialize: CodexSchema.V1InitializeParams;
readonly "thread/start": CodexSchema.V2ThreadStartParams;
readonly "thread/resume": CodexSchema.V2ThreadResumeParams;
readonly "thread/fork": CodexSchema.V2ThreadForkParams;
readonly "thread/archive": CodexSchema.V2ThreadArchiveParams;
readonly "thread/delete": CodexSchema.V2ThreadDeleteParams;
readonly "thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeParams;
readonly "thread/name/set": CodexSchema.V2ThreadSetNameParams;
readonly "thread/goal/set": CodexSchema.V2ThreadGoalSetParams;
readonly "thread/goal/get": CodexSchema.V2ThreadGoalGetParams;
readonly "thread/goal/clear": CodexSchema.V2ThreadGoalClearParams;
readonly "thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateParams;
readonly "thread/unarchive": CodexSchema.V2ThreadUnarchiveParams;
readonly "thread/compact/start": CodexSchema.V2ThreadCompactStartParams;
readonly "thread/shellCommand": CodexSchema.V2ThreadShellCommandParams;
readonly "thread/approveGuardianDeniedAction": CodexSchema.V2ThreadApproveGuardianDeniedActionParams;
readonly "thread/rollback": CodexSchema.V2ThreadRollbackParams;
readonly "thread/list": CodexSchema.V2ThreadListParams;
readonly "thread/loaded/list": CodexSchema.V2ThreadLoadedListParams;
readonly "thread/read": CodexSchema.V2ThreadReadParams;
readonly "thread/inject_items": CodexSchema.V2ThreadInjectItemsParams;
readonly "skills/list": CodexSchema.V2SkillsListParams;
readonly "skills/extraRoots/set": CodexSchema.V2SkillsExtraRootsSetParams;
readonly "hooks/list": CodexSchema.V2HooksListParams;
readonly "marketplace/add": CodexSchema.V2MarketplaceAddParams;
readonly "marketplace/remove": CodexSchema.V2MarketplaceRemoveParams;
readonly "marketplace/upgrade": CodexSchema.V2MarketplaceUpgradeParams;
readonly "plugin/list": CodexSchema.V2PluginListParams;
readonly "plugin/installed": CodexSchema.V2PluginInstalledParams;
readonly "plugin/read": CodexSchema.V2PluginReadParams;
readonly "plugin/skill/read": CodexSchema.V2PluginSkillReadParams;
readonly "plugin/share/save": CodexSchema.V2PluginShareSaveParams;
readonly "plugin/share/updateTargets": CodexSchema.V2PluginShareUpdateTargetsParams;
readonly "plugin/share/list": CodexSchema.V2PluginShareListParams;
readonly "plugin/share/checkout": CodexSchema.V2PluginShareCheckoutParams;
readonly "plugin/share/delete": CodexSchema.V2PluginShareDeleteParams;
readonly "app/read": CodexSchema.V2AppsReadParams;
readonly "app/list": CodexSchema.V2AppsListParams;
readonly "app/installed": CodexSchema.V2AppsInstalledParams;
readonly "fs/readFile": CodexSchema.V2FsReadFileParams;
readonly "fs/writeFile": CodexSchema.V2FsWriteFileParams;
readonly "fs/createDirectory": CodexSchema.V2FsCreateDirectoryParams;
readonly "fs/getMetadata": CodexSchema.V2FsGetMetadataParams;
readonly "fs/readDirectory": CodexSchema.V2FsReadDirectoryParams;
readonly "fs/remove": CodexSchema.V2FsRemoveParams;
readonly "fs/copy": CodexSchema.V2FsCopyParams;
readonly "fs/watch": CodexSchema.V2FsWatchParams;
readonly "fs/unwatch": CodexSchema.V2FsUnwatchParams;
readonly "skills/config/write": CodexSchema.V2SkillsConfigWriteParams;
readonly "plugin/install": CodexSchema.V2PluginInstallParams;
readonly "plugin/uninstall": CodexSchema.V2PluginUninstallParams;
readonly "turn/start": CodexSchema.V2TurnStartParams;
readonly "turn/steer": CodexSchema.V2TurnSteerParams;
readonly "turn/interrupt": CodexSchema.V2TurnInterruptParams;
readonly "review/start": CodexSchema.V2ReviewStartParams;
readonly "model/list": CodexSchema.V2ModelListParams;
readonly "modelProvider/capabilities/read": CodexSchema.V2ModelProviderCapabilitiesReadParams;
readonly "experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListParams;
readonly "permissionProfile/list": CodexSchema.V2PermissionProfileListParams;
readonly "experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetParams;
readonly "mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginParams;
readonly initialize: typeof CodexSchema.V1InitializeParams.Type;
readonly "thread/start": typeof CodexSchema.V2ThreadStartParams.Type;
readonly "thread/resume": typeof CodexSchema.V2ThreadResumeParams.Type;
readonly "thread/fork": typeof CodexSchema.V2ThreadForkParams.Type;
readonly "thread/archive": typeof CodexSchema.V2ThreadArchiveParams.Type;
readonly "thread/unsubscribe": typeof CodexSchema.V2ThreadUnsubscribeParams.Type;
readonly "thread/name/set": typeof CodexSchema.V2ThreadSetNameParams.Type;
readonly "thread/metadata/update": typeof CodexSchema.V2ThreadMetadataUpdateParams.Type;
readonly "thread/unarchive": typeof CodexSchema.V2ThreadUnarchiveParams.Type;
readonly "thread/compact/start": typeof CodexSchema.V2ThreadCompactStartParams.Type;
readonly "thread/shellCommand": typeof CodexSchema.V2ThreadShellCommandParams.Type;
readonly "thread/rollback": typeof CodexSchema.V2ThreadRollbackParams.Type;
readonly "thread/list": typeof CodexSchema.V2ThreadListParams.Type;
readonly "thread/loaded/list": typeof CodexSchema.V2ThreadLoadedListParams.Type;
readonly "thread/read": typeof CodexSchema.V2ThreadReadParams.Type;
readonly "skills/list": typeof CodexSchema.V2SkillsListParams.Type;
readonly "plugin/list": typeof CodexSchema.V2PluginListParams.Type;
readonly "plugin/read": typeof CodexSchema.V2PluginReadParams.Type;
readonly "app/list": typeof CodexSchema.V2AppsListParams.Type;
readonly "fs/readFile": typeof CodexSchema.V2FsReadFileParams.Type;
readonly "fs/writeFile": typeof CodexSchema.V2FsWriteFileParams.Type;
readonly "fs/createDirectory": typeof CodexSchema.V2FsCreateDirectoryParams.Type;
readonly "fs/getMetadata": typeof CodexSchema.V2FsGetMetadataParams.Type;
readonly "fs/readDirectory": typeof CodexSchema.V2FsReadDirectoryParams.Type;
readonly "fs/remove": typeof CodexSchema.V2FsRemoveParams.Type;
readonly "fs/copy": typeof CodexSchema.V2FsCopyParams.Type;
readonly "fs/watch": typeof CodexSchema.V2FsWatchParams.Type;
readonly "fs/unwatch": typeof CodexSchema.V2FsUnwatchParams.Type;
readonly "skills/config/write": typeof CodexSchema.V2SkillsConfigWriteParams.Type;
readonly "plugin/install": typeof CodexSchema.V2PluginInstallParams.Type;
readonly "plugin/uninstall": typeof CodexSchema.V2PluginUninstallParams.Type;
readonly "turn/start": typeof CodexSchema.V2TurnStartParams.Type;
readonly "turn/steer": typeof CodexSchema.V2TurnSteerParams.Type;
readonly "turn/interrupt": typeof CodexSchema.V2TurnInterruptParams.Type;
readonly "review/start": typeof CodexSchema.V2ReviewStartParams.Type;
readonly "model/list": typeof CodexSchema.V2ModelListParams.Type;
readonly "experimentalFeature/list": typeof CodexSchema.V2ExperimentalFeatureListParams.Type;
readonly "experimentalFeature/enablement/set": typeof CodexSchema.V2ExperimentalFeatureEnablementSetParams.Type;
readonly "mcpServer/oauth/login": typeof CodexSchema.V2McpServerOauthLoginParams.Type;
readonly "config/mcpServer/reload": undefined;
readonly "mcpServerStatus/list": CodexSchema.V2ListMcpServerStatusParams;
readonly "mcpServer/resource/read": CodexSchema.V2McpResourceReadParams;
readonly "mcpServer/tool/call": CodexSchema.V2McpServerToolCallParams;
readonly "windowsSandbox/setupStart": CodexSchema.V2WindowsSandboxSetupStartParams;
readonly "windowsSandbox/readiness": undefined;
readonly "account/login/start": CodexSchema.V2LoginAccountParams;
readonly "account/login/cancel": CodexSchema.V2CancelLoginAccountParams;
readonly "mcpServerStatus/list": typeof CodexSchema.V2ListMcpServerStatusParams.Type;
readonly "mcpServer/resource/read": typeof CodexSchema.V2McpResourceReadParams.Type;
readonly "mcpServer/tool/call": typeof CodexSchema.V2McpServerToolCallParams.Type;
readonly "windowsSandbox/setupStart": typeof CodexSchema.V2WindowsSandboxSetupStartParams.Type;
readonly "account/login/start": typeof CodexSchema.V2LoginAccountParams.Type;
readonly "account/login/cancel": typeof CodexSchema.V2CancelLoginAccountParams.Type;
readonly "account/logout": undefined;
readonly "account/rateLimits/read": undefined;
readonly "account/rateLimitResetCredit/consume": CodexSchema.V2ConsumeAccountRateLimitResetCreditParams;
readonly "account/usage/read": undefined;
readonly "account/workspaceMessages/read": undefined;
readonly "account/sendAddCreditsNudgeEmail": CodexSchema.V2SendAddCreditsNudgeEmailParams;
readonly "feedback/upload": CodexSchema.V2FeedbackUploadParams;
readonly "command/exec": CodexSchema.V2CommandExecParams;
readonly "command/exec/write": CodexSchema.V2CommandExecWriteParams;
readonly "command/exec/terminate": CodexSchema.V2CommandExecTerminateParams;
readonly "command/exec/resize": CodexSchema.V2CommandExecResizeParams;
readonly "config/read": CodexSchema.V2ConfigReadParams;
readonly "externalAgentConfig/detect": CodexSchema.V2ExternalAgentConfigDetectParams;
readonly "externalAgentConfig/import": CodexSchema.V2ExternalAgentConfigImportParams;
readonly "externalAgentConfig/import/readHistories": undefined;
readonly "config/value/write": CodexSchema.V2ConfigValueWriteParams;
readonly "config/batchWrite": CodexSchema.V2ConfigBatchWriteParams;
readonly "feedback/upload": typeof CodexSchema.V2FeedbackUploadParams.Type;
readonly "command/exec": typeof CodexSchema.V2CommandExecParams.Type;
readonly "command/exec/write": typeof CodexSchema.V2CommandExecWriteParams.Type;
readonly "command/exec/terminate": typeof CodexSchema.V2CommandExecTerminateParams.Type;
readonly "command/exec/resize": typeof CodexSchema.V2CommandExecResizeParams.Type;
readonly "config/read": typeof CodexSchema.V2ConfigReadParams.Type;
readonly "externalAgentConfig/detect": typeof CodexSchema.V2ExternalAgentConfigDetectParams.Type;
readonly "externalAgentConfig/import": typeof CodexSchema.V2ExternalAgentConfigImportParams.Type;
readonly "config/value/write": typeof CodexSchema.V2ConfigValueWriteParams.Type;
readonly "config/batchWrite": typeof CodexSchema.V2ConfigBatchWriteParams.Type;
readonly "configRequirements/read": undefined;
readonly "account/read": CodexSchema.V2GetAccountParams;
readonly getConversationSummary: CodexSchema.GetConversationSummaryParams;
readonly gitDiffToRemote: CodexSchema.GitDiffToRemoteParams;
readonly getAuthStatus: CodexSchema.GetAuthStatusParams;
readonly fuzzyFileSearch: CodexSchema.FuzzyFileSearchParams;
readonly "account/read": typeof CodexSchema.V2GetAccountParams.Type;
readonly getConversationSummary: typeof CodexSchema.GetConversationSummaryParams.Type;
readonly gitDiffToRemote: typeof CodexSchema.GitDiffToRemoteParams.Type;
readonly getAuthStatus: typeof CodexSchema.GetAuthStatusParams.Type;
readonly fuzzyFileSearch: typeof CodexSchema.FuzzyFileSearchParams.Type;
}
export interface ClientRequestResponsesByMethod {
readonly initialize: CodexSchema.V1InitializeResponse;
readonly "thread/start": CodexSchema.V2ThreadStartResponse;
readonly "thread/resume": CodexSchema.V2ThreadResumeResponse;
readonly "thread/fork": CodexSchema.V2ThreadForkResponse;
readonly "thread/archive": CodexSchema.V2ThreadArchiveResponse;
readonly "thread/delete": CodexSchema.V2ThreadDeleteResponse;
readonly "thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeResponse;
readonly "thread/name/set": CodexSchema.V2ThreadSetNameResponse;
readonly "thread/goal/set": CodexSchema.V2ThreadGoalSetResponse;
readonly "thread/goal/get": CodexSchema.V2ThreadGoalGetResponse;
readonly "thread/goal/clear": CodexSchema.V2ThreadGoalClearResponse;
readonly "thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateResponse;
readonly "thread/unarchive": CodexSchema.V2ThreadUnarchiveResponse;
readonly "thread/compact/start": CodexSchema.V2ThreadCompactStartResponse;
readonly "thread/shellCommand": CodexSchema.V2ThreadShellCommandResponse;
readonly "thread/approveGuardianDeniedAction": CodexSchema.V2ThreadApproveGuardianDeniedActionResponse;
readonly "thread/rollback": CodexSchema.V2ThreadRollbackResponse;
readonly "thread/list": CodexSchema.V2ThreadListResponse;
readonly "thread/loaded/list": CodexSchema.V2ThreadLoadedListResponse;
readonly "thread/read": CodexSchema.V2ThreadReadResponse;
readonly "thread/inject_items": CodexSchema.V2ThreadInjectItemsResponse;
readonly "skills/list": CodexSchema.V2SkillsListResponse;
readonly "skills/extraRoots/set": CodexSchema.V2SkillsExtraRootsSetResponse;
readonly "hooks/list": CodexSchema.V2HooksListResponse;
readonly "marketplace/add": CodexSchema.V2MarketplaceAddResponse;
readonly "marketplace/remove": CodexSchema.V2MarketplaceRemoveResponse;
readonly "marketplace/upgrade": CodexSchema.V2MarketplaceUpgradeResponse;
readonly "plugin/list": CodexSchema.V2PluginListResponse;
readonly "plugin/installed": CodexSchema.V2PluginInstalledResponse;
readonly "plugin/read": CodexSchema.V2PluginReadResponse;
readonly "plugin/skill/read": CodexSchema.V2PluginSkillReadResponse;
readonly "plugin/share/save": CodexSchema.V2PluginShareSaveResponse;
readonly "plugin/share/updateTargets": CodexSchema.V2PluginShareUpdateTargetsResponse;
readonly "plugin/share/list": CodexSchema.V2PluginShareListResponse;
readonly "plugin/share/checkout": CodexSchema.V2PluginShareCheckoutResponse;
readonly "plugin/share/delete": CodexSchema.V2PluginShareDeleteResponse;
readonly "app/read": CodexSchema.V2AppsReadResponse;
readonly "app/list": CodexSchema.V2AppsListResponse;
readonly "app/installed": CodexSchema.V2AppsInstalledResponse;
readonly "fs/readFile": CodexSchema.V2FsReadFileResponse;
readonly "fs/writeFile": CodexSchema.V2FsWriteFileResponse;
readonly "fs/createDirectory": CodexSchema.V2FsCreateDirectoryResponse;
readonly "fs/getMetadata": CodexSchema.V2FsGetMetadataResponse;
readonly "fs/readDirectory": CodexSchema.V2FsReadDirectoryResponse;
readonly "fs/remove": CodexSchema.V2FsRemoveResponse;
readonly "fs/copy": CodexSchema.V2FsCopyResponse;
readonly "fs/watch": CodexSchema.V2FsWatchResponse;
readonly "fs/unwatch": CodexSchema.V2FsUnwatchResponse;
readonly "skills/config/write": CodexSchema.V2SkillsConfigWriteResponse;
readonly "plugin/install": CodexSchema.V2PluginInstallResponse;
readonly "plugin/uninstall": CodexSchema.V2PluginUninstallResponse;
readonly "turn/start": CodexSchema.V2TurnStartResponse;
readonly "turn/steer": CodexSchema.V2TurnSteerResponse;
readonly "turn/interrupt": CodexSchema.V2TurnInterruptResponse;
readonly "review/start": CodexSchema.V2ReviewStartResponse;
readonly "model/list": CodexSchema.V2ModelListResponse;
readonly "modelProvider/capabilities/read": CodexSchema.V2ModelProviderCapabilitiesReadResponse;
readonly "experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListResponse;
readonly "permissionProfile/list": CodexSchema.V2PermissionProfileListResponse;
readonly "experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetResponse;
readonly "mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginResponse;
readonly "config/mcpServer/reload": CodexSchema.V2McpServerRefreshResponse;
readonly "mcpServerStatus/list": CodexSchema.V2ListMcpServerStatusResponse;
readonly "mcpServer/resource/read": CodexSchema.V2McpResourceReadResponse;
readonly "mcpServer/tool/call": CodexSchema.V2McpServerToolCallResponse;
readonly "windowsSandbox/setupStart": CodexSchema.V2WindowsSandboxSetupStartResponse;
readonly "windowsSandbox/readiness": CodexSchema.V2WindowsSandboxReadinessResponse;
readonly "account/login/start": CodexSchema.V2LoginAccountResponse;
readonly "account/login/cancel": CodexSchema.V2CancelLoginAccountResponse;
readonly "account/logout": CodexSchema.V2LogoutAccountResponse;
readonly "account/rateLimits/read": CodexSchema.V2GetAccountRateLimitsResponse;
readonly "account/rateLimitResetCredit/consume": CodexSchema.V2ConsumeAccountRateLimitResetCreditResponse;
readonly "account/usage/read": CodexSchema.V2GetAccountTokenUsageResponse;
readonly "account/workspaceMessages/read": CodexSchema.V2GetWorkspaceMessagesResponse;
readonly "account/sendAddCreditsNudgeEmail": CodexSchema.V2SendAddCreditsNudgeEmailResponse;
readonly "feedback/upload": CodexSchema.V2FeedbackUploadResponse;
readonly "command/exec": CodexSchema.V2CommandExecResponse;
readonly "command/exec/write": CodexSchema.V2CommandExecWriteResponse;
readonly "command/exec/terminate": CodexSchema.V2CommandExecTerminateResponse;
readonly "command/exec/resize": CodexSchema.V2CommandExecResizeResponse;
readonly "config/read": CodexSchema.V2ConfigReadResponse;
readonly "externalAgentConfig/detect": CodexSchema.V2ExternalAgentConfigDetectResponse;
readonly "externalAgentConfig/import": CodexSchema.V2ExternalAgentConfigImportResponse;
readonly "externalAgentConfig/import/readHistories": CodexSchema.V2ExternalAgentConfigImportHistoriesReadResponse;
readonly "config/value/write": CodexSchema.V2ConfigWriteResponse;
readonly "config/batchWrite": CodexSchema.V2ConfigWriteResponse;
readonly "configRequirements/read": CodexSchema.V2ConfigRequirementsReadResponse;
readonly "account/read": CodexSchema.V2GetAccountResponse;
readonly getConversationSummary: CodexSchema.GetConversationSummaryResponse;
readonly gitDiffToRemote: CodexSchema.GitDiffToRemoteResponse;
readonly getAuthStatus: CodexSchema.GetAuthStatusResponse;
readonly fuzzyFileSearch: CodexSchema.FuzzyFileSearchResponse;
readonly initialize: typeof CodexSchema.V1InitializeResponse.Type;
readonly "thread/start": typeof CodexSchema.V2ThreadStartResponse.Type;
readonly "thread/resume": typeof CodexSchema.V2ThreadResumeResponse.Type;
readonly "thread/fork": typeof CodexSchema.V2ThreadForkResponse.Type;
readonly "thread/archive": typeof CodexSchema.V2ThreadArchiveResponse.Type;
readonly "thread/unsubscribe": typeof CodexSchema.V2ThreadUnsubscribeResponse.Type;
readonly "thread/name/set": typeof CodexSchema.V2ThreadSetNameResponse.Type;
readonly "thread/metadata/update": typeof CodexSchema.V2ThreadMetadataUpdateResponse.Type;
readonly "thread/unarchive": typeof CodexSchema.V2ThreadUnarchiveResponse.Type;
readonly "thread/compact/start": typeof CodexSchema.V2ThreadCompactStartResponse.Type;
readonly "thread/shellCommand": typeof CodexSchema.V2ThreadShellCommandResponse.Type;
readonly "thread/rollback": typeof CodexSchema.V2ThreadRollbackResponse.Type;
readonly "thread/list": typeof CodexSchema.V2ThreadListResponse.Type;
readonly "thread/loaded/list": typeof CodexSchema.V2ThreadLoadedListResponse.Type;
readonly "thread/read": typeof CodexSchema.V2ThreadReadResponse.Type;
readonly "skills/list": typeof CodexSchema.V2SkillsListResponse.Type;
readonly "plugin/list": typeof CodexSchema.V2PluginListResponse.Type;
readonly "plugin/read": typeof CodexSchema.V2PluginReadResponse.Type;
readonly "app/list": typeof CodexSchema.V2AppsListResponse.Type;
readonly "fs/readFile": typeof CodexSchema.V2FsReadFileResponse.Type;
readonly "fs/writeFile": typeof CodexSchema.V2FsWriteFileResponse.Type;
readonly "fs/createDirectory": typeof CodexSchema.V2FsCreateDirectoryResponse.Type;
readonly "fs/getMetadata": typeof CodexSchema.V2FsGetMetadataResponse.Type;
readonly "fs/readDirectory": typeof CodexSchema.V2FsReadDirectoryResponse.Type;
readonly "fs/remove": typeof CodexSchema.V2FsRemoveResponse.Type;
readonly "fs/copy": typeof CodexSchema.V2FsCopyResponse.Type;
readonly "fs/watch": typeof CodexSchema.V2FsWatchResponse.Type;
readonly "fs/unwatch": typeof CodexSchema.V2FsUnwatchResponse.Type;
readonly "skills/config/write": typeof CodexSchema.V2SkillsConfigWriteResponse.Type;
readonly "plugin/install": typeof CodexSchema.V2PluginInstallResponse.Type;
readonly "plugin/uninstall": typeof CodexSchema.V2PluginUninstallResponse.Type;
readonly "turn/start": typeof CodexSchema.V2TurnStartResponse.Type;
readonly "turn/steer": typeof CodexSchema.V2TurnSteerResponse.Type;
readonly "turn/interrupt": typeof CodexSchema.V2TurnInterruptResponse.Type;
readonly "review/start": typeof CodexSchema.V2ReviewStartResponse.Type;
readonly "model/list": typeof CodexSchema.V2ModelListResponse.Type;
readonly "experimentalFeature/list": typeof CodexSchema.V2ExperimentalFeatureListResponse.Type;
readonly "experimentalFeature/enablement/set": typeof CodexSchema.V2ExperimentalFeatureEnablementSetResponse.Type;
readonly "mcpServer/oauth/login": typeof CodexSchema.V2McpServerOauthLoginResponse.Type;
readonly "config/mcpServer/reload": typeof CodexSchema.V2McpServerRefreshResponse.Type;
readonly "mcpServerStatus/list": typeof CodexSchema.V2ListMcpServerStatusResponse.Type;
readonly "mcpServer/resource/read": typeof CodexSchema.V2McpResourceReadResponse.Type;
readonly "mcpServer/tool/call": typeof CodexSchema.V2McpServerToolCallResponse.Type;
readonly "windowsSandbox/setupStart": typeof CodexSchema.V2WindowsSandboxSetupStartResponse.Type;
readonly "account/login/start": typeof CodexSchema.V2LoginAccountResponse.Type;
readonly "account/login/cancel": typeof CodexSchema.V2CancelLoginAccountResponse.Type;
readonly "account/logout": typeof CodexSchema.V2LogoutAccountResponse.Type;
readonly "account/rateLimits/read": typeof CodexSchema.V2GetAccountRateLimitsResponse.Type;
readonly "feedback/upload": typeof CodexSchema.V2FeedbackUploadResponse.Type;
readonly "command/exec": typeof CodexSchema.V2CommandExecResponse.Type;
readonly "command/exec/write": typeof CodexSchema.V2CommandExecWriteResponse.Type;
readonly "command/exec/terminate": typeof CodexSchema.V2CommandExecTerminateResponse.Type;
readonly "command/exec/resize": typeof CodexSchema.V2CommandExecResizeResponse.Type;
readonly "config/read": typeof CodexSchema.V2ConfigReadResponse.Type;
readonly "externalAgentConfig/detect": typeof CodexSchema.V2ExternalAgentConfigDetectResponse.Type;
readonly "externalAgentConfig/import": typeof CodexSchema.V2ExternalAgentConfigImportResponse.Type;
readonly "config/value/write": typeof CodexSchema.V2ConfigWriteResponse.Type;
readonly "config/batchWrite": typeof CodexSchema.V2ConfigWriteResponse.Type;
readonly "configRequirements/read": typeof CodexSchema.V2ConfigRequirementsReadResponse.Type;
readonly "account/read": typeof CodexSchema.V2GetAccountResponse.Type;
readonly getConversationSummary: typeof CodexSchema.GetConversationSummaryResponse.Type;
readonly gitDiffToRemote: typeof CodexSchema.GitDiffToRemoteResponse.Type;
readonly getAuthStatus: typeof CodexSchema.GetAuthStatusResponse.Type;
readonly fuzzyFileSearch: typeof CodexSchema.FuzzyFileSearchResponse.Type;
}
export interface ClientNotificationParamsByMethod {
@@ -390,104 +286,83 @@ export interface ClientNotificationParamsByMethod {
}
export interface ServerRequestParamsByMethod {
readonly "item/commandExecution/requestApproval": CodexSchema.CommandExecutionRequestApprovalParams;
readonly "item/fileChange/requestApproval": CodexSchema.FileChangeRequestApprovalParams;
readonly "item/tool/requestUserInput": CodexSchema.ToolRequestUserInputParams;
readonly "mcpServer/elicitation/request": CodexSchema.McpServerElicitationRequestParams;
readonly "item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalParams;
readonly "item/tool/call": CodexSchema.DynamicToolCallParams;
readonly "account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshParams;
readonly "attestation/generate": CodexSchema.AttestationGenerateParams;
readonly applyPatchApproval: CodexSchema.ApplyPatchApprovalParams;
readonly execCommandApproval: CodexSchema.ExecCommandApprovalParams;
readonly "item/commandExecution/requestApproval": typeof CodexSchema.CommandExecutionRequestApprovalParams.Type;
readonly "item/fileChange/requestApproval": typeof CodexSchema.FileChangeRequestApprovalParams.Type;
readonly "item/tool/requestUserInput": typeof CodexSchema.ToolRequestUserInputParams.Type;
readonly "mcpServer/elicitation/request": typeof CodexSchema.McpServerElicitationRequestParams.Type;
readonly "item/permissions/requestApproval": typeof CodexSchema.PermissionsRequestApprovalParams.Type;
readonly "item/tool/call": typeof CodexSchema.DynamicToolCallParams.Type;
readonly "account/chatgptAuthTokens/refresh": typeof CodexSchema.ChatgptAuthTokensRefreshParams.Type;
readonly applyPatchApproval: typeof CodexSchema.ApplyPatchApprovalParams.Type;
readonly execCommandApproval: typeof CodexSchema.ExecCommandApprovalParams.Type;
}
export interface ServerRequestResponsesByMethod {
readonly "item/commandExecution/requestApproval": CodexSchema.CommandExecutionRequestApprovalResponse;
readonly "item/fileChange/requestApproval": CodexSchema.FileChangeRequestApprovalResponse;
readonly "item/tool/requestUserInput": CodexSchema.ToolRequestUserInputResponse;
readonly "mcpServer/elicitation/request": CodexSchema.McpServerElicitationRequestResponse;
readonly "item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalResponse;
readonly "item/tool/call": CodexSchema.DynamicToolCallResponse;
readonly "account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshResponse;
readonly "attestation/generate": CodexSchema.AttestationGenerateResponse;
readonly applyPatchApproval: CodexSchema.ApplyPatchApprovalResponse;
readonly execCommandApproval: CodexSchema.ExecCommandApprovalResponse;
readonly "item/commandExecution/requestApproval": typeof CodexSchema.CommandExecutionRequestApprovalResponse.Type;
readonly "item/fileChange/requestApproval": typeof CodexSchema.FileChangeRequestApprovalResponse.Type;
readonly "item/tool/requestUserInput": typeof CodexSchema.ToolRequestUserInputResponse.Type;
readonly "mcpServer/elicitation/request": typeof CodexSchema.McpServerElicitationRequestResponse.Type;
readonly "item/permissions/requestApproval": typeof CodexSchema.PermissionsRequestApprovalResponse.Type;
readonly "item/tool/call": typeof CodexSchema.DynamicToolCallResponse.Type;
readonly "account/chatgptAuthTokens/refresh": typeof CodexSchema.ChatgptAuthTokensRefreshResponse.Type;
readonly applyPatchApproval: typeof CodexSchema.ApplyPatchApprovalResponse.Type;
readonly execCommandApproval: typeof CodexSchema.ExecCommandApprovalResponse.Type;
}
export interface ServerNotificationParamsByMethod {
readonly error: CodexSchema.V2ErrorNotification;
readonly "thread/started": CodexSchema.V2ThreadStartedNotification;
readonly "thread/status/changed": CodexSchema.V2ThreadStatusChangedNotification;
readonly "thread/archived": CodexSchema.V2ThreadArchivedNotification;
readonly "thread/deleted": CodexSchema.V2ThreadDeletedNotification;
readonly "thread/unarchived": CodexSchema.V2ThreadUnarchivedNotification;
readonly "thread/closed": CodexSchema.V2ThreadClosedNotification;
readonly "skills/changed": CodexSchema.V2SkillsChangedNotification;
readonly "thread/name/updated": CodexSchema.V2ThreadNameUpdatedNotification;
readonly "thread/goal/updated": CodexSchema.V2ThreadGoalUpdatedNotification;
readonly "thread/goal/cleared": CodexSchema.V2ThreadGoalClearedNotification;
readonly "thread/environment/connected": CodexSchema.V2EnvironmentConnectionNotification;
readonly "thread/environment/disconnected": CodexSchema.V2EnvironmentConnectionNotification;
readonly "thread/settings/updated": CodexSchema.V2ThreadSettingsUpdatedNotification;
readonly "thread/tokenUsage/updated": CodexSchema.V2ThreadTokenUsageUpdatedNotification;
readonly "turn/started": CodexSchema.V2TurnStartedNotification;
readonly "hook/started": CodexSchema.V2HookStartedNotification;
readonly "turn/completed": CodexSchema.V2TurnCompletedNotification;
readonly "hook/completed": CodexSchema.V2HookCompletedNotification;
readonly "turn/diff/updated": CodexSchema.V2TurnDiffUpdatedNotification;
readonly "turn/plan/updated": CodexSchema.V2TurnPlanUpdatedNotification;
readonly "item/started": CodexSchema.V2ItemStartedNotification;
readonly "item/autoApprovalReview/started": CodexSchema.V2ItemGuardianApprovalReviewStartedNotification;
readonly "item/autoApprovalReview/completed": CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification;
readonly "item/completed": CodexSchema.V2ItemCompletedNotification;
readonly "rawResponseItem/completed": CodexSchema.V2RawResponseItemCompletedNotification;
readonly "rawResponse/completed": CodexSchema.V2RawResponseCompletedNotification;
readonly "item/agentMessage/delta": CodexSchema.V2AgentMessageDeltaNotification;
readonly "item/plan/delta": CodexSchema.V2PlanDeltaNotification;
readonly "command/exec/outputDelta": CodexSchema.V2CommandExecOutputDeltaNotification;
readonly "process/outputDelta": CodexSchema.V2ProcessOutputDeltaNotification;
readonly "process/exited": CodexSchema.V2ProcessExitedNotification;
readonly "item/commandExecution/outputDelta": CodexSchema.V2CommandExecutionOutputDeltaNotification;
readonly "item/commandExecution/terminalInteraction": CodexSchema.V2TerminalInteractionNotification;
readonly "item/fileChange/outputDelta": CodexSchema.V2FileChangeOutputDeltaNotification;
readonly "item/fileChange/patchUpdated": CodexSchema.V2FileChangePatchUpdatedNotification;
readonly "serverRequest/resolved": CodexSchema.V2ServerRequestResolvedNotification;
readonly "item/mcpToolCall/progress": CodexSchema.V2McpToolCallProgressNotification;
readonly "mcpServer/oauthLogin/completed": CodexSchema.V2McpServerOauthLoginCompletedNotification;
readonly "mcpServer/startupStatus/updated": CodexSchema.V2McpServerStatusUpdatedNotification;
readonly "account/updated": CodexSchema.V2AccountUpdatedNotification;
readonly "account/rateLimits/updated": CodexSchema.V2AccountRateLimitsUpdatedNotification;
readonly "app/list/updated": CodexSchema.V2AppListUpdatedNotification;
readonly "remoteControl/status/changed": CodexSchema.V2RemoteControlStatusChangedNotification;
readonly "externalAgentConfig/import/progress": CodexSchema.V2ExternalAgentConfigImportProgressNotification;
readonly "externalAgentConfig/import/completed": CodexSchema.V2ExternalAgentConfigImportCompletedNotification;
readonly "fs/changed": CodexSchema.V2FsChangedNotification;
readonly "item/reasoning/summaryTextDelta": CodexSchema.V2ReasoningSummaryTextDeltaNotification;
readonly "item/reasoning/summaryPartAdded": CodexSchema.V2ReasoningSummaryPartAddedNotification;
readonly "item/reasoning/textDelta": CodexSchema.V2ReasoningTextDeltaNotification;
readonly "thread/compacted": CodexSchema.V2ContextCompactedNotification;
readonly "model/rerouted": CodexSchema.V2ModelReroutedNotification;
readonly "model/verification": CodexSchema.V2ModelVerificationNotification;
readonly "turn/moderationMetadata": CodexSchema.V2TurnModerationMetadataNotification;
readonly "model/safetyBuffering/updated": CodexSchema.V2ModelSafetyBufferingUpdatedNotification;
readonly warning: CodexSchema.V2WarningNotification;
readonly guardianWarning: CodexSchema.V2GuardianWarningNotification;
readonly deprecationNotice: CodexSchema.V2DeprecationNoticeNotification;
readonly configWarning: CodexSchema.V2ConfigWarningNotification;
readonly "fuzzyFileSearch/sessionUpdated": CodexSchema.FuzzyFileSearchSessionUpdatedNotification;
readonly "fuzzyFileSearch/sessionCompleted": CodexSchema.FuzzyFileSearchSessionCompletedNotification;
readonly "thread/realtime/started": CodexSchema.V2ThreadRealtimeStartedNotification;
readonly "thread/realtime/itemAdded": CodexSchema.V2ThreadRealtimeItemAddedNotification;
readonly "thread/realtime/transcript/delta": CodexSchema.V2ThreadRealtimeTranscriptDeltaNotification;
readonly "thread/realtime/transcript/done": CodexSchema.V2ThreadRealtimeTranscriptDoneNotification;
readonly "thread/realtime/outputAudio/delta": CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification;
readonly "thread/realtime/sdp": CodexSchema.V2ThreadRealtimeSdpNotification;
readonly "thread/realtime/error": CodexSchema.V2ThreadRealtimeErrorNotification;
readonly "thread/realtime/closed": CodexSchema.V2ThreadRealtimeClosedNotification;
readonly "windows/worldWritableWarning": CodexSchema.V2WindowsWorldWritableWarningNotification;
readonly "windowsSandbox/setupCompleted": CodexSchema.V2WindowsSandboxSetupCompletedNotification;
readonly "account/login/completed": CodexSchema.V2AccountLoginCompletedNotification;
readonly error: typeof CodexSchema.V2ErrorNotification.Type;
readonly "thread/started": typeof CodexSchema.V2ThreadStartedNotification.Type;
readonly "thread/status/changed": typeof CodexSchema.V2ThreadStatusChangedNotification.Type;
readonly "thread/archived": typeof CodexSchema.V2ThreadArchivedNotification.Type;
readonly "thread/unarchived": typeof CodexSchema.V2ThreadUnarchivedNotification.Type;
readonly "thread/closed": typeof CodexSchema.V2ThreadClosedNotification.Type;
readonly "skills/changed": typeof CodexSchema.V2SkillsChangedNotification.Type;
readonly "thread/name/updated": typeof CodexSchema.V2ThreadNameUpdatedNotification.Type;
readonly "thread/tokenUsage/updated": typeof CodexSchema.V2ThreadTokenUsageUpdatedNotification.Type;
readonly "turn/started": typeof CodexSchema.V2TurnStartedNotification.Type;
readonly "hook/started": typeof CodexSchema.V2HookStartedNotification.Type;
readonly "turn/completed": typeof CodexSchema.V2TurnCompletedNotification.Type;
readonly "hook/completed": typeof CodexSchema.V2HookCompletedNotification.Type;
readonly "turn/diff/updated": typeof CodexSchema.V2TurnDiffUpdatedNotification.Type;
readonly "turn/plan/updated": typeof CodexSchema.V2TurnPlanUpdatedNotification.Type;
readonly "item/started": typeof CodexSchema.V2ItemStartedNotification.Type;
readonly "item/autoApprovalReview/started": typeof CodexSchema.V2ItemGuardianApprovalReviewStartedNotification.Type;
readonly "item/autoApprovalReview/completed": typeof CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification.Type;
readonly "item/completed": typeof CodexSchema.V2ItemCompletedNotification.Type;
readonly "rawResponseItem/completed": typeof CodexSchema.V2RawResponseItemCompletedNotification.Type;
readonly "item/agentMessage/delta": typeof CodexSchema.V2AgentMessageDeltaNotification.Type;
readonly "item/plan/delta": typeof CodexSchema.V2PlanDeltaNotification.Type;
readonly "command/exec/outputDelta": typeof CodexSchema.V2CommandExecOutputDeltaNotification.Type;
readonly "item/commandExecution/outputDelta": typeof CodexSchema.V2CommandExecutionOutputDeltaNotification.Type;
readonly "item/commandExecution/terminalInteraction": typeof CodexSchema.V2TerminalInteractionNotification.Type;
readonly "item/fileChange/outputDelta": typeof CodexSchema.V2FileChangeOutputDeltaNotification.Type;
readonly "serverRequest/resolved": typeof CodexSchema.V2ServerRequestResolvedNotification.Type;
readonly "item/mcpToolCall/progress": typeof CodexSchema.V2McpToolCallProgressNotification.Type;
readonly "mcpServer/oauthLogin/completed": typeof CodexSchema.V2McpServerOauthLoginCompletedNotification.Type;
readonly "mcpServer/startupStatus/updated": typeof CodexSchema.V2McpServerStatusUpdatedNotification.Type;
readonly "account/updated": typeof CodexSchema.V2AccountUpdatedNotification.Type;
readonly "account/rateLimits/updated": typeof CodexSchema.V2AccountRateLimitsUpdatedNotification.Type;
readonly "app/list/updated": typeof CodexSchema.V2AppListUpdatedNotification.Type;
readonly "fs/changed": typeof CodexSchema.V2FsChangedNotification.Type;
readonly "item/reasoning/summaryTextDelta": typeof CodexSchema.V2ReasoningSummaryTextDeltaNotification.Type;
readonly "item/reasoning/summaryPartAdded": typeof CodexSchema.V2ReasoningSummaryPartAddedNotification.Type;
readonly "item/reasoning/textDelta": typeof CodexSchema.V2ReasoningTextDeltaNotification.Type;
readonly "thread/compacted": typeof CodexSchema.V2ContextCompactedNotification.Type;
readonly "model/rerouted": typeof CodexSchema.V2ModelReroutedNotification.Type;
readonly deprecationNotice: typeof CodexSchema.V2DeprecationNoticeNotification.Type;
readonly configWarning: typeof CodexSchema.V2ConfigWarningNotification.Type;
readonly "fuzzyFileSearch/sessionUpdated": typeof CodexSchema.FuzzyFileSearchSessionUpdatedNotification.Type;
readonly "fuzzyFileSearch/sessionCompleted": typeof CodexSchema.FuzzyFileSearchSessionCompletedNotification.Type;
readonly "thread/realtime/started": typeof CodexSchema.V2ThreadRealtimeStartedNotification.Type;
readonly "thread/realtime/itemAdded": typeof CodexSchema.V2ThreadRealtimeItemAddedNotification.Type;
readonly "thread/realtime/transcriptUpdated": typeof CodexSchema.V2ThreadRealtimeTranscriptUpdatedNotification.Type;
readonly "thread/realtime/outputAudio/delta": typeof CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification.Type;
readonly "thread/realtime/sdp": typeof CodexSchema.V2ThreadRealtimeSdpNotification.Type;
readonly "thread/realtime/error": typeof CodexSchema.V2ThreadRealtimeErrorNotification.Type;
readonly "thread/realtime/closed": typeof CodexSchema.V2ThreadRealtimeClosedNotification.Type;
readonly "windows/worldWritableWarning": typeof CodexSchema.V2WindowsWorldWritableWarningNotification.Type;
readonly "windowsSandbox/setupCompleted": typeof CodexSchema.V2WindowsSandboxSetupCompletedNotification.Type;
readonly "account/login/completed": typeof CodexSchema.V2AccountLoginCompletedNotification.Type;
}
export const CLIENT_REQUEST_PARAMS = {
@@ -496,40 +371,20 @@ export const CLIENT_REQUEST_PARAMS = {
"thread/resume": CodexSchema.V2ThreadResumeParams,
"thread/fork": CodexSchema.V2ThreadForkParams,
"thread/archive": CodexSchema.V2ThreadArchiveParams,
"thread/delete": CodexSchema.V2ThreadDeleteParams,
"thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeParams,
"thread/name/set": CodexSchema.V2ThreadSetNameParams,
"thread/goal/set": CodexSchema.V2ThreadGoalSetParams,
"thread/goal/get": CodexSchema.V2ThreadGoalGetParams,
"thread/goal/clear": CodexSchema.V2ThreadGoalClearParams,
"thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateParams,
"thread/unarchive": CodexSchema.V2ThreadUnarchiveParams,
"thread/compact/start": CodexSchema.V2ThreadCompactStartParams,
"thread/shellCommand": CodexSchema.V2ThreadShellCommandParams,
"thread/approveGuardianDeniedAction": CodexSchema.V2ThreadApproveGuardianDeniedActionParams,
"thread/rollback": CodexSchema.V2ThreadRollbackParams,
"thread/list": CodexSchema.V2ThreadListParams,
"thread/loaded/list": CodexSchema.V2ThreadLoadedListParams,
"thread/read": CodexSchema.V2ThreadReadParams,
"thread/inject_items": CodexSchema.V2ThreadInjectItemsParams,
"skills/list": CodexSchema.V2SkillsListParams,
"skills/extraRoots/set": CodexSchema.V2SkillsExtraRootsSetParams,
"hooks/list": CodexSchema.V2HooksListParams,
"marketplace/add": CodexSchema.V2MarketplaceAddParams,
"marketplace/remove": CodexSchema.V2MarketplaceRemoveParams,
"marketplace/upgrade": CodexSchema.V2MarketplaceUpgradeParams,
"plugin/list": CodexSchema.V2PluginListParams,
"plugin/installed": CodexSchema.V2PluginInstalledParams,
"plugin/read": CodexSchema.V2PluginReadParams,
"plugin/skill/read": CodexSchema.V2PluginSkillReadParams,
"plugin/share/save": CodexSchema.V2PluginShareSaveParams,
"plugin/share/updateTargets": CodexSchema.V2PluginShareUpdateTargetsParams,
"plugin/share/list": CodexSchema.V2PluginShareListParams,
"plugin/share/checkout": CodexSchema.V2PluginShareCheckoutParams,
"plugin/share/delete": CodexSchema.V2PluginShareDeleteParams,
"app/read": CodexSchema.V2AppsReadParams,
"app/list": CodexSchema.V2AppsListParams,
"app/installed": CodexSchema.V2AppsInstalledParams,
"fs/readFile": CodexSchema.V2FsReadFileParams,
"fs/writeFile": CodexSchema.V2FsWriteFileParams,
"fs/createDirectory": CodexSchema.V2FsCreateDirectoryParams,
@@ -547,9 +402,7 @@ export const CLIENT_REQUEST_PARAMS = {
"turn/interrupt": CodexSchema.V2TurnInterruptParams,
"review/start": CodexSchema.V2ReviewStartParams,
"model/list": CodexSchema.V2ModelListParams,
"modelProvider/capabilities/read": CodexSchema.V2ModelProviderCapabilitiesReadParams,
"experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListParams,
"permissionProfile/list": CodexSchema.V2PermissionProfileListParams,
"experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetParams,
"mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginParams,
"config/mcpServer/reload": undefined,
@@ -557,15 +410,10 @@ export const CLIENT_REQUEST_PARAMS = {
"mcpServer/resource/read": CodexSchema.V2McpResourceReadParams,
"mcpServer/tool/call": CodexSchema.V2McpServerToolCallParams,
"windowsSandbox/setupStart": CodexSchema.V2WindowsSandboxSetupStartParams,
"windowsSandbox/readiness": undefined,
"account/login/start": CodexSchema.V2LoginAccountParams,
"account/login/cancel": CodexSchema.V2CancelLoginAccountParams,
"account/logout": undefined,
"account/rateLimits/read": undefined,
"account/rateLimitResetCredit/consume": CodexSchema.V2ConsumeAccountRateLimitResetCreditParams,
"account/usage/read": undefined,
"account/workspaceMessages/read": undefined,
"account/sendAddCreditsNudgeEmail": CodexSchema.V2SendAddCreditsNudgeEmailParams,
"feedback/upload": CodexSchema.V2FeedbackUploadParams,
"command/exec": CodexSchema.V2CommandExecParams,
"command/exec/write": CodexSchema.V2CommandExecWriteParams,
@@ -574,7 +422,6 @@ export const CLIENT_REQUEST_PARAMS = {
"config/read": CodexSchema.V2ConfigReadParams,
"externalAgentConfig/detect": CodexSchema.V2ExternalAgentConfigDetectParams,
"externalAgentConfig/import": CodexSchema.V2ExternalAgentConfigImportParams,
"externalAgentConfig/import/readHistories": undefined,
"config/value/write": CodexSchema.V2ConfigValueWriteParams,
"config/batchWrite": CodexSchema.V2ConfigBatchWriteParams,
"configRequirements/read": undefined,
@@ -591,40 +438,20 @@ export const CLIENT_REQUEST_RESPONSES = {
"thread/resume": CodexSchema.V2ThreadResumeResponse,
"thread/fork": CodexSchema.V2ThreadForkResponse,
"thread/archive": CodexSchema.V2ThreadArchiveResponse,
"thread/delete": CodexSchema.V2ThreadDeleteResponse,
"thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeResponse,
"thread/name/set": CodexSchema.V2ThreadSetNameResponse,
"thread/goal/set": CodexSchema.V2ThreadGoalSetResponse,
"thread/goal/get": CodexSchema.V2ThreadGoalGetResponse,
"thread/goal/clear": CodexSchema.V2ThreadGoalClearResponse,
"thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateResponse,
"thread/unarchive": CodexSchema.V2ThreadUnarchiveResponse,
"thread/compact/start": CodexSchema.V2ThreadCompactStartResponse,
"thread/shellCommand": CodexSchema.V2ThreadShellCommandResponse,
"thread/approveGuardianDeniedAction": CodexSchema.V2ThreadApproveGuardianDeniedActionResponse,
"thread/rollback": CodexSchema.V2ThreadRollbackResponse,
"thread/list": CodexSchema.V2ThreadListResponse,
"thread/loaded/list": CodexSchema.V2ThreadLoadedListResponse,
"thread/read": CodexSchema.V2ThreadReadResponse,
"thread/inject_items": CodexSchema.V2ThreadInjectItemsResponse,
"skills/list": CodexSchema.V2SkillsListResponse,
"skills/extraRoots/set": CodexSchema.V2SkillsExtraRootsSetResponse,
"hooks/list": CodexSchema.V2HooksListResponse,
"marketplace/add": CodexSchema.V2MarketplaceAddResponse,
"marketplace/remove": CodexSchema.V2MarketplaceRemoveResponse,
"marketplace/upgrade": CodexSchema.V2MarketplaceUpgradeResponse,
"plugin/list": CodexSchema.V2PluginListResponse,
"plugin/installed": CodexSchema.V2PluginInstalledResponse,
"plugin/read": CodexSchema.V2PluginReadResponse,
"plugin/skill/read": CodexSchema.V2PluginSkillReadResponse,
"plugin/share/save": CodexSchema.V2PluginShareSaveResponse,
"plugin/share/updateTargets": CodexSchema.V2PluginShareUpdateTargetsResponse,
"plugin/share/list": CodexSchema.V2PluginShareListResponse,
"plugin/share/checkout": CodexSchema.V2PluginShareCheckoutResponse,
"plugin/share/delete": CodexSchema.V2PluginShareDeleteResponse,
"app/read": CodexSchema.V2AppsReadResponse,
"app/list": CodexSchema.V2AppsListResponse,
"app/installed": CodexSchema.V2AppsInstalledResponse,
"fs/readFile": CodexSchema.V2FsReadFileResponse,
"fs/writeFile": CodexSchema.V2FsWriteFileResponse,
"fs/createDirectory": CodexSchema.V2FsCreateDirectoryResponse,
@@ -642,9 +469,7 @@ export const CLIENT_REQUEST_RESPONSES = {
"turn/interrupt": CodexSchema.V2TurnInterruptResponse,
"review/start": CodexSchema.V2ReviewStartResponse,
"model/list": CodexSchema.V2ModelListResponse,
"modelProvider/capabilities/read": CodexSchema.V2ModelProviderCapabilitiesReadResponse,
"experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListResponse,
"permissionProfile/list": CodexSchema.V2PermissionProfileListResponse,
"experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetResponse,
"mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginResponse,
"config/mcpServer/reload": CodexSchema.V2McpServerRefreshResponse,
@@ -652,15 +477,10 @@ export const CLIENT_REQUEST_RESPONSES = {
"mcpServer/resource/read": CodexSchema.V2McpResourceReadResponse,
"mcpServer/tool/call": CodexSchema.V2McpServerToolCallResponse,
"windowsSandbox/setupStart": CodexSchema.V2WindowsSandboxSetupStartResponse,
"windowsSandbox/readiness": CodexSchema.V2WindowsSandboxReadinessResponse,
"account/login/start": CodexSchema.V2LoginAccountResponse,
"account/login/cancel": CodexSchema.V2CancelLoginAccountResponse,
"account/logout": CodexSchema.V2LogoutAccountResponse,
"account/rateLimits/read": CodexSchema.V2GetAccountRateLimitsResponse,
"account/rateLimitResetCredit/consume": CodexSchema.V2ConsumeAccountRateLimitResetCreditResponse,
"account/usage/read": CodexSchema.V2GetAccountTokenUsageResponse,
"account/workspaceMessages/read": CodexSchema.V2GetWorkspaceMessagesResponse,
"account/sendAddCreditsNudgeEmail": CodexSchema.V2SendAddCreditsNudgeEmailResponse,
"feedback/upload": CodexSchema.V2FeedbackUploadResponse,
"command/exec": CodexSchema.V2CommandExecResponse,
"command/exec/write": CodexSchema.V2CommandExecWriteResponse,
@@ -669,8 +489,6 @@ export const CLIENT_REQUEST_RESPONSES = {
"config/read": CodexSchema.V2ConfigReadResponse,
"externalAgentConfig/detect": CodexSchema.V2ExternalAgentConfigDetectResponse,
"externalAgentConfig/import": CodexSchema.V2ExternalAgentConfigImportResponse,
"externalAgentConfig/import/readHistories":
CodexSchema.V2ExternalAgentConfigImportHistoriesReadResponse,
"config/value/write": CodexSchema.V2ConfigWriteResponse,
"config/batchWrite": CodexSchema.V2ConfigWriteResponse,
"configRequirements/read": CodexSchema.V2ConfigRequirementsReadResponse,
@@ -693,7 +511,6 @@ export const SERVER_REQUEST_PARAMS = {
"item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalParams,
"item/tool/call": CodexSchema.DynamicToolCallParams,
"account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshParams,
"attestation/generate": CodexSchema.AttestationGenerateParams,
applyPatchApproval: CodexSchema.ApplyPatchApprovalParams,
execCommandApproval: CodexSchema.ExecCommandApprovalParams,
} as const;
@@ -706,7 +523,6 @@ export const SERVER_REQUEST_RESPONSES = {
"item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalResponse,
"item/tool/call": CodexSchema.DynamicToolCallResponse,
"account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshResponse,
"attestation/generate": CodexSchema.AttestationGenerateResponse,
applyPatchApproval: CodexSchema.ApplyPatchApprovalResponse,
execCommandApproval: CodexSchema.ExecCommandApprovalResponse,
} as const;
@@ -716,16 +532,10 @@ export const SERVER_NOTIFICATION_PARAMS = {
"thread/started": CodexSchema.V2ThreadStartedNotification,
"thread/status/changed": CodexSchema.V2ThreadStatusChangedNotification,
"thread/archived": CodexSchema.V2ThreadArchivedNotification,
"thread/deleted": CodexSchema.V2ThreadDeletedNotification,
"thread/unarchived": CodexSchema.V2ThreadUnarchivedNotification,
"thread/closed": CodexSchema.V2ThreadClosedNotification,
"skills/changed": CodexSchema.V2SkillsChangedNotification,
"thread/name/updated": CodexSchema.V2ThreadNameUpdatedNotification,
"thread/goal/updated": CodexSchema.V2ThreadGoalUpdatedNotification,
"thread/goal/cleared": CodexSchema.V2ThreadGoalClearedNotification,
"thread/environment/connected": CodexSchema.V2EnvironmentConnectionNotification,
"thread/environment/disconnected": CodexSchema.V2EnvironmentConnectionNotification,
"thread/settings/updated": CodexSchema.V2ThreadSettingsUpdatedNotification,
"thread/tokenUsage/updated": CodexSchema.V2ThreadTokenUsageUpdatedNotification,
"turn/started": CodexSchema.V2TurnStartedNotification,
"hook/started": CodexSchema.V2HookStartedNotification,
@@ -739,16 +549,12 @@ export const SERVER_NOTIFICATION_PARAMS = {
CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification,
"item/completed": CodexSchema.V2ItemCompletedNotification,
"rawResponseItem/completed": CodexSchema.V2RawResponseItemCompletedNotification,
"rawResponse/completed": CodexSchema.V2RawResponseCompletedNotification,
"item/agentMessage/delta": CodexSchema.V2AgentMessageDeltaNotification,
"item/plan/delta": CodexSchema.V2PlanDeltaNotification,
"command/exec/outputDelta": CodexSchema.V2CommandExecOutputDeltaNotification,
"process/outputDelta": CodexSchema.V2ProcessOutputDeltaNotification,
"process/exited": CodexSchema.V2ProcessExitedNotification,
"item/commandExecution/outputDelta": CodexSchema.V2CommandExecutionOutputDeltaNotification,
"item/commandExecution/terminalInteraction": CodexSchema.V2TerminalInteractionNotification,
"item/fileChange/outputDelta": CodexSchema.V2FileChangeOutputDeltaNotification,
"item/fileChange/patchUpdated": CodexSchema.V2FileChangePatchUpdatedNotification,
"serverRequest/resolved": CodexSchema.V2ServerRequestResolvedNotification,
"item/mcpToolCall/progress": CodexSchema.V2McpToolCallProgressNotification,
"mcpServer/oauthLogin/completed": CodexSchema.V2McpServerOauthLoginCompletedNotification,
@@ -756,30 +562,19 @@ export const SERVER_NOTIFICATION_PARAMS = {
"account/updated": CodexSchema.V2AccountUpdatedNotification,
"account/rateLimits/updated": CodexSchema.V2AccountRateLimitsUpdatedNotification,
"app/list/updated": CodexSchema.V2AppListUpdatedNotification,
"remoteControl/status/changed": CodexSchema.V2RemoteControlStatusChangedNotification,
"externalAgentConfig/import/progress":
CodexSchema.V2ExternalAgentConfigImportProgressNotification,
"externalAgentConfig/import/completed":
CodexSchema.V2ExternalAgentConfigImportCompletedNotification,
"fs/changed": CodexSchema.V2FsChangedNotification,
"item/reasoning/summaryTextDelta": CodexSchema.V2ReasoningSummaryTextDeltaNotification,
"item/reasoning/summaryPartAdded": CodexSchema.V2ReasoningSummaryPartAddedNotification,
"item/reasoning/textDelta": CodexSchema.V2ReasoningTextDeltaNotification,
"thread/compacted": CodexSchema.V2ContextCompactedNotification,
"model/rerouted": CodexSchema.V2ModelReroutedNotification,
"model/verification": CodexSchema.V2ModelVerificationNotification,
"turn/moderationMetadata": CodexSchema.V2TurnModerationMetadataNotification,
"model/safetyBuffering/updated": CodexSchema.V2ModelSafetyBufferingUpdatedNotification,
warning: CodexSchema.V2WarningNotification,
guardianWarning: CodexSchema.V2GuardianWarningNotification,
deprecationNotice: CodexSchema.V2DeprecationNoticeNotification,
configWarning: CodexSchema.V2ConfigWarningNotification,
"fuzzyFileSearch/sessionUpdated": CodexSchema.FuzzyFileSearchSessionUpdatedNotification,
"fuzzyFileSearch/sessionCompleted": CodexSchema.FuzzyFileSearchSessionCompletedNotification,
"thread/realtime/started": CodexSchema.V2ThreadRealtimeStartedNotification,
"thread/realtime/itemAdded": CodexSchema.V2ThreadRealtimeItemAddedNotification,
"thread/realtime/transcript/delta": CodexSchema.V2ThreadRealtimeTranscriptDeltaNotification,
"thread/realtime/transcript/done": CodexSchema.V2ThreadRealtimeTranscriptDoneNotification,
"thread/realtime/transcriptUpdated": CodexSchema.V2ThreadRealtimeTranscriptUpdatedNotification,
"thread/realtime/outputAudio/delta": CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification,
"thread/realtime/sdp": CodexSchema.V2ThreadRealtimeSdpNotification,
"thread/realtime/error": CodexSchema.V2ThreadRealtimeErrorNotification,
@@ -1,5 +1,5 @@
// This file is generated by the effect-codex-app-server package. Do not edit manually.
// Upstream protocol ref: 678157acaa819d5510adfe359abb5d0392cfe461
// Upstream protocol ref: dbfe855f4fd0f5dcdf079882652a8efe622b0595
import * as CodexSchema from "./schema.gen.ts";
@@ -14,12 +14,8 @@ export const v2 = {
AccountUpdatedNotification: CodexSchema.V2AccountUpdatedNotification,
AgentMessageDeltaNotification: CodexSchema.V2AgentMessageDeltaNotification,
AppListUpdatedNotification: CodexSchema.V2AppListUpdatedNotification,
AppsInstalledParams: CodexSchema.V2AppsInstalledParams,
AppsInstalledResponse: CodexSchema.V2AppsInstalledResponse,
AppsListParams: CodexSchema.V2AppsListParams,
AppsListResponse: CodexSchema.V2AppsListResponse,
AppsReadParams: CodexSchema.V2AppsReadParams,
AppsReadResponse: CodexSchema.V2AppsReadResponse,
CancelLoginAccountParams: CodexSchema.V2CancelLoginAccountParams,
CancelLoginAccountResponse: CodexSchema.V2CancelLoginAccountResponse,
CommandExecOutputDeltaNotification: CodexSchema.V2CommandExecOutputDeltaNotification,
@@ -39,12 +35,8 @@ export const v2 = {
ConfigValueWriteParams: CodexSchema.V2ConfigValueWriteParams,
ConfigWarningNotification: CodexSchema.V2ConfigWarningNotification,
ConfigWriteResponse: CodexSchema.V2ConfigWriteResponse,
ConsumeAccountRateLimitResetCreditParams: CodexSchema.V2ConsumeAccountRateLimitResetCreditParams,
ConsumeAccountRateLimitResetCreditResponse:
CodexSchema.V2ConsumeAccountRateLimitResetCreditResponse,
ContextCompactedNotification: CodexSchema.V2ContextCompactedNotification,
DeprecationNoticeNotification: CodexSchema.V2DeprecationNoticeNotification,
EnvironmentConnectionNotification: CodexSchema.V2EnvironmentConnectionNotification,
ErrorNotification: CodexSchema.V2ErrorNotification,
ExperimentalFeatureEnablementSetParams: CodexSchema.V2ExperimentalFeatureEnablementSetParams,
ExperimentalFeatureEnablementSetResponse: CodexSchema.V2ExperimentalFeatureEnablementSetResponse,
@@ -52,18 +44,11 @@ export const v2 = {
ExperimentalFeatureListResponse: CodexSchema.V2ExperimentalFeatureListResponse,
ExternalAgentConfigDetectParams: CodexSchema.V2ExternalAgentConfigDetectParams,
ExternalAgentConfigDetectResponse: CodexSchema.V2ExternalAgentConfigDetectResponse,
ExternalAgentConfigImportCompletedNotification:
CodexSchema.V2ExternalAgentConfigImportCompletedNotification,
ExternalAgentConfigImportHistoriesReadResponse:
CodexSchema.V2ExternalAgentConfigImportHistoriesReadResponse,
ExternalAgentConfigImportParams: CodexSchema.V2ExternalAgentConfigImportParams,
ExternalAgentConfigImportProgressNotification:
CodexSchema.V2ExternalAgentConfigImportProgressNotification,
ExternalAgentConfigImportResponse: CodexSchema.V2ExternalAgentConfigImportResponse,
FeedbackUploadParams: CodexSchema.V2FeedbackUploadParams,
FeedbackUploadResponse: CodexSchema.V2FeedbackUploadResponse,
FileChangeOutputDeltaNotification: CodexSchema.V2FileChangeOutputDeltaNotification,
FileChangePatchUpdatedNotification: CodexSchema.V2FileChangePatchUpdatedNotification,
FsChangedNotification: CodexSchema.V2FsChangedNotification,
FsCopyParams: CodexSchema.V2FsCopyParams,
FsCopyResponse: CodexSchema.V2FsCopyResponse,
@@ -86,12 +71,7 @@ export const v2 = {
GetAccountParams: CodexSchema.V2GetAccountParams,
GetAccountRateLimitsResponse: CodexSchema.V2GetAccountRateLimitsResponse,
GetAccountResponse: CodexSchema.V2GetAccountResponse,
GetAccountTokenUsageResponse: CodexSchema.V2GetAccountTokenUsageResponse,
GetWorkspaceMessagesResponse: CodexSchema.V2GetWorkspaceMessagesResponse,
GuardianWarningNotification: CodexSchema.V2GuardianWarningNotification,
HookCompletedNotification: CodexSchema.V2HookCompletedNotification,
HooksListParams: CodexSchema.V2HooksListParams,
HooksListResponse: CodexSchema.V2HooksListResponse,
HookStartedNotification: CodexSchema.V2HookStartedNotification,
ItemCompletedNotification: CodexSchema.V2ItemCompletedNotification,
ItemGuardianApprovalReviewCompletedNotification:
@@ -104,12 +84,6 @@ export const v2 = {
LoginAccountParams: CodexSchema.V2LoginAccountParams,
LoginAccountResponse: CodexSchema.V2LoginAccountResponse,
LogoutAccountResponse: CodexSchema.V2LogoutAccountResponse,
MarketplaceAddParams: CodexSchema.V2MarketplaceAddParams,
MarketplaceAddResponse: CodexSchema.V2MarketplaceAddResponse,
MarketplaceRemoveParams: CodexSchema.V2MarketplaceRemoveParams,
MarketplaceRemoveResponse: CodexSchema.V2MarketplaceRemoveResponse,
MarketplaceUpgradeParams: CodexSchema.V2MarketplaceUpgradeParams,
MarketplaceUpgradeResponse: CodexSchema.V2MarketplaceUpgradeResponse,
McpResourceReadParams: CodexSchema.V2McpResourceReadParams,
McpResourceReadResponse: CodexSchema.V2McpResourceReadResponse,
McpServerOauthLoginCompletedNotification: CodexSchema.V2McpServerOauthLoginCompletedNotification,
@@ -122,81 +96,37 @@ export const v2 = {
McpToolCallProgressNotification: CodexSchema.V2McpToolCallProgressNotification,
ModelListParams: CodexSchema.V2ModelListParams,
ModelListResponse: CodexSchema.V2ModelListResponse,
ModelProviderCapabilitiesReadParams: CodexSchema.V2ModelProviderCapabilitiesReadParams,
ModelProviderCapabilitiesReadResponse: CodexSchema.V2ModelProviderCapabilitiesReadResponse,
ModelReroutedNotification: CodexSchema.V2ModelReroutedNotification,
ModelSafetyBufferingUpdatedNotification: CodexSchema.V2ModelSafetyBufferingUpdatedNotification,
ModelVerificationNotification: CodexSchema.V2ModelVerificationNotification,
PermissionProfileListParams: CodexSchema.V2PermissionProfileListParams,
PermissionProfileListResponse: CodexSchema.V2PermissionProfileListResponse,
PlanDeltaNotification: CodexSchema.V2PlanDeltaNotification,
PluginInstalledParams: CodexSchema.V2PluginInstalledParams,
PluginInstalledResponse: CodexSchema.V2PluginInstalledResponse,
PluginInstallParams: CodexSchema.V2PluginInstallParams,
PluginInstallResponse: CodexSchema.V2PluginInstallResponse,
PluginListParams: CodexSchema.V2PluginListParams,
PluginListResponse: CodexSchema.V2PluginListResponse,
PluginReadParams: CodexSchema.V2PluginReadParams,
PluginReadResponse: CodexSchema.V2PluginReadResponse,
PluginShareCheckoutParams: CodexSchema.V2PluginShareCheckoutParams,
PluginShareCheckoutResponse: CodexSchema.V2PluginShareCheckoutResponse,
PluginShareDeleteParams: CodexSchema.V2PluginShareDeleteParams,
PluginShareDeleteResponse: CodexSchema.V2PluginShareDeleteResponse,
PluginShareListParams: CodexSchema.V2PluginShareListParams,
PluginShareListResponse: CodexSchema.V2PluginShareListResponse,
PluginShareSaveParams: CodexSchema.V2PluginShareSaveParams,
PluginShareSaveResponse: CodexSchema.V2PluginShareSaveResponse,
PluginShareUpdateTargetsParams: CodexSchema.V2PluginShareUpdateTargetsParams,
PluginShareUpdateTargetsResponse: CodexSchema.V2PluginShareUpdateTargetsResponse,
PluginSkillReadParams: CodexSchema.V2PluginSkillReadParams,
PluginSkillReadResponse: CodexSchema.V2PluginSkillReadResponse,
PluginUninstallParams: CodexSchema.V2PluginUninstallParams,
PluginUninstallResponse: CodexSchema.V2PluginUninstallResponse,
ProcessExitedNotification: CodexSchema.V2ProcessExitedNotification,
ProcessOutputDeltaNotification: CodexSchema.V2ProcessOutputDeltaNotification,
RawResponseCompletedNotification: CodexSchema.V2RawResponseCompletedNotification,
RawResponseItemCompletedNotification: CodexSchema.V2RawResponseItemCompletedNotification,
ReasoningSummaryPartAddedNotification: CodexSchema.V2ReasoningSummaryPartAddedNotification,
ReasoningSummaryTextDeltaNotification: CodexSchema.V2ReasoningSummaryTextDeltaNotification,
ReasoningTextDeltaNotification: CodexSchema.V2ReasoningTextDeltaNotification,
RemoteControlStatusChangedNotification: CodexSchema.V2RemoteControlStatusChangedNotification,
ReviewStartParams: CodexSchema.V2ReviewStartParams,
ReviewStartResponse: CodexSchema.V2ReviewStartResponse,
SendAddCreditsNudgeEmailParams: CodexSchema.V2SendAddCreditsNudgeEmailParams,
SendAddCreditsNudgeEmailResponse: CodexSchema.V2SendAddCreditsNudgeEmailResponse,
ServerRequestResolvedNotification: CodexSchema.V2ServerRequestResolvedNotification,
SkillsChangedNotification: CodexSchema.V2SkillsChangedNotification,
SkillsConfigWriteParams: CodexSchema.V2SkillsConfigWriteParams,
SkillsConfigWriteResponse: CodexSchema.V2SkillsConfigWriteResponse,
SkillsExtraRootsSetParams: CodexSchema.V2SkillsExtraRootsSetParams,
SkillsExtraRootsSetResponse: CodexSchema.V2SkillsExtraRootsSetResponse,
SkillsListParams: CodexSchema.V2SkillsListParams,
SkillsListResponse: CodexSchema.V2SkillsListResponse,
TerminalInteractionNotification: CodexSchema.V2TerminalInteractionNotification,
ThreadApproveGuardianDeniedActionParams: CodexSchema.V2ThreadApproveGuardianDeniedActionParams,
ThreadApproveGuardianDeniedActionResponse:
CodexSchema.V2ThreadApproveGuardianDeniedActionResponse,
ThreadArchivedNotification: CodexSchema.V2ThreadArchivedNotification,
ThreadArchiveParams: CodexSchema.V2ThreadArchiveParams,
ThreadArchiveResponse: CodexSchema.V2ThreadArchiveResponse,
ThreadClosedNotification: CodexSchema.V2ThreadClosedNotification,
ThreadCompactStartParams: CodexSchema.V2ThreadCompactStartParams,
ThreadCompactStartResponse: CodexSchema.V2ThreadCompactStartResponse,
ThreadDeletedNotification: CodexSchema.V2ThreadDeletedNotification,
ThreadDeleteParams: CodexSchema.V2ThreadDeleteParams,
ThreadDeleteResponse: CodexSchema.V2ThreadDeleteResponse,
ThreadForkParams: CodexSchema.V2ThreadForkParams,
ThreadForkResponse: CodexSchema.V2ThreadForkResponse,
ThreadGoalClearedNotification: CodexSchema.V2ThreadGoalClearedNotification,
ThreadGoalClearParams: CodexSchema.V2ThreadGoalClearParams,
ThreadGoalClearResponse: CodexSchema.V2ThreadGoalClearResponse,
ThreadGoalGetParams: CodexSchema.V2ThreadGoalGetParams,
ThreadGoalGetResponse: CodexSchema.V2ThreadGoalGetResponse,
ThreadGoalSetParams: CodexSchema.V2ThreadGoalSetParams,
ThreadGoalSetResponse: CodexSchema.V2ThreadGoalSetResponse,
ThreadGoalUpdatedNotification: CodexSchema.V2ThreadGoalUpdatedNotification,
ThreadInjectItemsParams: CodexSchema.V2ThreadInjectItemsParams,
ThreadInjectItemsResponse: CodexSchema.V2ThreadInjectItemsResponse,
ThreadListParams: CodexSchema.V2ThreadListParams,
ThreadListResponse: CodexSchema.V2ThreadListResponse,
ThreadLoadedListParams: CodexSchema.V2ThreadLoadedListParams,
@@ -213,16 +143,14 @@ export const v2 = {
CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification,
ThreadRealtimeSdpNotification: CodexSchema.V2ThreadRealtimeSdpNotification,
ThreadRealtimeStartedNotification: CodexSchema.V2ThreadRealtimeStartedNotification,
ThreadRealtimeTranscriptDeltaNotification:
CodexSchema.V2ThreadRealtimeTranscriptDeltaNotification,
ThreadRealtimeTranscriptDoneNotification: CodexSchema.V2ThreadRealtimeTranscriptDoneNotification,
ThreadRealtimeTranscriptUpdatedNotification:
CodexSchema.V2ThreadRealtimeTranscriptUpdatedNotification,
ThreadResumeParams: CodexSchema.V2ThreadResumeParams,
ThreadResumeResponse: CodexSchema.V2ThreadResumeResponse,
ThreadRollbackParams: CodexSchema.V2ThreadRollbackParams,
ThreadRollbackResponse: CodexSchema.V2ThreadRollbackResponse,
ThreadSetNameParams: CodexSchema.V2ThreadSetNameParams,
ThreadSetNameResponse: CodexSchema.V2ThreadSetNameResponse,
ThreadSettingsUpdatedNotification: CodexSchema.V2ThreadSettingsUpdatedNotification,
ThreadShellCommandParams: CodexSchema.V2ThreadShellCommandParams,
ThreadShellCommandResponse: CodexSchema.V2ThreadShellCommandResponse,
ThreadStartedNotification: CodexSchema.V2ThreadStartedNotification,
@@ -239,15 +167,12 @@ export const v2 = {
TurnDiffUpdatedNotification: CodexSchema.V2TurnDiffUpdatedNotification,
TurnInterruptParams: CodexSchema.V2TurnInterruptParams,
TurnInterruptResponse: CodexSchema.V2TurnInterruptResponse,
TurnModerationMetadataNotification: CodexSchema.V2TurnModerationMetadataNotification,
TurnPlanUpdatedNotification: CodexSchema.V2TurnPlanUpdatedNotification,
TurnStartedNotification: CodexSchema.V2TurnStartedNotification,
TurnStartParams: CodexSchema.V2TurnStartParams,
TurnStartResponse: CodexSchema.V2TurnStartResponse,
TurnSteerParams: CodexSchema.V2TurnSteerParams,
TurnSteerResponse: CodexSchema.V2TurnSteerResponse,
WarningNotification: CodexSchema.V2WarningNotification,
WindowsSandboxReadinessResponse: CodexSchema.V2WindowsSandboxReadinessResponse,
WindowsSandboxSetupCompletedNotification: CodexSchema.V2WindowsSandboxSetupCompletedNotification,
WindowsSandboxSetupStartParams: CodexSchema.V2WindowsSandboxSetupStartParams,
WindowsSandboxSetupStartResponse: CodexSchema.V2WindowsSandboxSetupStartResponse,
File diff suppressed because it is too large. Load diff
@@ -1,8 +1,11 @@
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as SchemaIssue from "effect/SchemaIssue";
import * as CodexError from "../errors.ts";
const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
export const JsonRpcId = Schema.Union([Schema.Number, Schema.String]);
export const JsonRpcError = Schema.Struct({
@@ -27,13 +30,16 @@ export const decodeOptionalPayload = <A, I>(
return Effect.sync(() => undefined as A);
}
return Effect.fail(
CodexError.CodexAppServerRequestError.unexpectedPayload(method, "decode-payload", raw),
CodexError.CodexAppServerRequestError.invalidParams(`${method} does not accept params`, raw),
);
}
return Schema.decodeUnknownEffect(schema)(raw).pipe(
Effect.mapError((error) =>
CodexError.CodexAppServerRequestError.invalidPayload(method, "decode-payload", error),
CodexError.CodexAppServerRequestError.invalidParams(
`Invalid ${method} payload: ${formatSchemaIssue(error.issue)}`,
{ issue: error.issue },
),
),
);
};
@@ -48,13 +54,19 @@ export const encodeOptionalPayload = <A, I>(
return Effect.sync(() => undefined);
}
return Effect.fail(
CodexError.CodexAppServerRequestError.unexpectedPayload(method, "encode-payload", payload),
CodexError.CodexAppServerRequestError.invalidParams(
`${method} does not accept params`,
payload,
),
);
}
return Schema.encodeEffect(schema)(payload).pipe(
Effect.mapError((error) =>
CodexError.CodexAppServerRequestError.invalidPayload(method, "encode-payload", error),
CodexError.CodexAppServerRequestError.invalidParams(
`Invalid ${method} payload: ${formatSchemaIssue(error.issue)}`,
{ issue: error.issue },
),
),
);
};
@@ -65,12 +77,12 @@ export const decodeNotificationPayload = <A, I>(
raw: unknown,
): Effect.Effect<A, CodexError.CodexAppServerProtocolParseError> =>
decodeOptionalPayload(method, schema, raw).pipe(
Effect.mapError((error) =>
CodexError.CodexAppServerProtocolParseError.fromRequestError(
"decode-notification-payload",
method,
error,
),
Effect.mapError(
(error) =>
new CodexError.CodexAppServerProtocolParseError({
detail: error.message,
cause: error,
}),
),
);
@@ -84,8 +96,6 @@ export const runHandler = Effect.fnUntraced(function* <A, B>(
}
return yield* handler(payload).pipe(
Effect.mapError((error) =>
CodexError.CodexAppServerRequestError.fromAppServerError(error, method),
),
Effect.mapError((error) => CodexError.normalizeToRequestError(error)),
);
});
@@ -9,6 +9,7 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import * as CodexError from "../errors.ts";
const encoder = new TextEncoder();
const decoder = new TextDecoder();
export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =>
Stdio.make({
@@ -24,7 +25,6 @@ export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =
export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {
const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();
const output = yield* Queue.unbounded<string>();
const decoder = new TextDecoder();
return {
stdio: Stdio.make({
@@ -32,10 +32,7 @@ export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {
stdin: Stream.fromQueue(input),
stdout: () =>
Sink.forEach((chunk: string | Uint8Array) =>
Queue.offer(
output,
typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true }),
),
Queue.offer(output, typeof chunk === "string" ? chunk : decoder.decode(chunk)),
),
stderr: () => Sink.drain,
}),
@@ -44,20 +41,14 @@ export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {
};
});
type ChildProcessTerminationHandle = Pick<
ChildProcessSpawner.ChildProcessHandle,
"exitCode" | "pid"
>;
export const makeTerminationError = (
handle: ChildProcessTerminationHandle,
handle: ChildProcessSpawner.ChildProcessHandle,
): Effect.Effect<CodexError.CodexAppServerError> =>
Effect.match(handle.exitCode, {
onFailure: (cause) =>
new CodexError.CodexAppServerTransportError({
operation: "read-process-exit-status",
pid: handle.pid,
detail: "Failed to determine Codex App Server process exit status",
cause,
}),
onSuccess: (code) => new CodexError.CodexAppServerProcessExitedError({ code, pid: handle.pid }),
onSuccess: (code) => new CodexError.CodexAppServerProcessExitedError({ code }),
});
@@ -14,17 +14,15 @@ import * as CodexClient from "./client.ts";
const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
path.join(import.meta.dirname, "../test/fixtures/codex-app-server-mock-peer.ts"),
);
const mockPeerArgs = (path: string) => [path];
it.layer(NodeServices.layer)("effect-codex-app-server client", (it) => {
const makeHandle = (env?: Record<string, string>) =>
const makeHandle = () =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const path = yield* Path.Path;
const peerCwd = path.join(import.meta.dirname, "..");
const command = ChildProcess.make(process.execPath, mockPeerArgs(yield* mockPeerPath), {
cwd: peerCwd,
...(env ? { env: { ...process.env, ...env } } : {}),
const command = ChildProcess.make("bun", ["run", yield* mockPeerPath], {
cwd: path.join(import.meta.dirname, ".."),
shell: process.platform === "win32",
});
return yield* spawner.spawn(command);
});
@@ -80,11 +78,11 @@ it.layer(NodeServices.layer)("effect-codex-app-server client", (it) => {
planType: "plus",
});
const path = yield* Path.Path;
const peerCwd = path.join(import.meta.dirname, "..");
const skills = yield* client.request("skills/list", { cwds: [peerCwd] });
const skills = yield* client.request("skills/list", {
cwds: [process.cwd()],
});
assert.equal(skills.data.length, 1);
assert.equal(skills.data[0]?.cwd, peerCwd);
assert.equal(skills.data[0]?.cwd, process.cwd());
return {
account,
@@ -123,35 +121,4 @@ it.layer(NodeServices.layer)("effect-codex-app-server client", (it) => {
]);
}),
);
it.effect("drains child stderr so large diagnostics cannot block protocol responses", () =>
Effect.gen(function* () {
const handle = yield* makeHandle({
CODEX_APP_SERVER_TEST_STDERR_BYTES: String(512 * 1024),
});
const scope = yield* Scope.make();
const clientLayer = CodexClient.layerChildProcess(handle);
const context = yield* Layer.buildWithScope(clientLayer, scope);
const initialized = yield* Effect.gen(function* () {
const client = yield* CodexClient.CodexAppServerClient;
return yield* client.request("initialize", {
clientInfo: {
name: "effect-codex-app-server-test",
title: "Effect Codex App Server Test",
version: "0.0.0",
},
capabilities: {
experimentalApi: true,
optOutNotificationMethods: null,
},
});
}).pipe(
Effect.timeout("5 seconds"),
Effect.provide(context),
Effect.ensuring(Scope.close(scope, Exit.void)),
);
assert.equal(initialized.userAgent, "mock-codex-app-server");
}),
);
});
+84 -55
View File
@@ -4,8 +4,7 @@ import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stdio from "effect/Stdio";
import * as Stream from "effect/Stream";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as CodexRpc from "./_generated/meta.gen.ts";
import * as CodexError from "./errors.ts";
@@ -35,47 +34,46 @@ interface CodexAppServerClientRaw {
readonly respondError: CodexProtocol.CodexAppServerPatchedProtocol["respondError"];
}
export interface CodexAppServerClientShape {
readonly raw: CodexAppServerClientRaw;
readonly request: <M extends CodexRpc.ClientRequestMethod>(
method: M,
payload: CodexRpc.ClientRequestParamsByMethod[M],
) => Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError>;
readonly notify: <M extends CodexRpc.ClientNotificationMethod>(
method: M,
payload: CodexRpc.ClientNotificationParamsByMethod[M],
) => Effect.Effect<void, CodexError.CodexAppServerError>;
readonly handleServerRequest: <M extends CodexRpc.ServerRequestMethod>(
method: M,
handler: (
payload: CodexRpc.ServerRequestParamsByMethod[M],
) => Effect.Effect<CodexRpc.ServerRequestResponsesByMethod[M], CodexError.CodexAppServerError>,
) => Effect.Effect<void>;
readonly handleServerNotification: <M extends CodexRpc.ServerNotificationMethod>(
method: M,
handler: (
payload: CodexRpc.ServerNotificationParamsByMethod[M],
) => Effect.Effect<void, CodexError.CodexAppServerError>,
) => Effect.Effect<void>;
readonly handleUnknownServerRequest: (
handler: (
method: string,
params: unknown,
) => Effect.Effect<unknown, CodexError.CodexAppServerError>,
) => Effect.Effect<void>;
readonly handleUnknownServerNotification: (
handler: (
method: string,
params: unknown,
) => Effect.Effect<void, CodexError.CodexAppServerError>,
) => Effect.Effect<void>;
}
export class CodexAppServerClient extends Context.Service<
CodexAppServerClient,
{
readonly raw: CodexAppServerClientRaw;
readonly request: <M extends CodexRpc.ClientRequestMethod>(
method: M,
payload: CodexRpc.ClientRequestParamsByMethod[M],
) => Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError>;
readonly notify: <M extends CodexRpc.ClientNotificationMethod>(
method: M,
payload: CodexRpc.ClientNotificationParamsByMethod[M],
) => Effect.Effect<void, CodexError.CodexAppServerError>;
readonly handleServerRequest: <M extends CodexRpc.ServerRequestMethod>(
method: M,
handler: (
payload: CodexRpc.ServerRequestParamsByMethod[M],
) => Effect.Effect<
CodexRpc.ServerRequestResponsesByMethod[M],
CodexError.CodexAppServerError
>,
) => Effect.Effect<void>;
readonly handleServerNotification: <M extends CodexRpc.ServerNotificationMethod>(
method: M,
handler: (
payload: CodexRpc.ServerNotificationParamsByMethod[M],
) => Effect.Effect<void, CodexError.CodexAppServerError>,
) => Effect.Effect<void>;
readonly handleUnknownServerRequest: (
handler: (
method: string,
params: unknown,
) => Effect.Effect<unknown, CodexError.CodexAppServerError>,
) => Effect.Effect<void>;
readonly handleUnknownServerNotification: (
handler: (
method: string,
params: unknown,
) => Effect.Effect<void, CodexError.CodexAppServerError>,
) => Effect.Effect<void>;
}
>()("effect-codex-app-server/client/CodexAppServerClient") {}
CodexAppServerClientShape
>()("effect-codex-app-server/CodexAppServerClient") {}
type ServerRequestHandler = (
payload: unknown,
@@ -88,7 +86,7 @@ export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make
stdio: Stdio.Stdio,
options: CodexAppServerClientOptions = {},
terminationError?: Effect.Effect<CodexError.CodexAppServerError>,
): Effect.fn.Return<CodexAppServerClient["Service"], never, Scope.Scope> {
): Effect.fn.Return<CodexAppServerClientShape, never, Scope.Scope> {
const requestHandlers = new Map<string, ServerRequestHandler>();
const notificationHandlers = new Map<string, Array<ServerNotificationHandler>>();
let unknownRequestHandler:
@@ -250,20 +248,51 @@ export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make
});
});
export const layer = (
stdio: Stdio.Stdio,
options: CodexAppServerClientOptions = {},
): Layer.Layer<CodexAppServerClient> => Layer.effect(CodexAppServerClient, make(stdio, options));
export const layerChildProcess = (
handle: ChildProcessSpawner.ChildProcessHandle,
options: CodexAppServerClientOptions = {},
): Layer.Layer<CodexAppServerClient> =>
Layer.effect(CodexAppServerClient, makeChildProcessClient(handle, options));
): Layer.Layer<CodexAppServerClient> => {
const stdio = makeChildStdio(handle);
const terminationError = makeTerminationError(handle);
return Layer.effect(CodexAppServerClient, make(stdio, options, terminationError));
};
const makeChildProcessClient = Effect.fn(
"effect-codex-app-server/CodexAppServerClient.makeChildProcessClient",
)(function* (handle: ChildProcessSpawner.ChildProcessHandle, options: CodexAppServerClientOptions) {
yield* Stream.runDrain(handle.stderr).pipe(Effect.ignore, Effect.forkScoped);
return yield* make(makeChildStdio(handle), options, makeTerminationError(handle));
});
export interface CodexAppServerCommandLayerOptions extends CodexAppServerClientOptions {
readonly command: string;
readonly args?: ReadonlyArray<string>;
readonly cwd?: string;
readonly env?: Record<string, string>;
}
export const layerCommand = (
options: CodexAppServerCommandLayerOptions,
): Layer.Layer<
CodexAppServerClient,
CodexError.CodexAppServerSpawnError,
ChildProcessSpawner.ChildProcessSpawner
> =>
Layer.effect(
CodexAppServerClient,
Effect.acquireRelease(
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const command = ChildProcess.make(options.command, [...(options.args ?? [])], {
...(options.cwd ? { cwd: options.cwd } : {}),
...(options.env ? { env: { ...process.env, ...options.env } } : {}),
shell: process.platform === "win32",
});
const handle = yield* spawner.spawn(command).pipe(
Effect.mapError(
(cause) =>
new CodexError.CodexAppServerSpawnError({
command: [options.command, ...(options.args ?? [])].join(" "),
cause,
}),
),
);
const client = yield* make(makeChildStdio(handle), options, makeTerminationError(handle));
return { client, handle };
}),
({ handle }) => handle.kill().pipe(Effect.orDie),
).pipe(Effect.map(({ client }) => client)),
);
+17 -293
View File
@@ -1,126 +1,4 @@
import * as Schema from "effect/Schema";
import type * as SchemaIssue from "effect/SchemaIssue";
export const CodexAppServerRequestOperation = Schema.Literals([
"decode-payload",
"encode-payload",
"handle-request",
"receive-response",
]);
export type CodexAppServerRequestOperation = typeof CodexAppServerRequestOperation.Type;
export const CodexAppServerSchemaIssueKind = Schema.Literals([
"Filter",
"Encoding",
"Pointer",
"Composite",
"AnyOf",
"InvalidType",
"InvalidValue",
"MissingKey",
"UnexpectedKey",
"Forbidden",
"OneOf",
]);
export type CodexAppServerSchemaIssueKind = typeof CodexAppServerSchemaIssueKind.Type;
export interface CodexAppServerSchemaIssueDiagnostics {
readonly issueCount: number;
readonly issueKinds: ReadonlyArray<CodexAppServerSchemaIssueKind>;
readonly maximumPathDepth: number;
}
const schemaIssueDiagnostics = (root: SchemaIssue.Issue): CodexAppServerSchemaIssueDiagnostics => {
let issueCount = 0;
let maximumPathDepth = 0;
const issueKinds = new Set<CodexAppServerSchemaIssueKind>();
const visit = (issue: SchemaIssue.Issue, pathDepth: number): void => {
issueCount += 1;
issueKinds.add(issue._tag);
maximumPathDepth = Math.max(maximumPathDepth, pathDepth);
switch (issue._tag) {
case "Filter":
case "Encoding":
visit(issue.issue, pathDepth);
break;
case "Pointer":
visit(issue.issue, pathDepth + issue.path.length);
break;
case "Composite":
case "AnyOf":
for (const child of issue.issues) visit(child, pathDepth);
break;
}
};
visit(root, 0);
return {
issueCount,
issueKinds: [...issueKinds],
maximumPathDepth,
};
};
export const CodexAppServerPayloadKind = Schema.Literals([
"null",
"array",
"string",
"number",
"boolean",
"bigint",
"object",
"symbol",
"function",
"undefined",
]);
export type CodexAppServerPayloadKind = typeof CodexAppServerPayloadKind.Type;
const payloadKind = (payload: unknown): CodexAppServerPayloadKind => {
if (payload === null) return "null";
if (Array.isArray(payload)) return "array";
return typeof payload;
};
const protocolMessageFields = ["id", "method", "params", "result", "error"] as const;
export const CodexAppServerProtocolMessageField = Schema.Literals(protocolMessageFields);
export type CodexAppServerProtocolMessageField = typeof CodexAppServerProtocolMessageField.Type;
export interface CodexAppServerRequestDiagnostics {
readonly method?: string;
readonly requestId?: string;
readonly operation?: CodexAppServerRequestOperation;
readonly cause?: unknown;
readonly issueCount?: number;
readonly issueKinds?: ReadonlyArray<CodexAppServerSchemaIssueKind>;
readonly maximumPathDepth?: number;
readonly payloadKind?: CodexAppServerPayloadKind;
}
export const CodexAppServerProtocolParseOperation = Schema.Literals([
"encode-wire-message",
"decode-wire-message",
"route-wire-message",
"decode-notification-payload",
"decode-request-payload",
"decode-response-payload",
]);
export type CodexAppServerProtocolParseOperation = typeof CodexAppServerProtocolParseOperation.Type;
export const CodexAppServerTransportOperation = Schema.Literals([
"read-input-stream",
"read-process-exit-status",
]);
export type CodexAppServerTransportOperation = typeof CodexAppServerTransportOperation.Type;
export const CodexAppServerIdentifierPurpose = Schema.Literals([
"provider-event",
"command-approval-request",
"file-change-approval-request",
"user-input-request",
]);
export type CodexAppServerIdentifierPurpose = typeof CodexAppServerIdentifierPurpose.Type;
export interface CodexAppServerProtocolErrorShape {
readonly code: number;
@@ -132,7 +10,7 @@ export class CodexAppServerSpawnError extends Schema.TaggedErrorClass<CodexAppSe
"CodexAppServerSpawnError",
{
command: Schema.optional(Schema.String),
cause: Schema.Defect(),
cause: Schema.Defect,
},
) {
override get message() {
@@ -146,8 +24,7 @@ export class CodexAppServerProcessExitedError extends Schema.TaggedErrorClass<Co
"CodexAppServerProcessExitedError",
{
code: Schema.optional(Schema.Number),
pid: Schema.optionalKey(Schema.Int),
cause: Schema.optional(Schema.Defect()),
cause: Schema.optional(Schema.Defect),
},
) {
override get message() {
@@ -160,107 +37,24 @@ export class CodexAppServerProcessExitedError extends Schema.TaggedErrorClass<Co
export class CodexAppServerProtocolParseError extends Schema.TaggedErrorClass<CodexAppServerProtocolParseError>()(
"CodexAppServerProtocolParseError",
{
operation: CodexAppServerProtocolParseOperation,
method: Schema.optionalKey(Schema.String),
requestId: Schema.optionalKey(Schema.String),
payloadKind: Schema.optionalKey(CodexAppServerPayloadKind),
presentFields: Schema.optionalKey(Schema.Array(CodexAppServerProtocolMessageField)),
issueCount: Schema.optionalKey(Schema.Number),
issueKinds: Schema.optionalKey(Schema.Array(CodexAppServerSchemaIssueKind)),
maximumPathDepth: Schema.optionalKey(Schema.Number),
cause: Schema.optional(Schema.Defect()),
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message() {
const method = this.method === undefined ? "" : ` for method '${this.method}'`;
return `Codex App Server protocol operation '${this.operation}' failed${method}.`;
}
static fromSchemaError(
operation: CodexAppServerProtocolParseOperation,
cause: Schema.SchemaError,
context: { readonly method?: string; readonly requestId?: string } = {},
) {
return new CodexAppServerProtocolParseError({
operation,
...context,
...schemaIssueDiagnostics(cause.issue),
cause,
});
}
static fromRequestError(
operation: CodexAppServerProtocolParseOperation,
method: string,
cause: CodexAppServerRequestError,
) {
return new CodexAppServerProtocolParseError({
operation,
method,
...(cause.issueCount === undefined ? {} : { issueCount: cause.issueCount }),
...(cause.issueKinds === undefined ? {} : { issueKinds: cause.issueKinds }),
...(cause.maximumPathDepth === undefined ? {} : { maximumPathDepth: cause.maximumPathDepth }),
cause,
});
}
static fromUnroutableMessage(message: unknown) {
const diagnostics = { payloadKind: payloadKind(message) };
if (typeof message !== "object" || message === null || Array.isArray(message)) {
return new CodexAppServerProtocolParseError({
operation: "route-wire-message",
...diagnostics,
});
}
const presentFields = protocolMessageFields.filter((field) => field in message);
const method =
"method" in message && typeof message.method === "string" ? message.method : undefined;
const requestId =
"id" in message && (typeof message.id === "string" || typeof message.id === "number")
? String(message.id)
: undefined;
return new CodexAppServerProtocolParseError({
operation: "route-wire-message",
...diagnostics,
presentFields,
...(method === undefined ? {} : { method }),
...(requestId === undefined ? {} : { requestId }),
});
return `Failed to parse Codex App Server protocol message: ${this.detail}`;
}
}
export class CodexAppServerTransportError extends Schema.TaggedErrorClass<CodexAppServerTransportError>()(
"CodexAppServerTransportError",
{
operation: CodexAppServerTransportOperation,
pid: Schema.optionalKey(Schema.Int),
cause: Schema.Defect(),
detail: Schema.String,
cause: Schema.Defect,
},
) {
override get message() {
return `Codex App Server transport operation '${this.operation}' failed.`;
}
}
export class CodexAppServerIdentifierGenerationError extends Schema.TaggedErrorClass<CodexAppServerIdentifierGenerationError>()(
"CodexAppServerIdentifierGenerationError",
{
purpose: CodexAppServerIdentifierPurpose,
cause: Schema.Defect(),
},
) {
override get message() {
return `Failed to generate Codex App Server identifier for ${this.purpose}.`;
}
}
export class CodexAppServerInputStreamEndedError extends Schema.TaggedErrorClass<CodexAppServerInputStreamEndedError>()(
"CodexAppServerInputStreamEndedError",
{},
) {
override get message() {
return "Codex App Server input stream ended.";
return this.detail;
}
}
@@ -270,51 +64,20 @@ export class CodexAppServerRequestError extends Schema.TaggedErrorClass<CodexApp
code: Schema.Number,
errorMessage: Schema.String,
data: Schema.optional(Schema.Unknown),
method: Schema.optionalKey(Schema.String),
requestId: Schema.optionalKey(Schema.String),
operation: Schema.optionalKey(CodexAppServerRequestOperation),
issueCount: Schema.optionalKey(Schema.Number),
issueKinds: Schema.optionalKey(Schema.Array(CodexAppServerSchemaIssueKind)),
maximumPathDepth: Schema.optionalKey(Schema.Number),
payloadKind: Schema.optionalKey(CodexAppServerPayloadKind),
cause: Schema.optionalKey(Schema.Defect()),
},
) {
override get message() {
return this.errorMessage;
}
static fromProtocolError(
error: CodexAppServerProtocolErrorShape,
method: string,
requestId: string,
) {
static fromProtocolError(error: CodexAppServerProtocolErrorShape) {
return new CodexAppServerRequestError({
code: error.code,
errorMessage: error.message,
...(error.data !== undefined ? { data: error.data } : {}),
method,
requestId,
operation: "receive-response",
cause: error,
});
}
static fromAppServerError(error: CodexAppServerError, method: string) {
if (error._tag === "CodexAppServerRequestError") {
return error;
}
return CodexAppServerRequestError.internalError(
`Codex App Server request handler failed for method '${method}'`,
undefined,
{
method,
operation: "handle-request",
cause: error,
},
);
}
static parseError(message = "Parse error", data?: unknown) {
return new CodexAppServerRequestError({
code: -32700,
@@ -338,62 +101,19 @@ export class CodexAppServerRequestError extends Schema.TaggedErrorClass<CodexApp
});
}
static invalidParams(
message = "Invalid params",
data?: unknown,
diagnostics: CodexAppServerRequestDiagnostics = {},
) {
static invalidParams(message = "Invalid params", data?: unknown) {
return new CodexAppServerRequestError({
code: -32602,
errorMessage: message,
...(data !== undefined ? { data } : {}),
...diagnostics,
});
}
static invalidPayload(
method: string,
operation: "decode-payload" | "encode-payload",
cause: Schema.SchemaError,
) {
const diagnostics = schemaIssueDiagnostics(cause.issue);
return new CodexAppServerRequestError({
code: -32602,
errorMessage: `Invalid payload for method '${method}' during '${operation}'`,
data: diagnostics,
method,
operation,
...diagnostics,
cause,
});
}
static unexpectedPayload(
method: string,
operation: "decode-payload" | "encode-payload",
payload: unknown,
) {
const diagnostics = { payloadKind: payloadKind(payload) };
return new CodexAppServerRequestError({
code: -32602,
errorMessage: `Method '${method}' does not accept a payload during '${operation}'`,
data: diagnostics,
method,
operation,
...diagnostics,
});
}
static internalError(
message = "Internal error",
data?: unknown,
diagnostics: CodexAppServerRequestDiagnostics = {},
) {
static internalError(message = "Internal error", data?: unknown) {
return new CodexAppServerRequestError({
code: -32603,
errorMessage: message,
...(data !== undefined ? { data } : {}),
...diagnostics,
});
}
@@ -420,8 +140,12 @@ export const CodexAppServerError = Schema.Union([
CodexAppServerProcessExitedError,
CodexAppServerProtocolParseError,
CodexAppServerTransportError,
CodexAppServerIdentifierGenerationError,
CodexAppServerInputStreamEndedError,
]);
export type CodexAppServerError = typeof CodexAppServerError.Type;
export function normalizeToRequestError(error: CodexAppServerError): CodexAppServerRequestError {
return Schema.is(CodexAppServerRequestError)(error)
? error
: CodexAppServerRequestError.internalError(error.message);
}
@@ -2,7 +2,6 @@ import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -10,124 +9,13 @@ import { assert, it } from "@effect/vitest";
import * as CodexError from "./errors.ts";
import * as CodexProtocol from "./protocol.ts";
import * as CodexRpc from "./rpc.ts";
import * as CodexSchema from "./schema.ts";
import { makeInMemoryStdio } from "./_internal/stdio.ts";
const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
const encoder = new TextEncoder();
const encodeJsonl = (value: unknown) => encoder.encode(`${encodeUnknownJsonString(value)}\n`);
const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));
const decodeAccountTokenUsageResponse = Schema.decodeUnknownEffect(
CodexRpc.CLIENT_REQUEST_RESPONSES["account/usage/read"],
);
const decodeAccountRateLimitsResponse = Schema.decodeUnknownEffect(
CodexRpc.CLIENT_REQUEST_RESPONSES["account/rateLimits/read"],
);
const decodeConsumeRateLimitResetCreditParams = Schema.decodeUnknownEffect(
CodexRpc.CLIENT_REQUEST_PARAMS["account/rateLimitResetCredit/consume"],
);
const decodeConsumeRateLimitResetCreditResponse = Schema.decodeUnknownEffect(
CodexRpc.CLIENT_REQUEST_RESPONSES["account/rateLimitResetCredit/consume"],
);
const encodeJsonl = (value: unknown) => encoder.encode(`${JSON.stringify(value)}\n`);
it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
it.effect("maps account usage responses to the upstream token usage schema", () =>
Effect.gen(function* () {
assert.strictEqual(
CodexRpc.CLIENT_REQUEST_RESPONSES["account/usage/read"],
CodexSchema.V2GetAccountTokenUsageResponse,
);
const decoded = yield* decodeAccountTokenUsageResponse({
dailyUsageBuckets: [{ startDate: "2026-06-10", tokens: 42 }],
summary: { lifetimeTokens: 42 },
});
assert.deepEqual(decoded, {
dailyUsageBuckets: [{ startDate: "2026-06-10", tokens: 42 }],
summary: { lifetimeTokens: 42 },
});
}),
);
it.effect("maps earned rate-limit reset credits from account rate-limit snapshots", () =>
Effect.gen(function* () {
assert.strictEqual(
CodexRpc.CLIENT_REQUEST_RESPONSES["account/rateLimits/read"],
CodexSchema.V2GetAccountRateLimitsResponse,
);
const response = {
rateLimits: {},
rateLimitResetCredits: {
availableCount: 2,
credits: [
{
id: "RateLimitResetCredit_1",
resetType: "codexRateLimits",
status: "available",
grantedAt: 1_781_654_400,
expiresAt: 1_784_246_400,
title: "Full reset",
description: "Ready to redeem",
},
{
id: "RateLimitResetCredit_2",
resetType: "unknown",
status: "unknown",
grantedAt: 1_781_654_401,
expiresAt: null,
},
],
},
} as const;
assert.deepEqual(yield* decodeAccountRateLimitsResponse(response), response);
assert.deepEqual(
yield* decodeAccountRateLimitsResponse({
rateLimits: {},
rateLimitResetCredits: { availableCount: 2, credits: null },
}),
{
rateLimits: {},
rateLimitResetCredits: { availableCount: 2, credits: null },
},
);
}),
);
it.effect("maps the earned rate-limit reset consume request and response", () =>
Effect.gen(function* () {
assert.equal(
CodexRpc.CLIENT_REQUEST_METHODS["account/rateLimitResetCredit/consume"],
"account/rateLimitResetCredit/consume",
);
assert.strictEqual(
CodexRpc.CLIENT_REQUEST_PARAMS["account/rateLimitResetCredit/consume"],
CodexSchema.V2ConsumeAccountRateLimitResetCreditParams,
);
assert.strictEqual(
CodexRpc.CLIENT_REQUEST_RESPONSES["account/rateLimitResetCredit/consume"],
CodexSchema.V2ConsumeAccountRateLimitResetCreditResponse,
);
assert.deepEqual(
yield* decodeConsumeRateLimitResetCreditParams({
idempotencyKey: "8ae96ff3-3425-4f4c-8772-b6fd61502868",
creditId: "RateLimitResetCredit_1",
}),
{
idempotencyKey: "8ae96ff3-3425-4f4c-8772-b6fd61502868",
creditId: "RateLimitResetCredit_1",
},
);
assert.deepEqual(yield* decodeConsumeRateLimitResetCreditResponse({ outcome: "reset" }), {
outcome: "reset",
});
}),
);
it.effect(
"encodes requests without a jsonrpc field and routes inbound requests and notifications",
() =>
@@ -172,7 +60,7 @@ it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
const pendingInitialize = yield* transport
.request("initialize", initializeParams)
.pipe(Effect.forkScoped);
assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
assert.deepEqual(JSON.parse(yield* Queue.take(output)), {
id: 1,
method: "initialize",
params: initializeParams,
@@ -265,7 +153,7 @@ it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
},
},
});
assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
assert.deepEqual(JSON.parse(yield* Queue.take(output)), {
id: 77,
result: {
answers: {
@@ -280,7 +168,7 @@ it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
78,
CodexError.CodexAppServerRequestError.methodNotFound("x/test"),
);
assert.deepEqual(yield* decodeJson(yield* Queue.take(output)), {
assert.deepEqual(JSON.parse(yield* Queue.take(output)), {
id: 78,
error: {
code: -32601,
@@ -297,151 +185,13 @@ it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
assert.instanceOf(bigintError, CodexError.CodexAppServerProtocolParseError);
assert.equal(bigintError.operation, "encode-wire-message");
assert.equal(bigintError.method, "x/test");
assert.exists(bigintError.cause);
assert.equal(
bigintError.message,
"Codex App Server protocol operation 'encode-wire-message' failed for method 'x/test'.",
);
assert.equal(bigintError.detail, "Failed to encode Codex App Server message");
const circular: Record<string, unknown> = {};
circular.self = circular;
const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
assert.instanceOf(circularError, CodexError.CodexAppServerProtocolParseError);
assert.equal(circularError.operation, "encode-wire-message");
assert.equal(circularError.method, "x/test");
assert.exists(circularError.cause);
const requestError = yield* transport.request("x/request", 1n).pipe(
Effect.match({
onFailure: (error) => error,
onSuccess: () => assert.fail("Expected request encoding to fail"),
}),
);
assert.instanceOf(requestError, CodexError.CodexAppServerProtocolParseError);
assert.deepInclude(requestError, {
operation: "encode-wire-message",
method: "x/request",
requestId: "1",
});
}),
);
it.effect("correlates response errors with the originating request", () =>
Effect.gen(function* () {
const { stdio, input, output } = yield* makeInMemoryStdio();
const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
const response = yield* transport.request("thread/start", {}).pipe(Effect.forkScoped);
yield* Queue.take(output);
yield* Queue.offer(
input,
encodeJsonl({
id: 1,
error: {
code: -32602,
message: "Invalid params",
data: { field: "cwd" },
},
}),
);
const error = yield* Fiber.join(response).pipe(
Effect.match({
onFailure: (error) => error,
onSuccess: () => assert.fail("Expected Codex App Server request to fail"),
}),
);
assert.instanceOf(error, CodexError.CodexAppServerRequestError);
assert.deepInclude(error, {
code: -32602,
errorMessage: "Invalid params",
method: "thread/start",
requestId: "1",
operation: "receive-response",
});
}),
);
it.effect("logs decode failures without copying the cause or wire payload", () =>
Effect.gen(function* () {
const secret = "codex-wire-secret-sentinel";
const { stdio, input } = yield* makeInMemoryStdio();
const events: Array<CodexProtocol.CodexAppServerProtocolLogEvent> = [];
const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
stdio,
logIncoming: true,
logger: (event) =>
Effect.sync(() => {
events.push(event);
}),
onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
});
yield* Queue.offer(input, encoder.encode(`{"secret":"${secret}"\n`));
yield* Deferred.await(termination);
const event = events.find(({ stage }) => stage === "decode_failed");
assert.exists(event);
assert.equal(event.direction, "incoming");
const payload = event.payload as Record<string, unknown>;
assert.equal(payload.operation, "decode-wire-message");
assert.isNumber(payload.issueCount);
assert.isArray(payload.issueKinds);
assert.isNumber(payload.maximumPathDepth);
assert.equal("cause" in payload, false);
assert.equal("detail" in payload, false);
assert.notInclude(encodeUnknownJsonString(event), secret);
}),
);
it.effect("describes unroutable messages with safe structural diagnostics", () =>
Effect.gen(function* () {
const secret = "codex-unroutable-secret-sentinel";
const { stdio, input } = yield* makeInMemoryStdio();
const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
stdio,
onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
});
yield* Queue.offer(
input,
encodeJsonl({ id: true, method: "thread/start", params: { token: secret } }),
);
const error = yield* Deferred.await(termination);
assert.instanceOf(error, CodexError.CodexAppServerProtocolParseError);
assert.deepInclude(error, {
operation: "route-wire-message",
method: "thread/start",
payloadKind: "object",
presentFields: ["id", "method", "params"],
});
assert.isUndefined(error.requestId);
assert.notProperty(error, "detail");
assert.notProperty(error, "cause");
assert.notInclude(error.message, secret);
}),
);
it.effect("classifies an input stream ending without inventing a cause", () =>
Effect.gen(function* () {
const { stdio, input } = yield* makeInMemoryStdio();
const termination = yield* Deferred.make<CodexError.CodexAppServerError>();
yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
stdio,
onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
});
yield* Queue.end(input);
const error = yield* Deferred.await(termination);
assert.instanceOf(error, CodexError.CodexAppServerInputStreamEndedError);
assert.equal(error.message, "Codex App Server input stream ended.");
assert.equal("cause" in error, false);
assert.equal(circularError.detail, "Failed to encode Codex App Server message");
}),
);
});
@@ -10,9 +10,6 @@ import * as Stream from "effect/Stream";
import * as CodexError from "./errors.ts";
import { JsonRpcId, JsonRpcResponseEnvelope } from "./_internal/shared.ts";
const isJsonRpcId = Schema.is(JsonRpcId);
const isJsonRpcResponseEnvelope = Schema.is(JsonRpcResponseEnvelope);
const isCodexAppServerError = Schema.is(CodexError.CodexAppServerError);
export interface CodexAppServerProtocolLogEvent {
readonly direction: "incoming" | "outgoing";
@@ -67,11 +64,6 @@ export interface CodexAppServerPatchedProtocol {
) => Effect.Effect<void, CodexError.CodexAppServerError>;
}
interface CodexAppServerPendingRequest {
readonly deferred: Deferred.Deferred<unknown, CodexError.CodexAppServerError>;
readonly method: string;
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
@@ -80,7 +72,7 @@ function isIncomingRequest(value: unknown): value is CodexAppServerIncomingReque
if (!isObject(value) || typeof value.method !== "string") {
return false;
}
return isJsonRpcId(value.id);
return Schema.is(JsonRpcId)(value.id);
}
function isIncomingNotification(value: unknown): value is CodexAppServerIncomingNotification {
@@ -88,51 +80,26 @@ function isIncomingNotification(value: unknown): value is CodexAppServerIncoming
}
function isIncomingResponse(value: unknown): value is typeof JsonRpcResponseEnvelope.Type {
return isJsonRpcResponseEnvelope(value);
return Schema.is(JsonRpcResponseEnvelope)(value);
}
const encodeJsonString = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
const decodeJsonString = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
const encodeWireMessage = (
message: Record<string, unknown>,
): Effect.Effect<string, CodexError.CodexAppServerProtocolParseError> =>
encodeJsonString(message).pipe(
Effect.map((encoded) => `${encoded}\n`),
Effect.mapError((cause) => {
const method = typeof message.method === "string" ? message.method : undefined;
const requestId =
typeof message.id === "string" || typeof message.id === "number"
? String(message.id)
: undefined;
return CodexError.CodexAppServerProtocolParseError.fromSchemaError(
"encode-wire-message",
Effect.try({
try: () => `${JSON.stringify(message)}\n`,
catch: (cause) =>
new CodexError.CodexAppServerProtocolParseError({
detail: "Failed to encode Codex App Server message",
cause,
{
...(method === undefined ? {} : { method }),
...(requestId === undefined ? {} : { requestId }),
},
);
}),
);
}),
});
const decodeWireMessage = (
line: string,
): Effect.Effect<unknown, CodexError.CodexAppServerProtocolParseError> =>
decodeJsonString(line).pipe(
Effect.mapError((cause) =>
CodexError.CodexAppServerProtocolParseError.fromSchemaError("decode-wire-message", cause),
),
);
const normalizeIncomingError = (
error: unknown,
operation: CodexError.CodexAppServerTransportOperation,
): CodexError.CodexAppServerError =>
isCodexAppServerError(error)
const normalizeIncomingError = (error: unknown, detail: string): CodexError.CodexAppServerError =>
Schema.is(CodexError.CodexAppServerError)(error)
? error
: new CodexError.CodexAppServerTransportError({
operation,
detail,
cause: error,
});
@@ -155,7 +122,9 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
const outgoing = yield* Queue.unbounded<string, Cause.Done<void>>();
const incomingNotifications = yield* Queue.unbounded<CodexAppServerIncomingNotification>();
const incomingRequests = yield* Queue.unbounded<CodexAppServerIncomingRequest>();
const pending = yield* Ref.make(new Map<string, CodexAppServerPendingRequest>());
const pending = yield* Ref.make(
new Map<string, Deferred.Deferred<unknown, CodexError.CodexAppServerError>>(),
);
const nextRequestId = yield* Ref.make(1);
const remainder = yield* Ref.make("");
const terminationHandled = yield* Ref.make(false);
@@ -176,7 +145,7 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
const failAllPending = (error: CodexError.CodexAppServerError) =>
Ref.get(pending).pipe(
Effect.flatMap((current) =>
Effect.forEach([...current.values()], ({ deferred }) => Deferred.fail(deferred, error), {
Effect.forEach([...current.values()], (deferred) => Deferred.fail(deferred, error), {
discard: true,
}),
),
@@ -229,16 +198,18 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
const resolvePending = (
requestId: string,
handler: (pendingRequest: CodexAppServerPendingRequest) => Effect.Effect<void>,
handler: (
deferred: Deferred.Deferred<unknown, CodexError.CodexAppServerError>,
) => Effect.Effect<void>,
) =>
Ref.modify(pending, (current) => {
const pendingRequest = current.get(requestId);
if (!pendingRequest) {
const deferred = current.get(requestId);
if (!deferred) {
return [Effect.void, current] as const;
}
const next = new Map(current);
next.delete(requestId);
return [handler(pendingRequest), next] as const;
return [handler(deferred), next] as const;
}).pipe(Effect.flatten);
const respond = (requestId: string | number, result: unknown) =>
@@ -253,20 +224,14 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
const requestId = String(response.id);
const protocolError = response.error;
if (protocolError !== undefined) {
return resolvePending(requestId, ({ deferred, method }) =>
return resolvePending(requestId, (deferred) =>
Deferred.fail(
deferred,
CodexError.CodexAppServerRequestError.fromProtocolError(
protocolError,
method,
requestId,
),
CodexError.CodexAppServerRequestError.fromProtocolError(protocolError),
),
);
}
return resolvePending(requestId, ({ deferred }) =>
Deferred.succeed(deferred, response.result),
);
return resolvePending(requestId, (deferred) => Deferred.succeed(deferred, response.result));
};
const handleRequest = (request: CodexAppServerIncomingRequest) =>
@@ -276,13 +241,7 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
? options.onRequest(request).pipe(
Effect.matchEffect({
onFailure: (error) =>
respondError(
request.id,
CodexError.CodexAppServerRequestError.fromAppServerError(
error,
request.method,
),
),
respondError(request.id, CodexError.normalizeToRequestError(error)),
onSuccess: (result) => respond(request.id, result),
}),
)
@@ -310,7 +269,9 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
return handleResponse(message);
}
return Effect.fail(
CodexError.CodexAppServerProtocolParseError.fromUnroutableMessage(message),
new CodexError.CodexAppServerProtocolParseError({
detail: "Received protocol message in an unknown shape",
}),
);
};
@@ -323,7 +284,16 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
stage: "raw",
payload: line,
}).pipe(
Effect.flatMap(() => decodeWireMessage(line)),
Effect.flatMap(() =>
Effect.try({
try: () => JSON.parse(line),
catch: (cause) =>
new CodexError.CodexAppServerProtocolParseError({
detail: "Failed to decode Codex App Server wire message",
cause,
}),
}),
),
Effect.tap((decoded) =>
logProtocol({
direction: "incoming",
@@ -336,14 +306,8 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
direction: "incoming",
stage: "decode_failed",
payload: {
operation: error.operation,
...(error.method === undefined ? {} : { method: error.method }),
...(error.requestId === undefined ? {} : { requestId: error.requestId }),
...(error.issueCount === undefined ? {} : { issueCount: error.issueCount }),
...(error.issueKinds === undefined ? {} : { issueKinds: error.issueKinds }),
...(error.maximumPathDepth === undefined
? {}
: { maximumPathDepth: error.maximumPathDepth }),
detail: error.detail,
cause: error.cause,
},
}),
),
@@ -364,7 +328,7 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
Effect.matchEffect({
onFailure: (error) =>
handleTermination(() =>
Effect.succeed(normalizeIncomingError(error, "read-input-stream")),
Effect.succeed(normalizeIncomingError(error, "Codex App Server input stream failed")),
),
onSuccess: () =>
Ref.get(remainder).pipe(
@@ -375,7 +339,12 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
handleTermination(
() =>
options.terminationError ??
Effect.succeed(new CodexError.CodexAppServerInputStreamEndedError({})),
Effect.succeed(
new CodexError.CodexAppServerTransportError({
detail: "Codex App Server input stream ended",
cause: new Error("Codex App Server input stream ended"),
}),
),
),
}),
),
@@ -392,14 +361,16 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
(current) => [current, current + 1] as const,
);
const deferred = yield* Deferred.make<unknown, CodexError.CodexAppServerError>();
yield* Ref.update(pending, (current) =>
new Map(current).set(String(requestId), { deferred, method }),
);
yield* Ref.update(pending, (current) => new Map(current).set(String(requestId), deferred));
yield* offerOutgoing({
id: requestId,
method,
...(payload !== undefined ? { params: payload } : {}),
}).pipe(Effect.tapError(() => removePending(String(requestId))));
}).pipe(
Effect.catch((error) =>
removePending(String(requestId)).pipe(Effect.andThen(Effect.fail(error))),
),
);
return yield* Deferred.await(deferred).pipe(
Effect.onInterrupt(() => removePending(String(requestId))),
);
@@ -1,6 +1,5 @@
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -8,14 +7,10 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import * as CodexClient from "../../src/client.ts";
const program = Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const handle = yield* spawner.spawn(
ChildProcess.make(process.env.CODEX_BIN ?? "codex", ["app-server"], {
cwd: process.cwd(),
shell: false,
}),
);
const codexLayer = CodexClient.layerChildProcess(handle, {
const codexLayer = CodexClient.layerCommand({
command: process.env.CODEX_BIN ?? "codex",
args: ["app-server"],
cwd: process.cwd(),
logIncoming: true,
logOutgoing: true,
});
@@ -50,17 +45,17 @@ const program = Effect.gen(function* () {
optOutNotificationMethods: null,
},
});
yield* Console.log("initialize", initialized);
yield* Console.log("initialize", JSON.stringify(initialized, null, 2));
yield* client.notify("initialized", undefined);
const account = yield* client.request("account/read", {});
yield* Console.log("account/read", account);
yield* Console.log("account/read", JSON.stringify(account, null, 2));
const skills = yield* client.request("skills/list", {
cwds: [process.cwd()],
});
yield* Console.log("skills/list", skills);
yield* Console.log("skills/list", JSON.stringify(skills, null, 2));
}).pipe(Effect.provide(codexLayer));
});
@@ -1,5 +1,3 @@
import * as NodeOS from "node:os";
let nextServerRequestId = 10_000;
let pendingSkillsListRequestId: number | string | null = null;
let pendingUserInputRequestId: number | null = null;
@@ -36,25 +34,11 @@ const handleMethod = (message: Record<string, unknown>) => {
switch (method) {
case "initialize": {
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone mock peer process has no Effect runtime.
const platform = NodeOS.platform();
const stderrBytes = Number(process.env.CODEX_APP_SERVER_TEST_STDERR_BYTES ?? 0);
if (Number.isFinite(stderrBytes) && stderrBytes > 0) {
process.stderr.write("x".repeat(stderrBytes), () => {
respond(message.id as number | string, {
userAgent: "mock-codex-app-server",
codexHome: process.cwd(),
platformFamily: platform === "win32" ? "windows" : "unix",
platformOs: platform === "darwin" ? "macos" : platform,
});
});
return;
}
respond(message.id as number | string, {
userAgent: "mock-codex-app-server",
codexHome: process.cwd(),
platformFamily: platform === "win32" ? "windows" : "unix",
platformOs: platform === "darwin" ? "macos" : platform,
platformFamily: process.platform === "win32" ? "windows" : "unix",
platformOs: process.platform === "darwin" ? "macos" : process.platform,
});
return;
}
+12 -1
View File
@@ -1,7 +1,18 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node"]
"plugins": [
{
"name": "@effect/language-service",
"namespaceImportPackages": ["@effect/platform-node"],
"diagnosticSeverity": {
"importFromBarrel": "error",
"anyUnknownInErrorContext": "warning",
"instanceOfSchema": "warning",
"deterministicKeys": "warning"
}
}
]
},
"include": ["src", "scripts", "test"]
}
+21 -4
View File
@@ -312,10 +312,27 @@ export function trimOrNull<T extends string>(value: T | null | undefined): T | n
return trimmed || null;
}
function cloneSelections(
selections: ReadonlyArray<ProviderOptionSelection>,
): Array<ProviderOptionSelection> {
return selections.map(cloneSelection);
/**
* Resolve the actual API model identifier from a model selection.
*
* Provider-aware: each provider can map `contextWindow` (or other options)
* to whatever the API requires. The canonical slug stored in the selection
* stays unchanged so the capabilities system keeps working.
*/
export function resolveApiModelId(modelSelection: ModelSelection): string {
switch (modelSelection.provider) {
case "claudeAgent": {
switch (modelSelection.options?.contextWindow) {
case "1m":
return `${modelSelection.model}[1m]`;
default:
return modelSelection.model;
}
}
default: {
return modelSelection.model;
}
}
}
export function createModelSelection(