Compare commits
16
Commits
No files matched your search
@@ -83,12 +83,6 @@ type CanonicalRuntimeEventType =
|
||||
| "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"
|
||||
@@ -111,20 +105,8 @@ type CanonicalRuntimeEventType =
|
||||
| "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";
|
||||
```
|
||||
|
||||
@@ -10,6 +10,9 @@ import {
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
ProviderTurnStartResult,
|
||||
RuntimeSessionId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Queue, Stream } from "effect";
|
||||
|
||||
@@ -167,24 +170,28 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
|
||||
const assistantDeltas: string[] = [];
|
||||
const deferredTurnCompletedEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeSessionId = RuntimeSessionId.makeUnsafe(input.sessionId);
|
||||
const runtimeThreadId = ThreadId.makeUnsafe(state.snapshot.threadId);
|
||||
const runtimeTurnId = TurnId.makeUnsafe(turnId);
|
||||
|
||||
for (const fixtureEvent of response.events) {
|
||||
const rawEvent: Record<string, unknown> = {
|
||||
...(fixtureEvent as Record<string, unknown>),
|
||||
eventId: randomUUID(),
|
||||
provider,
|
||||
sessionId: input.sessionId,
|
||||
sessionId: runtimeSessionId,
|
||||
createdAt: nowIso(),
|
||||
};
|
||||
if (Object.hasOwn(rawEvent, "threadId")) {
|
||||
rawEvent.threadId = state.snapshot.threadId;
|
||||
rawEvent.threadId = runtimeThreadId;
|
||||
}
|
||||
if (Object.hasOwn(rawEvent, "turnId")) {
|
||||
rawEvent.turnId = turnId;
|
||||
rawEvent.turnId = runtimeTurnId;
|
||||
}
|
||||
|
||||
const runtimeEvent = rawEvent as ProviderRuntimeEvent;
|
||||
if (runtimeEvent.type === "message.delta") {
|
||||
assistantDeltas.push(runtimeEvent.delta);
|
||||
if (runtimeEvent.type === "content.delta") {
|
||||
assistantDeltas.push(runtimeEvent.payload.delta);
|
||||
}
|
||||
if (runtimeEvent.type === "turn.completed") {
|
||||
deferredTurnCompletedEvents.push(runtimeEvent);
|
||||
@@ -223,15 +230,21 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe(randomUUID()),
|
||||
provider,
|
||||
sessionId: input.sessionId,
|
||||
sessionId: runtimeSessionId,
|
||||
createdAt: nowIso(),
|
||||
threadId: state.snapshot.threadId,
|
||||
turnId,
|
||||
status: "completed",
|
||||
threadId: runtimeThreadId,
|
||||
turnId: runtimeTurnId,
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
} else {
|
||||
for (const completedEvent of deferredTurnCompletedEvents) {
|
||||
yield* emit(completedEvent);
|
||||
yield* emit({
|
||||
...completedEvent,
|
||||
eventId: EventId.makeUnsafe(randomUUID()),
|
||||
sessionId: runtimeSessionId,
|
||||
threadId: runtimeThreadId,
|
||||
turnId: runtimeTurnId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
EventId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
RuntimeRequestId,
|
||||
RuntimeSessionId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
RuntimeItemId,
|
||||
type ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
const SESSION_ID = ProviderSessionId.makeUnsafe("fixture-session");
|
||||
const THREAD_ID = ProviderThreadId.makeUnsafe("fixture-thread");
|
||||
const TURN_ID = ProviderTurnId.makeUnsafe("fixture-turn");
|
||||
const REQUEST_ID = ApprovalRequestId.makeUnsafe("req-1");
|
||||
const SESSION_ID = RuntimeSessionId.makeUnsafe("fixture-session");
|
||||
const THREAD_ID = ThreadId.makeUnsafe("fixture-thread");
|
||||
const TURN_ID = TurnId.makeUnsafe("fixture-turn");
|
||||
const ITEM_ID = RuntimeItemId.makeUnsafe("fixture-item");
|
||||
const REQUEST_ID = RuntimeRequestId.makeUnsafe("req-1");
|
||||
|
||||
function baseEvent(
|
||||
eventId: string,
|
||||
@@ -31,29 +33,36 @@ export const codexTurnTextFixture = [
|
||||
...baseEvent("evt-1", "2026-02-23T00:00:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-2", "2026-02-23T00:00:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
delta: "I will make a small update.\n",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "I will make a small update.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-3", "2026-02-23T00:00:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
delta: "Done.\n",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Done.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-4", "2026-02-23T00:00:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
status: "completed",
|
||||
payload: { state: "completed" },
|
||||
},
|
||||
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
|
||||
] as ReadonlyArray<ProviderRuntimeEvent>;
|
||||
|
||||
export const codexTurnToolFixture = [
|
||||
{
|
||||
@@ -61,40 +70,50 @@ export const codexTurnToolFixture = [
|
||||
...baseEvent("evt-11", "2026-02-23T00:01:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "tool.started",
|
||||
type: "item.started",
|
||||
...baseEvent("evt-12", "2026-02-23T00:01:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
detail: "echo integration",
|
||||
itemId: ITEM_ID,
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
title: "Command run",
|
||||
detail: "echo integration",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "tool.completed",
|
||||
type: "item.completed",
|
||||
...baseEvent("evt-13", "2026-02-23T00:01:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
detail: "echo integration",
|
||||
itemId: ITEM_ID,
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
title: "Command run",
|
||||
detail: "echo integration",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-14", "2026-02-23T00:01:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
delta: "Applied the requested edit.\n",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Applied the requested edit.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-15", "2026-02-23T00:01:00.400Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
status: "completed",
|
||||
payload: { state: "completed" },
|
||||
},
|
||||
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
|
||||
] as ReadonlyArray<ProviderRuntimeEvent>;
|
||||
|
||||
export const codexTurnApprovalFixture = [
|
||||
{
|
||||
@@ -102,37 +121,45 @@ export const codexTurnApprovalFixture = [
|
||||
...baseEvent("evt-21", "2026-02-23T00:02:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "approval.requested",
|
||||
type: "request.opened",
|
||||
...baseEvent("evt-22", "2026-02-23T00:02:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
requestId: REQUEST_ID,
|
||||
requestKind: "command",
|
||||
detail: "Please approve command",
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
detail: "Please approve command",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "approval.resolved",
|
||||
type: "request.resolved",
|
||||
...baseEvent("evt-23", "2026-02-23T00:02:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
requestId: REQUEST_ID,
|
||||
requestKind: "command",
|
||||
decision: "accept",
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
decision: "accept",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-24", "2026-02-23T00:02:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
delta: "Approval received and command executed.\n",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Approval received and command executed.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-25", "2026-02-23T00:02:00.400Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
status: "completed",
|
||||
payload: { state: "completed" },
|
||||
},
|
||||
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
|
||||
] as ReadonlyArray<ProviderRuntimeEvent>;
|
||||
@@ -10,7 +10,10 @@ import {
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
RuntimeRequestId,
|
||||
RuntimeSessionId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Option, Schema } from "effect";
|
||||
@@ -36,9 +39,9 @@ const asApprovalRequestId = (value: string): ApprovalRequestId =>
|
||||
|
||||
const PROJECT_ID = asProjectId("project-1");
|
||||
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
|
||||
const FIXTURE_SESSION_ID = asProviderSessionId("fixture-session");
|
||||
const FIXTURE_THREAD_ID = asProviderThreadId("fixture-thread");
|
||||
const FIXTURE_TURN_ID = asProviderTurnId("fixture-turn");
|
||||
const FIXTURE_SESSION_ID = RuntimeSessionId.makeUnsafe("fixture-session");
|
||||
const FIXTURE_THREAD_ID = ThreadId.makeUnsafe("fixture-thread");
|
||||
const FIXTURE_TURN_ID = TurnId.makeUnsafe("fixture-turn");
|
||||
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
|
||||
type IntegrationProvider = "codex" | "claudeCode";
|
||||
|
||||
@@ -159,20 +162,21 @@ it.live("runs a single turn end-to-end and persists checkpoint state in sqlite +
|
||||
...runtimeBase("evt-single-1", "2026-02-24T10:00:00.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...runtimeBase("evt-single-2", "2026-02-24T10:00:00.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Single turn response.\n",
|
||||
payload: { streamKind: "assistant_text", delta: "Single turn response.\n" },
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-single-3", "2026-02-24T10:00:00.200Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
payload: { state: "completed" },
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -229,38 +233,35 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
...runtimeBase("evt-multi-1", "2026-02-24T10:01:00.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "tool.started",
|
||||
type: "item.started",
|
||||
...runtimeBase("evt-multi-2", "2026-02-24T10:01:00.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
detail: "README.md",
|
||||
payload: { itemType: "command_execution", status: "inProgress", title: "Edit file", detail: "README.md" },
|
||||
},
|
||||
{
|
||||
type: "tool.completed",
|
||||
type: "item.completed",
|
||||
...runtimeBase("evt-multi-3", "2026-02-24T10:01:00.200Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
detail: "README.md",
|
||||
payload: { itemType: "command_execution", status: "completed", title: "Edit file", detail: "README.md" },
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...runtimeBase("evt-multi-4", "2026-02-24T10:01:00.300Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Updated README to v2.\n",
|
||||
payload: { streamKind: "assistant_text", delta: "Updated README to v2.\n" },
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-multi-5", "2026-02-24T10:01:00.400Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
payload: { state: "completed" },
|
||||
},
|
||||
],
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
@@ -293,20 +294,21 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
...runtimeBase("evt-multi-6", "2026-02-24T10:02:00.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...runtimeBase("evt-multi-7", "2026-02-24T10:02:00.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Updated README to v3.\n",
|
||||
payload: { streamKind: "assistant_text", delta: "Updated README to v3.\n" },
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-multi-8", "2026-02-24T10:02:00.200Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
payload: { state: "completed" },
|
||||
},
|
||||
],
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
@@ -393,22 +395,22 @@ it.live("tracks approval requests and resolves pending approvals on user respons
|
||||
...runtimeBase("evt-approval-1", "2026-02-24T10:03:00.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "approval.requested",
|
||||
type: "request.opened",
|
||||
...runtimeBase("evt-approval-2", "2026-02-24T10:03:00.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
requestKind: "command",
|
||||
detail: "Approve command execution",
|
||||
requestId: RuntimeRequestId.makeUnsafe("req-approval-1"),
|
||||
payload: { requestType: "command_execution_approval", detail: "Approve command execution" },
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-approval-3", "2026-02-24T10:03:00.200Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
payload: { state: "completed" },
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -475,28 +477,28 @@ it.live("records failed turn runtime state and checkpoint status as error", () =
|
||||
...runtimeBase("evt-failure-1", "2026-02-24T10:04:00.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...runtimeBase("evt-failure-2", "2026-02-24T10:04:00.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Partial output before failure.\n",
|
||||
payload: { streamKind: "assistant_text", delta: "Partial output before failure.\n" },
|
||||
},
|
||||
{
|
||||
type: "runtime.error",
|
||||
...runtimeBase("evt-failure-3", "2026-02-24T10:04:00.200Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
message: "Sandbox command failed.",
|
||||
payload: { message: "Sandbox command failed." },
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-failure-4", "2026-02-24T10:04:00.300Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "failed",
|
||||
errorMessage: "Sandbox command failed.",
|
||||
payload: { state: "failed", errorMessage: "Sandbox command failed." },
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -547,38 +549,35 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
...runtimeBase("evt-revert-1", "2026-02-24T10:05:00.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "tool.started",
|
||||
type: "item.started",
|
||||
...runtimeBase("evt-revert-1-tool-started", "2026-02-24T10:05:00.025Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
detail: "README.md",
|
||||
payload: { itemType: "command_execution", status: "inProgress", title: "Edit file", detail: "README.md" },
|
||||
},
|
||||
{
|
||||
type: "tool.completed",
|
||||
type: "item.completed",
|
||||
...runtimeBase("evt-revert-1-tool-completed", "2026-02-24T10:05:00.035Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
detail: "README.md",
|
||||
payload: { itemType: "command_execution", status: "completed", title: "Edit file", detail: "README.md" },
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...runtimeBase("evt-revert-1a", "2026-02-24T10:05:00.050Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Updated README to v2.\n",
|
||||
payload: { streamKind: "assistant_text", delta: "Updated README to v2.\n" },
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-revert-2", "2026-02-24T10:05:00.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
payload: { state: "completed" },
|
||||
},
|
||||
],
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
@@ -610,38 +609,35 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
...runtimeBase("evt-revert-3", "2026-02-24T10:05:01.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "tool.started",
|
||||
type: "item.started",
|
||||
...runtimeBase("evt-revert-3-tool-started", "2026-02-24T10:05:01.025Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
detail: "README.md",
|
||||
payload: { itemType: "command_execution", status: "inProgress", title: "Edit file", detail: "README.md" },
|
||||
},
|
||||
{
|
||||
type: "tool.completed",
|
||||
type: "item.completed",
|
||||
...runtimeBase("evt-revert-3-tool-completed", "2026-02-24T10:05:01.035Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
detail: "README.md",
|
||||
payload: { itemType: "command_execution", status: "completed", title: "Edit file", detail: "README.md" },
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...runtimeBase("evt-revert-3a", "2026-02-24T10:05:01.050Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Updated README to v3.\n",
|
||||
payload: { streamKind: "assistant_text", delta: "Updated README to v3.\n" },
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-revert-4", "2026-02-24T10:05:01.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
payload: { state: "completed" },
|
||||
},
|
||||
],
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
@@ -768,20 +764,21 @@ it.live("starts a claudeCode session on first turn when provider is requested",
|
||||
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Claude first turn.\n",
|
||||
payload: { streamKind: "assistant_text", delta: "Claude first turn.\n" },
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
payload: { state: "completed" },
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -822,20 +819,21 @@ it.live("recovers claudeCode sessions after provider stopAll using persisted res
|
||||
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Turn before restart.\n",
|
||||
payload: { streamKind: "assistant_text", delta: "Turn before restart.\n" },
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
payload: { state: "completed" },
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -873,20 +871,21 @@ it.live("recovers claudeCode sessions after provider stopAll using persisted res
|
||||
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Turn after restart.\n",
|
||||
payload: { streamKind: "assistant_text", delta: "Turn after restart.\n" },
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
payload: { state: "completed" },
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -932,22 +931,22 @@ it.live("forwards claudeCode approval responses to the provider session", () =>
|
||||
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "approval.requested",
|
||||
type: "request.opened",
|
||||
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
requestKind: "command",
|
||||
detail: "Approve Claude tool call",
|
||||
requestId: RuntimeRequestId.makeUnsafe("req-approval-1"),
|
||||
payload: { requestType: "command_execution_approval", detail: "Approve Claude tool call" },
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
payload: { state: "completed" },
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -1007,20 +1006,21 @@ it.live("forwards thread.turn.interrupt to claudeCode provider sessions", () =>
|
||||
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Long running output.\n",
|
||||
payload: { streamKind: "assistant_text", delta: "Long running output.\n" },
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
payload: { state: "completed" },
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -1075,20 +1075,21 @@ it.live("reverts claudeCode turns and rolls back provider conversation state", (
|
||||
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "README -> v2\n",
|
||||
payload: { streamKind: "assistant_text", delta: "README -> v2\n" },
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
payload: { state: "completed" },
|
||||
},
|
||||
],
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
@@ -1122,20 +1123,21 @@ it.live("reverts claudeCode turns and rolls back provider conversation state", (
|
||||
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "README -> v3\n",
|
||||
payload: { streamKind: "assistant_text", delta: "README -> v3\n" },
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeCode"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
payload: { state: "completed" },
|
||||
},
|
||||
],
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect";
|
||||
import { Command, Flag } from "effect/unstable/cli";
|
||||
|
||||
// Dummy comment.
|
||||
import {
|
||||
DEFAULT_PORT,
|
||||
NetService,
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
ProjectId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
RuntimeSessionId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -40,8 +40,8 @@ import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
const asRuntimeSessionId = (value: string): RuntimeSessionId => RuntimeSessionId.makeUnsafe(value);
|
||||
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
|
||||
function createProviderServiceHarness(
|
||||
@@ -341,10 +341,11 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.started",
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-1"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-1"),
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
payload: {},
|
||||
});
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
@@ -356,11 +357,11 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-1"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-1"),
|
||||
status: "completed",
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
@@ -420,10 +421,11 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.started",
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-main"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-main"),
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-main"),
|
||||
payload: {},
|
||||
});
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
@@ -436,11 +438,11 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-aux"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-aux"),
|
||||
turnId: asProviderTurnId("turn-aux"),
|
||||
status: "completed",
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-aux"),
|
||||
turnId: asTurnId("turn-aux"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
||||
@@ -454,11 +456,11 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-main"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-main"),
|
||||
status: "completed",
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-main"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
@@ -500,10 +502,11 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.started",
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-claude-1"),
|
||||
provider: "claudeCode",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-claude-1"),
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-claude-1"),
|
||||
payload: {},
|
||||
});
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
@@ -515,11 +518,11 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-claude-1"),
|
||||
provider: "claudeCode",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-claude-1"),
|
||||
status: "completed",
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-claude-1"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
@@ -563,11 +566,11 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-missing-baseline"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-missing-baseline"),
|
||||
status: "completed",
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-missing-baseline"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
@@ -655,11 +658,11 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-missing-provider-cwd"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-missing"),
|
||||
sessionId: asRuntimeSessionId("sess-missing"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
|
||||
turnId: asProviderTurnId("turn-missing-cwd"),
|
||||
status: "completed",
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-missing"),
|
||||
turnId: asTurnId("turn-missing-cwd"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
@@ -675,7 +678,7 @@ describe("CheckpointReactor", () => {
|
||||
).toBe("v2\n");
|
||||
});
|
||||
|
||||
it("maps runtime checkpoint.captured into thread.turn.diff.complete when missing in read model", async () => {
|
||||
it("captures turn.completed into thread.turn.diff.complete when missing in read model", async () => {
|
||||
const harness = await createHarness();
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
@@ -700,16 +703,44 @@ describe("CheckpointReactor", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.makeUnsafe("cmd-diff-seed-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.makeUnsafe("cmd-diff-seed-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-2"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 2,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
harness.provider.emit({
|
||||
type: "checkpoint.captured",
|
||||
eventId: EventId.makeUnsafe("evt-checkpoint-captured-3"),
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-3"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-3"),
|
||||
turnCount: 3,
|
||||
status: "completed",
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-3"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
@@ -754,25 +785,25 @@ describe("CheckpointReactor", () => {
|
||||
);
|
||||
|
||||
harness.provider.emit({
|
||||
type: "checkpoint.captured",
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-runtime-capture-failure"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-runtime-failure"),
|
||||
turnCount: 1,
|
||||
status: "completed",
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-runtime-failure"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.started",
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-after-runtime-failure"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-after-runtime-failure"),
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-after-runtime-failure"),
|
||||
payload: {},
|
||||
});
|
||||
|
||||
await waitForGitRefExists(
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
MessageId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
type RuntimeSessionId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationEvent,
|
||||
@@ -179,7 +180,9 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.session?.providerSessionId === event.sessionId,
|
||||
(entry) =>
|
||||
entry.session?.providerSessionId !== undefined &&
|
||||
(entry.session.providerSessionId as string) === (event.sessionId as string),
|
||||
);
|
||||
if (!thread) {
|
||||
return;
|
||||
@@ -195,7 +198,6 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
// When a primary turn is active, only that turn may produce completion checkpoints.
|
||||
if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
|
||||
return;
|
||||
}
|
||||
@@ -266,7 +268,7 @@ const make = Effect.gen(function* () {
|
||||
),
|
||||
Effect.tapError((error) =>
|
||||
appendCaptureFailureActivity({
|
||||
sessionId: event.sessionId,
|
||||
sessionId: event.sessionId as unknown as ProviderSessionId,
|
||||
turnId,
|
||||
detail: `Checkpoint captured, but turn diff summary is unavailable: ${error.message}`,
|
||||
createdAt: event.createdAt,
|
||||
@@ -296,7 +298,7 @@ const make = Effect.gen(function* () {
|
||||
turnId,
|
||||
completedAt: now,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
status: checkpointStatusFromRuntime(event.status),
|
||||
status: checkpointStatusFromRuntime(event.payload.state),
|
||||
files,
|
||||
assistantMessageId,
|
||||
checkpointTurnCount: nextTurnCount,
|
||||
@@ -314,7 +316,7 @@ const make = Effect.gen(function* () {
|
||||
summary: "Checkpoint captured",
|
||||
payload: {
|
||||
turnCount: nextTurnCount,
|
||||
...(event.status !== undefined ? { status: event.status } : {}),
|
||||
...(event.payload.state !== undefined ? { status: event.payload.state } : {}),
|
||||
},
|
||||
turnId,
|
||||
createdAt: now,
|
||||
@@ -333,7 +335,9 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.session?.providerSessionId === event.sessionId,
|
||||
(entry) =>
|
||||
entry.session?.providerSessionId !== undefined &&
|
||||
(entry.session.providerSessionId as string) === (event.sessionId as string),
|
||||
);
|
||||
if (!thread) {
|
||||
return;
|
||||
@@ -581,7 +585,7 @@ const make = Effect.gen(function* () {
|
||||
yield* captureCheckpointFromTurnCompletion(event).pipe(
|
||||
Effect.catch((error) =>
|
||||
appendCaptureFailureActivity({
|
||||
sessionId: event.sessionId,
|
||||
sessionId: event.sessionId as unknown as ProviderSessionId,
|
||||
turnId,
|
||||
detail: error.message,
|
||||
createdAt: new Date().toISOString(),
|
||||
@@ -590,89 +594,6 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "checkpoint.captured") {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (!turnId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.session?.providerSessionId === event.sessionId,
|
||||
);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
thread.checkpoints.some(
|
||||
(checkpoint) =>
|
||||
checkpoint.turnId === turnId || checkpoint.checkpointTurnCount === event.turnCount,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sessionRuntime = yield* resolveSessionRuntimeForThread(thread.id);
|
||||
if (Option.isNone(sessionRuntime)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fromTurnCount = Math.max(0, event.turnCount - 1);
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(thread.id, fromTurnCount);
|
||||
const targetCheckpointRef = checkpointRefForThreadTurn(thread.id, event.turnCount);
|
||||
|
||||
const targetExists = yield* checkpointStore.hasCheckpointRef({
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
});
|
||||
if (!targetExists) {
|
||||
yield* checkpointStore.captureCheckpoint({
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
});
|
||||
}
|
||||
|
||||
const files = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef: targetCheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((diff) =>
|
||||
parseTurnDiffFilesFromUnifiedDiff(diff).map((file) => ({
|
||||
path: file.path,
|
||||
kind: "modified" as const,
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
})),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed([])),
|
||||
);
|
||||
|
||||
const assistantMessageId =
|
||||
thread.messages
|
||||
.toReversed()
|
||||
.find((entry) => entry.role === "assistant" && entry.turnId === turnId)?.id ??
|
||||
MessageId.makeUnsafe(`assistant:${turnId}`);
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: serverCommandId("checkpoint-runtime-captured-diff-complete"),
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
completedAt: event.createdAt,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
status: checkpointStatusFromRuntime(event.status),
|
||||
files,
|
||||
assistantMessageId,
|
||||
checkpointTurnCount: event.turnCount,
|
||||
createdAt: event.createdAt,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const processInput = (
|
||||
@@ -717,11 +638,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(providerService.streamEvents, (event) => {
|
||||
if (
|
||||
event.type !== "turn.started" &&
|
||||
event.type !== "turn.completed" &&
|
||||
event.type !== "checkpoint.captured"
|
||||
) {
|
||||
if (event.type !== "turn.started" && event.type !== "turn.completed") {
|
||||
return Effect.void;
|
||||
}
|
||||
return Queue.offer(queue, { source: "runtime", event }).pipe(Effect.asVoid);
|
||||
|
||||
@@ -4,11 +4,12 @@ import {
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderItemId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
RuntimeItemId,
|
||||
RuntimeSessionId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
@@ -33,8 +34,9 @@ const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
const asProviderThreadId = (value: string): ProviderThreadId =>
|
||||
ProviderThreadId.makeUnsafe(value);
|
||||
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
||||
const asRuntimeSessionId = (value: string): RuntimeSessionId => RuntimeSessionId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
const asRuntimeItemId = (value: string): RuntimeItemId => RuntimeItemId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
|
||||
@@ -190,9 +192,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
payload: {},
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
@@ -204,11 +207,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-turn-completed"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
turnId: asProviderTurnId("turn-1"),
|
||||
status: "failed",
|
||||
errorMessage: "turn failed",
|
||||
turnId: asTurnId("turn-1"),
|
||||
payload: { state: "failed", errorMessage: "turn failed" },
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
@@ -230,10 +232,11 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-midturn-lifecycle"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
threadId: asProviderThreadId("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-midturn-lifecycle"),
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-midturn-lifecycle"),
|
||||
payload: {},
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
@@ -247,17 +250,19 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "thread.started",
|
||||
eventId: asEventId("evt-thread-started-midturn-lifecycle"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asProviderThreadId("provider-thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-1"),
|
||||
payload: { providerThreadId: asProviderThreadId("provider-thread-1") },
|
||||
});
|
||||
harness.emit({
|
||||
type: "session.started",
|
||||
eventId: asEventId("evt-session-started-midturn-lifecycle"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asProviderThreadId("provider-thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-1"),
|
||||
payload: {},
|
||||
});
|
||||
|
||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
||||
@@ -270,11 +275,11 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-turn-completed-midturn-lifecycle"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asProviderThreadId("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-midturn-lifecycle"),
|
||||
status: "completed",
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-midturn-lifecycle"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
@@ -291,10 +296,11 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-primary"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
threadId: asProviderThreadId("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-primary"),
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-primary"),
|
||||
payload: {},
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
@@ -307,11 +313,11 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-turn-completed-aux"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asProviderThreadId("provider-thread-aux"),
|
||||
turnId: asProviderTurnId("turn-aux"),
|
||||
status: "completed",
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-aux"),
|
||||
turnId: asTurnId("turn-aux"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
||||
@@ -324,11 +330,11 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-turn-completed-primary"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asProviderThreadId("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-primary"),
|
||||
status: "completed",
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asTurnId("turn-primary"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
@@ -366,10 +372,11 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-claude-placeholder"),
|
||||
provider: "claudeCode",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asProviderThreadId("provider-thread-real"),
|
||||
turnId: asProviderTurnId("turn-claude-placeholder"),
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-real"),
|
||||
turnId: asTurnId("turn-claude-placeholder"),
|
||||
payload: {},
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
@@ -383,11 +390,11 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-turn-completed-claude-placeholder"),
|
||||
provider: "claudeCode",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asProviderThreadId("provider-thread-real"),
|
||||
turnId: asProviderTurnId("turn-claude-placeholder"),
|
||||
status: "completed",
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-real"),
|
||||
turnId: asTurnId("turn-claude-placeholder"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
@@ -404,9 +411,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-guarded"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-guarded-main"),
|
||||
turnId: asTurnId("turn-guarded-main"),
|
||||
payload: {},
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
@@ -420,10 +428,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-turn-completed-guarded-other"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
turnId: asProviderTurnId("turn-guarded-other"),
|
||||
status: "completed",
|
||||
turnId: asTurnId("turn-guarded-other"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
||||
@@ -436,10 +444,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-turn-completed-guarded-main"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
turnId: asProviderTurnId("turn-guarded-main"),
|
||||
status: "completed",
|
||||
turnId: asTurnId("turn-guarded-main"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
@@ -453,33 +461,34 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-message-delta-1"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-2"),
|
||||
itemId: asItemId("item-1"),
|
||||
delta: "hello",
|
||||
turnId: asTurnId("turn-2"),
|
||||
itemId: asRuntimeItemId("item-1"),
|
||||
payload: { streamKind: "assistant_text", delta: "hello" },
|
||||
});
|
||||
harness.emit({
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-message-delta-2"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-2"),
|
||||
itemId: asItemId("item-1"),
|
||||
delta: " world",
|
||||
turnId: asTurnId("turn-2"),
|
||||
itemId: asRuntimeItemId("item-1"),
|
||||
payload: { streamKind: "assistant_text", delta: " world" },
|
||||
});
|
||||
harness.emit({
|
||||
type: "message.completed",
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-message-completed"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-2"),
|
||||
itemId: asItemId("item-1"),
|
||||
turnId: asTurnId("turn-2"),
|
||||
itemId: asRuntimeItemId("item-1"),
|
||||
payload: { itemType: "assistant_message" },
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
@@ -498,9 +507,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-buffered"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-buffered"),
|
||||
turnId: asTurnId("turn-buffered"),
|
||||
payload: {},
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
@@ -509,14 +519,14 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-message-delta-buffered"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-buffered"),
|
||||
itemId: asItemId("item-buffered"),
|
||||
delta: "buffer me",
|
||||
turnId: asTurnId("turn-buffered"),
|
||||
itemId: asRuntimeItemId("item-buffered"),
|
||||
payload: { streamKind: "assistant_text", delta: "buffer me" },
|
||||
});
|
||||
|
||||
await Effect.runPromise(Effect.sleep("30 millis"));
|
||||
@@ -527,13 +537,14 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "message.completed",
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-message-completed-buffered"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-buffered"),
|
||||
itemId: asItemId("item-buffered"),
|
||||
turnId: asTurnId("turn-buffered"),
|
||||
itemId: asRuntimeItemId("item-buffered"),
|
||||
payload: { itemType: "assistant_message" },
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
@@ -573,9 +584,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-streaming-mode"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-streaming-mode"),
|
||||
turnId: asTurnId("turn-streaming-mode"),
|
||||
payload: {},
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
@@ -585,14 +597,14 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-message-delta-streaming-mode"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-streaming-mode"),
|
||||
itemId: asItemId("item-streaming-mode"),
|
||||
delta: "hello live",
|
||||
turnId: asTurnId("turn-streaming-mode"),
|
||||
itemId: asRuntimeItemId("item-streaming-mode"),
|
||||
payload: { streamKind: "assistant_text", delta: "hello live" },
|
||||
});
|
||||
|
||||
const liveThread = await waitForThread(
|
||||
@@ -611,13 +623,14 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(liveMessage?.streaming).toBe(true);
|
||||
|
||||
harness.emit({
|
||||
type: "message.completed",
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-message-completed-streaming-mode"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-streaming-mode"),
|
||||
itemId: asItemId("item-streaming-mode"),
|
||||
turnId: asTurnId("turn-streaming-mode"),
|
||||
itemId: asRuntimeItemId("item-streaming-mode"),
|
||||
payload: { itemType: "assistant_message" },
|
||||
});
|
||||
|
||||
const finalThread = await waitForThread(
|
||||
@@ -643,9 +656,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-buffer-spill"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-buffer-spill"),
|
||||
turnId: asTurnId("turn-buffer-spill"),
|
||||
payload: {},
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
@@ -655,23 +669,24 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-message-delta-buffer-spill"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-buffer-spill"),
|
||||
itemId: asItemId("item-buffer-spill"),
|
||||
delta: oversizedText,
|
||||
turnId: asTurnId("turn-buffer-spill"),
|
||||
itemId: asRuntimeItemId("item-buffer-spill"),
|
||||
payload: { streamKind: "assistant_text", delta: oversizedText },
|
||||
});
|
||||
harness.emit({
|
||||
type: "message.completed",
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-message-completed-buffer-spill"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-buffer-spill"),
|
||||
itemId: asItemId("item-buffer-spill"),
|
||||
turnId: asTurnId("turn-buffer-spill"),
|
||||
itemId: asRuntimeItemId("item-buffer-spill"),
|
||||
payload: { itemType: "assistant_message" },
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
@@ -695,9 +710,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-for-complete-dedup"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-complete-dedup"),
|
||||
turnId: asTurnId("turn-complete-dedup"),
|
||||
payload: {},
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
@@ -708,32 +724,33 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-message-delta-for-complete-dedup"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-complete-dedup"),
|
||||
itemId: asItemId("item-complete-dedup"),
|
||||
delta: "done",
|
||||
turnId: asTurnId("turn-complete-dedup"),
|
||||
itemId: asRuntimeItemId("item-complete-dedup"),
|
||||
payload: { streamKind: "assistant_text", delta: "done" },
|
||||
});
|
||||
harness.emit({
|
||||
type: "message.completed",
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-message-completed-for-complete-dedup"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-complete-dedup"),
|
||||
itemId: asItemId("item-complete-dedup"),
|
||||
turnId: asTurnId("turn-complete-dedup"),
|
||||
itemId: asRuntimeItemId("item-complete-dedup"),
|
||||
payload: { itemType: "assistant_message" },
|
||||
});
|
||||
harness.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-turn-completed-for-complete-dedup"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-complete-dedup"),
|
||||
status: "completed",
|
||||
turnId: asTurnId("turn-complete-dedup"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
@@ -771,10 +788,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "runtime.error",
|
||||
eventId: asEventId("evt-runtime-error"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-3"),
|
||||
message: "runtime exploded",
|
||||
turnId: asTurnId("turn-3"),
|
||||
payload: { message: "runtime exploded" },
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
@@ -796,29 +813,33 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
type: "session.started",
|
||||
eventId: asEventId("evt-session-started"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
message: "session started",
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-1"),
|
||||
payload: { message: "session started" },
|
||||
});
|
||||
harness.emit({
|
||||
type: "thread.started",
|
||||
eventId: asEventId("evt-thread-started"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-2"),
|
||||
threadId: ThreadId.makeUnsafe("provider-thread-2"),
|
||||
payload: { providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-2") },
|
||||
});
|
||||
harness.emit({
|
||||
type: "tool.started",
|
||||
type: "item.started",
|
||||
eventId: asEventId("evt-tool-started"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-9"),
|
||||
toolKind: "other",
|
||||
title: "Read file",
|
||||
detail: "/tmp/file.ts",
|
||||
turnId: asTurnId("turn-9"),
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "inProgress",
|
||||
title: "Read file",
|
||||
detail: "/tmp/file.ts",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
@@ -838,24 +859,24 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-invalid-delta"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: now,
|
||||
turnId: asProviderTurnId("turn-invalid"),
|
||||
itemId: asItemId("item-invalid"),
|
||||
delta: undefined,
|
||||
turnId: asTurnId("turn-invalid"),
|
||||
itemId: asRuntimeItemId("item-invalid"),
|
||||
payload: { streamKind: "assistant_text", delta: undefined },
|
||||
} as unknown as ProviderRuntimeEvent);
|
||||
|
||||
harness.emit({
|
||||
type: "runtime.error",
|
||||
eventId: asEventId("evt-runtime-error-after-failure"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
sessionId: asRuntimeSessionId("sess-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
turnId: asProviderTurnId("turn-after-failure"),
|
||||
message: "runtime still processed",
|
||||
turnId: asTurnId("turn-after-failure"),
|
||||
payload: { message: "runtime still processed" },
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
type AssistantDeliveryMode,
|
||||
type CanonicalItemType,
|
||||
CommandId,
|
||||
MessageId,
|
||||
type OrchestrationEvent,
|
||||
@@ -11,6 +12,7 @@ import {
|
||||
type OrchestrationThreadActivity,
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderSessionId,
|
||||
type RuntimeSessionId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Ref, Stream } from "effect";
|
||||
|
||||
@@ -21,7 +23,7 @@ import {
|
||||
type ProviderRuntimeIngestionShape,
|
||||
} from "../Services/ProviderRuntimeIngestion.ts";
|
||||
|
||||
const providerTurnKey = (sessionId: ProviderSessionId, turnId: TurnId) => `${sessionId}:${turnId}`;
|
||||
const providerTurnKey = (sessionId: RuntimeSessionId, turnId: TurnId) => `${sessionId}:${turnId}`;
|
||||
const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId =>
|
||||
CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
|
||||
|
||||
@@ -76,12 +78,37 @@ function truncateDetail(value: string, limit = 180): string {
|
||||
return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;
|
||||
}
|
||||
|
||||
function isToolItemType(itemType: CanonicalItemType): boolean {
|
||||
return (
|
||||
itemType === "command_execution" ||
|
||||
itemType === "file_change" ||
|
||||
itemType === "mcp_tool_call" ||
|
||||
itemType === "dynamic_tool_call" ||
|
||||
itemType === "web_search"
|
||||
);
|
||||
}
|
||||
|
||||
function toolActivityKindForItemType(itemType: CanonicalItemType): string {
|
||||
switch (itemType) {
|
||||
case "command_execution":
|
||||
return "command";
|
||||
case "file_change":
|
||||
return "file-change";
|
||||
default:
|
||||
return "other";
|
||||
}
|
||||
}
|
||||
|
||||
function runtimeEventToActivities(
|
||||
event: ProviderRuntimeEvent,
|
||||
): ReadonlyArray<OrchestrationThreadActivity> {
|
||||
const maybeSequence = event.sessionSequence !== undefined ? { sequence: event.sessionSequence } : {};
|
||||
switch (event.type) {
|
||||
case "approval.requested": {
|
||||
case "request.opened": {
|
||||
const requestKind = event.payload.requestType === "command_execution_approval"
|
||||
? "command"
|
||||
: event.payload.requestType === "file_change_approval"
|
||||
? "file-change"
|
||||
: "other";
|
||||
return [
|
||||
{
|
||||
id: event.eventId,
|
||||
@@ -89,21 +116,20 @@ function runtimeEventToActivities(
|
||||
tone: "approval",
|
||||
kind: "approval.requested",
|
||||
summary:
|
||||
event.requestKind === "command"
|
||||
requestKind === "command"
|
||||
? "Command approval requested"
|
||||
: "File-change approval requested",
|
||||
payload: {
|
||||
requestId: event.requestId,
|
||||
requestKind: event.requestKind,
|
||||
...(event.detail ? { detail: truncateDetail(event.detail) } : {}),
|
||||
requestKind,
|
||||
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
case "approval.resolved": {
|
||||
case "request.resolved": {
|
||||
return [
|
||||
{
|
||||
id: event.eventId,
|
||||
@@ -113,11 +139,10 @@ function runtimeEventToActivities(
|
||||
summary: "Approval resolved",
|
||||
payload: {
|
||||
requestId: event.requestId,
|
||||
...(event.requestKind ? { requestKind: event.requestKind } : {}),
|
||||
...(event.decision ? { decision: event.decision } : {}),
|
||||
...(event.payload.requestType ? { requestKind: event.payload.requestType } : {}),
|
||||
...(event.payload.decision ? { decision: event.payload.decision } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -131,46 +156,45 @@ function runtimeEventToActivities(
|
||||
kind: "runtime.error",
|
||||
summary: "Runtime error",
|
||||
payload: {
|
||||
message: truncateDetail(event.message),
|
||||
message: truncateDetail(event.payload.message),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
case "tool.completed": {
|
||||
case "item.completed": {
|
||||
if (!isToolItemType(event.payload.itemType)) 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) } : {}),
|
||||
toolKind: toolActivityKindForItemType(event.payload.itemType),
|
||||
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
case "tool.started": {
|
||||
case "item.started": {
|
||||
if (!isToolItemType(event.payload.itemType)) 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) } : {}),
|
||||
toolKind: toolActivityKindForItemType(event.payload.itemType),
|
||||
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -201,7 +225,7 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const rememberAssistantMessageId = (
|
||||
sessionId: ProviderSessionId,
|
||||
sessionId: RuntimeSessionId,
|
||||
turnId: TurnId,
|
||||
messageId: MessageId,
|
||||
) =>
|
||||
@@ -223,7 +247,7 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
const forgetAssistantMessageId = (
|
||||
sessionId: ProviderSessionId,
|
||||
sessionId: RuntimeSessionId,
|
||||
turnId: TurnId,
|
||||
messageId: MessageId,
|
||||
) =>
|
||||
@@ -243,14 +267,14 @@ const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const getAssistantMessageIdsForTurn = (sessionId: ProviderSessionId, turnId: TurnId) =>
|
||||
const getAssistantMessageIdsForTurn = (sessionId: RuntimeSessionId, turnId: TurnId) =>
|
||||
Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(sessionId, turnId)).pipe(
|
||||
Effect.map((existingIds) =>
|
||||
Option.getOrElse(existingIds, (): Set<MessageId> => new Set<MessageId>()),
|
||||
),
|
||||
);
|
||||
|
||||
const clearAssistantMessageIdsForTurn = (sessionId: ProviderSessionId, turnId: TurnId) =>
|
||||
const clearAssistantMessageIdsForTurn = (sessionId: RuntimeSessionId, turnId: TurnId) =>
|
||||
Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(sessionId, turnId));
|
||||
|
||||
const appendBufferedAssistantText = (messageId: MessageId, delta: string) =>
|
||||
@@ -266,7 +290,6 @@ const make = Effect.gen(function* () {
|
||||
return "";
|
||||
}
|
||||
|
||||
// Safety valve: flush full buffered text as an assistant delta to cap memory.
|
||||
yield* Cache.invalidate(bufferedAssistantTextByMessageId, messageId);
|
||||
return nextText;
|
||||
}),
|
||||
@@ -323,7 +346,7 @@ const make = Effect.gen(function* () {
|
||||
yield* clearAssistantMessageState(input.messageId);
|
||||
});
|
||||
|
||||
const clearTurnStateForSession = (sessionId: ProviderSessionId) =>
|
||||
const clearTurnStateForSession = (sessionId: RuntimeSessionId) =>
|
||||
Effect.gen(function* () {
|
||||
const prefix = `${sessionId}:`;
|
||||
const turnKeys = Array.from(yield* Cache.keys(turnMessageIdsByTurnKey));
|
||||
@@ -352,7 +375,9 @@ const make = Effect.gen(function* () {
|
||||
Effect.gen(function* () {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.session?.providerSessionId === event.sessionId,
|
||||
(entry) =>
|
||||
entry.session?.providerSessionId !== undefined &&
|
||||
(entry.session.providerSessionId as string) === (event.sessionId as string),
|
||||
);
|
||||
if (!thread) return;
|
||||
|
||||
@@ -365,7 +390,7 @@ const make = Effect.gen(function* () {
|
||||
? null
|
||||
: sessionProviderThreadId;
|
||||
const eventProviderThreadId = toProviderThreadId(event.threadId);
|
||||
const eventTurnId = toTurnId("turnId" in event ? event.turnId : undefined);
|
||||
const eventTurnId = toTurnId(event.turnId);
|
||||
const activeTurnId = thread.session?.activeTurnId ?? null;
|
||||
|
||||
const matchesThreadScope =
|
||||
@@ -388,7 +413,6 @@ const make = Effect.gen(function* () {
|
||||
if (!matchesThreadScope) {
|
||||
return false;
|
||||
}
|
||||
// Never let auxiliary/provider-side spawned threads replace the primary thread binding.
|
||||
if (
|
||||
eventProviderThreadId !== null &&
|
||||
scopedSessionProviderThreadId !== null &&
|
||||
@@ -409,11 +433,9 @@ const make = Effect.gen(function* () {
|
||||
if (conflictsWithActiveTurn || missingTurnForActiveTurn) {
|
||||
return false;
|
||||
}
|
||||
// Only the active turn may close the lifecycle state.
|
||||
if (activeTurnId !== null && eventTurnId !== undefined) {
|
||||
return sameId(activeTurnId, eventTurnId);
|
||||
}
|
||||
// If no active turn is tracked, accept completion scoped to this thread.
|
||||
return true;
|
||||
default:
|
||||
return true;
|
||||
@@ -434,8 +456,8 @@ const make = Effect.gen(function* () {
|
||||
? null
|
||||
: activeTurnId;
|
||||
const providerThreadIdFromEvent =
|
||||
event.type === "thread.started"
|
||||
? ProviderThreadId.makeUnsafe(event.threadId)
|
||||
event.type === "thread.started" && event.payload.providerThreadId
|
||||
? event.payload.providerThreadId
|
||||
: event.threadId !== undefined
|
||||
? ProviderThreadId.makeUnsafe(event.threadId)
|
||||
: null;
|
||||
@@ -448,17 +470,15 @@ const make = Effect.gen(function* () {
|
||||
case "session.exited":
|
||||
return "stopped";
|
||||
case "turn.completed":
|
||||
return event.status === "failed" ? "error" : "ready";
|
||||
return event.payload.state === "failed" ? "error" : "ready";
|
||||
case "session.started":
|
||||
case "thread.started":
|
||||
// Provider thread/session start notifications can arrive during an
|
||||
// active turn; preserve turn-running state in that case.
|
||||
return activeTurnId !== null ? "running" : "ready";
|
||||
}
|
||||
})();
|
||||
const lastError =
|
||||
event.type === "turn.completed" && event.status === "failed"
|
||||
? (event.errorMessage ?? thread.session?.lastError ?? "Turn failed")
|
||||
event.type === "turn.completed" && event.payload.state === "failed"
|
||||
? (event.payload.errorMessage ?? thread.session?.lastError ?? "Turn failed")
|
||||
: status === "ready"
|
||||
? null
|
||||
: (thread.session?.lastError ?? null);
|
||||
@@ -472,7 +492,7 @@ const make = Effect.gen(function* () {
|
||||
threadId: thread.id,
|
||||
status,
|
||||
providerName: event.provider,
|
||||
providerSessionId: event.sessionId,
|
||||
providerSessionId: event.sessionId as unknown as ProviderSessionId,
|
||||
providerThreadId,
|
||||
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
|
||||
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
|
||||
@@ -485,7 +505,7 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "message.delta" && event.delta.length > 0) {
|
||||
if (event.type === "content.delta" && event.payload.streamKind === "assistant_text" && event.payload.delta.length > 0) {
|
||||
const assistantMessageId = MessageId.makeUnsafe(
|
||||
`assistant:${event.itemId ?? event.turnId ?? event.sessionId}`,
|
||||
);
|
||||
@@ -496,7 +516,7 @@ 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, event.payload.delta);
|
||||
if (spillChunk.length > 0) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.delta",
|
||||
@@ -514,14 +534,14 @@ const make = Effect.gen(function* () {
|
||||
commandId: providerCommandId(event, "assistant-delta"),
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
delta: event.delta,
|
||||
delta: event.payload.delta,
|
||||
...(turnId ? { turnId } : {}),
|
||||
createdAt: now,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "message.completed") {
|
||||
if (event.type === "item.completed" && event.payload.itemType === "assistant_message") {
|
||||
const assistantMessageId = MessageId.makeUnsafe(`assistant:${event.itemId}`);
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (turnId) {
|
||||
@@ -591,12 +611,12 @@ const make = Effect.gen(function* () {
|
||||
threadId: thread.id,
|
||||
status: "error",
|
||||
providerName: event.provider,
|
||||
providerSessionId: event.sessionId,
|
||||
providerSessionId: event.sessionId as unknown as ProviderSessionId,
|
||||
providerThreadId,
|
||||
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
|
||||
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
|
||||
activeTurnId: eventTurnId ?? null,
|
||||
lastError: event.message,
|
||||
lastError: event.payload.message,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
|
||||
@@ -9,7 +9,7 @@ import type {
|
||||
SDKMessage,
|
||||
SDKUserMessage,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import { ApprovalRequestId, type ProviderTurnId } from "@t3tools/contracts";
|
||||
import { ApprovalRequestId, type ProviderTurnId, TurnId } from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect, Fiber, Random, Stream } from "effect";
|
||||
|
||||
@@ -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",
|
||||
],
|
||||
);
|
||||
@@ -328,27 +328,27 @@ describe("ClaudeCodeAdapterLive", () => {
|
||||
const turnStarted = runtimeEvents[1];
|
||||
assert.equal(turnStarted?.type, "turn.started");
|
||||
if (turnStarted?.type === "turn.started") {
|
||||
assert.equal(turnStarted.turnId, turn.turnId);
|
||||
assert.equal(turnStarted.turnId, TurnId.makeUnsafe(turn.turnId));
|
||||
}
|
||||
|
||||
const deltaEvent = runtimeEvents[3];
|
||||
assert.equal(deltaEvent?.type, "message.delta");
|
||||
if (deltaEvent?.type === "message.delta") {
|
||||
assert.equal(deltaEvent.delta, "Hi");
|
||||
assert.equal(deltaEvent.turnId, turn.turnId);
|
||||
assert.equal(deltaEvent?.type, "content.delta");
|
||||
if (deltaEvent?.type === "content.delta") {
|
||||
assert.equal(deltaEvent.payload.delta, "Hi");
|
||||
assert.equal(deltaEvent.turnId, TurnId.makeUnsafe(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.turnId, TurnId.makeUnsafe(turn.turnId));
|
||||
assert.equal(turnCompleted.payload.state, "completed");
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
@@ -418,21 +418,21 @@ 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.turnId, turn.turnId);
|
||||
assert.equal(deltaEvent?.type, "content.delta");
|
||||
if (deltaEvent?.type === "content.delta") {
|
||||
assert.equal(deltaEvent.payload.delta, "Late text");
|
||||
assert.equal(deltaEvent.turnId, TurnId.makeUnsafe(turn.turnId));
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
@@ -487,17 +487,17 @@ 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");
|
||||
assert.equal(deltaEvent.turnId, turn.turnId);
|
||||
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, TurnId.makeUnsafe(turn.turnId));
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
@@ -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,14 @@ 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;
|
||||
}
|
||||
|
||||
yield* adapter.respondToRequest(
|
||||
session.sessionId,
|
||||
ApprovalRequestId.makeUnsafe(requested.value.requestId),
|
||||
ApprovalRequestId.makeUnsafe(requested.value.requestId!),
|
||||
"accept",
|
||||
);
|
||||
|
||||
@@ -629,12 +629,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");
|
||||
@@ -730,7 +730,7 @@ describe("ClaudeCodeAdapterLive", () => {
|
||||
const firstCompleted = yield* Fiber.join(firstCompletedFiber);
|
||||
assert.equal(firstCompleted._tag, "Some");
|
||||
if (firstCompleted._tag === "Some" && firstCompleted.value.type === "turn.completed") {
|
||||
assert.equal(firstCompleted.value.turnId, firstTurn.turnId);
|
||||
assert.equal(firstCompleted.value.turnId, TurnId.makeUnsafe(firstTurn.turnId));
|
||||
}
|
||||
|
||||
const secondTurn = yield* adapter.sendTurn({
|
||||
@@ -756,7 +756,7 @@ describe("ClaudeCodeAdapterLive", () => {
|
||||
const secondCompleted = yield* Fiber.join(secondCompletedFiber);
|
||||
assert.equal(secondCompleted._tag, "Some");
|
||||
if (secondCompleted._tag === "Some" && secondCompleted.value.type === "turn.completed") {
|
||||
assert.equal(secondCompleted.value.turnId, secondTurn.turnId);
|
||||
assert.equal(secondCompleted.value.turnId, TurnId.makeUnsafe(secondTurn.turnId));
|
||||
}
|
||||
|
||||
const threadBeforeRollback = yield* adapter.readThread(session.sessionId);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* ClaudeCodeAdapterLive - Scoped live implementation for the Claude Code provider adapter.
|
||||
*
|
||||
* Wraps `@anthropic-ai/claude-agent-sdk` query sessions behind the generic
|
||||
* provider adapter contract and emits canonical runtime events.
|
||||
* provider adapter contract and emits V2 canonical runtime events.
|
||||
*
|
||||
* @module ClaudeCodeAdapterLive
|
||||
*/
|
||||
@@ -19,17 +19,21 @@ import {
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
type CanonicalItemType,
|
||||
type CanonicalRequestType,
|
||||
EventId,
|
||||
type ProviderApprovalDecision,
|
||||
ProviderItemId,
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderRuntimeToolKind,
|
||||
type ProviderRuntimeTurnStatus,
|
||||
type ProviderSendTurnInput,
|
||||
ProviderSessionId,
|
||||
type ProviderSession,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
RuntimeItemId,
|
||||
RuntimeRequestId,
|
||||
RuntimeSessionId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cause, DateTime, Deferred, Effect, Layer, Queue, Random, Ref, Stream } from "effect";
|
||||
|
||||
@@ -73,7 +77,7 @@ interface ClaudeTurnState {
|
||||
}
|
||||
|
||||
interface PendingApproval {
|
||||
readonly requestKind: "command" | "file-change";
|
||||
readonly requestKind: CanonicalRequestType;
|
||||
readonly detail?: string;
|
||||
readonly suggestions?: ReadonlyArray<PermissionUpdate>;
|
||||
readonly decision: Deferred.Deferred<ProviderApprovalDecision>;
|
||||
@@ -81,7 +85,7 @@ interface PendingApproval {
|
||||
|
||||
interface ToolInFlight {
|
||||
readonly itemId: string;
|
||||
readonly toolKind: ProviderRuntimeToolKind;
|
||||
readonly itemType: CanonicalItemType;
|
||||
readonly title: string;
|
||||
readonly detail?: string;
|
||||
}
|
||||
@@ -188,7 +192,7 @@ function readClaudeResumeState(resumeCursor: unknown): ClaudeResumeState | undef
|
||||
};
|
||||
}
|
||||
|
||||
function classifyToolKind(toolName: string): ProviderRuntimeToolKind {
|
||||
function classifyItemType(toolName: string): CanonicalItemType {
|
||||
const normalized = toolName.toLowerCase();
|
||||
if (
|
||||
normalized.includes("bash") ||
|
||||
@@ -196,7 +200,7 @@ function classifyToolKind(toolName: string): ProviderRuntimeToolKind {
|
||||
normalized.includes("shell") ||
|
||||
normalized.includes("terminal")
|
||||
) {
|
||||
return "command";
|
||||
return "command_execution";
|
||||
}
|
||||
if (
|
||||
normalized.includes("edit") ||
|
||||
@@ -207,13 +211,34 @@ function classifyToolKind(toolName: string): ProviderRuntimeToolKind {
|
||||
normalized.includes("create") ||
|
||||
normalized.includes("delete")
|
||||
) {
|
||||
return "file-change";
|
||||
return "file_change";
|
||||
}
|
||||
return "other";
|
||||
if (normalized.includes("mcp")) {
|
||||
return "mcp_tool_call";
|
||||
}
|
||||
return "dynamic_tool_call";
|
||||
}
|
||||
|
||||
function classifyRequestKind(toolName: string): "command" | "file-change" {
|
||||
return classifyToolKind(toolName) === "command" ? "command" : "file-change";
|
||||
function classifyRequestType(toolName: string): CanonicalRequestType {
|
||||
const itemType = classifyItemType(toolName);
|
||||
if (itemType === "command_execution") return "command_execution_approval";
|
||||
if (itemType === "file_change") return "file_change_approval";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function titleForItemType(itemType: CanonicalItemType): string {
|
||||
switch (itemType) {
|
||||
case "command_execution":
|
||||
return "Command run";
|
||||
case "file_change":
|
||||
return "File change";
|
||||
case "mcp_tool_call":
|
||||
return "MCP tool call";
|
||||
case "dynamic_tool_call":
|
||||
return "Tool call";
|
||||
default:
|
||||
return "Item";
|
||||
}
|
||||
}
|
||||
|
||||
function summarizeToolRequest(toolName: string, input: Record<string, unknown>): string {
|
||||
@@ -230,17 +255,6 @@ function summarizeToolRequest(toolName: string, input: Record<string, unknown>):
|
||||
return `${toolName}: ${serialized.slice(0, 397)}...`;
|
||||
}
|
||||
|
||||
function titleForTool(kind: ProviderRuntimeToolKind): string {
|
||||
switch (kind) {
|
||||
case "command":
|
||||
return "Command run";
|
||||
case "file-change":
|
||||
return "File change";
|
||||
case "other":
|
||||
return "Tool call";
|
||||
}
|
||||
}
|
||||
|
||||
function buildUserMessage(input: ProviderSendTurnInput): SDKUserMessage {
|
||||
const fragments: string[] = [];
|
||||
|
||||
@@ -269,18 +283,13 @@ function buildUserMessage(input: ProviderSendTurnInput): SDKUserMessage {
|
||||
} as SDKUserMessage;
|
||||
}
|
||||
|
||||
function turnStatusFromResult(result: SDKResultMessage): ProviderRuntimeTurnStatus {
|
||||
function turnStateFromResult(result: SDKResultMessage): "completed" | "failed" | "interrupted" | "cancelled" {
|
||||
if (result.subtype === "success") {
|
||||
return "completed";
|
||||
}
|
||||
|
||||
const errors = result.errors.join(" ").toLowerCase();
|
||||
if (errors.includes("interrupt")) {
|
||||
return "interrupted";
|
||||
}
|
||||
if (errors.includes("cancel")) {
|
||||
return "cancelled";
|
||||
}
|
||||
if (errors.includes("interrupt")) return "interrupted";
|
||||
if (errors.includes("cancel")) return "cancelled";
|
||||
return "failed";
|
||||
}
|
||||
|
||||
@@ -384,28 +393,6 @@ function sdkNativeMethod(message: SDKMessage): string {
|
||||
return `claude/${message.type}`;
|
||||
}
|
||||
|
||||
function sdkNativeItemId(message: SDKMessage): string | undefined {
|
||||
if (message.type === "assistant") {
|
||||
const maybeId = (message.message as { id?: unknown }).id;
|
||||
if (typeof maybeId === "string") {
|
||||
return maybeId;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (message.type === "stream_event") {
|
||||
const event = message.event as {
|
||||
type?: unknown;
|
||||
content_block?: { id?: unknown };
|
||||
};
|
||||
if (event.type === "content_block_start" && typeof event.content_block?.id === "string") {
|
||||
return event.content_block.id;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
return Effect.gen(function* () {
|
||||
const nativeEventLogger =
|
||||
@@ -440,8 +427,6 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
}
|
||||
|
||||
const observedAt = new Date().toISOString();
|
||||
const itemId = sdkNativeItemId(message);
|
||||
|
||||
nativeEventLogger.write({
|
||||
observedAt,
|
||||
event: {
|
||||
@@ -456,12 +441,33 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
method: sdkNativeMethod(message),
|
||||
...(typeof message.session_id === "string" ? { threadId: message.session_id } : {}),
|
||||
...(context.turnState ? { turnId: context.turnState.turnId } : {}),
|
||||
...(itemId ? { itemId: ProviderItemId.makeUnsafe(itemId) } : {}),
|
||||
payload: message,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const makeV2Base = (
|
||||
context: ClaudeSessionContext,
|
||||
stamp: { eventId: EventId; createdAt: string },
|
||||
) => ({
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
sessionId: RuntimeSessionId.makeUnsafe(context.session.sessionId),
|
||||
createdAt: stamp.createdAt,
|
||||
...(context.session.threadId
|
||||
? { threadId: ThreadId.makeUnsafe(context.session.threadId) }
|
||||
: {}),
|
||||
providerRefs: {
|
||||
providerSessionId: context.session.sessionId,
|
||||
...(context.session.threadId
|
||||
? { providerThreadId: context.session.threadId }
|
||||
: {}),
|
||||
...(context.turnState
|
||||
? { providerTurnId: context.turnState.turnId }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
|
||||
const snapshotThread = (
|
||||
context: ClaudeSessionContext,
|
||||
): Effect.Effect<{
|
||||
@@ -470,7 +476,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
id: ReturnType<typeof ProviderTurnId.makeUnsafe>;
|
||||
items: ReadonlyArray<unknown>;
|
||||
}>;
|
||||
}> =>
|
||||
}, ProviderAdapterValidationError> =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = context.session.threadId;
|
||||
if (!threadId) {
|
||||
@@ -534,12 +540,12 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
context.lastThreadStartedId = nextThreadId;
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "thread.started",
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: stamp.createdAt,
|
||||
threadId: nextThreadId,
|
||||
...makeV2Base(context, stamp),
|
||||
threadId: ThreadId.makeUnsafe(nextThreadId),
|
||||
type: "thread.started" as const,
|
||||
payload: {
|
||||
providerThreadId: nextThreadId,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -556,20 +562,19 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
const turnState = context.turnState;
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "runtime.error",
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: stamp.createdAt,
|
||||
...(context.session.threadId ? { threadId: context.session.threadId } : {}),
|
||||
...(turnState ? { turnId: turnState.turnId } : {}),
|
||||
message,
|
||||
...makeV2Base(context, stamp),
|
||||
...(turnState ? { turnId: TurnId.makeUnsafe(turnState.turnId) } : {}),
|
||||
type: "runtime.error" as const,
|
||||
payload: {
|
||||
message,
|
||||
class: "provider_error" as const,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const completeTurn = (
|
||||
context: ClaudeSessionContext,
|
||||
status: ProviderRuntimeTurnStatus,
|
||||
state: "completed" | "failed" | "interrupted" | "cancelled",
|
||||
errorMessage?: string,
|
||||
): Effect.Effect<void> =>
|
||||
Effect.gen(function* () {
|
||||
@@ -577,14 +582,12 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
if (!turnState) {
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: stamp.createdAt,
|
||||
...(context.session.threadId ? { threadId: context.session.threadId } : {}),
|
||||
status,
|
||||
...(errorMessage ? { errorMessage } : {}),
|
||||
...makeV2Base(context, stamp),
|
||||
type: "turn.completed" as const,
|
||||
payload: {
|
||||
state,
|
||||
...(errorMessage ? { errorMessage } : {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -593,28 +596,27 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
if (!turnState.emittedTextDelta && turnState.fallbackAssistantText.length > 0) {
|
||||
const deltaStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "message.delta",
|
||||
eventId: deltaStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: deltaStamp.createdAt,
|
||||
...(context.session.threadId ? { threadId: context.session.threadId } : {}),
|
||||
turnId: turnState.turnId,
|
||||
itemId: ProviderItemId.makeUnsafe(turnState.assistantItemId),
|
||||
delta: turnState.fallbackAssistantText,
|
||||
...makeV2Base(context, deltaStamp),
|
||||
turnId: TurnId.makeUnsafe(turnState.turnId),
|
||||
itemId: RuntimeItemId.makeUnsafe(turnState.assistantItemId),
|
||||
type: "content.delta" as const,
|
||||
payload: {
|
||||
streamKind: "assistant_text" as const,
|
||||
delta: turnState.fallbackAssistantText,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "message.completed",
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: stamp.createdAt,
|
||||
itemId: ProviderItemId.makeUnsafe(turnState.assistantItemId),
|
||||
...(context.session.threadId ? { threadId: context.session.threadId } : {}),
|
||||
turnId: turnState.turnId,
|
||||
...makeV2Base(context, stamp),
|
||||
itemId: RuntimeItemId.makeUnsafe(turnState.assistantItemId),
|
||||
turnId: TurnId.makeUnsafe(turnState.turnId),
|
||||
type: "item.completed" as const,
|
||||
payload: {
|
||||
itemType: "assistant_message" as const,
|
||||
status: "completed" as const,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -625,15 +627,13 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: stamp.createdAt,
|
||||
...(context.session.threadId ? { threadId: context.session.threadId } : {}),
|
||||
turnId: turnState.turnId,
|
||||
status,
|
||||
...(errorMessage ? { errorMessage } : {}),
|
||||
...makeV2Base(context, stamp),
|
||||
turnId: TurnId.makeUnsafe(turnState.turnId),
|
||||
type: "turn.completed" as const,
|
||||
payload: {
|
||||
state,
|
||||
...(errorMessage ? { errorMessage } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
const updatedAt = yield* nowIso;
|
||||
@@ -643,7 +643,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
status: "ready",
|
||||
activeTurnId: undefined,
|
||||
updatedAt,
|
||||
...(status === "failed" && errorMessage ? { lastError: errorMessage } : {}),
|
||||
...(state === "failed" && errorMessage ? { lastError: errorMessage } : {}),
|
||||
};
|
||||
yield* updateResumeCursor(context);
|
||||
});
|
||||
@@ -673,15 +673,14 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
}
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "message.delta",
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: stamp.createdAt,
|
||||
...(context.session.threadId ? { threadId: context.session.threadId } : {}),
|
||||
turnId: context.turnState.turnId,
|
||||
itemId: ProviderItemId.makeUnsafe(context.turnState.assistantItemId),
|
||||
delta: event.delta.text,
|
||||
...makeV2Base(context, stamp),
|
||||
turnId: TurnId.makeUnsafe(context.turnState.turnId),
|
||||
itemId: RuntimeItemId.makeUnsafe(context.turnState.assistantItemId),
|
||||
type: "content.delta" as const,
|
||||
payload: {
|
||||
streamKind: "assistant_text" as const,
|
||||
delta: event.delta.text,
|
||||
},
|
||||
});
|
||||
}
|
||||
return;
|
||||
@@ -698,7 +697,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
}
|
||||
|
||||
const toolName = block.name;
|
||||
const toolKind = classifyToolKind(toolName);
|
||||
const itemType = classifyItemType(toolName);
|
||||
const toolInput =
|
||||
typeof block.input === "object" && block.input !== null
|
||||
? (block.input as Record<string, unknown>)
|
||||
@@ -708,25 +707,24 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
|
||||
const tool: ToolInFlight = {
|
||||
itemId,
|
||||
toolKind,
|
||||
title: titleForTool(toolKind),
|
||||
itemType,
|
||||
title: titleForItemType(itemType),
|
||||
detail,
|
||||
};
|
||||
context.inFlightTools.set(index, tool);
|
||||
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "tool.started",
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: stamp.createdAt,
|
||||
...(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 } : {}),
|
||||
...makeV2Base(context, stamp),
|
||||
...(context.turnState ? { turnId: TurnId.makeUnsafe(context.turnState.turnId) } : {}),
|
||||
itemId: RuntimeItemId.makeUnsafe(tool.itemId),
|
||||
type: "item.started" as const,
|
||||
payload: {
|
||||
itemType: tool.itemType,
|
||||
status: "inProgress" as const,
|
||||
title: tool.title,
|
||||
...(tool.detail ? { detail: tool.detail } : {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -741,17 +739,16 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "tool.completed",
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: stamp.createdAt,
|
||||
...(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 } : {}),
|
||||
...makeV2Base(context, stamp),
|
||||
...(context.turnState ? { turnId: TurnId.makeUnsafe(context.turnState.turnId) } : {}),
|
||||
itemId: RuntimeItemId.makeUnsafe(tool.itemId),
|
||||
type: "item.completed" as const,
|
||||
payload: {
|
||||
itemType: tool.itemType,
|
||||
status: "completed" as const,
|
||||
title: tool.title,
|
||||
...(tool.detail ? { detail: tool.detail } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -792,14 +789,14 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
return;
|
||||
}
|
||||
|
||||
const status = turnStatusFromResult(message);
|
||||
const state = turnStateFromResult(message);
|
||||
const errorMessage = message.subtype === "success" ? undefined : message.errors[0];
|
||||
|
||||
if (status === "failed") {
|
||||
if (state === "failed") {
|
||||
yield* emitRuntimeError(context, errorMessage ?? "Claude turn failed.");
|
||||
}
|
||||
|
||||
yield* completeTurn(context, status, errorMessage);
|
||||
yield* completeTurn(context, state, errorMessage);
|
||||
});
|
||||
|
||||
const handleSdkMessage = (
|
||||
@@ -854,16 +851,14 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
yield* Deferred.succeed(pending.decision, "cancel");
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "approval.resolved",
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: stamp.createdAt,
|
||||
...(context.session.threadId ? { threadId: context.session.threadId } : {}),
|
||||
...(context.turnState ? { turnId: context.turnState.turnId } : {}),
|
||||
requestId,
|
||||
requestKind: pending.requestKind,
|
||||
decision: "cancel",
|
||||
...makeV2Base(context, stamp),
|
||||
...(context.turnState ? { turnId: TurnId.makeUnsafe(context.turnState.turnId) } : {}),
|
||||
requestId: RuntimeRequestId.makeUnsafe(requestId),
|
||||
type: "request.resolved" as const,
|
||||
payload: {
|
||||
requestType: pending.requestKind,
|
||||
decision: "cancel",
|
||||
},
|
||||
});
|
||||
}
|
||||
context.pendingApprovals.clear();
|
||||
@@ -887,13 +882,12 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
if (options?.emitExitEvent !== false) {
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.exited",
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: stamp.createdAt,
|
||||
...(context.session.threadId ? { threadId: context.session.threadId } : {}),
|
||||
message: "Session stopped",
|
||||
...makeV2Base(context, stamp),
|
||||
type: "session.exited" as const,
|
||||
payload: {
|
||||
reason: "Session stopped",
|
||||
exitKind: "graceful" as const,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -972,11 +966,11 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
}
|
||||
|
||||
const requestId = ApprovalRequestId.makeUnsafe(yield* Random.nextUUIDv4);
|
||||
const requestKind = classifyRequestKind(toolName);
|
||||
const requestType = classifyRequestType(toolName);
|
||||
const detail = summarizeToolRequest(toolName, toolInput);
|
||||
const decisionDeferred = yield* Deferred.make<ProviderApprovalDecision>();
|
||||
const pendingApproval: PendingApproval = {
|
||||
requestKind,
|
||||
requestKind: requestType,
|
||||
detail,
|
||||
decision: decisionDeferred,
|
||||
...(callbackOptions.suggestions
|
||||
@@ -986,16 +980,17 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
|
||||
const requestedStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "approval.requested",
|
||||
eventId: requestedStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: requestedStamp.createdAt,
|
||||
...(context.session.threadId ? { threadId: context.session.threadId } : {}),
|
||||
...(context.turnState ? { turnId: context.turnState.turnId } : {}),
|
||||
requestId,
|
||||
requestKind,
|
||||
detail,
|
||||
...makeV2Base(context, requestedStamp),
|
||||
...(context.turnState
|
||||
? { turnId: TurnId.makeUnsafe(context.turnState.turnId) }
|
||||
: {}),
|
||||
requestId: RuntimeRequestId.makeUnsafe(requestId),
|
||||
type: "request.opened" as const,
|
||||
payload: {
|
||||
requestType,
|
||||
detail,
|
||||
args: toolInput,
|
||||
},
|
||||
});
|
||||
|
||||
pendingApprovals.set(requestId, pendingApproval);
|
||||
@@ -1017,16 +1012,16 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
|
||||
const resolvedStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "approval.resolved",
|
||||
eventId: resolvedStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: resolvedStamp.createdAt,
|
||||
...(context.session.threadId ? { threadId: context.session.threadId } : {}),
|
||||
...(context.turnState ? { turnId: context.turnState.turnId } : {}),
|
||||
requestId,
|
||||
requestKind,
|
||||
decision,
|
||||
...makeV2Base(context, resolvedStamp),
|
||||
...(context.turnState
|
||||
? { turnId: TurnId.makeUnsafe(context.turnState.turnId) }
|
||||
: {}),
|
||||
requestId: RuntimeRequestId.makeUnsafe(requestId),
|
||||
type: "request.resolved" as const,
|
||||
payload: {
|
||||
requestType,
|
||||
decision,
|
||||
},
|
||||
});
|
||||
|
||||
if (decision === "accept" || decision === "acceptForSession") {
|
||||
@@ -1128,12 +1123,11 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
|
||||
const sessionStartedStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.started",
|
||||
eventId: sessionStartedStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
sessionId,
|
||||
createdAt: sessionStartedStamp.createdAt,
|
||||
...(threadId ? { threadId } : {}),
|
||||
...makeV2Base(context, sessionStartedStamp),
|
||||
type: "session.started" as const,
|
||||
payload: {
|
||||
...(resumeState?.resume ? { resume: resumeState } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
Effect.runFork(runSdkStream(context));
|
||||
@@ -1184,13 +1178,12 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
|
||||
const turnStartedStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.started",
|
||||
eventId: turnStartedStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
sessionId: context.session.sessionId,
|
||||
createdAt: turnStartedStamp.createdAt,
|
||||
...(context.session.threadId ? { threadId: context.session.threadId } : {}),
|
||||
turnId,
|
||||
...makeV2Base(context, turnStartedStamp),
|
||||
turnId: TurnId.makeUnsafe(turnId),
|
||||
type: "turn.started" as const,
|
||||
payload: {
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
const message = buildUserMessage(input);
|
||||
|
||||
@@ -211,8 +211,8 @@ 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");
|
||||
@@ -247,7 +247,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");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -9,13 +9,20 @@
|
||||
import {
|
||||
type ProviderEvent,
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderRuntimeTurnStatus,
|
||||
type ProviderRuntimeToolKind,
|
||||
ProviderItemId,
|
||||
type CanonicalItemType,
|
||||
type CanonicalRequestType,
|
||||
type RuntimeContentStreamKind,
|
||||
type RuntimeEventRawSource,
|
||||
type RuntimeTurnState,
|
||||
ProviderApprovalDecision,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
RuntimeItemId,
|
||||
RuntimeRequestId,
|
||||
RuntimeSessionId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Queue, Schema, Stream } from "effect";
|
||||
|
||||
@@ -96,7 +103,11 @@ function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function toTurnStatus(value: unknown): ProviderRuntimeTurnStatus | undefined {
|
||||
function asNumber(value: unknown): number | undefined {
|
||||
return typeof value === "number" ? value : undefined;
|
||||
}
|
||||
|
||||
function toTurnState(value: unknown): RuntimeTurnState | undefined {
|
||||
switch (value) {
|
||||
case "completed":
|
||||
case "failed":
|
||||
@@ -126,24 +137,54 @@ function shouldDropItemType(type: string): boolean {
|
||||
return type === "work" || type.startsWith("work ");
|
||||
}
|
||||
|
||||
function toolMeta(type: string):
|
||||
| {
|
||||
readonly toolKind: ProviderRuntimeToolKind;
|
||||
readonly title: string;
|
||||
}
|
||||
| undefined {
|
||||
if (type.includes("command")) {
|
||||
return { toolKind: "command", title: "Command run" };
|
||||
}
|
||||
if (type.includes("file change")) {
|
||||
return { toolKind: "file-change", title: "File change" };
|
||||
}
|
||||
if (type.includes("tool")) {
|
||||
return { toolKind: "other", title: "Tool call" };
|
||||
}
|
||||
function toCanonicalItemType(normalizedType: string): CanonicalItemType | undefined {
|
||||
if (normalizedType.includes("agent message")) return "assistant_message";
|
||||
if (normalizedType.includes("command")) return "command_execution";
|
||||
if (normalizedType.includes("file change")) return "file_change";
|
||||
if (normalizedType.includes("mcp") && normalizedType.includes("tool")) return "mcp_tool_call";
|
||||
if (normalizedType.includes("web search")) return "web_search";
|
||||
if (normalizedType.includes("tool")) return "dynamic_tool_call";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function isToolItemType(itemType: CanonicalItemType): boolean {
|
||||
return (
|
||||
itemType === "command_execution" ||
|
||||
itemType === "file_change" ||
|
||||
itemType === "mcp_tool_call" ||
|
||||
itemType === "dynamic_tool_call" ||
|
||||
itemType === "web_search"
|
||||
);
|
||||
}
|
||||
|
||||
function titleForItemType(itemType: CanonicalItemType): string {
|
||||
switch (itemType) {
|
||||
case "command_execution":
|
||||
return "Command run";
|
||||
case "file_change":
|
||||
return "File change";
|
||||
case "mcp_tool_call":
|
||||
return "MCP tool call";
|
||||
case "web_search":
|
||||
return "Web search";
|
||||
case "dynamic_tool_call":
|
||||
return "Tool call";
|
||||
default:
|
||||
return "Item";
|
||||
}
|
||||
}
|
||||
|
||||
function toCanonicalRequestType(requestKind: string): CanonicalRequestType {
|
||||
switch (requestKind) {
|
||||
case "command":
|
||||
return "command_execution_approval";
|
||||
case "file-change":
|
||||
return "file_change_approval";
|
||||
default:
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
function itemDetail(
|
||||
item: Record<string, unknown>,
|
||||
payload: Record<string, unknown>,
|
||||
@@ -170,84 +211,39 @@ function itemDetail(
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function mapMessageCompletedEvent(event: ProviderEvent): ProviderRuntimeEvent | undefined {
|
||||
if (event.method !== "item/completed") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const payload = asObject(event.payload);
|
||||
const item = asObject(payload?.item);
|
||||
if (!item) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const normalizedType = normalizeItemType(item.type ?? item.kind);
|
||||
if (!normalizedType.includes("agent message")) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const itemId = event.itemId ?? asString(item.id);
|
||||
if (!itemId) {
|
||||
return undefined;
|
||||
}
|
||||
function makeEventBase(event: ProviderEvent) {
|
||||
const rawSource: RuntimeEventRawSource =
|
||||
event.kind === "request"
|
||||
? "codex.app-server.request"
|
||||
: "codex.app-server.notification";
|
||||
|
||||
return {
|
||||
type: "message.completed",
|
||||
eventId: event.id,
|
||||
provider: event.provider,
|
||||
sessionId: event.sessionId,
|
||||
sessionId: RuntimeSessionId.makeUnsafe(event.sessionId),
|
||||
createdAt: event.createdAt,
|
||||
itemId: ProviderItemId.makeUnsafe(itemId),
|
||||
...(event.threadId ? { threadId: event.threadId } : {}),
|
||||
...(event.turnId ? { turnId: event.turnId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function mapToolEvent(event: ProviderEvent): ProviderRuntimeEvent | undefined {
|
||||
if (event.method !== "item/started" && event.method !== "item/completed") {
|
||||
return undefined;
|
||||
}
|
||||
const payload = asObject(event.payload);
|
||||
const item = asObject(payload?.item);
|
||||
if (!item) {
|
||||
return undefined;
|
||||
}
|
||||
const normalizedType = normalizeItemType(item.type ?? item.kind);
|
||||
if (shouldDropItemType(normalizedType)) {
|
||||
return undefined;
|
||||
}
|
||||
const meta = toolMeta(normalizedType);
|
||||
if (!meta) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const eventBase = {
|
||||
eventId: event.id,
|
||||
provider: event.provider,
|
||||
sessionId: event.sessionId,
|
||||
createdAt: event.createdAt,
|
||||
...(event.threadId ? { threadId: event.threadId } : {}),
|
||||
...(event.turnId ? { turnId: event.turnId } : {}),
|
||||
...(event.itemId ? { itemId: event.itemId } : {}),
|
||||
toolKind: meta.toolKind,
|
||||
title: meta.title,
|
||||
...(payload ? { detail: itemDetail(item, payload) } : {}),
|
||||
...(event.threadId !== undefined ? { threadId: ThreadId.makeUnsafe(event.threadId) } : {}),
|
||||
...(event.turnId !== undefined ? { turnId: TurnId.makeUnsafe(event.turnId) } : {}),
|
||||
...(event.itemId !== undefined ? { itemId: RuntimeItemId.makeUnsafe(event.itemId) } : {}),
|
||||
...(event.requestId !== undefined
|
||||
? { requestId: RuntimeRequestId.makeUnsafe(event.requestId) }
|
||||
: {}),
|
||||
providerRefs: {
|
||||
providerSessionId: event.sessionId,
|
||||
...(event.threadId !== undefined ? { providerThreadId: event.threadId } : {}),
|
||||
...(event.turnId !== undefined ? { providerTurnId: event.turnId } : {}),
|
||||
...(event.itemId !== undefined ? { providerItemId: event.itemId } : {}),
|
||||
},
|
||||
raw: {
|
||||
source: rawSource,
|
||||
method: event.method,
|
||||
payload: event.payload,
|
||||
},
|
||||
} as const;
|
||||
|
||||
if (event.method === "item/started") {
|
||||
return {
|
||||
type: "tool.started",
|
||||
...eventBase,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
type: "tool.completed",
|
||||
...eventBase,
|
||||
};
|
||||
}
|
||||
|
||||
function mapToRuntimeEvents(event: ProviderEvent): ReadonlyArray<ProviderRuntimeEvent> {
|
||||
const base = makeEventBase(event);
|
||||
const payload = asObject(event.payload);
|
||||
const turn = asObject(payload?.turn);
|
||||
|
||||
@@ -257,15 +253,13 @@ function mapToRuntimeEvents(event: ProviderEvent): ReadonlyArray<ProviderRuntime
|
||||
}
|
||||
return [
|
||||
{
|
||||
type: "runtime.error",
|
||||
eventId: event.id,
|
||||
provider: event.provider,
|
||||
sessionId: event.sessionId,
|
||||
createdAt: event.createdAt,
|
||||
...(event.threadId ? { threadId: event.threadId } : {}),
|
||||
...(event.turnId ? { turnId: event.turnId } : {}),
|
||||
...(event.itemId ? { itemId: event.itemId } : {}),
|
||||
message: event.message,
|
||||
...base,
|
||||
type: "runtime.error" as const,
|
||||
payload: {
|
||||
message: event.message,
|
||||
class: "provider_error" as const,
|
||||
...(payload ? { detail: payload } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -275,17 +269,14 @@ function mapToRuntimeEvents(event: ProviderEvent): ReadonlyArray<ProviderRuntime
|
||||
asString(payload?.command) ?? asString(payload?.reason) ?? asString(payload?.prompt);
|
||||
return [
|
||||
{
|
||||
type: "approval.requested",
|
||||
eventId: event.id,
|
||||
provider: event.provider,
|
||||
sessionId: event.sessionId,
|
||||
createdAt: event.createdAt,
|
||||
...(event.threadId ? { threadId: event.threadId } : {}),
|
||||
...(event.turnId ? { turnId: event.turnId } : {}),
|
||||
...(event.itemId ? { itemId: event.itemId } : {}),
|
||||
requestId: event.requestId,
|
||||
requestKind: event.requestKind,
|
||||
...(detail ? { detail } : {}),
|
||||
...base,
|
||||
requestId: RuntimeRequestId.makeUnsafe(event.requestId),
|
||||
type: "request.opened" as const,
|
||||
payload: {
|
||||
requestType: toCanonicalRequestType(event.requestKind),
|
||||
...(detail ? { detail } : {}),
|
||||
...(payload ? { args: payload } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -294,41 +285,103 @@ function mapToRuntimeEvents(event: ProviderEvent): ReadonlyArray<ProviderRuntime
|
||||
const decision = Schema.decodeUnknownSync(ProviderApprovalDecision)(payload?.decision);
|
||||
return [
|
||||
{
|
||||
type: "approval.resolved",
|
||||
eventId: event.id,
|
||||
provider: event.provider,
|
||||
sessionId: event.sessionId,
|
||||
createdAt: event.createdAt,
|
||||
...(event.threadId ? { threadId: event.threadId } : {}),
|
||||
...(event.turnId ? { turnId: event.turnId } : {}),
|
||||
...(event.itemId ? { itemId: event.itemId } : {}),
|
||||
requestId: event.requestId,
|
||||
...(event.requestKind ? { requestKind: event.requestKind } : {}),
|
||||
...(decision ? { decision } : {}),
|
||||
...base,
|
||||
requestId: RuntimeRequestId.makeUnsafe(event.requestId),
|
||||
type: "request.resolved" as const,
|
||||
payload: {
|
||||
requestType: event.requestKind
|
||||
? toCanonicalRequestType(event.requestKind)
|
||||
: ("unknown" as const),
|
||||
...(decision ? { decision } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const messageCompleted = mapMessageCompletedEvent(event);
|
||||
if (messageCompleted) {
|
||||
return [messageCompleted];
|
||||
if (event.method === "serverRequest/resolved" && event.requestId) {
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
requestId: RuntimeRequestId.makeUnsafe(event.requestId),
|
||||
type: "request.resolved" as const,
|
||||
payload: {
|
||||
requestType: event.requestKind
|
||||
? toCanonicalRequestType(event.requestKind)
|
||||
: ("unknown" as const),
|
||||
...(payload?.decision ? { decision: String(payload.decision) } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const tool = mapToolEvent(event);
|
||||
if (tool) {
|
||||
return [tool];
|
||||
if (event.method === "item/completed") {
|
||||
const item = asObject(payload?.item);
|
||||
if (!item) return [];
|
||||
const normalizedType = normalizeItemType(item.type ?? item.kind);
|
||||
const canonicalType = toCanonicalItemType(normalizedType);
|
||||
|
||||
if (canonicalType === "assistant_message") {
|
||||
const itemId = event.itemId ?? asString(item.id);
|
||||
if (!itemId) return [];
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
itemId: RuntimeItemId.makeUnsafe(itemId),
|
||||
type: "item.completed" as const,
|
||||
payload: {
|
||||
itemType: "assistant_message" as const,
|
||||
status: "completed" as const,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (canonicalType && isToolItemType(canonicalType) && !shouldDropItemType(normalizedType)) {
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
type: "item.completed" as const,
|
||||
payload: {
|
||||
itemType: canonicalType,
|
||||
status: "completed" as const,
|
||||
title: titleForItemType(canonicalType),
|
||||
...(payload ? { detail: itemDetail(item, payload) } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if (event.method === "item/started") {
|
||||
const item = asObject(payload?.item);
|
||||
if (!item) return [];
|
||||
const normalizedType = normalizeItemType(item.type ?? item.kind);
|
||||
if (shouldDropItemType(normalizedType)) return [];
|
||||
const canonicalType = toCanonicalItemType(normalizedType);
|
||||
if (!canonicalType || !isToolItemType(canonicalType)) return [];
|
||||
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
type: "item.started" as const,
|
||||
payload: {
|
||||
itemType: canonicalType,
|
||||
status: "inProgress" as const,
|
||||
title: titleForItemType(canonicalType),
|
||||
...(payload ? { detail: itemDetail(item, payload) } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "session/started") {
|
||||
return [
|
||||
{
|
||||
type: "session.started",
|
||||
eventId: event.id,
|
||||
provider: event.provider,
|
||||
sessionId: event.sessionId,
|
||||
createdAt: event.createdAt,
|
||||
...(event.threadId ? { threadId: event.threadId } : {}),
|
||||
...(event.message ? { message: event.message } : {}),
|
||||
...base,
|
||||
type: "session.started" as const,
|
||||
payload: {
|
||||
...(event.message ? { message: event.message } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -336,13 +389,11 @@ function mapToRuntimeEvents(event: ProviderEvent): ReadonlyArray<ProviderRuntime
|
||||
if (event.method === "session/exited" || event.method === "session/closed") {
|
||||
return [
|
||||
{
|
||||
type: "session.exited",
|
||||
eventId: event.id,
|
||||
provider: event.provider,
|
||||
sessionId: event.sessionId,
|
||||
createdAt: event.createdAt,
|
||||
...(event.threadId ? { threadId: event.threadId } : {}),
|
||||
...(event.message ? { message: event.message } : {}),
|
||||
...base,
|
||||
type: "session.exited" as const,
|
||||
payload: {
|
||||
...(event.message ? { reason: event.message } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -357,12 +408,12 @@ function mapToRuntimeEvents(event: ProviderEvent): ReadonlyArray<ProviderRuntime
|
||||
}
|
||||
return [
|
||||
{
|
||||
type: "thread.started",
|
||||
eventId: event.id,
|
||||
provider: event.provider,
|
||||
sessionId: event.sessionId,
|
||||
createdAt: event.createdAt,
|
||||
threadId,
|
||||
...base,
|
||||
threadId: ThreadId.makeUnsafe(threadId),
|
||||
type: "thread.started" as const,
|
||||
payload: {
|
||||
providerThreadId: ProviderThreadId.makeUnsafe(threadId),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -376,47 +427,169 @@ function mapToRuntimeEvents(event: ProviderEvent): ReadonlyArray<ProviderRuntime
|
||||
}
|
||||
return [
|
||||
{
|
||||
type: "turn.started",
|
||||
eventId: event.id,
|
||||
provider: event.provider,
|
||||
sessionId: event.sessionId,
|
||||
createdAt: event.createdAt,
|
||||
...(event.threadId ? { threadId: event.threadId } : {}),
|
||||
turnId,
|
||||
...base,
|
||||
turnId: TurnId.makeUnsafe(turnId),
|
||||
type: "turn.started" as const,
|
||||
payload: {
|
||||
...(asString(turn?.model) ? { model: asString(turn?.model) } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "turn/completed") {
|
||||
const state = toTurnState(turn?.status) ?? ("completed" as const);
|
||||
return [
|
||||
{
|
||||
type: "turn.completed",
|
||||
eventId: event.id,
|
||||
provider: event.provider,
|
||||
sessionId: event.sessionId,
|
||||
createdAt: event.createdAt,
|
||||
...(event.threadId ? { threadId: event.threadId } : {}),
|
||||
...(event.turnId ? { turnId: event.turnId } : {}),
|
||||
...(toTurnStatus(turn?.status) ? { status: toTurnStatus(turn?.status) } : {}),
|
||||
...(asString(asObject(turn?.error)?.message)
|
||||
? { errorMessage: asString(asObject(turn?.error)?.message) }
|
||||
: {}),
|
||||
...base,
|
||||
type: "turn.completed" as const,
|
||||
payload: {
|
||||
state,
|
||||
...(asString(asObject(turn?.error)?.message)
|
||||
? { errorMessage: asString(asObject(turn?.error)?.message) }
|
||||
: {}),
|
||||
...(turn?.usage !== undefined ? { usage: turn.usage } : {}),
|
||||
...(turn?.costUsd !== undefined ? { totalCostUsd: asNumber(turn.costUsd) } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "item/agentMessage/delta" && event.textDelta && event.textDelta.length > 0) {
|
||||
if (event.method === "turn/plan/updated" && payload) {
|
||||
const explanation = asString(payload.explanation);
|
||||
const rawPlan = payload.plan;
|
||||
if (Array.isArray(rawPlan)) {
|
||||
const plan = rawPlan.map((step: unknown) => {
|
||||
const s = asObject(step);
|
||||
return {
|
||||
step: asString(s?.step) ?? "",
|
||||
status: (asString(s?.status) ?? "pending") as "pending" | "inProgress" | "completed",
|
||||
};
|
||||
});
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
type: "turn.plan.updated" as const,
|
||||
payload: {
|
||||
...(explanation !== undefined ? { explanation } : {}),
|
||||
plan,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
event.method === "item/agentMessage/delta" &&
|
||||
event.textDelta &&
|
||||
event.textDelta.length > 0
|
||||
) {
|
||||
return [
|
||||
{
|
||||
type: "message.delta",
|
||||
eventId: event.id,
|
||||
provider: event.provider,
|
||||
sessionId: event.sessionId,
|
||||
createdAt: event.createdAt,
|
||||
...(event.threadId ? { threadId: event.threadId } : {}),
|
||||
...(event.turnId ? { turnId: event.turnId } : {}),
|
||||
...(event.itemId ? { itemId: event.itemId } : {}),
|
||||
delta: event.textDelta,
|
||||
...base,
|
||||
type: "content.delta" as const,
|
||||
payload: {
|
||||
streamKind: "assistant_text" as const,
|
||||
delta: event.textDelta,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "item/reasoning/textDelta" && event.textDelta) {
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
type: "content.delta" as const,
|
||||
payload: {
|
||||
streamKind: "reasoning_text" as const,
|
||||
delta: event.textDelta,
|
||||
...(asNumber(payload?.contentIndex) !== undefined
|
||||
? { contentIndex: asNumber(payload?.contentIndex) }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "item/reasoning/summaryTextDelta" && event.textDelta) {
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
type: "content.delta" as const,
|
||||
payload: {
|
||||
streamKind: "reasoning_summary_text" as const,
|
||||
delta: event.textDelta,
|
||||
...(asNumber(payload?.summaryIndex) !== undefined
|
||||
? { summaryIndex: asNumber(payload?.summaryIndex) }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "item/plan/delta" && event.textDelta) {
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
type: "content.delta" as const,
|
||||
payload: {
|
||||
streamKind: "plan_text" as const,
|
||||
delta: event.textDelta,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "item/commandExecution/outputDelta" && event.textDelta) {
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
type: "content.delta" as const,
|
||||
payload: {
|
||||
streamKind: "command_output" as const,
|
||||
delta: event.textDelta,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "item/fileChange/outputDelta" && event.textDelta) {
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
type: "content.delta" as const,
|
||||
payload: {
|
||||
streamKind: "file_change_output" as const,
|
||||
delta: event.textDelta,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "item/mcpToolCall/progress") {
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
type: "runtime.warning" as const,
|
||||
payload: {
|
||||
message: "MCP tool call progress",
|
||||
detail: payload,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "error" && event.message) {
|
||||
return [
|
||||
{
|
||||
...base,
|
||||
type: "runtime.error" as const,
|
||||
payload: {
|
||||
message: event.message,
|
||||
class: "provider_error" as const,
|
||||
...(payload ? { detail: payload } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
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, type 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,
|
||||
@@ -64,7 +81,7 @@ layer("ProviderAdapterRegistryLive", (it) => {
|
||||
assert.equal(claude, fakeClaudeAdapter);
|
||||
|
||||
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) => {
|
||||
|
||||
@@ -17,7 +17,10 @@ import {
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
RuntimeItemId,
|
||||
RuntimeSessionId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { it, assert, vi } from "@effect/vitest";
|
||||
import { assertFailure } from "@effect/vitest/utils";
|
||||
@@ -51,6 +54,9 @@ const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId
|
||||
const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
||||
const asRuntimeSessionId = (value: string): RuntimeSessionId => RuntimeSessionId.makeUnsafe(value);
|
||||
const asRuntimeTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
const asRuntimeItemId = (value: string): RuntimeItemId => RuntimeItemId.makeUnsafe(value);
|
||||
|
||||
function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
|
||||
const sessions = new Map<ProviderSessionId, ProviderSession>();
|
||||
@@ -385,7 +391,6 @@ it.effect(
|
||||
{
|
||||
provider: "codex",
|
||||
cwd: "/tmp/project",
|
||||
resumeThreadId: startedSession.threadId,
|
||||
resumeCursor: startedSession.resumeCursor,
|
||||
},
|
||||
],
|
||||
@@ -495,7 +500,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
{
|
||||
provider: "codex",
|
||||
cwd: "/tmp/project",
|
||||
resumeThreadId: initial.threadId,
|
||||
resumeCursor: initial.resumeCursor,
|
||||
},
|
||||
],
|
||||
@@ -530,7 +534,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
{
|
||||
provider: "codex",
|
||||
cwd: "/tmp/project-send-turn",
|
||||
resumeThreadId: initial.threadId,
|
||||
resumeCursor: initial.resumeCursor,
|
||||
},
|
||||
],
|
||||
@@ -627,11 +630,11 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-1"),
|
||||
provider: "codex",
|
||||
sessionId: session.sessionId,
|
||||
sessionId: asRuntimeSessionId(session.sessionId),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asProviderThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
status: "completed",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asRuntimeTurnId("turn-1"),
|
||||
payload: { state: "completed" },
|
||||
};
|
||||
|
||||
fanout.codex.emit(completedEvent);
|
||||
@@ -662,43 +665,44 @@ 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,
|
||||
sessionId: asRuntimeSessionId(session.sessionId),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asProviderThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asRuntimeTurnId("turn-1"),
|
||||
itemId: asRuntimeItemId("item-seq-1"),
|
||||
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,
|
||||
sessionId: asRuntimeSessionId(session.sessionId),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asProviderThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asRuntimeTurnId("turn-1"),
|
||||
itemId: asRuntimeItemId("item-seq-1"),
|
||||
payload: { itemType: "command_execution", title: "Command run" },
|
||||
});
|
||||
fanout.codex.emit({
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-seq-3"),
|
||||
provider: "codex",
|
||||
sessionId: session.sessionId,
|
||||
sessionId: asRuntimeSessionId(session.sessionId),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asProviderThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
status: "completed",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asRuntimeTurnId("turn-1"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
yield* Fiber.join(consumer);
|
||||
const received = yield* Ref.get(receivedRef);
|
||||
assert.equal(received.length, 3);
|
||||
assert.deepEqual(
|
||||
received.map((event) => event.sessionSequence),
|
||||
[1, 2, 3],
|
||||
received.map((event) => event.type),
|
||||
["item.started", "item.completed", "turn.completed"],
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -728,36 +732,36 @@ 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,
|
||||
sessionId: asRuntimeSessionId(session.sessionId),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asProviderThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
detail: "echo one",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asRuntimeTurnId("turn-1"),
|
||||
itemId: asRuntimeItemId("item-ordered-1"),
|
||||
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,
|
||||
sessionId: asRuntimeSessionId(session.sessionId),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asProviderThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
delta: "hello",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asRuntimeTurnId("turn-1"),
|
||||
itemId: asRuntimeItemId("item-ordered-2"),
|
||||
payload: { streamKind: "assistant_text", delta: "hello" },
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
eventId: asEventId("evt-ordered-3"),
|
||||
provider: "codex",
|
||||
sessionId: session.sessionId,
|
||||
sessionId: asRuntimeSessionId(session.sessionId),
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: asProviderThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
status: "completed",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asRuntimeTurnId("turn-1"),
|
||||
payload: { state: "completed" },
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
import {
|
||||
NonNegativeInt,
|
||||
ProviderSessionId,
|
||||
RuntimeSessionId,
|
||||
ThreadId,
|
||||
ProviderInterruptTurnInput,
|
||||
ProviderRespondToRequestInput,
|
||||
@@ -116,10 +117,10 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
|
||||
const routedSessionAliasesRef = yield* Ref.make<Map<ProviderSessionId, ProviderSessionId>>(
|
||||
const routedSessionAliasesRef = yield* Ref.make<Map<RuntimeSessionId, RuntimeSessionId>>(
|
||||
new Map(),
|
||||
);
|
||||
const sessionRuntimeSequenceRef = yield* Ref.make<Map<ProviderSessionId, number>>(new Map());
|
||||
const sessionRuntimeSequenceRef = yield* Ref.make<Map<RuntimeSessionId, number>>(new Map());
|
||||
|
||||
const canonicalizeRuntimeEventSession = (
|
||||
event: ProviderRuntimeEvent,
|
||||
@@ -146,13 +147,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
const currentSequence = next.get(canonicalEvent.sessionId) ?? 0;
|
||||
const sessionSequence = currentSequence + 1;
|
||||
next.set(canonicalEvent.sessionId, sessionSequence);
|
||||
return [
|
||||
{
|
||||
...canonicalEvent,
|
||||
sessionSequence,
|
||||
} satisfies ProviderRuntimeEvent,
|
||||
next,
|
||||
] as const;
|
||||
return [canonicalEvent, next] as const;
|
||||
}),
|
||||
),
|
||||
Effect.tap((canonicalEvent) =>
|
||||
@@ -187,22 +182,27 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
return providerThreadId;
|
||||
});
|
||||
|
||||
const toRuntimeSessionId = (id: ProviderSessionId): RuntimeSessionId =>
|
||||
RuntimeSessionId.makeUnsafe(id);
|
||||
|
||||
const clearAliasKey = (staleSessionId: ProviderSessionId) =>
|
||||
Ref.update(routedSessionAliasesRef, (current) => {
|
||||
if (!current.has(staleSessionId)) {
|
||||
const key = toRuntimeSessionId(staleSessionId);
|
||||
if (!current.has(key)) {
|
||||
return current;
|
||||
}
|
||||
const next = new Map(current);
|
||||
next.delete(staleSessionId);
|
||||
next.delete(key);
|
||||
return next;
|
||||
});
|
||||
|
||||
const clearAliasesReferencing = (sessionId: ProviderSessionId) =>
|
||||
Ref.update(routedSessionAliasesRef, (current) => {
|
||||
const target = toRuntimeSessionId(sessionId);
|
||||
let changed = false;
|
||||
const next = new Map<ProviderSessionId, ProviderSessionId>();
|
||||
const next = new Map<RuntimeSessionId, RuntimeSessionId>();
|
||||
for (const [key, value] of current) {
|
||||
if (key === sessionId || value === sessionId) {
|
||||
if (key === target || value === target) {
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
@@ -213,22 +213,25 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
|
||||
const clearSessionSequence = (sessionId: ProviderSessionId) =>
|
||||
Ref.update(sessionRuntimeSequenceRef, (current) => {
|
||||
if (!current.has(sessionId)) {
|
||||
const key = toRuntimeSessionId(sessionId);
|
||||
if (!current.has(key)) {
|
||||
return current;
|
||||
}
|
||||
const next = new Map(current);
|
||||
next.delete(sessionId);
|
||||
next.delete(key);
|
||||
return next;
|
||||
});
|
||||
|
||||
const setAlias = (staleSessionId: ProviderSessionId, liveSessionId: ProviderSessionId) =>
|
||||
Ref.update(routedSessionAliasesRef, (current) => {
|
||||
const existing = current.get(staleSessionId);
|
||||
if (existing === liveSessionId) {
|
||||
const staleKey = toRuntimeSessionId(staleSessionId);
|
||||
const liveKey = toRuntimeSessionId(liveSessionId);
|
||||
const existing = current.get(staleKey);
|
||||
if (existing === liveKey) {
|
||||
return current;
|
||||
}
|
||||
const next = new Map(current);
|
||||
next.set(staleSessionId, liveSessionId);
|
||||
next.set(staleKey, liveKey);
|
||||
return next;
|
||||
});
|
||||
|
||||
@@ -303,7 +306,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) {
|
||||
@@ -378,14 +380,15 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
}
|
||||
|
||||
const alias = yield* Ref.get(routedSessionAliasesRef).pipe(
|
||||
Effect.map((aliases) => aliases.get(input.sessionId)),
|
||||
Effect.map((aliases) => aliases.get(toRuntimeSessionId(input.sessionId))),
|
||||
);
|
||||
if (alias) {
|
||||
const aliasIsActive = yield* adapter.hasSession(alias);
|
||||
const aliasSessionId = ProviderSessionId.makeUnsafe(alias);
|
||||
const aliasIsActive = yield* adapter.hasSession(aliasSessionId);
|
||||
if (aliasIsActive) {
|
||||
return {
|
||||
adapter,
|
||||
sessionId: alias,
|
||||
sessionId: aliasSessionId,
|
||||
isActive: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
@@ -1,132 +1,36 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
|
||||
import { AcpInitializeResult, AcpSessionNewResult, AcpPermissionRequestParams } from "./CursorAdapter.ts";
|
||||
import { Schema } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { CursorCliStreamEvent } 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",
|
||||
describe("CursorAdapter ACP schemas", () => {
|
||||
it("decodes AcpInitializeResult", () => {
|
||||
const decoded = Schema.decodeUnknownSync(AcpInitializeResult)({
|
||||
protocolVersion: 1,
|
||||
});
|
||||
|
||||
expect(decoded.type).toBe("system");
|
||||
if (decoded.type !== "system") {
|
||||
return;
|
||||
}
|
||||
expect(decoded.subtype).toBe("init");
|
||||
expect(decoded.session_id).toBe("sess-1");
|
||||
expect(decoded.protocolVersion).toBe(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,
|
||||
it("decodes AcpSessionNewResult", () => {
|
||||
const decoded = Schema.decodeUnknownSync(AcpSessionNewResult)({
|
||||
sessionId: "sess-1",
|
||||
});
|
||||
|
||||
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");
|
||||
expect(decoded.sessionId).toBe("sess-1");
|
||||
});
|
||||
|
||||
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",
|
||||
},
|
||||
},
|
||||
},
|
||||
it("decodes AcpPermissionRequestParams", () => {
|
||||
const decoded = Schema.decodeUnknownSync(AcpPermissionRequestParams)({
|
||||
sessionId: "sess-1",
|
||||
toolCall: {
|
||||
toolCallId: "tc-1",
|
||||
title: "Run command",
|
||||
kind: "shell",
|
||||
status: "pending",
|
||||
},
|
||||
options: [{ optionId: "allow", name: "Allow", kind: "accept" }],
|
||||
});
|
||||
|
||||
expect(decoded.type).toBe("tool_call");
|
||||
if (decoded.type !== "tool_call") {
|
||||
return;
|
||||
}
|
||||
expect(decoded.subtype).toBe("completed");
|
||||
expect(decoded.call_id).toContain("\n");
|
||||
});
|
||||
|
||||
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,
|
||||
},
|
||||
});
|
||||
|
||||
expect(decoded.type).toBe("result");
|
||||
if (decoded.type !== "result") {
|
||||
return;
|
||||
}
|
||||
expect(decoded.subtype).toBe("success");
|
||||
expect(decoded.is_error).toBe(false);
|
||||
});
|
||||
|
||||
it("decodes connection/retry lifecycle events", () => {
|
||||
const reconnecting = Schema.decodeUnknownSync(CursorCliStreamEvent)({
|
||||
type: "connection",
|
||||
subtype: "reconnecting",
|
||||
session_id: "sess-1",
|
||||
});
|
||||
expect(reconnecting.type).toBe("connection");
|
||||
|
||||
const retry = Schema.decodeUnknownSync(CursorCliStreamEvent)({
|
||||
type: "retry",
|
||||
subtype: "resuming",
|
||||
session_id: "sess-1",
|
||||
});
|
||||
expect(retry.type).toBe("retry");
|
||||
});
|
||||
|
||||
it("rejects unsupported stream event types", () => {
|
||||
expect(() =>
|
||||
Schema.decodeUnknownSync(CursorCliStreamEvent)({
|
||||
type: "bogus",
|
||||
session_id: "sess-1",
|
||||
}),
|
||||
).toThrow();
|
||||
expect(decoded.sessionId).toBe("sess-1");
|
||||
expect(decoded.toolCall.toolCallId).toBe("tc-1");
|
||||
expect(decoded.options).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,11 @@
|
||||
/**
|
||||
* CursorAdapter - Cursor CLI implementation of the generic provider adapter contract.
|
||||
* CursorAdapter - Cursor ACP (`agent 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 process / JSON-RPC 2.0 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.
|
||||
* ACP schemas for decode/validation of JSON-RPC messages are defined here so
|
||||
* the layer implementation can validate protocol boundary in a single place.
|
||||
*
|
||||
* @module CursorAdapter
|
||||
*/
|
||||
@@ -14,201 +14,101 @@ 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 AcpSessionId = Schema.String.check(Schema.isNonEmpty());
|
||||
export type AcpSessionId = typeof AcpSessionId.Type;
|
||||
|
||||
export const CursorCliTextContentPart = Schema.Struct({
|
||||
export const AcpTextContent = Schema.Struct({
|
||||
type: Schema.Literal("text"),
|
||||
text: Schema.String,
|
||||
});
|
||||
export type CursorCliTextContentPart = typeof CursorCliTextContentPart.Type;
|
||||
export type AcpTextContent = typeof AcpTextContent.Type;
|
||||
|
||||
export const CursorCliContentPart = Schema.Union([
|
||||
CursorCliTextContentPart,
|
||||
Schema.Struct({
|
||||
type: Schema.String,
|
||||
}),
|
||||
]);
|
||||
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 const CursorCliAssistantMessage = Schema.Struct({
|
||||
role: Schema.Literal("assistant"),
|
||||
content: Schema.Array(CursorCliContentPart),
|
||||
});
|
||||
export type CursorCliAssistantMessage = typeof CursorCliAssistantMessage.Type;
|
||||
|
||||
export const CursorCliToolCallResult = Schema.Struct({
|
||||
success: Schema.optional(Schema.Unknown),
|
||||
failure: Schema.optional(Schema.Unknown),
|
||||
rejected: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
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({
|
||||
export const AcpSessionMode = Schema.Struct({
|
||||
id: Schema.String,
|
||||
name: Schema.String,
|
||||
arguments: Schema.String,
|
||||
result: Schema.optional(CursorCliToolCallResult),
|
||||
description: Schema.optional(Schema.String),
|
||||
});
|
||||
export type CursorCliFunctionToolCall = typeof CursorCliFunctionToolCall.Type;
|
||||
export type AcpSessionMode = typeof AcpSessionMode.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 const AcpSessionModes = Schema.Struct({
|
||||
currentModeId: Schema.String,
|
||||
availableModes: Schema.Array(AcpSessionMode),
|
||||
});
|
||||
export type CursorCliToolCallPayload = typeof CursorCliToolCallPayload.Type;
|
||||
export type AcpSessionModes = typeof AcpSessionModes.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 const AcpInitializeResult = Schema.Struct({
|
||||
protocolVersion: Schema.Number,
|
||||
agentCapabilities: Schema.optional(Schema.Unknown),
|
||||
authMethods: Schema.optional(Schema.Array(Schema.Unknown)),
|
||||
});
|
||||
export type CursorCliTokenUsage = typeof CursorCliTokenUsage.Type;
|
||||
export type AcpInitializeResult = typeof AcpInitializeResult.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 const AcpSessionNewResult = Schema.Struct({
|
||||
sessionId: AcpSessionId,
|
||||
modes: Schema.optional(AcpSessionModes),
|
||||
});
|
||||
export type CursorCliSystemInitEvent = typeof CursorCliSystemInitEvent.Type;
|
||||
export type AcpSessionNewResult = typeof AcpSessionNewResult.Type;
|
||||
|
||||
export const CursorCliUserEvent = Schema.Struct({
|
||||
type: Schema.Literal("user"),
|
||||
message: CursorCliUserMessage,
|
||||
session_id: CursorCliSessionId,
|
||||
...CursorCliTimestampMs,
|
||||
export const AcpPromptResult = Schema.Struct({
|
||||
stopReason: Schema.optional(Schema.String),
|
||||
});
|
||||
export type CursorCliUserEvent = typeof CursorCliUserEvent.Type;
|
||||
export type AcpPromptResult = typeof AcpPromptResult.Type;
|
||||
|
||||
export const CursorCliAssistantEvent = Schema.Struct({
|
||||
type: Schema.Literal("assistant"),
|
||||
message: CursorCliAssistantMessage,
|
||||
session_id: CursorCliSessionId,
|
||||
...CursorCliTimestampMs,
|
||||
export const AcpPermissionOption = Schema.Struct({
|
||||
optionId: Schema.String,
|
||||
name: Schema.String,
|
||||
kind: Schema.optional(Schema.String),
|
||||
});
|
||||
export type CursorCliAssistantEvent = typeof CursorCliAssistantEvent.Type;
|
||||
export type AcpPermissionOption = typeof AcpPermissionOption.Type;
|
||||
|
||||
export const CursorCliThinkingDeltaEvent = Schema.Struct({
|
||||
type: Schema.Literal("thinking"),
|
||||
subtype: Schema.Literal("delta"),
|
||||
text: Schema.String,
|
||||
session_id: CursorCliSessionId,
|
||||
...CursorCliTimestampMs,
|
||||
export const AcpPermissionToolCall = Schema.Struct({
|
||||
toolCallId: Schema.String,
|
||||
title: Schema.optional(Schema.String),
|
||||
kind: Schema.optional(Schema.String),
|
||||
status: Schema.optional(Schema.String),
|
||||
content: Schema.optional(Schema.Array(Schema.Unknown)),
|
||||
});
|
||||
export type CursorCliThinkingDeltaEvent = typeof CursorCliThinkingDeltaEvent.Type;
|
||||
export type AcpPermissionToolCall = typeof AcpPermissionToolCall.Type;
|
||||
|
||||
export const CursorCliThinkingCompletedEvent = Schema.Struct({
|
||||
type: Schema.Literal("thinking"),
|
||||
subtype: Schema.Literal("completed"),
|
||||
session_id: CursorCliSessionId,
|
||||
...CursorCliTimestampMs,
|
||||
export const AcpPermissionRequestParams = Schema.Struct({
|
||||
sessionId: AcpSessionId,
|
||||
toolCall: AcpPermissionToolCall,
|
||||
options: Schema.Array(AcpPermissionOption),
|
||||
});
|
||||
export type CursorCliThinkingCompletedEvent = typeof CursorCliThinkingCompletedEvent.Type;
|
||||
export type AcpPermissionRequestParams = typeof AcpPermissionRequestParams.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 type AcpSessionUpdateType =
|
||||
| "available_commands_update"
|
||||
| "agent_thought_chunk"
|
||||
| "agent_message_chunk"
|
||||
| "tool_call"
|
||||
| "tool_call_update";
|
||||
|
||||
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 interface AcpSessionUpdate {
|
||||
readonly sessionUpdate: AcpSessionUpdateType | string;
|
||||
readonly content?: { type: string; text: string };
|
||||
readonly toolCallId?: string;
|
||||
readonly title?: string;
|
||||
readonly kind?: string;
|
||||
readonly status?: string;
|
||||
readonly rawInput?: unknown;
|
||||
readonly rawOutput?: unknown;
|
||||
readonly availableCommands?: ReadonlyArray<{ name: string; description: string }>;
|
||||
}
|
||||
|
||||
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 interface AcpJsonRpcMessage {
|
||||
readonly jsonrpc?: string;
|
||||
readonly id?: number;
|
||||
readonly method?: string;
|
||||
readonly params?: unknown;
|
||||
readonly result?: unknown;
|
||||
readonly error?: { code: number; message: string; data?: unknown };
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* CursorAdapterShape - Service API for the Cursor provider adapter.
|
||||
*
|
||||
* `provider` is intentionally narrowed to `"cursor"` here. Until contracts add
|
||||
* Cursor to `ProviderKind`, this shape is defined via `Omit<...,"provider">`.
|
||||
*/
|
||||
export interface CursorAdapterShape
|
||||
extends Omit<ProviderAdapterShape<ProviderAdapterError>, "provider"> {
|
||||
export interface CursorAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {
|
||||
readonly provider: "cursor";
|
||||
}
|
||||
|
||||
/**
|
||||
* CursorAdapter - Service tag for Cursor provider adapter operations.
|
||||
*/
|
||||
export class CursorAdapter extends ServiceMap.Service<CursorAdapter, CursorAdapterShape>()(
|
||||
"t3/provider/Services/CursorAdapter",
|
||||
) {}
|
||||
@@ -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),
|
||||
|
||||
@@ -16,10 +16,13 @@ import {
|
||||
EventId,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
ProviderItemId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
RuntimeItemId,
|
||||
RuntimeSessionId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
type WebSocketResponse,
|
||||
@@ -61,7 +64,10 @@ const asProviderSessionId = (value: string): ProviderSessionId =>
|
||||
ProviderSessionId.makeUnsafe(value);
|
||||
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||
const asProviderItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
||||
const asRuntimeSessionId = (value: string): RuntimeSessionId => RuntimeSessionId.makeUnsafe(value);
|
||||
const asRuntimeItemId = (value: string): RuntimeItemId => RuntimeItemId.makeUnsafe(value);
|
||||
const asRuntimeThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
||||
const asRuntimeTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
|
||||
const defaultOpenService: OpenShape = {
|
||||
openBrowser: () => Effect.void,
|
||||
@@ -1176,14 +1182,18 @@ describe("WebSocket Server", () => {
|
||||
});
|
||||
|
||||
emitRuntimeEvent({
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-ws-runtime-message-delta"),
|
||||
provider: "codex",
|
||||
sessionId,
|
||||
sessionId: asRuntimeSessionId(sessionId),
|
||||
createdAt: new Date().toISOString(),
|
||||
turnId: asProviderTurnId("turn-1"),
|
||||
itemId: asProviderItemId("item-1"),
|
||||
delta: "hello from runtime",
|
||||
threadId: asRuntimeThreadId("thread-1"),
|
||||
turnId: asRuntimeTurnId("turn-1"),
|
||||
itemId: asRuntimeItemId("item-1"),
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "hello from runtime",
|
||||
},
|
||||
});
|
||||
|
||||
const domainPush = await waitForPush(ws, ORCHESTRATION_WS_CHANNELS.domainEvent, (push) => {
|
||||
|
||||
@@ -2,17 +2,18 @@ import {
|
||||
type ApprovalRequestId,
|
||||
CURSOR_REASONING_OPTIONS,
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_REASONING,
|
||||
EDITORS,
|
||||
type EditorId,
|
||||
type KeybindingCommand,
|
||||
type CodexReasoningEffort,
|
||||
type CursorReasoningOption,
|
||||
type MessageId,
|
||||
getDefaultModel,
|
||||
getDefaultReasoningEffort,
|
||||
getCursorModelCapabilities,
|
||||
getCursorModelFamilyOptions,
|
||||
getModelOptions,
|
||||
getReasoningOptions,
|
||||
getReasoningEffortOptions,
|
||||
type ProjectId,
|
||||
type ProjectEntry,
|
||||
type ProjectScript,
|
||||
@@ -20,7 +21,6 @@ import {
|
||||
parseCursorModelSelection,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
type ReasoningEffort,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderKind,
|
||||
@@ -406,7 +406,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const [sendPhase, setSendPhase] = useState<SendPhase>("idle");
|
||||
const [isConnecting, _setIsConnecting] = useState(false);
|
||||
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
|
||||
const [selectedEffort, setSelectedEffort] = useState(DEFAULT_REASONING);
|
||||
const [selectedEffort, setSelectedEffort] = useState<CodexReasoningEffort>(
|
||||
getDefaultReasoningEffort("codex"),
|
||||
);
|
||||
const [envMode, setEnvMode] = useState<"local" | "worktree">("local");
|
||||
const [selectedProviderByThread, setSelectedProviderByThread] = useState<
|
||||
Partial<Record<ThreadId, ProviderKind>>
|
||||
@@ -478,7 +480,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
getDefaultModel(selectedProvider) ??
|
||||
DEFAULT_MODEL,
|
||||
);
|
||||
const reasoningOptions = getReasoningOptions(selectedProvider);
|
||||
const reasoningOptions = getReasoningEffortOptions(selectedProvider);
|
||||
const supportsReasoningEffort = reasoningOptions.length > 0;
|
||||
const selectedCursorModel = useMemo(
|
||||
() => (selectedProvider === "cursor" ? parseCursorModelSelection(selectedModel) : null),
|
||||
@@ -1829,7 +1831,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
[onProviderModelSelect, selectedModel, selectedProvider],
|
||||
);
|
||||
const onEffortSelect = useCallback(
|
||||
(effort: ReasoningEffort) => {
|
||||
(effort: CodexReasoningEffort) => {
|
||||
setSelectedEffort(effort);
|
||||
scheduleComposerFocus();
|
||||
},
|
||||
@@ -3231,10 +3233,12 @@ const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
});
|
||||
|
||||
const ReasoningEffortPicker = memo(function ReasoningEffortPicker(props: {
|
||||
effort: ReasoningEffort;
|
||||
options: ReadonlyArray<ReasoningEffort>;
|
||||
onEffortChange: (effort: ReasoningEffort) => void;
|
||||
effort: CodexReasoningEffort;
|
||||
options: ReadonlyArray<CodexReasoningEffort>;
|
||||
onEffortChange: (effort: CodexReasoningEffort) => void;
|
||||
}) {
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort("codex");
|
||||
|
||||
return (
|
||||
<Select
|
||||
value={props.effort}
|
||||
@@ -3247,7 +3251,7 @@ const ReasoningEffortPicker = memo(function ReasoningEffortPicker(props: {
|
||||
{props.options.map((effort) => (
|
||||
<SelectItem key={effort} value={effort}>
|
||||
{effort}
|
||||
{effort === DEFAULT_REASONING ? " (default)" : ""}
|
||||
{effort === defaultReasoningEffort ? " (default)" : ""}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
|
||||
@@ -36,6 +36,14 @@ export const ProviderTurnId = makeEntityId("ProviderTurnId");
|
||||
export type ProviderTurnId = typeof ProviderTurnId.Type;
|
||||
export const ProviderItemId = makeEntityId("ProviderItemId");
|
||||
export type ProviderItemId = typeof ProviderItemId.Type;
|
||||
export const RuntimeSessionId = makeEntityId("RuntimeSessionId");
|
||||
export type RuntimeSessionId = typeof RuntimeSessionId.Type;
|
||||
export const RuntimeItemId = makeEntityId("RuntimeItemId");
|
||||
export type RuntimeItemId = typeof RuntimeItemId.Type;
|
||||
export const RuntimeRequestId = makeEntityId("RuntimeRequestId");
|
||||
export type RuntimeRequestId = typeof RuntimeRequestId.Type;
|
||||
export const RuntimeTaskId = makeEntityId("RuntimeTaskId");
|
||||
export type RuntimeTaskId = typeof RuntimeTaskId.Type;
|
||||
export const ApprovalRequestId = makeEntityId("ApprovalRequestId");
|
||||
export type ApprovalRequestId = typeof ApprovalRequestId.Type;
|
||||
export const CheckpointRef = makeEntityId("CheckpointRef");
|
||||
|
||||
@@ -7,12 +7,14 @@ import {
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
MODEL_OPTIONS,
|
||||
MODEL_OPTIONS_BY_PROVIDER,
|
||||
REASONING_EFFORT_OPTIONS_BY_PROVIDER,
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER,
|
||||
getDefaultModel,
|
||||
getDefaultReasoningEffort,
|
||||
getCursorModelFamilyOptions,
|
||||
getModelOptions,
|
||||
getReasoningOptions,
|
||||
getReasoningEffortOptions,
|
||||
normalizeModelSlug,
|
||||
REASONING_OPTIONS,
|
||||
parseCursorModelSelection,
|
||||
resolveCursorModelFromSelection,
|
||||
resolveModelSlug,
|
||||
@@ -143,12 +145,32 @@ describe("cursor model selection", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("getReasoningOptions", () => {
|
||||
describe("getReasoningEffortOptions", () => {
|
||||
it("returns codex reasoning options for codex", () => {
|
||||
expect(getReasoningOptions("codex")).toEqual(REASONING_OPTIONS);
|
||||
expect(getReasoningEffortOptions("codex")).toEqual(
|
||||
REASONING_EFFORT_OPTIONS_BY_PROVIDER.codex,
|
||||
);
|
||||
});
|
||||
|
||||
it("returns no reasoning options for claudeCode", () => {
|
||||
expect(getReasoningOptions("claudeCode")).toEqual([]);
|
||||
expect(getReasoningEffortOptions("claudeCode")).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns no reasoning options for cursor", () => {
|
||||
expect(getReasoningEffortOptions("cursor")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getDefaultReasoningEffort", () => {
|
||||
it("returns provider-scoped defaults", () => {
|
||||
expect(getDefaultReasoningEffort("codex")).toBe(
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER.codex,
|
||||
);
|
||||
expect(getDefaultReasoningEffort("claudeCode")).toBe(
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER.claudeCode,
|
||||
);
|
||||
expect(getDefaultReasoningEffort("cursor")).toBe(
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER.cursor,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -491,18 +491,31 @@ export function resolveModelSlugForProvider(
|
||||
return resolveModelSlug(model, provider);
|
||||
}
|
||||
|
||||
export const REASONING_OPTIONS_BY_PROVIDER = {
|
||||
codex: ["xhigh", "high", "medium", "low"],
|
||||
const CODEX_REASONING_EFFORT_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
|
||||
export type CodexReasoningEffort = (typeof CODEX_REASONING_EFFORT_OPTIONS)[number];
|
||||
|
||||
export const REASONING_EFFORT_OPTIONS_BY_PROVIDER = {
|
||||
codex: CODEX_REASONING_EFFORT_OPTIONS,
|
||||
claudeCode: [],
|
||||
} as const satisfies Record<ProviderKind, readonly string[]>;
|
||||
cursor: [],
|
||||
} as const satisfies Record<ProviderKind, readonly CodexReasoningEffort[]>;
|
||||
|
||||
// Backward compatibility for existing Codex-only call sites.
|
||||
export const REASONING_OPTIONS = REASONING_OPTIONS_BY_PROVIDER.codex;
|
||||
export type ReasoningEffort = (typeof REASONING_OPTIONS_BY_PROVIDER.codex)[number];
|
||||
export const DEFAULT_REASONING: ReasoningEffort = "high";
|
||||
export const DEFAULT_REASONING_EFFORT_BY_PROVIDER = {
|
||||
codex: "high",
|
||||
claudeCode: null,
|
||||
cursor: null,
|
||||
} as const satisfies Record<ProviderKind, CodexReasoningEffort | null>;
|
||||
|
||||
export function getReasoningOptions(
|
||||
export function getReasoningEffortOptions(
|
||||
provider: ProviderKind = "codex",
|
||||
): ReadonlyArray<ReasoningEffort> {
|
||||
return REASONING_OPTIONS_BY_PROVIDER[provider] as ReadonlyArray<ReasoningEffort>;
|
||||
): ReadonlyArray<CodexReasoningEffort> {
|
||||
return REASONING_EFFORT_OPTIONS_BY_PROVIDER[provider];
|
||||
}
|
||||
|
||||
export function getDefaultReasoningEffort(provider: "codex"): CodexReasoningEffort;
|
||||
export function getDefaultReasoningEffort(provider: ProviderKind): CodexReasoningEffort | null;
|
||||
export function getDefaultReasoningEffort(
|
||||
provider: ProviderKind = "codex",
|
||||
): CodexReasoningEffort | null {
|
||||
return DEFAULT_REASONING_EFFORT_BY_PROVIDER[provider];
|
||||
}
|
||||
@@ -62,9 +62,16 @@ export const ClaudeCodeProviderStartOptions = Schema.Struct({
|
||||
});
|
||||
export type ClaudeCodeProviderStartOptions = typeof ClaudeCodeProviderStartOptions.Type;
|
||||
|
||||
export const CursorProviderStartOptions = Schema.Struct({
|
||||
binaryPath: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
authMethodId: 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;
|
||||
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Schema } from "effect";
|
||||
|
||||
import { ProviderRuntimeEvent } from "./providerRuntime";
|
||||
|
||||
const decodeRuntimeEvent = Schema.decodeUnknownSync(ProviderRuntimeEvent);
|
||||
|
||||
describe("ProviderRuntimeEvent", () => {
|
||||
it("decodes turn.plan.updated for plan rendering", () => {
|
||||
const parsed = decodeRuntimeEvent({
|
||||
type: "turn.plan.updated",
|
||||
eventId: "event-1",
|
||||
provider: "claudeCode",
|
||||
sessionId: "runtime-session-1",
|
||||
createdAt: "2026-02-28T00:00:00.000Z",
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
payload: {
|
||||
explanation: "Implement schema updates",
|
||||
plan: [
|
||||
{ step: "Define event union", status: "completed" },
|
||||
{ step: "Wire adapter mapping", status: "inProgress" },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(parsed.type).toBe("turn.plan.updated");
|
||||
if (parsed.type !== "turn.plan.updated") {
|
||||
throw new Error("expected turn.plan.updated");
|
||||
}
|
||||
expect(parsed.payload.plan).toHaveLength(2);
|
||||
expect(parsed.payload.plan[1]?.status).toBe("inProgress");
|
||||
});
|
||||
|
||||
it("decodes user-input.requested with structured questions", () => {
|
||||
const parsed = decodeRuntimeEvent({
|
||||
type: "user-input.requested",
|
||||
eventId: "event-2",
|
||||
provider: "claudeCode",
|
||||
sessionId: "runtime-session-2",
|
||||
createdAt: "2026-02-28T00:00:01.000Z",
|
||||
requestId: "request-1",
|
||||
payload: {
|
||||
questions: [
|
||||
{
|
||||
id: "sandbox_mode",
|
||||
header: "Sandbox",
|
||||
question: "Which mode should be used?",
|
||||
options: [
|
||||
{
|
||||
label: "workspace-write",
|
||||
description: "Allow edits in workspace only",
|
||||
},
|
||||
{
|
||||
label: "danger-full-access",
|
||||
description: "Allow unrestricted access",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(parsed.type).toBe("user-input.requested");
|
||||
if (parsed.type !== "user-input.requested") {
|
||||
throw new Error("expected user-input.requested");
|
||||
}
|
||||
expect(parsed.payload.questions[0]?.id).toBe("sandbox_mode");
|
||||
expect(parsed.payload.questions[0]?.options).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("decodes user-input.resolved with answer map", () => {
|
||||
const parsed = decodeRuntimeEvent({
|
||||
type: "user-input.resolved",
|
||||
eventId: "event-3",
|
||||
provider: "claudeCode",
|
||||
sessionId: "runtime-session-2",
|
||||
createdAt: "2026-02-28T00:00:02.000Z",
|
||||
requestId: "request-1",
|
||||
payload: {
|
||||
answers: {
|
||||
sandbox_mode: "workspace-write",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(parsed.type).toBe("user-input.resolved");
|
||||
if (parsed.type !== "user-input.resolved") {
|
||||
throw new Error("expected user-input.resolved");
|
||||
}
|
||||
expect(parsed.payload.answers.sandbox_mode).toBe("workspace-write");
|
||||
});
|
||||
|
||||
it("rejects legacy message.delta type", () => {
|
||||
expect(() =>
|
||||
decodeRuntimeEvent({
|
||||
type: "message.delta",
|
||||
eventId: "event-4",
|
||||
provider: "codex",
|
||||
sessionId: "runtime-session-3",
|
||||
createdAt: "2026-02-28T00:00:03.000Z",
|
||||
payload: { delta: "legacy" },
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("rejects empty branded canonical ids", () => {
|
||||
expect(() =>
|
||||
decodeRuntimeEvent({
|
||||
type: "runtime.error",
|
||||
eventId: "event-5",
|
||||
provider: "codex",
|
||||
sessionId: "runtime-session-3",
|
||||
createdAt: "2026-02-28T00:00:03.000Z",
|
||||
threadId: " ",
|
||||
payload: { message: "boom" },
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,226 +1,447 @@
|
||||
import { Schema } from "effect";
|
||||
import { TrimmedNonEmptyString } from "./baseSchemas";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
EventId,
|
||||
NonNegativeInt,
|
||||
IsoDateTime,
|
||||
ProviderItemId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
IsoDateTime,
|
||||
RuntimeItemId,
|
||||
RuntimeRequestId,
|
||||
RuntimeSessionId,
|
||||
ThreadId,
|
||||
TrimmedNonEmptyString,
|
||||
TurnId,
|
||||
} from "./baseSchemas";
|
||||
import { ProviderApprovalDecision, ProviderKind, ProviderRequestKind } from "./orchestration";
|
||||
import { ProviderKind } from "./orchestration";
|
||||
|
||||
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
|
||||
const UnknownRecordSchema = Schema.Record(Schema.String, Schema.Unknown);
|
||||
|
||||
export const ProviderRuntimeToolKind = Schema.Union([ProviderRequestKind, Schema.Literal("other")]);
|
||||
export type ProviderRuntimeToolKind = typeof ProviderRuntimeToolKind.Type;
|
||||
export const RuntimeEventRawSource = Schema.Literals([
|
||||
"codex.app-server.notification",
|
||||
"codex.app-server.request",
|
||||
"codex.eventmsg",
|
||||
"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;
|
||||
|
||||
export const ProviderRuntimeTurnStatus = Schema.Literals([
|
||||
export const RuntimeEventRaw = Schema.Struct({
|
||||
source: RuntimeEventRawSource,
|
||||
method: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
messageType: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
payload: Schema.Unknown,
|
||||
});
|
||||
export type RuntimeEventRaw = typeof RuntimeEventRaw.Type;
|
||||
|
||||
export const ProviderRequestId = TrimmedNonEmptyStringSchema;
|
||||
export type ProviderRequestId = typeof ProviderRequestId.Type;
|
||||
|
||||
export const ProviderRefs = Schema.Struct({
|
||||
providerSessionId: Schema.optional(ProviderSessionId),
|
||||
providerThreadId: Schema.optional(ProviderThreadId),
|
||||
providerTurnId: Schema.optional(ProviderTurnId),
|
||||
providerItemId: Schema.optional(ProviderItemId),
|
||||
providerRequestId: Schema.optional(ProviderRequestId),
|
||||
});
|
||||
export type ProviderRefs = typeof ProviderRefs.Type;
|
||||
|
||||
export const RuntimeTurnState = Schema.Literals([
|
||||
"completed",
|
||||
"failed",
|
||||
"cancelled",
|
||||
"interrupted",
|
||||
"cancelled",
|
||||
]);
|
||||
export type ProviderRuntimeTurnStatus = typeof ProviderRuntimeTurnStatus.Type;
|
||||
export type RuntimeTurnState = typeof RuntimeTurnState.Type;
|
||||
|
||||
export const ProviderRuntimeSessionStartedEvent = Schema.Struct({
|
||||
type: Schema.Literal("session.started"),
|
||||
export const RuntimePlanStepStatus = Schema.Literals(["pending", "inProgress", "completed"]);
|
||||
export type RuntimePlanStepStatus = typeof RuntimePlanStepStatus.Type;
|
||||
|
||||
export const RuntimeItemStatus = Schema.Literals(["inProgress", "completed", "failed", "declined"]);
|
||||
export type RuntimeItemStatus = typeof RuntimeItemStatus.Type;
|
||||
|
||||
export const RuntimeContentStreamKind = Schema.Literals([
|
||||
"assistant_text",
|
||||
"reasoning_text",
|
||||
"reasoning_summary_text",
|
||||
"plan_text",
|
||||
"command_output",
|
||||
"file_change_output",
|
||||
"unknown",
|
||||
]);
|
||||
export type RuntimeContentStreamKind = typeof RuntimeContentStreamKind.Type;
|
||||
|
||||
export const RuntimeSessionExitKind = Schema.Literals(["graceful", "error"]);
|
||||
export type RuntimeSessionExitKind = typeof RuntimeSessionExitKind.Type;
|
||||
|
||||
export const RuntimeErrorClass = Schema.Literals([
|
||||
"provider_error",
|
||||
"transport_error",
|
||||
"permission_error",
|
||||
"validation_error",
|
||||
"unknown",
|
||||
]);
|
||||
export type RuntimeErrorClass = typeof RuntimeErrorClass.Type;
|
||||
|
||||
export const CanonicalItemType = Schema.Literals([
|
||||
"user_message",
|
||||
"assistant_message",
|
||||
"reasoning",
|
||||
"plan",
|
||||
"command_execution",
|
||||
"file_change",
|
||||
"mcp_tool_call",
|
||||
"dynamic_tool_call",
|
||||
"collab_agent_tool_call",
|
||||
"web_search",
|
||||
"image_view",
|
||||
"review_entered",
|
||||
"review_exited",
|
||||
"context_compaction",
|
||||
"error",
|
||||
"unknown",
|
||||
]);
|
||||
export type CanonicalItemType = typeof CanonicalItemType.Type;
|
||||
|
||||
export const CanonicalRequestType = Schema.Literals([
|
||||
"command_execution_approval",
|
||||
"file_change_approval",
|
||||
"apply_patch_approval",
|
||||
"exec_command_approval",
|
||||
"tool_user_input",
|
||||
"dynamic_tool_call",
|
||||
"unknown",
|
||||
]);
|
||||
export type CanonicalRequestType = typeof CanonicalRequestType.Type;
|
||||
|
||||
export const ProviderRuntimeEventType = Schema.Literals([
|
||||
"session.started",
|
||||
"session.exited",
|
||||
"thread.started",
|
||||
"turn.started",
|
||||
"turn.completed",
|
||||
"turn.plan.updated",
|
||||
"item.started",
|
||||
"item.updated",
|
||||
"item.completed",
|
||||
"content.delta",
|
||||
"request.opened",
|
||||
"request.resolved",
|
||||
"user-input.requested",
|
||||
"user-input.resolved",
|
||||
"runtime.warning",
|
||||
"runtime.error",
|
||||
]);
|
||||
export type ProviderRuntimeEventType = typeof ProviderRuntimeEventType.Type;
|
||||
|
||||
export const SessionStartedType = Schema.Literal("session.started");
|
||||
export const SessionExitedType = Schema.Literal("session.exited");
|
||||
export const ThreadStartedType = Schema.Literal("thread.started");
|
||||
export const TurnStartedType = Schema.Literal("turn.started");
|
||||
export const TurnCompletedType = Schema.Literal("turn.completed");
|
||||
export const TurnPlanUpdatedType = Schema.Literal("turn.plan.updated");
|
||||
export const ItemStartedType = Schema.Literal("item.started");
|
||||
export const ItemUpdatedType = Schema.Literal("item.updated");
|
||||
export const ItemCompletedType = Schema.Literal("item.completed");
|
||||
export const ContentDeltaType = Schema.Literal("content.delta");
|
||||
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 RuntimeWarningType = Schema.Literal("runtime.warning");
|
||||
export const RuntimeErrorType = Schema.Literal("runtime.error");
|
||||
|
||||
export const ProviderRuntimeEventBase = Schema.Struct({
|
||||
eventId: EventId,
|
||||
provider: ProviderKind,
|
||||
sessionId: ProviderSessionId,
|
||||
sessionSequence: Schema.optional(NonNegativeInt),
|
||||
sessionId: RuntimeSessionId,
|
||||
createdAt: IsoDateTime,
|
||||
threadId: Schema.optional(ProviderThreadId),
|
||||
threadId: Schema.optional(ThreadId),
|
||||
turnId: Schema.optional(TurnId),
|
||||
itemId: Schema.optional(RuntimeItemId),
|
||||
requestId: Schema.optional(RuntimeRequestId),
|
||||
providerRefs: Schema.optional(ProviderRefs),
|
||||
raw: Schema.optional(RuntimeEventRaw),
|
||||
});
|
||||
export type ProviderRuntimeEventBase = typeof ProviderRuntimeEventBase.Type;
|
||||
|
||||
export const SessionStartedPayload = Schema.Struct({
|
||||
message: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
resume: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
export type SessionStartedPayload = typeof SessionStartedPayload.Type;
|
||||
|
||||
export const SessionExitedPayload = Schema.Struct({
|
||||
reason: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
recoverable: Schema.optional(Schema.Boolean),
|
||||
exitKind: Schema.optional(RuntimeSessionExitKind),
|
||||
});
|
||||
export type SessionExitedPayload = typeof SessionExitedPayload.Type;
|
||||
|
||||
export const ThreadStartedPayload = Schema.Struct({
|
||||
providerThreadId: Schema.optional(ProviderThreadId),
|
||||
});
|
||||
export type ThreadStartedPayload = typeof ThreadStartedPayload.Type;
|
||||
|
||||
export const TurnStartedPayload = Schema.Struct({
|
||||
model: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
effort: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
export type TurnStartedPayload = typeof TurnStartedPayload.Type;
|
||||
|
||||
export const TurnCompletedPayload = Schema.Struct({
|
||||
state: RuntimeTurnState,
|
||||
stopReason: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)),
|
||||
usage: Schema.optional(Schema.Unknown),
|
||||
modelUsage: Schema.optional(UnknownRecordSchema),
|
||||
totalCostUsd: Schema.optional(Schema.Number),
|
||||
errorMessage: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
export type TurnCompletedPayload = typeof TurnCompletedPayload.Type;
|
||||
|
||||
export const RuntimePlanStep = Schema.Struct({
|
||||
step: TrimmedNonEmptyStringSchema,
|
||||
status: RuntimePlanStepStatus,
|
||||
});
|
||||
export type RuntimePlanStep = typeof RuntimePlanStep.Type;
|
||||
|
||||
export const TurnPlanUpdatedPayload = Schema.Struct({
|
||||
explanation: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)),
|
||||
plan: Schema.Array(RuntimePlanStep),
|
||||
});
|
||||
export type TurnPlanUpdatedPayload = typeof TurnPlanUpdatedPayload.Type;
|
||||
|
||||
export const ItemLifecyclePayload = Schema.Struct({
|
||||
itemType: CanonicalItemType,
|
||||
status: Schema.optional(RuntimeItemStatus),
|
||||
title: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
detail: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
data: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
export type ItemLifecyclePayload = typeof ItemLifecyclePayload.Type;
|
||||
|
||||
export const ContentDeltaPayload = Schema.Struct({
|
||||
streamKind: RuntimeContentStreamKind,
|
||||
delta: Schema.String,
|
||||
contentIndex: Schema.optional(Schema.Int),
|
||||
summaryIndex: Schema.optional(Schema.Int),
|
||||
});
|
||||
export type ContentDeltaPayload = typeof ContentDeltaPayload.Type;
|
||||
|
||||
export const RequestOpenedPayload = Schema.Struct({
|
||||
requestType: CanonicalRequestType,
|
||||
detail: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
args: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
export type RequestOpenedPayload = typeof RequestOpenedPayload.Type;
|
||||
|
||||
export const RequestResolvedPayload = Schema.Struct({
|
||||
requestType: CanonicalRequestType,
|
||||
decision: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
resolution: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
export type RequestResolvedPayload = typeof RequestResolvedPayload.Type;
|
||||
|
||||
export const UserInputQuestionOption = Schema.Struct({
|
||||
label: TrimmedNonEmptyStringSchema,
|
||||
description: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
export type UserInputQuestionOption = typeof UserInputQuestionOption.Type;
|
||||
|
||||
export const UserInputQuestion = Schema.Struct({
|
||||
id: TrimmedNonEmptyStringSchema,
|
||||
header: TrimmedNonEmptyStringSchema,
|
||||
question: TrimmedNonEmptyStringSchema,
|
||||
options: Schema.Array(UserInputQuestionOption),
|
||||
});
|
||||
export type UserInputQuestion = typeof UserInputQuestion.Type;
|
||||
|
||||
export const UserInputRequestedPayload = Schema.Struct({
|
||||
questions: Schema.Array(UserInputQuestion),
|
||||
});
|
||||
export type UserInputRequestedPayload = typeof UserInputRequestedPayload.Type;
|
||||
|
||||
export const UserInputResolvedPayload = Schema.Struct({
|
||||
answers: UnknownRecordSchema,
|
||||
});
|
||||
export type UserInputResolvedPayload = typeof UserInputResolvedPayload.Type;
|
||||
|
||||
export const RuntimeWarningPayload = Schema.Struct({
|
||||
message: TrimmedNonEmptyStringSchema,
|
||||
detail: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
export type RuntimeWarningPayload = typeof RuntimeWarningPayload.Type;
|
||||
|
||||
export const RuntimeErrorPayload = Schema.Struct({
|
||||
message: TrimmedNonEmptyStringSchema,
|
||||
class: Schema.optional(RuntimeErrorClass),
|
||||
detail: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
export type RuntimeErrorPayload = typeof RuntimeErrorPayload.Type;
|
||||
|
||||
export const ProviderRuntimeSessionStartedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: SessionStartedType,
|
||||
payload: SessionStartedPayload,
|
||||
});
|
||||
export type ProviderRuntimeSessionStartedEvent = typeof ProviderRuntimeSessionStartedEvent.Type;
|
||||
|
||||
export const ProviderRuntimeSessionExitedEvent = Schema.Struct({
|
||||
type: Schema.Literal("session.exited"),
|
||||
eventId: EventId,
|
||||
provider: ProviderKind,
|
||||
sessionId: ProviderSessionId,
|
||||
sessionSequence: Schema.optional(NonNegativeInt),
|
||||
createdAt: IsoDateTime,
|
||||
threadId: Schema.optional(ProviderThreadId),
|
||||
message: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: SessionExitedType,
|
||||
payload: SessionExitedPayload,
|
||||
});
|
||||
export type ProviderRuntimeSessionExitedEvent = typeof ProviderRuntimeSessionExitedEvent.Type;
|
||||
|
||||
export const ProviderRuntimeThreadStartedEvent = Schema.Struct({
|
||||
type: Schema.Literal("thread.started"),
|
||||
eventId: EventId,
|
||||
provider: ProviderKind,
|
||||
sessionId: ProviderSessionId,
|
||||
sessionSequence: Schema.optional(NonNegativeInt),
|
||||
createdAt: IsoDateTime,
|
||||
threadId: ProviderThreadId,
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ThreadStartedType,
|
||||
payload: ThreadStartedPayload,
|
||||
});
|
||||
export type ProviderRuntimeThreadStartedEvent = typeof ProviderRuntimeThreadStartedEvent.Type;
|
||||
|
||||
export const ProviderRuntimeTurnStartedEvent = Schema.Struct({
|
||||
type: Schema.Literal("turn.started"),
|
||||
eventId: EventId,
|
||||
provider: ProviderKind,
|
||||
sessionId: ProviderSessionId,
|
||||
sessionSequence: Schema.optional(NonNegativeInt),
|
||||
createdAt: IsoDateTime,
|
||||
threadId: Schema.optional(ProviderThreadId),
|
||||
turnId: ProviderTurnId,
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: TurnStartedType,
|
||||
payload: TurnStartedPayload,
|
||||
});
|
||||
export type ProviderRuntimeTurnStartedEvent = typeof ProviderRuntimeTurnStartedEvent.Type;
|
||||
|
||||
export const ProviderRuntimeTurnCompletedEvent = Schema.Struct({
|
||||
type: Schema.Literal("turn.completed"),
|
||||
eventId: EventId,
|
||||
provider: ProviderKind,
|
||||
sessionId: ProviderSessionId,
|
||||
sessionSequence: Schema.optional(NonNegativeInt),
|
||||
createdAt: IsoDateTime,
|
||||
threadId: Schema.optional(ProviderThreadId),
|
||||
turnId: Schema.optional(ProviderTurnId),
|
||||
status: Schema.optional(ProviderRuntimeTurnStatus),
|
||||
errorMessage: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: TurnCompletedType,
|
||||
payload: TurnCompletedPayload,
|
||||
});
|
||||
export type ProviderRuntimeTurnCompletedEvent = typeof ProviderRuntimeTurnCompletedEvent.Type;
|
||||
|
||||
export const ProviderRuntimeMessageDeltaEvent = Schema.Struct({
|
||||
type: Schema.Literal("message.delta"),
|
||||
eventId: EventId,
|
||||
provider: ProviderKind,
|
||||
sessionId: ProviderSessionId,
|
||||
sessionSequence: Schema.optional(NonNegativeInt),
|
||||
createdAt: IsoDateTime,
|
||||
threadId: Schema.optional(ProviderThreadId),
|
||||
turnId: Schema.optional(ProviderTurnId),
|
||||
itemId: Schema.optional(ProviderItemId),
|
||||
delta: Schema.String,
|
||||
export const ProviderRuntimeTurnPlanUpdatedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: TurnPlanUpdatedType,
|
||||
payload: TurnPlanUpdatedPayload,
|
||||
});
|
||||
export type ProviderRuntimeMessageDeltaEvent = typeof ProviderRuntimeMessageDeltaEvent.Type;
|
||||
export type ProviderRuntimeTurnPlanUpdatedEvent = typeof ProviderRuntimeTurnPlanUpdatedEvent.Type;
|
||||
|
||||
export const ProviderRuntimeMessageCompletedEvent = Schema.Struct({
|
||||
type: Schema.Literal("message.completed"),
|
||||
eventId: EventId,
|
||||
provider: ProviderKind,
|
||||
sessionId: ProviderSessionId,
|
||||
sessionSequence: Schema.optional(NonNegativeInt),
|
||||
createdAt: IsoDateTime,
|
||||
itemId: ProviderItemId,
|
||||
threadId: Schema.optional(ProviderThreadId),
|
||||
turnId: Schema.optional(ProviderTurnId),
|
||||
export const ProviderRuntimeItemStartedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ItemStartedType,
|
||||
payload: ItemLifecyclePayload,
|
||||
});
|
||||
export type ProviderRuntimeMessageCompletedEvent = typeof ProviderRuntimeMessageCompletedEvent.Type;
|
||||
export type ProviderRuntimeItemStartedEvent = typeof ProviderRuntimeItemStartedEvent.Type;
|
||||
|
||||
export const ProviderRuntimeToolStartedEvent = Schema.Struct({
|
||||
type: Schema.Literal("tool.started"),
|
||||
eventId: EventId,
|
||||
provider: ProviderKind,
|
||||
sessionId: ProviderSessionId,
|
||||
sessionSequence: Schema.optional(NonNegativeInt),
|
||||
createdAt: IsoDateTime,
|
||||
threadId: Schema.optional(ProviderThreadId),
|
||||
turnId: Schema.optional(ProviderTurnId),
|
||||
itemId: Schema.optional(ProviderItemId),
|
||||
toolKind: ProviderRuntimeToolKind,
|
||||
title: TrimmedNonEmptyStringSchema,
|
||||
detail: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
export const ProviderRuntimeItemUpdatedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ItemUpdatedType,
|
||||
payload: ItemLifecyclePayload,
|
||||
});
|
||||
export type ProviderRuntimeToolStartedEvent = typeof ProviderRuntimeToolStartedEvent.Type;
|
||||
export type ProviderRuntimeItemUpdatedEvent = typeof ProviderRuntimeItemUpdatedEvent.Type;
|
||||
|
||||
export const ProviderRuntimeToolCompletedEvent = Schema.Struct({
|
||||
type: Schema.Literal("tool.completed"),
|
||||
eventId: EventId,
|
||||
provider: ProviderKind,
|
||||
sessionId: ProviderSessionId,
|
||||
sessionSequence: Schema.optional(NonNegativeInt),
|
||||
createdAt: IsoDateTime,
|
||||
threadId: Schema.optional(ProviderThreadId),
|
||||
turnId: Schema.optional(ProviderTurnId),
|
||||
itemId: Schema.optional(ProviderItemId),
|
||||
toolKind: ProviderRuntimeToolKind,
|
||||
title: TrimmedNonEmptyStringSchema,
|
||||
detail: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
export const ProviderRuntimeItemCompletedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ItemCompletedType,
|
||||
payload: ItemLifecyclePayload,
|
||||
});
|
||||
export type ProviderRuntimeToolCompletedEvent = typeof ProviderRuntimeToolCompletedEvent.Type;
|
||||
export type ProviderRuntimeItemCompletedEvent = typeof ProviderRuntimeItemCompletedEvent.Type;
|
||||
|
||||
export const ProviderRuntimeApprovalRequestedEvent = Schema.Struct({
|
||||
type: Schema.Literal("approval.requested"),
|
||||
eventId: EventId,
|
||||
provider: ProviderKind,
|
||||
sessionId: ProviderSessionId,
|
||||
sessionSequence: Schema.optional(NonNegativeInt),
|
||||
createdAt: IsoDateTime,
|
||||
threadId: Schema.optional(ProviderThreadId),
|
||||
turnId: Schema.optional(ProviderTurnId),
|
||||
itemId: Schema.optional(ProviderItemId),
|
||||
requestId: ApprovalRequestId,
|
||||
requestKind: ProviderRequestKind,
|
||||
detail: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
export const ProviderRuntimeContentDeltaEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ContentDeltaType,
|
||||
payload: ContentDeltaPayload,
|
||||
});
|
||||
export type ProviderRuntimeApprovalRequestedEvent =
|
||||
typeof ProviderRuntimeApprovalRequestedEvent.Type;
|
||||
export type ProviderRuntimeContentDeltaEvent = typeof ProviderRuntimeContentDeltaEvent.Type;
|
||||
|
||||
export const ProviderRuntimeApprovalResolvedEvent = Schema.Struct({
|
||||
type: Schema.Literal("approval.resolved"),
|
||||
eventId: EventId,
|
||||
provider: ProviderKind,
|
||||
sessionId: ProviderSessionId,
|
||||
sessionSequence: Schema.optional(NonNegativeInt),
|
||||
createdAt: IsoDateTime,
|
||||
threadId: Schema.optional(ProviderThreadId),
|
||||
turnId: Schema.optional(ProviderTurnId),
|
||||
itemId: Schema.optional(ProviderItemId),
|
||||
requestId: ApprovalRequestId,
|
||||
requestKind: Schema.optional(ProviderRequestKind),
|
||||
decision: Schema.optional(ProviderApprovalDecision),
|
||||
export const ProviderRuntimeRequestOpenedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: RequestOpenedType,
|
||||
payload: RequestOpenedPayload,
|
||||
});
|
||||
export type ProviderRuntimeApprovalResolvedEvent = typeof ProviderRuntimeApprovalResolvedEvent.Type;
|
||||
export type ProviderRuntimeRequestOpenedEvent = typeof ProviderRuntimeRequestOpenedEvent.Type;
|
||||
|
||||
export const ProviderRuntimeCheckpointCapturedEvent = Schema.Struct({
|
||||
type: Schema.Literal("checkpoint.captured"),
|
||||
eventId: EventId,
|
||||
provider: ProviderKind,
|
||||
sessionId: ProviderSessionId,
|
||||
sessionSequence: Schema.optional(NonNegativeInt),
|
||||
createdAt: IsoDateTime,
|
||||
threadId: ProviderThreadId,
|
||||
turnId: Schema.optional(ProviderTurnId),
|
||||
turnCount: NonNegativeInt,
|
||||
status: Schema.optional(ProviderRuntimeTurnStatus),
|
||||
export const ProviderRuntimeRequestResolvedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: RequestResolvedType,
|
||||
payload: RequestResolvedPayload,
|
||||
});
|
||||
export type ProviderRuntimeCheckpointCapturedEvent =
|
||||
typeof ProviderRuntimeCheckpointCapturedEvent.Type;
|
||||
export type ProviderRuntimeRequestResolvedEvent = typeof ProviderRuntimeRequestResolvedEvent.Type;
|
||||
|
||||
export const ProviderRuntimeUserInputRequestedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: UserInputRequestedType,
|
||||
payload: UserInputRequestedPayload,
|
||||
});
|
||||
export type ProviderRuntimeUserInputRequestedEvent =
|
||||
typeof ProviderRuntimeUserInputRequestedEvent.Type;
|
||||
|
||||
export const ProviderRuntimeUserInputResolvedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: UserInputResolvedType,
|
||||
payload: UserInputResolvedPayload,
|
||||
});
|
||||
export type ProviderRuntimeUserInputResolvedEvent =
|
||||
typeof ProviderRuntimeUserInputResolvedEvent.Type;
|
||||
|
||||
export const ProviderRuntimeWarningEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: RuntimeWarningType,
|
||||
payload: RuntimeWarningPayload,
|
||||
});
|
||||
export type ProviderRuntimeWarningEvent = typeof ProviderRuntimeWarningEvent.Type;
|
||||
|
||||
export const ProviderRuntimeErrorEvent = Schema.Struct({
|
||||
type: Schema.Literal("runtime.error"),
|
||||
eventId: EventId,
|
||||
provider: ProviderKind,
|
||||
sessionId: ProviderSessionId,
|
||||
sessionSequence: Schema.optional(NonNegativeInt),
|
||||
createdAt: IsoDateTime,
|
||||
threadId: Schema.optional(ProviderThreadId),
|
||||
turnId: Schema.optional(ProviderTurnId),
|
||||
itemId: Schema.optional(ProviderItemId),
|
||||
message: TrimmedNonEmptyStringSchema,
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: RuntimeErrorType,
|
||||
payload: RuntimeErrorPayload,
|
||||
});
|
||||
export type ProviderRuntimeErrorEvent = typeof ProviderRuntimeErrorEvent.Type;
|
||||
|
||||
export const ProviderRuntimeEvent = Schema.Union([
|
||||
export const ProviderRuntimeEventV2 = Schema.Union([
|
||||
ProviderRuntimeSessionStartedEvent,
|
||||
ProviderRuntimeSessionExitedEvent,
|
||||
ProviderRuntimeThreadStartedEvent,
|
||||
ProviderRuntimeTurnStartedEvent,
|
||||
ProviderRuntimeTurnCompletedEvent,
|
||||
ProviderRuntimeMessageDeltaEvent,
|
||||
ProviderRuntimeMessageCompletedEvent,
|
||||
ProviderRuntimeToolStartedEvent,
|
||||
ProviderRuntimeToolCompletedEvent,
|
||||
ProviderRuntimeApprovalRequestedEvent,
|
||||
ProviderRuntimeApprovalResolvedEvent,
|
||||
ProviderRuntimeCheckpointCapturedEvent,
|
||||
ProviderRuntimeTurnPlanUpdatedEvent,
|
||||
ProviderRuntimeItemStartedEvent,
|
||||
ProviderRuntimeItemUpdatedEvent,
|
||||
ProviderRuntimeItemCompletedEvent,
|
||||
ProviderRuntimeContentDeltaEvent,
|
||||
ProviderRuntimeRequestOpenedEvent,
|
||||
ProviderRuntimeRequestResolvedEvent,
|
||||
ProviderRuntimeUserInputRequestedEvent,
|
||||
ProviderRuntimeUserInputResolvedEvent,
|
||||
ProviderRuntimeWarningEvent,
|
||||
ProviderRuntimeErrorEvent,
|
||||
]);
|
||||
export type ProviderRuntimeEvent = typeof ProviderRuntimeEvent.Type;
|
||||
export type ProviderRuntimeEventV2 = typeof ProviderRuntimeEventV2.Type;
|
||||
|
||||
export const ProviderRuntimeEvent = ProviderRuntimeEventV2;
|
||||
export type ProviderRuntimeEvent = ProviderRuntimeEventV2;
|
||||
|
||||
export const ProviderRuntimeMessageDeltaEvent = ProviderRuntimeContentDeltaEvent;
|
||||
export type ProviderRuntimeMessageDeltaEvent = ProviderRuntimeContentDeltaEvent;
|
||||
export const ProviderRuntimeMessageCompletedEvent = ProviderRuntimeItemCompletedEvent;
|
||||
export type ProviderRuntimeMessageCompletedEvent = ProviderRuntimeItemCompletedEvent;
|
||||
export const ProviderRuntimeToolStartedEvent = ProviderRuntimeItemStartedEvent;
|
||||
export type ProviderRuntimeToolStartedEvent = ProviderRuntimeItemStartedEvent;
|
||||
export const ProviderRuntimeToolCompletedEvent = ProviderRuntimeItemCompletedEvent;
|
||||
export type ProviderRuntimeToolCompletedEvent = ProviderRuntimeItemCompletedEvent;
|
||||
export const ProviderRuntimeApprovalRequestedEvent = ProviderRuntimeRequestOpenedEvent;
|
||||
export type ProviderRuntimeApprovalRequestedEvent = ProviderRuntimeRequestOpenedEvent;
|
||||
export const ProviderRuntimeApprovalResolvedEvent = ProviderRuntimeRequestResolvedEvent;
|
||||
export type ProviderRuntimeApprovalResolvedEvent = ProviderRuntimeRequestResolvedEvent;
|
||||
|
||||
export const ProviderRuntimeToolKind = Schema.Literals([
|
||||
"command_execution",
|
||||
"file_change",
|
||||
"mcp_tool_call",
|
||||
"dynamic_tool_call",
|
||||
"other",
|
||||
]);
|
||||
export type ProviderRuntimeToolKind = typeof ProviderRuntimeToolKind.Type;
|
||||
|
||||
export const ProviderRuntimeTurnStatus = RuntimeTurnState;
|
||||
export type ProviderRuntimeTurnStatus = RuntimeTurnState;
|
||||
Reference in new issue
Block a user