Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
645e6dbe3c | ||
|
|
e448221739 | ||
|
|
57ca254abe |
No files matched your search
@@ -43,6 +43,36 @@ function createSendTurnHarness() {
|
||||
return { manager, context, requireSession, sendRequest, updateSession };
|
||||
}
|
||||
|
||||
function createThreadControlHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: "thread_1",
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
.spyOn(
|
||||
manager as unknown as { requireSession: (sessionId: string) => unknown },
|
||||
"requireSession",
|
||||
)
|
||||
.mockReturnValue(context);
|
||||
const sendRequest = vi.spyOn(
|
||||
manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
|
||||
"sendRequest",
|
||||
);
|
||||
const updateSession = vi
|
||||
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
|
||||
.mockImplementation(() => {});
|
||||
|
||||
return { manager, context, requireSession, sendRequest, updateSession };
|
||||
}
|
||||
|
||||
describe("classifyCodexStderrLine", () => {
|
||||
it("ignores empty lines", () => {
|
||||
expect(classifyCodexStderrLine(" ")).toBeNull();
|
||||
@@ -198,3 +228,62 @@ describe("sendTurn", () => {
|
||||
).rejects.toThrow("Turn input must include text or attachments.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("thread checkpoint control", () => {
|
||||
it("reads thread turns from thread/read", async () => {
|
||||
const { manager, context, requireSession, sendRequest } = createThreadControlHarness();
|
||||
sendRequest.mockResolvedValue({
|
||||
thread: {
|
||||
id: "thread_1",
|
||||
turns: [
|
||||
{
|
||||
id: "turn_1",
|
||||
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const result = await manager.readThread("sess_1");
|
||||
|
||||
expect(requireSession).toHaveBeenCalledWith("sess_1");
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
|
||||
threadId: "thread_1",
|
||||
includeTurns: true,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
threadId: "thread_1",
|
||||
turns: [
|
||||
{
|
||||
id: "turn_1",
|
||||
items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("rolls back turns via thread/rollback and resets session running state", async () => {
|
||||
const { manager, context, sendRequest, updateSession } = createThreadControlHarness();
|
||||
sendRequest.mockResolvedValue({
|
||||
thread: {
|
||||
id: "thread_1",
|
||||
turns: [],
|
||||
},
|
||||
});
|
||||
|
||||
const result = await manager.rollbackThread("sess_1", 2);
|
||||
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/rollback", {
|
||||
threadId: "thread_1",
|
||||
numTurns: 2,
|
||||
});
|
||||
expect(updateSession).toHaveBeenCalledWith(context, {
|
||||
status: "ready",
|
||||
activeTurnId: undefined,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
threadId: "thread_1",
|
||||
turns: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -65,6 +65,16 @@ interface JsonRpcNotification {
|
||||
params?: unknown;
|
||||
}
|
||||
|
||||
export interface CodexThreadTurnSnapshot {
|
||||
id: string;
|
||||
items: unknown[];
|
||||
}
|
||||
|
||||
export interface CodexThreadSnapshot {
|
||||
threadId: string;
|
||||
turns: CodexThreadTurnSnapshot[];
|
||||
}
|
||||
|
||||
const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
|
||||
const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
|
||||
const CODEX_STDERR_LOG_REGEX =
|
||||
@@ -331,6 +341,41 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
}
|
||||
|
||||
async readThread(sessionId: string): Promise<CodexThreadSnapshot> {
|
||||
const context = this.requireSession(sessionId);
|
||||
const threadId = context.session.threadId;
|
||||
if (!threadId) {
|
||||
throw new Error("Session is missing a thread id.");
|
||||
}
|
||||
|
||||
const response = await this.sendRequest(context, "thread/read", {
|
||||
threadId,
|
||||
includeTurns: true,
|
||||
});
|
||||
return this.parseThreadSnapshot("thread/read", response);
|
||||
}
|
||||
|
||||
async rollbackThread(sessionId: string, numTurns: number): Promise<CodexThreadSnapshot> {
|
||||
const context = this.requireSession(sessionId);
|
||||
const threadId = context.session.threadId;
|
||||
if (!threadId) {
|
||||
throw new Error("Session is missing a thread id.");
|
||||
}
|
||||
if (!Number.isInteger(numTurns) || numTurns < 1) {
|
||||
throw new Error("numTurns must be an integer >= 1.");
|
||||
}
|
||||
|
||||
const response = await this.sendRequest(context, "thread/rollback", {
|
||||
threadId,
|
||||
numTurns,
|
||||
});
|
||||
this.updateSession(context, {
|
||||
status: "ready",
|
||||
activeTurnId: undefined,
|
||||
});
|
||||
return this.parseThreadSnapshot("thread/rollback", response);
|
||||
}
|
||||
|
||||
async respondToRequest(
|
||||
sessionId: string,
|
||||
requestId: string,
|
||||
@@ -742,6 +787,31 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private parseThreadSnapshot(method: string, response: unknown): CodexThreadSnapshot {
|
||||
const responseRecord = this.readObject(response);
|
||||
const thread = this.readObject(responseRecord, "thread");
|
||||
const threadId = this.readString(thread, "id") ?? this.readString(responseRecord, "threadId");
|
||||
if (!threadId) {
|
||||
throw new Error(`${method} response did not include a thread id.`);
|
||||
}
|
||||
|
||||
const turnsRaw = this.readArray(thread, "turns") ?? this.readArray(responseRecord, "turns") ?? [];
|
||||
const turns = turnsRaw.map((turnValue, index) => {
|
||||
const turn = this.readObject(turnValue);
|
||||
const turnId = this.readString(turn, "id") ?? `${threadId}:turn:${index + 1}`;
|
||||
const items = this.readArray(turn, "items") ?? [];
|
||||
return {
|
||||
id: turnId,
|
||||
items,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
threadId,
|
||||
turns,
|
||||
};
|
||||
}
|
||||
|
||||
private isServerRequest(value: unknown): value is JsonRpcRequest {
|
||||
if (!value || typeof value !== "object") {
|
||||
return false;
|
||||
@@ -823,6 +893,16 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return target as Record<string, unknown>;
|
||||
}
|
||||
|
||||
private readArray(value: unknown, key?: string): unknown[] | undefined {
|
||||
const target =
|
||||
key === undefined
|
||||
? value
|
||||
: value && typeof value === "object"
|
||||
? (value as Record<string, unknown>)[key]
|
||||
: undefined;
|
||||
return Array.isArray(target) ? target : undefined;
|
||||
}
|
||||
|
||||
private readString(value: unknown, key: string): string | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { checkpointRefForThreadTurn, FilesystemCheckpointStore } from "./filesystemCheckpointStore";
|
||||
import { runProcess } from "./processRunner";
|
||||
|
||||
async function runGit(cwd: string, args: readonly string[]): Promise<string> {
|
||||
const result = await runProcess("git", args, {
|
||||
cwd,
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
if (result.code !== 0) {
|
||||
throw new Error(result.stderr.trim() || `git ${args.join(" ")} failed`);
|
||||
}
|
||||
return result.stdout.trim();
|
||||
}
|
||||
|
||||
function exists(filePath: string): boolean {
|
||||
return fs.existsSync(filePath);
|
||||
}
|
||||
|
||||
async function createRepo(): Promise<string> {
|
||||
const cwd = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoints-test-"));
|
||||
await runGit(cwd, ["init", "--initial-branch=main"]);
|
||||
await runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||
await runGit(cwd, ["config", "user.name", "Test User"]);
|
||||
await writeFile(path.join(cwd, "README.md"), "v1\n");
|
||||
await writeFile(path.join(cwd, "tracked.txt"), "tracked-v1\n");
|
||||
await runGit(cwd, ["add", "."]);
|
||||
await runGit(cwd, ["commit", "-m", "Initial"]);
|
||||
return cwd;
|
||||
}
|
||||
|
||||
describe("FilesystemCheckpointStore", () => {
|
||||
it("captures refs without mutating branch history and restores workspace state", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const threadId = "thr_1";
|
||||
|
||||
try {
|
||||
const headBefore = await runGit(cwd, ["rev-parse", "HEAD"]);
|
||||
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
|
||||
const rootRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const rootCommit = await runGit(cwd, ["rev-parse", "--verify", `${rootRef}^{commit}`]);
|
||||
expect(rootCommit.length).toBeGreaterThan(0);
|
||||
expect(await runGit(cwd, ["rev-parse", "HEAD"])).toBe(headBefore);
|
||||
|
||||
await writeFile(path.join(cwd, "README.md"), "v2\n");
|
||||
await rm(path.join(cwd, "tracked.txt"));
|
||||
await writeFile(path.join(cwd, "notes.md"), "notes\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
|
||||
await writeFile(path.join(cwd, "README.md"), "v3\n");
|
||||
await writeFile(path.join(cwd, "scratch.txt"), "scratch\n");
|
||||
await writeFile(path.join(cwd, "tracked.txt"), "tracked-new\n");
|
||||
|
||||
const restoredRoot = await store.restoreCheckpoint({ cwd, threadId, turnCount: 0 });
|
||||
expect(restoredRoot).toBe(true);
|
||||
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("v1\n");
|
||||
expect(await readFile(path.join(cwd, "tracked.txt"), "utf8")).toBe("tracked-v1\n");
|
||||
expect(exists(path.join(cwd, "notes.md"))).toBe(false);
|
||||
expect(exists(path.join(cwd, "scratch.txt"))).toBe(false);
|
||||
|
||||
const restoredTurn1 = await store.restoreCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
expect(restoredTurn1).toBe(true);
|
||||
expect(await readFile(path.join(cwd, "README.md"), "utf8")).toBe("v2\n");
|
||||
expect(exists(path.join(cwd, "tracked.txt"))).toBe(false);
|
||||
expect(await readFile(path.join(cwd, "notes.md"), "utf8")).toBe("notes\n");
|
||||
expect(exists(path.join(cwd, "scratch.txt"))).toBe(false);
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("returns false when restoring a missing checkpoint", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
|
||||
try {
|
||||
const restored = await store.restoreCheckpoint({
|
||||
cwd,
|
||||
threadId: "thr_2",
|
||||
turnCount: 999,
|
||||
});
|
||||
expect(restored).toBe(false);
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("prunes refs newer than the retained turn", async () => {
|
||||
const cwd = await createRepo();
|
||||
const store = new FilesystemCheckpointStore();
|
||||
const threadId = "thr_3";
|
||||
|
||||
try {
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 0 });
|
||||
await writeFile(path.join(cwd, "README.md"), "turn1\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 1 });
|
||||
await writeFile(path.join(cwd, "README.md"), "turn2\n");
|
||||
await store.captureCheckpoint({ cwd, threadId, turnCount: 2 });
|
||||
|
||||
await store.pruneAfterTurn({
|
||||
cwd,
|
||||
threadId,
|
||||
maxTurnCount: 1,
|
||||
});
|
||||
|
||||
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 0 })).toBe(true);
|
||||
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 1 })).toBe(true);
|
||||
expect(await store.hasCheckpoint({ cwd, threadId, turnCount: 2 })).toBe(false);
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("detects non-repo folders", async () => {
|
||||
const cwd = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoints-nonrepo-"));
|
||||
const store = new FilesystemCheckpointStore();
|
||||
|
||||
try {
|
||||
expect(await store.isGitRepository(cwd)).toBe(false);
|
||||
} finally {
|
||||
await rm(cwd, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,202 @@
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { runProcess } from "./processRunner";
|
||||
|
||||
const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
||||
|
||||
function quoteGitCommand(args: readonly string[]): string {
|
||||
return `git ${args.join(" ")}`;
|
||||
}
|
||||
|
||||
function checkpointRefThreadSegment(threadId: string): string {
|
||||
return Buffer.from(threadId, "utf8").toString("base64url");
|
||||
}
|
||||
|
||||
export function checkpointRefForThreadTurn(threadId: string, turnCount: number): string {
|
||||
if (!Number.isInteger(turnCount) || turnCount < 0) {
|
||||
throw new Error(`Invalid checkpoint turn count: ${turnCount}`);
|
||||
}
|
||||
return `${CHECKPOINT_REFS_PREFIX}/${checkpointRefThreadSegment(threadId)}/turn/${turnCount}`;
|
||||
}
|
||||
|
||||
interface GitOptions {
|
||||
env?: NodeJS.ProcessEnv;
|
||||
stdin?: string;
|
||||
allowNonZeroExit?: boolean;
|
||||
}
|
||||
|
||||
export class FilesystemCheckpointStore {
|
||||
async isGitRepository(cwd: string): Promise<boolean> {
|
||||
const result = await this.runGit(cwd, ["rev-parse", "--is-inside-work-tree"], {
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
return result.code === 0 && result.stdout.trim() === "true";
|
||||
}
|
||||
|
||||
async captureCheckpoint(input: { cwd: string; threadId: string; turnCount: number }): Promise<void> {
|
||||
const { cwd, threadId, turnCount } = input;
|
||||
const ref = checkpointRefForThreadTurn(threadId, turnCount);
|
||||
|
||||
const tempDir = await mkdtemp(path.join(os.tmpdir(), "t3-fs-checkpoint-"));
|
||||
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
|
||||
const commitEnv: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
GIT_INDEX_FILE: tempIndexPath,
|
||||
GIT_AUTHOR_NAME: "T3 Code",
|
||||
GIT_AUTHOR_EMAIL: "[email protected]",
|
||||
GIT_COMMITTER_NAME: "T3 Code",
|
||||
GIT_COMMITTER_EMAIL: "[email protected]",
|
||||
};
|
||||
|
||||
try {
|
||||
await writeFile(tempIndexPath, "");
|
||||
|
||||
const hasHead = await this.hasHeadCommit(cwd);
|
||||
if (hasHead) {
|
||||
await this.runGit(cwd, ["read-tree", "HEAD"], { env: commitEnv });
|
||||
}
|
||||
|
||||
await this.runGit(cwd, ["add", "-A", "--", "."], { env: commitEnv });
|
||||
const writeTreeResult = await this.runGit(cwd, ["write-tree"], { env: commitEnv });
|
||||
const treeOid = writeTreeResult.stdout.trim();
|
||||
if (!treeOid) {
|
||||
throw new Error("git write-tree returned an empty tree oid.");
|
||||
}
|
||||
|
||||
const message = `t3 checkpoint thread=${threadId} turn=${turnCount}`;
|
||||
const commitTreeResult = await this.runGit(cwd, ["commit-tree", treeOid], {
|
||||
env: commitEnv,
|
||||
stdin: `${message}\n`,
|
||||
});
|
||||
const commitOid = commitTreeResult.stdout.trim();
|
||||
if (!commitOid) {
|
||||
throw new Error("git commit-tree returned an empty commit oid.");
|
||||
}
|
||||
|
||||
await this.runGit(cwd, ["update-ref", ref, commitOid]);
|
||||
} finally {
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async hasCheckpoint(input: { cwd: string; threadId: string; turnCount: number }): Promise<boolean> {
|
||||
const { cwd, threadId, turnCount } = input;
|
||||
const ref = checkpointRefForThreadTurn(threadId, turnCount);
|
||||
const commit = await this.resolveCheckpointCommit(cwd, ref);
|
||||
return commit !== null;
|
||||
}
|
||||
|
||||
async restoreCheckpoint(input: { cwd: string; threadId: string; turnCount: number }): Promise<boolean> {
|
||||
const { cwd, threadId, turnCount } = input;
|
||||
const ref = checkpointRefForThreadTurn(threadId, turnCount);
|
||||
const commitOid = await this.resolveCheckpointCommit(cwd, ref);
|
||||
if (!commitOid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
await this.runGit(cwd, ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."]);
|
||||
await this.runGit(cwd, ["clean", "-fd", "--", "."]);
|
||||
await this.runGit(cwd, ["reset", "--quiet", "--", "."], { allowNonZeroExit: true });
|
||||
return true;
|
||||
}
|
||||
|
||||
async pruneAfterTurn(input: { cwd: string; threadId: string; maxTurnCount: number }): Promise<void> {
|
||||
const { cwd, threadId, maxTurnCount } = input;
|
||||
if (!Number.isInteger(maxTurnCount) || maxTurnCount < 0) {
|
||||
throw new Error(`Invalid max turn count: ${maxTurnCount}`);
|
||||
}
|
||||
|
||||
const threadRefPrefix = `${CHECKPOINT_REFS_PREFIX}/${checkpointRefThreadSegment(threadId)}/turn/`;
|
||||
const result = await this.runGit(cwd, ["for-each-ref", "--format=%(refname)", threadRefPrefix], {
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
if (result.code !== 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const refsToDelete = result.stdout
|
||||
.split(/\r?\n/g)
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0)
|
||||
.filter((refName) => {
|
||||
const turn = this.readRefTurnCount(refName);
|
||||
return turn !== null && turn > maxTurnCount;
|
||||
});
|
||||
|
||||
await Promise.all(
|
||||
refsToDelete.map((refName) =>
|
||||
this.runGit(cwd, ["update-ref", "-d", refName], { allowNonZeroExit: true }),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private async hasHeadCommit(cwd: string): Promise<boolean> {
|
||||
const result = await this.runGit(cwd, ["rev-parse", "--verify", "HEAD"], {
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
return result.code === 0;
|
||||
}
|
||||
|
||||
private async resolveCheckpointCommit(cwd: string, ref: string): Promise<string | null> {
|
||||
const result = await this.runGit(cwd, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], {
|
||||
allowNonZeroExit: true,
|
||||
});
|
||||
if (result.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
const commit = result.stdout.trim();
|
||||
return commit.length > 0 ? commit : null;
|
||||
}
|
||||
|
||||
private readRefTurnCount(ref: string): number | null {
|
||||
const segments = ref.split("/");
|
||||
const rawTurn = segments.at(-1);
|
||||
if (!rawTurn) {
|
||||
return null;
|
||||
}
|
||||
const turn = Number.parseInt(rawTurn, 10);
|
||||
return Number.isInteger(turn) && turn >= 0 ? turn : null;
|
||||
}
|
||||
|
||||
private async runGit(
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
options: GitOptions = {},
|
||||
): Promise<Awaited<ReturnType<typeof runProcess>>> {
|
||||
let result: Awaited<ReturnType<typeof runProcess>>;
|
||||
try {
|
||||
result = await runProcess("git", args, {
|
||||
cwd,
|
||||
env: options.env,
|
||||
stdin: options.stdin,
|
||||
timeoutMs: DEFAULT_TIMEOUT_MS,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: DEFAULT_MAX_OUTPUT_BYTES,
|
||||
outputMode: "truncate",
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`Failed to run ${quoteGitCommand(args)}: ${message}`, { cause: error });
|
||||
}
|
||||
|
||||
if (result.timedOut) {
|
||||
throw new Error(`${quoteGitCommand(args)} timed out.`);
|
||||
}
|
||||
|
||||
if (!options.allowNonZeroExit && result.code !== 0) {
|
||||
const stderr = result.stderr.trim();
|
||||
throw new Error(
|
||||
stderr.length > 0
|
||||
? `${quoteGitCommand(args)} failed: ${stderr}`
|
||||
: `${quoteGitCommand(args)} failed with code ${result.code ?? "null"}.`,
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ProviderManager } from "./providerManager";
|
||||
|
||||
@@ -59,4 +59,255 @@ describe("ProviderManager", () => {
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("rejects checkpoint operations for unknown sessions", async () => {
|
||||
const manager = new ProviderManager();
|
||||
|
||||
await expect(
|
||||
manager.listCheckpoints({
|
||||
sessionId: "missing-session",
|
||||
}),
|
||||
).rejects.toThrow("Unknown provider session: missing-session");
|
||||
|
||||
await expect(
|
||||
manager.revertToCheckpoint({
|
||||
sessionId: "missing-session",
|
||||
turnCount: 0,
|
||||
}),
|
||||
).rejects.toThrow("Unknown provider session: missing-session");
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("derives checkpoints from thread turns", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const codex = (
|
||||
manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
).codex;
|
||||
|
||||
codex.hasSession = () => true;
|
||||
codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [
|
||||
{
|
||||
id: "turn_1",
|
||||
items: [
|
||||
{
|
||||
type: "userMessage",
|
||||
content: [{ type: "text", text: "Refactor the logger" }],
|
||||
},
|
||||
{
|
||||
type: "agentMessage",
|
||||
text: "I refactored it.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await manager.listCheckpoints({
|
||||
sessionId: "sess_1",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
threadId: "thr_1",
|
||||
checkpoints: [
|
||||
{
|
||||
id: "root",
|
||||
turnCount: 0,
|
||||
messageCount: 0,
|
||||
label: "Start of conversation",
|
||||
isCurrent: false,
|
||||
},
|
||||
{
|
||||
id: "turn_1",
|
||||
turnCount: 1,
|
||||
messageCount: 2,
|
||||
label: "Turn 1",
|
||||
preview: "Refactor the logger",
|
||||
isCurrent: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("rolls back from a selected checkpoint turn count", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const codex = (
|
||||
manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
rollbackThread: (sessionId: string, numTurns: number) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
).codex;
|
||||
|
||||
const rollbackCalls: Array<{ sessionId: string; numTurns: number }> = [];
|
||||
codex.hasSession = () => true;
|
||||
codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [
|
||||
{ id: "turn_1", items: [] },
|
||||
{ id: "turn_2", items: [] },
|
||||
{ id: "turn_3", items: [] },
|
||||
],
|
||||
});
|
||||
codex.rollbackThread = async (sessionId, numTurns) => {
|
||||
rollbackCalls.push({ sessionId, numTurns });
|
||||
return {
|
||||
threadId: "thr_1",
|
||||
turns: [{ id: "turn_1", items: [] }],
|
||||
};
|
||||
};
|
||||
|
||||
const result = await manager.revertToCheckpoint({
|
||||
sessionId: "sess_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
|
||||
expect(rollbackCalls).toEqual([{ sessionId: "sess_1", numTurns: 2 }]);
|
||||
expect(result.threadId).toBe("thr_1");
|
||||
expect(result.turnCount).toBe(1);
|
||||
expect(result.messageCount).toBe(0);
|
||||
expect(result.rolledBackTurns).toBe(2);
|
||||
expect(result.checkpoints).toHaveLength(2);
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("restores filesystem checkpoint when reverting and checkpointing is enabled", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
rollbackThread: (sessionId: string, numTurns: number) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
hasCheckpoint: (input: { cwd: string; threadId: string; turnCount: number }) => Promise<boolean>;
|
||||
restoreCheckpoint: (input: {
|
||||
cwd: string;
|
||||
threadId: string;
|
||||
turnCount: number;
|
||||
}) => Promise<boolean>;
|
||||
pruneAfterTurn: (input: { cwd: string; threadId: string; maxTurnCount: number }) => Promise<void>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
internals.codex.hasSession = () => true;
|
||||
internals.codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [
|
||||
{ id: "turn_1", items: [] },
|
||||
{ id: "turn_2", items: [] },
|
||||
],
|
||||
});
|
||||
internals.codex.rollbackThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [{ id: "turn_1", items: [] }],
|
||||
});
|
||||
const hasCheckpoint = vi.fn(async () => true);
|
||||
const restoreCheckpoint = vi.fn(async () => true);
|
||||
const pruneAfterTurn = vi.fn(async () => undefined);
|
||||
internals.filesystemCheckpointStore.hasCheckpoint = hasCheckpoint;
|
||||
internals.filesystemCheckpointStore.restoreCheckpoint = restoreCheckpoint;
|
||||
internals.filesystemCheckpointStore.pruneAfterTurn = pruneAfterTurn;
|
||||
internals.sessionCheckpointCwds.set("sess_1", "/repo");
|
||||
|
||||
const result = await manager.revertToCheckpoint({
|
||||
sessionId: "sess_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
|
||||
expect(result.turnCount).toBe(1);
|
||||
expect(hasCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
expect(restoreCheckpoint).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
turnCount: 1,
|
||||
});
|
||||
expect(pruneAfterTurn).toHaveBeenCalledWith({
|
||||
cwd: "/repo",
|
||||
threadId: "thr_1",
|
||||
maxTurnCount: 1,
|
||||
});
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
|
||||
it("fails before rollback when filesystem checkpoint is missing", async () => {
|
||||
const manager = new ProviderManager();
|
||||
const internals = manager as unknown as {
|
||||
codex: {
|
||||
hasSession: (sessionId: string) => boolean;
|
||||
readThread: (sessionId: string) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
rollbackThread: (sessionId: string, numTurns: number) => Promise<{
|
||||
threadId: string;
|
||||
turns: Array<{ id: string; items: unknown[] }>;
|
||||
}>;
|
||||
};
|
||||
filesystemCheckpointStore: {
|
||||
hasCheckpoint: (input: { cwd: string; threadId: string; turnCount: number }) => Promise<boolean>;
|
||||
};
|
||||
sessionCheckpointCwds: Map<string, string>;
|
||||
};
|
||||
|
||||
const rollbackSpy = vi.fn(async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [{ id: "turn_1", items: [] }],
|
||||
}));
|
||||
|
||||
internals.codex.hasSession = () => true;
|
||||
internals.codex.readThread = async () => ({
|
||||
threadId: "thr_1",
|
||||
turns: [
|
||||
{ id: "turn_1", items: [] },
|
||||
{ id: "turn_2", items: [] },
|
||||
],
|
||||
});
|
||||
internals.codex.rollbackThread = rollbackSpy;
|
||||
internals.filesystemCheckpointStore.hasCheckpoint = async () => false;
|
||||
internals.sessionCheckpointCwds.set("sess_1", "/repo");
|
||||
|
||||
await expect(
|
||||
manager.revertToCheckpoint({
|
||||
sessionId: "sess_1",
|
||||
turnCount: 1,
|
||||
}),
|
||||
).rejects.toThrow("Filesystem checkpoint is unavailable for turn 1 in thread thr_1.");
|
||||
expect(rollbackSpy).not.toHaveBeenCalled();
|
||||
|
||||
manager.dispose();
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,16 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import {
|
||||
type ProviderCheckpoint,
|
||||
type ProviderEvent,
|
||||
type ProviderInterruptTurnInput,
|
||||
type ProviderListCheckpointsInput,
|
||||
type ProviderListCheckpointsResult,
|
||||
type ProviderRevertToCheckpointInput,
|
||||
type ProviderRevertToCheckpointResult,
|
||||
type ProviderRespondToRequestInput,
|
||||
type ProviderSendTurnInput,
|
||||
type ProviderSession,
|
||||
@@ -12,23 +18,154 @@ import {
|
||||
type ProviderStopSessionInput,
|
||||
type ProviderTurnStartResult,
|
||||
providerInterruptTurnInputSchema,
|
||||
providerListCheckpointsInputSchema,
|
||||
providerRevertToCheckpointInputSchema,
|
||||
providerRespondToRequestInputSchema,
|
||||
providerSendTurnInputSchema,
|
||||
providerSessionStartInputSchema,
|
||||
providerStopSessionInputSchema,
|
||||
} from "@t3tools/contracts";
|
||||
import type { CodexThreadTurnSnapshot } from "./codexAppServerManager";
|
||||
import { CodexAppServerManager } from "./codexAppServerManager";
|
||||
import { FilesystemCheckpointStore } from "./filesystemCheckpointStore";
|
||||
|
||||
export interface ProviderManagerEvents {
|
||||
event: [event: ProviderEvent];
|
||||
}
|
||||
|
||||
function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function asArray(value: unknown): unknown[] {
|
||||
return Array.isArray(value) ? value : [];
|
||||
}
|
||||
|
||||
function trimToPreview(value: string): string {
|
||||
const normalized = value.replace(/\s+/g, " ").trim();
|
||||
if (normalized.length <= 120) {
|
||||
return normalized;
|
||||
}
|
||||
return `${normalized.slice(0, 117)}...`;
|
||||
}
|
||||
|
||||
function summarizeUserMessageContent(content: unknown[]): string | undefined {
|
||||
const segments: string[] = [];
|
||||
|
||||
for (const part of content) {
|
||||
const record = asObject(part);
|
||||
const type = asString(record?.type);
|
||||
if (!type) continue;
|
||||
|
||||
if (type === "text") {
|
||||
const text = asString(record?.text);
|
||||
if (text && text.trim().length > 0) {
|
||||
segments.push(text.trim());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (type === "image") {
|
||||
segments.push("[Image attachment]");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (type === "localImage") {
|
||||
segments.push("[Local image attachment]");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (segments.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return trimToPreview(segments.join(" "));
|
||||
}
|
||||
|
||||
function summarizeTurn(turn: CodexThreadTurnSnapshot): {
|
||||
messageCountDelta: number;
|
||||
preview?: string;
|
||||
} {
|
||||
let messageCountDelta = 0;
|
||||
let preview: string | undefined;
|
||||
|
||||
for (const item of turn.items) {
|
||||
const record = asObject(item);
|
||||
const type = asString(record?.type);
|
||||
if (!type) continue;
|
||||
|
||||
if (type === "userMessage") {
|
||||
messageCountDelta += 1;
|
||||
if (!preview) {
|
||||
const content = asArray(record?.content);
|
||||
preview = summarizeUserMessageContent(content);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (type === "agentMessage") {
|
||||
messageCountDelta += 1;
|
||||
if (!preview) {
|
||||
const text = asString(record?.text);
|
||||
if (text && text.trim().length > 0) {
|
||||
preview = trimToPreview(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
messageCountDelta,
|
||||
...(preview ? { preview } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function buildCheckpoints(turns: CodexThreadTurnSnapshot[]): ProviderCheckpoint[] {
|
||||
const checkpoints: ProviderCheckpoint[] = [];
|
||||
let messageCount = 0;
|
||||
const isEmpty = turns.length === 0;
|
||||
checkpoints.push({
|
||||
id: "root",
|
||||
turnCount: 0,
|
||||
messageCount: 0,
|
||||
label: "Start of conversation",
|
||||
isCurrent: isEmpty,
|
||||
});
|
||||
|
||||
for (let index = 0; index < turns.length; index += 1) {
|
||||
const turn = turns[index];
|
||||
if (!turn) continue;
|
||||
const turnSummary = summarizeTurn(turn);
|
||||
messageCount += turnSummary.messageCountDelta;
|
||||
checkpoints.push({
|
||||
id: turn.id,
|
||||
turnCount: index + 1,
|
||||
messageCount,
|
||||
label: `Turn ${index + 1}`,
|
||||
...(turnSummary.preview ? { preview: turnSummary.preview } : {}),
|
||||
isCurrent: index === turns.length - 1,
|
||||
});
|
||||
}
|
||||
|
||||
return checkpoints;
|
||||
}
|
||||
|
||||
export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
private readonly codex = new CodexAppServerManager();
|
||||
private readonly filesystemCheckpointStore = new FilesystemCheckpointStore();
|
||||
private readonly threadLogsDir: string;
|
||||
private readonly threadLogStreams = new Map<string, fs.WriteStream>();
|
||||
private readonly sessionThreadIds = new Map<string, string>();
|
||||
private readonly pendingEventsBySession = new Map<string, ProviderEvent[]>();
|
||||
private readonly sessionCheckpointCwds = new Map<string, string>();
|
||||
private readonly filesystemLocks = new Map<string, Promise<void>>();
|
||||
private disposed = false;
|
||||
private readonly onCodexEvent = (event: ProviderEvent) => {
|
||||
if (this.disposed) {
|
||||
@@ -37,6 +174,7 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
|
||||
this.routeEventToThreadLog(event);
|
||||
this.emit("event", event);
|
||||
this.maybeCaptureFilesystemCheckpoint(event);
|
||||
};
|
||||
|
||||
constructor() {
|
||||
@@ -60,6 +198,11 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
this.sessionThreadIds.set(session.sessionId, session.threadId);
|
||||
this.flushPendingSessionEvents(session.sessionId, session.threadId);
|
||||
}
|
||||
await this.initializeFilesystemCheckpointing(session).catch((error) => {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Failed to initialize filesystem checkpoints.";
|
||||
this.emitFilesystemCheckpointError(session.sessionId, message, session.threadId);
|
||||
});
|
||||
return session;
|
||||
}
|
||||
|
||||
@@ -95,12 +238,99 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
this.codex.stopSession(input.sessionId);
|
||||
this.sessionThreadIds.delete(input.sessionId);
|
||||
this.pendingEventsBySession.delete(input.sessionId);
|
||||
this.sessionCheckpointCwds.delete(input.sessionId);
|
||||
this.filesystemLocks.delete(input.sessionId);
|
||||
}
|
||||
|
||||
listSessions(): ProviderSession[] {
|
||||
return this.codex.listSessions();
|
||||
}
|
||||
|
||||
async listCheckpoints(raw: ProviderListCheckpointsInput): Promise<ProviderListCheckpointsResult> {
|
||||
const input = providerListCheckpointsInputSchema.parse(raw);
|
||||
if (!this.codex.hasSession(input.sessionId)) {
|
||||
throw new Error(`Unknown provider session: ${input.sessionId}`);
|
||||
}
|
||||
|
||||
const snapshot = await this.codex.readThread(input.sessionId);
|
||||
return {
|
||||
threadId: snapshot.threadId,
|
||||
checkpoints: buildCheckpoints(snapshot.turns),
|
||||
};
|
||||
}
|
||||
|
||||
async revertToCheckpoint(
|
||||
raw: ProviderRevertToCheckpointInput,
|
||||
): Promise<ProviderRevertToCheckpointResult> {
|
||||
const input = providerRevertToCheckpointInputSchema.parse(raw);
|
||||
if (!this.codex.hasSession(input.sessionId)) {
|
||||
throw new Error(`Unknown provider session: ${input.sessionId}`);
|
||||
}
|
||||
|
||||
return this.withFilesystemLock(input.sessionId, async () => {
|
||||
const beforeSnapshot = await this.codex.readThread(input.sessionId);
|
||||
const currentTurnCount = beforeSnapshot.turns.length;
|
||||
if (input.turnCount > currentTurnCount) {
|
||||
throw new Error(
|
||||
`Checkpoint turn count ${input.turnCount} exceeds current turn count ${currentTurnCount}.`,
|
||||
);
|
||||
}
|
||||
|
||||
const checkpointCwd = this.sessionCheckpointCwds.get(input.sessionId);
|
||||
if (checkpointCwd) {
|
||||
const hasCheckpoint = await this.filesystemCheckpointStore.hasCheckpoint({
|
||||
cwd: checkpointCwd,
|
||||
threadId: beforeSnapshot.threadId,
|
||||
turnCount: input.turnCount,
|
||||
});
|
||||
if (!hasCheckpoint) {
|
||||
throw new Error(
|
||||
`Filesystem checkpoint is unavailable for turn ${input.turnCount} in thread ${beforeSnapshot.threadId}.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const requestedRollbackTurns = currentTurnCount - input.turnCount;
|
||||
const afterSnapshot =
|
||||
requestedRollbackTurns > 0
|
||||
? await this.codex.rollbackThread(input.sessionId, requestedRollbackTurns)
|
||||
: beforeSnapshot;
|
||||
|
||||
if (checkpointCwd) {
|
||||
const restored = await this.filesystemCheckpointStore.restoreCheckpoint({
|
||||
cwd: checkpointCwd,
|
||||
threadId: beforeSnapshot.threadId,
|
||||
turnCount: input.turnCount,
|
||||
});
|
||||
if (!restored) {
|
||||
throw new Error(
|
||||
`Filesystem checkpoint is unavailable for turn ${input.turnCount} in thread ${beforeSnapshot.threadId}.`,
|
||||
);
|
||||
}
|
||||
await this.filesystemCheckpointStore.pruneAfterTurn({
|
||||
cwd: checkpointCwd,
|
||||
threadId: afterSnapshot.threadId,
|
||||
maxTurnCount: afterSnapshot.turns.length,
|
||||
});
|
||||
}
|
||||
|
||||
const checkpoints = buildCheckpoints(afterSnapshot.turns);
|
||||
const currentCheckpoint =
|
||||
checkpoints.find((checkpoint) => checkpoint.isCurrent) ??
|
||||
checkpoints[checkpoints.length - 1] ??
|
||||
checkpoints[0];
|
||||
const rolledBackTurns = Math.max(0, currentTurnCount - afterSnapshot.turns.length);
|
||||
|
||||
return {
|
||||
threadId: afterSnapshot.threadId,
|
||||
turnCount: currentCheckpoint?.turnCount ?? 0,
|
||||
messageCount: currentCheckpoint?.messageCount ?? 0,
|
||||
rolledBackTurns,
|
||||
checkpoints,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
stopAll(): void {
|
||||
this.codex.stopAll();
|
||||
}
|
||||
@@ -118,6 +348,88 @@ export class ProviderManager extends EventEmitter<ProviderManagerEvents> {
|
||||
this.threadLogStreams.clear();
|
||||
this.sessionThreadIds.clear();
|
||||
this.pendingEventsBySession.clear();
|
||||
this.sessionCheckpointCwds.clear();
|
||||
this.filesystemLocks.clear();
|
||||
}
|
||||
|
||||
private async initializeFilesystemCheckpointing(session: ProviderSession): Promise<void> {
|
||||
const cwd = session.cwd ?? process.cwd();
|
||||
|
||||
await this.withFilesystemLock(session.sessionId, async () => {
|
||||
const supportsGit = await this.filesystemCheckpointStore.isGitRepository(cwd);
|
||||
if (!supportsGit) {
|
||||
this.sessionCheckpointCwds.delete(session.sessionId);
|
||||
return;
|
||||
}
|
||||
|
||||
const snapshot = await this.codex.readThread(session.sessionId);
|
||||
await this.filesystemCheckpointStore.captureCheckpoint({
|
||||
cwd,
|
||||
threadId: snapshot.threadId,
|
||||
turnCount: snapshot.turns.length,
|
||||
});
|
||||
this.sessionCheckpointCwds.set(session.sessionId, cwd);
|
||||
});
|
||||
}
|
||||
|
||||
private maybeCaptureFilesystemCheckpoint(event: ProviderEvent): void {
|
||||
if (event.kind !== "notification" || event.method !== "turn/completed") {
|
||||
return;
|
||||
}
|
||||
|
||||
const checkpointCwd = this.sessionCheckpointCwds.get(event.sessionId);
|
||||
if (!checkpointCwd) {
|
||||
return;
|
||||
}
|
||||
|
||||
void this.withFilesystemLock(event.sessionId, async () => {
|
||||
if (!this.codex.hasSession(event.sessionId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const snapshot = await this.codex.readThread(event.sessionId);
|
||||
await this.filesystemCheckpointStore.captureCheckpoint({
|
||||
cwd: checkpointCwd,
|
||||
threadId: snapshot.threadId,
|
||||
turnCount: snapshot.turns.length,
|
||||
});
|
||||
}).catch((error) => {
|
||||
const message = error instanceof Error ? error.message : "Failed to capture checkpoint.";
|
||||
this.emitFilesystemCheckpointError(event.sessionId, message, event.threadId);
|
||||
});
|
||||
}
|
||||
|
||||
private emitFilesystemCheckpointError(
|
||||
sessionId: string,
|
||||
message: string,
|
||||
threadId?: string,
|
||||
): void {
|
||||
this.emit("event", {
|
||||
id: randomUUID(),
|
||||
kind: "error",
|
||||
provider: "codex",
|
||||
sessionId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "checkpoint/filesystemError",
|
||||
message,
|
||||
...(threadId ? { threadId } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
private withFilesystemLock<T>(sessionId: string, fn: () => Promise<T>): Promise<T> {
|
||||
const previous = this.filesystemLocks.get(sessionId) ?? Promise.resolve();
|
||||
const next = previous.catch(() => undefined).then(fn);
|
||||
const completion = next.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
this.filesystemLocks.set(sessionId, completion);
|
||||
return next.finally(() => {
|
||||
const tracked = this.filesystemLocks.get(sessionId);
|
||||
if (tracked === completion) {
|
||||
this.filesystemLocks.delete(sessionId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private routeEventToThreadLog(event: ProviderEvent): void {
|
||||
|
||||
@@ -591,6 +591,30 @@ describe("WebSocket Server", () => {
|
||||
expect(response.result).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns unknown-session errors for checkpoint RPCs without an active provider session", async () => {
|
||||
server = createTestServer({ cwd: "/test" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const ws = await connectWs(port);
|
||||
connections.push(ws);
|
||||
await waitForMessage(ws);
|
||||
|
||||
const listResponse = await sendRequest(ws, WS_METHODS.providersListCheckpoints, {
|
||||
sessionId: "missing-session",
|
||||
});
|
||||
expect(listResponse.result).toBeUndefined();
|
||||
expect(listResponse.error?.message).toContain("Unknown provider session");
|
||||
|
||||
const revertResponse = await sendRequest(ws, WS_METHODS.providersRevertToCheckpoint, {
|
||||
sessionId: "missing-session",
|
||||
turnCount: 0,
|
||||
});
|
||||
expect(revertResponse.result).toBeUndefined();
|
||||
expect(revertResponse.error?.message).toContain("Unknown provider session");
|
||||
});
|
||||
|
||||
it("routes terminal RPC methods and broadcasts terminal events", async () => {
|
||||
const cwd = makeTempDir("t3code-ws-terminal-cwd-");
|
||||
const terminalManager = new MockTerminalManager();
|
||||
|
||||
@@ -309,6 +309,12 @@ export function createServer(options: ServerOptions) {
|
||||
case WS_METHODS.providersListSessions:
|
||||
return providerManager.listSessions();
|
||||
|
||||
case WS_METHODS.providersListCheckpoints:
|
||||
return providerManager.listCheckpoints(request.params as never);
|
||||
|
||||
case WS_METHODS.providersRevertToCheckpoint:
|
||||
return providerManager.revertToCheckpoint(request.params as never);
|
||||
|
||||
case WS_METHODS.projectsList:
|
||||
return projectRegistry.list();
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
type ProviderCheckpoint,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderSendTurnAttachmentInput,
|
||||
@@ -151,6 +152,9 @@ export default function ChatView() {
|
||||
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
|
||||
const [isSending, setIsSending] = useState(false);
|
||||
const [isConnecting, setIsConnecting] = useState(false);
|
||||
const [isLoadingCheckpoints, setIsLoadingCheckpoints] = useState(false);
|
||||
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
|
||||
const [checkpoints, setCheckpoints] = useState<ProviderCheckpoint[]>([]);
|
||||
const [selectedEffort, setSelectedEffort] = useState(DEFAULT_REASONING);
|
||||
const [envMode, setEnvMode] = useState<"local" | "worktree">("local");
|
||||
const [isSwitchingRuntimeMode, setIsSwitchingRuntimeMode] = useState(false);
|
||||
@@ -174,7 +178,7 @@ export default function ChatView() {
|
||||
activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL,
|
||||
);
|
||||
const phase = derivePhase(activeThread?.session ?? null);
|
||||
const isWorking = phase === "running" || isSending || isConnecting;
|
||||
const isWorking = phase === "running" || isSending || isConnecting || isRevertingCheckpoint;
|
||||
const nowIso = new Date(nowTick).toISOString();
|
||||
const workLogEntries = useMemo(
|
||||
() => deriveWorkLogEntries(activeThread?.events ?? [], undefined),
|
||||
@@ -294,6 +298,12 @@ export default function ChatView() {
|
||||
(activeThread.messages.length > 0 ||
|
||||
(activeThread.session !== null && activeThread.session.status !== "closed")),
|
||||
);
|
||||
const canCheckpoint =
|
||||
Boolean(api && activeThread && (activeThread.codexThreadId ?? activeThread.session?.threadId)) &&
|
||||
phase !== "running" &&
|
||||
!isSending &&
|
||||
!isConnecting &&
|
||||
!isRevertingCheckpoint;
|
||||
|
||||
const revokePreviewUrls = useCallback((images: Array<{ previewUrl?: string }>) => {
|
||||
for (const image of images) {
|
||||
@@ -436,6 +446,12 @@ export default function ChatView() {
|
||||
setExpandedWorkGroups({});
|
||||
}, [activeThread?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
setCheckpoints([]);
|
||||
setIsLoadingCheckpoints(false);
|
||||
setIsRevertingCheckpoint(false);
|
||||
}, [activeThread?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThread?.id || activeThread.terminalOpen) return;
|
||||
const frame = window.requestAnimationFrame(() => {
|
||||
@@ -767,6 +783,78 @@ export default function ChatView() {
|
||||
}
|
||||
};
|
||||
|
||||
const loadCheckpoints = async (): Promise<ProviderCheckpoint[] | null> => {
|
||||
if (!api || !activeThread) return null;
|
||||
if (phase === "running" || isSending || isConnecting || isRevertingCheckpoint) {
|
||||
return null;
|
||||
}
|
||||
const hasThreadIdentity = Boolean(activeThread.codexThreadId ?? activeThread.session?.threadId);
|
||||
if (!hasThreadIdentity) {
|
||||
setCheckpoints([]);
|
||||
return [];
|
||||
}
|
||||
|
||||
setIsLoadingCheckpoints(true);
|
||||
setThreadError(activeThread.id, null);
|
||||
try {
|
||||
const sessionInfo = await ensureSession();
|
||||
if (!sessionInfo) {
|
||||
return null;
|
||||
}
|
||||
const result = await api.providers.listCheckpoints({
|
||||
sessionId: sessionInfo.sessionId,
|
||||
});
|
||||
setCheckpoints(result.checkpoints);
|
||||
return result.checkpoints;
|
||||
} catch (err) {
|
||||
setThreadError(
|
||||
activeThread.id,
|
||||
err instanceof Error ? err.message : "Failed to load checkpoints.",
|
||||
);
|
||||
return null;
|
||||
} finally {
|
||||
setIsLoadingCheckpoints(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onRevertToCheckpoint = async (checkpoint: ProviderCheckpoint) => {
|
||||
if (!api || !activeThread || checkpoint.isCurrent || isRevertingCheckpoint) {
|
||||
return;
|
||||
}
|
||||
if (phase === "running" || isSending || isConnecting) {
|
||||
setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
|
||||
return;
|
||||
}
|
||||
|
||||
setIsRevertingCheckpoint(true);
|
||||
setThreadError(activeThread.id, null);
|
||||
try {
|
||||
const sessionInfo = await ensureSession();
|
||||
if (!sessionInfo) {
|
||||
return;
|
||||
}
|
||||
const result = await api.providers.revertToCheckpoint({
|
||||
sessionId: sessionInfo.sessionId,
|
||||
turnCount: checkpoint.turnCount,
|
||||
});
|
||||
dispatch({
|
||||
type: "REVERT_TO_CHECKPOINT",
|
||||
threadId: activeThread.id,
|
||||
sessionId: sessionInfo.sessionId,
|
||||
threadRuntimeId: result.threadId,
|
||||
messageCount: result.messageCount,
|
||||
});
|
||||
setCheckpoints(result.checkpoints);
|
||||
} catch (err) {
|
||||
setThreadError(
|
||||
activeThread.id,
|
||||
err instanceof Error ? err.message : "Failed to revert checkpoint.",
|
||||
);
|
||||
} finally {
|
||||
setIsRevertingCheckpoint(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onSend = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!api || !activeThread || isSending || isConnecting) return;
|
||||
@@ -998,6 +1086,14 @@ export default function ChatView() {
|
||||
gitCwd={gitCwd}
|
||||
diffOpen={state.diffOpen}
|
||||
onToggleDiff={onToggleDiff}
|
||||
checkpoints={checkpoints}
|
||||
canCheckpoint={canCheckpoint}
|
||||
isLoadingCheckpoints={isLoadingCheckpoints}
|
||||
isRevertingCheckpoint={isRevertingCheckpoint}
|
||||
onOpenCheckpoints={() => {
|
||||
void loadCheckpoints();
|
||||
}}
|
||||
onRevertToCheckpoint={onRevertToCheckpoint}
|
||||
/>
|
||||
</header>
|
||||
|
||||
@@ -1291,6 +1387,12 @@ interface ChatHeaderProps {
|
||||
gitCwd: string | null;
|
||||
diffOpen: boolean;
|
||||
onToggleDiff: () => void;
|
||||
checkpoints: ProviderCheckpoint[];
|
||||
canCheckpoint: boolean;
|
||||
isLoadingCheckpoints: boolean;
|
||||
isRevertingCheckpoint: boolean;
|
||||
onOpenCheckpoints: () => void;
|
||||
onRevertToCheckpoint: (checkpoint: ProviderCheckpoint) => void;
|
||||
}
|
||||
|
||||
const ChatHeader = memo(function ChatHeader({
|
||||
@@ -1301,6 +1403,12 @@ const ChatHeader = memo(function ChatHeader({
|
||||
gitCwd,
|
||||
diffOpen,
|
||||
onToggleDiff,
|
||||
checkpoints,
|
||||
canCheckpoint,
|
||||
isLoadingCheckpoints,
|
||||
isRevertingCheckpoint,
|
||||
onOpenCheckpoints,
|
||||
onRevertToCheckpoint,
|
||||
}: ChatHeaderProps) {
|
||||
return (
|
||||
<>
|
||||
@@ -1311,6 +1419,46 @@ const ChatHeader = memo(function ChatHeader({
|
||||
<div className="flex items-center gap-3">
|
||||
{activeProjectName && <OpenInPicker keybindings={keybindings} />}
|
||||
{activeProjectName && <GitActionsControl api={api} gitCwd={gitCwd} />}
|
||||
<Menu>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
||||
disabled={!canCheckpoint || isRevertingCheckpoint}
|
||||
onClick={onOpenCheckpoints}
|
||||
>
|
||||
{isRevertingCheckpoint
|
||||
? "Reverting..."
|
||||
: isLoadingCheckpoints
|
||||
? "Loading..."
|
||||
: "Checkpoints"}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<MenuPopup align="end" className="w-72">
|
||||
{!canCheckpoint ? (
|
||||
<MenuItem disabled>Send at least one message to create checkpoints.</MenuItem>
|
||||
) : checkpoints.length === 0 ? (
|
||||
<MenuItem disabled>
|
||||
{isLoadingCheckpoints ? "Loading checkpoints..." : "No checkpoints available."}
|
||||
</MenuItem>
|
||||
) : (
|
||||
checkpoints.map((checkpoint) => (
|
||||
<MenuItem
|
||||
key={checkpoint.id}
|
||||
disabled={checkpoint.isCurrent || isRevertingCheckpoint}
|
||||
onClick={() => onRevertToCheckpoint(checkpoint)}
|
||||
>
|
||||
{checkpoint.label}
|
||||
{checkpoint.preview ? `: ${checkpoint.preview}` : ""}
|
||||
{checkpoint.isCurrent ? " (Current)" : ""}
|
||||
</MenuItem>
|
||||
))
|
||||
)}
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
|
||||
@@ -574,4 +574,66 @@ describe("store reducer thread continuity", () => {
|
||||
expect(next.threads[0]?.latestTurnCompletedAt).toBe(completedAt);
|
||||
expect(next.threads[0]?.lastVisitedAt).toBe(completedAt);
|
||||
});
|
||||
|
||||
it("reverts thread state to a checkpoint snapshot", () => {
|
||||
const state = makeState(
|
||||
makeThread({
|
||||
codexThreadId: "thr_before",
|
||||
session: makeSession({
|
||||
status: "running",
|
||||
threadId: "thr_before",
|
||||
activeTurnId: "turn-live",
|
||||
}),
|
||||
messages: [
|
||||
{
|
||||
id: "m-1",
|
||||
role: "user",
|
||||
text: "First",
|
||||
createdAt: "2026-02-08T10:00:00.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: "m-2",
|
||||
role: "assistant",
|
||||
text: "First reply",
|
||||
createdAt: "2026-02-08T10:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: "m-3",
|
||||
role: "user",
|
||||
text: "Second",
|
||||
createdAt: "2026-02-08T10:00:02.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
events: [
|
||||
makeEvent({
|
||||
method: "turn/started",
|
||||
turnId: "turn-live",
|
||||
}),
|
||||
],
|
||||
error: "temporary failure",
|
||||
latestTurnId: "turn-live",
|
||||
latestTurnStartedAt: "2026-02-08T10:00:03.000Z",
|
||||
}),
|
||||
);
|
||||
|
||||
const next = reducer(state, {
|
||||
type: "REVERT_TO_CHECKPOINT",
|
||||
threadId: "thread-local-1",
|
||||
sessionId: "sess-1",
|
||||
threadRuntimeId: "thr_after",
|
||||
messageCount: 2,
|
||||
});
|
||||
|
||||
expect(next.threads[0]?.codexThreadId).toBe("thr_after");
|
||||
expect(next.threads[0]?.messages.map((message) => message.id)).toEqual(["m-1", "m-2"]);
|
||||
expect(next.threads[0]?.events).toEqual([]);
|
||||
expect(next.threads[0]?.error).toBeNull();
|
||||
expect(next.threads[0]?.session?.status).toBe("ready");
|
||||
expect(next.threads[0]?.session?.activeTurnId).toBeUndefined();
|
||||
expect(next.threads[0]?.session?.threadId).toBe("thr_after");
|
||||
expect(next.threads[0]?.latestTurnId).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -56,6 +56,13 @@ type Action =
|
||||
| { type: "SET_ERROR"; threadId: string; error: string | null }
|
||||
| { type: "SET_THREAD_TITLE"; threadId: string; title: string }
|
||||
| { type: "SET_THREAD_MODEL"; threadId: string; model: string }
|
||||
| {
|
||||
type: "REVERT_TO_CHECKPOINT";
|
||||
threadId: string;
|
||||
sessionId: string;
|
||||
threadRuntimeId: string;
|
||||
messageCount: number;
|
||||
}
|
||||
| {
|
||||
type: "SET_THREAD_BRANCH";
|
||||
threadId: string;
|
||||
@@ -798,6 +805,38 @@ export function reducer(state: AppState, action: Action): AppState {
|
||||
})),
|
||||
};
|
||||
|
||||
case "REVERT_TO_CHECKPOINT":
|
||||
return {
|
||||
...state,
|
||||
threads: updateThread(state.threads, action.threadId, (t) => {
|
||||
const nextMessageCount = Math.max(0, Math.floor(action.messageCount));
|
||||
const now = new Date().toISOString();
|
||||
return {
|
||||
...t,
|
||||
codexThreadId: action.threadRuntimeId,
|
||||
session:
|
||||
t.session?.sessionId === action.sessionId
|
||||
? {
|
||||
...t.session,
|
||||
status: "ready",
|
||||
threadId: action.threadRuntimeId,
|
||||
activeTurnId: undefined,
|
||||
updatedAt: now,
|
||||
lastError: undefined,
|
||||
}
|
||||
: t.session,
|
||||
messages: t.messages.slice(0, nextMessageCount),
|
||||
events: [],
|
||||
error: null,
|
||||
latestTurnId: undefined,
|
||||
latestTurnStartedAt: undefined,
|
||||
latestTurnCompletedAt: undefined,
|
||||
latestTurnDurationMs: undefined,
|
||||
lastVisitedAt: now,
|
||||
};
|
||||
}),
|
||||
};
|
||||
|
||||
case "SET_THREAD_BRANCH": {
|
||||
return {
|
||||
...state,
|
||||
|
||||
@@ -91,6 +91,9 @@ export function createWsNativeApi(): NativeApi {
|
||||
respondToRequest: (input) => transport.request(WS_METHODS.providersRespondToRequest, input),
|
||||
stopSession: (input) => transport.request(WS_METHODS.providersStopSession, input),
|
||||
listSessions: () => transport.request(WS_METHODS.providersListSessions),
|
||||
listCheckpoints: (input) => transport.request(WS_METHODS.providersListCheckpoints, input),
|
||||
revertToCheckpoint: (input) =>
|
||||
transport.request(WS_METHODS.providersRevertToCheckpoint, input),
|
||||
onEvent: (callback) =>
|
||||
transport.subscribe(WS_CHANNELS.providerEvent, callback as (data: unknown) => void),
|
||||
},
|
||||
|
||||
@@ -18,6 +18,10 @@ import type {
|
||||
import type {
|
||||
ProviderEvent,
|
||||
ProviderInterruptTurnInput,
|
||||
ProviderListCheckpointsInput,
|
||||
ProviderListCheckpointsResult,
|
||||
ProviderRevertToCheckpointInput,
|
||||
ProviderRevertToCheckpointResult,
|
||||
ProviderRespondToRequestInput,
|
||||
ProviderSendTurnInput,
|
||||
ProviderSession,
|
||||
@@ -84,6 +88,10 @@ export interface NativeApi {
|
||||
respondToRequest: (input: ProviderRespondToRequestInput) => Promise<void>;
|
||||
stopSession: (input: ProviderStopSessionInput) => Promise<void>;
|
||||
listSessions: () => Promise<ProviderSession[]>;
|
||||
listCheckpoints: (input: ProviderListCheckpointsInput) => Promise<ProviderListCheckpointsResult>;
|
||||
revertToCheckpoint: (
|
||||
input: ProviderRevertToCheckpointInput,
|
||||
) => Promise<ProviderRevertToCheckpointResult>;
|
||||
onEvent: (callback: (event: ProviderEvent) => void) => () => void;
|
||||
};
|
||||
projects: {
|
||||
|
||||
@@ -2,7 +2,12 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
providerCheckpointSchema,
|
||||
providerEventSchema,
|
||||
providerListCheckpointsInputSchema,
|
||||
providerListCheckpointsResultSchema,
|
||||
providerRevertToCheckpointInputSchema,
|
||||
providerRevertToCheckpointResultSchema,
|
||||
providerRespondToRequestInputSchema,
|
||||
providerSendTurnInputSchema,
|
||||
providerSessionStartInputSchema,
|
||||
@@ -157,3 +162,71 @@ describe("providerRespondToRequestInputSchema", () => {
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("provider checkpoint schemas", () => {
|
||||
it("accepts list checkpoint inputs", () => {
|
||||
const parsed = providerListCheckpointsInputSchema.parse({
|
||||
sessionId: "sess_1",
|
||||
});
|
||||
expect(parsed.sessionId).toBe("sess_1");
|
||||
});
|
||||
|
||||
it("accepts checkpoint records and list results", () => {
|
||||
const checkpoint = providerCheckpointSchema.parse({
|
||||
id: "turn_1",
|
||||
turnCount: 1,
|
||||
messageCount: 2,
|
||||
label: "Turn 1",
|
||||
preview: "Summarize this file",
|
||||
isCurrent: true,
|
||||
});
|
||||
expect(checkpoint.turnCount).toBe(1);
|
||||
|
||||
const listResult = providerListCheckpointsResultSchema.parse({
|
||||
threadId: "thr_1",
|
||||
checkpoints: [checkpoint],
|
||||
});
|
||||
expect(listResult.checkpoints).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("accepts revert checkpoint input/result", () => {
|
||||
const input = providerRevertToCheckpointInputSchema.parse({
|
||||
sessionId: "sess_1",
|
||||
turnCount: 2,
|
||||
});
|
||||
expect(input.turnCount).toBe(2);
|
||||
|
||||
const result = providerRevertToCheckpointResultSchema.parse({
|
||||
threadId: "thr_1",
|
||||
turnCount: 2,
|
||||
messageCount: 4,
|
||||
rolledBackTurns: 1,
|
||||
checkpoints: [
|
||||
{
|
||||
id: "root",
|
||||
turnCount: 0,
|
||||
messageCount: 0,
|
||||
label: "Start of conversation",
|
||||
isCurrent: false,
|
||||
},
|
||||
{
|
||||
id: "turn_2",
|
||||
turnCount: 2,
|
||||
messageCount: 4,
|
||||
label: "Turn 2",
|
||||
isCurrent: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(result.rolledBackTurns).toBe(1);
|
||||
});
|
||||
|
||||
it("rejects negative turn counts", () => {
|
||||
expect(() =>
|
||||
providerRevertToCheckpointInputSchema.parse({
|
||||
sessionId: "sess_1",
|
||||
turnCount: -1,
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -111,6 +111,37 @@ export const providerStopSessionInputSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
});
|
||||
|
||||
export const providerListCheckpointsInputSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
});
|
||||
|
||||
export const providerCheckpointSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
turnCount: z.number().int().min(0),
|
||||
messageCount: z.number().int().min(0),
|
||||
label: z.string().min(1),
|
||||
preview: z.string().min(1).optional(),
|
||||
isCurrent: z.boolean(),
|
||||
});
|
||||
|
||||
export const providerListCheckpointsResultSchema = z.object({
|
||||
threadId: z.string().min(1),
|
||||
checkpoints: z.array(providerCheckpointSchema),
|
||||
});
|
||||
|
||||
export const providerRevertToCheckpointInputSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
turnCount: z.number().int().min(0),
|
||||
});
|
||||
|
||||
export const providerRevertToCheckpointResultSchema = z.object({
|
||||
threadId: z.string().min(1),
|
||||
turnCount: z.number().int().min(0),
|
||||
messageCount: z.number().int().min(0),
|
||||
rolledBackTurns: z.number().int().min(0),
|
||||
checkpoints: z.array(providerCheckpointSchema),
|
||||
});
|
||||
|
||||
export const providerRespondToRequestInputSchema = z.object({
|
||||
sessionId: z.string().min(1),
|
||||
requestId: z.string().min(1),
|
||||
@@ -151,6 +182,13 @@ export type ProviderSendTurnInput = z.input<typeof providerSendTurnInputSchema>;
|
||||
export type ProviderTurnStartResult = z.infer<typeof providerTurnStartResultSchema>;
|
||||
export type ProviderInterruptTurnInput = z.input<typeof providerInterruptTurnInputSchema>;
|
||||
export type ProviderStopSessionInput = z.input<typeof providerStopSessionInputSchema>;
|
||||
export type ProviderListCheckpointsInput = z.input<typeof providerListCheckpointsInputSchema>;
|
||||
export type ProviderCheckpoint = z.infer<typeof providerCheckpointSchema>;
|
||||
export type ProviderListCheckpointsResult = z.infer<typeof providerListCheckpointsResultSchema>;
|
||||
export type ProviderRevertToCheckpointInput = z.input<typeof providerRevertToCheckpointInputSchema>;
|
||||
export type ProviderRevertToCheckpointResult = z.infer<
|
||||
typeof providerRevertToCheckpointResultSchema
|
||||
>;
|
||||
export type ProviderRespondToRequestInput = z.input<typeof providerRespondToRequestInputSchema>;
|
||||
export type ProviderEventKind = z.infer<typeof providerEventKindSchema>;
|
||||
export type ProviderEvent = z.infer<typeof providerEventSchema>;
|
||||
@@ -10,6 +10,8 @@ export const WS_METHODS = {
|
||||
providersRespondToRequest: "providers.respondToRequest",
|
||||
providersStopSession: "providers.stopSession",
|
||||
providersListSessions: "providers.listSessions",
|
||||
providersListCheckpoints: "providers.listCheckpoints",
|
||||
providersRevertToCheckpoint: "providers.revertToCheckpoint",
|
||||
|
||||
// Project registry methods
|
||||
projectsList: "projects.list",
|
||||
|
||||
Reference in new issue
Block a user