Integrate Codex app-server support

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-04-17 17:29:53 -07:00
1 parent 9df3c64021
commit 308dd659da
73 files changed
+39850 -6741

No files matched your search

@@ -39,6 +39,12 @@ 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");
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() {
@@ -167,7 +173,7 @@ const startTurn = (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);
@@ -346,7 +352,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);
@@ -527,7 +533,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);
@@ -608,264 +614,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(() => {
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.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(() => {
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.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(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]);
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) =>
@@ -902,7 +917,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* () {
@@ -959,7 +974,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* () {
@@ -1005,6 +1020,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();
@@ -1067,7 +1083,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* () {
@@ -1141,7 +1157,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* () {
@@ -1210,126 +1226,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", "claudeAgent"),
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", "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",
},
});
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", "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* 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]);
}),
"claudeAgent",
),
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,
);
+1
View File
@@ -44,6 +44,7 @@
"@types/bun": "catalog:",
"@types/node": "catalog:",
"effect-acp": "workspace:*",
"effect-codex-app-server": "workspace:*",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
+1 -23
View File
@@ -11,7 +11,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";
@@ -30,27 +29,6 @@ let currentContext = "272k";
let currentFast = false;
const cancelledSessions = new Set<string>();
function logExit(reason: string): void {
if (!exitLogPath) {
return;
}
appendFileSync(exitLogPath, `${reason}\n`, "utf8");
}
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> = [
@@ -287,7 +265,7 @@ const program = Effect.gen(function* () {
yield* agent.handleCancel(({ sessionId }) =>
Effect.sync(() => {
cancelledSessions.add(String(sessionId ?? "mock-session-1"));
cancelledSessions.add(String(sessionId));
}),
);
@@ -316,10 +316,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() {
@@ -377,10 +377,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
File diff suppressed because it is too large. Load diff
@@ -28,7 +28,7 @@ import {
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
import { getCodexModelCapabilities } from "../../provider/codexModels.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { normalizeCodexModelOptionsWithCapabilities } from "@t3tools/shared/model";
@@ -96,22 +96,6 @@ function withFakeAcpAgent<A, E, R>(
});
}
function waitForFileContent(path: string): Effect.Effect<string> {
return Effect.promise(async () => {
const deadline = Date.now() + 5_000;
for (;;) {
try {
return readFileSync(path, "utf8");
} catch (error) {
if (Date.now() >= deadline) {
throw error instanceof Error ? error : new Error(String(error));
}
}
await new Promise((resolve) => setTimeout(resolve, 25));
}
});
}
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-"));
@@ -161,6 +145,14 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
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) =>
@@ -258,41 +250,4 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
}),
),
);
it.effect("closes the ACP child process after text generation completes", () => {
const exitLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-exit-log-"));
const exitLogPath = path.join(exitLogDir, "exit.log");
return withFakeAcpAgent(
{
T3_ACP_EXIT_LOG_PATH: exitLogPath,
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
subject: "Close runtime after generation",
body: "",
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-runtime-close",
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: "composer-2",
},
});
expect(generated.subject).toBe("Close runtime after generation");
const exitLog = yield* waitForFileContent(exitLogPath);
expect(exitLog).toContain("exit:0");
rmSync(exitLogDir, { recursive: true, force: true });
}),
);
});
});
+187 -194
View File
@@ -183,8 +183,16 @@ function splitNullSeparatedPaths(input: string): string[] {
// ── Tests ──
it.layer(TestLayer)("git integration", (it) => {
const LONG_EFFECT_TEST_TIMEOUT_MS = 30_000;
const ASYNC_GIT_WAIT_TIMEOUT_MS = 30_000;
const effect = (
name: string,
test: Parameters<typeof it.effect>[1],
timeout = LONG_EFFECT_TEST_TIMEOUT_MS,
) => it.effect(name, test, timeout);
describe("shell process execution", () => {
it.effect("caps captured output when maxOutputBytes is exceeded", () =>
effect("caps captured output when maxOutputBytes is exceeded", () =>
Effect.gen(function* () {
const result = yield* runShellCommand({
command: `node -e "process.stdout.write('x'.repeat(2000))"`,
@@ -203,7 +211,7 @@ it.layer(TestLayer)("git integration", (it) => {
// ── initGitRepo ──
describe("initGitRepo", () => {
it.effect("creates a valid git repo", () =>
effect("creates a valid git repo", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* (yield* GitCore).initRepo({ cwd: tmp });
@@ -211,7 +219,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("listGitBranches reports isRepo: true after init + commit", () =>
effect("listGitBranches reports isRepo: true after init + commit", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -307,7 +315,7 @@ it.layer(TestLayer)("git integration", (it) => {
// ── listGitBranches ──
describe("listGitBranches", () => {
it.effect("returns isRepo: false for non-git directory", () =>
effect("returns isRepo: false for non-git directory", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const result = yield* (yield* GitCore).listBranches({ cwd: tmp });
@@ -317,7 +325,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("returns isRepo: false for deleted directories", () =>
effect("returns isRepo: false for deleted directories", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const deletedDir = path.join(tmp, "deleted-repo");
@@ -332,7 +340,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("returns the current branch with current: true", () =>
effect("returns the current branch with current: true", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -343,7 +351,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("does not include detached HEAD pseudo-refs as branches", () =>
effect("does not include detached HEAD pseudo-refs as branches", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -355,7 +363,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("keeps current branch first and sorts the remaining branches by recency", () =>
effect("keeps current branch first and sorts the remaining branches by recency", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -393,7 +401,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("keeps default branch right after current branch", () =>
effect("keeps default branch right after current branch", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
@@ -437,7 +445,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("lists multiple branches after creating them", () =>
effect("lists multiple branches after creating them", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -548,7 +556,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("lists local branches first and remote branches last", () =>
effect("lists local branches first and remote branches last", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const tmp = yield* makeTmpDir();
@@ -595,7 +603,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("includes remoteName metadata for remotes with slash in the name", () =>
effect("includes remoteName metadata for remotes with slash in the name", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const tmp = yield* makeTmpDir();
@@ -666,7 +674,7 @@ it.layer(TestLayer)("git integration", (it) => {
// ── checkoutGitBranch ──
describe("checkoutGitBranch", () => {
it.effect("checks out an existing branch", () =>
effect("checks out an existing branch", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -680,7 +688,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("refreshes upstream behind count after checkout when remote branch advanced", () =>
effect("refreshes upstream behind count after checkout when remote branch advanced", () =>
Effect.gen(function* () {
const context = yield* Effect.context<never>();
const runPromise = Effect.runPromiseWith(context);
@@ -726,7 +734,7 @@ it.layer(TestLayer)("git integration", (it) => {
expect(details.behindCount).toBe(1);
},
{
timeout: 10_000,
timeout: ASYNC_GIT_WAIT_TIMEOUT_MS,
interval: 100,
},
),
@@ -734,7 +742,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("statusDetails remains successful when upstream refresh fails after checkout", () =>
effect("statusDetails remains successful when upstream refresh fails after checkout", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
@@ -781,7 +789,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("defers upstream refresh until statusDetails is requested", () =>
effect("defers upstream refresh until statusDetails is requested", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
@@ -826,7 +834,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("coalesces upstream refreshes across sibling worktrees on the same remote", () =>
effect("shares upstream refreshes across worktrees that use the same git common dir", () =>
Effect.gen(function* () {
const ok = (stdout = "") =>
Effect.succeed({
@@ -900,83 +908,78 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect(
"briefly backs off failed upstream refreshes across sibling worktrees on one remote",
() =>
Effect.gen(function* () {
const ok = (stdout = "") =>
Effect.succeed({
code: 0,
stdout,
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
});
effect("briefly backs off failed upstream refreshes across sibling worktrees", () =>
Effect.gen(function* () {
const ok = (stdout = "") =>
Effect.succeed({
code: 0,
stdout,
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
});
let fetchCount = 0;
const core = yield* makeIsolatedGitCore((input) => {
if (
input.args[0] === "rev-parse" &&
input.args[1] === "--abbrev-ref" &&
input.args[2] === "--symbolic-full-name" &&
input.args[3] === "@{upstream}"
) {
return ok(
input.cwd === "/repo/worktrees/pr-123"
? "origin/feature/pr-123\n"
: "origin/main\n",
);
}
if (input.args[0] === "remote") {
return ok("origin\n");
}
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
return ok("/repo/.git\n");
}
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
fetchCount += 1;
return Effect.fail(
new GitCommandError({
operation: input.operation,
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "simulated fetch timeout",
}),
);
}
if (input.operation === "GitCore.statusDetails.status") {
return ok(
input.cwd === "/repo/worktrees/pr-123"
? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n"
: "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n",
);
}
if (
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
input.operation === "GitCore.statusDetails.stagedNumstat"
) {
return ok();
}
if (input.operation === "GitCore.statusDetails.defaultRef") {
return ok("refs/remotes/origin/main\n");
}
let fetchCount = 0;
const core = yield* makeIsolatedGitCore((input) => {
if (
input.args[0] === "rev-parse" &&
input.args[1] === "--abbrev-ref" &&
input.args[2] === "--symbolic-full-name" &&
input.args[3] === "@{upstream}"
) {
return ok(
input.cwd === "/repo/worktrees/pr-123" ? "origin/feature/pr-123\n" : "origin/main\n",
);
}
if (input.args[0] === "remote") {
return ok("origin\n");
}
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
return ok("/repo/.git\n");
}
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
fetchCount += 1;
return Effect.fail(
new GitCommandError({
operation: input.operation,
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "Unexpected git command in refresh failure cooldown test.",
detail: "simulated fetch timeout",
}),
);
});
yield* core.statusDetails("/repo/worktrees/main");
yield* core.statusDetails("/repo/worktrees/pr-123");
expect(fetchCount).toBe(1);
}),
}
if (input.operation === "GitCore.statusDetails.status") {
return ok(
input.cwd === "/repo/worktrees/pr-123"
? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n"
: "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n",
);
}
if (
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
input.operation === "GitCore.statusDetails.stagedNumstat"
) {
return ok();
}
if (input.operation === "GitCore.statusDetails.defaultRef") {
return ok("refs/remotes/origin/main\n");
}
return Effect.fail(
new GitCommandError({
operation: input.operation,
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "Unexpected git command in refresh failure cooldown test.",
}),
);
});
yield* core.statusDetails("/repo/worktrees/main");
yield* core.statusDetails("/repo/worktrees/pr-123");
expect(fetchCount).toBe(1);
}),
);
it.effect("throws when branch does not exist", () =>
effect("throws when branch does not exist", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -987,7 +990,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("does not silently checkout a local branch when a remote ref no longer exists", () =>
effect("does not silently checkout a local branch when a remote ref no longer exists", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
@@ -1010,7 +1013,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("checks out a remote tracking branch when remote name contains slashes", () =>
effect("checks out a remote tracking branch when remote name contains slashes", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const prefixRemote = yield* makeTmpDir();
@@ -1075,7 +1078,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect(
effect(
"falls back to detached checkout when --track would conflict with an existing local branch",
() =>
Effect.gen(function* () {
@@ -1105,7 +1108,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("throws when checkout would overwrite uncommitted changes", () =>
effect("throws when checkout would overwrite uncommitted changes", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1143,7 +1146,7 @@ it.layer(TestLayer)("git integration", (it) => {
// ── createGitBranch ──
describe("createGitBranch", () => {
it.effect("creates a new branch visible in listGitBranches", () =>
effect("creates a new branch visible in listGitBranches", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1154,7 +1157,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("throws when branch already exists", () =>
effect("throws when branch already exists", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1170,7 +1173,7 @@ it.layer(TestLayer)("git integration", (it) => {
// ── renameGitBranch ──
describe("renameGitBranch", () => {
it.effect("renames the current branch", () =>
effect("renames the current branch", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1192,7 +1195,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("returns success without git invocation when old/new names match", () =>
effect("returns success without git invocation when old/new names match", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1210,7 +1213,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("appends numeric suffix when target branch already exists", () =>
effect("appends numeric suffix when target branch already exists", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1237,7 +1240,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("increments suffix until it finds an available branch name", () =>
effect("increments suffix until it finds an available branch name", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1256,7 +1259,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("uses '--' separator for branch rename arguments", () =>
effect("uses '--' separator for branch rename arguments", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1287,7 +1290,7 @@ it.layer(TestLayer)("git integration", (it) => {
// ── createGitWorktree + removeGitWorktree ──
describe("createGitWorktree", () => {
it.effect("creates a worktree with a new branch from the base branch", () =>
effect("creates a worktree with a new branch from the base branch", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1314,7 +1317,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("worktree has the new branch checked out", () =>
effect("worktree has the new branch checked out", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1339,7 +1342,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("creates a worktree for an existing branch when newBranch is omitted", () =>
effect("creates a worktree for an existing branch when newBranch is omitted", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1361,7 +1364,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("throws when new branch name already exists", () =>
effect("throws when new branch name already exists", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1384,7 +1387,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("listGitBranches from worktree cwd reports worktree branch as current", () =>
effect("listGitBranches from worktree cwd reports worktree branch as current", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1416,7 +1419,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("removeGitWorktree cleans up the worktree", () =>
effect("removeGitWorktree cleans up the worktree", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1439,7 +1442,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("removeGitWorktree force removes a dirty worktree", () =>
effect("removeGitWorktree force removes a dirty worktree", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1474,7 +1477,7 @@ it.layer(TestLayer)("git integration", (it) => {
// ── Full flow: local branch checkout ──
describe("full flow: local branch checkout", () => {
it.effect("init → commit → create branch → checkout → verify current", () =>
effect("init → commit → create branch → checkout → verify current", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1491,7 +1494,7 @@ it.layer(TestLayer)("git integration", (it) => {
// ── Full flow: worktree creation from base branch ──
describe("full flow: worktree creation", () => {
it.effect("creates worktree with new branch from current branch", () =>
effect("creates worktree with new branch from current branch", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1526,7 +1529,7 @@ it.layer(TestLayer)("git integration", (it) => {
});
describe("fetchPullRequestBranch", () => {
it.effect("fetches a GitHub pull request ref into a local branch without checkout", () =>
effect("fetches a GitHub pull request ref into a local branch without checkout", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const { initialBranch } = yield* initRepoWithCommit(tmp);
@@ -1559,7 +1562,7 @@ it.layer(TestLayer)("git integration", (it) => {
// ── Full flow: thread switching simulation ──
describe("full flow: thread switching (checkout toggling)", () => {
it.effect("checkout a → checkout b → checkout a → current matches", () =>
effect("checkout a → checkout b → checkout a → current matches", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1587,7 +1590,7 @@ it.layer(TestLayer)("git integration", (it) => {
// ── Full flow: checkout conflict ──
describe("full flow: checkout conflict", () => {
it.effect("uncommitted changes prevent checkout to a diverged branch", () =>
effect("uncommitted changes prevent checkout to a diverged branch", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1621,7 +1624,7 @@ it.layer(TestLayer)("git integration", (it) => {
});
describe("GitCore", () => {
it.effect("supports branch lifecycle operations through the service API", () =>
effect("supports branch lifecycle operations through the service API", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const core = yield* GitCore;
@@ -1645,7 +1648,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect(
effect(
"reuses an existing remote when the target URL only differs by a trailing slash after .git",
() =>
Effect.gen(function* () {
@@ -1666,7 +1669,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("reports status details and dirty state", () =>
effect("reports status details and dirty state", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1682,7 +1685,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("returns a non-repo status for deleted directories", () =>
effect("returns a non-repo status for deleted directories", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const deletedDir = path.join(tmp, "deleted-repo");
@@ -1713,7 +1716,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("computes ahead count against base branch when no upstream is configured", () =>
effect("computes ahead count against base branch when no upstream is configured", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1733,39 +1736,37 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect(
"computes ahead count against origin/default when local default branch is missing",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
effect("computes ahead count against origin/default when local default branch is missing", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const initialBranch = (yield* (yield* GitCore).listBranches({
cwd: source,
})).branches.find((branch) => branch.current)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", initialBranch]);
yield* git(source, ["checkout", "-b", "feature/remote-base-only"]);
yield* writeTextFile(
path.join(source, "feature.txt"),
`ahead of origin/${initialBranch}\n`,
);
yield* git(source, ["add", "feature.txt"]);
yield* git(source, ["commit", "-m", "feature commit"]);
yield* git(source, ["branch", "-D", initialBranch]);
yield* initRepoWithCommit(source);
const initialBranch = (yield* (yield* GitCore).listBranches({
cwd: source,
})).branches.find((branch) => branch.current)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", initialBranch]);
yield* git(source, ["checkout", "-b", "feature/remote-base-only"]);
yield* writeTextFile(
path.join(source, "feature.txt"),
`ahead of origin/${initialBranch}\n`,
);
yield* git(source, ["add", "feature.txt"]);
yield* git(source, ["commit", "-m", "feature commit"]);
yield* git(source, ["branch", "-D", initialBranch]);
const core = yield* GitCore;
const details = yield* core.statusDetails(source);
expect(details.branch).toBe("feature/remote-base-only");
expect(details.hasUpstream).toBe(false);
expect(details.aheadCount).toBe(1);
expect(details.behindCount).toBe(0);
}),
const core = yield* GitCore;
const details = yield* core.statusDetails(source);
expect(details.branch).toBe("feature/remote-base-only");
expect(details.hasUpstream).toBe(false);
expect(details.aheadCount).toBe(1);
expect(details.behindCount).toBe(0);
}),
);
it.effect(
effect(
"computes ahead count against a non-origin remote-prefixed gh-merge-base candidate",
() =>
Effect.gen(function* () {
@@ -1803,7 +1804,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("skips push when no upstream is configured and branch is not ahead of base", () =>
effect("skips push when no upstream is configured and branch is not ahead of base", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -1819,7 +1820,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("pushes with upstream setup when no comparable base branch exists", () =>
effect("pushes with upstream setup when no comparable base branch exists", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
@@ -1844,7 +1845,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("pushes with upstream setup to the only configured non-origin remote", () =>
effect("pushes with upstream setup to the only configured non-origin remote", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
@@ -1869,7 +1870,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect(
effect(
"pushes with upstream setup when comparable base exists but remote branch is missing",
() =>
Effect.gen(function* () {
@@ -1905,7 +1906,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("prefers branch pushRemote over origin when setting upstream", () =>
effect("prefers branch pushRemote over origin when setting upstream", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const origin = yield* makeTmpDir();
@@ -1942,7 +1943,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect(
effect(
"pushes renamed PR worktree branches to their tracked upstream branch even when push.default is current",
() =>
Effect.gen(function* () {
@@ -1989,7 +1990,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("pushes to the tracked upstream when the remote name contains slashes", () =>
effect("pushes to the tracked upstream when the remote name contains slashes", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
@@ -2030,7 +2031,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("includes command context when worktree removal fails", () =>
effect("includes command context when worktree removal fails", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -2051,46 +2052,38 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect(
"refreshes upstream before statusDetails so behind count reflects remote updates",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
const clone = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
effect("refreshes upstream before statusDetails so behind count reflects remote updates", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
const clone = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const initialBranch = (yield* (yield* GitCore).listBranches({
cwd: source,
})).branches.find((branch) => branch.current)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", initialBranch]);
yield* initRepoWithCommit(source);
const initialBranch = (yield* (yield* GitCore).listBranches({
cwd: source,
})).branches.find((branch) => branch.current)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", initialBranch]);
yield* git(clone, ["clone", remote, "."]);
yield* git(clone, ["config", "user.email", "[email protected]"]);
yield* git(clone, ["config", "user.name", "Test"]);
yield* git(clone, [
"checkout",
"-B",
initialBranch,
"--track",
`origin/${initialBranch}`,
]);
yield* writeTextFile(path.join(clone, "CHANGELOG.md"), "remote change\n");
yield* git(clone, ["add", "CHANGELOG.md"]);
yield* git(clone, ["commit", "-m", "remote update"]);
yield* git(clone, ["push", "origin", initialBranch]);
yield* git(clone, ["clone", remote, "."]);
yield* git(clone, ["config", "user.email", "[email protected]"]);
yield* git(clone, ["config", "user.name", "Test"]);
yield* git(clone, ["checkout", "-B", initialBranch, "--track", `origin/${initialBranch}`]);
yield* writeTextFile(path.join(clone, "CHANGELOG.md"), "remote change\n");
yield* git(clone, ["add", "CHANGELOG.md"]);
yield* git(clone, ["commit", "-m", "remote update"]);
yield* git(clone, ["push", "origin", initialBranch]);
const core = yield* GitCore;
const details = yield* core.statusDetails(source);
expect(details.branch).toBe(initialBranch);
expect(details.aheadCount).toBe(0);
expect(details.behindCount).toBe(1);
}),
const core = yield* GitCore;
const details = yield* core.statusDetails(source);
expect(details.branch).toBe(initialBranch);
expect(details.aheadCount).toBe(0);
expect(details.behindCount).toBe(1);
}),
);
it.effect("prepares commit context by auto-staging and creates commit", () =>
effect("prepares commit context by auto-staging and creates commit", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -2108,7 +2101,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("prepareCommitContext stages only selected files when filePaths provided", () =>
effect("prepareCommitContext stages only selected files when filePaths provided", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -2131,7 +2124,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("prepareCommitContext stages everything when filePaths is undefined", () =>
effect("prepareCommitContext stages everything when filePaths is undefined", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -2147,7 +2140,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("prepareCommitContext truncates oversized staged patches instead of failing", () =>
effect("prepareCommitContext truncates oversized staged patches instead of failing", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -2162,7 +2155,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("readRangeContext truncates oversized diff patches instead of failing", () =>
effect("readRangeContext truncates oversized diff patches instead of failing", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const { initialBranch } = yield* initRepoWithCommit(tmp);
@@ -2181,7 +2174,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("pushes with upstream setup and then skips when up to date", () =>
effect("pushes with upstream setup and then skips when up to date", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
@@ -2209,7 +2202,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("pulls behind branch and then reports up-to-date", () =>
effect("pulls behind branch and then reports up-to-date", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
@@ -2241,7 +2234,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("top-level pullGitBranch rejects when no upstream exists", () =>
effect("top-level pullGitBranch rejects when no upstream exists", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -2253,7 +2246,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("lists branches when recency lookup fails", () =>
effect("lists branches when recency lookup fails", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
@@ -2283,7 +2276,7 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("falls back to empty remote branch data when remote lookups fail", () =>
effect("falls back to empty remote branch data when remote lookups fail", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
+171 -170
View File
@@ -671,7 +671,14 @@ const GitManagerTestLayer = GitCoreLive.pipe(
);
it.layer(GitManagerTestLayer)("GitManager", (it) => {
it.effect("status includes PR metadata when branch already has an open PR", () =>
const LONG_EFFECT_TEST_TIMEOUT_MS = 30_000;
const effect = (
name: string,
test: Parameters<typeof it.effect>[1],
timeout = LONG_EFFECT_TEST_TIMEOUT_MS,
) => it.effect(name, test, timeout);
effect("status includes PR metadata when branch already has an open PR", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -712,7 +719,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("status trims PR metadata returned by gh before publishing it", () =>
effect("status trims PR metadata returned by gh before publishing it", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -750,7 +757,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("status ignores invalid gh pr list entries and keeps valid ones", () =>
effect("status ignores invalid gh pr list entries and keeps valid ones", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -801,7 +808,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("status preserves lowercase merged and closed PR states from gh json", () =>
effect("status preserves lowercase merged and closed PR states from gh json", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -850,7 +857,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("status returns an explicit non-repo result for non-git directories", () =>
effect("status returns an explicit non-repo result for non-git directories", () =>
Effect.gen(function* () {
const cwd = yield* makeTempDir("t3code-git-manager-non-repo-");
const { manager } = yield* makeManager();
@@ -876,7 +883,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("status returns an explicit non-repo result for deleted directories", () =>
effect("status returns an explicit non-repo result for deleted directories", () =>
Effect.gen(function* () {
const rootDir = yield* makeTempDir("t3code-git-manager-missing-dir-");
const cwd = path.join(rootDir, "deleted-repo");
@@ -905,7 +912,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("status briefly caches repeated lookups for the same cwd", () =>
effect("status briefly caches repeated lookups for the same cwd", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -936,7 +943,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect(
effect(
"status ignores unrelated fork PRs when the current branch tracks the same repository",
() =>
Effect.gen(function* () {
@@ -977,7 +984,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect(
effect(
"status detects cross-repo PRs from the upstream remote URL owner",
() =>
Effect.gen(function* () {
@@ -1039,10 +1046,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
"pr list --head jasonLaster:statemachine --state all --limit 20 --json number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
);
}),
20_000,
LONG_EFFECT_TEST_TIMEOUT_MS,
);
it.effect(
effect(
"status ignores synthetic local branch aliases when the upstream remote name contains slashes",
() =>
Effect.gen(function* () {
@@ -1147,10 +1154,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
),
).toBe(false);
}),
20_000,
LONG_EFFECT_TEST_TIMEOUT_MS,
);
it.effect("status returns merged PR state when latest PR was merged", () =>
effect("status returns merged PR state when latest PR was merged", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -1188,7 +1195,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("status prefers open PR when merged PR has newer updatedAt", () =>
effect("status prefers open PR when merged PR has newer updatedAt", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -1235,7 +1242,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("status is resilient to gh lookup failures and returns pr null", () =>
effect("status is resilient to gh lookup failures and returns pr null", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -1259,7 +1266,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("creates a commit when working tree is dirty", () =>
effect("creates a commit when working tree is dirty", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -1294,7 +1301,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("uses custom commit message when provided", () =>
effect("uses custom commit message when provided", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -1337,7 +1344,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("commits only selected files when filePaths is provided", () =>
effect("commits only selected files when filePaths is provided", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -1362,7 +1369,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("creates feature branch, commits, and pushes with featureBranch option", () =>
effect("creates feature branch, commits, and pushes with featureBranch option", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -1425,7 +1432,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("featureBranch uses custom commit message and derives branch name", () =>
effect("featureBranch uses custom commit message and derives branch name", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -1468,7 +1475,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("skips commit when there are no uncommitted changes", () =>
effect("skips commit when there are no uncommitted changes", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -1486,7 +1493,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("featureBranch returns error when worktree is clean", () =>
effect("featureBranch returns error when worktree is clean", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -1505,7 +1512,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("commits and pushes with upstream auto-setup when needed", () =>
effect("commits and pushes with upstream auto-setup when needed", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -1532,7 +1539,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect(
effect(
"pushes and creates PR from a no-upstream branch when local commits are ahead of base",
() =>
Effect.gen(function* () {
@@ -1583,7 +1590,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("skips push when branch is already up to date", () =>
effect("skips push when branch is already up to date", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -1604,7 +1611,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("pushes existing clean commits without rerunning commit logic", () =>
effect("pushes existing clean commits without rerunning commit logic", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -1632,7 +1639,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("create_pr pushes a clean branch before creating the PR when needed", () =>
effect("create_pr pushes a clean branch before creating the PR when needed", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -1678,7 +1685,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("returns existing PR metadata for commit/push/pr action", () =>
effect("returns existing PR metadata for commit/push/pr action", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -1723,7 +1730,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect(
effect(
"returns existing cross-repo PR metadata using the fork owner selector",
() =>
Effect.gen(function* () {
@@ -1778,10 +1785,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
).toBe(true);
expect(ghCalls.some((call) => call.startsWith("pr create "))).toBe(false);
}),
12_000,
LONG_EFFECT_TEST_TIMEOUT_MS,
);
it.effect(
effect(
"returns the correct existing PR when a slash remote checks out to a synthetic local alias",
() =>
Effect.gen(function* () {
@@ -1870,10 +1877,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
false,
);
}),
20_000,
LONG_EFFECT_TEST_TIMEOUT_MS,
);
it.effect(
effect(
"prefers owner-qualified selectors before bare branch names for cross-repo PRs",
() =>
Effect.gen(function* () {
@@ -1940,10 +1947,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(ownerSelectorCallIndex).toBeGreaterThanOrEqual(0);
expect(ghCalls.some((call) => call.startsWith("pr create "))).toBe(false);
}),
12_000,
LONG_EFFECT_TEST_TIMEOUT_MS,
);
it.effect(
effect(
"stops probing head selectors after finding an existing PR",
() =>
Effect.gen(function* () {
@@ -2002,10 +2009,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
"pr list --head octocat:statemachine --state open --limit 1",
);
}),
12_000,
LONG_EFFECT_TEST_TIMEOUT_MS,
);
it.effect("creates PR when one does not already exist", () =>
effect("creates PR when one does not already exist", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -2050,79 +2057,75 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect(
"creates a new PR instead of reusing an unrelated fork PR with the same head branch",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/no-fork-match"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
yield* runGit(repoDir, ["add", "changes.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/no-fork-match"]);
effect("creates a new PR instead of reusing an unrelated fork PR with the same head branch", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/no-fork-match"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "changes.txt"), "change\n");
yield* runGit(repoDir, ["add", "changes.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
yield* runGit(repoDir, ["push", "-u", "origin", "feature/no-fork-match"]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
JSON.stringify([
{
number: 1661,
title: "Fork PR with same branch name",
url: "https://github.com/pingdotgg/t3code/pull/1661",
baseRefName: "main",
headRefName: "feature/no-fork-match",
state: "OPEN",
isCrossRepository: true,
headRepository: {
nameWithOwner: "lnieuwenhuis/t3code",
},
headRepositoryOwner: {
login: "lnieuwenhuis",
},
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
JSON.stringify([
{
number: 1661,
title: "Fork PR with same branch name",
url: "https://github.com/pingdotgg/t3code/pull/1661",
baseRefName: "main",
headRefName: "feature/no-fork-match",
state: "OPEN",
isCrossRepository: true,
headRepository: {
nameWithOwner: "lnieuwenhuis/t3code",
},
]),
JSON.stringify([
{
number: 188,
title: "Add stacked git actions",
url: "https://github.com/pingdotgg/codething-mvp/pull/188",
baseRefName: "main",
headRefName: "feature/no-fork-match",
state: "OPEN",
isCrossRepository: false,
headRepositoryOwner: {
login: "lnieuwenhuis",
},
]),
],
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push_pr",
});
},
]),
JSON.stringify([
{
number: 188,
title: "Add stacked git actions",
url: "https://github.com/pingdotgg/codething-mvp/pull/188",
baseRefName: "main",
headRefName: "feature/no-fork-match",
state: "OPEN",
isCrossRepository: false,
},
]),
],
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push_pr",
});
expect(result.pr.status).toBe("created");
expect(result.pr.number).toBe(188);
expect(result.toast).toEqual({
title: "Created PR #188",
description: "Add stacked git actions",
cta: {
kind: "open_pr",
label: "View PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/188",
},
});
expect(
ghCalls.some((call) =>
call.includes("pr create --base main --head feature/no-fork-match"),
),
).toBe(true);
}),
expect(result.pr.status).toBe("created");
expect(result.pr.number).toBe(188);
expect(result.toast).toEqual({
title: "Created PR #188",
description: "Add stacked git actions",
cta: {
kind: "open_pr",
label: "View PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/188",
},
});
expect(
ghCalls.some((call) => call.includes("pr create --base main --head feature/no-fork-match")),
).toBe(true);
}),
);
it.effect("creates cross-repo PRs with the fork owner selector and default base branch", () =>
effect("creates cross-repo PRs with the fork owner selector and default base branch", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -2188,7 +2191,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("rejects push/pr actions from detached HEAD", () =>
effect("rejects push/pr actions from detached HEAD", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -2206,7 +2209,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("surfaces missing gh binary errors", () =>
effect("surfaces missing gh binary errors", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -2235,7 +2238,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("surfaces gh auth errors with guidance", () =>
effect("surfaces gh auth errors with guidance", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -2264,7 +2267,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("resolves pull requests from #number references", () =>
effect("resolves pull requests from #number references", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -2299,7 +2302,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("prepares pull request threads in local mode by checking out the PR branch", () =>
effect("prepares pull request threads in local mode by checking out the PR branch", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -2335,7 +2338,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("prepares pull request threads in worktree mode on the PR head branch", () =>
effect("prepares pull request threads in worktree mode on the PR head branch", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -2495,7 +2498,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("preserves fork upstream tracking when preparing a local PR thread", () =>
effect("preserves fork upstream tracking when preparing a local PR thread", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -2548,7 +2551,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("derives fork repository identity from PR URL when GitHub omits nameWithOwner", () =>
effect("derives fork repository identity from PR URL when GitHub omits nameWithOwner", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -2605,7 +2608,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("reuses an existing dedicated worktree for the PR head branch", () =>
effect("reuses an existing dedicated worktree for the PR head branch", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -2653,7 +2656,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect(
effect(
"does not block fork PR worktree prep when the fork head branch collides with root main",
() =>
Effect.gen(function* () {
@@ -2713,67 +2716,65 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect(
"does not overwrite an existing local main branch when preparing a fork PR worktree",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const originDir = yield* createBareRemote();
const forkDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["checkout", "-b", "fork-main-source"]);
fs.writeFileSync(path.join(repoDir, "fork-main-second.txt"), "fork main second\n");
yield* runGit(repoDir, ["add", "fork-main-second.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Fork main second branch"]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "fork-main-source:main"]);
yield* runGit(repoDir, ["checkout", "main"]);
const localMainBefore = (yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim();
yield* runGit(repoDir, ["checkout", "-b", "feature/root-branch"]);
effect("does not overwrite an existing local main branch when preparing a fork PR worktree", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const originDir = yield* createBareRemote();
const forkDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["remote", "add", "fork-seed", forkDir]);
yield* runGit(repoDir, ["checkout", "-b", "fork-main-source"]);
fs.writeFileSync(path.join(repoDir, "fork-main-second.txt"), "fork main second\n");
yield* runGit(repoDir, ["add", "fork-main-second.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Fork main second branch"]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "fork-main-source:main"]);
yield* runGit(repoDir, ["checkout", "main"]);
const localMainBefore = (yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim();
yield* runGit(repoDir, ["checkout", "-b", "feature/root-branch"]);
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 92,
title: "Fork main overwrite PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/92",
baseRefName: "main",
headRefName: "main",
state: "open",
isCrossRepository: true,
headRepositoryNameWithOwner: "octocat/codething-mvp",
headRepositoryOwnerLogin: "octocat",
},
repositoryCloneUrls: {
"octocat/codething-mvp": {
url: forkDir,
sshUrl: forkDir,
},
const { manager } = yield* makeManager({
ghScenario: {
pullRequest: {
number: 92,
title: "Fork main overwrite PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/92",
baseRefName: "main",
headRefName: "main",
state: "open",
isCrossRepository: true,
headRepositoryNameWithOwner: "octocat/codething-mvp",
headRepositoryOwnerLogin: "octocat",
},
repositoryCloneUrls: {
"octocat/codething-mvp": {
url: forkDir,
sshUrl: forkDir,
},
},
});
},
});
const result = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "92",
mode: "worktree",
});
const result = yield* preparePullRequestThread(manager, {
cwd: repoDir,
reference: "92",
mode: "worktree",
});
expect(result.branch).toBe("t3code/pr-92/main");
expect((yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim()).toBe(localMainBefore);
expect(
(yield* runGit(result.worktreePath as string, [
"rev-parse",
"--abbrev-ref",
"@{upstream}",
])).stdout.trim(),
).toBe("fork-seed/main");
}),
expect(result.branch).toBe("t3code/pr-92/main");
expect((yield* runGit(repoDir, ["rev-parse", "main"])).stdout.trim()).toBe(localMainBefore);
expect(
(yield* runGit(result.worktreePath as string, [
"rev-parse",
"--abbrev-ref",
"@{upstream}",
])).stdout.trim(),
).toBe("fork-seed/main");
}),
);
it.effect("reuses an existing PR worktree and restores fork upstream tracking", () =>
effect("reuses an existing PR worktree and restores fork upstream tracking", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -2905,7 +2906,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("emits ordered progress events for commit hooks", () =>
effect("emits ordered progress events for commit hooks", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -2968,7 +2969,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("emits action_failed when a commit hook rejects", () =>
effect("emits action_failed when a commit hook rejects", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
@@ -49,16 +49,16 @@ const makeRoutingTextGeneration = Effect.gen(function* () {
const codex = yield* CodexTextGen;
const claude = yield* ClaudeTextGen;
const cursor = yield* CursorTextGen;
const openCode = yield* OpenCodeTextGen;
const opencode = yield* OpenCodeTextGen;
const route = (provider?: TextGenerationProvider): TextGenerationShape =>
provider === "claudeAgent"
? claude
: provider === "opencode"
? openCode
: provider === "cursor"
? cursor
: codex;
const providerToService = {
codex,
claudeAgent: claude,
cursor,
opencode,
};
const route = (provider: TextGenerationProvider | "opencode") => providerToService[provider];
return {
generateCommitMessage: (input) =>
@@ -13,7 +13,7 @@ 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" | "opencode";
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor";
export interface CommitMessageGenerationInput {
cwd: string;
@@ -121,7 +121,7 @@ async function waitForThread(
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
activities: ReadonlyArray<{ kind: string }>;
}) => boolean,
timeoutMs = 15_000,
timeoutMs = 30_000,
) {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<{
@@ -146,7 +146,7 @@ async function waitForThread(
async function waitForEvent(
engine: OrchestrationEngineShape,
predicate: (event: { type: string }) => boolean,
timeoutMs = 15_000,
timeoutMs = 30_000,
) {
const deadline = Date.now() + timeoutMs;
const poll = async () => {
@@ -197,7 +197,7 @@ 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) {
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 30_000) {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<void> => {
if (gitRefExists(cwd, ref)) {
@@ -213,6 +213,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 | CheckpointStore,
unknown
@@ -371,7 +374,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 = new Date().toISOString();
@@ -541,7 +544,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: "claudeAgent",
@@ -602,7 +605,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 = new Date().toISOString();
@@ -649,7 +652,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,
@@ -686,7 +689,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,
@@ -737,7 +740,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 = new Date().toISOString();
@@ -779,7 +782,7 @@ describe("CheckpointReactor", () => {
);
});
it("continues processing runtime events after a single checkpoint runtime failure", async () => {
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-"),
);
@@ -839,7 +842,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 = new Date().toISOString();
@@ -917,7 +920,7 @@ describe("CheckpointReactor", () => {
).toBe(false);
});
it("executes provider revert and emits thread.reverted for claude sessions", async () => {
test("executes provider revert and emits thread.reverted for claude sessions", async () => {
const harness = await createHarness({ providerName: "claudeAgent" });
const createdAt = new Date().toISOString();
@@ -986,7 +989,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 = new Date().toISOString();
@@ -1069,7 +1072,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 = new Date().toISOString();
@@ -13,7 +13,7 @@ import {
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
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";
@@ -357,6 +357,59 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
it("records session lastError and clears active turn when provider turn start fails", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
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-session-error"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-session-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?.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 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();
const now = new Date().toISOString();
@@ -970,6 +1023,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 = new Date().toISOString();
@@ -1275,37 +1385,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 = new Date().toISOString();
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,
@@ -1314,19 +1417,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: {
provider: "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"),
},
});
});
@@ -1371,6 +1528,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 = new Date().toISOString();
@@ -98,7 +98,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") ||
@@ -114,7 +114,7 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = findProviderAdapterRequestError(cause);
if (error) {
if (Schema.is(ProviderAdapterRequestError)(error)) {
return error.detail.toLowerCase().includes("unknown pending user-input request");
}
return Cause.pretty(cause).toLowerCase().includes("unknown pending user-input request");
@@ -211,7 +211,7 @@ const make = Effect.gen(function* () {
? failReason.error
: undefined;
if (providerError) {
return providerError.detail;
return providerError.message;
}
return Cause.pretty(cause);
};
@@ -334,6 +334,9 @@ 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 providerChanged =
requestedModelSelection !== undefined &&
requestedModelSelection.provider !== currentProvider;
const sessionModelSwitch =
currentProvider === undefined
? "in-session"
@@ -350,15 +353,14 @@ const make = Effect.gen(function* () {
if (
!runtimeModeChanged &&
!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,
@@ -367,6 +369,7 @@ const make = Effect.gen(function* () {
currentRuntimeMode: thread.session?.runtimeMode,
desiredRuntimeMode: thread.runtimeMode,
runtimeModeChanged,
providerChanged,
modelChanged,
shouldRestartForModelChange,
shouldRestartForModelSelectionChange,
@@ -602,9 +605,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,
@@ -621,22 +621,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,
@@ -657,7 +644,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* (
@@ -10,6 +10,7 @@ import type {
} from "@t3tools/contracts";
import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { resolveApiModelId } from "@t3tools/shared/model";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import {
query as claudeQuery,
@@ -164,13 +165,50 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo
);
}
export function resolveClaudeApiModelId(modelSelection: ClaudeModelSelection): string {
switch (modelSelection.options?.contextWindow) {
case "1m":
return `${modelSelection.model}[1m]`;
default:
return modelSelection.model;
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...",
},
});
}
export function resolveClaudeApiModelId(modelSelection: ClaudeModelSelection): string {
return resolveApiModelId(modelSelection);
}
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
readonly status: Exclude<ServerProviderState, "disabled">;
@@ -820,7 +858,7 @@ export const ClaudeProviderLive = Layer.effect(
Stream.map((settings) => settings.providers.claudeAgent),
),
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
initialSnapshot: makePendingClaudeProvider,
buildInitialSnapshot: buildInitialClaudeProviderSnapshot,
checkProvider,
});
}),
@@ -12,20 +12,21 @@ import {
TurnId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { afterAll, it, vi } from "@effect/vitest";
import { it, vi } from "@effect/vitest";
import { Effect, Fiber, Layer, Option, Stream } from "effect";
import { Effect, Fiber, Layer, Option, Queue, Stream } from "effect";
import {
CodexAppServerManager,
type CodexAppServerStartSessionInput,
type CodexAppServerSendTurnInput,
} from "../../codexAppServerManager.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderAdapterValidationError } from "../Errors.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import {
type CodexSessionRuntimeOptions,
type CodexSessionRuntimeSendTurnInput,
type CodexSessionRuntimeShape,
type CodexThreadSnapshot,
} from "../codex/CodexSessionRuntime.ts";
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
@@ -33,110 +34,122 @@ const asTurnId = (value: string): TurnId => TurnId.make(value);
const asEventId = (value: string): EventId => EventId.make(value);
const asItemId = (value: string): ProviderItemId => ProviderItemId.make(value);
class FakeCodexManager extends CodexAppServerManager {
public startSessionImpl = vi.fn(
async (input: CodexAppServerStartSessionInput): Promise<ProviderSession> => {
const now = new Date().toISOString();
return {
provider: "codex",
status: "ready",
runtimeMode: input.runtimeMode,
threadId: input.threadId,
cwd: input.cwd,
createdAt: now,
updatedAt: now,
};
class FakeCodexRuntime implements CodexSessionRuntimeShape {
private readonly eventQueue = Effect.runSync(Queue.unbounded<ProviderEvent>());
private readonly now = new Date().toISOString();
public readonly startImpl = vi.fn(() =>
Promise.resolve({
provider: "codex" as const,
status: "ready" as const,
runtimeMode: this.options.runtimeMode,
threadId: this.options.threadId,
cwd: this.options.cwd,
...(this.options.model ? { model: this.options.model } : {}),
createdAt: this.now,
updatedAt: this.now,
} satisfies ProviderSession),
);
public readonly sendTurnImpl = vi.fn(
(_input: CodexSessionRuntimeSendTurnInput): Promise<ProviderTurnStartResult> =>
Promise.resolve({
threadId: this.options.threadId,
turnId: asTurnId("turn-1"),
}),
);
public readonly interruptTurnImpl = vi.fn(
(_turnId?: TurnId): Promise<void> => Promise.resolve(undefined),
);
public readonly readThreadImpl = vi.fn(
(): Promise<CodexThreadSnapshot> =>
Promise.resolve({
threadId: "provider-thread-1",
turns: [],
}),
);
public readonly rollbackThreadImpl = vi.fn(
(_numTurns: number): Promise<CodexThreadSnapshot> =>
Promise.resolve({
threadId: "provider-thread-1",
turns: [],
}),
);
public readonly respondToRequestImpl = vi.fn(
(_requestId: ApprovalRequestId, _decision: ProviderApprovalDecision): Promise<void> =>
Promise.resolve(undefined),
);
public readonly respondToUserInputImpl = vi.fn(
(_requestId: ApprovalRequestId, _answers: ProviderUserInputAnswers): Promise<void> =>
Promise.resolve(undefined),
);
public readonly closeImpl = vi.fn(() => Promise.resolve(undefined));
readonly options: CodexSessionRuntimeOptions;
constructor(options: CodexSessionRuntimeOptions) {
this.options = options;
}
start() {
return Effect.promise(() => this.startImpl());
}
getSession = Effect.promise(() => this.startImpl());
sendTurn(input: CodexSessionRuntimeSendTurnInput) {
return Effect.promise(() => this.sendTurnImpl(input));
}
interruptTurn(turnId?: TurnId) {
return Effect.promise(() => this.interruptTurnImpl(turnId));
}
readThread = Effect.promise(() => this.readThreadImpl());
rollbackThread(numTurns: number) {
return Effect.promise(() => this.rollbackThreadImpl(numTurns));
}
respondToRequest(requestId: ApprovalRequestId, decision: ProviderApprovalDecision) {
return Effect.promise(() => this.respondToRequestImpl(requestId, decision));
}
respondToUserInput(requestId: ApprovalRequestId, answers: ProviderUserInputAnswers) {
return Effect.promise(() => this.respondToUserInputImpl(requestId, answers));
}
get events() {
return Stream.fromQueue(this.eventQueue);
}
close = Effect.promise(() => this.closeImpl());
emit(event: ProviderEvent) {
return Queue.offer(this.eventQueue, event).pipe(Effect.asVoid);
}
}
function makeRuntimeFactory() {
const runtimes: Array<FakeCodexRuntime> = [];
const factory = vi.fn((options: CodexSessionRuntimeOptions) => {
const runtime = new FakeCodexRuntime(options);
runtimes.push(runtime);
return Effect.succeed(runtime);
});
return {
factory,
get lastRuntime(): FakeCodexRuntime | undefined {
return runtimes.at(-1);
},
);
public sendTurnImpl = vi.fn(
async (_input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> => ({
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-1"),
}),
);
public interruptTurnImpl = vi.fn(
async (_threadId: ThreadId, _turnId?: TurnId): Promise<void> => undefined,
);
public readThreadImpl = vi.fn(async (_threadId: ThreadId) => ({
threadId: asThreadId("thread-1"),
turns: [],
}));
public rollbackThreadImpl = vi.fn(async (_threadId: ThreadId, _numTurns: number) => ({
threadId: asThreadId("thread-1"),
turns: [],
}));
public respondToRequestImpl = vi.fn(
async (
_threadId: ThreadId,
_requestId: ApprovalRequestId,
_decision: ProviderApprovalDecision,
): Promise<void> => undefined,
);
public respondToUserInputImpl = vi.fn(
async (
_threadId: ThreadId,
_requestId: ApprovalRequestId,
_answers: ProviderUserInputAnswers,
): Promise<void> => undefined,
);
public stopAllImpl = vi.fn(() => undefined);
override startSession(input: CodexAppServerStartSessionInput): Promise<ProviderSession> {
return this.startSessionImpl(input);
}
override sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
return this.sendTurnImpl(input);
}
override interruptTurn(threadId: ThreadId, turnId?: TurnId): Promise<void> {
return this.interruptTurnImpl(threadId, turnId);
}
override readThread(threadId: ThreadId) {
return this.readThreadImpl(threadId);
}
override rollbackThread(threadId: ThreadId, numTurns: number) {
return this.rollbackThreadImpl(threadId, numTurns);
}
override respondToRequest(
threadId: ThreadId,
requestId: ApprovalRequestId,
decision: ProviderApprovalDecision,
): Promise<void> {
return this.respondToRequestImpl(threadId, requestId, decision);
}
override respondToUserInput(
threadId: ThreadId,
requestId: ApprovalRequestId,
answers: ProviderUserInputAnswers,
): Promise<void> {
return this.respondToUserInputImpl(threadId, requestId, answers);
}
override stopSession(_threadId: ThreadId): void {}
override listSessions(): ProviderSession[] {
return [];
}
override hasSession(_threadId: ThreadId): boolean {
return false;
}
override stopAll(): void {
this.stopAllImpl();
}
};
}
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
@@ -148,9 +161,9 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory
listBindings: () => Effect.succeed([]),
});
const validationManager = new FakeCodexManager();
const validationRuntimeFactory = makeRuntimeFactory();
const validationLayer = it.layer(
makeCodexAdapterLive({ manager: validationManager }).pipe(
makeCodexAdapterLive({ makeRuntime: validationRuntimeFactory.factory }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -179,12 +192,12 @@ validationLayer("CodexAdapterLive validation", (it) => {
issue: "Expected provider 'codex' but received 'claudeAgent'.",
}),
);
assert.equal(validationManager.startSessionImpl.mock.calls.length, 0);
assert.equal(validationRuntimeFactory.factory.mock.calls.length, 0);
}),
);
it.effect("maps codex model options before starting a session", () =>
Effect.gen(function* () {
validationManager.startSessionImpl.mockClear();
validationRuntimeFactory.factory.mockClear();
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
@@ -200,24 +213,21 @@ validationLayer("CodexAdapterLive validation", (it) => {
runtimeMode: "full-access",
});
assert.deepStrictEqual(validationManager.startSessionImpl.mock.calls[0]?.[0], {
provider: "codex",
threadId: asThreadId("thread-1"),
assert.deepStrictEqual(validationRuntimeFactory.factory.mock.calls[0]?.[0], {
binaryPath: "codex",
cwd: process.cwd(),
model: "gpt-5.3-codex",
serviceTier: "fast",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
});
}),
);
});
const sessionErrorManager = new FakeCodexManager();
sessionErrorManager.sendTurnImpl.mockImplementation(async () => {
throw new Error("Unknown session: sess-missing");
});
const sessionRuntimeFactory = makeRuntimeFactory();
const sessionErrorLayer = it.layer(
makeCodexAdapterLive({ manager: sessionErrorManager }).pipe(
makeCodexAdapterLive({ makeRuntime: sessionRuntimeFactory.factory }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -226,7 +236,7 @@ const sessionErrorLayer = it.layer(
);
sessionErrorLayer("CodexAdapterLive session errors", (it) => {
it.effect("maps unknown-session sendTurn errors to ProviderAdapterSessionNotFoundError", () =>
it.effect("maps missing adapter sessions to ProviderAdapterSessionNotFoundError", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const result = yield* adapter
@@ -241,14 +251,20 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
assert.equal(result.failure._tag, "ProviderAdapterSessionNotFoundError");
assert.equal(result.failure.provider, "codex");
assert.equal(result.failure.threadId, "sess-missing");
assert.equal(result.failure.cause instanceof Error, true);
}),
);
it.effect("maps codex model options before sending a turn", () =>
Effect.gen(function* () {
sessionErrorManager.sendTurnImpl.mockClear();
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
provider: "codex",
threadId: asThreadId("sess-missing"),
runtimeMode: "full-access",
});
const runtime = sessionRuntimeFactory.lastRuntime;
assert.ok(runtime);
runtime.sendTurnImpl.mockClear();
yield* Effect.ignore(
adapter.sendTurn({
@@ -266,8 +282,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
}),
);
assert.deepStrictEqual(sessionErrorManager.sendTurnImpl.mock.calls[0]?.[0], {
threadId: asThreadId("sess-missing"),
assert.deepStrictEqual(runtime.sendTurnImpl.mock.calls[0]?.[0], {
input: "hello",
model: "gpt-5.3-codex",
effort: "high",
@@ -277,9 +292,9 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
);
});
const lifecycleManager = new FakeCodexManager();
const lifecycleRuntimeFactory = makeRuntimeFactory();
const lifecycleLayer = it.layer(
makeCodexAdapterLive({ manager: lifecycleManager }).pipe(
makeCodexAdapterLive({ makeRuntime: lifecycleRuntimeFactory.factory }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
@@ -287,10 +302,24 @@ const lifecycleLayer = it.layer(
),
);
function startLifecycleRuntime() {
return Effect.gen(function* () {
const adapter = yield* CodexAdapter;
yield* adapter.startSession({
provider: "codex",
threadId: asThreadId("thread-1"),
runtimeMode: "full-access",
});
const runtime = lifecycleRuntimeFactory.lastRuntime;
assert.ok(runtime);
return { adapter, runtime };
});
}
lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("maps completed agent message items to canonical item.completed events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
const event: ProviderEvent = {
@@ -303,14 +332,17 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
turnId: asTurnId("turn-1"),
itemId: asItemId("msg_1"),
payload: {
threadId: "thread-1",
turnId: "turn-1",
item: {
type: "agentMessage",
id: "msg_1",
text: "done",
},
},
};
lifecycleManager.emit("event", event);
yield* runtime.emit(event);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
@@ -329,7 +361,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("maps completed plan items to canonical proposed-plan completion events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
const event: ProviderEvent = {
@@ -342,15 +374,17 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
turnId: asTurnId("turn-1"),
itemId: asItemId("plan_1"),
payload: {
threadId: "thread-1",
turnId: "turn-1",
item: {
type: "Plan",
type: "plan",
id: "plan_1",
text: "## Final plan\n\n- one\n- two",
},
},
};
lifecycleManager.emit("event", event);
yield* runtime.emit(event);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
@@ -368,10 +402,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("maps plan deltas to canonical proposed-plan delta events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
lifecycleManager.emit("event", {
yield* runtime.emit({
id: asEventId("evt-plan-delta"),
kind: "notification",
provider: "codex",
@@ -381,6 +415,9 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
turnId: asTurnId("turn-1"),
itemId: asItemId("plan_1"),
payload: {
threadId: "thread-1",
turnId: "turn-1",
itemId: "plan_1",
delta: "## Final plan",
},
} satisfies ProviderEvent);
@@ -402,7 +439,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("maps session/closed lifecycle events to canonical session.exited runtime events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
const event: ProviderEvent = {
@@ -415,7 +452,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
message: "Session stopped",
};
lifecycleManager.emit("event", event);
yield* runtime.emit(event);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
@@ -433,10 +470,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("maps retryable Codex error notifications to runtime.warning", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
lifecycleManager.emit("event", {
yield* runtime.emit({
id: asEventId("evt-retryable-error"),
kind: "notification",
provider: "codex",
@@ -445,6 +482,8 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
method: "error",
turnId: asTurnId("turn-1"),
payload: {
threadId: "thread-1",
turnId: "turn-1",
error: {
message: "Reconnecting... 2/5",
},
@@ -469,10 +508,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("maps process stderr notifications to runtime.warning", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
lifecycleManager.emit("event", {
yield* runtime.emit({
id: asEventId("evt-process-stderr"),
kind: "notification",
provider: "codex",
@@ -503,10 +542,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("maps fatal websocket stderr notifications to runtime.error", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
lifecycleManager.emit("event", {
yield* runtime.emit({
id: asEventId("evt-process-stderr-websocket"),
kind: "notification",
provider: "codex",
@@ -539,7 +578,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("preserves request type when mapping serverRequest/resolved", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
const event: ProviderEvent = {
@@ -549,16 +588,15 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "serverRequest/resolved",
requestKind: "command",
requestId: ApprovalRequestId.make("req-1"),
payload: {
request: {
method: "item/commandExecution/requestApproval",
},
decision: "accept",
threadId: "thread-1",
requestId: "req-1",
},
};
lifecycleManager.emit("event", event);
yield* runtime.emit(event);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
@@ -575,7 +613,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("preserves file-read request type when mapping serverRequest/resolved", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
const event: ProviderEvent = {
@@ -585,16 +623,15 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "serverRequest/resolved",
requestKind: "file-read",
requestId: ApprovalRequestId.make("req-file-read-1"),
payload: {
request: {
method: "item/fileRead/requestApproval",
},
decision: "accept",
threadId: "thread-1",
requestId: "req-file-read-1",
},
};
lifecycleManager.emit("event", event);
yield* runtime.emit(event);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
@@ -611,7 +648,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("preserves explicit empty multi-select user-input answers", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
const event: ProviderEvent = {
@@ -623,12 +660,14 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
method: "item/tool/requestUserInput/answered",
payload: {
answers: {
scope: [],
scope: {
answers: [],
},
},
},
};
lifecycleManager.emit("event", event);
yield* runtime.emit(event);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
@@ -647,7 +686,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
it.effect("maps windowsSandbox/setupCompleted to session state and warning on failure", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 2)).pipe(
Effect.forkChild,
);
@@ -661,12 +700,13 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
method: "windowsSandbox/setupCompleted",
message: "Sandbox setup failed",
payload: {
mode: "unelevated",
success: false,
detail: "unsupported environment",
error: "unsupported environment",
},
};
lifecycleManager.emit("event", event);
yield* runtime.emit(event);
const events = Array.from(yield* Fiber.join(eventsFiber));
assert.equal(events.length, 2);
@@ -691,12 +731,12 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
"maps requestUserInput requests and answered notifications to canonical user-input events",
() =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 2)).pipe(
Effect.forkChild,
);
lifecycleManager.emit("event", {
yield* runtime.emit({
id: asEventId("evt-user-input-requested"),
kind: "request",
provider: "codex",
@@ -705,6 +745,9 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
method: "item/tool/requestUserInput",
requestId: ApprovalRequestId.make("req-user-input-1"),
payload: {
itemId: "item-user-input-1",
threadId: "thread-1",
turnId: "turn-1",
questions: [
{
id: "sandbox_mode",
@@ -716,12 +759,11 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
description: "Allow workspace writes only",
},
],
multiSelect: true,
},
],
},
} satisfies ProviderEvent);
lifecycleManager.emit("event", {
yield* runtime.emit({
id: asEventId("evt-user-input-resolved"),
kind: "notification",
provider: "codex",
@@ -743,7 +785,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
if (events[0]?.type === "user-input.requested") {
assert.equal(events[0].requestId, "req-user-input-1");
assert.equal(events[0].payload.questions[0]?.id, "sandbox_mode");
assert.equal(events[0].payload.questions[0]?.multiSelect, true);
assert.equal(events[0].payload.questions[0]?.multiSelect, false);
}
assert.equal(events[1]?.type, "user-input.resolved");
@@ -756,168 +798,12 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
}),
);
it.effect("maps Codex task and reasoning event chunks into canonical runtime events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 5)).pipe(
Effect.forkChild,
);
lifecycleManager.emit("event", {
id: asEventId("evt-codex-task-started"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "codex/event/task_started",
payload: {
id: "turn-structured-1",
msg: {
type: "task_started",
turn_id: "turn-structured-1",
collaboration_mode_kind: "plan",
},
},
} satisfies ProviderEvent);
lifecycleManager.emit("event", {
id: asEventId("evt-codex-agent-reasoning"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "codex/event/agent_reasoning",
payload: {
id: "turn-structured-1",
msg: {
type: "agent_reasoning",
text: "Need to compare both transport layers before finalizing the plan.",
},
},
} satisfies ProviderEvent);
lifecycleManager.emit("event", {
id: asEventId("evt-codex-reasoning-delta"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "codex/event/reasoning_content_delta",
payload: {
id: "turn-structured-1",
msg: {
type: "reasoning_content_delta",
turn_id: "turn-structured-1",
item_id: "rs_reasoning_1",
delta: "**Compare** transport boundaries",
summary_index: 0,
},
},
} satisfies ProviderEvent);
lifecycleManager.emit("event", {
id: asEventId("evt-codex-task-complete"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "codex/event/task_complete",
payload: {
id: "turn-structured-1",
msg: {
type: "task_complete",
turn_id: "turn-structured-1",
last_agent_message: "<proposed_plan>\n# Ship it\n</proposed_plan>",
},
},
} satisfies ProviderEvent);
const events = Array.from(yield* Fiber.join(eventsFiber));
assert.equal(events[0]?.type, "task.started");
if (events[0]?.type === "task.started") {
assert.equal(events[0].turnId, "turn-structured-1");
assert.equal(events[0].payload.taskId, "turn-structured-1");
assert.equal(events[0].payload.taskType, "plan");
}
assert.equal(events[1]?.type, "task.progress");
if (events[1]?.type === "task.progress") {
assert.equal(events[1].payload.taskId, "turn-structured-1");
assert.equal(
events[1].payload.description,
"Need to compare both transport layers before finalizing the plan.",
);
}
assert.equal(events[2]?.type, "content.delta");
if (events[2]?.type === "content.delta") {
assert.equal(events[2].turnId, "turn-structured-1");
assert.equal(events[2].itemId, "rs_reasoning_1");
assert.equal(events[2].payload.streamKind, "reasoning_summary_text");
assert.equal(events[2].payload.summaryIndex, 0);
}
assert.equal(events[3]?.type, "task.completed");
if (events[3]?.type === "task.completed") {
assert.equal(events[3].turnId, "turn-structured-1");
assert.equal(events[3].payload.taskId, "turn-structured-1");
assert.equal(events[3].payload.summary, "<proposed_plan>\n# Ship it\n</proposed_plan>");
}
assert.equal(events[4]?.type, "turn.proposed.completed");
if (events[4]?.type === "turn.proposed.completed") {
assert.equal(events[4].turnId, "turn-structured-1");
assert.equal(events[4].payload.planMarkdown, "# Ship it");
}
}),
);
it.effect("prefers manager-assigned turn ids for Codex task events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
lifecycleManager.emit("event", {
id: asEventId("evt-codex-task-started-parent-turn"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-parent"),
createdAt: new Date().toISOString(),
method: "codex/event/task_started",
payload: {
id: "turn-child",
msg: {
type: "task_started",
turn_id: "turn-child",
collaboration_mode_kind: "default",
},
conversationId: "child-provider-thread",
},
} satisfies ProviderEvent);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
if (firstEvent._tag !== "Some") {
return;
}
assert.equal(firstEvent.value.type, "task.started");
if (firstEvent.value.type !== "task.started") {
return;
}
assert.equal(firstEvent.value.turnId, "turn-parent");
assert.equal(firstEvent.value.providerRefs?.providerTurnId, "turn-parent");
assert.equal(firstEvent.value.payload.taskId, "turn-child");
}),
);
it.effect("unwraps Codex token usage payloads for context window events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const { adapter, runtime } = yield* startLifecycleRuntime();
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
lifecycleManager.emit("event", {
yield* runtime.emit({
id: asEventId("evt-codex-thread-token-usage-updated"),
kind: "notification",
provider: "codex",
@@ -976,10 +862,3 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
}),
);
});
afterAll(() => {
if (lifecycleManager.stopAllImpl.mock.calls.length === 0) {
lifecycleManager.stopAll();
}
assert.ok(lifecycleManager.stopAllImpl.mock.calls.length >= 1);
});
File diff suppressed because it is too large. Load diff
+104 -176
View File
@@ -1,15 +1,14 @@
import * as OS from "node:os";
import type {
ModelCapabilities,
CodexSettings,
ServerProvider,
ServerProviderModel,
ServerProviderAuth,
ServerProviderSkill,
ServerProviderState,
} from "@t3tools/contracts";
import {
Cache,
Data,
Duration,
Effect,
Equal,
@@ -45,137 +44,61 @@ import {
codexAuthSubType,
type CodexAccountSnapshot,
} from "../codexAccount.ts";
import { probeCodexDiscovery } from "../codexAppServer.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 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: [],
};
const PROVIDER = "codex" as const;
const OPENAI_AUTH_PROVIDERS = new Set(["openai"]);
const BUILT_IN_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_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ??
DEFAULT_CODEX_MODEL_CAPABILITIES
class CodexDiscoveryCacheKey extends Data.Class<{
readonly binaryPath: string;
readonly homePath?: string;
readonly cwd: string;
}> {}
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...",
},
});
}
export function parseAuthStatusFromOutput(result: CommandResult): {
@@ -307,7 +230,7 @@ const probeCodexCapabilities = (input: {
readonly homePath?: string;
readonly cwd: string;
}) =>
Effect.tryPromise((signal) => probeCodexDiscovery({ ...input, signal })).pipe(
probeCodexDiscovery(input).pipe(
Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
Effect.result,
Effect.map((result) => {
@@ -355,7 +278,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
BUILT_IN_CODEX_MODELS,
PROVIDER,
codexSettings.customModels,
DEFAULT_CODEX_MODEL_CAPABILITIES,
@@ -552,46 +475,52 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
});
});
const makePendingCodexProvider = (codexSettings: CodexSettings): ServerProvider => {
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
codexSettings.customModels,
DEFAULT_CODEX_MODEL_CAPABILITIES,
);
const applyCodexDiscoverySnapshot = (
snapshot: ServerProvider,
discovery: CodexDiscoverySnapshot,
): ServerProvider => {
const authType = codexAuthSubType(discovery.account);
const authLabel = codexAuthSubLabel(discovery.account);
if (!codexSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
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,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Codex provider status has not been checked in this session yet.",
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* () {
@@ -602,8 +531,8 @@ export const CodexProviderLive = Layer.effect(
const accountProbeCache = yield* Cache.make({
capacity: 4,
timeToLive: Duration.minutes(5),
lookup: (key: string) => {
const [binaryPath, homePath, cwd] = JSON.parse(key) as [string, string | undefined, string];
lookup: (key: CodexDiscoveryCacheKey) => {
const { binaryPath, homePath, cwd } = key;
return probeCodexCapabilities({
binaryPath,
cwd,
@@ -616,17 +545,9 @@ export const CodexProviderLive = Layer.effect(
readonly binaryPath: string;
readonly homePath?: string;
readonly cwd: string;
}) =>
Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath, input.cwd]));
}) => Cache.get(accountProbeCache, new CodexDiscoveryCacheKey(input));
const checkProvider = checkCodexProviderStatus(
(input) =>
getDiscovery({
...input,
cwd: process.cwd(),
}).pipe(Effect.map((discovery) => discovery?.account)),
(input) => getDiscovery(input).pipe(Effect.map((discovery) => discovery?.skills)),
).pipe(
const checkProvider = checkCodexProviderStatus().pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
@@ -642,8 +563,15 @@ export const CodexProviderLive = Layer.effect(
Stream.map((settings) => settings.providers.codex),
),
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
initialSnapshot: makePendingCodexProvider,
buildInitialSnapshot: buildInitialCodexProviderSnapshot,
checkProvider,
enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
enrichCodexSnapshotViaDiscovery({
settings,
snapshot,
publishSnapshot,
getDiscovery,
}),
});
}),
);
@@ -18,10 +18,7 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
const bunExe = "bun";
async function makeMockAgentWrapper(
extraEnv?: Record<string, string>,
options?: { initialDelaySeconds?: number },
) {
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 ?? {})
@@ -29,7 +26,6 @@ async function makeMockAgentWrapper(
.join("\n");
const script = `#!/bin/sh
${envExports}
${options?.initialDelaySeconds ? `sleep ${JSON.stringify(String(options.initialDelaySeconds))}` : ""}
exec ${JSON.stringify(bunExe)} ${JSON.stringify(mockAgentPath)} "$@"
`;
await writeFile(wrapperPath, script, "utf8");
@@ -77,19 +73,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 readFile(filePath, "utf8");
if (raw.trim().length > 0) {
return raw;
}
} catch {}
await new Promise((resolve) => setTimeout(resolve, 50));
}
throw new Error(`Timed out waiting for file content at ${filePath}`);
}
const cursorAdapterTestLayer = it.layer(
makeCursorAdapterLive().pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
@@ -185,90 +168,6 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
}),
);
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(() =>
mkdtemp(path.join(os.tmpdir(), "cursor-adapter-exit-log-")),
);
const exitLogPath = path.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: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "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(() =>
mkdtemp(path.join(os.tmpdir(), "cursor-adapter-concurrent-exit-log-")),
);
const exitLogPath = path.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: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "cursor", model: "default" },
}),
adapter.startSession({
threadId,
provider: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "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;
@@ -316,14 +215,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,
@@ -339,80 +236,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(() => mkdtemp(path.join(os.tmpdir(), "cursor-acp-")));
const requestLogPath = path.join(tempDir, "requests.ndjson");
const argvLogPath = path.join(tempDir, "argv.txt");
yield* Effect.promise(() => writeFile(requestLogPath, "", "utf8"));
const wrapperPath = yield* Effect.promise(() =>
makeProbeWrapper(requestLogPath, argvLogPath),
);
yield* serverSettings.updateSettings({
providers: { cursor: { binaryPath: wrapperPath } },
});
const modelSelection = {
provider: "cursor" as const,
model: "gpt-5.4",
options: {
reasoning: "xhigh" as const,
contextWindow: "1m",
fastMode: true,
},
};
yield* adapter.startSession({
threadId,
provider: "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",
() =>
@@ -974,92 +797,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: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "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: "cursor",
cwd: process.cwd(),
runtimeMode: "full-access",
modelSelection: { provider: "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;
+363 -478
View File
@@ -7,7 +7,6 @@ import * as nodePath from "node:path";
import {
ApprovalRequestId,
type CursorModelOptions,
EventId,
type ProviderApprovalDecision,
type ProviderInteractionMode,
@@ -23,17 +22,12 @@ import {
DateTime,
Deferred,
Effect,
Exit,
Fiber,
FileSystem,
Layer,
Option,
PubSub,
Queue,
Random,
Scope,
Semaphore,
Stream,
SynchronizedRef,
} from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import type * as EffectAcpSchema from "effect-acp/schema";
@@ -99,7 +93,6 @@ interface PendingUserInput {
interface CursorSessionContext {
readonly threadId: ThreadId;
session: ProviderSession;
readonly scope: Scope.Closeable;
readonly acp: AcpSessionRuntimeShape;
notificationFiber: Fiber.Fiber<void, never> | undefined;
readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;
@@ -215,55 +208,6 @@ function resolveRequestedModeId(input: {
);
}
function applyRequestedSessionConfiguration<E>(input: {
readonly runtime: AcpSessionRuntimeShape;
readonly runtimeMode: RuntimeMode;
readonly interactionMode: ProviderInteractionMode | undefined;
readonly modelSelection:
| {
readonly model: string;
readonly options?: CursorModelOptions | null | undefined;
}
| undefined;
readonly mapError: (context: {
readonly cause: import("effect-acp/errors").AcpError;
readonly method: "session/set_config_option" | "session/set_mode";
}) => E;
}): Effect.Effect<void, E> {
return Effect.gen(function* () {
if (input.modelSelection) {
yield* applyCursorAcpModelSelection({
runtime: input.runtime,
model: input.modelSelection.model,
modelOptions: input.modelSelection.options,
mapError: ({ cause }) =>
input.mapError({
cause,
method: "session/set_config_option",
}),
});
}
const requestedModeId = resolveRequestedModeId({
interactionMode: input.interactionMode,
runtimeMode: input.runtimeMode,
modeState: yield* input.runtime.getModeState,
});
if (!requestedModeId) {
return;
}
yield* input.runtime.setMode(requestedModeId).pipe(
Effect.mapError((cause) =>
input.mapError({
cause,
method: "session/set_mode",
}),
),
);
});
}
function selectAutoApprovedPermissionOption(
request: EffectAcpSchema.RequestPermissionRequest,
): string | undefined {
@@ -293,40 +237,16 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
stream: "native",
})
: undefined);
const managedNativeEventLogger =
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
const sessions = new Map<ThreadId, CursorSessionContext>();
const threadLocksRef = yield* SynchronizedRef.make(new Map<string, Semaphore.Semaphore>());
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.make(id));
const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });
const offerRuntimeEvent = (event: ProviderRuntimeEvent) =>
PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid);
const getThreadSemaphore = (threadId: string) =>
SynchronizedRef.modifyEffect(threadLocksRef, (current) => {
const existing: Option.Option<Semaphore.Semaphore> = Option.fromNullishOr(
current.get(threadId),
);
return Option.match(existing, {
onNone: () =>
Semaphore.make(1).pipe(
Effect.map((semaphore) => {
const next = new Map(current);
next.set(threadId, semaphore);
return [semaphore, next] as const;
}),
),
onSome: (semaphore) => Effect.succeed([semaphore, current] as const),
});
});
const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>
Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));
Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid);
const logNative = (
threadId: ThreadId,
@@ -408,7 +328,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
if (ctx.notificationFiber) {
yield* Fiber.interrupt(ctx.notificationFiber);
}
yield* Effect.ignore(Scope.close(ctx.scope, Exit.void));
yield* Effect.ignore(ctx.acp.close);
sessions.delete(ctx.threadId);
yield* offerRuntimeEvent({
type: "session.exited",
@@ -420,395 +340,355 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
});
const startSession: CursorAdapterShape["startSession"] = (input) =>
withThreadLock(
input.threadId,
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}'.`,
});
}
if (!input.cwd?.trim()) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "startSession",
issue: "cwd is required and must be non-empty.",
});
}
const cwd = nodePath.resolve(input.cwd.trim());
const cursorModelSelection =
input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined;
const existing = sessions.get(input.threadId);
if (existing && !existing.stopped) {
yield* stopSessionInternal(existing);
}
const cursorSettings = yield* serverSettingsService.getSettings.pipe(
Effect.map((settings) => settings.providers.cursor),
Effect.mapError(
(error) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: error.message,
cause: error,
}),
),
);
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
const sessionScope = yield* Scope.make("sequential");
let sessionScopeTransferred = false;
yield* Effect.addFinalizer(() =>
sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void),
);
let ctx!: CursorSessionContext;
const resumeSessionId = parseCursorResume(input.resumeCursor)?.sessionId;
const acpNativeLoggers = makeAcpNativeLoggers({
nativeEventLogger,
Effect.gen(function* () {
if (input.provider !== undefined && input.provider !== PROVIDER) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
threadId: input.threadId,
operation: "startSession",
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
});
}
if (!input.cwd?.trim()) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "startSession",
issue: "cwd is required and must be non-empty.",
});
}
const acp = yield* makeCursorAcpRuntime({
cursorSettings,
childProcessSpawner,
cwd,
...(resumeSessionId ? { resumeSessionId } : {}),
clientInfo: { name: "t3-code", version: "0.0.0" },
...acpNativeLoggers,
}).pipe(
Effect.provideService(Scope.Scope, sessionScope),
Effect.mapError(
(cause) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: cause.message,
cause,
}),
),
const cwd = nodePath.resolve(input.cwd.trim());
const cursorModelSelection =
input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined;
const existing = sessions.get(input.threadId);
if (existing && !existing.stopped) {
yield* stopSessionInternal(existing);
}
const cursorSettings = yield* serverSettingsService.getSettings.pipe(
Effect.map((settings) => settings.providers.cursor),
Effect.mapError(
(error) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: error.message,
cause: error,
}),
),
);
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
let ctx!: CursorSessionContext;
const resumeSessionId = parseCursorResume(input.resumeCursor)?.sessionId;
const acpNativeLoggers = makeAcpNativeLoggers({
nativeEventLogger,
provider: PROVIDER,
threadId: input.threadId,
});
const acp = yield* makeCursorAcpRuntime({
cursorSettings,
childProcessSpawner,
cwd,
...(resumeSessionId ? { resumeSessionId } : {}),
clientInfo: { name: "t3-code", version: "0.0.0" },
...acpNativeLoggers,
}).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: cause.message,
cause,
}),
),
);
const started = yield* Effect.gen(function* () {
yield* acp.handleExtRequest("cursor/ask_question", CursorAskQuestionRequest, (params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/ask_question",
params,
"acp.cursor.extension",
);
const requestId = ApprovalRequestId.make(crypto.randomUUID());
const runtimeRequestId = RuntimeRequestId.make(requestId);
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
pendingUserInputs.set(requestId, { answers });
yield* offerRuntimeEvent({
type: "user-input.requested",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
payload: { questions: extractAskQuestions(params) },
raw: {
source: "acp.cursor.extension",
method: "cursor/ask_question",
payload: params,
},
});
const resolved = yield* Deferred.await(answers);
pendingUserInputs.delete(requestId);
yield* offerRuntimeEvent({
type: "user-input.resolved",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
payload: { answers: resolved },
});
return { answers: resolved };
}),
);
const started = yield* Effect.gen(function* () {
yield* acp.handleExtRequest("cursor/ask_question", CursorAskQuestionRequest, (params) =>
yield* acp.handleExtRequest("cursor/create_plan", CursorCreatePlanRequest, (params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/create_plan",
params,
"acp.cursor.extension",
);
yield* offerRuntimeEvent({
type: "turn.proposed.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
payload: { planMarkdown: extractPlanMarkdown(params) },
raw: {
source: "acp.cursor.extension",
method: "cursor/create_plan",
payload: params,
},
});
return { accepted: true } as const;
}),
);
yield* acp.handleExtNotification(
"cursor/update_todos",
CursorUpdateTodosRequest,
(params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/ask_question",
"cursor/update_todos",
params,
"acp.cursor.extension",
);
const requestId = ApprovalRequestId.make(crypto.randomUUID());
const runtimeRequestId = RuntimeRequestId.make(requestId);
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
pendingUserInputs.set(requestId, { answers });
yield* offerRuntimeEvent({
type: "user-input.requested",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
payload: { questions: extractAskQuestions(params) },
raw: {
source: "acp.cursor.extension",
method: "cursor/ask_question",
payload: params,
},
});
const resolved = yield* Deferred.await(answers);
pendingUserInputs.delete(requestId);
yield* offerRuntimeEvent({
type: "user-input.resolved",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
payload: { answers: resolved },
});
return { answers: resolved };
}),
);
yield* acp.handleExtRequest("cursor/create_plan", CursorCreatePlanRequest, (params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/create_plan",
params,
"acp.cursor.extension",
);
yield* offerRuntimeEvent({
type: "turn.proposed.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
payload: { planMarkdown: extractPlanMarkdown(params) },
raw: {
source: "acp.cursor.extension",
method: "cursor/create_plan",
payload: params,
},
});
return { accepted: true } as const;
}),
);
yield* acp.handleExtNotification(
"cursor/update_todos",
CursorUpdateTodosRequest,
(params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/update_todos",
if (ctx) {
yield* emitPlanUpdate(
ctx,
extractTodosAsPlan(params),
params,
"acp.cursor.extension",
"cursor/update_todos",
);
if (ctx) {
yield* emitPlanUpdate(
ctx,
extractTodosAsPlan(params),
params,
"acp.cursor.extension",
"cursor/update_todos",
);
}
}),
);
yield* acp.handleRequestPermission((params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"session/request_permission",
params,
"acp.jsonrpc",
);
if (input.runtimeMode === "full-access") {
const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);
if (autoApprovedOptionId !== undefined) {
return {
outcome: {
outcome: "selected" as const,
optionId: autoApprovedOptionId,
},
};
}
}
const permissionRequest = parsePermissionRequest(params);
const requestId = ApprovalRequestId.make(crypto.randomUUID());
const runtimeRequestId = RuntimeRequestId.make(requestId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
pendingApprovals.set(requestId, {
decision,
kind: permissionRequest.kind,
});
yield* offerRuntimeEvent(
makeAcpRequestOpenedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
detail: permissionRequest.detail ?? JSON.stringify(params).slice(0, 2000),
args: params,
source: "acp.jsonrpc",
method: "session/request_permission",
rawPayload: params,
}),
);
const resolved = yield* Deferred.await(decision);
pendingApprovals.delete(requestId);
yield* offerRuntimeEvent(
makeAcpRequestResolvedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
decision: resolved,
}),
);
return {
outcome:
resolved === "cancel"
? ({ outcome: "cancelled" } as const)
: {
outcome: "selected" as const,
optionId: acpPermissionOutcome(resolved),
},
};
}),
);
return yield* acp.start();
}).pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/start", error),
),
);
yield* applyRequestedSessionConfiguration({
runtime: acp,
runtimeMode: input.runtimeMode,
interactionMode: undefined,
modelSelection: cursorModelSelection,
mapError: ({ cause, method }) =>
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
});
const now = yield* nowIso;
const session: ProviderSession = {
provider: PROVIDER,
status: "ready",
runtimeMode: input.runtimeMode,
cwd,
model: cursorModelSelection?.model,
threadId: input.threadId,
resumeCursor: {
schemaVersion: CURSOR_RESUME_VERSION,
sessionId: started.sessionId,
},
createdAt: now,
updatedAt: now,
};
ctx = {
threadId: input.threadId,
session,
scope: sessionScope,
acp,
notificationFiber: undefined,
pendingApprovals,
pendingUserInputs,
turns: [],
lastPlanFingerprint: undefined,
activeTurnId: undefined,
stopped: false,
};
const nf = yield* Stream.runDrain(
Stream.mapEffect(acp.getEvents(), (event) =>
Effect.gen(function* () {
switch (event._tag) {
case "ModeChanged":
return;
case "AssistantItemStarted":
yield* offerRuntimeEvent(
makeAcpAssistantItemEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
itemId: event.itemId,
lifecycle: "item.started",
}),
);
return;
case "AssistantItemCompleted":
yield* offerRuntimeEvent(
makeAcpAssistantItemEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
itemId: event.itemId,
lifecycle: "item.completed",
}),
);
return;
case "PlanUpdated":
yield* logNative(
ctx.threadId,
"session/update",
event.rawPayload,
"acp.jsonrpc",
);
yield* emitPlanUpdate(
ctx,
event.payload,
event.rawPayload,
"acp.jsonrpc",
"session/update",
);
return;
case "ToolCallUpdated":
yield* logNative(
ctx.threadId,
"session/update",
event.rawPayload,
"acp.jsonrpc",
);
yield* offerRuntimeEvent(
makeAcpToolCallEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
toolCall: event.toolCall,
rawPayload: event.rawPayload,
}),
);
return;
case "ContentDelta":
yield* logNative(
ctx.threadId,
"session/update",
event.rawPayload,
"acp.jsonrpc",
);
yield* offerRuntimeEvent(
makeAcpContentDeltaEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
...(event.itemId ? { itemId: event.itemId } : {}),
text: event.text,
rawPayload: event.rawPayload,
}),
);
return;
yield* acp.handleRequestPermission((params) =>
Effect.gen(function* () {
yield* logNative(input.threadId, "session/request_permission", params, "acp.jsonrpc");
if (ctx?.session.runtimeMode === "full-access") {
const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);
if (autoApprovedOptionId !== undefined) {
return {
outcome: {
outcome: "selected" as const,
optionId: autoApprovedOptionId,
},
};
}
}),
),
).pipe(Effect.forkChild);
}
const permissionRequest = parsePermissionRequest(params);
const requestId = ApprovalRequestId.make(crypto.randomUUID());
const runtimeRequestId = RuntimeRequestId.make(requestId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
pendingApprovals.set(requestId, {
decision,
kind: permissionRequest.kind,
});
yield* offerRuntimeEvent(
makeAcpRequestOpenedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
detail: permissionRequest.detail ?? JSON.stringify(params).slice(0, 2000),
args: params,
source: "acp.jsonrpc",
method: "session/request_permission",
rawPayload: params,
}),
);
const resolved = yield* Deferred.await(decision);
pendingApprovals.delete(requestId);
yield* offerRuntimeEvent(
makeAcpRequestResolvedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
decision: resolved,
}),
);
return {
outcome:
resolved === "cancel"
? ({ outcome: "cancelled" } as const)
: {
outcome: "selected" as const,
optionId: acpPermissionOutcome(resolved),
},
};
}),
);
return yield* acp.start();
}).pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/start", error),
),
);
ctx.notificationFiber = nf;
sessions.set(input.threadId, ctx);
sessionScopeTransferred = true;
const now = yield* nowIso;
const session: ProviderSession = {
provider: PROVIDER,
status: "ready",
runtimeMode: input.runtimeMode,
cwd,
model: cursorModelSelection?.model,
threadId: input.threadId,
resumeCursor: {
schemaVersion: CURSOR_RESUME_VERSION,
sessionId: started.sessionId,
},
createdAt: now,
updatedAt: now,
};
yield* offerRuntimeEvent({
type: "session.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { resume: started.initializeResult },
});
yield* offerRuntimeEvent({
type: "session.state.changed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { state: "ready", reason: "Cursor ACP session ready" },
});
yield* offerRuntimeEvent({
type: "thread.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { providerThreadId: started.sessionId },
});
ctx = {
threadId: input.threadId,
session,
acp,
notificationFiber: undefined,
pendingApprovals,
pendingUserInputs,
turns: [],
lastPlanFingerprint: undefined,
activeTurnId: undefined,
stopped: false,
};
return session;
}).pipe(Effect.scoped),
);
const nf = yield* Stream.runDrain(
Stream.mapEffect(acp.events, (event) =>
Effect.gen(function* () {
switch (event._tag) {
case "ModeChanged":
return;
case "AssistantItemStarted":
yield* offerRuntimeEvent(
makeAcpAssistantItemEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
itemId: event.itemId,
lifecycle: "item.started",
}),
);
return;
case "AssistantItemCompleted":
yield* offerRuntimeEvent(
makeAcpAssistantItemEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
itemId: event.itemId,
lifecycle: "item.completed",
}),
);
return;
case "PlanUpdated":
yield* logNative(ctx.threadId, "session/update", event.rawPayload, "acp.jsonrpc");
yield* emitPlanUpdate(
ctx,
event.payload,
event.rawPayload,
"acp.jsonrpc",
"session/update",
);
return;
case "ToolCallUpdated":
yield* logNative(ctx.threadId, "session/update", event.rawPayload, "acp.jsonrpc");
yield* offerRuntimeEvent(
makeAcpToolCallEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
toolCall: event.toolCall,
rawPayload: event.rawPayload,
}),
);
return;
case "ContentDelta":
yield* logNative(ctx.threadId, "session/update", event.rawPayload, "acp.jsonrpc");
yield* offerRuntimeEvent(
makeAcpContentDeltaEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: ctx.threadId,
turnId: ctx.activeTurnId,
...(event.itemId ? { itemId: event.itemId } : {}),
text: event.text,
rawPayload: event.rawPayload,
}),
);
return;
}
}),
),
).pipe(Effect.forkChild);
ctx.notificationFiber = nf;
sessions.set(input.threadId, ctx);
yield* offerRuntimeEvent({
type: "session.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { resume: started.initializeResult },
});
yield* offerRuntimeEvent({
type: "session.state.changed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { state: "ready", reason: "Cursor ACP session ready" },
});
yield* offerRuntimeEvent({
type: "thread.started",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
payload: { providerThreadId: started.sessionId },
});
return session;
});
const sendTurn: CursorAdapterShape["sendTurn"] = (input) =>
Effect.gen(function* () {
@@ -818,19 +698,12 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
input.modelSelection?.provider === "cursor" ? input.modelSelection : undefined;
const model = turnModelSelection?.model ?? ctx.session.model;
const resolvedModel = resolveCursorAcpBaseModelId(model);
yield* applyRequestedSessionConfiguration({
yield* applyCursorAcpModelSelection({
runtime: ctx.acp,
runtimeMode: ctx.session.runtimeMode,
interactionMode: input.interactionMode,
modelSelection:
model === undefined
? undefined
: {
model,
options: turnModelSelection?.options,
},
mapError: ({ cause, method }) =>
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
model,
modelOptions: turnModelSelection?.options,
mapError: ({ cause }) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_config_option", cause),
});
ctx.activeTurnId = turnId;
ctx.lastPlanFingerprint = undefined;
@@ -840,6 +713,23 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
updatedAt: yield* nowIso,
};
const requestedModeId = resolveRequestedModeId({
interactionMode: input.interactionMode,
runtimeMode: ctx.session.runtimeMode,
modeState: yield* ctx.acp.getModeState,
});
if (requestedModeId) {
yield* Effect.ignore(
ctx.acp
.setMode(requestedModeId)
.pipe(
Effect.mapError((error) =>
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_mode", error),
),
),
);
}
yield* offerRuntimeEvent({
type: "turn.started",
...(yield* makeEventStamp()),
@@ -934,7 +824,6 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);
yield* Effect.ignore(
ctx.acp.cancel.pipe(
Effect.mapError((error) =>
@@ -1002,13 +891,10 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
});
const stopSession: CursorAdapterShape["stopSession"] = (threadId) =>
withThreadLock(
threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
yield* stopSessionInternal(ctx);
}),
);
Effect.gen(function* () {
const ctx = yield* requireSession(threadId);
yield* stopSessionInternal(ctx);
});
const listSessions: CursorAdapterShape["listSessions"] = () =>
Effect.sync(() => Array.from(sessions.values(), (c) => ({ ...c.session })));
@@ -1024,13 +910,10 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
yield* Effect.addFinalizer(() =>
Effect.forEach(sessions.values(), stopSessionInternal, { discard: true }).pipe(
Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)),
Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
Effect.tap(() => Queue.shutdown(runtimeEventQueue)),
),
);
const streamEvents = Stream.fromPubSub(runtimeEventPubSub);
return {
provider: PROVIDER,
capabilities: { sessionModelSwitch: "in-session" },
@@ -1045,7 +928,9 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
listSessions,
hasSession,
stopAll,
streamEvents,
get streamEvents() {
return Stream.fromQueue(runtimeEventQueue);
},
} satisfies CursorAdapterShape;
});
}
@@ -1,20 +1,9 @@
import * as path from "node:path";
import * as os from "node:os";
import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect } from "effect";
import { describe, expect, it } from "vitest";
import type * as EffectAcpSchema from "effect-acp/schema";
import type { CursorSettings, ServerProviderModel } from "@t3tools/contracts";
import {
buildCursorProviderSnapshot,
buildCursorCapabilitiesFromConfigOptions,
buildCursorDiscoveredModelsFromConfigOptions,
discoverCursorModelCapabilitiesViaAcp,
discoverCursorModelsViaAcp,
getCursorFallbackModels,
getCursorParameterizedModelPickerUnsupportedMessage,
parseCursorAboutOutput,
@@ -24,37 +13,6 @@ import {
resolveCursorAcpConfigUpdates,
} from "./CursorProvider.ts";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {
const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-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}
exec ${JSON.stringify("bun")} ${JSON.stringify(mockAgentPath)} "$@"
`;
await writeFile(wrapperPath, script, "utf8");
await chmod(wrapperPath, 0o755);
return wrapperPath;
}
async function waitForFileContent(filePath: string, attempts = 40): Promise<string> {
for (let attempt = 0; attempt < attempts; attempt += 1) {
try {
const content = await readFile(filePath, "utf8");
if (content.trim().length > 0) {
return content;
}
} catch {}
await new Promise((resolve) => setTimeout(resolve, 50));
}
throw new Error(`Timed out waiting for file content at ${filePath}`);
}
const parameterizedGpt54ConfigOptions = [
{
type: "select",
@@ -132,64 +90,6 @@ const parameterizedClaudeConfigOptions = [
},
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
const parameterizedClaudeModelOptionConfigOptions = [
{
type: "select",
currentValue: "claude-opus-4-6",
options: [{ name: "Opus 4.6", value: "claude-opus-4-6" }],
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",
},
{
type: "select",
currentValue: "true",
options: [
{ name: "Off", value: "false" },
{ name: "Fast", value: "true" },
],
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",
},
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
const sessionNewCursorConfigOptions = [
{
type: "select",
@@ -232,21 +132,6 @@ const sessionNewCursorConfigOptions = [
},
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
const baseCursorSettings: CursorSettings = {
enabled: true,
binaryPath: "agent",
apiEndpoint: "",
customModels: [],
};
const emptyCapabilities = {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
} as const;
describe("getCursorFallbackModels", () => {
it("does not publish any built-in cursor models before ACP discovery", () => {
expect(
@@ -257,56 +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: "Cursor ACP model discovery failed. Check server logs for details.",
}),
).toMatchObject({
status: "error",
message:
"Cursor Agent is not authenticated. Run `agent login` and try again. Cursor ACP model discovery failed. Check server logs for details.",
models: [
{
slug: "claude-sonnet-4-6",
isCustom: true,
},
],
});
});
});
describe("buildCursorCapabilitiesFromConfigOptions", () => {
it("derives model capabilities from parameterized Cursor ACP config options", () => {
expect(buildCursorCapabilitiesFromConfigOptions(parameterizedGpt54ConfigOptions)).toEqual({
@@ -339,23 +174,6 @@ describe("buildCursorCapabilitiesFromConfigOptions", () => {
promptInjectedEffortLevels: [],
});
});
it("prefers the newer model_option effort control over legacy thought_level", () => {
expect(
buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeModelOptionConfigOptions),
).toEqual({
reasoningEffortLevels: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High" },
{ value: "max", label: "Max", isDefault: true },
],
supportsFastMode: true,
supportsThinkingToggle: true,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
});
});
});
describe("buildCursorDiscoveredModelsFromConfigOptions", () => {
@@ -437,91 +255,6 @@ describe("buildCursorDiscoveredModelsFromConfigOptions", () => {
});
});
describe("discoverCursorModelsViaAcp", () => {
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
const wrapperPath = await makeMockAgentWrapper();
const models = await Effect.runPromise(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}).pipe(Effect.provide(NodeServices.layer), 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 tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-exit-log-"));
const exitLogPath = path.join(tempDir, "exit.log");
const wrapperPath = await makeMockAgentWrapper({
T3_ACP_EXIT_LOG_PATH: exitLogPath,
});
await Effect.runPromise(
discoverCursorModelsViaAcp({
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
}).pipe(Effect.provide(NodeServices.layer)),
);
const exitLog = await waitForFileContent(exitLogPath);
expect(exitLog).toContain("SIGTERM");
});
});
describe("discoverCursorModelCapabilitiesViaAcp", () => {
it("closes all ACP probe runtimes after capability enrichment completes", async () => {
const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-capabilities-exit-log-"));
const exitLogPath = path.join(tempDir, "exit.log");
const wrapperPath = await makeMockAgentWrapper({
T3_ACP_EXIT_LOG_PATH: exitLogPath,
});
const existingModels: ReadonlyArray<ServerProviderModel> = [
{ slug: "default", name: "Auto", isCustom: false, capabilities: emptyCapabilities },
{ slug: "composer-2", name: "Composer 2", isCustom: false, capabilities: emptyCapabilities },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, capabilities: emptyCapabilities },
{
slug: "claude-opus-4-6",
name: "Opus 4.6",
isCustom: false,
capabilities: emptyCapabilities,
},
];
const models = await Effect.runPromise(
discoverCursorModelCapabilitiesViaAcp(
{
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
},
existingModels,
).pipe(Effect.provide(NodeServices.layer)),
);
expect(models.map((model) => model.slug)).toEqual([
"default",
"composer-2",
"gpt-5.4",
"claude-opus-4-6",
]);
const exitLog = await waitForFileContent(exitLogPath);
expect(exitLog.match(/SIGTERM/g)?.length ?? 0).toBe(4);
});
});
describe("parseCursorAboutOutput", () => {
it("parses json about output and forwards subscription metadata", () => {
expect(
@@ -672,16 +405,4 @@ describe("resolveCursorAcpConfigUpdates", () => {
}),
).toEqual([{ configId: "fast", value: "false" }]);
});
it("writes Cursor effort changes through the newer model_option config when available", () => {
expect(
resolveCursorAcpConfigUpdates(parameterizedClaudeModelOptionConfigOptions, {
reasoning: "max",
thinking: false,
}),
).toEqual([
{ configId: "effort", value: "max" },
{ configId: "thinking", value: "false" },
]);
});
});
@@ -107,7 +107,7 @@ function buildEventBase(input: {
raw: {
source: "opencode.sdk.event",
payload: input.raw,
},
} as unknown as ProviderRuntimeEvent["raw"],
}
: {}),
};
@@ -4,14 +4,9 @@ import { assertFailure } from "@effect/vitest/utils";
import { Effect, Layer, Stream } from "effect";
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";
import { CursorAdapter } from "../Services/CursorAdapter.ts";
import type { CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.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";
@@ -51,23 +46,6 @@ const fakeClaudeAdapter: ClaudeAdapterShape = {
streamEvents: Stream.empty,
};
const fakeOpenCodeAdapter: OpenCodeAdapterShape = {
provider: "opencode",
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,
};
const fakeCursorAdapter: CursorAdapterShape = {
provider: "cursor",
capabilities: { sessionModelSwitch: "in-session" },
@@ -92,7 +70,6 @@ const layer = it.layer(
Layer.mergeAll(
Layer.succeed(CodexAdapter, fakeCodexAdapter),
Layer.succeed(ClaudeAdapter, fakeClaudeAdapter),
Layer.succeed(OpenCodeAdapter, fakeOpenCodeAdapter),
Layer.succeed(CursorAdapter, fakeCursorAdapter),
),
),
@@ -106,15 +83,13 @@ layer("ProviderAdapterRegistryLive", (it) => {
const registry = yield* ProviderAdapterRegistry;
const codex = yield* registry.getByProvider("codex");
const claude = yield* registry.getByProvider("claudeAgent");
const openCode = yield* registry.getByProvider("opencode");
const cursor = yield* registry.getByProvider("cursor");
assert.equal(codex, fakeCodexAdapter);
assert.equal(claude, fakeClaudeAdapter);
assert.equal(openCode, fakeOpenCodeAdapter);
assert.equal(cursor, fakeCursorAdapter);
const providers = yield* registry.listProviders();
assert.deepEqual(providers, ["codex", "claudeAgent", "opencode", "cursor"]);
assert.deepEqual(providers, ["codex", "claudeAgent", "cursor"]);
}),
);
@@ -18,7 +18,6 @@ import {
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import { CursorAdapter } from "../Services/CursorAdapter.ts";
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
export interface ProviderAdapterRegistryLiveOptions {
readonly adapters?: ReadonlyArray<ProviderAdapterShape<ProviderAdapterError>>;
@@ -31,12 +30,7 @@ const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(fun
const adapters =
options?.adapters !== undefined
? options.adapters
: [
yield* CodexAdapter,
yield* ClaudeAdapter,
yield* OpenCodeAdapter,
...(cursorAdapterOption._tag === "Some" ? [cursorAdapterOption.value] : []),
];
: [yield* CodexAdapter, yield* ClaudeAdapter, yield* CursorAdapter];
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
@@ -793,9 +793,20 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry;
const refreshed = yield* registry.refresh("codex");
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 ready = yield* registry.getProviders;
assert.strictEqual(
refreshed.find((status) => status.provider === "codex")?.status,
ready.find((status) => status.provider === "codex")?.status,
"ready",
);
@@ -33,6 +33,8 @@ describe("AcpSessionRuntime", () => {
_meta: { parameterizedModelPicker: true },
},
});
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -72,7 +74,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",
@@ -93,6 +95,8 @@ describe("AcpSessionRuntime", () => {
) {
expect(assistantDelta.itemId).toBe(assistantStart.itemId);
}
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -120,7 +124,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",
@@ -151,6 +155,8 @@ describe("AcpSessionRuntime", () => {
expect(secondStarted.itemId).not.toBe(firstStarted.itemId);
expect(secondDelta.itemId).toBe(secondStarted.itemId);
}
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -181,7 +187,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");
@@ -189,6 +195,8 @@ describe("AcpSessionRuntime", () => {
expect(toolCall.toolCall.status).toBe("completed");
expect(toolCall.toolCall.title).toBe("Read file");
}
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -240,41 +248,8 @@ describe("AcpSessionRuntime", () => {
(event) => event.method === "session/prompt" && event.status === "succeeded",
),
).toBe(true);
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
authMethodId: "test",
spawn: {
command: bunExe,
args: [mockAgentPath],
},
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<AcpSessionRequestLogEvent> = [];
return Effect.gen(function* () {
const runtime = yield* 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({
@@ -318,6 +293,8 @@ describe("AcpSessionRuntime", () => {
expect(
protocolEvents.some((event) => event.direction === "incoming" && event.stage === "decoded"),
).toBe(true);
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -360,6 +337,8 @@ describe("AcpSessionRuntime", () => {
expect(error.message).toContain("composer-2[fast=true]");
}
yield* runtime.close;
const recordedRequests = readFileSync(requestLogPath, "utf8")
.trim()
.split("\n")
@@ -372,6 +351,8 @@ describe("AcpSessionRuntime", () => {
message.params?.value === "composer-2[fast=false]",
),
).toBe(false);
rmSync(tempDir, { recursive: true, force: true });
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -389,7 +370,6 @@ describe("AcpSessionRuntime", () => {
),
Effect.scoped,
Effect.provide(NodeServices.layer),
Effect.ensuring(Effect.sync(() => rmSync(tempDir, { recursive: true, force: true }))),
);
});
});
@@ -164,24 +164,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",
@@ -415,13 +415,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": {
@@ -77,7 +77,7 @@ export interface AcpSessionRuntimeShape {
readonly handleExtRequest: EffectAcpClient.AcpClientShape["handleExtRequest"];
readonly handleExtNotification: EffectAcpClient.AcpClientShape["handleExtNotification"];
readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
readonly getEvents: () => Stream.Stream<AcpParsedSessionEvent, never>;
readonly events: Stream.Stream<AcpParsedSessionEvent, never>;
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
readonly getConfigOptions: Effect.Effect<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
readonly prompt: (
@@ -100,6 +100,7 @@ export interface AcpSessionRuntimeShape {
method: string,
payload: unknown,
) => Effect.Effect<void, EffectAcpErrors.AcpError>;
readonly close: Effect.Effect<void>;
}
interface AcpStartedState extends AcpSessionRuntimeStartResult {}
@@ -141,11 +142,11 @@ const makeAcpSessionRuntime = (
): Effect.Effect<
AcpSessionRuntimeShape,
EffectAcpErrors.AcpError,
ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
ChildProcessSpawner.ChildProcessSpawner
> =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const runtimeScope = yield* Scope.Scope;
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>());
@@ -226,6 +227,7 @@ const makeAcpSessionRuntime = (
params: notification,
}),
);
const close = Scope.close(runtimeScope, Exit.void).pipe(Effect.asVoid);
const initializeClientCapabilities = {
fs: {
@@ -309,47 +311,32 @@ const makeAcpSessionRuntime = (
| 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* () {
@@ -482,7 +469,7 @@ const makeAcpSessionRuntime = (
handleExtRequest: acp.handleExtRequest,
handleExtNotification: acp.handleExtNotification,
start: () => start,
getEvents: () => Stream.fromQueue(eventQueue),
events: Stream.fromQueue(eventQueue),
getModeState: Ref.get(modeStateRef),
getConfigOptions: Ref.get(configOptionsRef),
prompt: (payload) =>
@@ -516,17 +503,7 @@ const makeAcpSessionRuntime = (
Effect.flatMap((started) => acp.agent.cancel({ sessionId: started.sessionId })),
),
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(
@@ -536,6 +513,7 @@ const makeAcpSessionRuntime = (
request: (method, payload) =>
runLoggedRequest(method, payload, acp.raw.request(method, payload)),
notify: acp.raw.notify,
close,
} satisfies AcpSessionRuntimeShape;
});
@@ -549,20 +527,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,
@@ -16,6 +16,7 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
const runtime = yield* AcpSessionRuntime;
const started = yield* runtime.start();
expect(started.initializeResult).toBeDefined();
yield* runtime.close;
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
@@ -54,10 +55,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",
);
console.log("Model config option:", JSON.stringify(modelConfig, null, 2));
console.log(
@@ -67,6 +65,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({
@@ -113,16 +112,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,5 +1,5 @@
import { type CursorModelOptions, type CursorSettings } from "@t3tools/contracts";
import { Effect, Layer, Scope } from "effect";
import { Effect, Layer } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import type * as EffectAcpErrors from "effect-acp/errors";
@@ -47,7 +47,7 @@ export function buildCursorAcpSpawnInput(
export const makeCursorAcpRuntime = (
input: CursorAcpRuntimeInput,
): Effect.Effect<AcpSessionRuntimeShape, EffectAcpErrors.AcpError, Scope.Scope> =>
): Effect.Effect<AcpSessionRuntimeShape, EffectAcpErrors.AcpError> =>
Effect.gen(function* () {
const acpContext = yield* Layer.build(
AcpSessionRuntime.layer({
@@ -62,7 +62,7 @@ export const makeCursorAcpRuntime = (
),
);
return yield* Effect.service(AcpSessionRuntime).pipe(Effect.provide(acpContext));
});
}).pipe(Effect.scoped);
interface CursorAcpModelSelectionRuntime {
readonly getConfigOptions: AcpSessionRuntimeShape["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
+15 -27
View File
@@ -1,3 +1,4 @@
import type * as EffectCodexSchema from "effect-codex-app-server/schema";
import type { ServerProviderModel } from "@t3tools/contracts";
export type CodexPlanType =
@@ -21,23 +22,19 @@ export const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
export const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
const CODEX_SPARK_ENABLED_PLAN_TYPES = new Set<CodexPlanType>(["pro"]);
function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") {
return undefined;
export function readCodexAccountSnapshotResponse(
response: EffectCodexSchema.V2GetAccountResponse,
): CodexAccountSnapshot {
const account = response.account;
if (!account) {
return {
type: "unknown",
planType: null,
sparkEnabled: false,
};
}
return value as Record<string, unknown>;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
const record = asObject(response);
const account = asObject(record?.account) ?? record;
const accountType = asString(account?.type);
if (accountType === "apiKey") {
if (account.type === "apiKey") {
return {
type: "apiKey",
planType: null,
@@ -45,19 +42,10 @@ export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapsho
};
}
if (accountType === "chatgpt") {
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
return {
type: "chatgpt",
planType,
sparkEnabled: CODEX_SPARK_ENABLED_PLAN_TYPES.has(planType),
};
}
return {
type: "unknown",
planType: null,
sparkEnabled: false,
type: "chatgpt",
planType: account.planType as CodexPlanType,
sparkEnabled: CODEX_SPARK_ENABLED_PLAN_TYPES.has(account.planType as CodexPlanType),
};
}
@@ -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",
},
]);
});
});
+108 -194
View File
@@ -1,85 +1,67 @@
import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
import readline from "node:readline";
import type { ServerProviderSkill } from "@t3tools/contracts";
import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount.ts";
import { spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
interface JsonRpcProbeResponse {
readonly id?: unknown;
readonly result?: unknown;
readonly error?: {
readonly message?: unknown;
};
}
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>;
}
function readErrorMessage(response: JsonRpcProbeResponse): string | undefined {
return typeof response.error?.message === "string" ? response.error.message : undefined;
export class CodexDiscoveryProbeError extends Schema.TaggedErrorClass<CodexDiscoveryProbeError>()(
"CodexDiscoveryProbeError",
{
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return this.detail;
}
}
function readObject(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
}
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);
function readArray(value: unknown): ReadonlyArray<unknown> | undefined {
return Array.isArray(value) ? value : undefined;
}
return skills.map((skill) => {
const shortDescription =
skill.shortDescription ?? skill.interface?.shortDescription ?? undefined;
function readString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
const parsedSkill: Mutable<ServerProviderSkill> = {
name: skill.name,
path: skill.path,
enabled: skill.enabled,
};
function nonEmptyTrimmed(value: unknown): string | undefined {
const candidate = readString(value)?.trim();
return candidate ? candidate : undefined;
}
function parseCodexSkillsResult(result: unknown, cwd: string): ReadonlyArray<ServerProviderSkill> {
const resultRecord = readObject(result);
const dataBuckets = readArray(resultRecord?.data) ?? [];
const matchingBucket = dataBuckets.find(
(value) => nonEmptyTrimmed(readObject(value)?.cwd) === cwd,
);
const rawSkills =
readArray(readObject(matchingBucket)?.skills) ?? readArray(resultRecord?.skills) ?? [];
return rawSkills.flatMap((value) => {
const skill = readObject(value);
const display = readObject(skill?.interface);
const name = nonEmptyTrimmed(skill?.name);
const path = nonEmptyTrimmed(skill?.path);
if (!name || !path) {
return [];
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 [
{
name,
path,
enabled: skill?.enabled !== false,
...(nonEmptyTrimmed(skill?.description)
? { description: nonEmptyTrimmed(skill?.description) }
: {}),
...(nonEmptyTrimmed(skill?.scope) ? { scope: nonEmptyTrimmed(skill?.scope) } : {}),
...(nonEmptyTrimmed(display?.displayName)
? { displayName: nonEmptyTrimmed(display?.displayName) }
: {}),
...(nonEmptyTrimmed(skill?.shortDescription) || nonEmptyTrimmed(display?.shortDescription)
? {
shortDescription:
nonEmptyTrimmed(skill?.shortDescription) ??
nonEmptyTrimmed(display?.shortDescription),
}
: {}),
} satisfies ServerProviderSkill,
];
return parsedSkill;
});
}
export function buildCodexInitializeParams() {
export function buildCodexInitializeParams(): EffectCodexSchema.V1InitializeParams {
return {
clientInfo: {
name: "t3code_desktop",
@@ -89,7 +71,7 @@ export function buildCodexInitializeParams() {
capabilities: {
experimentalApi: true,
},
} as const;
};
}
export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): void {
@@ -105,137 +87,69 @@ export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): vo
child.kill();
}
export async function probeCodexDiscovery(input: {
export const probeCodexDiscovery = Effect.fn("probeCodexDiscovery")(function* (input: {
readonly binaryPath: string;
readonly homePath?: string;
readonly cwd: string;
readonly signal?: AbortSignal;
}): Promise<CodexDiscoverySnapshot> {
return await new Promise((resolve, reject) => {
const child = spawn(input.binaryPath, ["app-server"], {
env: {
...process.env,
...(input.homePath ? { CODEX_HOME: input.homePath } : {}),
},
stdio: ["pipe", "pipe", "pipe"],
shell: process.platform === "win32",
});
const output = readline.createInterface({ input: child.stdout });
}) {
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),
);
let completed = false;
let account: CodexAccountSnapshot | undefined;
let skills: ReadonlyArray<ServerProviderSkill> | undefined;
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 cleanup = () => {
output.removeAllListeners();
output.close();
child.removeAllListeners();
if (!child.killed) {
killCodexChildProcess(child);
}
};
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,
}),
),
);
const finish = (callback: () => void) => {
if (completed) return;
completed = true;
cleanup();
callback();
};
const fail = (error: unknown) =>
finish(() =>
reject(
error instanceof Error
? error
: new Error(`Codex discovery probe failed: ${String(error)}.`),
),
);
const maybeResolve = () => {
if (account && skills !== undefined) {
const resolvedAccount = account;
const resolvedSkills = skills;
finish(() => resolve({ account: resolvedAccount, skills: resolvedSkills }));
}
};
if (input.signal?.aborted) {
fail(new Error("Codex discovery probe aborted."));
return;
}
input.signal?.addEventListener("abort", () =>
fail(new Error("Codex discovery probe aborted.")),
);
const writeMessage = (message: unknown) => {
if (!child.stdin.writable) {
fail(new Error("Cannot write to codex app-server stdin."));
return;
}
child.stdin.write(`${JSON.stringify(message)}\n`);
};
output.on("line", (line) => {
let parsed: unknown;
try {
parsed = JSON.parse(line);
} catch {
fail(new Error("Received invalid JSON from codex app-server during discovery probe."));
return;
}
if (!parsed || typeof parsed !== "object") {
return;
}
const response = parsed as JsonRpcProbeResponse;
if (response.id === 1) {
const errorMessage = readErrorMessage(response);
if (errorMessage) {
fail(new Error(`initialize failed: ${errorMessage}`));
return;
}
writeMessage({ method: "initialized" });
writeMessage({ id: 2, method: "skills/list", params: { cwds: [input.cwd] } });
writeMessage({ id: 3, method: "account/read", params: {} });
return;
}
if (response.id === 2) {
const errorMessage = readErrorMessage(response);
skills = errorMessage ? [] : parseCodexSkillsResult(response.result, input.cwd);
maybeResolve();
return;
}
if (response.id === 3) {
const errorMessage = readErrorMessage(response);
if (errorMessage) {
fail(new Error(`account/read failed: ${errorMessage}`));
return;
}
account = readCodexAccountSnapshot(response.result);
maybeResolve();
}
});
child.once("error", fail);
child.once("exit", (code, signal) => {
if (completed) return;
fail(
new Error(
`codex app-server exited before probe completed (code=${code ?? "null"}, signal=${signal ?? "null"}).`,
),
);
});
writeMessage({
id: 1,
method: "initialize",
params: buildCodexInitializeParams(),
});
});
}
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
);
}
@@ -16,7 +16,8 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
readonly getSettings: Effect.Effect<Settings>;
readonly streamSettings: Stream.Stream<Settings>;
readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
readonly initialSnapshot: (settings: Settings) => 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;
@@ -26,18 +27,26 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
}) => Effect.Effect<void>;
readonly refreshInterval?: Duration.Input;
}): 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 = 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;
@@ -49,6 +58,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
if (state.enrichmentGeneration !== generation || Equal.equals(state.snapshot, nextSnapshot)) {
return [null, state] as const;
}
return [
nextSnapshot,
{
@@ -114,6 +124,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;
@@ -126,6 +137,28 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
return yield* applySnapshot(nextSettings, { forceRefresh: true });
});
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)),
).pipe(Effect.forkScoped);
@@ -136,17 +169,17 @@ 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 {
getSnapshot: input.getSettings.pipe(
Effect.flatMap(applySnapshot),
Effect.tapError(Effect.logError),
Effect.orDie,
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() {
+1 -1
View File
@@ -105,7 +105,7 @@ export class ServerSettingsService extends Context.Service<
const ServerSettingsJson = fromLenientJson(ServerSettings);
const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent", "opencode", "cursor"];
const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent", "cursor"];
/**
* Ensure the `textGenerationModelSelection` points to an enabled provider.
@@ -102,23 +102,25 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
},
},
]
: [
{
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 === "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}
@@ -1,5 +1,5 @@
import { type ProviderKind, type ServerProvider } from "@t3tools/contracts";
import { resolveSelectableModel } from "@t3tools/shared/model";
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";
@@ -59,22 +59,24 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
disabled?: boolean;
triggerVariant?: VariantProps<typeof buttonVariants>["variant"];
triggerClassName?: string;
disabledReason?: string;
onProviderModelChange: (provider: ProviderKind, model: string) => void;
}) {
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 === props.model)?.name ?? props.model;
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;
if (!value) return;
const resolvedModel = resolveSelectableModel(
provider,
value,
props.modelOptionsByProvider[provider],
);
const resolvedModel =
resolveSelectableModel(provider, value, props.modelOptionsByProvider[provider]) ??
resolveModelSlugForProvider(provider, value);
if (!resolvedModel) return;
props.onProviderModelChange(provider, resolvedModel);
setIsMenuOpen(false);
@@ -103,6 +105,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
props.triggerClassName,
)}
disabled={props.disabled}
title={props.disabled ? props.disabledReason : undefined}
/>
}
>
@@ -128,7 +131,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
{props.lockedProvider !== null ? (
<MenuGroup>
<MenuRadioGroup
value={props.model}
value={selectedModelValue}
onValueChange={(value) => handleModelChange(props.lockedProvider!, value)}
>
{props.modelOptionsByProvider[props.lockedProvider].map((modelOption) => (
@@ -186,7 +189,15 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
<MenuSubPopup className="[--available-height:min(24rem,70vh)]" sideOffset={4}>
<MenuGroup>
<MenuRadioGroup
value={props.provider === option.value ? props.model : ""}
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) => (
@@ -628,92 +628,6 @@ describe("TraitsPicker (Codex)", () => {
});
});
// ── OpenCode TraitsPicker tests ───────────────────────────────────────
async function mountOpenCodePicker(props: { model?: string; options?: OpenCodeModelOptions }) {
const threadId = ThreadId.make("thread-opencode-traits");
const threadRef = scopeThreadRef(LOCAL_ENVIRONMENT_ID, threadId);
const threadKey = scopedThreadKey(threadRef);
const model = props.model ?? DEFAULT_MODEL_BY_PROVIDER.opencode;
const draftsByThreadKey: Record<string, ComposerThreadDraftState> = {
[threadKey]: {
prompt: "",
images: [],
nonPersistedImageIds: [],
persistedAttachments: [],
terminalContexts: [],
modelSelectionByProvider: {
opencode: {
provider: "opencode",
model,
...(props.options ? { options: props.options } : {}),
},
},
activeProvider: "opencode",
runtimeMode: null,
interactionMode: null,
},
};
useComposerDraftStore.setState({
draftsByThreadKey,
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
});
const host = document.createElement("div");
document.body.append(host);
const screen = await render(
<TraitsPicker
provider="opencode"
models={findTestProvider("opencode").models}
threadRef={threadRef}
model={model}
prompt=""
modelOptions={props.options}
onPromptChange={() => {}}
/>,
{ container: host },
);
const cleanup = async () => {
await screen.unmount();
host.remove();
};
return {
[Symbol.asyncDispose]: cleanup,
cleanup,
};
}
describe("TraitsPicker (OpenCode)", () => {
afterEach(() => {
document.body.innerHTML = "";
localStorage.removeItem(COMPOSER_DRAFT_STORAGE_KEY);
useComposerDraftStore.setState({
draftsByThreadKey: {},
draftThreadsByThreadKey: {},
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
stickyModelSelectionByProvider: {},
});
});
it("shows the selected agent label with capitalization in the trigger", async () => {
await using _ = await mountOpenCodePicker({
options: {
variant: "medium",
agent: "plan",
},
});
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Medium · Plan");
expect(text).not.toContain("Medium · plan");
});
});
});
describe("TraitsPicker (Cursor)", () => {
afterEach(() => {
document.body.innerHTML = "";
@@ -27,6 +27,86 @@ const CODEX_MODELS: ReadonlyArray<ServerProviderModel> = [
},
];
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",
@@ -313,6 +393,141 @@ describe("getComposerProviderState", () => {
});
});
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",
+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({
-27
View File
@@ -1029,33 +1029,6 @@ describe("composerDraftStore modelSelection", () => {
);
});
it("preserves the selected Cursor model when only traits change", () => {
const store = useComposerDraftStore.getState();
store.setProviderModelOptions(
threadRef,
"cursor",
{
reasoning: "high",
},
{
model: "gpt-5.4",
persistSticky: true,
},
);
expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.modelSelectionByProvider.cursor).toEqual(
modelSelection("cursor", "gpt-5.4", {
reasoning: "high",
}),
);
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.cursor).toEqual(
modelSelection("cursor", "gpt-5.4", {
reasoning: "high",
}),
);
});
it("updates only the draft when sticky persistence is omitted", () => {
const store = useComposerDraftStore.getState();
+29 -35
View File
@@ -1038,41 +1038,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, undefined);
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({
@@ -1517,3 +1482,32 @@ describe("deriveActiveWorkStartedAt", () => {
).toBe("2026-02-27T21:11:00.000Z");
});
});
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,
});
});
});
+2 -3
View File
@@ -1,6 +1,7 @@
import type {
EnvironmentId,
MessageId,
ModelSelection,
OrchestrationCheckpointSummary,
OrchestrationEvent,
OrchestrationLatestTurn,
@@ -129,9 +130,7 @@ function arraysEqual<T>(left: readonly T[], right: readonly T[]): boolean {
return left.length === right.length && left.every((value, index) => value === right[index]);
}
function normalizeModelSelection<T extends { provider: ProviderKind; model: string }>(
selection: T,
): T {
function normalizeModelSelection<T extends ModelSelection>(selection: T): T {
return {
...selection,
model: resolveModelSlugForProvider(selection.provider, selection.model),
+276 -270
View File
File diff suppressed because it is too large. Load diff
+1 -2
View File
@@ -46,6 +46,7 @@ export const CursorModelOptions = Schema.Struct({
contextWindow: Schema.optional(Schema.String),
});
export type CursorModelOptions = typeof CursorModelOptions.Type;
export const OpenCodeModelOptions = Schema.Struct({
variant: Schema.optional(TrimmedNonEmptyString),
agent: Schema.optional(TrimmedNonEmptyString),
@@ -141,8 +142,6 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string,
opencode: {},
};
// ── Provider display names ────────────────────────────────────────────
export const PROVIDER_DISPLAY_NAMES: Record<ProviderKind, string> = {
codex: "Codex",
claudeAgent: "Claude",
+4
View File
@@ -30,6 +30,10 @@ 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([
@@ -24,7 +24,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"]),
]);
+1 -1
View File
@@ -92,7 +92,7 @@ export const ClaudeSettings = Schema.Struct({
export type ClaudeSettings = typeof ClaudeSettings.Type;
export const CursorSettings = Schema.Struct({
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
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([]))),
@@ -0,0 +1,48 @@
{
"name": "effect-codex-app-server",
"private": true,
"type": "module",
"exports": {
"./client": {
"types": "./src/client.ts",
"import": "./src/client.ts"
},
"./schema": {
"types": "./src/schema.ts",
"import": "./src/schema.ts"
},
"./rpc": {
"types": "./src/rpc.ts",
"import": "./src/rpc.ts"
},
"./protocol": {
"types": "./src/protocol.ts",
"import": "./src/protocol.ts"
},
"./errors": {
"types": "./src/errors.ts",
"import": "./src/errors.ts"
}
},
"scripts": {
"dev": "tsdown src/client.ts src/rpc.ts src/protocol.ts src/schema.ts --format esm,cjs --dts --watch --clean",
"build": "tsdown src/client.ts src/rpc.ts src/protocol.ts src/schema.ts --format esm,cjs --dts --clean",
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"generate": "bun run scripts/generate.ts",
"probe": "bun run test/examples/codex-app-server-probe.ts"
},
"dependencies": {
"effect": "catalog:"
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/openapi-generator": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/vitest": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
}
}
@@ -0,0 +1,772 @@
#!/usr/bin/env node
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { make as makeJsonSchemaGenerator } from "@effect/openapi-generator/JsonSchemaGenerator";
import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
const UPSTREAM_REF = "dbfe855f4fd0f5dcdf079882652a8efe622b0595";
const USER_AGENT = "effect-codex-app-server-generator";
const GITHUB_API_BASE =
"https://api.github.com/repos/openai/codex/contents/codex-rs/app-server-protocol";
const GithubContentEntries = Schema.Array(
Schema.Struct({
name: Schema.String,
path: Schema.String,
download_url: Schema.NullOr(Schema.String),
type: Schema.String,
}),
);
type GithubContentEntry = (typeof GithubContentEntries.Type)[number];
interface GeneratedPaths {
readonly generatedDir: string;
readonly schemaOutputPath: string;
readonly metaOutputPath: string;
readonly namespacesOutputPath: string;
}
interface MethodEntry {
readonly method: string;
readonly paramsType?: string;
}
interface JsonSchemaFile {
readonly namespace?: string;
readonly exportName: string;
readonly fileName: string;
readonly downloadUrl: string;
readonly qualifiedName: string;
}
class GeneratorError extends Schema.TaggedErrorClass<GeneratorError>()("GeneratorError", {
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message() {
return this.detail;
}
}
const ManualSchemas: Record<string, typeof Schema.Json.Type> = {
GetAuthStatusParams: {
type: "object",
title: "GetAuthStatusParams",
properties: {
includeToken: {
anyOf: [{ type: "boolean" }, { type: "null" }],
},
refreshToken: {
anyOf: [{ type: "boolean" }, { type: "null" }],
},
},
},
GetConversationSummaryParams: {
title: "GetConversationSummaryParams",
oneOf: [
{
type: "object",
properties: {
rolloutPath: { type: "string" },
},
required: ["rolloutPath"],
},
{
type: "object",
properties: {
conversationId: { type: "string" },
},
required: ["conversationId"],
},
],
},
GetConversationSummaryResponse: {
type: "object",
title: "GetConversationSummaryResponse",
properties: {
summary: {},
},
required: ["summary"],
},
GitDiffToRemoteParams: {
type: "object",
title: "GitDiffToRemoteParams",
properties: {
cwd: { type: "string" },
},
required: ["cwd"],
},
GitDiffToRemoteResponse: {
type: "object",
title: "GitDiffToRemoteResponse",
properties: {
sha: { type: "string" },
diff: { type: "string" },
},
required: ["sha", "diff"],
},
GetAuthStatusResponse: {
type: "object",
title: "GetAuthStatusResponse",
properties: {
authMethod: {
anyOf: [{}, { type: "null" }],
},
authToken: {
anyOf: [{ type: "string" }, { type: "null" }],
},
requiresOpenaiAuth: {
anyOf: [{ type: "boolean" }, { type: "null" }],
},
},
required: ["authMethod", "authToken", "requiresOpenaiAuth"],
},
};
const getGeneratedPaths = Effect.fn("getGeneratedPaths")(function* () {
const path = yield* Path.Path;
const generatedDir = path.join(import.meta.dirname, "..", "src", "_generated");
return {
generatedDir,
schemaOutputPath: path.join(generatedDir, "schema.gen.ts"),
metaOutputPath: path.join(generatedDir, "meta.gen.ts"),
namespacesOutputPath: path.join(generatedDir, "namespaces.gen.ts"),
} satisfies GeneratedPaths;
});
const ensureGeneratedDir = Effect.fn("ensureGeneratedDir")(function* () {
const fs = yield* FileSystem.FileSystem;
const { generatedDir } = yield* getGeneratedPaths();
yield* fs.makeDirectory(generatedDir, { recursive: true });
});
const fetchText = Effect.fn("fetchText")(function* (url: string) {
const response = yield* Effect.tryPromise({
try: () =>
fetch(url, {
headers: {
"user-agent": USER_AGENT,
},
}),
catch: (cause) =>
new GeneratorError({
detail: `Failed to fetch ${url}`,
cause,
}),
});
if (!response.ok) {
const detail = yield* Effect.tryPromise({
try: () => response.text(),
catch: () => "",
});
return yield* Effect.fail(
new GeneratorError({
detail: `Failed to download ${url}: ${response.status} ${detail}`,
}),
);
}
return yield* Effect.tryPromise({
try: () => response.text(),
catch: (cause) =>
new GeneratorError({
detail: `Failed to read response body for ${url}`,
cause,
}),
});
});
const fetchDirectoryEntries = Effect.fn("fetchDirectoryEntries")(function* (path: string) {
const raw = yield* fetchText(`${GITHUB_API_BASE}/${path}?ref=${UPSTREAM_REF}`);
return yield* Schema.decodeEffect(Schema.fromJsonString(GithubContentEntries))(raw);
});
function collectSchemaEntries(
chunk: string,
): ReadonlyArray<{ readonly name: string; readonly code: string }> {
const lines = chunk
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0 && !line.startsWith("//"));
const entries: Array<{ name: string; code: string }> = [];
for (let index = 0; index < lines.length; index += 1) {
const typeLine = lines[index];
if (!typeLine?.startsWith("export type ")) {
continue;
}
const constLine = lines[index + 1];
if (!constLine?.startsWith("export const ")) {
throw new Error(`Malformed generator output near: ${typeLine}`);
}
const match = /^export type ([A-Za-z0-9_]+)/.exec(typeLine);
if (!match?.[1]) {
throw new Error(`Could not extract schema name from: ${typeLine}`);
}
entries.push({
name: match[1],
code: `${typeLine}\n${constLine}`,
});
index += 1;
}
return entries;
}
function normalizeNullableTypes(value: typeof Schema.Json.Type): typeof Schema.Json.Type {
if (Array.isArray(value)) {
return value.map(normalizeNullableTypes);
}
if (value === null || typeof value !== "object") {
return value;
}
const normalizedEntries = Object.entries(value).map(([key, child]) => [
key,
normalizeNullableTypes(child),
]);
const normalizedObject = Object.fromEntries(normalizedEntries) as Record<
string,
typeof Schema.Json.Type
>;
const typeValue = normalizedObject.type;
if (!Array.isArray(typeValue)) {
return normalizedObject;
}
const normalizedTypes = typeValue.filter((entry): entry is string => typeof entry === "string");
if (normalizedTypes.length !== typeValue.length || !normalizedTypes.includes("null")) {
return normalizedObject;
}
const nonNullTypes = normalizedTypes.filter((entry) => entry !== "null");
if (nonNullTypes.length !== 1) {
return normalizedObject;
}
const nonNullType = nonNullTypes[0]!;
const nextObject: Record<string, typeof Schema.Json.Type> = {};
for (const [key, child] of Object.entries(normalizedObject)) {
if (key !== "type") {
nextObject[key] = child;
}
}
return {
anyOf: [
{
...nextObject,
type: nonNullType,
},
{ type: "null" },
],
};
}
function stripNullDefaults(value: typeof Schema.Json.Type): typeof Schema.Json.Type {
if (Array.isArray(value)) {
return value.map(stripNullDefaults);
}
if (value === null || typeof value !== "object") {
return value;
}
return Object.fromEntries(
Object.entries(value)
.filter(([key, child]) => !(key === "default" && child === null))
.map(([key, child]) => [key, stripNullDefaults(child)]),
) as typeof Schema.Json.Type;
}
function toPascalCaseMethod(method: string) {
return method
.split("/")
.flatMap((segment) => segment.split(/(?=[A-Z])/))
.flatMap((segment) => segment.split(/[-_]/))
.filter(Boolean)
.map((segment) => segment[0]!.toUpperCase() + segment.slice(1))
.join("");
}
function parseRequestEntries(fileContents: string): ReadonlyArray<MethodEntry> {
const entryPattern = /\{\s*"method":\s*"([^"]+)",\s*id:\s*RequestId,\s*params:\s*([^,}]+)/g;
const entries: Array<MethodEntry> = [];
let match: RegExpExecArray | null;
while ((match = entryPattern.exec(fileContents)) !== null) {
entries.push({
method: match[1]!,
paramsType: match[2]!.trim(),
});
}
return entries;
}
function parseNotificationEntries(fileContents: string): ReadonlyArray<MethodEntry> {
const entryPattern = /\{\s*"method":\s*"([^"]+)"(?:,\s*"params":\s*([^ }]+))?\s*\}/g;
const entries: Array<MethodEntry> = [];
let match: RegExpExecArray | null;
while ((match = entryPattern.exec(fileContents)) !== null) {
entries.push({
method: match[1]!,
...(match[2] ? { paramsType: match[2].trim() } : {}),
});
}
return entries;
}
function resolveSchemaTypeName(
rawTypeName: string,
generatedSchemaNames: ReadonlySet<string>,
): string {
if (rawTypeName === "undefined") {
return "undefined";
}
const candidates = [
rawTypeName,
`V2${rawTypeName}`,
`V1${rawTypeName}`,
`SerdeJson${rawTypeName}`,
];
for (const candidate of candidates) {
if (generatedSchemaNames.has(candidate)) {
return candidate;
}
}
throw new Error(`Unable to resolve schema type name: ${rawTypeName}`);
}
function resolveResponseTypeName(
method: string,
paramsType: string | undefined,
generatedSchemaNames: ReadonlySet<string>,
): string {
const overrides: Record<string, string> = {
"account/logout": "LogoutAccountResponse",
"account/rateLimits/read": "GetAccountRateLimitsResponse",
"config/batchWrite": "ConfigWriteResponse",
"config/mcpServer/reload": "McpServerRefreshResponse",
"config/value/write": "ConfigWriteResponse",
"configRequirements/read": "ConfigRequirementsReadResponse",
};
const override = overrides[method];
if (override) {
return resolveSchemaTypeName(override, generatedSchemaNames);
}
if (paramsType && paramsType !== "undefined") {
const fromParams = paramsType.replace(/Params$/, "Response");
try {
return resolveSchemaTypeName(fromParams, generatedSchemaNames);
} catch {
// Fall through to method-based lookup.
}
}
return resolveSchemaTypeName(`${toPascalCaseMethod(method)}Response`, generatedSchemaNames);
}
function renderMethodConstants(constantName: string, entries: ReadonlyArray<MethodEntry>) {
return [
`export const ${constantName} = {`,
...entries.map(
(entry) => ` ${JSON.stringify(entry.method)}: ${JSON.stringify(entry.method)},`,
),
"} as const;",
"",
].join("\n");
}
function renderTypeInterface(
interfaceName: string,
entries: ReadonlyArray<MethodEntry>,
typeName: (entry: MethodEntry) => string,
) {
return [
`export interface ${interfaceName} {`,
...entries.map((entry) => ` readonly ${JSON.stringify(entry.method)}: ${typeName(entry)};`),
"}",
"",
].join("\n");
}
function renderSchemaMap(
constantName: string,
entries: ReadonlyArray<MethodEntry>,
typeName: (entry: MethodEntry) => string,
) {
return [
`export const ${constantName} = {`,
...entries.map((entry) => {
const schemaName = typeName(entry);
return ` ${JSON.stringify(entry.method)}: ${
schemaName === "undefined" ? "undefined" : `CodexSchema.${schemaName}`
},`;
}),
"} as const;",
"",
].join("\n");
}
function renderSchemaTypeReference(schemaName: string) {
return schemaName === "undefined" ? "undefined" : `typeof CodexSchema.${schemaName}.Type`;
}
function exportNameForPath(filePath: string): string {
const relative = filePath.replace(/^schema\/json\//, "").replace(/\.json$/, "");
if (!relative.includes("/")) {
return relative;
}
const [namespace, name] = relative.split("/", 2) as [string, string];
const namespacePrefix = namespace
.split(/[^A-Za-z0-9]+/)
.filter(Boolean)
.map((segment) => segment[0]!.toUpperCase() + segment.slice(1))
.join("");
return `${namespacePrefix}${name}`;
}
function buildJsonSchemaFiles(
entries: ReadonlyArray<GithubContentEntry>,
): ReadonlyArray<JsonSchemaFile> {
return entries
.filter(
(entry) =>
entry.type === "file" &&
entry.name.endsWith(".json") &&
entry.download_url !== null &&
!entry.name.startsWith("codex_app_server_protocol."),
)
.map((entry) => {
const relative = entry.path.replace(/^codex-rs\/app-server-protocol\/schema\/json\//, "");
const parts = relative.split("/");
if (parts.length > 1) {
return {
namespace: parts[0]!,
exportName: exportNameForPath(relative),
fileName: entry.name,
downloadUrl: entry.download_url!,
qualifiedName: relative.replace(/\.json$/, ""),
} satisfies JsonSchemaFile;
}
return {
exportName: exportNameForPath(relative),
fileName: entry.name,
downloadUrl: entry.download_url!,
qualifiedName: relative.replace(/\.json$/, ""),
} satisfies JsonSchemaFile;
});
}
function rewriteExternalRefs(
value: typeof Schema.Json.Type,
localDefinitionNames: ReadonlyMap<string, string>,
currentNamespace: string | undefined,
exportNameByQualifiedName: ReadonlyMap<string, string>,
): typeof Schema.Json.Type {
if (Array.isArray(value)) {
return value.map((entry) =>
rewriteExternalRefs(entry, localDefinitionNames, currentNamespace, exportNameByQualifiedName),
);
}
if (value === null || typeof value !== "object") {
return value;
}
return Object.fromEntries(
Object.entries(value).map(([key, child]) => {
if (key === "$ref" && typeof child === "string" && child.startsWith("#/definitions/")) {
const definitionName = child.slice("#/definitions/".length);
const localRewrite = localDefinitionNames.get(definitionName);
if (localRewrite) {
return [key, `#/definitions/${localRewrite}`];
}
const candidates = [
...(currentNamespace ? [`${currentNamespace}/${definitionName}`] : []),
definitionName,
definitionName.replace(/^v[12]\//, ""),
definitionName.replace(/^serde_json\//, ""),
`v2/${definitionName}`,
`v1/${definitionName}`,
`serde_json/${definitionName}`,
];
const rewritten = candidates
.map((candidate) => exportNameByQualifiedName.get(candidate))
.find((candidate) => candidate !== undefined);
if (!rewritten) {
throw new Error(`Missing rewritten definition for ref: ${child}`);
}
return [key, `#/definitions/${rewritten}`];
}
return [
key,
rewriteExternalRefs(
child,
localDefinitionNames,
currentNamespace,
exportNameByQualifiedName,
),
];
}),
) as typeof Schema.Json.Type;
}
const generateFiles = Effect.fn("generateFiles")(function* () {
yield* ensureGeneratedDir();
const [rootJsonEntries, v1JsonEntries, v2JsonEntries] = yield* Effect.all([
fetchDirectoryEntries("schema/json"),
fetchDirectoryEntries("schema/json/v1"),
fetchDirectoryEntries("schema/json/v2"),
]);
const jsonSchemaFiles = [
...buildJsonSchemaFiles(rootJsonEntries),
...buildJsonSchemaFiles(v1JsonEntries),
...buildJsonSchemaFiles(v2JsonEntries),
].toSorted((left, right) => left.exportName.localeCompare(right.exportName));
const exportNameByQualifiedName = new Map(
jsonSchemaFiles.map((file) => [file.qualifiedName, file.exportName]),
);
const aggregateSchemas: Record<string, typeof Schema.Json.Type> = {};
for (const file of jsonSchemaFiles) {
const raw = yield* fetchText(file.downloadUrl);
const parsed = JSON.parse(raw) as {
readonly definitions?: Record<string, typeof Schema.Json.Type>;
} & Record<string, typeof Schema.Json.Type>;
const localDefinitionNames = new Map(
Object.keys(parsed.definitions ?? {}).map((definitionName) => [
definitionName,
`${file.exportName}__${definitionName.replace(/[^A-Za-z0-9]/g, "")}`,
]),
);
for (const [definitionName, definitionSchema] of Object.entries(parsed.definitions ?? {})) {
aggregateSchemas[localDefinitionNames.get(definitionName)!] = stripNullDefaults(
normalizeNullableTypes(
rewriteExternalRefs(
definitionSchema,
localDefinitionNames,
file.namespace,
exportNameByQualifiedName,
),
),
);
}
const topLevelSchema: Record<string, typeof Schema.Json.Type> = {};
for (const [key, value] of Object.entries(parsed)) {
if (key !== "definitions") {
topLevelSchema[key] = value;
}
}
aggregateSchemas[file.exportName] = stripNullDefaults(
normalizeNullableTypes(
rewriteExternalRefs(
topLevelSchema,
localDefinitionNames,
file.namespace,
exportNameByQualifiedName,
),
),
);
}
for (const [name, schema] of Object.entries(ManualSchemas)) {
if (!(name in aggregateSchemas)) {
aggregateSchemas[name] = stripNullDefaults(normalizeNullableTypes(schema));
}
}
const generator = makeJsonSchemaGenerator();
for (const [name, schema] of Object.entries(aggregateSchemas).toSorted(([left], [right]) =>
left.localeCompare(right),
)) {
generator.addSchema(name, schema as never);
}
const generatedEntries = new Map<string, string>();
const output = generator.generate("openapi-3.1", aggregateSchemas as never, false).trim();
if (output.length > 0) {
for (const entry of collectSchemaEntries(output)) {
if (!generatedEntries.has(entry.name)) {
generatedEntries.set(entry.name, entry.code);
}
}
}
const generatedSchemaNames = new Set(generatedEntries.keys());
const clientRequestRaw = yield* fetchText(
`https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts`,
);
const clientNotificationRaw = yield* fetchText(
`https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientNotification.ts`,
);
const serverRequestRaw = yield* fetchText(
`https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerRequest.ts`,
);
const serverNotificationRaw = yield* fetchText(
`https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts`,
);
const clientRequestEntries = parseRequestEntries(clientRequestRaw);
const clientNotificationEntries = parseNotificationEntries(clientNotificationRaw);
const serverRequestEntries = parseRequestEntries(serverRequestRaw);
const serverNotificationEntries = parseNotificationEntries(serverNotificationRaw);
const prelude = [
"// This file is generated by the effect-codex-app-server package. Do not edit manually.",
`// Upstream protocol ref: ${UPSTREAM_REF}`,
"",
];
const schemaOutput = [
...prelude,
'import * as Schema from "effect/Schema";',
"",
[...generatedEntries.values()].join("\n\n"),
"",
].join("\n");
const metaOutput = [
...prelude,
'import * as CodexSchema from "./schema.gen.ts";',
"",
renderMethodConstants("CLIENT_REQUEST_METHODS", clientRequestEntries),
renderMethodConstants("CLIENT_NOTIFICATION_METHODS", clientNotificationEntries),
renderMethodConstants("SERVER_REQUEST_METHODS", serverRequestEntries),
renderMethodConstants("SERVER_NOTIFICATION_METHODS", serverNotificationEntries),
"export type ClientRequestMethod = keyof typeof CLIENT_REQUEST_METHODS;",
"export type ClientNotificationMethod = keyof typeof CLIENT_NOTIFICATION_METHODS;",
"export type ServerRequestMethod = keyof typeof SERVER_REQUEST_METHODS;",
"export type ServerNotificationMethod = keyof typeof SERVER_NOTIFICATION_METHODS;",
"",
renderTypeInterface("ClientRequestParamsByMethod", clientRequestEntries, (entry) =>
renderSchemaTypeReference(
resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
),
),
renderTypeInterface("ClientRequestResponsesByMethod", clientRequestEntries, (entry) =>
renderSchemaTypeReference(
resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
),
),
renderTypeInterface("ClientNotificationParamsByMethod", clientNotificationEntries, (entry) =>
renderSchemaTypeReference(
resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
),
),
renderTypeInterface("ServerRequestParamsByMethod", serverRequestEntries, (entry) =>
renderSchemaTypeReference(
resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
),
),
renderTypeInterface("ServerRequestResponsesByMethod", serverRequestEntries, (entry) =>
renderSchemaTypeReference(
resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
),
),
renderTypeInterface("ServerNotificationParamsByMethod", serverNotificationEntries, (entry) =>
renderSchemaTypeReference(
resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
),
),
renderSchemaMap("CLIENT_REQUEST_PARAMS", clientRequestEntries, (entry) =>
resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
),
renderSchemaMap("CLIENT_REQUEST_RESPONSES", clientRequestEntries, (entry) =>
resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
),
renderSchemaMap("CLIENT_NOTIFICATION_PARAMS", clientNotificationEntries, (entry) =>
resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
),
renderSchemaMap("SERVER_REQUEST_PARAMS", serverRequestEntries, (entry) =>
resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
),
renderSchemaMap("SERVER_REQUEST_RESPONSES", serverRequestEntries, (entry) =>
resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
),
renderSchemaMap("SERVER_NOTIFICATION_PARAMS", serverNotificationEntries, (entry) =>
resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
),
].join("\n");
const namespaceGroups = new Map<string, Array<JsonSchemaFile>>();
for (const file of jsonSchemaFiles) {
if (!file.namespace) {
continue;
}
const current = namespaceGroups.get(file.namespace) ?? [];
current.push(file);
namespaceGroups.set(file.namespace, current);
}
const namespacesOutput = [
...prelude,
'import * as CodexSchema from "./schema.gen.ts";',
"",
...[...namespaceGroups.entries()]
.toSorted(([left], [right]) => left.localeCompare(right))
.map(([namespace, files]) => {
const constantName = namespace.replace(/[^A-Za-z0-9]/g, "");
return [
`export const ${constantName} = {`,
...files
.toSorted((left, right) => left.fileName.localeCompare(right.fileName))
.map(
(file) =>
` ${JSON.stringify(file.fileName.replace(/\.json$/, ""))}: CodexSchema.${file.exportName},`,
),
"} as const;",
"",
].join("\n");
}),
].join("\n");
const fs = yield* FileSystem.FileSystem;
const { generatedDir, metaOutputPath, namespacesOutputPath, schemaOutputPath } =
yield* getGeneratedPaths();
yield* fs.writeFileString(schemaOutputPath, schemaOutput);
yield* fs.writeFileString(metaOutputPath, metaOutput);
yield* fs.writeFileString(namespacesOutputPath, namespacesOutput);
yield* Effect.log(`Generated Codex App Server schemas from ${UPSTREAM_REF}`);
yield* Effect.service(ChildProcessSpawner.ChildProcessSpawner).pipe(
Effect.flatMap((spawner) => spawner.spawn(ChildProcess.make("bun", ["oxfmt", generatedDir]))),
Effect.flatMap((child) => child.exitCode),
Effect.tap((code) =>
code === 0
? Effect.void
: Effect.fail(
new GeneratorError({
detail: `oxfmt failed with exit code ${code}`,
}),
),
),
);
});
generateFiles().pipe(
Effect.scoped,
Effect.provide(Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer)),
NodeRuntime.runMain,
);
@@ -0,0 +1,585 @@
// This file is generated by the effect-codex-app-server package. Do not edit manually.
// Upstream protocol ref: dbfe855f4fd0f5dcdf079882652a8efe622b0595
import * as CodexSchema from "./schema.gen.ts";
export const CLIENT_REQUEST_METHODS = {
initialize: "initialize",
"thread/start": "thread/start",
"thread/resume": "thread/resume",
"thread/fork": "thread/fork",
"thread/archive": "thread/archive",
"thread/unsubscribe": "thread/unsubscribe",
"thread/name/set": "thread/name/set",
"thread/metadata/update": "thread/metadata/update",
"thread/unarchive": "thread/unarchive",
"thread/compact/start": "thread/compact/start",
"thread/shellCommand": "thread/shellCommand",
"thread/rollback": "thread/rollback",
"thread/list": "thread/list",
"thread/loaded/list": "thread/loaded/list",
"thread/read": "thread/read",
"skills/list": "skills/list",
"plugin/list": "plugin/list",
"plugin/read": "plugin/read",
"app/list": "app/list",
"fs/readFile": "fs/readFile",
"fs/writeFile": "fs/writeFile",
"fs/createDirectory": "fs/createDirectory",
"fs/getMetadata": "fs/getMetadata",
"fs/readDirectory": "fs/readDirectory",
"fs/remove": "fs/remove",
"fs/copy": "fs/copy",
"fs/watch": "fs/watch",
"fs/unwatch": "fs/unwatch",
"skills/config/write": "skills/config/write",
"plugin/install": "plugin/install",
"plugin/uninstall": "plugin/uninstall",
"turn/start": "turn/start",
"turn/steer": "turn/steer",
"turn/interrupt": "turn/interrupt",
"review/start": "review/start",
"model/list": "model/list",
"experimentalFeature/list": "experimentalFeature/list",
"experimentalFeature/enablement/set": "experimentalFeature/enablement/set",
"mcpServer/oauth/login": "mcpServer/oauth/login",
"config/mcpServer/reload": "config/mcpServer/reload",
"mcpServerStatus/list": "mcpServerStatus/list",
"mcpServer/resource/read": "mcpServer/resource/read",
"mcpServer/tool/call": "mcpServer/tool/call",
"windowsSandbox/setupStart": "windowsSandbox/setupStart",
"account/login/start": "account/login/start",
"account/login/cancel": "account/login/cancel",
"account/logout": "account/logout",
"account/rateLimits/read": "account/rateLimits/read",
"feedback/upload": "feedback/upload",
"command/exec": "command/exec",
"command/exec/write": "command/exec/write",
"command/exec/terminate": "command/exec/terminate",
"command/exec/resize": "command/exec/resize",
"config/read": "config/read",
"externalAgentConfig/detect": "externalAgentConfig/detect",
"externalAgentConfig/import": "externalAgentConfig/import",
"config/value/write": "config/value/write",
"config/batchWrite": "config/batchWrite",
"configRequirements/read": "configRequirements/read",
"account/read": "account/read",
getConversationSummary: "getConversationSummary",
gitDiffToRemote: "gitDiffToRemote",
getAuthStatus: "getAuthStatus",
fuzzyFileSearch: "fuzzyFileSearch",
} as const;
export const CLIENT_NOTIFICATION_METHODS = {
initialized: "initialized",
} as const;
export const SERVER_REQUEST_METHODS = {
"item/commandExecution/requestApproval": "item/commandExecution/requestApproval",
"item/fileChange/requestApproval": "item/fileChange/requestApproval",
"item/tool/requestUserInput": "item/tool/requestUserInput",
"mcpServer/elicitation/request": "mcpServer/elicitation/request",
"item/permissions/requestApproval": "item/permissions/requestApproval",
"item/tool/call": "item/tool/call",
"account/chatgptAuthTokens/refresh": "account/chatgptAuthTokens/refresh",
applyPatchApproval: "applyPatchApproval",
execCommandApproval: "execCommandApproval",
} as const;
export const SERVER_NOTIFICATION_METHODS = {
error: "error",
"thread/started": "thread/started",
"thread/status/changed": "thread/status/changed",
"thread/archived": "thread/archived",
"thread/unarchived": "thread/unarchived",
"thread/closed": "thread/closed",
"skills/changed": "skills/changed",
"thread/name/updated": "thread/name/updated",
"thread/tokenUsage/updated": "thread/tokenUsage/updated",
"turn/started": "turn/started",
"hook/started": "hook/started",
"turn/completed": "turn/completed",
"hook/completed": "hook/completed",
"turn/diff/updated": "turn/diff/updated",
"turn/plan/updated": "turn/plan/updated",
"item/started": "item/started",
"item/autoApprovalReview/started": "item/autoApprovalReview/started",
"item/autoApprovalReview/completed": "item/autoApprovalReview/completed",
"item/completed": "item/completed",
"rawResponseItem/completed": "rawResponseItem/completed",
"item/agentMessage/delta": "item/agentMessage/delta",
"item/plan/delta": "item/plan/delta",
"command/exec/outputDelta": "command/exec/outputDelta",
"item/commandExecution/outputDelta": "item/commandExecution/outputDelta",
"item/commandExecution/terminalInteraction": "item/commandExecution/terminalInteraction",
"item/fileChange/outputDelta": "item/fileChange/outputDelta",
"serverRequest/resolved": "serverRequest/resolved",
"item/mcpToolCall/progress": "item/mcpToolCall/progress",
"mcpServer/oauthLogin/completed": "mcpServer/oauthLogin/completed",
"mcpServer/startupStatus/updated": "mcpServer/startupStatus/updated",
"account/updated": "account/updated",
"account/rateLimits/updated": "account/rateLimits/updated",
"app/list/updated": "app/list/updated",
"fs/changed": "fs/changed",
"item/reasoning/summaryTextDelta": "item/reasoning/summaryTextDelta",
"item/reasoning/summaryPartAdded": "item/reasoning/summaryPartAdded",
"item/reasoning/textDelta": "item/reasoning/textDelta",
"thread/compacted": "thread/compacted",
"model/rerouted": "model/rerouted",
deprecationNotice: "deprecationNotice",
configWarning: "configWarning",
"fuzzyFileSearch/sessionUpdated": "fuzzyFileSearch/sessionUpdated",
"fuzzyFileSearch/sessionCompleted": "fuzzyFileSearch/sessionCompleted",
"thread/realtime/started": "thread/realtime/started",
"thread/realtime/itemAdded": "thread/realtime/itemAdded",
"thread/realtime/transcriptUpdated": "thread/realtime/transcriptUpdated",
"thread/realtime/outputAudio/delta": "thread/realtime/outputAudio/delta",
"thread/realtime/sdp": "thread/realtime/sdp",
"thread/realtime/error": "thread/realtime/error",
"thread/realtime/closed": "thread/realtime/closed",
"windows/worldWritableWarning": "windows/worldWritableWarning",
"windowsSandbox/setupCompleted": "windowsSandbox/setupCompleted",
"account/login/completed": "account/login/completed",
} as const;
export type ClientRequestMethod = keyof typeof CLIENT_REQUEST_METHODS;
export type ClientNotificationMethod = keyof typeof CLIENT_NOTIFICATION_METHODS;
export type ServerRequestMethod = keyof typeof SERVER_REQUEST_METHODS;
export type ServerNotificationMethod = keyof typeof SERVER_NOTIFICATION_METHODS;
export interface ClientRequestParamsByMethod {
readonly initialize: typeof CodexSchema.V1InitializeParams.Type;
readonly "thread/start": typeof CodexSchema.V2ThreadStartParams.Type;
readonly "thread/resume": typeof CodexSchema.V2ThreadResumeParams.Type;
readonly "thread/fork": typeof CodexSchema.V2ThreadForkParams.Type;
readonly "thread/archive": typeof CodexSchema.V2ThreadArchiveParams.Type;
readonly "thread/unsubscribe": typeof CodexSchema.V2ThreadUnsubscribeParams.Type;
readonly "thread/name/set": typeof CodexSchema.V2ThreadSetNameParams.Type;
readonly "thread/metadata/update": typeof CodexSchema.V2ThreadMetadataUpdateParams.Type;
readonly "thread/unarchive": typeof CodexSchema.V2ThreadUnarchiveParams.Type;
readonly "thread/compact/start": typeof CodexSchema.V2ThreadCompactStartParams.Type;
readonly "thread/shellCommand": typeof CodexSchema.V2ThreadShellCommandParams.Type;
readonly "thread/rollback": typeof CodexSchema.V2ThreadRollbackParams.Type;
readonly "thread/list": typeof CodexSchema.V2ThreadListParams.Type;
readonly "thread/loaded/list": typeof CodexSchema.V2ThreadLoadedListParams.Type;
readonly "thread/read": typeof CodexSchema.V2ThreadReadParams.Type;
readonly "skills/list": typeof CodexSchema.V2SkillsListParams.Type;
readonly "plugin/list": typeof CodexSchema.V2PluginListParams.Type;
readonly "plugin/read": typeof CodexSchema.V2PluginReadParams.Type;
readonly "app/list": typeof CodexSchema.V2AppsListParams.Type;
readonly "fs/readFile": typeof CodexSchema.V2FsReadFileParams.Type;
readonly "fs/writeFile": typeof CodexSchema.V2FsWriteFileParams.Type;
readonly "fs/createDirectory": typeof CodexSchema.V2FsCreateDirectoryParams.Type;
readonly "fs/getMetadata": typeof CodexSchema.V2FsGetMetadataParams.Type;
readonly "fs/readDirectory": typeof CodexSchema.V2FsReadDirectoryParams.Type;
readonly "fs/remove": typeof CodexSchema.V2FsRemoveParams.Type;
readonly "fs/copy": typeof CodexSchema.V2FsCopyParams.Type;
readonly "fs/watch": typeof CodexSchema.V2FsWatchParams.Type;
readonly "fs/unwatch": typeof CodexSchema.V2FsUnwatchParams.Type;
readonly "skills/config/write": typeof CodexSchema.V2SkillsConfigWriteParams.Type;
readonly "plugin/install": typeof CodexSchema.V2PluginInstallParams.Type;
readonly "plugin/uninstall": typeof CodexSchema.V2PluginUninstallParams.Type;
readonly "turn/start": typeof CodexSchema.V2TurnStartParams.Type;
readonly "turn/steer": typeof CodexSchema.V2TurnSteerParams.Type;
readonly "turn/interrupt": typeof CodexSchema.V2TurnInterruptParams.Type;
readonly "review/start": typeof CodexSchema.V2ReviewStartParams.Type;
readonly "model/list": typeof CodexSchema.V2ModelListParams.Type;
readonly "experimentalFeature/list": typeof CodexSchema.V2ExperimentalFeatureListParams.Type;
readonly "experimentalFeature/enablement/set": typeof CodexSchema.V2ExperimentalFeatureEnablementSetParams.Type;
readonly "mcpServer/oauth/login": typeof CodexSchema.V2McpServerOauthLoginParams.Type;
readonly "config/mcpServer/reload": undefined;
readonly "mcpServerStatus/list": typeof CodexSchema.V2ListMcpServerStatusParams.Type;
readonly "mcpServer/resource/read": typeof CodexSchema.V2McpResourceReadParams.Type;
readonly "mcpServer/tool/call": typeof CodexSchema.V2McpServerToolCallParams.Type;
readonly "windowsSandbox/setupStart": typeof CodexSchema.V2WindowsSandboxSetupStartParams.Type;
readonly "account/login/start": typeof CodexSchema.V2LoginAccountParams.Type;
readonly "account/login/cancel": typeof CodexSchema.V2CancelLoginAccountParams.Type;
readonly "account/logout": undefined;
readonly "account/rateLimits/read": undefined;
readonly "feedback/upload": typeof CodexSchema.V2FeedbackUploadParams.Type;
readonly "command/exec": typeof CodexSchema.V2CommandExecParams.Type;
readonly "command/exec/write": typeof CodexSchema.V2CommandExecWriteParams.Type;
readonly "command/exec/terminate": typeof CodexSchema.V2CommandExecTerminateParams.Type;
readonly "command/exec/resize": typeof CodexSchema.V2CommandExecResizeParams.Type;
readonly "config/read": typeof CodexSchema.V2ConfigReadParams.Type;
readonly "externalAgentConfig/detect": typeof CodexSchema.V2ExternalAgentConfigDetectParams.Type;
readonly "externalAgentConfig/import": typeof CodexSchema.V2ExternalAgentConfigImportParams.Type;
readonly "config/value/write": typeof CodexSchema.V2ConfigValueWriteParams.Type;
readonly "config/batchWrite": typeof CodexSchema.V2ConfigBatchWriteParams.Type;
readonly "configRequirements/read": undefined;
readonly "account/read": typeof CodexSchema.V2GetAccountParams.Type;
readonly getConversationSummary: typeof CodexSchema.GetConversationSummaryParams.Type;
readonly gitDiffToRemote: typeof CodexSchema.GitDiffToRemoteParams.Type;
readonly getAuthStatus: typeof CodexSchema.GetAuthStatusParams.Type;
readonly fuzzyFileSearch: typeof CodexSchema.FuzzyFileSearchParams.Type;
}
export interface ClientRequestResponsesByMethod {
readonly initialize: typeof CodexSchema.V1InitializeResponse.Type;
readonly "thread/start": typeof CodexSchema.V2ThreadStartResponse.Type;
readonly "thread/resume": typeof CodexSchema.V2ThreadResumeResponse.Type;
readonly "thread/fork": typeof CodexSchema.V2ThreadForkResponse.Type;
readonly "thread/archive": typeof CodexSchema.V2ThreadArchiveResponse.Type;
readonly "thread/unsubscribe": typeof CodexSchema.V2ThreadUnsubscribeResponse.Type;
readonly "thread/name/set": typeof CodexSchema.V2ThreadSetNameResponse.Type;
readonly "thread/metadata/update": typeof CodexSchema.V2ThreadMetadataUpdateResponse.Type;
readonly "thread/unarchive": typeof CodexSchema.V2ThreadUnarchiveResponse.Type;
readonly "thread/compact/start": typeof CodexSchema.V2ThreadCompactStartResponse.Type;
readonly "thread/shellCommand": typeof CodexSchema.V2ThreadShellCommandResponse.Type;
readonly "thread/rollback": typeof CodexSchema.V2ThreadRollbackResponse.Type;
readonly "thread/list": typeof CodexSchema.V2ThreadListResponse.Type;
readonly "thread/loaded/list": typeof CodexSchema.V2ThreadLoadedListResponse.Type;
readonly "thread/read": typeof CodexSchema.V2ThreadReadResponse.Type;
readonly "skills/list": typeof CodexSchema.V2SkillsListResponse.Type;
readonly "plugin/list": typeof CodexSchema.V2PluginListResponse.Type;
readonly "plugin/read": typeof CodexSchema.V2PluginReadResponse.Type;
readonly "app/list": typeof CodexSchema.V2AppsListResponse.Type;
readonly "fs/readFile": typeof CodexSchema.V2FsReadFileResponse.Type;
readonly "fs/writeFile": typeof CodexSchema.V2FsWriteFileResponse.Type;
readonly "fs/createDirectory": typeof CodexSchema.V2FsCreateDirectoryResponse.Type;
readonly "fs/getMetadata": typeof CodexSchema.V2FsGetMetadataResponse.Type;
readonly "fs/readDirectory": typeof CodexSchema.V2FsReadDirectoryResponse.Type;
readonly "fs/remove": typeof CodexSchema.V2FsRemoveResponse.Type;
readonly "fs/copy": typeof CodexSchema.V2FsCopyResponse.Type;
readonly "fs/watch": typeof CodexSchema.V2FsWatchResponse.Type;
readonly "fs/unwatch": typeof CodexSchema.V2FsUnwatchResponse.Type;
readonly "skills/config/write": typeof CodexSchema.V2SkillsConfigWriteResponse.Type;
readonly "plugin/install": typeof CodexSchema.V2PluginInstallResponse.Type;
readonly "plugin/uninstall": typeof CodexSchema.V2PluginUninstallResponse.Type;
readonly "turn/start": typeof CodexSchema.V2TurnStartResponse.Type;
readonly "turn/steer": typeof CodexSchema.V2TurnSteerResponse.Type;
readonly "turn/interrupt": typeof CodexSchema.V2TurnInterruptResponse.Type;
readonly "review/start": typeof CodexSchema.V2ReviewStartResponse.Type;
readonly "model/list": typeof CodexSchema.V2ModelListResponse.Type;
readonly "experimentalFeature/list": typeof CodexSchema.V2ExperimentalFeatureListResponse.Type;
readonly "experimentalFeature/enablement/set": typeof CodexSchema.V2ExperimentalFeatureEnablementSetResponse.Type;
readonly "mcpServer/oauth/login": typeof CodexSchema.V2McpServerOauthLoginResponse.Type;
readonly "config/mcpServer/reload": typeof CodexSchema.V2McpServerRefreshResponse.Type;
readonly "mcpServerStatus/list": typeof CodexSchema.V2ListMcpServerStatusResponse.Type;
readonly "mcpServer/resource/read": typeof CodexSchema.V2McpResourceReadResponse.Type;
readonly "mcpServer/tool/call": typeof CodexSchema.V2McpServerToolCallResponse.Type;
readonly "windowsSandbox/setupStart": typeof CodexSchema.V2WindowsSandboxSetupStartResponse.Type;
readonly "account/login/start": typeof CodexSchema.V2LoginAccountResponse.Type;
readonly "account/login/cancel": typeof CodexSchema.V2CancelLoginAccountResponse.Type;
readonly "account/logout": typeof CodexSchema.V2LogoutAccountResponse.Type;
readonly "account/rateLimits/read": typeof CodexSchema.V2GetAccountRateLimitsResponse.Type;
readonly "feedback/upload": typeof CodexSchema.V2FeedbackUploadResponse.Type;
readonly "command/exec": typeof CodexSchema.V2CommandExecResponse.Type;
readonly "command/exec/write": typeof CodexSchema.V2CommandExecWriteResponse.Type;
readonly "command/exec/terminate": typeof CodexSchema.V2CommandExecTerminateResponse.Type;
readonly "command/exec/resize": typeof CodexSchema.V2CommandExecResizeResponse.Type;
readonly "config/read": typeof CodexSchema.V2ConfigReadResponse.Type;
readonly "externalAgentConfig/detect": typeof CodexSchema.V2ExternalAgentConfigDetectResponse.Type;
readonly "externalAgentConfig/import": typeof CodexSchema.V2ExternalAgentConfigImportResponse.Type;
readonly "config/value/write": typeof CodexSchema.V2ConfigWriteResponse.Type;
readonly "config/batchWrite": typeof CodexSchema.V2ConfigWriteResponse.Type;
readonly "configRequirements/read": typeof CodexSchema.V2ConfigRequirementsReadResponse.Type;
readonly "account/read": typeof CodexSchema.V2GetAccountResponse.Type;
readonly getConversationSummary: typeof CodexSchema.GetConversationSummaryResponse.Type;
readonly gitDiffToRemote: typeof CodexSchema.GitDiffToRemoteResponse.Type;
readonly getAuthStatus: typeof CodexSchema.GetAuthStatusResponse.Type;
readonly fuzzyFileSearch: typeof CodexSchema.FuzzyFileSearchResponse.Type;
}
export interface ClientNotificationParamsByMethod {
readonly initialized: undefined;
}
export interface ServerRequestParamsByMethod {
readonly "item/commandExecution/requestApproval": typeof CodexSchema.CommandExecutionRequestApprovalParams.Type;
readonly "item/fileChange/requestApproval": typeof CodexSchema.FileChangeRequestApprovalParams.Type;
readonly "item/tool/requestUserInput": typeof CodexSchema.ToolRequestUserInputParams.Type;
readonly "mcpServer/elicitation/request": typeof CodexSchema.McpServerElicitationRequestParams.Type;
readonly "item/permissions/requestApproval": typeof CodexSchema.PermissionsRequestApprovalParams.Type;
readonly "item/tool/call": typeof CodexSchema.DynamicToolCallParams.Type;
readonly "account/chatgptAuthTokens/refresh": typeof CodexSchema.ChatgptAuthTokensRefreshParams.Type;
readonly applyPatchApproval: typeof CodexSchema.ApplyPatchApprovalParams.Type;
readonly execCommandApproval: typeof CodexSchema.ExecCommandApprovalParams.Type;
}
export interface ServerRequestResponsesByMethod {
readonly "item/commandExecution/requestApproval": typeof CodexSchema.CommandExecutionRequestApprovalResponse.Type;
readonly "item/fileChange/requestApproval": typeof CodexSchema.FileChangeRequestApprovalResponse.Type;
readonly "item/tool/requestUserInput": typeof CodexSchema.ToolRequestUserInputResponse.Type;
readonly "mcpServer/elicitation/request": typeof CodexSchema.McpServerElicitationRequestResponse.Type;
readonly "item/permissions/requestApproval": typeof CodexSchema.PermissionsRequestApprovalResponse.Type;
readonly "item/tool/call": typeof CodexSchema.DynamicToolCallResponse.Type;
readonly "account/chatgptAuthTokens/refresh": typeof CodexSchema.ChatgptAuthTokensRefreshResponse.Type;
readonly applyPatchApproval: typeof CodexSchema.ApplyPatchApprovalResponse.Type;
readonly execCommandApproval: typeof CodexSchema.ExecCommandApprovalResponse.Type;
}
export interface ServerNotificationParamsByMethod {
readonly error: typeof CodexSchema.V2ErrorNotification.Type;
readonly "thread/started": typeof CodexSchema.V2ThreadStartedNotification.Type;
readonly "thread/status/changed": typeof CodexSchema.V2ThreadStatusChangedNotification.Type;
readonly "thread/archived": typeof CodexSchema.V2ThreadArchivedNotification.Type;
readonly "thread/unarchived": typeof CodexSchema.V2ThreadUnarchivedNotification.Type;
readonly "thread/closed": typeof CodexSchema.V2ThreadClosedNotification.Type;
readonly "skills/changed": typeof CodexSchema.V2SkillsChangedNotification.Type;
readonly "thread/name/updated": typeof CodexSchema.V2ThreadNameUpdatedNotification.Type;
readonly "thread/tokenUsage/updated": typeof CodexSchema.V2ThreadTokenUsageUpdatedNotification.Type;
readonly "turn/started": typeof CodexSchema.V2TurnStartedNotification.Type;
readonly "hook/started": typeof CodexSchema.V2HookStartedNotification.Type;
readonly "turn/completed": typeof CodexSchema.V2TurnCompletedNotification.Type;
readonly "hook/completed": typeof CodexSchema.V2HookCompletedNotification.Type;
readonly "turn/diff/updated": typeof CodexSchema.V2TurnDiffUpdatedNotification.Type;
readonly "turn/plan/updated": typeof CodexSchema.V2TurnPlanUpdatedNotification.Type;
readonly "item/started": typeof CodexSchema.V2ItemStartedNotification.Type;
readonly "item/autoApprovalReview/started": typeof CodexSchema.V2ItemGuardianApprovalReviewStartedNotification.Type;
readonly "item/autoApprovalReview/completed": typeof CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification.Type;
readonly "item/completed": typeof CodexSchema.V2ItemCompletedNotification.Type;
readonly "rawResponseItem/completed": typeof CodexSchema.V2RawResponseItemCompletedNotification.Type;
readonly "item/agentMessage/delta": typeof CodexSchema.V2AgentMessageDeltaNotification.Type;
readonly "item/plan/delta": typeof CodexSchema.V2PlanDeltaNotification.Type;
readonly "command/exec/outputDelta": typeof CodexSchema.V2CommandExecOutputDeltaNotification.Type;
readonly "item/commandExecution/outputDelta": typeof CodexSchema.V2CommandExecutionOutputDeltaNotification.Type;
readonly "item/commandExecution/terminalInteraction": typeof CodexSchema.V2TerminalInteractionNotification.Type;
readonly "item/fileChange/outputDelta": typeof CodexSchema.V2FileChangeOutputDeltaNotification.Type;
readonly "serverRequest/resolved": typeof CodexSchema.V2ServerRequestResolvedNotification.Type;
readonly "item/mcpToolCall/progress": typeof CodexSchema.V2McpToolCallProgressNotification.Type;
readonly "mcpServer/oauthLogin/completed": typeof CodexSchema.V2McpServerOauthLoginCompletedNotification.Type;
readonly "mcpServer/startupStatus/updated": typeof CodexSchema.V2McpServerStatusUpdatedNotification.Type;
readonly "account/updated": typeof CodexSchema.V2AccountUpdatedNotification.Type;
readonly "account/rateLimits/updated": typeof CodexSchema.V2AccountRateLimitsUpdatedNotification.Type;
readonly "app/list/updated": typeof CodexSchema.V2AppListUpdatedNotification.Type;
readonly "fs/changed": typeof CodexSchema.V2FsChangedNotification.Type;
readonly "item/reasoning/summaryTextDelta": typeof CodexSchema.V2ReasoningSummaryTextDeltaNotification.Type;
readonly "item/reasoning/summaryPartAdded": typeof CodexSchema.V2ReasoningSummaryPartAddedNotification.Type;
readonly "item/reasoning/textDelta": typeof CodexSchema.V2ReasoningTextDeltaNotification.Type;
readonly "thread/compacted": typeof CodexSchema.V2ContextCompactedNotification.Type;
readonly "model/rerouted": typeof CodexSchema.V2ModelReroutedNotification.Type;
readonly deprecationNotice: typeof CodexSchema.V2DeprecationNoticeNotification.Type;
readonly configWarning: typeof CodexSchema.V2ConfigWarningNotification.Type;
readonly "fuzzyFileSearch/sessionUpdated": typeof CodexSchema.FuzzyFileSearchSessionUpdatedNotification.Type;
readonly "fuzzyFileSearch/sessionCompleted": typeof CodexSchema.FuzzyFileSearchSessionCompletedNotification.Type;
readonly "thread/realtime/started": typeof CodexSchema.V2ThreadRealtimeStartedNotification.Type;
readonly "thread/realtime/itemAdded": typeof CodexSchema.V2ThreadRealtimeItemAddedNotification.Type;
readonly "thread/realtime/transcriptUpdated": typeof CodexSchema.V2ThreadRealtimeTranscriptUpdatedNotification.Type;
readonly "thread/realtime/outputAudio/delta": typeof CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification.Type;
readonly "thread/realtime/sdp": typeof CodexSchema.V2ThreadRealtimeSdpNotification.Type;
readonly "thread/realtime/error": typeof CodexSchema.V2ThreadRealtimeErrorNotification.Type;
readonly "thread/realtime/closed": typeof CodexSchema.V2ThreadRealtimeClosedNotification.Type;
readonly "windows/worldWritableWarning": typeof CodexSchema.V2WindowsWorldWritableWarningNotification.Type;
readonly "windowsSandbox/setupCompleted": typeof CodexSchema.V2WindowsSandboxSetupCompletedNotification.Type;
readonly "account/login/completed": typeof CodexSchema.V2AccountLoginCompletedNotification.Type;
}
export const CLIENT_REQUEST_PARAMS = {
initialize: CodexSchema.V1InitializeParams,
"thread/start": CodexSchema.V2ThreadStartParams,
"thread/resume": CodexSchema.V2ThreadResumeParams,
"thread/fork": CodexSchema.V2ThreadForkParams,
"thread/archive": CodexSchema.V2ThreadArchiveParams,
"thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeParams,
"thread/name/set": CodexSchema.V2ThreadSetNameParams,
"thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateParams,
"thread/unarchive": CodexSchema.V2ThreadUnarchiveParams,
"thread/compact/start": CodexSchema.V2ThreadCompactStartParams,
"thread/shellCommand": CodexSchema.V2ThreadShellCommandParams,
"thread/rollback": CodexSchema.V2ThreadRollbackParams,
"thread/list": CodexSchema.V2ThreadListParams,
"thread/loaded/list": CodexSchema.V2ThreadLoadedListParams,
"thread/read": CodexSchema.V2ThreadReadParams,
"skills/list": CodexSchema.V2SkillsListParams,
"plugin/list": CodexSchema.V2PluginListParams,
"plugin/read": CodexSchema.V2PluginReadParams,
"app/list": CodexSchema.V2AppsListParams,
"fs/readFile": CodexSchema.V2FsReadFileParams,
"fs/writeFile": CodexSchema.V2FsWriteFileParams,
"fs/createDirectory": CodexSchema.V2FsCreateDirectoryParams,
"fs/getMetadata": CodexSchema.V2FsGetMetadataParams,
"fs/readDirectory": CodexSchema.V2FsReadDirectoryParams,
"fs/remove": CodexSchema.V2FsRemoveParams,
"fs/copy": CodexSchema.V2FsCopyParams,
"fs/watch": CodexSchema.V2FsWatchParams,
"fs/unwatch": CodexSchema.V2FsUnwatchParams,
"skills/config/write": CodexSchema.V2SkillsConfigWriteParams,
"plugin/install": CodexSchema.V2PluginInstallParams,
"plugin/uninstall": CodexSchema.V2PluginUninstallParams,
"turn/start": CodexSchema.V2TurnStartParams,
"turn/steer": CodexSchema.V2TurnSteerParams,
"turn/interrupt": CodexSchema.V2TurnInterruptParams,
"review/start": CodexSchema.V2ReviewStartParams,
"model/list": CodexSchema.V2ModelListParams,
"experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListParams,
"experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetParams,
"mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginParams,
"config/mcpServer/reload": undefined,
"mcpServerStatus/list": CodexSchema.V2ListMcpServerStatusParams,
"mcpServer/resource/read": CodexSchema.V2McpResourceReadParams,
"mcpServer/tool/call": CodexSchema.V2McpServerToolCallParams,
"windowsSandbox/setupStart": CodexSchema.V2WindowsSandboxSetupStartParams,
"account/login/start": CodexSchema.V2LoginAccountParams,
"account/login/cancel": CodexSchema.V2CancelLoginAccountParams,
"account/logout": undefined,
"account/rateLimits/read": undefined,
"feedback/upload": CodexSchema.V2FeedbackUploadParams,
"command/exec": CodexSchema.V2CommandExecParams,
"command/exec/write": CodexSchema.V2CommandExecWriteParams,
"command/exec/terminate": CodexSchema.V2CommandExecTerminateParams,
"command/exec/resize": CodexSchema.V2CommandExecResizeParams,
"config/read": CodexSchema.V2ConfigReadParams,
"externalAgentConfig/detect": CodexSchema.V2ExternalAgentConfigDetectParams,
"externalAgentConfig/import": CodexSchema.V2ExternalAgentConfigImportParams,
"config/value/write": CodexSchema.V2ConfigValueWriteParams,
"config/batchWrite": CodexSchema.V2ConfigBatchWriteParams,
"configRequirements/read": undefined,
"account/read": CodexSchema.V2GetAccountParams,
getConversationSummary: CodexSchema.GetConversationSummaryParams,
gitDiffToRemote: CodexSchema.GitDiffToRemoteParams,
getAuthStatus: CodexSchema.GetAuthStatusParams,
fuzzyFileSearch: CodexSchema.FuzzyFileSearchParams,
} as const;
export const CLIENT_REQUEST_RESPONSES = {
initialize: CodexSchema.V1InitializeResponse,
"thread/start": CodexSchema.V2ThreadStartResponse,
"thread/resume": CodexSchema.V2ThreadResumeResponse,
"thread/fork": CodexSchema.V2ThreadForkResponse,
"thread/archive": CodexSchema.V2ThreadArchiveResponse,
"thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeResponse,
"thread/name/set": CodexSchema.V2ThreadSetNameResponse,
"thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateResponse,
"thread/unarchive": CodexSchema.V2ThreadUnarchiveResponse,
"thread/compact/start": CodexSchema.V2ThreadCompactStartResponse,
"thread/shellCommand": CodexSchema.V2ThreadShellCommandResponse,
"thread/rollback": CodexSchema.V2ThreadRollbackResponse,
"thread/list": CodexSchema.V2ThreadListResponse,
"thread/loaded/list": CodexSchema.V2ThreadLoadedListResponse,
"thread/read": CodexSchema.V2ThreadReadResponse,
"skills/list": CodexSchema.V2SkillsListResponse,
"plugin/list": CodexSchema.V2PluginListResponse,
"plugin/read": CodexSchema.V2PluginReadResponse,
"app/list": CodexSchema.V2AppsListResponse,
"fs/readFile": CodexSchema.V2FsReadFileResponse,
"fs/writeFile": CodexSchema.V2FsWriteFileResponse,
"fs/createDirectory": CodexSchema.V2FsCreateDirectoryResponse,
"fs/getMetadata": CodexSchema.V2FsGetMetadataResponse,
"fs/readDirectory": CodexSchema.V2FsReadDirectoryResponse,
"fs/remove": CodexSchema.V2FsRemoveResponse,
"fs/copy": CodexSchema.V2FsCopyResponse,
"fs/watch": CodexSchema.V2FsWatchResponse,
"fs/unwatch": CodexSchema.V2FsUnwatchResponse,
"skills/config/write": CodexSchema.V2SkillsConfigWriteResponse,
"plugin/install": CodexSchema.V2PluginInstallResponse,
"plugin/uninstall": CodexSchema.V2PluginUninstallResponse,
"turn/start": CodexSchema.V2TurnStartResponse,
"turn/steer": CodexSchema.V2TurnSteerResponse,
"turn/interrupt": CodexSchema.V2TurnInterruptResponse,
"review/start": CodexSchema.V2ReviewStartResponse,
"model/list": CodexSchema.V2ModelListResponse,
"experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListResponse,
"experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetResponse,
"mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginResponse,
"config/mcpServer/reload": CodexSchema.V2McpServerRefreshResponse,
"mcpServerStatus/list": CodexSchema.V2ListMcpServerStatusResponse,
"mcpServer/resource/read": CodexSchema.V2McpResourceReadResponse,
"mcpServer/tool/call": CodexSchema.V2McpServerToolCallResponse,
"windowsSandbox/setupStart": CodexSchema.V2WindowsSandboxSetupStartResponse,
"account/login/start": CodexSchema.V2LoginAccountResponse,
"account/login/cancel": CodexSchema.V2CancelLoginAccountResponse,
"account/logout": CodexSchema.V2LogoutAccountResponse,
"account/rateLimits/read": CodexSchema.V2GetAccountRateLimitsResponse,
"feedback/upload": CodexSchema.V2FeedbackUploadResponse,
"command/exec": CodexSchema.V2CommandExecResponse,
"command/exec/write": CodexSchema.V2CommandExecWriteResponse,
"command/exec/terminate": CodexSchema.V2CommandExecTerminateResponse,
"command/exec/resize": CodexSchema.V2CommandExecResizeResponse,
"config/read": CodexSchema.V2ConfigReadResponse,
"externalAgentConfig/detect": CodexSchema.V2ExternalAgentConfigDetectResponse,
"externalAgentConfig/import": CodexSchema.V2ExternalAgentConfigImportResponse,
"config/value/write": CodexSchema.V2ConfigWriteResponse,
"config/batchWrite": CodexSchema.V2ConfigWriteResponse,
"configRequirements/read": CodexSchema.V2ConfigRequirementsReadResponse,
"account/read": CodexSchema.V2GetAccountResponse,
getConversationSummary: CodexSchema.GetConversationSummaryResponse,
gitDiffToRemote: CodexSchema.GitDiffToRemoteResponse,
getAuthStatus: CodexSchema.GetAuthStatusResponse,
fuzzyFileSearch: CodexSchema.FuzzyFileSearchResponse,
} as const;
export const CLIENT_NOTIFICATION_PARAMS = {
initialized: undefined,
} as const;
export const SERVER_REQUEST_PARAMS = {
"item/commandExecution/requestApproval": CodexSchema.CommandExecutionRequestApprovalParams,
"item/fileChange/requestApproval": CodexSchema.FileChangeRequestApprovalParams,
"item/tool/requestUserInput": CodexSchema.ToolRequestUserInputParams,
"mcpServer/elicitation/request": CodexSchema.McpServerElicitationRequestParams,
"item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalParams,
"item/tool/call": CodexSchema.DynamicToolCallParams,
"account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshParams,
applyPatchApproval: CodexSchema.ApplyPatchApprovalParams,
execCommandApproval: CodexSchema.ExecCommandApprovalParams,
} as const;
export const SERVER_REQUEST_RESPONSES = {
"item/commandExecution/requestApproval": CodexSchema.CommandExecutionRequestApprovalResponse,
"item/fileChange/requestApproval": CodexSchema.FileChangeRequestApprovalResponse,
"item/tool/requestUserInput": CodexSchema.ToolRequestUserInputResponse,
"mcpServer/elicitation/request": CodexSchema.McpServerElicitationRequestResponse,
"item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalResponse,
"item/tool/call": CodexSchema.DynamicToolCallResponse,
"account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshResponse,
applyPatchApproval: CodexSchema.ApplyPatchApprovalResponse,
execCommandApproval: CodexSchema.ExecCommandApprovalResponse,
} as const;
export const SERVER_NOTIFICATION_PARAMS = {
error: CodexSchema.V2ErrorNotification,
"thread/started": CodexSchema.V2ThreadStartedNotification,
"thread/status/changed": CodexSchema.V2ThreadStatusChangedNotification,
"thread/archived": CodexSchema.V2ThreadArchivedNotification,
"thread/unarchived": CodexSchema.V2ThreadUnarchivedNotification,
"thread/closed": CodexSchema.V2ThreadClosedNotification,
"skills/changed": CodexSchema.V2SkillsChangedNotification,
"thread/name/updated": CodexSchema.V2ThreadNameUpdatedNotification,
"thread/tokenUsage/updated": CodexSchema.V2ThreadTokenUsageUpdatedNotification,
"turn/started": CodexSchema.V2TurnStartedNotification,
"hook/started": CodexSchema.V2HookStartedNotification,
"turn/completed": CodexSchema.V2TurnCompletedNotification,
"hook/completed": CodexSchema.V2HookCompletedNotification,
"turn/diff/updated": CodexSchema.V2TurnDiffUpdatedNotification,
"turn/plan/updated": CodexSchema.V2TurnPlanUpdatedNotification,
"item/started": CodexSchema.V2ItemStartedNotification,
"item/autoApprovalReview/started": CodexSchema.V2ItemGuardianApprovalReviewStartedNotification,
"item/autoApprovalReview/completed":
CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification,
"item/completed": CodexSchema.V2ItemCompletedNotification,
"rawResponseItem/completed": CodexSchema.V2RawResponseItemCompletedNotification,
"item/agentMessage/delta": CodexSchema.V2AgentMessageDeltaNotification,
"item/plan/delta": CodexSchema.V2PlanDeltaNotification,
"command/exec/outputDelta": CodexSchema.V2CommandExecOutputDeltaNotification,
"item/commandExecution/outputDelta": CodexSchema.V2CommandExecutionOutputDeltaNotification,
"item/commandExecution/terminalInteraction": CodexSchema.V2TerminalInteractionNotification,
"item/fileChange/outputDelta": CodexSchema.V2FileChangeOutputDeltaNotification,
"serverRequest/resolved": CodexSchema.V2ServerRequestResolvedNotification,
"item/mcpToolCall/progress": CodexSchema.V2McpToolCallProgressNotification,
"mcpServer/oauthLogin/completed": CodexSchema.V2McpServerOauthLoginCompletedNotification,
"mcpServer/startupStatus/updated": CodexSchema.V2McpServerStatusUpdatedNotification,
"account/updated": CodexSchema.V2AccountUpdatedNotification,
"account/rateLimits/updated": CodexSchema.V2AccountRateLimitsUpdatedNotification,
"app/list/updated": CodexSchema.V2AppListUpdatedNotification,
"fs/changed": CodexSchema.V2FsChangedNotification,
"item/reasoning/summaryTextDelta": CodexSchema.V2ReasoningSummaryTextDeltaNotification,
"item/reasoning/summaryPartAdded": CodexSchema.V2ReasoningSummaryPartAddedNotification,
"item/reasoning/textDelta": CodexSchema.V2ReasoningTextDeltaNotification,
"thread/compacted": CodexSchema.V2ContextCompactedNotification,
"model/rerouted": CodexSchema.V2ModelReroutedNotification,
deprecationNotice: CodexSchema.V2DeprecationNoticeNotification,
configWarning: CodexSchema.V2ConfigWarningNotification,
"fuzzyFileSearch/sessionUpdated": CodexSchema.FuzzyFileSearchSessionUpdatedNotification,
"fuzzyFileSearch/sessionCompleted": CodexSchema.FuzzyFileSearchSessionCompletedNotification,
"thread/realtime/started": CodexSchema.V2ThreadRealtimeStartedNotification,
"thread/realtime/itemAdded": CodexSchema.V2ThreadRealtimeItemAddedNotification,
"thread/realtime/transcriptUpdated": CodexSchema.V2ThreadRealtimeTranscriptUpdatedNotification,
"thread/realtime/outputAudio/delta": CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification,
"thread/realtime/sdp": CodexSchema.V2ThreadRealtimeSdpNotification,
"thread/realtime/error": CodexSchema.V2ThreadRealtimeErrorNotification,
"thread/realtime/closed": CodexSchema.V2ThreadRealtimeClosedNotification,
"windows/worldWritableWarning": CodexSchema.V2WindowsWorldWritableWarningNotification,
"windowsSandbox/setupCompleted": CodexSchema.V2WindowsSandboxSetupCompletedNotification,
"account/login/completed": CodexSchema.V2AccountLoginCompletedNotification,
} as const;
@@ -0,0 +1,180 @@
// This file is generated by the effect-codex-app-server package. Do not edit manually.
// Upstream protocol ref: dbfe855f4fd0f5dcdf079882652a8efe622b0595
import * as CodexSchema from "./schema.gen.ts";
export const v1 = {
InitializeParams: CodexSchema.V1InitializeParams,
InitializeResponse: CodexSchema.V1InitializeResponse,
} as const;
export const v2 = {
AccountLoginCompletedNotification: CodexSchema.V2AccountLoginCompletedNotification,
AccountRateLimitsUpdatedNotification: CodexSchema.V2AccountRateLimitsUpdatedNotification,
AccountUpdatedNotification: CodexSchema.V2AccountUpdatedNotification,
AgentMessageDeltaNotification: CodexSchema.V2AgentMessageDeltaNotification,
AppListUpdatedNotification: CodexSchema.V2AppListUpdatedNotification,
AppsListParams: CodexSchema.V2AppsListParams,
AppsListResponse: CodexSchema.V2AppsListResponse,
CancelLoginAccountParams: CodexSchema.V2CancelLoginAccountParams,
CancelLoginAccountResponse: CodexSchema.V2CancelLoginAccountResponse,
CommandExecOutputDeltaNotification: CodexSchema.V2CommandExecOutputDeltaNotification,
CommandExecParams: CodexSchema.V2CommandExecParams,
CommandExecResizeParams: CodexSchema.V2CommandExecResizeParams,
CommandExecResizeResponse: CodexSchema.V2CommandExecResizeResponse,
CommandExecResponse: CodexSchema.V2CommandExecResponse,
CommandExecTerminateParams: CodexSchema.V2CommandExecTerminateParams,
CommandExecTerminateResponse: CodexSchema.V2CommandExecTerminateResponse,
CommandExecutionOutputDeltaNotification: CodexSchema.V2CommandExecutionOutputDeltaNotification,
CommandExecWriteParams: CodexSchema.V2CommandExecWriteParams,
CommandExecWriteResponse: CodexSchema.V2CommandExecWriteResponse,
ConfigBatchWriteParams: CodexSchema.V2ConfigBatchWriteParams,
ConfigReadParams: CodexSchema.V2ConfigReadParams,
ConfigReadResponse: CodexSchema.V2ConfigReadResponse,
ConfigRequirementsReadResponse: CodexSchema.V2ConfigRequirementsReadResponse,
ConfigValueWriteParams: CodexSchema.V2ConfigValueWriteParams,
ConfigWarningNotification: CodexSchema.V2ConfigWarningNotification,
ConfigWriteResponse: CodexSchema.V2ConfigWriteResponse,
ContextCompactedNotification: CodexSchema.V2ContextCompactedNotification,
DeprecationNoticeNotification: CodexSchema.V2DeprecationNoticeNotification,
ErrorNotification: CodexSchema.V2ErrorNotification,
ExperimentalFeatureEnablementSetParams: CodexSchema.V2ExperimentalFeatureEnablementSetParams,
ExperimentalFeatureEnablementSetResponse: CodexSchema.V2ExperimentalFeatureEnablementSetResponse,
ExperimentalFeatureListParams: CodexSchema.V2ExperimentalFeatureListParams,
ExperimentalFeatureListResponse: CodexSchema.V2ExperimentalFeatureListResponse,
ExternalAgentConfigDetectParams: CodexSchema.V2ExternalAgentConfigDetectParams,
ExternalAgentConfigDetectResponse: CodexSchema.V2ExternalAgentConfigDetectResponse,
ExternalAgentConfigImportParams: CodexSchema.V2ExternalAgentConfigImportParams,
ExternalAgentConfigImportResponse: CodexSchema.V2ExternalAgentConfigImportResponse,
FeedbackUploadParams: CodexSchema.V2FeedbackUploadParams,
FeedbackUploadResponse: CodexSchema.V2FeedbackUploadResponse,
FileChangeOutputDeltaNotification: CodexSchema.V2FileChangeOutputDeltaNotification,
FsChangedNotification: CodexSchema.V2FsChangedNotification,
FsCopyParams: CodexSchema.V2FsCopyParams,
FsCopyResponse: CodexSchema.V2FsCopyResponse,
FsCreateDirectoryParams: CodexSchema.V2FsCreateDirectoryParams,
FsCreateDirectoryResponse: CodexSchema.V2FsCreateDirectoryResponse,
FsGetMetadataParams: CodexSchema.V2FsGetMetadataParams,
FsGetMetadataResponse: CodexSchema.V2FsGetMetadataResponse,
FsReadDirectoryParams: CodexSchema.V2FsReadDirectoryParams,
FsReadDirectoryResponse: CodexSchema.V2FsReadDirectoryResponse,
FsReadFileParams: CodexSchema.V2FsReadFileParams,
FsReadFileResponse: CodexSchema.V2FsReadFileResponse,
FsRemoveParams: CodexSchema.V2FsRemoveParams,
FsRemoveResponse: CodexSchema.V2FsRemoveResponse,
FsUnwatchParams: CodexSchema.V2FsUnwatchParams,
FsUnwatchResponse: CodexSchema.V2FsUnwatchResponse,
FsWatchParams: CodexSchema.V2FsWatchParams,
FsWatchResponse: CodexSchema.V2FsWatchResponse,
FsWriteFileParams: CodexSchema.V2FsWriteFileParams,
FsWriteFileResponse: CodexSchema.V2FsWriteFileResponse,
GetAccountParams: CodexSchema.V2GetAccountParams,
GetAccountRateLimitsResponse: CodexSchema.V2GetAccountRateLimitsResponse,
GetAccountResponse: CodexSchema.V2GetAccountResponse,
HookCompletedNotification: CodexSchema.V2HookCompletedNotification,
HookStartedNotification: CodexSchema.V2HookStartedNotification,
ItemCompletedNotification: CodexSchema.V2ItemCompletedNotification,
ItemGuardianApprovalReviewCompletedNotification:
CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification,
ItemGuardianApprovalReviewStartedNotification:
CodexSchema.V2ItemGuardianApprovalReviewStartedNotification,
ItemStartedNotification: CodexSchema.V2ItemStartedNotification,
ListMcpServerStatusParams: CodexSchema.V2ListMcpServerStatusParams,
ListMcpServerStatusResponse: CodexSchema.V2ListMcpServerStatusResponse,
LoginAccountParams: CodexSchema.V2LoginAccountParams,
LoginAccountResponse: CodexSchema.V2LoginAccountResponse,
LogoutAccountResponse: CodexSchema.V2LogoutAccountResponse,
McpResourceReadParams: CodexSchema.V2McpResourceReadParams,
McpResourceReadResponse: CodexSchema.V2McpResourceReadResponse,
McpServerOauthLoginCompletedNotification: CodexSchema.V2McpServerOauthLoginCompletedNotification,
McpServerOauthLoginParams: CodexSchema.V2McpServerOauthLoginParams,
McpServerOauthLoginResponse: CodexSchema.V2McpServerOauthLoginResponse,
McpServerRefreshResponse: CodexSchema.V2McpServerRefreshResponse,
McpServerStatusUpdatedNotification: CodexSchema.V2McpServerStatusUpdatedNotification,
McpServerToolCallParams: CodexSchema.V2McpServerToolCallParams,
McpServerToolCallResponse: CodexSchema.V2McpServerToolCallResponse,
McpToolCallProgressNotification: CodexSchema.V2McpToolCallProgressNotification,
ModelListParams: CodexSchema.V2ModelListParams,
ModelListResponse: CodexSchema.V2ModelListResponse,
ModelReroutedNotification: CodexSchema.V2ModelReroutedNotification,
PlanDeltaNotification: CodexSchema.V2PlanDeltaNotification,
PluginInstallParams: CodexSchema.V2PluginInstallParams,
PluginInstallResponse: CodexSchema.V2PluginInstallResponse,
PluginListParams: CodexSchema.V2PluginListParams,
PluginListResponse: CodexSchema.V2PluginListResponse,
PluginReadParams: CodexSchema.V2PluginReadParams,
PluginReadResponse: CodexSchema.V2PluginReadResponse,
PluginUninstallParams: CodexSchema.V2PluginUninstallParams,
PluginUninstallResponse: CodexSchema.V2PluginUninstallResponse,
RawResponseItemCompletedNotification: CodexSchema.V2RawResponseItemCompletedNotification,
ReasoningSummaryPartAddedNotification: CodexSchema.V2ReasoningSummaryPartAddedNotification,
ReasoningSummaryTextDeltaNotification: CodexSchema.V2ReasoningSummaryTextDeltaNotification,
ReasoningTextDeltaNotification: CodexSchema.V2ReasoningTextDeltaNotification,
ReviewStartParams: CodexSchema.V2ReviewStartParams,
ReviewStartResponse: CodexSchema.V2ReviewStartResponse,
ServerRequestResolvedNotification: CodexSchema.V2ServerRequestResolvedNotification,
SkillsChangedNotification: CodexSchema.V2SkillsChangedNotification,
SkillsConfigWriteParams: CodexSchema.V2SkillsConfigWriteParams,
SkillsConfigWriteResponse: CodexSchema.V2SkillsConfigWriteResponse,
SkillsListParams: CodexSchema.V2SkillsListParams,
SkillsListResponse: CodexSchema.V2SkillsListResponse,
TerminalInteractionNotification: CodexSchema.V2TerminalInteractionNotification,
ThreadArchivedNotification: CodexSchema.V2ThreadArchivedNotification,
ThreadArchiveParams: CodexSchema.V2ThreadArchiveParams,
ThreadArchiveResponse: CodexSchema.V2ThreadArchiveResponse,
ThreadClosedNotification: CodexSchema.V2ThreadClosedNotification,
ThreadCompactStartParams: CodexSchema.V2ThreadCompactStartParams,
ThreadCompactStartResponse: CodexSchema.V2ThreadCompactStartResponse,
ThreadForkParams: CodexSchema.V2ThreadForkParams,
ThreadForkResponse: CodexSchema.V2ThreadForkResponse,
ThreadListParams: CodexSchema.V2ThreadListParams,
ThreadListResponse: CodexSchema.V2ThreadListResponse,
ThreadLoadedListParams: CodexSchema.V2ThreadLoadedListParams,
ThreadLoadedListResponse: CodexSchema.V2ThreadLoadedListResponse,
ThreadMetadataUpdateParams: CodexSchema.V2ThreadMetadataUpdateParams,
ThreadMetadataUpdateResponse: CodexSchema.V2ThreadMetadataUpdateResponse,
ThreadNameUpdatedNotification: CodexSchema.V2ThreadNameUpdatedNotification,
ThreadReadParams: CodexSchema.V2ThreadReadParams,
ThreadReadResponse: CodexSchema.V2ThreadReadResponse,
ThreadRealtimeClosedNotification: CodexSchema.V2ThreadRealtimeClosedNotification,
ThreadRealtimeErrorNotification: CodexSchema.V2ThreadRealtimeErrorNotification,
ThreadRealtimeItemAddedNotification: CodexSchema.V2ThreadRealtimeItemAddedNotification,
ThreadRealtimeOutputAudioDeltaNotification:
CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification,
ThreadRealtimeSdpNotification: CodexSchema.V2ThreadRealtimeSdpNotification,
ThreadRealtimeStartedNotification: CodexSchema.V2ThreadRealtimeStartedNotification,
ThreadRealtimeTranscriptUpdatedNotification:
CodexSchema.V2ThreadRealtimeTranscriptUpdatedNotification,
ThreadResumeParams: CodexSchema.V2ThreadResumeParams,
ThreadResumeResponse: CodexSchema.V2ThreadResumeResponse,
ThreadRollbackParams: CodexSchema.V2ThreadRollbackParams,
ThreadRollbackResponse: CodexSchema.V2ThreadRollbackResponse,
ThreadSetNameParams: CodexSchema.V2ThreadSetNameParams,
ThreadSetNameResponse: CodexSchema.V2ThreadSetNameResponse,
ThreadShellCommandParams: CodexSchema.V2ThreadShellCommandParams,
ThreadShellCommandResponse: CodexSchema.V2ThreadShellCommandResponse,
ThreadStartedNotification: CodexSchema.V2ThreadStartedNotification,
ThreadStartParams: CodexSchema.V2ThreadStartParams,
ThreadStartResponse: CodexSchema.V2ThreadStartResponse,
ThreadStatusChangedNotification: CodexSchema.V2ThreadStatusChangedNotification,
ThreadTokenUsageUpdatedNotification: CodexSchema.V2ThreadTokenUsageUpdatedNotification,
ThreadUnarchivedNotification: CodexSchema.V2ThreadUnarchivedNotification,
ThreadUnarchiveParams: CodexSchema.V2ThreadUnarchiveParams,
ThreadUnarchiveResponse: CodexSchema.V2ThreadUnarchiveResponse,
ThreadUnsubscribeParams: CodexSchema.V2ThreadUnsubscribeParams,
ThreadUnsubscribeResponse: CodexSchema.V2ThreadUnsubscribeResponse,
TurnCompletedNotification: CodexSchema.V2TurnCompletedNotification,
TurnDiffUpdatedNotification: CodexSchema.V2TurnDiffUpdatedNotification,
TurnInterruptParams: CodexSchema.V2TurnInterruptParams,
TurnInterruptResponse: CodexSchema.V2TurnInterruptResponse,
TurnPlanUpdatedNotification: CodexSchema.V2TurnPlanUpdatedNotification,
TurnStartedNotification: CodexSchema.V2TurnStartedNotification,
TurnStartParams: CodexSchema.V2TurnStartParams,
TurnStartResponse: CodexSchema.V2TurnStartResponse,
TurnSteerParams: CodexSchema.V2TurnSteerParams,
TurnSteerResponse: CodexSchema.V2TurnSteerResponse,
WindowsSandboxSetupCompletedNotification: CodexSchema.V2WindowsSandboxSetupCompletedNotification,
WindowsSandboxSetupStartParams: CodexSchema.V2WindowsSandboxSetupStartParams,
WindowsSandboxSetupStartResponse: CodexSchema.V2WindowsSandboxSetupStartResponse,
WindowsWorldWritableWarningNotification: CodexSchema.V2WindowsWorldWritableWarningNotification,
} as const;
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,101 @@
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as SchemaIssue from "effect/SchemaIssue";
import * as CodexError from "../errors.ts";
const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
export const JsonRpcId = Schema.Union([Schema.Number, Schema.String]);
export const JsonRpcError = Schema.Struct({
code: Schema.Number,
message: Schema.String,
data: Schema.optional(Schema.Unknown),
});
export const JsonRpcResponseEnvelope = Schema.Struct({
id: JsonRpcId,
result: Schema.optional(Schema.Unknown),
error: Schema.optional(JsonRpcError),
});
export const decodeOptionalPayload = <A, I>(
method: string,
schema: Schema.Codec<A, I> | undefined,
raw: unknown,
): Effect.Effect<A, CodexError.CodexAppServerRequestError> => {
if (!schema) {
if (raw === undefined) {
return Effect.sync(() => undefined as A);
}
return Effect.fail(
CodexError.CodexAppServerRequestError.invalidParams(`${method} does not accept params`, raw),
);
}
return Schema.decodeUnknownEffect(schema)(raw).pipe(
Effect.mapError((error) =>
CodexError.CodexAppServerRequestError.invalidParams(
`Invalid ${method} payload: ${formatSchemaIssue(error.issue)}`,
{ issue: error.issue },
),
),
);
};
export const encodeOptionalPayload = <A, I>(
method: string,
schema: Schema.Codec<A, I> | undefined,
payload: A,
): Effect.Effect<I | undefined, CodexError.CodexAppServerRequestError> => {
if (!schema) {
if (payload === undefined) {
return Effect.sync(() => undefined);
}
return Effect.fail(
CodexError.CodexAppServerRequestError.invalidParams(
`${method} does not accept params`,
payload,
),
);
}
return Schema.encodeEffect(schema)(payload).pipe(
Effect.mapError((error) =>
CodexError.CodexAppServerRequestError.invalidParams(
`Invalid ${method} payload: ${formatSchemaIssue(error.issue)}`,
{ issue: error.issue },
),
),
);
};
export const decodeNotificationPayload = <A, I>(
method: string,
schema: Schema.Codec<A, I> | undefined,
raw: unknown,
): Effect.Effect<A, CodexError.CodexAppServerProtocolParseError> =>
decodeOptionalPayload(method, schema, raw).pipe(
Effect.mapError(
(error) =>
new CodexError.CodexAppServerProtocolParseError({
detail: error.message,
cause: error,
}),
),
);
export const runHandler = Effect.fnUntraced(function* <A, B>(
handler: ((payload: A) => Effect.Effect<B, CodexError.CodexAppServerError>) | undefined,
payload: A,
method: string,
) {
if (!handler) {
return yield* CodexError.CodexAppServerRequestError.methodNotFound(method);
}
return yield* handler(payload).pipe(
Effect.mapError((error) => CodexError.normalizeToRequestError(error)),
);
});
@@ -0,0 +1,54 @@
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Queue from "effect/Queue";
import * as Sink from "effect/Sink";
import * as Stdio from "effect/Stdio";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as CodexError from "../errors.ts";
const encoder = new TextEncoder();
const decoder = new TextDecoder();
export const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =>
Stdio.make({
args: Effect.succeed([]),
stdin: handle.stdout,
stdout: () =>
Sink.mapInput(handle.stdin, (chunk: string | Uint8Array) =>
typeof chunk === "string" ? encoder.encode(chunk) : chunk,
),
stderr: () => Sink.drain,
});
export const makeInMemoryStdio = Effect.fn("makeInMemoryStdio")(function* () {
const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();
const output = yield* Queue.unbounded<string>();
return {
stdio: Stdio.make({
args: Effect.succeed([]),
stdin: Stream.fromQueue(input),
stdout: () =>
Sink.forEach((chunk: string | Uint8Array) =>
Queue.offer(output, typeof chunk === "string" ? chunk : decoder.decode(chunk)),
),
stderr: () => Sink.drain,
}),
input,
output,
};
});
export const makeTerminationError = (
handle: ChildProcessSpawner.ChildProcessHandle,
): Effect.Effect<CodexError.CodexAppServerError> =>
Effect.match(handle.exitCode, {
onFailure: (cause) =>
new CodexError.CodexAppServerTransportError({
detail: "Failed to determine Codex App Server process exit status",
cause,
}),
onSuccess: (code) => new CodexError.CodexAppServerProcessExitedError({ code }),
});
@@ -0,0 +1,124 @@
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Effect from "effect/Effect";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as CodexClient from "./client.ts";
const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
path.join(import.meta.dirname, "../test/fixtures/codex-app-server-mock-peer.ts"),
);
it.layer(NodeServices.layer)("effect-codex-app-server client", (it) => {
const makeHandle = () =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const path = yield* Path.Path;
const command = ChildProcess.make("bun", ["run", yield* mockPeerPath], {
cwd: path.join(import.meta.dirname, ".."),
shell: process.platform === "win32",
});
return yield* spawner.spawn(command);
});
it.effect("initializes, handles typed server requests, and reads account and skills data", () =>
Effect.gen(function* () {
const userInputRequests = yield* Ref.make<Array<unknown>>([]);
const messageDeltas = yield* Ref.make<Array<unknown>>([]);
const handle = yield* makeHandle();
const scope = yield* Scope.make();
const clientLayer = CodexClient.layerChildProcess(handle);
const context = yield* Layer.buildWithScope(clientLayer, scope);
const result = yield* Effect.gen(function* () {
const client = yield* CodexClient.CodexAppServerClient;
yield* client.handleServerRequest("item/tool/requestUserInput", (payload) =>
Ref.update(userInputRequests, (current) => [...current, payload]).pipe(
Effect.as({
answers: {
approved: {
answers: ["yes"],
},
},
}),
),
);
yield* client.handleServerNotification("item/agentMessage/delta", (payload) =>
Ref.update(messageDeltas, (current) => [...current, payload]),
);
const initialized = yield* client.request("initialize", {
clientInfo: {
name: "effect-codex-app-server-test",
title: "Effect Codex App Server Test",
version: "0.0.0",
},
capabilities: {
experimentalApi: true,
optOutNotificationMethods: null,
},
});
assert.equal(initialized.userAgent, "mock-codex-app-server");
yield* client.notify("initialized", undefined);
const account = yield* client.request("account/read", {});
assert.equal(account.requiresOpenaiAuth, false);
assert.deepEqual(account.account, {
type: "chatgpt",
email: "[email protected]",
planType: "plus",
});
const skills = yield* client.request("skills/list", {
cwds: [process.cwd()],
});
assert.equal(skills.data.length, 1);
assert.equal(skills.data[0]?.cwd, process.cwd());
return {
account,
skills,
};
}).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
assert.equal(result.skills.data[0]?.skills.length, 0);
assert.deepEqual(yield* Ref.get(userInputRequests), [
{
itemId: "item-approval-1",
threadId: "thread-1",
turnId: "turn-1",
questions: [
{
id: "approved",
header: "Approve",
question: "Continue with the mock skills request?",
options: [
{
label: "yes",
description: "Approve the request",
},
],
},
],
},
]);
assert.deepEqual(yield* Ref.get(messageDeltas), [
{
delta: "Mock server is ready.",
itemId: "item-1",
threadId: "thread-1",
turnId: "turn-1",
},
]);
}),
);
});
@@ -0,0 +1,298 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stdio from "effect/Stdio";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as CodexRpc from "./_generated/meta.gen.ts";
import * as CodexError from "./errors.ts";
import * as CodexProtocol from "./protocol.ts";
import {
decodeNotificationPayload,
decodeOptionalPayload,
encodeOptionalPayload,
runHandler,
} from "./_internal/shared.ts";
import { makeChildStdio, makeTerminationError } from "./_internal/stdio.ts";
export interface CodexAppServerClientOptions {
readonly logIncoming?: boolean;
readonly logOutgoing?: boolean;
readonly logger?: (
event: CodexProtocol.CodexAppServerProtocolLogEvent,
) => Effect.Effect<void, never>;
}
interface CodexAppServerClientRaw {
readonly notifications: CodexProtocol.CodexAppServerPatchedProtocol["incomingNotifications"];
readonly requests: CodexProtocol.CodexAppServerPatchedProtocol["incomingRequests"];
readonly request: CodexProtocol.CodexAppServerPatchedProtocol["request"];
readonly notify: CodexProtocol.CodexAppServerPatchedProtocol["notify"];
readonly respond: CodexProtocol.CodexAppServerPatchedProtocol["respond"];
readonly respondError: CodexProtocol.CodexAppServerPatchedProtocol["respondError"];
}
export interface CodexAppServerClientShape {
readonly raw: CodexAppServerClientRaw;
readonly request: <M extends CodexRpc.ClientRequestMethod>(
method: M,
payload: CodexRpc.ClientRequestParamsByMethod[M],
) => Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError>;
readonly notify: <M extends CodexRpc.ClientNotificationMethod>(
method: M,
payload: CodexRpc.ClientNotificationParamsByMethod[M],
) => Effect.Effect<void, CodexError.CodexAppServerError>;
readonly handleServerRequest: <M extends CodexRpc.ServerRequestMethod>(
method: M,
handler: (
payload: CodexRpc.ServerRequestParamsByMethod[M],
) => Effect.Effect<CodexRpc.ServerRequestResponsesByMethod[M], CodexError.CodexAppServerError>,
) => Effect.Effect<void>;
readonly handleServerNotification: <M extends CodexRpc.ServerNotificationMethod>(
method: M,
handler: (
payload: CodexRpc.ServerNotificationParamsByMethod[M],
) => Effect.Effect<void, CodexError.CodexAppServerError>,
) => Effect.Effect<void>;
readonly handleUnknownServerRequest: (
handler: (
method: string,
params: unknown,
) => Effect.Effect<unknown, CodexError.CodexAppServerError>,
) => Effect.Effect<void>;
readonly handleUnknownServerNotification: (
handler: (
method: string,
params: unknown,
) => Effect.Effect<void, CodexError.CodexAppServerError>,
) => Effect.Effect<void>;
}
export class CodexAppServerClient extends Context.Service<
CodexAppServerClient,
CodexAppServerClientShape
>()("effect-codex-app-server/CodexAppServerClient") {}
type ServerRequestHandler = (
payload: unknown,
) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
type ServerNotificationHandler = (
payload: unknown,
) => Effect.Effect<void, CodexError.CodexAppServerError>;
export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make")(function* (
stdio: Stdio.Stdio,
options: CodexAppServerClientOptions = {},
terminationError?: Effect.Effect<CodexError.CodexAppServerError>,
): Effect.fn.Return<CodexAppServerClientShape, never, Scope.Scope> {
const requestHandlers = new Map<string, ServerRequestHandler>();
const notificationHandlers = new Map<string, Array<ServerNotificationHandler>>();
let unknownRequestHandler:
| ((method: string, params: unknown) => Effect.Effect<unknown, CodexError.CodexAppServerError>)
| undefined;
let unknownNotificationHandler:
| ((method: string, params: unknown) => Effect.Effect<void, CodexError.CodexAppServerError>)
| undefined;
const getServerRequestParamSchema = <M extends CodexRpc.ServerRequestMethod>(
method: M,
):
| Schema.Codec<CodexRpc.ServerRequestParamsByMethod[M], CodexRpc.ServerRequestParamsByMethod[M]>
| undefined => CodexRpc.SERVER_REQUEST_PARAMS[method] as never;
const getServerRequestResponseSchema = <M extends CodexRpc.ServerRequestMethod>(
method: M,
):
| Schema.Codec<
CodexRpc.ServerRequestResponsesByMethod[M],
CodexRpc.ServerRequestResponsesByMethod[M]
>
| undefined => CodexRpc.SERVER_REQUEST_RESPONSES[method] as never;
const getClientRequestParamSchema = <M extends CodexRpc.ClientRequestMethod>(
method: M,
):
| Schema.Codec<CodexRpc.ClientRequestParamsByMethod[M], CodexRpc.ClientRequestParamsByMethod[M]>
| undefined => CodexRpc.CLIENT_REQUEST_PARAMS[method] as never;
const getClientRequestResponseSchema = <M extends CodexRpc.ClientRequestMethod>(
method: M,
):
| Schema.Codec<
CodexRpc.ClientRequestResponsesByMethod[M],
CodexRpc.ClientRequestResponsesByMethod[M]
>
| undefined => CodexRpc.CLIENT_REQUEST_RESPONSES[method] as never;
const getClientNotificationParamSchema = <M extends CodexRpc.ClientNotificationMethod>(
method: M,
):
| Schema.Codec<
CodexRpc.ClientNotificationParamsByMethod[M],
CodexRpc.ClientNotificationParamsByMethod[M]
>
| undefined => CodexRpc.CLIENT_NOTIFICATION_PARAMS[method] as never;
const dispatchNotification = (
notification: CodexProtocol.CodexAppServerIncomingNotification,
): Effect.Effect<void, never> => {
const schema =
notification.method in CodexRpc.SERVER_NOTIFICATION_PARAMS
? CodexRpc.SERVER_NOTIFICATION_PARAMS[
notification.method as CodexRpc.ServerNotificationMethod
]
: undefined;
const handlers = notificationHandlers.get(notification.method) ?? [];
if (schema) {
return decodeNotificationPayload(notification.method, schema, notification.params).pipe(
Effect.flatMap((decoded) =>
Effect.forEach(handlers, (handler) => handler(decoded), { discard: true }),
),
Effect.catch(() => Effect.void),
);
}
return unknownNotificationHandler
? unknownNotificationHandler(notification.method, notification.params).pipe(
Effect.catch(() => Effect.void),
)
: Effect.void;
};
const dispatchRequest = (
request: CodexProtocol.CodexAppServerIncomingRequest,
): Effect.Effect<unknown, CodexError.CodexAppServerError> => {
if (request.method in CodexRpc.SERVER_REQUEST_PARAMS) {
const method = request.method as CodexRpc.ServerRequestMethod;
const payloadSchema = getServerRequestParamSchema(method);
const responseSchema = getServerRequestResponseSchema(method);
const handler = requestHandlers.get(method);
return decodeOptionalPayload(method, payloadSchema, request.params).pipe(
Effect.flatMap((decoded) => runHandler(handler, decoded, method)),
Effect.flatMap((result) => encodeOptionalPayload(method, responseSchema, result)),
);
}
return unknownRequestHandler
? unknownRequestHandler(request.method, request.params)
: Effect.fail(CodexError.CodexAppServerRequestError.methodNotFound(request.method));
};
const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({
stdio,
...(terminationError ? { terminationError } : {}),
...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),
...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),
...(options.logger ? { logger: options.logger } : {}),
onNotification: dispatchNotification,
onRequest: dispatchRequest,
});
const request = <M extends CodexRpc.ClientRequestMethod>(
method: M,
payload: CodexRpc.ClientRequestParamsByMethod[M],
): Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError> =>
encodeOptionalPayload(method, getClientRequestParamSchema(method), payload).pipe(
Effect.flatMap((encoded) => transport.request(method, encoded)),
Effect.flatMap(
(
raw,
): Effect.Effect<
CodexRpc.ClientRequestResponsesByMethod[M],
CodexError.CodexAppServerError
> => decodeOptionalPayload(method, getClientRequestResponseSchema(method), raw),
),
);
const notify = <M extends CodexRpc.ClientNotificationMethod>(
method: M,
payload: CodexRpc.ClientNotificationParamsByMethod[M],
) =>
encodeOptionalPayload(method, getClientNotificationParamSchema(method), payload).pipe(
Effect.flatMap((encoded) => transport.notify(method, encoded)),
);
return CodexAppServerClient.of({
raw: {
notifications: transport.incomingNotifications,
requests: transport.incomingRequests,
request: transport.request,
notify: transport.notify,
respond: transport.respond,
respondError: transport.respondError,
},
request,
notify,
handleServerRequest: (method, handler) =>
Effect.sync(() => {
requestHandlers.set(method, handler as ServerRequestHandler);
}),
handleServerNotification: (method, handler) =>
Effect.sync(() => {
const current = notificationHandlers.get(method) ?? [];
current.push(handler as ServerNotificationHandler);
notificationHandlers.set(method, current);
}),
handleUnknownServerRequest: (handler) =>
Effect.sync(() => {
unknownRequestHandler = handler;
}),
handleUnknownServerNotification: (handler) =>
Effect.sync(() => {
unknownNotificationHandler = handler;
}),
});
});
export const layerChildProcess = (
handle: ChildProcessSpawner.ChildProcessHandle,
options: CodexAppServerClientOptions = {},
): Layer.Layer<CodexAppServerClient> => {
const stdio = makeChildStdio(handle);
const terminationError = makeTerminationError(handle);
return Layer.effect(CodexAppServerClient, make(stdio, options, terminationError));
};
export interface CodexAppServerCommandLayerOptions extends CodexAppServerClientOptions {
readonly command: string;
readonly args?: ReadonlyArray<string>;
readonly cwd?: string;
readonly env?: Record<string, string>;
}
export const layerCommand = (
options: CodexAppServerCommandLayerOptions,
): Layer.Layer<
CodexAppServerClient,
CodexError.CodexAppServerSpawnError,
ChildProcessSpawner.ChildProcessSpawner
> =>
Layer.effect(
CodexAppServerClient,
Effect.acquireRelease(
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const command = ChildProcess.make(options.command, [...(options.args ?? [])], {
...(options.cwd ? { cwd: options.cwd } : {}),
...(options.env ? { env: { ...process.env, ...options.env } } : {}),
shell: process.platform === "win32",
});
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)),
);
@@ -0,0 +1,151 @@
import * as Schema from "effect/Schema";
export interface CodexAppServerProtocolErrorShape {
readonly code: number;
readonly message: string;
readonly data?: unknown;
}
export class CodexAppServerSpawnError extends Schema.TaggedErrorClass<CodexAppServerSpawnError>()(
"CodexAppServerSpawnError",
{
command: Schema.optional(Schema.String),
cause: Schema.Defect,
},
) {
override get message() {
return this.command
? `Failed to spawn Codex App Server process for command: ${this.command}`
: "Failed to spawn Codex App Server process";
}
}
export class CodexAppServerProcessExitedError extends Schema.TaggedErrorClass<CodexAppServerProcessExitedError>()(
"CodexAppServerProcessExitedError",
{
code: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect),
},
) {
override get message() {
return this.code === undefined
? "Codex App Server process exited"
: `Codex App Server process exited with code ${this.code}`;
}
}
export class CodexAppServerProtocolParseError extends Schema.TaggedErrorClass<CodexAppServerProtocolParseError>()(
"CodexAppServerProtocolParseError",
{
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message() {
return `Failed to parse Codex App Server protocol message: ${this.detail}`;
}
}
export class CodexAppServerTransportError extends Schema.TaggedErrorClass<CodexAppServerTransportError>()(
"CodexAppServerTransportError",
{
detail: Schema.String,
cause: Schema.Defect,
},
) {
override get message() {
return this.detail;
}
}
export class CodexAppServerRequestError extends Schema.TaggedErrorClass<CodexAppServerRequestError>()(
"CodexAppServerRequestError",
{
code: Schema.Number,
errorMessage: Schema.String,
data: Schema.optional(Schema.Unknown),
},
) {
override get message() {
return this.errorMessage;
}
static fromProtocolError(error: CodexAppServerProtocolErrorShape) {
return new CodexAppServerRequestError({
code: error.code,
errorMessage: error.message,
...(error.data !== undefined ? { data: error.data } : {}),
});
}
static parseError(message = "Parse error", data?: unknown) {
return new CodexAppServerRequestError({
code: -32700,
errorMessage: message,
...(data !== undefined ? { data } : {}),
});
}
static invalidRequest(message = "Invalid request", data?: unknown) {
return new CodexAppServerRequestError({
code: -32600,
errorMessage: message,
...(data !== undefined ? { data } : {}),
});
}
static methodNotFound(method: string) {
return new CodexAppServerRequestError({
code: -32601,
errorMessage: `Method not found: ${method}`,
});
}
static invalidParams(message = "Invalid params", data?: unknown) {
return new CodexAppServerRequestError({
code: -32602,
errorMessage: message,
...(data !== undefined ? { data } : {}),
});
}
static internalError(message = "Internal error", data?: unknown) {
return new CodexAppServerRequestError({
code: -32603,
errorMessage: message,
...(data !== undefined ? { data } : {}),
});
}
static overloaded(message = "Server overloaded; retry later.", data?: unknown) {
return new CodexAppServerRequestError({
code: -32001,
errorMessage: message,
...(data !== undefined ? { data } : {}),
});
}
toProtocolError(): CodexAppServerProtocolErrorShape {
return {
code: this.code,
message: this.errorMessage,
...(this.data !== undefined ? { data: this.data } : {}),
};
}
}
export const CodexAppServerError = Schema.Union([
CodexAppServerRequestError,
CodexAppServerSpawnError,
CodexAppServerProcessExitedError,
CodexAppServerProtocolParseError,
CodexAppServerTransportError,
]);
export type CodexAppServerError = typeof CodexAppServerError.Type;
export function normalizeToRequestError(error: CodexAppServerError): CodexAppServerRequestError {
return Schema.is(CodexAppServerRequestError)(error)
? error
: CodexAppServerRequestError.internalError(error.message);
}
@@ -0,0 +1,197 @@
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as CodexError from "./errors.ts";
import * as CodexProtocol from "./protocol.ts";
import { makeInMemoryStdio } from "./_internal/stdio.ts";
const encoder = new TextEncoder();
const encodeJsonl = (value: unknown) => encoder.encode(`${JSON.stringify(value)}\n`);
it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
it.effect(
"encodes requests without a jsonrpc field and routes inbound requests and notifications",
() =>
Effect.gen(function* () {
const { stdio, input, output } = yield* makeInMemoryStdio();
const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
const notificationDeferred =
yield* Deferred.make<ReadonlyArray<CodexProtocol.CodexAppServerIncomingNotification>>();
const requestDeferred =
yield* Deferred.make<ReadonlyArray<CodexProtocol.CodexAppServerIncomingRequest>>();
yield* transport.incomingNotifications.pipe(
Stream.take(1),
Stream.runCollect,
Effect.flatMap((notifications) => Deferred.succeed(notificationDeferred, notifications)),
Effect.forkScoped,
);
yield* transport.incomingRequests.pipe(
Stream.take(1),
Stream.runCollect,
Effect.flatMap((requests) => Deferred.succeed(requestDeferred, requests)),
Effect.forkScoped,
);
yield* transport.notify("initialized");
assert.equal(yield* Queue.take(output), '{"method":"initialized"}\n');
const initializeParams = {
clientInfo: {
name: "effect-codex-app-server-test",
title: "Effect Codex App Server Test",
version: "0.0.0",
},
capabilities: {
experimentalApi: true,
optOutNotificationMethods: null,
},
};
const pendingInitialize = yield* transport
.request("initialize", initializeParams)
.pipe(Effect.forkScoped);
assert.deepEqual(JSON.parse(yield* Queue.take(output)), {
id: 1,
method: "initialize",
params: initializeParams,
});
yield* Queue.offer(
input,
encodeJsonl({
method: "item/agentMessage/delta",
params: {
delta: "Hello from the mock peer.",
itemId: "item-1",
threadId: "thread-1",
turnId: "turn-1",
},
}),
);
yield* Queue.offer(
input,
encodeJsonl({
id: 77,
method: "item/tool/requestUserInput",
params: {
itemId: "item-approval-1",
threadId: "thread-1",
turnId: "turn-1",
questions: [
{
id: "approved",
header: "Approve",
question: "Continue?",
},
],
},
}),
);
yield* Queue.offer(
input,
encodeJsonl({
id: 1,
result: {
userAgent: "mock-codex-app-server",
codexHome: "/tmp/codex-home",
platformFamily: "unix",
platformOs: "macos",
},
}),
);
assert.deepEqual(yield* Fiber.join(pendingInitialize), {
userAgent: "mock-codex-app-server",
codexHome: "/tmp/codex-home",
platformFamily: "unix",
platformOs: "macos",
});
assert.deepEqual(yield* Deferred.await(notificationDeferred), [
{
method: "item/agentMessage/delta",
params: {
delta: "Hello from the mock peer.",
itemId: "item-1",
threadId: "thread-1",
turnId: "turn-1",
},
},
]);
assert.deepEqual(yield* Deferred.await(requestDeferred), [
{
id: 77,
method: "item/tool/requestUserInput",
params: {
itemId: "item-approval-1",
threadId: "thread-1",
turnId: "turn-1",
questions: [
{
id: "approved",
header: "Approve",
question: "Continue?",
},
],
},
},
]);
yield* transport.respond(77, {
answers: {
approved: {
answers: ["yes"],
},
},
});
assert.deepEqual(JSON.parse(yield* Queue.take(output)), {
id: 77,
result: {
answers: {
approved: {
answers: ["yes"],
},
},
},
});
yield* transport.respondError(
78,
CodexError.CodexAppServerRequestError.methodNotFound("x/test"),
);
assert.deepEqual(JSON.parse(yield* Queue.take(output)), {
id: 78,
error: {
code: -32601,
message: "Method not found: x/test",
},
});
}),
);
it.effect("surfaces JSON encoding failures as protocol parse errors", () =>
Effect.gen(function* () {
const { stdio } = yield* makeInMemoryStdio();
const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio });
const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
assert.instanceOf(bigintError, CodexError.CodexAppServerProtocolParseError);
assert.equal(bigintError.detail, "Failed to encode Codex App Server message");
const circular: Record<string, unknown> = {};
circular.self = circular;
const circularError = yield* transport.notify("x/test", circular).pipe(Effect.flip);
assert.instanceOf(circularError, CodexError.CodexAppServerProtocolParseError);
assert.equal(circularError.detail, "Failed to encode Codex App Server message");
}),
);
});
@@ -0,0 +1,394 @@
import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
import * as Schema from "effect/Schema";
import * as Stdio from "effect/Stdio";
import * as Stream from "effect/Stream";
import * as CodexError from "./errors.ts";
import { JsonRpcId, JsonRpcResponseEnvelope } from "./_internal/shared.ts";
export interface CodexAppServerProtocolLogEvent {
readonly direction: "incoming" | "outgoing";
readonly stage: "raw" | "decoded" | "decode_failed";
readonly payload: unknown;
}
export interface CodexAppServerIncomingNotification {
readonly method: string;
readonly params?: unknown;
}
export interface CodexAppServerIncomingRequest {
readonly id: string | number;
readonly method: string;
readonly params?: unknown;
}
export interface CodexAppServerPatchedProtocolOptions {
readonly stdio: Stdio.Stdio;
readonly terminationError?: Effect.Effect<CodexError.CodexAppServerError>;
readonly logIncoming?: boolean;
readonly logOutgoing?: boolean;
readonly logger?: (event: CodexAppServerProtocolLogEvent) => Effect.Effect<void, never>;
readonly onNotification?: (
notification: CodexAppServerIncomingNotification,
) => Effect.Effect<void, never>;
readonly onRequest?: (
request: CodexAppServerIncomingRequest,
) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
readonly onTermination?: (error: CodexError.CodexAppServerError) => Effect.Effect<void, never>;
}
export interface CodexAppServerPatchedProtocol {
readonly incomingNotifications: Stream.Stream<CodexAppServerIncomingNotification>;
readonly incomingRequests: Stream.Stream<CodexAppServerIncomingRequest>;
readonly request: (
method: string,
payload?: unknown,
) => Effect.Effect<unknown, CodexError.CodexAppServerError>;
readonly notify: (
method: string,
payload?: unknown,
) => Effect.Effect<void, CodexError.CodexAppServerError>;
readonly respond: (
requestId: string | number,
result: unknown,
) => Effect.Effect<void, CodexError.CodexAppServerError>;
readonly respondError: (
requestId: string | number,
error: CodexError.CodexAppServerRequestError,
) => Effect.Effect<void, CodexError.CodexAppServerError>;
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function isIncomingRequest(value: unknown): value is CodexAppServerIncomingRequest {
if (!isObject(value) || typeof value.method !== "string") {
return false;
}
return Schema.is(JsonRpcId)(value.id);
}
function isIncomingNotification(value: unknown): value is CodexAppServerIncomingNotification {
return isObject(value) && typeof value.method === "string" && !("id" in value);
}
function isIncomingResponse(value: unknown): value is typeof JsonRpcResponseEnvelope.Type {
return Schema.is(JsonRpcResponseEnvelope)(value);
}
const encodeWireMessage = (
message: Record<string, unknown>,
): Effect.Effect<string, CodexError.CodexAppServerProtocolParseError> =>
Effect.try({
try: () => `${JSON.stringify(message)}\n`,
catch: (cause) =>
new CodexError.CodexAppServerProtocolParseError({
detail: "Failed to encode Codex App Server message",
cause,
}),
});
const normalizeIncomingError = (error: unknown, detail: string): CodexError.CodexAppServerError =>
Schema.is(CodexError.CodexAppServerError)(error)
? error
: new CodexError.CodexAppServerTransportError({
detail,
cause: error,
});
const toProtocolMessage = (
requestId: string | number,
fields: {
readonly result?: unknown;
readonly error?: CodexError.CodexAppServerProtocolErrorShape;
},
): { readonly [key: string]: unknown } => ({
id: requestId,
...(fields.result !== undefined ? { result: fields.result } : {}),
...(fields.error !== undefined ? { error: fields.error } : {}),
});
export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPatchedProtocol")(
function* (
options: CodexAppServerPatchedProtocolOptions,
): Effect.fn.Return<CodexAppServerPatchedProtocol, never, Scope.Scope> {
const outgoing = yield* Queue.unbounded<string, Cause.Done<void>>();
const incomingNotifications = yield* Queue.unbounded<CodexAppServerIncomingNotification>();
const incomingRequests = yield* Queue.unbounded<CodexAppServerIncomingRequest>();
const pending = yield* Ref.make(
new Map<string, Deferred.Deferred<unknown, CodexError.CodexAppServerError>>(),
);
const nextRequestId = yield* Ref.make(1);
const remainder = yield* Ref.make("");
const terminationHandled = yield* Ref.make(false);
const logProtocol = (event: CodexAppServerProtocolLogEvent) => {
if (event.direction === "incoming" && !options.logIncoming) {
return Effect.void;
}
if (event.direction === "outgoing" && !options.logOutgoing) {
return Effect.void;
}
return (
options.logger?.(event) ??
Effect.logDebug("Codex App Server protocol event").pipe(Effect.annotateLogs({ event }))
);
};
const failAllPending = (error: CodexError.CodexAppServerError) =>
Ref.get(pending).pipe(
Effect.flatMap((current) =>
Effect.forEach([...current.values()], (deferred) => Deferred.fail(deferred, error), {
discard: true,
}),
),
Effect.andThen(Ref.set(pending, new Map())),
);
const handleTermination = (classify: () => Effect.Effect<CodexError.CodexAppServerError>) =>
Ref.modify(terminationHandled, (handled) => {
if (handled) {
return [Effect.void, true] as const;
}
return [
Effect.gen(function* () {
const error = yield* classify();
yield* failAllPending(error);
yield* Queue.end(outgoing);
if (options.onTermination) {
yield* options.onTermination(error);
}
}),
true,
] as const;
}).pipe(Effect.flatten);
const offerOutgoing = (message: Record<string, unknown>) =>
Effect.gen(function* () {
yield* logProtocol({
direction: "outgoing",
stage: "decoded",
payload: message,
});
const encoded = yield* encodeWireMessage(message);
yield* logProtocol({
direction: "outgoing",
stage: "raw",
payload: encoded,
});
yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid);
});
const removePending = (requestId: string) =>
Ref.update(pending, (current) => {
if (!current.has(requestId)) {
return current;
}
const next = new Map(current);
next.delete(requestId);
return next;
});
const resolvePending = (
requestId: string,
handler: (
deferred: Deferred.Deferred<unknown, CodexError.CodexAppServerError>,
) => Effect.Effect<void>,
) =>
Ref.modify(pending, (current) => {
const deferred = current.get(requestId);
if (!deferred) {
return [Effect.void, current] as const;
}
const next = new Map(current);
next.delete(requestId);
return [handler(deferred), next] as const;
}).pipe(Effect.flatten);
const respond = (requestId: string | number, result: unknown) =>
offerOutgoing(toProtocolMessage(requestId, { result }));
const respondError = (
requestId: string | number,
error: CodexError.CodexAppServerRequestError,
) => offerOutgoing(toProtocolMessage(requestId, { error: error.toProtocolError() }));
const handleResponse = (response: typeof JsonRpcResponseEnvelope.Type) => {
const requestId = String(response.id);
const protocolError = response.error;
if (protocolError !== undefined) {
return resolvePending(requestId, (deferred) =>
Deferred.fail(
deferred,
CodexError.CodexAppServerRequestError.fromProtocolError(protocolError),
),
);
}
return resolvePending(requestId, (deferred) => Deferred.succeed(deferred, response.result));
};
const handleRequest = (request: CodexAppServerIncomingRequest) =>
Queue.offer(incomingRequests, request).pipe(
Effect.andThen(
options.onRequest
? options.onRequest(request).pipe(
Effect.matchEffect({
onFailure: (error) =>
respondError(request.id, CodexError.normalizeToRequestError(error)),
onSuccess: (result) => respond(request.id, result),
}),
)
: Effect.void,
),
Effect.asVoid,
);
const handleNotification = (notification: CodexAppServerIncomingNotification) =>
Queue.offer(incomingNotifications, notification).pipe(
Effect.andThen(options.onNotification ? options.onNotification(notification) : Effect.void),
Effect.asVoid,
);
const routeMessage = (
message: unknown,
): Effect.Effect<void, CodexError.CodexAppServerError> => {
if (isIncomingRequest(message)) {
return handleRequest(message);
}
if (isIncomingNotification(message)) {
return handleNotification(message);
}
if (isIncomingResponse(message)) {
return handleResponse(message);
}
return Effect.fail(
new CodexError.CodexAppServerProtocolParseError({
detail: "Received protocol message in an unknown shape",
}),
);
};
const handleLine = (line: string): Effect.Effect<void, CodexError.CodexAppServerError> => {
if (line.trim().length === 0) {
return Effect.void;
}
return logProtocol({
direction: "incoming",
stage: "raw",
payload: line,
}).pipe(
Effect.flatMap(() =>
Effect.try({
try: () => JSON.parse(line),
catch: (cause) =>
new CodexError.CodexAppServerProtocolParseError({
detail: "Failed to decode Codex App Server wire message",
cause,
}),
}),
),
Effect.tap((decoded) =>
logProtocol({
direction: "incoming",
stage: "decoded",
payload: decoded,
}),
),
Effect.tapErrorTag("CodexAppServerProtocolParseError", (error) =>
logProtocol({
direction: "incoming",
stage: "decode_failed",
payload: {
detail: error.detail,
cause: error.cause,
},
}),
),
Effect.flatMap(routeMessage),
);
};
yield* options.stdio.stdin.pipe(
Stream.decodeText(),
Stream.runForEach((chunk) =>
Ref.modify(remainder, (current) => {
const combined = current + chunk;
const lines = combined.split("\n");
const nextRemainder = lines.pop() ?? "";
return [lines.map((line) => line.replace(/\r$/, "")), nextRemainder] as const;
}).pipe(Effect.flatMap((lines) => Effect.forEach(lines, handleLine, { discard: true }))),
),
Effect.matchEffect({
onFailure: (error) =>
handleTermination(() =>
Effect.succeed(normalizeIncomingError(error, "Codex App Server input stream failed")),
),
onSuccess: () =>
Ref.get(remainder).pipe(
Effect.flatMap((line) => (line.trim().length === 0 ? Effect.void : handleLine(line))),
Effect.matchEffect({
onFailure: (error) => handleTermination(() => Effect.succeed(error)),
onSuccess: () =>
handleTermination(
() =>
options.terminationError ??
Effect.succeed(
new CodexError.CodexAppServerTransportError({
detail: "Codex App Server input stream ended",
cause: new Error("Codex App Server input stream ended"),
}),
),
),
}),
),
}),
Effect.forkScoped,
);
yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);
const request = (method: string, payload?: unknown) =>
Effect.gen(function* () {
const requestId = yield* Ref.modify(
nextRequestId,
(current) => [current, current + 1] as const,
);
const deferred = yield* Deferred.make<unknown, CodexError.CodexAppServerError>();
yield* Ref.update(pending, (current) => new Map(current).set(String(requestId), deferred));
yield* offerOutgoing({
id: requestId,
method,
...(payload !== undefined ? { params: payload } : {}),
}).pipe(
Effect.catch((error) =>
removePending(String(requestId)).pipe(Effect.andThen(Effect.fail(error))),
),
);
return yield* Deferred.await(deferred).pipe(
Effect.onInterrupt(() => removePending(String(requestId))),
);
});
const notify = (method: string, payload?: unknown) =>
offerOutgoing({
method,
...(payload !== undefined ? { params: payload } : {}),
});
return {
incomingNotifications: Stream.fromQueue(incomingNotifications),
incomingRequests: Stream.fromQueue(incomingRequests),
request,
notify,
respond,
respondError,
} satisfies CodexAppServerPatchedProtocol;
},
);
@@ -0,0 +1 @@
export * from "./_generated/meta.gen.ts";
@@ -0,0 +1,3 @@
export * from "./_generated/schema.gen.ts";
export * from "./_generated/meta.gen.ts";
export * from "./_generated/namespaces.gen.ts";
@@ -0,0 +1,62 @@
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as CodexClient from "../../src/client.ts";
const program = Effect.gen(function* () {
const codexLayer = CodexClient.layerCommand({
command: process.env.CODEX_BIN ?? "codex",
args: ["app-server"],
cwd: process.cwd(),
logIncoming: true,
logOutgoing: true,
});
yield* Effect.gen(function* () {
const client = yield* CodexClient.CodexAppServerClient;
yield* client.handleServerRequest("item/tool/requestUserInput", (payload) =>
Effect.succeed({
answers: Object.fromEntries(
payload.questions.map((question) => [
question.id,
{
answers:
question.options && question.options.length > 0
? [question.options[0]!.label]
: ["ok"],
},
]),
),
}),
);
const initialized = yield* client.request("initialize", {
clientInfo: {
name: "effect-codex-app-server-probe",
title: "Effect Codex App Server Probe",
version: "0.0.0",
},
capabilities: {
experimentalApi: true,
optOutNotificationMethods: null,
},
});
yield* Console.log("initialize", JSON.stringify(initialized, null, 2));
yield* client.notify("initialized", undefined);
const account = yield* client.request("account/read", {});
yield* Console.log("account/read", JSON.stringify(account, null, 2));
const skills = yield* client.request("skills/list", {
cwds: [process.cwd()],
});
yield* Console.log("skills/list", JSON.stringify(skills, null, 2));
}).pipe(Effect.provide(codexLayer));
});
program.pipe(Effect.scoped, Effect.provide(NodeServices.layer), NodeRuntime.runMain);
@@ -0,0 +1,144 @@
let nextServerRequestId = 10_000;
let pendingSkillsListRequestId: number | string | null = null;
let pendingUserInputRequestId: number | null = null;
const writeMessage = (message: unknown) => {
process.stdout.write(`${JSON.stringify(message)}\n`);
};
const respond = (id: number | string, result: unknown) => {
writeMessage({ id, result });
};
const respondError = (id: number | string, code: number, message: string) => {
writeMessage({
id,
error: {
code,
message,
},
});
};
const sendRequest = (method: string, params: unknown) => {
const id = nextServerRequestId++;
writeMessage({ id, method, params });
return id;
};
const handleMethod = (message: Record<string, unknown>) => {
const method = message.method;
if (typeof method !== "string") {
return;
}
switch (method) {
case "initialize": {
respond(message.id as number | string, {
userAgent: "mock-codex-app-server",
codexHome: process.cwd(),
platformFamily: process.platform === "win32" ? "windows" : "unix",
platformOs: process.platform === "darwin" ? "macos" : process.platform,
});
return;
}
case "initialized": {
writeMessage({
method: "item/agentMessage/delta",
params: {
delta: "Mock server is ready.",
itemId: "item-1",
threadId: "thread-1",
turnId: "turn-1",
},
});
return;
}
case "account/read": {
respond(message.id as number | string, {
account: {
type: "chatgpt",
email: "[email protected]",
planType: "plus",
},
requiresOpenaiAuth: false,
});
return;
}
case "skills/list": {
pendingSkillsListRequestId = message.id as number | string;
pendingUserInputRequestId = sendRequest("item/tool/requestUserInput", {
itemId: "item-approval-1",
threadId: "thread-1",
turnId: "turn-1",
questions: [
{
id: "approved",
header: "Approve",
question: "Continue with the mock skills request?",
options: [
{
label: "yes",
description: "Approve the request",
},
],
},
],
});
return;
}
default: {
if (message.id !== undefined) {
respondError(message.id as number | string, -32601, `Unhandled request: ${method}`);
}
}
}
};
const handleResponse = (message: Record<string, unknown>) => {
if (message.id !== pendingUserInputRequestId) {
return;
}
pendingUserInputRequestId = null;
respond(pendingSkillsListRequestId!, {
data: [
{
cwd: process.cwd(),
errors: [],
skills: [],
},
],
});
pendingSkillsListRequestId = null;
};
let remainder = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
remainder += chunk;
const lines = remainder.split("\n");
remainder = lines.pop() ?? "";
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.length === 0) {
continue;
}
const message = JSON.parse(trimmed) as Record<string, unknown>;
if ("method" in message) {
handleMethod(message);
continue;
}
if ("id" in message) {
handleResponse(message);
}
}
});
process.stdin.on("end", () => {
process.exit(0);
});
@@ -0,0 +1,18 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"plugins": [
{
"name": "@effect/language-service",
"namespaceImportPackages": ["@effect/platform-node"],
"diagnosticSeverity": {
"importFromBarrel": "error",
"anyUnknownInErrorContext": "warning",
"instanceOfSchema": "warning",
"deterministicKeys": "warning"
}
}
]
},
"include": ["src", "scripts", "test"]
}
+23
View File
@@ -249,6 +249,29 @@ export function trimOrNull<T extends string>(value: T | null | undefined): T | n
return trimmed || null;
}
/**
* 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(
provider: ProviderKind,
model: string,
+1
View File
@@ -25,6 +25,7 @@ const workspaceFiles = [
"packages/contracts/package.json",
"packages/shared/package.json",
"packages/effect-acp/package.json",
"packages/effect-codex-app-server/package.json",
"scripts/package.json",
] as const;