feat(orchestration-v2): wire claude adapter primitives
Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
13ed2dbdca
commit
40747fff7b
70 files changed
+5309
-617
No files matched your search
@@ -0,0 +1,358 @@
|
||||
import {
|
||||
forkSession,
|
||||
query,
|
||||
type SDKAssistantMessage,
|
||||
type SDKMessage,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ProviderInstanceId, type ProviderReplayEntry } from "@t3tools/contracts";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Random from "effect/Random";
|
||||
|
||||
import {
|
||||
makeClaudeQueryOptions,
|
||||
makeClaudeUserMessage,
|
||||
type ClaudeAgentSdkQueryOptions,
|
||||
} from "../src/orchestration-v2/Adapters/ClaudeAdapterV2.ts";
|
||||
import { makeCheckpointWorkspace } from "../src/orchestration-v2/testkit/ReplayFixtureWorkspace.ts";
|
||||
|
||||
const SCENARIO = "thread_fork_native_fork_local_rollback";
|
||||
const DEFAULT_OUTPUT = new URL(
|
||||
"../src/orchestration-v2/testkit/fixtures/thread_fork_native_fork_local_rollback/claude_transcript.ndjson",
|
||||
import.meta.url,
|
||||
).pathname;
|
||||
const CLAUDE_PROVIDER = "claudeAgent" as const;
|
||||
const PROTOCOL = "claude-agent-sdk.query" as const;
|
||||
const MODEL_SELECTION = {
|
||||
instanceId: ProviderInstanceId.make(CLAUDE_PROVIDER),
|
||||
model: process.env.T3_CLAUDE_REPLAY_MODEL ?? "claude-sonnet-4-6",
|
||||
} as const;
|
||||
const SOURCE_PROMPT =
|
||||
"For this fork-local rollback fixture, respond with exactly: fork local source alpha";
|
||||
const FORK_FIRST_PROMPT =
|
||||
"For this fork-local rollback fixture, respond with exactly: fork local first";
|
||||
const FORK_SECOND_PROMPT =
|
||||
"For this fork-local rollback fixture, respond with exactly: fork local second";
|
||||
const FORK_AFTER_ROLLBACK_PROMPT =
|
||||
"Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content.";
|
||||
|
||||
class PromptQueue implements AsyncIterable<ReturnType<typeof makeClaudeUserMessage>> {
|
||||
readonly #items: Array<ReturnType<typeof makeClaudeUserMessage>> = [];
|
||||
readonly #waiters: Array<
|
||||
(value: IteratorResult<ReturnType<typeof makeClaudeUserMessage>>) => void
|
||||
> = [];
|
||||
#closed = false;
|
||||
|
||||
offer(message: ReturnType<typeof makeClaudeUserMessage>): void {
|
||||
const waiter = this.#waiters.shift();
|
||||
if (waiter !== undefined) {
|
||||
waiter({ done: false, value: message });
|
||||
return;
|
||||
}
|
||||
this.#items.push(message);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.#closed = true;
|
||||
for (const waiter of this.#waiters.splice(0)) {
|
||||
waiter({ done: true, value: undefined });
|
||||
}
|
||||
}
|
||||
|
||||
[Symbol.asyncIterator](): AsyncIterator<ReturnType<typeof makeClaudeUserMessage>> {
|
||||
return {
|
||||
next: () => {
|
||||
const value = this.#items.shift();
|
||||
if (value !== undefined) {
|
||||
return Promise.resolve({ done: false, value });
|
||||
}
|
||||
if (this.#closed) {
|
||||
return Promise.resolve({ done: true, value: undefined });
|
||||
}
|
||||
return new Promise((resolve) => this.#waiters.push(resolve));
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function readArgValue(name: string): string | undefined {
|
||||
const args = process.argv.slice(2);
|
||||
const index = args.indexOf(name);
|
||||
return index >= 0 ? args[index + 1] : undefined;
|
||||
}
|
||||
|
||||
function dirname(filePath: string): string {
|
||||
const normalized = filePath.replace(/\/+$/u, "");
|
||||
const lastSlash = normalized.lastIndexOf("/");
|
||||
if (lastSlash < 0) {
|
||||
return ".";
|
||||
}
|
||||
return lastSlash === 0 ? "/" : normalized.slice(0, lastSlash);
|
||||
}
|
||||
|
||||
function sanitizeValue(
|
||||
value: unknown,
|
||||
pathFragments: ReadonlyArray<readonly [string, string]>,
|
||||
): unknown {
|
||||
if (typeof value === "string") {
|
||||
return pathFragments.reduce(
|
||||
(sanitized, [actual, replacement]) =>
|
||||
actual.length === 0 ? sanitized : sanitized.split(actual).join(replacement),
|
||||
value,
|
||||
);
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((entry) => sanitizeValue(entry, pathFragments));
|
||||
}
|
||||
if (typeof value === "object" && value !== null) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(value).map(([key, entry]) => [key, sanitizeValue(entry, pathFragments)]),
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function stableOptions(options: ClaudeAgentSdkQueryOptions): ClaudeAgentSdkQueryOptions {
|
||||
const stable = {
|
||||
model: options.model,
|
||||
tools: options.tools,
|
||||
permissionMode: options.permissionMode,
|
||||
...(options.allowedTools === undefined ? {} : { allowedTools: options.allowedTools }),
|
||||
...(options.disallowedTools === undefined ? {} : { disallowedTools: options.disallowedTools }),
|
||||
...(options.settings === undefined ? {} : { settings: options.settings }),
|
||||
...(options.allowDangerouslySkipPermissions === true
|
||||
? { allowDangerouslySkipPermissions: true }
|
||||
: {}),
|
||||
...(options.resumeSessionAt === undefined ? {} : { resumeSessionAt: options.resumeSessionAt }),
|
||||
...(options.forkSession === true ? { forkSession: true } : {}),
|
||||
};
|
||||
return options.resume === undefined
|
||||
? { ...stable, sessionId: options.sessionId }
|
||||
: { ...stable, resume: options.resume };
|
||||
}
|
||||
|
||||
function queryOptions(input: {
|
||||
readonly cwd: string;
|
||||
readonly nativeThreadId: string;
|
||||
readonly resume: boolean;
|
||||
readonly resumeSessionAt?: string;
|
||||
}): ClaudeAgentSdkQueryOptions {
|
||||
return {
|
||||
...makeClaudeQueryOptions({
|
||||
modelSelection: MODEL_SELECTION,
|
||||
cwd: input.cwd,
|
||||
nativeThreadId: input.nativeThreadId,
|
||||
resume: input.resume,
|
||||
tools: { type: "preset", preset: "claude_code" },
|
||||
permissionMode: "bypassPermissions",
|
||||
allowDangerouslySkipPermissions: true,
|
||||
}),
|
||||
...(input.resumeSessionAt === undefined ? {} : { resumeSessionAt: input.resumeSessionAt }),
|
||||
};
|
||||
}
|
||||
|
||||
async function recordTurn(input: {
|
||||
readonly entries: Array<ProviderReplayEntry>;
|
||||
readonly iterator: AsyncIterator<SDKMessage>;
|
||||
readonly promptQueue: PromptQueue;
|
||||
readonly prompt: string;
|
||||
readonly label: string;
|
||||
readonly pathFragments: ReadonlyArray<readonly [string, string]>;
|
||||
}): Promise<SDKAssistantMessage["uuid"]> {
|
||||
const message = makeClaudeUserMessage({ text: input.prompt });
|
||||
input.entries.push({
|
||||
type: "expect_outbound",
|
||||
label: input.label,
|
||||
frame: { type: "prompt.offer", message },
|
||||
});
|
||||
input.promptQueue.offer(message);
|
||||
|
||||
let assistantMessageUuid: SDKAssistantMessage["uuid"] | null = null;
|
||||
while (true) {
|
||||
const next = await input.iterator.next();
|
||||
if (next.done === true) {
|
||||
throw new Error(`Claude query ended before ${input.label} completed.`);
|
||||
}
|
||||
const frame = sanitizeValue(next.value, input.pathFragments);
|
||||
input.entries.push({
|
||||
type: "emit_inbound",
|
||||
label: next.value.type,
|
||||
frame,
|
||||
});
|
||||
if (next.value.type === "assistant") {
|
||||
assistantMessageUuid = next.value.uuid;
|
||||
}
|
||||
if (next.value.type === "result") {
|
||||
if (assistantMessageUuid === null) {
|
||||
throw new Error(`Claude query completed ${input.label} without assistant UUID.`);
|
||||
}
|
||||
return assistantMessageUuid;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function encodeTranscript(input: {
|
||||
readonly entries: ReadonlyArray<ProviderReplayEntry>;
|
||||
readonly metadata: Record<string, unknown>;
|
||||
}): string {
|
||||
return [
|
||||
JSON.stringify({
|
||||
type: "transcript_start",
|
||||
provider: CLAUDE_PROVIDER,
|
||||
protocol: PROTOCOL,
|
||||
version: "0.2.111",
|
||||
scenario: SCENARIO,
|
||||
metadata: input.metadata,
|
||||
}),
|
||||
...input.entries.map((entry) => JSON.stringify(entry)),
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
const outputPath = readArgValue("--out") ?? DEFAULT_OUTPUT;
|
||||
const cwd =
|
||||
process.env.T3_CLAUDE_REPLAY_CWD ??
|
||||
(await makeCheckpointWorkspace(`claude-agent-sdk-record-${SCENARIO}`));
|
||||
const cwdRealPath = await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
return yield* fs.realPath(cwd);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
const pathFragments = [
|
||||
[cwd, `/tmp/claude-replay-${SCENARIO}`],
|
||||
[cwdRealPath, `/tmp/claude-replay-${SCENARIO}`],
|
||||
[process.env.HOME ?? "", "/home/replay-user"],
|
||||
] as const;
|
||||
const sessionId =
|
||||
process.env.T3_CLAUDE_REPLAY_SESSION_ID ?? (await Effect.runPromise(Random.nextUUIDv4));
|
||||
const entries: Array<ProviderReplayEntry> = [];
|
||||
const metadata: Record<string, unknown> = {
|
||||
prompts: [SOURCE_PROMPT, FORK_FIRST_PROMPT, FORK_SECOND_PROMPT, FORK_AFTER_ROLLBACK_PROMPT],
|
||||
model: MODEL_SELECTION.model,
|
||||
nativeSessionId: sessionId,
|
||||
queryMode: "fork_session_resume_at_fork_cursor",
|
||||
tools: "claude_code",
|
||||
permissionMode: "bypassPermissions",
|
||||
generatedBy: "probeClaudeForkLocalRollbackReplay",
|
||||
};
|
||||
|
||||
const sourceQueue = new PromptQueue();
|
||||
const sourceOptions = queryOptions({ cwd, nativeThreadId: sessionId, resume: false });
|
||||
entries.push({
|
||||
type: "expect_outbound",
|
||||
label: "query.open:source",
|
||||
frame: { type: "query.open", options: stableOptions(sourceOptions) },
|
||||
});
|
||||
const sourceRuntime = query({ prompt: sourceQueue, options: sourceOptions });
|
||||
try {
|
||||
const sourceCursor = await recordTurn({
|
||||
entries,
|
||||
iterator: sourceRuntime[Symbol.asyncIterator](),
|
||||
promptQueue: sourceQueue,
|
||||
prompt: SOURCE_PROMPT,
|
||||
label: "prompt.offer:source",
|
||||
pathFragments,
|
||||
});
|
||||
sourceQueue.close();
|
||||
sourceRuntime.close();
|
||||
entries.push({ type: "runtime_exit", status: "success" });
|
||||
|
||||
entries.push({
|
||||
type: "expect_outbound",
|
||||
label: "session.fork",
|
||||
frame: {
|
||||
type: "session.fork",
|
||||
sessionId,
|
||||
options: {
|
||||
dir: `/tmp/claude-replay-${SCENARIO}`,
|
||||
upToMessageId: sourceCursor,
|
||||
},
|
||||
},
|
||||
});
|
||||
const forked = await forkSession(sessionId, { dir: cwd, upToMessageId: sourceCursor });
|
||||
metadata.sourceAssistantMessageUuids = [sourceCursor];
|
||||
metadata.forkUpToMessageId = sourceCursor;
|
||||
metadata.forkedNativeSessionId = forked.sessionId;
|
||||
entries.push({
|
||||
type: "emit_inbound",
|
||||
label: "session.forked",
|
||||
frame: { type: "session.forked", sessionId: forked.sessionId },
|
||||
});
|
||||
|
||||
const forkQueue = new PromptQueue();
|
||||
const forkOptions = queryOptions({ cwd, nativeThreadId: forked.sessionId, resume: true });
|
||||
entries.push({
|
||||
type: "expect_outbound",
|
||||
label: "query.open:fork",
|
||||
frame: { type: "query.open", options: stableOptions(forkOptions) },
|
||||
});
|
||||
const forkRuntime = query({ prompt: forkQueue, options: forkOptions });
|
||||
const forkIterator = forkRuntime[Symbol.asyncIterator]();
|
||||
const forkFirstCursor = await recordTurn({
|
||||
entries,
|
||||
iterator: forkIterator,
|
||||
promptQueue: forkQueue,
|
||||
prompt: FORK_FIRST_PROMPT,
|
||||
label: "prompt.offer:fork-first",
|
||||
pathFragments,
|
||||
});
|
||||
const forkSecondCursor = await recordTurn({
|
||||
entries,
|
||||
iterator: forkIterator,
|
||||
promptQueue: forkQueue,
|
||||
prompt: FORK_SECOND_PROMPT,
|
||||
label: "prompt.offer:fork-second",
|
||||
pathFragments,
|
||||
});
|
||||
forkQueue.close();
|
||||
forkRuntime.close();
|
||||
entries.push({ type: "runtime_exit", status: "success" });
|
||||
metadata.forkAssistantMessageUuids = [forkFirstCursor, forkSecondCursor];
|
||||
metadata.resumeSessionAt = forkFirstCursor;
|
||||
|
||||
const resumedQueue = new PromptQueue();
|
||||
const resumedOptions = queryOptions({
|
||||
cwd,
|
||||
nativeThreadId: forked.sessionId,
|
||||
resume: true,
|
||||
resumeSessionAt: forkFirstCursor,
|
||||
});
|
||||
entries.push({
|
||||
type: "expect_outbound",
|
||||
label: "query.open:fork-resume-at-cursor",
|
||||
frame: { type: "query.open", options: stableOptions(resumedOptions) },
|
||||
});
|
||||
const resumedRuntime = query({ prompt: resumedQueue, options: resumedOptions });
|
||||
await recordTurn({
|
||||
entries,
|
||||
iterator: resumedRuntime[Symbol.asyncIterator](),
|
||||
promptQueue: resumedQueue,
|
||||
prompt: FORK_AFTER_ROLLBACK_PROMPT,
|
||||
label: "prompt.offer:fork-after-rollback",
|
||||
pathFragments,
|
||||
});
|
||||
resumedQueue.close();
|
||||
resumedRuntime.close();
|
||||
entries.push({ type: "runtime_exit", status: "success" });
|
||||
} catch (error) {
|
||||
sourceQueue.close();
|
||||
sourceRuntime.close();
|
||||
entries.push({
|
||||
type: "runtime_exit",
|
||||
status: "error",
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
|
||||
await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
yield* fs.makeDirectory(dirname(outputPath), { recursive: true });
|
||||
yield* fs.writeFileString(outputPath, encodeTranscript({ entries, metadata }));
|
||||
yield* Console.log(`Wrote ${entries.length} ${PROTOCOL} replay entries to ${outputPath}`);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
@@ -1,5 +1,8 @@
|
||||
import { mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
recordClaudeAgentSdkReplayTranscript,
|
||||
@@ -22,6 +25,15 @@ import {
|
||||
RESTRICTED_GRANULAR_POLICY,
|
||||
MULTI_TURN_SECOND_PROMPT,
|
||||
SIMPLE_PROMPT,
|
||||
SUBAGENT_PROMPT,
|
||||
THREAD_FORK_NATIVE_PRIOR_TURN_ALPHA_PROMPT,
|
||||
THREAD_FORK_NATIVE_PRIOR_TURN_BETA_PROMPT,
|
||||
THREAD_FORK_NATIVE_PRIOR_TURN_REPEAT_PROMPT,
|
||||
THREAD_FORK_NATIVE_SOURCE_PROMPT,
|
||||
THREAD_FORK_NATIVE_TARGET_PROMPT,
|
||||
THREAD_ROLLBACK_AFTER_PROMPT,
|
||||
THREAD_ROLLBACK_FIRST_PROMPT,
|
||||
THREAD_ROLLBACK_SECOND_PROMPT,
|
||||
TOOL_CALL_READ_ONLY_PROMPT,
|
||||
TOOL_CALL_READ_ONLY_WORKSPACE_ROOT,
|
||||
TOOL_CALL_WRITE_PROMPT,
|
||||
@@ -117,6 +129,38 @@ const CLAUDE_RECORDINGS = {
|
||||
queryMode: "streaming",
|
||||
enableTools: true,
|
||||
},
|
||||
subagent: {
|
||||
prompts: [SUBAGENT_PROMPT],
|
||||
defaultTranscriptFile: "fixtures/subagent/claude_transcript.ndjson",
|
||||
queryMode: "streaming",
|
||||
enableTools: true,
|
||||
},
|
||||
thread_rollback: {
|
||||
prompts: [
|
||||
THREAD_ROLLBACK_FIRST_PROMPT,
|
||||
THREAD_ROLLBACK_SECOND_PROMPT,
|
||||
THREAD_ROLLBACK_AFTER_PROMPT,
|
||||
],
|
||||
defaultTranscriptFile: "fixtures/thread_rollback/claude_transcript.ndjson",
|
||||
queryMode: "resume_at_cursor",
|
||||
enableTools: true,
|
||||
},
|
||||
thread_fork_native: {
|
||||
prompts: [THREAD_FORK_NATIVE_SOURCE_PROMPT, THREAD_FORK_NATIVE_TARGET_PROMPT],
|
||||
defaultTranscriptFile: "fixtures/thread_fork_native/claude_transcript.ndjson",
|
||||
queryMode: "fork_session",
|
||||
enableTools: true,
|
||||
},
|
||||
thread_fork_native_prior_turn: {
|
||||
prompts: [
|
||||
THREAD_FORK_NATIVE_PRIOR_TURN_ALPHA_PROMPT,
|
||||
THREAD_FORK_NATIVE_PRIOR_TURN_BETA_PROMPT,
|
||||
THREAD_FORK_NATIVE_PRIOR_TURN_REPEAT_PROMPT,
|
||||
],
|
||||
defaultTranscriptFile: "fixtures/thread_fork_native_prior_turn/claude_transcript.ndjson",
|
||||
queryMode: "fork_session_prior_turn",
|
||||
enableTools: true,
|
||||
},
|
||||
} as const;
|
||||
|
||||
function readArgValue(name: string): string | undefined {
|
||||
@@ -128,6 +172,9 @@ function readArgValue(name: string): string | undefined {
|
||||
type ClaudeRecordingQueryMode =
|
||||
| "streaming"
|
||||
| "restart"
|
||||
| "resume_at_cursor"
|
||||
| "fork_session"
|
||||
| "fork_session_prior_turn"
|
||||
| "active_steering"
|
||||
| "interrupt"
|
||||
| "interrupt_restart";
|
||||
@@ -140,6 +187,9 @@ function selectedQueryMode(defaultMode: ClaudeRecordingQueryMode): ClaudeRecordi
|
||||
if (
|
||||
raw === "streaming" ||
|
||||
raw === "restart" ||
|
||||
raw === "resume_at_cursor" ||
|
||||
raw === "fork_session" ||
|
||||
raw === "fork_session_prior_turn" ||
|
||||
raw === "active_steering" ||
|
||||
raw === "interrupt" ||
|
||||
raw === "interrupt_restart"
|
||||
@@ -147,12 +197,13 @@ function selectedQueryMode(defaultMode: ClaudeRecordingQueryMode): ClaudeRecordi
|
||||
return raw;
|
||||
}
|
||||
throw new Error(
|
||||
`Unsupported Claude replay query mode '${raw}'. Use 'streaming', 'restart', 'active_steering', 'interrupt', or 'interrupt_restart'.`,
|
||||
`Unsupported Claude replay query mode '${raw}'. Use 'streaming', 'restart', 'resume_at_cursor', 'fork_session', 'fork_session_prior_turn', 'active_steering', 'interrupt', or 'interrupt_restart'.`,
|
||||
);
|
||||
}
|
||||
|
||||
const scenario = readArgValue("--scenario") ?? process.env.T3_CLAUDE_REPLAY_SCENARIO ?? "simple";
|
||||
const recording = CLAUDE_RECORDINGS[scenario as keyof typeof CLAUDE_RECORDINGS];
|
||||
const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
|
||||
|
||||
if (recording === undefined) {
|
||||
throw new Error(
|
||||
@@ -179,6 +230,23 @@ function encodeTranscriptNdjson(
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function dirname(filePath: string): string {
|
||||
const normalized = filePath.replace(/\/+$/u, "");
|
||||
const lastSlash = normalized.lastIndexOf("/");
|
||||
if (lastSlash < 0) {
|
||||
return ".";
|
||||
}
|
||||
return lastSlash === 0 ? "/" : normalized.slice(0, lastSlash);
|
||||
}
|
||||
|
||||
function joinPath(directory: string, fileName: string): string {
|
||||
return `${directory.replace(/\/+$/u, "")}/${fileName.replace(/^\/+/u, "")}`;
|
||||
}
|
||||
|
||||
function runFileSystem<A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem>): Promise<A> {
|
||||
return Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
|
||||
}
|
||||
|
||||
function selectedPrompts(): ReadonlyArray<string> {
|
||||
if (process.env.T3_CLAUDE_REPLAY_PROMPTS !== undefined) {
|
||||
return process.env.T3_CLAUDE_REPLAY_PROMPTS.split("\n---\n").filter(
|
||||
@@ -212,8 +280,13 @@ function runtimePolicyForRecording(input: {
|
||||
}
|
||||
|
||||
async function makeToolCallReadOnlyRecordingWorkspace(): Promise<string> {
|
||||
await rm(TOOL_CALL_READ_ONLY_WORKSPACE_ROOT, { recursive: true, force: true });
|
||||
await mkdir(TOOL_CALL_READ_ONLY_WORKSPACE_ROOT, { recursive: true });
|
||||
await runFileSystem(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
yield* fs.remove(TOOL_CALL_READ_ONLY_WORKSPACE_ROOT, { recursive: true, force: true });
|
||||
yield* fs.makeDirectory(TOOL_CALL_READ_ONLY_WORKSPACE_ROOT, { recursive: true });
|
||||
}),
|
||||
);
|
||||
return TOOL_CALL_READ_ONLY_WORKSPACE_ROOT;
|
||||
}
|
||||
|
||||
@@ -224,34 +297,29 @@ const cwd =
|
||||
: await makeCheckpointWorkspace(`claude-agent-sdk-record-${scenario}`));
|
||||
const shouldRemoveCwd = process.env.T3_CLAUDE_REPLAY_CWD === undefined;
|
||||
|
||||
if (shouldRemoveCwd && scenario === "tool_call_read_only") {
|
||||
await writeFile(
|
||||
path.join(cwd, "package.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: "claude-read-only-fixture",
|
||||
private: true,
|
||||
scripts: { typecheck: "tsc --noEmit" },
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
"utf8",
|
||||
);
|
||||
await writeFile(
|
||||
path.join(cwd, "tsconfig.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
compilerOptions: {
|
||||
module: "ESNext",
|
||||
strict: true,
|
||||
target: "ES2022",
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
"utf8",
|
||||
if (shouldRemoveCwd && (scenario === "tool_call_read_only" || scenario === "subagent")) {
|
||||
await runFileSystem(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
yield* fs.writeFileString(
|
||||
joinPath(cwd, "package.json"),
|
||||
encodeUnknownJsonString({
|
||||
name: "claude-read-only-fixture",
|
||||
private: true,
|
||||
scripts: { typecheck: "tsc --noEmit" },
|
||||
}),
|
||||
);
|
||||
yield* fs.writeFileString(
|
||||
joinPath(cwd, "tsconfig.json"),
|
||||
encodeUnknownJsonString({
|
||||
compilerOptions: {
|
||||
module: "ESNext",
|
||||
strict: true,
|
||||
target: "ES2022",
|
||||
},
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -284,13 +352,25 @@ try {
|
||||
...(queryPolicy.installPermissionCallback ? { enablePermissionCallback: true } : {}),
|
||||
...("interruptAfter" in recording ? { interruptAfter: recording.interruptAfter } : {}),
|
||||
});
|
||||
await mkdir(path.dirname(outputPath), { recursive: true });
|
||||
await writeFile(outputPath, encodeTranscriptNdjson(transcript), "utf8");
|
||||
console.log(
|
||||
`Wrote ${transcript.entries.length} ${CLAUDE_AGENT_SDK_REPLAY_PROTOCOL} replay entries to ${outputPath}`,
|
||||
await runFileSystem(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
yield* fs.makeDirectory(dirname(outputPath), { recursive: true });
|
||||
yield* fs.writeFileString(outputPath, encodeTranscriptNdjson(transcript));
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
Console.log(
|
||||
`Wrote ${transcript.entries.length} ${CLAUDE_AGENT_SDK_REPLAY_PROTOCOL} replay entries to ${outputPath}`,
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
if (shouldRemoveCwd) {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
await runFileSystem(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
yield* fs.remove(cwd, { recursive: true, force: true });
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Deferred, FileSystem, Path, PlatformError } from "effect";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
@@ -238,7 +241,6 @@ function getTurnId(response: TurnStartResponse): string {
|
||||
|
||||
function readOnlyFullAccessSandbox(): SandboxPolicy {
|
||||
return {
|
||||
access: { type: "fullAccess" },
|
||||
networkAccess: false,
|
||||
type: "readOnly",
|
||||
};
|
||||
@@ -246,11 +248,6 @@ function readOnlyFullAccessSandbox(): SandboxPolicy {
|
||||
|
||||
function readOnlyRestrictedSandbox(): SandboxPolicy {
|
||||
return {
|
||||
access: {
|
||||
includePlatformDefaults: false,
|
||||
readableRoots: [],
|
||||
type: "restricted",
|
||||
},
|
||||
networkAccess: false,
|
||||
type: "readOnly",
|
||||
};
|
||||
@@ -259,7 +256,6 @@ function readOnlyRestrictedSandbox(): SandboxPolicy {
|
||||
function workspaceWriteSandbox(): SandboxPolicy {
|
||||
return {
|
||||
networkAccess: false,
|
||||
readOnlyAccess: { type: "fullAccess" },
|
||||
type: "workspaceWrite",
|
||||
writableRoots: [],
|
||||
};
|
||||
|
||||
@@ -1,17 +1,36 @@
|
||||
import { ProviderSessionId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
ClaudeSettings,
|
||||
MessageId,
|
||||
NodeId,
|
||||
ProviderInstanceId,
|
||||
ProviderSessionId,
|
||||
ProviderTurnId,
|
||||
RunAttemptId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import type { EventNdjsonLogger } from "../../provider/Layers/EventNdjsonLogger.ts";
|
||||
import { ProviderAdapterV2RuntimePolicy } from "../ProviderAdapter.ts";
|
||||
import {
|
||||
CLAUDE_AGENT_SDK_QUERY_PROTOCOL,
|
||||
CLAUDE_DEFAULT_INSTANCE_ID,
|
||||
CLAUDE_PROVIDER,
|
||||
CLAUDE_READ_ONLY_ALLOWED_TOOLS,
|
||||
ClaudeProviderCapabilitiesV2,
|
||||
claudeRuntimeQueryPolicyForRuntimePolicy,
|
||||
loggedClaudeQueryOptions,
|
||||
makeClaudeAdapterV2,
|
||||
makeClaudeAgentSdkProtocolLogger,
|
||||
type ClaudeAgentSdkQueryOptions,
|
||||
type ClaudeAgentSdkQueryOpenInput,
|
||||
} from "./ClaudeAdapterV2.ts";
|
||||
import { layer as idAllocatorLayer, IdAllocatorV2 } from "../IdAllocator.ts";
|
||||
|
||||
describe("ClaudeAdapterV2 runtime query policy", () => {
|
||||
it("maps canonical read-only never policy to Claude dontAsk with read-only tools", () => {
|
||||
@@ -201,3 +220,144 @@ describe("ClaudeAdapterV2 native protocol logging", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("ClaudeAdapterV2 native fork", () => {
|
||||
it("advertises Claude Agent SDK session forks", () => {
|
||||
assert.equal(ClaudeProviderCapabilitiesV2.threads.canForkThread, true);
|
||||
assert.equal(ClaudeProviderCapabilitiesV2.threads.canForkFromTurn, true);
|
||||
});
|
||||
|
||||
it.effect("forks at the source assistant cursor and resumes the forked session", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const idAllocator = yield* IdAllocatorV2;
|
||||
const openedQueries: Array<ClaudeAgentSdkQueryOpenInput> = [];
|
||||
const forkCalls: Array<{
|
||||
readonly sessionId: string;
|
||||
readonly options: unknown;
|
||||
readonly threadId: ThreadId;
|
||||
readonly providerSessionId: ProviderSessionId;
|
||||
}> = [];
|
||||
const adapter = makeClaudeAdapterV2({
|
||||
instanceId: CLAUDE_DEFAULT_INSTANCE_ID,
|
||||
settings: Schema.decodeSync(ClaudeSettings)({}),
|
||||
environment: {},
|
||||
idAllocator,
|
||||
queryRunner: {
|
||||
allocateSessionId: Effect.succeed("source-native-session"),
|
||||
open: (input) =>
|
||||
Effect.sync(() => {
|
||||
openedQueries.push(input);
|
||||
return {
|
||||
messages: Stream.empty,
|
||||
offer: () => Effect.void,
|
||||
setModel: () => Effect.void,
|
||||
interrupt: Effect.void,
|
||||
close: Effect.void,
|
||||
};
|
||||
}),
|
||||
forkSession: (input) =>
|
||||
Effect.sync(() => {
|
||||
forkCalls.push(input);
|
||||
return { sessionId: "forked-native-session" };
|
||||
}),
|
||||
assertComplete: Effect.void,
|
||||
},
|
||||
});
|
||||
const providerSessionId = ProviderSessionId.make("provider-session-claude-fork");
|
||||
const sourceThreadId = ThreadId.make("thread-claude-fork-source");
|
||||
const targetThreadId = ThreadId.make("thread-claude-fork-target");
|
||||
const runtime = yield* adapter.openSession({
|
||||
threadId: sourceThreadId,
|
||||
providerSessionId,
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make(CLAUDE_PROVIDER),
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
runtimePolicy: ProviderAdapterV2RuntimePolicy.make({
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
cwd: "/workspace",
|
||||
}),
|
||||
});
|
||||
const sourceProviderThread = yield* runtime.ensureThread({
|
||||
threadId: sourceThreadId,
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make(CLAUDE_PROVIDER),
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
runtimePolicy: ProviderAdapterV2RuntimePolicy.make({
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
cwd: "/workspace",
|
||||
}),
|
||||
});
|
||||
const now = yield* DateTime.now;
|
||||
const providerTurnId = ProviderTurnId.make("provider-turn-claude-source");
|
||||
const forkedProviderThread = yield* runtime.forkThread({
|
||||
sourceProviderThread,
|
||||
sourceProviderTurns: [
|
||||
{
|
||||
id: providerTurnId,
|
||||
providerThreadId: sourceProviderThread.id,
|
||||
nodeId: NodeId.make("node-claude-source"),
|
||||
runAttemptId: RunAttemptId.make("run-attempt-claude-source"),
|
||||
nativeTurnRef: {
|
||||
provider: CLAUDE_PROVIDER,
|
||||
nativeId: "assistant-message-cursor",
|
||||
strength: "weak",
|
||||
},
|
||||
ordinal: 1,
|
||||
status: "completed",
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
},
|
||||
],
|
||||
providerTurnId,
|
||||
targetThreadId,
|
||||
});
|
||||
|
||||
assert.deepEqual(forkCalls, [
|
||||
{
|
||||
sessionId: "source-native-session",
|
||||
options: {
|
||||
dir: "/workspace",
|
||||
upToMessageId: "assistant-message-cursor",
|
||||
},
|
||||
threadId: targetThreadId,
|
||||
providerSessionId,
|
||||
},
|
||||
]);
|
||||
assert.equal(forkedProviderThread.nativeThreadRef?.nativeId, "forked-native-session");
|
||||
assert.equal(forkedProviderThread.forkedFrom?.providerThreadId, sourceProviderThread.id);
|
||||
assert.equal(forkedProviderThread.forkedFrom?.providerTurnId, providerTurnId);
|
||||
|
||||
yield* runtime.startTurn({
|
||||
threadId: targetThreadId,
|
||||
runId: RunId.make("run-claude-fork-target"),
|
||||
runOrdinal: 1,
|
||||
attemptId: RunAttemptId.make("run-attempt-claude-fork-target"),
|
||||
rootNodeId: NodeId.make("node-claude-fork-target-root"),
|
||||
providerThread: forkedProviderThread,
|
||||
message: {
|
||||
messageId: MessageId.make("message-claude-fork-target"),
|
||||
text: "Respond with fork ok",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make(CLAUDE_PROVIDER),
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
runtimePolicy: ProviderAdapterV2RuntimePolicy.make({
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
cwd: "/workspace",
|
||||
}),
|
||||
});
|
||||
|
||||
assert.equal(openedQueries[0]?.options.resume, "forked-native-session");
|
||||
assert.equal(openedQueries[0]?.options.sessionId, undefined);
|
||||
}).pipe(Effect.provide(idAllocatorLayer)),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,9 +1,9 @@
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
forkSession,
|
||||
query,
|
||||
type CanUseTool,
|
||||
type PermissionResult,
|
||||
type SDKAssistantMessage,
|
||||
type SDKMessage,
|
||||
type SDKUserMessage,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
@@ -14,7 +14,12 @@ import {
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderReplayTranscript,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Random, Schema, Stream } from "effect";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Random from "effect/Random";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import {
|
||||
CLAUDE_PROVIDER,
|
||||
@@ -22,6 +27,7 @@ import {
|
||||
ClaudeAgentSdkQueryRunnerError,
|
||||
makeClaudeUserMessage,
|
||||
makeClaudeQueryOptions,
|
||||
type ClaudeAgentSdkSessionForkInput,
|
||||
type ClaudeAgentSdkQueryOpenInput,
|
||||
type ClaudeAgentSdkQueryOptions,
|
||||
type ClaudeAgentSdkQuerySession,
|
||||
@@ -189,15 +195,32 @@ interface ClaudePermissionResponseFrame {
|
||||
readonly result: PermissionResult;
|
||||
}
|
||||
|
||||
interface ClaudeSessionForkFrame {
|
||||
readonly type: "session.fork";
|
||||
readonly sessionId: string;
|
||||
readonly options: {
|
||||
readonly dir?: string;
|
||||
readonly upToMessageId?: string;
|
||||
readonly title?: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface ClaudeSessionForkedFrame {
|
||||
readonly type: "session.forked";
|
||||
readonly sessionId: string;
|
||||
}
|
||||
|
||||
type ClaudeOutboundFrame =
|
||||
| ClaudeQueryOpenFrame
|
||||
| ClaudePromptOfferFrame
|
||||
| ClaudeQuerySetModelFrame
|
||||
| ClaudeQueryInterruptFrame
|
||||
| ClaudePermissionResponseFrame;
|
||||
| ClaudePermissionResponseFrame
|
||||
| ClaudeSessionForkFrame;
|
||||
|
||||
interface ClaudeQueryRunner {
|
||||
readonly open: (input: ClaudeAgentSdkQueryOpenInput) => ClaudeAgentSdkQuerySession;
|
||||
readonly forkSession: (input: ClaudeAgentSdkSessionForkInput) => ClaudeSessionForkedFrame;
|
||||
readonly assertComplete: () => void;
|
||||
}
|
||||
|
||||
@@ -220,8 +243,16 @@ function sameFrame(left: unknown, right: unknown): boolean {
|
||||
}
|
||||
|
||||
function isClaudeSdkReplayMessage(frame: unknown): frame is SDKMessage {
|
||||
if (typeof frame !== "object" || frame === null) {
|
||||
return false;
|
||||
}
|
||||
const type = Reflect.get(frame, "type");
|
||||
return (
|
||||
typeof frame === "object" && frame !== null && typeof Reflect.get(frame, "type") === "string"
|
||||
type === "assistant" ||
|
||||
type === "user" ||
|
||||
type === "result" ||
|
||||
type === "system" ||
|
||||
type === "rate_limit_event"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -299,6 +330,8 @@ function stableClaudeQueryOptions(options: ClaudeAgentSdkQueryOptions): ClaudeAg
|
||||
...(options.allowDangerouslySkipPermissions === true
|
||||
? { allowDangerouslySkipPermissions: true }
|
||||
: {}),
|
||||
...(options.resumeSessionAt === undefined ? {} : { resumeSessionAt: options.resumeSessionAt }),
|
||||
...(options.forkSession === true ? { forkSession: true } : {}),
|
||||
};
|
||||
return options.resume === undefined
|
||||
? { ...stable, sessionId: options.sessionId }
|
||||
@@ -321,6 +354,23 @@ function makeClaudePromptOfferFrame(message: SDKUserMessage): ClaudePromptOfferF
|
||||
};
|
||||
}
|
||||
|
||||
function makeClaudeSessionForkFrame(
|
||||
input: ClaudeAgentSdkSessionForkInput,
|
||||
scenario: string,
|
||||
): ClaudeSessionForkFrame {
|
||||
return {
|
||||
type: "session.fork",
|
||||
sessionId: input.sessionId,
|
||||
options: {
|
||||
...(input.options.dir === undefined ? {} : { dir: sanitizedReplayCwd(scenario) }),
|
||||
...(input.options.upToMessageId === undefined
|
||||
? {}
|
||||
: { upToMessageId: input.options.upToMessageId }),
|
||||
...(input.options.title === undefined ? {} : { title: input.options.title }),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeReplayQueryRunner(transcript: ClaudeAgentSdkReplayTranscript): ClaudeQueryRunner {
|
||||
let cursor = 0;
|
||||
let failure: ClaudeAgentSdkReplayError | null = null;
|
||||
@@ -442,6 +492,48 @@ function makeReplayQueryRunner(transcript: ClaudeAgentSdkReplayTranscript): Clau
|
||||
advance();
|
||||
};
|
||||
|
||||
const assertNextForkedFrame = (): ClaudeSessionForkedFrame => {
|
||||
const entry = transcript.entries[cursor];
|
||||
if (entry === undefined) {
|
||||
return fail(
|
||||
new ClaudeReplayExhaustedError({
|
||||
scenario: transcript.scenario,
|
||||
cursor,
|
||||
actual: { type: "session.forked" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (entry.type !== "emit_inbound") {
|
||||
return fail(
|
||||
new ClaudeReplayUnexpectedOutboundError({
|
||||
scenario: transcript.scenario,
|
||||
cursor,
|
||||
expectedType: entry.type,
|
||||
actual: { type: "session.forked" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (
|
||||
typeof entry.frame !== "object" ||
|
||||
entry.frame === null ||
|
||||
Reflect.get(entry.frame, "type") !== "session.forked" ||
|
||||
typeof Reflect.get(entry.frame, "sessionId") !== "string"
|
||||
) {
|
||||
return fail(
|
||||
new ClaudeReplayFrameMismatchError({
|
||||
scenario: transcript.scenario,
|
||||
cursor,
|
||||
expected: { type: "session.forked" },
|
||||
actual: entry.frame,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const frame = entry.frame as ClaudeSessionForkedFrame;
|
||||
advance();
|
||||
return frame;
|
||||
};
|
||||
|
||||
const replayEffect = (tryEffect: () => void) =>
|
||||
Effect.try({
|
||||
try: tryEffect,
|
||||
@@ -473,6 +565,10 @@ function makeReplayQueryRunner(transcript: ClaudeAgentSdkReplayTranscript): Clau
|
||||
close: Effect.void,
|
||||
};
|
||||
},
|
||||
forkSession: (input) => {
|
||||
assertNextOutboundFrame(makeClaudeSessionForkFrame(input, transcript.scenario));
|
||||
return assertNextForkedFrame();
|
||||
},
|
||||
assertComplete: () => {
|
||||
if (failure !== null) {
|
||||
throw failure;
|
||||
@@ -539,6 +635,11 @@ const makeClaudeAgentSdkReplayQueryRunner = Effect.fn("ClaudeAgentSdkReplayQuery
|
||||
try: () => queryRunner.open(input),
|
||||
catch: (cause) => replayQueryRunnerError(transcript, cause),
|
||||
}),
|
||||
forkSession: (input) =>
|
||||
Effect.try({
|
||||
try: () => queryRunner.forkSession(input),
|
||||
catch: (cause) => replayQueryRunnerError(transcript, cause),
|
||||
}),
|
||||
assertComplete: Effect.try({
|
||||
try: () => queryRunner.assertComplete(),
|
||||
catch: (cause) => replayQueryRunnerError(transcript, cause),
|
||||
@@ -553,11 +654,52 @@ export function makeClaudeAgentSdkReplayQueryRunnerLayer(
|
||||
return Layer.effect(ClaudeAgentSdkQueryRunner, makeClaudeAgentSdkReplayQueryRunner(transcript));
|
||||
}
|
||||
|
||||
export function makeClaudeAgentSdkReplayLayer(
|
||||
transcript: ClaudeAgentSdkReplayTranscript,
|
||||
): Layer.Layer<ClaudeAgentSdkQueryRunner> {
|
||||
const queryRunner = makeReplayQueryRunner(transcript);
|
||||
return Layer.effect(
|
||||
ClaudeAgentSdkQueryRunner,
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
queryRunner.assertComplete();
|
||||
}),
|
||||
);
|
||||
|
||||
return ClaudeAgentSdkQueryRunner.of({
|
||||
allocateSessionId: Effect.succeed(nativeSessionIdFor(transcript)),
|
||||
open: (input) =>
|
||||
Effect.try({
|
||||
try: () => queryRunner.open(input),
|
||||
catch: (cause) => replayQueryRunnerError(transcript, cause),
|
||||
}),
|
||||
forkSession: (input) =>
|
||||
Effect.try({
|
||||
try: () => queryRunner.forkSession(input),
|
||||
catch: (cause) => replayQueryRunnerError(transcript, cause),
|
||||
}),
|
||||
assertComplete: Effect.try({
|
||||
try: () => queryRunner.assertComplete(),
|
||||
catch: (cause) => replayQueryRunnerError(transcript, cause),
|
||||
}),
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function makeClaudeProviderAdapterRegistryReplayLayer(
|
||||
transcript: ClaudeAgentSdkReplayTranscript,
|
||||
) {
|
||||
const adapterLayer = claudeAdapterLayer.pipe(
|
||||
Layer.provide(makeClaudeAgentSdkReplayQueryRunnerLayer(transcript)),
|
||||
return makeProviderAdapterRegistryDriverLayer({
|
||||
drivers: [ClaudeAdapterV2Driver],
|
||||
configMap: {
|
||||
[CLAUDE_DEFAULT_INSTANCE_ID]: {
|
||||
driver: CLAUDE_DRIVER_KIND,
|
||||
},
|
||||
},
|
||||
}).pipe(
|
||||
Layer.provide(makeClaudeAgentSdkReplayLayer(transcript)),
|
||||
Layer.provide(idAllocatorLayer),
|
||||
);
|
||||
return layerFromProviderAdapter.pipe(Layer.provide(adapterLayer));
|
||||
@@ -570,7 +712,7 @@ export async function replayClaudeAgentSdkTranscript(input: {
|
||||
readonly cwd?: string;
|
||||
}): Promise<ReadonlyArray<SDKMessage>> {
|
||||
return input.transcript.entries.flatMap((entry) =>
|
||||
entry.type === "emit_inbound" && !isClaudePermissionRequestFrame(entry.frame)
|
||||
entry.type === "emit_inbound" && isClaudeSdkReplayMessage(entry.frame)
|
||||
? [sdkMessageFromReplayFrame(entry.frame)]
|
||||
: [],
|
||||
);
|
||||
@@ -655,9 +797,19 @@ function sanitizedReplayCwd(scenario: string): string {
|
||||
return `/tmp/claude-replay-${scenario}`;
|
||||
}
|
||||
|
||||
function parentDirectory(input: string): string {
|
||||
const trimmed = input.replace(/\/+$/u, "");
|
||||
const lastSlash = trimmed.lastIndexOf("/");
|
||||
if (lastSlash <= 0) {
|
||||
return "/";
|
||||
}
|
||||
return trimmed.slice(0, lastSlash);
|
||||
}
|
||||
|
||||
function sanitizeReplayText(input: { readonly text: string; readonly scenario: string }): string {
|
||||
const sanitizedCwd = sanitizedReplayCwd(input.scenario);
|
||||
return [path.resolve(process.cwd(), "../.."), process.cwd()]
|
||||
const repoRoot = parentDirectory(parentDirectory(process.cwd()));
|
||||
return [repoRoot, process.cwd()]
|
||||
.toSorted((left, right) => right.length - left.length)
|
||||
.reduce((text, localPath) => text.replaceAll(localPath, sanitizedCwd), input.text);
|
||||
}
|
||||
@@ -785,6 +937,51 @@ async function recordMessagesUntilTurnResult(input: {
|
||||
}
|
||||
}
|
||||
|
||||
async function recordMessagesUntilTurnResultWithCursor(input: {
|
||||
readonly iterator: AsyncIterator<SDKMessage>;
|
||||
readonly entries: Array<ProviderReplayEntry>;
|
||||
readonly scenario: string;
|
||||
}): Promise<{
|
||||
readonly completed: boolean;
|
||||
readonly assistantMessageUuid: SDKAssistantMessage["uuid"] | null;
|
||||
}> {
|
||||
let assistantMessageUuid: SDKAssistantMessage["uuid"] | null = null;
|
||||
while (true) {
|
||||
const next = await input.iterator.next();
|
||||
if (next.done === true) {
|
||||
return { completed: false, assistantMessageUuid };
|
||||
}
|
||||
const replayMessage = sanitizeSdkMessageForReplay({
|
||||
message: next.value,
|
||||
scenario: input.scenario,
|
||||
});
|
||||
input.entries.push({
|
||||
type: "emit_inbound",
|
||||
label: replayMessage.type,
|
||||
frame: replayMessage,
|
||||
});
|
||||
if (replayMessage.type === "assistant") {
|
||||
assistantMessageUuid = replayMessage.uuid;
|
||||
}
|
||||
if (replayMessage.type === "result") {
|
||||
return { completed: true, assistantMessageUuid };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function requireAssistantCursor(input: {
|
||||
readonly scenario: string;
|
||||
readonly promptIndex: number;
|
||||
readonly cursor: SDKAssistantMessage["uuid"] | null;
|
||||
}): SDKAssistantMessage["uuid"] {
|
||||
if (input.cursor !== null) {
|
||||
return input.cursor;
|
||||
}
|
||||
throw new Error(
|
||||
`Claude replay scenario ${input.scenario} prompt ${input.promptIndex} completed without an SDKAssistantMessage.uuid cursor.`,
|
||||
);
|
||||
}
|
||||
|
||||
async function recordMessagesUntilTurnResults(input: {
|
||||
readonly iterator: AsyncIterator<SDKMessage>;
|
||||
readonly entries: Array<ProviderReplayEntry>;
|
||||
@@ -1205,6 +1402,342 @@ async function recordClaudeRestartingQueries(input: {
|
||||
}
|
||||
}
|
||||
|
||||
async function recordClaudeResumeAtCursorQuery(input: {
|
||||
readonly scenario: string;
|
||||
readonly prompts: ReadonlyArray<string>;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly cwd: string;
|
||||
readonly sessionId: string;
|
||||
readonly entries: Array<ProviderReplayEntry>;
|
||||
readonly metadata: Record<string, unknown>;
|
||||
readonly enableTools?: boolean;
|
||||
readonly tools?: ClaudeAgentSdkQueryTools;
|
||||
readonly permissionMode?: ClaudeAgentSdkQueryOptions["permissionMode"];
|
||||
readonly allowedTools?: ReadonlyArray<string>;
|
||||
readonly disallowedTools?: ReadonlyArray<string>;
|
||||
readonly allowDangerouslySkipPermissions?: boolean;
|
||||
}): Promise<void> {
|
||||
if (input.prompts.length !== 3) {
|
||||
throw new Error(
|
||||
`Claude resume-at-cursor replay scenario ${input.scenario} requires exactly three prompts.`,
|
||||
);
|
||||
}
|
||||
|
||||
const sourcePromptQueue = new RecordingPromptQueue();
|
||||
const sourceOptions = makeClaudeQueryOptions({
|
||||
modelSelection: input.modelSelection,
|
||||
nativeThreadId: input.sessionId,
|
||||
resume: false,
|
||||
cwd: input.cwd,
|
||||
...(input.enableTools === true
|
||||
? {
|
||||
tools: input.tools ?? { type: "preset", preset: "claude_code" },
|
||||
permissionMode: input.permissionMode ?? "default",
|
||||
...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }),
|
||||
...(input.disallowedTools === undefined
|
||||
? {}
|
||||
: { disallowedTools: input.disallowedTools }),
|
||||
...(input.allowDangerouslySkipPermissions === true
|
||||
? { allowDangerouslySkipPermissions: true }
|
||||
: {}),
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
|
||||
input.entries.push({
|
||||
type: "expect_outbound",
|
||||
label: "query.open:source",
|
||||
frame: makeClaudeQueryOpenFrame({ options: sourceOptions }),
|
||||
});
|
||||
const sourceRuntime = query({
|
||||
prompt: sourcePromptQueue,
|
||||
options: sourceOptions,
|
||||
});
|
||||
const sourceIterator = sourceRuntime[Symbol.asyncIterator]();
|
||||
|
||||
try {
|
||||
const sourceCursors: Array<SDKAssistantMessage["uuid"]> = [];
|
||||
for (const [index, prompt] of input.prompts.slice(0, 2).entries()) {
|
||||
const message = makeClaudeUserMessage({ text: prompt });
|
||||
input.entries.push({
|
||||
type: "expect_outbound",
|
||||
label: `prompt.offer:${index + 1}`,
|
||||
frame: makeClaudePromptOfferFrame(message),
|
||||
});
|
||||
sourcePromptQueue.offer(message);
|
||||
const result = await recordMessagesUntilTurnResultWithCursor({
|
||||
iterator: sourceIterator,
|
||||
entries: input.entries,
|
||||
scenario: input.scenario,
|
||||
});
|
||||
if (!result.completed) {
|
||||
throw new Error(`Claude source query ended before prompt ${index + 1} completed.`);
|
||||
}
|
||||
sourceCursors.push(
|
||||
requireAssistantCursor({
|
||||
scenario: input.scenario,
|
||||
promptIndex: index + 1,
|
||||
cursor: result.assistantMessageUuid,
|
||||
}),
|
||||
);
|
||||
}
|
||||
sourcePromptQueue.close();
|
||||
sourceRuntime.close();
|
||||
input.entries.push({
|
||||
type: "runtime_exit",
|
||||
status: "success",
|
||||
});
|
||||
|
||||
const resumeSessionAt = sourceCursors[0]!;
|
||||
input.metadata.resumeSessionAt = resumeSessionAt;
|
||||
input.metadata.sourceAssistantMessageUuids = sourceCursors;
|
||||
|
||||
const resumedPromptQueue = new RecordingPromptQueue();
|
||||
const resumedOptions = {
|
||||
...makeClaudeQueryOptions({
|
||||
modelSelection: input.modelSelection,
|
||||
nativeThreadId: input.sessionId,
|
||||
resume: true,
|
||||
cwd: input.cwd,
|
||||
...(input.enableTools === true
|
||||
? {
|
||||
tools: input.tools ?? { type: "preset", preset: "claude_code" },
|
||||
permissionMode: input.permissionMode ?? "default",
|
||||
...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }),
|
||||
...(input.disallowedTools === undefined
|
||||
? {}
|
||||
: { disallowedTools: input.disallowedTools }),
|
||||
...(input.allowDangerouslySkipPermissions === true
|
||||
? { allowDangerouslySkipPermissions: true }
|
||||
: {}),
|
||||
}
|
||||
: {}),
|
||||
}),
|
||||
resumeSessionAt,
|
||||
} satisfies ClaudeAgentSdkQueryOptions;
|
||||
input.entries.push({
|
||||
type: "expect_outbound",
|
||||
label: "query.open:resume_at_cursor",
|
||||
frame: makeClaudeQueryOpenFrame({ options: resumedOptions }),
|
||||
});
|
||||
const resumedMessage = makeClaudeUserMessage({ text: input.prompts[2]! });
|
||||
input.entries.push({
|
||||
type: "expect_outbound",
|
||||
label: "prompt.offer:3",
|
||||
frame: makeClaudePromptOfferFrame(resumedMessage),
|
||||
});
|
||||
|
||||
const resumedRuntime = query({
|
||||
prompt: resumedPromptQueue,
|
||||
options: resumedOptions,
|
||||
});
|
||||
resumedPromptQueue.offer(resumedMessage);
|
||||
resumedPromptQueue.close();
|
||||
const resumedIterator = resumedRuntime[Symbol.asyncIterator]();
|
||||
await recordMessagesUntilIteratorDone({
|
||||
iterator: resumedIterator,
|
||||
entries: input.entries,
|
||||
scenario: input.scenario,
|
||||
});
|
||||
resumedRuntime.close();
|
||||
input.entries.push({
|
||||
type: "runtime_exit",
|
||||
status: "success",
|
||||
});
|
||||
} catch (error) {
|
||||
sourcePromptQueue.close();
|
||||
sourceRuntime.close();
|
||||
input.entries.push({
|
||||
type: "runtime_exit",
|
||||
status: "error",
|
||||
error: serializeReplayError(error, input.scenario),
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function recordClaudeForkSessionQuery(input: {
|
||||
readonly scenario: string;
|
||||
readonly prompts: ReadonlyArray<string>;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly cwd: string;
|
||||
readonly sessionId: string;
|
||||
readonly entries: Array<ProviderReplayEntry>;
|
||||
readonly metadata: Record<string, unknown>;
|
||||
readonly forkFromPromptIndex?: 1 | 2;
|
||||
readonly enableTools?: boolean;
|
||||
readonly tools?: ClaudeAgentSdkQueryTools;
|
||||
readonly permissionMode?: ClaudeAgentSdkQueryOptions["permissionMode"];
|
||||
readonly allowedTools?: ReadonlyArray<string>;
|
||||
readonly disallowedTools?: ReadonlyArray<string>;
|
||||
readonly allowDangerouslySkipPermissions?: boolean;
|
||||
}): Promise<void> {
|
||||
if (input.prompts.length < 2) {
|
||||
throw new Error(
|
||||
`Claude fork-session replay scenario ${input.scenario} requires at least two prompts.`,
|
||||
);
|
||||
}
|
||||
const sourcePromptCount = input.prompts.length - 1;
|
||||
const forkFromPromptIndex = input.forkFromPromptIndex ?? sourcePromptCount;
|
||||
if (forkFromPromptIndex > sourcePromptCount) {
|
||||
throw new Error(
|
||||
`Claude fork-session replay scenario ${input.scenario} cannot fork from prompt ${forkFromPromptIndex} after recording ${sourcePromptCount} source prompts.`,
|
||||
);
|
||||
}
|
||||
|
||||
const sourcePromptQueue = new RecordingPromptQueue();
|
||||
const sourceOptions = makeClaudeQueryOptions({
|
||||
modelSelection: input.modelSelection,
|
||||
nativeThreadId: input.sessionId,
|
||||
resume: false,
|
||||
cwd: input.cwd,
|
||||
...(input.enableTools === true
|
||||
? {
|
||||
tools: input.tools ?? { type: "preset", preset: "claude_code" },
|
||||
permissionMode: input.permissionMode ?? "default",
|
||||
...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }),
|
||||
...(input.disallowedTools === undefined
|
||||
? {}
|
||||
: { disallowedTools: input.disallowedTools }),
|
||||
...(input.allowDangerouslySkipPermissions === true
|
||||
? { allowDangerouslySkipPermissions: true }
|
||||
: {}),
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
input.entries.push({
|
||||
type: "expect_outbound",
|
||||
label: "query.open:source",
|
||||
frame: makeClaudeQueryOpenFrame({ options: sourceOptions }),
|
||||
});
|
||||
const sourceRuntime = query({
|
||||
prompt: sourcePromptQueue,
|
||||
options: sourceOptions,
|
||||
});
|
||||
const sourceIterator = sourceRuntime[Symbol.asyncIterator]();
|
||||
|
||||
try {
|
||||
const sourceCursors: Array<SDKAssistantMessage["uuid"]> = [];
|
||||
for (const [index, prompt] of input.prompts.slice(0, sourcePromptCount).entries()) {
|
||||
const message = makeClaudeUserMessage({ text: prompt });
|
||||
input.entries.push({
|
||||
type: "expect_outbound",
|
||||
label: `prompt.offer:${index + 1}`,
|
||||
frame: makeClaudePromptOfferFrame(message),
|
||||
});
|
||||
sourcePromptQueue.offer(message);
|
||||
const result = await recordMessagesUntilTurnResultWithCursor({
|
||||
iterator: sourceIterator,
|
||||
entries: input.entries,
|
||||
scenario: input.scenario,
|
||||
});
|
||||
if (!result.completed) {
|
||||
throw new Error(`Claude source query ended before prompt ${index + 1} completed.`);
|
||||
}
|
||||
sourceCursors.push(
|
||||
requireAssistantCursor({
|
||||
scenario: input.scenario,
|
||||
promptIndex: index + 1,
|
||||
cursor: result.assistantMessageUuid,
|
||||
}),
|
||||
);
|
||||
}
|
||||
sourcePromptQueue.close();
|
||||
sourceRuntime.close();
|
||||
input.entries.push({
|
||||
type: "runtime_exit",
|
||||
status: "success",
|
||||
});
|
||||
|
||||
const upToMessageId = sourceCursors[forkFromPromptIndex - 1]!;
|
||||
input.metadata.sourceAssistantMessageUuids = sourceCursors;
|
||||
input.metadata.forkUpToMessageId = upToMessageId;
|
||||
input.entries.push({
|
||||
type: "expect_outbound",
|
||||
label: "session.fork",
|
||||
frame: {
|
||||
type: "session.fork",
|
||||
sessionId: input.sessionId,
|
||||
options: {
|
||||
dir: sanitizedReplayCwd(input.scenario),
|
||||
upToMessageId,
|
||||
},
|
||||
},
|
||||
});
|
||||
const forked = await forkSession(input.sessionId, {
|
||||
dir: input.cwd,
|
||||
upToMessageId,
|
||||
});
|
||||
input.metadata.forkedNativeSessionId = forked.sessionId;
|
||||
input.entries.push({
|
||||
type: "emit_inbound",
|
||||
label: "session.forked",
|
||||
frame: {
|
||||
type: "session.forked",
|
||||
sessionId: forked.sessionId,
|
||||
},
|
||||
});
|
||||
|
||||
const targetPromptQueue = new RecordingPromptQueue();
|
||||
const targetOptions = makeClaudeQueryOptions({
|
||||
modelSelection: input.modelSelection,
|
||||
nativeThreadId: forked.sessionId,
|
||||
resume: true,
|
||||
cwd: input.cwd,
|
||||
...(input.enableTools === true
|
||||
? {
|
||||
tools: input.tools ?? { type: "preset", preset: "claude_code" },
|
||||
permissionMode: input.permissionMode ?? "default",
|
||||
...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }),
|
||||
...(input.disallowedTools === undefined
|
||||
? {}
|
||||
: { disallowedTools: input.disallowedTools }),
|
||||
...(input.allowDangerouslySkipPermissions === true
|
||||
? { allowDangerouslySkipPermissions: true }
|
||||
: {}),
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
input.entries.push({
|
||||
type: "expect_outbound",
|
||||
label: "query.open:fork",
|
||||
frame: makeClaudeQueryOpenFrame({ options: targetOptions }),
|
||||
});
|
||||
const targetMessage = makeClaudeUserMessage({ text: input.prompts[sourcePromptCount]! });
|
||||
input.entries.push({
|
||||
type: "expect_outbound",
|
||||
label: `prompt.offer:${sourcePromptCount + 1}`,
|
||||
frame: makeClaudePromptOfferFrame(targetMessage),
|
||||
});
|
||||
const targetRuntime = query({
|
||||
prompt: targetPromptQueue,
|
||||
options: targetOptions,
|
||||
});
|
||||
targetPromptQueue.offer(targetMessage);
|
||||
targetPromptQueue.close();
|
||||
const targetIterator = targetRuntime[Symbol.asyncIterator]();
|
||||
await recordMessagesUntilIteratorDone({
|
||||
iterator: targetIterator,
|
||||
entries: input.entries,
|
||||
scenario: input.scenario,
|
||||
});
|
||||
targetRuntime.close();
|
||||
input.entries.push({
|
||||
type: "runtime_exit",
|
||||
status: "success",
|
||||
});
|
||||
} catch (error) {
|
||||
sourcePromptQueue.close();
|
||||
sourceRuntime.close();
|
||||
input.entries.push({
|
||||
type: "runtime_exit",
|
||||
status: "error",
|
||||
error: serializeReplayError(error, input.scenario),
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function recordInterruptedClaudeQuery(input: {
|
||||
readonly scenario: string;
|
||||
readonly prompt: string;
|
||||
@@ -1267,7 +1800,7 @@ async function recordInterruptedClaudeQuery(input: {
|
||||
entries: input.entries,
|
||||
scenario: input.scenario,
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 250));
|
||||
await Effect.runPromise(Effect.sleep(Duration.millis(250)));
|
||||
}
|
||||
input.entries.push({
|
||||
type: "expect_outbound",
|
||||
@@ -1469,6 +2002,9 @@ export async function recordClaudeAgentSdkReplayTranscript(input: {
|
||||
readonly queryMode?:
|
||||
| "streaming"
|
||||
| "restart"
|
||||
| "resume_at_cursor"
|
||||
| "fork_session"
|
||||
| "fork_session_prior_turn"
|
||||
| "active_steering"
|
||||
| "interrupt"
|
||||
| "interrupt_restart";
|
||||
@@ -1491,6 +2027,7 @@ export async function recordClaudeAgentSdkReplayTranscript(input: {
|
||||
const entries: Array<ProviderReplayEntry> = [];
|
||||
const sessionId = input.sessionId ?? (await Effect.runPromise(Random.nextUUIDv4));
|
||||
const queryMode = input.queryMode ?? "streaming";
|
||||
const recordingMetadata: Record<string, unknown> = {};
|
||||
if (queryMode === "streaming") {
|
||||
await recordClaudeStreamingQuery({
|
||||
scenario: input.scenario,
|
||||
@@ -1554,6 +2091,43 @@ export async function recordClaudeAgentSdkReplayTranscript(input: {
|
||||
? {}
|
||||
: { allowDangerouslySkipPermissions: input.allowDangerouslySkipPermissions }),
|
||||
});
|
||||
} else if (queryMode === "resume_at_cursor") {
|
||||
await recordClaudeResumeAtCursorQuery({
|
||||
scenario: input.scenario,
|
||||
prompts: input.prompts,
|
||||
modelSelection: input.modelSelection,
|
||||
cwd: input.cwd,
|
||||
sessionId,
|
||||
entries,
|
||||
metadata: recordingMetadata,
|
||||
...(input.enableTools === undefined ? {} : { enableTools: input.enableTools }),
|
||||
...(input.tools === undefined ? {} : { tools: input.tools }),
|
||||
...(input.permissionMode === undefined ? {} : { permissionMode: input.permissionMode }),
|
||||
...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }),
|
||||
...(input.disallowedTools === undefined ? {} : { disallowedTools: input.disallowedTools }),
|
||||
...(input.allowDangerouslySkipPermissions === undefined
|
||||
? {}
|
||||
: { allowDangerouslySkipPermissions: input.allowDangerouslySkipPermissions }),
|
||||
});
|
||||
} else if (queryMode === "fork_session" || queryMode === "fork_session_prior_turn") {
|
||||
await recordClaudeForkSessionQuery({
|
||||
scenario: input.scenario,
|
||||
prompts: input.prompts,
|
||||
modelSelection: input.modelSelection,
|
||||
cwd: input.cwd,
|
||||
sessionId,
|
||||
entries,
|
||||
metadata: recordingMetadata,
|
||||
...(queryMode === "fork_session_prior_turn" ? { forkFromPromptIndex: 1 as const } : {}),
|
||||
...(input.enableTools === undefined ? {} : { enableTools: input.enableTools }),
|
||||
...(input.tools === undefined ? {} : { tools: input.tools }),
|
||||
...(input.permissionMode === undefined ? {} : { permissionMode: input.permissionMode }),
|
||||
...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }),
|
||||
...(input.disallowedTools === undefined ? {} : { disallowedTools: input.disallowedTools }),
|
||||
...(input.allowDangerouslySkipPermissions === undefined
|
||||
? {}
|
||||
: { allowDangerouslySkipPermissions: input.allowDangerouslySkipPermissions }),
|
||||
});
|
||||
} else if (queryMode === "interrupt") {
|
||||
await recordClaudeInterruptQuery({
|
||||
scenario: input.scenario,
|
||||
@@ -1614,6 +2188,7 @@ export async function recordClaudeAgentSdkReplayTranscript(input: {
|
||||
: { permissionDecision: input.permissionDecision }),
|
||||
...(input.interruptAfter === undefined ? {} : { interruptAfter: input.interruptAfter }),
|
||||
generatedBy: "recordClaudeAgentSdkReplayTranscript",
|
||||
...recordingMetadata,
|
||||
},
|
||||
entries,
|
||||
};
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import {
|
||||
type CanUseTool,
|
||||
forkSession as forkClaudeSession,
|
||||
type ForkSessionOptions,
|
||||
type ForkSessionResult,
|
||||
query,
|
||||
type Options as ClaudeQueryOptions,
|
||||
type PermissionMode,
|
||||
@@ -69,8 +72,10 @@ import {
|
||||
ProviderAdapterV2,
|
||||
type ProviderAdapterV2EnsureThreadInput,
|
||||
type ProviderAdapterV2Event,
|
||||
type ProviderAdapterV2ForkThreadInput,
|
||||
type ProviderAdapterV2InterruptInput,
|
||||
type ProviderAdapterV2OpenSessionInput,
|
||||
type ProviderAdapterV2RollbackThreadInput,
|
||||
type ProviderAdapterV2RuntimePolicy,
|
||||
type ProviderAdapterV2Shape,
|
||||
type ProviderAdapterV2SessionRuntime,
|
||||
@@ -99,9 +104,9 @@ export const ClaudeProviderCapabilitiesV2 = {
|
||||
threads: {
|
||||
canCreateEmptyThread: true,
|
||||
canReadThreadSnapshot: false,
|
||||
canRollbackThread: false,
|
||||
canForkThread: false,
|
||||
canForkFromTurn: false,
|
||||
canRollbackThread: true,
|
||||
canForkThread: true,
|
||||
canForkFromTurn: true,
|
||||
canForkFromSubagentThread: false,
|
||||
exposesNativeThreadId: true,
|
||||
},
|
||||
@@ -147,9 +152,9 @@ export const ClaudeProviderCapabilitiesV2 = {
|
||||
planDeltasHaveItemIds: false,
|
||||
},
|
||||
subagents: {
|
||||
supportsSubagents: false,
|
||||
supportsSubagents: true,
|
||||
exposesSubagentThreadIds: false,
|
||||
emitsSubagentLifecycle: false,
|
||||
emitsSubagentLifecycle: true,
|
||||
canWaitForSubagents: false,
|
||||
canCloseSubagents: false,
|
||||
canForkSubagentThread: false,
|
||||
@@ -167,8 +172,8 @@ export const ClaudeProviderCapabilitiesV2 = {
|
||||
checkpointing: {
|
||||
appCanCheckpointFilesystem: true,
|
||||
supportsNestedCheckpointScopes: true,
|
||||
providerCanRollbackConversation: false,
|
||||
providerRollbackReturnsSnapshot: false,
|
||||
providerCanRollbackConversation: true,
|
||||
providerRollbackReturnsSnapshot: true,
|
||||
providerCanReadConversationSnapshot: false,
|
||||
},
|
||||
identity: {
|
||||
@@ -260,6 +265,9 @@ export interface ClaudeAgentSdkQueryRunnerShape {
|
||||
readonly open: (
|
||||
input: ClaudeAgentSdkQueryOpenInput,
|
||||
) => Effect.Effect<ClaudeAgentSdkQuerySession, ClaudeAgentSdkQueryRunnerError>;
|
||||
readonly forkSession: (
|
||||
input: ClaudeAgentSdkSessionForkInput,
|
||||
) => Effect.Effect<ForkSessionResult, ClaudeAgentSdkQueryRunnerError>;
|
||||
readonly assertComplete: Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
|
||||
}
|
||||
|
||||
@@ -268,6 +276,13 @@ export class ClaudeAgentSdkQueryRunner extends Context.Service<
|
||||
ClaudeAgentSdkQueryRunnerShape
|
||||
>()("t3/orchestration-v2/ClaudeAgentSdkQueryRunner") {}
|
||||
|
||||
export interface ClaudeAgentSdkSessionForkInput {
|
||||
readonly sessionId: string;
|
||||
readonly options: ForkSessionOptions;
|
||||
readonly threadId: ThreadId;
|
||||
readonly providerSessionId: OrchestrationV2ProviderSession["id"];
|
||||
}
|
||||
|
||||
function queryRunnerError(cause: unknown, method: string): ClaudeAgentSdkQueryRunnerError {
|
||||
return Schema.is(ClaudeAgentSdkQueryRunnerError)(cause)
|
||||
? cause
|
||||
@@ -287,6 +302,7 @@ export interface ClaudeAgentSdkLoggedQueryOptions {
|
||||
readonly permissionMode: ClaudeAgentSdkQueryOptions["permissionMode"];
|
||||
readonly sessionId?: string;
|
||||
readonly resume?: string;
|
||||
readonly resumeSessionAt?: ClaudeAgentSdkQueryOptions["resumeSessionAt"];
|
||||
readonly cwd?: ClaudeAgentSdkQueryOptions["cwd"];
|
||||
readonly allowedTools?: ClaudeAgentSdkQueryOptions["allowedTools"];
|
||||
readonly disallowedTools?: ClaudeAgentSdkQueryOptions["disallowedTools"];
|
||||
@@ -337,6 +353,23 @@ export type ClaudeAgentSdkProtocolLogEvent =
|
||||
readonly type: "query.close";
|
||||
};
|
||||
}
|
||||
| {
|
||||
readonly direction: "outgoing";
|
||||
readonly stage: "decoded";
|
||||
readonly payload: {
|
||||
readonly type: "session.fork";
|
||||
readonly sessionId: string;
|
||||
readonly options: ForkSessionOptions;
|
||||
};
|
||||
}
|
||||
| {
|
||||
readonly direction: "incoming";
|
||||
readonly stage: "decoded";
|
||||
readonly payload: {
|
||||
readonly type: "session.forked";
|
||||
readonly sessionId: string;
|
||||
};
|
||||
}
|
||||
| {
|
||||
readonly direction: "incoming";
|
||||
readonly stage: "decoded";
|
||||
@@ -356,6 +389,7 @@ export function loggedClaudeQueryOptions(
|
||||
permissionMode: options.permissionMode,
|
||||
...(options.sessionId === undefined ? {} : { sessionId: options.sessionId }),
|
||||
...(options.resume === undefined ? {} : { resume: options.resume }),
|
||||
...(options.resumeSessionAt === undefined ? {} : { resumeSessionAt: options.resumeSessionAt }),
|
||||
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
|
||||
...(options.allowedTools === undefined ? {} : { allowedTools: options.allowedTools }),
|
||||
...(options.disallowedTools === undefined ? {} : { disallowedTools: options.disallowedTools }),
|
||||
@@ -515,6 +549,39 @@ export const claudeAgentSdkQueryRunnerLiveLayer: Layer.Layer<
|
||||
),
|
||||
} satisfies ClaudeAgentSdkQuerySession;
|
||||
}),
|
||||
forkSession: Effect.fn("ClaudeAgentSdkQueryRunner.forkSession")(function* (
|
||||
input: ClaudeAgentSdkSessionForkInput,
|
||||
) {
|
||||
const protocolLogger = makeClaudeAgentSdkProtocolLogger({
|
||||
nativeEventLogger,
|
||||
threadId: input.threadId,
|
||||
providerSessionId: input.providerSessionId,
|
||||
});
|
||||
const logProtocolEvent = (event: ClaudeAgentSdkProtocolLogEvent) =>
|
||||
protocolLogger === undefined ? Effect.void : protocolLogger(event);
|
||||
yield* logProtocolEvent({
|
||||
direction: "outgoing",
|
||||
stage: "decoded",
|
||||
payload: {
|
||||
type: "session.fork",
|
||||
sessionId: input.sessionId,
|
||||
options: input.options,
|
||||
},
|
||||
});
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: () => forkClaudeSession(input.sessionId, input.options),
|
||||
catch: (cause) => queryRunnerError(cause, "forkSession"),
|
||||
});
|
||||
yield* logProtocolEvent({
|
||||
direction: "incoming",
|
||||
stage: "decoded",
|
||||
payload: {
|
||||
type: "session.forked",
|
||||
sessionId: result.sessionId,
|
||||
},
|
||||
});
|
||||
return result;
|
||||
}),
|
||||
assertComplete: Effect.void,
|
||||
});
|
||||
}),
|
||||
@@ -524,6 +591,7 @@ export function makeClaudeQueryOptions(input: {
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly nativeThreadId: string;
|
||||
readonly resume: boolean;
|
||||
readonly resumeSessionAt?: string;
|
||||
readonly cwd: string | null;
|
||||
readonly settings?: ClaudeSettings;
|
||||
readonly sdkSettings?: string | ClaudeSdkSettings;
|
||||
@@ -546,6 +614,7 @@ export function makeClaudeQueryOptions(input: {
|
||||
tools: claudeAgentSdkQueryToolsForSdk(selectedTools),
|
||||
permissionMode: input.permissionMode ?? "default",
|
||||
...threadIdentity,
|
||||
...(input.resumeSessionAt === undefined ? {} : { resumeSessionAt: input.resumeSessionAt }),
|
||||
...(input.allowedTools === undefined ? {} : { allowedTools: [...input.allowedTools] }),
|
||||
...(input.disallowedTools === undefined ? {} : { disallowedTools: [...input.disallowedTools] }),
|
||||
...(input.canUseTool === undefined ? {} : { canUseTool: input.canUseTool }),
|
||||
@@ -612,8 +681,10 @@ function resultTextFromSdkMessage(
|
||||
function makeProviderThread(input: {
|
||||
readonly idAllocator: IdAllocatorV2Shape;
|
||||
readonly appThreadId: OrchestrationV2ProviderThread["appThreadId"];
|
||||
readonly ownerNodeId?: OrchestrationV2ProviderThread["ownerNodeId"];
|
||||
readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"];
|
||||
readonly nativeThreadId: string;
|
||||
readonly forkedFrom?: NonNullable<OrchestrationV2ProviderThread["forkedFrom"]>;
|
||||
readonly now: DateTime.Utc;
|
||||
}): OrchestrationV2ProviderThread {
|
||||
return {
|
||||
@@ -624,17 +695,18 @@ function makeProviderThread(input: {
|
||||
provider: CLAUDE_PROVIDER,
|
||||
providerSessionId: input.providerSessionId,
|
||||
appThreadId: input.appThreadId,
|
||||
ownerNodeId: null,
|
||||
ownerNodeId: input.ownerNodeId ?? null,
|
||||
nativeThreadRef: {
|
||||
provider: CLAUDE_PROVIDER,
|
||||
nativeId: input.nativeThreadId,
|
||||
strength: "strong",
|
||||
},
|
||||
nativeConversationHeadRef: null,
|
||||
status: "idle",
|
||||
firstRunOrdinal: null,
|
||||
lastRunOrdinal: null,
|
||||
handoffIds: [],
|
||||
forkedFrom: null,
|
||||
forkedFrom: input.forkedFrom ?? null,
|
||||
createdAt: input.now,
|
||||
updatedAt: input.now,
|
||||
};
|
||||
@@ -653,6 +725,120 @@ const getNativeThreadId = Effect.fnUntraced(function* (
|
||||
return nativeThreadId;
|
||||
});
|
||||
|
||||
const isSyntheticClaudeTurnId = (nativeTurnId: string): boolean => nativeTurnId.startsWith("turn:");
|
||||
|
||||
const isTerminalProviderTurn = (turn: OrchestrationV2ProviderTurn): boolean =>
|
||||
turn.status === "completed" ||
|
||||
turn.status === "interrupted" ||
|
||||
turn.status === "failed" ||
|
||||
turn.status === "cancelled";
|
||||
|
||||
const getNativeConversationHeadId = Effect.fnUntraced(function* (
|
||||
providerThread: OrchestrationV2ProviderThread,
|
||||
) {
|
||||
const nativeHeadRef = providerThread.nativeConversationHeadRef;
|
||||
if (nativeHeadRef === null) {
|
||||
return undefined;
|
||||
}
|
||||
if (nativeHeadRef.provider !== CLAUDE_PROVIDER) {
|
||||
return yield* new ProviderAdapterProtocolError({
|
||||
provider: CLAUDE_PROVIDER,
|
||||
detail: `Provider thread ${providerThread.id} has a non-Claude native conversation head reference.`,
|
||||
});
|
||||
}
|
||||
if (nativeHeadRef.nativeId === null) {
|
||||
return yield* new ProviderAdapterProtocolError({
|
||||
provider: CLAUDE_PROVIDER,
|
||||
detail: `Provider thread ${providerThread.id} has a Claude native conversation head reference without a native id.`,
|
||||
});
|
||||
}
|
||||
return nativeHeadRef.nativeId;
|
||||
});
|
||||
|
||||
const resolveClaudeForkUpToMessageId = Effect.fn("ClaudeAdapterV2.resolveForkUpToMessageId")(
|
||||
function* (input: ProviderAdapterV2ForkThreadInput) {
|
||||
if (input.providerTurnId === undefined || input.sourceProviderTurns === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const sourceTurns = input.sourceProviderTurns
|
||||
.filter((turn) => turn.providerThreadId === input.sourceProviderThread.id)
|
||||
.toSorted((left, right) => left.ordinal - right.ordinal);
|
||||
const boundaryIndex = sourceTurns.findIndex((turn) => turn.id === input.providerTurnId);
|
||||
if (boundaryIndex < 0) {
|
||||
return yield* new ProviderAdapterForkThreadError({
|
||||
provider: CLAUDE_PROVIDER,
|
||||
providerThreadId: input.sourceProviderThread.id,
|
||||
cause: `Cannot fork Claude thread from provider turn ${input.providerTurnId}: source turn was not found in provider thread ${input.sourceProviderThread.id}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const boundaryNativeId = sourceTurns[boundaryIndex]?.nativeTurnRef?.nativeId;
|
||||
if (
|
||||
boundaryNativeId !== undefined &&
|
||||
boundaryNativeId !== null &&
|
||||
!isSyntheticClaudeTurnId(boundaryNativeId)
|
||||
) {
|
||||
return boundaryNativeId;
|
||||
}
|
||||
|
||||
const terminalTurnsAfterBoundary = sourceTurns
|
||||
.slice(boundaryIndex + 1)
|
||||
.filter(isTerminalProviderTurn);
|
||||
if (terminalTurnsAfterBoundary.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return yield* new ProviderAdapterForkThreadError({
|
||||
provider: CLAUDE_PROVIDER,
|
||||
providerThreadId: input.sourceProviderThread.id,
|
||||
cause: `Cannot fork Claude thread from prior provider turn ${input.providerTurnId}: no SDK assistant message cursor was recorded for that turn.`,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const resolveClaudeRollbackResumeSessionAt = Effect.fn(
|
||||
"ClaudeAdapterV2.resolveRollbackResumeSessionAt",
|
||||
)(function* (input: ProviderAdapterV2RollbackThreadInput) {
|
||||
switch (input.target.type) {
|
||||
case "thread_start":
|
||||
return null;
|
||||
case "provider_turn": {
|
||||
const target = input.target;
|
||||
if (target.providerTurn.providerThreadId !== input.providerThread.id) {
|
||||
return yield* new ProviderAdapterRollbackThreadError({
|
||||
provider: CLAUDE_PROVIDER,
|
||||
providerThreadId: input.providerThread.id,
|
||||
cause: `Cannot roll back Claude thread ${input.providerThread.id} to provider turn ${target.providerTurn.id}: target turn belongs to provider thread ${target.providerTurn.providerThreadId}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const nativeTurnRef = target.providerTurn.nativeTurnRef;
|
||||
if (
|
||||
nativeTurnRef !== null &&
|
||||
nativeTurnRef.provider === CLAUDE_PROVIDER &&
|
||||
nativeTurnRef.nativeId !== null &&
|
||||
!isSyntheticClaudeTurnId(nativeTurnRef.nativeId)
|
||||
) {
|
||||
return nativeTurnRef.nativeId;
|
||||
}
|
||||
|
||||
const providerTurnsAfterTarget = input.providerThreadTurns.filter(
|
||||
(turn) => turn.ordinal > target.providerTurn.ordinal && isTerminalProviderTurn(turn),
|
||||
);
|
||||
if (providerTurnsAfterTarget.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return yield* new ProviderAdapterRollbackThreadError({
|
||||
provider: CLAUDE_PROVIDER,
|
||||
providerThreadId: input.providerThread.id,
|
||||
cause: `Cannot roll back Claude thread ${input.providerThread.id} to provider turn ${target.providerTurn.id}: no SDK assistant message cursor was recorded for that turn.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export function makeClaudeUserMessage(input: {
|
||||
readonly text: string;
|
||||
readonly priority?: SDKUserMessage["priority"];
|
||||
@@ -853,6 +1039,7 @@ const CLAUDE_KNOWN_TOOL_CLASSIFICATIONS: Record<
|
||||
readonly requestKind: ProviderRequestKind;
|
||||
}
|
||||
> = {
|
||||
agent: { itemType: "dynamic_tool", requestKind: "command" },
|
||||
bash: { itemType: "command_execution", requestKind: "command" },
|
||||
edit: { itemType: "file_change", requestKind: "file-change" },
|
||||
glob: { itemType: "dynamic_tool", requestKind: "file-read" },
|
||||
@@ -1221,6 +1408,12 @@ function claudeToolResultEntriesFromMessage(message: SDKMessage): ReadonlyArray<
|
||||
];
|
||||
}
|
||||
|
||||
function parentToolUseIdFromSdkMessage(message: SDKMessage): string | null {
|
||||
return message.type === "assistant" || message.type === "user"
|
||||
? message.parent_tool_use_id
|
||||
: null;
|
||||
}
|
||||
|
||||
function permissionResultFromDecision(input: {
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
readonly toolInput: Record<string, unknown>;
|
||||
@@ -1363,6 +1556,7 @@ function buildAssistantArtifacts(input: {
|
||||
interface ActiveClaudeTurnContext {
|
||||
readonly input: ProviderAdapterV2TurnInput;
|
||||
readonly nativeTurnId: string;
|
||||
nativeMessageCursor: string | null;
|
||||
readonly providerTurnId: OrchestrationV2ProviderTurn["id"];
|
||||
readonly providerTurnOrdinal: number;
|
||||
readonly startedAt: DateTime.Utc;
|
||||
@@ -1371,6 +1565,8 @@ interface ActiveClaudeTurnContext {
|
||||
nativeItemId: string;
|
||||
};
|
||||
readonly toolCalls: Map<string, ActiveClaudeToolCall>;
|
||||
readonly subagentNodesByTaskId: Map<string, OrchestrationV2ExecutionNode["id"]>;
|
||||
readonly subagentNodesByToolUseId: Map<string, OrchestrationV2ExecutionNode["id"]>;
|
||||
}
|
||||
|
||||
interface ClaudeLiveQueryContext {
|
||||
@@ -1386,6 +1582,7 @@ interface ActiveClaudeToolCall {
|
||||
readonly toolName: string;
|
||||
readonly classification: ClaudeToolClassification;
|
||||
readonly input: ClaudeNativeToolInput;
|
||||
readonly parentNodeId: OrchestrationV2ExecutionNode["id"];
|
||||
readonly startedAt: DateTime.Utc;
|
||||
}
|
||||
|
||||
@@ -1476,7 +1673,7 @@ export function makeClaudeAdapterV2(
|
||||
runAttemptId: input.context.input.attemptId,
|
||||
nativeTurnRef: {
|
||||
provider: CLAUDE_PROVIDER,
|
||||
nativeId: input.context.nativeTurnId,
|
||||
nativeId: input.context.nativeMessageCursor ?? input.context.nativeTurnId,
|
||||
strength: "weak",
|
||||
},
|
||||
ordinal: input.context.providerTurnOrdinal,
|
||||
@@ -1491,6 +1688,7 @@ export function makeClaudeAdapterV2(
|
||||
readonly toolName: string;
|
||||
readonly classification: ClaudeToolClassification;
|
||||
readonly toolInput: ClaudeNativeToolInput;
|
||||
readonly parentNodeId: OrchestrationV2ExecutionNode["id"];
|
||||
readonly output: ClaudeNativeToolOutput;
|
||||
readonly status: Extract<
|
||||
OrchestrationV2TurnItem["status"],
|
||||
@@ -1518,7 +1716,7 @@ export function makeClaudeAdapterV2(
|
||||
id: nodeId,
|
||||
threadId: input.context.input.threadId,
|
||||
runId: input.context.input.runId,
|
||||
parentNodeId: input.context.input.rootNodeId,
|
||||
parentNodeId: input.parentNodeId,
|
||||
rootNodeId: input.context.input.rootNodeId,
|
||||
kind: "tool_call",
|
||||
status: input.status,
|
||||
@@ -1621,11 +1819,72 @@ export function makeClaudeAdapterV2(
|
||||
});
|
||||
});
|
||||
|
||||
const updateClaudeSubagentNode = Effect.fnUntraced(function* (input: {
|
||||
readonly context: ActiveClaudeTurnContext;
|
||||
readonly taskId: string;
|
||||
readonly toolUseId?: string;
|
||||
readonly status: Extract<
|
||||
OrchestrationV2ExecutionNode["status"],
|
||||
"running" | "completed" | "failed" | "cancelled"
|
||||
>;
|
||||
}) {
|
||||
const existingNodeId =
|
||||
input.context.subagentNodesByTaskId.get(input.taskId) ??
|
||||
(input.toolUseId === undefined
|
||||
? undefined
|
||||
: input.context.subagentNodesByToolUseId.get(input.toolUseId));
|
||||
if (existingNodeId === undefined && input.status !== "running") {
|
||||
return;
|
||||
}
|
||||
|
||||
const now = yield* DateTime.now;
|
||||
const nativeItemId = `task:${input.taskId}`;
|
||||
const nodeId =
|
||||
existingNodeId ??
|
||||
idAllocator.derive.nodeFromProviderItem({
|
||||
provider: CLAUDE_PROVIDER,
|
||||
nativeItemId,
|
||||
});
|
||||
if (existingNodeId === undefined) {
|
||||
input.context.subagentNodesByTaskId.set(input.taskId, nodeId);
|
||||
if (input.toolUseId !== undefined) {
|
||||
input.context.subagentNodesByToolUseId.set(input.toolUseId, nodeId);
|
||||
}
|
||||
}
|
||||
|
||||
yield* emitProviderEvent({
|
||||
type: "node.updated",
|
||||
provider: CLAUDE_PROVIDER,
|
||||
node: {
|
||||
id: nodeId,
|
||||
threadId: input.context.input.threadId,
|
||||
runId: input.context.input.runId,
|
||||
parentNodeId: input.context.input.rootNodeId,
|
||||
rootNodeId: input.context.input.rootNodeId,
|
||||
kind: "subagent",
|
||||
status: input.status,
|
||||
countsForRun: false,
|
||||
providerThreadId: input.context.input.providerThread.id,
|
||||
providerTurnId: input.context.providerTurnId,
|
||||
nativeItemRef: {
|
||||
provider: CLAUDE_PROVIDER,
|
||||
nativeId: input.taskId,
|
||||
strength: "strong",
|
||||
},
|
||||
runtimeRequestId: null,
|
||||
checkpointScopeId: null,
|
||||
startedAt: now,
|
||||
completedAt: input.status === "running" ? null : now,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const ensureToolCallStarted = Effect.fnUntraced(function* (input: {
|
||||
readonly context: ActiveClaudeTurnContext;
|
||||
readonly nativeItemId: string;
|
||||
readonly toolName: string;
|
||||
readonly toolInput: ClaudeNativeToolInput;
|
||||
readonly parentToolUseId: string | null;
|
||||
}) {
|
||||
const existing = input.context.toolCalls.get(input.nativeItemId);
|
||||
if (existing !== undefined) {
|
||||
@@ -1633,11 +1892,17 @@ export function makeClaudeAdapterV2(
|
||||
}
|
||||
const startedAt = yield* DateTime.now;
|
||||
const classification = classifyClaudeNativeTool(input.toolName);
|
||||
const parentNodeId =
|
||||
input.parentToolUseId === null
|
||||
? input.context.input.rootNodeId
|
||||
: (input.context.subagentNodesByToolUseId.get(input.parentToolUseId) ??
|
||||
input.context.input.rootNodeId);
|
||||
const toolCall: ActiveClaudeToolCall = {
|
||||
nativeItemId: input.nativeItemId,
|
||||
toolName: input.toolName,
|
||||
classification,
|
||||
input: input.toolInput,
|
||||
parentNodeId,
|
||||
startedAt,
|
||||
};
|
||||
input.context.toolCalls.set(input.nativeItemId, toolCall);
|
||||
@@ -1647,6 +1912,7 @@ export function makeClaudeAdapterV2(
|
||||
toolName: input.toolName,
|
||||
classification,
|
||||
toolInput: input.toolInput,
|
||||
parentNodeId,
|
||||
output: NO_CLAUDE_NATIVE_TOOL_OUTPUT,
|
||||
status: "running",
|
||||
startedAt,
|
||||
@@ -1761,6 +2027,7 @@ export function makeClaudeAdapterV2(
|
||||
toolName: toolCall.toolName,
|
||||
classification: toolCall.classification,
|
||||
toolInput: toolCall.input,
|
||||
parentNodeId: toolCall.parentNodeId,
|
||||
output: NO_CLAUDE_NATIVE_TOOL_OUTPUT,
|
||||
status: "failed",
|
||||
startedAt: toolCall.startedAt,
|
||||
@@ -1818,6 +2085,26 @@ export function makeClaudeAdapterV2(
|
||||
completedAt: input.completedAt,
|
||||
}),
|
||||
}),
|
||||
...(input.status === "completed" &&
|
||||
input.context.input.providerThread.nativeConversationHeadRef !== null
|
||||
? [
|
||||
emitProviderEvent({
|
||||
type: "provider_thread.updated" as const,
|
||||
provider: CLAUDE_PROVIDER,
|
||||
providerThread: {
|
||||
...input.context.input.providerThread,
|
||||
providerSessionId: session.id,
|
||||
nativeConversationHeadRef: null,
|
||||
status: "idle" as const,
|
||||
firstRunOrdinal:
|
||||
input.context.input.providerThread.firstRunOrdinal ??
|
||||
input.context.input.runOrdinal,
|
||||
lastRunOrdinal: input.context.input.runOrdinal,
|
||||
updatedAt: input.completedAt,
|
||||
},
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
emitProviderEvent({
|
||||
type: "turn.terminal",
|
||||
provider: CLAUDE_PROVIDER,
|
||||
@@ -1879,16 +2166,45 @@ export function makeClaudeAdapterV2(
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "assistant") {
|
||||
context.nativeMessageCursor = message.uuid;
|
||||
}
|
||||
|
||||
if (message.type === "system" && message.subtype === "task_started") {
|
||||
yield* updateClaudeSubagentNode({
|
||||
context,
|
||||
taskId: message.task_id,
|
||||
...(message.tool_use_id === undefined ? {} : { toolUseId: message.tool_use_id }),
|
||||
status: "running",
|
||||
});
|
||||
}
|
||||
|
||||
if (message.type === "system" && message.subtype === "task_notification") {
|
||||
yield* updateClaudeSubagentNode({
|
||||
context,
|
||||
taskId: message.task_id,
|
||||
...(message.tool_use_id === undefined ? {} : { toolUseId: message.tool_use_id }),
|
||||
status:
|
||||
message.status === "completed"
|
||||
? "completed"
|
||||
: message.status === "stopped"
|
||||
? "cancelled"
|
||||
: "failed",
|
||||
});
|
||||
}
|
||||
|
||||
for (const toolUse of claudeToolUseBlocksFromAssistantMessage(message)) {
|
||||
yield* ensureToolCallStarted({
|
||||
context,
|
||||
nativeItemId: toolUse.id,
|
||||
toolName: toolUse.name,
|
||||
toolInput: claudeNativeToolInputFromUnknown(toolUse.input),
|
||||
parentToolUseId: parentToolUseIdFromSdkMessage(message),
|
||||
});
|
||||
}
|
||||
|
||||
for (const { toolResult, output } of claudeToolResultEntriesFromMessage(message)) {
|
||||
const parentToolUseId = parentToolUseIdFromSdkMessage(message);
|
||||
const toolCall =
|
||||
context.toolCalls.get(toolResult.tool_use_id) ??
|
||||
(yield* ensureToolCallStarted({
|
||||
@@ -1896,6 +2212,7 @@ export function makeClaudeAdapterV2(
|
||||
nativeItemId: toolResult.tool_use_id,
|
||||
toolName: toolNameFromClaudeToolResult(toolResult),
|
||||
toolInput: EMPTY_CLAUDE_NATIVE_TOOL_INPUT,
|
||||
parentToolUseId,
|
||||
}));
|
||||
const completedAt = yield* DateTime.now;
|
||||
const artifacts = yield* buildToolCallArtifacts({
|
||||
@@ -1904,6 +2221,7 @@ export function makeClaudeAdapterV2(
|
||||
toolName: toolCall.toolName,
|
||||
classification: toolCall.classification,
|
||||
toolInput: toolCall.input,
|
||||
parentNodeId: toolCall.parentNodeId,
|
||||
output,
|
||||
status: isClaudeToolResultError(toolResult) ? "failed" : "completed",
|
||||
startedAt: toolCall.startedAt,
|
||||
@@ -1971,6 +2289,7 @@ export function makeClaudeAdapterV2(
|
||||
nativeItemId: nativeRequestId,
|
||||
toolName,
|
||||
toolInput: nativeToolInput,
|
||||
parentToolUseId: null,
|
||||
});
|
||||
|
||||
const requestKind = providerRequestKindFromClaudeTool(toolName);
|
||||
@@ -2051,6 +2370,7 @@ export function makeClaudeAdapterV2(
|
||||
) {
|
||||
const queryPolicy = claudeRuntimeQueryPolicyForRuntimePolicy(turnInput.runtimePolicy);
|
||||
const queryPolicyKey = claudeRuntimeQueryPolicyKey(queryPolicy);
|
||||
const resumeSessionAt = yield* getNativeConversationHeadId(turnInput.providerThread);
|
||||
const existing = yield* Ref.get(queryContext);
|
||||
if (
|
||||
existing !== null &&
|
||||
@@ -2077,13 +2397,15 @@ export function makeClaudeAdapterV2(
|
||||
updated.add(nativeThreadId);
|
||||
return [false, updated];
|
||||
});
|
||||
const shouldResume = resumeSessionAt !== undefined || openedWithResume;
|
||||
const querySession = yield* queryRunner.open({
|
||||
threadId: turnInput.threadId,
|
||||
providerSessionId: input.providerSessionId,
|
||||
options: makeClaudeQueryOptions({
|
||||
modelSelection: turnInput.modelSelection,
|
||||
nativeThreadId,
|
||||
resume: openedWithResume,
|
||||
resume: shouldResume,
|
||||
...(resumeSessionAt === undefined ? {} : { resumeSessionAt }),
|
||||
cwd: turnInput.runtimePolicy.cwd,
|
||||
settings: adapterOptions.settings,
|
||||
environment: adapterOptions.environment,
|
||||
@@ -2157,6 +2479,7 @@ export function makeClaudeAdapterV2(
|
||||
const context: ActiveClaudeTurnContext = {
|
||||
input: turnInput,
|
||||
nativeTurnId,
|
||||
nativeMessageCursor: null,
|
||||
providerTurnId,
|
||||
providerTurnOrdinal,
|
||||
startedAt,
|
||||
@@ -2165,6 +2488,8 @@ export function makeClaudeAdapterV2(
|
||||
nativeItemId: `assistant:${turnInput.runId}`,
|
||||
},
|
||||
toolCalls: new Map(),
|
||||
subagentNodesByTaskId: new Map(),
|
||||
subagentNodesByToolUseId: new Map(),
|
||||
};
|
||||
const querySession = yield* openQuery(turnInput, nativeThreadId);
|
||||
yield* Ref.set(activeTurn, context);
|
||||
@@ -2310,6 +2635,30 @@ export function makeClaudeAdapterV2(
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const closeLiveQueryForNativeThread = Effect.fnUntraced(function* (nativeThreadId: string) {
|
||||
const existing = yield* Ref.get(queryContext);
|
||||
if (existing === null || existing.nativeThreadId !== nativeThreadId) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* existing.query.close.pipe(Effect.ignore);
|
||||
const closed = yield* Deferred.await(existing.closed).pipe(
|
||||
Effect.timeoutOption("10 seconds"),
|
||||
);
|
||||
if (Option.isSome(closed)) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* Effect.logWarning("orchestration-v2.claude-query-close-timeout-before-fork", {
|
||||
providerSessionId: input.providerSessionId,
|
||||
nativeThreadId,
|
||||
});
|
||||
yield* Ref.update(queryContext, (current) =>
|
||||
current?.query === existing.query ? null : current,
|
||||
);
|
||||
yield* Deferred.succeed(existing.closed, undefined);
|
||||
});
|
||||
yield* Effect.addFinalizer(() => closeSession());
|
||||
|
||||
const runtime: ProviderAdapterV2SessionRuntime = {
|
||||
@@ -2417,22 +2766,136 @@ export function makeClaudeAdapterV2(
|
||||
cause: "Claude V2 adapter does not implement snapshots.",
|
||||
}),
|
||||
),
|
||||
rollbackThread: (rollbackInput) =>
|
||||
Effect.fail(
|
||||
new ProviderAdapterRollbackThreadError({
|
||||
provider: CLAUDE_PROVIDER,
|
||||
providerThreadId: rollbackInput.providerThread.id,
|
||||
cause: "Claude V2 adapter does not implement rollback.",
|
||||
}),
|
||||
),
|
||||
forkThread: (forkInput) =>
|
||||
Effect.fail(
|
||||
new ProviderAdapterForkThreadError({
|
||||
provider: CLAUDE_PROVIDER,
|
||||
providerThreadId: forkInput.sourceProviderThread.id,
|
||||
cause: "Claude V2 adapter does not implement forks.",
|
||||
}),
|
||||
),
|
||||
rollbackThread: Effect.fn("ClaudeAdapterV2.rollbackThread")(
|
||||
function* (rollbackInput) {
|
||||
const currentTurn = yield* Ref.get(activeTurn);
|
||||
if (currentTurn !== null) {
|
||||
return yield* new ProviderAdapterProtocolError({
|
||||
provider: CLAUDE_PROVIDER,
|
||||
detail: `Cannot roll back Claude provider thread ${rollbackInput.providerThread.id} while provider turn ${currentTurn.providerTurnId} is active.`,
|
||||
});
|
||||
}
|
||||
|
||||
const nativeThreadId = yield* getNativeThreadId(rollbackInput.providerThread);
|
||||
yield* closeLiveQueryForNativeThread(nativeThreadId);
|
||||
const now = yield* DateTime.now;
|
||||
|
||||
if (rollbackInput.target.type === "thread_start") {
|
||||
const resetNativeThreadId = yield* queryRunner.allocateSessionId;
|
||||
return {
|
||||
providerThread: {
|
||||
...makeProviderThread({
|
||||
idAllocator,
|
||||
appThreadId: rollbackInput.providerThread.appThreadId,
|
||||
...(rollbackInput.providerThread.ownerNodeId === null
|
||||
? {}
|
||||
: { ownerNodeId: rollbackInput.providerThread.ownerNodeId }),
|
||||
providerSessionId: input.providerSessionId,
|
||||
nativeThreadId: resetNativeThreadId,
|
||||
...(rollbackInput.providerThread.forkedFrom === null
|
||||
? {}
|
||||
: { forkedFrom: rollbackInput.providerThread.forkedFrom }),
|
||||
now,
|
||||
}),
|
||||
handoffIds: rollbackInput.providerThread.handoffIds,
|
||||
},
|
||||
providerTurns: [],
|
||||
messages: [],
|
||||
runtimeRequests: [],
|
||||
};
|
||||
}
|
||||
|
||||
const resumeSessionAt = yield* resolveClaudeRollbackResumeSessionAt(rollbackInput);
|
||||
return {
|
||||
providerThread: {
|
||||
...rollbackInput.providerThread,
|
||||
providerSessionId: input.providerSessionId,
|
||||
nativeConversationHeadRef:
|
||||
resumeSessionAt === null
|
||||
? null
|
||||
: {
|
||||
provider: CLAUDE_PROVIDER,
|
||||
nativeId: resumeSessionAt,
|
||||
strength: "weak" as const,
|
||||
},
|
||||
status: "idle" as const,
|
||||
lastRunOrdinal: rollbackInput.target.appRunOrdinal,
|
||||
updatedAt: now,
|
||||
},
|
||||
providerTurns: [],
|
||||
messages: [],
|
||||
runtimeRequests: [],
|
||||
};
|
||||
},
|
||||
(effect, rollbackInput) =>
|
||||
effect.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
Schema.is(ProviderAdapterRollbackThreadError)(cause)
|
||||
? cause
|
||||
: new ProviderAdapterRollbackThreadError({
|
||||
provider: CLAUDE_PROVIDER,
|
||||
providerThreadId: rollbackInput.providerThread.id,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
forkThread: Effect.fn("ClaudeAdapterV2.forkThread")(
|
||||
function* (forkInput) {
|
||||
const currentTurn = yield* Ref.get(activeTurn);
|
||||
if (currentTurn !== null) {
|
||||
return yield* new ProviderAdapterProtocolError({
|
||||
provider: CLAUDE_PROVIDER,
|
||||
detail: `Cannot fork Claude provider thread ${forkInput.sourceProviderThread.id} while provider turn ${currentTurn.providerTurnId} is active.`,
|
||||
});
|
||||
}
|
||||
|
||||
const sourceNativeThreadId = yield* getNativeThreadId(forkInput.sourceProviderThread);
|
||||
yield* closeLiveQueryForNativeThread(sourceNativeThreadId);
|
||||
const upToMessageId = yield* resolveClaudeForkUpToMessageId(forkInput);
|
||||
const forkOptions: ForkSessionOptions = {
|
||||
...(input.runtimePolicy.cwd === null ? {} : { dir: input.runtimePolicy.cwd }),
|
||||
...(upToMessageId === undefined ? {} : { upToMessageId }),
|
||||
};
|
||||
const forked = yield* queryRunner.forkSession({
|
||||
sessionId: sourceNativeThreadId,
|
||||
options: forkOptions,
|
||||
threadId: forkInput.targetThreadId,
|
||||
providerSessionId: input.providerSessionId,
|
||||
});
|
||||
yield* Ref.update(openedNativeThreads, (current) => {
|
||||
const updated = new Set(current);
|
||||
updated.add(forked.sessionId);
|
||||
return updated;
|
||||
});
|
||||
const now = yield* DateTime.now;
|
||||
return makeProviderThread({
|
||||
idAllocator,
|
||||
appThreadId: forkInput.targetThreadId,
|
||||
ownerNodeId: forkInput.ownerNodeId ?? null,
|
||||
providerSessionId: input.providerSessionId,
|
||||
nativeThreadId: forked.sessionId,
|
||||
forkedFrom: {
|
||||
providerThreadId: forkInput.sourceProviderThread.id,
|
||||
...(forkInput.providerTurnId === undefined
|
||||
? {}
|
||||
: { providerTurnId: forkInput.providerTurnId }),
|
||||
},
|
||||
now,
|
||||
});
|
||||
},
|
||||
(effect, forkInput) =>
|
||||
effect.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterForkThreadError({
|
||||
provider: CLAUDE_PROVIDER,
|
||||
providerThreadId: forkInput.sourceProviderThread.id,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
};
|
||||
|
||||
return runtime;
|
||||
|
||||
@@ -1,9 +1,23 @@
|
||||
import { ProviderSessionId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
CheckpointId,
|
||||
NodeId,
|
||||
type OrchestrationV2ProviderThread,
|
||||
type OrchestrationV2ProviderTurn,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
RunAttemptId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import type { EventNdjsonLogger } from "../../provider/Layers/EventNdjsonLogger.ts";
|
||||
import { makeCodexAppServerProtocolLogger } from "./CodexAdapterV2.ts";
|
||||
import {
|
||||
makeCodexAppServerProtocolLogger,
|
||||
resolveCodexRollbackTurnCount,
|
||||
} from "./CodexAdapterV2.ts";
|
||||
|
||||
describe("CodexAdapterV2 native protocol logging", () => {
|
||||
it.effect("writes app-server protocol frames to the native provider log", () =>
|
||||
@@ -65,3 +79,68 @@ describe("CodexAdapterV2 native protocol logging", () => {
|
||||
assert.equal(protocolLogger, undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe("CodexAdapterV2 rollback mapping", () => {
|
||||
it.effect("derives native rollback count from durable provider turns", () =>
|
||||
Effect.gen(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
const providerThreadId = ProviderThreadId.make("provider-thread-codex-rollback");
|
||||
const providerThread: OrchestrationV2ProviderThread = {
|
||||
id: providerThreadId,
|
||||
provider: "codex",
|
||||
providerSessionId: ProviderSessionId.make("provider-session-codex-rollback"),
|
||||
appThreadId: ThreadId.make("thread-codex-rollback"),
|
||||
ownerNodeId: null,
|
||||
nativeThreadRef: {
|
||||
provider: "codex",
|
||||
nativeId: "native-thread-codex-rollback",
|
||||
strength: "strong",
|
||||
},
|
||||
nativeConversationHeadRef: null,
|
||||
status: "idle",
|
||||
firstRunOrdinal: 1,
|
||||
lastRunOrdinal: 3,
|
||||
handoffIds: [],
|
||||
forkedFrom: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
const providerTurn = (
|
||||
id: string,
|
||||
ordinal: number,
|
||||
status: OrchestrationV2ProviderTurn["status"],
|
||||
): OrchestrationV2ProviderTurn => ({
|
||||
id: ProviderTurnId.make(id),
|
||||
providerThreadId,
|
||||
nodeId: NodeId.make(`node-${id}`),
|
||||
runAttemptId: RunAttemptId.make(`run-attempt-${id}`),
|
||||
nativeTurnRef: {
|
||||
provider: "codex",
|
||||
nativeId: `native-${id}`,
|
||||
strength: "strong",
|
||||
},
|
||||
ordinal,
|
||||
status,
|
||||
startedAt: now,
|
||||
completedAt: status === "running" || status === "pending" ? null : now,
|
||||
});
|
||||
const firstTurn = providerTurn("provider-turn-first", 1, "completed");
|
||||
const secondTurn = providerTurn("provider-turn-second", 2, "completed");
|
||||
const runningTurn = providerTurn("provider-turn-running", 3, "running");
|
||||
const interruptedTurn = providerTurn("provider-turn-interrupted", 4, "interrupted");
|
||||
|
||||
const numTurns = yield* resolveCodexRollbackTurnCount({
|
||||
providerThread,
|
||||
target: {
|
||||
type: "provider_turn",
|
||||
checkpointId: CheckpointId.make("checkpoint-first"),
|
||||
appRunOrdinal: 1,
|
||||
providerTurn: firstTurn,
|
||||
},
|
||||
providerThreadTurns: [interruptedTurn, runningTurn, secondTurn, firstTurn],
|
||||
});
|
||||
|
||||
assert.equal(numTurns, 2);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -2,10 +2,12 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import type { ProviderReplayTranscript } from "@t3tools/contracts";
|
||||
import * as CodexClient from "effect-codex-app-server/client";
|
||||
import * as CodexReplay from "effect-codex-app-server/replay";
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
import { mkdirSync, mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { ServerConfig, type ServerConfigShape } from "../../config.ts";
|
||||
import { layer as idAllocatorLayer } from "../IdAllocator.ts";
|
||||
@@ -46,69 +48,83 @@ function metadataFromTranscript(transcript: ProviderReplayTranscript): {
|
||||
};
|
||||
}
|
||||
|
||||
function makeReplayServerConfig(scenario: string): ServerConfigShape {
|
||||
const baseDir = mkdtempSync(path.join(tmpdir(), `t3-orchestration-v2-codex-${scenario}-`));
|
||||
const stateDir = path.join(baseDir, "userdata");
|
||||
const logsDir = path.join(stateDir, "logs");
|
||||
const providerLogsDir = path.join(logsDir, "provider");
|
||||
const terminalLogsDir = path.join(logsDir, "terminals");
|
||||
const attachmentsDir = path.join(stateDir, "attachments");
|
||||
const worktreesDir = path.join(baseDir, "worktrees");
|
||||
const providerStatusCacheDir = path.join(baseDir, "caches");
|
||||
function makeReplayServerConfig(
|
||||
scenario: string,
|
||||
): Effect.Effect<
|
||||
ServerConfigShape,
|
||||
PlatformError.PlatformError,
|
||||
FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fs.makeTempDirectory({
|
||||
prefix: `t3-orchestration-v2-codex-${scenario}-`,
|
||||
});
|
||||
const stateDir = path.join(baseDir, "userdata");
|
||||
const logsDir = path.join(stateDir, "logs");
|
||||
const providerLogsDir = path.join(logsDir, "provider");
|
||||
const terminalLogsDir = path.join(logsDir, "terminals");
|
||||
const attachmentsDir = path.join(stateDir, "attachments");
|
||||
const worktreesDir = path.join(baseDir, "worktrees");
|
||||
const providerStatusCacheDir = path.join(baseDir, "caches");
|
||||
|
||||
for (const directory of [
|
||||
stateDir,
|
||||
logsDir,
|
||||
providerLogsDir,
|
||||
terminalLogsDir,
|
||||
attachmentsDir,
|
||||
worktreesDir,
|
||||
providerStatusCacheDir,
|
||||
]) {
|
||||
mkdirSync(directory, { recursive: true });
|
||||
}
|
||||
for (const directory of [
|
||||
stateDir,
|
||||
logsDir,
|
||||
providerLogsDir,
|
||||
terminalLogsDir,
|
||||
attachmentsDir,
|
||||
worktreesDir,
|
||||
providerStatusCacheDir,
|
||||
]) {
|
||||
yield* fs.makeDirectory(directory, { recursive: true });
|
||||
}
|
||||
|
||||
return {
|
||||
logLevel: "Error",
|
||||
traceMinLevel: "Info",
|
||||
traceTimingEnabled: true,
|
||||
traceBatchWindowMs: 200,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
otlpTracesUrl: undefined,
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
otlpServiceName: "t3-server",
|
||||
mode: "web",
|
||||
port: 0,
|
||||
host: undefined,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
stateDir,
|
||||
dbPath: path.join(stateDir, "state.sqlite"),
|
||||
keybindingsConfigPath: path.join(stateDir, "keybindings.json"),
|
||||
settingsPath: path.join(stateDir, "settings.json"),
|
||||
providerStatusCacheDir,
|
||||
worktreesDir,
|
||||
attachmentsDir,
|
||||
logsDir,
|
||||
serverLogPath: path.join(logsDir, "server.log"),
|
||||
serverTracePath: path.join(logsDir, "server.trace.ndjson"),
|
||||
providerLogsDir,
|
||||
providerEventLogPath: path.join(providerLogsDir, "events.log"),
|
||||
terminalLogsDir,
|
||||
anonymousIdPath: path.join(stateDir, "anonymous-id"),
|
||||
environmentIdPath: path.join(stateDir, "environment-id"),
|
||||
serverRuntimeStatePath: path.join(stateDir, "server-runtime.json"),
|
||||
secretsDir: path.join(stateDir, "secrets"),
|
||||
};
|
||||
return {
|
||||
logLevel: "Error",
|
||||
traceMinLevel: "Info",
|
||||
traceTimingEnabled: true,
|
||||
traceBatchWindowMs: 200,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
otlpTracesUrl: undefined,
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
otlpServiceName: "t3-server",
|
||||
mode: "web",
|
||||
port: 0,
|
||||
host: undefined,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
stateDir,
|
||||
dbPath: path.join(stateDir, "state.sqlite"),
|
||||
keybindingsConfigPath: path.join(stateDir, "keybindings.json"),
|
||||
settingsPath: path.join(stateDir, "settings.json"),
|
||||
providerStatusCacheDir,
|
||||
worktreesDir,
|
||||
attachmentsDir,
|
||||
logsDir,
|
||||
serverLogPath: path.join(logsDir, "server.log"),
|
||||
serverTracePath: path.join(logsDir, "server.trace.ndjson"),
|
||||
providerLogsDir,
|
||||
providerEventLogPath: path.join(providerLogsDir, "events.log"),
|
||||
terminalLogsDir,
|
||||
anonymousIdPath: path.join(stateDir, "anonymous-id"),
|
||||
environmentIdPath: path.join(stateDir, "environment-id"),
|
||||
serverRuntimeStatePath: path.join(stateDir, "server-runtime.json"),
|
||||
secretsDir: path.join(stateDir, "secrets"),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function makeCodexProviderAdapterRegistryReplayLayer(input: {
|
||||
@@ -137,11 +153,18 @@ export function makeCodexProviderAdapterRegistryReplayLayer(input: {
|
||||
);
|
||||
}),
|
||||
});
|
||||
const serverConfigLayer = Layer.succeed(
|
||||
const serverConfigLayer = Layer.effect(
|
||||
ServerConfig,
|
||||
makeReplayServerConfig(input.transcript.scenario),
|
||||
);
|
||||
const adapterLayer = codexAdapterLayer.pipe(
|
||||
makeReplayServerConfig(input.transcript.scenario).pipe(Effect.orDie),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
const registryLayer = makeProviderAdapterRegistryDriverLayer({
|
||||
drivers: [CodexAdapterV2Driver],
|
||||
configMap: {
|
||||
[CODEX_DEFAULT_INSTANCE_ID]: {
|
||||
driver: CODEX_DRIVER_KIND,
|
||||
},
|
||||
},
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
replayClientFactoryLayer,
|
||||
|
||||
@@ -19,19 +19,18 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import * as CodexClient from "effect-codex-app-server/client";
|
||||
import * as CodexSchema from "effect-codex-app-server/schema";
|
||||
import {
|
||||
Context,
|
||||
DateTime,
|
||||
Deferred,
|
||||
Effect,
|
||||
FileSystem,
|
||||
Layer,
|
||||
Queue,
|
||||
Ref,
|
||||
Schema,
|
||||
Scope,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
@@ -58,6 +57,7 @@ import {
|
||||
ProviderAdapterV2,
|
||||
type ProviderAdapterV2Event,
|
||||
type ProviderAdapterV2ForkThreadInput,
|
||||
type ProviderAdapterV2RollbackThreadInput,
|
||||
type ProviderAdapterV2RuntimePolicy,
|
||||
type ProviderAdapterV2SessionRuntime,
|
||||
type ProviderAdapterV2SteerInput,
|
||||
@@ -180,7 +180,7 @@ function normalizeCodexCause(error: unknown): unknown {
|
||||
function codexTimestamp(seconds: number | null | undefined): DateTime.Utc {
|
||||
return seconds === null || seconds === undefined
|
||||
? DateTime.nowUnsafe()
|
||||
: DateTime.fromDateUnsafe(new Date(seconds * 1000));
|
||||
: DateTime.makeUnsafe(seconds * 1000);
|
||||
}
|
||||
|
||||
function mapCodexTurnStatus(
|
||||
@@ -481,6 +481,7 @@ function providerThreadFromCodexThread(input: {
|
||||
nativeId: input.thread.id,
|
||||
strength: "strong" as const,
|
||||
},
|
||||
nativeConversationHeadRef: null,
|
||||
status: "idle",
|
||||
firstRunOrdinal: null,
|
||||
lastRunOrdinal: null,
|
||||
@@ -497,17 +498,37 @@ const isTerminalProviderTurn = (turn: OrchestrationV2ProviderTurn): boolean =>
|
||||
turn.status === "failed" ||
|
||||
turn.status === "cancelled";
|
||||
|
||||
const providerTurnsForThread = (
|
||||
providerTurns: ReadonlyArray<OrchestrationV2ProviderTurn>,
|
||||
providerThread: OrchestrationV2ProviderThread,
|
||||
): ReadonlyArray<OrchestrationV2ProviderTurn> =>
|
||||
providerTurns.filter((turn) => turn.providerThreadId === providerThread.id);
|
||||
|
||||
const countTerminalTurnsAfterBoundary = (
|
||||
providerTurns: ReadonlyArray<OrchestrationV2ProviderTurn>,
|
||||
providerTurnId: ProviderTurnId,
|
||||
): number | null => {
|
||||
const boundaryTurn = providerTurns.find((turn) => turn.id === providerTurnId);
|
||||
if (boundaryTurn === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return providerTurns.filter(
|
||||
(turn) => turn.ordinal > boundaryTurn.ordinal && isTerminalProviderTurn(turn),
|
||||
).length;
|
||||
};
|
||||
|
||||
const resolveCodexForkRollbackTurnCount = Effect.fn("CodexAdapterV2.resolveForkRollbackTurnCount")(
|
||||
function* (input: ProviderAdapterV2ForkThreadInput) {
|
||||
if (input.providerTurnId === undefined || input.sourceProviderTurns === undefined) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const sourceTurns = input.sourceProviderTurns
|
||||
.filter((turn) => turn.providerThreadId === input.sourceProviderThread.id)
|
||||
.toSorted((left, right) => left.ordinal - right.ordinal);
|
||||
const boundaryIndex = sourceTurns.findIndex((turn) => turn.id === input.providerTurnId);
|
||||
if (boundaryIndex < 0) {
|
||||
const rollbackTurnCount = countTerminalTurnsAfterBoundary(
|
||||
providerTurnsForThread(input.sourceProviderTurns, input.sourceProviderThread),
|
||||
input.providerTurnId,
|
||||
);
|
||||
if (rollbackTurnCount === null) {
|
||||
return yield* new ProviderAdapterForkThreadError({
|
||||
provider: CODEX_PROVIDER,
|
||||
providerThreadId: input.sourceProviderThread.id,
|
||||
@@ -515,7 +536,40 @@ const resolveCodexForkRollbackTurnCount = Effect.fn("CodexAdapterV2.resolveForkR
|
||||
});
|
||||
}
|
||||
|
||||
return sourceTurns.slice(boundaryIndex + 1).filter(isTerminalProviderTurn).length;
|
||||
return rollbackTurnCount;
|
||||
},
|
||||
);
|
||||
|
||||
export const resolveCodexRollbackTurnCount = Effect.fn("CodexAdapterV2.resolveRollbackTurnCount")(
|
||||
function* (input: ProviderAdapterV2RollbackThreadInput) {
|
||||
const providerTurns = input.providerThreadTurns;
|
||||
switch (input.target.type) {
|
||||
case "thread_start":
|
||||
return providerTurns.filter(isTerminalProviderTurn).length;
|
||||
case "provider_turn": {
|
||||
if (input.target.providerTurn.providerThreadId !== input.providerThread.id) {
|
||||
return yield* new ProviderAdapterRollbackThreadError({
|
||||
provider: CODEX_PROVIDER,
|
||||
providerThreadId: input.providerThread.id,
|
||||
cause: `Cannot roll back Codex thread ${input.providerThread.id} to provider turn ${input.target.providerTurn.id}: target turn belongs to provider thread ${input.target.providerTurn.providerThreadId}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const rollbackTurnCount = countTerminalTurnsAfterBoundary(
|
||||
providerTurns,
|
||||
input.target.providerTurn.id,
|
||||
);
|
||||
if (rollbackTurnCount === null) {
|
||||
return yield* new ProviderAdapterRollbackThreadError({
|
||||
provider: CODEX_PROVIDER,
|
||||
providerThreadId: input.providerThread.id,
|
||||
cause: `Cannot roll back Codex thread ${input.providerThread.id} to provider turn ${input.target.providerTurn.id}: target turn was not found in durable provider turn history.`,
|
||||
});
|
||||
}
|
||||
|
||||
return rollbackTurnCount;
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -739,31 +793,46 @@ export const layer: Layer.Layer<
|
||||
return;
|
||||
}
|
||||
|
||||
yield* client.request("initialize", {
|
||||
clientInfo: CODEX_CLIENT_INFO,
|
||||
capabilities: CODEX_CLIENT_CAPABILITIES,
|
||||
});
|
||||
yield* client.notify("initialized", undefined);
|
||||
yield* Ref.set(initialized, true);
|
||||
});
|
||||
const now = yield* DateTime.now;
|
||||
const session = providerSession({
|
||||
providerSessionId: input.providerSessionId,
|
||||
cwd: input.runtimePolicy.cwd,
|
||||
model: input.modelSelection.model,
|
||||
now,
|
||||
});
|
||||
const events = yield* Queue.unbounded<ProviderAdapterV2Event>();
|
||||
const activeTurns = yield* Ref.make(new Map<string, ActiveCodexTurnContext>());
|
||||
const turnWaiters = yield* Ref.make(new Map<string, Deferred.Deferred<void, never>>());
|
||||
const itemOrdinals = yield* Ref.make(new Map<string, number>());
|
||||
const nextItemOrdinalsByTurn = yield* Ref.make(new Map<string, number>());
|
||||
const agentMessageDeltas = yield* Ref.make(new Map<string, string>());
|
||||
const planDeltas = yield* Ref.make(new Map<string, string>());
|
||||
const planIds = yield* Ref.make(new Map<string, OrchestrationV2PlanArtifact["id"]>());
|
||||
const pendingRuntimeRequests = yield* Ref.make(
|
||||
new Map<string, PendingCodexRuntimeRequest>(),
|
||||
);
|
||||
const now = yield* DateTime.now;
|
||||
for (const [index, nativeThreadId] of input.item.receiverThreadIds.entries()) {
|
||||
const subagentNodeId = idAllocator.derive.nodeFromProviderItem({
|
||||
provider: CODEX_PROVIDER,
|
||||
nativeItemId: `${input.item.id}:${nativeThreadId}`,
|
||||
});
|
||||
const providerThread = {
|
||||
id: idAllocator.derive.providerThread({
|
||||
provider: CODEX_PROVIDER,
|
||||
nativeThreadId,
|
||||
}),
|
||||
provider: CODEX_PROVIDER,
|
||||
providerSessionId: input.context.providerThread.providerSessionId,
|
||||
appThreadId: input.context.input.threadId,
|
||||
ownerNodeId: subagentNodeId,
|
||||
nativeThreadRef: {
|
||||
provider: CODEX_PROVIDER,
|
||||
nativeId: nativeThreadId,
|
||||
strength: "strong" as const,
|
||||
},
|
||||
nativeConversationHeadRef: null,
|
||||
status: "idle" as const,
|
||||
firstRunOrdinal: input.context.input.runOrdinal,
|
||||
lastRunOrdinal: input.context.input.runOrdinal,
|
||||
handoffIds: [],
|
||||
forkedFrom: {
|
||||
providerThreadId: input.context.providerThread.id,
|
||||
providerTurnId: input.context.providerTurnId,
|
||||
},
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
} satisfies OrchestrationV2ProviderThread;
|
||||
const subagent = {
|
||||
parentContext: input.context,
|
||||
providerThread,
|
||||
subagentNodeId,
|
||||
nativeToolCallId: input.item.id,
|
||||
ordinal: index + 1,
|
||||
startedAt: now,
|
||||
} satisfies CodexSubagentThreadContext;
|
||||
|
||||
const emitProviderEvent = (event: ProviderAdapterV2Event) =>
|
||||
Queue.offer(events, event).pipe(Effect.asVoid);
|
||||
@@ -2354,15 +2423,26 @@ export const layer: Layer.Layer<
|
||||
yield* emitProviderEvent({
|
||||
type: "node.updated",
|
||||
provider: CODEX_PROVIDER,
|
||||
node: artifacts.node,
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
type: "turn_item.updated",
|
||||
provider: CODEX_PROVIDER,
|
||||
turnItem: artifacts.turnItem,
|
||||
});
|
||||
return;
|
||||
}
|
||||
nativeId: response.thread.id,
|
||||
strength: "strong",
|
||||
},
|
||||
nativeConversationHeadRef: threadInput.providerThread.nativeConversationHeadRef,
|
||||
updatedAt: codexTimestamp(response.thread.updatedAt),
|
||||
} satisfies OrchestrationV2ProviderThread;
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterResumeThreadError({
|
||||
provider: CODEX_PROVIDER,
|
||||
providerSessionId: input.providerSessionId,
|
||||
providerThreadId: threadInput.providerThread.id,
|
||||
cause: normalizeCodexCause(cause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
startTurn: (turnInput) =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = yield* getNativeThreadId(turnInput.providerThread);
|
||||
|
||||
if (payload.item.type === "fileChange") {
|
||||
const artifacts = yield* buildFileChangeArtifacts(context, payload.item);
|
||||
@@ -3143,69 +3223,79 @@ export const layer: Layer.Layer<
|
||||
status: "idle" as const,
|
||||
updatedAt: codexTimestamp(response.thread.updatedAt),
|
||||
},
|
||||
nativeConversationHeadRef: threadInput.providerThread.nativeConversationHeadRef,
|
||||
updatedAt: codexTimestamp(response.thread.updatedAt),
|
||||
},
|
||||
providerTurns: [],
|
||||
messages: [],
|
||||
runtimeRequests: [],
|
||||
providerPayload: response.thread,
|
||||
};
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterReadThreadSnapshotError({
|
||||
provider: CODEX_PROVIDER,
|
||||
providerThreadId: threadInput.providerThread.id,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
rollbackThread: (threadInput) =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = yield* getNativeThreadId(threadInput.providerThread);
|
||||
const numTurns = yield* resolveCodexRollbackTurnCount(threadInput);
|
||||
const nativeConversationHeadRef =
|
||||
threadInput.target.type === "provider_turn"
|
||||
? threadInput.target.providerTurn.nativeTurnRef
|
||||
: null;
|
||||
if (numTurns === 0) {
|
||||
return {
|
||||
providerThread: {
|
||||
...threadInput.providerThread,
|
||||
nativeConversationHeadRef,
|
||||
status: "idle" as const,
|
||||
},
|
||||
providerTurns: [],
|
||||
messages: [],
|
||||
runtimeRequests: [],
|
||||
providerPayload: response.thread,
|
||||
};
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRollbackThreadError({
|
||||
provider: CODEX_PROVIDER,
|
||||
providerThreadId: threadInput.providerThread.id,
|
||||
cause: normalizeCodexCause(cause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
forkThread: (threadInput) =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = yield* getNativeThreadId(threadInput.sourceProviderThread);
|
||||
const response = yield* ensureInitialized.pipe(
|
||||
Effect.andThen(client.request("thread/fork", { threadId })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterForkThreadError({
|
||||
provider: CODEX_PROVIDER,
|
||||
providerThreadId: threadInput.sourceProviderThread.id,
|
||||
cause: normalizeCodexCause(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
const rollbackTurnCount = yield* resolveCodexForkRollbackTurnCount(threadInput);
|
||||
const forkedThread =
|
||||
rollbackTurnCount === 0
|
||||
? response.thread
|
||||
: (yield* ensureInitialized.pipe(
|
||||
Effect.andThen(
|
||||
client.request("thread/rollback", {
|
||||
threadId: response.thread.id,
|
||||
numTurns: rollbackTurnCount,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterForkThreadError({
|
||||
provider: CODEX_PROVIDER,
|
||||
providerThreadId: threadInput.sourceProviderThread.id,
|
||||
cause: normalizeCodexCause(cause),
|
||||
}),
|
||||
),
|
||||
)).thread;
|
||||
return providerThreadFromCodexThread({
|
||||
appThreadId: threadInput.targetThreadId,
|
||||
idAllocator,
|
||||
ownerNodeId: threadInput.ownerNodeId ?? null,
|
||||
providerSessionId: input.providerSessionId,
|
||||
thread: forkedThread,
|
||||
forkedFrom: {
|
||||
providerThreadId: threadInput.sourceProviderThread.id,
|
||||
...(threadInput.providerTurnId === undefined
|
||||
? {}
|
||||
: { providerTurnId: threadInput.providerTurnId }),
|
||||
}
|
||||
const response = yield* ensureInitialized.pipe(
|
||||
Effect.andThen(client.request("thread/rollback", { threadId, numTurns })),
|
||||
);
|
||||
return {
|
||||
providerThread: {
|
||||
...threadInput.providerThread,
|
||||
nativeThreadRef: {
|
||||
provider: CODEX_PROVIDER,
|
||||
nativeId: response.thread.id,
|
||||
strength: "strong" as const,
|
||||
},
|
||||
});
|
||||
}).pipe(
|
||||
nativeConversationHeadRef,
|
||||
status: "idle" as const,
|
||||
updatedAt: codexTimestamp(response.thread.updatedAt),
|
||||
},
|
||||
providerTurns: [],
|
||||
messages: [],
|
||||
runtimeRequests: [],
|
||||
providerPayload: response.thread,
|
||||
};
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRollbackThreadError({
|
||||
provider: CODEX_PROVIDER,
|
||||
providerThreadId: threadInput.providerThread.id,
|
||||
cause: normalizeCodexCause(cause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
forkThread: (threadInput) =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = yield* getNativeThreadId(threadInput.sourceProviderThread);
|
||||
const response = yield* ensureInitialized.pipe(
|
||||
Effect.andThen(client.request("thread/fork", { threadId })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterForkThreadError({
|
||||
|
||||
@@ -10,8 +10,9 @@ import {
|
||||
RunId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context, Schema } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type * as Effect from "effect/Effect";
|
||||
|
||||
export class CheckpointPolicyPrepareRunError extends Schema.TaggedErrorClass<CheckpointPolicyPrepareRunError>()(
|
||||
"CheckpointPolicyPrepareRunError",
|
||||
|
||||
@@ -9,7 +9,13 @@ import {
|
||||
RunId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context, DateTime, Effect, Encoding, Layer, Ref, Schema } from "effect";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import { parseTurnDiffFilesFromUnifiedDiff } from "../checkpointing/Diffs.ts";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { CommandId, type OrchestrationV2ProviderCapabilities, ThreadId } from "@t3tools/contracts";
|
||||
import { Effect } from "effect";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
|
||||
import {
|
||||
|
||||
@@ -8,7 +8,10 @@ import {
|
||||
RunId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context, Effect, Layer, Schema } from "effect";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export const MessageDispatchDecisionV2 = Schema.Union([
|
||||
Schema.Struct({
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { CommandId, NonNegativeInt, ThreadId } from "@t3tools/contracts";
|
||||
import { Context, DateTime, Effect, Layer, Option, Schema } from "effect";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,7 +6,11 @@ import {
|
||||
RunId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context, DateTime, Effect, Layer, Schema } from "effect";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { IdAllocatorV2 } from "./IdAllocator.ts";
|
||||
|
||||
|
||||
@@ -13,8 +13,10 @@ import {
|
||||
ThreadId,
|
||||
TurnItemId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context, Option, Schema } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type * as Effect from "effect/Effect";
|
||||
|
||||
export const CorrelationScopeV2 = Schema.Struct({
|
||||
provider: ProviderKind,
|
||||
|
||||
@@ -4,7 +4,12 @@ import {
|
||||
OrchestrationV2StoredEvent,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context, Effect, Layer, PubSub, Schema, Stream } from "effect";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { EventStoreV2 } from "./EventStore.ts";
|
||||
|
||||
@@ -5,7 +5,11 @@ import {
|
||||
OrchestrationV2StoredEvent,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context, Effect, Layer, Schema, Stream } from "effect";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
/**
|
||||
@@ -89,9 +93,11 @@ type EventRow = {
|
||||
const encodeEventJson = Schema.encodeEffect(Schema.fromJsonString(OrchestrationV2DomainEventJson));
|
||||
const decodeEventJson = Schema.decodeUnknownEffect(OrchestrationV2DomainEventJson);
|
||||
const decodeStoredEvent = Schema.decodeUnknownEffect(OrchestrationV2StoredEvent);
|
||||
const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
|
||||
const decodeUnknownJsonString = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
|
||||
|
||||
function parseJson(json: string): unknown {
|
||||
return JSON.parse(json) as unknown;
|
||||
return decodeUnknownJsonString(json);
|
||||
}
|
||||
|
||||
function compactUndefined(record: Record<string, unknown>): Record<string, unknown> {
|
||||
@@ -171,7 +177,7 @@ export const layer: Layer.Layer<EventStoreV2, never, SqlClient.SqlClient> = Laye
|
||||
${event.rawEventId ?? null},
|
||||
${event.type},
|
||||
${normalized.occurredAt},
|
||||
${JSON.stringify(normalized.payload)}
|
||||
${encodeUnknownJsonString(normalized.payload)}
|
||||
)
|
||||
RETURNING
|
||||
sequence,
|
||||
|
||||
@@ -20,7 +20,11 @@ import {
|
||||
ThreadId,
|
||||
TurnItemId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context, Effect, Layer, Random, Schema } from "effect";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Random from "effect/Random";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export const IdAllocatorV2Kind = Schema.Literals([
|
||||
"command",
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
type OrchestrationV2DomainEvent,
|
||||
type OrchestrationV2ExecutionNode,
|
||||
type OrchestrationV2ProviderThread,
|
||||
type OrchestrationV2ProviderTurn,
|
||||
type OrchestrationV2Run,
|
||||
type OrchestrationV2RunAttempt,
|
||||
type OrchestrationV2ShellSnapshot,
|
||||
@@ -21,7 +22,14 @@ import {
|
||||
type OrchestrationV2TurnItem,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context, DateTime, Effect, Layer, Option, Ref, Schema, Stream } from "effect";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import { CheckpointServiceV2 } from "./CheckpointService.ts";
|
||||
@@ -34,6 +42,7 @@ import {
|
||||
import { EventSinkV2 } from "./EventSink.ts";
|
||||
import { IdAllocatorV2 } from "./IdAllocator.ts";
|
||||
import { ProjectionStoreV2 } from "./ProjectionStore.ts";
|
||||
import type { ProviderAdapterV2RollbackTarget } from "./ProviderAdapter.ts";
|
||||
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
|
||||
import { RunExecutionServiceV2 } from "./RunExecutionService.ts";
|
||||
import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
|
||||
@@ -218,21 +227,29 @@ function providerThreadForRun(
|
||||
: projection.providerThreads.find((candidate) => candidate.id === run.providerThreadId);
|
||||
}
|
||||
|
||||
function providerTurnForRun(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
run: OrchestrationV2Run,
|
||||
): OrchestrationV2ProviderTurn | undefined {
|
||||
if (run.activeAttemptId === null) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return (
|
||||
projection.providerTurns.find((turn) => turn.runAttemptId === run.activeAttemptId) ??
|
||||
projection.providerTurns.find((turn) => {
|
||||
const attempt = projection.attempts.find((candidate) => candidate.id === run.activeAttemptId);
|
||||
return attempt?.providerTurnId === turn.id;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function contextSourcePointForRun(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
run: OrchestrationV2Run,
|
||||
): OrchestrationV2ContextSourcePoint {
|
||||
const providerThread = providerThreadForRun(projection, run);
|
||||
const providerTurn =
|
||||
run.activeAttemptId === null
|
||||
? undefined
|
||||
: (projection.providerTurns.find((turn) => turn.runAttemptId === run.activeAttemptId) ??
|
||||
projection.providerTurns.find((turn) => {
|
||||
const attempt = projection.attempts.find(
|
||||
(candidate) => candidate.id === run.activeAttemptId,
|
||||
);
|
||||
return attempt?.providerTurnId === turn.id;
|
||||
}));
|
||||
const providerTurn = providerTurnForRun(projection, run);
|
||||
return {
|
||||
threadId: projection.thread.id,
|
||||
runId: run.id,
|
||||
@@ -2846,6 +2863,47 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
const runsToRollback = projection.runs.filter(
|
||||
(run) => run.ordinal > targetOrdinal && run.status === "completed",
|
||||
);
|
||||
const providerThreadTurns = projection.providerTurns.filter(
|
||||
(turn) => turn.providerThreadId === providerThread.id,
|
||||
);
|
||||
const rollbackTarget: ProviderAdapterV2RollbackTarget =
|
||||
targetOrdinal === 0
|
||||
? {
|
||||
type: "thread_start",
|
||||
checkpointId: targetCheckpoint.id,
|
||||
appRunOrdinal: 0,
|
||||
}
|
||||
: yield* Effect.gen(function* () {
|
||||
const targetRun = projection.runs.find((run) => run.ordinal === targetOrdinal);
|
||||
if (targetRun === undefined) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Cannot roll back to checkpoint ${targetCheckpoint.id}: no run exists for app ordinal ${targetOrdinal}.`,
|
||||
});
|
||||
}
|
||||
const targetProviderTurn = providerTurnForRun(projection, targetRun);
|
||||
if (targetProviderTurn === undefined) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Cannot roll back to checkpoint ${targetCheckpoint.id}: run ${targetRun.id} has no provider turn.`,
|
||||
});
|
||||
}
|
||||
if (targetProviderTurn.providerThreadId !== providerThread.id) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Cannot roll back provider thread ${providerThread.id} to checkpoint ${targetCheckpoint.id}: target provider turn ${targetProviderTurn.id} belongs to provider thread ${targetProviderTurn.providerThreadId}.`,
|
||||
});
|
||||
}
|
||||
return {
|
||||
type: "provider_turn" as const,
|
||||
checkpointId: targetCheckpoint.id,
|
||||
appRunOrdinal: targetOrdinal,
|
||||
providerTurn: targetProviderTurn,
|
||||
};
|
||||
});
|
||||
yield* checkpointService
|
||||
.restore({
|
||||
scope: targetScope,
|
||||
@@ -2868,7 +2926,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
: yield* session
|
||||
.rollbackThread({
|
||||
providerThread,
|
||||
providerPayload: { numTurns },
|
||||
target: rollbackTarget,
|
||||
providerThreadTurns,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
|
||||
@@ -1,6 +1,22 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { EventId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { DateTime, Effect, Layer } from "effect";
|
||||
import {
|
||||
EventId,
|
||||
MessageId,
|
||||
type ModelSelection,
|
||||
NodeId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
RunAttemptId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
TurnItemId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
@@ -10,6 +26,11 @@ const TestLayer = Layer.mergeAll(
|
||||
projectionStoreLayer.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
|
||||
SqlitePersistenceMemory,
|
||||
);
|
||||
const modelSelection = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
} satisfies ModelSelection;
|
||||
const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
|
||||
|
||||
it.layer(TestLayer)("ProjectionStoreV2", (it) => {
|
||||
it.effect("builds shell snapshots without decoding full turn item payloads", () =>
|
||||
@@ -80,7 +101,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
|
||||
${"user_message"},
|
||||
${"completed"},
|
||||
${nowIso},
|
||||
${JSON.stringify({
|
||||
${encodeUnknownJsonString({
|
||||
id: "turn-item:stale-user-message",
|
||||
threadId,
|
||||
runId: null,
|
||||
@@ -125,4 +146,593 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => {
|
||||
assert.equal(fullProjectionExit._tag, "Failure");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("removes rolled back runs from the active visible projection", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionStore = yield* ProjectionStoreV2;
|
||||
const now = yield* DateTime.now;
|
||||
const threadId = ThreadId.make("thread:projection-rollback-prune");
|
||||
const projectId = ProjectId.make("project:projection-rollback-prune");
|
||||
const runId = RunId.make("run:projection-rollback-prune");
|
||||
const attemptId = RunAttemptId.make("attempt:projection-rollback-prune");
|
||||
const rootNodeId = NodeId.make("node:projection-rollback-prune:root");
|
||||
const assistantNodeId = NodeId.make("node:projection-rollback-prune:assistant");
|
||||
const providerThreadId = ProviderThreadId.make("provider-thread:projection-rollback-prune");
|
||||
const providerTurnId = ProviderTurnId.make("provider-turn:projection-rollback-prune");
|
||||
const userMessageId = MessageId.make("message:projection-rollback-prune:user");
|
||||
const assistantMessageId = MessageId.make("message:projection-rollback-prune:assistant");
|
||||
const userTurnItemId = TurnItemId.make("turn-item:projection-rollback-prune:user");
|
||||
const assistantTurnItemId = TurnItemId.make("turn-item:projection-rollback-prune:assistant");
|
||||
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-rollback-prune:thread-created"),
|
||||
type: "thread.created",
|
||||
threadId,
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: threadId,
|
||||
projectId,
|
||||
title: "Projection rollback prune",
|
||||
defaultProvider: "codex",
|
||||
modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
activeProviderThreadId: providerThreadId,
|
||||
lineage: {
|
||||
parentThreadId: null,
|
||||
relationshipToParent: null,
|
||||
rootThreadId: threadId,
|
||||
},
|
||||
forkedFrom: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-rollback-prune:provider-thread"),
|
||||
type: "provider-thread.updated",
|
||||
threadId,
|
||||
provider: "codex",
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: providerThreadId,
|
||||
provider: "codex",
|
||||
providerSessionId: null,
|
||||
appThreadId: threadId,
|
||||
ownerNodeId: null,
|
||||
nativeThreadRef: null,
|
||||
nativeConversationHeadRef: null,
|
||||
status: "active",
|
||||
firstRunOrdinal: 1,
|
||||
lastRunOrdinal: 1,
|
||||
handoffIds: [],
|
||||
forkedFrom: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-rollback-prune:run-created"),
|
||||
type: "run.created",
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
provider: "codex",
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: runId,
|
||||
threadId,
|
||||
ordinal: 1,
|
||||
provider: "codex",
|
||||
modelSelection,
|
||||
providerThreadId,
|
||||
userMessageId,
|
||||
rootNodeId,
|
||||
activeAttemptId: attemptId,
|
||||
status: "completed",
|
||||
requestedAt: now,
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
checkpointId: null,
|
||||
contextHandoffId: null,
|
||||
},
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-rollback-prune:attempt-created"),
|
||||
type: "run-attempt.created",
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
provider: "codex",
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: attemptId,
|
||||
runId,
|
||||
attemptOrdinal: 1,
|
||||
rootNodeId,
|
||||
provider: "codex",
|
||||
providerThreadId,
|
||||
providerTurnId,
|
||||
reason: "initial",
|
||||
status: "completed",
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
},
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-rollback-prune:root-node"),
|
||||
type: "node.updated",
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
provider: "codex",
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: rootNodeId,
|
||||
threadId,
|
||||
runId,
|
||||
parentNodeId: null,
|
||||
rootNodeId,
|
||||
kind: "root_turn",
|
||||
status: "completed",
|
||||
countsForRun: true,
|
||||
providerThreadId,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
runtimeRequestId: null,
|
||||
checkpointScopeId: null,
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
},
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-rollback-prune:assistant-node"),
|
||||
type: "node.updated",
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: assistantNodeId,
|
||||
provider: "codex",
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: assistantNodeId,
|
||||
threadId,
|
||||
runId,
|
||||
parentNodeId: rootNodeId,
|
||||
rootNodeId,
|
||||
kind: "assistant_message",
|
||||
status: "completed",
|
||||
countsForRun: false,
|
||||
providerThreadId,
|
||||
providerTurnId,
|
||||
nativeItemRef: null,
|
||||
runtimeRequestId: null,
|
||||
checkpointScopeId: null,
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
},
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-rollback-prune:provider-turn"),
|
||||
type: "provider-turn.updated",
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
provider: "codex",
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: providerTurnId,
|
||||
providerThreadId,
|
||||
nodeId: rootNodeId,
|
||||
runAttemptId: attemptId,
|
||||
nativeTurnRef: null,
|
||||
ordinal: 1,
|
||||
status: "completed",
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
},
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-rollback-prune:user-message"),
|
||||
type: "message.updated",
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
provider: "codex",
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: userMessageId,
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
role: "user",
|
||||
text: "rolled back user",
|
||||
attachments: [],
|
||||
streaming: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-rollback-prune:assistant-message"),
|
||||
type: "message.updated",
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: assistantNodeId,
|
||||
provider: "codex",
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: assistantMessageId,
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: assistantNodeId,
|
||||
role: "assistant",
|
||||
text: "rolled back assistant",
|
||||
attachments: [],
|
||||
streaming: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-rollback-prune:user-item"),
|
||||
type: "turn-item.updated",
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
provider: "codex",
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: userTurnItemId,
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
providerThreadId,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: 100,
|
||||
status: "completed",
|
||||
title: null,
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
updatedAt: now,
|
||||
type: "user_message",
|
||||
messageId: userMessageId,
|
||||
inputIntent: "turn_start",
|
||||
text: "rolled back user",
|
||||
attachments: [],
|
||||
},
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-rollback-prune:assistant-item"),
|
||||
type: "turn-item.updated",
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: assistantNodeId,
|
||||
provider: "codex",
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: assistantTurnItemId,
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: assistantNodeId,
|
||||
providerThreadId,
|
||||
providerTurnId,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: 101,
|
||||
status: "completed",
|
||||
title: null,
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
updatedAt: now,
|
||||
type: "assistant_message",
|
||||
messageId: assistantMessageId,
|
||||
text: "rolled back assistant",
|
||||
streaming: false,
|
||||
},
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-rollback-prune:run-rolled-back"),
|
||||
type: "run.updated",
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
provider: "codex",
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: runId,
|
||||
threadId,
|
||||
ordinal: 1,
|
||||
provider: "codex",
|
||||
modelSelection,
|
||||
providerThreadId,
|
||||
userMessageId,
|
||||
rootNodeId,
|
||||
activeAttemptId: attemptId,
|
||||
status: "rolled_back",
|
||||
requestedAt: now,
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
checkpointId: null,
|
||||
contextHandoffId: null,
|
||||
},
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-rollback-prune:root-rolled-back"),
|
||||
type: "node.updated",
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
provider: "codex",
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: rootNodeId,
|
||||
threadId,
|
||||
runId,
|
||||
parentNodeId: null,
|
||||
rootNodeId,
|
||||
kind: "root_turn",
|
||||
status: "rolled_back",
|
||||
countsForRun: true,
|
||||
providerThreadId,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
runtimeRequestId: null,
|
||||
checkpointScopeId: null,
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
const projection = yield* projectionStore.getThreadProjection(threadId);
|
||||
|
||||
assert.deepEqual(
|
||||
projection.runs.map((run) => run.status),
|
||||
["rolled_back"],
|
||||
);
|
||||
assert.deepEqual(
|
||||
projection.nodes.map((node) => [node.id, node.status]),
|
||||
[
|
||||
[assistantNodeId, "completed"],
|
||||
[rootNodeId, "rolled_back"],
|
||||
],
|
||||
);
|
||||
assert.lengthOf(projection.providerTurns, 1);
|
||||
assert.lengthOf(projection.messages, 2);
|
||||
assert.lengthOf(projection.turnItems, 2);
|
||||
assert.lengthOf(projection.visibleTurnItems, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps fork visible items stable after a source run is rolled back", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionStore = yield* ProjectionStoreV2;
|
||||
const now = yield* DateTime.now;
|
||||
const projectId = ProjectId.make("project:projection-fork-source-rollback");
|
||||
const sourceThreadId = ThreadId.make("thread:projection-fork-source-rollback:source");
|
||||
const targetThreadId = ThreadId.make("thread:projection-fork-source-rollback:target");
|
||||
const sourceProviderThreadId = ProviderThreadId.make(
|
||||
"provider-thread:projection-fork-source-rollback:source",
|
||||
);
|
||||
const targetProviderThreadId = ProviderThreadId.make(
|
||||
"provider-thread:projection-fork-source-rollback:target",
|
||||
);
|
||||
const sourceRun1Id = RunId.make("run:projection-fork-source-rollback:source:1");
|
||||
const sourceRun2Id = RunId.make("run:projection-fork-source-rollback:source:2");
|
||||
const sourceRun1NodeId = NodeId.make("node:projection-fork-source-rollback:source:1");
|
||||
const sourceRun2NodeId = NodeId.make("node:projection-fork-source-rollback:source:2");
|
||||
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-fork-source-rollback:source-thread"),
|
||||
type: "thread.created",
|
||||
threadId: sourceThreadId,
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: sourceThreadId,
|
||||
projectId,
|
||||
title: "Projection fork source rollback source",
|
||||
defaultProvider: "codex",
|
||||
modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
activeProviderThreadId: sourceProviderThreadId,
|
||||
lineage: {
|
||||
parentThreadId: null,
|
||||
relationshipToParent: null,
|
||||
rootThreadId: sourceThreadId,
|
||||
},
|
||||
forkedFrom: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-fork-source-rollback:target-thread"),
|
||||
type: "thread.created",
|
||||
threadId: targetThreadId,
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: targetThreadId,
|
||||
projectId,
|
||||
title: "Projection fork source rollback target",
|
||||
defaultProvider: "codex",
|
||||
modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
activeProviderThreadId: targetProviderThreadId,
|
||||
lineage: {
|
||||
parentThreadId: sourceThreadId,
|
||||
relationshipToParent: "fork",
|
||||
rootThreadId: sourceThreadId,
|
||||
},
|
||||
forkedFrom: {
|
||||
type: "run",
|
||||
threadId: sourceThreadId,
|
||||
runId: sourceRun2Id,
|
||||
},
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
for (const [ordinal, runId, nodeId, promptText, responseText] of [
|
||||
[1, sourceRun1Id, sourceRun1NodeId, "source one", "one"],
|
||||
[2, sourceRun2Id, sourceRun2NodeId, "source two", "two"],
|
||||
] as const) {
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make(`event:projection-fork-source-rollback:run-${ordinal}`),
|
||||
type: "run.created",
|
||||
threadId: sourceThreadId,
|
||||
runId,
|
||||
nodeId,
|
||||
provider: "codex",
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: runId,
|
||||
threadId: sourceThreadId,
|
||||
ordinal,
|
||||
provider: "codex",
|
||||
modelSelection,
|
||||
providerThreadId: sourceProviderThreadId,
|
||||
userMessageId: MessageId.make(
|
||||
`message:projection-fork-source-rollback:user:${ordinal}`,
|
||||
),
|
||||
rootNodeId: nodeId,
|
||||
activeAttemptId: null,
|
||||
status: "completed",
|
||||
requestedAt: now,
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
checkpointId: null,
|
||||
contextHandoffId: null,
|
||||
},
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make(`event:projection-fork-source-rollback:user-item-${ordinal}`),
|
||||
type: "turn-item.updated",
|
||||
threadId: sourceThreadId,
|
||||
runId,
|
||||
nodeId,
|
||||
provider: "codex",
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: TurnItemId.make(`turn-item:projection-fork-source-rollback:user:${ordinal}`),
|
||||
threadId: sourceThreadId,
|
||||
runId,
|
||||
nodeId,
|
||||
providerThreadId: sourceProviderThreadId,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: ordinal * 100,
|
||||
status: "completed",
|
||||
title: null,
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
updatedAt: now,
|
||||
type: "user_message",
|
||||
messageId: MessageId.make(`message:projection-fork-source-rollback:user:${ordinal}`),
|
||||
inputIntent: "turn_start",
|
||||
text: promptText,
|
||||
attachments: [],
|
||||
},
|
||||
});
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make(`event:projection-fork-source-rollback:assistant-item-${ordinal}`),
|
||||
type: "turn-item.updated",
|
||||
threadId: sourceThreadId,
|
||||
runId,
|
||||
nodeId,
|
||||
provider: "codex",
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: TurnItemId.make(`turn-item:projection-fork-source-rollback:assistant:${ordinal}`),
|
||||
threadId: sourceThreadId,
|
||||
runId,
|
||||
nodeId,
|
||||
providerThreadId: sourceProviderThreadId,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: ordinal * 100 + 1,
|
||||
status: "completed",
|
||||
title: null,
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
updatedAt: now,
|
||||
type: "assistant_message",
|
||||
messageId: MessageId.make(
|
||||
`message:projection-fork-source-rollback:assistant:${ordinal}`,
|
||||
),
|
||||
text: responseText,
|
||||
streaming: false,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const targetBeforeRollback = yield* projectionStore.getThreadProjection(targetThreadId);
|
||||
assert.deepEqual(
|
||||
targetBeforeRollback.visibleTurnItems.map((row) => row.item.type),
|
||||
["user_message", "assistant_message", "user_message", "assistant_message", "fork"],
|
||||
);
|
||||
|
||||
yield* projectionStore.apply({
|
||||
id: EventId.make("event:projection-fork-source-rollback:run-2-rolled-back"),
|
||||
type: "run.updated",
|
||||
threadId: sourceThreadId,
|
||||
runId: sourceRun2Id,
|
||||
nodeId: sourceRun2NodeId,
|
||||
provider: "codex",
|
||||
occurredAt: now,
|
||||
payload: {
|
||||
id: sourceRun2Id,
|
||||
threadId: sourceThreadId,
|
||||
ordinal: 2,
|
||||
provider: "codex",
|
||||
modelSelection,
|
||||
providerThreadId: sourceProviderThreadId,
|
||||
userMessageId: MessageId.make("message:projection-fork-source-rollback:user:2"),
|
||||
rootNodeId: sourceRun2NodeId,
|
||||
activeAttemptId: null,
|
||||
status: "rolled_back",
|
||||
requestedAt: now,
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
checkpointId: null,
|
||||
contextHandoffId: null,
|
||||
},
|
||||
});
|
||||
|
||||
const targetAfterRollback = yield* projectionStore.getThreadProjection(targetThreadId);
|
||||
assert.deepEqual(
|
||||
targetAfterRollback.visibleTurnItems.map((row) => [
|
||||
row.visibility,
|
||||
row.item.type,
|
||||
row.item.type === "user_message" || row.item.type === "assistant_message"
|
||||
? row.item.text
|
||||
: row.item.title,
|
||||
]),
|
||||
[
|
||||
["inherited", "user_message", "source one"],
|
||||
["inherited", "assistant_message", "one"],
|
||||
["inherited", "user_message", "source two"],
|
||||
["inherited", "assistant_message", "two"],
|
||||
["synthetic", "fork", "Forked from conversation"],
|
||||
],
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -28,7 +28,12 @@ import {
|
||||
ThreadId,
|
||||
TurnItemId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context, DateTime, Effect, Layer, Ref, Schema } from "effect";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export class ProjectionStoreApplyEventError extends Schema.TaggedErrorClass<ProjectionStoreApplyEventError>()(
|
||||
@@ -154,10 +159,10 @@ export function applyToProjection(
|
||||
};
|
||||
case "run.created":
|
||||
case "run.updated":
|
||||
return {
|
||||
return withLocalVisibleTurnItems({
|
||||
...base,
|
||||
runs: upsertById(base.runs, event.payload),
|
||||
};
|
||||
});
|
||||
case "run-attempt.created":
|
||||
case "run-attempt.updated":
|
||||
return {
|
||||
@@ -406,12 +411,38 @@ function sortMessagesByTurnItemOrder(
|
||||
});
|
||||
}
|
||||
|
||||
function localVisibleTurnItems(
|
||||
turnItems: ReadonlyArray<OrchestrationV2TurnItem>,
|
||||
function rolledBackRunIds(projection: OrchestrationV2ThreadProjection): ReadonlySet<RunId> {
|
||||
return new Set(
|
||||
projection.runs.filter((run) => run.status === "rolled_back").map((run) => run.id),
|
||||
);
|
||||
}
|
||||
|
||||
function activeLocalTurnItems(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): Array<OrchestrationV2ProjectedTurnItem> {
|
||||
return turnItems.map((item, position) => ({
|
||||
position,
|
||||
visibility: "local",
|
||||
const rolledBack = rolledBackRunIds(projection);
|
||||
return projection.turnItems
|
||||
.filter((item) => item.runId === null || !rolledBack.has(item.runId))
|
||||
.map((item, position) => ({
|
||||
position,
|
||||
visibility: "local" as const,
|
||||
sourceThreadId: item.threadId,
|
||||
sourceItemId: item.id,
|
||||
item,
|
||||
}));
|
||||
}
|
||||
|
||||
function localVisibleTurnItems(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): Array<OrchestrationV2ProjectedTurnItem> {
|
||||
return activeLocalTurnItems(projection);
|
||||
}
|
||||
|
||||
function inheritedVisibleTurnItemsFromLocalItems(
|
||||
items: ReadonlyArray<OrchestrationV2TurnItem>,
|
||||
): Array<Omit<OrchestrationV2ProjectedTurnItem, "position">> {
|
||||
return items.map((item) => ({
|
||||
visibility: "inherited" as const,
|
||||
sourceThreadId: item.threadId,
|
||||
sourceItemId: item.id,
|
||||
item,
|
||||
@@ -423,7 +454,7 @@ function withLocalVisibleTurnItems(
|
||||
): OrchestrationV2ThreadProjection {
|
||||
return {
|
||||
...projection,
|
||||
visibleTurnItems: localVisibleTurnItems(projection.turnItems),
|
||||
visibleTurnItems: localVisibleTurnItems(projection),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -469,27 +500,27 @@ function visibleTurnItemsThroughRun(input: {
|
||||
}
|
||||
|
||||
const runOrdinalById = new Map(input.sourceProjection.runs.map((run) => [run.id, run.ordinal]));
|
||||
return input.sourceProjection.visibleTurnItems
|
||||
.filter((row) => {
|
||||
const item = row.item;
|
||||
if (item.threadId !== input.sourceProjection.thread.id) {
|
||||
return true;
|
||||
}
|
||||
if (item.type === "fork") {
|
||||
return true;
|
||||
}
|
||||
const inheritedPrefix = input.sourceProjection.visibleTurnItems
|
||||
.filter(
|
||||
(row) => row.item.threadId !== input.sourceProjection.thread.id || row.item.type === "fork",
|
||||
)
|
||||
.map((row) => ({
|
||||
visibility: "inherited" as const,
|
||||
sourceThreadId: row.sourceThreadId,
|
||||
sourceItemId: row.sourceItemId,
|
||||
item: row.item,
|
||||
}));
|
||||
const localPrefix = inheritedVisibleTurnItemsFromLocalItems(
|
||||
input.sourceProjection.turnItems.filter((item) => {
|
||||
if (item.runId === null) {
|
||||
return false;
|
||||
}
|
||||
const ordinal = runOrdinalById.get(item.runId);
|
||||
return ordinal !== undefined && ordinal <= sourceRun.ordinal;
|
||||
})
|
||||
.map((row) => ({
|
||||
visibility: "inherited",
|
||||
sourceThreadId: row.sourceThreadId,
|
||||
sourceItemId: row.sourceItemId,
|
||||
item: row.item,
|
||||
}));
|
||||
}),
|
||||
);
|
||||
|
||||
return [...inheritedPrefix, ...localPrefix];
|
||||
}
|
||||
|
||||
function buildVisibleTurnItems(input: {
|
||||
@@ -498,7 +529,7 @@ function buildVisibleTurnItems(input: {
|
||||
}): Array<OrchestrationV2ProjectedTurnItem> {
|
||||
const forkedFrom = input.projection.thread.forkedFrom;
|
||||
if (forkedFrom?.type !== "run" || input.sourceProjection === null) {
|
||||
return localVisibleTurnItems(input.projection.turnItems);
|
||||
return localVisibleTurnItems(input.projection);
|
||||
}
|
||||
|
||||
const inherited = visibleTurnItemsThroughRun({
|
||||
@@ -510,11 +541,11 @@ function buildVisibleTurnItems(input: {
|
||||
sourceThreadId: forkedFrom.threadId,
|
||||
sourceRunId: forkedFrom.runId,
|
||||
});
|
||||
const local = input.projection.turnItems.map((item) => ({
|
||||
const local = activeLocalTurnItems(input.projection).map((row) => ({
|
||||
visibility: "local" as const,
|
||||
sourceThreadId: item.threadId,
|
||||
sourceItemId: item.id,
|
||||
item,
|
||||
sourceThreadId: row.sourceThreadId,
|
||||
sourceItemId: row.sourceItemId,
|
||||
item: row.item,
|
||||
}));
|
||||
|
||||
return renumberVisibleTurnItems([
|
||||
@@ -546,7 +577,7 @@ export function threadShellFromProjection(
|
||||
activeProviderThreadId: projection.thread.activeProviderThreadId,
|
||||
latestRunId: latestRun?.id ?? null,
|
||||
status: latestRun?.status ?? "idle",
|
||||
itemCount: projection.turnItems.length,
|
||||
itemCount: activeLocalTurnItems(projection).length,
|
||||
visibleItemCount: projection.visibleTurnItems.length,
|
||||
createdAt: projection.thread.createdAt,
|
||||
updatedAt: projection.updatedAt,
|
||||
@@ -1490,8 +1521,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
|
||||
decodeRows(decodeContextTransferPayload, threadId)(contextTransferRows),
|
||||
]);
|
||||
const orderedMessages = sortMessagesByTurnItemOrder(messages, turnItems);
|
||||
|
||||
return {
|
||||
const projection = {
|
||||
thread,
|
||||
runs,
|
||||
attempts,
|
||||
@@ -1507,9 +1537,10 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
|
||||
checkpoints,
|
||||
contextHandoffs,
|
||||
contextTransfers,
|
||||
visibleTurnItems: localVisibleTurnItems(turnItems),
|
||||
visibleTurnItems: [],
|
||||
updatedAt: thread.updatedAt,
|
||||
} satisfies OrchestrationV2ThreadProjection;
|
||||
return withLocalVisibleTurnItems(projection);
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
Schema.is(ProjectionStoreThreadNotFoundError)(cause)
|
||||
@@ -1572,7 +1603,10 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
|
||||
(
|
||||
SELECT COUNT(*)
|
||||
FROM orchestration_v2_projection_turn_items i
|
||||
LEFT JOIN orchestration_v2_projection_runs r
|
||||
ON r.run_id = i.run_id
|
||||
WHERE i.thread_id = t.thread_id
|
||||
AND (i.run_id IS NULL OR r.status <> 'rolled_back')
|
||||
) AS item_count
|
||||
FROM orchestration_v2_projection_threads t
|
||||
WHERE t.deleted_at IS NULL
|
||||
|
||||
@@ -27,8 +27,11 @@ import {
|
||||
RunId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context, Schema } from "effect";
|
||||
import type { Effect, Scope, Stream } from "effect";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import type * as Stream from "effect/Stream";
|
||||
|
||||
export const ProviderAdapterV2RuntimePolicy = Schema.Struct({
|
||||
runtimeMode: RuntimeMode,
|
||||
@@ -385,10 +388,23 @@ export interface ProviderAdapterV2ReadThreadSnapshotInput {
|
||||
readonly providerThread: OrchestrationV2ProviderThread;
|
||||
}
|
||||
|
||||
export type ProviderAdapterV2RollbackTarget =
|
||||
| {
|
||||
readonly type: "thread_start";
|
||||
readonly checkpointId: CheckpointId;
|
||||
readonly appRunOrdinal: 0;
|
||||
}
|
||||
| {
|
||||
readonly type: "provider_turn";
|
||||
readonly checkpointId: CheckpointId;
|
||||
readonly appRunOrdinal: number;
|
||||
readonly providerTurn: OrchestrationV2ProviderTurn;
|
||||
};
|
||||
|
||||
export interface ProviderAdapterV2RollbackThreadInput {
|
||||
readonly providerThread: OrchestrationV2ProviderThread;
|
||||
readonly providerTurnId?: ProviderTurnId;
|
||||
readonly providerPayload?: unknown;
|
||||
readonly target: ProviderAdapterV2RollbackTarget;
|
||||
readonly providerThreadTurns: ReadonlyArray<OrchestrationV2ProviderTurn>;
|
||||
}
|
||||
|
||||
export interface ProviderAdapterV2ForkThreadInput {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import {
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ProviderInstanceEnvironment,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type * as Effect from "effect/Effect";
|
||||
import type * as Scope from "effect/Scope";
|
||||
|
||||
import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
|
||||
|
||||
export class ProviderAdapterDriverCreateError extends Schema.TaggedErrorClass<ProviderAdapterDriverCreateError>()(
|
||||
"ProviderAdapterDriverCreateError",
|
||||
{
|
||||
driver: ProviderDriverKind,
|
||||
instanceId: ProviderInstanceId,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to create orchestration-v2 provider adapter ${this.instanceId} (${this.driver}): ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ProviderAdapterDriverCreateInput<Config> {
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly displayName: string | undefined;
|
||||
readonly accentColor?: string | undefined;
|
||||
readonly environment: ProviderInstanceEnvironment;
|
||||
readonly enabled: boolean;
|
||||
readonly config: Config;
|
||||
}
|
||||
|
||||
export interface ProviderAdapterDriver<Config, R = never> {
|
||||
readonly driverKind: ProviderDriverKind;
|
||||
readonly configSchema: Schema.Codec<Config, unknown>;
|
||||
readonly defaultConfig: () => Config;
|
||||
readonly create: (
|
||||
input: ProviderAdapterDriverCreateInput<Config>,
|
||||
) => Effect.Effect<ProviderAdapterV2Shape, ProviderAdapterDriverCreateError, R | Scope.Scope>;
|
||||
}
|
||||
|
||||
export type AnyProviderAdapterDriver<R = never> = ProviderAdapterDriver<any, R>;
|
||||
@@ -0,0 +1,177 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import {
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type OrchestrationV2ProviderCapabilities,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import type { ProviderAdapterDriver } from "./ProviderAdapterDriver.ts";
|
||||
import {
|
||||
makeDriverLayerFromSettings,
|
||||
ProviderAdapterRegistryV2,
|
||||
} from "./ProviderAdapterRegistry.ts";
|
||||
|
||||
const capabilities = {
|
||||
sessions: {
|
||||
supportsMultipleProviderThreadsPerSession: false,
|
||||
supportsModelSwitchInSession: false,
|
||||
supportsProviderSwitchingViaHandoff: false,
|
||||
supportsRuntimeModeSwitchInSession: false,
|
||||
pendingRequestsSurviveRestart: false,
|
||||
},
|
||||
threads: {
|
||||
canCreateEmptyThread: false,
|
||||
canReadThreadSnapshot: false,
|
||||
canRollbackThread: false,
|
||||
canForkThread: false,
|
||||
canForkFromTurn: false,
|
||||
canForkFromSubagentThread: false,
|
||||
exposesNativeThreadId: false,
|
||||
},
|
||||
turns: {
|
||||
exposesNativeTurnId: false,
|
||||
emitsTurnStarted: false,
|
||||
emitsTurnCompleted: false,
|
||||
supportsInterrupt: false,
|
||||
supportsActiveSteering: false,
|
||||
supportsSteeringByInterruptRestart: false,
|
||||
supportsQueuedMessages: false,
|
||||
terminalStatusQuality: "weak",
|
||||
},
|
||||
streaming: {
|
||||
streamsAssistantText: false,
|
||||
streamsReasoning: false,
|
||||
streamsToolOutput: false,
|
||||
streamsPlanText: false,
|
||||
emitsMessageCompleted: false,
|
||||
},
|
||||
tools: {
|
||||
exposesToolItemIds: false,
|
||||
emitsToolStarted: false,
|
||||
emitsToolCompleted: false,
|
||||
emitsToolOutput: false,
|
||||
supportsMcpTools: false,
|
||||
supportsDynamicToolCallbacks: false,
|
||||
},
|
||||
approvals: {
|
||||
supportsCommandApproval: false,
|
||||
supportsFileReadApproval: false,
|
||||
supportsFileChangeApproval: false,
|
||||
supportsApplyPatchApproval: false,
|
||||
approvalsHaveNativeRequestIds: false,
|
||||
approvalCallbacksAreLiveOnly: false,
|
||||
approvalsCanOriginateFromSubagents: false,
|
||||
},
|
||||
planning: {
|
||||
emitsPlanUpdated: false,
|
||||
emitsTodoList: false,
|
||||
emitsProposedPlan: false,
|
||||
supportsStructuredQuestions: false,
|
||||
planDeltasHaveItemIds: false,
|
||||
},
|
||||
subagents: {
|
||||
supportsSubagents: false,
|
||||
exposesSubagentThreadIds: false,
|
||||
emitsSubagentLifecycle: false,
|
||||
canWaitForSubagents: false,
|
||||
canCloseSubagents: false,
|
||||
canForkSubagentThread: false,
|
||||
},
|
||||
context: {
|
||||
acceptsSystemContext: false,
|
||||
acceptsDeveloperContext: false,
|
||||
acceptsSyntheticUserContext: false,
|
||||
canGenerateSummaries: false,
|
||||
canConsumeHandoffSummaries: false,
|
||||
supportsDeltaHandoff: false,
|
||||
supportsFullThreadHandoff: false,
|
||||
maxRecommendedHandoffChars: null,
|
||||
},
|
||||
checkpointing: {
|
||||
appCanCheckpointFilesystem: false,
|
||||
supportsNestedCheckpointScopes: false,
|
||||
providerCanRollbackConversation: false,
|
||||
providerRollbackReturnsSnapshot: false,
|
||||
providerCanReadConversationSnapshot: false,
|
||||
},
|
||||
identity: {
|
||||
nativeThreadIds: "none",
|
||||
nativeTurnIds: "none",
|
||||
nativeItemIds: "none",
|
||||
nativeRequestIds: "none",
|
||||
},
|
||||
} satisfies OrchestrationV2ProviderCapabilities;
|
||||
|
||||
const FakeConfig = Schema.Struct({});
|
||||
type FakeConfig = typeof FakeConfig.Type;
|
||||
|
||||
function makeFakeDriver(driverKind: ProviderDriverKind): ProviderAdapterDriver<FakeConfig> {
|
||||
return {
|
||||
driverKind,
|
||||
configSchema: FakeConfig,
|
||||
defaultConfig: () => ({}),
|
||||
create: ({ instanceId }) =>
|
||||
Effect.succeed({
|
||||
instanceId,
|
||||
provider: driverKind,
|
||||
getCapabilities: () => Effect.succeed(capabilities),
|
||||
openSession: () => Effect.die("fake adapter does not open sessions"),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
const codexDriver = ProviderDriverKind.make("codex");
|
||||
const claudeDriver = ProviderDriverKind.make("claudeAgent");
|
||||
const codexWork = ProviderInstanceId.make("codex_work");
|
||||
const claudeWork = ProviderInstanceId.make("claude_work");
|
||||
const TestSettingsLayer = ServerSettingsService.layerTest({
|
||||
providerInstances: {
|
||||
[codexWork]: { driver: codexDriver, config: {} },
|
||||
[claudeWork]: { driver: claudeDriver, config: {} },
|
||||
},
|
||||
});
|
||||
const TestLayer = makeDriverLayerFromSettings({
|
||||
drivers: [makeFakeDriver(codexDriver), makeFakeDriver(claudeDriver)],
|
||||
}).pipe(Layer.provideMerge(TestSettingsLayer));
|
||||
|
||||
it.effect("builds one V2 adapter per configured provider instance", () =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* ProviderAdapterRegistryV2;
|
||||
const instances = yield* registry.list();
|
||||
const codexWorkAdapter = yield* registry.get(codexWork);
|
||||
const claudeWorkAdapter = yield* registry.get(claudeWork);
|
||||
|
||||
assert.deepEqual(instances, [
|
||||
codexWork,
|
||||
claudeWork,
|
||||
ProviderInstanceId.make("codex"),
|
||||
ProviderInstanceId.make("claudeAgent"),
|
||||
]);
|
||||
assert.equal(codexWorkAdapter.instanceId, codexWork);
|
||||
assert.equal(claudeWorkAdapter.instanceId, claudeWork);
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
|
||||
it.effect("resolves provider instances added after the V2 registry was constructed", () =>
|
||||
Effect.gen(function* () {
|
||||
const registry = yield* ProviderAdapterRegistryV2;
|
||||
const settings = yield* ServerSettingsService;
|
||||
const codexAfterStart = ProviderInstanceId.make("codex_after_start");
|
||||
|
||||
yield* settings.updateSettings({
|
||||
providerInstances: {
|
||||
[codexAfterStart]: { driver: codexDriver, config: {} },
|
||||
},
|
||||
});
|
||||
|
||||
const adapter = yield* registry.get(codexAfterStart);
|
||||
const instances = yield* registry.list();
|
||||
|
||||
assert.equal(adapter.instanceId, codexAfterStart);
|
||||
assert.isTrue(instances.includes(codexAfterStart));
|
||||
}).pipe(Effect.provide(TestLayer)),
|
||||
);
|
||||
@@ -1,5 +1,22 @@
|
||||
import { ProviderKind } from "@t3tools/contracts";
|
||||
import { Context, Effect, Layer, Schema } from "effect";
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
ProviderDriverKind as ProviderDriverKindSchema,
|
||||
ProviderInstanceId,
|
||||
type ProviderDriverKind,
|
||||
type ProviderInstanceConfig,
|
||||
type ProviderInstanceConfigMap,
|
||||
type ServerSettings,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Equal from "effect/Equal";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { ProviderAdapterV2, type ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
|
||||
|
||||
@@ -14,7 +31,10 @@ export class ProviderAdapterRegistryLookupError extends Schema.TaggedErrorClass<
|
||||
}
|
||||
}
|
||||
|
||||
export const ProviderAdapterRegistryV2Error = Schema.Union([ProviderAdapterRegistryLookupError]);
|
||||
export const ProviderAdapterRegistryV2Error = Schema.Union([
|
||||
ProviderAdapterRegistryLookupError,
|
||||
ProviderAdapterDriverCreateError,
|
||||
]);
|
||||
export type ProviderAdapterRegistryV2Error = typeof ProviderAdapterRegistryV2Error.Type;
|
||||
|
||||
export interface ProviderAdapterRegistryV2Shape {
|
||||
@@ -106,6 +126,127 @@ const decodedConfigEnabled = (config: unknown): boolean | undefined => {
|
||||
return typeof enabled === "boolean" ? enabled : undefined;
|
||||
};
|
||||
|
||||
interface LiveAdapterEntry {
|
||||
readonly adapter: ProviderAdapterV2Shape;
|
||||
readonly scope: Scope.Closeable;
|
||||
readonly entry: ProviderInstanceConfig;
|
||||
}
|
||||
|
||||
const entryEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean =>
|
||||
Equal.equals(a, b);
|
||||
|
||||
const makeSettingsReadError = (cause: unknown): ProviderAdapterDriverCreateError =>
|
||||
new ProviderAdapterDriverCreateError({
|
||||
driver: ProviderDriverKindSchema.make("settings"),
|
||||
instanceId: ProviderInstanceId.make("settings"),
|
||||
detail: "Failed to read server settings before building provider adapters.",
|
||||
cause,
|
||||
});
|
||||
|
||||
function makeDriversById<R>(
|
||||
drivers: ReadonlyArray<AnyProviderAdapterDriver<R>>,
|
||||
): ReadonlyMap<ProviderDriverKind, AnyProviderAdapterDriver<R>> {
|
||||
return new Map<ProviderDriverKind, AnyProviderAdapterDriver<R>>(
|
||||
drivers.map((driver) => [driver.driverKind, driver]),
|
||||
);
|
||||
}
|
||||
|
||||
const createAdapterEntryFromConfigEntry = Effect.fn(
|
||||
"ProviderAdapterRegistry.createAdapterEntryFromConfigEntry",
|
||||
)(function* <R>(input: {
|
||||
readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderAdapterDriver<R>>;
|
||||
readonly parentScope: Scope.Scope;
|
||||
readonly instanceId: ProviderInstanceId;
|
||||
readonly entry: ProviderInstanceConfig;
|
||||
}): Effect.fn.Return<LiveAdapterEntry, ProviderAdapterDriverCreateError, R> {
|
||||
const driver = input.driversById.get(input.entry.driver);
|
||||
if (driver === undefined) {
|
||||
return yield* new ProviderAdapterDriverCreateError({
|
||||
driver: input.entry.driver,
|
||||
instanceId: input.instanceId,
|
||||
detail: "Unknown provider driver.",
|
||||
});
|
||||
}
|
||||
|
||||
const decodeConfig = Schema.decodeUnknownEffect(driver.configSchema);
|
||||
const typedConfig = yield* decodeConfig(input.entry.config ?? driver.defaultConfig()).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterDriverCreateError({
|
||||
driver: input.entry.driver,
|
||||
instanceId: input.instanceId,
|
||||
detail: "Invalid provider instance config.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const childScope = yield* Scope.make();
|
||||
yield* Scope.addFinalizer(
|
||||
input.parentScope,
|
||||
Scope.close(childScope, Exit.void).pipe(Effect.ignore),
|
||||
);
|
||||
|
||||
const adapter = yield* driver
|
||||
.create({
|
||||
instanceId: input.instanceId,
|
||||
displayName: input.entry.displayName,
|
||||
accentColor: input.entry.accentColor,
|
||||
environment: input.entry.environment ?? [],
|
||||
enabled: input.entry.enabled ?? decodedConfigEnabled(typedConfig) ?? true,
|
||||
config: typedConfig,
|
||||
})
|
||||
.pipe(
|
||||
Effect.provideService(Scope.Scope, childScope),
|
||||
Effect.tapError(() => Scope.close(childScope, Exit.void).pipe(Effect.ignore)),
|
||||
);
|
||||
|
||||
return {
|
||||
adapter,
|
||||
scope: childScope,
|
||||
entry: input.entry,
|
||||
};
|
||||
});
|
||||
|
||||
const buildAdaptersFromConfigMap = Effect.fn("ProviderAdapterRegistry.buildAdaptersFromConfigMap")(
|
||||
function* <R>(input: {
|
||||
readonly drivers: ReadonlyArray<AnyProviderAdapterDriver<R>>;
|
||||
readonly configMap: ProviderInstanceConfigMap;
|
||||
readonly parentScope: Scope.Scope;
|
||||
}): Effect.fn.Return<
|
||||
ReadonlyMap<ProviderInstanceId, LiveAdapterEntry>,
|
||||
ProviderAdapterRegistryBuildError,
|
||||
R
|
||||
> {
|
||||
const driversById = makeDriversById(input.drivers);
|
||||
const adapters = new Map<ProviderInstanceId, LiveAdapterEntry>();
|
||||
|
||||
for (const [rawInstanceId, entry] of Object.entries(input.configMap)) {
|
||||
const instanceId = ProviderInstanceId.make(rawInstanceId);
|
||||
if (!driversById.has(entry.driver)) {
|
||||
yield* Effect.logWarning("Skipping orchestration-v2 provider adapter with unknown driver", {
|
||||
instanceId,
|
||||
driver: entry.driver,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const adapter = yield* createAdapterEntryFromConfigEntry({
|
||||
driversById,
|
||||
parentScope: input.parentScope,
|
||||
instanceId,
|
||||
entry,
|
||||
});
|
||||
adapters.set(instanceId, adapter);
|
||||
}
|
||||
|
||||
return adapters;
|
||||
},
|
||||
);
|
||||
|
||||
const closeAdapterEntry = (entry: LiveAdapterEntry): Effect.Effect<void> =>
|
||||
Scope.close(entry.scope, Exit.void).pipe(Effect.ignore);
|
||||
|
||||
export function makeRegistryFromConfigMap<R>(input: {
|
||||
readonly drivers: ReadonlyArray<AnyProviderAdapterDriver<R>>;
|
||||
readonly configMap: ProviderInstanceConfigMap;
|
||||
@@ -115,48 +256,9 @@ export function makeRegistryFromConfigMap<R>(input: {
|
||||
R | Scope.Scope
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const driversById = new Map<ProviderDriverKind, AnyProviderAdapterDriver<R>>(
|
||||
input.drivers.map((driver) => [driver.driverKind, driver]),
|
||||
);
|
||||
const adapters: Array<ProviderAdapterV2Shape> = [];
|
||||
|
||||
for (const [rawInstanceId, entry] of Object.entries(input.configMap)) {
|
||||
const instanceId = ProviderInstanceId.make(rawInstanceId);
|
||||
const driver = driversById.get(entry.driver);
|
||||
if (driver === undefined) {
|
||||
yield* Effect.logWarning("Skipping orchestration-v2 provider adapter with unknown driver", {
|
||||
instanceId,
|
||||
driver: entry.driver,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const typedConfig = yield* Schema.decodeUnknownEffect(driver.configSchema)(
|
||||
entry.config ?? driver.defaultConfig(),
|
||||
).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterDriverCreateError({
|
||||
driver: entry.driver,
|
||||
instanceId,
|
||||
detail: "Invalid provider instance config.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const adapter = yield* driver.create({
|
||||
instanceId,
|
||||
displayName: entry.displayName,
|
||||
accentColor: entry.accentColor,
|
||||
environment: entry.environment ?? [],
|
||||
enabled: entry.enabled ?? decodedConfigEnabled(typedConfig) ?? true,
|
||||
config: typedConfig,
|
||||
});
|
||||
adapters.push(adapter);
|
||||
}
|
||||
|
||||
return makeRegistry(adapters);
|
||||
const parentScope = yield* Effect.scope;
|
||||
const entries = yield* buildAdaptersFromConfigMap({ ...input, parentScope });
|
||||
return makeRegistry(Array.from(entries.values()).map((entry) => entry.adapter));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -179,25 +281,158 @@ export function makeDriverLayerFromSettings<R>(input: {
|
||||
ProviderAdapterRegistryBuildError,
|
||||
R | ServerSettingsService
|
||||
> {
|
||||
return Layer.unwrap(
|
||||
return Layer.effect(
|
||||
ProviderAdapterRegistryV2,
|
||||
Effect.gen(function* () {
|
||||
const settingsService = yield* ServerSettingsService;
|
||||
const parentScope = yield* Effect.scope;
|
||||
const driverContext = yield* Effect.context<R>();
|
||||
const settings = yield* settingsService.getSettings.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterDriverCreateError({
|
||||
driver: ProviderDriverKindSchema.make("settings"),
|
||||
instanceId: ProviderInstanceId.make("settings"),
|
||||
detail: "Failed to read server settings before building provider adapters.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => makeSettingsReadError(cause)),
|
||||
);
|
||||
const configMap = deriveProviderAdapterInstanceConfigMap({
|
||||
settings,
|
||||
drivers: input.drivers,
|
||||
});
|
||||
return makeDriverLayer({ drivers: input.drivers, configMap });
|
||||
const initialAdapters = yield* buildAdaptersFromConfigMap({
|
||||
drivers: input.drivers,
|
||||
configMap,
|
||||
parentScope,
|
||||
});
|
||||
const adaptersRef = yield* Ref.make(initialAdapters);
|
||||
const reconcileSemaphore = yield* Semaphore.make(1);
|
||||
const driversById = makeDriversById(input.drivers);
|
||||
|
||||
const reconcileConfigMapWithR = Effect.fn("ProviderAdapterRegistry.reconcileConfigMap")(
|
||||
function* (
|
||||
nextConfigMap: ProviderInstanceConfigMap,
|
||||
): Effect.fn.Return<void, ProviderAdapterRegistryBuildError, R> {
|
||||
const previous = yield* Ref.get(adaptersRef);
|
||||
const nextEntries = new Map<ProviderInstanceId, LiveAdapterEntry>();
|
||||
const staleEntries: Array<LiveAdapterEntry> = [];
|
||||
const nextIds = new Set<ProviderInstanceId>();
|
||||
|
||||
for (const [rawInstanceId, entry] of Object.entries(nextConfigMap)) {
|
||||
const instanceId = ProviderInstanceId.make(rawInstanceId);
|
||||
nextIds.add(instanceId);
|
||||
|
||||
if (!driversById.has(entry.driver)) {
|
||||
yield* Effect.logWarning(
|
||||
"Skipping orchestration-v2 provider adapter with unknown driver",
|
||||
{
|
||||
instanceId,
|
||||
driver: entry.driver,
|
||||
},
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const existing = previous.get(instanceId);
|
||||
if (existing !== undefined && entryEqual(existing.entry, entry)) {
|
||||
nextEntries.set(instanceId, existing);
|
||||
continue;
|
||||
}
|
||||
|
||||
const nextEntry = yield* createAdapterEntryFromConfigEntry({
|
||||
driversById,
|
||||
parentScope,
|
||||
instanceId,
|
||||
entry,
|
||||
});
|
||||
nextEntries.set(instanceId, nextEntry);
|
||||
if (existing !== undefined) {
|
||||
staleEntries.push(existing);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [instanceId, existing] of previous) {
|
||||
if (!nextIds.has(instanceId)) {
|
||||
staleEntries.push(existing);
|
||||
}
|
||||
}
|
||||
|
||||
yield* Ref.set(adaptersRef, nextEntries);
|
||||
for (const entry of staleEntries) {
|
||||
yield* closeAdapterEntry(entry);
|
||||
}
|
||||
},
|
||||
);
|
||||
const reconcileConfigMap = (nextConfigMap: ProviderInstanceConfigMap) =>
|
||||
reconcileConfigMapWithR(nextConfigMap).pipe(Effect.provideContext(driverContext));
|
||||
|
||||
const refreshFromSettings = Effect.fn("ProviderAdapterRegistry.refreshFromSettings")(
|
||||
function* (): Effect.fn.Return<void, ProviderAdapterRegistryV2Error, never> {
|
||||
const latestSettings = yield* settingsService.getSettings.pipe(
|
||||
Effect.mapError((cause) => makeSettingsReadError(cause)),
|
||||
);
|
||||
yield* reconcileConfigMap(
|
||||
deriveProviderAdapterInstanceConfigMap({
|
||||
settings: latestSettings,
|
||||
drivers: input.drivers,
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
yield* settingsService.streamChanges.pipe(
|
||||
Stream.runForEach((nextSettings) =>
|
||||
reconcileSemaphore.withPermits(1)(
|
||||
reconcileConfigMap(
|
||||
deriveProviderAdapterInstanceConfigMap({
|
||||
settings: nextSettings,
|
||||
drivers: input.drivers,
|
||||
}),
|
||||
).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logError("Orchestration-v2 provider adapter registry reconcile failed", {
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const refreshAndGet = Effect.fn("ProviderAdapterRegistry.refreshAndGet")(function* (
|
||||
instanceId: ProviderInstanceId,
|
||||
): Effect.fn.Return<ProviderAdapterV2Shape, ProviderAdapterRegistryV2Error, never> {
|
||||
return yield* reconcileSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const cached = (yield* Ref.get(adaptersRef)).get(instanceId);
|
||||
if (cached !== undefined) {
|
||||
return cached.adapter;
|
||||
}
|
||||
|
||||
yield* refreshFromSettings();
|
||||
const refreshed = (yield* Ref.get(adaptersRef)).get(instanceId);
|
||||
if (refreshed === undefined) {
|
||||
return yield* new ProviderAdapterRegistryLookupError({ instanceId });
|
||||
}
|
||||
return refreshed.adapter;
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const get = Effect.fn("ProviderAdapterRegistry.get")(function* (
|
||||
instanceId: ProviderInstanceId,
|
||||
): Effect.fn.Return<ProviderAdapterV2Shape, ProviderAdapterRegistryV2Error, never> {
|
||||
const cached = (yield* Ref.get(adaptersRef)).get(instanceId);
|
||||
if (cached !== undefined) {
|
||||
return cached.adapter;
|
||||
}
|
||||
return yield* refreshAndGet(instanceId);
|
||||
});
|
||||
|
||||
return ProviderAdapterRegistryV2.of({
|
||||
get,
|
||||
list: () =>
|
||||
Ref.get(adaptersRef).pipe(
|
||||
Effect.map((adapters) =>
|
||||
Array.from(adapters.values()).map((entry) => entry.adapter.instanceId),
|
||||
),
|
||||
),
|
||||
} satisfies ProviderAdapterRegistryV2Shape);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,10 @@ import {
|
||||
type OrchestrationV2DomainEvent,
|
||||
type OrchestrationV2ProviderThread,
|
||||
} from "@t3tools/contracts";
|
||||
import { DateTime, Effect, Layer, Stream } from "effect";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
import { EventSinkV2, layer as eventSinkLayer } from "./EventSink.ts";
|
||||
@@ -120,6 +123,7 @@ layer("ProviderEventIngestorV2", (it) => {
|
||||
nativeId: "native-thread",
|
||||
strength: "strong",
|
||||
},
|
||||
nativeConversationHeadRef: null,
|
||||
status: "idle",
|
||||
firstRunOrdinal: null,
|
||||
lastRunOrdinal: null,
|
||||
|
||||
@@ -8,7 +8,11 @@ import {
|
||||
RunId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context, DateTime, Effect, Layer, Schema } from "effect";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { EventSinkV2 } from "./EventSink.ts";
|
||||
import { IdAllocatorV2 } from "./IdAllocator.ts";
|
||||
|
||||
@@ -9,7 +9,13 @@ import {
|
||||
type ProviderSessionId,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { DateTime, Effect, Layer, Option, Queue, Ref, Stream } from "effect";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { TestClock } from "effect/testing";
|
||||
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
@@ -151,6 +157,7 @@ function makeProviderThread(input: {
|
||||
nativeId: "native-thread",
|
||||
strength: "strong",
|
||||
},
|
||||
nativeConversationHeadRef: null,
|
||||
status: "idle",
|
||||
firstRunOrdinal: null,
|
||||
lastRunOrdinal: null,
|
||||
|
||||
@@ -7,22 +7,20 @@ import {
|
||||
ProviderSessionId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
Cause,
|
||||
Clock,
|
||||
Context,
|
||||
DateTime,
|
||||
Duration,
|
||||
Effect,
|
||||
Exit,
|
||||
Fiber,
|
||||
Layer,
|
||||
Option,
|
||||
Ref,
|
||||
Schema,
|
||||
Scope,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { EventSinkV2 } from "./EventSink.ts";
|
||||
import { IdAllocatorV2 } from "./IdAllocator.ts";
|
||||
|
||||
@@ -6,7 +6,9 @@ import {
|
||||
RunId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context, Schema, Effect } from "effect";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export const ProviderSwitchStrategyV2 = Schema.Literals([
|
||||
"resume_with_delta_handoff",
|
||||
|
||||
@@ -11,7 +11,14 @@ import {
|
||||
type ProviderSessionId,
|
||||
type RunAttemptId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context, DateTime, Effect, Fiber, Layer, Ref, Schema, Stream } from "effect";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { CheckpointServiceV2 } from "./CheckpointService.ts";
|
||||
import { EventSinkV2 } from "./EventSink.ts";
|
||||
@@ -280,6 +287,7 @@ export const layer: Layer.Layer<
|
||||
OrchestrationV2Run["status"],
|
||||
"completed" | "interrupted" | "failed" | "cancelled"
|
||||
> | null>(null);
|
||||
const latestProviderThread = yield* Ref.make(input.providerThread);
|
||||
const providerEventFiber = yield* input.session.events.pipe(
|
||||
Stream.takeUntil((event) => event.type === "turn.terminal"),
|
||||
Stream.runForEach((event) =>
|
||||
@@ -291,6 +299,9 @@ export const layer: Layer.Layer<
|
||||
nodeId: input.rootNode.id,
|
||||
event,
|
||||
});
|
||||
if (event.type === "provider_thread.updated") {
|
||||
yield* Ref.set(latestProviderThread, event.providerThread);
|
||||
}
|
||||
if (event.type === "turn.terminal") {
|
||||
yield* Ref.set(terminalStatus, event.status);
|
||||
}
|
||||
@@ -303,11 +314,12 @@ export const layer: Layer.Layer<
|
||||
if (status === null) {
|
||||
return;
|
||||
}
|
||||
const providerThread = yield* Ref.get(latestProviderThread);
|
||||
yield* writeFinalRunEvents({
|
||||
run: input.run,
|
||||
rootNode: input.rootNode,
|
||||
checkpointScope: input.checkpointScope,
|
||||
providerThread: input.providerThread,
|
||||
providerThread,
|
||||
attempt: input.attempt,
|
||||
status,
|
||||
runtimePolicy: input.runtimePolicy,
|
||||
@@ -319,15 +331,18 @@ export const layer: Layer.Layer<
|
||||
}),
|
||||
),
|
||||
Effect.catchCause((cause) =>
|
||||
writeFinalRunEvents({
|
||||
run: input.run,
|
||||
rootNode: input.rootNode,
|
||||
checkpointScope: input.checkpointScope,
|
||||
providerThread: input.providerThread,
|
||||
attempt: input.attempt,
|
||||
status: "failed",
|
||||
runtimePolicy: input.runtimePolicy,
|
||||
}).pipe(
|
||||
Ref.get(latestProviderThread).pipe(
|
||||
Effect.flatMap((providerThread) =>
|
||||
writeFinalRunEvents({
|
||||
run: input.run,
|
||||
rootNode: input.rootNode,
|
||||
checkpointScope: input.checkpointScope,
|
||||
providerThread,
|
||||
attempt: input.attempt,
|
||||
status: "failed",
|
||||
runtimePolicy: input.runtimePolicy,
|
||||
}),
|
||||
),
|
||||
Effect.mapError(
|
||||
(writeCause) =>
|
||||
new RunExecutionIngestError({
|
||||
@@ -371,12 +386,13 @@ export const layer: Layer.Layer<
|
||||
.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Fiber.interrupt(providerEventFiber).pipe(
|
||||
Effect.andThen(
|
||||
Effect.andThen(Ref.get(latestProviderThread)),
|
||||
Effect.flatMap((providerThread) =>
|
||||
writeFinalRunEvents({
|
||||
run: input.run,
|
||||
rootNode: input.rootNode,
|
||||
checkpointScope: input.checkpointScope,
|
||||
providerThread: input.providerThread,
|
||||
providerThread,
|
||||
attempt: input.attempt,
|
||||
status: "failed",
|
||||
runtimePolicy: input.runtimePolicy,
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { ModelSelection, OrchestrationV2AppThread, ProviderKind } from "@t3tools/contracts";
|
||||
import { Context, Effect, Layer, Schema } from "effect";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
ProviderAdapterV2RuntimePolicy,
|
||||
|
||||
@@ -6,8 +6,9 @@ import {
|
||||
RuntimeRequestId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context, Schema } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type * as Effect from "effect/Effect";
|
||||
|
||||
export class RuntimeRequestOpenError extends Schema.TaggedErrorClass<RuntimeRequestOpenError>()(
|
||||
"RuntimeRequestOpenError",
|
||||
|
||||
@@ -143,13 +143,13 @@ Target docs:
|
||||
|
||||
TODO:
|
||||
|
||||
- [ ] Defer subagents until lineage, context transfer, and provider capability policy are stable.
|
||||
- [x] Add provider-native subagent observation for Codex and Claude replay-backed fixtures.
|
||||
- [ ] Model native subagents and app-owned cross-provider subagents as related thread/subthread graph
|
||||
entries with different creator/lifecycle policy.
|
||||
- [ ] Preserve native provider subagent refs where available, but do not make the app graph depend on
|
||||
provider-native ids as primary ids.
|
||||
- [ ] Add projection support for subagent lifecycle, wait, close, result transfer, and pending approvals
|
||||
originating from subagents.
|
||||
- [ ] Add deeper tests for subagent wait, close, result transfer, pending approvals, failed/stopped
|
||||
tasks, and fork-from-subagent behavior.
|
||||
|
||||
FOOD FOR THOUGHT:
|
||||
|
||||
|
||||
@@ -3,8 +3,9 @@ import {
|
||||
OrchestrationV2ThreadForkSourcePoint,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context, Schema } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Schema from "effect/Schema";
|
||||
import type * as Effect from "effect/Effect";
|
||||
|
||||
export class ThreadForkPlanError extends Schema.TaggedErrorClass<ThreadForkPlanError>()(
|
||||
"ThreadForkPlanError",
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import { userFacingDispatchErrorMessage } from "./UserFacingErrors.ts";
|
||||
|
||||
describe("userFacingDispatchErrorMessage", () => {
|
||||
it("returns the deepest actionable domain error instead of generic dispatch wrappers", () => {
|
||||
const message = userFacingDispatchErrorMessage({
|
||||
message: "Failed to dispatch orchestration command checkpoint.rollback (command-1).",
|
||||
cause: {
|
||||
message: "Provider adapter failed while dispatching orchestration command command-1.",
|
||||
cause: {
|
||||
message:
|
||||
"claudeAgent cannot satisfy rollback for command command-1: provider conversation rollback is unavailable",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(
|
||||
message,
|
||||
"claudeAgent cannot satisfy rollback for command command-1: provider conversation rollback is unavailable",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses explicit detail fields as user-facing messages", () => {
|
||||
assert.equal(
|
||||
userFacingDispatchErrorMessage({
|
||||
message: "Failed to dispatch orchestration command message.dispatch (command-1).",
|
||||
cause: {
|
||||
detail: "Claude provider thread provider-thread-1 has no live query.",
|
||||
},
|
||||
}),
|
||||
"Claude provider thread provider-thread-1 has no live query.",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
const GENERIC_ERROR_PREFIXES = [
|
||||
"Failed to dispatch orchestration V2 command",
|
||||
"Failed to dispatch orchestration command ",
|
||||
"Provider adapter failed while dispatching orchestration command ",
|
||||
];
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
function textValue(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
|
||||
}
|
||||
|
||||
function messageFrom(value: unknown): string | undefined {
|
||||
if (typeof value === "string") {
|
||||
return textValue(value);
|
||||
}
|
||||
if (value instanceof Error) {
|
||||
return textValue(value.message);
|
||||
}
|
||||
if (!isRecord(value)) {
|
||||
return undefined;
|
||||
}
|
||||
return textValue(value.detail) ?? textValue(value.message);
|
||||
}
|
||||
|
||||
function isGenericErrorMessage(message: string): boolean {
|
||||
return GENERIC_ERROR_PREFIXES.some((prefix) => message.startsWith(prefix));
|
||||
}
|
||||
|
||||
function collectErrorMessages(value: unknown, seen: Set<unknown>): ReadonlyArray<string> {
|
||||
if (value === undefined || value === null || seen.has(value)) {
|
||||
return [];
|
||||
}
|
||||
seen.add(value);
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.flatMap((item) => collectErrorMessages(item, seen));
|
||||
}
|
||||
|
||||
const message = messageFrom(value);
|
||||
if (!isRecord(value)) {
|
||||
return message === undefined ? [] : [message];
|
||||
}
|
||||
|
||||
const nested = [
|
||||
...collectErrorMessages(value.cause, seen),
|
||||
...collectErrorMessages(value.error, seen),
|
||||
...collectErrorMessages(value.errors, seen),
|
||||
];
|
||||
|
||||
return message === undefined ? nested : [message, ...nested];
|
||||
}
|
||||
|
||||
export function userFacingDispatchErrorMessage(cause: unknown): string | undefined {
|
||||
const messages = collectErrorMessages(cause, new Set()).filter(
|
||||
(message, index, allMessages) =>
|
||||
!isGenericErrorMessage(message) && allMessages.indexOf(message) === index,
|
||||
);
|
||||
return messages.at(-1);
|
||||
}
|
||||
@@ -1,7 +1,14 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { CommandId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { Effect, Layer } from "effect";
|
||||
import {
|
||||
CommandId,
|
||||
type ModelSelection,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import { CheckpointStoreLive } from "../checkpointing/Layers/CheckpointStore.ts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Effect, Layer } from "effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import {
|
||||
claudeAgentSdkQueryRunnerLiveLayer,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import type { ProviderReplayTranscript } from "@t3tools/contracts";
|
||||
import { Effect } from "effect";
|
||||
import { readFile, rm } from "node:fs/promises";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
|
||||
import { classifyClaudeNativeTool } from "../Adapters/ClaudeAdapterV2.ts";
|
||||
import {
|
||||
@@ -19,10 +20,24 @@ import { makeCheckpointWorkspace } from "./ReplayFixtureWorkspace.ts";
|
||||
import { decodeProviderReplayNdjson } from "./ReplayTranscriptNdjson.ts";
|
||||
|
||||
async function readTranscript(file: URL): Promise<ProviderReplayTranscript> {
|
||||
const text = await readFile(file, "utf8");
|
||||
const text = await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
return yield* fs.readFileString(decodeURIComponent(file.pathname));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
return await Effect.runPromise(decodeProviderReplayNdjson(text));
|
||||
}
|
||||
|
||||
async function removeDirectory(path: string): Promise<void> {
|
||||
await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
yield* fs.remove(path, { recursive: true, force: true });
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
}
|
||||
|
||||
function claudeFixture(name: string) {
|
||||
const fixture = ORCHESTRATOR_REPLAY_FIXTURES.find((entry) => entry.name === name);
|
||||
const provider = fixture?.providers.find((entry) => entry.provider === "claudeAgent");
|
||||
@@ -32,10 +47,60 @@ function claudeFixture(name: string) {
|
||||
return { fixture, provider };
|
||||
}
|
||||
|
||||
async function readClaudeTranscriptFixture(path: string): Promise<ProviderReplayTranscript> {
|
||||
return await readTranscript(
|
||||
new URL(`./fixtures/${path}/claude_transcript.ndjson`, import.meta.url),
|
||||
);
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
function metadataString(transcript: ProviderReplayTranscript, key: string): string {
|
||||
const value = transcript.metadata?.[key];
|
||||
if (typeof value !== "string") {
|
||||
throw new Error(`${transcript.scenario} metadata.${key} must be a string.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
type FramedReplayEntry = Extract<
|
||||
ProviderReplayTranscript["entries"][number],
|
||||
{ readonly frame: unknown }
|
||||
>;
|
||||
|
||||
function frameRecord(entry: FramedReplayEntry): Record<string, unknown> {
|
||||
if (!isRecord(entry.frame)) {
|
||||
throw new Error("Replay entry frame must be an object.");
|
||||
}
|
||||
return entry.frame;
|
||||
}
|
||||
|
||||
function findEntryFrame(
|
||||
transcript: ProviderReplayTranscript,
|
||||
label: string,
|
||||
): Record<string, unknown> {
|
||||
const entry = transcript.entries.find(
|
||||
(candidate): candidate is FramedReplayEntry =>
|
||||
"label" in candidate && candidate.label === label && "frame" in candidate,
|
||||
);
|
||||
assert.isDefined(entry, `${transcript.scenario} must include replay entry ${label}`);
|
||||
return frameRecord(entry);
|
||||
}
|
||||
|
||||
function successResultTexts(transcript: ProviderReplayTranscript): ReadonlyArray<string> {
|
||||
return transcript.entries.flatMap((entry) => {
|
||||
if (entry.type !== "emit_inbound" || !isRecord(entry.frame)) {
|
||||
return [];
|
||||
}
|
||||
if (entry.frame.type !== "result" || entry.frame.subtype !== "success") {
|
||||
return [];
|
||||
}
|
||||
return typeof entry.frame.result === "string" ? [entry.frame.result] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function claudeToolUseNamesFromTranscript(
|
||||
transcript: ProviderReplayTranscript,
|
||||
): ReadonlyArray<string> {
|
||||
@@ -91,6 +156,59 @@ describe("Claude Agent SDK replay fixtures", () => {
|
||||
assert.deepEqual([...unknownToolNames], []);
|
||||
});
|
||||
|
||||
it("keeps unregistered native conversation-state transcripts reviewable", async () => {
|
||||
const rollback = await readClaudeTranscriptFixture("thread_rollback");
|
||||
assert.equal(rollback.metadata?.queryMode, "resume_at_cursor");
|
||||
const rollbackCursor = metadataString(rollback, "resumeSessionAt");
|
||||
const rollbackResumeFrame = findEntryFrame(rollback, "query.open:resume_at_cursor");
|
||||
const rollbackResumeOptions = rollbackResumeFrame.options;
|
||||
if (!isRecord(rollbackResumeOptions)) {
|
||||
throw new Error("Rollback resume query.open options must be an object.");
|
||||
}
|
||||
assert.equal(rollbackResumeOptions.resumeSessionAt, rollbackCursor);
|
||||
const rollbackFinalText = successResultTexts(rollback).at(-1) ?? "";
|
||||
assert.include(rollbackFinalText, "rollback fixture first turn complete");
|
||||
assert.notInclude(rollbackFinalText, "rollback fixture second turn complete");
|
||||
|
||||
const latestFork = await readClaudeTranscriptFixture("thread_fork_native");
|
||||
assert.equal(latestFork.metadata?.queryMode, "fork_session");
|
||||
const latestForkedSessionId = metadataString(latestFork, "forkedNativeSessionId");
|
||||
const latestForkedFrame = findEntryFrame(latestFork, "session.forked");
|
||||
assert.equal(latestForkedFrame.sessionId, latestForkedSessionId);
|
||||
|
||||
const priorFork = await readClaudeTranscriptFixture("thread_fork_native_prior_turn");
|
||||
assert.equal(priorFork.metadata?.queryMode, "fork_session_prior_turn");
|
||||
const priorForkCursor = metadataString(priorFork, "forkUpToMessageId");
|
||||
const priorForkFrame = findEntryFrame(priorFork, "session.fork");
|
||||
const priorForkOptions = priorForkFrame.options;
|
||||
if (!isRecord(priorForkOptions)) {
|
||||
throw new Error("Prior-turn fork options must be an object.");
|
||||
}
|
||||
assert.equal(priorForkOptions.upToMessageId, priorForkCursor);
|
||||
const priorForkFinalText = successResultTexts(priorFork).at(-1) ?? "";
|
||||
assert.include(priorForkFinalText, "fork boundary alpha");
|
||||
assert.notInclude(priorForkFinalText, "fork boundary beta");
|
||||
|
||||
const forkLocalRollback = await readClaudeTranscriptFixture(
|
||||
"thread_fork_native_fork_local_rollback",
|
||||
);
|
||||
assert.equal(forkLocalRollback.metadata?.queryMode, "fork_session_resume_at_fork_cursor");
|
||||
const forkLocalRollbackCursor = metadataString(forkLocalRollback, "resumeSessionAt");
|
||||
const forkLocalRollbackFrame = findEntryFrame(
|
||||
forkLocalRollback,
|
||||
"query.open:fork-resume-at-cursor",
|
||||
);
|
||||
const forkLocalRollbackOptions = forkLocalRollbackFrame.options;
|
||||
if (!isRecord(forkLocalRollbackOptions)) {
|
||||
throw new Error("Fork-local rollback resume query.open options must be an object.");
|
||||
}
|
||||
assert.equal(forkLocalRollbackOptions.resumeSessionAt, forkLocalRollbackCursor);
|
||||
const forkLocalRollbackFinalText = successResultTexts(forkLocalRollback).at(-1) ?? "";
|
||||
assert.include(forkLocalRollbackFinalText, "fork local source alpha");
|
||||
assert.include(forkLocalRollbackFinalText, "fork local first");
|
||||
assert.notInclude(forkLocalRollbackFinalText, "fork local second");
|
||||
});
|
||||
|
||||
it.skipIf(process.env.T3_RECORD_CLAUDE_AGENT_SDK_FIXTURE !== "1")(
|
||||
"records simple from real Claude Code query() output",
|
||||
async () => {
|
||||
@@ -109,7 +227,7 @@ describe("Claude Agent SDK replay fixtures", () => {
|
||||
assert.equal(transcript.protocol, "claude-agent-sdk.query");
|
||||
assert.isAtLeast(transcript.entries.length, 3);
|
||||
} finally {
|
||||
await rm(checkpointWorkspace, { recursive: true, force: true });
|
||||
await removeDirectory(checkpointWorkspace);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import type { ProviderReplayTranscript } from "@t3tools/contracts";
|
||||
import * as CodexReplay from "effect-codex-app-server/replay";
|
||||
import { Effect, Schema } from "effect";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { ORCHESTRATOR_REPLAY_FIXTURES } from "./fixtures/index.ts";
|
||||
import { decodeProviderReplayNdjson } from "./ReplayTranscriptNdjson.ts";
|
||||
@@ -166,7 +168,12 @@ const scenarioExpectations = {
|
||||
} as const;
|
||||
|
||||
async function readTranscript(file: URL): Promise<ProviderReplayTranscript> {
|
||||
const text = await readFile(file, "utf8");
|
||||
const text = await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
return yield* fs.readFileString(decodeURIComponent(file.pathname));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
return await Effect.runPromise(decodeProviderReplayNdjson(text));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Effect, Random } from "effect";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Random from "effect/Random";
|
||||
import { TestClock } from "effect/testing";
|
||||
|
||||
export function provideDeterministicTestRuntime<A, E, R>(
|
||||
|
||||
+10
-3
@@ -1,7 +1,9 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { OrchestrationV2Command, type ProviderReplayTranscript } from "@t3tools/contracts";
|
||||
import { Effect, Schema } from "effect";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { layer as idAllocatorLayer } from "../IdAllocator.ts";
|
||||
import { provideDeterministicTestRuntime } from "./DeterministicRuntime.ts";
|
||||
@@ -10,7 +12,12 @@ import { materializeFixtureInput } from "./fixtures/shared.ts";
|
||||
import { decodeProviderReplayNdjson } from "./ReplayTranscriptNdjson.ts";
|
||||
|
||||
async function readTranscript(file: URL): Promise<ProviderReplayTranscript> {
|
||||
const text = await readFile(file, "utf8");
|
||||
const text = await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
return yield* fs.readFileString(decodeURIComponent(file.pathname));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
return await Effect.runPromise(decodeProviderReplayNdjson(text));
|
||||
}
|
||||
|
||||
|
||||
+19
-4
@@ -1,7 +1,8 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import type { ProviderReplayTranscript } from "@t3tools/contracts";
|
||||
import { Effect } from "effect";
|
||||
import { readFile, rm } from "node:fs/promises";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
|
||||
import { ClaudeOrchestratorReplayHarness } from "../Adapters/ClaudeAdapterV2.testkit.ts";
|
||||
import { CodexOrchestratorReplayHarness } from "../Adapters/CodexAdapterV2.testkit.ts";
|
||||
@@ -21,10 +22,24 @@ import { makeCheckpointWorkspace } from "./ReplayFixtureWorkspace.ts";
|
||||
import { decodeProviderReplayNdjson } from "./ReplayTranscriptNdjson.ts";
|
||||
|
||||
async function readTranscript(file: URL): Promise<ProviderReplayTranscript> {
|
||||
const text = await readFile(file, "utf8");
|
||||
const text = await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
return yield* fs.readFileString(decodeURIComponent(file.pathname));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
return await Effect.runPromise(decodeProviderReplayNdjson(text));
|
||||
}
|
||||
|
||||
async function removeDirectory(path: string): Promise<void> {
|
||||
await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
yield* fs.remove(path, { recursive: true, force: true });
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
}
|
||||
|
||||
async function runFixtureProvider<Transcript extends ProviderReplayTranscript, Error>(input: {
|
||||
readonly fixtureName: string;
|
||||
readonly buildInput: () => OrchestratorFixtureInput;
|
||||
@@ -68,7 +83,7 @@ async function runFixtureProvider<Transcript extends ProviderReplayTranscript, E
|
||||
const latestRun = projection.runs.at(-1);
|
||||
assert.deepEqual(latestRun?.modelSelection, input.provider.modelSelection);
|
||||
} finally {
|
||||
await rm(checkpointWorkspace, { recursive: true, force: true });
|
||||
await removeDirectory(checkpointWorkspace);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+25
-12
@@ -1,11 +1,11 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as CodexReplay from "effect-codex-app-server/replay";
|
||||
import { mkdirSync, mkdtempSync } from "node:fs";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import {
|
||||
CodexOrchestratorReplayHarness,
|
||||
@@ -38,9 +38,15 @@ const FIRST_FINAL = "provider thread resume fixture first turn complete";
|
||||
const SECOND_FINAL = "provider thread resume fixture second turn complete";
|
||||
|
||||
async function readCodexTranscript(): Promise<CodexReplay.CodexAppServerReplayTranscript> {
|
||||
const text = await readFile(
|
||||
new URL("./fixtures/provider_thread_resume/codex_transcript.ndjson", import.meta.url),
|
||||
"utf8",
|
||||
const file = new URL(
|
||||
"./fixtures/provider_thread_resume/codex_transcript.ndjson",
|
||||
import.meta.url,
|
||||
);
|
||||
const text = await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
return yield* fs.readFileString(decodeURIComponent(file.pathname));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
const transcript = await Effect.runPromise(decodeProviderReplayNdjson(text));
|
||||
return Schema.decodeUnknownSync(CodexReplay.CodexAppServerReplayTranscript)(transcript);
|
||||
@@ -65,12 +71,16 @@ function splitAfterFirstIdle(materialized: MaterializedOrchestratorFixtureInput)
|
||||
describe("orchestrator replay recovery", () => {
|
||||
it("resumes a provider-native Codex thread after recreating the orchestrator runtime", async () => {
|
||||
const transcript = await readCodexTranscript();
|
||||
const tempDir = mkdtempSync(path.join(tmpdir(), "t3-orchestration-v2-recovery-"));
|
||||
mkdirSync(tempDir, { recursive: true });
|
||||
const dbPath = path.join(tempDir, "state.sqlite");
|
||||
|
||||
await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempDir = yield* fs.makeTempDirectory({
|
||||
prefix: "t3-orchestration-v2-recovery-",
|
||||
});
|
||||
yield* fs.makeDirectory(tempDir, { recursive: true });
|
||||
const dbPath = path.join(tempDir, "state.sqlite");
|
||||
const driver = yield* CodexReplay.makeReplayDriver(transcript);
|
||||
const materialized = yield* materializeFixtureInput({
|
||||
scenario: "provider_thread_resume",
|
||||
@@ -136,7 +146,10 @@ describe("orchestrator replay recovery", () => {
|
||||
assertAssistantTextIncludes(projection, FIRST_FINAL);
|
||||
assertAssistantTextIncludes(projection, SECOND_FINAL);
|
||||
assert.lengthOf(projection.providerThreads, 1);
|
||||
}).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime),
|
||||
}).pipe(
|
||||
Effect.provide(Layer.mergeAll(idAllocatorLayer, NodeServices.layer)),
|
||||
provideDeterministicTestRuntime,
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -12,7 +12,12 @@ import type {
|
||||
CommandId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Duration, Effect, Fiber, Ref, Schema, Stream } from "effect";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { TestClock } from "effect/testing";
|
||||
|
||||
import { OrchestratorV2, type OrchestratorV2Error } from "../Orchestrator.ts";
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import type { ProviderKind, ProviderReplayTranscript } from "@t3tools/contracts";
|
||||
import { Effect, Layer, PlatformError } from "effect";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import type * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import type { MigrationError } from "effect/unstable/sql/Migrator";
|
||||
import type { SqlError } from "effect/unstable/sql/SqlError";
|
||||
import { mkdirSync, mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
|
||||
import { ServerConfig, type ServerConfigShape } from "../../config.ts";
|
||||
@@ -38,70 +39,84 @@ import {
|
||||
type OrchestratorV2ScenarioResult,
|
||||
} from "./OrchestratorScenario.ts";
|
||||
|
||||
function makeReplayServerConfig(scenario: string): ServerConfigShape {
|
||||
function makeReplayServerConfig(
|
||||
scenario: string,
|
||||
): Effect.Effect<
|
||||
ServerConfigShape,
|
||||
PlatformError.PlatformError,
|
||||
FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const safeScenario = scenario.replace(/[^a-z0-9_-]+/gi, "-");
|
||||
const baseDir = mkdtempSync(path.join(tmpdir(), `t3-orchestration-v2-replay-${safeScenario}-`));
|
||||
const stateDir = path.join(baseDir, "userdata");
|
||||
const logsDir = path.join(stateDir, "logs");
|
||||
const providerLogsDir = path.join(logsDir, "provider");
|
||||
const terminalLogsDir = path.join(logsDir, "terminals");
|
||||
const attachmentsDir = path.join(stateDir, "attachments");
|
||||
const worktreesDir = path.join(baseDir, "worktrees");
|
||||
const providerStatusCacheDir = path.join(baseDir, "caches");
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const baseDir = yield* fs.makeTempDirectory({
|
||||
prefix: `t3-orchestration-v2-replay-${safeScenario}-`,
|
||||
});
|
||||
const stateDir = path.join(baseDir, "userdata");
|
||||
const logsDir = path.join(stateDir, "logs");
|
||||
const providerLogsDir = path.join(logsDir, "provider");
|
||||
const terminalLogsDir = path.join(logsDir, "terminals");
|
||||
const attachmentsDir = path.join(stateDir, "attachments");
|
||||
const worktreesDir = path.join(baseDir, "worktrees");
|
||||
const providerStatusCacheDir = path.join(baseDir, "caches");
|
||||
|
||||
for (const directory of [
|
||||
stateDir,
|
||||
logsDir,
|
||||
providerLogsDir,
|
||||
terminalLogsDir,
|
||||
attachmentsDir,
|
||||
worktreesDir,
|
||||
providerStatusCacheDir,
|
||||
]) {
|
||||
mkdirSync(directory, { recursive: true });
|
||||
}
|
||||
for (const directory of [
|
||||
stateDir,
|
||||
logsDir,
|
||||
providerLogsDir,
|
||||
terminalLogsDir,
|
||||
attachmentsDir,
|
||||
worktreesDir,
|
||||
providerStatusCacheDir,
|
||||
]) {
|
||||
yield* fs.makeDirectory(directory, { recursive: true });
|
||||
}
|
||||
|
||||
return {
|
||||
logLevel: "Error",
|
||||
traceMinLevel: "Info",
|
||||
traceTimingEnabled: true,
|
||||
traceBatchWindowMs: 200,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
otlpTracesUrl: undefined,
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
otlpServiceName: "t3-server",
|
||||
mode: "web",
|
||||
port: 0,
|
||||
host: undefined,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
stateDir,
|
||||
dbPath: path.join(stateDir, "state.sqlite"),
|
||||
keybindingsConfigPath: path.join(stateDir, "keybindings.json"),
|
||||
settingsPath: path.join(stateDir, "settings.json"),
|
||||
providerStatusCacheDir,
|
||||
worktreesDir,
|
||||
attachmentsDir,
|
||||
logsDir,
|
||||
serverLogPath: path.join(logsDir, "server.log"),
|
||||
serverTracePath: path.join(logsDir, "server.trace.ndjson"),
|
||||
providerLogsDir,
|
||||
providerEventLogPath: path.join(providerLogsDir, "events.log"),
|
||||
terminalLogsDir,
|
||||
anonymousIdPath: path.join(stateDir, "anonymous-id"),
|
||||
environmentIdPath: path.join(stateDir, "environment-id"),
|
||||
serverRuntimeStatePath: path.join(stateDir, "server-runtime.json"),
|
||||
secretsDir: path.join(stateDir, "secrets"),
|
||||
};
|
||||
return {
|
||||
logLevel: "Error",
|
||||
traceMinLevel: "Info",
|
||||
traceTimingEnabled: true,
|
||||
traceBatchWindowMs: 200,
|
||||
traceMaxBytes: 10 * 1024 * 1024,
|
||||
traceMaxFiles: 10,
|
||||
otlpTracesUrl: undefined,
|
||||
otlpMetricsUrl: undefined,
|
||||
otlpExportIntervalMs: 10_000,
|
||||
otlpServiceName: "t3-server",
|
||||
mode: "web",
|
||||
port: 0,
|
||||
host: undefined,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
stateDir,
|
||||
dbPath: path.join(stateDir, "state.sqlite"),
|
||||
keybindingsConfigPath: path.join(stateDir, "keybindings.json"),
|
||||
settingsPath: path.join(stateDir, "settings.json"),
|
||||
providerStatusCacheDir,
|
||||
worktreesDir,
|
||||
attachmentsDir,
|
||||
logsDir,
|
||||
serverLogPath: path.join(logsDir, "server.log"),
|
||||
serverTracePath: path.join(logsDir, "server.trace.ndjson"),
|
||||
providerLogsDir,
|
||||
providerEventLogPath: path.join(providerLogsDir, "events.log"),
|
||||
terminalLogsDir,
|
||||
anonymousIdPath: path.join(stateDir, "anonymous-id"),
|
||||
environmentIdPath: path.join(stateDir, "environment-id"),
|
||||
serverRuntimeStatePath: path.join(stateDir, "server-runtime.json"),
|
||||
secretsDir: path.join(stateDir, "secrets"),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export interface OrchestratorV2ProviderReplayScenario<
|
||||
@@ -165,7 +180,10 @@ export function makeOrchestratorV2ProviderReplayLayer<
|
||||
} = {},
|
||||
): Layer.Layer<OrchestratorV2, Error | MigrationError | PlatformError.PlatformError | SqlError> {
|
||||
const registryLayer = harness.makeProviderAdapterRegistryLayer(scenario.transcript);
|
||||
const serverConfigLayer = Layer.succeed(ServerConfig, makeReplayServerConfig(scenario.name));
|
||||
const serverConfigLayer = Layer.effect(
|
||||
ServerConfig,
|
||||
makeReplayServerConfig(scenario.name).pipe(Effect.orDie),
|
||||
).pipe(Layer.provide(NodeServices.layer));
|
||||
const runtimeLayer =
|
||||
scenario.runtimePolicyOverride === undefined
|
||||
? runtimePolicyLayer
|
||||
|
||||
@@ -1,18 +1,58 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdtemp, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
class ReplayFixtureGitCommandError extends Schema.TaggedErrorClass<ReplayFixtureGitCommandError>()(
|
||||
"ReplayFixtureGitCommandError",
|
||||
{
|
||||
command: Schema.String,
|
||||
exitCode: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `${this.command} failed with exit ${this.exitCode}.`;
|
||||
}
|
||||
}
|
||||
|
||||
function runGit(
|
||||
cwd: string,
|
||||
args: ReadonlyArray<string>,
|
||||
): Effect.Effect<
|
||||
void,
|
||||
ReplayFixtureGitCommandError | PlatformError.PlatformError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const exitCode = yield* spawner.exitCode(ChildProcess.make("git", args, { cwd }));
|
||||
if (Number(exitCode) !== 0) {
|
||||
return yield* new ReplayFixtureGitCommandError({
|
||||
command: `git ${args.join(" ")}`,
|
||||
exitCode: Number(exitCode),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function makeCheckpointWorkspace(fixtureName: string): Promise<string> {
|
||||
const cwd = await mkdtemp(path.join(tmpdir(), `t3-orchestrator-v2-${fixtureName}-`));
|
||||
await execFileAsync("git", ["init"], { cwd });
|
||||
await execFileAsync("git", ["config", "user.name", "T3 Code Test"], { cwd });
|
||||
await execFileAsync("git", ["config", "user.email", "[email protected]"], { cwd });
|
||||
await writeFile(path.join(cwd, "README.md"), `# ${fixtureName}\n`, "utf8");
|
||||
await execFileAsync("git", ["add", "README.md"], { cwd });
|
||||
await execFileAsync("git", ["commit", "-m", "initial"], { cwd });
|
||||
return cwd;
|
||||
return await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const cwd = yield* fs.makeTempDirectory({
|
||||
prefix: `t3-orchestrator-v2-${fixtureName}-`,
|
||||
});
|
||||
yield* runGit(cwd, ["init"]);
|
||||
yield* runGit(cwd, ["config", "user.name", "T3 Code Test"]);
|
||||
yield* runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||
yield* fs.writeFileString(path.join(cwd, "README.md"), `# ${fixtureName}\n`);
|
||||
yield* runGit(cwd, ["add", "README.md"]);
|
||||
yield* runGit(cwd, ["commit", "-m", "initial"]);
|
||||
return cwd;
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ProviderReplayNdjsonParseError } from "./ReplayTranscriptNdjson.ts";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect, Schema } from "effect";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { decodeProviderReplayNdjson } from "./ReplayTranscriptNdjson.ts";
|
||||
|
||||
|
||||
@@ -4,7 +4,8 @@ import {
|
||||
ProviderReplayTranscript,
|
||||
type ProviderReplayTranscriptHeader,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Schema } from "effect";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export class ProviderReplayNdjsonLineParseError extends Schema.TaggedErrorClass<ProviderReplayNdjsonLineParseError>()(
|
||||
"ProviderReplayNdjsonLineParseError",
|
||||
|
||||
@@ -4,22 +4,46 @@ import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
type OrchestrationV2Command,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
ProviderInstanceId,
|
||||
type ProviderReplayEntry,
|
||||
type ProviderReplayTranscript,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, FileSystem, Path } from "effect";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ClaudeOrchestratorReplayHarness } from "../Adapters/ClaudeAdapterV2.testkit.ts";
|
||||
import { CodexOrchestratorReplayHarness } from "../Adapters/CodexAdapterV2.testkit.ts";
|
||||
import { IdAllocatorV2, layer as idAllocatorLayer } from "../IdAllocator.ts";
|
||||
import { provideDeterministicTestRuntime } from "./DeterministicRuntime.ts";
|
||||
import {
|
||||
THREAD_FORK_NATIVE_PRIOR_TURN_ALPHA_PROMPT,
|
||||
THREAD_FORK_NATIVE_PRIOR_TURN_BETA_PROMPT,
|
||||
THREAD_FORK_NATIVE_PRIOR_TURN_REPEAT_PROMPT,
|
||||
THREAD_FORK_NATIVE_SOURCE_PROMPT,
|
||||
THREAD_FORK_NATIVE_TARGET_PROMPT,
|
||||
} from "./fixtures/shared.ts";
|
||||
import { runOrchestratorV2ProviderReplayScenario } from "./ProviderReplayHarness.ts";
|
||||
import { decodeProviderReplayNdjson } from "./ReplayTranscriptNdjson.ts";
|
||||
|
||||
const CODEX_MODEL_SELECTION = { provider: "codex", model: "gpt-5.4" } as const;
|
||||
const CODEX_MODEL_SELECTION = {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
} as const;
|
||||
const CLAUDE_MODEL_SELECTION = {
|
||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
model: "claude-sonnet-4-6",
|
||||
} as const;
|
||||
const TRANSCRIPT_PATH = `${import.meta.dirname}/fixtures/thread_fork_native/codex_transcript.ndjson`;
|
||||
const PRIOR_TURN_TRANSCRIPT_PATH = `${import.meta.dirname}/fixtures/thread_fork_native_prior_turn/codex_transcript.ndjson`;
|
||||
const CLAUDE_TRANSCRIPT_PATH = `${import.meta.dirname}/fixtures/thread_fork_native/claude_transcript.ndjson`;
|
||||
const CLAUDE_PRIOR_TURN_TRANSCRIPT_PATH = `${import.meta.dirname}/fixtures/thread_fork_native_prior_turn/claude_transcript.ndjson`;
|
||||
const CLAUDE_FORK_LOCAL_ROLLBACK_TRANSCRIPT_PATH = `${import.meta.dirname}/fixtures/thread_fork_native_fork_local_rollback/claude_transcript.ndjson`;
|
||||
const CODEX_READ_ONLY_NEVER_POLICY = {
|
||||
approvalPolicy: "never",
|
||||
sandboxPolicy: {
|
||||
@@ -29,12 +53,34 @@ const CODEX_READ_ONLY_NEVER_POLICY = {
|
||||
},
|
||||
} as const;
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
class ThreadForkGitCommandError extends Schema.TaggedErrorClass<ThreadForkGitCommandError>()(
|
||||
"ThreadForkGitCommandError",
|
||||
{
|
||||
command: Schema.String,
|
||||
exitCode: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `${this.command} failed with exit ${this.exitCode}.`;
|
||||
}
|
||||
}
|
||||
|
||||
function runGit(
|
||||
cwd: string,
|
||||
args: ReadonlyArray<string>,
|
||||
): Effect.Effect<
|
||||
void,
|
||||
ThreadForkGitCommandError | PlatformError.PlatformError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const exitCode = yield* spawner.exitCode(ChildProcess.make("git", args, { cwd }));
|
||||
if (Number(exitCode) !== 0) {
|
||||
return yield* Effect.fail(new Error(`git ${args.join(" ")} failed with exit ${exitCode}`));
|
||||
return yield* new ThreadForkGitCommandError({
|
||||
command: `git ${args.join(" ")}`,
|
||||
exitCode: Number(exitCode),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -60,6 +106,36 @@ function readTranscript(transcriptPath: string = TRANSCRIPT_PATH) {
|
||||
});
|
||||
}
|
||||
|
||||
function metadataString(transcript: ProviderReplayTranscript, key: string): string {
|
||||
const value = transcript.metadata?.[key];
|
||||
if (typeof value !== "string") {
|
||||
throw new Error(`Transcript ${transcript.scenario} is missing metadata string ${key}.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function metadataStringArray(
|
||||
transcript: ProviderReplayTranscript,
|
||||
key: string,
|
||||
): ReadonlyArray<string> {
|
||||
const value = transcript.metadata?.[key];
|
||||
if (!Array.isArray(value) || !value.every((entry) => typeof entry === "string")) {
|
||||
throw new Error(`Transcript ${transcript.scenario} is missing metadata string array ${key}.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function userAndAssistantText(
|
||||
projection: Pick<OrchestrationV2ThreadProjection, "visibleTurnItems">,
|
||||
): string {
|
||||
return projection.visibleTurnItems
|
||||
.flatMap((row) => {
|
||||
const item = row.item;
|
||||
return item.type === "user_message" || item.type === "assistant_message" ? [item.text] : [];
|
||||
})
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
function compactExpectedText(text: string, maxLength = 240): string {
|
||||
const compacted = text.replace(/\s+/g, " ").trim();
|
||||
if (compacted.length <= maxLength) {
|
||||
@@ -365,7 +441,7 @@ describe("orchestration V2 thread fork", () => {
|
||||
}),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-source"),
|
||||
text: "Respond with the following text: source fork seed ok",
|
||||
text: THREAD_FORK_NATIVE_SOURCE_PROMPT,
|
||||
attachments: [],
|
||||
modelSelection: CODEX_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
@@ -394,7 +470,7 @@ describe("orchestration V2 thread fork", () => {
|
||||
}),
|
||||
threadId: targetThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-target"),
|
||||
text: "Respond with the following text: fork native ok",
|
||||
text: THREAD_FORK_NATIVE_TARGET_PROMPT,
|
||||
attachments: [],
|
||||
modelSelection: CODEX_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
@@ -488,6 +564,137 @@ describe("orchestration V2 thread fork", () => {
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"creates an idle app fork and resolves it with Claude native session fork on first dispatch",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const rawTranscript = yield* readTranscript(CLAUDE_TRANSCRIPT_PATH);
|
||||
const transcript = yield* ClaudeOrchestratorReplayHarness.decodeTranscript(rawTranscript);
|
||||
const forkedNativeSessionId = metadataString(transcript, "forkedNativeSessionId");
|
||||
const cwd = yield* Effect.acquireRelease(makeCheckpointWorkspace, (directory) =>
|
||||
Effect.service(FileSystem.FileSystem).pipe(
|
||||
Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })),
|
||||
Effect.orDie,
|
||||
),
|
||||
);
|
||||
|
||||
const materialized = yield* Effect.gen(function* () {
|
||||
const ids = yield* IdAllocatorV2;
|
||||
const projectId = yield* ids.allocate.project({ fixtureName: "thread-fork-native" });
|
||||
const sourceThreadId = yield* ids.allocate.thread({
|
||||
fixtureName: "thread-fork-native-source",
|
||||
projectId,
|
||||
});
|
||||
const targetThreadId = ThreadId.make("thread-fork-native-target");
|
||||
|
||||
const commands = [
|
||||
{
|
||||
type: "thread.create",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native",
|
||||
commandName: "thread-create-source",
|
||||
}),
|
||||
threadId: sourceThreadId,
|
||||
projectId,
|
||||
title: "Source thread",
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native",
|
||||
commandName: "source-message",
|
||||
}),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-source"),
|
||||
text: THREAD_FORK_NATIVE_SOURCE_PROMPT,
|
||||
attachments: [],
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
},
|
||||
{
|
||||
type: "thread.fork",
|
||||
commandId: CommandId.make("command-thread-fork-native"),
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
sourcePoint: { type: "latest_stable" },
|
||||
title: "Forked thread",
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native",
|
||||
commandName: "target-message",
|
||||
}),
|
||||
threadId: targetThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-target"),
|
||||
text: THREAD_FORK_NATIVE_TARGET_PROMPT,
|
||||
attachments: [],
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
},
|
||||
] satisfies ReadonlyArray<OrchestrationV2Command>;
|
||||
|
||||
return {
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
commands,
|
||||
};
|
||||
}).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime);
|
||||
|
||||
const result = yield* runOrchestratorV2ProviderReplayScenario(
|
||||
{
|
||||
name: "thread_fork_native/claude",
|
||||
transcript,
|
||||
commands: materialized.commands,
|
||||
steps: [
|
||||
{ type: "dispatch", command: materialized.commands[0]!, await: true },
|
||||
{ type: "advance_clock", duration: "1 millis" },
|
||||
{ type: "dispatch", command: materialized.commands[1]!, await: true },
|
||||
{ type: "await_thread_idle", threadId: materialized.sourceThreadId },
|
||||
{ type: "dispatch", command: materialized.commands[2]!, await: true },
|
||||
{ type: "dispatch", command: materialized.commands[3]!, await: true },
|
||||
{ type: "await_thread_idle", threadId: materialized.targetThreadId },
|
||||
],
|
||||
projectionThreadIds: [materialized.sourceThreadId, materialized.targetThreadId],
|
||||
runtimePolicyOverride: { cwd },
|
||||
},
|
||||
ClaudeOrchestratorReplayHarness,
|
||||
).pipe(provideDeterministicTestRuntime);
|
||||
|
||||
const sourceProjection = result.projections.get(materialized.sourceThreadId);
|
||||
const targetProjection = result.projections.get(materialized.targetThreadId);
|
||||
assert.isDefined(sourceProjection);
|
||||
assert.isDefined(targetProjection);
|
||||
assert.equal(
|
||||
targetProjection.providerThreads[0]?.nativeThreadRef?.nativeId,
|
||||
forkedNativeSessionId,
|
||||
);
|
||||
assert.equal(
|
||||
targetProjection.providerThreads[0]?.forkedFrom?.providerThreadId,
|
||||
sourceProjection.providerThreads[0]?.id,
|
||||
);
|
||||
assert.include(
|
||||
targetProjection.turnItems
|
||||
.filter((item) => item.type === "assistant_message")
|
||||
.map((item) => item.text)
|
||||
.join("\n"),
|
||||
"fork native ok",
|
||||
);
|
||||
|
||||
const transfers = targetProjection.contextTransfers.filter(
|
||||
(transfer) => transfer.targetThreadId === materialized.targetThreadId,
|
||||
);
|
||||
assert.lengthOf(transfers, 1);
|
||||
assert.equal(transfers[0]?.status, "consumed");
|
||||
assert.equal(transfers[0]?.resolution?.strategy, "native_fork");
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"rolls back a Codex native fork when forking from an earlier completed source turn",
|
||||
() =>
|
||||
@@ -537,7 +744,7 @@ describe("orchestration V2 thread fork", () => {
|
||||
}),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-prior-turn-alpha"),
|
||||
text: "For this fork-boundary fixture, respond with exactly: fork boundary alpha",
|
||||
text: THREAD_FORK_NATIVE_PRIOR_TURN_ALPHA_PROMPT,
|
||||
attachments: [],
|
||||
modelSelection: CODEX_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
@@ -550,7 +757,7 @@ describe("orchestration V2 thread fork", () => {
|
||||
}),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-prior-turn-beta"),
|
||||
text: "For this fork-boundary fixture, respond with exactly: fork boundary beta",
|
||||
text: THREAD_FORK_NATIVE_PRIOR_TURN_BETA_PROMPT,
|
||||
attachments: [],
|
||||
modelSelection: CODEX_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
@@ -571,7 +778,7 @@ describe("orchestration V2 thread fork", () => {
|
||||
}),
|
||||
threadId: targetThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-prior-turn-repeat"),
|
||||
text: "Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content.",
|
||||
text: THREAD_FORK_NATIVE_PRIOR_TURN_REPEAT_PROMPT,
|
||||
attachments: [],
|
||||
modelSelection: CODEX_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
@@ -660,14 +867,526 @@ describe("orchestration V2 thread fork", () => {
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("forks a Claude native session from an earlier completed source turn", () =>
|
||||
Effect.gen(function* () {
|
||||
const rawTranscript = yield* readTranscript(CLAUDE_PRIOR_TURN_TRANSCRIPT_PATH);
|
||||
const transcript = yield* ClaudeOrchestratorReplayHarness.decodeTranscript(rawTranscript);
|
||||
const forkedNativeSessionId = metadataString(transcript, "forkedNativeSessionId");
|
||||
const cwd = yield* Effect.acquireRelease(makeCheckpointWorkspace, (directory) =>
|
||||
Effect.service(FileSystem.FileSystem).pipe(
|
||||
Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })),
|
||||
Effect.orDie,
|
||||
),
|
||||
);
|
||||
|
||||
const materialized = yield* Effect.gen(function* () {
|
||||
const ids = yield* IdAllocatorV2;
|
||||
const projectId = yield* ids.allocate.project({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
});
|
||||
const sourceThreadId = yield* ids.allocate.thread({
|
||||
fixtureName: "thread-fork-native-prior-turn-source",
|
||||
projectId,
|
||||
});
|
||||
const targetThreadId = ThreadId.make("thread-fork-native-prior-turn-target");
|
||||
const firstRunId = ids.derive.run({ threadId: sourceThreadId, ordinal: 1 });
|
||||
|
||||
const commands = [
|
||||
{
|
||||
type: "thread.create",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "thread-create-source",
|
||||
}),
|
||||
threadId: sourceThreadId,
|
||||
projectId,
|
||||
title: "Source thread",
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "source-message-alpha",
|
||||
}),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-prior-turn-alpha"),
|
||||
text: THREAD_FORK_NATIVE_PRIOR_TURN_ALPHA_PROMPT,
|
||||
attachments: [],
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "source-message-beta",
|
||||
}),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-prior-turn-beta"),
|
||||
text: THREAD_FORK_NATIVE_PRIOR_TURN_BETA_PROMPT,
|
||||
attachments: [],
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
},
|
||||
{
|
||||
type: "thread.fork",
|
||||
commandId: CommandId.make("command-thread-fork-native-prior-turn"),
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
sourcePoint: { type: "run", runId: firstRunId },
|
||||
title: "Forked from first response",
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn",
|
||||
commandName: "target-message-repeat",
|
||||
}),
|
||||
threadId: targetThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-prior-turn-repeat"),
|
||||
text: THREAD_FORK_NATIVE_PRIOR_TURN_REPEAT_PROMPT,
|
||||
attachments: [],
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
},
|
||||
] satisfies ReadonlyArray<OrchestrationV2Command>;
|
||||
|
||||
return {
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
commands,
|
||||
};
|
||||
}).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime);
|
||||
|
||||
const result = yield* runOrchestratorV2ProviderReplayScenario(
|
||||
{
|
||||
name: "thread_fork_native_prior_turn/claude",
|
||||
transcript,
|
||||
commands: materialized.commands,
|
||||
steps: [
|
||||
{ type: "dispatch", command: materialized.commands[0]!, await: true },
|
||||
{ type: "advance_clock", duration: "1 millis" },
|
||||
{ type: "dispatch", command: materialized.commands[1]!, await: true },
|
||||
{ type: "await_thread_idle", threadId: materialized.sourceThreadId },
|
||||
{ type: "dispatch", command: materialized.commands[2]!, await: true },
|
||||
{ type: "await_thread_idle", threadId: materialized.sourceThreadId },
|
||||
{ type: "dispatch", command: materialized.commands[3]!, await: true },
|
||||
{ type: "dispatch", command: materialized.commands[4]!, await: true },
|
||||
{ type: "await_thread_idle", threadId: materialized.targetThreadId },
|
||||
],
|
||||
projectionThreadIds: [materialized.sourceThreadId, materialized.targetThreadId],
|
||||
runtimePolicyOverride: { cwd },
|
||||
},
|
||||
ClaudeOrchestratorReplayHarness,
|
||||
).pipe(provideDeterministicTestRuntime);
|
||||
|
||||
const targetProjection = result.projections.get(materialized.targetThreadId);
|
||||
assert.isDefined(targetProjection);
|
||||
assert.equal(
|
||||
targetProjection.providerThreads[0]?.nativeThreadRef?.nativeId,
|
||||
forkedNativeSessionId,
|
||||
);
|
||||
const targetAssistantText = targetProjection.turnItems
|
||||
.filter((item) => item.type === "assistant_message")
|
||||
.map((item) => item.text)
|
||||
.join("\n");
|
||||
assert.include(targetAssistantText, "fork boundary alpha");
|
||||
assert.notInclude(
|
||||
targetAssistantText,
|
||||
"fork boundary beta",
|
||||
"forking from the first source run must not preserve later source turns in native Claude context",
|
||||
);
|
||||
assert.equal(targetProjection.contextTransfers[0]?.resolution?.strategy, "native_fork");
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("keeps a Claude native fork stable when the source thread rolls back", () =>
|
||||
Effect.gen(function* () {
|
||||
const rawTranscript = yield* readTranscript(CLAUDE_PRIOR_TURN_TRANSCRIPT_PATH);
|
||||
const transcript = yield* ClaudeOrchestratorReplayHarness.decodeTranscript(rawTranscript);
|
||||
const forkedNativeSessionId = metadataString(transcript, "forkedNativeSessionId");
|
||||
const sourceAssistantMessageUuids = metadataStringArray(
|
||||
transcript,
|
||||
"sourceAssistantMessageUuids",
|
||||
);
|
||||
const cwd = yield* Effect.acquireRelease(makeCheckpointWorkspace, (directory) =>
|
||||
Effect.service(FileSystem.FileSystem).pipe(
|
||||
Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })),
|
||||
Effect.orDie,
|
||||
),
|
||||
);
|
||||
|
||||
const materialized = yield* Effect.gen(function* () {
|
||||
const ids = yield* IdAllocatorV2;
|
||||
const projectId = yield* ids.allocate.project({
|
||||
fixtureName: "thread-fork-native-prior-turn-source-rollback",
|
||||
});
|
||||
const sourceThreadId = yield* ids.allocate.thread({
|
||||
fixtureName: "thread-fork-native-prior-turn-source-rollback-source",
|
||||
projectId,
|
||||
});
|
||||
const targetThreadId = ThreadId.make(
|
||||
"thread-fork-native-prior-turn-source-rollback-target",
|
||||
);
|
||||
const firstRunId = ids.derive.run({ threadId: sourceThreadId, ordinal: 1 });
|
||||
const checkpointScopeId = yield* ids.allocate.checkpointScope({
|
||||
threadId: sourceThreadId,
|
||||
name: "root",
|
||||
});
|
||||
const firstCheckpointId = yield* ids.allocate.checkpoint({
|
||||
checkpointScopeId,
|
||||
name: "1",
|
||||
});
|
||||
|
||||
const commands = [
|
||||
{
|
||||
type: "thread.create",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn-source-rollback",
|
||||
commandName: "thread-create-source",
|
||||
}),
|
||||
threadId: sourceThreadId,
|
||||
projectId,
|
||||
title: "Source thread",
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn-source-rollback",
|
||||
commandName: "source-message-alpha",
|
||||
}),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make(
|
||||
"message-thread-fork-native-prior-turn-source-rollback-alpha",
|
||||
),
|
||||
text: THREAD_FORK_NATIVE_PRIOR_TURN_ALPHA_PROMPT,
|
||||
attachments: [],
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn-source-rollback",
|
||||
commandName: "source-message-beta",
|
||||
}),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-prior-turn-source-rollback-beta"),
|
||||
text: THREAD_FORK_NATIVE_PRIOR_TURN_BETA_PROMPT,
|
||||
attachments: [],
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
},
|
||||
{
|
||||
type: "thread.fork",
|
||||
commandId: CommandId.make("command-thread-fork-native-prior-turn-source-rollback"),
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
sourcePoint: { type: "run", runId: firstRunId },
|
||||
title: "Forked from first response",
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn-source-rollback",
|
||||
commandName: "target-message-repeat",
|
||||
}),
|
||||
threadId: targetThreadId,
|
||||
messageId: MessageId.make(
|
||||
"message-thread-fork-native-prior-turn-source-rollback-repeat",
|
||||
),
|
||||
text: THREAD_FORK_NATIVE_PRIOR_TURN_REPEAT_PROMPT,
|
||||
attachments: [],
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
},
|
||||
{
|
||||
type: "checkpoint.rollback",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-prior-turn-source-rollback",
|
||||
commandName: "rollback-source-to-alpha",
|
||||
}),
|
||||
threadId: sourceThreadId,
|
||||
scopeId: checkpointScopeId,
|
||||
checkpointId: firstCheckpointId,
|
||||
},
|
||||
] satisfies ReadonlyArray<OrchestrationV2Command>;
|
||||
|
||||
return {
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
commands,
|
||||
};
|
||||
}).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime);
|
||||
|
||||
const result = yield* runOrchestratorV2ProviderReplayScenario(
|
||||
{
|
||||
name: "thread_fork_native_prior_turn_source_rollback/claude",
|
||||
transcript,
|
||||
commands: materialized.commands,
|
||||
steps: [
|
||||
{ type: "dispatch", command: materialized.commands[0]!, await: true },
|
||||
{ type: "advance_clock", duration: "1 millis" },
|
||||
{ type: "dispatch", command: materialized.commands[1]!, await: true },
|
||||
{ type: "await_thread_idle", threadId: materialized.sourceThreadId },
|
||||
{ type: "dispatch", command: materialized.commands[2]!, await: true },
|
||||
{ type: "await_thread_idle", threadId: materialized.sourceThreadId },
|
||||
{ type: "dispatch", command: materialized.commands[3]!, await: true },
|
||||
{ type: "dispatch", command: materialized.commands[4]!, await: true },
|
||||
{ type: "await_thread_idle", threadId: materialized.targetThreadId },
|
||||
{ type: "dispatch", command: materialized.commands[5]!, await: true },
|
||||
],
|
||||
projectionThreadIds: [materialized.sourceThreadId, materialized.targetThreadId],
|
||||
runtimePolicyOverride: { cwd },
|
||||
},
|
||||
ClaudeOrchestratorReplayHarness,
|
||||
).pipe(provideDeterministicTestRuntime);
|
||||
|
||||
const sourceProjection = result.projections.get(materialized.sourceThreadId);
|
||||
const targetProjection = result.projections.get(materialized.targetThreadId);
|
||||
assert.isDefined(sourceProjection);
|
||||
assert.isDefined(targetProjection);
|
||||
|
||||
assert.equal(
|
||||
sourceProjection.runs.map((run) => run.status).join(","),
|
||||
"completed,rolled_back",
|
||||
);
|
||||
assert.equal(
|
||||
sourceProjection.providerThreads[0]?.nativeConversationHeadRef?.nativeId,
|
||||
sourceAssistantMessageUuids[0],
|
||||
"source rollback should persist the Claude resume cursor for the first assistant message",
|
||||
);
|
||||
assert.equal(
|
||||
targetProjection.providerThreads[0]?.nativeThreadRef?.nativeId,
|
||||
forkedNativeSessionId,
|
||||
);
|
||||
assert.equal(targetProjection.providerThreads[0]?.nativeConversationHeadRef, null);
|
||||
|
||||
const sourceVisibleText = userAndAssistantText(sourceProjection);
|
||||
assert.include(sourceVisibleText, "fork boundary alpha");
|
||||
assert.notInclude(sourceVisibleText, "fork boundary beta");
|
||||
|
||||
const targetVisibleText = userAndAssistantText(targetProjection);
|
||||
assert.include(targetVisibleText, "fork boundary alpha");
|
||||
assert.notInclude(
|
||||
targetVisibleText,
|
||||
"fork boundary beta",
|
||||
"source rollback must not cause the fork target to inherit turns past its fork point",
|
||||
);
|
||||
assert.equal(targetProjection.contextTransfers[0]?.resolution?.strategy, "native_fork");
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("rolls back a Claude native fork to an earlier fork-local turn", () =>
|
||||
Effect.gen(function* () {
|
||||
const rawTranscript = yield* readTranscript(CLAUDE_FORK_LOCAL_ROLLBACK_TRANSCRIPT_PATH);
|
||||
const transcript = yield* ClaudeOrchestratorReplayHarness.decodeTranscript(rawTranscript);
|
||||
const forkedNativeSessionId = metadataString(transcript, "forkedNativeSessionId");
|
||||
const resumeSessionAt = metadataString(transcript, "resumeSessionAt");
|
||||
const prompts = metadataStringArray(transcript, "prompts");
|
||||
const [sourcePrompt, forkFirstPrompt, forkSecondPrompt, repeatPrompt] = prompts;
|
||||
if (
|
||||
sourcePrompt === undefined ||
|
||||
forkFirstPrompt === undefined ||
|
||||
forkSecondPrompt === undefined ||
|
||||
repeatPrompt === undefined
|
||||
) {
|
||||
throw new Error("Claude fork-local rollback transcript is missing expected prompts.");
|
||||
}
|
||||
|
||||
const cwd = yield* Effect.acquireRelease(makeCheckpointWorkspace, (directory) =>
|
||||
Effect.service(FileSystem.FileSystem).pipe(
|
||||
Effect.flatMap((fs) => fs.remove(directory, { recursive: true, force: true })),
|
||||
Effect.orDie,
|
||||
),
|
||||
);
|
||||
|
||||
const materialized = yield* Effect.gen(function* () {
|
||||
const ids = yield* IdAllocatorV2;
|
||||
const projectId = yield* ids.allocate.project({
|
||||
fixtureName: "thread-fork-native-fork-local-rollback",
|
||||
});
|
||||
const sourceThreadId = yield* ids.allocate.thread({
|
||||
fixtureName: "thread-fork-native-fork-local-rollback-source",
|
||||
projectId,
|
||||
});
|
||||
const targetThreadId = ThreadId.make("thread-fork-native-fork-local-rollback-target");
|
||||
const targetCheckpointScopeId = yield* ids.allocate.checkpointScope({
|
||||
threadId: targetThreadId,
|
||||
name: "root",
|
||||
});
|
||||
const targetFirstCheckpointId = yield* ids.allocate.checkpoint({
|
||||
checkpointScopeId: targetCheckpointScopeId,
|
||||
name: "1",
|
||||
});
|
||||
|
||||
const commands = [
|
||||
{
|
||||
type: "thread.create",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-fork-local-rollback",
|
||||
commandName: "thread-create-source",
|
||||
}),
|
||||
threadId: sourceThreadId,
|
||||
projectId,
|
||||
title: "Source thread",
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-fork-local-rollback",
|
||||
commandName: "source-message",
|
||||
}),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-fork-local-rollback-source"),
|
||||
text: sourcePrompt,
|
||||
attachments: [],
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
},
|
||||
{
|
||||
type: "thread.fork",
|
||||
commandId: CommandId.make("command-thread-fork-native-fork-local-rollback"),
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
sourcePoint: { type: "latest_stable" },
|
||||
title: "Forked thread",
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-fork-local-rollback",
|
||||
commandName: "fork-first-message",
|
||||
}),
|
||||
threadId: targetThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-fork-local-rollback-first"),
|
||||
text: forkFirstPrompt,
|
||||
attachments: [],
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-fork-local-rollback",
|
||||
commandName: "fork-second-message",
|
||||
}),
|
||||
threadId: targetThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-fork-local-rollback-second"),
|
||||
text: forkSecondPrompt,
|
||||
attachments: [],
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
},
|
||||
{
|
||||
type: "checkpoint.rollback",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-fork-local-rollback",
|
||||
commandName: "rollback-fork-to-first",
|
||||
}),
|
||||
threadId: targetThreadId,
|
||||
scopeId: targetCheckpointScopeId,
|
||||
checkpointId: targetFirstCheckpointId,
|
||||
},
|
||||
{
|
||||
type: "message.dispatch",
|
||||
commandId: yield* ids.allocate.command({
|
||||
fixtureName: "thread-fork-native-fork-local-rollback",
|
||||
commandName: "fork-repeat-after-rollback",
|
||||
}),
|
||||
threadId: targetThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-fork-local-rollback-repeat"),
|
||||
text: repeatPrompt,
|
||||
attachments: [],
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
},
|
||||
] satisfies ReadonlyArray<OrchestrationV2Command>;
|
||||
|
||||
return {
|
||||
sourceThreadId,
|
||||
targetThreadId,
|
||||
commands,
|
||||
};
|
||||
}).pipe(Effect.provide(idAllocatorLayer), provideDeterministicTestRuntime);
|
||||
|
||||
const result = yield* runOrchestratorV2ProviderReplayScenario(
|
||||
{
|
||||
name: "thread_fork_native_fork_local_rollback/claude",
|
||||
transcript,
|
||||
commands: materialized.commands,
|
||||
steps: [
|
||||
{ type: "dispatch", command: materialized.commands[0]!, await: true },
|
||||
{ type: "advance_clock", duration: "1 millis" },
|
||||
{ type: "dispatch", command: materialized.commands[1]!, await: true },
|
||||
{ type: "await_thread_idle", threadId: materialized.sourceThreadId },
|
||||
{ type: "dispatch", command: materialized.commands[2]!, await: true },
|
||||
{ type: "dispatch", command: materialized.commands[3]!, await: true },
|
||||
{ type: "await_thread_idle", threadId: materialized.targetThreadId },
|
||||
{ type: "dispatch", command: materialized.commands[4]!, await: true },
|
||||
{ type: "await_thread_idle", threadId: materialized.targetThreadId },
|
||||
{ type: "dispatch", command: materialized.commands[5]!, await: true },
|
||||
{ type: "dispatch", command: materialized.commands[6]!, await: true },
|
||||
{ type: "await_thread_idle", threadId: materialized.targetThreadId },
|
||||
],
|
||||
projectionThreadIds: [materialized.sourceThreadId, materialized.targetThreadId],
|
||||
runtimePolicyOverride: { cwd },
|
||||
},
|
||||
ClaudeOrchestratorReplayHarness,
|
||||
).pipe(provideDeterministicTestRuntime);
|
||||
|
||||
const targetProjection = result.projections.get(materialized.targetThreadId);
|
||||
assert.isDefined(targetProjection);
|
||||
assert.equal(
|
||||
targetProjection.providerThreads[0]?.nativeThreadRef?.nativeId,
|
||||
forkedNativeSessionId,
|
||||
);
|
||||
assert.isString(resumeSessionAt);
|
||||
|
||||
const targetVisibleText = userAndAssistantText(targetProjection);
|
||||
assert.include(targetVisibleText, "fork local source alpha");
|
||||
assert.include(targetVisibleText, "fork local first");
|
||||
assert.notInclude(
|
||||
targetVisibleText,
|
||||
"fork local second",
|
||||
"rolled back fork-local turns must disappear from the projected fork thread",
|
||||
);
|
||||
|
||||
const targetVisibleAssistantText = targetProjection.visibleTurnItems
|
||||
.map((row) => row.item)
|
||||
.filter((item) => item.type === "assistant_message")
|
||||
.map((item) => item.text)
|
||||
.join("\n");
|
||||
assert.notInclude(
|
||||
targetVisibleAssistantText,
|
||||
"fork local second",
|
||||
"resumeSessionAt must reopen the Claude fork before the rolled-back second fork turn",
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("merges a fork delta back into the source thread through context handoff", () =>
|
||||
Effect.gen(function* () {
|
||||
const rawTranscript = yield* readTranscript(PRIOR_TURN_TRANSCRIPT_PATH);
|
||||
const forkNativeThreadId = "019dd6ba-47b7-7092-8688-9cf7fe5f6498";
|
||||
const sourceNativeThreadId = "019dd6ba-2681-7bf0-b051-141b0cbcbb27";
|
||||
const forkRepeatNativeTurnId = "019dd6ba-47eb-7041-ad45-5abe752c28c9";
|
||||
const forkPrompt =
|
||||
"Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content.";
|
||||
const forkPrompt = THREAD_FORK_NATIVE_PRIOR_TURN_REPEAT_PROMPT;
|
||||
const mergeBackPrompt = "Acknowledge the fork context with exactly: merge back acknowledged";
|
||||
const mergeBackAssistantText = "merge back acknowledged";
|
||||
const materialized = yield* Effect.gen(function* () {
|
||||
@@ -707,7 +1426,7 @@ describe("orchestration V2 thread fork", () => {
|
||||
}),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-prior-turn-alpha"),
|
||||
text: "For this fork-boundary fixture, respond with exactly: fork boundary alpha",
|
||||
text: THREAD_FORK_NATIVE_PRIOR_TURN_ALPHA_PROMPT,
|
||||
attachments: [],
|
||||
modelSelection: CODEX_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
@@ -720,7 +1439,7 @@ describe("orchestration V2 thread fork", () => {
|
||||
}),
|
||||
threadId: sourceThreadId,
|
||||
messageId: MessageId.make("message-thread-fork-native-prior-turn-beta"),
|
||||
text: "For this fork-boundary fixture, respond with exactly: fork boundary beta",
|
||||
text: THREAD_FORK_NATIVE_PRIOR_TURN_BETA_PROMPT,
|
||||
attachments: [],
|
||||
modelSelection: CODEX_MODEL_SELECTION,
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
|
||||
@@ -14,7 +14,9 @@ import { assertSimpleClaudeOutput } from "./simple/claude_output.ts";
|
||||
import { assertSimpleOutput } from "./simple/codex_output.ts";
|
||||
import { simpleInput } from "./simple/input.ts";
|
||||
import { assertSubagentOutput } from "./subagent/codex_output.ts";
|
||||
import { assertClaudeSubagentOutput } from "./subagent/claude_output.ts";
|
||||
import { subagentInput } from "./subagent/input.ts";
|
||||
import { assertClaudeThreadRollbackOutput } from "./thread_rollback/claude_output.ts";
|
||||
import { assertThreadRollbackOutput } from "./thread_rollback/codex_output.ts";
|
||||
import { threadRollbackInput } from "./thread_rollback/input.ts";
|
||||
import { assertTodoListOutput } from "./todo_list/codex_output.ts";
|
||||
@@ -172,6 +174,12 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
|
||||
runtimePolicyOverride: READ_ONLY_ON_REQUEST_POLICY,
|
||||
assertOutput: assertSubagentOutput,
|
||||
},
|
||||
{
|
||||
provider: "claudeAgent",
|
||||
transcriptFile: new URL("./subagent/claude_transcript.ndjson", import.meta.url),
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
assertOutput: assertClaudeSubagentOutput,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -369,6 +377,12 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
|
||||
modelSelection: CODEX_MODEL_SELECTION,
|
||||
assertOutput: assertThreadRollbackOutput,
|
||||
},
|
||||
{
|
||||
provider: "claudeAgent",
|
||||
transcriptFile: new URL("./thread_rollback/claude_transcript.ndjson", import.meta.url),
|
||||
modelSelection: CLAUDE_MODEL_SELECTION,
|
||||
assertOutput: assertClaudeThreadRollbackOutput,
|
||||
},
|
||||
],
|
||||
},
|
||||
] satisfies ReadonlyArray<OrchestratorReplayFixture>;
|
||||
@@ -385,8 +399,7 @@ export const ORCHESTRATOR_REPLAY_FIXTURES = [
|
||||
// and docs/orchestration-v2/thread-lineage-and-context-transfer.md. The return fixture should
|
||||
// prefer a delta handoff into an existing Claude provider thread.
|
||||
|
||||
// TODO(claude-v2/fork-rollback-subagents): add Claude providers to fork, rollback, and subagent
|
||||
// fixtures only after Claude's native behavior is proven by real transcripts, or after V2 has an
|
||||
// explicit portable fallback. Cross-reference `thread_fork_native/codex_transcript.ndjson`,
|
||||
// `thread_rollback/codex_transcript.ndjson`, `subagent/codex_transcript.ndjson`, and
|
||||
// TODO(claude-v2/context-transfer-fixtures): register provider-switch, merge-back, and cross-provider
|
||||
// fork fixtures after each path has a real provider transcript. Cross-reference
|
||||
// docs/orchestration-v2/provider-switching-and-context.md and
|
||||
// docs/orchestration-v2/thread-lineage-and-context-transfer.md.
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
type ProviderReplayTranscript,
|
||||
type ProviderUserInputAnswers,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect } from "effect";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import type {
|
||||
OrchestratorV2ScenarioResult,
|
||||
@@ -54,6 +54,15 @@ export const THREAD_ROLLBACK_FIRST_PROMPT =
|
||||
export const THREAD_ROLLBACK_SECOND_PROMPT =
|
||||
"Respond with exactly: rollback fixture second turn complete";
|
||||
export const THREAD_ROLLBACK_AFTER_PROMPT = "Repeat the conversation verbatim.";
|
||||
export const THREAD_FORK_NATIVE_SOURCE_PROMPT =
|
||||
"Respond with the following text: source fork seed ok";
|
||||
export const THREAD_FORK_NATIVE_TARGET_PROMPT = "Respond with the following text: fork native ok";
|
||||
export const THREAD_FORK_NATIVE_PRIOR_TURN_ALPHA_PROMPT =
|
||||
"For this fork-boundary fixture, respond with exactly: fork boundary alpha";
|
||||
export const THREAD_FORK_NATIVE_PRIOR_TURN_BETA_PROMPT =
|
||||
"For this fork-boundary fixture, respond with exactly: fork boundary beta";
|
||||
export const THREAD_FORK_NATIVE_PRIOR_TURN_REPEAT_PROMPT =
|
||||
"Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content.";
|
||||
export const TODO_LIST_PROMPT =
|
||||
"Use the update_plan tool to track exactly three steps: inspect package.json, inspect tsconfig.json, report completion. Then read package.json and tsconfig.json, and answer exactly: todo list fixture complete";
|
||||
export const PLAN_QUESTIONS_PROMPT =
|
||||
@@ -744,6 +753,26 @@ export function assertTurnItemTypes(
|
||||
}
|
||||
}
|
||||
|
||||
export function assertTurnItemTypeSequence(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
expectedTypes: ReadonlyArray<OrchestrationV2TurnItem["type"]>,
|
||||
) {
|
||||
assert.deepEqual(
|
||||
projection.turnItems.map((item) => item.type),
|
||||
expectedTypes,
|
||||
);
|
||||
}
|
||||
|
||||
export function assertVisibleTurnItemTypeSequence(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
expectedTypes: ReadonlyArray<OrchestrationV2TurnItem["type"]>,
|
||||
) {
|
||||
assert.deepEqual(
|
||||
projection.visibleTurnItems.map((row) => row.item.type),
|
||||
expectedTypes,
|
||||
);
|
||||
}
|
||||
|
||||
export function assertAssistantTextIncludes(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
expectedText: string,
|
||||
@@ -827,6 +856,48 @@ export function assertUserMessagesInclude(
|
||||
}
|
||||
}
|
||||
|
||||
export function assertUserMessagesExclude(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
rejectedTexts: ReadonlyArray<string>,
|
||||
) {
|
||||
for (const rejectedText of rejectedTexts) {
|
||||
assert.isFalse(
|
||||
projection.turnItems.some(
|
||||
(item) => item.type === "user_message" && item.text.includes(rejectedText),
|
||||
),
|
||||
`expected user input to exclude ${JSON.stringify(rejectedText)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertVisibleUserMessagesInclude(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
expectedTexts: ReadonlyArray<string>,
|
||||
) {
|
||||
for (const expectedText of expectedTexts) {
|
||||
assert.isTrue(
|
||||
projection.visibleTurnItems.some(
|
||||
(row) => row.item.type === "user_message" && row.item.text.includes(expectedText),
|
||||
),
|
||||
`expected visible user input to include ${JSON.stringify(expectedText)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertVisibleUserMessagesExclude(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
rejectedTexts: ReadonlyArray<string>,
|
||||
) {
|
||||
for (const rejectedText of rejectedTexts) {
|
||||
assert.isFalse(
|
||||
projection.visibleTurnItems.some(
|
||||
(row) => row.item.type === "user_message" && row.item.text.includes(rejectedText),
|
||||
),
|
||||
`expected visible user input to exclude ${JSON.stringify(rejectedText)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertUserMessageInputIntents(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
expectedIntents: ReadonlyArray<OrchestrationV2UserMessageInputIntent>,
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { assert } from "@effect/vitest";
|
||||
import type { ProviderReplayTranscript } from "@t3tools/contracts";
|
||||
|
||||
import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
|
||||
import {
|
||||
assertAssistantTextIncludes,
|
||||
assertBaseProjection,
|
||||
assertExecutionNodeKinds,
|
||||
assertNoExtraAppRunsForProviderChildren,
|
||||
assertRunProviderTurnCardinality,
|
||||
assertSemanticProjectionIntegrity,
|
||||
assertTurnItemTypes,
|
||||
assertUserMessagesInclude,
|
||||
projectionFor,
|
||||
SUBAGENT_PROMPT,
|
||||
} from "../shared.ts";
|
||||
|
||||
export function assertClaudeSubagentOutput(
|
||||
result: OrchestratorV2ScenarioResult,
|
||||
transcript: ProviderReplayTranscript,
|
||||
) {
|
||||
assertBaseProjection({
|
||||
result,
|
||||
transcript,
|
||||
runCount: 1,
|
||||
runStatuses: ["completed"],
|
||||
});
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertExecutionNodeKinds(projection, ["root_turn", "subagent", "tool_call"]);
|
||||
assertTurnItemTypes(projection, ["user_message", "dynamic_tool", "assistant_message"]);
|
||||
assertRunProviderTurnCardinality({ projection, rootRunCount: 1 });
|
||||
assertNoExtraAppRunsForProviderChildren({ projection, expectedAppRuns: 1 });
|
||||
assertUserMessagesInclude(projection, [SUBAGENT_PROMPT]);
|
||||
assertAssistantTextIncludes(projection, "claude-read-only-fixture");
|
||||
assertAssistantTextIncludes(projection, "ES2022");
|
||||
|
||||
const subagentNodes = projection.nodes.filter((node) => node.kind === "subagent");
|
||||
assert.lengthOf(subagentNodes, 2);
|
||||
assert.deepEqual(
|
||||
subagentNodes.map((node) => node.status),
|
||||
["completed", "completed"],
|
||||
);
|
||||
|
||||
const subagentNodeIds = new Set(subagentNodes.map((node) => node.id));
|
||||
const nestedToolNodes = projection.nodes.filter(
|
||||
(node) =>
|
||||
node.kind === "tool_call" &&
|
||||
node.parentNodeId !== null &&
|
||||
subagentNodeIds.has(node.parentNodeId),
|
||||
);
|
||||
assert.isAtLeast(nestedToolNodes.length, 2);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
{"type":"transcript_start","provider":"claudeAgent","protocol":"claude-agent-sdk.query","version":"0.2.111","scenario":"subagent","metadata":{"prompts":["Spawn 2 subagents, one to read package.json and one to read tsconfig.json"],"model":"claude-sonnet-4-6","nativeSessionId":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","queryMode":"streaming","tools":"claude_code","permissionMode":"bypassPermissions","generatedBy":"recordClaudeAgentSdkReplayTranscript"}}
|
||||
{"type":"expect_outbound","label":"query.open","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"sessionId":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d"}}}
|
||||
{"type":"expect_outbound","label":"prompt.offer:1","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Spawn 2 subagents, one to read package.json and one to read tsconfig.json"},"parent_tool_use_id":null}}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_started","hook_id":"4fde9c84-285e-4a68-9070-3704c94168f6","hook_name":"SessionStart:startup","hook_event":"SessionStart","uuid":"caf0439c-1455-4bd5-bcbf-14be3b13db5c","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_response","hook_id":"4fde9c84-285e-4a68-9070-3704c94168f6","hook_name":"SessionStart:startup","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"5af52be5-9839-49fb-aebe-da4068d0ba2a","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.111","cwd":"/tmp/claude-replay-subagent","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"38e13364-a3ab-43cf-865f-cb790e39532b","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_014tG9SY8VfiqS7bCEAJ1oKt","type":"message","role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to spawn 2 subagents in parallel - one to read package.json and one to read tsconfig.json.","signature":"ErMCCmUIDhgCKkBRbKaYlD+XeRoQv536GegpaFwi9jwMXXtuPsLxongxP3e2xG7qRV+sWykxHk4twYSGIzmfHtgg9TYwH4IBe1GuMhFjbGF1ZGUtc29ubmV0LTQtNjgAQgh0aGlua2luZxIMasLti+z60m9mTQ7iGgwfWbzjzMVaZS/99/0iMBzqZIXucbe83OrH5rh5RJUMDW06UPJkxEczZtLVG/CEhmOLiPnJ23mzX4QZkbxHBip8IqOdwO4Zse+34IUUKau4H/PkUq20GEDeRENlujYtF+YkMI8wk9Oh3X/xKjUy+/kj0udJORGyQp7W0oTRRBojJNT6uYQ53rx+5d8BNwIjJMs2GUAlyBDCJz14UrfXDY3qQTqmtBowAlVKaKx6w8KZLNdGVFdH0nVzqugdMBgB"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":2351,"cache_read_input_tokens":9455,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":2351},"output_tokens":0,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"682886b5-991a-42be-9f6f-0b92cd685c3d"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_014tG9SY8VfiqS7bCEAJ1oKt","type":"message","role":"assistant","content":[{"type":"text","text":"I'll spawn both subagents simultaneously right now!"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":2351,"cache_read_input_tokens":9455,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":2351},"output_tokens":0,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"79a75f39-f73f-428d-9009-986d85044454"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_014tG9SY8VfiqS7bCEAJ1oKt","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01FfHTrUeymLi4LfqJVmTZjz","name":"Agent","input":{"description":"Read package.json","prompt":"Read the file `package.json` in the current working directory and return its full contents."},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":2351,"cache_read_input_tokens":9455,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":2351},"output_tokens":0,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"3688ac34-266c-43f3-bd97-863da3485701"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"task_started","task_id":"a35c9b7d354c20172","tool_use_id":"toolu_01FfHTrUeymLi4LfqJVmTZjz","description":"Read package.json","task_type":"local_agent","prompt":"Read the file `package.json` in the current working directory and return its full contents.","uuid":"5de9156d-9c9c-414e-9a5c-4f88878f7f27","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d"}}
|
||||
{"type":"emit_inbound","label":"user","frame":{"type":"user","message":{"role":"user","content":[{"type":"text","text":"Read the file `package.json` in the current working directory and return its full contents."}]},"parent_tool_use_id":"toolu_01FfHTrUeymLi4LfqJVmTZjz","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"4e7570c6-2512-4307-99ea-37f4cb98ba74","timestamp":"2026-05-27T00:24:44.805Z"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_014tG9SY8VfiqS7bCEAJ1oKt","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_0113VSWTCamvp1adXDZrK5NG","name":"Agent","input":{"description":"Read tsconfig.json","prompt":"Read the file `tsconfig.json` in the current working directory and return its full contents."},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":2351,"cache_read_input_tokens":9455,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":2351},"output_tokens":0,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"caf23ae6-07b0-4934-a5bf-a4c7e95d112e"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"task_started","task_id":"a3d3213ffad1bd057","tool_use_id":"toolu_0113VSWTCamvp1adXDZrK5NG","description":"Read tsconfig.json","task_type":"local_agent","prompt":"Read the file `tsconfig.json` in the current working directory and return its full contents.","uuid":"e907d290-9015-42f1-a80b-f7d0835b9c96","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d"}}
|
||||
{"type":"emit_inbound","label":"user","frame":{"type":"user","message":{"role":"user","content":[{"type":"text","text":"Read the file `tsconfig.json` in the current working directory and return its full contents."}]},"parent_tool_use_id":"toolu_0113VSWTCamvp1adXDZrK5NG","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"01811bb7-eb17-4da4-b511-0bbee0ae887f","timestamp":"2026-05-27T00:24:44.900Z"}}
|
||||
{"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"d61e6565-fa4c-4fd6-9174-17c93b91614b","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"task_progress","task_id":"a35c9b7d354c20172","tool_use_id":"toolu_01FfHTrUeymLi4LfqJVmTZjz","description":"Reading package.json","usage":{"total_tokens":8707,"tool_uses":1,"duration_ms":2053},"last_tool_name":"Read","uuid":"4ed5c537-4bc1-424f-9462-8efb9d5dd0ab","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01DqozNMytHgJ2P5Buwf5f6A","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01EV8j88CPEmhoWF3iuvaFSC","name":"Read","input":{"file_path":"/private/var/folders/b3/b51_pdxj7dl0t981zpqkxxhr0000gn/T/t3-orchestrator-v2-claude-agent-sdk-record-subagent-jAoxxI/package.json"},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":1139,"cache_read_input_tokens":7492,"cache_creation":{"ephemeral_5m_input_tokens":1139,"ephemeral_1h_input_tokens":0},"output_tokens":73,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":"toolu_01FfHTrUeymLi4LfqJVmTZjz","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"debf5765-e302-4724-8df7-c64d11108860"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"task_progress","task_id":"a3d3213ffad1bd057","tool_use_id":"toolu_0113VSWTCamvp1adXDZrK5NG","description":"Reading tsconfig.json","usage":{"total_tokens":8708,"tool_uses":1,"duration_ms":2093},"last_tool_name":"Read","uuid":"e31a6683-35ab-49f0-8913-1e8a8d559343","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_019MHopVQzAkpKERfKvRB1cj","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_01P6KQcUPy8t2bCbFjv8K4Jz","name":"Read","input":{"file_path":"/private/var/folders/b3/b51_pdxj7dl0t981zpqkxxhr0000gn/T/t3-orchestrator-v2-claude-agent-sdk-record-subagent-jAoxxI/tsconfig.json"},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":1140,"cache_read_input_tokens":7492,"cache_creation":{"ephemeral_5m_input_tokens":1140,"ephemeral_1h_input_tokens":0},"output_tokens":73,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":"toolu_0113VSWTCamvp1adXDZrK5NG","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"a5d6d0ed-bc30-43fb-9295-f338fedbf020"}}
|
||||
{"type":"emit_inbound","label":"user","frame":{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01P6KQcUPy8t2bCbFjv8K4Jz","type":"tool_result","content":"1\t{\"compilerOptions\":{\"module\":\"ESNext\",\"strict\":true,\"target\":\"ES2022\"}}"}]},"parent_tool_use_id":"toolu_0113VSWTCamvp1adXDZrK5NG","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"6814c55d-46df-4aeb-b594-f8819f353925","timestamp":"2026-05-27T00:24:46.995Z"}}
|
||||
{"type":"emit_inbound","label":"user","frame":{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01EV8j88CPEmhoWF3iuvaFSC","type":"tool_result","content":"1\t{\"name\":\"claude-read-only-fixture\",\"private\":true,\"scripts\":{\"typecheck\":\"tsc --noEmit\"}}"}]},"parent_tool_use_id":"toolu_01FfHTrUeymLi4LfqJVmTZjz","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"cd552b77-8f0a-4984-b2e1-8eeea3e63148","timestamp":"2026-05-27T00:24:46.875Z"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"task_notification","task_id":"a3d3213ffad1bd057","tool_use_id":"toolu_0113VSWTCamvp1adXDZrK5NG","status":"completed","output_file":"","summary":"Read tsconfig.json","usage":{"total_tokens":10750,"tool_uses":1,"duration_ms":5183},"uuid":"71cc121b-cc9f-42ad-aaea-40730ef81125","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d"}}
|
||||
{"type":"emit_inbound","label":"user","frame":{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_0113VSWTCamvp1adXDZrK5NG","type":"tool_result","content":[{"type":"text","text":"Here are the full contents of `tsconfig.json`:\n\n```json\n{\"compilerOptions\":{\"module\":\"ESNext\",\"strict\":true,\"target\":\"ES2022\"}}\n```\n\nIt is a minimal TypeScript configuration with three compiler options set:\n- `module`: `ESNext` — uses ES module syntax\n- `strict`: `true` — enables all strict type-checking options\n- `target`: `ES2022` — compiles down to ES2022 JavaScript"},{"type":"text","text":"agentId: a3d3213ffad1bd057 (use SendMessage with to: 'a3d3213ffad1bd057' to continue this agent)\n<usage>total_tokens: 10783\ntool_uses: 1\nduration_ms: 5186</usage>"}]}]},"parent_tool_use_id":null,"session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"526e0d3c-7688-4b39-8b54-4aa438b93f07","timestamp":"2026-05-27T00:24:50.087Z","tool_use_result":{"status":"completed","prompt":"Read the file `tsconfig.json` in the current working directory and return its full contents.","agentId":"a3d3213ffad1bd057","agentType":"general-purpose","content":[{"type":"text","text":"Here are the full contents of `tsconfig.json`:\n\n```json\n{\"compilerOptions\":{\"module\":\"ESNext\",\"strict\":true,\"target\":\"ES2022\"}}\n```\n\nIt is a minimal TypeScript configuration with three compiler options set:\n- `module`: `ESNext` — uses ES module syntax\n- `strict`: `true` — enables all strict type-checking options\n- `target`: `ES2022` — compiles down to ES2022 JavaScript"}],"totalDurationMs":5186,"totalTokens":10783,"totalToolUseCount":1,"usage":{"input_tokens":1,"cache_creation_input_tokens":2043,"cache_read_input_tokens":8632,"output_tokens":107,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":2043},"inference_geo":"","iterations":[{"input_tokens":1,"output_tokens":107,"cache_read_input_tokens":8632,"cache_creation_input_tokens":2043,"cache_creation":{"ephemeral_5m_input_tokens":2043,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard"},"toolStats":{"readCount":1,"searchCount":0,"bashCount":0,"editFileCount":0,"linesAdded":0,"linesRemoved":0,"otherToolCount":0}}}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"task_notification","task_id":"a35c9b7d354c20172","tool_use_id":"toolu_01FfHTrUeymLi4LfqJVmTZjz","status":"completed","output_file":"","summary":"Read package.json","usage":{"total_tokens":10755,"tool_uses":1,"duration_ms":6211},"uuid":"5fd5a6f9-6045-4b50-99d9-a0bbe8991047","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d"}}
|
||||
{"type":"emit_inbound","label":"user","frame":{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01FfHTrUeymLi4LfqJVmTZjz","type":"tool_result","content":[{"type":"text","text":"Here are the full contents of `package.json`:\n\n```json\n{\"name\":\"claude-read-only-fixture\",\"private\":true,\"scripts\":{\"typecheck\":\"tsc --noEmit\"}}\n```\n\nFormatted for readability:\n\n```json\n{\n \"name\": \"claude-read-only-fixture\",\n \"private\": true,\n \"scripts\": {\n \"typecheck\": \"tsc --noEmit\"\n }\n}\n```\n\nThe file is minimal, containing just the package name (`claude-read-only-fixture`), a `private: true` flag, and a single script (`typecheck`) that runs the TypeScript compiler in no-emit mode."},{"type":"text","text":"agentId: a35c9b7d354c20172 (use SendMessage with to: 'a35c9b7d354c20172' to continue this agent)\n<usage>total_tokens: 10839\ntool_uses: 1\nduration_ms: 6213</usage>"}]}]},"parent_tool_use_id":null,"session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"3dac736f-a3d6-4f43-b01d-92c17f34b020","timestamp":"2026-05-27T00:24:51.018Z","tool_use_result":{"status":"completed","prompt":"Read the file `package.json` in the current working directory and return its full contents.","agentId":"a35c9b7d354c20172","agentType":"general-purpose","content":[{"type":"text","text":"Here are the full contents of `package.json`:\n\n```json\n{\"name\":\"claude-read-only-fixture\",\"private\":true,\"scripts\":{\"typecheck\":\"tsc --noEmit\"}}\n```\n\nFormatted for readability:\n\n```json\n{\n \"name\": \"claude-read-only-fixture\",\n \"private\": true,\n \"scripts\": {\n \"typecheck\": \"tsc --noEmit\"\n }\n}\n```\n\nThe file is minimal, containing just the package name (`claude-read-only-fixture`), a `private: true` flag, and a single script (`typecheck`) that runs the TypeScript compiler in no-emit mode."}],"totalDurationMs":6213,"totalTokens":10839,"totalToolUseCount":1,"usage":{"input_tokens":1,"cache_creation_input_tokens":2049,"cache_read_input_tokens":8631,"output_tokens":158,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":2049},"inference_geo":"","iterations":[{"input_tokens":1,"output_tokens":158,"cache_read_input_tokens":8631,"cache_creation_input_tokens":2049,"cache_creation":{"ephemeral_5m_input_tokens":2049,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard"},"toolStats":{"readCount":1,"searchCount":0,"bashCount":0,"editFileCount":0,"linesAdded":0,"linesRemoved":0,"otherToolCount":0}}}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_0149tB2WYRkkPLcXTkYZknLb","type":"message","role":"assistant","content":[{"type":"text","text":"Both subagents completed in parallel! Here's a summary of what they found:\n\n---\n\n### 📦 `package.json`\n```json\n{\n \"name\": \"claude-read-only-fixture\",\n \"private\": true,\n \"scripts\": {\n \"typecheck\": \"tsc --noEmit\"\n }\n}\n```\nA minimal package config — private package named `claude-read-only-fixture` with a single `typecheck` script.\n\n---\n\n### 🔧 `tsconfig.json`\n```json\n{\n \"compilerOptions\": {\n \"module\": \"ESNext\",\n \"strict\": true,\n \"target\": \"ES2022\"\n }\n}\n```\nA lean TypeScript config targeting **ES2022**, using **ESNext modules**, and enabling **strict** type-checking."}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":209,"cache_creation_input_tokens":481,"cache_read_input_tokens":11806,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":481},"output_tokens":2,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","uuid":"dbd66caf-dabe-4f13-956a-3a4e276c1e80"}}
|
||||
{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":16909,"duration_api_ms":18827,"num_turns":3,"result":"Both subagents completed in parallel! Here's a summary of what they found:\n\n---\n\n### 📦 `package.json`\n```json\n{\n \"name\": \"claude-read-only-fixture\",\n \"private\": true,\n \"scripts\": {\n \"typecheck\": \"tsc --noEmit\"\n }\n}\n```\nA minimal package config — private package named `claude-read-only-fixture` with a single `typecheck` script.\n\n---\n\n### 🔧 `tsconfig.json`\n```json\n{\n \"compilerOptions\": {\n \"module\": \"ESNext\",\n \"strict\": true,\n \"target\": \"ES2022\"\n }\n}\n```\nA lean TypeScript config targeting **ES2022**, using **ESNext modules**, and enabling **strict** type-checking.","stop_reason":"end_turn","session_id":"edf38df1-8d2f-4781-b9e3-f9e72ba7b76d","total_cost_usd":0.06497865000000001,"usage":{"input_tokens":212,"cache_creation_input_tokens":2832,"cache_read_input_tokens":21261,"output_tokens":419,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":2832,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":209,"output_tokens":201,"cache_read_input_tokens":11806,"cache_creation_input_tokens":481,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":481},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":220,"outputTokens":917,"cacheReadInputTokens":53508,"cacheCreationInputTokens":9203,"webSearchRequests":0,"costUSD":0.06497865000000001,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"aa48d52b-3473-44a8-b291-3844d61a4105"}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
{"type":"transcript_start","provider":"claudeAgent","protocol":"claude-agent-sdk.query","version":"0.2.111","scenario":"thread_fork_native","metadata":{"prompts":["Respond with the following text: source fork seed ok","Respond with the following text: fork native ok"],"model":"claude-sonnet-4-6","nativeSessionId":"8d0dafab-45d3-45eb-abef-41b9e55d5ff9","queryMode":"fork_session","tools":"claude_code","permissionMode":"bypassPermissions","generatedBy":"recordClaudeAgentSdkReplayTranscript","sourceAssistantMessageUuids":["68baa075-b7d4-4689-866b-96bd51e570c3"],"forkUpToMessageId":"68baa075-b7d4-4689-866b-96bd51e570c3","forkedNativeSessionId":"7e7ad6ec-db4a-4510-85ff-59df35cf7fad"}}
|
||||
{"type":"expect_outbound","label":"query.open:source","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"sessionId":"8d0dafab-45d3-45eb-abef-41b9e55d5ff9"}}}
|
||||
{"type":"expect_outbound","label":"prompt.offer:1","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Respond with the following text: source fork seed ok"},"parent_tool_use_id":null}}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_started","hook_id":"72dd9de7-b5a9-46bf-9c57-9bca11344e73","hook_name":"SessionStart:startup","hook_event":"SessionStart","uuid":"4edf7621-d696-4b60-9821-187bcac04c7d","session_id":"8d0dafab-45d3-45eb-abef-41b9e55d5ff9"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_response","hook_id":"72dd9de7-b5a9-46bf-9c57-9bca11344e73","hook_name":"SessionStart:startup","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"6959d784-05f0-48b4-97de-d3f4a11b4b1a","session_id":"8d0dafab-45d3-45eb-abef-41b9e55d5ff9"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.111","cwd":"/tmp/claude-replay-thread_fork_native","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"fd90233b-ff4e-429c-a3b2-088d9b3bafc8","session_id":"8d0dafab-45d3-45eb-abef-41b9e55d5ff9"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01RzC6FfR9RGxxVcrpBK6duZ","type":"message","role":"assistant","content":[{"type":"text","text":"source fork seed ok"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":2339,"cache_read_input_tokens":9455,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":2339},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"8d0dafab-45d3-45eb-abef-41b9e55d5ff9","uuid":"68baa075-b7d4-4689-866b-96bd51e570c3"}}
|
||||
{"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"84451d3f-e7ba-4d80-aea3-4fbc442f4b3b","session_id":"8d0dafab-45d3-45eb-abef-41b9e55d5ff9"}}
|
||||
{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":2066,"duration_api_ms":1815,"num_turns":1,"result":"source fork seed ok","stop_reason":"end_turn","session_id":"8d0dafab-45d3-45eb-abef-41b9e55d5ff9","total_cost_usd":0.01172175,"usage":{"input_tokens":3,"cache_creation_input_tokens":2339,"cache_read_input_tokens":9455,"output_tokens":7,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":2339,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":3,"output_tokens":7,"cache_read_input_tokens":9455,"cache_creation_input_tokens":2339,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":2339},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":3,"outputTokens":7,"cacheReadInputTokens":9455,"cacheCreationInputTokens":2339,"webSearchRequests":0,"costUSD":0.01172175,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"892cdc1f-e2d5-440d-ae57-ca27d32f63f1"}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
{"type":"expect_outbound","label":"session.fork","frame":{"type":"session.fork","sessionId":"8d0dafab-45d3-45eb-abef-41b9e55d5ff9","options":{"dir":"/tmp/claude-replay-thread_fork_native","upToMessageId":"68baa075-b7d4-4689-866b-96bd51e570c3"}}}
|
||||
{"type":"emit_inbound","label":"session.forked","frame":{"type":"session.forked","sessionId":"7e7ad6ec-db4a-4510-85ff-59df35cf7fad"}}
|
||||
{"type":"expect_outbound","label":"query.open:fork","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"resume":"7e7ad6ec-db4a-4510-85ff-59df35cf7fad"}}}
|
||||
{"type":"expect_outbound","label":"prompt.offer:2","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Respond with the following text: fork native ok"},"parent_tool_use_id":null}}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_started","hook_id":"53ad62fa-7988-4d2e-9efd-e923756eb7e5","hook_name":"SessionStart:resume","hook_event":"SessionStart","uuid":"c2160988-c159-4ace-abd3-1eb6bbaa76ad","session_id":"d2c41d57-6ad4-4c9e-9444-f93bc492aa53"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_response","hook_id":"53ad62fa-7988-4d2e-9efd-e923756eb7e5","hook_name":"SessionStart:resume","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"fa30d315-9265-40ec-afbe-c76704c6d66c","session_id":"d2c41d57-6ad4-4c9e-9444-f93bc492aa53"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.111","cwd":"/tmp/claude-replay-thread_fork_native","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"41edb892-5f02-4bdd-bef3-5945d3414fc8","session_id":"7e7ad6ec-db4a-4510-85ff-59df35cf7fad"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01MvGdK8D9o71fU1raKAbM69","type":"message","role":"assistant","content":[{"type":"text","text":"fork native ok"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":20,"cache_read_input_tokens":11794,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":20},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"7e7ad6ec-db4a-4510-85ff-59df35cf7fad","uuid":"b800a4dd-77a5-4e68-acac-1c651a50a02e"}}
|
||||
{"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"91026341-c039-4110-928f-4ab67cd13375","session_id":"7e7ad6ec-db4a-4510-85ff-59df35cf7fad"}}
|
||||
{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":4452,"duration_api_ms":3680,"num_turns":1,"result":"fork native ok","stop_reason":"end_turn","session_id":"7e7ad6ec-db4a-4510-85ff-59df35cf7fad","total_cost_usd":0.0037122,"usage":{"input_tokens":3,"cache_creation_input_tokens":20,"cache_read_input_tokens":11794,"output_tokens":6,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":20,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":3,"output_tokens":6,"cache_read_input_tokens":11794,"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":20},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":3,"outputTokens":6,"cacheReadInputTokens":11794,"cacheCreationInputTokens":20,"webSearchRequests":0,"costUSD":0.0037122,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"cc267266-37bf-4cac-a602-ecfabd1e8170"}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
{"type":"transcript_start","provider":"claudeAgent","protocol":"claude-agent-sdk.query","version":"0.2.111","scenario":"thread_fork_native_fork_local_rollback","metadata":{"prompts":["For this fork-local rollback fixture, respond with exactly: fork local source alpha","For this fork-local rollback fixture, respond with exactly: fork local first","For this fork-local rollback fixture, respond with exactly: fork local second","Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content."],"model":"claude-sonnet-4-6","nativeSessionId":"273fe17b-65fb-451f-ad99-ff19d323852d","queryMode":"fork_session_resume_at_fork_cursor","tools":"claude_code","permissionMode":"bypassPermissions","generatedBy":"probeClaudeForkLocalRollbackReplay","sourceAssistantMessageUuids":["7659a146-b729-47b6-aac2-8fc0c0981e92"],"forkUpToMessageId":"7659a146-b729-47b6-aac2-8fc0c0981e92","forkedNativeSessionId":"c9784d72-7e4f-4994-8c21-2e7e670ff91c","forkAssistantMessageUuids":["14310fd5-a1aa-448b-8880-de52f86541b1","b9bb4e45-d52d-4fb3-adf7-4b5e4d9d0dd6"],"resumeSessionAt":"14310fd5-a1aa-448b-8880-de52f86541b1"}}
|
||||
{"type":"expect_outbound","label":"query.open:source","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"sessionId":"273fe17b-65fb-451f-ad99-ff19d323852d"}}}
|
||||
{"type":"expect_outbound","label":"prompt.offer:source","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"For this fork-local rollback fixture, respond with exactly: fork local source alpha"},"parent_tool_use_id":null}}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_started","hook_id":"36e94137-12f0-4e71-828b-bd4c76467204","hook_name":"SessionStart:startup","hook_event":"SessionStart","uuid":"f8884f88-0672-4602-bb93-a35473be10f8","session_id":"273fe17b-65fb-451f-ad99-ff19d323852d"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_response","hook_id":"36e94137-12f0-4e71-828b-bd4c76467204","hook_name":"SessionStart:startup","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"9b44ee7b-9a43-41a6-993d-6cb5945a8210","session_id":"273fe17b-65fb-451f-ad99-ff19d323852d"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","cwd":"/private/tmp/claude-replay-thread_fork_native_fork_local_rollback","session_id":"273fe17b-65fb-451f-ad99-ff19d323852d","tools":["Task","AskUserQuestion","Bash","CronCreate","CronDelete","CronList","Edit","EnterPlanMode","EnterWorktree","ExitPlanMode","ExitWorktree","Glob","Grep","ListMcpResourcesTool","Monitor","NotebookEdit","PushNotification","Read","ReadMcpResourceTool","RemoteTrigger","ScheduleWakeup","Skill","TaskOutput","TaskStop","TodoWrite","ToolSearch","WebFetch","WebSearch","Write","mcp__claude_ai_Google_Drive__authenticate","mcp__claude_ai_Google_Drive__complete_authentication","mcp__uidotsh__uidotsh_fetch"],"mcp_servers":[{"name":"uidotsh","status":"connected"},{"name":"claude.ai Google Drive","status":"needs-auth"}],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":["update-config","debug","simplify","batch","less-permission-prompts","loop","schedule","claude-api","expo-dev-client","ui","agent-browser","native-data-fetching","expo-deployment","btca-cli","uniwind","web-design-guidelines","react-doctor","migrate-nativewind-to-uniwind","building-native-ui","frontend-design","turborepo","vercel-composition-patterns","expo-cicd-workflows","expo-tailwind-setup","coderabbit:review","coderabbit:coderabbit-review","coderabbit:code-review","agent-browser:agent-browser","frontend-design:frontend-design","coderabbit:autofix","compact","context","cost","heapdump","init","review","security-review","extra-usage","insights","team-onboarding"],"apiKeySource":"none","claude_code_version":"2.1.111","output_style":"default","agents":["coderabbit:code-reviewer","Explore","general-purpose","Plan","statusline-setup"],"skills":["update-config","debug","simplify","batch","less-permission-prompts","loop","schedule","claude-api","expo-dev-client","ui","agent-browser","native-data-fetching","expo-deployment","btca-cli","uniwind","web-design-guidelines","react-doctor","migrate-nativewind-to-uniwind","building-native-ui","frontend-design","turborepo","vercel-composition-patterns","expo-cicd-workflows","expo-tailwind-setup","coderabbit:code-review","agent-browser:agent-browser","frontend-design:frontend-design","coderabbit:autofix","coderabbit:code-review"],"plugins":[{"name":"coderabbit","path":"/home/replay-user/.claude/plugins/marketplaces/coderabbit/","source":"coderabbit@coderabbit"},{"name":"agent-browser","path":"/home/replay-user/.claude/plugins/cache/agent-browser/agent-browser/ea17db856473","source":"agent-browser@agent-browser"},{"name":"frontend-design","path":"/home/replay-user/.claude/plugins/cache/claude-plugins-official/frontend-design/unknown","source":"frontend-design@claude-plugins-official"},{"name":"coderabbit","path":"/home/replay-user/.claude/plugins/cache/claude-plugins-official/coderabbit/1.1.1","source":"coderabbit@claude-plugins-official"}],"uuid":"1e7d6f8f-2295-42cb-a413-50274ffe1bdd","memory_paths":{"auto":"/home/replay-user/.claude/projects/-private-var-folders-b3-b51-pdxj7dl0t981zpqkxxhr0000gn-T-t3-orchestrator-v2-claude-agent-sdk-record-thread-fork-native-fork-local-rollback-6isYFV/memory/"},"fast_mode_state":"off"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01GymzntxN7tobzwVerJJDMw","type":"message","role":"assistant","content":[{"type":"text","text":"fork local source alpha"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":0,"cache_read_input_tokens":11800,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"273fe17b-65fb-451f-ad99-ff19d323852d","uuid":"7659a146-b729-47b6-aac2-8fc0c0981e92"}}
|
||||
{"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed","resetsAt":1779846000,"rateLimitType":"five_hour","overageStatus":"rejected","overageDisabledReason":"org_level_disabled","isUsingOverage":false},"uuid":"94e56646-7610-4a7a-8245-9301469861ae","session_id":"273fe17b-65fb-451f-ad99-ff19d323852d"}}
|
||||
{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":2928,"duration_api_ms":1977,"num_turns":1,"result":"fork local source alpha","stop_reason":"end_turn","session_id":"273fe17b-65fb-451f-ad99-ff19d323852d","total_cost_usd":0.0036539999999999997,"usage":{"input_tokens":3,"cache_creation_input_tokens":0,"cache_read_input_tokens":11800,"output_tokens":7,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":3,"output_tokens":7,"cache_read_input_tokens":11800,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":3,"outputTokens":7,"cacheReadInputTokens":11800,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.0036539999999999997,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"684990a5-0d00-4928-a332-fdc2c66769c6"}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
{"type":"expect_outbound","label":"session.fork","frame":{"type":"session.fork","sessionId":"273fe17b-65fb-451f-ad99-ff19d323852d","options":{"dir":"/tmp/claude-replay-thread_fork_native_fork_local_rollback","upToMessageId":"7659a146-b729-47b6-aac2-8fc0c0981e92"}}}
|
||||
{"type":"emit_inbound","label":"session.forked","frame":{"type":"session.forked","sessionId":"c9784d72-7e4f-4994-8c21-2e7e670ff91c"}}
|
||||
{"type":"expect_outbound","label":"query.open:fork","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"resume":"c9784d72-7e4f-4994-8c21-2e7e670ff91c"}}}
|
||||
{"type":"expect_outbound","label":"prompt.offer:fork-first","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"For this fork-local rollback fixture, respond with exactly: fork local first"},"parent_tool_use_id":null}}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_started","hook_id":"b8ac144f-11aa-4f98-96f3-9c9caa8c93ef","hook_name":"SessionStart:resume","hook_event":"SessionStart","uuid":"7e53533c-0f7a-4c67-bed4-0124e8b57438","session_id":"1eb8c977-ac69-4559-8501-92edb5a32f2f"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_response","hook_id":"b8ac144f-11aa-4f98-96f3-9c9caa8c93ef","hook_name":"SessionStart:resume","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"c176d46f-750b-4bab-9d7a-ab863903a141","session_id":"1eb8c977-ac69-4559-8501-92edb5a32f2f"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","cwd":"/private/tmp/claude-replay-thread_fork_native_fork_local_rollback","session_id":"c9784d72-7e4f-4994-8c21-2e7e670ff91c","tools":["Task","AskUserQuestion","Bash","CronCreate","CronDelete","CronList","Edit","EnterPlanMode","EnterWorktree","ExitPlanMode","ExitWorktree","Glob","Grep","ListMcpResourcesTool","Monitor","NotebookEdit","PushNotification","Read","ReadMcpResourceTool","RemoteTrigger","ScheduleWakeup","Skill","TaskOutput","TaskStop","TodoWrite","ToolSearch","WebFetch","WebSearch","Write","mcp__claude_ai_Google_Drive__authenticate","mcp__claude_ai_Google_Drive__complete_authentication","mcp__uidotsh__uidotsh_fetch"],"mcp_servers":[{"name":"uidotsh","status":"connected"},{"name":"claude.ai Google Drive","status":"needs-auth"}],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":["update-config","debug","simplify","batch","less-permission-prompts","loop","schedule","claude-api","expo-dev-client","ui","agent-browser","native-data-fetching","expo-deployment","btca-cli","uniwind","web-design-guidelines","react-doctor","migrate-nativewind-to-uniwind","building-native-ui","frontend-design","turborepo","vercel-composition-patterns","expo-cicd-workflows","expo-tailwind-setup","coderabbit:review","coderabbit:coderabbit-review","coderabbit:code-review","agent-browser:agent-browser","frontend-design:frontend-design","coderabbit:autofix","compact","context","cost","heapdump","init","review","security-review","extra-usage","insights","team-onboarding"],"apiKeySource":"none","claude_code_version":"2.1.111","output_style":"default","agents":["coderabbit:code-reviewer","Explore","general-purpose","Plan","statusline-setup"],"skills":["update-config","debug","simplify","batch","less-permission-prompts","loop","schedule","claude-api","expo-dev-client","ui","agent-browser","native-data-fetching","expo-deployment","btca-cli","uniwind","web-design-guidelines","react-doctor","migrate-nativewind-to-uniwind","building-native-ui","frontend-design","turborepo","vercel-composition-patterns","expo-cicd-workflows","expo-tailwind-setup","coderabbit:code-review","agent-browser:agent-browser","frontend-design:frontend-design","coderabbit:autofix","coderabbit:code-review"],"plugins":[{"name":"coderabbit","path":"/home/replay-user/.claude/plugins/cache/coderabbit/coderabbit/1.0.0","source":"coderabbit@coderabbit"},{"name":"agent-browser","path":"/home/replay-user/.claude/plugins/cache/agent-browser/agent-browser/ea17db856473","source":"agent-browser@agent-browser"},{"name":"frontend-design","path":"/home/replay-user/.claude/plugins/cache/claude-plugins-official/frontend-design/unknown","source":"frontend-design@claude-plugins-official"},{"name":"coderabbit","path":"/home/replay-user/.claude/plugins/cache/claude-plugins-official/coderabbit/1.1.1","source":"coderabbit@claude-plugins-official"}],"uuid":"741656e7-2341-497c-83bc-89e946bd631f","memory_paths":{"auto":"/home/replay-user/.claude/projects/-private-var-folders-b3-b51-pdxj7dl0t981zpqkxxhr0000gn-T-t3-orchestrator-v2-claude-agent-sdk-record-thread-fork-native-fork-local-rollback-6isYFV/memory/"},"fast_mode_state":"off"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01Fum9PErU1oqWY16swx8VpU","type":"message","role":"assistant","content":[{"type":"text","text":"fork local first"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":0,"cache_read_input_tokens":11826,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"c9784d72-7e4f-4994-8c21-2e7e670ff91c","uuid":"14310fd5-a1aa-448b-8880-de52f86541b1"}}
|
||||
{"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed","resetsAt":1779846000,"rateLimitType":"five_hour","overageStatus":"rejected","overageDisabledReason":"org_level_disabled","isUsingOverage":false},"uuid":"830763b3-7ff2-4b0f-8dd9-35b141cca7a4","session_id":"c9784d72-7e4f-4994-8c21-2e7e670ff91c"}}
|
||||
{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":2891,"duration_api_ms":2011,"num_turns":1,"result":"fork local first","stop_reason":"end_turn","session_id":"c9784d72-7e4f-4994-8c21-2e7e670ff91c","total_cost_usd":0.0036468,"usage":{"input_tokens":3,"cache_creation_input_tokens":0,"cache_read_input_tokens":11826,"output_tokens":6,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":3,"output_tokens":6,"cache_read_input_tokens":11826,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":3,"outputTokens":6,"cacheReadInputTokens":11826,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.0036468,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"bac4638c-4c4e-4e8d-9361-1c32f538297e"}}
|
||||
{"type":"expect_outbound","label":"prompt.offer:fork-second","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"For this fork-local rollback fixture, respond with exactly: fork local second"},"parent_tool_use_id":null}}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","cwd":"/private/tmp/claude-replay-thread_fork_native_fork_local_rollback","session_id":"c9784d72-7e4f-4994-8c21-2e7e670ff91c","tools":["Task","AskUserQuestion","Bash","CronCreate","CronDelete","CronList","Edit","EnterPlanMode","EnterWorktree","ExitPlanMode","ExitWorktree","Glob","Grep","ListMcpResourcesTool","Monitor","NotebookEdit","PushNotification","Read","ReadMcpResourceTool","RemoteTrigger","ScheduleWakeup","Skill","TaskOutput","TaskStop","TodoWrite","ToolSearch","WebFetch","WebSearch","Write","mcp__claude_ai_Google_Drive__authenticate","mcp__claude_ai_Google_Drive__complete_authentication","mcp__uidotsh__uidotsh_fetch"],"mcp_servers":[{"name":"uidotsh","status":"connected"},{"name":"claude.ai Google Drive","status":"needs-auth"}],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":["update-config","debug","simplify","batch","less-permission-prompts","loop","schedule","claude-api","expo-dev-client","ui","agent-browser","native-data-fetching","expo-deployment","btca-cli","uniwind","web-design-guidelines","react-doctor","migrate-nativewind-to-uniwind","building-native-ui","frontend-design","turborepo","vercel-composition-patterns","expo-cicd-workflows","expo-tailwind-setup","coderabbit:review","coderabbit:coderabbit-review","coderabbit:code-review","agent-browser:agent-browser","frontend-design:frontend-design","coderabbit:autofix","compact","context","cost","heapdump","init","review","security-review","extra-usage","insights","team-onboarding"],"apiKeySource":"none","claude_code_version":"2.1.111","output_style":"default","agents":["coderabbit:code-reviewer","Explore","general-purpose","Plan","statusline-setup"],"skills":["update-config","debug","simplify","batch","less-permission-prompts","loop","schedule","claude-api","expo-dev-client","ui","agent-browser","native-data-fetching","expo-deployment","btca-cli","uniwind","web-design-guidelines","react-doctor","migrate-nativewind-to-uniwind","building-native-ui","frontend-design","turborepo","vercel-composition-patterns","expo-cicd-workflows","expo-tailwind-setup","coderabbit:code-review","agent-browser:agent-browser","frontend-design:frontend-design","coderabbit:autofix","coderabbit:code-review"],"plugins":[{"name":"coderabbit","path":"/home/replay-user/.claude/plugins/cache/coderabbit/coderabbit/1.0.0","source":"coderabbit@coderabbit"},{"name":"agent-browser","path":"/home/replay-user/.claude/plugins/cache/agent-browser/agent-browser/ea17db856473","source":"agent-browser@agent-browser"},{"name":"frontend-design","path":"/home/replay-user/.claude/plugins/cache/claude-plugins-official/frontend-design/unknown","source":"frontend-design@claude-plugins-official"},{"name":"coderabbit","path":"/home/replay-user/.claude/plugins/cache/claude-plugins-official/coderabbit/1.1.1","source":"coderabbit@claude-plugins-official"}],"uuid":"d53475a1-0a9f-4c9e-b247-b3b9d347229f","memory_paths":{"auto":"/home/replay-user/.claude/projects/-private-var-folders-b3-b51-pdxj7dl0t981zpqkxxhr0000gn-T-t3-orchestrator-v2-claude-agent-sdk-record-thread-fork-native-fork-local-rollback-6isYFV/memory/"},"fast_mode_state":"off"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_016vLjeBrWCvu6QqJMFd8jDp","type":"message","role":"assistant","content":[{"type":"text","text":"fork local second"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":0,"cache_read_input_tokens":11851,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"output_tokens":6,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"c9784d72-7e4f-4994-8c21-2e7e670ff91c","uuid":"b9bb4e45-d52d-4fb3-adf7-4b5e4d9d0dd6"}}
|
||||
{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":2787,"duration_api_ms":3998,"num_turns":1,"result":"fork local second","stop_reason":"end_turn","session_id":"c9784d72-7e4f-4994-8c21-2e7e670ff91c","total_cost_usd":0.0073011,"usage":{"input_tokens":3,"cache_creation_input_tokens":0,"cache_read_input_tokens":11851,"output_tokens":6,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":3,"output_tokens":6,"cache_read_input_tokens":11851,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":6,"outputTokens":12,"cacheReadInputTokens":23677,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.0073011,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"af3731ff-720f-4919-87f6-c0b27b3ee21e"}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
{"type":"expect_outbound","label":"query.open:fork-resume-at-cursor","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"resumeSessionAt":"14310fd5-a1aa-448b-8880-de52f86541b1","resume":"c9784d72-7e4f-4994-8c21-2e7e670ff91c"}}}
|
||||
{"type":"expect_outbound","label":"prompt.offer:fork-after-rollback","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content."},"parent_tool_use_id":null}}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_started","hook_id":"9deedf90-8751-4ba3-8602-4499dba72f9c","hook_name":"SessionStart:resume","hook_event":"SessionStart","uuid":"c2908d02-3d69-4d36-bc32-50aaa32e4e92","session_id":"05a5ea05-d17a-4841-98e3-7cf6957f3f0a"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_response","hook_id":"9deedf90-8751-4ba3-8602-4499dba72f9c","hook_name":"SessionStart:resume","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"f438cfbd-c7e3-4c83-a047-205862b253e6","session_id":"05a5ea05-d17a-4841-98e3-7cf6957f3f0a"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","cwd":"/private/tmp/claude-replay-thread_fork_native_fork_local_rollback","session_id":"c9784d72-7e4f-4994-8c21-2e7e670ff91c","tools":["Task","AskUserQuestion","Bash","CronCreate","CronDelete","CronList","Edit","EnterPlanMode","EnterWorktree","ExitPlanMode","ExitWorktree","Glob","Grep","ListMcpResourcesTool","Monitor","NotebookEdit","PushNotification","Read","ReadMcpResourceTool","RemoteTrigger","ScheduleWakeup","Skill","TaskOutput","TaskStop","TodoWrite","ToolSearch","WebFetch","WebSearch","Write","mcp__claude_ai_Google_Drive__authenticate","mcp__claude_ai_Google_Drive__complete_authentication","mcp__uidotsh__uidotsh_fetch"],"mcp_servers":[{"name":"uidotsh","status":"connected"},{"name":"claude.ai Google Drive","status":"needs-auth"}],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":["update-config","debug","simplify","batch","less-permission-prompts","loop","schedule","claude-api","expo-dev-client","ui","agent-browser","native-data-fetching","expo-deployment","btca-cli","uniwind","web-design-guidelines","react-doctor","migrate-nativewind-to-uniwind","building-native-ui","frontend-design","turborepo","vercel-composition-patterns","expo-cicd-workflows","expo-tailwind-setup","coderabbit:review","coderabbit:coderabbit-review","coderabbit:code-review","agent-browser:agent-browser","frontend-design:frontend-design","coderabbit:autofix","compact","context","cost","heapdump","init","review","security-review","extra-usage","insights","team-onboarding"],"apiKeySource":"none","claude_code_version":"2.1.111","output_style":"default","agents":["coderabbit:code-reviewer","Explore","general-purpose","Plan","statusline-setup"],"skills":["update-config","debug","simplify","batch","less-permission-prompts","loop","schedule","claude-api","expo-dev-client","ui","agent-browser","native-data-fetching","expo-deployment","btca-cli","uniwind","web-design-guidelines","react-doctor","migrate-nativewind-to-uniwind","building-native-ui","frontend-design","turborepo","vercel-composition-patterns","expo-cicd-workflows","expo-tailwind-setup","coderabbit:code-review","agent-browser:agent-browser","frontend-design:frontend-design","coderabbit:code-review","coderabbit:autofix"],"plugins":[{"name":"coderabbit","path":"/home/replay-user/.claude/plugins/marketplaces/coderabbit/","source":"coderabbit@coderabbit"},{"name":"agent-browser","path":"/home/replay-user/.claude/plugins/cache/agent-browser/agent-browser/ea17db856473","source":"agent-browser@agent-browser"},{"name":"frontend-design","path":"/home/replay-user/.claude/plugins/cache/claude-plugins-official/frontend-design/unknown","source":"frontend-design@claude-plugins-official"},{"name":"coderabbit","path":"/home/replay-user/.claude/plugins/cache/claude-plugins-official/coderabbit/1.1.1","source":"coderabbit@claude-plugins-official"}],"uuid":"54c3aef7-de37-41de-81e9-b79cf044464b","memory_paths":{"auto":"/home/replay-user/.claude/projects/-private-var-folders-b3-b51-pdxj7dl0t981zpqkxxhr0000gn-T-t3-orchestrator-v2-claude-agent-sdk-record-thread-fork-native-fork-local-rollback-6isYFV/memory/"},"fast_mode_state":"off"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01SMtNaYRbU1BonxpaTu5bxG","type":"message","role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to repeat the user-visible conversation so far verbatim, including only user and assistant messages.","signature":"Er4CCmUIDhgCKkAHbcjlRRK3rHsyqzZn5jI5+wWIl32x7k4E5feJpl1bBZVM6FJVJDBBV5ZgPlHGZMMALoCcDsULDBqzwNbRQ8o0MhFjbGF1ZGUtc29ubmV0LTQtNjgAQgh0aGlua2luZxIMoLzq1u1TRvWwekqBGgwtjzuuwl6xVaBbaIwiMFElE3wNpvOZkdvQJt0d5Iy2NLdr4Wfwrm+7xTXMyx8a6uiOS9qM9NCvBFlNCOV80SqGARBc5k/ENzjBSzsiEbFPeRQi7CV0sm3Csm4WAbC92/ulSlHrBa/+2flxuX4BC24CtUORK7vwEaBjXCmClZibaHWKTmk2cq1SXGzQGifcNR94R5O/B7/oYR/VBEaZb7ctHHXaO7SEifznsRhPibvj9wG4BnxU99aoUgnk1riwYsyEXWsg1rFNGAE="}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":0,"cache_read_input_tokens":11864,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"output_tokens":8,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"c9784d72-7e4f-4994-8c21-2e7e670ff91c","uuid":"a259ccd5-2f6b-4e3c-9c1a-ce55d21c5ba5"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01SMtNaYRbU1BonxpaTu5bxG","type":"message","role":"assistant","content":[{"type":"text","text":"**User:** For this fork-local rollback fixture, respond with exactly: fork local source alpha\n\n**Assistant:** fork local source alpha\n\n**User:** For this fork-local rollback fixture, respond with exactly: fork local first\n\n**Assistant:** fork local first\n\n**User:** Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content."}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":0,"cache_read_input_tokens":11864,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"output_tokens":8,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"c9784d72-7e4f-4994-8c21-2e7e670ff91c","uuid":"1ef6575a-75b1-4568-84cb-0eadc9e224e6"}}
|
||||
{"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed","resetsAt":1779846000,"rateLimitType":"five_hour","overageStatus":"rejected","overageDisabledReason":"org_level_disabled","isUsingOverage":false},"uuid":"a39eccdb-a0f9-4b39-bbd1-6931138dc5d0","session_id":"c9784d72-7e4f-4994-8c21-2e7e670ff91c"}}
|
||||
{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":4060,"duration_api_ms":3133,"num_turns":1,"result":"**User:** For this fork-local rollback fixture, respond with exactly: fork local source alpha\n\n**Assistant:** fork local source alpha\n\n**User:** For this fork-local rollback fixture, respond with exactly: fork local first\n\n**Assistant:** fork local first\n\n**User:** Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content.","stop_reason":"end_turn","session_id":"c9784d72-7e4f-4994-8c21-2e7e670ff91c","total_cost_usd":0.005518199999999999,"usage":{"input_tokens":3,"cache_creation_input_tokens":0,"cache_read_input_tokens":11864,"output_tokens":130,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":3,"output_tokens":130,"cache_read_input_tokens":11864,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":3,"outputTokens":130,"cacheReadInputTokens":11864,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.005518199999999999,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"7741f0e1-8180-48d8-8073-0295e00a19f8"}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
{"type":"transcript_start","provider":"claudeAgent","protocol":"claude-agent-sdk.query","version":"0.2.111","scenario":"thread_fork_native_prior_turn","metadata":{"prompts":["For this fork-boundary fixture, respond with exactly: fork boundary alpha","For this fork-boundary fixture, respond with exactly: fork boundary beta","Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content."],"model":"claude-sonnet-4-6","nativeSessionId":"a91391e1-0de3-4107-a7c9-db7b1bbd8b99","queryMode":"fork_session_prior_turn","tools":"claude_code","permissionMode":"bypassPermissions","generatedBy":"recordClaudeAgentSdkReplayTranscript","sourceAssistantMessageUuids":["be0e3276-8c27-44bf-8ed0-0b4424e9f902","c517b74b-9537-4260-afcb-186c4056c0a4"],"forkUpToMessageId":"be0e3276-8c27-44bf-8ed0-0b4424e9f902","forkedNativeSessionId":"f5cc58dd-0d74-4950-9fb5-2a9fded47ddd"}}
|
||||
{"type":"expect_outbound","label":"query.open:source","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"sessionId":"a91391e1-0de3-4107-a7c9-db7b1bbd8b99"}}}
|
||||
{"type":"expect_outbound","label":"prompt.offer:1","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"For this fork-boundary fixture, respond with exactly: fork boundary alpha"},"parent_tool_use_id":null}}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_started","hook_id":"25b085e7-a6e9-4f30-9708-b189c961d06f","hook_name":"SessionStart:startup","hook_event":"SessionStart","uuid":"42c40147-86c8-4294-bdb4-f1815f48808e","session_id":"a91391e1-0de3-4107-a7c9-db7b1bbd8b99"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_response","hook_id":"25b085e7-a6e9-4f30-9708-b189c961d06f","hook_name":"SessionStart:startup","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"9804deb1-9abf-4e58-9d04-6e163dc7b0af","session_id":"a91391e1-0de3-4107-a7c9-db7b1bbd8b99"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.111","cwd":"/tmp/claude-replay-thread_fork_native_prior_turn","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"b9412e24-eefc-4838-9ede-bb6e00951d15","session_id":"a91391e1-0de3-4107-a7c9-db7b1bbd8b99"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_014hdmSJdwbpJ5NkFgqbhfEe","type":"message","role":"assistant","content":[{"type":"text","text":"fork boundary alpha"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":2342,"cache_read_input_tokens":9455,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":2342},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"a91391e1-0de3-4107-a7c9-db7b1bbd8b99","uuid":"be0e3276-8c27-44bf-8ed0-0b4424e9f902"}}
|
||||
{"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"0c649726-b7a2-4e89-a62a-a9ae534905c7","session_id":"a91391e1-0de3-4107-a7c9-db7b1bbd8b99"}}
|
||||
{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":1174,"duration_api_ms":897,"num_turns":1,"result":"fork boundary alpha","stop_reason":"end_turn","session_id":"a91391e1-0de3-4107-a7c9-db7b1bbd8b99","total_cost_usd":0.011718000000000001,"usage":{"input_tokens":3,"cache_creation_input_tokens":2342,"cache_read_input_tokens":9455,"output_tokens":6,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":2342,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":3,"output_tokens":6,"cache_read_input_tokens":9455,"cache_creation_input_tokens":2342,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":2342},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":3,"outputTokens":6,"cacheReadInputTokens":9455,"cacheCreationInputTokens":2342,"webSearchRequests":0,"costUSD":0.011718000000000001,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"d384185c-9b38-44a4-8917-53d7a8765a5a"}}
|
||||
{"type":"expect_outbound","label":"prompt.offer:2","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"For this fork-boundary fixture, respond with exactly: fork boundary beta"},"parent_tool_use_id":null}}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.111","cwd":"/tmp/claude-replay-thread_fork_native_prior_turn","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"5fd1f879-e742-4911-95e3-3dfb0141dc52","session_id":"a91391e1-0de3-4107-a7c9-db7b1bbd8b99"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_0181K4CdzyVanM6Px26CQP7L","type":"message","role":"assistant","content":[{"type":"text","text":"fork boundary beta"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":23,"cache_read_input_tokens":11797,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":23},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"a91391e1-0de3-4107-a7c9-db7b1bbd8b99","uuid":"c517b74b-9537-4260-afcb-186c4056c0a4"}}
|
||||
{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":2545,"duration_api_ms":3001,"num_turns":1,"result":"fork boundary beta","stop_reason":"end_turn","session_id":"a91391e1-0de3-4107-a7c9-db7b1bbd8b99","total_cost_usd":0.01544235,"usage":{"input_tokens":3,"cache_creation_input_tokens":23,"cache_read_input_tokens":11797,"output_tokens":6,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":23,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":3,"output_tokens":6,"cache_read_input_tokens":11797,"cache_creation_input_tokens":23,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":23},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":6,"outputTokens":12,"cacheReadInputTokens":21252,"cacheCreationInputTokens":2365,"webSearchRequests":0,"costUSD":0.01544235,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"e4f26af4-3a60-45f3-8d5c-c0f8b968c400"}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
{"type":"expect_outbound","label":"session.fork","frame":{"type":"session.fork","sessionId":"a91391e1-0de3-4107-a7c9-db7b1bbd8b99","options":{"dir":"/tmp/claude-replay-thread_fork_native_prior_turn","upToMessageId":"be0e3276-8c27-44bf-8ed0-0b4424e9f902"}}}
|
||||
{"type":"emit_inbound","label":"session.forked","frame":{"type":"session.forked","sessionId":"f5cc58dd-0d74-4950-9fb5-2a9fded47ddd"}}
|
||||
{"type":"expect_outbound","label":"query.open:fork","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"resume":"f5cc58dd-0d74-4950-9fb5-2a9fded47ddd"}}}
|
||||
{"type":"expect_outbound","label":"prompt.offer:3","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content."},"parent_tool_use_id":null}}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_started","hook_id":"6ce9327c-4534-484c-96e5-b47fa1a3143f","hook_name":"SessionStart:resume","hook_event":"SessionStart","uuid":"d4280b57-8334-4021-971d-93bba0e38b4c","session_id":"1dc8dab2-9e1b-4475-bd46-f40e2ebca07d"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_response","hook_id":"6ce9327c-4534-484c-96e5-b47fa1a3143f","hook_name":"SessionStart:resume","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"ac1dee1e-63c5-4db8-81b7-e1f68ecadf01","session_id":"1dc8dab2-9e1b-4475-bd46-f40e2ebca07d"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.111","cwd":"/tmp/claude-replay-thread_fork_native_prior_turn","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"65e2ff1d-ded8-42d2-a491-70fed78b2368","session_id":"f5cc58dd-0d74-4950-9fb5-2a9fded47ddd"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01NP2pmrWJHY1AZ8HWqgsCQS","type":"message","role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to repeat the user-visible conversation so far verbatim, including only user and assistant messages.","signature":"ErQCClsIDRgCKkAHbcjlRRK3rHsyqzZn5jI5+wWIl32x7k4E5feJpl1bBZVM6FJVJDBBV5ZgPlHGZMMALoCcDsULDBqzwNbRQ8o0MhFjbGF1ZGUtc29ubmV0LTQtNjgAEgzxdU+J4dE9HPjPJBwaDFLfMOU1oTIY4zJlVSIwkqZMdRU0W/uaPIztqHfQSORVwpEKdR6RAOJb0t5E+IOBu+tFmopmwfCbQjON3NoEKoYBs8E4pkuYLNz2Q+Qp7XeZOdCvvXUTYVIBJ90r2tl9NtEyDgCKce2VtEShQxnPZH9OhcyuEuKrL8c+Fsc8rTj6vYelMB2UJfj9KI1bREqSwoBf1oD7uwiuOz+S40+1Tx7LprJUcmw+JzkTO73YmVr8EHYGCHbQlLSeUHm7NgypEkTcOAaETiIYAQ=="}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":38,"cache_read_input_tokens":11797,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":38},"output_tokens":7,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"f5cc58dd-0d74-4950-9fb5-2a9fded47ddd","uuid":"3a81c9d0-22dd-4bbd-8f27-103c75e2878c"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01NP2pmrWJHY1AZ8HWqgsCQS","type":"message","role":"assistant","content":[{"type":"text","text":"**User:** For this fork-boundary fixture, respond with exactly: fork boundary alpha\n\n**Assistant:** fork boundary alpha\n\n**User:** Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content."}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":38,"cache_read_input_tokens":11797,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":38},"output_tokens":7,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"f5cc58dd-0d74-4950-9fb5-2a9fded47ddd","uuid":"90f4c83b-8fff-454a-a95d-aa0cf87ff967"}}
|
||||
{"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"74ba363a-dc66-4335-b18c-b335f75d4c9b","session_id":"f5cc58dd-0d74-4950-9fb5-2a9fded47ddd"}}
|
||||
{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":2557,"duration_api_ms":2194,"num_turns":1,"result":"**User:** For this fork-boundary fixture, respond with exactly: fork boundary alpha\n\n**Assistant:** fork boundary alpha\n\n**User:** Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content.","stop_reason":"end_turn","session_id":"f5cc58dd-0d74-4950-9fb5-2a9fded47ddd","total_cost_usd":0.0051756,"usage":{"input_tokens":3,"cache_creation_input_tokens":38,"cache_read_input_tokens":11797,"output_tokens":99,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":38,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":3,"output_tokens":99,"cache_read_input_tokens":11797,"cache_creation_input_tokens":38,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":38},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":3,"outputTokens":99,"cacheReadInputTokens":11797,"cacheCreationInputTokens":38,"webSearchRequests":0,"costUSD":0.0051756,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"6fe96da3-b212-41e9-be7b-12d5aee4f191"}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { assert } from "@effect/vitest";
|
||||
import type { ProviderReplayTranscript } from "@t3tools/contracts";
|
||||
|
||||
import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";
|
||||
import {
|
||||
assertBaseProjection,
|
||||
assertRunOrdinals,
|
||||
assertSemanticProjectionIntegrity,
|
||||
assertTurnItemTypeSequence,
|
||||
assertUserMessagesInclude,
|
||||
assertVisibleTurnItemTypeSequence,
|
||||
assertVisibleUserMessagesExclude,
|
||||
assertVisibleUserMessagesInclude,
|
||||
projectionFor,
|
||||
THREAD_ROLLBACK_AFTER_PROMPT,
|
||||
THREAD_ROLLBACK_FIRST_PROMPT,
|
||||
THREAD_ROLLBACK_SECOND_PROMPT,
|
||||
} from "../shared.ts";
|
||||
|
||||
export function assertClaudeThreadRollbackOutput(
|
||||
result: OrchestratorV2ScenarioResult,
|
||||
transcript: ProviderReplayTranscript,
|
||||
) {
|
||||
assertBaseProjection({
|
||||
result,
|
||||
transcript,
|
||||
runCount: 3,
|
||||
runStatuses: ["completed", "rolled_back", "completed"],
|
||||
});
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertRunOrdinals(projection, [1, 2, 3]);
|
||||
assertTurnItemTypeSequence(projection, [
|
||||
"user_message",
|
||||
"assistant_message",
|
||||
"checkpoint",
|
||||
"user_message",
|
||||
"assistant_message",
|
||||
"checkpoint",
|
||||
"user_message",
|
||||
"assistant_message",
|
||||
"checkpoint",
|
||||
]);
|
||||
assertVisibleTurnItemTypeSequence(projection, [
|
||||
"user_message",
|
||||
"assistant_message",
|
||||
"checkpoint",
|
||||
"user_message",
|
||||
"assistant_message",
|
||||
"checkpoint",
|
||||
]);
|
||||
assertUserMessagesInclude(projection, [
|
||||
THREAD_ROLLBACK_FIRST_PROMPT,
|
||||
THREAD_ROLLBACK_SECOND_PROMPT,
|
||||
THREAD_ROLLBACK_AFTER_PROMPT,
|
||||
]);
|
||||
assertVisibleUserMessagesInclude(projection, [
|
||||
THREAD_ROLLBACK_FIRST_PROMPT,
|
||||
THREAD_ROLLBACK_AFTER_PROMPT,
|
||||
]);
|
||||
assertVisibleUserMessagesExclude(projection, [THREAD_ROLLBACK_SECOND_PROMPT]);
|
||||
assert.isAtLeast(projection.checkpoints.length, 2);
|
||||
assert.isTrue(
|
||||
projection.runs.some((run) => run.status === "rolled_back"),
|
||||
"rollback must be visible in run state",
|
||||
);
|
||||
assert.equal(projection.providerThreads[0]?.nativeConversationHeadRef, null);
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
{"type":"transcript_start","provider":"claudeAgent","protocol":"claude-agent-sdk.query","version":"0.2.111","scenario":"thread_rollback","metadata":{"prompts":["Respond with exactly: rollback fixture first turn complete","Respond with exactly: rollback fixture second turn complete","Repeat the conversation verbatim."],"model":"claude-sonnet-4-6","nativeSessionId":"f9415703-bf61-49e3-8155-1d3fed83f935","queryMode":"resume_at_cursor","tools":"claude_code","permissionMode":"bypassPermissions","generatedBy":"recordClaudeAgentSdkReplayTranscript","resumeSessionAt":"3831efb6-619c-4c16-a38a-bf788040ac42","sourceAssistantMessageUuids":["3831efb6-619c-4c16-a38a-bf788040ac42","d03f5cd6-5e8b-4cf5-998f-7d96a923ecf8"]}}
|
||||
{"type":"expect_outbound","label":"query.open:source","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"sessionId":"f9415703-bf61-49e3-8155-1d3fed83f935"}}}
|
||||
{"type":"expect_outbound","label":"prompt.offer:1","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Respond with exactly: rollback fixture first turn complete"},"parent_tool_use_id":null}}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_started","hook_id":"10af24d0-396e-4d26-a07b-d6c66704b322","hook_name":"SessionStart:startup","hook_event":"SessionStart","uuid":"45ae7f96-b6f0-49fa-933d-ea449ac377ea","session_id":"f9415703-bf61-49e3-8155-1d3fed83f935"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_response","hook_id":"10af24d0-396e-4d26-a07b-d6c66704b322","hook_name":"SessionStart:startup","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"b3e745a0-d47d-4bb8-b67f-5faf244eb50d","session_id":"f9415703-bf61-49e3-8155-1d3fed83f935"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.111","cwd":"/tmp/claude-replay-thread_rollback","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"218871ce-bb95-4526-ba59-0dcc71e47835","session_id":"f9415703-bf61-49e3-8155-1d3fed83f935"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01NUv7RH7XTuJnHd6WyVG1Vo","type":"message","role":"assistant","content":[{"type":"text","text":"rollback fixture first turn complete"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":11794,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":11794},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"f9415703-bf61-49e3-8155-1d3fed83f935","uuid":"3831efb6-619c-4c16-a38a-bf788040ac42"}}
|
||||
{"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"db72cb9f-000f-454a-8b05-cc231a6434ed","session_id":"f9415703-bf61-49e3-8155-1d3fed83f935"}}
|
||||
{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":1813,"duration_api_ms":1317,"num_turns":1,"result":"rollback fixture first turn complete","stop_reason":"end_turn","session_id":"f9415703-bf61-49e3-8155-1d3fed83f935","total_cost_usd":0.0443715,"usage":{"input_tokens":3,"cache_creation_input_tokens":11794,"cache_read_input_tokens":0,"output_tokens":9,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":11794,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":3,"output_tokens":9,"cache_read_input_tokens":0,"cache_creation_input_tokens":11794,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":11794},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":3,"outputTokens":9,"cacheReadInputTokens":0,"cacheCreationInputTokens":11794,"webSearchRequests":0,"costUSD":0.0443715,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"7b499f7a-fb88-462d-bdd0-aa4841528c96"}}
|
||||
{"type":"expect_outbound","label":"prompt.offer:2","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Respond with exactly: rollback fixture second turn complete"},"parent_tool_use_id":null}}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.111","cwd":"/tmp/claude-replay-thread_rollback","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"b398ca88-f2c0-4606-9480-d4a37be9fcdc","session_id":"f9415703-bf61-49e3-8155-1d3fed83f935"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_01U9BNPSbhQkJZsmNc4VpdBn","type":"message","role":"assistant","content":[{"type":"text","text":"rollback fixture second turn complete"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":23,"cache_read_input_tokens":11794,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":23},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"f9415703-bf61-49e3-8155-1d3fed83f935","uuid":"d03f5cd6-5e8b-4cf5-998f-7d96a923ecf8"}}
|
||||
{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":1563,"duration_api_ms":2262,"num_turns":1,"result":"rollback fixture second turn complete","stop_reason":"end_turn","session_id":"f9415703-bf61-49e3-8155-1d3fed83f935","total_cost_usd":0.04813995,"usage":{"input_tokens":3,"cache_creation_input_tokens":23,"cache_read_input_tokens":11794,"output_tokens":9,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":23,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":3,"output_tokens":9,"cache_read_input_tokens":11794,"cache_creation_input_tokens":23,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":23},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":6,"outputTokens":18,"cacheReadInputTokens":11794,"cacheCreationInputTokens":11817,"webSearchRequests":0,"costUSD":0.04813995,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"badfd2cf-d9be-486f-a0ad-fdd84c9b644f"}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
{"type":"expect_outbound","label":"query.open:resume_at_cursor","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"resumeSessionAt":"3831efb6-619c-4c16-a38a-bf788040ac42","resume":"f9415703-bf61-49e3-8155-1d3fed83f935"}}}
|
||||
{"type":"expect_outbound","label":"prompt.offer:3","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Repeat the conversation verbatim."},"parent_tool_use_id":null}}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_started","hook_id":"c9f667e7-ca12-49e9-a8ba-bdbca3abbb52","hook_name":"SessionStart:resume","hook_event":"SessionStart","uuid":"8ca5d046-22be-4a78-b62d-017a82cacde5","session_id":"364d2478-ab5e-4d54-8f1a-ac5985780b94"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_response","hook_id":"c9f667e7-ca12-49e9-a8ba-bdbca3abbb52","hook_name":"SessionStart:resume","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"6369a44f-6abb-4e6b-8302-603b2ae6f4af","session_id":"364d2478-ab5e-4d54-8f1a-ac5985780b94"}}
|
||||
{"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.111","cwd":"/tmp/claude-replay-thread_rollback","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"18ad1c2a-af69-41b0-b5c4-68368d89338e","session_id":"f9415703-bf61-49e3-8155-1d3fed83f935"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_018VXP9s6TV1dsMYKJDkM5cb","type":"message","role":"assistant","content":[{"type":"thinking","thinking":"The user wants me to repeat the conversation verbatim. Let me recall the conversation so far.","signature":"EpoCClsIDRgCKkAWt3L1MZbqQnRJfaQpC/zTmnX+89ilokWcVeWkpDrrEY2oZntDTkRch9BHty3vZDGi5JqizC60fkS3UYDi9nvdMhFjbGF1ZGUtc29ubmV0LTQtNjgAEgy2iD+JrxDeNoidixsaDLnyeHyQiuJ87Mp2HSIwYxphRaf5TTSOq0kBF/cS2SYHvchyl7A857XzjZC6x1+n1WRVjeFu85/guUqGhkbpKm2zNZSjsFz9IVYeNWdsNuBbUftQ5RZuBipNrqaJfXtBuGl7NHeBArYZvFgcNZMScvsFrYjII7RWaEOAZYaiRnxSUzrZB+rEe0xnx0PJHKM3Vv5uVJl68/JXEyTfWV1hgKGa5hm6rUpoudwW7eujGAE="}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":20,"cache_read_input_tokens":11794,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":20},"output_tokens":6,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"f9415703-bf61-49e3-8155-1d3fed83f935","uuid":"2a455c39-eef8-45b9-83f5-11567ff0459b"}}
|
||||
{"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_018VXP9s6TV1dsMYKJDkM5cb","type":"message","role":"assistant","content":[{"type":"text","text":"Here is the conversation verbatim:\n\n---\n\n**User:** Respond with exactly: rollback fixture first turn complete\n\n**Assistant:** rollback fixture first turn complete\n\n---\n\n**User:** Repeat the conversation verbatim."}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":20,"cache_read_input_tokens":11794,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":20},"output_tokens":6,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"f9415703-bf61-49e3-8155-1d3fed83f935","uuid":"572fafb1-2351-4f3a-848d-7b4703496bc3"}}
|
||||
{"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"f3a34752-3bb6-42d7-a5d2-230917f30a7c","session_id":"f9415703-bf61-49e3-8155-1d3fed83f935"}}
|
||||
{"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":2368,"duration_api_ms":1731,"num_turns":1,"result":"Here is the conversation verbatim:\n\n---\n\n**User:** Respond with exactly: rollback fixture first turn complete\n\n**Assistant:** rollback fixture first turn complete\n\n---\n\n**User:** Repeat the conversation verbatim.","stop_reason":"end_turn","session_id":"f9415703-bf61-49e3-8155-1d3fed83f935","total_cost_usd":0.0049272000000000005,"usage":{"input_tokens":3,"cache_creation_input_tokens":20,"cache_read_input_tokens":11794,"output_tokens":87,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":20,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":3,"output_tokens":87,"cache_read_input_tokens":11794,"cache_creation_input_tokens":20,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":20},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":3,"outputTokens":87,"cacheReadInputTokens":11794,"cacheCreationInputTokens":20,"webSearchRequests":0,"costUSD":0.0049272000000000005,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"980fa6e9-fcc5-4f52-92c7-ff95c180a46a"}}
|
||||
{"type":"runtime_exit","status":"success"}
|
||||
@@ -6,9 +6,11 @@ import {
|
||||
assertBaseProjection,
|
||||
assertRunOrdinals,
|
||||
assertSemanticProjectionIntegrity,
|
||||
assertTurnItemTypes,
|
||||
assertTurnItemTypeSequence,
|
||||
assertVisibleTurnItemTypeSequence,
|
||||
assertVisibleUserMessagesExclude,
|
||||
assertVisibleUserMessagesInclude,
|
||||
assertUserMessagesInclude,
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems,
|
||||
projectionFor,
|
||||
THREAD_ROLLBACK_AFTER_PROMPT,
|
||||
THREAD_ROLLBACK_FIRST_PROMPT,
|
||||
@@ -28,14 +30,36 @@ export function assertThreadRollbackOutput(
|
||||
|
||||
const projection = projectionFor(result, transcript.scenario);
|
||||
assertSemanticProjectionIntegrity(projection);
|
||||
assertVisibleTurnItemsMirrorLocalTurnItems(projection);
|
||||
assertRunOrdinals(projection, [1, 2, 3]);
|
||||
assertTurnItemTypes(projection, ["user_message", "assistant_message", "checkpoint"]);
|
||||
assertTurnItemTypeSequence(projection, [
|
||||
"user_message",
|
||||
"assistant_message",
|
||||
"checkpoint",
|
||||
"user_message",
|
||||
"assistant_message",
|
||||
"checkpoint",
|
||||
"user_message",
|
||||
"assistant_message",
|
||||
"checkpoint",
|
||||
]);
|
||||
assertVisibleTurnItemTypeSequence(projection, [
|
||||
"user_message",
|
||||
"assistant_message",
|
||||
"checkpoint",
|
||||
"user_message",
|
||||
"assistant_message",
|
||||
"checkpoint",
|
||||
]);
|
||||
assertUserMessagesInclude(projection, [
|
||||
THREAD_ROLLBACK_FIRST_PROMPT,
|
||||
THREAD_ROLLBACK_SECOND_PROMPT,
|
||||
THREAD_ROLLBACK_AFTER_PROMPT,
|
||||
]);
|
||||
assertVisibleUserMessagesInclude(projection, [
|
||||
THREAD_ROLLBACK_FIRST_PROMPT,
|
||||
THREAD_ROLLBACK_AFTER_PROMPT,
|
||||
]);
|
||||
assertVisibleUserMessagesExclude(projection, [THREAD_ROLLBACK_SECOND_PROMPT]);
|
||||
assert.isAtLeast(projection.checkpoints.length, 2);
|
||||
assert.isTrue(
|
||||
projection.runs.some((run) => run.status === "rolled_back"),
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* scopedSafeTeardown — run a scope-requiring effect so that finalizer
|
||||
* failures during scope close cannot override the body's Exit.
|
||||
*
|
||||
* Motivation
|
||||
* ----------
|
||||
* The obvious pattern is `body.pipe(Effect.scoped)`: provide a fresh
|
||||
* Scope, run the body, close the scope with the body's Exit. If a
|
||||
* finalizer (e.g. `ChildProcess.kill` from an effect-codex-app-server
|
||||
* spawn) dies during that close, the combined Exit becomes the
|
||||
* finalizer's defect — even when the body already succeeded.
|
||||
*
|
||||
* Concretely this bit us in the Codex provider probe: a successful
|
||||
* `initialize` → `account/read` → `skills/list` → `model/list`
|
||||
* round-trip produced a `CodexAppServerProviderSnapshot`, but the
|
||||
* `Layer.build(CodexClient.layerCommand(...))` finalizer then failed to
|
||||
* kill the `codex app-server` subprocess with a `PlatformError`. The
|
||||
* defect bubbled past `Effect.result` in `checkCodexProviderStatus`,
|
||||
* died `refreshOneSource`, and `providersRef` never saw the snapshot.
|
||||
*
|
||||
* Strategy
|
||||
* --------
|
||||
* 1. Make a fresh scope manually.
|
||||
* 2. Run the body against that scope, capturing its Exit via
|
||||
* `Effect.exit`.
|
||||
* 3. Run the body inside an interruptible region, but capture the Exit from
|
||||
* success, failure, defect, or interruption.
|
||||
* 4. Close the scope, catching any cause (typed failure *or* defect)
|
||||
* with a log.
|
||||
* 5. Replay the captured Exit so typed body failures still surface and
|
||||
* successes still return their value.
|
||||
*
|
||||
* The helper deliberately logs teardown causes at `Warning` level —
|
||||
* silently swallowing them is dangerous because they usually indicate a
|
||||
* real bug in a downstream Layer's finalizer.
|
||||
*
|
||||
* @module provider/Layers/scopedSafeTeardown
|
||||
*/
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
/**
|
||||
* Run `effect` with a freshly made `Scope.Scope`, guaranteeing that
|
||||
* teardown failures cannot override the body's Exit.
|
||||
*
|
||||
* Shape matches `Effect.scoped`: takes an effect whose env includes
|
||||
* `Scope.Scope`, returns one whose env excludes it.
|
||||
*
|
||||
* @param label Short label for the warning log emitted when teardown
|
||||
* fails. Use something like `"codex-probe"`.
|
||||
*/
|
||||
export const scopedSafeTeardown =
|
||||
(label: string) =>
|
||||
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, Exclude<R, Scope.Scope>> =>
|
||||
Effect.uninterruptibleMask((restore) =>
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* Scope.make();
|
||||
|
||||
const bodyExit = yield* effect.pipe(
|
||||
restore,
|
||||
Effect.provideService(Scope.Scope, scope),
|
||||
Effect.exit,
|
||||
);
|
||||
|
||||
yield* Scope.close(scope, bodyExit).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning(`${label} teardown errored; preserving body result`, cause),
|
||||
),
|
||||
);
|
||||
return yield* bodyExit;
|
||||
}),
|
||||
) as Effect.Effect<A, E, Exclude<R, Scope.Scope>>;
|
||||
+11
-9
@@ -77,6 +77,7 @@ import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts";
|
||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestratorV2 } from "./orchestration-v2/Orchestrator.ts";
|
||||
import { userFacingDispatchErrorMessage } from "./orchestration-v2/UserFacingErrors.ts";
|
||||
import {
|
||||
observeRpcEffect as instrumentRpcEffect,
|
||||
observeRpcStream as instrumentRpcStream,
|
||||
@@ -1387,15 +1388,16 @@ const makeWsRpcLayer = (
|
||||
ORCHESTRATION_V2_WS_METHODS.dispatchCommand,
|
||||
orchestrationV2.dispatch(command).pipe(
|
||||
Effect.map((result) => ({ sequence: result.sequence })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationV2DispatchCommandError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
message: "Failed to dispatch orchestration V2 command",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => {
|
||||
const detail = userFacingDispatchErrorMessage(cause);
|
||||
return new OrchestrationV2DispatchCommandError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
message: detail ?? "Failed to dispatch orchestration V2 command",
|
||||
...(detail === undefined ? {} : { detail }),
|
||||
cause,
|
||||
});
|
||||
}),
|
||||
),
|
||||
{
|
||||
"rpc.aggregate": "orchestrationV2",
|
||||
|
||||
@@ -20,15 +20,23 @@ import {
|
||||
type ServerProvider,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
import { GitMergeIcon } from "lucide-react";
|
||||
import type { CSSProperties, DragEvent, ReactNode } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { ProviderModelPicker } from "../components/chat/ProviderModelPicker";
|
||||
import { getPrimaryEnvironmentConnection } from "../environments/runtime";
|
||||
import { useSettings } from "../hooks/useSettings";
|
||||
import { newCommandId, newMessageId, newProjectId, newThreadId } from "../lib/utils";
|
||||
import { deriveProviderInstanceEntries, sortProviderInstanceEntries } from "../providerInstances";
|
||||
import { GitMergeIcon } from "lucide-react";
|
||||
import { type AppModelOption, getAppModelOptionsForInstance } from "../modelSelection";
|
||||
import {
|
||||
type ProviderInstanceEntry,
|
||||
deriveProviderInstanceEntries,
|
||||
sortProviderInstanceEntries,
|
||||
} from "../providerInstances";
|
||||
import { useServerKeybindings, useServerProviders } from "../rpc/serverState";
|
||||
|
||||
export const Route = createFileRoute("/debug/orchestration-v2")({
|
||||
component: OrchestrationV2DebugRoute,
|
||||
@@ -39,10 +47,7 @@ const DEBUG_CODEX_DRIVER = ProviderDriverKind.make("codex");
|
||||
const DEBUG_CLAUDE_DRIVER = ProviderDriverKind.make("claudeAgent");
|
||||
const DEBUG_CODEX_INSTANCE_ID = ProviderInstanceId.make("codex");
|
||||
const DEBUG_CLAUDE_INSTANCE_ID = ProviderInstanceId.make("claudeAgent");
|
||||
const DEFAULT_MODEL_SELECTION = {
|
||||
instanceId: DEBUG_CODEX_INSTANCE_ID,
|
||||
model: "gpt-5.4",
|
||||
} satisfies ModelSelection;
|
||||
const DEFAULT_MODEL_SELECTION = createModelSelection(DEBUG_CODEX_INSTANCE_ID, "gpt-5.4");
|
||||
|
||||
const DEBUG_PROVIDER_SNAPSHOTS: ReadonlyArray<ServerProvider> = [
|
||||
{
|
||||
@@ -56,6 +61,20 @@ const DEBUG_PROVIDER_SNAPSHOTS: ReadonlyArray<ServerProvider> = [
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
models: [
|
||||
{
|
||||
slug: "gpt-5.5",
|
||||
name: "GPT-5.5",
|
||||
shortName: "5.5",
|
||||
isCustom: false,
|
||||
capabilities: null,
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.3-codex",
|
||||
name: "GPT-5.3 Codex",
|
||||
shortName: "5.3",
|
||||
isCustom: false,
|
||||
capabilities: null,
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
@@ -71,16 +90,16 @@ const DEBUG_PROVIDER_SNAPSHOTS: ReadonlyArray<ServerProvider> = [
|
||||
capabilities: null,
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.3-codex",
|
||||
name: "GPT-5.3 Codex",
|
||||
shortName: "5.3",
|
||||
slug: "gpt-5.3-codex-spark",
|
||||
name: "GPT-5.3 Codex Spark",
|
||||
shortName: "Spark",
|
||||
isCustom: false,
|
||||
capabilities: null,
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.3-codex-spark",
|
||||
name: "GPT-5.3 Codex Spark",
|
||||
shortName: "Spark",
|
||||
slug: "gpt-5.2",
|
||||
name: "GPT-5.2",
|
||||
shortName: "5.2",
|
||||
isCustom: false,
|
||||
capabilities: null,
|
||||
},
|
||||
@@ -133,14 +152,6 @@ const DEBUG_PROVIDER_SNAPSHOTS: ReadonlyArray<ServerProvider> = [
|
||||
},
|
||||
];
|
||||
|
||||
const DEBUG_PROVIDER_INSTANCE_ENTRIES = sortProviderInstanceEntries(
|
||||
deriveProviderInstanceEntries(DEBUG_PROVIDER_SNAPSHOTS),
|
||||
);
|
||||
|
||||
const DEBUG_MODEL_OPTIONS_BY_INSTANCE = new Map(
|
||||
DEBUG_PROVIDER_SNAPSHOTS.map((provider) => [provider.instanceId, provider.models] as const),
|
||||
);
|
||||
|
||||
type LogEntry =
|
||||
| {
|
||||
readonly type: "command";
|
||||
@@ -173,6 +184,9 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
}
|
||||
|
||||
function formatErrorMessage(error: unknown): string {
|
||||
if (isRecord(error) && typeof error.detail === "string" && error.detail.trim().length > 0) {
|
||||
return error.detail;
|
||||
}
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
return error.message;
|
||||
}
|
||||
@@ -256,6 +270,36 @@ function useNow(intervalMs = 10_000): number {
|
||||
return now;
|
||||
}
|
||||
|
||||
function selectDebugFallbackProviderInstance(
|
||||
entries: ReadonlyArray<ProviderInstanceEntry>,
|
||||
): ProviderInstanceEntry | undefined {
|
||||
return (
|
||||
entries.find((entry) => entry.enabled && entry.isAvailable && entry.status === "ready") ??
|
||||
entries.find((entry) => entry.enabled && entry.isAvailable) ??
|
||||
entries[0]
|
||||
);
|
||||
}
|
||||
|
||||
function resolveDebugModelSelection(
|
||||
current: ModelSelection,
|
||||
entries: ReadonlyArray<ProviderInstanceEntry>,
|
||||
modelOptionsByInstance: ReadonlyMap<ProviderInstanceId, ReadonlyArray<AppModelOption>>,
|
||||
): ModelSelection {
|
||||
const currentEntry = entries.find((entry) => entry.instanceId === current.instanceId);
|
||||
const entry = currentEntry ?? selectDebugFallbackProviderInstance(entries);
|
||||
if (!entry) return current;
|
||||
|
||||
const modelOptions = modelOptionsByInstance.get(entry.instanceId) ?? [];
|
||||
const hasCurrentModel =
|
||||
currentEntry !== undefined && modelOptions.some((option) => option.slug === current.model);
|
||||
if (currentEntry !== undefined && (modelOptions.length === 0 || hasCurrentModel)) {
|
||||
return current;
|
||||
}
|
||||
|
||||
const model = modelOptions[0]?.slug ?? current.model;
|
||||
return createModelSelection(entry.instanceId, model);
|
||||
}
|
||||
|
||||
const IS_MAC =
|
||||
typeof navigator !== "undefined" && /Mac|iPhone|iPad|iPod/i.test(navigator.userAgent);
|
||||
|
||||
@@ -448,6 +492,37 @@ function upsertVisibleTurnItem(
|
||||
);
|
||||
}
|
||||
|
||||
function rolledBackRunIds(projection: OrchestrationV2ThreadProjection): ReadonlySet<RunId> {
|
||||
return new Set(
|
||||
projection.runs.filter((run) => run.status === "rolled_back").map((run) => run.id),
|
||||
);
|
||||
}
|
||||
|
||||
function shouldShowLocalTurnItem(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
item: OrchestrationV2TurnItem,
|
||||
): boolean {
|
||||
return item.runId === null || !rolledBackRunIds(projection).has(item.runId);
|
||||
}
|
||||
|
||||
function activeVisibleTurnItems(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): OrchestrationV2ThreadProjection["visibleTurnItems"] {
|
||||
const rolledBack = rolledBackRunIds(projection);
|
||||
return projection.visibleTurnItems
|
||||
.filter(
|
||||
(row) =>
|
||||
row.visibility !== "local" || row.item.runId === null || !rolledBack.has(row.item.runId),
|
||||
)
|
||||
.map((row, position) => ({
|
||||
position,
|
||||
visibility: row.visibility,
|
||||
sourceThreadId: row.sourceThreadId,
|
||||
sourceItemId: row.sourceItemId,
|
||||
item: row.item,
|
||||
}));
|
||||
}
|
||||
|
||||
function applyStreamEventToProjection(
|
||||
projection: OrchestrationV2ThreadProjection | null,
|
||||
event: OrchestrationV2DomainEvent,
|
||||
@@ -465,11 +540,16 @@ function applyStreamEventToProjection(
|
||||
case "thread.created":
|
||||
return { ...base, thread: event.payload };
|
||||
case "run.created":
|
||||
case "run.updated":
|
||||
return {
|
||||
case "run.updated": {
|
||||
const nextProjection = {
|
||||
...base,
|
||||
runs: upsertProjectionEntity(base.runs, event.payload),
|
||||
};
|
||||
return {
|
||||
...nextProjection,
|
||||
visibleTurnItems: activeVisibleTurnItems(nextProjection),
|
||||
};
|
||||
}
|
||||
case "run-attempt.created":
|
||||
case "run-attempt.updated":
|
||||
return {
|
||||
@@ -511,12 +591,24 @@ function applyStreamEventToProjection(
|
||||
...base,
|
||||
plans: upsertProjectionEntity(base.plans, event.payload),
|
||||
};
|
||||
case "turn-item.updated":
|
||||
return {
|
||||
case "turn-item.updated": {
|
||||
const nextProjection = {
|
||||
...base,
|
||||
turnItems: upsertProjectionEntity(base.turnItems, event.payload),
|
||||
visibleTurnItems: upsertVisibleTurnItem(base, event.payload),
|
||||
};
|
||||
const withoutStaleItem = {
|
||||
...nextProjection,
|
||||
visibleTurnItems: activeVisibleTurnItems(nextProjection).filter(
|
||||
(row) => row.sourceItemId !== event.payload.id,
|
||||
),
|
||||
};
|
||||
return {
|
||||
...nextProjection,
|
||||
visibleTurnItems: shouldShowLocalTurnItem(nextProjection, event.payload)
|
||||
? upsertVisibleTurnItem(withoutStaleItem, event.payload)
|
||||
: withoutStaleItem.visibleTurnItems,
|
||||
};
|
||||
}
|
||||
case "checkpoint-scope.created":
|
||||
return {
|
||||
...base,
|
||||
@@ -1524,6 +1616,37 @@ function OrchestrationV2DebugRoute() {
|
||||
const unsubscribeRef = useRef<(() => void) | null>(null);
|
||||
const shellUnsubscribeRef = useRef<(() => void) | null>(null);
|
||||
|
||||
const serverProviders = useServerProviders();
|
||||
const settings = useSettings();
|
||||
const keybindings = useServerKeybindings();
|
||||
const providerSnapshots = serverProviders.length > 0 ? serverProviders : DEBUG_PROVIDER_SNAPSHOTS;
|
||||
const providerInstanceEntries = useMemo<ReadonlyArray<ProviderInstanceEntry>>(
|
||||
() => sortProviderInstanceEntries(deriveProviderInstanceEntries(providerSnapshots)),
|
||||
[providerSnapshots],
|
||||
);
|
||||
const modelOptionsByInstance = useMemo<
|
||||
ReadonlyMap<ProviderInstanceId, ReadonlyArray<AppModelOption>>
|
||||
>(() => {
|
||||
const out = new Map<ProviderInstanceId, ReadonlyArray<AppModelOption>>();
|
||||
for (const entry of providerInstanceEntries) {
|
||||
out.set(entry.instanceId, getAppModelOptionsForInstance(settings, entry));
|
||||
}
|
||||
return out;
|
||||
}, [providerInstanceEntries, settings]);
|
||||
|
||||
useEffect(() => {
|
||||
setModelSelection((current) => {
|
||||
const next = resolveDebugModelSelection(
|
||||
current,
|
||||
providerInstanceEntries,
|
||||
modelOptionsByInstance,
|
||||
);
|
||||
return current.instanceId === next.instanceId && current.model === next.model
|
||||
? current
|
||||
: next;
|
||||
});
|
||||
}, [modelOptionsByInstance, providerInstanceEntries]);
|
||||
|
||||
const hiddenPanels = useMemo(
|
||||
() => ALL_PANEL_KEYS.filter((key) => !visiblePanels.includes(key)),
|
||||
[visiblePanels],
|
||||
@@ -1679,7 +1802,10 @@ function OrchestrationV2DebugRoute() {
|
||||
async (nextThreadId: ThreadId) => {
|
||||
setThreadId(nextThreadId);
|
||||
subscribeToThread(nextThreadId);
|
||||
await refreshProjection(nextThreadId);
|
||||
const nextProjection = await refreshProjection(nextThreadId);
|
||||
if (nextProjection !== null) {
|
||||
setModelSelection(nextProjection.thread.modelSelection);
|
||||
}
|
||||
},
|
||||
[refreshProjection, subscribeToThread],
|
||||
);
|
||||
@@ -1764,7 +1890,7 @@ function OrchestrationV2DebugRoute() {
|
||||
} catch (error) {
|
||||
appendLog({
|
||||
type: "error",
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
message: formatErrorMessage(error),
|
||||
});
|
||||
} finally {
|
||||
setIsBusy(false);
|
||||
@@ -1803,7 +1929,7 @@ function OrchestrationV2DebugRoute() {
|
||||
} catch (error) {
|
||||
appendLog({
|
||||
type: "error",
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
message: formatErrorMessage(error),
|
||||
});
|
||||
} finally {
|
||||
setIsBusy(false);
|
||||
@@ -1855,7 +1981,7 @@ function OrchestrationV2DebugRoute() {
|
||||
} catch (error) {
|
||||
appendLog({
|
||||
type: "error",
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
message: formatErrorMessage(error),
|
||||
});
|
||||
} finally {
|
||||
setIsBusy(false);
|
||||
@@ -1944,7 +2070,7 @@ function OrchestrationV2DebugRoute() {
|
||||
} catch (error) {
|
||||
appendLog({
|
||||
type: "error",
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
message: formatErrorMessage(error),
|
||||
});
|
||||
} finally {
|
||||
setIsBusy(false);
|
||||
@@ -2040,14 +2166,15 @@ function OrchestrationV2DebugRoute() {
|
||||
activeInstanceId={modelSelection.instanceId}
|
||||
model={modelSelection.model}
|
||||
lockedProvider={null}
|
||||
instanceEntries={DEBUG_PROVIDER_INSTANCE_ENTRIES}
|
||||
modelOptionsByInstance={DEBUG_MODEL_OPTIONS_BY_INSTANCE}
|
||||
instanceEntries={providerInstanceEntries}
|
||||
keybindings={keybindings}
|
||||
modelOptionsByInstance={modelOptionsByInstance}
|
||||
compact
|
||||
disabled={isBusy}
|
||||
disabled={isBusy || providerInstanceEntries.length === 0}
|
||||
triggerVariant="outline"
|
||||
triggerClassName="h-9 max-w-64 bg-background"
|
||||
onInstanceModelChange={(instanceId, model) => {
|
||||
setModelSelection({ instanceId, model });
|
||||
setModelSelection(createModelSelection(instanceId, model));
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
|
||||
@@ -96,6 +96,7 @@ ProviderThread
|
||||
providerSessionId?
|
||||
appThreadId?
|
||||
nativeThreadRef?
|
||||
nativeConversationHeadRef?
|
||||
coveredRunRange?
|
||||
contextHandoffIds[]
|
||||
forkSource?
|
||||
@@ -349,6 +350,7 @@ type ProviderThread = {
|
||||
appThreadId: ThreadId | null;
|
||||
ownerNodeId: NodeId | null;
|
||||
nativeThreadRef: string | null;
|
||||
nativeConversationHeadRef: ProviderRef | null;
|
||||
status: "not_loaded" | "idle" | "active" | "archived" | "closed" | "error";
|
||||
firstRunOrdinal: number | null;
|
||||
lastRunOrdinal: number | null;
|
||||
|
||||
@@ -277,7 +277,7 @@ Provider resume flow:
|
||||
|
||||
```text
|
||||
resolve activeProviderThreadId
|
||||
resolve nativeThreadRef / resume cursor
|
||||
resolve nativeThreadRef / nativeConversationHeadRef resume cursor
|
||||
start ProviderSession
|
||||
provider resume
|
||||
bind new ProviderSessionId to ProviderThread
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DateTime, Schema } from "effect";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
CheckpointId,
|
||||
@@ -26,7 +27,7 @@ import {
|
||||
OrchestrationV2TurnItem,
|
||||
} from "./orchestrationV2.ts";
|
||||
|
||||
const now = DateTime.fromDateUnsafe(new Date("2026-04-20T00:00:00.000Z"));
|
||||
const now = DateTime.makeUnsafe("2026-04-20T00:00:00.000Z");
|
||||
|
||||
describe("orchestration V2 contracts", () => {
|
||||
it("decodes nested checkpoint scopes without making child scopes advance app run count", () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Schema } from "effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
CheckpointId,
|
||||
@@ -426,6 +426,7 @@ export const OrchestrationV2ProviderThread = Schema.Struct({
|
||||
appThreadId: Schema.NullOr(ThreadId),
|
||||
ownerNodeId: Schema.NullOr(NodeId),
|
||||
nativeThreadRef: Schema.NullOr(OrchestrationV2ProviderRef),
|
||||
nativeConversationHeadRef: Schema.NullOr(OrchestrationV2ProviderRef),
|
||||
status: Schema.Literals(["not_loaded", "idle", "active", "archived", "closed", "error"]),
|
||||
firstRunOrdinal: Schema.NullOr(PositiveInt),
|
||||
lastRunOrdinal: Schema.NullOr(PositiveInt),
|
||||
@@ -1488,6 +1489,7 @@ export class OrchestrationV2DispatchCommandError extends Schema.TaggedErrorClass
|
||||
commandId: CommandId,
|
||||
commandType: Schema.String,
|
||||
message: Schema.String,
|
||||
detail: Schema.optional(Schema.String),
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
|
||||
@@ -42,6 +42,7 @@ export const CodexAppServerReplayTranscript = Schema.Struct({
|
||||
entries: Schema.Array(CodexAppServerReplayEntry),
|
||||
});
|
||||
export type CodexAppServerReplayTranscript = typeof CodexAppServerReplayTranscript.Type;
|
||||
const decodeOutboundJsonFrame = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
|
||||
|
||||
export class CodexAppServerReplayJsonParseError extends Schema.TaggedErrorClass<CodexAppServerReplayJsonParseError>()(
|
||||
"CodexAppServerReplayJsonParseError",
|
||||
@@ -363,7 +364,7 @@ const makeReplayClientWithState = Effect.fn(
|
||||
return Effect.void;
|
||||
}
|
||||
return Effect.try({
|
||||
try: () => JSON.parse(trimmed),
|
||||
try: () => decodeOutboundJsonFrame(trimmed),
|
||||
catch: (cause) =>
|
||||
new CodexAppServerReplayJsonParseError({
|
||||
scenario: transcript.scenario,
|
||||
|
||||
Reference in new issue
Block a user