Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex 625da23b47 Harden Claude stream interruption handling
- preserve interrupted Claude turns separately from runtime failures
- ignore ede_diagnostic-only results and mark interrupted tool results as declined
- add regression coverage for interrupted stream edge cases

Co-authored-by: codex <[email protected]>
2026-04-10 12:57:40 -07:00
234 changed files with 3036 additions and 5979 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.17",
"version": "0.0.15",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
+1 -54
View File
@@ -36,57 +36,6 @@ describe("resolveDesktopBackendPort", () => {
]);
});
it("treats wildcard-bound ports as unavailable even when loopback probing succeeds", async () => {
const canListenOnHost = vi.fn(async (port: number, host: string) => {
if (port === 3773 && host === "127.0.0.1") return true;
if (port === 3773 && host === "0.0.0.0") return false;
return port === 3774;
});
await expect(
resolveDesktopBackendPort({
host: "127.0.0.1",
requiredHosts: ["0.0.0.0"],
startPort: 3773,
canListenOnHost,
}),
).resolves.toBe(3774);
expect(canListenOnHost.mock.calls).toEqual([
[3773, "127.0.0.1"],
[3773, "0.0.0.0"],
[3774, "127.0.0.1"],
[3774, "0.0.0.0"],
]);
});
it("checks overlapping hosts sequentially to avoid self-interference", async () => {
let inFlightCount = 0;
const canListenOnHost = vi.fn(async (_port: number, _host: string) => {
inFlightCount += 1;
const overlapped = inFlightCount > 1;
await Promise.resolve();
inFlightCount -= 1;
return !overlapped;
});
await expect(
resolveDesktopBackendPort({
host: "127.0.0.1",
requiredHosts: ["0.0.0.0", "::"],
startPort: 3773,
maxPort: 3773,
canListenOnHost,
}),
).resolves.toBe(3773);
expect(canListenOnHost.mock.calls).toEqual([
[3773, "127.0.0.1"],
[3773, "0.0.0.0"],
[3773, "::"],
]);
});
it("fails when the scan range is exhausted", async () => {
const canListenOnHost = vi.fn(async () => false);
@@ -97,9 +46,7 @@ describe("resolveDesktopBackendPort", () => {
maxPort: 65535,
canListenOnHost,
}),
).rejects.toThrow(
"No desktop backend port is available on hosts 127.0.0.1 between 65534 and 65535",
);
).rejects.toThrow("No desktop backend port is available on 127.0.0.1 between 65534 and 65535");
expect(canListenOnHost.mock.calls).toEqual([
[65534, "127.0.0.1"],
+2 -32
View File
@@ -8,7 +8,6 @@ export interface ResolveDesktopBackendPortOptions {
readonly host: string;
readonly startPort?: number;
readonly maxPort?: number;
readonly requiredHosts?: ReadonlyArray<string>;
readonly canListenOnHost?: (port: number, host: string) => Promise<boolean>;
}
@@ -22,37 +21,10 @@ const defaultCanListenOnHost = async (port: number, host: string): Promise<boole
const isValidPort = (port: number): boolean =>
Number.isInteger(port) && port >= 1 && port <= MAX_TCP_PORT;
const normalizeHosts = (
host: string,
requiredHosts: ReadonlyArray<string>,
): ReadonlyArray<string> =>
Array.from(
new Set(
[host, ...requiredHosts]
.map((candidate) => candidate.trim())
.filter((candidate) => candidate.length > 0),
),
);
async function canListenOnAllHosts(
port: number,
hosts: ReadonlyArray<string>,
canListenOnHost: (port: number, host: string) => Promise<boolean>,
): Promise<boolean> {
for (const candidateHost of hosts) {
if (!(await canListenOnHost(port, candidateHost))) {
return false;
}
}
return true;
}
export async function resolveDesktopBackendPort({
host,
startPort = DEFAULT_DESKTOP_BACKEND_PORT,
maxPort = MAX_TCP_PORT,
requiredHosts = [],
canListenOnHost = defaultCanListenOnHost,
}: ResolveDesktopBackendPortOptions): Promise<number> {
if (!isValidPort(startPort)) {
@@ -67,17 +39,15 @@ export async function resolveDesktopBackendPort({
throw new Error(`Desktop backend max port ${maxPort} is below start port ${startPort}`);
}
const hostsToCheck = normalizeHosts(host, requiredHosts);
// Keep desktop startup predictable across app restarts by probing upward from
// the same preferred port instead of picking a fresh ephemeral port.
for (let port = startPort; port <= maxPort; port += 1) {
if (await canListenOnAllHosts(port, hostsToCheck, canListenOnHost)) {
if (await canListenOnHost(port, host)) {
return port;
}
}
throw new Error(
`No desktop backend port is available on hosts ${hostsToCheck.join(", ")} between ${startPort} and ${maxPort}`,
`No desktop backend port is available on ${host} between ${startPort} and ${maxPort}`,
);
}
+1 -1
View File
@@ -58,7 +58,7 @@ const clientSettings: ClientSettings = {
};
const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
environmentId: EnvironmentId.make("environment-1"),
environmentId: EnvironmentId.makeUnsafe("environment-1"),
label: "Remote environment",
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
-10
View File
@@ -117,7 +117,6 @@ const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
const DESKTOP_UPDATE_CHANNEL = "latest";
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
const DESKTOP_REQUIRED_PORT_PROBE_HOSTS = ["0.0.0.0", "::"] as const;
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
type LinuxDesktopNamedApp = Electron.App & {
@@ -1696,14 +1695,6 @@ function createWindow(): BrowserWindow {
);
}
if (params.mediaType === "image") {
menuTemplate.push({
label: "Copy Image",
click: () => window.webContents.copyImageAt(params.x, params.y),
});
menuTemplate.push({ type: "separator" });
}
menuTemplate.push(
{ role: "cut", enabled: params.editFlags.canCut },
{ role: "copy", enabled: params.editFlags.canCopy },
@@ -1782,7 +1773,6 @@ async function bootstrap(): Promise<void> {
(await resolveDesktopBackendPort({
host: DESKTOP_LOOPBACK_HOST,
startPort: DEFAULT_DESKTOP_BACKEND_PORT,
requiredHosts: DESKTOP_REQUIRED_PORT_PROBE_HOSTS,
}));
writeDesktopLogHeader(
configuredBackendPort === undefined
@@ -438,7 +438,7 @@ export const makeOrchestrationIntegrationHarness = (
) =>
waitFor(
pendingApprovalRepository
.getByRequestId({ requestId: ApprovalRequestId.make(requestId) })
.getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
.pipe(
Effect.map((row) =>
Option.match(row, {
@@ -289,7 +289,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
state.turnCount += 1;
const turnCount = state.turnCount;
const turnId = TurnId.make(`turn-${turnCount}`);
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
const response = state.queuedResponses.shift();
if (!response) {
@@ -307,7 +307,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
...(fixtureEvent as Record<string, unknown>),
eventId: randomUUID(),
provider,
sessionId: RuntimeSessionId.make(String(input.threadId)),
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
createdAt: nowIso(),
};
rawEvent.threadId = state.snapshot.threadId;
@@ -363,7 +363,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
if (deferredTurnCompletedEvents.length === 0) {
yield* emit({
type: "turn.completed",
eventId: EventId.make(randomUUID()),
eventId: EventId.makeUnsafe(randomUUID()),
provider,
createdAt: nowIso(),
threadId: state.snapshot.threadId,
@@ -472,15 +472,6 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
sessions.clear();
});
const compactThread: ProviderAdapterShape<ProviderAdapterError>["compactThread"] = (threadId) =>
readThread(threadId).pipe(
Effect.map((snapshot) => {
const latestTurn = snapshot.turns.at(-1);
const latestItem = latestTurn?.items.at(-1);
return typeof latestItem === "string" ? latestItem : null;
}),
);
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
provider,
capabilities: {
@@ -495,7 +486,6 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
listSessions,
hasSession,
readThread,
compactThread,
rollbackThread,
stopAll,
streamEvents: Stream.fromQueue(runtimeEvents),
@@ -5,14 +5,14 @@ const PROVIDER = "codex" as const;
const SESSION_ID = "fixture-session";
const THREAD_ID = "fixture-thread";
const TURN_ID = "fixture-turn";
const REQUEST_ID = RuntimeRequestId.make("req-1");
const REQUEST_ID = RuntimeRequestId.makeUnsafe("req-1");
function baseEvent(
eventId: string,
createdAt: string,
): Pick<LegacyProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
return {
eventId: EventId.make(eventId),
eventId: EventId.makeUnsafe(eventId),
provider: PROVIDER,
sessionId: SESSION_ID,
createdAt,
@@ -30,13 +30,14 @@ import type {
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
const asMessageId = (value: string): MessageId => MessageId.make(value);
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asEventId = (value: string): EventId => EventId.make(value);
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asApprovalRequestId = (value: string): ApprovalRequestId =>
ApprovalRequestId.makeUnsafe(value);
const PROJECT_ID = asProjectId("project-1");
const THREAD_ID = ThreadId.make("thread-1");
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
const FIXTURE_TURN_ID = "fixture-turn";
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
type IntegrationProvider = ProviderKind;
@@ -111,7 +112,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
yield* harness.engine.dispatch({
type: "project.create",
commandId: CommandId.make("cmd-project-create"),
commandId: CommandId.makeUnsafe("cmd-project-create"),
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
@@ -124,7 +125,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
yield* harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create"),
commandId: CommandId.makeUnsafe("cmd-thread-create"),
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
@@ -149,7 +150,7 @@ const startTurn = (input: {
}) =>
input.harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make(input.commandId),
commandId: CommandId.makeUnsafe(input.commandId),
threadId: THREAD_ID,
message: {
messageId: asMessageId(input.messageId),
@@ -260,7 +261,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
yield* harness.engine.dispatch({
type: "project.create",
commandId: CommandId.make("cmd-project-create-real-codex"),
commandId: CommandId.makeUnsafe("cmd-project-create-real-codex"),
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
@@ -273,7 +274,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
yield* harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create-real-codex"),
commandId: CommandId.makeUnsafe("cmd-thread-create-real-codex"),
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
@@ -290,7 +291,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-real-codex-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-1"),
threadId: THREAD_ID,
message: {
messageId: asMessageId("msg-real-codex-1"),
@@ -317,7 +318,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-real-codex-2"),
commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-2"),
threadId: THREAD_ID,
message: {
messageId: asMessageId("msg-real-codex-2"),
@@ -582,7 +583,7 @@ it.live("tracks approval requests and resolves pending approvals on user respons
yield* harness.engine.dispatch({
type: "thread.approval.respond",
commandId: CommandId.make("cmd-approval-respond"),
commandId: CommandId.makeUnsafe("cmd-approval-respond"),
threadId: THREAD_ID,
requestId: APPROVAL_REQUEST_ID,
decision: "accept",
@@ -814,7 +815,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.make("cmd-checkpoint-revert"),
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
@@ -874,7 +875,7 @@ it.live(
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.make("cmd-checkpoint-revert-no-session"),
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-no-session"),
threadId: THREAD_ID,
turnCount: 0,
createdAt: nowIso(),
@@ -1118,7 +1119,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
yield* harness.engine.dispatch({
type: "thread.approval.respond",
commandId: CommandId.make("cmd-claude-approval-respond"),
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
threadId: THREAD_ID,
requestId: APPROVAL_REQUEST_ID,
decision: "accept",
@@ -1191,7 +1192,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
yield* harness.engine.dispatch({
type: "thread.turn.interrupt",
commandId: CommandId.make("cmd-turn-interrupt-claude"),
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
threadId: THREAD_ID,
createdAt: nowIso(),
});
@@ -1308,7 +1309,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.make("cmd-checkpoint-revert-claude"),
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
@@ -122,12 +122,15 @@ it.live("replays typed runtime fixture events", () =>
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
threadId: ThreadId.make("thread-integration-typed"),
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
});
const session = yield* provider.startSession(
ThreadId.makeUnsafe("thread-integration-typed"),
{
threadId: ThreadId.makeUnsafe("thread-integration-typed"),
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
},
);
assert.equal((session.threadId ?? "").length > 0, true);
const observedEvents = yield* runTurn({
@@ -154,12 +157,15 @@ it.live("replays file-changing fixture turn events", () =>
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
threadId: ThreadId.make("thread-integration-tools"),
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
});
const session = yield* provider.startSession(
ThreadId.makeUnsafe("thread-integration-tools"),
{
threadId: ThreadId.makeUnsafe("thread-integration-tools"),
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
},
);
assert.equal((session.threadId ?? "").length > 0, true);
const observedEvents = yield* runTurn({
@@ -190,12 +196,15 @@ it.live("runs multi-turn tool/approval flow", () =>
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
threadId: ThreadId.make("thread-integration-multi"),
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
});
const session = yield* provider.startSession(
ThreadId.makeUnsafe("thread-integration-multi"),
{
threadId: ThreadId.makeUnsafe("thread-integration-multi"),
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
},
);
assert.equal((session.threadId ?? "").length > 0, true);
const firstTurnEvents = yield* runTurn({
@@ -241,12 +250,15 @@ it.live("rolls back provider conversation state only", () =>
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
threadId: ThreadId.make("thread-integration-rollback"),
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
});
const session = yield* provider.startSession(
ThreadId.makeUnsafe("thread-integration-rollback"),
{
threadId: ThreadId.makeUnsafe("thread-integration-rollback"),
provider: "codex",
cwd: fixture.cwd,
runtimeMode: "full-access",
},
);
assert.equal((session.threadId ?? "").length > 0, true);
yield* runTurn({
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.17",
"version": "0.0.15",
"license": "MIT",
"repository": {
"type": "git",
+3 -25
View File
@@ -14,22 +14,6 @@ import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog
import rootPackageJson from "../../../package.json" with { type: "json" };
import serverPackageJson from "../package.json" with { type: "json" };
interface PackageJson {
name: string;
repository: {
type: string;
url: string;
directory: string;
};
bin: Record<string, string>;
type: string;
version: string;
engines: Record<string, string>;
files: string[];
dependencies: Record<string, string>;
overrides: Record<string, string>;
}
class CliError extends Data.TaggedError("CliError")<{
readonly message: string;
readonly cause?: unknown;
@@ -193,7 +177,7 @@ const publishCmd = Command.make(
const backupPath = `${packageJsonPath}.bak`;
// Assert build assets exist
for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
const abs = path.join(serverDir, relPath);
if (!(yield* fs.exists(abs))) {
return yield* new CliError({
@@ -208,7 +192,7 @@ const publishCmd = Command.make(
// Resolve catalog dependencies before any file mutations. If this throws,
// acquire fails and no release hook runs, so filesystem must still be untouched.
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
const pkg: PackageJson = {
const pkg = {
name: serverPackageJson.name,
repository: serverPackageJson.repository,
bin: serverPackageJson.bin,
@@ -216,8 +200,7 @@ const publishCmd = Command.make(
version,
engines: serverPackageJson.engines,
files: serverPackageJson.files,
dependencies: serverPackageJson.dependencies,
overrides: rootPackageJson.overrides,
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
};
pkg.dependencies = resolveCatalogDependencies(
@@ -225,11 +208,6 @@ const publishCmd = Command.make(
rootPackageJson.workspaces.catalog,
"apps/server dependencies",
);
pkg.overrides = resolveCatalogDependencies(
pkg.overrides,
rootPackageJson.workspaces.catalog,
"root overrides",
);
const original = yield* fs.readFileString(packageJsonPath);
yield* fs.writeFileString(backupPath, original);
+1 -11
View File
@@ -20,10 +20,7 @@ import {
AuthError,
type ServerAuthShape,
} from "../Services/ServerAuth.ts";
import {
SessionCredentialError,
SessionCredentialService,
} from "../Services/SessionCredentialService.ts";
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
import { AuthControlPlaneLive, AuthCoreLive } from "./AuthControlPlane.ts";
type BootstrapExchangeResult = {
@@ -68,13 +65,6 @@ export const makeServerAuth = Effect.gen(function* () {
const authenticateToken = (token: string): Effect.Effect<AuthenticatedSession, AuthError> =>
sessions.verify(token).pipe(
Effect.tapError((cause: SessionCredentialError) =>
Effect.logWarning("Rejected authenticated session credential.").pipe(
Effect.annotateLogs({
reason: cause.message,
}),
),
),
Effect.map((session) => ({
sessionId: session.sessionId,
subject: session.subject,
@@ -33,12 +33,10 @@ it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {
expect(descriptor.policy).toBe("desktop-managed-local");
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]);
expect(descriptor.sessionCookieName).toBe("t3_session_3773");
}).pipe(
Effect.provide(
makeServerAuthPolicyLayer({
mode: "desktop",
port: 3773,
}),
),
),
@@ -68,7 +66,6 @@ it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {
expect(descriptor.policy).toBe("loopback-browser");
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
expect(descriptor.sessionCookieName).toBe("t3_session");
}).pipe(
Effect.provide(
makeServerAuthPolicyLayer({
@@ -3,7 +3,7 @@ import { Effect, Layer } from "effect";
import { ServerConfig } from "../../config.ts";
import { ServerAuthPolicy, type ServerAuthPolicyShape } from "../Services/ServerAuthPolicy.ts";
import { resolveSessionCookieName } from "../utils.ts";
import { SESSION_COOKIE_NAME } from "../utils.ts";
import { isLoopbackHost, isWildcardHost } from "../../startupAccess.ts";
export const makeServerAuthPolicy = Effect.gen(function* () {
@@ -30,10 +30,7 @@ export const makeServerAuthPolicy = Effect.gen(function* () {
policy,
bootstrapMethods,
sessionMethods: ["browser-session-cookie", "bearer-session-token"],
sessionCookieName: resolveSessionCookieName({
mode: config.mode,
port: config.port,
}),
sessionCookieName: SESSION_COOKIE_NAME,
};
return {
@@ -1,6 +1,6 @@
import * as Crypto from "node:crypto";
import { Effect, FileSystem, Layer, Path, Predicate } from "effect";
import { Effect, FileSystem, Layer, Path } from "effect";
import * as PlatformError from "effect/PlatformError";
import { ServerConfig } from "../../config.ts";
@@ -28,14 +28,17 @@ export const makeServerSecretStore = Effect.gen(function* () {
const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
const isPlatformError = (u: unknown): u is PlatformError.PlatformError =>
Predicate.isTagged(u, "PlatformError");
const isMissingSecretFileError = (cause: unknown): cause is PlatformError.PlatformError =>
cause instanceof PlatformError.PlatformError && cause.reason._tag === "NotFound";
const isAlreadyExistsSecretFileError = (cause: unknown): cause is PlatformError.PlatformError =>
cause instanceof PlatformError.PlatformError && cause.reason._tag === "AlreadyExists";
const get: ServerSecretStoreShape["get"] = (name) =>
fileSystem.readFile(resolveSecretPath(name)).pipe(
Effect.map((bytes) => Uint8Array.from(bytes)),
Effect.catch((cause) =>
cause.reason._tag === "NotFound"
isMissingSecretFileError(cause)
? Effect.succeed(null)
: Effect.fail(
new SecretStoreError({
@@ -105,7 +108,7 @@ export const makeServerSecretStore = Effect.gen(function* () {
return create(name, generated).pipe(
Effect.as(Uint8Array.from(generated)),
Effect.catchTag("SecretStoreError", (error) =>
isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists"
isAlreadyExistsSecretFileError(error.cause)
? get(name).pipe(
Effect.flatMap((created) =>
created !== null
@@ -126,7 +129,7 @@ export const makeServerSecretStore = Effect.gen(function* () {
const remove: ServerSecretStoreShape["remove"] = (name) =>
fileSystem.remove(resolveSecretPath(name)).pipe(
Effect.catch((cause) =>
cause.reason._tag === "NotFound"
isMissingSecretFileError(cause)
? Effect.void
: Effect.fail(
new SecretStoreError({
@@ -2,10 +2,10 @@ import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "
import { Clock, DateTime, Duration, Effect, Layer, PubSub, Ref, Schema, Stream } from "effect";
import { Option } from "effect";
import { ServerConfig } from "../../config.ts";
import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts";
import { AuthSessionRepository } from "../../persistence/Services/AuthSessions.ts";
import { ServerSecretStore } from "../Services/ServerSecretStore.ts";
import { SESSION_COOKIE_NAME } from "../utils.ts";
import {
SessionCredentialError,
SessionCredentialService,
@@ -17,7 +17,6 @@ import {
import {
base64UrlDecodeUtf8,
base64UrlEncode,
resolveSessionCookieName,
signPayload,
timingSafeEqualBase64Url,
} from "../utils.ts";
@@ -82,16 +81,11 @@ function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthCli
}
export const makeSessionCredentialService = Effect.gen(function* () {
const serverConfig = yield* ServerConfig;
const secretStore = yield* ServerSecretStore;
const authSessions = yield* AuthSessionRepository;
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
const cookieName = resolveSessionCookieName({
mode: serverConfig.mode,
port: serverConfig.port,
});
const toSessionCredentialError = (message: string) => (cause: unknown) =>
new SessionCredentialError({
@@ -194,7 +188,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {
const issue: SessionCredentialServiceShape["issue"] = (input) =>
Effect.gen(function* () {
const sessionId = AuthSessionId.make(crypto.randomUUID());
const sessionId = AuthSessionId.makeUnsafe(crypto.randomUUID());
const issuedAt = yield* DateTime.now;
const expiresAt = DateTime.add(issuedAt, {
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
@@ -478,7 +472,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {
}).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke other sessions.")));
return {
cookieName,
cookieName: SESSION_COOKIE_NAME,
issue,
verify,
issueWebSocketToken,
@@ -4,7 +4,7 @@ import type {
AuthPairingLink,
AuthSessionId,
} from "@t3tools/contracts";
import { Data, DateTime, Duration, Effect, Context } from "effect";
import { Data, DateTime, Duration, Effect, ServiceMap } from "effect";
import { SessionRole } from "./SessionCredentialService";
export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
@@ -64,6 +64,6 @@ export interface AuthControlPlaneShape {
) => Effect.Effect<number, AuthControlPlaneError>;
}
export class AuthControlPlane extends Context.Service<AuthControlPlane, AuthControlPlaneShape>()(
export class AuthControlPlane extends ServiceMap.Service<AuthControlPlane, AuthControlPlaneShape>()(
"t3/AuthControlPlane",
) {}
@@ -1,5 +1,5 @@
import type { AuthPairingLink, ServerAuthBootstrapMethod } from "@t3tools/contracts";
import { Data, DateTime, Duration, Context } from "effect";
import { Data, DateTime, Duration, ServiceMap } from "effect";
import type { Effect, Stream } from "effect";
export type BootstrapCredentialRole = "owner" | "client";
@@ -51,7 +51,7 @@ export interface BootstrapCredentialServiceShape {
readonly consume: (credential: string) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
}
export class BootstrapCredentialService extends Context.Service<
export class BootstrapCredentialService extends ServiceMap.Service<
BootstrapCredentialService,
BootstrapCredentialServiceShape
>()("t3/auth/Services/BootstrapCredentialService") {}
+2 -2
View File
@@ -12,7 +12,7 @@ import type {
ServerAuthSessionMethod,
AuthWebSocketTokenResult,
} from "@t3tools/contracts";
import { Data, DateTime, Context } from "effect";
import { Data, DateTime, ServiceMap } from "effect";
import type { Effect } from "effect";
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import type { SessionRole } from "./SessionCredentialService.ts";
@@ -79,6 +79,6 @@ export interface ServerAuthShape {
readonly issueStartupPairingUrl: (baseUrl: string) => Effect.Effect<string, AuthError>;
}
export class ServerAuth extends Context.Service<ServerAuth, ServerAuthShape>()(
export class ServerAuth extends ServiceMap.Service<ServerAuth, ServerAuthShape>()(
"t3/auth/Services/ServerAuth",
) {}
@@ -1,11 +1,11 @@
import type { ServerAuthDescriptor } from "@t3tools/contracts";
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
export interface ServerAuthPolicyShape {
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
}
export class ServerAuthPolicy extends Context.Service<ServerAuthPolicy, ServerAuthPolicyShape>()(
export class ServerAuthPolicy extends ServiceMap.Service<ServerAuthPolicy, ServerAuthPolicyShape>()(
"t3/auth/Services/ServerAuthPolicy",
) {}
@@ -1,4 +1,4 @@
import { Data, Context } from "effect";
import { Data, ServiceMap } from "effect";
import type { Effect } from "effect";
export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{
@@ -16,6 +16,7 @@ export interface ServerSecretStoreShape {
readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
}
export class ServerSecretStore extends Context.Service<ServerSecretStore, ServerSecretStoreShape>()(
"t3/auth/Services/ServerSecretStore",
) {}
export class ServerSecretStore extends ServiceMap.Service<
ServerSecretStore,
ServerSecretStoreShape
>()("t3/auth/Services/ServerSecretStore") {}
@@ -4,7 +4,7 @@ import type {
AuthSessionId,
ServerAuthSessionMethod,
} from "@t3tools/contracts";
import { Data, DateTime, Duration, Context } from "effect";
import { Data, DateTime, Duration, ServiceMap } from "effect";
import type { Effect, Stream } from "effect";
export type SessionRole = "owner" | "client";
@@ -81,7 +81,7 @@ export interface SessionCredentialServiceShape {
readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
}
export class SessionCredentialService extends Context.Service<
export class SessionCredentialService extends ServiceMap.Service<
SessionCredentialService,
SessionCredentialServiceShape
>()("t3/auth/Services/SessionCredentialService") {}
+1 -12
View File
@@ -2,18 +2,7 @@ import type { AuthClientMetadata, AuthClientMetadataDeviceType } from "@t3tools/
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as Crypto from "node:crypto";
const SESSION_COOKIE_NAME = "t3_session";
export function resolveSessionCookieName(input: {
readonly mode: "web" | "desktop";
readonly port: number;
}): string {
if (input.mode !== "desktop") {
return SESSION_COOKIE_NAME;
}
return `${SESSION_COOKIE_NAME}_${input.port}`;
}
export const SESSION_COOKIE_NAME = "t3_session";
export function base64UrlEncode(input: string | Uint8Array): string {
const buffer = typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.from(input);
@@ -26,7 +26,7 @@ function makeThreadCheckpointContext(input: {
worktreePath: input.worktreePath,
checkpoints: [
{
turnId: TurnId.make("turn-1"),
turnId: TurnId.makeUnsafe("turn-1"),
checkpointTurnCount: input.checkpointTurnCount,
checkpointRef: input.checkpointRef,
status: "ready",
@@ -40,8 +40,8 @@ function makeThreadCheckpointContext(input: {
describe("CheckpointDiffQueryLive", () => {
it("computes diffs using canonical turn-0 checkpoint refs", async () => {
const projectId = ProjectId.make("project-1");
const threadId = ThreadId.make("thread-1");
const projectId = ProjectId.makeUnsafe("project-1");
const threadId = ThreadId.makeUnsafe("thread-1");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
const hasCheckpointRefCalls: Array<CheckpointRef> = [];
const diffCheckpointsCalls: Array<{
@@ -119,7 +119,7 @@ describe("CheckpointDiffQueryLive", () => {
});
it("fails when the thread is missing from the snapshot", async () => {
const threadId = ThreadId.make("thread-missing");
const threadId = ThreadId.makeUnsafe("thread-missing");
const checkpointStore: CheckpointStoreShape = {
isGitRepository: () => Effect.succeed(true),
@@ -93,7 +93,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const checkpointStore = yield* CheckpointStore;
const threadId = ThreadId.make("thread-checkpoint-store");
const threadId = ThreadId.makeUnsafe("thread-checkpoint-store");
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
@@ -12,7 +12,7 @@ import type {
OrchestrationGetTurnDiffInput,
OrchestrationGetTurnDiffResult,
} from "@t3tools/contracts";
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { CheckpointServiceError } from "../Errors.ts";
@@ -43,7 +43,7 @@ export interface CheckpointDiffQueryShape {
/**
* CheckpointDiffQuery - Service tag for checkpoint diff queries.
*/
export class CheckpointDiffQuery extends Context.Service<
export class CheckpointDiffQuery extends ServiceMap.Service<
CheckpointDiffQuery,
CheckpointDiffQueryShape
>()("t3/checkpointing/Services/CheckpointDiffQuery") {}
@@ -5,12 +5,12 @@
* workspace thread timeline. It does not store user-facing checkpoint metadata
* and does not coordinate provider conversation rollback.
*
* Uses Effect `Context.Service` for dependency injection and exposes typed
* Uses Effect `ServiceMap.Service` for dependency injection and exposes typed
* domain errors for checkpoint storage operations.
*
* @module CheckpointStore
*/
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { CheckpointStoreError } from "../Errors.ts";
@@ -95,6 +95,6 @@ export interface CheckpointStoreShape {
/**
* CheckpointStore - Service tag for checkpoint persistence and restore operations.
*/
export class CheckpointStore extends Context.Service<CheckpointStore, CheckpointStoreShape>()(
export class CheckpointStore extends ServiceMap.Service<CheckpointStore, CheckpointStoreShape>()(
"t3/checkpointing/Services/CheckpointStore",
) {}
+1 -1
View File
@@ -4,7 +4,7 @@ import { CheckpointRef, ProjectId, type ThreadId } from "@t3tools/contracts";
export const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
export function checkpointRefForThreadTurn(threadId: ThreadId, turnCount: number): CheckpointRef {
return CheckpointRef.make(
return CheckpointRef.makeUnsafe(
`${CHECKPOINT_REFS_PREFIX}/${Encoding.encodeBase64Url(threadId)}/turn/${turnCount}`,
);
}
-63
View File
@@ -153,69 +153,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
}),
);
it.effect("preserves explicit false CLI boolean flags over env and bootstrap values", () =>
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = join(os.tmpdir(), "t3-cli-config-false-flags");
const fd = yield* openBootstrapFd({
noBrowser: true,
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
});
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
const resolved = yield* resolveServerConfig(
{
mode: Option.some("web"),
port: Option.some(8788),
host: Option.some("127.0.0.1"),
baseDir: Option.some(baseDir),
cwd: Option.none(),
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
noBrowser: Option.some(false),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.some(false),
logWebSocketEvents: Option.some(false),
},
Option.none(),
).pipe(
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
T3CODE_BOOTSTRAP_FD: String(fd),
T3CODE_NO_BROWSER: "true",
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
T3CODE_LOG_WS_EVENTS: "true",
},
}),
),
NetService.layer,
),
),
);
expect(resolved).toEqual({
logLevel: "Info",
...defaultObservabilityConfig,
mode: "web",
port: 8788,
cwd: process.cwd(),
baseDir,
...derivedPaths,
host: "127.0.0.1",
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:4173"),
noBrowser: false,
startupPresentation: "browser",
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
});
}),
);
it.effect("uses bootstrap envelope values as fallbacks when flags and env are absent", () =>
Effect.gen(function* () {
const { join } = yield* Path.Path;
-4
View File
@@ -152,10 +152,6 @@ it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
runCliWithRuntime(["--log-level", "debug", "--version"]),
);
it.effect("accepts canonical --no-<flag> boolean negation", () =>
runCliWithRuntime(["--no-log-websocket-events", "--version"]),
);
it.effect("rejects invalid log-level casing before launching the server", () =>
Effect.gen(function* () {
const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip);
+68 -37
View File
@@ -193,6 +193,9 @@ interface CliAuthLocationFlags {
readonly devUrl?: Option.Option<URL>;
}
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
const resolveOptionPrecedence = <Value>(
...values: ReadonlyArray<Option.Option<Value>>
): Option.Option<Value> => Option.firstSomeOf(values);
@@ -238,13 +241,12 @@ export const resolveServerConfig = (
bootstrapFd !== undefined
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
: Option.none();
const bootstrap = Option.getOrUndefined(bootstrapEnvelope);
const mode: RuntimeMode = Option.getOrElse(
resolveOptionPrecedence(
normalizedFlags.mode,
Option.fromUndefinedOr(env.mode),
Option.fromUndefinedOr(bootstrap?.mode),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.mode)),
),
() => "web",
);
@@ -253,7 +255,7 @@ export const resolveServerConfig = (
resolveOptionPrecedence(
normalizedFlags.port,
Option.fromUndefinedOr(env.port),
Option.fromUndefinedOr(bootstrap?.port),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.port)),
),
{
onSome: (value) => Effect.succeed(value),
@@ -269,7 +271,7 @@ export const resolveServerConfig = (
resolveOptionPrecedence(
normalizedFlags.devUrl,
Option.fromUndefinedOr(env.devUrl),
Option.fromUndefinedOr(bootstrap?.devUrl),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.devUrl)),
),
() => undefined,
);
@@ -278,7 +280,9 @@ export const resolveServerConfig = (
resolveOptionPrecedence(
normalizedFlags.baseDir,
Option.fromUndefinedOr(env.t3Home),
Option.fromUndefinedOr(bootstrap?.t3Home),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.t3Home),
),
),
),
);
@@ -293,41 +297,60 @@ export const resolveServerConfig = (
const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
const startupPresentation = options?.startupPresentation ?? "browser";
const isHeadlessStartup = startupPresentation === "headless";
const noBrowser = Option.getOrElse(
resolveOptionPrecedence(
isHeadlessStartup ? Option.some(true) : Option.none(),
normalizedFlags.noBrowser,
Option.fromUndefinedOr(env.noBrowser),
Option.fromUndefinedOr(bootstrap?.noBrowser),
const noBrowser =
startupPresentation === "headless"
? true
: resolveBooleanFlag(
normalizedFlags.noBrowser,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.noBrowser),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.noBrowser),
),
),
() => mode === "desktop",
),
);
const desktopBootstrapToken = Option.getOrUndefined(
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.desktopBootstrapToken),
),
() => mode === "desktop",
);
const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
const autoBootstrapProjectFromCwd = Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
isHeadlessStartup ? Option.some(false) : Option.none(),
normalizedFlags.autoBootstrapProjectFromCwd,
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
Option.fromUndefinedOr(bootstrap?.autoBootstrapProjectFromCwd),
const autoBootstrapProjectFromCwd =
options?.forceAutoBootstrapProjectFromCwd ??
(startupPresentation === "headless"
? false
: resolveBooleanFlag(
normalizedFlags.autoBootstrapProjectFromCwd,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
),
),
() => mode === "web",
),
));
const logWebSocketEvents = resolveBooleanFlag(
normalizedFlags.logWebSocketEvents,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.logWebSocketEvents),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.logWebSocketEvents),
),
),
() => Boolean(devUrl),
),
() => mode === "web",
);
const logWebSocketEvents = Option.getOrElse(
resolveOptionPrecedence(
normalizedFlags.logWebSocketEvents,
Option.fromUndefinedOr(env.logWebSocketEvents),
Option.fromUndefinedOr(bootstrap?.logWebSocketEvents),
),
() => Boolean(devUrl),
);
const staticDir = devUrl ? undefined : yield* resolveStaticDir();
const host = Option.getOrElse(
resolveOptionPrecedence(
normalizedFlags.host,
Option.fromUndefinedOr(env.host),
Option.fromUndefinedOr(bootstrap?.host),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
),
() => (mode === "desktop" ? "127.0.0.1" : undefined),
);
@@ -342,11 +365,19 @@ export const resolveServerConfig = (
traceMaxFiles: env.traceMaxFiles,
otlpTracesUrl:
env.otlpTracesUrl ??
bootstrap?.otlpTracesUrl ??
Option.getOrUndefined(
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.otlpTracesUrl),
),
) ??
persistedObservabilitySettings.otlpTracesUrl,
otlpMetricsUrl:
env.otlpMetricsUrl ??
bootstrap?.otlpMetricsUrl ??
Option.getOrUndefined(
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.otlpMetricsUrl),
),
) ??
persistedObservabilitySettings.otlpMetricsUrl,
otlpExportIntervalMs: env.otlpExportIntervalMs,
otlpServiceName: env.otlpServiceName,
@@ -999,10 +1030,10 @@ const projectAddCommand = Command.make("add", {
}
const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
const projectId = ProjectId.make(crypto.randomUUID());
const projectId = ProjectId.makeUnsafe(crypto.randomUUID());
yield* dispatch({
type: "project.create",
commandId: CommandId.make(crypto.randomUUID()),
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
projectId,
title,
workspaceRoot,
@@ -1040,7 +1071,7 @@ const projectRemoveCommand = Command.make("remove", {
});
yield* dispatch({
type: "project.delete",
commandId: CommandId.make(crypto.randomUUID()),
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
projectId: project.id,
});
return `Removed project ${project.id} (${project.title}).`;
@@ -1080,7 +1111,7 @@ const projectRenameCommand = Command.make("rename", {
yield* dispatch({
type: "project.meta.update",
commandId: CommandId.make(crypto.randomUUID()),
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
projectId: project.id,
title: nextTitle,
});
@@ -17,7 +17,7 @@ import {
resolveCodexModelForAccount,
} from "./codexAppServerManager";
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
function createSendTurnHarness() {
const manager = new CodexAppServerManager();
@@ -111,9 +111,9 @@ function createPendingUserInputHarness() {
},
pendingUserInputs: new Map([
[
ApprovalRequestId.make("req-user-input-1"),
ApprovalRequestId.makeUnsafe("req-user-input-1"),
{
requestId: ApprovalRequestId.make("req-user-input-1"),
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
jsonRpcId: 42,
threadId: asThreadId("thread_1"),
},
@@ -743,7 +743,7 @@ describe("respondToUserInput", () => {
await manager.respondToUserInput(
asThreadId("thread_1"),
ApprovalRequestId.make("req-user-input-1"),
ApprovalRequestId.makeUnsafe("req-user-input-1"),
{
scope: "All request methods",
compat: "Keep current envelope",
@@ -780,7 +780,7 @@ describe("respondToUserInput", () => {
await manager.respondToUserInput(
asThreadId("thread_1"),
ApprovalRequestId.make("req-user-input-1"),
ApprovalRequestId.makeUnsafe("req-user-input-1"),
{
scope: [],
},
+16 -71
View File
@@ -19,7 +19,7 @@ import {
ProviderInteractionMode,
} from "@t3tools/contracts";
import { normalizeModelSlug } from "@t3tools/shared/model";
import { Effect, Context } from "effect";
import { Effect, ServiceMap } from "effect";
import {
formatCodexCliUpgradeMessage,
@@ -138,7 +138,6 @@ export interface CodexThreadSnapshot {
}
const CODEX_VERSION_CHECK_TIMEOUT_MS = 4_000;
const CODEX_THREAD_COMPACTION_TIMEOUT_MS = 60_000;
const ANSI_ESCAPE_CHAR = String.fromCharCode(27);
const ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\[[0-9;]*m`, "g");
@@ -440,7 +439,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
private readonly sessions = new Map<ThreadId, CodexSessionContext>();
private runPromise: (effect: Effect.Effect<unknown, never>) => Promise<unknown>;
constructor(services?: Context.Context<never>) {
constructor(services?: ServiceMap.ServiceMap<never>) {
super();
this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise;
}
@@ -641,7 +640,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
this.stopSession(threadId);
} else {
this.emitEvent({
id: EventId.make(randomUUID()),
id: EventId.makeUnsafe(randomUUID()),
kind: "error",
provider: "codex",
threadId,
@@ -740,7 +739,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
if (!turnIdRaw) {
throw new Error("turn/start response did not include a turn id.");
}
const turnId = TurnId.make(turnIdRaw);
const turnId = TurnId.makeUnsafe(turnIdRaw);
this.updateSession(context, {
status: "running",
@@ -796,60 +795,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
return this.parseThreadSnapshot("thread/read", response);
}
async compactThread(threadId: ThreadId): Promise<CodexThreadSnapshot> {
const context = this.requireSession(threadId);
const providerThreadId = readResumeThreadId({
threadId: context.session.threadId,
runtimeMode: context.session.runtimeMode,
resumeCursor: context.session.resumeCursor,
});
if (!providerThreadId) {
throw new Error("Session is missing a provider resume thread id.");
}
const compactionWait = {
cleanup: () => undefined,
};
const waitForCompaction = new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
compactionWait.cleanup();
reject(new Error("Timed out waiting for Codex thread compaction."));
}, CODEX_THREAD_COMPACTION_TIMEOUT_MS);
const onEvent = (event: ProviderEvent) => {
if (
event.provider !== "codex" ||
event.threadId !== context.session.threadId ||
event.kind !== "notification"
) {
return;
}
if (event.method === "thread/compacted") {
compactionWait.cleanup();
resolve();
}
};
compactionWait.cleanup = () => {
clearTimeout(timeout);
this.off("event", onEvent);
};
this.on("event", onEvent);
});
try {
await this.sendRequest(context, "thread/compact/start", {
threadId: providerThreadId,
});
await waitForCompaction;
} catch (error) {
compactionWait.cleanup();
throw error;
}
return this.readThread(threadId);
}
async rollbackThread(threadId: ThreadId, numTurns: number): Promise<CodexThreadSnapshot> {
const context = this.requireSession(threadId);
const providerThreadId = readResumeThreadId({
@@ -895,7 +840,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
});
this.emitEvent({
id: EventId.make(randomUUID()),
id: EventId.makeUnsafe(randomUUID()),
kind: "notification",
provider: "codex",
threadId: context.session.threadId,
@@ -934,7 +879,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
});
this.emitEvent({
id: EventId.make(randomUUID()),
id: EventId.makeUnsafe(randomUUID()),
kind: "notification",
provider: "codex",
threadId: context.session.threadId,
@@ -1116,7 +1061,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
: undefined;
this.emitEvent({
id: EventId.make(randomUUID()),
id: EventId.makeUnsafe(randomUUID()),
kind: "notification",
provider: "codex",
threadId: context.session.threadId,
@@ -1189,7 +1134,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
const requestKind = this.requestKindForMethod(request.method);
let requestId: ApprovalRequestId | undefined;
if (requestKind) {
requestId = ApprovalRequestId.make(randomUUID());
requestId = ApprovalRequestId.makeUnsafe(randomUUID());
const pendingRequest: PendingApprovalRequest = {
requestId,
jsonRpcId: request.id,
@@ -1208,7 +1153,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (request.method === "item/tool/requestUserInput") {
requestId = ApprovalRequestId.make(randomUUID());
requestId = ApprovalRequestId.makeUnsafe(randomUUID());
context.pendingUserInputs.set(requestId, {
requestId,
jsonRpcId: request.id,
@@ -1219,7 +1164,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
this.emitEvent({
id: EventId.make(randomUUID()),
id: EventId.makeUnsafe(randomUUID()),
kind: "request",
provider: "codex",
threadId: context.session.threadId,
@@ -1309,7 +1254,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
this.emitEvent({
id: EventId.make(randomUUID()),
id: EventId.makeUnsafe(randomUUID()),
kind: "session",
provider: "codex",
threadId: context.session.threadId,
@@ -1321,7 +1266,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
private emitErrorEvent(context: CodexSessionContext, method: string, message: string): void {
this.emitEvent({
id: EventId.make(randomUUID()),
id: EventId.makeUnsafe(randomUUID()),
kind: "error",
provider: "codex",
threadId: context.session.threadId,
@@ -1337,7 +1282,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
message: string,
): void {
this.emitEvent({
id: EventId.make(randomUUID()),
id: EventId.makeUnsafe(randomUUID()),
kind: "notification",
provider: "codex",
threadId: context.session.threadId,
@@ -1396,7 +1341,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
const turns = turnsRaw.map((turnValue, index) => {
const turn = this.readObject(turnValue);
const turnIdRaw = this.readString(turn, "id") ?? `${threadIdRaw}:turn:${index + 1}`;
const turnId = TurnId.make(turnIdRaw);
const turnId = TurnId.makeUnsafe(turnIdRaw);
const items = this.readArray(turn, "items") ?? [];
return {
id: turnId,
@@ -1645,9 +1590,9 @@ function readResumeThreadId(input: {
}
function toTurnId(value: string | undefined): TurnId | undefined {
return brandIfNonEmpty(value, TurnId.make);
return brandIfNonEmpty(value, TurnId.makeUnsafe);
}
function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
return brandIfNonEmpty(value, ProviderItemId.make);
return brandIfNonEmpty(value, ProviderItemId.makeUnsafe);
}
+2 -2
View File
@@ -6,7 +6,7 @@
*
* @module ServerConfig
*/
import { Effect, FileSystem, Layer, LogLevel, Path, Schema, Context } from "effect";
import { Effect, FileSystem, Layer, LogLevel, Path, Schema, ServiceMap } from "effect";
export const DEFAULT_PORT = 3773;
@@ -120,7 +120,7 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server
/**
* ServerConfig - Service tag for server runtime configuration.
*/
export class ServerConfig extends Context.Service<ServerConfig, ServerConfigShape>()(
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
"t3/config/ServerConfig",
) {
static readonly layerTest = (cwd: string, baseDirOrPrefix: string | { prefix: string }) =>
@@ -64,7 +64,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
return generated;
});
const environmentId = EnvironmentId.make(environmentIdRaw);
const environmentId = EnvironmentId.makeUnsafe(environmentIdRaw);
const cwdBaseName = path.basename(serverConfig.cwd).trim();
const label = yield* resolveServerEnvironmentLabel({
cwdBaseName,
@@ -51,13 +51,11 @@ const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
command: string,
args: readonly string[],
) {
const result = yield* Effect.tryPromise({
try: () =>
runProcess(command, args, {
allowNonZeroExit: true,
}),
catch: () => null,
}).pipe(Effect.orElseSucceed(() => null));
const result = yield* Effect.tryPromise(() =>
runProcess(command, args, {
allowNonZeroExit: true,
}),
).pipe(Effect.orElseSucceed(() => null));
if (!result || result.code !== 0) {
return null;
@@ -1,5 +1,5 @@
import type { EnvironmentId, ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
export interface ServerEnvironmentShape {
@@ -7,6 +7,7 @@ export interface ServerEnvironmentShape {
readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;
}
export class ServerEnvironment extends Context.Service<ServerEnvironment, ServerEnvironmentShape>()(
"t3/environment/Services/ServerEnvironment",
) {}
export class ServerEnvironment extends ServiceMap.Service<
ServerEnvironment,
ServerEnvironmentShape
>()("t3/environment/Services/ServerEnvironment") {}
+2 -2
View File
@@ -649,8 +649,8 @@ it.layer(TestLayer)("git integration", (it) => {
it.effect("refreshes upstream behind count after checkout when remote branch advanced", () =>
Effect.gen(function* () {
const context = yield* Effect.context<never>();
const runPromise = Effect.runPromiseWith(context);
const services = yield* Effect.services();
const runPromise = Effect.runPromiseWith(services);
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
+3 -2
View File
@@ -933,8 +933,9 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
return true as const;
});
const statusUpstreamRefreshCache = yield* Cache.makeWith(refreshStatusUpstreamCacheEntry, {
const statusUpstreamRefreshCache = yield* Cache.makeWith({
capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
lookup: refreshStatusUpstreamCacheEntry,
// Keep successful refreshes warm and briefly back off failed refreshes to avoid retry storms.
timeToLive: (exit) =>
Exit.isSuccess(exit)
@@ -2001,7 +2002,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
"GitCore.removeWorktree",
input.cwd,
args,
`${commandLabel(args)} failed (cwd: ${input.cwd}): ${error.message}`,
`${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`,
error,
),
),
+2 -2
View File
@@ -1,4 +1,4 @@
import { Effect, Layer, Schema, SchemaIssue } from "effect";
import { Effect, Layer, Schema } from "effect";
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
import { runProcess } from "../../processRunner";
@@ -154,7 +154,7 @@ function decodeGitHubJson<S extends Schema.Top>(
(error) =>
new GitHubCliError({
operation,
detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
detail: error instanceof Error ? `${invalidDetail}: ${error.message}` : invalidDetail,
cause: error,
}),
),
+4 -2
View File
@@ -731,8 +731,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
workingTree: details.workingTree,
} satisfies GitStatusLocalResult;
});
const localStatusResultCache = yield* Cache.makeWith(readLocalStatus, {
const localStatusResultCache = yield* Cache.makeWith({
capacity: STATUS_RESULT_CACHE_CAPACITY,
lookup: readLocalStatus,
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
});
const invalidateLocalStatusResultCache = (cwd: string) =>
@@ -763,8 +764,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
pr,
} satisfies GitStatusRemoteResult;
});
const remoteStatusResultCache = yield* Cache.makeWith(readRemoteStatus, {
const remoteStatusResultCache = yield* Cache.makeWith({
capacity: STATUS_RESULT_CACHE_CAPACITY,
lookup: readRemoteStatus,
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
});
const invalidateRemoteStatusResultCache = (cwd: string) =>
@@ -9,7 +9,7 @@
*
* @module RoutingTextGeneration
*/
import { Effect, Layer, Context } from "effect";
import { Effect, Layer, ServiceMap } from "effect";
import {
TextGeneration,
@@ -23,11 +23,11 @@ import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
// Internal service tags so both concrete layers can coexist.
// ---------------------------------------------------------------------------
class CodexTextGen extends Context.Service<CodexTextGen, TextGenerationShape>()(
class CodexTextGen extends ServiceMap.Service<CodexTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/CodexTextGen",
) {}
class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>()(
class ClaudeTextGen extends ServiceMap.Service<ClaudeTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
) {}
+4 -2
View File
@@ -6,7 +6,7 @@
*
* @module GitCore
*/
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type {
GitCheckoutInput,
@@ -310,4 +310,6 @@ export interface GitCoreShape {
/**
* GitCore - Service tag for low-level Git repository operations.
*/
export class GitCore extends Context.Service<GitCore, GitCoreShape>()("t3/git/Services/GitCore") {}
export class GitCore extends ServiceMap.Service<GitCore, GitCoreShape>()(
"t3/git/Services/GitCore",
) {}
+2 -2
View File
@@ -5,7 +5,7 @@
*
* @module GitHubCli
*/
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ProcessRunResult } from "../../processRunner";
@@ -98,6 +98,6 @@ export interface GitHubCliShape {
/**
* GitHubCli - Service tag for GitHub CLI process execution.
*/
export class GitHubCli extends Context.Service<GitHubCli, GitHubCliShape>()(
export class GitHubCli extends ServiceMap.Service<GitHubCli, GitHubCliShape>()(
"t3/git/Services/GitHubCli",
) {}
+2 -2
View File
@@ -19,7 +19,7 @@ import {
GitStatusInput,
GitStatusResult,
} from "@t3tools/contracts";
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { GitManagerServiceError } from "@t3tools/contracts";
@@ -99,6 +99,6 @@ export interface GitManagerShape {
/**
* GitManager - Service tag for stacked Git workflow orchestration.
*/
export class GitManager extends Context.Service<GitManager, GitManagerShape>()(
export class GitManager extends ServiceMap.Service<GitManager, GitManagerShape>()(
"t3/git/Services/GitManager",
) {}
@@ -1,4 +1,4 @@
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Effect, Stream } from "effect";
import type {
GitManagerServiceError,
@@ -21,7 +21,7 @@ export interface GitStatusBroadcasterShape {
) => Stream.Stream<GitStatusStreamEvent, GitManagerServiceError>;
}
export class GitStatusBroadcaster extends Context.Service<
export class GitStatusBroadcaster extends ServiceMap.Service<
GitStatusBroadcaster,
GitStatusBroadcasterShape
>()("t3/git/Services/GitStatusBroadcaster") {}
@@ -6,7 +6,7 @@
*
* @module TextGeneration
*/
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
@@ -118,6 +118,6 @@ export interface TextGenerationShape {
/**
* TextGeneration - Service tag for commit and PR text generation.
*/
export class TextGeneration extends Context.Service<TextGeneration, TextGenerationShape>()(
export class TextGeneration extends ServiceMap.Service<TextGeneration, TextGenerationShape>()(
"t3/git/Services/TextGeneration",
) {}
+2 -2
View File
@@ -39,7 +39,7 @@ import {
SchemaIssue,
SchemaTransformation,
Ref,
Context,
ServiceMap,
Scope,
Stream,
} from "effect";
@@ -521,7 +521,7 @@ export interface KeybindingsShape {
/**
* Keybindings - Service tag for keybinding configuration operations.
*/
export class Keybindings extends Context.Service<Keybindings, KeybindingsShape>()(
export class Keybindings extends ServiceMap.Service<Keybindings, KeybindingsShape>()(
"t3/keybindings",
) {}
@@ -1,4 +1,4 @@
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { TraceRecord } from "../TraceRecord.ts";
@@ -7,7 +7,7 @@ export interface BrowserTraceCollectorShape {
readonly record: (records: ReadonlyArray<TraceRecord>) => Effect.Effect<void>;
}
export class BrowserTraceCollector extends Context.Service<
export class BrowserTraceCollector extends ServiceMap.Service<
BrowserTraceCollector,
BrowserTraceCollectorShape
>()("t3/observability/Services/BrowserTraceCollector") {}
+2 -2
View File
@@ -11,7 +11,7 @@ import { accessSync, constants, statSync } from "node:fs";
import { extname, join } from "node:path";
import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
import { Context, Effect, Layer } from "effect";
import { ServiceMap, Effect, Layer } from "effect";
// ==============================
// Definitions
@@ -247,7 +247,7 @@ export interface OpenShape {
/**
* Open - Service tag for browser/editor launch operations.
*/
export class Open extends Context.Service<Open, OpenShape>()("t3/open") {}
export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
// ==============================
// Implementations
@@ -44,8 +44,8 @@ import { ServerConfig } from "../../config.ts";
import { WorkspaceEntriesLive } from "../../workspace/Layers/WorkspaceEntries.ts";
import { WorkspacePathsLive } from "../../workspace/Layers/WorkspacePaths.ts";
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asTurnId = (value: string): TurnId => TurnId.make(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
@@ -81,7 +81,7 @@ function createProviderServiceHarness(
provider: providerName,
status: "ready",
runtimeMode: "full-access",
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
cwd: sessionCwd,
createdAt: now,
updatedAt: now,
@@ -95,10 +95,8 @@ function createProviderServiceHarness(
respondToRequest: () => unsupported(),
respondToUserInput: () => unsupported(),
stopSession: () => unsupported(),
stopSessionForProvider: () => unsupported(),
listSessions,
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
compactThread: () => unsupported(),
rollbackConversation,
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
@@ -132,7 +130,7 @@ async function waitForThread(
activities: ReadonlyArray<{ kind: string }>;
}> => {
const readModel = await Effect.runPromise(engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
if (thread && predicate(thread)) {
return thread;
}
@@ -312,7 +310,7 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
engine.dispatch({
type: "project.create",
commandId: CommandId.make("cmd-project-create"),
commandId: CommandId.makeUnsafe("cmd-project-create"),
projectId: asProjectId("project-1"),
title: "Test Project",
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
@@ -326,8 +324,8 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-thread-create"),
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
@@ -346,21 +344,21 @@ describe("CheckpointReactor", () => {
await runtime.runPromise(
checkpointStore.captureCheckpoint({
cwd,
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
}),
);
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
await runtime.runPromise(
checkpointStore.captureCheckpoint({
cwd,
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
}),
);
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
await runtime.runPromise(
checkpointStore.captureCheckpoint({
cwd,
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2),
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
}),
);
}
@@ -380,10 +378,10 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-capture"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set-capture"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
@@ -397,26 +395,26 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.started",
eventId: EventId.make("evt-turn-started-1"),
eventId: EventId.makeUnsafe("evt-turn-started-1"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
});
await waitForGitRefExists(
harness.cwd,
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
);
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-1"),
eventId: EventId.makeUnsafe("evt-turn-completed-1"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
payload: { state: "completed" },
});
@@ -428,22 +426,22 @@ describe("CheckpointReactor", () => {
);
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
expect(
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0)),
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0)),
).toBe(true);
expect(
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)),
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
).toBe(true);
expect(
gitShowFileAtRef(
harness.cwd,
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
"README.md",
),
).toBe("v1\n");
expect(
gitShowFileAtRef(
harness.cwd,
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
"README.md",
),
).toBe("v2\n");
@@ -458,10 +456,10 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-refresh-local-status"),
eventId: EventId.makeUnsafe("evt-turn-completed-refresh-local-status"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-refresh-local-status"),
payload: { state: "completed" },
});
@@ -478,10 +476,10 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-primary-running"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set-primary-running"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
runtimeMode: "approval-required",
@@ -495,43 +493,45 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.started",
eventId: EventId.make("evt-turn-started-main"),
eventId: EventId.makeUnsafe("evt-turn-started-main"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-main"),
});
await waitForGitRefExists(
harness.cwd,
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
);
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-aux"),
eventId: EventId.makeUnsafe("evt-turn-completed-aux"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-aux"),
payload: { state: "completed" },
});
await harness.drain();
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const midThread = midReadModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
expect(midThread?.checkpoints).toHaveLength(0);
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-main"),
eventId: EventId.makeUnsafe("evt-turn-completed-main"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-main"),
payload: { state: "completed" },
});
@@ -553,10 +553,10 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-capture-claude"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set-capture-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeAgent",
runtimeMode: "approval-required",
@@ -570,24 +570,24 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.started",
eventId: EventId.make("evt-turn-started-claude-1"),
eventId: EventId.makeUnsafe("evt-turn-started-claude-1"),
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-1"),
});
await waitForGitRefExists(
harness.cwd,
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
);
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-claude-1"),
eventId: EventId.makeUnsafe("evt-turn-completed-claude-1"),
provider: "claudeAgent",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-1"),
payload: { state: "completed" },
});
@@ -600,7 +600,7 @@ describe("CheckpointReactor", () => {
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
expect(
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)),
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
).toBe(true);
});
@@ -611,10 +611,10 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-missing-baseline-diff"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set-missing-baseline-diff"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
@@ -628,11 +628,11 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-missing-baseline"),
eventId: EventId.makeUnsafe("evt-turn-completed-missing-baseline"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-missing-baseline"),
payload: { state: "completed" },
});
@@ -661,10 +661,10 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-for-baseline"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-for-baseline"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: MessageId.make("message-user-1"),
messageId: MessageId.makeUnsafe("message-user-1"),
role: "user",
text: "start turn",
attachments: [],
@@ -677,12 +677,12 @@ describe("CheckpointReactor", () => {
await waitForGitRefExists(
harness.cwd,
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
);
expect(
gitShowFileAtRef(
harness.cwd,
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
"README.md",
),
).toBe("v1\n");
@@ -699,10 +699,10 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-missing-provider-cwd"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set-missing-provider-cwd"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
runtimeMode: "approval-required",
@@ -717,23 +717,23 @@ describe("CheckpointReactor", () => {
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-missing-provider-cwd"),
eventId: EventId.makeUnsafe("evt-turn-completed-missing-provider-cwd"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-missing-cwd"),
payload: { state: "completed" },
});
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
expect(
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)),
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
).toBe(true);
expect(
gitShowFileAtRef(
harness.cwd,
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
"README.md",
),
).toBe("v2\n");
@@ -746,10 +746,10 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-checkpoint-captured"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set-checkpoint-captured"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
@@ -763,11 +763,11 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "checkpoint.captured",
eventId: EventId.make("evt-checkpoint-captured-3"),
eventId: EventId.makeUnsafe("evt-checkpoint-captured-3"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-3"),
turnCount: 3,
status: "completed",
@@ -775,7 +775,7 @@ describe("CheckpointReactor", () => {
await harness.drain();
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(
false,
);
@@ -796,10 +796,10 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-non-repo-runtime"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set-non-repo-runtime"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
@@ -813,31 +813,31 @@ describe("CheckpointReactor", () => {
harness.provider.emit({
type: "turn.completed",
eventId: EventId.make("evt-runtime-capture-failure"),
eventId: EventId.makeUnsafe("evt-runtime-capture-failure"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-runtime-failure"),
payload: { state: "completed" },
});
harness.provider.emit({
type: "turn.started",
eventId: EventId.make("evt-turn-started-after-runtime-failure"),
eventId: EventId.makeUnsafe("evt-turn-started-after-runtime-failure"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-after-runtime-failure"),
});
await waitForGitRefExists(
harness.cwd,
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
);
expect(
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0)),
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0)),
).toBe(true);
});
@@ -848,10 +848,10 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
@@ -866,11 +866,11 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.diff.complete",
commandId: CommandId.make("cmd-diff-1"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-diff-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
completedAt: createdAt,
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
status: "ready",
files: [],
checkpointTurnCount: 1,
@@ -880,11 +880,11 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.diff.complete",
commandId: CommandId.make("cmd-diff-2"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-diff-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-2"),
completedAt: createdAt,
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2),
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
status: "ready",
files: [],
checkpointTurnCount: 2,
@@ -895,8 +895,8 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.make("cmd-revert-request"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-revert-request"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnCount: 1,
createdAt,
}),
@@ -910,12 +910,12 @@ describe("CheckpointReactor", () => {
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
numTurns: 1,
});
expect(fs.readFileSync(path.join(harness.cwd, "README.md"), "utf8")).toBe("v2\n");
expect(
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2)),
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2)),
).toBe(false);
});
@@ -926,10 +926,10 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-claude"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeAgent",
runtimeMode: "approval-required",
@@ -944,11 +944,11 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.diff.complete",
commandId: CommandId.make("cmd-diff-claude-1"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-diff-claude-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-1"),
completedAt: createdAt,
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
status: "ready",
files: [],
checkpointTurnCount: 1,
@@ -958,11 +958,11 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.diff.complete",
commandId: CommandId.make("cmd-diff-claude-2"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-diff-claude-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-claude-2"),
completedAt: createdAt,
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2),
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
status: "ready",
files: [],
checkpointTurnCount: 2,
@@ -973,8 +973,8 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.make("cmd-revert-request-claude"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-revert-request-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnCount: 1,
createdAt,
}),
@@ -983,7 +983,7 @@ describe("CheckpointReactor", () => {
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
numTurns: 1,
});
});
@@ -995,10 +995,10 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-inline-revert"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set-inline-revert"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
@@ -1013,11 +1013,11 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.diff.complete",
commandId: CommandId.make("cmd-inline-revert-diff-1"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-inline-revert-diff-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
completedAt: createdAt,
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
status: "ready",
files: [],
checkpointTurnCount: 1,
@@ -1027,11 +1027,11 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.diff.complete",
commandId: CommandId.make("cmd-inline-revert-diff-2"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-inline-revert-diff-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-2"),
completedAt: createdAt,
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2),
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
status: "ready",
files: [],
checkpointTurnCount: 2,
@@ -1042,8 +1042,8 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.make("cmd-sequenced-revert-request-1"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-sequenced-revert-request-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnCount: 1,
createdAt,
}),
@@ -1051,8 +1051,8 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.make("cmd-sequenced-revert-request-0"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-sequenced-revert-request-0"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnCount: 0,
createdAt,
}),
@@ -1062,11 +1062,11 @@ describe("CheckpointReactor", () => {
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(2);
expect(harness.provider.rollbackConversation.mock.calls[0]?.[0]).toEqual({
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
numTurns: 1,
});
expect(harness.provider.rollbackConversation.mock.calls[1]?.[0]).toEqual({
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
numTurns: 1,
});
});
@@ -1078,8 +1078,8 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.make("cmd-revert-no-session"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-revert-no-session"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnCount: 1,
createdAt,
}),
@@ -38,7 +38,7 @@ type ReactorInput =
};
function toTurnId(value: string | undefined): TurnId | null {
return value === undefined ? null : TurnId.make(String(value));
return value === undefined ? null : TurnId.makeUnsafe(String(value));
}
function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
@@ -62,7 +62,7 @@ function checkpointStatusFromRuntime(status: string | undefined): "ready" | "mis
}
const serverCommandId = (tag: string): CommandId =>
CommandId.make(`server:${tag}:${crypto.randomUUID()}`);
CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`);
const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
@@ -83,7 +83,7 @@ const make = Effect.gen(function* () {
commandId: serverCommandId("checkpoint-revert-failure"),
threadId: input.threadId,
activity: {
id: EventId.make(crypto.randomUUID()),
id: EventId.makeUnsafe(crypto.randomUUID()),
tone: "error",
kind: "checkpoint.revert.failed",
summary: "Checkpoint revert failed",
@@ -108,7 +108,7 @@ const make = Effect.gen(function* () {
commandId: serverCommandId("checkpoint-capture-failure"),
threadId: input.threadId,
activity: {
id: EventId.make(crypto.randomUUID()),
id: EventId.makeUnsafe(crypto.randomUUID()),
tone: "error",
kind: "checkpoint.capture.failed",
summary: "Checkpoint capture failed",
@@ -270,7 +270,7 @@ const make = Effect.gen(function* () {
input.thread.messages
.toReversed()
.find((entry) => entry.role === "assistant" && entry.turnId === input.turnId)?.id ??
MessageId.make(`assistant:${input.turnId}`);
MessageId.makeUnsafe(`assistant:${input.turnId}`);
yield* orchestrationEngine.dispatch({
type: "thread.turn.diff.complete",
@@ -307,7 +307,7 @@ const make = Effect.gen(function* () {
commandId: serverCommandId("checkpoint-captured-activity"),
threadId: input.threadId,
activity: {
id: EventId.make(crypto.randomUUID()),
id: EventId.makeUnsafe(crypto.randomUUID()),
tone: "info",
kind: "checkpoint.captured",
summary: "Checkpoint captured",
@@ -32,10 +32,10 @@ import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"
import { ServerConfig } from "../../config.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asMessageId = (value: string): MessageId => MessageId.make(value);
const asTurnId = (value: string): TurnId => TurnId.make(value);
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
async function createOrchestrationSystem() {
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
@@ -115,7 +115,7 @@ describe("OrchestrationEngine", () => {
],
threads: [
{
id: ThreadId.make("thread-bootstrap"),
id: ThreadId.makeUnsafe("thread-bootstrap"),
projectId: asProjectId("project-bootstrap"),
title: "Bootstrap Thread",
modelSelection: {
@@ -183,7 +183,7 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "project.create",
commandId: CommandId.make("cmd-project-1-create"),
commandId: CommandId.makeUnsafe("cmd-project-1-create"),
projectId: asProjectId("project-1"),
title: "Project 1",
workspaceRoot: "/tmp/project-1",
@@ -197,8 +197,8 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-1-create"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-thread-1-create"),
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
@@ -215,8 +215,8 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-1"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("msg-1"),
role: "user",
@@ -243,7 +243,7 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "project.create",
commandId: CommandId.make("cmd-project-archive-create"),
commandId: CommandId.makeUnsafe("cmd-project-archive-create"),
projectId: asProjectId("project-archive"),
title: "Project Archive",
workspaceRoot: "/tmp/project-archive",
@@ -257,8 +257,8 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-archive-create"),
threadId: ThreadId.make("thread-archive"),
commandId: CommandId.makeUnsafe("cmd-thread-archive-create"),
threadId: ThreadId.makeUnsafe("thread-archive"),
projectId: asProjectId("project-archive"),
title: "Archive me",
modelSelection: {
@@ -276,8 +276,8 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "thread.archive",
commandId: CommandId.make("cmd-thread-archive"),
threadId: ThreadId.make("thread-archive"),
commandId: CommandId.makeUnsafe("cmd-thread-archive"),
threadId: ThreadId.makeUnsafe("thread-archive"),
}),
);
expect(
@@ -289,8 +289,8 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "thread.unarchive",
commandId: CommandId.make("cmd-thread-unarchive"),
threadId: ThreadId.make("thread-archive"),
commandId: CommandId.makeUnsafe("cmd-thread-unarchive"),
threadId: ThreadId.makeUnsafe("thread-archive"),
}),
);
expect(
@@ -310,7 +310,7 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "project.create",
commandId: CommandId.make("cmd-project-replay-create"),
commandId: CommandId.makeUnsafe("cmd-project-replay-create"),
projectId: asProjectId("project-replay"),
title: "Replay Project",
workspaceRoot: "/tmp/project-replay",
@@ -324,8 +324,8 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-replay-create"),
threadId: ThreadId.make("thread-replay"),
commandId: CommandId.makeUnsafe("cmd-thread-replay-create"),
threadId: ThreadId.makeUnsafe("thread-replay"),
projectId: asProjectId("project-replay"),
title: "replay",
modelSelection: {
@@ -342,8 +342,8 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "thread.delete",
commandId: CommandId.make("cmd-thread-replay-delete"),
threadId: ThreadId.make("thread-replay"),
commandId: CommandId.makeUnsafe("cmd-thread-replay-delete"),
threadId: ThreadId.makeUnsafe("thread-replay"),
}),
);
@@ -368,7 +368,7 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "project.create",
commandId: CommandId.make("cmd-project-stream-create"),
commandId: CommandId.makeUnsafe("cmd-project-stream-create"),
projectId: asProjectId("project-stream"),
title: "Stream Project",
workspaceRoot: "/tmp/project-stream",
@@ -392,8 +392,8 @@ describe("OrchestrationEngine", () => {
yield* Effect.sleep("10 millis");
yield* engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-stream-thread-create"),
threadId: ThreadId.make("thread-stream"),
commandId: CommandId.makeUnsafe("cmd-stream-thread-create"),
threadId: ThreadId.makeUnsafe("thread-stream"),
projectId: asProjectId("project-stream"),
title: "domain-stream",
modelSelection: {
@@ -408,8 +408,8 @@ describe("OrchestrationEngine", () => {
});
yield* engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("cmd-stream-thread-update"),
threadId: ThreadId.make("thread-stream"),
commandId: CommandId.makeUnsafe("cmd-stream-thread-update"),
threadId: ThreadId.makeUnsafe("thread-stream"),
title: "domain-stream-updated",
});
eventTypes.push((yield* Queue.take(eventQueue)).type);
@@ -429,7 +429,7 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "project.create",
commandId: CommandId.make("cmd-project-ack-create"),
commandId: CommandId.makeUnsafe("cmd-project-ack-create"),
projectId: asProjectId("project-ack"),
title: "Ack Project",
workspaceRoot: "/tmp/project-ack",
@@ -444,8 +444,8 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-ack-create"),
threadId: ThreadId.make("thread-ack"),
commandId: CommandId.makeUnsafe("cmd-thread-ack-create"),
threadId: ThreadId.makeUnsafe("thread-ack"),
projectId: asProjectId("project-ack"),
title: "Ack Thread",
modelSelection: {
@@ -481,8 +481,8 @@ describe("OrchestrationEngine", () => {
system.run(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-missing-project"),
threadId: ThreadId.make("thread-missing-project"),
commandId: CommandId.makeUnsafe("cmd-thread-missing-project"),
threadId: ThreadId.makeUnsafe("thread-missing-project"),
projectId: asProjectId("project-missing"),
title: "Missing Project Thread",
modelSelection: {
@@ -518,7 +518,7 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "project.create",
commandId: CommandId.make("cmd-project-turn-diff-create"),
commandId: CommandId.makeUnsafe("cmd-project-turn-diff-create"),
projectId: asProjectId("project-turn-diff"),
title: "Turn Diff Project",
workspaceRoot: "/tmp/project-turn-diff",
@@ -532,8 +532,8 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-turn-diff-create"),
threadId: ThreadId.make("thread-turn-diff"),
commandId: CommandId.makeUnsafe("cmd-thread-turn-diff-create"),
threadId: ThreadId.makeUnsafe("thread-turn-diff"),
projectId: asProjectId("project-turn-diff"),
title: "Turn diff thread",
modelSelection: {
@@ -550,8 +550,8 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "thread.turn.diff.complete",
commandId: CommandId.make("cmd-turn-diff-complete"),
threadId: ThreadId.make("thread-turn-diff"),
commandId: CommandId.makeUnsafe("cmd-turn-diff-complete"),
threadId: ThreadId.makeUnsafe("thread-turn-diff"),
turnId: asTurnId("turn-1"),
completedAt: createdAt,
checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"),
@@ -590,7 +590,7 @@ describe("OrchestrationEngine", () => {
const flakyStore: OrchestrationEventStoreShape = {
append(event) {
if (shouldFailFirstAppend && event.commandId === CommandId.make("cmd-flaky-1")) {
if (shouldFailFirstAppend && event.commandId === CommandId.makeUnsafe("cmd-flaky-1")) {
shouldFailFirstAppend = false;
return Effect.fail(
new PersistenceSqlError({
@@ -637,7 +637,7 @@ describe("OrchestrationEngine", () => {
await runtime.runPromise(
engine.dispatch({
type: "project.create",
commandId: CommandId.make("cmd-project-flaky-create"),
commandId: CommandId.makeUnsafe("cmd-project-flaky-create"),
projectId: asProjectId("project-flaky"),
title: "Flaky Project",
workspaceRoot: "/tmp/project-flaky",
@@ -653,8 +653,8 @@ describe("OrchestrationEngine", () => {
runtime.runPromise(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-flaky-1"),
threadId: ThreadId.make("thread-flaky-fail"),
commandId: CommandId.makeUnsafe("cmd-flaky-1"),
threadId: ThreadId.makeUnsafe("thread-flaky-fail"),
projectId: asProjectId("project-flaky"),
title: "flaky-fail",
modelSelection: {
@@ -673,8 +673,8 @@ describe("OrchestrationEngine", () => {
const result = await runtime.runPromise(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-flaky-2"),
threadId: ThreadId.make("thread-flaky-ok"),
commandId: CommandId.makeUnsafe("cmd-flaky-2"),
threadId: ThreadId.makeUnsafe("thread-flaky-ok"),
projectId: asProjectId("project-flaky"),
title: "flaky-ok",
modelSelection: {
@@ -701,7 +701,7 @@ describe("OrchestrationEngine", () => {
projectEvent: (event) => {
if (
shouldFailRequestedProjection &&
event.commandId === CommandId.make("cmd-turn-start-atomic") &&
event.commandId === CommandId.makeUnsafe("cmd-turn-start-atomic") &&
event.type === "thread.turn-start-requested"
) {
shouldFailRequestedProjection = false;
@@ -732,7 +732,7 @@ describe("OrchestrationEngine", () => {
await runtime.runPromise(
engine.dispatch({
type: "project.create",
commandId: CommandId.make("cmd-project-atomic-create"),
commandId: CommandId.makeUnsafe("cmd-project-atomic-create"),
projectId: asProjectId("project-atomic"),
title: "Atomic Project",
workspaceRoot: "/tmp/project-atomic",
@@ -746,8 +746,8 @@ describe("OrchestrationEngine", () => {
await runtime.runPromise(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-atomic-create"),
threadId: ThreadId.make("thread-atomic"),
commandId: CommandId.makeUnsafe("cmd-thread-atomic-create"),
threadId: ThreadId.makeUnsafe("thread-atomic"),
projectId: asProjectId("project-atomic"),
title: "atomic",
modelSelection: {
@@ -764,8 +764,8 @@ describe("OrchestrationEngine", () => {
const turnStartCommand = {
type: "thread.turn.start" as const,
commandId: CommandId.make("cmd-turn-start-atomic"),
threadId: ThreadId.make("thread-atomic"),
commandId: CommandId.makeUnsafe("cmd-turn-start-atomic"),
threadId: ThreadId.makeUnsafe("thread-atomic"),
message: {
messageId: asMessageId("msg-atomic-1"),
role: "user" as const,
@@ -845,7 +845,7 @@ describe("OrchestrationEngine", () => {
projectEvent: (event) => {
if (
shouldFailProjection &&
event.commandId === CommandId.make("cmd-thread-meta-sync-fail")
event.commandId === CommandId.makeUnsafe("cmd-thread-meta-sync-fail")
) {
shouldFailProjection = false;
return Effect.fail(
@@ -875,7 +875,7 @@ describe("OrchestrationEngine", () => {
await runtime.runPromise(
engine.dispatch({
type: "project.create",
commandId: CommandId.make("cmd-project-sync-create"),
commandId: CommandId.makeUnsafe("cmd-project-sync-create"),
projectId: asProjectId("project-sync"),
title: "Sync Project",
workspaceRoot: "/tmp/project-sync",
@@ -889,8 +889,8 @@ describe("OrchestrationEngine", () => {
await runtime.runPromise(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-sync-create"),
threadId: ThreadId.make("thread-sync"),
commandId: CommandId.makeUnsafe("cmd-thread-sync-create"),
threadId: ThreadId.makeUnsafe("thread-sync"),
projectId: asProjectId("project-sync"),
title: "sync-before",
modelSelection: {
@@ -909,8 +909,8 @@ describe("OrchestrationEngine", () => {
runtime.runPromise(
engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("cmd-thread-meta-sync-fail"),
threadId: ThreadId.make("thread-sync"),
commandId: CommandId.makeUnsafe("cmd-thread-meta-sync-fail"),
threadId: ThreadId.makeUnsafe("thread-sync"),
title: "sync-after-failed-projection",
}),
),
@@ -934,8 +934,8 @@ describe("OrchestrationEngine", () => {
system.run(
engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-invariant-missing-thread"),
threadId: ThreadId.make("thread-missing"),
commandId: CommandId.makeUnsafe("cmd-invariant-missing-thread"),
threadId: ThreadId.makeUnsafe("thread-missing"),
message: {
messageId: asMessageId("msg-missing"),
role: "user",
@@ -960,7 +960,7 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "project.create",
commandId: CommandId.make("cmd-project-duplicate-create"),
commandId: CommandId.makeUnsafe("cmd-project-duplicate-create"),
projectId: asProjectId("project-duplicate"),
title: "Duplicate Project",
workspaceRoot: "/tmp/project-duplicate",
@@ -975,8 +975,8 @@ describe("OrchestrationEngine", () => {
await system.run(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-duplicate-1"),
threadId: ThreadId.make("thread-duplicate"),
commandId: CommandId.makeUnsafe("cmd-thread-duplicate-1"),
threadId: ThreadId.makeUnsafe("thread-duplicate"),
projectId: asProjectId("project-duplicate"),
title: "duplicate",
modelSelection: {
@@ -995,8 +995,8 @@ describe("OrchestrationEngine", () => {
system.run(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-duplicate-2"),
threadId: ThreadId.make("thread-duplicate"),
commandId: CommandId.makeUnsafe("cmd-thread-duplicate-2"),
threadId: ThreadId.makeUnsafe("thread-duplicate"),
projectId: asProjectId("project-duplicate"),
title: "duplicate",
modelSelection: {
File diff suppressed because it is too large. Load diff
@@ -86,7 +86,7 @@ function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
return null;
}
const requestId = (payload as Record<string, unknown>).requestId;
return typeof requestId === "string" ? ApprovalRequestId.make(requestId) : null;
return typeof requestId === "string" ? ApprovalRequestId.makeUnsafe(requestId) : null;
}
function retainProjectionMessagesAfterRevert(
@@ -9,11 +9,11 @@ import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asTurnId = (value: string): TurnId => TurnId.make(value);
const asMessageId = (value: string): MessageId => MessageId.make(value);
const asEventId = (value: string): EventId => EventId.make(value);
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
const projectionSnapshotLayer = it.layer(
OrchestrationProjectionSnapshotQueryLive.pipe(
@@ -259,7 +259,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
]);
assert.deepEqual(snapshot.threads, [
{
id: ThreadId.make("thread-1"),
id: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread 1",
modelSelection: {
@@ -278,7 +278,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
completedAt: "2026-02-24T00:00:08.000Z",
assistantMessageId: asMessageId("message-1"),
sourceProposedPlan: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
planId: "plan-1",
},
},
@@ -303,7 +303,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
turnId: asTurnId("turn-1"),
planMarkdown: "# Ship it",
implementedAt: "2026-02-24T00:00:05.500Z",
implementationThreadId: ThreadId.make("thread-2"),
implementationThreadId: ThreadId.makeUnsafe("thread-2"),
createdAt: "2026-02-24T00:00:05.000Z",
updatedAt: "2026-02-24T00:00:05.500Z",
},
@@ -331,7 +331,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
},
],
session: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
runtimeMode: "approval-required",
@@ -473,7 +473,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
);
assert.equal(firstThreadId._tag, "Some");
if (firstThreadId._tag === "Some") {
assert.equal(firstThreadId.value, ThreadId.make("thread-first"));
assert.equal(firstThreadId.value, ThreadId.makeUnsafe("thread-first"));
}
}),
);
@@ -596,12 +596,12 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
`;
const context = yield* snapshotQuery.getThreadCheckpointContext(
ThreadId.make("thread-context"),
ThreadId.makeUnsafe("thread-context"),
);
assert.equal(context._tag, "Some");
if (context._tag === "Some") {
assert.deepEqual(context.value, {
threadId: ThreadId.make("thread-context"),
threadId: ThreadId.makeUnsafe("thread-context"),
projectId: asProjectId("project-context"),
workspaceRoot: "/tmp/context-workspace",
worktreePath: "/tmp/context-worktree",
@@ -38,10 +38,11 @@ import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ServerSettingsService } from "../../serverSettings.ts";
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
const asMessageId = (value: string): MessageId => MessageId.make(value);
const asTurnId = (value: string): TurnId => TurnId.make(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asApprovalRequestId = (value: string): ApprovalRequestId =>
ApprovalRequestId.makeUnsafe(value);
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const deriveServerPathsSync = (baseDir: string, devUrl: URL | undefined) =>
Effect.runSync(deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer)));
@@ -106,7 +107,7 @@ describe("ProviderCommandReactor", () => {
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
let nextSessionIndex = 1;
const runtimeSessions: Array<ProviderSession> = [];
const defaultModelSelection = input?.threadModelSelection ?? {
const modelSelection = input?.threadModelSelection ?? {
provider: "codex",
model: "gpt-5-codex",
};
@@ -121,27 +122,10 @@ describe("ProviderCommandReactor", () => {
input !== null &&
"threadId" in input &&
typeof input.threadId === "string"
? ThreadId.make(input.threadId)
: ThreadId.make(`thread-${sessionIndex}`);
const provider =
typeof input === "object" &&
input !== null &&
"provider" in input &&
(input.provider === "codex" || input.provider === "claudeAgent")
? input.provider
: defaultModelSelection.provider;
const model =
typeof input === "object" &&
input !== null &&
"modelSelection" in input &&
typeof input.modelSelection === "object" &&
input.modelSelection !== null &&
"model" in input.modelSelection &&
typeof input.modelSelection.model === "string"
? input.modelSelection.model
: defaultModelSelection.model;
? ThreadId.makeUnsafe(input.threadId)
: ThreadId.makeUnsafe(`thread-${sessionIndex}`);
const session: ProviderSession = {
provider,
provider: modelSelection.provider,
status: "ready" as const,
runtimeMode:
typeof input === "object" &&
@@ -150,39 +134,24 @@ describe("ProviderCommandReactor", () => {
(input.runtimeMode === "approval-required" || input.runtimeMode === "full-access")
? input.runtimeMode
: "full-access",
...(model ? { model } : {}),
...(modelSelection.model !== undefined ? { model: modelSelection.model } : {}),
threadId,
resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` },
createdAt: now,
updatedAt: now,
};
const existingIndex = runtimeSessions.findIndex(
(runtimeSession) =>
runtimeSession.threadId === threadId && runtimeSession.provider === provider,
);
if (existingIndex >= 0) {
runtimeSessions.splice(existingIndex, 1, session);
} else {
runtimeSessions.push(session);
}
runtimeSessions.push(session);
return Effect.succeed(session);
});
const sendTurn = vi.fn((_: unknown) =>
Effect.succeed({
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
}),
);
const interruptTurn = vi.fn((_: unknown) => Effect.void);
const respondToRequest = vi.fn<ProviderServiceShape["respondToRequest"]>(() => Effect.void);
const respondToUserInput = vi.fn<ProviderServiceShape["respondToUserInput"]>(() => Effect.void);
const compactThread = vi.fn((input: unknown) =>
Effect.succeed(
typeof input === "object" && input !== null && "threadId" in input
? `Summary for ${String(input.threadId)}`
: "Summary",
),
);
const stopSession = vi.fn((input: unknown) =>
Effect.sync(() => {
const threadId =
@@ -192,18 +161,7 @@ describe("ProviderCommandReactor", () => {
if (!threadId) {
return;
}
const provider =
typeof input === "object" &&
input !== null &&
"provider" in input &&
(input.provider === "codex" || input.provider === "claudeAgent")
? input.provider
: undefined;
const index = runtimeSessions.findIndex(
(session) =>
session.threadId === threadId &&
(provider === undefined || session.provider === provider),
);
const index = runtimeSessions.findIndex((session) => session.threadId === threadId);
if (index >= 0) {
runtimeSessions.splice(index, 1);
}
@@ -244,9 +202,7 @@ describe("ProviderCommandReactor", () => {
interruptTurn: interruptTurn as ProviderServiceShape["interruptTurn"],
respondToRequest: respondToRequest as ProviderServiceShape["respondToRequest"],
respondToUserInput: respondToUserInput as ProviderServiceShape["respondToUserInput"],
compactThread: compactThread as ProviderServiceShape["compactThread"],
stopSession: stopSession as ProviderServiceShape["stopSession"],
stopSessionForProvider: stopSession as ProviderServiceShape["stopSessionForProvider"],
listSessions: () => Effect.succeed(runtimeSessions),
getCapabilities: (_provider) =>
Effect.succeed({
@@ -291,22 +247,22 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
engine.dispatch({
type: "project.create",
commandId: CommandId.make("cmd-project-create"),
commandId: CommandId.makeUnsafe("cmd-project-create"),
projectId: asProjectId("project-1"),
title: "Provider Project",
workspaceRoot: "/tmp/provider-project",
defaultModelSelection: defaultModelSelection,
defaultModelSelection: modelSelection,
createdAt: now,
}),
);
await Effect.runPromise(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-thread-create"),
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: defaultModelSelection,
modelSelection: modelSelection,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -322,7 +278,6 @@ describe("ProviderCommandReactor", () => {
interruptTurn,
respondToRequest,
respondToUserInput,
compactThread,
stopSession,
renameBranch,
generateBranchName,
@@ -339,8 +294,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-1"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-1"),
role: "user",
@@ -355,7 +310,7 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[0]).toEqual(ThreadId.make("thread-1"));
expect(harness.startSession.mock.calls[0]?.[0]).toEqual(ThreadId.makeUnsafe("thread-1"));
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
cwd: "/tmp/provider-project",
modelSelection: {
@@ -366,7 +321,7 @@ describe("ProviderCommandReactor", () => {
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
@@ -380,8 +335,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("cmd-thread-title-seed"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-thread-title-seed"),
threadId: ThreadId.makeUnsafe("thread-1"),
title: seededTitle,
}),
);
@@ -389,8 +344,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-title"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-title"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-title"),
role: "user",
@@ -412,12 +367,12 @@ describe("ProviderCommandReactor", () => {
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
return (
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"))?.title ===
"Generated title"
);
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.title).toBe("Generated title");
});
@@ -429,8 +384,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("cmd-thread-title-custom"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-thread-title-custom"),
threadId: ThreadId.makeUnsafe("thread-1"),
title: "Keep this custom title",
}),
);
@@ -438,8 +393,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-title-preserve"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-title-preserve"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-title-preserve"),
role: "user",
@@ -457,7 +412,7 @@ describe("ProviderCommandReactor", () => {
expect(harness.generateThreadTitle).not.toHaveBeenCalled();
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.title).toBe("Keep this custom title");
});
@@ -474,8 +429,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("cmd-thread-title-formatted-seed"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-thread-title-formatted-seed"),
threadId: ThreadId.makeUnsafe("thread-1"),
title: seededTitle,
}),
);
@@ -483,8 +438,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-title-formatted"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-title-formatted"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-title-formatted"),
role: "user",
@@ -502,13 +457,13 @@ describe("ProviderCommandReactor", () => {
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
return (
readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.title ===
readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"))?.title ===
"Reconnect spinner resume bug"
);
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.title).toBe("Reconnect spinner resume bug");
});
@@ -519,8 +474,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.meta.update",
commandId: CommandId.make("cmd-thread-branch"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-thread-branch"),
threadId: ThreadId.makeUnsafe("thread-1"),
branch: "t3code/1234abcd",
worktreePath: "/tmp/provider-project-worktree",
}),
@@ -544,8 +499,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-branch-model"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-branch-model"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-branch-model"),
role: "user",
@@ -571,8 +526,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-fast"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-fast"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-fast"),
role: "user",
@@ -606,7 +561,7 @@ describe("ProviderCommandReactor", () => {
},
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
@@ -627,8 +582,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-claude-effort"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-claude-effort"),
role: "user",
@@ -660,7 +615,7 @@ describe("ProviderCommandReactor", () => {
},
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
@@ -680,8 +635,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-claude-fast-mode"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-fast-mode"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-claude-fast-mode"),
role: "user",
@@ -713,7 +668,7 @@ describe("ProviderCommandReactor", () => {
},
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
@@ -731,8 +686,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.interaction-mode.set",
commandId: CommandId.make("cmd-interaction-mode-set-plan"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-interaction-mode-set-plan"),
threadId: ThreadId.makeUnsafe("thread-1"),
interactionMode: "plan",
createdAt: now,
}),
@@ -741,8 +696,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-plan"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-plan"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-plan"),
role: "user",
@@ -757,12 +712,12 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
interactionMode: "plan",
});
});
it("starts the requested provider on the first turn even when the thread default differs", async () => {
it("rejects a first turn when requested provider conflicts with the thread model", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "codex", model: "gpt-5-codex" },
});
@@ -771,8 +726,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-provider-first"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-first"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-provider-first"),
role: "user",
@@ -789,28 +744,31 @@ describe("ProviderCommandReactor", () => {
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
expect(harness.startSession).not.toHaveBeenCalled();
expect(harness.sendTurn).not.toHaveBeenCalled();
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(harness.compactThread).not.toHaveBeenCalled();
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session).toBeNull();
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
summary: "Provider turn start failed",
payload: {
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
},
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
input: "hello claude",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
},
});
expect(thread?.session?.providerName).toBe("claudeAgent");
});
it("preserves the active session model when in-session model switching is unsupported", async () => {
@@ -820,8 +778,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-unsupported-1"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-unsupported-1"),
role: "user",
@@ -839,8 +797,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-unsupported-2"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-unsupported-2"),
role: "user",
@@ -856,7 +814,7 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -871,8 +829,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-unchanged-1"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-unchanged-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-unchanged-1"),
role: "user",
@@ -891,8 +849,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-unchanged-2"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-unchanged-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-unchanged-2"),
role: "user",
@@ -919,8 +877,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-claude-effort-1"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-claude-effort-1"),
role: "user",
@@ -946,8 +904,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-claude-effort-2"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-claude-effort-2"),
role: "user",
@@ -988,8 +946,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.runtime-mode.set",
commandId: CommandId.make("cmd-runtime-mode-set-initial-full-access"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-initial-full-access"),
threadId: ThreadId.makeUnsafe("thread-1"),
runtimeMode: "full-access",
createdAt: now,
}),
@@ -998,8 +956,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-runtime-mode-1"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-runtime-mode-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-runtime-mode-1"),
role: "user",
@@ -1018,8 +976,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.runtime-mode.set",
commandId: CommandId.make("cmd-runtime-mode-set-1"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
runtimeMode: "approval-required",
createdAt: now,
}),
@@ -1027,15 +985,17 @@ describe("ProviderCommandReactor", () => {
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
return thread?.runtimeMode === "approval-required";
});
await waitFor(() => harness.startSession.mock.calls.length === 2);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-runtime-mode-2"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-runtime-mode-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-runtime-mode-2"),
role: "user",
@@ -1052,16 +1012,16 @@ describe("ProviderCommandReactor", () => {
expect(harness.stopSession.mock.calls.length).toBe(0);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
resumeCursor: { opaque: "resume-1" },
runtimeMode: "approval-required",
});
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
@@ -1075,10 +1035,10 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-runtime-mode-claude"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set-runtime-mode-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
@@ -1093,8 +1053,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.runtime-mode.set",
commandId: CommandId.make("cmd-runtime-mode-set-claude-no-options"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-claude-no-options"),
threadId: ThreadId.makeUnsafe("thread-1"),
runtimeMode: "approval-required",
createdAt: now,
}),
@@ -1111,15 +1071,15 @@ describe("ProviderCommandReactor", () => {
});
});
it("compacts and hands off context when switching providers mid-thread", async () => {
it("rejects provider changes after a thread is already bound to a session provider", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-provider-switch-1"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-switch-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-provider-switch-1"),
role: "user",
@@ -1138,8 +1098,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-provider-switch-2"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-switch-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-provider-switch-2"),
role: "user",
@@ -1156,69 +1116,33 @@ describe("ProviderCommandReactor", () => {
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 2);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
expect(harness.compactThread.mock.calls.length).toBe(1);
expect(harness.compactThread.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
});
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
provider: "claudeAgent",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
},
});
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
},
});
const switchedTurnInput = harness.sendTurn.mock.calls[1]?.[0] as { input?: string } | undefined;
expect(switchedTurnInput?.input).toContain("<provider_handoff>");
expect(switchedTurnInput?.input).toContain("Summary for thread-1");
expect(switchedTurnInput?.input).toContain("second");
expect(harness.stopSession.mock.calls.length).toBe(1);
expect(harness.stopSession.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-1"),
provider: "codex",
});
expect(harness.startSession.mock.calls.length).toBe(1);
expect(harness.sendTurn.mock.calls.length).toBe(1);
expect(harness.stopSession.mock.calls.length).toBe(0);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.providerName).toBe("claudeAgent");
expect(thread?.session?.providerName).toBe("codex");
expect(thread?.session?.runtimeMode).toBe("approval-required");
expect(
thread?.activities.filter((activity) => activity.kind.startsWith("provider.handoff.")),
).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "provider.handoff.compacting",
summary: "Handing off thread",
turnId: null,
payload: expect.objectContaining({
sourceProvider: "codex",
targetProvider: "claudeAgent",
}),
}),
expect.objectContaining({
kind: "provider.handoff.completed",
summary: "Handed off thread",
turnId: null,
payload: expect.objectContaining({
sourceProvider: "codex",
targetProvider: "claudeAgent",
}),
}),
]),
);
expect(
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed"),
).toBe(false);
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
},
});
});
it("does not stop the active session when restart fails before rebind", async () => {
@@ -1228,8 +1152,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.runtime-mode.set",
commandId: CommandId.make("cmd-runtime-mode-set-initial-full-access-2"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-initial-full-access-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
runtimeMode: "full-access",
createdAt: now,
}),
@@ -1238,8 +1162,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-restart-failure-1"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-restart-failure-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-restart-failure-1"),
role: "user",
@@ -1262,8 +1186,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.runtime-mode.set",
commandId: CommandId.make("cmd-runtime-mode-set-restart-failure"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-restart-failure"),
threadId: ThreadId.makeUnsafe("thread-1"),
runtimeMode: "approval-required",
createdAt: now,
}),
@@ -1271,7 +1195,9 @@ describe("ProviderCommandReactor", () => {
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
return thread?.runtimeMode === "approval-required";
});
await waitFor(() => harness.startSession.mock.calls.length === 2);
@@ -1281,7 +1207,7 @@ describe("ProviderCommandReactor", () => {
expect(harness.sendTurn.mock.calls.length).toBe(1);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session?.threadId).toBe("thread-1");
expect(thread?.session?.runtimeMode).toBe("full-access");
});
@@ -1293,10 +1219,10 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
runtimeMode: "approval-required",
@@ -1311,8 +1237,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.interrupt",
commandId: CommandId.make("cmd-turn-interrupt"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-interrupt"),
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: asTurnId("turn-1"),
createdAt: now,
}),
@@ -1331,10 +1257,10 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-for-approval"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set-for-approval"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
runtimeMode: "approval-required",
@@ -1349,8 +1275,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.approval.respond",
commandId: CommandId.make("cmd-approval-respond"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-approval-respond"),
threadId: ThreadId.makeUnsafe("thread-1"),
requestId: asApprovalRequestId("approval-request-1"),
decision: "accept",
createdAt: now,
@@ -1372,10 +1298,10 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-for-user-input"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set-for-user-input"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
runtimeMode: "approval-required",
@@ -1390,8 +1316,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.user-input.respond",
commandId: CommandId.make("cmd-user-input-respond"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-user-input-respond"),
threadId: ThreadId.makeUnsafe("thread-1"),
requestId: asApprovalRequestId("user-input-request-1"),
answers: {
sandbox_mode: "workspace-write",
@@ -1426,10 +1352,10 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-for-approval-error"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set-for-approval-error"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
runtimeMode: "approval-required",
@@ -1444,10 +1370,10 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.activity.append",
commandId: CommandId.make("cmd-approval-requested"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-approval-requested"),
threadId: ThreadId.makeUnsafe("thread-1"),
activity: {
id: EventId.make("activity-approval-requested"),
id: EventId.makeUnsafe("activity-approval-requested"),
tone: "approval",
kind: "approval.requested",
summary: "Command approval requested",
@@ -1465,8 +1391,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.approval.respond",
commandId: CommandId.make("cmd-approval-respond-stale"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-approval-respond-stale"),
threadId: ThreadId.makeUnsafe("thread-1"),
requestId: asApprovalRequestId("approval-request-1"),
decision: "acceptForSession",
createdAt: now,
@@ -1475,7 +1401,9 @@ describe("ProviderCommandReactor", () => {
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
if (!thread) return false;
return thread.activities.some(
(activity) => activity.kind === "provider.approval.respond.failed",
@@ -1483,7 +1411,7 @@ describe("ProviderCommandReactor", () => {
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread).toBeDefined();
const failureActivity = thread?.activities.find(
@@ -1521,10 +1449,10 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-for-user-input-error"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set-for-user-input-error"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "claudeAgent",
runtimeMode: "approval-required",
@@ -1539,10 +1467,10 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.activity.append",
commandId: CommandId.make("cmd-user-input-requested"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-user-input-requested"),
threadId: ThreadId.makeUnsafe("thread-1"),
activity: {
id: EventId.make("activity-user-input-requested"),
id: EventId.makeUnsafe("activity-user-input-requested"),
tone: "info",
kind: "user-input.requested",
summary: "User input requested",
@@ -1572,8 +1500,8 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.user-input.respond",
commandId: CommandId.make("cmd-user-input-respond-stale"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-user-input-respond-stale"),
threadId: ThreadId.makeUnsafe("thread-1"),
requestId: asApprovalRequestId("user-input-request-1"),
answers: {
sandbox_mode: "workspace-write",
@@ -1584,7 +1512,9 @@ describe("ProviderCommandReactor", () => {
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
if (!thread) return false;
return thread.activities.some(
(activity) => activity.kind === "provider.user-input.respond.failed",
@@ -1592,7 +1522,7 @@ describe("ProviderCommandReactor", () => {
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread).toBeDefined();
const failureActivity = thread?.activities.find(
@@ -1621,10 +1551,10 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-for-stop"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-set-for-stop"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
@@ -1639,15 +1569,15 @@ describe("ProviderCommandReactor", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.stop",
commandId: CommandId.make("cmd-session-stop"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-stop"),
threadId: ThreadId.makeUnsafe("thread-1"),
createdAt: now,
}),
);
await waitFor(() => harness.stopSession.mock.calls.length === 1);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread?.session).not.toBeNull();
expect(thread?.session?.status).toBe("stopped");
expect(thread?.session?.threadId).toBe("thread-1");
@@ -18,7 +18,6 @@ import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
import { ProviderAdapterRequestError, ProviderServiceError } from "../../provider/Errors.ts";
import { buildProviderSwitchHandoffInput } from "../../provider/handoffSummary.ts";
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
@@ -41,12 +40,6 @@ type ProviderIntentEvent = Extract<
}
>;
interface ProviderSwitchHandoff {
readonly sourceProvider: ProviderKind;
readonly targetProvider: ProviderKind;
readonly compactSummary: string | null;
}
function toNonEmptyProviderInput(value: string | undefined): string | undefined {
const normalized = value?.trim();
return normalized && normalized.length > 0 ? normalized : undefined;
@@ -74,7 +67,7 @@ const turnStartKeyForEvent = (event: ProviderIntentEvent): string =>
event.commandId !== null ? `command:${event.commandId}` : `event:${event.eventId}`;
const serverCommandId = (tag: string): CommandId =>
CommandId.make(`server:${tag}:${crypto.randomUUID()}`);
CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`);
const HANDLED_TURN_START_KEY_MAX = 10_000;
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
@@ -193,7 +186,7 @@ const make = Effect.gen(function* () {
commandId: serverCommandId("provider-failure-activity"),
threadId: input.threadId,
activity: {
id: EventId.make(crypto.randomUUID()),
id: EventId.makeUnsafe(crypto.randomUUID()),
tone: "error",
kind: input.kind,
summary: input.summary,
@@ -207,34 +200,6 @@ const make = Effect.gen(function* () {
createdAt: input.createdAt,
});
const appendProviderHandoffActivity = (input: {
readonly threadId: ThreadId;
readonly kind: "provider.handoff.compacting" | "provider.handoff.completed";
readonly summary: string;
readonly sourceProvider: ProviderKind;
readonly targetProvider: ProviderKind;
readonly turnId: TurnId | null;
readonly createdAt: string;
}) =>
orchestrationEngine.dispatch({
type: "thread.activity.append",
commandId: serverCommandId("provider-handoff-activity"),
threadId: input.threadId,
activity: {
id: EventId.make(crypto.randomUUID()),
tone: "info",
kind: input.kind,
summary: input.summary,
payload: {
sourceProvider: input.sourceProvider,
targetProvider: input.targetProvider,
},
turnId: input.turnId,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
});
const setThreadSession = (input: {
readonly threadId: ThreadId;
readonly session: OrchestrationSession;
@@ -258,7 +223,6 @@ const make = Effect.gen(function* () {
createdAt: string,
options?: {
readonly modelSelection?: ModelSelection;
readonly turnId?: TurnId | null;
},
) {
const readModel = yield* orchestrationEngine.getReadModel();
@@ -274,8 +238,19 @@ const make = Effect.gen(function* () {
? thread.session.providerName
: undefined;
const requestedModelSelection = options?.modelSelection;
const threadProvider: ProviderKind = currentProvider ?? thread.modelSelection.provider;
if (
requestedModelSelection !== undefined &&
requestedModelSelection.provider !== threadProvider
) {
return yield* new ProviderAdapterRequestError({
provider: threadProvider,
method: "thread.turn.start",
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${requestedModelSelection.provider}'.`,
});
}
const preferredProvider: ProviderKind = currentProvider ?? threadProvider;
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
const desiredProvider: ProviderKind = desiredModelSelection.provider;
const effectiveCwd = resolveThreadWorkspaceCwd({
thread,
projects: readModel.projects,
@@ -292,7 +267,7 @@ const make = Effect.gen(function* () {
}) =>
providerService.startSession(threadId, {
threadId,
provider: input?.provider ?? desiredProvider,
...(preferredProvider ? { provider: preferredProvider } : {}),
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
modelSelection: desiredModelSelection,
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
@@ -315,21 +290,6 @@ const make = Effect.gen(function* () {
createdAt,
});
const startAndBindProviderSession = (input?: {
readonly resumeCursor?: unknown;
readonly provider?: ProviderKind;
}) =>
startProviderSession(input).pipe(
Effect.tap((session) =>
Effect.logInfo("provider command reactor restarted provider session", {
threadId,
provider: session.provider,
runtimeMode: session.runtimeMode,
}),
),
Effect.tap(bindSessionToThread),
);
const existingSessionThreadId =
thread.session && thread.session.status !== "stopped" ? thread.id : null;
if (existingSessionThreadId) {
@@ -358,10 +318,7 @@ const make = Effect.gen(function* () {
!shouldRestartForModelChange &&
!shouldRestartForModelSelectionChange
) {
return {
threadId: existingSessionThreadId,
handoff: null,
} as const;
return existingSessionThreadId;
}
const resumeCursor =
@@ -382,74 +339,23 @@ const make = Effect.gen(function* () {
shouldRestartForModelSelectionChange,
hasResumeCursor: resumeCursor !== undefined,
});
if (providerChanged && currentProvider) {
yield* appendProviderHandoffActivity({
threadId,
kind: "provider.handoff.compacting",
summary: "Handing off thread",
sourceProvider: currentProvider,
targetProvider: desiredProvider,
turnId: options?.turnId ?? null,
createdAt,
});
const compactSummary = yield* providerService.compactThread({
threadId: existingSessionThreadId,
});
const restartedSession = yield* startAndBindProviderSession({
provider: desiredProvider,
});
yield* providerService
.stopSessionForProvider({
threadId: existingSessionThreadId,
provider: currentProvider,
})
.pipe(
Effect.catchCause((cause) =>
Effect.logWarning(
"provider command reactor failed to stop replaced provider session",
{
threadId,
provider: currentProvider,
cause: Cause.pretty(cause),
},
),
),
);
yield* appendProviderHandoffActivity({
threadId,
kind: "provider.handoff.completed",
summary: "Handed off thread",
sourceProvider: currentProvider,
targetProvider: desiredProvider,
turnId: options?.turnId ?? null,
createdAt,
});
return {
threadId: restartedSession.threadId,
handoff: {
sourceProvider: currentProvider,
targetProvider: desiredProvider,
compactSummary,
} satisfies ProviderSwitchHandoff,
} as const;
}
const restartedSession = yield* startAndBindProviderSession(
resumeCursor !== undefined ? { resumeCursor, provider: desiredProvider } : undefined,
const restartedSession = yield* startProviderSession(
resumeCursor !== undefined ? { resumeCursor } : undefined,
);
return {
threadId: restartedSession.threadId,
handoff: null,
} as const;
yield* Effect.logInfo("provider command reactor restarted provider session", {
threadId,
previousSessionId: existingSessionThreadId,
restartedSessionThreadId: restartedSession.threadId,
provider: restartedSession.provider,
runtimeMode: restartedSession.runtimeMode,
});
yield* bindSessionToThread(restartedSession);
return restartedSession.threadId;
}
const startedSession = yield* startAndBindProviderSession({
provider: desiredProvider,
});
return {
threadId: startedSession.threadId,
handoff: null,
} as const;
const startedSession = yield* startProviderSession(undefined);
yield* bindSessionToThread(startedSession);
return startedSession.threadId;
});
const sendTurnForThread = Effect.fn("sendTurnForThread")(function* (input: {
@@ -464,23 +370,15 @@ const make = Effect.gen(function* () {
if (!thread) {
return;
}
const ensuredSession = yield* ensureSessionForThread(input.threadId, input.createdAt, {
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
turnId: thread.latestTurn?.turnId ?? null,
});
yield* ensureSessionForThread(
input.threadId,
input.createdAt,
input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {},
);
if (input.modelSelection !== undefined) {
threadModelSelections.set(input.threadId, input.modelSelection);
}
const normalizedInput = ensuredSession.handoff
? toNonEmptyProviderInput(
buildProviderSwitchHandoffInput({
sourceProvider: ensuredSession.handoff.sourceProvider,
targetProvider: ensuredSession.handoff.targetProvider,
compactSummary: ensuredSession.handoff.compactSummary,
userMessage: input.messageText,
}),
)
: toNonEmptyProviderInput(input.messageText);
const normalizedInput = toNonEmptyProviderInput(input.messageText);
const normalizedAttachments = input.attachments ?? [];
const activeSession = yield* providerService
.listSessions()
@@ -47,12 +47,12 @@ function makeTestServerSettingsLayer(overrides: Partial<ServerSettings> = {}) {
return ServerSettingsService.layerTest(overrides);
}
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asItemId = (value: string): ProviderItemId => ProviderItemId.make(value);
const asEventId = (value: string): EventId => EventId.make(value);
const asMessageId = (value: string): MessageId => MessageId.make(value);
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
const asTurnId = (value: string): TurnId => TurnId.make(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
type LegacyProviderRuntimeEvent = {
readonly type: string;
@@ -96,10 +96,8 @@ function createProviderServiceHarness() {
respondToRequest: () => unsupported(),
respondToUserInput: () => unsupported(),
stopSession: () => unsupported(),
stopSessionForProvider: () => unsupported(),
listSessions: () => Effect.succeed([...runtimeSessions]),
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
compactThread: () => unsupported(),
rollbackConversation: () => unsupported(),
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
@@ -229,7 +227,7 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
engine.dispatch({
type: "project.create",
commandId: CommandId.make("cmd-provider-project-create"),
commandId: CommandId.makeUnsafe("cmd-provider-project-create"),
projectId: asProjectId("project-1"),
title: "Provider Project",
workspaceRoot,
@@ -243,8 +241,8 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-thread-create"),
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
@@ -261,10 +259,10 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-seed"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-seed"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
@@ -279,7 +277,7 @@ describe("ProviderRuntimeIngestion", () => {
provider: "codex",
status: "ready",
runtimeMode: "approval-required",
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
createdAt,
updatedAt: createdAt,
});
@@ -459,7 +457,9 @@ describe("ProviderRuntimeIngestion", () => {
await harness.drain();
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const midThread = midReadModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
expect(midThread?.session?.status).toBe("running");
expect(midThread?.session?.activeTurnId).toBe("turn-midturn-lifecycle");
@@ -486,10 +486,10 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-seed-claude-placeholder"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-session-seed-claude-placeholder"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeAgent",
runtimeMode: "approval-required",
@@ -564,7 +564,9 @@ describe("ProviderRuntimeIngestion", () => {
await harness.drain();
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const midThread = midReadModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
expect(midThread?.session?.status).toBe("running");
expect(midThread?.session?.activeTurnId).toBe("turn-primary");
@@ -616,7 +618,9 @@ describe("ProviderRuntimeIngestion", () => {
await harness.drain();
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const midThread = midReadModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
expect(midThread?.session?.status).toBe("running");
expect(midThread?.session?.activeTurnId).toBe("turn-guarded-main");
@@ -766,7 +770,7 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create-plan-source"),
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source"),
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
@@ -784,7 +788,7 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-plan-source"),
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source"),
threadId: sourceThreadId,
session: {
threadId: sourceThreadId,
@@ -801,7 +805,7 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create-plan-target"),
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-target"),
threadId: targetThreadId,
projectId: asProjectId("project-1"),
title: "Plan Target",
@@ -819,7 +823,7 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-plan-target"),
commandId: CommandId.makeUnsafe("cmd-session-set-plan-target"),
threadId: targetThreadId,
session: {
threadId: targetThreadId,
@@ -878,7 +882,7 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-plan-target"),
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target"),
threadId: targetThreadId,
message: {
messageId: asMessageId("msg-plan-target"),
@@ -953,7 +957,7 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create-plan-source-guarded"),
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source-guarded"),
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
@@ -971,7 +975,7 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-plan-source-guarded"),
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source-guarded"),
threadId: sourceThreadId,
session: {
threadId: sourceThreadId,
@@ -1047,7 +1051,7 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-plan-target-guarded"),
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target-guarded"),
threadId: targetThreadId,
message: {
messageId: asMessageId("msg-plan-target-guarded"),
@@ -1106,7 +1110,7 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create-plan-source-unrelated"),
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source-unrelated"),
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
@@ -1124,7 +1128,7 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-plan-source-unrelated"),
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source-unrelated"),
threadId: sourceThreadId,
session: {
threadId: sourceThreadId,
@@ -1141,7 +1145,7 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create-plan-target-unrelated"),
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-target-unrelated"),
threadId: targetThreadId,
projectId: asProjectId("project-1"),
title: "Plan Target",
@@ -1159,7 +1163,7 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-plan-target-unrelated"),
commandId: CommandId.makeUnsafe("cmd-session-set-plan-target-unrelated"),
threadId: targetThreadId,
session: {
threadId: targetThreadId,
@@ -1209,7 +1213,7 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-plan-target-unrelated"),
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target-unrelated"),
threadId: targetThreadId,
message: {
messageId: asMessageId("msg-plan-target-unrelated"),
@@ -1360,7 +1364,9 @@ describe("ProviderRuntimeIngestion", () => {
await harness.drain();
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const midThread = midReadModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
expect(
midThread?.messages.some(
(message: ProviderRuntimeTestMessage) => message.id === "assistant:item-buffered",
@@ -1401,8 +1407,8 @@ describe("ProviderRuntimeIngestion", () => {
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-streaming-mode"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-streaming-mode"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("message-streaming-mode"),
role: "user",
@@ -1643,7 +1649,7 @@ describe("ProviderRuntimeIngestion", () => {
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
requestId: ApprovalRequestId.make("req-open"),
requestId: ApprovalRequestId.makeUnsafe("req-open"),
payload: {
requestType: "command_execution_approval",
detail: "pwd",
@@ -1656,7 +1662,7 @@ describe("ProviderRuntimeIngestion", () => {
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
requestId: ApprovalRequestId.make("req-open"),
requestId: ApprovalRequestId.makeUnsafe("req-open"),
payload: {
requestType: "command_execution_approval",
decision: "accept",
@@ -1675,7 +1681,7 @@ describe("ProviderRuntimeIngestion", () => {
);
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread).toBeDefined();
const requested = thread?.activities.find(
@@ -2280,7 +2286,7 @@ describe("ProviderRuntimeIngestion", () => {
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-user-input"),
requestId: ApprovalRequestId.make("req-user-input-1"),
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
payload: {
questions: [
{
@@ -2305,7 +2311,7 @@ describe("ProviderRuntimeIngestion", () => {
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-user-input"),
requestId: ApprovalRequestId.make("req-user-input-1"),
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
payload: {
answers: {
sandbox_mode: "workspace-write",
@@ -30,7 +30,7 @@ import { ServerSettingsService } from "../../serverSettings.ts";
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId =>
CommandId.make(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120);
@@ -57,11 +57,11 @@ type RuntimeIngestionInput =
};
function toTurnId(value: TurnId | string | undefined): TurnId | undefined {
return value === undefined ? undefined : TurnId.make(String(value));
return value === undefined ? undefined : TurnId.makeUnsafe(String(value));
}
function toApprovalRequestId(value: string | undefined): ApprovalRequestId | undefined {
return value === undefined ? undefined : ApprovalRequestId.make(value);
return value === undefined ? undefined : ApprovalRequestId.makeUnsafe(value);
}
function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
@@ -857,7 +857,7 @@ const make = Effect.fn("make")(function* () {
yield* orchestrationEngine.dispatch({
type: "thread.proposed-plan.upsert",
commandId: CommandId.make(
commandId: CommandId.makeUnsafe(
`provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`,
),
threadId: sourceThread.id,
@@ -882,7 +882,6 @@ const make = Effect.fn("make")(function* () {
const now = event.createdAt;
const eventTurnId = toTurnId(event.turnId);
const activeTurnId = thread.session?.activeTurnId ?? null;
const sessionProviderName = thread.session?.providerName ?? null;
const conflictsWithActiveTurn =
activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
@@ -892,17 +891,6 @@ const make = Effect.fn("make")(function* () {
if (!STRICT_PROVIDER_LIFECYCLE_GUARD) {
return true;
}
if (sessionProviderName !== null && sessionProviderName !== event.provider) {
switch (event.type) {
case "session.started":
case "session.state.changed":
case "session.exited":
case "thread.started":
case "turn.started":
case "turn.completed":
return false;
}
}
switch (event.type) {
case "session.exited":
return true;
@@ -1015,7 +1003,7 @@ const make = Effect.fn("make")(function* () {
event.type === "turn.proposed.delta" ? event.payload.delta : undefined;
if (assistantDelta && assistantDelta.length > 0) {
const assistantMessageId = MessageId.make(
const assistantMessageId = MessageId.makeUnsafe(
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
);
const turnId = toTurnId(event.turnId);
@@ -1061,7 +1049,9 @@ const make = Effect.fn("make")(function* () {
const assistantCompletion =
event.type === "item.completed" && event.payload.itemType === "assistant_message"
? {
messageId: MessageId.make(`assistant:${event.itemId ?? event.turnId ?? event.eventId}`),
messageId: MessageId.makeUnsafe(
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
),
fallbackText: event.payload.detail,
}
: undefined;
@@ -1147,7 +1137,7 @@ const make = Effect.fn("make")(function* () {
}
}
if (event.type === "session.exited" && shouldApplyThreadLifecycle) {
if (event.type === "session.exited") {
yield* clearTurnStateForSession(thread.id);
}
@@ -1156,8 +1146,7 @@ const make = Effect.fn("make")(function* () {
const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD
? true
: (sessionProviderName === null || sessionProviderName === event.provider) &&
(activeTurnId === null || eventTurnId === undefined || sameId(activeTurnId, eventTurnId));
: activeTurnId === null || eventTurnId === undefined || sameId(activeTurnId, eventTurnId);
if (shouldApplyRuntimeError) {
yield* orchestrationEngine.dispatch({
@@ -1197,7 +1186,7 @@ const make = Effect.fn("make")(function* () {
if (thread.checkpoints.some((c) => c.turnId === turnId)) {
// Already tracked; no-op.
} else {
const assistantMessageId = MessageId.make(
const assistantMessageId = MessageId.makeUnsafe(
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
);
const maxTurnCount = thread.checkpoints.reduce(
@@ -1210,7 +1199,7 @@ const make = Effect.fn("make")(function* () {
threadId: thread.id,
turnId,
completedAt: now,
checkpointRef: CheckpointRef.make(`provider-diff:${event.eventId}`),
checkpointRef: CheckpointRef.makeUnsafe(`provider-diff:${event.eventId}`),
status: "missing",
files: [],
assistantMessageId,
@@ -6,7 +6,7 @@
*
* @module CheckpointReactor
*/
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Effect, Scope } from "effect";
/**
@@ -34,6 +34,7 @@ export interface CheckpointReactorShape {
/**
* CheckpointReactor - Service tag for checkpoint reactor workers.
*/
export class CheckpointReactor extends Context.Service<CheckpointReactor, CheckpointReactorShape>()(
"t3/orchestration/Services/CheckpointReactor",
) {}
export class CheckpointReactor extends ServiceMap.Service<
CheckpointReactor,
CheckpointReactorShape
>()("t3/orchestration/Services/CheckpointReactor") {}
@@ -5,7 +5,7 @@
* `OrchestrationEventStore` persistence. It does not own provider process
* management or transport concerns (e.g. websocket request parsing).
*
* Uses Effect `Context.Service` for dependency injection. Command dispatch,
* Uses Effect `ServiceMap.Service` for dependency injection. Command dispatch,
* replay, and unknown-input decoding all return typed domain errors.
*
* @module OrchestrationEngineService
@@ -15,7 +15,7 @@ import type {
OrchestrationEvent,
OrchestrationReadModel,
} from "@t3tools/contracts";
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Effect, Stream } from "effect";
import type { OrchestrationDispatchError } from "../Errors.ts";
@@ -74,7 +74,7 @@ export interface OrchestrationEngineShape {
* })
* ```
*/
export class OrchestrationEngineService extends Context.Service<
export class OrchestrationEngineService extends ServiceMap.Service<
OrchestrationEngineService,
OrchestrationEngineShape
>()("t3/orchestration/Services/OrchestrationEngine/OrchestrationEngineService") {}
@@ -6,7 +6,7 @@
*
* @module OrchestrationReactor
*/
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Effect, Scope } from "effect";
/**
@@ -25,7 +25,7 @@ export interface OrchestrationReactorShape {
/**
* OrchestrationReactor - Service tag for orchestration reactor coordination.
*/
export class OrchestrationReactor extends Context.Service<
export class OrchestrationReactor extends ServiceMap.Service<
OrchestrationReactor,
OrchestrationReactorShape
>()("t3/orchestration/Services/OrchestrationReactor") {}
@@ -7,7 +7,7 @@
* @module OrchestrationProjectionPipeline
*/
import type { OrchestrationEvent } from "@t3tools/contracts";
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../../persistence/Errors.ts";
@@ -36,7 +36,7 @@ export interface OrchestrationProjectionPipelineShape {
/**
* OrchestrationProjectionPipeline - Service tag for orchestration projections.
*/
export class OrchestrationProjectionPipeline extends Context.Service<
export class OrchestrationProjectionPipeline extends ServiceMap.Service<
OrchestrationProjectionPipeline,
OrchestrationProjectionPipelineShape
>()("t3/orchestration/Services/ProjectionPipeline/OrchestrationProjectionPipeline") {}
@@ -13,7 +13,7 @@ import type {
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Option } from "effect";
import type { Effect } from "effect";
@@ -74,7 +74,7 @@ export interface ProjectionSnapshotQueryShape {
/**
* ProjectionSnapshotQuery - Service tag for projection snapshot queries.
*/
export class ProjectionSnapshotQuery extends Context.Service<
export class ProjectionSnapshotQuery extends ServiceMap.Service<
ProjectionSnapshotQuery,
ProjectionSnapshotQueryShape
>()("t3/orchestration/Services/ProjectionSnapshotQuery") {}
@@ -6,7 +6,7 @@
*
* @module ProviderCommandReactor
*/
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Effect, Scope } from "effect";
/**
@@ -34,7 +34,7 @@ export interface ProviderCommandReactorShape {
/**
* ProviderCommandReactor - Service tag for provider command reaction workers.
*/
export class ProviderCommandReactor extends Context.Service<
export class ProviderCommandReactor extends ServiceMap.Service<
ProviderCommandReactor,
ProviderCommandReactorShape
>()("t3/orchestration/Services/ProviderCommandReactor") {}
@@ -6,7 +6,7 @@
*
* @module ProviderRuntimeIngestionService
*/
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Effect, Scope } from "effect";
/**
@@ -34,7 +34,7 @@ export interface ProviderRuntimeIngestionShape {
/**
* ProviderRuntimeIngestionService - Service tag for runtime ingestion workers.
*/
export class ProviderRuntimeIngestionService extends Context.Service<
export class ProviderRuntimeIngestionService extends ServiceMap.Service<
ProviderRuntimeIngestionService,
ProviderRuntimeIngestionShape
>()("t3/orchestration/Services/ProviderRuntimeIngestion/ProviderRuntimeIngestionService") {}
@@ -15,7 +15,7 @@
* @module RuntimeReceiptBus
*/
import { CheckpointRef, IsoDateTime, NonNegativeInt, ThreadId, TurnId } from "@t3tools/contracts";
import { Schema, Context } from "effect";
import { Schema, ServiceMap } from "effect";
import type { Effect, Stream } from "effect";
export const CheckpointBaselineCapturedReceipt = Schema.Struct({
@@ -59,6 +59,7 @@ export interface RuntimeReceiptBusShape {
readonly streamEventsForTest: Stream.Stream<OrchestrationRuntimeReceipt>;
}
export class RuntimeReceiptBus extends Context.Service<RuntimeReceiptBus, RuntimeReceiptBusShape>()(
"t3/orchestration/Services/RuntimeReceiptBus",
) {}
export class RuntimeReceiptBus extends ServiceMap.Service<
RuntimeReceiptBus,
RuntimeReceiptBusShape
>()("t3/orchestration/Services/RuntimeReceiptBus") {}
@@ -25,7 +25,7 @@ const readModel: OrchestrationReadModel = {
updatedAt: now,
projects: [
{
id: ProjectId.make("project-a"),
id: ProjectId.makeUnsafe("project-a"),
title: "Project A",
workspaceRoot: "/tmp/project-a",
defaultModelSelection: {
@@ -38,7 +38,7 @@ const readModel: OrchestrationReadModel = {
deletedAt: null,
},
{
id: ProjectId.make("project-b"),
id: ProjectId.makeUnsafe("project-b"),
title: "Project B",
workspaceRoot: "/tmp/project-b",
defaultModelSelection: {
@@ -53,8 +53,8 @@ const readModel: OrchestrationReadModel = {
],
threads: [
{
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-a"),
id: ThreadId.makeUnsafe("thread-1"),
projectId: ProjectId.makeUnsafe("project-a"),
title: "Thread A",
modelSelection: {
provider: "codex",
@@ -76,8 +76,8 @@ const readModel: OrchestrationReadModel = {
deletedAt: null,
},
{
id: ThreadId.make("thread-2"),
projectId: ProjectId.make("project-b"),
id: ThreadId.makeUnsafe("thread-2"),
projectId: ProjectId.makeUnsafe("project-b"),
title: "Thread B",
modelSelection: {
provider: "codex",
@@ -103,10 +103,10 @@ const readModel: OrchestrationReadModel = {
const messageSendCommand: OrchestrationCommand = {
type: "thread.turn.start",
commandId: CommandId.make("cmd-1"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: MessageId.make("msg-1"),
messageId: MessageId.makeUnsafe("msg-1"),
role: "user",
text: "hello",
attachments: [],
@@ -118,11 +118,13 @@ const messageSendCommand: OrchestrationCommand = {
describe("commandInvariants", () => {
it("finds threads by id and project", () => {
expect(findThreadById(readModel, ThreadId.make("thread-1"))?.projectId).toBe("project-a");
expect(findThreadById(readModel, ThreadId.make("missing"))).toBeUndefined();
expect(findThreadById(readModel, ThreadId.makeUnsafe("thread-1"))?.projectId).toBe("project-a");
expect(findThreadById(readModel, ThreadId.makeUnsafe("missing"))).toBeUndefined();
expect(
listThreadsByProjectId(readModel, ProjectId.make("project-b")).map((thread) => thread.id),
).toEqual([ThreadId.make("thread-2")]);
listThreadsByProjectId(readModel, ProjectId.makeUnsafe("project-b")).map(
(thread) => thread.id,
),
).toEqual([ThreadId.makeUnsafe("thread-2")]);
});
it("requires existing thread", async () => {
@@ -130,17 +132,17 @@ describe("commandInvariants", () => {
requireThread({
readModel,
command: messageSendCommand,
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
}),
);
expect(thread.id).toBe(ThreadId.make("thread-1"));
expect(thread.id).toBe(ThreadId.makeUnsafe("thread-1"));
await expect(
Effect.runPromise(
requireThread({
readModel,
command: messageSendCommand,
threadId: ThreadId.make("missing"),
threadId: ThreadId.makeUnsafe("missing"),
}),
),
).rejects.toThrow("does not exist");
@@ -152,9 +154,9 @@ describe("commandInvariants", () => {
readModel,
command: {
type: "thread.create",
commandId: CommandId.make("cmd-2"),
threadId: ThreadId.make("thread-3"),
projectId: ProjectId.make("project-a"),
commandId: CommandId.makeUnsafe("cmd-2"),
threadId: ThreadId.makeUnsafe("thread-3"),
projectId: ProjectId.makeUnsafe("project-a"),
title: "new",
modelSelection: {
provider: "codex",
@@ -166,7 +168,7 @@ describe("commandInvariants", () => {
worktreePath: null,
createdAt: now,
},
threadId: ThreadId.make("thread-3"),
threadId: ThreadId.makeUnsafe("thread-3"),
}),
);
@@ -176,9 +178,9 @@ describe("commandInvariants", () => {
readModel,
command: {
type: "thread.create",
commandId: CommandId.make("cmd-3"),
threadId: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-a"),
commandId: CommandId.makeUnsafe("cmd-3"),
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: ProjectId.makeUnsafe("project-a"),
title: "dup",
modelSelection: {
provider: "codex",
@@ -190,7 +192,7 @@ describe("commandInvariants", () => {
worktreePath: null,
createdAt: now,
},
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
}),
),
).rejects.toThrow("already exists");
@@ -12,9 +12,9 @@ import { Effect } from "effect";
import { decideOrchestrationCommand } from "./decider.ts";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
const asEventId = (value: string): EventId => EventId.make(value);
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asMessageId = (value: string): MessageId => MessageId.make(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
describe("decider project scripts", () => {
it("emits empty scripts on project.create", async () => {
@@ -25,7 +25,7 @@ describe("decider project scripts", () => {
decideOrchestrationCommand({
command: {
type: "project.create",
commandId: CommandId.make("cmd-project-create-scripts"),
commandId: CommandId.makeUnsafe("cmd-project-create-scripts"),
projectId: asProjectId("project-scripts"),
title: "Scripts",
workspaceRoot: "/tmp/scripts",
@@ -51,9 +51,9 @@ describe("decider project scripts", () => {
aggregateId: asProjectId("project-scripts"),
type: "project.created",
occurredAt: now,
commandId: CommandId.make("cmd-project-create-scripts"),
commandId: CommandId.makeUnsafe("cmd-project-create-scripts"),
causationEventId: null,
correlationId: CommandId.make("cmd-project-create-scripts"),
correlationId: CommandId.makeUnsafe("cmd-project-create-scripts"),
metadata: {},
payload: {
projectId: asProjectId("project-scripts"),
@@ -81,7 +81,7 @@ describe("decider project scripts", () => {
decideOrchestrationCommand({
command: {
type: "project.meta.update",
commandId: CommandId.make("cmd-project-update-scripts"),
commandId: CommandId.makeUnsafe("cmd-project-update-scripts"),
projectId: asProjectId("project-scripts"),
scripts: Array.from(scripts),
},
@@ -105,9 +105,9 @@ describe("decider project scripts", () => {
aggregateId: asProjectId("project-1"),
type: "project.created",
occurredAt: now,
commandId: CommandId.make("cmd-project-create"),
commandId: CommandId.makeUnsafe("cmd-project-create"),
causationEventId: null,
correlationId: CommandId.make("cmd-project-create"),
correlationId: CommandId.makeUnsafe("cmd-project-create"),
metadata: {},
payload: {
projectId: asProjectId("project-1"),
@@ -125,15 +125,15 @@ describe("decider project scripts", () => {
sequence: 2,
eventId: asEventId("evt-thread-create"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
aggregateId: ThreadId.makeUnsafe("thread-1"),
type: "thread.created",
occurredAt: now,
commandId: CommandId.make("cmd-thread-create"),
commandId: CommandId.makeUnsafe("cmd-thread-create"),
causationEventId: null,
correlationId: CommandId.make("cmd-thread-create"),
correlationId: CommandId.makeUnsafe("cmd-thread-create"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
@@ -154,8 +154,8 @@ describe("decider project scripts", () => {
decideOrchestrationCommand({
command: {
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("message-user-1"),
role: "user",
@@ -189,7 +189,7 @@ describe("decider project scripts", () => {
return;
}
expect(turnStartEvent.payload).toMatchObject({
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
messageId: asMessageId("message-user-1"),
modelSelection: {
provider: "codex",
@@ -214,9 +214,9 @@ describe("decider project scripts", () => {
aggregateId: asProjectId("project-1"),
type: "project.created",
occurredAt: now,
commandId: CommandId.make("cmd-project-create"),
commandId: CommandId.makeUnsafe("cmd-project-create"),
causationEventId: null,
correlationId: CommandId.make("cmd-project-create"),
correlationId: CommandId.makeUnsafe("cmd-project-create"),
metadata: {},
payload: {
projectId: asProjectId("project-1"),
@@ -234,15 +234,15 @@ describe("decider project scripts", () => {
sequence: 2,
eventId: asEventId("evt-thread-create"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
aggregateId: ThreadId.makeUnsafe("thread-1"),
type: "thread.created",
occurredAt: now,
commandId: CommandId.make("cmd-thread-create"),
commandId: CommandId.makeUnsafe("cmd-thread-create"),
causationEventId: null,
correlationId: CommandId.make("cmd-thread-create"),
correlationId: CommandId.makeUnsafe("cmd-thread-create"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
@@ -263,8 +263,8 @@ describe("decider project scripts", () => {
decideOrchestrationCommand({
command: {
type: "thread.runtime-mode.set",
commandId: CommandId.make("cmd-runtime-mode-set"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set"),
threadId: ThreadId.makeUnsafe("thread-1"),
runtimeMode: "approval-required",
createdAt: now,
},
@@ -279,7 +279,7 @@ describe("decider project scripts", () => {
expect(singleResult).toMatchObject({
type: "thread.runtime-mode-set",
payload: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
runtimeMode: "approval-required",
},
});
@@ -296,9 +296,9 @@ describe("decider project scripts", () => {
aggregateId: asProjectId("project-1"),
type: "project.created",
occurredAt: now,
commandId: CommandId.make("cmd-project-create"),
commandId: CommandId.makeUnsafe("cmd-project-create"),
causationEventId: null,
correlationId: CommandId.make("cmd-project-create"),
correlationId: CommandId.makeUnsafe("cmd-project-create"),
metadata: {},
payload: {
projectId: asProjectId("project-1"),
@@ -316,15 +316,15 @@ describe("decider project scripts", () => {
sequence: 2,
eventId: asEventId("evt-thread-create"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-1"),
aggregateId: ThreadId.makeUnsafe("thread-1"),
type: "thread.created",
occurredAt: now,
commandId: CommandId.make("cmd-thread-create"),
commandId: CommandId.makeUnsafe("cmd-thread-create"),
causationEventId: null,
correlationId: CommandId.make("cmd-thread-create"),
correlationId: CommandId.makeUnsafe("cmd-thread-create"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
@@ -345,8 +345,8 @@ describe("decider project scripts", () => {
decideOrchestrationCommand({
command: {
type: "thread.interaction-mode.set",
commandId: CommandId.make("cmd-interaction-mode-set"),
threadId: ThreadId.make("thread-1"),
commandId: CommandId.makeUnsafe("cmd-interaction-mode-set"),
threadId: ThreadId.makeUnsafe("thread-1"),
interactionMode: "plan",
createdAt: now,
},
@@ -361,7 +361,7 @@ describe("decider project scripts", () => {
expect(singleResult).toMatchObject({
type: "thread.interaction-mode-set",
payload: {
threadId: ThreadId.make("thread-1"),
threadId: ThreadId.makeUnsafe("thread-1"),
interactionMode: "plan",
},
});
@@ -21,15 +21,15 @@ function makeEvent(input: {
}): OrchestrationEvent {
return {
sequence: input.sequence,
eventId: EventId.make(`event-${input.sequence}`),
eventId: EventId.makeUnsafe(`event-${input.sequence}`),
type: input.type,
aggregateKind: input.aggregateKind,
aggregateId:
input.aggregateKind === "project"
? ProjectId.make(input.aggregateId)
: ThreadId.make(input.aggregateId),
? ProjectId.makeUnsafe(input.aggregateId)
: ThreadId.makeUnsafe(input.aggregateId),
occurredAt: input.occurredAt,
commandId: input.commandId === null ? null : CommandId.make(input.commandId),
commandId: input.commandId === null ? null : CommandId.makeUnsafe(input.commandId),
causationEventId: null,
correlationId: null,
metadata: {},
@@ -21,18 +21,18 @@ layer("OrchestrationEventStore", (it) => {
const appended = yield* eventStore.append({
type: "project.created",
eventId: EventId.make("evt-store-roundtrip"),
eventId: EventId.makeUnsafe("evt-store-roundtrip"),
aggregateKind: "project",
aggregateId: ProjectId.make("project-roundtrip"),
aggregateId: ProjectId.makeUnsafe("project-roundtrip"),
occurredAt: now,
commandId: CommandId.make("cmd-store-roundtrip"),
commandId: CommandId.makeUnsafe("cmd-store-roundtrip"),
causationEventId: null,
correlationId: CommandId.make("cmd-store-roundtrip"),
correlationId: CommandId.makeUnsafe("cmd-store-roundtrip"),
metadata: {
adapterKey: "codex",
},
payload: {
projectId: ProjectId.make("project-roundtrip"),
projectId: ProjectId.makeUnsafe("project-roundtrip"),
title: "Roundtrip Project",
workspaceRoot: "/tmp/project-roundtrip",
defaultModelSelection: null,
@@ -87,13 +87,13 @@ layer("OrchestrationEventStore", (it) => {
metadata_json
)
VALUES (
${EventId.make("evt-store-invalid-json")},
${EventId.makeUnsafe("evt-store-invalid-json")},
${"project"},
${ProjectId.make("project-invalid-json")},
${ProjectId.makeUnsafe("project-invalid-json")},
${0},
${"project.created"},
${now},
${CommandId.make("cmd-store-invalid-json")},
${CommandId.makeUnsafe("cmd-store-invalid-json")},
${null},
${null},
${"server"},
@@ -24,7 +24,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
const sql = yield* SqlClient.SqlClient;
yield* projects.upsert({
projectId: ProjectId.make("project-null-options"),
projectId: ProjectId.makeUnsafe("project-null-options"),
title: "Null options project",
workspaceRoot: "/tmp/project-null-options",
defaultModelSelection: {
@@ -58,7 +58,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
);
const persisted = yield* projects.getById({
projectId: ProjectId.make("project-null-options"),
projectId: ProjectId.makeUnsafe("project-null-options"),
});
assert.deepStrictEqual(Option.getOrNull(persisted)?.defaultModelSelection, {
provider: "codex",
@@ -73,8 +73,8 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
const sql = yield* SqlClient.SqlClient;
yield* threads.upsert({
threadId: ThreadId.make("thread-null-options"),
projectId: ProjectId.make("project-null-options"),
threadId: ThreadId.makeUnsafe("thread-null-options"),
projectId: ProjectId.makeUnsafe("project-null-options"),
title: "Null options thread",
modelSelection: {
provider: "claudeAgent",
@@ -112,7 +112,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
);
const persisted = yield* threads.getById({
threadId: ThreadId.make("thread-null-options"),
threadId: ThreadId.makeUnsafe("thread-null-options"),
});
assert.deepStrictEqual(Option.getOrNull(persisted)?.modelSelection, {
provider: "claudeAgent",
@@ -14,8 +14,8 @@ layer("ProjectionThreadMessageRepository", (it) => {
it.effect("preserves existing attachments when upsert omits attachments", () =>
Effect.gen(function* () {
const repository = yield* ProjectionThreadMessageRepository;
const threadId = ThreadId.make("thread-preserve-attachments");
const messageId = MessageId.make("message-preserve-attachments");
const threadId = ThreadId.makeUnsafe("thread-preserve-attachments");
const messageId = MessageId.makeUnsafe("message-preserve-attachments");
const createdAt = "2026-02-28T19:00:00.000Z";
const updatedAt = "2026-02-28T19:00:01.000Z";
const persistedAttachments = [
@@ -68,8 +68,8 @@ layer("ProjectionThreadMessageRepository", (it) => {
it.effect("allows explicit attachment clearing with an empty array", () =>
Effect.gen(function* () {
const repository = yield* ProjectionThreadMessageRepository;
const threadId = ThreadId.make("thread-clear-attachments");
const messageId = MessageId.make("message-clear-attachments");
const threadId = ThreadId.makeUnsafe("thread-clear-attachments");
const messageId = MessageId.makeUnsafe("message-clear-attachments");
const createdAt = "2026-02-28T19:10:00.000Z";
yield* repository.upsert({
+10 -10
View File
@@ -15,7 +15,7 @@ import { identity } from "effect/Function";
import * as Layer from "effect/Layer";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Context from "effect/Context";
import * as ServiceMap from "effect/ServiceMap";
import * as Stream from "effect/Stream";
import * as Reactivity from "effect/unstable/reactivity/Reactivity";
import * as Client from "effect/unstable/sql/SqlClient";
@@ -32,7 +32,7 @@ export type TypeId = "~local/sqlite-node/SqliteClient";
/**
* SqliteClient - Effect service tag for the sqlite SQL client.
*/
export const SqliteClient = Context.Service<Client.SqlClient>("t3/persistence/NodeSqliteClient");
export const SqliteClient = ServiceMap.Service<Client.SqlClient>("t3/persistence/NodeSqliteClient");
export interface SqliteClientConfig {
readonly filename: string;
@@ -120,7 +120,7 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
const runStatement = (statement: StatementSync, params: ReadonlyArray<unknown>, raw: boolean) =>
Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
statement.setReadBigInts(Boolean(Context.get(fiber.context, Client.SafeIntegers)));
statement.setReadBigInts(Boolean(ServiceMap.get(fiber.services, Client.SafeIntegers)));
try {
if (hasRows(statement)) {
return Effect.succeed(statement.all(...(params as any)));
@@ -200,7 +200,7 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));
const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
const fiber = Fiber.getCurrent()!;
const scope = Context.getUnsafe(fiber.context, Scope.Scope);
const scope = ServiceMap.getUnsafe(fiber.services, Scope.Scope);
return Effect.as(
Effect.tap(restore(semaphore.take(1)), () => Scope.addFinalizer(scope, semaphore.release(1))),
connection,
@@ -251,27 +251,27 @@ const makeMemory = (
export const layerConfig = (
config: Config.Wrap<SqliteClientConfig>,
): Layer.Layer<Client.SqlClient, Config.ConfigError> =>
Layer.effectContext(
Layer.effectServices(
Config.unwrap(config)
.asEffect()
.pipe(
Effect.flatMap(make),
Effect.map((client) =>
Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)),
ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)),
),
),
).pipe(Layer.provide(Reactivity.layer));
export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient> =>
Layer.effectContext(
Layer.effectServices(
Effect.map(make(config), (client) =>
Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)),
ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)),
),
).pipe(Layer.provide(Reactivity.layer));
export const layerMemory = (config: SqliteMemoryClientConfig = {}): Layer.Layer<Client.SqlClient> =>
Layer.effectContext(
Layer.effectServices(
Effect.map(makeMemory(config), (client) =>
Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)),
ServiceMap.make(SqliteClient, client).pipe(ServiceMap.add(Client.SqlClient, client)),
),
).pipe(Layer.provide(Reactivity.layer));
@@ -1,4 +1,4 @@
import { Option, Schema, Context } from "effect";
import { Option, Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
import type { AuthPairingLinkRepositoryError } from "../Errors.ts";
@@ -70,7 +70,7 @@ export interface AuthPairingLinkRepositoryShape {
) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;
}
export class AuthPairingLinkRepository extends Context.Service<
export class AuthPairingLinkRepository extends ServiceMap.Service<
AuthPairingLinkRepository,
AuthPairingLinkRepositoryShape
>()("t3/persistence/Services/AuthPairingLinks/AuthPairingLinkRepository") {}
@@ -1,5 +1,5 @@
import { AuthClientMetadataDeviceType, AuthSessionId } from "@t3tools/contracts";
import { Option, Schema, Context } from "effect";
import { Option, Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
import type { AuthSessionRepositoryError } from "../Errors.ts";
@@ -87,7 +87,7 @@ export interface AuthSessionRepositoryShape {
) => Effect.Effect<void, AuthSessionRepositoryError>;
}
export class AuthSessionRepository extends Context.Service<
export class AuthSessionRepository extends ServiceMap.Service<
AuthSessionRepository,
AuthSessionRepositoryShape
>()("t3/persistence/Services/AuthSessions/AuthSessionRepository") {}
@@ -15,7 +15,7 @@ import {
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import { Option, Schema, Context } from "effect";
import { Option, Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
import type { OrchestrationCommandReceiptRepositoryError } from "../Errors.ts";
@@ -63,7 +63,7 @@ export interface OrchestrationCommandReceiptRepositoryShape {
/**
* OrchestrationCommandReceiptRepository - Service tag for command receipt persistence.
*/
export class OrchestrationCommandReceiptRepository extends Context.Service<
export class OrchestrationCommandReceiptRepository extends ServiceMap.Service<
OrchestrationCommandReceiptRepository,
OrchestrationCommandReceiptRepositoryShape
>()("t3/persistence/Services/OrchestrationCommandReceipts/OrchestrationCommandReceiptRepository") {}
@@ -4,13 +4,13 @@
* Owns durable append/replay access to the orchestration event stream. It does
* not reduce events into read models or apply command validation rules.
*
* Uses Effect `Context.Service` for dependency injection and exposes typed
* Uses Effect `ServiceMap.Service` for dependency injection and exposes typed
* persistence/decode errors for event append and replay operations.
*
* @module OrchestrationEventStore
*/
import { OrchestrationEvent } from "@t3tools/contracts";
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Effect, Stream } from "effect";
import type { OrchestrationEventStoreError } from "../Errors.ts";
@@ -64,7 +64,7 @@ export interface OrchestrationEventStoreShape {
* })
* ```
*/
export class OrchestrationEventStore extends Context.Service<
export class OrchestrationEventStore extends ServiceMap.Service<
OrchestrationEventStore,
OrchestrationEventStoreShape
>()("t3/persistence/Services/OrchestrationEventStore") {}
@@ -16,7 +16,7 @@ import {
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { Option, Context, Schema } from "effect";
import { Option, ServiceMap, Schema } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../Errors.ts";
@@ -87,7 +87,7 @@ export interface ProjectionCheckpointRepositoryShape {
/**
* ProjectionCheckpointRepository - Service tag for checkpoint projection persistence.
*/
export class ProjectionCheckpointRepository extends Context.Service<
export class ProjectionCheckpointRepository extends ServiceMap.Service<
ProjectionCheckpointRepository,
ProjectionCheckpointRepositoryShape
>()("t3/persistence/Services/ProjectionCheckpoints/ProjectionCheckpointRepository") {}
@@ -14,7 +14,7 @@ import {
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { Option, Schema, Context } from "effect";
import { Option, Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../Errors.ts";
@@ -85,7 +85,7 @@ export interface ProjectionPendingApprovalRepositoryShape {
/**
* ProjectionPendingApprovalRepository - Service tag for pending approval persistence.
*/
export class ProjectionPendingApprovalRepository extends Context.Service<
export class ProjectionPendingApprovalRepository extends ServiceMap.Service<
ProjectionPendingApprovalRepository,
ProjectionPendingApprovalRepositoryShape
>()("t3/persistence/Services/ProjectionPendingApprovals/ProjectionPendingApprovalRepository") {}
@@ -7,7 +7,7 @@
* @module ProjectionProjectRepository
*/
import { IsoDateTime, ModelSelection, ProjectId, ProjectScript } from "@t3tools/contracts";
import { Option, Schema, Context } from "effect";
import { Option, Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../Errors.ts";
@@ -73,7 +73,7 @@ export interface ProjectionProjectRepositoryShape {
/**
* ProjectionProjectRepository - Service tag for project projection persistence.
*/
export class ProjectionProjectRepository extends Context.Service<
export class ProjectionProjectRepository extends ServiceMap.Service<
ProjectionProjectRepository,
ProjectionProjectRepositoryShape
>()("t3/persistence/Services/ProjectionProjects/ProjectionProjectRepository") {}
@@ -7,7 +7,7 @@
* @module ProjectionStateRepository
*/
import { IsoDateTime, NonNegativeInt } from "@t3tools/contracts";
import { Option, Schema, Context } from "effect";
import { Option, Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../Errors.ts";
@@ -58,7 +58,7 @@ export interface ProjectionStateRepositoryShape {
/**
* ProjectionStateRepository - Service tag for projection cursor persistence.
*/
export class ProjectionStateRepository extends Context.Service<
export class ProjectionStateRepository extends ServiceMap.Service<
ProjectionStateRepository,
ProjectionStateRepositoryShape
>()("t3/persistence/Services/ProjectionState/ProjectionStateRepository") {}
@@ -14,7 +14,7 @@ import {
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { Schema, Context } from "effect";
import { Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../Errors.ts";
@@ -77,7 +77,7 @@ export interface ProjectionThreadActivityRepositoryShape {
/**
* ProjectionThreadActivityRepository - Service tag for thread activity persistence.
*/
export class ProjectionThreadActivityRepository extends Context.Service<
export class ProjectionThreadActivityRepository extends ServiceMap.Service<
ProjectionThreadActivityRepository,
ProjectionThreadActivityRepositoryShape
>()("t3/persistence/Services/ProjectionThreadActivities/ProjectionThreadActivityRepository") {}
@@ -14,7 +14,7 @@ import {
TurnId,
IsoDateTime,
} from "@t3tools/contracts";
import { Schema, Context } from "effect";
import { Schema, ServiceMap } from "effect";
import type { Option } from "effect";
import type { Effect } from "effect";
@@ -88,7 +88,7 @@ export interface ProjectionThreadMessageRepositoryShape {
/**
* ProjectionThreadMessageRepository - Service tag for message projection persistence.
*/
export class ProjectionThreadMessageRepository extends Context.Service<
export class ProjectionThreadMessageRepository extends ServiceMap.Service<
ProjectionThreadMessageRepository,
ProjectionThreadMessageRepositoryShape
>()("t3/persistence/Services/ProjectionThreadMessages/ProjectionThreadMessageRepository") {}
@@ -5,7 +5,7 @@ import {
TrimmedNonEmptyString,
TurnId,
} from "@t3tools/contracts";
import { Schema, Context } from "effect";
import { Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../Errors.ts";
@@ -46,7 +46,7 @@ export interface ProjectionThreadProposedPlanRepositoryShape {
) => Effect.Effect<void, ProjectionRepositoryError>;
}
export class ProjectionThreadProposedPlanRepository extends Context.Service<
export class ProjectionThreadProposedPlanRepository extends ServiceMap.Service<
ProjectionThreadProposedPlanRepository,
ProjectionThreadProposedPlanRepositoryShape
>()(
@@ -13,7 +13,7 @@ import {
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { Option, Schema, Context } from "effect";
import { Option, Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../Errors.ts";
@@ -68,7 +68,7 @@ export interface ProjectionThreadSessionRepositoryShape {
/**
* ProjectionThreadSessionRepository - Service tag for thread-session persistence.
*/
export class ProjectionThreadSessionRepository extends Context.Service<
export class ProjectionThreadSessionRepository extends ServiceMap.Service<
ProjectionThreadSessionRepository,
ProjectionThreadSessionRepositoryShape
>()("t3/persistence/Services/ProjectionThreadSessions/ProjectionThreadSessionRepository") {}
@@ -15,7 +15,7 @@ import {
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { Option, Schema, Context } from "effect";
import { Option, Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../Errors.ts";
@@ -90,7 +90,7 @@ export interface ProjectionThreadRepositoryShape {
/**
* ProjectionThreadRepository - Service tag for thread projection persistence.
*/
export class ProjectionThreadRepository extends Context.Service<
export class ProjectionThreadRepository extends ServiceMap.Service<
ProjectionThreadRepository,
ProjectionThreadRepositoryShape
>()("t3/persistence/Services/ProjectionThreads/ProjectionThreadRepository") {}
@@ -17,7 +17,7 @@ import {
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { Option, Schema, Context } from "effect";
import { Option, Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../Errors.ts";
@@ -162,7 +162,7 @@ export interface ProjectionTurnRepositoryShape {
) => Effect.Effect<void, ProjectionRepositoryError>;
}
export class ProjectionTurnRepository extends Context.Service<
export class ProjectionTurnRepository extends ServiceMap.Service<
ProjectionTurnRepository,
ProjectionTurnRepositoryShape
>()("t3/persistence/Services/ProjectionTurns/ProjectionTurnRepository") {}
@@ -11,7 +11,7 @@ import {
RuntimeMode,
ThreadId,
} from "@t3tools/contracts";
import { Option, Schema, Context } from "effect";
import { Option, Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ProviderSessionRuntimeRepositoryError } from "../Errors.ts";
@@ -75,7 +75,7 @@ export interface ProviderSessionRuntimeRepositoryShape {
/**
* ProviderSessionRuntimeRepository - Service tag for provider runtime persistence.
*/
export class ProviderSessionRuntimeRepository extends Context.Service<
export class ProviderSessionRuntimeRepository extends ServiceMap.Service<
ProviderSessionRuntimeRepository,
ProviderSessionRuntimeRepositoryShape
>()("t3/persistence/Services/ProviderSessionRuntime/ProviderSessionRuntimeRepository") {}
@@ -116,19 +116,17 @@ async function resolveRepositoryIdentityFromCacheKey(
export const makeRepositoryIdentityResolver = Effect.fn("makeRepositoryIdentityResolver")(
function* (options: RepositoryIdentityResolverOptions = {}) {
const repositoryIdentityCache = yield* Cache.makeWith<string, RepositoryIdentity | null>(
(cacheKey) => Effect.promise(() => resolveRepositoryIdentityFromCacheKey(cacheKey)),
{
capacity: options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY,
timeToLive: Exit.match({
onSuccess: (value) =>
value === null
? (options.negativeCacheTtl ?? DEFAULT_NEGATIVE_CACHE_TTL)
: (options.positiveCacheTtl ?? DEFAULT_POSITIVE_CACHE_TTL),
onFailure: () => Duration.zero,
}),
},
);
const repositoryIdentityCache = yield* Cache.makeWith<string, RepositoryIdentity | null>({
capacity: options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY,
lookup: (cacheKey) => Effect.promise(() => resolveRepositoryIdentityFromCacheKey(cacheKey)),
timeToLive: Exit.match({
onSuccess: (value) =>
value === null
? (options.negativeCacheTtl ?? DEFAULT_NEGATIVE_CACHE_TTL)
: (options.positiveCacheTtl ?? DEFAULT_POSITIVE_CACHE_TTL),
onFailure: () => Duration.zero,
}),
});
const resolve: RepositoryIdentityResolverShape["resolve"] = Effect.fn(
"RepositoryIdentityResolver.resolve",
@@ -6,7 +6,7 @@
*
* @module ProjectFaviconResolver
*/
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
/**
@@ -24,7 +24,7 @@ export interface ProjectFaviconResolverShape {
/**
* ProjectFaviconResolver - Service tag for project favicon resolution.
*/
export class ProjectFaviconResolver extends Context.Service<
export class ProjectFaviconResolver extends ServiceMap.Service<
ProjectFaviconResolver,
ProjectFaviconResolverShape
>()("t3/project/Services/ProjectFaviconResolver") {}
@@ -1,4 +1,4 @@
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
export interface ProjectSetupScriptRunnerResultNoScript {
@@ -31,7 +31,7 @@ export interface ProjectSetupScriptRunnerShape {
) => Effect.Effect<ProjectSetupScriptRunnerResult, Error>;
}
export class ProjectSetupScriptRunner extends Context.Service<
export class ProjectSetupScriptRunner extends ServiceMap.Service<
ProjectSetupScriptRunner,
ProjectSetupScriptRunnerShape
>()("t3/project/ProjectSetupScriptRunner") {}
@@ -1,12 +1,12 @@
import type { RepositoryIdentity } from "@t3tools/contracts";
import { Context } from "effect";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
export interface RepositoryIdentityResolverShape {
readonly resolve: (cwd: string) => Effect.Effect<RepositoryIdentity | null>;
}
export class RepositoryIdentityResolver extends Context.Service<
export class RepositoryIdentityResolver extends ServiceMap.Service<
RepositoryIdentityResolver,
RepositoryIdentityResolverShape
>()("t3/project/Services/RepositoryIdentityResolver") {}
@@ -237,8 +237,10 @@ async function readFirstPromptMessage(
return next.value;
}
const THREAD_ID = ThreadId.make("thread-claude-1");
const RESUME_THREAD_ID = ThreadId.make("thread-claude-resume");
const THREAD_ID = ThreadId.makeUnsafe("thread-claude-1");
const RESUME_THREAD_ID = ThreadId.makeUnsafe("thread-claude-resume");
const INTERRUPTED_TOOL_RESULT_TEXT =
"The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed.";
describe("ClaudeAdapterLive", () => {
it.effect("returns validation error for non-claude provider on startSession", () => {
@@ -1101,11 +1103,187 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("does not surface ede_diagnostic-only Claude results as runtime errors", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
harness.query.emit({
type: "result",
subtype: "error_during_execution",
is_error: false,
errors: ["[ede_diagnostic] result_type=user last_content_type=n/a stop_reason=tool_use"],
stop_reason: "tool_use",
session_id: "sdk-session-ede-diagnostic",
uuid: "result-ede-diagnostic",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
assert.deepEqual(
runtimeEvents.map((event) => event.type),
[
"session.started",
"session.configured",
"session.state.changed",
"turn.started",
"thread.started",
"turn.completed",
],
);
const turnCompleted = runtimeEvents[runtimeEvents.length - 1];
assert.equal(turnCompleted?.type, "turn.completed");
if (turnCompleted?.type === "turn.completed") {
assert.equal(String(turnCompleted.turnId), String(turn.turnId));
assert.equal(turnCompleted.payload.state, "completed");
assert.isUndefined(turnCompleted.payload.errorMessage);
assert.equal(turnCompleted.payload.stopReason, "tool_use");
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect(
"marks rejected tool results after interruptTurn as declined and completes interrupted",
() => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 10).pipe(
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
harness.query.emit({
type: "stream_event",
session_id: "sdk-session-interrupted-tool-result",
uuid: "stream-tool-start-interrupted",
parent_tool_use_id: null,
event: {
type: "content_block_start",
index: 1,
content_block: {
type: "tool_use",
id: "tool-bash-1",
name: "Bash",
input: {
command: "ls",
},
},
},
} as unknown as SDKMessage);
yield* adapter.interruptTurn(session.threadId, turn.turnId);
harness.query.emit({
type: "user",
session_id: "sdk-session-interrupted-tool-result",
uuid: "user-tool-result-interrupted",
parent_tool_use_id: null,
message: {
role: "user",
content: [
{
type: "tool_result",
tool_use_id: "tool-bash-1",
content: INTERRUPTED_TOOL_RESULT_TEXT,
is_error: true,
},
],
},
} as unknown as SDKMessage);
harness.query.emit({
type: "result",
subtype: "error_during_execution",
is_error: true,
errors: [INTERRUPTED_TOOL_RESULT_TEXT],
stop_reason: "tool_use",
session_id: "sdk-session-interrupted-tool-result",
uuid: "result-interrupted-tool-result",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
assert.deepEqual(
runtimeEvents.map((event) => event.type),
[
"session.started",
"session.configured",
"session.state.changed",
"turn.started",
"thread.started",
"item.started",
"item.updated",
"content.delta",
"item.completed",
"turn.completed",
],
);
const toolUpdated = runtimeEvents[6];
assert.equal(toolUpdated?.type, "item.updated");
if (toolUpdated?.type === "item.updated") {
assert.equal(toolUpdated.payload.status, "declined");
}
const toolCompleted = runtimeEvents[8];
assert.equal(toolCompleted?.type, "item.completed");
if (toolCompleted?.type === "item.completed") {
assert.equal(toolCompleted.payload.status, "declined");
}
const turnCompleted = runtimeEvents[9];
assert.equal(turnCompleted?.type, "turn.completed");
if (turnCompleted?.type === "turn.completed") {
assert.equal(String(turnCompleted.turnId), String(turn.turnId));
assert.equal(turnCompleted.payload.state, "interrupted");
assert.equal(turnCompleted.payload.errorMessage, "Claude runtime interrupted.");
assert.equal(turnCompleted.payload.stopReason, "tool_use");
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
},
);
it.effect("closes the session when the Claude stream aborts after a turn starts", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const context = yield* Effect.context<never>();
const runFork = Effect.runForkWith(context);
const services = yield* Effect.services();
const runFork = Effect.runForkWith(services);
const adapter = yield* ClaudeAdapter;
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
@@ -1169,6 +1347,145 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect(
"treats Claude ede_diagnostic tool_use cancellation as interrupted without a runtime error",
() => {
const harness = makeHarness();
return Effect.gen(function* () {
const services = yield* Effect.services();
const runFork = Effect.runForkWith(services);
const adapter = yield* ClaudeAdapter;
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
const runtimeEventsFiber = runFork(
Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}),
),
);
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: THREAD_ID,
input: "hello",
attachments: [],
});
harness.query.fail(
new Error("[ede_diagnostic] result_type=user last_content_type=n/a stop_reason=tool_use"),
);
yield* Effect.yieldNow;
yield* Effect.yieldNow;
yield* Effect.yieldNow;
runtimeEventsFiber.interruptUnsafe();
assert.deepEqual(
runtimeEvents.map((event) => event.type),
[
"session.started",
"session.configured",
"session.state.changed",
"turn.started",
"turn.completed",
"session.exited",
],
);
const turnCompleted = runtimeEvents[4];
assert.equal(turnCompleted?.type, "turn.completed");
if (turnCompleted?.type === "turn.completed") {
assert.equal(String(turnCompleted.turnId), String(turn.turnId));
assert.equal(turnCompleted.payload.state, "interrupted");
assert.equal(turnCompleted.payload.errorMessage, "Claude runtime interrupted.");
}
const sessionExited = runtimeEvents[5];
assert.equal(sessionExited?.type, "session.exited");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
},
);
it.effect(
"treats aborted Claude stream failures after interruptTurn as interrupted without a runtime error",
() => {
const harness = makeHarness();
return Effect.gen(function* () {
const services = yield* Effect.services();
const runFork = Effect.runForkWith(services);
const adapter = yield* ClaudeAdapter;
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
const runtimeEventsFiber = runFork(
Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => {
runtimeEvents.push(event);
}),
),
);
yield* adapter.startSession({
threadId: THREAD_ID,
provider: "claudeAgent",
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: THREAD_ID,
input: "hello",
attachments: [],
});
yield* adapter.interruptTurn(THREAD_ID, turn.turnId);
harness.query.fail(
"Error: Request was aborted.\n at makeRequest (/$bunfs/root/src/entrypoints/cli.js:50:3448)\n at processTicksAndRejections (native:7:39)",
);
yield* Effect.yieldNow;
yield* Effect.yieldNow;
yield* Effect.yieldNow;
runtimeEventsFiber.interruptUnsafe();
assert.deepEqual(
runtimeEvents.map((event) => event.type),
[
"session.started",
"session.configured",
"session.state.changed",
"turn.started",
"turn.completed",
"session.exited",
],
);
const turnCompleted = runtimeEvents[4];
assert.equal(turnCompleted?.type, "turn.completed");
if (turnCompleted?.type === "turn.completed") {
assert.equal(String(turnCompleted.turnId), String(turn.turnId));
assert.equal(turnCompleted.payload.state, "interrupted");
assert.equal(turnCompleted.payload.errorMessage, "Claude runtime interrupted.");
}
const sessionExited = runtimeEvents[5];
assert.equal(sessionExited?.type, "session.exited");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
},
);
it.effect("stopSession does not throw into the SDK prompt consumer", () => {
// The SDK consumes user messages via `for await (... of prompt)`.
// Stopping a session must end that loop cleanly — not throw an error.
@@ -1204,8 +1521,8 @@ describe("ClaudeAdapterLive", () => {
);
return Effect.gen(function* () {
const context = yield* Effect.context<never>();
const runFork = Effect.runForkWith(context);
const services = yield* Effect.services();
const runFork = Effect.runForkWith(services);
const adapter = yield* ClaudeAdapter;
@@ -1228,11 +1545,9 @@ describe("ClaudeAdapterLive", () => {
runtimeEventsFiber.interruptUnsafe();
assert.equal(
assert.isUndefined(
promptConsumerError,
undefined,
`Prompt consumer should not receive a thrown error on session stop, ` +
`but got: "${promptConsumerError instanceof Error ? promptConsumerError.message : String(promptConsumerError)}"`,
"Prompt consumer should not receive a thrown error on session stop",
);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
@@ -2108,7 +2423,7 @@ describe("ClaudeAdapterLive", () => {
return;
}
assert.deepEqual(requested.value.providerRefs, {
providerItemId: ProviderItemId.make("tool-use-1"),
providerItemId: ProviderItemId.makeUnsafe("tool-use-1"),
});
const runtimeRequestId = requested.value.requestId;
assert.equal(typeof runtimeRequestId, "string");
@@ -2118,7 +2433,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.respondToRequest(
session.threadId,
ApprovalRequestId.make(runtimeRequestId),
ApprovalRequestId.makeUnsafe(runtimeRequestId),
"accept",
);
@@ -2134,7 +2449,7 @@ describe("ClaudeAdapterLive", () => {
assert.equal(resolved.value.requestId, requested.value.requestId);
assert.equal(resolved.value.payload.decision, "accept");
assert.deepEqual(resolved.value.providerRefs, {
providerItemId: ProviderItemId.make("tool-use-1"),
providerItemId: ProviderItemId.makeUnsafe("tool-use-1"),
});
const permissionResult = yield* Effect.promise(() => permissionPromise);
@@ -2183,7 +2498,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.respondToRequest(
session.threadId,
ApprovalRequestId.make(String(agentRequested.value.requestId)),
ApprovalRequestId.makeUnsafe(String(agentRequested.value.requestId)),
"accept",
);
yield* Stream.runHead(adapter.streamEvents);
@@ -2207,7 +2522,7 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.respondToRequest(
session.threadId,
ApprovalRequestId.make(String(grepRequested.value.requestId)),
ApprovalRequestId.makeUnsafe(String(grepRequested.value.requestId)),
"accept",
);
yield* Stream.runHead(adapter.streamEvents);
@@ -2629,7 +2944,7 @@ describe("ClaudeAdapterLive", () => {
}
assert.equal(proposedEvent.value.payload.planMarkdown, "# Ship it\n\n- one\n- two");
assert.deepEqual(proposedEvent.value.providerRefs, {
providerItemId: ProviderItemId.make("tool-exit-1"),
providerItemId: ProviderItemId.makeUnsafe("tool-exit-1"),
});
const permissionResult = yield* Effect.promise(() => permissionPromise);
@@ -2707,7 +3022,7 @@ describe("ClaudeAdapterLive", () => {
}
assert.equal(proposedEvent.value.payload.planMarkdown, "# Final plan\n\n- capture it");
assert.deepEqual(proposedEvent.value.providerRefs, {
providerItemId: ProviderItemId.make("tool-exit-2"),
providerItemId: ProviderItemId.makeUnsafe("tool-exit-2"),
});
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
@@ -2798,13 +3113,15 @@ describe("ClaudeAdapterLive", () => {
assert.equal(requestedEvent.value.payload.questions.length, 1);
assert.equal(requestedEvent.value.payload.questions[0]?.question, "Which framework?");
assert.deepEqual(requestedEvent.value.providerRefs, {
providerItemId: ProviderItemId.make("tool-ask-1"),
providerItemId: ProviderItemId.makeUnsafe("tool-ask-1"),
});
// Respond with the user's answers.
yield* adapter.respondToUserInput(session.threadId, ApprovalRequestId.make(requestId!), {
"Which framework?": "React",
});
yield* adapter.respondToUserInput(
session.threadId,
ApprovalRequestId.makeUnsafe(requestId!),
{ "Which framework?": "React" },
);
// The adapter should emit a user-input.resolved event.
const resolvedEvent = yield* Stream.runHead(adapter.streamEvents);
@@ -2820,7 +3137,7 @@ describe("ClaudeAdapterLive", () => {
"Which framework?": "React",
});
assert.deepEqual(resolvedEvent.value.providerRefs, {
providerItemId: ProviderItemId.make("tool-ask-1"),
providerItemId: ProviderItemId.makeUnsafe("tool-ask-1"),
});
// The canUseTool promise should resolve with the answers in SDK format.
@@ -2887,9 +3204,11 @@ describe("ClaudeAdapterLive", () => {
}
const requestId = requestedEvent.value.requestId;
yield* adapter.respondToUserInput(session.threadId, ApprovalRequestId.make(requestId!), {
"Deploy to which env?": "Staging",
});
yield* adapter.respondToUserInput(
session.threadId,
ApprovalRequestId.makeUnsafe(requestId!),
{ "Deploy to which env?": "Staging" },
);
// Drain the resolved event.
yield* Stream.runHead(adapter.streamEvents);
+142 -156
View File
@@ -8,7 +8,6 @@
*/
import {
type CanUseTool,
type HookCallback,
query,
type Options as ClaudeQueryOptions,
type PermissionMode,
@@ -56,10 +55,12 @@ import {
FileSystem,
Fiber,
Layer,
Option,
Queue,
Random,
Ref,
Stream,
Schema,
} from "effect";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
@@ -78,8 +79,6 @@ import { ClaudeAdapter, type ClaudeAdapterShape } from "../Services/ClaudeAdapte
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const PROVIDER = "claudeAgent" as const;
const CLAUDE_COMPACT_COMMAND = "/compact";
const CLAUDE_COMPACT_TIMEOUT_MS = 60_000;
type ClaudeTextStreamKind = Extract<RuntimeContentStreamKind, "assistant_text" | "reasoning_text">;
type ClaudeToolResultStreamKind = Extract<
RuntimeContentStreamKind,
@@ -133,10 +132,6 @@ interface PendingUserInput {
readonly answers: Deferred.Deferred<ProviderUserInputAnswers>;
}
interface PendingCompaction {
readonly summary: Deferred.Deferred<string | null>;
}
interface ToolInFlight {
readonly itemId: string;
readonly itemType: CanonicalItemType;
@@ -152,7 +147,7 @@ interface ClaudeSessionContext {
session: ProviderSession;
readonly promptQueue: Queue.Queue<PromptQueueItem>;
readonly query: ClaudeQueryRuntime;
streamFiber: Fiber.Fiber<void, Error> | undefined;
streamFiber: Fiber.Fiber<void, ClaudeStreamError> | undefined;
readonly startedAt: string;
readonly basePermissionMode: PermissionMode | undefined;
currentApiModelId: string | undefined;
@@ -164,12 +159,12 @@ interface ClaudeSessionContext {
items: Array<unknown>;
}>;
readonly inFlightTools: Map<number, ToolInFlight>;
pendingCompaction: PendingCompaction | undefined;
turnState: ClaudeTurnState | undefined;
lastKnownContextWindow: number | undefined;
lastKnownTokenUsage: ThreadTokenUsageSnapshot | undefined;
lastAssistantUuid: string | undefined;
lastThreadStartedId: string | undefined;
interruptRequested: boolean;
stopped: boolean;
}
@@ -190,6 +185,23 @@ export interface ClaudeAdapterLiveOptions {
readonly nativeEventLogger?: EventNdjsonLogger;
}
class ClaudeStreamInterruptedError extends Schema.TaggedErrorClass<ClaudeStreamInterruptedError>()(
"ClaudeStreamInterruptedError",
{
message: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {}
class ClaudeStreamFailedError extends Schema.TaggedErrorClass<ClaudeStreamFailedError>()(
"ClaudeStreamFailedError",
{
message: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {}
const isClaudeStreamInterruptedError = Schema.is(ClaudeStreamInterruptedError);
type ClaudeStreamError = ClaudeStreamInterruptedError | ClaudeStreamFailedError;
function isUuid(value: string): boolean {
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
}
@@ -198,29 +210,6 @@ function isSyntheticClaudeThreadId(value: string): boolean {
return value.startsWith("claude-thread-");
}
function toMessage(cause: unknown, fallback: string): string {
if (cause instanceof Error && cause.message.length > 0) {
return cause.message;
}
return fallback;
}
function toError(cause: unknown, fallback: string): Error {
return cause instanceof Error ? cause : new Error(toMessage(cause, fallback));
}
function normalizeClaudeStreamMessages(cause: Cause.Cause<Error>): ReadonlyArray<string> {
const errors = Cause.prettyErrors(cause)
.map((error) => error.message.trim())
.filter((message) => message.length > 0);
if (errors.length > 0) {
return errors;
}
const squashed = toMessage(Cause.squash(cause), "").trim();
return squashed.length > 0 ? [squashed] : [];
}
function getEffectiveClaudeCodeEffort(
effort: ClaudeCodeEffort | null | undefined,
): Exclude<ClaudeCodeEffort, "ultrathink"> | null {
@@ -239,22 +228,18 @@ function isClaudeInterruptedMessage(message: string): boolean {
);
}
function isClaudeInterruptedCause(cause: Cause.Cause<Error>): boolean {
function isClaudeDiagnosticMessage(message: string): boolean {
return message.toLowerCase().includes("[ede_diagnostic]");
}
function isClaudeInterruptedToolResultMessage(message: string): boolean {
const normalized = message.toLowerCase();
return (
Cause.hasInterruptsOnly(cause) ||
normalizeClaudeStreamMessages(cause).some(isClaudeInterruptedMessage)
normalized.includes("tool use was rejected") ||
normalized.includes("doesn't want to proceed with this tool use")
);
}
function messageFromClaudeStreamCause(cause: Cause.Cause<Error>, fallback: string): string {
return normalizeClaudeStreamMessages(cause)[0] ?? fallback;
}
function interruptionMessageFromClaudeCause(cause: Cause.Cause<Error>): string {
const message = messageFromClaudeStreamCause(cause, "Claude runtime interrupted.");
return isClaudeInterruptedMessage(message) ? "Claude runtime interrupted." : message;
}
function resultErrorsText(result: SDKResultMessage): string {
return "errors" in result && Array.isArray(result.errors)
? result.errors.join(" ").toLowerCase()
@@ -277,7 +262,7 @@ function isInterruptedResult(result: SDKResultMessage): boolean {
}
function asRuntimeItemId(value: string): RuntimeItemId {
return RuntimeItemId.make(value);
return RuntimeItemId.makeUnsafe(value);
}
function maxClaudeContextWindowFromModelUsage(modelUsage: unknown): number | undefined {
@@ -361,7 +346,7 @@ function asCanonicalTurnId(value: TurnId): TurnId {
}
function asRuntimeRequestId(value: ApprovalRequestId): RuntimeRequestId {
return RuntimeRequestId.make(value);
return RuntimeRequestId.makeUnsafe(value);
}
function readClaudeResumeState(resumeCursor: unknown): ClaudeResumeState | undefined {
@@ -379,7 +364,7 @@ function readClaudeResumeState(resumeCursor: unknown): ClaudeResumeState | undef
const threadIdCandidate = typeof cursor.threadId === "string" ? cursor.threadId : undefined;
const threadId =
threadIdCandidate && !isSyntheticClaudeThreadId(threadIdCandidate)
? ThreadId.make(threadIdCandidate)
? ThreadId.makeUnsafe(threadIdCandidate)
: undefined;
const resumeCandidate =
typeof cursor.resume === "string"
@@ -605,7 +590,7 @@ const buildUserMessageEffect = Effect.fn("buildUserMessageEffect")(function* (
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "turn/start",
detail: toMessage(cause, "Failed to read attachment file."),
detail: `Failed to read attachment file: ${cause.message}.`,
cause,
}),
),
@@ -634,6 +619,11 @@ function turnStatusFromResult(result: SDKResultMessage): ProviderRuntimeTurnStat
if (errors.includes("cancel")) {
return "cancelled";
}
if (result.is_error === false) {
return "completed";
}
return "failed";
}
@@ -649,7 +639,7 @@ function nativeProviderRefs(
): NonNullable<ProviderRuntimeEvent["providerRefs"]> {
if (options?.providerItemId) {
return {
providerItemId: ProviderItemId.make(options.providerItemId),
providerItemId: ProviderItemId.makeUnsafe(options.providerItemId),
};
}
return {};
@@ -821,7 +811,7 @@ function toSessionError(
threadId: ThreadId,
cause: unknown,
): ProviderAdapterSessionNotFoundError | ProviderAdapterSessionClosedError | undefined {
const normalized = toMessage(cause, "").toLowerCase();
const normalized = cause instanceof Error ? cause.message.toLowerCase() : "";
if (normalized.includes("unknown session") || normalized.includes("not found")) {
return new ProviderAdapterSessionNotFoundError({
provider: PROVIDER,
@@ -847,7 +837,7 @@ function toRequestError(threadId: ThreadId, method: string, cause: unknown): Pro
return new ProviderAdapterRequestError({
provider: PROVIDER,
method,
detail: toMessage(cause, `${method} failed`),
detail: cause instanceof Error ? `${method} failed: ${cause.message}` : `${method} failed`,
cause,
});
}
@@ -942,7 +932,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const serverSettingsService = yield* ServerSettingsService;
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.make(id));
const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.makeUnsafe(id));
const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });
const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
@@ -975,7 +965,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
? { providerThreadId: message.session_id }
: {}),
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
...(itemId ? { itemId: ProviderItemId.make(itemId) } : {}),
...(itemId ? { itemId: ProviderItemId.makeUnsafe(itemId) } : {}),
payload: message,
},
},
@@ -1330,6 +1320,42 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
});
const handleClaudeStreamError = (
context: ClaudeSessionContext,
cause: Cause.Cause<ClaudeStreamError>,
) => {
if (context.interruptRequested) {
return context.turnState
? completeTurn(context, "interrupted", "Claude runtime interrupted.")
: Effect.void;
}
return Option.match(Cause.findErrorOption(cause), {
onNone: () =>
context.turnState
? completeTurn(context, "failed", "Claude runtime stream failed.")
: Effect.void,
onSome: (streamError) =>
isClaudeStreamInterruptedError(streamError)
? context.turnState
? completeTurn(context, "interrupted", "Claude runtime interrupted.")
: Effect.void
: Effect.gen(function* () {
const message = streamError.message;
if (isClaudeDiagnosticMessage(message)) {
if (context.turnState) {
yield* completeTurn(context, "interrupted", "Claude runtime interrupted.");
}
return;
}
yield* emitRuntimeError(context, message, Cause.pretty(cause));
if (context.turnState) {
yield* completeTurn(context, "failed", message);
}
}),
});
};
const completeTurn = Effect.fn("completeTurn")(function* (
context: ClaudeSessionContext,
status: ProviderRuntimeTurnStatus,
@@ -1489,6 +1515,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const updatedAt = yield* nowIso;
context.turnState = undefined;
context.interruptRequested = false;
context.session = {
...context.session,
status: "ready",
@@ -1736,7 +1763,15 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
}
const [index, tool] = toolEntry;
const itemStatus = toolResult.isError ? "failed" : "completed";
const interruptedToolResult =
context.interruptRequested &&
toolResult.isError &&
isClaudeInterruptedToolResultMessage(toolResult.text);
const itemStatus = interruptedToolResult
? "declined"
: toolResult.isError
? "failed"
: "completed";
const toolData = {
toolName: tool.toolName,
input: tool.input,
@@ -1754,7 +1789,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
itemId: asRuntimeItemId(tool.itemId),
payload: {
itemType: tool.itemType,
status: toolResult.isError ? "failed" : "inProgress",
status: interruptedToolResult ? "declined" : toolResult.isError ? "failed" : "inProgress",
title: tool.title,
...(tool.detail ? { detail: tool.detail } : {}),
data: toolData,
@@ -1830,7 +1865,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
// Auto-start a synthetic turn for assistant messages that arrive without
// an active turn (e.g., background agent/subagent responses between user prompts).
if (!context.turnState) {
const turnId = TurnId.make(yield* Random.nextUUIDv4);
const turnId = TurnId.makeUnsafe(yield* Random.nextUUIDv4);
const startedAt = yield* nowIso;
context.turnState = {
turnId,
@@ -1914,8 +1949,17 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
return;
}
const status = turnStatusFromResult(message);
const errorMessage = message.subtype === "success" ? undefined : message.errors[0];
const status =
context.interruptRequested && message.subtype !== "success"
? "interrupted"
: turnStatusFromResult(message);
// Skip [ede_diagnostic] entries (SDK-internal diagnostics, not user-facing errors).
const errorMessage =
status === "interrupted" && context.interruptRequested
? "Claude runtime interrupted."
: message.subtype === "success"
? undefined
: message.errors.find((entry: string) => !isClaudeDiagnosticMessage(entry));
if (status === "failed") {
yield* emitRuntimeError(context, errorMessage ?? "Claude turn failed.");
@@ -2021,7 +2065,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...base,
type: "task.started",
payload: {
taskId: RuntimeTaskId.make(message.task_id),
taskId: RuntimeTaskId.makeUnsafe(message.task_id),
description: message.description,
...(message.task_type ? { taskType: message.task_type } : {}),
},
@@ -2051,7 +2095,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...base,
type: "task.progress",
payload: {
taskId: RuntimeTaskId.make(message.task_id),
taskId: RuntimeTaskId.makeUnsafe(message.task_id),
description: message.description,
...(message.summary ? { summary: message.summary } : {}),
...(message.usage ? { usage: message.usage } : {}),
@@ -2083,7 +2127,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...base,
type: "task.completed",
payload: {
taskId: RuntimeTaskId.make(message.task_id),
taskId: RuntimeTaskId.makeUnsafe(message.task_id),
status: message.status,
...(message.summary ? { summary: message.summary } : {}),
...(message.usage ? { usage: message.usage } : {}),
@@ -2234,39 +2278,40 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
}
});
const runSdkStream = (context: ClaudeSessionContext): Effect.Effect<void, Error> =>
Stream.fromAsyncIterable(context.query, (cause) =>
toError(cause, "Claude runtime stream failed."),
).pipe(
const runSdkStream = (context: ClaudeSessionContext) =>
Stream.fromAsyncIterable(context.query, (cause) => {
const message =
typeof cause === "string" && cause.trim().length > 0
? cause
: cause instanceof Error && cause.message.trim().length > 0
? cause.message
: "Claude runtime stream failed.";
return isClaudeInterruptedMessage(message)
? new ClaudeStreamInterruptedError({ message, cause })
: new ClaudeStreamFailedError({ message, cause });
}).pipe(
Stream.takeWhile(() => !context.stopped),
Stream.runForEach((message) => handleSdkMessage(context, message)),
);
const handleStreamExit = Effect.fn("handleStreamExit")(function* (
context: ClaudeSessionContext,
exit: Exit.Exit<void, Error>,
exit: Exit.Exit<void, ClaudeStreamError>,
) {
if (context.stopped) {
return;
}
if (Exit.isFailure(exit)) {
if (isClaudeInterruptedCause(exit.cause)) {
if (context.turnState) {
yield* completeTurn(
context,
"interrupted",
interruptionMessageFromClaudeCause(exit.cause),
);
}
} else {
const message = messageFromClaudeStreamCause(exit.cause, "Claude runtime stream failed.");
yield* emitRuntimeError(context, message, Cause.pretty(exit.cause));
yield* completeTurn(context, "failed", message);
}
} else if (context.turnState) {
yield* completeTurn(context, "interrupted", "Claude runtime stream ended.");
}
yield* Exit.match(exit, {
onSuccess: () =>
context.turnState
? completeTurn(context, "interrupted", "Claude runtime stream ended.")
: Effect.void,
onFailure: (cause) =>
Cause.hasInterruptsOnly(cause) && context.turnState
? completeTurn(context, "interrupted", "Claude runtime interrupted.")
: handleClaudeStreamError(context, cause),
});
yield* stopSessionInternal(context, {
emitExitEvent: true,
@@ -2305,11 +2350,6 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
yield* completeTurn(context, "interrupted", "Session stopped.");
}
if (context.pendingCompaction) {
yield* Deferred.succeed(context.pendingCompaction.summary, null).pipe(Effect.ignore);
context.pendingCompaction = undefined;
}
yield* Queue.shutdown(context.promptQueue);
const streamFiber = context.streamFiber;
@@ -2393,9 +2433,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
existingResumeSessionId === undefined ? yield* Random.nextUUIDv4 : undefined;
const sessionId = existingResumeSessionId ?? newSessionId;
const runtimeContext = yield* Effect.context<never>();
const runFork = Effect.runForkWith(runtimeContext);
const runPromise = Effect.runPromiseWith(runtimeContext);
const services = yield* Effect.services();
const runFork = Effect.runForkWith(services);
const runPromise = Effect.runPromiseWith(services);
const promptQueue = yield* Queue.unbounded<PromptQueueItem>();
const prompt = Stream.fromQueue(promptQueue).pipe(
@@ -2412,15 +2452,6 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const inFlightTools = new Map<number, ToolInFlight>();
const contextRef = yield* Ref.make<ClaudeSessionContext | undefined>(undefined);
const postCompactHook: HookCallback = async (hookInput) => {
if (hookInput.hook_event_name === "PostCompact") {
const context = await runPromise(Ref.get(contextRef));
if (context?.pendingCompaction) {
runFork(Deferred.succeed(context.pendingCompaction.summary, hookInput.compact_summary));
}
}
return { continue: true };
};
/**
* Handle AskUserQuestion tool calls by emitting a `user-input.requested`
@@ -2431,7 +2462,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
toolInput: Record<string, unknown>,
callbackOptions: { readonly signal: AbortSignal; readonly toolUseID?: string },
) {
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
const requestId = ApprovalRequestId.makeUnsafe(yield* Random.nextUUIDv4);
// Parse questions from the SDK's AskUserQuestion input.
const rawQuestions = Array.isArray(toolInput.questions) ? toolInput.questions : [];
@@ -2584,7 +2615,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
} satisfies PermissionResult;
}
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
const requestId = ApprovalRequestId.makeUnsafe(yield* Random.nextUUIDv4);
const requestType = classifyRequestType(toolName);
const detail = summarizeToolRequest(toolName, toolInput);
const decisionDeferred = yield* Deferred.make<ProviderApprovalDecision>();
@@ -2742,9 +2773,6 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
canUseTool,
env: process.env,
...(input.cwd ? { additionalDirectories: [input.cwd] } : {}),
hooks: {
PostCompact: [{ hooks: [postCompactHook] }],
},
};
const queryRuntime = yield* Effect.try({
@@ -2757,7 +2785,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId,
detail: toMessage(cause, "Failed to start Claude runtime session."),
detail: `Failed to create Claude runtime query: ${String(cause)}.`,
cause,
}),
});
@@ -2793,12 +2821,12 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
pendingUserInputs,
turns: [],
inFlightTools,
pendingCompaction: undefined,
turnState: undefined,
lastKnownContextWindow: undefined,
lastKnownTokenUsage: undefined,
lastAssistantUuid: resumeState?.resumeSessionAt,
lastThreadStartedId: undefined,
interruptRequested: false,
stopped: false,
};
yield* Ref.set(contextRef, context);
@@ -2916,7 +2944,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
}
const turnId = TurnId.make(yield* Random.nextUUIDv4);
const turnId = TurnId.makeUnsafe(yield* Random.nextUUIDv4);
const turnState: ClaudeTurnState = {
turnId,
startedAt: yield* nowIso,
@@ -2929,6 +2957,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const updatedAt = yield* nowIso;
context.turnState = turnState;
context.interruptRequested = false;
context.session = {
...context.session,
status: "running",
@@ -2970,9 +2999,13 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const interruptTurn: ClaudeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")(
function* (threadId, _turnId) {
const context = yield* requireSession(threadId);
context.interruptRequested = true;
yield* Effect.tryPromise({
try: () => context.query.interrupt(),
catch: (cause) => toRequestError(threadId, "turn/interrupt", cause),
catch: (cause) => {
context.interruptRequested = false;
return toRequestError(threadId, "turn/interrupt", cause);
},
});
},
);
@@ -2984,52 +3017,6 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
);
const compactThread: ClaudeAdapterShape["compactThread"] = Effect.fn("compactThread")(
function* (threadId) {
const context = yield* requireSession(threadId);
if (context.pendingCompaction) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "thread/compact/start",
detail: "Claude thread compaction is already in progress.",
});
}
const summary = yield* Deferred.make<string | null>();
context.pendingCompaction = { summary };
yield* Queue.offer(context.promptQueue, {
type: "message",
message: buildUserMessage({
sdkContent: [{ type: "text", text: CLAUDE_COMPACT_COMMAND }],
}),
}).pipe(Effect.mapError((cause) => toRequestError(threadId, "thread/compact/start", cause)));
return yield* Deferred.await(summary).pipe(
Effect.raceFirst(
Effect.sleep(CLAUDE_COMPACT_TIMEOUT_MS).pipe(
Effect.flatMap(() =>
Effect.fail(
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "thread/compact/start",
detail: "Timed out waiting for Claude thread compaction.",
}),
),
),
),
),
Effect.ensuring(
Effect.sync(() => {
if (context.pendingCompaction?.summary === summary) {
context.pendingCompaction = undefined;
}
}),
),
);
},
);
const rollbackThread: ClaudeAdapterShape["rollbackThread"] = Effect.fn("rollbackThread")(
function* (threadId, numTurns) {
const context = yield* requireSession(threadId);
@@ -3122,7 +3109,6 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
sendTurn,
interruptTurn,
readThread,
compactThread,
rollbackThread,
respondToRequest,
respondToUserInput,
+61 -110
View File
@@ -4,16 +4,12 @@ import type {
ServerProvider,
ServerProviderModel,
ServerProviderAuth,
ServerProviderSlashCommand,
ServerProviderState,
} from "@t3tools/contracts";
import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import {
query as claudeQuery,
type SlashCommand as ClaudeSlashCommand,
} from "@anthropic-ai/claude-agent-sdk";
import { query as claudeQuery } from "@anthropic-ai/claude-agent-sdk";
import {
buildServerProvider,
@@ -280,6 +276,18 @@ function extractClaudeAuthMethodFromOutput(result: CommandResult): string | unde
return Option.getOrUndefined(findAuthMethod(parsed.success));
}
// ── Dynamic model capability adjustment ─────────────────────────────
/** Subscription types where the 1M context window is included in the plan. */
const PREMIUM_SUBSCRIPTION_TYPES = new Set([
"max",
"maxplan",
"max5",
"max20",
"enterprise",
"team",
]);
function toTitleCaseWords(value: string): string {
return value
.split(/[\s_-]+/g)
@@ -340,78 +348,45 @@ function claudeAuthMetadata(input: {
return undefined;
}
/**
* Adjust the built-in model list based on the user's detected subscription.
*
* - Premium tiers (Max, Enterprise, Team): 1M context becomes the default.
* - Other tiers (Pro, free, unknown): 200k context stays the default;
* 1M remains available as a manual option so users can still enable it.
*/
export function adjustModelsForSubscription(
baseModels: ReadonlyArray<ServerProviderModel>,
subscriptionType: string | undefined,
): ReadonlyArray<ServerProviderModel> {
const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
if (!normalized || !PREMIUM_SUBSCRIPTION_TYPES.has(normalized)) {
return baseModels;
}
// Flip 1M to be the default for premium users
return baseModels.map((model) => {
const caps = model.capabilities;
if (!caps || caps.contextWindowOptions.length === 0) return model;
return {
...model,
capabilities: {
...caps,
contextWindowOptions: caps.contextWindowOptions.map((opt) =>
opt.value === "1m"
? { value: opt.value, label: opt.label, isDefault: true as const }
: { value: opt.value, label: opt.label },
),
},
};
});
}
// ── SDK capability probe ────────────────────────────────────────────
const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
function nonEmptyProbeString(value: string): string | undefined {
const candidate = value.trim();
return candidate ? candidate : undefined;
}
function parseClaudeInitializationCommands(
commands: ReadonlyArray<ClaudeSlashCommand> | undefined,
): ReadonlyArray<ServerProviderSlashCommand> {
return dedupeSlashCommands(
(commands ?? []).flatMap((command) => {
const name = nonEmptyProbeString(command.name);
if (!name) {
return [];
}
const description = nonEmptyProbeString(command.description);
const argumentHint = nonEmptyProbeString(command.argumentHint);
return [
{
name,
...(description ? { description } : {}),
...(argumentHint ? { input: { hint: argumentHint } } : {}),
} satisfies ServerProviderSlashCommand,
];
}),
);
}
function dedupeSlashCommands(
commands: ReadonlyArray<ServerProviderSlashCommand>,
): ReadonlyArray<ServerProviderSlashCommand> {
const commandsByName = new Map<string, ServerProviderSlashCommand>();
for (const command of commands) {
const name = nonEmptyProbeString(command.name);
if (!name) {
continue;
}
const key = name.toLowerCase();
const existing = commandsByName.get(key);
if (!existing) {
commandsByName.set(key, {
...command,
name,
});
continue;
}
commandsByName.set(key, {
...existing,
...(existing.description
? {}
: command.description
? { description: command.description }
: {}),
...(existing.input?.hint
? {}
: command.input?.hint
? { input: { hint: command.input.hint } }
: {}),
});
}
return [...commandsByName.values()];
}
/**
* Probe account information by spawning a lightweight Claude Agent SDK
* session and reading the initialization result.
@@ -433,16 +408,13 @@ const probeClaudeCapabilities = (binaryPath: string) => {
pathToClaudeCodeExecutable: binaryPath,
abortController: abort,
maxTurns: 0,
settingSources: ["user", "project", "local"],
settingSources: [],
allowedTools: [],
stderr: () => {},
},
});
const init = await q.initializationResult();
return {
subscriptionType: init.account?.subscriptionType,
slashCommands: parseClaudeInitializationCommands(init.commands),
};
return { subscriptionType: init.account?.subscriptionType };
}).pipe(
Effect.ensuring(
Effect.sync(() => {
@@ -471,9 +443,6 @@ const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (args: Readonly
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
resolveSubscriptionType?: (binaryPath: string) => Effect.Effect<string | undefined>,
resolveSlashCommands?: (
binaryPath: string,
) => Effect.Effect<ReadonlyArray<ServerProviderSlashCommand> | undefined>,
): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
@@ -526,7 +495,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
: `Failed to execute Claude Agent CLI health check: ${error.message}.`,
},
});
}
@@ -569,14 +538,6 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
});
}
const slashCommands =
(resolveSlashCommands
? yield* resolveSlashCommands(claudeSettings.binaryPath).pipe(
Effect.orElseSucceed(() => undefined),
)
: undefined) ?? [];
const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
// ── Auth check + subscription detection ────────────────────────────
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
@@ -602,6 +563,8 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
subscriptionType = yield* resolveSubscriptionType(claudeSettings.binaryPath);
}
const resolvedModels = adjustModelsForSubscription(models, subscriptionType);
// ── Handle auth results (same logic as before, adjusted models) ──
if (Result.isFailure(authProbe)) {
@@ -610,17 +573,13 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
slashCommands: dedupedSlashCommands,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message:
error instanceof Error
? `Could not verify Claude authentication status: ${error.message}.`
: "Could not verify Claude authentication status.",
message: `Could not verify Claude authentication status: ${error.message}.`,
},
});
}
@@ -630,8 +589,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
slashCommands: dedupedSlashCommands,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
@@ -648,8 +606,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
slashCommands: dedupedSlashCommands,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
@@ -672,18 +629,12 @@ export const ClaudeProviderLive = Layer.effect(
const subscriptionProbeCache = yield* Cache.make({
capacity: 1,
timeToLive: Duration.minutes(5),
lookup: (binaryPath: string) => probeClaudeCapabilities(binaryPath),
lookup: (binaryPath: string) =>
probeClaudeCapabilities(binaryPath).pipe(Effect.map((r) => r?.subscriptionType)),
});
const checkProvider = checkClaudeProviderStatus(
(binaryPath) =>
Cache.get(subscriptionProbeCache, binaryPath).pipe(
Effect.map((probe) => probe?.subscriptionType),
),
(binaryPath) =>
Cache.get(subscriptionProbeCache, binaryPath).pipe(
Effect.map((probe) => probe?.slashCommands),
),
const checkProvider = checkClaudeProviderStatus((binaryPath) =>
Cache.get(subscriptionProbeCache, binaryPath),
).pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
@@ -28,10 +28,10 @@ import { CodexAdapter } from "../Services/CodexAdapter.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
import { makeCodexAdapterLive } from "./CodexAdapter.ts";
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
const asTurnId = (value: string): TurnId => TurnId.make(value);
const asEventId = (value: string): EventId => EventId.make(value);
const asItemId = (value: string): ProviderItemId => ProviderItemId.make(value);
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
class FakeCodexManager extends CodexAppServerManager {
public startSessionImpl = vi.fn(
@@ -65,11 +65,6 @@ class FakeCodexManager extends CodexAppServerManager {
turns: [],
}));
public compactThreadImpl = vi.fn(async (_threadId: ThreadId) => ({
threadId: asThreadId("thread-1"),
turns: [],
}));
public rollbackThreadImpl = vi.fn(async (_threadId: ThreadId, _numTurns: number) => ({
threadId: asThreadId("thread-1"),
turns: [],
@@ -109,10 +104,6 @@ class FakeCodexManager extends CodexAppServerManager {
return this.readThreadImpl(threadId);
}
override compactThread(threadId: ThreadId) {
return this.compactThreadImpl(threadId);
}
override rollbackThread(threadId: ThreadId, numTurns: number) {
return this.rollbackThreadImpl(threadId, numTurns);
}
@@ -247,7 +238,14 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
.pipe(Effect.result);
assert.equal(result._tag, "Failure");
if (result._tag !== "Failure") {
return;
}
assert.equal(result.failure._tag, "ProviderAdapterSessionNotFoundError");
if (result.failure._tag !== "ProviderAdapterSessionNotFoundError") {
return;
}
assert.equal(result.failure.provider, "codex");
assert.equal(result.failure.threadId, "sess-missing");
assert.equal(result.failure.cause instanceof Error, true);
@@ -558,7 +556,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "serverRequest/resolved",
requestId: ApprovalRequestId.make("req-1"),
requestId: ApprovalRequestId.makeUnsafe("req-1"),
payload: {
request: {
method: "item/commandExecution/requestApproval",
@@ -594,7 +592,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "serverRequest/resolved",
requestId: ApprovalRequestId.make("req-file-read-1"),
requestId: ApprovalRequestId.makeUnsafe("req-file-read-1"),
payload: {
request: {
method: "item/fileRead/requestApproval",
@@ -712,7 +710,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "item/tool/requestUserInput",
requestId: ApprovalRequestId.make("req-user-input-1"),
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
payload: {
questions: [
{
@@ -737,7 +735,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "item/tool/requestUserInput/answered",
requestId: ApprovalRequestId.make("req-user-input-1"),
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
payload: {
answers: {
sandbox_mode: {
+20 -21
View File
@@ -22,7 +22,7 @@ import {
TurnId,
ProviderSendTurnInput,
} from "@t3tools/contracts";
import { Effect, FileSystem, Layer, Queue, Schema, Context, Stream } from "effect";
import { Effect, FileSystem, Layer, Queue, Schema, ServiceMap, Stream } from "effect";
import {
ProviderAdapterProcessError,
@@ -40,23 +40,29 @@ import {
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { extractCompactionSummaryFromSnapshot } from "../handoffSummary.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const PROVIDER = "codex" as const;
export interface CodexAdapterLiveOptions {
readonly manager?: CodexAppServerManager;
readonly makeManager?: (services?: Context.Context<never>) => CodexAppServerManager;
readonly makeManager?: (services?: ServiceMap.ServiceMap<never>) => CodexAppServerManager;
readonly nativeEventLogPath?: string;
readonly nativeEventLogger?: EventNdjsonLogger;
}
function toMessage(cause: unknown, fallback: string): string {
if (cause instanceof Error && cause.message.length > 0) {
return cause.message;
}
return fallback;
}
function toSessionError(
threadId: ThreadId,
cause: unknown,
): ProviderAdapterSessionNotFoundError | ProviderAdapterSessionClosedError | undefined {
const normalized = cause instanceof Error ? cause.message.toLowerCase() : "";
const normalized = toMessage(cause, "").toLowerCase();
if (normalized.includes("unknown session") || normalized.includes("unknown provider session")) {
return new ProviderAdapterSessionNotFoundError({
provider: PROVIDER,
@@ -82,7 +88,7 @@ function toRequestError(threadId: ThreadId, method: string, cause: unknown): Pro
return new ProviderAdapterRequestError({
provider: PROVIDER,
method,
detail: cause instanceof Error ? `${method} failed: ${cause.message}` : `${method} failed`,
detail: toMessage(cause, `${method} failed`),
cause,
});
}
@@ -156,11 +162,11 @@ function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | un
}
function toTurnId(value: string | undefined): TurnId | undefined {
return value?.trim() ? TurnId.make(value) : undefined;
return value?.trim() ? TurnId.makeUnsafe(value) : undefined;
}
function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
return value?.trim() ? ProviderItemId.make(value) : undefined;
return value?.trim() ? ProviderItemId.makeUnsafe(value) : undefined;
}
function toTurnStatus(value: unknown): "completed" | "failed" | "cancelled" | "interrupted" {
@@ -448,15 +454,15 @@ function extractProposedPlanMarkdown(text: string | undefined): string | undefin
}
function asRuntimeItemId(itemId: ProviderItemId): RuntimeItemId {
return RuntimeItemId.make(itemId);
return RuntimeItemId.makeUnsafe(itemId);
}
function asRuntimeRequestId(requestId: string): RuntimeRequestId {
return RuntimeRequestId.make(requestId);
return RuntimeRequestId.makeUnsafe(requestId);
}
function asRuntimeTaskId(taskId: string): RuntimeTaskId {
return RuntimeTaskId.make(taskId);
return RuntimeTaskId.makeUnsafe(taskId);
}
function codexEventMessage(
@@ -1360,7 +1366,7 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
if (options?.manager) {
return options.manager;
}
const services = yield* Effect.context<never>();
const services = yield* Effect.services<never>();
return options?.makeManager?.(services) ?? new CodexAppServerManager(services);
});
@@ -1421,7 +1427,7 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: `Failed to start Codex adapter session: ${cause instanceof Error ? cause.message : String(cause)}.`,
detail: toMessage(cause, "Failed to start Codex adapter session."),
cause,
}),
});
@@ -1449,7 +1455,7 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "turn/start",
detail: `Failed to read attachment file: ${cause.message}.`,
detail: toMessage(cause, "Failed to read attachment file."),
cause,
}),
),
@@ -1515,12 +1521,6 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
})),
);
const compactThread: CodexAdapterShape["compactThread"] = (threadId) =>
Effect.tryPromise({
try: () => manager.compactThread(threadId),
catch: (cause) => toRequestError(threadId, "thread/compact/start", cause),
}).pipe(Effect.map((snapshot) => extractCompactionSummaryFromSnapshot(snapshot)));
const rollbackThread: CodexAdapterShape["rollbackThread"] = (threadId, numTurns) => {
if (!Number.isInteger(numTurns) || numTurns < 1) {
return Effect.fail(
@@ -1585,7 +1585,7 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
});
const registerListener = Effect.fn("registerListener")(function* () {
const services = yield* Effect.context<never>();
const services = yield* Effect.services<never>();
const listenerEffect = Effect.fn("listener")(function* (event: ProviderEvent) {
yield* writeNativeEvent(event);
const runtimeEvents = mapToRuntimeEvents(event, event.threadId);
@@ -1626,7 +1626,6 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
sendTurn,
interruptTurn,
readThread,
compactThread,
rollbackThread,
respondToRequest,
respondToUserInput,
Loaded 100 of 234 files, more files were not shown because too many files have changed in this diff. Show more