Implement v2 canonical provider runtime adapters

Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
Cursor AgentandJulius Marminge committed 2026-03-01 11:30:28 +00:00
1 parent 7ef6b20f81
commit 14865dc7a6
23 files changed
+4336 -681

No files matched your search

@@ -25,7 +25,7 @@ import type {
} from "../src/provider/Services/ProviderAdapter.ts";
export interface TestTurnResponse {
readonly events: ReadonlyArray<ProviderRuntimeEvent>;
readonly events: ReadonlyArray<Record<string, unknown>>;
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<string, unknown> = {
...(fixtureEvent as Record<string, unknown>),
...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<string, unknown>)
: 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) {
@@ -53,7 +53,7 @@ export const codexTurnTextFixture = [
turnId: TURN_ID,
status: "completed",
},
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
];
export const codexTurnToolFixture = [
{
@@ -94,7 +94,7 @@ export const codexTurnToolFixture = [
turnId: TURN_ID,
status: "completed",
},
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
];
export const codexTurnApprovalFixture = [
{
@@ -135,4 +135,4 @@ export const codexTurnApprovalFixture = [
turnId: TURN_ID,
status: "completed",
},
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
];
@@ -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<string, unknown>;
function createProviderServiceHarness(
cwd: string,
hasSession = true,
sessionCwd = cwd,
providerName: "codex" | "claudeCode" = "codex",
) {
): {
service: ProviderServiceShape;
rollbackConversation: ReturnType<typeof vi.fn>;
emit: (event: RuntimeEventInput) => void;
} {
const now = new Date().toISOString();
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
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");
@@ -48,6 +48,46 @@ function sameId(left: string | null | undefined, right: string | null | undefine
return left === right;
}
function asObject(value: unknown): Record<string, unknown> | undefined {
return value !== null && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: 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<ProviderRuntimeEvent, { type: "turn.completed" }>,
): "completed" | "failed" | "interrupted" | "cancelled" | undefined {
const payload = asObject((event as Record<string, unknown>).payload);
const state = asString(payload?.state);
if (
state === "completed" ||
state === "failed" ||
state === "interrupted" ||
state === "cancelled"
) {
return state;
}
const legacyStatus = asString((event as Record<string, unknown>).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<string, unknown>;
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<string, unknown>).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;
}
@@ -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<string, unknown>;
function createProviderServiceHarness() {
function createProviderServiceHarness(): {
service: ProviderServiceShape;
emit: (event: RuntimeEventInput) => void;
} {
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
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(
@@ -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<string, unknown> | undefined {
return value !== null && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function eventPayloadRecord(event: ProviderRuntimeEvent): Record<string, unknown> | undefined {
const rawEvent = event as unknown as Record<string, unknown>;
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<string, unknown>;
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<string, unknown>;
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<string, unknown>;
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<OrchestrationThreadActivity> {
const maybeSequence = event.sessionSequence !== undefined ? { sequence: event.sessionSequence } : {};
const rawEvent = event as unknown as Record<string, unknown>;
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<string, unknown>;
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,
@@ -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");
@@ -137,6 +137,17 @@ function toMessage(cause: unknown, fallback: string): string {
return fallback;
}
function firstNonEmptyString(...values: ReadonlyArray<unknown>): 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, unknown>): 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<typeof ProviderThreadId.makeUnsafe>;
turns: ReadonlyArray<{
id: ReturnType<typeof ProviderTurnId.makeUnsafe>;
items: ReadonlyArray<unknown>;
}>;
}> =>
): Effect.Effect<
{
threadId: ReturnType<typeof ProviderThreadId.makeUnsafe>;
turns: ReadonlyArray<{
id: ReturnType<typeof ProviderTurnId.makeUnsafe>;
items: ReadonlyArray<unknown>;
}>;
},
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);
@@ -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");
}),
);
});
File diff suppressed because it is too large. Load diff
@@ -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<string> = [];
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<string, unknown>, 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<string, unknown>;
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));
});
});
File diff suppressed because it is too large. Load diff
@@ -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"]);
}),
);
@@ -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<ProviderAdapterShape<ProviderAdapterError>>;
@@ -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) => {
@@ -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<ProviderRuntimeEvent> = [
{
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",
},
},
];
@@ -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) {
@@ -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();
});
+127 -173
View File
@@ -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.
+5 -1
View File
@@ -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),
+2 -2
View File
@@ -1089,8 +1089,8 @@ describe("WebSocket Server", () => {
it("keeps orchestration domain push behavior for provider runtime events", async () => {
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
const sessionId = asProviderSessionId("sess-test");
const emitRuntimeEvent = (event: ProviderRuntimeEvent) => {
Effect.runSync(PubSub.publish(runtimeEventPubSub, event));
const emitRuntimeEvent = (event: ProviderRuntimeEvent | Record<string, unknown>) => {
Effect.runSync(PubSub.publish(runtimeEventPubSub, event as ProviderRuntimeEvent));
};
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
const providerService: ProviderServiceShape = {
+6
View File
@@ -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;
@@ -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", () => {
+545 -16
View File
@@ -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;