From 14865dc7a66cf6b5f7322e31f70df92f74fbb1d0 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 1 Mar 2026 11:30:28 +0000 Subject: [PATCH] Implement v2 canonical provider runtime adapters Co-authored-by: Julius Marminge --- .../TestProviderAdapter.integration.ts | 29 +- .../integration/fixtures/providerRuntime.ts | 6 +- .../Layers/CheckpointReactor.test.ts | 35 +- .../orchestration/Layers/CheckpointReactor.ts | 73 +- .../Layers/ProviderRuntimeIngestion.test.ts | 56 +- .../Layers/ProviderRuntimeIngestion.ts | 297 ++- .../provider/Layers/ClaudeCodeAdapter.test.ts | 67 +- .../src/provider/Layers/ClaudeCodeAdapter.ts | 158 +- .../src/provider/Layers/CodexAdapter.test.ts | 10 +- .../src/provider/Layers/CodexAdapter.ts | 1089 ++++++++--- .../src/provider/Layers/CursorAdapter.test.ts | 350 ++++ .../src/provider/Layers/CursorAdapter.ts | 1714 +++++++++++++++++ .../Layers/ProviderAdapterRegistry.test.ts | 21 +- .../Layers/ProviderAdapterRegistry.ts | 3 +- .../provider/Layers/ProviderService.test.ts | 48 +- .../src/provider/Layers/ProviderService.ts | 1 - .../provider/Services/CursorAdapter.test.ts | 181 +- .../src/provider/Services/CursorAdapter.ts | 300 ++- apps/server/src/serverLayers.ts | 6 +- apps/server/src/wsServer.test.ts | 4 +- packages/contracts/src/provider.ts | 6 + .../contracts/src/providerRuntime.test.ts | 2 +- packages/contracts/src/providerRuntime.ts | 561 +++++- 23 files changed, 4336 insertions(+), 681 deletions(-) create mode 100644 apps/server/src/provider/Layers/CursorAdapter.test.ts create mode 100644 apps/server/src/provider/Layers/CursorAdapter.ts diff --git a/apps/server/integration/TestProviderAdapter.integration.ts b/apps/server/integration/TestProviderAdapter.integration.ts index db4f9c6835..52c290c52a 100644 --- a/apps/server/integration/TestProviderAdapter.integration.ts +++ b/apps/server/integration/TestProviderAdapter.integration.ts @@ -25,7 +25,7 @@ import type { } from "../src/provider/Services/ProviderAdapter.ts"; export interface TestTurnResponse { - readonly events: ReadonlyArray; + readonly events: ReadonlyArray>; readonly mutateWorkspace?: (input: { readonly cwd: string; readonly turnCount: number; @@ -169,7 +169,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter const deferredTurnCompletedEvents: ProviderRuntimeEvent[] = []; for (const fixtureEvent of response.events) { const rawEvent: Record = { - ...(fixtureEvent as Record), + ...fixtureEvent, eventId: randomUUID(), provider, sessionId: input.sessionId, @@ -183,10 +183,25 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter } const runtimeEvent = rawEvent as ProviderRuntimeEvent; - if (runtimeEvent.type === "message.delta") { - assistantDeltas.push(runtimeEvent.delta); + const runtimeEventType = + typeof rawEvent.type === "string" ? rawEvent.type : runtimeEvent.type; + if (runtimeEventType === "message.delta" && typeof rawEvent.delta === "string") { + assistantDeltas.push(rawEvent.delta); } - if (runtimeEvent.type === "turn.completed") { + if (runtimeEventType === "content.delta") { + const payload = + rawEvent.payload && typeof rawEvent.payload === "object" && !Array.isArray(rawEvent.payload) + ? (rawEvent.payload as Record) + : undefined; + if ( + payload?.streamKind === "assistant_text" && + typeof payload.delta === "string" && + payload.delta.length > 0 + ) { + assistantDeltas.push(payload.delta); + } + } + if (runtimeEventType === "turn.completed") { deferredTurnCompletedEvents.push(runtimeEvent); continue; } @@ -227,7 +242,9 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter createdAt: nowIso(), threadId: state.snapshot.threadId, turnId, - status: "completed", + payload: { + state: "completed", + }, }); } else { for (const completedEvent of deferredTurnCompletedEvents) { diff --git a/apps/server/integration/fixtures/providerRuntime.ts b/apps/server/integration/fixtures/providerRuntime.ts index c846fcb704..15806159e4 100644 --- a/apps/server/integration/fixtures/providerRuntime.ts +++ b/apps/server/integration/fixtures/providerRuntime.ts @@ -53,7 +53,7 @@ export const codexTurnTextFixture = [ turnId: TURN_ID, status: "completed", }, -] satisfies ReadonlyArray; +]; export const codexTurnToolFixture = [ { @@ -94,7 +94,7 @@ export const codexTurnToolFixture = [ turnId: TURN_ID, status: "completed", }, -] satisfies ReadonlyArray; +]; export const codexTurnApprovalFixture = [ { @@ -135,4 +135,4 @@ export const codexTurnApprovalFixture = [ turnId: TURN_ID, status: "completed", }, -] satisfies ReadonlyArray; +]; diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts index 9c54139a89..2c9d8b65ae 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts @@ -43,13 +43,18 @@ const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.make const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value); const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value); const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value); +type RuntimeEventInput = ProviderRuntimeEvent | Record; function createProviderServiceHarness( cwd: string, hasSession = true, sessionCwd = cwd, providerName: "codex" | "claudeCode" = "codex", -) { +): { + service: ProviderServiceShape; + rollbackConversation: ReturnType; + emit: (event: RuntimeEventInput) => void; +} { const now = new Date().toISOString(); const runtimeEventPubSub = Effect.runSync(PubSub.unbounded()); const rollbackConversation = vi.fn( @@ -84,8 +89,8 @@ function createProviderServiceHarness( streamEvents: Stream.fromPubSub(runtimeEventPubSub), }; - const emit = (event: ProviderRuntimeEvent): void => { - Effect.runSync(PubSub.publish(runtimeEventPubSub, event)); + const emit = (event: RuntimeEventInput): void => { + Effect.runSync(PubSub.publish(runtimeEventPubSub, event as ProviderRuntimeEvent)); }; return { @@ -360,7 +365,9 @@ describe("CheckpointReactor", () => { createdAt: new Date().toISOString(), threadId: ProviderThreadId.makeUnsafe("provider-thread-1"), turnId: asProviderTurnId("turn-1"), - status: "completed", + payload: { + state: "completed", + }, }); await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed"); @@ -440,7 +447,9 @@ describe("CheckpointReactor", () => { createdAt: new Date().toISOString(), threadId: ProviderThreadId.makeUnsafe("provider-thread-aux"), turnId: asProviderTurnId("turn-aux"), - status: "completed", + payload: { + state: "completed", + }, }); await Effect.runPromise(Effect.sleep("40 millis")); @@ -458,7 +467,9 @@ describe("CheckpointReactor", () => { createdAt: new Date().toISOString(), threadId: ProviderThreadId.makeUnsafe("provider-thread-1"), turnId: asProviderTurnId("turn-main"), - status: "completed", + payload: { + state: "completed", + }, }); const thread = await waitForThread( @@ -519,7 +530,9 @@ describe("CheckpointReactor", () => { createdAt: new Date().toISOString(), threadId: ProviderThreadId.makeUnsafe("provider-thread-1"), turnId: asProviderTurnId("turn-claude-1"), - status: "completed", + payload: { + state: "completed", + }, }); await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed"); @@ -567,7 +580,9 @@ describe("CheckpointReactor", () => { createdAt: new Date().toISOString(), threadId: ProviderThreadId.makeUnsafe("provider-thread-1"), turnId: asProviderTurnId("turn-missing-baseline"), - status: "completed", + payload: { + state: "completed", + }, }); await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed"); @@ -659,7 +674,9 @@ describe("CheckpointReactor", () => { createdAt: new Date().toISOString(), threadId: ProviderThreadId.makeUnsafe("provider-thread-missing"), turnId: asProviderTurnId("turn-missing-cwd"), - status: "completed", + payload: { + state: "completed", + }, }); await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed"); diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.ts index 71b51ba737..ac861193bb 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts @@ -48,6 +48,46 @@ function sameId(left: string | null | undefined, right: string | null | undefine return left === right; } +function asObject(value: unknown): Record | undefined { + return value !== null && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : undefined; +} + +function asString(value: unknown): string | undefined { + return typeof value === "string" ? value : undefined; +} + +function asNumber(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) ? value : undefined; +} + +function turnStateFromCompletion( + event: Extract, +): "completed" | "failed" | "interrupted" | "cancelled" | undefined { + const payload = asObject((event as Record).payload); + const state = asString(payload?.state); + if ( + state === "completed" || + state === "failed" || + state === "interrupted" || + state === "cancelled" + ) { + return state; + } + + const legacyStatus = asString((event as Record).status); + if ( + legacyStatus === "completed" || + legacyStatus === "failed" || + legacyStatus === "interrupted" || + legacyStatus === "cancelled" + ) { + return legacyStatus; + } + return undefined; +} + function checkpointStatusFromRuntime(status: string | undefined): "ready" | "missing" | "error" { switch (status) { case "failed": @@ -287,6 +327,7 @@ const make = Effect.gen(function* () { .toReversed() .find((entry) => entry.role === "assistant" && entry.turnId === turnId)?.id ?? MessageId.makeUnsafe(`assistant:${turnId}`); + const turnState = turnStateFromCompletion(event); const now = event.createdAt; yield* orchestrationEngine.dispatch({ @@ -296,7 +337,7 @@ const make = Effect.gen(function* () { turnId, completedAt: now, checkpointRef: targetCheckpointRef, - status: checkpointStatusFromRuntime(event.status), + status: checkpointStatusFromRuntime(turnState), files, assistantMessageId, checkpointTurnCount: nextTurnCount, @@ -314,7 +355,7 @@ const make = Effect.gen(function* () { summary: "Checkpoint captured", payload: { turnCount: nextTurnCount, - ...(event.status !== undefined ? { status: event.status } : {}), + ...(turnState !== undefined ? { status: turnState } : {}), }, turnId, createdAt: now, @@ -571,6 +612,9 @@ const make = Effect.gen(function* () { }); const processRuntimeEvent = Effect.fnUntraced(function* (event: ProviderRuntimeEvent) { + const rawEvent = event as unknown as Record; + const rawEventType = asString(rawEvent.type) ?? event.type; + if (event.type === "turn.started") { yield* ensurePreTurnBaselineFromTurnStart(event); return; @@ -591,11 +635,15 @@ const make = Effect.gen(function* () { return; } - if (event.type === "checkpoint.captured") { - const turnId = toTurnId(event.turnId); + if (rawEventType === "checkpoint.captured") { + const turnId = toTurnId(asString(rawEvent.turnId)); if (!turnId) { return; } + const checkpointTurnCount = asNumber(rawEvent.turnCount); + if (checkpointTurnCount === undefined) { + return; + } const readModel = yield* orchestrationEngine.getReadModel(); const thread = readModel.threads.find( @@ -608,7 +656,7 @@ const make = Effect.gen(function* () { if ( thread.checkpoints.some( (checkpoint) => - checkpoint.turnId === turnId || checkpoint.checkpointTurnCount === event.turnCount, + checkpoint.turnId === turnId || checkpoint.checkpointTurnCount === checkpointTurnCount, ) ) { return; @@ -619,9 +667,9 @@ const make = Effect.gen(function* () { return; } - const fromTurnCount = Math.max(0, event.turnCount - 1); + const fromTurnCount = Math.max(0, checkpointTurnCount - 1); const fromCheckpointRef = checkpointRefForThreadTurn(thread.id, fromTurnCount); - const targetCheckpointRef = checkpointRefForThreadTurn(thread.id, event.turnCount); + const targetCheckpointRef = checkpointRefForThreadTurn(thread.id, checkpointTurnCount); const targetExists = yield* checkpointStore.hasCheckpointRef({ cwd: sessionRuntime.value.cwd, @@ -666,10 +714,10 @@ const make = Effect.gen(function* () { turnId, completedAt: event.createdAt, checkpointRef: targetCheckpointRef, - status: checkpointStatusFromRuntime(event.status), + status: checkpointStatusFromRuntime(asString(rawEvent.status)), files, assistantMessageId, - checkpointTurnCount: event.turnCount, + checkpointTurnCount, createdAt: event.createdAt, }); } @@ -717,10 +765,11 @@ const make = Effect.gen(function* () { yield* Effect.forkScoped( Stream.runForEach(providerService.streamEvents, (event) => { + const rawType = asString((event as unknown as Record).type) ?? event.type; if ( - event.type !== "turn.started" && - event.type !== "turn.completed" && - event.type !== "checkpoint.captured" + rawType !== "turn.started" && + rawType !== "turn.completed" && + rawType !== "checkpoint.captured" ) { return Effect.void; } diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 02d6390fa5..aa9d697f43 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -37,8 +37,12 @@ const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeU const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value); const asEventId = (value: string): EventId => EventId.makeUnsafe(value); const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value); +type RuntimeEventInput = ProviderRuntimeEvent | Record; -function createProviderServiceHarness() { +function createProviderServiceHarness(): { + service: ProviderServiceShape; + emit: (event: RuntimeEventInput) => void; +} { const runtimeEventPubSub = Effect.runSync(PubSub.unbounded()); const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never; @@ -54,8 +58,8 @@ function createProviderServiceHarness() { streamEvents: Stream.fromPubSub(runtimeEventPubSub), }; - const emit = (event: ProviderRuntimeEvent): void => { - Effect.runSync(PubSub.publish(runtimeEventPubSub, event)); + const emit = (event: RuntimeEventInput): void => { + Effect.runSync(PubSub.publish(runtimeEventPubSub, event as ProviderRuntimeEvent)); }; return { @@ -207,8 +211,10 @@ describe("ProviderRuntimeIngestion", () => { sessionId: asSessionId("sess-1"), createdAt: new Date().toISOString(), turnId: asProviderTurnId("turn-1"), - status: "failed", - errorMessage: "turn failed", + payload: { + state: "failed", + errorMessage: "turn failed", + }, }); const thread = await waitForThread( @@ -274,7 +280,9 @@ describe("ProviderRuntimeIngestion", () => { createdAt: new Date().toISOString(), threadId: asProviderThreadId("provider-thread-1"), turnId: asProviderTurnId("turn-midturn-lifecycle"), - status: "completed", + payload: { + state: "completed", + }, }); await waitForThread( @@ -311,7 +319,9 @@ describe("ProviderRuntimeIngestion", () => { createdAt: new Date().toISOString(), threadId: asProviderThreadId("provider-thread-aux"), turnId: asProviderTurnId("turn-aux"), - status: "completed", + payload: { + state: "completed", + }, }); await Effect.runPromise(Effect.sleep("40 millis")); @@ -328,7 +338,9 @@ describe("ProviderRuntimeIngestion", () => { createdAt: new Date().toISOString(), threadId: asProviderThreadId("provider-thread-1"), turnId: asProviderTurnId("turn-primary"), - status: "completed", + payload: { + state: "completed", + }, }); await waitForThread( @@ -387,7 +399,9 @@ describe("ProviderRuntimeIngestion", () => { createdAt: new Date().toISOString(), threadId: asProviderThreadId("provider-thread-real"), turnId: asProviderTurnId("turn-claude-placeholder"), - status: "completed", + payload: { + state: "completed", + }, }); await waitForThread( @@ -423,7 +437,9 @@ describe("ProviderRuntimeIngestion", () => { sessionId: asSessionId("sess-1"), createdAt: new Date().toISOString(), turnId: asProviderTurnId("turn-guarded-other"), - status: "completed", + payload: { + state: "completed", + }, }); await Effect.runPromise(Effect.sleep("40 millis")); @@ -439,7 +455,9 @@ describe("ProviderRuntimeIngestion", () => { sessionId: asSessionId("sess-1"), createdAt: new Date().toISOString(), turnId: asProviderTurnId("turn-guarded-main"), - status: "completed", + payload: { + state: "completed", + }, }); await waitForThread( @@ -733,7 +751,9 @@ describe("ProviderRuntimeIngestion", () => { sessionId: asSessionId("sess-1"), createdAt: now, turnId: asProviderTurnId("turn-complete-dedup"), - status: "completed", + payload: { + state: "completed", + }, }); await waitForThread( @@ -774,7 +794,9 @@ describe("ProviderRuntimeIngestion", () => { sessionId: asSessionId("sess-1"), createdAt: now, turnId: asProviderTurnId("turn-3"), - message: "runtime exploded", + payload: { + message: "runtime exploded", + }, }); const thread = await waitForThread( @@ -799,7 +821,9 @@ describe("ProviderRuntimeIngestion", () => { sessionId: asSessionId("sess-1"), createdAt: now, threadId: ProviderThreadId.makeUnsafe("provider-thread-1"), - message: "session started", + payload: { + message: "session started", + }, }); harness.emit({ type: "thread.started", @@ -855,7 +879,9 @@ describe("ProviderRuntimeIngestion", () => { sessionId: asSessionId("sess-1"), createdAt: new Date().toISOString(), turnId: asProviderTurnId("turn-after-failure"), - message: "runtime still processed", + payload: { + message: "runtime still processed", + }, }); const thread = await waitForThread( diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index 10b36ce760..d8930d072b 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -76,12 +76,148 @@ function truncateDetail(value: string, limit = 180): string { return value.length > limit ? `${value.slice(0, limit - 3)}...` : value; } +function asObject(value: unknown): Record | undefined { + return value !== null && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : undefined; +} + +function asString(value: unknown): string | undefined { + return typeof value === "string" ? value : undefined; +} + +function eventPayloadRecord(event: ProviderRuntimeEvent): Record | undefined { + const rawEvent = event as unknown as Record; + return asObject(rawEvent.payload); +} + +function mapLegacyTurnStatusToState( + status: unknown, +): "completed" | "failed" | "cancelled" | "interrupted" | undefined { + switch (status) { + case "completed": + case "failed": + case "cancelled": + case "interrupted": + return status; + default: + return undefined; + } +} + +function getTurnCompletionState(event: ProviderRuntimeEvent): + | "completed" + | "failed" + | "cancelled" + | "interrupted" + | undefined { + if (event.type !== "turn.completed") { + return undefined; + } + const payload = eventPayloadRecord(event); + const stateFromPayload = mapLegacyTurnStatusToState(payload?.state); + if (stateFromPayload !== undefined) { + return stateFromPayload; + } + const rawEvent = event as unknown as Record; + return mapLegacyTurnStatusToState(rawEvent.status); +} + +function getTurnCompletionErrorMessage(event: ProviderRuntimeEvent): string | undefined { + if (event.type !== "turn.completed") { + return undefined; + } + const payload = eventPayloadRecord(event); + const payloadMessage = asString(payload?.errorMessage); + if (payloadMessage !== undefined) { + return payloadMessage; + } + const rawEvent = event as unknown as Record; + return asString(rawEvent.errorMessage); +} + +function getRuntimeErrorMessage(event: ProviderRuntimeEvent): string { + if (event.type !== "runtime.error") { + return "Runtime error"; + } + const payload = eventPayloadRecord(event); + const payloadMessage = asString(payload?.message); + if (payloadMessage !== undefined && payloadMessage.length > 0) { + return payloadMessage; + } + const rawEvent = event as unknown as Record; + const legacyMessage = asString(rawEvent.message); + if (legacyMessage !== undefined && legacyMessage.length > 0) { + return legacyMessage; + } + return "Runtime error"; +} + +function mapLegacyRequestType(value: unknown): + | "command_execution_approval" + | "file_change_approval" + | "apply_patch_approval" + | "exec_command_approval" + | "tool_user_input" + | "dynamic_tool_call" + | "auth_tokens_refresh" + | "unknown" { + switch (value) { + case "command_execution_approval": + case "file_change_approval": + case "apply_patch_approval": + case "exec_command_approval": + case "tool_user_input": + case "dynamic_tool_call": + case "auth_tokens_refresh": + return value; + case "command": + return "command_execution_approval"; + case "file-change": + return "file_change_approval"; + case "apply_patch": + return "apply_patch_approval"; + case "exec_command": + return "exec_command_approval"; + case "user_input": + return "tool_user_input"; + case "tool": + return "dynamic_tool_call"; + case "auth": + return "auth_tokens_refresh"; + default: + return "unknown"; + } +} + +function mapLegacyToolKindToItemType( + value: unknown, +): "command_execution" | "file_change" | "apply_patch" | "dynamic_tool_call" { + switch (value) { + case "command_execution": + case "command": + return "command_execution"; + case "file_change": + case "file-change": + return "file_change"; + case "apply_patch": + return "apply_patch"; + default: + return "dynamic_tool_call"; + } +} + function runtimeEventToActivities( event: ProviderRuntimeEvent, ): ReadonlyArray { const maybeSequence = event.sessionSequence !== undefined ? { sequence: event.sessionSequence } : {}; + const rawEvent = event as unknown as Record; + const rawEventType = asString(rawEvent.type); switch (event.type) { - case "approval.requested": { + case "request.opened": { + const isCommandLike = + event.payload.requestType === "command_execution_approval" || + event.payload.requestType === "exec_command_approval"; return [ { id: event.eventId, @@ -89,13 +225,16 @@ function runtimeEventToActivities( tone: "approval", kind: "approval.requested", summary: - event.requestKind === "command" + isCommandLike ? "Command approval requested" - : "File-change approval requested", + : event.payload.requestType === "file_change_approval" || + event.payload.requestType === "apply_patch_approval" + ? "File-change approval requested" + : "Approval requested", payload: { requestId: event.requestId, - requestKind: event.requestKind, - ...(event.detail ? { detail: truncateDetail(event.detail) } : {}), + requestType: event.payload.requestType, + ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}), }, turnId: toTurnId(event.turnId) ?? null, ...maybeSequence, @@ -103,7 +242,7 @@ function runtimeEventToActivities( ]; } - case "approval.resolved": { + case "request.resolved": { return [ { id: event.eventId, @@ -113,8 +252,8 @@ function runtimeEventToActivities( summary: "Approval resolved", payload: { requestId: event.requestId, - ...(event.requestKind ? { requestKind: event.requestKind } : {}), - ...(event.decision ? { decision: event.decision } : {}), + requestType: event.payload.requestType, + ...(event.payload.decision ? { decision: event.payload.decision } : {}), }, turnId: toTurnId(event.turnId) ?? null, ...maybeSequence, @@ -131,7 +270,7 @@ function runtimeEventToActivities( kind: "runtime.error", summary: "Runtime error", payload: { - message: truncateDetail(event.message), + message: truncateDetail(getRuntimeErrorMessage(event)), }, turnId: toTurnId(event.turnId) ?? null, ...maybeSequence, @@ -139,17 +278,20 @@ function runtimeEventToActivities( ]; } - case "tool.completed": { + case "item.completed": { + if (event.payload.itemType === "assistant_message") { + return []; + } return [ { id: event.eventId, createdAt: event.createdAt, tone: "tool", kind: "tool.completed", - summary: `${event.title} complete`, + summary: `${event.payload.title ?? "Tool"} complete`, payload: { - toolKind: event.toolKind, - ...(event.detail ? { detail: truncateDetail(event.detail) } : {}), + itemType: event.payload.itemType, + ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}), }, turnId: toTurnId(event.turnId) ?? null, ...maybeSequence, @@ -157,17 +299,20 @@ function runtimeEventToActivities( ]; } - case "tool.started": { + case "item.started": { + if (event.payload.itemType === "assistant_message") { + return []; + } return [ { id: event.eventId, createdAt: event.createdAt, tone: "tool", kind: "tool.started", - summary: `${event.title} started`, + summary: `${event.payload.title ?? "Tool"} started`, payload: { - toolKind: event.toolKind, - ...(event.detail ? { detail: truncateDetail(event.detail) } : {}), + itemType: event.payload.itemType, + ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}), }, turnId: toTurnId(event.turnId) ?? null, ...maybeSequence, @@ -176,8 +321,80 @@ function runtimeEventToActivities( } default: - return []; + break; } + + if (rawEventType === "approval.requested") { + const requestType = mapLegacyRequestType(rawEvent.requestType ?? rawEvent.requestKind); + const detail = asString(rawEvent.detail); + const requestId = asString(rawEvent.requestId); + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: "approval", + kind: "approval.requested", + summary: + requestType === "command_execution_approval" || requestType === "exec_command_approval" + ? "Command approval requested" + : requestType === "file_change_approval" || requestType === "apply_patch_approval" + ? "File-change approval requested" + : "Approval requested", + payload: { + ...(requestId ? { requestId } : {}), + requestType, + ...(detail ? { detail: truncateDetail(detail) } : {}), + }, + turnId: toTurnId(asString(rawEvent.turnId)) ?? null, + ...maybeSequence, + }, + ]; + } + + if (rawEventType === "approval.resolved") { + const requestType = mapLegacyRequestType(rawEvent.requestType ?? rawEvent.requestKind); + const requestId = asString(rawEvent.requestId); + const decision = asString(rawEvent.decision); + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: "approval", + kind: "approval.resolved", + summary: "Approval resolved", + payload: { + ...(requestId ? { requestId } : {}), + requestType, + ...(decision ? { decision } : {}), + }, + turnId: toTurnId(asString(rawEvent.turnId)) ?? null, + ...maybeSequence, + }, + ]; + } + + if (rawEventType === "tool.started" || rawEventType === "tool.completed") { + const itemType = mapLegacyToolKindToItemType(rawEvent.toolKind); + const title = asString(rawEvent.title) ?? "Tool"; + const detail = asString(rawEvent.detail); + return [ + { + id: event.eventId, + createdAt: event.createdAt, + tone: "tool", + kind: rawEventType === "tool.started" ? "tool.started" : "tool.completed", + summary: `${title} ${rawEventType === "tool.started" ? "started" : "complete"}`, + payload: { + itemType, + ...(detail ? { detail: truncateDetail(detail) } : {}), + }, + turnId: toTurnId(asString(rawEvent.turnId)) ?? null, + ...maybeSequence, + }, + ]; + } + + return []; } const make = Effect.gen(function* () { @@ -350,6 +567,8 @@ const make = Effect.gen(function* () { const processRuntimeEvent = (event: ProviderRuntimeEvent) => Effect.gen(function* () { + const rawEvent = event as unknown as Record; + const rawEventType = asString(rawEvent.type) ?? event.type; const readModel = yield* orchestrationEngine.getReadModel(); const thread = readModel.threads.find( (entry) => entry.session?.providerSessionId === event.sessionId, @@ -427,6 +646,7 @@ const make = Effect.gen(function* () { event.type === "turn.started" || event.type === "turn.completed" ) { + const turnCompletionState = getTurnCompletionState(event); const nextActiveTurnId = event.type === "turn.started" ? (eventTurnId ?? null) @@ -435,7 +655,7 @@ const make = Effect.gen(function* () { : activeTurnId; const providerThreadIdFromEvent = event.type === "thread.started" - ? ProviderThreadId.makeUnsafe(event.threadId) + ? (event.threadId ? ProviderThreadId.makeUnsafe(event.threadId) : null) : event.threadId !== undefined ? ProviderThreadId.makeUnsafe(event.threadId) : null; @@ -448,7 +668,7 @@ const make = Effect.gen(function* () { case "session.exited": return "stopped"; case "turn.completed": - return event.status === "failed" ? "error" : "ready"; + return turnCompletionState === "failed" ? "error" : "ready"; case "session.started": case "thread.started": // Provider thread/session start notifications can arrive during an @@ -457,8 +677,8 @@ const make = Effect.gen(function* () { } })(); const lastError = - event.type === "turn.completed" && event.status === "failed" - ? (event.errorMessage ?? thread.session?.lastError ?? "Turn failed") + event.type === "turn.completed" && turnCompletionState === "failed" + ? (getTurnCompletionErrorMessage(event) ?? thread.session?.lastError ?? "Turn failed") : status === "ready" ? null : (thread.session?.lastError ?? null); @@ -485,7 +705,19 @@ const make = Effect.gen(function* () { } } - if (event.type === "message.delta" && event.delta.length > 0) { + const isV2AssistantTextDelta = + event.type === "content.delta" && event.payload.streamKind === "assistant_text"; + const isLegacyAssistantTextDelta = rawEventType === "message.delta"; + if (isV2AssistantTextDelta || isLegacyAssistantTextDelta) { + const delta = ( + event.type === "content.delta" + ? event.payload.delta + : ((rawEvent.delta as string | undefined) as string) + ).toString(); + if (delta.length === 0) { + return; + } + const assistantMessageId = MessageId.makeUnsafe( `assistant:${event.itemId ?? event.turnId ?? event.sessionId}`, ); @@ -496,7 +728,10 @@ const make = Effect.gen(function* () { const assistantDeliveryMode = yield* Ref.get(assistantDeliveryModeRef); if (assistantDeliveryMode === "buffered") { - const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, event.delta); + const spillChunk = yield* appendBufferedAssistantText( + assistantMessageId, + delta, + ); if (spillChunk.length > 0) { yield* orchestrationEngine.dispatch({ type: "thread.message.assistant.delta", @@ -514,15 +749,20 @@ const make = Effect.gen(function* () { commandId: providerCommandId(event, "assistant-delta"), threadId: thread.id, messageId: assistantMessageId, - delta: event.delta, + delta, ...(turnId ? { turnId } : {}), createdAt: now, }); } } - if (event.type === "message.completed") { - const assistantMessageId = MessageId.makeUnsafe(`assistant:${event.itemId}`); + const isAssistantMessageCompleted = + (event.type === "item.completed" && event.payload.itemType === "assistant_message") || + rawEventType === "message.completed"; + if (isAssistantMessageCompleted) { + const assistantMessageId = MessageId.makeUnsafe( + `assistant:${event.itemId ?? asString(rawEvent.itemId) ?? event.turnId ?? event.sessionId}`, + ); const turnId = toTurnId(event.turnId); if (turnId) { yield* rememberAssistantMessageId(event.sessionId, turnId, assistantMessageId); @@ -570,6 +810,7 @@ const make = Effect.gen(function* () { } if (event.type === "runtime.error") { + const runtimeErrorMessage = getRuntimeErrorMessage(event); const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD ? true : matchesThreadScope && @@ -596,7 +837,7 @@ const make = Effect.gen(function* () { approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY, sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE, activeTurnId: eventTurnId ?? null, - lastError: event.message, + lastError: runtimeErrorMessage, updatedAt: now, }, createdAt: now, diff --git a/apps/server/src/provider/Layers/ClaudeCodeAdapter.test.ts b/apps/server/src/provider/Layers/ClaudeCodeAdapter.test.ts index 5394dee2f8..6a231bcfac 100644 --- a/apps/server/src/provider/Layers/ClaudeCodeAdapter.test.ts +++ b/apps/server/src/provider/Layers/ClaudeCodeAdapter.test.ts @@ -317,10 +317,10 @@ describe("ClaudeCodeAdapterLive", () => { "session.started", "turn.started", "thread.started", - "message.delta", - "tool.started", - "tool.completed", - "message.completed", + "content.delta", + "item.started", + "item.completed", + "item.completed", "turn.completed", ], ); @@ -332,23 +332,23 @@ describe("ClaudeCodeAdapterLive", () => { } const deltaEvent = runtimeEvents[3]; - assert.equal(deltaEvent?.type, "message.delta"); - if (deltaEvent?.type === "message.delta") { - assert.equal(deltaEvent.delta, "Hi"); + assert.equal(deltaEvent?.type, "content.delta"); + if (deltaEvent?.type === "content.delta") { + assert.equal(deltaEvent.payload.delta, "Hi"); assert.equal(deltaEvent.turnId, turn.turnId); } const toolStarted = runtimeEvents[4]; - assert.equal(toolStarted?.type, "tool.started"); - if (toolStarted?.type === "tool.started") { - assert.equal(toolStarted.toolKind, "command"); + assert.equal(toolStarted?.type, "item.started"); + if (toolStarted?.type === "item.started") { + assert.equal(toolStarted.payload.itemType, "command_execution"); } const turnCompleted = runtimeEvents[7]; assert.equal(turnCompleted?.type, "turn.completed"); if (turnCompleted?.type === "turn.completed") { assert.equal(turnCompleted.turnId, turn.turnId); - assert.equal(turnCompleted.status, "completed"); + assert.equal(turnCompleted.payload.state, "completed"); } }).pipe( Effect.provideService(Random.Random, makeDeterministicRandomService()), @@ -418,20 +418,20 @@ describe("ClaudeCodeAdapterLive", () => { "session.started", "turn.started", "thread.started", - "message.delta", - "message.completed", + "content.delta", + "item.completed", "turn.completed", ], ); - const deltaIndex = runtimeEvents.findIndex((event) => event.type === "message.delta"); - const completedIndex = runtimeEvents.findIndex((event) => event.type === "message.completed"); + const deltaIndex = runtimeEvents.findIndex((event) => event.type === "content.delta"); + const completedIndex = runtimeEvents.findIndex((event) => event.type === "item.completed"); assert.equal(deltaIndex >= 0 && completedIndex >= 0 && deltaIndex < completedIndex, true); const deltaEvent = runtimeEvents[deltaIndex]; - assert.equal(deltaEvent?.type, "message.delta"); - if (deltaEvent?.type === "message.delta") { - assert.equal(deltaEvent.delta, "Late text"); + assert.equal(deltaEvent?.type, "content.delta"); + if (deltaEvent?.type === "content.delta") { + assert.equal(deltaEvent.payload.delta, "Late text"); assert.equal(deltaEvent.turnId, turn.turnId); } }).pipe( @@ -487,16 +487,16 @@ describe("ClaudeCodeAdapterLive", () => { "session.started", "turn.started", "thread.started", - "message.delta", - "message.completed", + "content.delta", + "item.completed", "turn.completed", ], ); - const deltaEvent = runtimeEvents.find((event) => event.type === "message.delta"); - assert.equal(deltaEvent?.type, "message.delta"); - if (deltaEvent?.type === "message.delta") { - assert.equal(deltaEvent.delta, "Fallback hello"); + const deltaEvent = runtimeEvents.find((event) => event.type === "content.delta"); + assert.equal(deltaEvent?.type, "content.delta"); + if (deltaEvent?.type === "content.delta") { + assert.equal(deltaEvent.payload.delta, "Fallback hello"); assert.equal(deltaEvent.turnId, turn.turnId); } }).pipe( @@ -552,7 +552,7 @@ describe("ClaudeCodeAdapterLive", () => { const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber)); assert.deepEqual( runtimeEvents.map((event) => event.type), - ["session.started", "turn.started", "thread.started", "message.completed", "turn.completed"], + ["session.started", "turn.started", "thread.started", "item.completed", "turn.completed"], ); const sessionStarted = runtimeEvents[0]; @@ -613,14 +613,19 @@ describe("ClaudeCodeAdapterLive", () => { if (requested._tag !== "Some") { return; } - assert.equal(requested.value.type, "approval.requested"); - if (requested.value.type !== "approval.requested") { + assert.equal(requested.value.type, "request.opened"); + if (requested.value.type !== "request.opened") { + return; + } + const requestId = requested.value.requestId; + assert.notStrictEqual(requestId, undefined); + if (!requestId) { return; } yield* adapter.respondToRequest( session.sessionId, - ApprovalRequestId.makeUnsafe(requested.value.requestId), + ApprovalRequestId.makeUnsafe(requestId), "accept", ); @@ -629,12 +634,12 @@ describe("ClaudeCodeAdapterLive", () => { if (resolved._tag !== "Some") { return; } - assert.equal(resolved.value.type, "approval.resolved"); - if (resolved.value.type !== "approval.resolved") { + assert.equal(resolved.value.type, "request.resolved"); + if (resolved.value.type !== "request.resolved") { return; } assert.equal(resolved.value.requestId, requested.value.requestId); - assert.equal(resolved.value.decision, "accept"); + assert.equal(resolved.value.payload.decision, "accept"); const permissionResult = yield* Effect.promise(() => permissionPromise); assert.equal((permissionResult as PermissionResult).behavior, "allow"); diff --git a/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts b/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts index 8289a3e40e..3a6c2ca7bc 100644 --- a/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeCodeAdapter.ts @@ -137,6 +137,17 @@ function toMessage(cause: unknown, fallback: string): string { return fallback; } +function firstNonEmptyString(...values: ReadonlyArray): string | undefined { + for (const value of values) { + if (typeof value !== "string") continue; + const trimmed = value.trim(); + if (trimmed.length > 0) { + return trimmed; + } + } + return undefined; +} + function toPermissionMode(value: unknown): PermissionMode | undefined { switch (value) { case "default": @@ -216,6 +227,25 @@ function classifyRequestKind(toolName: string): "command" | "file-change" { return classifyToolKind(toolName) === "command" ? "command" : "file-change"; } +function requestTypeForApprovalKind( + kind: "command" | "file-change", +): "command_execution_approval" | "file_change_approval" { + return kind === "command" ? "command_execution_approval" : "file_change_approval"; +} + +function itemTypeForToolKind( + kind: ProviderRuntimeToolKind, +): "command_execution" | "file_change" | "dynamic_tool_call" { + switch (kind) { + case "command": + return "command_execution"; + case "file-change": + return "file_change"; + case "other": + return "dynamic_tool_call"; + } +} + function summarizeToolRequest(toolName: string, input: Record): string { const commandValue = input.command ?? input.cmd; const command = typeof commandValue === "string" ? commandValue : undefined; @@ -464,13 +494,16 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { const snapshotThread = ( context: ClaudeSessionContext, - ): Effect.Effect<{ - threadId: ReturnType; - turns: ReadonlyArray<{ - id: ReturnType; - items: ReadonlyArray; - }>; - }> => + ): Effect.Effect< + { + threadId: ReturnType; + turns: ReadonlyArray<{ + id: ReturnType; + items: ReadonlyArray; + }>; + }, + ProviderAdapterValidationError + > => Effect.gen(function* () { const threadId = context.session.threadId; if (!threadId) { @@ -540,6 +573,9 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { sessionId: context.session.sessionId, createdAt: stamp.createdAt, threadId: nextThreadId, + payload: { + providerThreadId: nextThreadId, + }, }); } }); @@ -563,7 +599,11 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { createdAt: stamp.createdAt, ...(context.session.threadId ? { threadId: context.session.threadId } : {}), ...(turnState ? { turnId: turnState.turnId } : {}), - message, + payload: { + message, + class: "provider_error", + ...(cause !== undefined ? { detail: cause } : {}), + }, }); }); @@ -583,8 +623,10 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { sessionId: context.session.sessionId, createdAt: stamp.createdAt, ...(context.session.threadId ? { threadId: context.session.threadId } : {}), - status, - ...(errorMessage ? { errorMessage } : {}), + payload: { + state: status, + ...(errorMessage ? { errorMessage } : {}), + }, }); return; } @@ -593,7 +635,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { if (!turnState.emittedTextDelta && turnState.fallbackAssistantText.length > 0) { const deltaStamp = yield* makeEventStamp(); yield* offerRuntimeEvent({ - type: "message.delta", + type: "content.delta", eventId: deltaStamp.eventId, provider: PROVIDER, sessionId: context.session.sessionId, @@ -601,13 +643,16 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { ...(context.session.threadId ? { threadId: context.session.threadId } : {}), turnId: turnState.turnId, itemId: ProviderItemId.makeUnsafe(turnState.assistantItemId), - delta: turnState.fallbackAssistantText, + payload: { + streamKind: "assistant_text", + delta: turnState.fallbackAssistantText, + }, }); } const stamp = yield* makeEventStamp(); yield* offerRuntimeEvent({ - type: "message.completed", + type: "item.completed", eventId: stamp.eventId, provider: PROVIDER, sessionId: context.session.sessionId, @@ -615,6 +660,10 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { itemId: ProviderItemId.makeUnsafe(turnState.assistantItemId), ...(context.session.threadId ? { threadId: context.session.threadId } : {}), turnId: turnState.turnId, + payload: { + itemType: "assistant_message", + status: "completed", + }, }); } @@ -632,8 +681,10 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { createdAt: stamp.createdAt, ...(context.session.threadId ? { threadId: context.session.threadId } : {}), turnId: turnState.turnId, - status, - ...(errorMessage ? { errorMessage } : {}), + payload: { + state: status, + ...(errorMessage ? { errorMessage } : {}), + }, }); const updatedAt = yield* nowIso; @@ -673,7 +724,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { } const stamp = yield* makeEventStamp(); yield* offerRuntimeEvent({ - type: "message.delta", + type: "content.delta", eventId: stamp.eventId, provider: PROVIDER, sessionId: context.session.sessionId, @@ -681,7 +732,10 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { ...(context.session.threadId ? { threadId: context.session.threadId } : {}), turnId: context.turnState.turnId, itemId: ProviderItemId.makeUnsafe(context.turnState.assistantItemId), - delta: event.delta.text, + payload: { + streamKind: "assistant_text", + delta: event.delta.text, + }, }); } return; @@ -716,7 +770,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { const stamp = yield* makeEventStamp(); yield* offerRuntimeEvent({ - type: "tool.started", + type: "item.started", eventId: stamp.eventId, provider: PROVIDER, sessionId: context.session.sessionId, @@ -724,9 +778,17 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { ...(context.session.threadId ? { threadId: context.session.threadId } : {}), ...(context.turnState ? { turnId: context.turnState.turnId } : {}), itemId: ProviderItemId.makeUnsafe(tool.itemId), - toolKind: tool.toolKind, - title: tool.title, - ...(tool.detail ? { detail: tool.detail } : {}), + payload: { + itemType: itemTypeForToolKind(tool.toolKind), + status: "inProgress", + title: tool.title, + ...(tool.detail ? { detail: tool.detail } : {}), + data: { + toolKind: tool.toolKind, + toolName, + toolInput, + }, + }, }); return; } @@ -741,7 +803,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { const stamp = yield* makeEventStamp(); yield* offerRuntimeEvent({ - type: "tool.completed", + type: "item.completed", eventId: stamp.eventId, provider: PROVIDER, sessionId: context.session.sessionId, @@ -749,9 +811,15 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { ...(context.session.threadId ? { threadId: context.session.threadId } : {}), ...(context.turnState ? { turnId: context.turnState.turnId } : {}), itemId: ProviderItemId.makeUnsafe(tool.itemId), - toolKind: tool.toolKind, - title: tool.title, - ...(tool.detail ? { detail: tool.detail } : {}), + payload: { + itemType: itemTypeForToolKind(tool.toolKind), + status: "completed", + title: tool.title, + ...(tool.detail ? { detail: tool.detail } : {}), + data: { + toolKind: tool.toolKind, + }, + }, }); } }); @@ -854,7 +922,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { yield* Deferred.succeed(pending.decision, "cancel"); const stamp = yield* makeEventStamp(); yield* offerRuntimeEvent({ - type: "approval.resolved", + type: "request.resolved", eventId: stamp.eventId, provider: PROVIDER, sessionId: context.session.sessionId, @@ -862,8 +930,10 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { ...(context.session.threadId ? { threadId: context.session.threadId } : {}), ...(context.turnState ? { turnId: context.turnState.turnId } : {}), requestId, - requestKind: pending.requestKind, - decision: "cancel", + payload: { + requestType: requestTypeForApprovalKind(pending.requestKind), + decision: "cancel", + }, }); } context.pendingApprovals.clear(); @@ -893,7 +963,11 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { sessionId: context.session.sessionId, createdAt: stamp.createdAt, ...(context.session.threadId ? { threadId: context.session.threadId } : {}), - message: "Session stopped", + payload: { + reason: "Session stopped", + recoverable: true, + exitKind: "graceful", + }, }); } @@ -986,7 +1060,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { const requestedStamp = yield* makeEventStamp(); yield* offerRuntimeEvent({ - type: "approval.requested", + type: "request.opened", eventId: requestedStamp.eventId, provider: PROVIDER, sessionId: context.session.sessionId, @@ -994,8 +1068,11 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { ...(context.session.threadId ? { threadId: context.session.threadId } : {}), ...(context.turnState ? { turnId: context.turnState.turnId } : {}), requestId, - requestKind, - detail, + payload: { + requestType: requestTypeForApprovalKind(requestKind), + detail, + args: toolInput, + }, }); pendingApprovals.set(requestId, pendingApproval); @@ -1017,7 +1094,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { const resolvedStamp = yield* makeEventStamp(); yield* offerRuntimeEvent({ - type: "approval.resolved", + type: "request.resolved", eventId: resolvedStamp.eventId, provider: PROVIDER, sessionId: context.session.sessionId, @@ -1025,8 +1102,10 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { ...(context.session.threadId ? { threadId: context.session.threadId } : {}), ...(context.turnState ? { turnId: context.turnState.turnId } : {}), requestId, - requestKind, - decision, + payload: { + requestType: requestTypeForApprovalKind(requestKind), + decision, + }, }); if (decision === "accept" || decision === "acceptForSession") { @@ -1134,6 +1213,9 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { sessionId, createdAt: sessionStartedStamp.createdAt, ...(threadId ? { threadId } : {}), + payload: { + ...(resumeState ? { resume: resumeState } : {}), + }, }); Effect.runFork(runSdkStream(context)); @@ -1191,6 +1273,12 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) { createdAt: turnStartedStamp.createdAt, ...(context.session.threadId ? { threadId: context.session.threadId } : {}), turnId, + payload: { + ...(firstNonEmptyString(input.model, context.session.model) + ? { model: firstNonEmptyString(input.model, context.session.model) } + : {}), + ...(input.effort ? { effort: input.effort } : {}), + }, }); const message = buildUserMessage(input); diff --git a/apps/server/src/provider/Layers/CodexAdapter.test.ts b/apps/server/src/provider/Layers/CodexAdapter.test.ts index c51e6963aa..0208e47782 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.test.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.test.ts @@ -181,7 +181,7 @@ const lifecycleManager = new FakeCodexManager(); const lifecycleLayer = it.layer(makeCodexAdapterLive({ manager: lifecycleManager })); lifecycleLayer("CodexAdapterLive lifecycle", (it) => { - it.effect("maps completed agent message items to canonical message.completed events", () => + it.effect("maps completed agent message items to canonical item.completed events", () => Effect.gen(function* () { const adapter = yield* CodexAdapter; const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); @@ -211,12 +211,14 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { if (firstEvent._tag !== "Some") { return; } - assert.equal(firstEvent.value.type, "message.completed"); - if (firstEvent.value.type !== "message.completed") { + assert.equal(firstEvent.value.type, "item.completed"); + if (firstEvent.value.type !== "item.completed") { return; } assert.equal(firstEvent.value.itemId, "msg_1"); assert.equal(firstEvent.value.turnId, "turn-1"); + assert.equal(firstEvent.value.payload.itemType, "assistant_message"); + assert.equal(firstEvent.value.payload.status, "completed"); }), ); @@ -247,7 +249,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { return; } assert.equal(firstEvent.value.sessionId, "sess-1"); - assert.equal(firstEvent.value.message, "Session stopped"); + assert.equal(firstEvent.value.payload.reason, "Session stopped"); }), ); }); diff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.ts index 35f517a55a..20de5e775d 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.ts @@ -7,17 +7,17 @@ * @module CodexAdapterLive */ import { + ApprovalRequestId, + type CanonicalItemType, + type CanonicalRequestType, + ProviderItemId, type ProviderEvent, type ProviderRuntimeEvent, - type ProviderRuntimeTurnStatus, - type ProviderRuntimeToolKind, - ProviderItemId, - ProviderApprovalDecision, ProviderSessionId, ProviderThreadId, ProviderTurnId, } from "@t3tools/contracts"; -import { Effect, Layer, Queue, Schema, Stream } from "effect"; +import { Effect, Layer, Queue, Stream } from "effect"; import { ProviderAdapterProcessError, @@ -96,16 +96,27 @@ function asString(value: unknown): string | undefined { return typeof value === "string" ? value : undefined; } -function toTurnStatus(value: unknown): ProviderRuntimeTurnStatus | undefined { - switch (value) { - case "completed": - case "failed": - case "cancelled": - case "interrupted": - return value; - default: - return undefined; +function asArray(value: unknown): ReadonlyArray | undefined { + return Array.isArray(value) ? value : undefined; +} + +function asBoolean(value: unknown): boolean | undefined { + return typeof value === "boolean" ? value : undefined; +} + +function asNumber(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) ? value : undefined; +} + +function firstNonEmptyString(...values: Array): string | undefined { + for (const value of values) { + if (typeof value !== "string") continue; + const trimmed = value.trim(); + if (trimmed.length > 0) { + return trimmed; + } } + return undefined; } function normalizeItemType(raw: unknown): string { @@ -119,309 +130,949 @@ function normalizeItemType(raw: unknown): string { .toLowerCase(); } -function shouldDropItemType(type: string): boolean { - if (type.includes("preamble") || type.includes("reasoning") || type.includes("thought")) { - return true; +function toItemType(raw: unknown): CanonicalItemType { + const normalizedType = normalizeItemType(raw); + if (normalizedType.includes("assistant message") || normalizedType.includes("agent message")) { + return "assistant_message"; } - return type === "work" || type.startsWith("work "); + if (normalizedType.includes("user message")) { + return "user_message"; + } + if (normalizedType.includes("reasoning") || normalizedType.includes("thought")) { + return "reasoning"; + } + if (normalizedType.includes("plan")) { + return "plan"; + } + if (normalizedType.includes("command")) { + return "command_execution"; + } + if (normalizedType.includes("file change") || normalizedType.includes("patch")) { + return "file_change"; + } + if (normalizedType.includes("mcp")) { + return "mcp_tool_call"; + } + if (normalizedType.includes("dynamic tool") || normalizedType.includes("tool call")) { + return "dynamic_tool_call"; + } + if (normalizedType.includes("collab")) { + return "collab_agent_tool_call"; + } + if (normalizedType.includes("web search")) { + return "web_search"; + } + if (normalizedType.includes("image")) { + return "image_view"; + } + if (normalizedType.includes("review entered")) { + return "review_entered"; + } + if (normalizedType.includes("review exited")) { + return "review_exited"; + } + if (normalizedType.includes("compact")) { + return "context_compaction"; + } + if (normalizedType.includes("error")) { + return "error"; + } + return "unknown"; } -function toolMeta(type: string): - | { - readonly toolKind: ProviderRuntimeToolKind; - readonly title: string; - } +function toRequestTypeFromKind(kind: ProviderEvent["requestKind"]): CanonicalRequestType { + switch (kind) { + case "command": + return "command_execution_approval"; + case "file-change": + return "file_change_approval"; + default: + return "unknown"; + } +} + +function toRequestType(method: string, kind: ProviderEvent["requestKind"]): CanonicalRequestType { + switch (method) { + case "item/commandExecution/requestApproval": + return "command_execution_approval"; + case "item/fileChange/requestApproval": + return "file_change_approval"; + case "applyPatchApproval": + return "apply_patch_approval"; + case "execCommandApproval": + return "exec_command_approval"; + case "item/tool/requestUserInput": + return "tool_user_input"; + case "item/tool/call": + return "dynamic_tool_call"; + case "account/chatgptAuthTokens/refresh": + return "auth_tokens_refresh"; + default: + return toRequestTypeFromKind(kind); + } +} + +function toTurnState(value: unknown): "completed" | "failed" | "interrupted" | "cancelled" | undefined { + switch (value) { + case "completed": + case "failed": + case "cancelled": + case "interrupted": + return value; + case "interruptedByUser": + return "interrupted"; + default: + return undefined; + } +} + +function toThreadState(value: unknown): + | "active" + | "idle" + | "archived" + | "closed" + | "compacted" + | "error" | undefined { - if (type.includes("command")) { - return { toolKind: "command", title: "Command run" }; - } - if (type.includes("file change")) { - return { toolKind: "file-change", title: "File change" }; - } - if (type.includes("tool")) { - return { toolKind: "other", title: "Tool call" }; - } + const normalized = asString(value)?.toLowerCase(); + if (!normalized) return undefined; + if (normalized.includes("archiv")) return "archived"; + if (normalized.includes("closed")) return "closed"; + if (normalized.includes("compact")) return "compacted"; + if (normalized.includes("error")) return "error"; + if (normalized.includes("idle")) return "idle"; + if (normalized.includes("active") || normalized.includes("running")) return "active"; return undefined; } -function itemDetail( - item: Record, - payload: Record, -): string | undefined { - const nestedResult = asObject(item.result); - const candidates = [ - asString(item.command), - asString(item.title), - asString(item.summary), - asString(item.text), - asString(item.path), - asString(item.prompt), - asString(nestedResult?.command), - asString(payload.command), - asString(payload.message), - asString(payload.prompt), - ]; - for (const candidate of candidates) { - if (!candidate) continue; - const trimmed = candidate.trim(); - if (trimmed.length === 0) continue; - return trimmed; +function toItemStatus(value: unknown): "inProgress" | "completed" | "failed" | "declined" | undefined { + switch (value) { + case "inProgress": + case "completed": + case "failed": + case "declined": + return value; + case "in_progress": + return "inProgress"; + default: + return undefined; } - return undefined; } -function mapMessageCompletedEvent(event: ProviderEvent): ProviderRuntimeEvent | undefined { - if (event.method !== "item/completed") { - return undefined; +function normalizePlanStatus(value: unknown): "pending" | "inProgress" | "completed" { + switch (value) { + case "completed": + return "completed"; + case "inProgress": + case "in_progress": + return "inProgress"; + default: + return "pending"; } +} - const payload = asObject(event.payload); - const item = asObject(payload?.item); - if (!item) { - return undefined; - } +function eventRawSource(event: ProviderEvent): "codex.app-server.notification" | "codex.app-server.request" { + return event.kind === "request" ? "codex.app-server.request" : "codex.app-server.notification"; +} - const normalizedType = normalizeItemType(item.type ?? item.kind); - if (!normalizedType.includes("agent message")) { - return undefined; +function mapStatusMethodToSessionState(method: string): + | "starting" + | "ready" + | "running" + | "waiting" + | "stopped" + | "error" + | undefined { + switch (method) { + case "session/connecting": + return "starting"; + case "session/ready": + return "ready"; + case "session/running": + return "running"; + case "session/waiting": + return "waiting"; + case "session/closed": + return "stopped"; + case "session/exited": + return "stopped"; + case "session/startFailed": + return "error"; + default: + return undefined; } +} - const itemId = event.itemId ?? asString(item.id); - if (!itemId) { - return undefined; - } +function buildBase( + event: ProviderEvent, + overrides?: { + readonly threadId?: string; + readonly turnId?: string; + readonly itemId?: string; + readonly requestId?: string; + }, +) { + const threadIdRaw = overrides?.threadId ?? event.threadId; + const turnIdRaw = overrides?.turnId ?? event.turnId; + const itemIdRaw = overrides?.itemId ?? event.itemId; + const requestIdRaw = overrides?.requestId ?? event.requestId; + const rawPayload = + event.payload ?? (event.message ? { message: event.message } : { method: event.method, kind: event.kind }); return { - type: "message.completed", eventId: event.id, provider: event.provider, sessionId: event.sessionId, createdAt: event.createdAt, - itemId: ProviderItemId.makeUnsafe(itemId), - ...(event.threadId ? { threadId: event.threadId } : {}), - ...(event.turnId ? { turnId: event.turnId } : {}), + ...(threadIdRaw ? { threadId: ProviderThreadId.makeUnsafe(threadIdRaw) } : {}), + ...(turnIdRaw ? { turnId: ProviderTurnId.makeUnsafe(turnIdRaw) } : {}), + ...(itemIdRaw ? { itemId: ProviderItemId.makeUnsafe(itemIdRaw) } : {}), + ...(requestIdRaw ? { requestId: ApprovalRequestId.makeUnsafe(requestIdRaw) } : {}), + providerRefs: { + providerSessionId: event.sessionId, + ...(threadIdRaw ? { providerThreadId: ProviderThreadId.makeUnsafe(threadIdRaw) } : {}), + ...(turnIdRaw ? { providerTurnId: ProviderTurnId.makeUnsafe(turnIdRaw) } : {}), + ...(itemIdRaw ? { providerItemId: ProviderItemId.makeUnsafe(itemIdRaw) } : {}), + ...(requestIdRaw ? { providerRequestId: requestIdRaw } : {}), + }, + raw: { + source: eventRawSource(event), + method: event.method, + payload: rawPayload, + }, + } as const; +} + +function extractQuestions(payload: Record | undefined): unknown { + if (!payload) { + return []; + } + if ("questions" in payload) { + return payload.questions; + } + return payload; +} + +function itemLifecyclePayload( + method: "item/started" | "item/completed" | "item/reasoning/summaryPartAdded" | "item/commandExecution/terminalInteraction", + item: Record | undefined, + payload: Record | undefined, +) { + const title = firstNonEmptyString(item?.title, item?.name, payload?.title); + const detail = firstNonEmptyString( + item?.command, + item?.summary, + item?.text, + item?.path, + payload?.command, + payload?.message, + payload?.prompt, + ); + const statusFromPayload = toItemStatus(item?.status ?? payload?.status); + const status = + method === "item/started" + ? (statusFromPayload ?? "inProgress") + : method === "item/completed" + ? (statusFromPayload ?? "completed") + : statusFromPayload; + return { + itemType: toItemType(item?.type ?? item?.kind ?? payload?.itemType ?? method), + ...(status ? { status } : {}), + ...(title ? { title } : {}), + ...(detail ? { detail } : {}), + ...(payload ? { data: payload } : {}), }; } -function mapToolEvent(event: ProviderEvent): ProviderRuntimeEvent | undefined { - if (event.method !== "item/started" && event.method !== "item/completed") { - return undefined; - } - const payload = asObject(event.payload); - const item = asObject(payload?.item); - if (!item) { - return undefined; - } - const normalizedType = normalizeItemType(item.type ?? item.kind); - if (shouldDropItemType(normalizedType)) { - return undefined; - } - const meta = toolMeta(normalizedType); - if (!meta) { - return undefined; - } - - const eventBase = { - eventId: event.id, - provider: event.provider, - sessionId: event.sessionId, - createdAt: event.createdAt, - ...(event.threadId ? { threadId: event.threadId } : {}), - ...(event.turnId ? { turnId: event.turnId } : {}), - ...(event.itemId ? { itemId: event.itemId } : {}), - toolKind: meta.toolKind, - title: meta.title, - ...(payload ? { detail: itemDetail(item, payload) } : {}), - } as const; - - if (event.method === "item/started") { - return { - type: "tool.started", - ...eventBase, - }; - } - +function toPlanPayload(payload: Record | undefined) { + const explanation = asString(payload?.explanation) ?? null; + const planEntries = asArray(payload?.plan) ?? []; + const plan = planEntries + .map((entry, index) => { + const value = asObject(entry); + const step = + firstNonEmptyString(value?.step, value?.title, value?.description) ?? `Step ${index + 1}`; + const status = normalizePlanStatus(value?.status); + return { step, status } as const; + }) + .filter((step) => step.step.trim().length > 0); return { - type: "tool.completed", - ...eventBase, + ...(explanation !== null ? { explanation } : {}), + plan, }; } function mapToRuntimeEvents(event: ProviderEvent): ReadonlyArray { const payload = asObject(event.payload); const turn = asObject(payload?.turn); + const item = asObject(payload?.item); + const threadIdFromPayload = asString(asObject(payload?.thread)?.id); + const turnIdFromPayload = asString(turn?.id) ?? asString(payload?.turnId); + const itemIdFromPayload = asString(item?.id) ?? asString(payload?.itemId); + const summaryIndex = asNumber(payload?.summaryIndex); + const contentIndex = asNumber(payload?.contentIndex); + const requestType = toRequestType(event.method, event.requestKind); + const requestId = event.requestId ? String(event.requestId) : undefined; if (event.kind === "error") { - if (!event.message) { - return []; - } + const message = + firstNonEmptyString(event.message, asString(asObject(payload?.error)?.message), asString(payload?.message)) ?? + "Codex provider runtime error"; return [ { + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + ...(turnIdFromPayload ? { turnId: turnIdFromPayload } : {}), + ...(itemIdFromPayload ? { itemId: itemIdFromPayload } : {}), + }), type: "runtime.error", - eventId: event.id, - provider: event.provider, - sessionId: event.sessionId, - createdAt: event.createdAt, - ...(event.threadId ? { threadId: event.threadId } : {}), - ...(event.turnId ? { turnId: event.turnId } : {}), - ...(event.itemId ? { itemId: event.itemId } : {}), - message: event.message, + payload: { + message, + class: "provider_error", + ...(payload ? { detail: payload } : {}), + }, }, ]; } - if (event.kind === "request" && event.requestId && event.requestKind) { - const detail = - asString(payload?.command) ?? asString(payload?.reason) ?? asString(payload?.prompt); - return [ - { - type: "approval.requested", - eventId: event.id, - provider: event.provider, - sessionId: event.sessionId, - createdAt: event.createdAt, - ...(event.threadId ? { threadId: event.threadId } : {}), - ...(event.turnId ? { turnId: event.turnId } : {}), - ...(event.itemId ? { itemId: event.itemId } : {}), - requestId: event.requestId, - requestKind: event.requestKind, + if (event.kind === "request") { + const detail = firstNonEmptyString( + payload?.command, + payload?.reason, + payload?.prompt, + payload?.message, + payload?.detail, + ); + const openedEvent: ProviderRuntimeEvent = { + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + ...(turnIdFromPayload ? { turnId: turnIdFromPayload } : {}), + ...(itemIdFromPayload ? { itemId: itemIdFromPayload } : {}), + ...(requestId ? { requestId } : {}), + }), + type: "request.opened", + payload: { + requestType, ...(detail ? { detail } : {}), + ...(payload ? { args: payload } : {}), }, - ]; + }; + if (event.method === "item/tool/requestUserInput") { + return [ + openedEvent, + { + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + ...(turnIdFromPayload ? { turnId: turnIdFromPayload } : {}), + ...(itemIdFromPayload ? { itemId: itemIdFromPayload } : {}), + ...(requestId ? { requestId } : {}), + }), + type: "user-input.requested", + payload: { + questions: extractQuestions(payload), + }, + }, + ]; + } + return [openedEvent]; } - if (event.method === "item/requestApproval/decision" && event.requestId) { - const decision = Schema.decodeUnknownSync(ProviderApprovalDecision)(payload?.decision); + if ( + (event.method === "item/requestApproval/decision" || event.method === "serverRequest/resolved") && + requestId + ) { + const decision = firstNonEmptyString(payload?.decision, payload?.resolution); return [ { - type: "approval.resolved", - eventId: event.id, - provider: event.provider, - sessionId: event.sessionId, - createdAt: event.createdAt, - ...(event.threadId ? { threadId: event.threadId } : {}), - ...(event.turnId ? { turnId: event.turnId } : {}), - ...(event.itemId ? { itemId: event.itemId } : {}), - requestId: event.requestId, - ...(event.requestKind ? { requestKind: event.requestKind } : {}), - ...(decision ? { decision } : {}), + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + ...(turnIdFromPayload ? { turnId: turnIdFromPayload } : {}), + ...(itemIdFromPayload ? { itemId: itemIdFromPayload } : {}), + requestId, + }), + type: "request.resolved", + payload: { + requestType, + ...(decision ? { decision } : {}), + ...(payload ? { resolution: payload } : {}), + }, }, ]; } - const messageCompleted = mapMessageCompletedEvent(event); - if (messageCompleted) { - return [messageCompleted]; + const sessionState = mapStatusMethodToSessionState(event.method); + if (event.method === "session/ready") { + return [ + { + ...buildBase(event), + type: "session.started", + payload: { + ...(event.message ? { message: event.message } : {}), + ...(payload ? { resume: payload } : {}), + }, + }, + { + ...buildBase(event), + type: "session.state.changed", + payload: { + state: "ready", + ...(event.message ? { reason: event.message } : {}), + }, + }, + ]; } - const tool = mapToolEvent(event); - if (tool) { - return [tool]; + if (sessionState) { + if (event.method === "session/closed" || event.method === "session/exited") { + return [ + { + ...buildBase(event), + type: "session.exited", + payload: { + ...(event.message ? { reason: event.message } : {}), + recoverable: event.method === "session/closed", + exitKind: event.method === "session/closed" ? "graceful" : "error", + }, + }, + ]; + } + + return [ + { + ...buildBase(event), + type: "session.state.changed", + payload: { + state: sessionState, + ...(event.message ? { reason: event.message } : {}), + }, + }, + ]; } if (event.method === "session/started") { return [ { + ...buildBase(event), type: "session.started", - eventId: event.id, - provider: event.provider, - sessionId: event.sessionId, - createdAt: event.createdAt, - ...(event.threadId ? { threadId: event.threadId } : {}), - ...(event.message ? { message: event.message } : {}), - }, - ]; - } - - if (event.method === "session/exited" || event.method === "session/closed") { - return [ - { - type: "session.exited", - eventId: event.id, - provider: event.provider, - sessionId: event.sessionId, - createdAt: event.createdAt, - ...(event.threadId ? { threadId: event.threadId } : {}), - ...(event.message ? { message: event.message } : {}), + payload: { + ...(event.message ? { message: event.message } : {}), + ...(payload ? { resume: payload } : {}), + }, }, ]; } if (event.method === "thread/started") { - const payloadThreadId = asString(asObject(payload?.thread)?.id); - const threadId = - event.threadId ?? - (payloadThreadId ? ProviderThreadId.makeUnsafe(payloadThreadId) : undefined); + const threadId = event.threadId ?? threadIdFromPayload; if (!threadId) { return []; } return [ { + ...buildBase(event, { threadId }), type: "thread.started", - eventId: event.id, - provider: event.provider, - sessionId: event.sessionId, - createdAt: event.createdAt, - threadId, + payload: { + providerThreadId: ProviderThreadId.makeUnsafe(threadId), + }, + }, + ]; + } + + if (event.method === "thread/status/changed") { + const status = toThreadState(payload?.status ?? asObject(payload?.threadStatus)?.state); + if (!status) { + return []; + } + return [ + { + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + }), + type: "thread.state.changed", + payload: { + state: status, + ...(payload ? { detail: payload } : {}), + }, + }, + ]; + } + + if (event.method === "thread/archived" || event.method === "thread/unarchived" || event.method === "thread/closed" || event.method === "thread/compacted") { + const state = + event.method === "thread/archived" + ? "archived" + : event.method === "thread/closed" + ? "closed" + : event.method === "thread/compacted" + ? "compacted" + : "active"; + return [ + { + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + }), + type: "thread.state.changed", + payload: { + state, + ...(payload ? { detail: payload } : {}), + }, + }, + ]; + } + + if (event.method === "thread/name/updated") { + return [ + { + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + }), + type: "thread.metadata.updated", + payload: { + ...(firstNonEmptyString(payload?.threadName, payload?.name) ? { name: firstNonEmptyString(payload?.threadName, payload?.name) } : {}), + ...(payload ? { metadata: payload } : {}), + }, + }, + ]; + } + + if (event.method === "thread/tokenUsage/updated") { + return [ + { + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + }), + type: "thread.token-usage.updated", + payload: { + usage: payload ?? event.payload ?? {}, + }, + }, + ]; + } + + if (event.method === "thread/realtime/started") { + return [ + { + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + }), + type: "thread.realtime.started", + payload: { + ...(asString(payload?.realtimeSessionId) ? { realtimeSessionId: asString(payload?.realtimeSessionId) } : {}), + }, + }, + ]; + } + + if (event.method === "thread/realtime/itemAdded") { + return [ + { + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + }), + type: "thread.realtime.item-added", + payload: { + item: payload?.item ?? event.payload ?? {}, + }, + }, + ]; + } + + if (event.method === "thread/realtime/outputAudio/delta") { + return [ + { + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + }), + type: "thread.realtime.audio.delta", + payload: { + audio: payload?.audio ?? event.payload ?? {}, + }, + }, + ]; + } + + if (event.method === "thread/realtime/error") { + const message = firstNonEmptyString(payload?.message, event.message) ?? "Realtime error"; + return [ + { + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + }), + type: "thread.realtime.error", + payload: { message }, + }, + ]; + } + + if (event.method === "thread/realtime/closed") { + return [ + { + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + }), + type: "thread.realtime.closed", + payload: { + ...(firstNonEmptyString(payload?.reason, event.message) ? { reason: firstNonEmptyString(payload?.reason, event.message) } : {}), + }, }, ]; } if (event.method === "turn/started") { - const payloadTurnId = asString(turn?.id); - const turnId = - event.turnId ?? (payloadTurnId ? ProviderTurnId.makeUnsafe(payloadTurnId) : undefined); + const turnId = event.turnId ?? turnIdFromPayload; if (!turnId) { return []; } return [ { + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + turnId, + }), type: "turn.started", - eventId: event.id, - provider: event.provider, - sessionId: event.sessionId, - createdAt: event.createdAt, - ...(event.threadId ? { threadId: event.threadId } : {}), - turnId, + payload: { + ...(firstNonEmptyString(turn?.model, payload?.model) ? { model: firstNonEmptyString(turn?.model, payload?.model) } : {}), + ...(firstNonEmptyString(turn?.effort, payload?.effort) ? { effort: firstNonEmptyString(turn?.effort, payload?.effort) } : {}), + }, }, ]; } if (event.method === "turn/completed") { + const state = toTurnState(turn?.status) ?? "completed"; + const errorMessage = firstNonEmptyString(asObject(turn?.error)?.message, event.message); return [ { + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + ...(turnIdFromPayload ? { turnId: turnIdFromPayload } : {}), + }), type: "turn.completed", - eventId: event.id, - provider: event.provider, - sessionId: event.sessionId, - createdAt: event.createdAt, - ...(event.threadId ? { threadId: event.threadId } : {}), - ...(event.turnId ? { turnId: event.turnId } : {}), - ...(toTurnStatus(turn?.status) ? { status: toTurnStatus(turn?.status) } : {}), - ...(asString(asObject(turn?.error)?.message) - ? { errorMessage: asString(asObject(turn?.error)?.message) } - : {}), + payload: { + state, + ...(asString(turn?.stopReason) ? { stopReason: asString(turn?.stopReason) } : {}), + ...(turn?.usage !== undefined ? { usage: turn.usage } : {}), + ...(asObject(turn?.modelUsage) ? { modelUsage: asObject(turn?.modelUsage) } : {}), + ...(asNumber(turn?.totalCostUsd) !== undefined ? { totalCostUsd: asNumber(turn?.totalCostUsd) } : {}), + ...(errorMessage ? { errorMessage } : {}), + }, }, ]; } - if (event.method === "item/agentMessage/delta" && event.textDelta && event.textDelta.length > 0) { + if (event.method === "turn/aborted") { return [ { - type: "message.delta", - eventId: event.id, - provider: event.provider, - sessionId: event.sessionId, - createdAt: event.createdAt, - ...(event.threadId ? { threadId: event.threadId } : {}), - ...(event.turnId ? { turnId: event.turnId } : {}), - ...(event.itemId ? { itemId: event.itemId } : {}), - delta: event.textDelta, + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + ...(turnIdFromPayload ? { turnId: turnIdFromPayload } : {}), + }), + type: "turn.aborted", + payload: { + reason: firstNonEmptyString(payload?.reason, event.message) ?? "Turn aborted", + }, }, ]; } - return []; + if (event.method === "turn/plan/updated") { + return [ + { + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + ...(turnIdFromPayload ? { turnId: turnIdFromPayload } : {}), + }), + type: "turn.plan.updated", + payload: toPlanPayload(payload), + }, + ]; + } + + if (event.method === "turn/diff/updated") { + const unifiedDiff = asString(payload?.unifiedDiff) ?? asString(payload?.diff) ?? ""; + return [ + { + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + ...(turnIdFromPayload ? { turnId: turnIdFromPayload } : {}), + }), + type: "turn.diff.updated", + payload: { unifiedDiff }, + }, + ]; + } + + if ( + event.method === "item/started" || + event.method === "item/completed" || + event.method === "item/reasoning/summaryPartAdded" || + event.method === "item/commandExecution/terminalInteraction" + ) { + const resolvedItemId = event.itemId ?? itemIdFromPayload; + const base = buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + ...(turnIdFromPayload ? { turnId: turnIdFromPayload } : {}), + ...(resolvedItemId ? { itemId: resolvedItemId } : {}), + }); + const payloadShape = itemLifecyclePayload(event.method, item, payload); + const type = + event.method === "item/started" + ? "item.started" + : event.method === "item/completed" + ? "item.completed" + : "item.updated"; + return [{ ...base, type, payload: payloadShape }]; + } + + if (event.method === "error") { + const message = + firstNonEmptyString(asObject(payload?.error)?.message, event.message) ?? + "Codex server runtime error"; + return [ + { + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + ...(turnIdFromPayload ? { turnId: turnIdFromPayload } : {}), + ...(itemIdFromPayload ? { itemId: itemIdFromPayload } : {}), + }), + type: "runtime.error", + payload: { + message, + class: "provider_error", + ...(payload ? { detail: payload } : {}), + }, + }, + ]; + } + + if ( + event.method === "item/agentMessage/delta" || + event.method === "item/plan/delta" || + event.method === "item/commandExecution/outputDelta" || + event.method === "item/fileChange/outputDelta" || + event.method === "item/reasoning/summaryTextDelta" || + event.method === "item/reasoning/textDelta" + ) { + const delta = + firstNonEmptyString( + event.textDelta, + payload?.delta, + payload?.text, + payload?.outputDelta, + payload?.summaryTextDelta, + payload?.textDelta, + ) ?? ""; + if (delta.length === 0) { + return []; + } + const streamKind = + event.method === "item/agentMessage/delta" + ? "assistant_text" + : event.method === "item/plan/delta" + ? "plan_text" + : event.method === "item/commandExecution/outputDelta" + ? "command_output" + : event.method === "item/fileChange/outputDelta" + ? "file_change_output" + : event.method === "item/reasoning/summaryTextDelta" + ? "reasoning_summary_text" + : "reasoning_text"; + return [ + { + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + ...(turnIdFromPayload ? { turnId: turnIdFromPayload } : {}), + ...(itemIdFromPayload ? { itemId: itemIdFromPayload } : {}), + }), + type: "content.delta", + payload: { + streamKind, + delta, + ...(contentIndex !== undefined ? { contentIndex } : {}), + ...(summaryIndex !== undefined ? { summaryIndex } : {}), + }, + }, + ]; + } + + if (event.method === "item/mcpToolCall/progress") { + const summary = firstNonEmptyString(payload?.summary, payload?.message); + return [ + { + ...buildBase(event, { + ...(threadIdFromPayload ? { threadId: threadIdFromPayload } : {}), + ...(turnIdFromPayload ? { turnId: turnIdFromPayload } : {}), + ...(itemIdFromPayload ? { itemId: itemIdFromPayload } : {}), + }), + type: "tool.progress", + payload: { + ...(asString(payload?.toolUseId) ? { toolUseId: asString(payload?.toolUseId) } : {}), + ...(asString(payload?.toolName) ? { toolName: asString(payload?.toolName) } : {}), + ...(summary ? { summary } : {}), + ...(asNumber(payload?.elapsedSeconds) !== undefined + ? { elapsedSeconds: asNumber(payload?.elapsedSeconds) } + : {}), + }, + }, + ]; + } + + if (event.method === "model/rerouted") { + const fromModel = firstNonEmptyString(payload?.fromModel); + const toModel = firstNonEmptyString(payload?.toModel); + const reason = firstNonEmptyString(payload?.reason); + if (!fromModel || !toModel || !reason) { + return []; + } + return [ + { + ...buildBase(event), + type: "model.rerouted", + payload: { + fromModel, + toModel, + reason, + }, + }, + ]; + } + + if (event.method === "deprecationNotice") { + const summary = firstNonEmptyString(payload?.summary, event.message); + if (!summary) { + return []; + } + return [ + { + ...buildBase(event), + type: "deprecation.notice", + payload: { + summary, + ...(firstNonEmptyString(payload?.details) ? { details: firstNonEmptyString(payload?.details) } : {}), + }, + }, + ]; + } + + if (event.method === "configWarning") { + const summary = firstNonEmptyString(payload?.summary, event.message); + if (!summary) { + return []; + } + return [ + { + ...buildBase(event), + type: "config.warning", + payload: { + summary, + ...(firstNonEmptyString(payload?.details) ? { details: firstNonEmptyString(payload?.details) } : {}), + ...(firstNonEmptyString(payload?.path) ? { path: firstNonEmptyString(payload?.path) } : {}), + ...(payload?.range !== undefined ? { range: payload.range } : {}), + }, + }, + ]; + } + + if (event.method === "account/updated") { + return [ + { + ...buildBase(event), + type: "account.updated", + payload: { + account: payload ?? event.payload ?? {}, + }, + }, + ]; + } + + if (event.method === "account/rateLimits/updated") { + return [ + { + ...buildBase(event), + type: "account.rate-limits.updated", + payload: { + rateLimits: payload ?? event.payload ?? {}, + }, + }, + ]; + } + + if (event.method === "mcpServer/oauthLogin/completed") { + return [ + { + ...buildBase(event), + type: "mcp.oauth.completed", + payload: { + success: asBoolean(payload?.success) ?? false, + ...(firstNonEmptyString(payload?.name) ? { name: firstNonEmptyString(payload?.name) } : {}), + ...(firstNonEmptyString(payload?.error) ? { error: firstNonEmptyString(payload?.error) } : {}), + }, + }, + ]; + } + + if (event.method === "account/login/completed") { + return [ + { + ...buildBase(event), + type: "auth.status", + payload: { + isAuthenticating: false, + ...(firstNonEmptyString(event.message) ? { output: [firstNonEmptyString(event.message)!] } : {}), + ...(firstNonEmptyString(payload?.error) ? { error: firstNonEmptyString(payload?.error) } : {}), + }, + }, + ]; + } + + if (event.method === "windowsSandbox/setupCompleted") { + return [ + { + ...buildBase(event), + type: "session.state.changed", + payload: { + state: asBoolean(payload?.success) === false ? "error" : "ready", + ...(event.message ? { reason: event.message } : {}), + }, + }, + { + ...buildBase(event), + type: "runtime.warning", + payload: { + message: + firstNonEmptyString(event.message, payload?.message) ?? + "Windows sandbox setup completed", + ...(payload ? { detail: payload } : {}), + }, + }, + ]; + } + + if (event.method === "windows/worldWritableWarning" || event.method === "app/list/updated") { + return [ + { + ...buildBase(event), + type: "runtime.warning", + payload: { + message: + firstNonEmptyString(event.message, payload?.message) ?? + `Unhandled codex notification: ${event.method}`, + ...(payload ? { detail: payload } : {}), + }, + }, + ]; + } + + return [ + { + ...buildBase(event), + type: "runtime.warning", + payload: { + message: `Unhandled codex notification: ${event.method}`, + ...(payload ? { detail: payload } : {}), + }, + }, + ]; } const makeCodexAdapter = (options?: CodexAdapterLiveOptions) => diff --git a/apps/server/src/provider/Layers/CursorAdapter.test.ts b/apps/server/src/provider/Layers/CursorAdapter.test.ts new file mode 100644 index 0000000000..e82a12f2e4 --- /dev/null +++ b/apps/server/src/provider/Layers/CursorAdapter.test.ts @@ -0,0 +1,350 @@ +import { EventEmitter } from "node:events"; +import { PassThrough, Writable } from "node:stream"; + +import { ApprovalRequestId } from "@t3tools/contracts"; +import { assert, describe, it } from "@effect/vitest"; +import { Effect, Fiber, Stream } from "effect"; + +import { CursorAdapter } from "../Services/CursorAdapter.ts"; +import { makeCursorAdapterLive } from "./CursorAdapter.ts"; + +class JsonLineWritable extends Writable { + private buffer = ""; + + constructor(private readonly onLine: (line: string) => void) { + super(); + } + + override _write( + chunk: Buffer | string, + _encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ) { + this.buffer += chunk.toString(); + let newlineIndex = this.buffer.indexOf("\n"); + while (newlineIndex >= 0) { + const line = this.buffer.slice(0, newlineIndex).trim(); + this.buffer = this.buffer.slice(newlineIndex + 1); + if (line.length > 0) { + this.onLine(line); + } + newlineIndex = this.buffer.indexOf("\n"); + } + callback(); + } +} + +class FakeCursorAcpProcess extends EventEmitter { + readonly stdout = new PassThrough(); + readonly stderr = new PassThrough(); + readonly stdin: Writable; + killed = false; + + readonly permissionSelections: Array = []; + private readonly sessionId = "acp-session-1"; + private nextPermissionRequestId = 900; + + constructor() { + super(); + this.stdin = new JsonLineWritable((line) => this.onClientLine(line)); + } + + kill(signal?: NodeJS.Signals): boolean { + if (this.killed) return true; + this.killed = true; + this.emit("exit", 0, signal ?? null); + return true; + } + + private send(message: unknown): void { + this.stdout.write(`${JSON.stringify(message)}\n`); + } + + private sendSessionUpdate(sessionUpdate: Record, sessionId = this.sessionId): void { + this.send({ + jsonrpc: "2.0", + method: "session/update", + params: { + sessionId, + update: sessionUpdate, + }, + }); + } + + private sendPermissionRequest(sessionId = this.sessionId): void { + const requestId = this.nextPermissionRequestId; + this.nextPermissionRequestId += 1; + this.send({ + jsonrpc: "2.0", + id: requestId, + method: "session/request_permission", + params: { + sessionId, + toolCall: { + kind: "execute", + title: "Terminal", + command: "pwd", + }, + options: [ + { optionId: "allow-once", title: "Allow once" }, + { optionId: "allow-always", title: "Always allow" }, + { optionId: "reject-once", title: "Reject" }, + ], + }, + }); + } + + private onClientLine(line: string): void { + const parsed = JSON.parse(line) as Record; + const method = typeof parsed.method === "string" ? parsed.method : undefined; + const id = parsed.id; + + if (!method && (typeof id === "string" || typeof id === "number")) { + const optionId = + (parsed.result as { outcome?: { optionId?: unknown } } | undefined)?.outcome?.optionId; + if (typeof optionId === "string") { + this.permissionSelections.push(optionId); + } + return; + } + + if (method === "initialize") { + this.send({ + jsonrpc: "2.0", + id, + result: { + protocolVersion: 1, + agentCapabilities: { + loadSession: true, + }, + authMethods: [{ id: "cursor_login" }], + }, + }); + return; + } + + if (method === "authenticate") { + this.send({ + jsonrpc: "2.0", + id, + result: {}, + }); + return; + } + + if (method === "session/new" || method === "session/load") { + this.send({ + jsonrpc: "2.0", + id, + result: { + sessionId: this.sessionId, + modes: ["agent", "plan", "ask"], + }, + }); + return; + } + + if (method === "session/prompt") { + const params = parsed.params as { sessionId?: unknown } | undefined; + const sessionId = typeof params?.sessionId === "string" ? params.sessionId : this.sessionId; + setTimeout(() => { + this.sendSessionUpdate( + { + sessionUpdate: "agent_thought_chunk", + content: { type: "text", text: "thinking..." }, + }, + sessionId, + ); + this.sendSessionUpdate( + { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "hello from cursor" }, + }, + sessionId, + ); + this.sendSessionUpdate( + { + sessionUpdate: "tool_call", + toolCallId: "tool-1", + title: "Terminal", + kind: "execute", + rawInput: { command: "pwd" }, + }, + sessionId, + ); + this.sendPermissionRequest(sessionId); + this.sendSessionUpdate( + { + sessionUpdate: "tool_call_update", + toolCallId: "tool-1", + status: "completed", + rawOutput: { exitCode: 0, stdout: "/workspace\n", stderr: "" }, + }, + sessionId, + ); + this.send({ + jsonrpc: "2.0", + id, + result: { + stopReason: "end_turn", + }, + }); + }, 0); + return; + } + + if (method === "session/cancel") { + this.send({ + jsonrpc: "2.0", + id, + error: { + code: -32601, + message: "Method not found", + }, + }); + return; + } + + this.send({ + jsonrpc: "2.0", + id, + error: { + code: -32601, + message: `Unsupported method: ${method ?? "unknown"}`, + }, + }); + } +} + +function makeHarness() { + const fakeProcess = new FakeCursorAcpProcess(); + const layer = makeCursorAdapterLive({ + spawnProcess: () => fakeProcess as never, + }); + return { + fakeProcess, + layer, + }; +} + +describe("CursorAdapterLive", () => { + it.effect("maps ACP lifecycle and prompt streaming to canonical v2 events", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* CursorAdapter; + + const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 13).pipe( + Stream.runCollect, + Effect.forkChild, + ); + + const session = yield* adapter.startSession({ + provider: "cursor", + }); + + const turn = yield* adapter.sendTurn({ + sessionId: session.sessionId, + input: "hello", + attachments: [], + }); + + const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber)); + + assert.equal(session.threadId, "acp-session-1"); + assert.equal(turn.turnId.startsWith("cursor-turn-"), true); + + assert.equal(runtimeEvents.some((event) => event.type === "session.configured"), true); + assert.equal(runtimeEvents.some((event) => event.type === "auth.status"), true); + assert.equal(runtimeEvents.some((event) => event.type === "thread.started"), true); + assert.equal(runtimeEvents.some((event) => event.type === "turn.started"), true); + assert.equal( + runtimeEvents.some( + (event) => + event.type === "content.delta" && + event.payload.streamKind === "assistant_text" && + event.payload.delta === "hello from cursor", + ), + true, + ); + assert.equal( + runtimeEvents.some( + (event) => + event.type === "item.started" && + event.payload.itemType === "command_execution" && + event.payload.status === "inProgress", + ), + true, + ); + assert.equal( + runtimeEvents.some( + (event) => + event.type === "item.completed" && + event.payload.itemType === "command_execution" && + event.payload.status === "completed", + ), + true, + ); + assert.equal( + runtimeEvents.some( + (event) => + event.type === "turn.completed" && + event.turnId === turn.turnId && + event.payload.state === "completed", + ), + true, + ); + }).pipe(Effect.provide(harness.layer)); + }); + + it.effect("bridges ACP permission requests through respondToRequest", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const adapter = yield* CursorAdapter; + + const session = yield* adapter.startSession({ + provider: "cursor", + }); + + const openedFiber = yield* Stream.filter(adapter.streamEvents, (event) => event.type === "request.opened").pipe( + Stream.runHead, + Effect.forkChild, + ); + const resolvedFiber = yield* Stream.filter( + adapter.streamEvents, + (event) => event.type === "request.resolved", + ).pipe(Stream.runHead, Effect.forkChild); + + yield* adapter.sendTurn({ + sessionId: session.sessionId, + input: "trigger permission", + attachments: [], + }); + + const opened = yield* Fiber.join(openedFiber); + assert.equal(opened._tag, "Some"); + if (opened._tag !== "Some" || opened.value.type !== "request.opened") { + return; + } + const requestId = opened.value.requestId; + assert.notStrictEqual(requestId, undefined); + if (!requestId) { + return; + } + + yield* adapter.respondToRequest( + session.sessionId, + ApprovalRequestId.makeUnsafe(requestId), + "acceptForSession", + ); + + const resolved = yield* Fiber.join(resolvedFiber); + assert.equal(resolved._tag, "Some"); + if (resolved._tag !== "Some" || resolved.value.type !== "request.resolved") { + return; + } + + assert.equal(resolved.value.payload.decision, "acceptForSession"); + assert.equal(harness.fakeProcess.permissionSelections.includes("allow-always"), true); + }).pipe(Effect.provide(harness.layer)); + }); +}); diff --git a/apps/server/src/provider/Layers/CursorAdapter.ts b/apps/server/src/provider/Layers/CursorAdapter.ts new file mode 100644 index 0000000000..8757a3b125 --- /dev/null +++ b/apps/server/src/provider/Layers/CursorAdapter.ts @@ -0,0 +1,1714 @@ +/** + * CursorAdapterLive - Scoped live implementation for the Cursor ACP provider adapter. + * + * Implements JSON-RPC 2.0 over stdio for `agent acp`, projects ACP session updates + * into canonical provider runtime events, and bridges external approval requests. + * + * @module CursorAdapterLive + */ +import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import readline from "node:readline"; + +import { + ApprovalRequestId, + EventId, + ProviderItemId, + type ProviderApprovalDecision, + type ProviderRuntimeEvent, + type ProviderSendTurnInput, + ProviderSessionId, + type ProviderSession, + type ProviderSessionStartInput, + ProviderThreadId, + ProviderTurnId, +} from "@t3tools/contracts"; +import { Effect, Layer, Queue, Stream } from "effect"; + +import { + ProviderAdapterProcessError, + ProviderAdapterRequestError, + ProviderAdapterSessionClosedError, + ProviderAdapterSessionNotFoundError, + ProviderAdapterValidationError, + type ProviderAdapterError, +} from "../Errors.ts"; +import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts"; +import { CursorAdapter, type CursorAdapterShape } from "../Services/CursorAdapter.ts"; + +const PROVIDER = "cursor" as const; +const DEFAULT_REQUEST_TIMEOUT_MS = 30_000; + +interface PendingRpcRequest { + readonly method: string; + readonly timeout: ReturnType; + readonly resolve: (value: unknown) => void; + readonly reject: (error: Error) => void; +} + +interface PendingPermissionRequest { + readonly jsonRpcId: string | number; + readonly requestType: + | "command_execution_approval" + | "file_change_approval" + | "apply_patch_approval" + | "exec_command_approval" + | "tool_user_input" + | "dynamic_tool_call" + | "auth_tokens_refresh" + | "unknown"; + readonly options: ReadonlyArray; +} + +interface ToolInFlight { + readonly itemId: ProviderItemId; + readonly itemType: "command_execution" | "file_change" | "dynamic_tool_call"; + title?: string; + detail?: string; +} + +interface CursorTurnState { + readonly turnId: ProviderTurnId; + readonly assistantItemId: ProviderItemId; + readonly startedAt: string; + readonly items: Array; + assistantCompleted: boolean; + assistantText: string; +} + +interface CursorSessionContext { + session: ProviderSession; + readonly child: ChildProcessWithoutNullStreams; + readonly stdoutRl: readline.Interface; + readonly stderrRl: readline.Interface; + readonly pendingRequests: Map; + readonly pendingPermissions: Map; + readonly toolsByToolCallId: Map; + readonly turns: Array<{ id: ProviderTurnId; items: ReadonlyArray }>; + turnState: CursorTurnState | undefined; + acpSessionId: string | undefined; + nextRequestId: number; + stopping: boolean; +} + +interface CursorResumeState { + readonly sessionId?: string; + readonly turnCount?: number; +} + +interface JsonRpcResponseEnvelope { + readonly id: string | number; + readonly result?: unknown; + readonly error?: { + readonly code?: number; + readonly message?: string; + readonly data?: unknown; + }; +} + +interface JsonRpcRequestEnvelope { + readonly id: string | number; + readonly method: string; + readonly params?: unknown; +} + +interface JsonRpcNotificationEnvelope { + readonly method: string; + readonly params?: unknown; +} + +export interface CursorAdapterLiveOptions { + readonly nativeEventLogPath?: string; + readonly spawnProcess?: (input: { + readonly binaryPath: string; + readonly cwd: string; + }) => ChildProcessWithoutNullStreams; +} + +function toMessage(cause: unknown, fallback: string): string { + if (cause instanceof Error && cause.message.length > 0) { + return cause.message; + } + if (typeof cause === "string" && cause.length > 0) { + return cause; + } + if (cause && typeof cause === "object") { + const message = (cause as { message?: unknown }).message; + if (typeof message === "string" && message.length > 0) { + return message; + } + } + return fallback; +} + +function asObject(value: unknown): Record | undefined { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : undefined; +} + +function asArray(value: unknown): ReadonlyArray | undefined { + return Array.isArray(value) ? value : undefined; +} + +function asString(value: unknown): string | undefined { + return typeof value === "string" ? value : undefined; +} + +function asNumber(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) ? value : undefined; +} + +function firstNonEmptyString(...values: ReadonlyArray): string | undefined { + for (const value of values) { + if (typeof value !== "string") continue; + const trimmed = value.trim(); + if (trimmed.length > 0) { + return trimmed; + } + } + return undefined; +} + +function asRpcError( + cause: unknown, +): { readonly code?: number; readonly message: string; readonly data?: unknown } | undefined { + const object = asObject(cause); + if (!object) { + return undefined; + } + const code = asNumber(object.code); + const message = asString(object.message); + if (!message) { + return undefined; + } + return { + ...(code !== undefined ? { code } : {}), + message, + ...(object.data !== undefined ? { data: object.data } : {}), + }; +} + +function toSessionError( + sessionId: ProviderSessionId, + cause: unknown, +): ProviderAdapterSessionNotFoundError | ProviderAdapterSessionClosedError | undefined { + const normalized = toMessage(cause, "").toLowerCase(); + if (normalized.includes("unknown session") || normalized.includes("not found")) { + return new ProviderAdapterSessionNotFoundError({ + provider: PROVIDER, + sessionId, + cause, + }); + } + if (normalized.includes("closed")) { + return new ProviderAdapterSessionClosedError({ + provider: PROVIDER, + sessionId, + cause, + }); + } + return undefined; +} + +function toRequestError( + sessionId: ProviderSessionId, + method: string, + cause: unknown, +): ProviderAdapterError { + const sessionError = toSessionError(sessionId, cause); + if (sessionError) { + return sessionError; + } + return new ProviderAdapterRequestError({ + provider: PROVIDER, + method, + detail: toMessage(cause, `${method} failed`), + cause, + }); +} + +function mapStopReasonToTurnState(value: string | undefined): "completed" | "failed" | "interrupted" | "cancelled" { + switch (value) { + case "cancelled": + return "cancelled"; + case "interrupted": + return "interrupted"; + case "failed": + return "failed"; + default: + return "completed"; + } +} + +function mapPermissionRequestType( + toolCall: unknown, +): + | "command_execution_approval" + | "file_change_approval" + | "apply_patch_approval" + | "exec_command_approval" + | "tool_user_input" + | "dynamic_tool_call" + | "auth_tokens_refresh" + | "unknown" { + const record = asObject(toolCall); + const kind = asString(record?.kind)?.toLowerCase(); + if (!kind) { + return "unknown"; + } + if (kind.includes("execute") || kind.includes("terminal") || kind.includes("command")) { + return "command_execution_approval"; + } + if (kind.includes("edit") || kind.includes("write") || kind.includes("file")) { + return "file_change_approval"; + } + return "unknown"; +} + +function classifyToolItemType(input: { + readonly kind?: string; + readonly title?: string; + readonly rawInput?: unknown; +}): "command_execution" | "file_change" | "dynamic_tool_call" { + const kind = input.kind?.toLowerCase(); + const title = input.title?.toLowerCase(); + const rawInput = asObject(input.rawInput); + const command = firstNonEmptyString(rawInput?.command, rawInput?.cmd); + + if ( + (kind && (kind.includes("execute") || kind.includes("terminal") || kind.includes("command"))) || + (title && (title.includes("terminal") || title.includes("bash"))) || + command + ) { + return "command_execution"; + } + + if ( + (kind && (kind.includes("edit") || kind.includes("write") || kind.includes("file"))) || + (title && title.includes("file")) + ) { + return "file_change"; + } + + return "dynamic_tool_call"; +} + +function summarizeToolInput(rawInput: unknown, title?: string): string | undefined { + const input = asObject(rawInput); + const command = firstNonEmptyString(input?.command, input?.cmd); + if (command) { + return command; + } + return firstNonEmptyString(title); +} + +function summarizeToolOutput(rawOutput: unknown): string | undefined { + const output = asObject(rawOutput); + if (!output) { + return undefined; + } + const exitCode = asNumber(output.exitCode); + const stdout = firstNonEmptyString(output.stdout); + const stderr = firstNonEmptyString(output.stderr); + const summary = firstNonEmptyString(output.summary, output.message); + + if (summary) { + return summary; + } + if (exitCode !== undefined || stdout || stderr) { + const chunks: Array = []; + if (exitCode !== undefined) chunks.push(`exit=${exitCode}`); + if (stdout) chunks.push(`stdout=${stdout.slice(0, 160)}`); + if (stderr) chunks.push(`stderr=${stderr.slice(0, 160)}`); + return chunks.join(" "); + } + + const serialized = JSON.stringify(output); + return serialized.length > 240 ? `${serialized.slice(0, 237)}...` : serialized; +} + +function readCursorResumeState(resumeCursor: unknown): CursorResumeState | undefined { + const cursor = asObject(resumeCursor); + if (!cursor) { + return undefined; + } + const sessionId = + firstNonEmptyString(cursor.sessionId, cursor.acpSessionId, cursor.providerSessionId) ?? undefined; + const turnCountValue = cursor.turnCount; + const turnCount = + typeof turnCountValue === "number" && Number.isInteger(turnCountValue) && turnCountValue >= 0 + ? turnCountValue + : undefined; + if (!sessionId && turnCount === undefined) { + return undefined; + } + return { + ...(sessionId ? { sessionId } : {}), + ...(turnCount !== undefined ? { turnCount } : {}), + }; +} + +function buildPrompt(input: ProviderSendTurnInput): Array<{ type: "text"; text: string }> { + const chunks: Array<{ type: "text"; text: string }> = []; + if (input.input && input.input.trim().length > 0) { + chunks.push({ type: "text", text: input.input.trim() }); + } + + for (const attachment of input.attachments ?? []) { + if (attachment.type === "image") { + chunks.push({ + type: "text", + text: `Attached image: ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`, + }); + } + } + + return chunks; +} + +const makeCursorAdapter = (options?: CursorAdapterLiveOptions) => + Effect.gen(function* () { + const nativeEventLogger = + options?.nativeEventLogPath !== undefined + ? makeEventNdjsonLogger(options.nativeEventLogPath) + : undefined; + + const runtimeEventQueue = yield* Queue.unbounded(); + const sessions = new Map(); + + const stamp = () => ({ + eventId: EventId.makeUnsafe(randomUUID()), + createdAt: new Date().toISOString(), + }); + + const emitRuntimeEvent = (event: ProviderRuntimeEvent): void => { + Queue.offerAllUnsafe(runtimeEventQueue, [event]); + }; + + const logNative = (record: unknown) => { + nativeEventLogger?.write({ + observedAt: new Date().toISOString(), + record, + }); + }; + + const baseEvent = ( + context: CursorSessionContext, + raw: { + readonly source: "cursor.acp.notification" | "cursor.acp.request" | "cursor.acp.response"; + readonly method: string; + readonly payload: unknown; + }, + overrides?: { + readonly turnId?: ProviderTurnId; + readonly itemId?: ProviderItemId; + readonly requestId?: ApprovalRequestId; + }, +) => { + const eventStamp = stamp(); + const threadId = context.session.threadId; + const turnId = overrides?.turnId ?? context.turnState?.turnId; + return { + eventId: eventStamp.eventId, + provider: PROVIDER, + sessionId: context.session.sessionId, + createdAt: eventStamp.createdAt, + ...(threadId ? { threadId } : {}), + ...(turnId ? { turnId } : {}), + ...(overrides?.itemId ? { itemId: overrides.itemId } : {}), + ...(overrides?.requestId ? { requestId: overrides.requestId } : {}), + providerRefs: { + providerSessionId: context.session.sessionId, + ...(threadId ? { providerThreadId: threadId } : {}), + ...(turnId ? { providerTurnId: turnId } : {}), + ...(overrides?.itemId ? { providerItemId: overrides.itemId } : {}), + ...(overrides?.requestId ? { providerRequestId: overrides.requestId } : {}), + }, + raw, + } as const; + }; + + const rejectPendingRequests = (context: CursorSessionContext, message: string) => { + for (const [id, pending] of context.pendingRequests) { + clearTimeout(pending.timeout); + pending.reject(new Error(message)); + context.pendingRequests.delete(id); + } + }; + + const completeTurn = ( + context: CursorSessionContext, + state: "completed" | "failed" | "interrupted" | "cancelled", + options?: { + readonly stopReason?: string; + readonly errorMessage?: string; + }, + ) => { + const turnState = context.turnState; + if (!turnState) { + return; + } + + if (!turnState.assistantCompleted) { + emitRuntimeEvent({ + ...baseEvent( + context, + { + source: "cursor.acp.response", + method: "session/prompt", + payload: { + stopReason: options?.stopReason ?? null, + }, + }, + { itemId: turnState.assistantItemId, turnId: turnState.turnId }, + ), + type: "item.completed", + payload: { + itemType: "assistant_message", + status: state === "failed" ? "failed" : "completed", + ...(turnState.assistantText.length > 0 ? { detail: turnState.assistantText.slice(0, 200) } : {}), + }, + }); + turnState.assistantCompleted = true; + } + + context.turns.push({ + id: turnState.turnId, + items: [...turnState.items], + }); + + emitRuntimeEvent({ + ...baseEvent( + context, + { + source: "cursor.acp.response", + method: "session/prompt", + payload: { + stopReason: options?.stopReason ?? null, + }, + }, + { turnId: turnState.turnId }, + ), + type: "turn.completed", + payload: { + state, + ...(options?.stopReason ? { stopReason: options.stopReason } : {}), + ...(options?.errorMessage ? { errorMessage: options.errorMessage } : {}), + }, + }); + + context.turnState = undefined; + context.session = { + ...context.session, + status: state === "failed" ? "error" : "ready", + activeTurnId: undefined, + updatedAt: new Date().toISOString(), + ...(state === "failed" && options?.errorMessage ? { lastError: options.errorMessage } : {}), + }; + }; + + const stopSessionInternal = ( + context: CursorSessionContext, + options?: { + readonly emitExitEvent?: boolean; + }, + ) => { + if (context.stopping) { + return; + } + context.stopping = true; + + for (const [requestId, pending] of context.pendingPermissions) { + emitRuntimeEvent({ + ...baseEvent( + context, + { + source: "cursor.acp.response", + method: "session/request_permission", + payload: { + decision: "cancel", + }, + }, + { requestId }, + ), + type: "request.resolved", + payload: { + requestType: pending.requestType, + decision: "cancel", + }, + }); + } + context.pendingPermissions.clear(); + + if (context.turnState) { + completeTurn(context, "interrupted", { + errorMessage: "Session stopped.", + stopReason: "interrupted", + }); + } + + rejectPendingRequests(context, "Cursor ACP session stopped before request completed."); + + try { + context.stdoutRl.close(); + } catch { + // no-op + } + try { + context.stderrRl.close(); + } catch { + // no-op + } + try { + if (!context.child.killed) { + context.child.kill("SIGTERM"); + } + } catch { + // no-op + } + + context.session = { + ...context.session, + status: "closed", + activeTurnId: undefined, + updatedAt: new Date().toISOString(), + }; + + if (options?.emitExitEvent !== false) { + emitRuntimeEvent({ + ...baseEvent(context, { + source: "cursor.acp.notification", + method: "session/exited", + payload: { reason: "Session stopped" }, + }), + type: "session.exited", + payload: { + reason: "Session stopped", + recoverable: true, + exitKind: "graceful", + }, + }); + } + + sessions.delete(context.session.sessionId); + }; + + const requireSession = ( + sessionId: ProviderSessionId, + ): Effect.Effect => { + const context = sessions.get(sessionId); + if (!context) { + return Effect.fail( + new ProviderAdapterSessionNotFoundError({ + provider: PROVIDER, + sessionId, + }), + ); + } + if (context.stopping || context.session.status === "closed") { + return Effect.fail( + new ProviderAdapterSessionClosedError({ + provider: PROVIDER, + sessionId, + }), + ); + } + return Effect.succeed(context); + }; + + const writeMessage = (context: CursorSessionContext, message: unknown): void => { + if (!context.child.stdin.writable) { + throw new Error("Cursor ACP stdin is not writable."); + } + logNative({ + direction: "client->server", + sessionId: context.session.sessionId, + message, + }); + context.child.stdin.write(`${JSON.stringify(message)}\n`); + }; + + const sendRequest = ( + context: CursorSessionContext, + method: string, + params: unknown, + timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS, + ): Promise => + new Promise((resolve, reject) => { + const id = context.nextRequestId; + context.nextRequestId += 1; + const key = String(id); + const timeout = setTimeout(() => { + context.pendingRequests.delete(key); + reject(new Error(`Timed out waiting for ${method}.`)); + }, timeoutMs); + + context.pendingRequests.set(key, { + method, + timeout, + resolve, + reject, + }); + + writeMessage(context, { + jsonrpc: "2.0", + id, + method, + params, + }); + }); + + const handleSessionUpdate = ( + context: CursorSessionContext, + update: Record, + rawParams: unknown, + ) => { + const sessionUpdate = asString(update.sessionUpdate); + if (!sessionUpdate) { + emitRuntimeEvent({ + ...baseEvent(context, { + source: "cursor.acp.notification", + method: "session/update", + payload: rawParams, + }), + type: "runtime.warning", + payload: { + message: "Cursor ACP session/update missing sessionUpdate discriminator.", + detail: rawParams, + }, + }); + return; + } + + if (sessionUpdate === "available_commands_update") { + emitRuntimeEvent({ + ...baseEvent(context, { + source: "cursor.acp.notification", + method: "session/update", + payload: rawParams, + }), + type: "session.configured", + payload: { + config: { + availableCommands: update.availableCommands ?? [], + }, + }, + }); + return; + } + + if (sessionUpdate === "agent_thought_chunk") { + const text = firstNonEmptyString(asObject(update.content)?.text); + if (!text) return; + emitRuntimeEvent({ + ...baseEvent(context, { + source: "cursor.acp.notification", + method: "session/update", + payload: rawParams, + }), + type: "content.delta", + payload: { + streamKind: "reasoning_text", + delta: text, + }, + }); + return; + } + + if (sessionUpdate === "agent_message_chunk") { + const text = firstNonEmptyString(asObject(update.content)?.text); + if (!text) return; + const assistantItemId = + context.turnState?.assistantItemId ?? + ProviderItemId.makeUnsafe(`cursor-assistant-${randomUUID()}`); + if (context.turnState) { + context.turnState.assistantText = `${context.turnState.assistantText}${text}`; + context.turnState.items.push({ + type: "agent_message_chunk", + text, + }); + } + emitRuntimeEvent({ + ...baseEvent( + context, + { + source: "cursor.acp.notification", + method: "session/update", + payload: rawParams, + }, + { itemId: assistantItemId }, + ), + type: "content.delta", + payload: { + streamKind: "assistant_text", + delta: text, + }, + }); + return; + } + + if (sessionUpdate === "tool_call") { + const toolCallId = asString(update.toolCallId); + if (!toolCallId) return; + const existing = context.toolsByToolCallId.get(toolCallId); + const title = firstNonEmptyString(update.title) ?? "Tool call"; + const kind = firstNonEmptyString(update.kind); + const rawInput = update.rawInput; + const detail = summarizeToolInput(rawInput, title); + const classifyInput = { + ...(kind ? { kind } : {}), + ...(title ? { title } : {}), + ...(rawInput !== undefined ? { rawInput } : {}), + }; + if (!existing) { + const tool: ToolInFlight = { + itemId: ProviderItemId.makeUnsafe(`cursor-tool-${toolCallId}`), + itemType: classifyToolItemType(classifyInput), + title, + ...(detail ? { detail } : {}), + }; + context.toolsByToolCallId.set(toolCallId, tool); + context.turnState?.items.push({ + type: "tool_call", + toolCallId, + rawInput, + }); + emitRuntimeEvent({ + ...baseEvent( + context, + { + source: "cursor.acp.notification", + method: "session/update", + payload: rawParams, + }, + { itemId: tool.itemId }, + ), + type: "item.started", + payload: { + itemType: tool.itemType, + status: "inProgress", + title: tool.title, + ...(tool.detail ? { detail: tool.detail } : {}), + data: { + toolCallId, + rawInput, + }, + }, + }); + return; + } + + existing.title = title; + if (detail !== undefined) { + existing.detail = detail; + } else { + delete existing.detail; + } + emitRuntimeEvent({ + ...baseEvent( + context, + { + source: "cursor.acp.notification", + method: "session/update", + payload: rawParams, + }, + { itemId: existing.itemId }, + ), + type: "item.updated", + payload: { + itemType: existing.itemType, + status: "inProgress", + title: existing.title, + ...(existing.detail ? { detail: existing.detail } : {}), + data: { + toolCallId, + rawInput, + }, + }, + }); + return; + } + + if (sessionUpdate === "tool_call_update") { + const toolCallId = asString(update.toolCallId); + if (!toolCallId) return; + const status = firstNonEmptyString(update.status)?.toLowerCase() ?? "in_progress"; + const updateKind = firstNonEmptyString(update.kind); + const updateTitle = firstNonEmptyString(update.title); + const classifyInput = { + ...(updateKind ? { kind: updateKind } : {}), + ...(updateTitle ? { title: updateTitle } : {}), + ...(update.rawInput !== undefined ? { rawInput: update.rawInput } : {}), + }; + const existing = + context.toolsByToolCallId.get(toolCallId) ?? + ({ + itemId: ProviderItemId.makeUnsafe(`cursor-tool-${toolCallId}`), + itemType: classifyToolItemType(classifyInput), + title: updateTitle ?? "Tool call", + } satisfies ToolInFlight); + + context.toolsByToolCallId.set(toolCallId, existing); + const detail = summarizeToolOutput(update.rawOutput) ?? existing.detail; + + if (status === "completed") { + context.toolsByToolCallId.delete(toolCallId); + context.turnState?.items.push({ + type: "tool_call_update", + toolCallId, + status, + rawOutput: update.rawOutput, + }); + const exitCode = asNumber(asObject(update.rawOutput)?.exitCode); + const lifecycleStatus = exitCode !== undefined && exitCode !== 0 ? "failed" : "completed"; + emitRuntimeEvent({ + ...baseEvent( + context, + { + source: "cursor.acp.notification", + method: "session/update", + payload: rawParams, + }, + { itemId: existing.itemId }, + ), + type: "item.completed", + payload: { + itemType: existing.itemType, + status: lifecycleStatus, + title: existing.title, + ...(detail ? { detail } : {}), + data: { + toolCallId, + rawOutput: update.rawOutput, + }, + }, + }); + return; + } + + emitRuntimeEvent({ + ...baseEvent( + context, + { + source: "cursor.acp.notification", + method: "session/update", + payload: rawParams, + }, + { itemId: existing.itemId }, + ), + type: "item.updated", + payload: { + itemType: existing.itemType, + status: "inProgress", + title: existing.title, + ...(detail ? { detail } : {}), + data: { + toolCallId, + rawOutput: update.rawOutput, + }, + }, + }); + return; + } + + emitRuntimeEvent({ + ...baseEvent(context, { + source: "cursor.acp.notification", + method: "session/update", + payload: rawParams, + }), + type: "runtime.warning", + payload: { + message: `Unhandled Cursor ACP session update: ${sessionUpdate}`, + detail: rawParams, + }, + }); + }; + + const handleServerRequest = (context: CursorSessionContext, request: JsonRpcRequestEnvelope) => { + if (request.method !== "session/request_permission") { + writeMessage(context, { + jsonrpc: "2.0", + id: request.id, + result: { + outcome: { + outcome: "selected", + optionId: "reject-once", + }, + }, + }); + emitRuntimeEvent({ + ...baseEvent(context, { + source: "cursor.acp.request", + method: request.method, + payload: request.params ?? {}, + }), + type: "runtime.warning", + payload: { + message: `Unsupported Cursor ACP server request: ${request.method}`, + detail: request.params ?? {}, + }, + }); + return; + } + + const params = asObject(request.params); + const options = asArray(params?.options) ?? []; + const optionIds = options + .map((option) => asString(asObject(option)?.optionId)) + .filter((value): value is string => value !== undefined); + const requestType = mapPermissionRequestType(params?.toolCall); + const requestId = ApprovalRequestId.makeUnsafe(randomUUID()); + + context.pendingPermissions.set(requestId, { + jsonRpcId: request.id, + requestType, + options: optionIds, + }); + + emitRuntimeEvent({ + ...baseEvent( + context, + { + source: "cursor.acp.request", + method: request.method, + payload: request.params ?? {}, + }, + { requestId }, + ), + type: "request.opened", + payload: { + requestType, + ...(firstNonEmptyString(asObject(params?.toolCall)?.title, asObject(params?.toolCall)?.kind) + ? { + detail: firstNonEmptyString( + asObject(params?.toolCall)?.title, + asObject(params?.toolCall)?.kind, + ), + } + : {}), + args: request.params ?? {}, + }, + }); + }; + + const handleNotification = ( + context: CursorSessionContext, + notification: JsonRpcNotificationEnvelope, + ) => { + if (notification.method === "session/update") { + const params = asObject(notification.params); + const update = asObject(params?.update); + if (!update) { + emitRuntimeEvent({ + ...baseEvent(context, { + source: "cursor.acp.notification", + method: notification.method, + payload: notification.params ?? {}, + }), + type: "runtime.warning", + payload: { + message: "Cursor ACP session/update is missing params.update.", + detail: notification.params ?? {}, + }, + }); + return; + } + handleSessionUpdate(context, update, notification.params ?? {}); + return; + } + + emitRuntimeEvent({ + ...baseEvent(context, { + source: "cursor.acp.notification", + method: notification.method, + payload: notification.params ?? {}, + }), + type: "runtime.warning", + payload: { + message: `Unhandled Cursor ACP notification: ${notification.method}`, + detail: notification.params ?? {}, + }, + }); + }; + + const handleResponse = (context: CursorSessionContext, response: JsonRpcResponseEnvelope) => { + const key = String(response.id); + const pending = context.pendingRequests.get(key); + if (!pending) { + return; + } + clearTimeout(pending.timeout); + context.pendingRequests.delete(key); + + if (response.error) { + pending.reject( + new Error(`${pending.method} failed: ${response.error.message ?? "Unknown JSON-RPC error"}`, { + cause: response.error, + }), + ); + return; + } + + pending.resolve(response.result); + }; + + const handleStdoutLine = (context: CursorSessionContext, line: string) => { + let parsed: unknown; + try { + parsed = JSON.parse(line); + } catch { + emitRuntimeEvent({ + ...baseEvent(context, { + source: "cursor.acp.notification", + method: "protocol/parseError", + payload: line, + }), + type: "runtime.warning", + payload: { + message: "Cursor ACP emitted invalid JSON.", + detail: line, + }, + }); + return; + } + + logNative({ + direction: "server->client", + sessionId: context.session.sessionId, + message: parsed, + }); + + const message = asObject(parsed); + if (!message) return; + const method = asString(message.method); + const id = message.id; + const hasId = typeof id === "string" || typeof id === "number"; + + if (hasId && method) { + handleServerRequest(context, { + id, + method, + params: message.params, + }); + return; + } + + if (hasId && !method) { + const responseErrorObject = asObject(message.error); + const responseErrorCode = asNumber(responseErrorObject?.code); + const responseErrorMessage = asString(responseErrorObject?.message); + const responseError = responseErrorObject + ? { + ...(responseErrorCode !== undefined ? { code: responseErrorCode } : {}), + ...(responseErrorMessage !== undefined ? { message: responseErrorMessage } : {}), + ...(responseErrorObject.data !== undefined ? { data: responseErrorObject.data } : {}), + } + : undefined; + handleResponse(context, { + id, + ...(message.result !== undefined ? { result: message.result } : {}), + ...(responseError ? { error: responseError } : {}), + }); + return; + } + + if (!hasId && method) { + handleNotification(context, { + method, + params: message.params, + }); + } + }; + + const startSession: CursorAdapterShape["startSession"] = (input) => + Effect.gen(function* () { + if (input.provider !== undefined && input.provider !== PROVIDER) { + return yield* new ProviderAdapterValidationError({ + provider: PROVIDER, + operation: "startSession", + issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`, + }); + } + + const sessionId = ProviderSessionId.makeUnsafe(`cursor-session-${randomUUID()}`); + const startedAt = new Date().toISOString(); + const cursorOptions = input.providerOptions?.cursor as { binaryPath?: string } | undefined; + const binaryPath = cursorOptions?.binaryPath ?? "agent"; + const cwd = input.cwd ?? process.cwd(); + const spawnProcess = + options?.spawnProcess ?? + ((spawnInput: { readonly binaryPath: string; readonly cwd: string }) => + spawn(spawnInput.binaryPath, ["acp"], { + cwd: spawnInput.cwd, + stdio: ["pipe", "pipe", "pipe"], + env: { + ...process.env, + NO_COLOR: "1", + }, + })); + + let context: CursorSessionContext | undefined; + + try { + const child = spawnProcess({ binaryPath, cwd }); + + const stdoutRl = readline.createInterface({ input: child.stdout }); + const stderrRl = readline.createInterface({ input: child.stderr }); + + const session: ProviderSession = { + sessionId, + provider: PROVIDER, + status: "connecting", + cwd, + ...(input.model ? { model: input.model } : {}), + resumeCursor: { + turnCount: 0, + }, + createdAt: startedAt, + updatedAt: startedAt, + }; + + context = { + session, + child, + stdoutRl, + stderrRl, + pendingRequests: new Map(), + pendingPermissions: new Map(), + toolsByToolCallId: new Map(), + turns: [], + turnState: undefined, + acpSessionId: undefined, + nextRequestId: 1, + stopping: false, + }; + sessions.set(sessionId, context); + + stdoutRl.on("line", (line) => handleStdoutLine(context!, line)); + stderrRl.on("line", (line) => { + logNative({ + direction: "stderr", + sessionId: context?.session.sessionId, + line, + }); + const message = line.trim(); + if (message.length === 0) return; + emitRuntimeEvent({ + ...baseEvent(context!, { + source: "cursor.acp.notification", + method: "process/stderr", + payload: line, + }), + type: "runtime.warning", + payload: { + message, + }, + }); + }); + + child.on("exit", (code, signal) => { + if (!context || context.stopping) { + return; + } + + const message = `Cursor ACP exited (code=${String(code)}, signal=${String(signal)}).`; + rejectPendingRequests(context, message); + completeTurn(context, "failed", { + errorMessage: message, + stopReason: "failed", + }); + emitRuntimeEvent({ + ...baseEvent(context, { + source: "cursor.acp.notification", + method: "session/exited", + payload: { code, signal }, + }), + type: "runtime.error", + payload: { + message, + class: "transport_error", + detail: { code, signal }, + }, + }); + emitRuntimeEvent({ + ...baseEvent(context, { + source: "cursor.acp.notification", + method: "session/exited", + payload: { code, signal }, + }), + type: "session.exited", + payload: { + reason: message, + recoverable: true, + exitKind: "error", + }, + }); + sessions.delete(context.session.sessionId); + }); + + const initializeResult = yield* Effect.tryPromise({ + try: () => + sendRequest(context!, "initialize", { + protocolVersion: 1, + clientCapabilities: { + fs: { readTextFile: false, writeTextFile: false }, + terminal: false, + }, + clientInfo: { + name: "t3code_cursor_adapter", + version: "0.1.0", + }, + }), + catch: (cause) => toRequestError(sessionId, "initialize", cause), + }); + + emitRuntimeEvent({ + ...baseEvent(context, { + source: "cursor.acp.response", + method: "initialize", + payload: initializeResult, + }), + type: "session.configured", + payload: { + config: asObject(initializeResult) ?? { initializeResult }, + }, + }); + + const authenticateResult = yield* Effect.tryPromise({ + try: () => + sendRequest(context!, "authenticate", { + methodId: "cursor_login", + }), + catch: (cause) => toRequestError(sessionId, "authenticate", cause), + }); + + emitRuntimeEvent({ + ...baseEvent(context, { + source: "cursor.acp.response", + method: "authenticate", + payload: authenticateResult, + }), + type: "auth.status", + payload: { + isAuthenticating: false, + }, + }); + + const resumeState = readCursorResumeState(input.resumeCursor); + const sessionResult = yield* Effect.tryPromise({ + try: () => + resumeState?.sessionId + ? sendRequest(context!, "session/load", { + sessionId: resumeState.sessionId, + cwd, + mcpServers: [], + ...(input.model ? { model: input.model } : {}), + }) + : sendRequest(context!, "session/new", { + cwd, + mcpServers: [], + ...(input.model ? { model: input.model } : {}), + }), + catch: (cause) => toRequestError(sessionId, "session/new", cause), + }); + + const acpSessionId = firstNonEmptyString(asObject(sessionResult)?.sessionId); + if (!acpSessionId) { + return yield* new ProviderAdapterProcessError({ + provider: PROVIDER, + sessionId, + detail: "Cursor ACP session/new response did not include a sessionId.", + cause: sessionResult, + }); + } + + const threadId = ProviderThreadId.makeUnsafe(acpSessionId); + context.acpSessionId = acpSessionId; + context.session = { + ...context.session, + status: "ready", + threadId, + resumeCursor: { + sessionId: acpSessionId, + turnCount: resumeState?.turnCount ?? 0, + }, + updatedAt: new Date().toISOString(), + }; + + emitRuntimeEvent({ + ...baseEvent(context, { + source: "cursor.acp.response", + method: resumeState?.sessionId ? "session/load" : "session/new", + payload: sessionResult, + }), + type: "session.started", + payload: { + ...(resumeState ? { resume: resumeState } : {}), + }, + }); + emitRuntimeEvent({ + ...baseEvent(context, { + source: "cursor.acp.response", + method: resumeState?.sessionId ? "session/load" : "session/new", + payload: sessionResult, + }), + type: "thread.started", + payload: { + providerThreadId: threadId, + }, + }); + emitRuntimeEvent({ + ...baseEvent(context, { + source: "cursor.acp.response", + method: resumeState?.sessionId ? "session/load" : "session/new", + payload: sessionResult, + }), + type: "session.state.changed", + payload: { + state: "ready", + }, + }); + + return { ...context.session }; + } catch (cause) { + if (context) { + stopSessionInternal(context, { emitExitEvent: false }); + sessions.delete(context.session.sessionId); + } + return yield* new ProviderAdapterProcessError({ + provider: PROVIDER, + sessionId, + detail: toMessage(cause, "Failed to start Cursor ACP session."), + cause, + }); + } + }); + + const sendTurn: CursorAdapterShape["sendTurn"] = (input) => + Effect.gen(function* () { + const context = yield* requireSession(input.sessionId); + if (context.turnState) { + return yield* new ProviderAdapterValidationError({ + provider: PROVIDER, + operation: "sendTurn", + issue: `Session '${input.sessionId}' already has an active turn '${context.turnState.turnId}'.`, + }); + } + if (!context.acpSessionId) { + return yield* new ProviderAdapterSessionNotFoundError({ + provider: PROVIDER, + sessionId: input.sessionId, + }); + } + + const prompt = buildPrompt(input); + if (prompt.length === 0) { + return yield* new ProviderAdapterValidationError({ + provider: PROVIDER, + operation: "sendTurn", + issue: "Turn input must include text or attachments.", + }); + } + + const turnId = ProviderTurnId.makeUnsafe(`cursor-turn-${randomUUID()}`); + const assistantItemId = ProviderItemId.makeUnsafe(`cursor-assistant-${randomUUID()}`); + context.turnState = { + turnId, + assistantItemId, + startedAt: new Date().toISOString(), + items: [], + assistantCompleted: false, + assistantText: "", + }; + context.session = { + ...context.session, + status: "running", + activeTurnId: turnId, + updatedAt: new Date().toISOString(), + }; + + emitRuntimeEvent({ + ...baseEvent( + context, + { + source: "cursor.acp.request", + method: "session/prompt", + payload: { + sessionId: context.acpSessionId, + prompt, + }, + }, + { turnId }, + ), + type: "turn.started", + payload: { + ...(firstNonEmptyString(input.model, context.session.model) + ? { model: firstNonEmptyString(input.model, context.session.model) } + : {}), + }, + }); + + const promptResult = yield* Effect.tryPromise({ + try: () => + sendRequest(context, "session/prompt", { + sessionId: context.acpSessionId, + prompt, + }), + catch: (cause) => toRequestError(input.sessionId, "session/prompt", cause), + }).pipe( + Effect.catch((error) => + Effect.gen(function* () { + const rpcError = asRpcError((error as { cause?: unknown }).cause ?? error); + const message = rpcError?.message ?? toMessage(error, "Cursor prompt failed."); + emitRuntimeEvent({ + ...baseEvent( + context, + { + source: "cursor.acp.response", + method: "session/prompt", + payload: { + ...(rpcError ? { error: rpcError } : { error }), + }, + }, + { turnId }, + ), + type: "runtime.error", + payload: { + message, + class: + rpcError?.code === -32601 + ? "validation_error" + : rpcError?.code === -32602 + ? "validation_error" + : rpcError?.code === -32603 + ? "provider_error" + : "provider_error", + ...(rpcError ? { detail: rpcError } : {}), + }, + }); + completeTurn(context, "failed", { + stopReason: "failed", + errorMessage: message, + }); + return yield* Effect.fail(error); + }), + ), + ); + + const stopReason = firstNonEmptyString(asObject(promptResult)?.stopReason) ?? "end_turn"; + const turnState = mapStopReasonToTurnState(stopReason); + completeTurn(context, turnState, { + stopReason, + ...(turnState === "failed" ? { errorMessage: "Cursor turn failed." } : {}), + }); + context.session = { + ...context.session, + resumeCursor: { + sessionId: context.acpSessionId, + turnCount: context.turns.length, + }, + updatedAt: new Date().toISOString(), + }; + + return { + ...(context.session.threadId ? { threadId: context.session.threadId } : {}), + turnId, + ...(context.session.resumeCursor ? { resumeCursor: context.session.resumeCursor } : {}), + }; + }); + + const interruptTurn: CursorAdapterShape["interruptTurn"] = (sessionId, _turnId) => + Effect.gen(function* () { + const context = yield* requireSession(sessionId); + if (!context.turnState || !context.acpSessionId) { + return; + } + const turnId = context.turnState.turnId; + + yield* Effect.tryPromise({ + try: () => + sendRequest( + context, + "session/cancel", + { + sessionId: context.acpSessionId, + }, + 15_000, + ), + catch: (cause) => toRequestError(sessionId, "session/cancel", cause), + }).pipe( + Effect.catch((error) => { + const rpcError = asRpcError((error as { cause?: unknown }).cause ?? error); + if (rpcError?.code !== -32601) { + return Effect.fail(error); + } + emitRuntimeEvent({ + ...baseEvent( + context, + { + source: "cursor.acp.response", + method: "session/cancel", + payload: { error: rpcError }, + }, + { turnId }, + ), + type: "runtime.warning", + payload: { + message: "Cursor ACP session/cancel is not supported; using interrupted fallback.", + detail: rpcError, + }, + }); + completeTurn(context, "interrupted", { + stopReason: "interrupted", + errorMessage: "Interrupted by fallback because session/cancel is unsupported.", + }); + return Effect.void; + }), + ); + }); + + const respondToRequest: CursorAdapterShape["respondToRequest"] = (sessionId, requestId, decision) => + Effect.gen(function* () { + const context = yield* requireSession(sessionId); + const pending = context.pendingPermissions.get(requestId); + if (!pending) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "session/request_permission", + detail: `Unknown pending permission request: ${requestId}`, + }); + } + + const preferredOptionId = + decision === "acceptForSession" + ? "allow-always" + : decision === "accept" + ? "allow-once" + : "reject-once"; + const selectedOptionId = + pending.options.find((candidate) => candidate === preferredOptionId) ?? + pending.options[0] ?? + preferredOptionId; + + yield* Effect.try({ + try: () => { + writeMessage(context, { + jsonrpc: "2.0", + id: pending.jsonRpcId, + result: { + outcome: { + outcome: "selected", + optionId: selectedOptionId, + }, + }, + }); + }, + catch: (cause) => toRequestError(sessionId, "session/request_permission", cause), + }); + + context.pendingPermissions.delete(requestId); + + emitRuntimeEvent({ + ...baseEvent( + context, + { + source: "cursor.acp.response", + method: "session/request_permission", + payload: { + optionId: selectedOptionId, + }, + }, + { requestId }, + ), + type: "request.resolved", + payload: { + requestType: pending.requestType, + decision, + resolution: { + optionId: selectedOptionId, + }, + }, + }); + }); + + const readThread: CursorAdapterShape["readThread"] = (sessionId) => + Effect.gen(function* () { + const context = yield* requireSession(sessionId); + const threadId = context.session.threadId; + if (!threadId) { + return yield* new ProviderAdapterValidationError({ + provider: PROVIDER, + operation: "readThread", + issue: "Session thread id is not initialized yet.", + }); + } + return { + threadId, + turns: context.turns.map((turn) => ({ + id: turn.id, + items: [...turn.items], + })), + }; + }); + + const rollbackThread: CursorAdapterShape["rollbackThread"] = (sessionId, _numTurns) => + Effect.fail( + new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "thread/rollback", + detail: `Cursor ACP does not currently support thread rollback for session '${sessionId}'.`, + }), + ); + + const stopSession: CursorAdapterShape["stopSession"] = (sessionId) => + Effect.gen(function* () { + const context = yield* requireSession(sessionId); + stopSessionInternal(context, { emitExitEvent: true }); + }); + + const listSessions: CursorAdapterShape["listSessions"] = () => + Effect.sync(() => Array.from(sessions.values(), ({ session }) => ({ ...session }))); + + const hasSession: CursorAdapterShape["hasSession"] = (sessionId) => + Effect.sync(() => { + const context = sessions.get(sessionId); + return context !== undefined && !context.stopping; + }); + + const stopAll: CursorAdapterShape["stopAll"] = () => + Effect.sync(() => { + for (const context of sessions.values()) { + stopSessionInternal(context, { emitExitEvent: true }); + } + }); + + yield* Effect.addFinalizer(() => + stopAll().pipe( + Effect.orElseSucceed(() => undefined), + Effect.tap(() => Queue.shutdown(runtimeEventQueue)), + ), + ); + + return { + provider: PROVIDER, + startSession, + sendTurn, + interruptTurn, + readThread, + rollbackThread, + respondToRequest, + stopSession, + listSessions, + hasSession, + stopAll, + streamEvents: Stream.fromQueue(runtimeEventQueue), + } satisfies CursorAdapterShape; + }); + +export const CursorAdapterLive = Layer.effect(CursorAdapter, makeCursorAdapter()); + +export function makeCursorAdapterLive(options?: CursorAdapterLiveOptions) { + return Layer.effect(CursorAdapter, makeCursorAdapter(options)); +} diff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts index edd2a5c18a..75ed7576cb 100644 --- a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts @@ -6,6 +6,7 @@ import { Effect, Layer, Stream } from "effect"; import { ClaudeCodeAdapter, ClaudeCodeAdapterShape } from "../Services/ClaudeCodeAdapter.ts"; import { CodexAdapter, CodexAdapterShape } from "../Services/CodexAdapter.ts"; +import { CursorAdapter, CursorAdapterShape } from "../Services/CursorAdapter.ts"; import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts"; import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts"; import { ProviderUnsupportedError } from "../Errors.ts"; @@ -41,6 +42,21 @@ const fakeClaudeAdapter: ClaudeCodeAdapterShape = { streamEvents: Stream.empty, }; +const fakeCursorAdapter: CursorAdapterShape = { + provider: "cursor", + startSession: vi.fn(), + sendTurn: vi.fn(), + interruptTurn: vi.fn(), + respondToRequest: vi.fn(), + stopSession: vi.fn(), + listSessions: vi.fn(), + hasSession: vi.fn(), + readThread: vi.fn(), + rollbackThread: vi.fn(), + stopAll: vi.fn(), + streamEvents: Stream.empty, +}; + const layer = it.layer( Layer.mergeAll( Layer.provide( @@ -48,6 +64,7 @@ const layer = it.layer( Layer.mergeAll( Layer.succeed(CodexAdapter, fakeCodexAdapter), Layer.succeed(ClaudeCodeAdapter, fakeClaudeAdapter), + Layer.succeed(CursorAdapter, fakeCursorAdapter), ), ), NodeServices.layer, @@ -60,11 +77,13 @@ layer("ProviderAdapterRegistryLive", (it) => { const registry = yield* ProviderAdapterRegistry; const codex = yield* registry.getByProvider("codex"); const claude = yield* registry.getByProvider("claudeCode"); + const cursor = yield* registry.getByProvider("cursor"); assert.equal(codex, fakeCodexAdapter); assert.equal(claude, fakeClaudeAdapter); + assert.equal(cursor, fakeCursorAdapter); const providers = yield* registry.listProviders(); - assert.deepEqual(providers, ["codex", "claudeCode"]); + assert.deepEqual(providers, ["codex", "claudeCode", "cursor"]); }), ); diff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts index 37c4309518..37b2e40d12 100644 --- a/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts +++ b/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts @@ -17,6 +17,7 @@ import { } from "../Services/ProviderAdapterRegistry.ts"; import { ClaudeCodeAdapter } from "../Services/ClaudeCodeAdapter.ts"; import { CodexAdapter } from "../Services/CodexAdapter.ts"; +import { CursorAdapter } from "../Services/CursorAdapter.ts"; export interface ProviderAdapterRegistryLiveOptions { readonly adapters?: ReadonlyArray>; @@ -27,7 +28,7 @@ const makeProviderAdapterRegistry = (options?: ProviderAdapterRegistryLiveOption const adapters = options?.adapters !== undefined ? options.adapters - : [yield* CodexAdapter, yield* ClaudeCodeAdapter]; + : [yield* CodexAdapter, yield* ClaudeCodeAdapter, yield* CursorAdapter]; const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter])); const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => { diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index ffe8acf5f7..1cbe1b5165 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -385,7 +385,6 @@ it.effect( { provider: "codex", cwd: "/tmp/project", - resumeThreadId: startedSession.threadId, resumeCursor: startedSession.resumeCursor, }, ], @@ -495,7 +494,6 @@ routing.layer("ProviderServiceLive routing", (it) => { { provider: "codex", cwd: "/tmp/project", - resumeThreadId: initial.threadId, resumeCursor: initial.resumeCursor, }, ], @@ -530,7 +528,6 @@ routing.layer("ProviderServiceLive routing", (it) => { { provider: "codex", cwd: "/tmp/project-send-turn", - resumeThreadId: initial.threadId, resumeCursor: initial.resumeCursor, }, ], @@ -631,7 +628,9 @@ fanout.layer("ProviderServiceLive fanout", (it) => { createdAt: new Date().toISOString(), threadId: asProviderThreadId("thread-1"), turnId: asTurnId("turn-1"), - status: "completed", + payload: { + state: "completed", + }, }; fanout.codex.emit(completedEvent); @@ -662,26 +661,30 @@ fanout.layer("ProviderServiceLive fanout", (it) => { yield* sleep(20); fanout.codex.emit({ - type: "tool.started", + type: "item.started", eventId: asEventId("evt-seq-1"), provider: "codex", sessionId: session.sessionId, createdAt: new Date().toISOString(), threadId: asProviderThreadId("thread-1"), turnId: asTurnId("turn-1"), - toolKind: "command", - title: "Command run", + payload: { + itemType: "command_execution", + title: "Command run", + }, }); fanout.codex.emit({ - type: "tool.completed", + type: "item.completed", eventId: asEventId("evt-seq-2"), provider: "codex", sessionId: session.sessionId, createdAt: new Date().toISOString(), threadId: asProviderThreadId("thread-1"), turnId: asTurnId("turn-1"), - toolKind: "command", - title: "Command run", + payload: { + itemType: "command_execution", + title: "Command run", + }, }); fanout.codex.emit({ type: "turn.completed", @@ -691,7 +694,9 @@ fanout.layer("ProviderServiceLive fanout", (it) => { createdAt: new Date().toISOString(), threadId: asProviderThreadId("thread-1"), turnId: asTurnId("turn-1"), - status: "completed", + payload: { + state: "completed", + }, }); yield* Fiber.join(consumer); @@ -728,26 +733,31 @@ fanout.layer("ProviderServiceLive fanout", (it) => { const events: ReadonlyArray = [ { - type: "tool.completed", + type: "item.completed", eventId: asEventId("evt-ordered-1"), provider: "codex", sessionId: session.sessionId, createdAt: new Date().toISOString(), threadId: asProviderThreadId("thread-1"), turnId: asTurnId("turn-1"), - toolKind: "command", - title: "Command run", - detail: "echo one", + payload: { + itemType: "command_execution", + title: "Command run", + detail: "echo one", + }, }, { - type: "message.delta", + type: "content.delta", eventId: asEventId("evt-ordered-2"), provider: "codex", sessionId: session.sessionId, createdAt: new Date().toISOString(), threadId: asProviderThreadId("thread-1"), turnId: asTurnId("turn-1"), - delta: "hello", + payload: { + streamKind: "assistant_text", + delta: "hello", + }, }, { type: "turn.completed", @@ -757,7 +767,9 @@ fanout.layer("ProviderServiceLive fanout", (it) => { createdAt: new Date().toISOString(), threadId: asProviderThreadId("thread-1"), turnId: asTurnId("turn-1"), - status: "completed", + payload: { + state: "completed", + }, }, ]; diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index 7a7c7594da..ef57d4a9cb 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -303,7 +303,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) => const resumed = yield* adapter.startSession({ provider: input.binding.provider, ...(persistedCwd ? { cwd: persistedCwd } : {}), - ...(resumeThreadId ? { resumeThreadId } : {}), ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}), }); if (resumed.provider !== adapter.provider) { diff --git a/apps/server/src/provider/Services/CursorAdapter.test.ts b/apps/server/src/provider/Services/CursorAdapter.test.ts index 1284d0970f..df9753c455 100644 --- a/apps/server/src/provider/Services/CursorAdapter.test.ts +++ b/apps/server/src/provider/Services/CursorAdapter.test.ts @@ -1,131 +1,102 @@ import { Schema } from "effect"; import { describe, expect, it } from "vitest"; -import { CursorCliStreamEvent } from "./CursorAdapter.ts"; +import { + CursorAcpPermissionRequest, + CursorAcpResponseEnvelope, + CursorAcpSessionUpdate, + CursorAcpSessionUpdateNotification, +} from "./CursorAdapter.ts"; -describe("CursorCliStreamEvent", () => { - it("decodes system/init events", () => { - const decoded = Schema.decodeUnknownSync(CursorCliStreamEvent)({ - type: "system", - subtype: "init", - session_id: "sess-1", - apiKeySource: "login", - cwd: "/tmp/project", - model: "Auto", - permissionMode: "default", - }); - - expect(decoded.type).toBe("system"); - if (decoded.type !== "system") { - return; - } - expect(decoded.subtype).toBe("init"); - expect(decoded.session_id).toBe("sess-1"); - }); - - it("decodes thinking delta/completed events", () => { - const delta = Schema.decodeUnknownSync(CursorCliStreamEvent)({ - type: "thinking", - subtype: "delta", - text: "draft", - session_id: "sess-1", - timestamp_ms: 123, - }); - - expect(delta.type).toBe("thinking"); - if (delta.type !== "thinking") { - return; - } - expect(delta.subtype).toBe("delta"); - - const completed = Schema.decodeUnknownSync(CursorCliStreamEvent)({ - type: "thinking", - subtype: "completed", - session_id: "sess-1", - }); - - expect(completed.type).toBe("thinking"); - if (completed.type !== "thinking") { - return; - } - expect(completed.subtype).toBe("completed"); - }); - - it("decodes tool_call completed events with rejected results", () => { - const decoded = Schema.decodeUnknownSync(CursorCliStreamEvent)({ - type: "tool_call", - subtype: "completed", - call_id: "tool-1\nline-2", - session_id: "sess-1", - tool_call: { - shellToolCall: { - args: { - command: "rm -rf /tmp/nope", - }, - result: { - rejected: { - reason: "approval denied", - }, +describe("Cursor ACP schemas", () => { + it("decodes session/update thought chunk notifications", () => { + const decoded = Schema.decodeUnknownSync(CursorAcpSessionUpdateNotification)({ + jsonrpc: "2.0", + method: "session/update", + params: { + sessionId: "sess-1", + update: { + sessionUpdate: "agent_thought_chunk", + content: { + type: "text", + text: "thinking...", }, }, }, }); - expect(decoded.type).toBe("tool_call"); - if (decoded.type !== "tool_call") { - return; - } - expect(decoded.subtype).toBe("completed"); - expect(decoded.call_id).toContain("\n"); + expect(decoded.method).toBe("session/update"); + expect(decoded.params.update.sessionUpdate).toBe("agent_thought_chunk"); }); - it("decodes result success events with usage payload", () => { - const decoded = Schema.decodeUnknownSync(CursorCliStreamEvent)({ - type: "result", - subtype: "success", - duration_ms: 100, - duration_api_ms: 90, - is_error: false, - result: "OK", - session_id: "sess-1", - request_id: "req-1", - usage: { - inputTokens: 10, - outputTokens: 5, - cacheReadTokens: 2, - cacheWriteTokens: 1, + it("decodes tool_call_update completion payloads", () => { + const decoded = Schema.decodeUnknownSync(CursorAcpSessionUpdate)({ + sessionUpdate: "tool_call_update", + toolCallId: "tool-1", + status: "completed", + title: "Terminal", + rawOutput: { + exitCode: 0, + stdout: "/workspace\n", }, }); - expect(decoded.type).toBe("result"); - if (decoded.type !== "result") { + expect(decoded.sessionUpdate).toBe("tool_call_update"); + if (decoded.sessionUpdate !== "tool_call_update") { return; } - expect(decoded.subtype).toBe("success"); - expect(decoded.is_error).toBe(false); + expect(decoded.toolCallId).toBe("tool-1"); + expect(decoded.status).toBe("completed"); }); - it("decodes connection/retry lifecycle events", () => { - const reconnecting = Schema.decodeUnknownSync(CursorCliStreamEvent)({ - type: "connection", - subtype: "reconnecting", - session_id: "sess-1", + it("decodes permission requests with options", () => { + const decoded = Schema.decodeUnknownSync(CursorAcpPermissionRequest)({ + jsonrpc: "2.0", + id: 7, + method: "session/request_permission", + params: { + sessionId: "sess-1", + toolCall: { + kind: "execute", + command: "pwd", + }, + options: [ + { optionId: "allow-once", title: "Allow once" }, + { optionId: "allow-always", title: "Always allow" }, + { optionId: "reject-once", title: "Reject" }, + ], + }, }); - expect(reconnecting.type).toBe("connection"); - const retry = Schema.decodeUnknownSync(CursorCliStreamEvent)({ - type: "retry", - subtype: "resuming", - session_id: "sess-1", - }); - expect(retry.type).toBe("retry"); + expect(decoded.method).toBe("session/request_permission"); + expect(decoded.params.options).toHaveLength(3); }); - it("rejects unsupported stream event types", () => { + it("decodes json-rpc response envelopes", () => { + const success = Schema.decodeUnknownSync(CursorAcpResponseEnvelope)({ + jsonrpc: "2.0", + id: 1, + result: { stopReason: "end_turn" }, + }); + expect(success.id).toBe(1); + expect(success.result).toEqual({ stopReason: "end_turn" }); + + const error = Schema.decodeUnknownSync(CursorAcpResponseEnvelope)({ + jsonrpc: "2.0", + id: "2", + error: { + code: -32601, + message: "Method not found", + }, + }); + expect(error.id).toBe("2"); + expect(error.error?.code).toBe(-32601); + }); + + it("rejects unsupported session update kinds", () => { expect(() => - Schema.decodeUnknownSync(CursorCliStreamEvent)({ - type: "bogus", - session_id: "sess-1", + Schema.decodeUnknownSync(CursorAcpSessionUpdate)({ + sessionUpdate: "unknown_update_type", }), ).toThrow(); }); diff --git a/apps/server/src/provider/Services/CursorAdapter.ts b/apps/server/src/provider/Services/CursorAdapter.ts index c7ee46d46a..42c00f4fb2 100644 --- a/apps/server/src/provider/Services/CursorAdapter.ts +++ b/apps/server/src/provider/Services/CursorAdapter.ts @@ -1,11 +1,11 @@ /** - * CursorAdapter - Cursor CLI implementation of the generic provider adapter contract. + * CursorAdapter - Cursor ACP implementation of the generic provider adapter contract. * - * This service will own Cursor CLI (`agent`) process / stream-json semantics and emit + * This service owns Cursor ACP (`agent acp`) JSON-RPC stream semantics and emits * canonical provider runtime events via the shared provider adapter contract. * - * This file intentionally defines raw Cursor stream-json schemas up front so the future - * layer implementation can decode/validate NDJSON lines in a single place. + * This file defines ACP transport envelopes and high-signal payload schemas used by + * the live layer implementation for safe boundary decoding. * * @module CursorAdapter */ @@ -14,186 +14,140 @@ import { Schema, ServiceMap } from "effect"; import type { ProviderAdapterError } from "../Errors.ts"; import type { ProviderAdapterShape } from "./ProviderAdapter.ts"; -export const CursorCliSessionId = Schema.String.check(Schema.isNonEmpty()); -export type CursorCliSessionId = typeof CursorCliSessionId.Type; +export const CursorAcpJsonRpcId = Schema.Union([Schema.String, Schema.Number]); +export type CursorAcpJsonRpcId = typeof CursorAcpJsonRpcId.Type; -export const CursorCliTextContentPart = Schema.Struct({ +export const CursorAcpError = Schema.Struct({ + code: Schema.Number, + message: Schema.String, + data: Schema.optional(Schema.Unknown), +}); +export type CursorAcpError = typeof CursorAcpError.Type; + +export const CursorAcpResponseEnvelope = Schema.Struct({ + jsonrpc: Schema.Literal("2.0"), + id: CursorAcpJsonRpcId, + result: Schema.optional(Schema.Unknown), + error: Schema.optional(CursorAcpError), +}); +export type CursorAcpResponseEnvelope = typeof CursorAcpResponseEnvelope.Type; + +export const CursorAcpRequestEnvelope = Schema.Struct({ + jsonrpc: Schema.Literal("2.0"), + id: CursorAcpJsonRpcId, + method: Schema.String, + params: Schema.optional(Schema.Unknown), +}); +export type CursorAcpRequestEnvelope = typeof CursorAcpRequestEnvelope.Type; + +export const CursorAcpNotificationEnvelope = Schema.Struct({ + jsonrpc: Schema.Literal("2.0"), + method: Schema.String, + params: Schema.optional(Schema.Unknown), +}); +export type CursorAcpNotificationEnvelope = typeof CursorAcpNotificationEnvelope.Type; + +export const CursorAcpInitializeResult = Schema.Struct({ + protocolVersion: Schema.Unknown, + agentCapabilities: Schema.optional(Schema.Unknown), + authMethods: Schema.optional(Schema.Array(Schema.Unknown)), +}); +export type CursorAcpInitializeResult = typeof CursorAcpInitializeResult.Type; + +export const CursorAcpSessionResult = Schema.Struct({ + sessionId: Schema.String.check(Schema.isNonEmpty()), + modes: Schema.optional(Schema.Array(Schema.String)), +}); +export type CursorAcpSessionResult = typeof CursorAcpSessionResult.Type; + +export const CursorAcpPromptResult = Schema.Struct({ + stopReason: Schema.String, +}); +export type CursorAcpPromptResult = typeof CursorAcpPromptResult.Type; + +export const CursorAcpTextContent = Schema.Struct({ type: Schema.Literal("text"), text: Schema.String, }); -export type CursorCliTextContentPart = typeof CursorCliTextContentPart.Type; +export type CursorAcpTextContent = typeof CursorAcpTextContent.Type; -export const CursorCliContentPart = Schema.Union([ - CursorCliTextContentPart, - Schema.Struct({ - type: Schema.String, +export const CursorAcpSessionUpdateAvailableCommands = Schema.Struct({ + sessionUpdate: Schema.Literal("available_commands_update"), + availableCommands: Schema.optional(Schema.Array(Schema.Unknown)), +}); +export type CursorAcpSessionUpdateAvailableCommands = + typeof CursorAcpSessionUpdateAvailableCommands.Type; + +export const CursorAcpSessionUpdateThoughtChunk = Schema.Struct({ + sessionUpdate: Schema.Literal("agent_thought_chunk"), + content: Schema.optional(CursorAcpTextContent), +}); +export type CursorAcpSessionUpdateThoughtChunk = typeof CursorAcpSessionUpdateThoughtChunk.Type; + +export const CursorAcpSessionUpdateMessageChunk = Schema.Struct({ + sessionUpdate: Schema.Literal("agent_message_chunk"), + content: Schema.optional(CursorAcpTextContent), +}); +export type CursorAcpSessionUpdateMessageChunk = typeof CursorAcpSessionUpdateMessageChunk.Type; + +export const CursorAcpSessionUpdateToolCall = Schema.Struct({ + sessionUpdate: Schema.Literal("tool_call"), + toolCallId: Schema.String, + title: Schema.optional(Schema.String), + kind: Schema.optional(Schema.String), + rawInput: Schema.optional(Schema.Unknown), +}); +export type CursorAcpSessionUpdateToolCall = typeof CursorAcpSessionUpdateToolCall.Type; + +export const CursorAcpSessionUpdateToolCallUpdate = Schema.Struct({ + sessionUpdate: Schema.Literal("tool_call_update"), + toolCallId: Schema.String, + status: Schema.String, + title: Schema.optional(Schema.String), + kind: Schema.optional(Schema.String), + rawInput: Schema.optional(Schema.Unknown), + rawOutput: Schema.optional(Schema.Unknown), +}); +export type CursorAcpSessionUpdateToolCallUpdate = + typeof CursorAcpSessionUpdateToolCallUpdate.Type; + +export const CursorAcpSessionUpdate = Schema.Union([ + CursorAcpSessionUpdateAvailableCommands, + CursorAcpSessionUpdateThoughtChunk, + CursorAcpSessionUpdateMessageChunk, + CursorAcpSessionUpdateToolCall, + CursorAcpSessionUpdateToolCallUpdate, +]); +export type CursorAcpSessionUpdate = typeof CursorAcpSessionUpdate.Type; + +export const CursorAcpSessionUpdateNotification = Schema.Struct({ + jsonrpc: Schema.Literal("2.0"), + method: Schema.Literal("session/update"), + params: Schema.Struct({ + sessionId: Schema.String, + update: CursorAcpSessionUpdate, }), -]); -export type CursorCliContentPart = typeof CursorCliContentPart.Type; - -export const CursorCliUserMessage = Schema.Struct({ - role: Schema.Literal("user"), - content: Schema.Array(CursorCliContentPart), }); -export type CursorCliUserMessage = typeof CursorCliUserMessage.Type; +export type CursorAcpSessionUpdateNotification = typeof CursorAcpSessionUpdateNotification.Type; -export const CursorCliAssistantMessage = Schema.Struct({ - role: Schema.Literal("assistant"), - content: Schema.Array(CursorCliContentPart), +export const CursorAcpPermissionOption = Schema.Struct({ + optionId: Schema.String, + title: Schema.optional(Schema.String), + detail: Schema.optional(Schema.String), }); -export type CursorCliAssistantMessage = typeof CursorCliAssistantMessage.Type; +export type CursorAcpPermissionOption = typeof CursorAcpPermissionOption.Type; -export const CursorCliToolCallResult = Schema.Struct({ - success: Schema.optional(Schema.Unknown), - failure: Schema.optional(Schema.Unknown), - rejected: Schema.optional(Schema.Unknown), +export const CursorAcpPermissionRequest = Schema.Struct({ + jsonrpc: Schema.Literal("2.0"), + id: CursorAcpJsonRpcId, + method: Schema.Literal("session/request_permission"), + params: Schema.Struct({ + sessionId: Schema.String, + toolCall: Schema.optional(Schema.Unknown), + options: Schema.Array(CursorAcpPermissionOption), + }), }); -export type CursorCliToolCallResult = typeof CursorCliToolCallResult.Type; - -export const CursorCliToolCallEntry = Schema.Struct({ - args: Schema.optional(Schema.Unknown), - result: Schema.optional(CursorCliToolCallResult), -}); -export type CursorCliToolCallEntry = typeof CursorCliToolCallEntry.Type; - -export const CursorCliFunctionToolCall = Schema.Struct({ - name: Schema.String, - arguments: Schema.String, - result: Schema.optional(CursorCliToolCallResult), -}); -export type CursorCliFunctionToolCall = typeof CursorCliFunctionToolCall.Type; - -export const CursorCliToolCallPayload = Schema.Struct({ - readToolCall: Schema.optional(CursorCliToolCallEntry), - writeToolCall: Schema.optional(CursorCliToolCallEntry), - editToolCall: Schema.optional(CursorCliToolCallEntry), - shellToolCall: Schema.optional(CursorCliToolCallEntry), - grepToolCall: Schema.optional(CursorCliToolCallEntry), - globToolCall: Schema.optional(CursorCliToolCallEntry), - function: Schema.optional(CursorCliFunctionToolCall), -}); -export type CursorCliToolCallPayload = typeof CursorCliToolCallPayload.Type; - -export const CursorCliTokenUsage = Schema.Struct({ - inputTokens: Schema.optional(Schema.Number), - outputTokens: Schema.optional(Schema.Number), - cacheReadTokens: Schema.optional(Schema.Number), - cacheWriteTokens: Schema.optional(Schema.Number), -}); -export type CursorCliTokenUsage = typeof CursorCliTokenUsage.Type; - -const CursorCliTimestampMs = { - timestamp_ms: Schema.optional(Schema.Number), -} as const; - -export const CursorCliSystemInitEvent = Schema.Struct({ - type: Schema.Literal("system"), - subtype: Schema.Literal("init"), - session_id: CursorCliSessionId, - apiKeySource: Schema.optional(Schema.String), - cwd: Schema.optional(Schema.String), - model: Schema.optional(Schema.String), - permissionMode: Schema.optional(Schema.String), - ...CursorCliTimestampMs, -}); -export type CursorCliSystemInitEvent = typeof CursorCliSystemInitEvent.Type; - -export const CursorCliUserEvent = Schema.Struct({ - type: Schema.Literal("user"), - message: CursorCliUserMessage, - session_id: CursorCliSessionId, - ...CursorCliTimestampMs, -}); -export type CursorCliUserEvent = typeof CursorCliUserEvent.Type; - -export const CursorCliAssistantEvent = Schema.Struct({ - type: Schema.Literal("assistant"), - message: CursorCliAssistantMessage, - session_id: CursorCliSessionId, - ...CursorCliTimestampMs, -}); -export type CursorCliAssistantEvent = typeof CursorCliAssistantEvent.Type; - -export const CursorCliThinkingDeltaEvent = Schema.Struct({ - type: Schema.Literal("thinking"), - subtype: Schema.Literal("delta"), - text: Schema.String, - session_id: CursorCliSessionId, - ...CursorCliTimestampMs, -}); -export type CursorCliThinkingDeltaEvent = typeof CursorCliThinkingDeltaEvent.Type; - -export const CursorCliThinkingCompletedEvent = Schema.Struct({ - type: Schema.Literal("thinking"), - subtype: Schema.Literal("completed"), - session_id: CursorCliSessionId, - ...CursorCliTimestampMs, -}); -export type CursorCliThinkingCompletedEvent = typeof CursorCliThinkingCompletedEvent.Type; - -export const CursorCliToolCallStartedEvent = Schema.Struct({ - type: Schema.Literal("tool_call"), - subtype: Schema.Literal("started"), - call_id: Schema.String, - tool_call: CursorCliToolCallPayload, - session_id: CursorCliSessionId, - ...CursorCliTimestampMs, -}); -export type CursorCliToolCallStartedEvent = typeof CursorCliToolCallStartedEvent.Type; - -export const CursorCliToolCallCompletedEvent = Schema.Struct({ - type: Schema.Literal("tool_call"), - subtype: Schema.Literal("completed"), - call_id: Schema.String, - tool_call: CursorCliToolCallPayload, - session_id: CursorCliSessionId, - ...CursorCliTimestampMs, -}); -export type CursorCliToolCallCompletedEvent = typeof CursorCliToolCallCompletedEvent.Type; - -export const CursorCliResultSuccessEvent = Schema.Struct({ - type: Schema.Literal("result"), - subtype: Schema.Literal("success"), - duration_ms: Schema.Number, - duration_api_ms: Schema.optional(Schema.Number), - is_error: Schema.Boolean, - result: Schema.String, - session_id: CursorCliSessionId, - request_id: Schema.optional(Schema.String), - usage: Schema.optional(CursorCliTokenUsage), - ...CursorCliTimestampMs, -}); -export type CursorCliResultSuccessEvent = typeof CursorCliResultSuccessEvent.Type; - -export const CursorCliConnectionEvent = Schema.Struct({ - type: Schema.Literal("connection"), - subtype: Schema.Literals(["reconnecting", "reconnected"]), - session_id: Schema.optional(CursorCliSessionId), - ...CursorCliTimestampMs, -}); -export type CursorCliConnectionEvent = typeof CursorCliConnectionEvent.Type; - -export const CursorCliRetryEvent = Schema.Struct({ - type: Schema.Literal("retry"), - subtype: Schema.Literals(["starting", "resuming"]), - session_id: Schema.optional(CursorCliSessionId), - ...CursorCliTimestampMs, -}); -export type CursorCliRetryEvent = typeof CursorCliRetryEvent.Type; - -export const CursorCliStreamEvent = Schema.Union([ - CursorCliSystemInitEvent, - CursorCliUserEvent, - CursorCliAssistantEvent, - CursorCliThinkingDeltaEvent, - CursorCliThinkingCompletedEvent, - CursorCliToolCallStartedEvent, - CursorCliToolCallCompletedEvent, - CursorCliResultSuccessEvent, - CursorCliConnectionEvent, - CursorCliRetryEvent, -]); -export type CursorCliStreamEvent = typeof CursorCliStreamEvent.Type; +export type CursorAcpPermissionRequest = typeof CursorAcpPermissionRequest.Type; /** * CursorAdapterShape - Service API for the Cursor provider adapter. diff --git a/apps/server/src/serverLayers.ts b/apps/server/src/serverLayers.ts index fc0ebb35ef..6c3ad1f711 100644 --- a/apps/server/src/serverLayers.ts +++ b/apps/server/src/serverLayers.ts @@ -20,6 +20,7 @@ import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRun import { ProviderUnsupportedError } from "./provider/Errors"; import { makeClaudeCodeAdapterLive } from "./provider/Layers/ClaudeCodeAdapter"; import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter"; +import { makeCursorAdapterLive } from "./provider/Layers/CursorAdapter"; import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry"; import { makeProviderServiceLive } from "./provider/Layers/ProviderService"; import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory"; @@ -49,8 +50,11 @@ export function makeServerProviderLayer(): Layer.Layer< const claudeAdapterLayer = makeClaudeCodeAdapterLive({ nativeEventLogPath: path.join(providerLogsDir, "provider-native.ndjson"), }); + const cursorAdapterLayer = makeCursorAdapterLive({ + nativeEventLogPath: path.join(providerLogsDir, "provider-native.ndjson"), + }); const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe( - Layer.provide(Layer.mergeAll(codexAdapterLayer, claudeAdapterLayer)), + Layer.provide(Layer.mergeAll(codexAdapterLayer, claudeAdapterLayer, cursorAdapterLayer)), ); const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe( Layer.provide(ProviderSessionRuntimeRepositoryLive), diff --git a/apps/server/src/wsServer.test.ts b/apps/server/src/wsServer.test.ts index f475dde9d1..fcf8cf0d6b 100644 --- a/apps/server/src/wsServer.test.ts +++ b/apps/server/src/wsServer.test.ts @@ -1089,8 +1089,8 @@ describe("WebSocket Server", () => { it("keeps orchestration domain push behavior for provider runtime events", async () => { const runtimeEventPubSub = Effect.runSync(PubSub.unbounded()); const sessionId = asProviderSessionId("sess-test"); - const emitRuntimeEvent = (event: ProviderRuntimeEvent) => { - Effect.runSync(PubSub.publish(runtimeEventPubSub, event)); + const emitRuntimeEvent = (event: ProviderRuntimeEvent | Record) => { + Effect.runSync(PubSub.publish(runtimeEventPubSub, event as ProviderRuntimeEvent)); }; const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never; const providerService: ProviderServiceShape = { diff --git a/packages/contracts/src/provider.ts b/packages/contracts/src/provider.ts index 3307ad4dc0..e763e101ae 100644 --- a/packages/contracts/src/provider.ts +++ b/packages/contracts/src/provider.ts @@ -62,9 +62,15 @@ export const ClaudeCodeProviderStartOptions = Schema.Struct({ }); export type ClaudeCodeProviderStartOptions = typeof ClaudeCodeProviderStartOptions.Type; +export const CursorProviderStartOptions = Schema.Struct({ + binaryPath: Schema.optional(TrimmedNonEmptyStringSchema), +}); +export type CursorProviderStartOptions = typeof CursorProviderStartOptions.Type; + export const ProviderStartOptions = Schema.Struct({ codex: Schema.optional(CodexProviderStartOptions), claudeCode: Schema.optional(ClaudeCodeProviderStartOptions), + cursor: Schema.optional(CursorProviderStartOptions), }); export type ProviderStartOptions = typeof ProviderStartOptions.Type; diff --git a/packages/contracts/src/providerRuntime.test.ts b/packages/contracts/src/providerRuntime.test.ts index b5c1821974..1d87301ee1 100644 --- a/packages/contracts/src/providerRuntime.test.ts +++ b/packages/contracts/src/providerRuntime.test.ts @@ -3,7 +3,7 @@ import { Schema } from "effect"; import { ProviderRuntimeEvent } from "./providerRuntime"; -const decodeRuntimeEvent = Schema.decodeUnknownSync(ProviderRuntimeEvent); +const decodeRuntimeEvent = Schema.decodeUnknownSync(ProviderRuntimeEvent as any); describe("ProviderRuntimeEvent", () => { it("decodes turn.plan.updated for plan rendering", () => { diff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.ts index ebe5b21bd8..c7ad0b9d65 100644 --- a/packages/contracts/src/providerRuntime.ts +++ b/packages/contracts/src/providerRuntime.ts @@ -1,17 +1,15 @@ import { Schema } from "effect"; import { + ApprovalRequestId, EventId, IsoDateTime, + NonNegativeInt, ProviderItemId, ProviderSessionId, ProviderThreadId, ProviderTurnId, - RuntimeItemId, - RuntimeRequestId, - RuntimeSessionId, - ThreadId, + RuntimeTaskId, TrimmedNonEmptyString, - TurnId, } from "./baseSchemas"; import { ProviderKind } from "./orchestration"; @@ -25,6 +23,9 @@ export const RuntimeEventRawSource = Schema.Literals([ "claude.sdk.message", "claude.sdk.permission", "codex.sdk.thread-event", + "cursor.acp.notification", + "cursor.acp.request", + "cursor.acp.response", ]); export type RuntimeEventRawSource = typeof RuntimeEventRawSource.Type; @@ -56,6 +57,26 @@ export const RuntimeTurnState = Schema.Literals([ ]); export type RuntimeTurnState = typeof RuntimeTurnState.Type; +export const RuntimeSessionState = Schema.Literals([ + "starting", + "ready", + "running", + "waiting", + "stopped", + "error", +]); +export type RuntimeSessionState = typeof RuntimeSessionState.Type; + +export const RuntimeThreadState = Schema.Literals([ + "active", + "idle", + "archived", + "closed", + "compacted", + "error", +]); +export type RuntimeThreadState = typeof RuntimeThreadState.Type; + export const RuntimePlanStepStatus = Schema.Literals(["pending", "inProgress", "completed"]); export type RuntimePlanStepStatus = typeof RuntimePlanStepStatus.Type; @@ -94,6 +115,12 @@ export const CanonicalItemType = Schema.Literals([ "file_change", "mcp_tool_call", "dynamic_tool_call", + "collab_agent_tool_call", + "web_search", + "image_view", + "review_entered", + "review_exited", + "context_compaction", "error", "unknown", ]); @@ -106,17 +133,30 @@ export const CanonicalRequestType = Schema.Literals([ "exec_command_approval", "tool_user_input", "dynamic_tool_call", + "auth_tokens_refresh", "unknown", ]); export type CanonicalRequestType = typeof CanonicalRequestType.Type; export const ProviderRuntimeEventType = Schema.Literals([ "session.started", + "session.configured", + "session.state.changed", "session.exited", "thread.started", + "thread.state.changed", + "thread.metadata.updated", + "thread.token-usage.updated", + "thread.realtime.started", + "thread.realtime.item-added", + "thread.realtime.audio.delta", + "thread.realtime.error", + "thread.realtime.closed", "turn.started", "turn.completed", + "turn.aborted", "turn.plan.updated", + "turn.diff.updated", "item.started", "item.updated", "item.completed", @@ -125,17 +165,46 @@ export const ProviderRuntimeEventType = Schema.Literals([ "request.resolved", "user-input.requested", "user-input.resolved", + "task.started", + "task.progress", + "task.completed", + "hook.started", + "hook.progress", + "hook.completed", + "tool.progress", + "tool.summary", + "auth.status", + "account.updated", + "account.rate-limits.updated", + "mcp.status.updated", + "mcp.oauth.completed", + "model.rerouted", + "config.warning", + "deprecation.notice", + "files.persisted", "runtime.warning", "runtime.error", ]); export type ProviderRuntimeEventType = typeof ProviderRuntimeEventType.Type; export const SessionStartedType = Schema.Literal("session.started"); +export const SessionConfiguredType = Schema.Literal("session.configured"); +export const SessionStateChangedType = Schema.Literal("session.state.changed"); export const SessionExitedType = Schema.Literal("session.exited"); export const ThreadStartedType = Schema.Literal("thread.started"); +export const ThreadStateChangedType = Schema.Literal("thread.state.changed"); +export const ThreadMetadataUpdatedType = Schema.Literal("thread.metadata.updated"); +export const ThreadTokenUsageUpdatedType = Schema.Literal("thread.token-usage.updated"); +export const ThreadRealtimeStartedType = Schema.Literal("thread.realtime.started"); +export const ThreadRealtimeItemAddedType = Schema.Literal("thread.realtime.item-added"); +export const ThreadRealtimeAudioDeltaType = Schema.Literal("thread.realtime.audio.delta"); +export const ThreadRealtimeErrorType = Schema.Literal("thread.realtime.error"); +export const ThreadRealtimeClosedType = Schema.Literal("thread.realtime.closed"); export const TurnStartedType = Schema.Literal("turn.started"); export const TurnCompletedType = Schema.Literal("turn.completed"); +export const TurnAbortedType = Schema.Literal("turn.aborted"); export const TurnPlanUpdatedType = Schema.Literal("turn.plan.updated"); +export const TurnDiffUpdatedType = Schema.Literal("turn.diff.updated"); export const ItemStartedType = Schema.Literal("item.started"); export const ItemUpdatedType = Schema.Literal("item.updated"); export const ItemCompletedType = Schema.Literal("item.completed"); @@ -144,18 +213,36 @@ export const RequestOpenedType = Schema.Literal("request.opened"); export const RequestResolvedType = Schema.Literal("request.resolved"); export const UserInputRequestedType = Schema.Literal("user-input.requested"); export const UserInputResolvedType = Schema.Literal("user-input.resolved"); +export const TaskStartedType = Schema.Literal("task.started"); +export const TaskProgressType = Schema.Literal("task.progress"); +export const TaskCompletedType = Schema.Literal("task.completed"); +export const HookStartedType = Schema.Literal("hook.started"); +export const HookProgressType = Schema.Literal("hook.progress"); +export const HookCompletedType = Schema.Literal("hook.completed"); +export const ToolProgressType = Schema.Literal("tool.progress"); +export const ToolSummaryType = Schema.Literal("tool.summary"); +export const AuthStatusType = Schema.Literal("auth.status"); +export const AccountUpdatedType = Schema.Literal("account.updated"); +export const AccountRateLimitsUpdatedType = Schema.Literal("account.rate-limits.updated"); +export const McpStatusUpdatedType = Schema.Literal("mcp.status.updated"); +export const McpOauthCompletedType = Schema.Literal("mcp.oauth.completed"); +export const ModelReroutedType = Schema.Literal("model.rerouted"); +export const ConfigWarningType = Schema.Literal("config.warning"); +export const DeprecationNoticeType = Schema.Literal("deprecation.notice"); +export const FilesPersistedType = Schema.Literal("files.persisted"); export const RuntimeWarningType = Schema.Literal("runtime.warning"); export const RuntimeErrorType = Schema.Literal("runtime.error"); export const ProviderRuntimeEventBase = Schema.Struct({ eventId: EventId, provider: ProviderKind, - sessionId: RuntimeSessionId, + sessionId: ProviderSessionId, createdAt: IsoDateTime, - threadId: Schema.optional(ThreadId), - turnId: Schema.optional(TurnId), - itemId: Schema.optional(RuntimeItemId), - requestId: Schema.optional(RuntimeRequestId), + sessionSequence: Schema.optional(NonNegativeInt), + threadId: Schema.optional(ProviderThreadId), + turnId: Schema.optional(ProviderTurnId), + itemId: Schema.optional(ProviderItemId), + requestId: Schema.optional(ApprovalRequestId), providerRefs: Schema.optional(ProviderRefs), raw: Schema.optional(RuntimeEventRaw), }); @@ -167,6 +254,18 @@ export const SessionStartedPayload = Schema.Struct({ }); export type SessionStartedPayload = typeof SessionStartedPayload.Type; +export const SessionConfiguredPayload = Schema.Struct({ + config: UnknownRecordSchema, +}); +export type SessionConfiguredPayload = typeof SessionConfiguredPayload.Type; + +export const SessionStateChangedPayload = Schema.Struct({ + state: RuntimeSessionState, + reason: Schema.optional(TrimmedNonEmptyStringSchema), + detail: Schema.optional(TrimmedNonEmptyStringSchema), +}); +export type SessionStateChangedPayload = typeof SessionStateChangedPayload.Type; + export const SessionExitedPayload = Schema.Struct({ reason: Schema.optional(TrimmedNonEmptyStringSchema), recoverable: Schema.optional(Schema.Boolean), @@ -179,6 +278,48 @@ export const ThreadStartedPayload = Schema.Struct({ }); export type ThreadStartedPayload = typeof ThreadStartedPayload.Type; +export const ThreadStateChangedPayload = Schema.Struct({ + state: RuntimeThreadState, + detail: Schema.optional(Schema.Unknown), +}); +export type ThreadStateChangedPayload = typeof ThreadStateChangedPayload.Type; + +export const ThreadMetadataUpdatedPayload = Schema.Struct({ + name: Schema.optional(TrimmedNonEmptyStringSchema), + metadata: Schema.optional(UnknownRecordSchema), +}); +export type ThreadMetadataUpdatedPayload = typeof ThreadMetadataUpdatedPayload.Type; + +export const ThreadTokenUsageUpdatedPayload = Schema.Struct({ + usage: Schema.Unknown, +}); +export type ThreadTokenUsageUpdatedPayload = typeof ThreadTokenUsageUpdatedPayload.Type; + +export const ThreadRealtimeStartedPayload = Schema.Struct({ + realtimeSessionId: Schema.optional(Schema.String), +}); +export type ThreadRealtimeStartedPayload = typeof ThreadRealtimeStartedPayload.Type; + +export const ThreadRealtimeItemAddedPayload = Schema.Struct({ + item: Schema.Unknown, +}); +export type ThreadRealtimeItemAddedPayload = typeof ThreadRealtimeItemAddedPayload.Type; + +export const ThreadRealtimeAudioDeltaPayload = Schema.Struct({ + audio: Schema.Unknown, +}); +export type ThreadRealtimeAudioDeltaPayload = typeof ThreadRealtimeAudioDeltaPayload.Type; + +export const ThreadRealtimeErrorPayload = Schema.Struct({ + message: TrimmedNonEmptyStringSchema, +}); +export type ThreadRealtimeErrorPayload = typeof ThreadRealtimeErrorPayload.Type; + +export const ThreadRealtimeClosedPayload = Schema.Struct({ + reason: Schema.optional(TrimmedNonEmptyStringSchema), +}); +export type ThreadRealtimeClosedPayload = typeof ThreadRealtimeClosedPayload.Type; + export const TurnStartedPayload = Schema.Struct({ model: Schema.optional(TrimmedNonEmptyStringSchema), effort: Schema.optional(TrimmedNonEmptyStringSchema), @@ -195,6 +336,11 @@ export const TurnCompletedPayload = Schema.Struct({ }); export type TurnCompletedPayload = typeof TurnCompletedPayload.Type; +export const TurnAbortedPayload = Schema.Struct({ + reason: TrimmedNonEmptyStringSchema, +}); +export type TurnAbortedPayload = typeof TurnAbortedPayload.Type; + export const RuntimePlanStep = Schema.Struct({ step: TrimmedNonEmptyStringSchema, status: RuntimePlanStepStatus, @@ -207,6 +353,11 @@ export const TurnPlanUpdatedPayload = Schema.Struct({ }); export type TurnPlanUpdatedPayload = typeof TurnPlanUpdatedPayload.Type; +export const TurnDiffUpdatedPayload = Schema.Struct({ + unifiedDiff: Schema.String, +}); +export type TurnDiffUpdatedPayload = typeof TurnDiffUpdatedPayload.Type; + export const ItemLifecyclePayload = Schema.Struct({ itemType: CanonicalItemType, status: Schema.optional(RuntimeItemStatus), @@ -253,15 +404,151 @@ export const UserInputQuestion = Schema.Struct({ export type UserInputQuestion = typeof UserInputQuestion.Type; export const UserInputRequestedPayload = Schema.Struct({ - questions: Schema.Array(UserInputQuestion), + questions: Schema.Unknown, }); export type UserInputRequestedPayload = typeof UserInputRequestedPayload.Type; export const UserInputResolvedPayload = Schema.Struct({ - answers: UnknownRecordSchema, + answers: Schema.Unknown, }); export type UserInputResolvedPayload = typeof UserInputResolvedPayload.Type; +export const TaskStartedPayload = Schema.Struct({ + taskId: RuntimeTaskId, + description: Schema.optional(TrimmedNonEmptyStringSchema), + taskType: Schema.optional(TrimmedNonEmptyStringSchema), +}); +export type TaskStartedPayload = typeof TaskStartedPayload.Type; + +export const TaskProgressPayload = Schema.Struct({ + taskId: RuntimeTaskId, + description: TrimmedNonEmptyStringSchema, + usage: Schema.optional(Schema.Unknown), + lastToolName: Schema.optional(TrimmedNonEmptyStringSchema), +}); +export type TaskProgressPayload = typeof TaskProgressPayload.Type; + +export const TaskCompletedStatus = Schema.Literals(["completed", "failed", "stopped"]); +export type TaskCompletedStatus = typeof TaskCompletedStatus.Type; + +export const TaskCompletedPayload = Schema.Struct({ + taskId: RuntimeTaskId, + status: TaskCompletedStatus, + summary: Schema.optional(TrimmedNonEmptyStringSchema), + usage: Schema.optional(Schema.Unknown), +}); +export type TaskCompletedPayload = typeof TaskCompletedPayload.Type; + +export const HookOutcome = Schema.Literals(["success", "error", "cancelled"]); +export type HookOutcome = typeof HookOutcome.Type; + +export const HookStartedPayload = Schema.Struct({ + hookId: TrimmedNonEmptyStringSchema, + hookName: TrimmedNonEmptyStringSchema, + hookEvent: TrimmedNonEmptyStringSchema, +}); +export type HookStartedPayload = typeof HookStartedPayload.Type; + +export const HookProgressPayload = Schema.Struct({ + hookId: TrimmedNonEmptyStringSchema, + output: Schema.optional(Schema.String), + stdout: Schema.optional(Schema.String), + stderr: Schema.optional(Schema.String), +}); +export type HookProgressPayload = typeof HookProgressPayload.Type; + +export const HookCompletedPayload = Schema.Struct({ + hookId: TrimmedNonEmptyStringSchema, + outcome: HookOutcome, + output: Schema.optional(Schema.String), + stdout: Schema.optional(Schema.String), + stderr: Schema.optional(Schema.String), + exitCode: Schema.optional(Schema.Int), +}); +export type HookCompletedPayload = typeof HookCompletedPayload.Type; + +export const ToolProgressPayload = Schema.Struct({ + toolUseId: Schema.optional(TrimmedNonEmptyStringSchema), + toolName: Schema.optional(TrimmedNonEmptyStringSchema), + summary: Schema.optional(TrimmedNonEmptyStringSchema), + elapsedSeconds: Schema.optional(Schema.Number), +}); +export type ToolProgressPayload = typeof ToolProgressPayload.Type; + +export const ToolSummaryPayload = Schema.Struct({ + summary: TrimmedNonEmptyStringSchema, + precedingToolUseIds: Schema.optional(Schema.Array(TrimmedNonEmptyStringSchema)), +}); +export type ToolSummaryPayload = typeof ToolSummaryPayload.Type; + +export const AuthStatusPayload = Schema.Struct({ + isAuthenticating: Schema.optional(Schema.Boolean), + output: Schema.optional(Schema.Array(Schema.String)), + error: Schema.optional(TrimmedNonEmptyStringSchema), +}); +export type AuthStatusPayload = typeof AuthStatusPayload.Type; + +export const AccountUpdatedPayload = Schema.Struct({ + account: Schema.Unknown, +}); +export type AccountUpdatedPayload = typeof AccountUpdatedPayload.Type; + +export const AccountRateLimitsUpdatedPayload = Schema.Struct({ + rateLimits: Schema.Unknown, +}); +export type AccountRateLimitsUpdatedPayload = typeof AccountRateLimitsUpdatedPayload.Type; + +export const McpStatusUpdatedPayload = Schema.Struct({ + status: Schema.Unknown, +}); +export type McpStatusUpdatedPayload = typeof McpStatusUpdatedPayload.Type; + +export const McpOauthCompletedPayload = Schema.Struct({ + success: Schema.Boolean, + name: Schema.optional(TrimmedNonEmptyStringSchema), + error: Schema.optional(TrimmedNonEmptyStringSchema), +}); +export type McpOauthCompletedPayload = typeof McpOauthCompletedPayload.Type; + +export const ModelReroutedPayload = Schema.Struct({ + fromModel: TrimmedNonEmptyStringSchema, + toModel: TrimmedNonEmptyStringSchema, + reason: TrimmedNonEmptyStringSchema, +}); +export type ModelReroutedPayload = typeof ModelReroutedPayload.Type; + +export const ConfigWarningPayload = Schema.Struct({ + summary: TrimmedNonEmptyStringSchema, + details: Schema.optional(TrimmedNonEmptyStringSchema), + path: Schema.optional(TrimmedNonEmptyStringSchema), + range: Schema.optional(Schema.Unknown), +}); +export type ConfigWarningPayload = typeof ConfigWarningPayload.Type; + +export const DeprecationNoticePayload = Schema.Struct({ + summary: TrimmedNonEmptyStringSchema, + details: Schema.optional(TrimmedNonEmptyStringSchema), +}); +export type DeprecationNoticePayload = typeof DeprecationNoticePayload.Type; + +export const PersistedFile = Schema.Struct({ + filename: TrimmedNonEmptyStringSchema, + fileId: TrimmedNonEmptyStringSchema, +}); +export type PersistedFile = typeof PersistedFile.Type; + +export const PersistedFileFailure = Schema.Struct({ + filename: TrimmedNonEmptyStringSchema, + error: TrimmedNonEmptyStringSchema, +}); +export type PersistedFileFailure = typeof PersistedFileFailure.Type; + +export const FilesPersistedPayload = Schema.Struct({ + files: Schema.Array(PersistedFile), + failed: Schema.optional(Schema.Array(PersistedFileFailure)), +}); +export type FilesPersistedPayload = typeof FilesPersistedPayload.Type; + export const RuntimeWarningPayload = Schema.Struct({ message: TrimmedNonEmptyStringSchema, detail: Schema.optional(Schema.Unknown), @@ -282,6 +569,21 @@ export const ProviderRuntimeSessionStartedEvent = Schema.Struct({ }); export type ProviderRuntimeSessionStartedEvent = typeof ProviderRuntimeSessionStartedEvent.Type; +export const ProviderRuntimeSessionConfiguredEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: SessionConfiguredType, + payload: SessionConfiguredPayload, +}); +export type ProviderRuntimeSessionConfiguredEvent = typeof ProviderRuntimeSessionConfiguredEvent.Type; + +export const ProviderRuntimeSessionStateChangedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: SessionStateChangedType, + payload: SessionStateChangedPayload, +}); +export type ProviderRuntimeSessionStateChangedEvent = + typeof ProviderRuntimeSessionStateChangedEvent.Type; + export const ProviderRuntimeSessionExitedEvent = Schema.Struct({ ...ProviderRuntimeEventBase.fields, type: SessionExitedType, @@ -296,6 +598,70 @@ export const ProviderRuntimeThreadStartedEvent = Schema.Struct({ }); export type ProviderRuntimeThreadStartedEvent = typeof ProviderRuntimeThreadStartedEvent.Type; +export const ProviderRuntimeThreadStateChangedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: ThreadStateChangedType, + payload: ThreadStateChangedPayload, +}); +export type ProviderRuntimeThreadStateChangedEvent = + typeof ProviderRuntimeThreadStateChangedEvent.Type; + +export const ProviderRuntimeThreadMetadataUpdatedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: ThreadMetadataUpdatedType, + payload: ThreadMetadataUpdatedPayload, +}); +export type ProviderRuntimeThreadMetadataUpdatedEvent = + typeof ProviderRuntimeThreadMetadataUpdatedEvent.Type; + +export const ProviderRuntimeThreadTokenUsageUpdatedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: ThreadTokenUsageUpdatedType, + payload: ThreadTokenUsageUpdatedPayload, +}); +export type ProviderRuntimeThreadTokenUsageUpdatedEvent = + typeof ProviderRuntimeThreadTokenUsageUpdatedEvent.Type; + +export const ProviderRuntimeThreadRealtimeStartedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: ThreadRealtimeStartedType, + payload: ThreadRealtimeStartedPayload, +}); +export type ProviderRuntimeThreadRealtimeStartedEvent = + typeof ProviderRuntimeThreadRealtimeStartedEvent.Type; + +export const ProviderRuntimeThreadRealtimeItemAddedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: ThreadRealtimeItemAddedType, + payload: ThreadRealtimeItemAddedPayload, +}); +export type ProviderRuntimeThreadRealtimeItemAddedEvent = + typeof ProviderRuntimeThreadRealtimeItemAddedEvent.Type; + +export const ProviderRuntimeThreadRealtimeAudioDeltaEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: ThreadRealtimeAudioDeltaType, + payload: ThreadRealtimeAudioDeltaPayload, +}); +export type ProviderRuntimeThreadRealtimeAudioDeltaEvent = + typeof ProviderRuntimeThreadRealtimeAudioDeltaEvent.Type; + +export const ProviderRuntimeThreadRealtimeErrorEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: ThreadRealtimeErrorType, + payload: ThreadRealtimeErrorPayload, +}); +export type ProviderRuntimeThreadRealtimeErrorEvent = + typeof ProviderRuntimeThreadRealtimeErrorEvent.Type; + +export const ProviderRuntimeThreadRealtimeClosedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: ThreadRealtimeClosedType, + payload: ThreadRealtimeClosedPayload, +}); +export type ProviderRuntimeThreadRealtimeClosedEvent = + typeof ProviderRuntimeThreadRealtimeClosedEvent.Type; + export const ProviderRuntimeTurnStartedEvent = Schema.Struct({ ...ProviderRuntimeEventBase.fields, type: TurnStartedType, @@ -310,6 +676,13 @@ export const ProviderRuntimeTurnCompletedEvent = Schema.Struct({ }); export type ProviderRuntimeTurnCompletedEvent = typeof ProviderRuntimeTurnCompletedEvent.Type; +export const ProviderRuntimeTurnAbortedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: TurnAbortedType, + payload: TurnAbortedPayload, +}); +export type ProviderRuntimeTurnAbortedEvent = typeof ProviderRuntimeTurnAbortedEvent.Type; + export const ProviderRuntimeTurnPlanUpdatedEvent = Schema.Struct({ ...ProviderRuntimeEventBase.fields, type: TurnPlanUpdatedType, @@ -317,6 +690,13 @@ export const ProviderRuntimeTurnPlanUpdatedEvent = Schema.Struct({ }); export type ProviderRuntimeTurnPlanUpdatedEvent = typeof ProviderRuntimeTurnPlanUpdatedEvent.Type; +export const ProviderRuntimeTurnDiffUpdatedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: TurnDiffUpdatedType, + payload: TurnDiffUpdatedPayload, +}); +export type ProviderRuntimeTurnDiffUpdatedEvent = typeof ProviderRuntimeTurnDiffUpdatedEvent.Type; + export const ProviderRuntimeItemStartedEvent = Schema.Struct({ ...ProviderRuntimeEventBase.fields, type: ItemStartedType, @@ -375,6 +755,128 @@ export const ProviderRuntimeUserInputResolvedEvent = Schema.Struct({ export type ProviderRuntimeUserInputResolvedEvent = typeof ProviderRuntimeUserInputResolvedEvent.Type; +export const ProviderRuntimeTaskStartedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: TaskStartedType, + payload: TaskStartedPayload, +}); +export type ProviderRuntimeTaskStartedEvent = typeof ProviderRuntimeTaskStartedEvent.Type; + +export const ProviderRuntimeTaskProgressEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: TaskProgressType, + payload: TaskProgressPayload, +}); +export type ProviderRuntimeTaskProgressEvent = typeof ProviderRuntimeTaskProgressEvent.Type; + +export const ProviderRuntimeTaskCompletedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: TaskCompletedType, + payload: TaskCompletedPayload, +}); +export type ProviderRuntimeTaskCompletedEvent = typeof ProviderRuntimeTaskCompletedEvent.Type; + +export const ProviderRuntimeHookStartedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: HookStartedType, + payload: HookStartedPayload, +}); +export type ProviderRuntimeHookStartedEvent = typeof ProviderRuntimeHookStartedEvent.Type; + +export const ProviderRuntimeHookProgressEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: HookProgressType, + payload: HookProgressPayload, +}); +export type ProviderRuntimeHookProgressEvent = typeof ProviderRuntimeHookProgressEvent.Type; + +export const ProviderRuntimeHookCompletedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: HookCompletedType, + payload: HookCompletedPayload, +}); +export type ProviderRuntimeHookCompletedEvent = typeof ProviderRuntimeHookCompletedEvent.Type; + +export const ProviderRuntimeToolProgressEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: ToolProgressType, + payload: ToolProgressPayload, +}); +export type ProviderRuntimeToolProgressEvent = typeof ProviderRuntimeToolProgressEvent.Type; + +export const ProviderRuntimeToolSummaryEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: ToolSummaryType, + payload: ToolSummaryPayload, +}); +export type ProviderRuntimeToolSummaryEvent = typeof ProviderRuntimeToolSummaryEvent.Type; + +export const ProviderRuntimeAuthStatusEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: AuthStatusType, + payload: AuthStatusPayload, +}); +export type ProviderRuntimeAuthStatusEvent = typeof ProviderRuntimeAuthStatusEvent.Type; + +export const ProviderRuntimeAccountUpdatedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: AccountUpdatedType, + payload: AccountUpdatedPayload, +}); +export type ProviderRuntimeAccountUpdatedEvent = typeof ProviderRuntimeAccountUpdatedEvent.Type; + +export const ProviderRuntimeAccountRateLimitsUpdatedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: AccountRateLimitsUpdatedType, + payload: AccountRateLimitsUpdatedPayload, +}); +export type ProviderRuntimeAccountRateLimitsUpdatedEvent = + typeof ProviderRuntimeAccountRateLimitsUpdatedEvent.Type; + +export const ProviderRuntimeMcpStatusUpdatedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: McpStatusUpdatedType, + payload: McpStatusUpdatedPayload, +}); +export type ProviderRuntimeMcpStatusUpdatedEvent = typeof ProviderRuntimeMcpStatusUpdatedEvent.Type; + +export const ProviderRuntimeMcpOauthCompletedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: McpOauthCompletedType, + payload: McpOauthCompletedPayload, +}); +export type ProviderRuntimeMcpOauthCompletedEvent = + typeof ProviderRuntimeMcpOauthCompletedEvent.Type; + +export const ProviderRuntimeModelReroutedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: ModelReroutedType, + payload: ModelReroutedPayload, +}); +export type ProviderRuntimeModelReroutedEvent = typeof ProviderRuntimeModelReroutedEvent.Type; + +export const ProviderRuntimeConfigWarningEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: ConfigWarningType, + payload: ConfigWarningPayload, +}); +export type ProviderRuntimeConfigWarningEvent = typeof ProviderRuntimeConfigWarningEvent.Type; + +export const ProviderRuntimeDeprecationNoticeEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: DeprecationNoticeType, + payload: DeprecationNoticePayload, +}); +export type ProviderRuntimeDeprecationNoticeEvent = + typeof ProviderRuntimeDeprecationNoticeEvent.Type; + +export const ProviderRuntimeFilesPersistedEvent = Schema.Struct({ + ...ProviderRuntimeEventBase.fields, + type: FilesPersistedType, + payload: FilesPersistedPayload, +}); +export type ProviderRuntimeFilesPersistedEvent = typeof ProviderRuntimeFilesPersistedEvent.Type; + export const ProviderRuntimeWarningEvent = Schema.Struct({ ...ProviderRuntimeEventBase.fields, type: RuntimeWarningType, @@ -391,11 +893,23 @@ export type ProviderRuntimeErrorEvent = typeof ProviderRuntimeErrorEvent.Type; export const ProviderRuntimeEventV2 = Schema.Union([ ProviderRuntimeSessionStartedEvent, + ProviderRuntimeSessionConfiguredEvent, + ProviderRuntimeSessionStateChangedEvent, ProviderRuntimeSessionExitedEvent, ProviderRuntimeThreadStartedEvent, + ProviderRuntimeThreadStateChangedEvent, + ProviderRuntimeThreadMetadataUpdatedEvent, + ProviderRuntimeThreadTokenUsageUpdatedEvent, + ProviderRuntimeThreadRealtimeStartedEvent, + ProviderRuntimeThreadRealtimeItemAddedEvent, + ProviderRuntimeThreadRealtimeAudioDeltaEvent, + ProviderRuntimeThreadRealtimeErrorEvent, + ProviderRuntimeThreadRealtimeClosedEvent, ProviderRuntimeTurnStartedEvent, ProviderRuntimeTurnCompletedEvent, + ProviderRuntimeTurnAbortedEvent, ProviderRuntimeTurnPlanUpdatedEvent, + ProviderRuntimeTurnDiffUpdatedEvent, ProviderRuntimeItemStartedEvent, ProviderRuntimeItemUpdatedEvent, ProviderRuntimeItemCompletedEvent, @@ -404,6 +918,23 @@ export const ProviderRuntimeEventV2 = Schema.Union([ ProviderRuntimeRequestResolvedEvent, ProviderRuntimeUserInputRequestedEvent, ProviderRuntimeUserInputResolvedEvent, + ProviderRuntimeTaskStartedEvent, + ProviderRuntimeTaskProgressEvent, + ProviderRuntimeTaskCompletedEvent, + ProviderRuntimeHookStartedEvent, + ProviderRuntimeHookProgressEvent, + ProviderRuntimeHookCompletedEvent, + ProviderRuntimeToolProgressEvent, + ProviderRuntimeToolSummaryEvent, + ProviderRuntimeAuthStatusEvent, + ProviderRuntimeAccountUpdatedEvent, + ProviderRuntimeAccountRateLimitsUpdatedEvent, + ProviderRuntimeMcpStatusUpdatedEvent, + ProviderRuntimeMcpOauthCompletedEvent, + ProviderRuntimeModelReroutedEvent, + ProviderRuntimeConfigWarningEvent, + ProviderRuntimeDeprecationNoticeEvent, + ProviderRuntimeFilesPersistedEvent, ProviderRuntimeWarningEvent, ProviderRuntimeErrorEvent, ]); @@ -426,10 +957,8 @@ export const ProviderRuntimeApprovalResolvedEvent = ProviderRuntimeRequestResolv export type ProviderRuntimeApprovalResolvedEvent = ProviderRuntimeRequestResolvedEvent; export const ProviderRuntimeToolKind = Schema.Literals([ - "command_execution", - "file_change", - "mcp_tool_call", - "dynamic_tool_call", + "command", + "file-change", "other", ]); export type ProviderRuntimeToolKind = typeof ProviderRuntimeToolKind.Type;