Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge f6f1b9c4a3 Instrument workspace entries tests via service construction
Co-authored-by: Julius Marminge <[email protected]>
2026-05-24 16:10:32 +00:00
Cursor AgentandJulius Marminge d283d94ad3 Fix workspace entries filesystem test layer
Co-authored-by: Julius Marminge <[email protected]>
2026-05-24 16:09:42 +00:00
Cursor AgentandJulius Marminge 63a9c85c26 Use Effect FileSystem for workspace entries
Co-authored-by: Julius Marminge <[email protected]>
2026-05-24 16:09:10 +00:00
51 changed files with 1018 additions and 1234 deletions

No files matched your search

-8
View File
@@ -46,14 +46,6 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Ensure Electron runtime is installed
run: |
if ! node -e "require('./apps/desktop/node_modules/electron')" >/dev/null 2>&1; then
rm -rf apps/desktop/node_modules/electron/dist apps/desktop/node_modules/electron/path.txt
bun apps/desktop/node_modules/electron/install.js
fi
node -e "require('./apps/desktop/node_modules/electron')"
- name: Format
run: bun run fmt:check
+2 -3
View File
@@ -1,8 +1,8 @@
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Random from "effect/Random";
import * as Ref from "effect/Ref";
import * as NetService from "@t3tools/shared/Net";
@@ -26,8 +26,7 @@ const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
const MAX_TCP_PORT = 65_535;
const DESKTOP_BACKEND_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::"] as const;
const makeDesktopRunId = Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomUUIDv4),
const makeDesktopRunId = Random.nextUUIDv4.pipe(
Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
);
@@ -1,12 +1,10 @@
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Random from "effect/Random";
import * as Ref from "effect/Ref";
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
@@ -15,10 +13,7 @@ import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
export interface DesktopBackendConfigurationShape {
readonly resolve: Effect.Effect<
DesktopBackendManager.DesktopBackendStartConfig,
PlatformError.PlatformError
>;
readonly resolve: Effect.Effect<DesktopBackendManager.DesktopBackendStartConfig>;
}
export class DesktopBackendConfiguration extends Context.Service<
@@ -85,6 +80,23 @@ const readPersistedBackendObservabilitySettings: Effect.Effect<
};
});
const getOrCreateBootstrapToken = Effect.fn("desktop.backendConfiguration.bootstrapToken")(
function* (tokenRef: Ref.Ref<Option.Option<string>>) {
const existing = yield* Ref.get(tokenRef);
if (Option.isSome(existing)) {
return existing.value;
}
let token = "";
while (token.length < 48) {
token += (yield* Random.nextUUIDv4).replace(/-/g, "");
}
token = token.slice(0, 48);
yield* Ref.set(tokenRef, Option.some(token));
return token;
},
);
const resolveBackendStartConfig = Effect.fn("desktop.backendConfiguration.resolveStartConfig")(
function* (input: {
readonly bootstrapToken: string;
@@ -136,22 +148,11 @@ export const layer = Layer.effect(
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const crypto = yield* Crypto.Crypto;
const tokenRef = yield* Ref.make(Option.none<string>());
const getOrCreateBootstrapToken = Effect.gen(function* () {
const existing = yield* Ref.get(tokenRef);
if (Option.isSome(existing)) {
return existing.value;
}
const token = Encoding.encodeHex(yield* crypto.randomBytes(24));
yield* Ref.set(tokenRef, Option.some(token));
return token;
});
return DesktopBackendConfiguration.of({
resolve: Effect.gen(function* () {
const bootstrapToken = yield* getOrCreateBootstrapToken;
const bootstrapToken = yield* getOrCreateBootstrapToken(tokenRef);
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
@@ -329,19 +329,9 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
}
yield* Ref.set(desktopState.backendReady, false);
const config = yield* configuration.resolve.pipe(
Effect.tapError((error) =>
logBackendManagerError("failed to generate desktop backend configuration", {
cause: error.message,
}),
),
Effect.option,
);
if (Option.isNone(config)) {
return;
}
const config = yield* configuration.resolve;
const entryExists = yield* fileSystem
.exists(config.value.entryPath)
.exists(config.entryPath)
.pipe(Effect.orElseSucceed(() => false));
yield* cancelRestart;
@@ -349,11 +339,11 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
...latest,
desiredRunning: true,
ready: false,
config: Option.some(config.value),
config: Option.some(config),
}));
if (!entryExists) {
yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
yield* scheduleRestart(`missing server entry at ${config.entryPath}`);
return;
}
@@ -435,7 +425,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
});
const program = runBackendProcess({
...config.value,
...config,
onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
yield* updateActiveRun(runId, (run) => ({
...run,
@@ -443,7 +433,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
}));
yield* backendOutputLog.writeSessionBoundary({
phase: "START",
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
details: `pid=${pid} port=${config.bootstrap.port} cwd=${config.cwd}`,
});
}),
onReady: Effect.fn("desktop.backendManager.onReady")(function* () {
+10 -16
View File
@@ -6,7 +6,6 @@ import {
} from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -14,6 +13,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Random from "effect/Random";
import * as Schema from "effect/Schema";
import * as SynchronizedRef from "effect/SynchronizedRef";
@@ -222,10 +222,10 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp
readonly settingsPath: string;
readonly settings: DesktopSettings;
readonly defaultSettings: DesktopSettings;
readonly suffix: string;
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.settingsPath);
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
const suffix = (yield* Random.nextUUIDv4).replace(/-/g, "");
const tempPath = `${input.settingsPath}.${process.pid}.${suffix}.tmp`;
const encoded = yield* encodeDesktopSettingsJson(
toDesktopSettingsDocument(input.settings, input.defaultSettings),
);
@@ -240,7 +240,6 @@ export const layer = Layer.effect(
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const crypto = yield* Crypto.Crypto;
const settingsRef = yield* SynchronizedRef.make(environment.defaultDesktopSettings);
const persist = (
@@ -252,18 +251,13 @@ export const layer = Layer.effect(
return Effect.succeed([settingsChange(settings, false), settings] as const);
}
return crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.flatMap((suffix) =>
writeSettings({
fileSystem,
path,
settingsPath: environment.desktopSettingsPath,
settings: nextSettings,
defaultSettings: environment.defaultDesktopSettings,
suffix,
}),
),
return writeSettings({
fileSystem,
path,
settingsPath: environment.desktopSettingsPath,
settings: nextSettings,
defaultSettings: environment.defaultDesktopSettings,
}).pipe(
Effect.mapError((cause) => new DesktopSettingsWriteError({ cause })),
Effect.as([settingsChange(nextSettings, true), nextSettings] as const),
);
@@ -1,7 +1,6 @@
import { ClientSettingsSchema, type ClientSettings } from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -9,6 +8,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Random from "effect/Random";
import * as Schema from "effect/Schema";
import * as Ref from "effect/Ref";
@@ -74,10 +74,10 @@ const writeClientSettings = Effect.fnUntraced(function* (input: {
readonly path: Path.Path;
readonly settingsPath: string;
readonly settings: ClientSettings;
readonly suffix: string;
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.settingsPath);
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
const suffix = (yield* Random.nextUUIDv4).replace(/-/g, "");
const tempPath = `${input.settingsPath}.${process.pid}.${suffix}.tmp`;
const encoded = yield* encodeClientSettingsJson(input.settings);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
@@ -90,24 +90,18 @@ export const layer = Layer.effect(
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const crypto = yield* Crypto.Crypto;
return DesktopClientSettings.of({
get: readClientSettings(fileSystem, environment.clientSettingsPath).pipe(
Effect.withSpan("desktop.clientSettings.get"),
),
set: (settings) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.flatMap((suffix) =>
writeClientSettings({
fileSystem,
path,
settingsPath: environment.clientSettingsPath,
settings,
suffix,
}),
),
writeClientSettings({
fileSystem,
path,
settingsPath: environment.clientSettingsPath,
settings,
}).pipe(
Effect.mapError((cause) => new DesktopClientSettingsWriteError({ cause })),
Effect.withSpan("desktop.clientSettings.set"),
),
@@ -1,7 +1,6 @@
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
@@ -10,6 +9,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Random from "effect/Random";
import * as Schema from "effect/Schema";
import * as Ref from "effect/Ref";
@@ -200,10 +200,10 @@ const writeRegistryDocument = Effect.fn("desktop.savedEnvironments.writeRegistry
readonly path: Path.Path;
readonly registryPath: string;
readonly document: SavedEnvironmentRegistryDocument;
readonly suffix: string;
}): Effect.fn.Return<void, PlatformError.PlatformError | Schema.SchemaError> {
const directory = input.path.dirname(input.registryPath);
const tempPath = `${input.registryPath}.${process.pid}.${input.suffix}.tmp`;
const suffix = (yield* Random.nextUUIDv4).replace(/-/g, "");
const tempPath = `${input.registryPath}.${process.pid}.${suffix}.tmp`;
const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document);
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
@@ -247,22 +247,14 @@ export const layer = Layer.effect(
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const crypto = yield* Crypto.Crypto;
const writeDocument = (document: SavedEnvironmentRegistryDocument) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.flatMap((suffix) =>
writeRegistryDocument({
fileSystem,
path,
registryPath: environment.savedEnvironmentRegistryPath,
document,
suffix,
}),
),
Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })),
);
writeRegistryDocument({
fileSystem,
path,
registryPath: environment.savedEnvironmentRegistryPath,
document,
}).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
return DesktopSavedEnvironments.of({
getRegistry: readRegistryDocument(fileSystem, environment.savedEnvironmentRegistryPath).pipe(
@@ -1,5 +1,4 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
@@ -87,7 +86,6 @@ function makeElectronWindowLayer(window: ReturnType<typeof makeTestWindow>["wind
function makeLayer(window: ReturnType<typeof makeTestWindow>["window"]) {
return DesktopSshPasswordPrompts.layer({ passwordPromptTimeoutMs: 1_000 }).pipe(
Layer.provide(makeElectronWindowLayer(window)),
Layer.provide(NodeServices.layer),
Layer.provideMerge(TestClock.layer()),
);
}
@@ -2,7 +2,6 @@ import type { DesktopSshPasswordPromptRequest } from "@t3tools/contracts";
import { DesktopSshPasswordPromptResolutionInputSchema } from "@t3tools/contracts";
import type { SshPasswordRequest } from "@t3tools/ssh/auth";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
@@ -10,6 +9,7 @@ import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Random from "effect/Random";
import * as Ref from "effect/Ref";
import * as IpcChannels from "../ipc/channels.ts";
@@ -163,7 +163,6 @@ const failPending = (
const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: LayerOptions = {}) {
const electronWindow = yield* ElectronWindow.ElectronWindow;
const crypto = yield* Crypto.Crypto;
const pendingRef = yield* Ref.make(new Map<string, PendingSshPasswordPrompt>());
const passwordPromptTimeoutMs =
options.passwordPromptTimeoutMs ?? DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS;
@@ -231,11 +230,7 @@ const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: La
});
}
const requestId = yield* crypto.randomUUIDv4.pipe(
Effect.mapError(
() => new DesktopSshPromptUnavailableError({ reason: "Secure randomness is unavailable." }),
),
);
const requestId = yield* Random.nextUUIDv4;
const now = yield* DateTime.now;
const expiresAt = DateTime.formatIso(
DateTime.add(now, { milliseconds: passwordPromptTimeoutMs }),
@@ -11,8 +11,8 @@ import {
ProviderDriverKind,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Crypto from "effect/Crypto";
import * as Queue from "effect/Queue";
import * as Random from "effect/Random";
import * as Stream from "effect/Stream";
import {
@@ -226,7 +226,6 @@ function missingSessionEffect(
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
Effect.gen(function* () {
const provider = options?.provider ?? ProviderDriverKind.make("codex");
const crypto = yield* Crypto.Crypto;
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
let sessionCount = 0;
const sessions = new Map<ThreadId, SessionState>();
@@ -242,18 +241,6 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
>();
const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event);
const randomUUIDv4 = (threadId: ThreadId) =>
crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterValidationError({
provider,
operation: "crypto/randomUUIDv4",
issue: `Failed to generate test runtime identifier for thread '${threadId}'.`,
cause,
}),
),
);
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
Effect.gen(function* () {
@@ -322,7 +309,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
for (const fixtureEvent of response.events) {
const rawEvent: Record<string, unknown> = {
...(fixtureEvent as Record<string, unknown>),
eventId: yield* randomUUIDv4(input.threadId),
eventId: yield* Random.nextUUIDv4,
provider,
sessionId: RuntimeSessionId.make(String(input.threadId)),
};
@@ -379,7 +366,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
if (deferredTurnCompletedEvents.length === 0) {
yield* emit({
type: "turn.completed",
eventId: EventId.make(yield* randomUUIDv4(input.threadId)),
eventId: EventId.make(yield* Random.nextUUIDv4),
provider,
createdAt: nowIso(),
threadId: state.snapshot.threadId,
+3 -1
View File
@@ -1,6 +1,7 @@
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Random from "effect/Random";
export const writeFileStringAtomically = (input: {
readonly filePath: string;
@@ -10,6 +11,7 @@ export const writeFileStringAtomically = (input: {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempFileId = yield* Random.nextUUIDv4;
const targetDirectory = path.dirname(input.filePath);
yield* fs.makeDirectory(targetDirectory, { recursive: true });
@@ -17,7 +19,7 @@ export const writeFileStringAtomically = (input: {
directory: targetDirectory,
prefix: `${path.basename(input.filePath)}.`,
});
const tempPath = path.join(tempDirectory, "contents.tmp");
const tempPath = path.join(tempDirectory, `${tempFileId}.tmp`);
yield* fs.writeFileString(tempPath, input.contents);
yield* fs.rename(tempPath, input.filePath);
+5 -16
View File
@@ -5,7 +5,6 @@ import {
type ClientOrchestrationCommand,
} from "@t3tools/contracts";
import * as Console from "effect/Console";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
@@ -59,16 +58,6 @@ class ProjectCommandError extends Data.TaggedError("ProjectCommandError")<{
readonly message: string;
}> {}
const projectCommandUuid = Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomUUIDv4),
Effect.mapError(
() =>
new ProjectCommandError({
message: "Failed to generate a project command identifier.",
}),
),
);
const ProjectCliRuntimeLive = Layer.mergeAll(
WorkspacePathsLive,
OrchestrationLayerLive.pipe(
@@ -271,7 +260,7 @@ const runProjectMutation = Effect.fn("runProjectMutation")(function* (
}) => Effect.Effect<
string,
Error,
Crypto.Crypto | FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | WorkspacePaths
FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | WorkspacePaths
>,
) {
const logLevel = yield* GlobalFlag.LogLevel;
@@ -354,10 +343,10 @@ const projectAddCommand = Command.make("add", {
}
const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
const projectId = ProjectId.make(yield* projectCommandUuid);
const projectId = ProjectId.make(crypto.randomUUID());
yield* dispatch({
type: "project.create",
commandId: CommandId.make(yield* projectCommandUuid),
commandId: CommandId.make(crypto.randomUUID()),
projectId,
title,
workspaceRoot,
@@ -395,7 +384,7 @@ const projectRemoveCommand = Command.make("remove", {
});
yield* dispatch({
type: "project.delete",
commandId: CommandId.make(yield* projectCommandUuid),
commandId: CommandId.make(crypto.randomUUID()),
projectId: project.id,
});
return `Removed project ${project.id} (${project.title}).`;
@@ -435,7 +424,7 @@ const projectRenameCommand = Command.make("rename", {
yield* dispatch({
type: "project.meta.update",
commandId: CommandId.make(yield* projectCommandUuid),
commandId: CommandId.make(crypto.randomUUID()),
projectId: project.id,
title: nextTitle,
});
@@ -1,9 +1,9 @@
import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Random from "effect/Random";
import { ServerConfig } from "../../config.ts";
import { layer as ProcessRunnerLive } from "../../processRunner.ts";
@@ -39,7 +39,6 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const crypto = yield* Crypto.Crypto;
const readPersistedEnvironmentId = Effect.gen(function* () {
const exists = yield* fileSystem
@@ -65,7 +64,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
return persisted;
}
const generated = yield* crypto.randomUUIDv4;
const generated = yield* Random.nextUUIDv4;
yield* persistEnvironmentId(generated);
return generated;
});
+22 -28
View File
@@ -1,7 +1,8 @@
import { randomUUID } from "node:crypto";
import * as Arr from "effect/Array";
import * as Cache from "effect/Cache";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -531,39 +532,32 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const sourceControlProviders = yield* SourceControlProviderRegistry;
const textGeneration = yield* TextGeneration;
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
const crypto = yield* Crypto.Crypto;
const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });
const serverSettingsService = yield* ServerSettingsService;
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
Effect.mapError((cause) =>
gitManagerError("randomUUIDv4", "Failed to generate Git operation identifier.", cause),
),
);
const createProgressEmitter = (
input: { cwd: string; action: GitStackedAction },
options?: GitRunStackedActionOptions,
) =>
(options?.actionId === undefined ? randomUUIDv4 : Effect.succeed(options.actionId)).pipe(
Effect.map((actionId) => {
const reporter = options?.progressReporter;
const emit = (event: GitActionProgressPayload) =>
reporter
? reporter.publish({
actionId,
cwd: input.cwd,
action: input.action,
...event,
} as GitActionProgressEvent)
: Effect.void;
) => {
const actionId = options?.actionId ?? randomUUID();
const reporter = options?.progressReporter;
return {
actionId,
emit,
};
}),
);
const emit = (event: GitActionProgressPayload) =>
reporter
? reporter.publish({
actionId,
cwd: input.cwd,
action: input.action,
...event,
} as GitActionProgressEvent)
: Effect.void;
return {
actionId,
emit,
};
};
const configurePullRequestHeadUpstreamBase = Effect.fn("configurePullRequestHeadUpstream")(
function* (
@@ -1307,7 +1301,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
modelSelection,
});
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${yield* randomUUIDv4}.md`);
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
yield* fileSystem
.writeFileString(bodyFile, generated.body)
.pipe(
@@ -1597,7 +1591,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fn("runStackedAction")(
function* (input, options) {
const progress = yield* createProgressEmitter(input, options);
const progress = createProgressEmitter(input, options);
const currentPhase = yield* Ref.make<Option.Option<GitActionProgressPhase>>(Option.none());
const runAction = Effect.fn("runStackedAction.runAction")(function* (): Effect.fn.Return<
@@ -211,7 +211,6 @@ describe("OrchestrationEngine", () => {
Layer.provide(Layer.succeed(OrchestrationEventStore, eventStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(SqlitePersistenceMemory),
Layer.provideMerge(NodeServices.layer),
);
const runtime = ManagedRuntime.make(layer);
@@ -7,7 +7,6 @@ import type {
import { OrchestrationCommand } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
@@ -82,7 +81,6 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const commandReceiptRepository = yield* OrchestrationCommandReceiptRepository;
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const crypto = yield* Crypto.Crypto;
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
let commandReadModel = createEmptyReadModel(yield* nowIso);
@@ -153,18 +151,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const eventBase = yield* decideOrchestrationCommand({
command: envelope.command,
readModel: commandReadModel,
}).pipe(
Effect.provideService(Crypto.Crypto, crypto),
Effect.mapError((cause) =>
isOrchestrationCommandInvariantError(cause)
? cause
: new OrchestrationCommandInvariantError({
commandType: envelope.command.type,
detail: "Failed to generate an event identifier.",
cause,
}),
),
);
});
const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
const committedCommand = yield* sql
.withTransaction(
@@ -15,7 +15,6 @@ import {
import { isTemporaryWorktreeBranch, WORKTREE_BRANCH_PREFIX } from "@t3tools/shared/git";
import * as Cache from "effect/Cache";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
@@ -82,6 +81,9 @@ function mapProviderSessionStatusToOrchestrationStatus(
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()}`);
const HANDLED_TURN_START_KEY_MAX = 10_000;
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
@@ -176,7 +178,6 @@ function buildGeneratedWorktreeBranchName(raw: string): string {
}
const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const providerService = yield* ProviderService;
@@ -184,9 +185,6 @@ const make = Effect.gen(function* () {
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const textGeneration = yield* TextGeneration;
const serverSettingsService = yield* ServerSettingsService;
const serverCommandId = (tag: string) =>
crypto.randomUUIDv4.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));
const serverEventId = () => crypto.randomUUIDv4.pipe(Effect.map(EventId.make));
const handledTurnStartKeys = yield* Cache.make<string, true>({
capacity: HANDLED_TURN_START_KEY_MAX,
timeToLive: HANDLED_TURN_START_KEY_TTL,
@@ -216,31 +214,24 @@ const make = Effect.gen(function* () {
readonly createdAt: string;
readonly requestId?: string;
}) =>
Effect.all({
orchestrationEngine.dispatch({
type: "thread.activity.append",
commandId: serverCommandId("provider-failure-activity"),
eventId: serverEventId(),
}).pipe(
Effect.flatMap(({ commandId, eventId }) =>
orchestrationEngine.dispatch({
type: "thread.activity.append",
commandId,
threadId: input.threadId,
activity: {
id: eventId,
tone: "error",
kind: input.kind,
summary: input.summary,
payload: {
detail: input.detail,
...(input.requestId ? { requestId: input.requestId } : {}),
},
turnId: input.turnId,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
}),
),
);
threadId: input.threadId,
activity: {
id: EventId.make(crypto.randomUUID()),
tone: "error",
kind: input.kind,
summary: input.summary,
payload: {
detail: input.detail,
...(input.requestId ? { requestId: input.requestId } : {}),
},
turnId: input.turnId,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
});
const formatFailureDetail = (cause: Cause.Cause<unknown>): string => {
const failReason = cause.reasons.find(Cause.isFailReason);
@@ -258,17 +249,13 @@ const make = Effect.gen(function* () {
readonly session: OrchestrationSession;
readonly createdAt: string;
}) =>
serverCommandId("provider-session-set").pipe(
Effect.flatMap((commandId) =>
orchestrationEngine.dispatch({
type: "thread.session.set",
commandId,
threadId: input.threadId,
session: input.session,
createdAt: input.createdAt,
}),
),
);
orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: serverCommandId("provider-session-set"),
threadId: input.threadId,
session: input.session,
createdAt: input.createdAt,
});
const setThreadSessionErrorOnTurnStartFailure = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
@@ -623,7 +610,7 @@ const make = Effect.gen(function* () {
const renamed = yield* gitWorkflow.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: yield* serverCommandId("worktree-branch-rename"),
commandId: serverCommandId("worktree-branch-rename"),
threadId: input.threadId,
branch: renamed.branch,
worktreePath: cwd,
@@ -670,7 +657,7 @@ const make = Effect.gen(function* () {
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: yield* serverCommandId("thread-title-rename"),
commandId: serverCommandId("thread-title-rename"),
threadId: input.threadId,
title: generated.title,
});
@@ -19,7 +19,6 @@ import {
} from "@t3tools/contracts";
import * as Cache from "effect/Cache";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -40,6 +39,8 @@ import {
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()}`);
interface AssistantSegmentState {
baseKey: string;
@@ -606,16 +607,11 @@ function runtimeEventToActivities(
}
const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const providerService = yield* ProviderService;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const serverSettingsService = yield* ServerSettingsService;
const providerCommandId = (event: ProviderRuntimeEvent, tag: string) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => CommandId.make(`provider:${event.eventId}:${tag}:${uuid}`)),
);
const turnMessageIdsByTurnKey = yield* Cache.make<string, Set<MessageId>>({
capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
@@ -852,7 +848,7 @@ const make = Effect.gen(function* () {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.delta",
commandId: yield* providerCommandId(input.event, input.commandTag),
commandId: providerCommandId(input.event, input.commandTag),
threadId: input.threadId,
messageId: input.messageId,
delta: bufferedText,
@@ -919,7 +915,7 @@ const make = Effect.gen(function* () {
if (hasRenderableText) {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.delta",
commandId: yield* providerCommandId(input.event, input.finalDeltaCommandTag),
commandId: providerCommandId(input.event, input.finalDeltaCommandTag),
threadId: input.threadId,
messageId: input.messageId,
delta: text,
@@ -931,7 +927,7 @@ const make = Effect.gen(function* () {
if (input.hasProjectedMessage || hasRenderableText) {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.complete",
commandId: yield* providerCommandId(input.event, input.commandTag),
commandId: providerCommandId(input.event, input.commandTag),
threadId: input.threadId,
messageId: input.messageId,
...(input.turnId ? { turnId: input.turnId } : {}),
@@ -1007,7 +1003,7 @@ const make = Effect.gen(function* () {
const existingPlan = findProposedPlanById(input.threadProposedPlans, input.planId);
yield* orchestrationEngine.dispatch({
type: "thread.proposed-plan.upsert",
commandId: yield* providerCommandId(input.event, "proposed-plan-upsert"),
commandId: providerCommandId(input.event, "proposed-plan-upsert"),
threadId: input.threadId,
proposedPlan: {
id: input.planId,
@@ -1163,11 +1159,10 @@ const make = Effect.gen(function* () {
return;
}
const commandUuid = yield* crypto.randomUUIDv4;
yield* orchestrationEngine.dispatch({
type: "thread.proposed-plan.upsert",
commandId: CommandId.make(
`provider:source-proposed-plan-implemented:${implementationThreadId}:${commandUuid}`,
`provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`,
),
threadId: sourceThread.id,
proposedPlan: {
@@ -1301,7 +1296,7 @@ const make = Effect.gen(function* () {
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: yield* providerCommandId(event, "thread-session-set"),
commandId: providerCommandId(event, "thread-session-set"),
threadId: thread.id,
session: {
threadId: thread.id,
@@ -1347,7 +1342,7 @@ const make = Effect.gen(function* () {
if (spillChunk.length > 0) {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.delta",
commandId: yield* providerCommandId(event, "assistant-delta-buffer-spill"),
commandId: providerCommandId(event, "assistant-delta-buffer-spill"),
threadId: thread.id,
messageId: assistantMessageId,
delta: spillChunk,
@@ -1358,7 +1353,7 @@ const make = Effect.gen(function* () {
} else {
yield* orchestrationEngine.dispatch({
type: "thread.message.assistant.delta",
commandId: yield* providerCommandId(event, "assistant-delta"),
commandId: providerCommandId(event, "assistant-delta"),
threadId: thread.id,
messageId: assistantMessageId,
delta: assistantDelta,
@@ -1551,7 +1546,7 @@ const make = Effect.gen(function* () {
if (shouldApplyRuntimeError) {
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: yield* providerCommandId(event, "runtime-error-session-set"),
commandId: providerCommandId(event, "runtime-error-session-set"),
threadId: thread.id,
session: {
threadId: thread.id,
@@ -1573,7 +1568,7 @@ const make = Effect.gen(function* () {
if (event.type === "thread.metadata.updated" && event.payload.name) {
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: yield* providerCommandId(event, "thread-meta-update"),
commandId: providerCommandId(event, "thread-meta-update"),
threadId: thread.id,
title: event.payload.name,
});
@@ -1601,7 +1596,7 @@ const make = Effect.gen(function* () {
);
yield* orchestrationEngine.dispatch({
type: "thread.turn.diff.complete",
commandId: yield* providerCommandId(event, "thread-turn-diff-complete"),
commandId: providerCommandId(event, "thread-turn-diff-complete"),
threadId: thread.id,
turnId,
completedAt: now,
@@ -1618,17 +1613,13 @@ const make = Effect.gen(function* () {
const activities = runtimeEventToActivities(event);
yield* Effect.forEach(activities, (activity) =>
providerCommandId(event, "thread-activity-append").pipe(
Effect.flatMap((commandId) =>
orchestrationEngine.dispatch({
type: "thread.activity.append",
commandId,
threadId: thread.id,
activity,
createdAt: activity.createdAt,
}),
),
),
orchestrationEngine.dispatch({
type: "thread.activity.append",
commandId: providerCommandId(event, "thread-activity-append"),
threadId: thread.id,
activity,
createdAt: activity.createdAt,
}),
).pipe(Effect.asVoid);
});
@@ -6,11 +6,11 @@ import {
ThreadId,
type OrchestrationCommand,
type OrchestrationEvent,
type OrchestrationReadModel,
ProviderInstanceId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { describe, expect, it } from "vitest";
import { decideOrchestrationCommand } from "./decider.ts";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
@@ -20,87 +20,93 @@ const asEventId = (value: string): EventId => EventId.make(value);
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
const seedReadModel = Effect.gen(function* () {
async function seedReadModel(): Promise<OrchestrationReadModel> {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const withProject = yield* projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create"),
aggregateKind: "project",
aggregateId: asProjectId("project-delete"),
type: "project.created",
occurredAt: now,
commandId: asCommandId("cmd-project-create"),
causationEventId: null,
correlationId: asCommandId("cmd-project-create"),
metadata: {},
payload: {
projectId: asProjectId("project-delete"),
title: "Project Delete",
workspaceRoot: "/tmp/project-delete",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
const withFirstThread = yield* projectEvent(withProject, {
sequence: 2,
eventId: asEventId("evt-thread-create-1"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-delete-1"),
type: "thread.created",
occurredAt: now,
commandId: asCommandId("cmd-thread-create-1"),
causationEventId: null,
correlationId: asCommandId("cmd-thread-create-1"),
metadata: {},
payload: {
threadId: asThreadId("thread-delete-1"),
projectId: asProjectId("project-delete"),
title: "Thread Delete 1",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
const withProject = await Effect.runPromise(
projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create"),
aggregateKind: "project",
aggregateId: asProjectId("project-delete"),
type: "project.created",
occurredAt: now,
commandId: asCommandId("cmd-project-create"),
causationEventId: null,
correlationId: asCommandId("cmd-project-create"),
metadata: {},
payload: {
projectId: asProjectId("project-delete"),
title: "Project Delete",
workspaceRoot: "/tmp/project-delete",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
}),
);
return yield* projectEvent(withFirstThread, {
sequence: 3,
eventId: asEventId("evt-thread-create-2"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-delete-2"),
type: "thread.created",
occurredAt: now,
commandId: asCommandId("cmd-thread-create-2"),
causationEventId: null,
correlationId: asCommandId("cmd-thread-create-2"),
metadata: {},
payload: {
threadId: asThreadId("thread-delete-2"),
projectId: asProjectId("project-delete"),
title: "Thread Delete 2",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
const withFirstThread = await Effect.runPromise(
projectEvent(withProject, {
sequence: 2,
eventId: asEventId("evt-thread-create-1"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-delete-1"),
type: "thread.created",
occurredAt: now,
commandId: asCommandId("cmd-thread-create-1"),
causationEventId: null,
correlationId: asCommandId("cmd-thread-create-1"),
metadata: {},
payload: {
threadId: asThreadId("thread-delete-1"),
projectId: asProjectId("project-delete"),
title: "Thread Delete 1",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
});
}),
);
return Effect.runPromise(
projectEvent(withFirstThread, {
sequence: 3,
eventId: asEventId("evt-thread-create-2"),
aggregateKind: "thread",
aggregateId: asThreadId("thread-delete-2"),
type: "thread.created",
occurredAt: now,
commandId: asCommandId("cmd-thread-create-2"),
causationEventId: null,
correlationId: asCommandId("cmd-thread-create-2"),
metadata: {},
payload: {
threadId: asThreadId("thread-delete-2"),
projectId: asProjectId("project-delete"),
title: "Thread Delete 2",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
);
}
type PlannedEvent = Omit<OrchestrationEvent, "sequence">;
@@ -136,11 +142,12 @@ function normalizeDeleteEvent(event: PlannedEvent | ReadonlyArray<PlannedEvent>)
});
}
it.layer(NodeServices.layer)("decider deletion flows", (it) => {
it.effect("rejects deleting a non-empty project without force", () =>
Effect.gen(function* () {
const readModel = yield* seedReadModel;
const error = yield* Effect.flip(
describe("decider deletion flows", () => {
it("rejects deleting a non-empty project without force", async () => {
const readModel = await seedReadModel();
await expect(
Effect.runPromise(
decideOrchestrationCommand({
command: {
type: "project.delete",
@@ -149,69 +156,72 @@ it.layer(NodeServices.layer)("decider deletion flows", (it) => {
},
readModel,
}),
);
expect(error.message).toContain("cannot be deleted without force=true");
}),
);
),
).rejects.toThrow("cannot be deleted without force=true");
});
it.effect("reuses thread.delete semantics when force-deleting a non-empty project", () =>
Effect.gen(function* () {
const readModel = yield* seedReadModel;
const projectDeleteCommand: Extract<OrchestrationCommand, { type: "project.delete" }> = {
type: "project.delete",
commandId: asCommandId("cmd-project-delete-force"),
projectId: asProjectId("project-delete"),
force: true,
};
it("reuses thread.delete semantics when force-deleting a non-empty project", async () => {
const readModel = await seedReadModel();
const projectDeleteCommand: Extract<OrchestrationCommand, { type: "project.delete" }> = {
type: "project.delete",
commandId: asCommandId("cmd-project-delete-force"),
projectId: asProjectId("project-delete"),
force: true,
};
const forcedResult = yield* decideOrchestrationCommand({
const forcedResult = await Effect.runPromise(
decideOrchestrationCommand({
command: projectDeleteCommand,
readModel,
});
const forcedEvents = Array.isArray(forcedResult) ? forcedResult : [forcedResult];
}),
);
const forcedEvents = Array.isArray(forcedResult) ? forcedResult : [forcedResult];
expect(forcedEvents.map((event) => event.type)).toEqual([
"thread.deleted",
"thread.deleted",
"project.deleted",
]);
expect(forcedEvents.map((event) => event.type)).toEqual([
"thread.deleted",
"thread.deleted",
"project.deleted",
]);
let sequentialReadModel = readModel;
let nextSequence = readModel.snapshotSequence;
const sequentialEvents: PlannedEvent[] = [];
for (const nextCommand of [
{
type: "thread.delete",
commandId: projectDeleteCommand.commandId,
threadId: asThreadId("thread-delete-1"),
},
{
type: "thread.delete",
commandId: projectDeleteCommand.commandId,
threadId: asThreadId("thread-delete-2"),
},
{
type: "project.delete",
commandId: projectDeleteCommand.commandId,
projectId: asProjectId("project-delete"),
},
] satisfies ReadonlyArray<OrchestrationCommand>) {
const decided = yield* decideOrchestrationCommand({
let sequentialReadModel = readModel;
let nextSequence = readModel.snapshotSequence;
const sequentialEvents: PlannedEvent[] = [];
for (const nextCommand of [
{
type: "thread.delete",
commandId: projectDeleteCommand.commandId,
threadId: asThreadId("thread-delete-1"),
},
{
type: "thread.delete",
commandId: projectDeleteCommand.commandId,
threadId: asThreadId("thread-delete-2"),
},
{
type: "project.delete",
commandId: projectDeleteCommand.commandId,
projectId: asProjectId("project-delete"),
},
] satisfies ReadonlyArray<OrchestrationCommand>) {
const decided = await Effect.runPromise(
decideOrchestrationCommand({
command: nextCommand,
readModel: sequentialReadModel,
});
const nextEvents = Array.isArray(decided) ? decided : [decided];
sequentialEvents.push(...nextEvents);
for (const nextEvent of nextEvents) {
nextSequence += 1;
sequentialReadModel = yield* projectEvent(sequentialReadModel, {
}),
);
const nextEvents = Array.isArray(decided) ? decided : [decided];
sequentialEvents.push(...nextEvents);
for (const nextEvent of nextEvents) {
nextSequence += 1;
sequentialReadModel = await Effect.runPromise(
projectEvent(sequentialReadModel, {
...nextEvent,
sequence: nextSequence,
});
}
}),
);
}
}
expect(normalizeDeleteEvent(forcedResult)).toEqual(normalizeDeleteEvent(sequentialEvents));
}),
);
expect(normalizeDeleteEvent(forcedResult)).toEqual(normalizeDeleteEvent(sequentialEvents));
});
});
@@ -8,9 +8,8 @@ import {
ProviderInstanceId,
} from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import { expect, it } from "@effect/vitest";
import { describe, expect, it } from "vitest";
import * as Effect from "effect/Effect";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { decideOrchestrationCommand } from "./decider.ts";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
@@ -18,13 +17,14 @@ 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);
it.layer(NodeServices.layer)("decider project scripts", (it) => {
it.effect("emits empty scripts on project.create", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const readModel = createEmptyReadModel(now);
const result = yield* decideOrchestrationCommand({
describe("decider project scripts", () => {
it("emits empty scripts on project.create", async () => {
const now = "2026-01-01T00:00:00.000Z";
const readModel = createEmptyReadModel(now);
const result = await Effect.runPromise(
decideOrchestrationCommand({
command: {
type: "project.create",
commandId: CommandId.make("cmd-project-create-scripts"),
@@ -34,19 +34,19 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
createdAt: now,
},
readModel,
});
}),
);
const event = Array.isArray(result) ? result[0] : result;
expect(event.type).toBe("project.created");
expect((event.payload as { scripts: unknown[] }).scripts).toEqual([]);
}),
);
const event = Array.isArray(result) ? result[0] : result;
expect(event.type).toBe("project.created");
expect((event.payload as { scripts: unknown[] }).scripts).toEqual([]);
});
it.effect("propagates scripts in project.meta.update payload", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const readModel = yield* projectEvent(initial, {
it("propagates scripts in project.meta.update payload", async () => {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const readModel = await Effect.runPromise(
projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create-scripts"),
aggregateKind: "project",
@@ -66,19 +66,21 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
createdAt: now,
updatedAt: now,
},
});
}),
);
const scripts = [
{
id: "lint",
name: "Lint",
command: "bun run lint",
icon: "lint",
runOnWorktreeCreate: false,
},
] as const;
const scripts = [
{
id: "lint",
name: "Lint",
command: "bun run lint",
icon: "lint",
runOnWorktreeCreate: false,
},
] as const;
const result = yield* decideOrchestrationCommand({
const result = await Effect.runPromise(
decideOrchestrationCommand({
command: {
type: "project.meta.update",
commandId: CommandId.make("cmd-project-update-scripts"),
@@ -86,19 +88,19 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
scripts: Array.from(scripts),
},
readModel,
});
}),
);
const event = Array.isArray(result) ? result[0] : result;
expect(event.type).toBe("project.meta-updated");
expect((event.payload as { scripts?: unknown[] }).scripts).toEqual(scripts);
}),
);
const event = Array.isArray(result) ? result[0] : result;
expect(event.type).toBe("project.meta-updated");
expect((event.payload as { scripts?: unknown[] }).scripts).toEqual(scripts);
});
it.effect("emits user message and turn-start-requested events for thread.turn.start", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const withProject = yield* projectEvent(initial, {
it("emits user message and turn-start-requested events for thread.turn.start", async () => {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const withProject = await Effect.runPromise(
projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create"),
aggregateKind: "project",
@@ -118,8 +120,10 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
createdAt: now,
updatedAt: now,
},
});
const readModel = yield* projectEvent(withProject, {
}),
);
const readModel = await Effect.runPromise(
projectEvent(withProject, {
sequence: 2,
eventId: asEventId("evt-thread-create"),
aggregateKind: "thread",
@@ -145,9 +149,11 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
createdAt: now,
updatedAt: now,
},
});
}),
);
const result = yield* decideOrchestrationCommand({
const result = await Effect.runPromise(
decideOrchestrationCommand({
command: {
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start"),
@@ -167,35 +173,35 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
createdAt: now,
},
readModel,
});
}),
);
expect(Array.isArray(result)).toBe(true);
const events = Array.isArray(result) ? result : [result];
expect(events).toHaveLength(2);
expect(events[0]?.type).toBe("thread.message-sent");
const turnStartEvent = events[1];
expect(turnStartEvent?.type).toBe("thread.turn-start-requested");
expect(turnStartEvent?.causationEventId).toBe(events[0]?.eventId ?? null);
if (turnStartEvent?.type !== "thread.turn-start-requested") {
return;
}
expect(turnStartEvent.payload).toMatchObject({
threadId: ThreadId.make("thread-1"),
messageId: asMessageId("message-user-1"),
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
runtimeMode: "approval-required",
});
}),
);
expect(Array.isArray(result)).toBe(true);
const events = Array.isArray(result) ? result : [result];
expect(events).toHaveLength(2);
expect(events[0]?.type).toBe("thread.message-sent");
const turnStartEvent = events[1];
expect(turnStartEvent?.type).toBe("thread.turn-start-requested");
expect(turnStartEvent?.causationEventId).toBe(events[0]?.eventId ?? null);
if (turnStartEvent?.type !== "thread.turn-start-requested") {
return;
}
expect(turnStartEvent.payload).toMatchObject({
threadId: ThreadId.make("thread-1"),
messageId: asMessageId("message-user-1"),
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
{ id: "reasoningEffort", value: "high" },
{ id: "fastMode", value: true },
]),
runtimeMode: "approval-required",
});
});
it.effect("emits thread.runtime-mode-set from thread.runtime-mode.set", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const withProject = yield* projectEvent(initial, {
it("emits thread.runtime-mode-set from thread.runtime-mode.set", async () => {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const withProject = await Effect.runPromise(
projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create"),
aggregateKind: "project",
@@ -215,8 +221,10 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
createdAt: now,
updatedAt: now,
},
});
const readModel = yield* projectEvent(withProject, {
}),
);
const readModel = await Effect.runPromise(
projectEvent(withProject, {
sequence: 2,
eventId: asEventId("evt-thread-create"),
aggregateKind: "thread",
@@ -242,9 +250,11 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
createdAt: now,
updatedAt: now,
},
});
}),
);
const result = yield* decideOrchestrationCommand({
const result = await Effect.runPromise(
decideOrchestrationCommand({
command: {
type: "thread.runtime-mode.set",
commandId: CommandId.make("cmd-runtime-mode-set"),
@@ -253,27 +263,27 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
createdAt: now,
},
readModel,
});
}),
);
const singleResult = Array.isArray(result) ? null : result;
if (singleResult === null) {
throw new Error("Expected a single runtime-mode-set event.");
}
expect(singleResult).toMatchObject({
type: "thread.runtime-mode-set",
payload: {
threadId: ThreadId.make("thread-1"),
runtimeMode: "approval-required",
},
});
}),
);
const singleResult = Array.isArray(result) ? null : result;
if (singleResult === null) {
throw new Error("Expected a single runtime-mode-set event.");
}
expect(singleResult).toMatchObject({
type: "thread.runtime-mode-set",
payload: {
threadId: ThreadId.make("thread-1"),
runtimeMode: "approval-required",
},
});
});
it.effect("emits thread.interaction-mode-set from thread.interaction-mode.set", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const withProject = yield* projectEvent(initial, {
it("emits thread.interaction-mode-set from thread.interaction-mode.set", async () => {
const now = "2026-01-01T00:00:00.000Z";
const initial = createEmptyReadModel(now);
const withProject = await Effect.runPromise(
projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create"),
aggregateKind: "project",
@@ -293,8 +303,10 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
createdAt: now,
updatedAt: now,
},
});
const readModel = yield* projectEvent(withProject, {
}),
);
const readModel = await Effect.runPromise(
projectEvent(withProject, {
sequence: 2,
eventId: asEventId("evt-thread-create"),
aggregateKind: "thread",
@@ -320,9 +332,11 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
createdAt: now,
updatedAt: now,
},
});
}),
);
const result = yield* decideOrchestrationCommand({
const result = await Effect.runPromise(
decideOrchestrationCommand({
command: {
type: "thread.interaction-mode.set",
commandId: CommandId.make("cmd-interaction-mode-set"),
@@ -331,19 +345,19 @@ it.layer(NodeServices.layer)("decider project scripts", (it) => {
createdAt: now,
},
readModel,
});
}),
);
const singleResult = Array.isArray(result) ? null : result;
if (singleResult === null) {
throw new Error("Expected a single interaction-mode-set event.");
}
expect(singleResult).toMatchObject({
type: "thread.interaction-mode-set",
payload: {
threadId: ThreadId.make("thread-1"),
interactionMode: "plan",
},
});
}),
);
const singleResult = Array.isArray(result) ? null : result;
if (singleResult === null) {
throw new Error("Expected a single interaction-mode-set event.");
}
expect(singleResult).toMatchObject({
type: "thread.interaction-mode-set",
payload: {
threadId: ThreadId.make("thread-1"),
interactionMode: "plan",
},
});
});
});
+65 -86
View File
@@ -1,13 +1,10 @@
import {
EventId,
type OrchestrationCommand,
type OrchestrationEvent,
type OrchestrationReadModel,
import type {
OrchestrationCommand,
OrchestrationEvent,
OrchestrationReadModel,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import type * as PlatformError from "effect/PlatformError";
import { OrchestrationCommandInvariantError } from "./Errors.ts";
import {
@@ -30,27 +27,17 @@ function withEventBase(
readonly occurredAt: string;
readonly metadata?: OrchestrationEvent["metadata"];
},
): Effect.Effect<
Omit<OrchestrationEvent, "sequence" | "type" | "payload">,
PlatformError.PlatformError,
Crypto.Crypto
> {
return Crypto.Crypto.pipe(
Effect.flatMap((crypto) =>
crypto.randomUUIDv4.pipe(
Effect.map((eventId) => ({
eventId: EventId.make(eventId),
aggregateKind: input.aggregateKind,
aggregateId: input.aggregateId,
occurredAt: input.occurredAt,
commandId: input.commandId,
causationEventId: null,
correlationId: input.commandId,
metadata: input.metadata ?? {},
})),
),
),
);
): Omit<OrchestrationEvent, "sequence" | "type" | "payload"> {
return {
eventId: crypto.randomUUID() as OrchestrationEvent["eventId"],
aggregateKind: input.aggregateKind,
aggregateId: input.aggregateId,
occurredAt: input.occurredAt,
commandId: input.commandId,
causationEventId: null,
correlationId: input.commandId,
metadata: input.metadata ?? {},
};
}
type PlannedOrchestrationEvent = Omit<OrchestrationEvent, "sequence">;
@@ -65,11 +52,7 @@ const decideCommandSequence = Effect.fn("decideCommandSequence")(function* ({
}: {
readonly commands: ReadonlyArray<OrchestrationCommand>;
readonly readModel: OrchestrationReadModel;
}): Effect.fn.Return<
ReadonlyArray<PlannedOrchestrationEvent>,
OrchestrationCommandInvariantError | PlatformError.PlatformError,
Crypto.Crypto
> {
}): Effect.fn.Return<ReadonlyArray<PlannedOrchestrationEvent>, OrchestrationCommandInvariantError> {
let nextReadModel = readModel;
let nextSequence = readModel.snapshotSequence;
const plannedEvents: PlannedOrchestrationEvent[] = [];
@@ -99,11 +82,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
}: {
readonly command: OrchestrationCommand;
readonly readModel: OrchestrationReadModel;
}): Effect.fn.Return<
DecideOrchestrationCommandResult,
OrchestrationCommandInvariantError | PlatformError.PlatformError,
Crypto.Crypto
> {
}): Effect.fn.Return<DecideOrchestrationCommandResult, OrchestrationCommandInvariantError> {
switch (command.type) {
case "project.create": {
yield* requireProjectAbsent({
@@ -113,12 +92,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
});
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "project",
aggregateId: command.projectId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
}),
type: "project.created",
payload: {
projectId: command.projectId,
@@ -140,12 +119,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
});
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "project",
aggregateId: command.projectId,
occurredAt,
commandId: command.commandId,
})),
}),
type: "project.meta-updated",
payload: {
projectId: command.projectId,
@@ -197,12 +176,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "project",
aggregateId: command.projectId,
occurredAt,
commandId: command.commandId,
})),
}),
type: "project.deleted" as const,
payload: {
projectId: command.projectId,
@@ -223,12 +202,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
}),
type: "thread.created",
payload: {
threadId: command.threadId,
@@ -253,12 +232,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
});
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
}),
type: "thread.deleted",
payload: {
threadId: command.threadId,
@@ -275,12 +254,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
});
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
}),
type: "thread.archived",
payload: {
threadId: command.threadId,
@@ -298,12 +277,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
});
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
}),
type: "thread.unarchived",
payload: {
threadId: command.threadId,
@@ -320,12 +299,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
});
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
}),
type: "thread.meta-updated",
payload: {
threadId: command.threadId,
@@ -348,12 +327,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
});
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
}),
type: "thread.runtime-mode-set",
payload: {
threadId: command.threadId,
@@ -371,12 +350,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
});
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
}),
type: "thread.interaction-mode-set",
payload: {
threadId: command.threadId,
@@ -417,12 +396,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
});
}
const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
}),
type: "thread.message-sent",
payload: {
threadId: command.threadId,
@@ -437,12 +416,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
},
};
const turnStartRequestedEvent: Omit<OrchestrationEvent, "sequence"> = {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
}),
causationEventId: userMessageEvent.eventId,
type: "thread.turn-start-requested",
payload: {
@@ -468,12 +447,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
}),
type: "thread.turn-interrupt-requested",
payload: {
threadId: command.threadId,
@@ -490,7 +469,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
@@ -498,7 +477,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
metadata: {
requestId: command.requestId,
},
})),
}),
type: "thread.approval-response-requested",
payload: {
threadId: command.threadId,
@@ -516,7 +495,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
@@ -524,7 +503,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
metadata: {
requestId: command.requestId,
},
})),
}),
type: "thread.user-input-response-requested",
payload: {
threadId: command.threadId,
@@ -542,12 +521,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
}),
type: "thread.checkpoint-revert-requested",
payload: {
threadId: command.threadId,
@@ -564,12 +543,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
}),
type: "thread.session-stop-requested",
payload: {
threadId: command.threadId,
@@ -585,13 +564,13 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
metadata: {},
})),
}),
type: "thread.session-set",
payload: {
threadId: command.threadId,
@@ -607,12 +586,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
}),
type: "thread.message-sent",
payload: {
threadId: command.threadId,
@@ -634,12 +613,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
}),
type: "thread.message-sent",
payload: {
threadId: command.threadId,
@@ -661,12 +640,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
}),
type: "thread.proposed-plan-upserted",
payload: {
threadId: command.threadId,
@@ -682,12 +661,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
}),
type: "thread.turn-diff-completed",
payload: {
threadId: command.threadId,
@@ -709,12 +688,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
});
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
}),
type: "thread.reverted",
payload: {
threadId: command.threadId,
@@ -738,13 +717,13 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
.requestId as OrchestrationEvent["metadata"]["requestId"])
: undefined;
return {
...(yield* withEventBase({
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
...(requestId !== undefined ? { metadata: { requestId } } : {}),
})),
}),
type: "thread.activity-appended",
payload: {
threadId: command.threadId,
@@ -252,12 +252,14 @@ export const layerConfig = (
config: Config.Wrap<SqliteClientConfig>,
): Layer.Layer<Client.SqlClient, Config.ConfigError> =>
Layer.effectContext(
Config.unwrap(config).pipe(
Effect.flatMap(make),
Effect.map((client) =>
Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)),
Config.unwrap(config)
.asEffect()
.pipe(
Effect.flatMap(make),
Effect.map((client) =>
Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)),
),
),
),
).pipe(Layer.provide(Reactivity.layer));
export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient> =>
@@ -1,12 +1,12 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { assertSuccess } from "@effect/vitest/utils";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Random from "effect/Random";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
@@ -651,9 +651,7 @@ it.layer(NodeServices.layer)("launchEditorProcess", (it) => {
Effect.gen(function* () {
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {});
const result = yield* launchEditorProcess({
command: `t3code-no-such-command-${yield* Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomUUIDv4),
)}`,
command: `t3code-no-such-command-${yield* Random.nextUUIDv4}`,
args: [],
}).pipe(Effect.provide(spawnerLayer), Effect.result);
assert.equal(result._tag, "Failure");
@@ -15,7 +15,6 @@
import { ClaudeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
import * as Cache from "effect/Cache";
import * as Duration from "effect/Duration";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
@@ -78,7 +77,6 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
export type ClaudeDriverEnv =
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
@@ -23,7 +23,6 @@
*/
import { CodexSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
import * as Duration from "effect/Duration";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
@@ -70,7 +69,6 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
*/
export type CodexDriverEnv =
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
@@ -14,7 +14,6 @@
*/
import { CursorSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
import * as Duration from "effect/Duration";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
@@ -62,7 +61,6 @@ const UPDATE = makeStaticProviderMaintenanceResolver(
export type CursorDriverEnv =
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
| HttpClient.HttpClient
| Path.Path
@@ -14,7 +14,6 @@
*/
import { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
import * as Duration from "effect/Duration";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
@@ -74,7 +73,6 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
export type OpenCodeDriverEnv =
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
| HttpClient.HttpClient
| OpenCodeRuntime
@@ -52,7 +52,6 @@ import {
resolvePromptInjectedEffort,
} from "@t3tools/shared/model";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
@@ -61,6 +60,7 @@ import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Random from "effect/Random";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
@@ -998,7 +998,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const crypto = yield* Crypto.Crypto;
const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, options?.environment).pipe(
Effect.provideService(Path.Path, path),
);
@@ -1025,18 +1024,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "crypto/randomUUIDv4",
detail: "Failed to generate Claude runtime identifier.",
cause,
}),
),
);
const nextEventId = Effect.map(randomUUIDv4, (id) => EventId.make(id));
const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.make(id));
const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });
const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
@@ -1060,7 +1048,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
id:
"uuid" in message && typeof message.uuid === "string"
? message.uuid
: yield* randomUUIDv4,
: yield* Random.nextUUIDv4,
kind: "notification",
provider: PROVIDER,
createdAt: observedAt,
@@ -1144,7 +1132,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
}
const block: AssistantTextBlockState = {
itemId: yield* randomUUIDv4,
itemId: yield* Random.nextUUIDv4,
blockIndex,
emittedTextDelta: false,
fallbackText: options?.fallbackText ?? "",
@@ -1977,7 +1965,7 @@ export 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* randomUUIDv4);
const turnId = TurnId.make(yield* Random.nextUUIDv4);
const startedAt = yield* nowIso;
context.turnState = {
turnId,
@@ -2390,17 +2378,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
toProcessError(cause, "Claude runtime stream failed.", context.session.threadId),
).pipe(
Stream.takeWhile(() => !context.stopped),
Stream.runForEach((message) =>
handleSdkMessage(context, message).pipe(
Effect.mapError((cause) =>
toProcessError(
cause,
"Failed to process Claude runtime event.",
context.session.threadId,
),
),
),
),
Stream.runForEach((message) => handleSdkMessage(context, message)),
);
const handleStreamExit = Effect.fn("handleStreamExit")(function* (
@@ -2574,7 +2552,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const resumeState = readClaudeResumeState(input.resumeCursor);
const threadId = input.threadId;
const existingResumeSessionId = resumeState?.resume;
const newSessionId = existingResumeSessionId === undefined ? yield* randomUUIDv4 : undefined;
const newSessionId =
existingResumeSessionId === undefined ? yield* Random.nextUUIDv4 : undefined;
const sessionId = existingResumeSessionId ?? newSessionId;
const runtimeContext = yield* Effect.context<never>();
@@ -2609,7 +2588,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
readonly toolUseID?: string;
},
) {
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
// Parse questions from the SDK's AskUserQuestion input.
// `id` MUST equal the full question text — Claude SDK >= 2.1.121 looks
@@ -2779,7 +2758,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
} satisfies PermissionResult;
}
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
const requestType = classifyRequestType(toolName);
const detail = summarizeToolRequest(toolName, toolInput);
const decisionDeferred = yield* Deferred.make<ProviderApprovalDecision>();
@@ -3080,11 +3059,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
if (context.streamFiber === streamFiber) {
context.streamFiber = undefined;
}
return handleStreamExit(context, exit).pipe(
Effect.catch((cause) =>
Effect.logError("Failed to close Claude runtime stream.", { cause }),
),
);
return handleStreamExit(context, exit);
}),
),
);
@@ -3145,7 +3120,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
}
const turnId = TurnId.make(yield* randomUUIDv4);
const turnId = TurnId.make(yield* Random.nextUUIDv4);
const turnState: ClaudeTurnState = {
turnId,
startedAt: yield* nowIso,
@@ -3294,12 +3269,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
emitExitEvent: false,
}),
{ discard: true },
).pipe(
Effect.catch((cause) =>
Effect.logError("Failed to emit Claude session shutdown event.", { cause }),
),
Effect.tap(() => Queue.shutdown(runtimeEventQueue)),
),
).pipe(Effect.tap(() => Queue.shutdown(runtimeEventQueue))),
);
return {
@@ -50,36 +50,6 @@ const CLAUDE_PRESENTATION = {
} as const;
const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "claude-opus-4-8",
name: "Claude Opus 4.8",
isCustom: false,
capabilities: createModelCapabilities({
optionDescriptors: [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High" },
{ value: "xhigh", label: "Extra High", isDefault: true },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
promptInjectedValues: ["ultrathink"],
}),
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
}),
],
}),
},
{
slug: "claude-opus-4-7",
name: "Claude Opus 4.7",
@@ -209,24 +179,22 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
},
];
function supportsClaudeOpus47or48(version: string | null | undefined): boolean {
function supportsClaudeOpus47(version: string | null | undefined): boolean {
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_4_7_VERSION) >= 0 : false;
}
function getBuiltInClaudeModelsForVersion(
version: string | null | undefined,
): ReadonlyArray<ServerProviderModel> {
if (supportsClaudeOpus47or48(version)) {
if (supportsClaudeOpus47(version)) {
return BUILT_IN_MODELS;
}
return BUILT_IN_MODELS.filter(
(model) => model.slug !== "claude-opus-4-7" && model.slug !== "claude-opus-4-8",
);
return BUILT_IN_MODELS.filter((model) => model.slug !== "claude-opus-4-7");
}
function formatClaudeOpusUpgradeMessage(model: string, version: string | null): string {
function formatClaudeOpus47UpgradeMessage(version: string | null): string {
const versionLabel = version ? `v${version}` : "the installed version";
return `Claude Code ${versionLabel} is too old for Claude Opus ${model}. Upgrade to v${MINIMUM_CLAUDE_OPUS_4_7_VERSION} or newer to access it.`;
return `Claude Code ${versionLabel} is too old for Claude Opus 4.7. Upgrade to v${MINIMUM_CLAUDE_OPUS_4_7_VERSION} or newer to access it.`;
}
export function getClaudeModelCapabilities(model: string | null | undefined): ModelCapabilities {
@@ -649,9 +617,9 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
claudeSettings.customModels,
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
);
const opus47UpgradeMessage = supportsClaudeOpus47or48(parsedVersion)
const opus47UpgradeMessage = supportsClaudeOpus47(parsedVersion)
? undefined
: formatClaudeOpusUpgradeMessage("4.8", parsedVersion);
: formatClaudeOpus47UpgradeMessage(parsedVersion);
const capabilities = resolveCapabilities
? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
@@ -25,7 +25,6 @@ import {
ProviderSendTurnInput,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Crypto from "effect/Crypto";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
@@ -1350,7 +1349,6 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("codex");
const fileSystem = yield* FileSystem.FileSystem;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const crypto = yield* Crypto.Crypto;
const serverConfig = yield* Effect.service(ServerConfig);
const nativeEventLogger =
options?.nativeEventLogger ??
@@ -1408,7 +1406,6 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
const runtime = yield* createRuntime(runtimeInput).pipe(
Effect.provideService(Scope.Scope, sessionScope),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
Effect.provideService(Crypto.Crypto, crypto),
Effect.mapError(
(cause) =>
new ProviderAdapterProcessError({
@@ -17,7 +17,6 @@ import {
TurnId,
} from "@t3tools/contracts";
import { normalizeModelSlug } from "@t3tools/shared/model";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
@@ -26,6 +25,7 @@ import * as Layer from "effect/Layer";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
import * as Random from "effect/Random";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as SchemaIssue from "effect/SchemaIssue";
@@ -697,12 +697,11 @@ export const makeCodexSessionRuntime = (
): Effect.Effect<
CodexSessionRuntimeShape,
CodexErrors.CodexAppServerError,
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope
ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
> =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const runtimeScope = yield* Scope.Scope;
const crypto = yield* Crypto.Crypto;
const events = yield* Queue.unbounded<ProviderEvent>();
const pendingApprovalsRef = yield* Ref.make(new Map<ApprovalRequestId, PendingApproval>());
const approvalCorrelationsRef = yield* Ref.make(new Map<string, ApprovalCorrelation>());
@@ -747,15 +746,6 @@ export const makeCodexSessionRuntime = (
);
const serverNotifications = yield* Queue.unbounded<CodexServerNotification>();
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new CodexErrors.CodexAppServerTransportError({
detail: "Failed to generate Codex runtime identifier.",
cause,
}),
),
);
const sessionCreatedAt = yield* nowIso;
const initialSession = {
@@ -775,7 +765,7 @@ export const makeCodexSessionRuntime = (
const emitEvent = (event: Omit<ProviderEvent, "id" | "provider" | "createdAt">) =>
Effect.gen(function* () {
const id = yield* randomUUIDv4;
const id = yield* Random.nextUUIDv4;
return yield* offerEvent({
id: EventId.make(id),
provider: PROVIDER,
@@ -943,7 +933,7 @@ export const makeCodexSessionRuntime = (
yield* client.handleServerRequest("item/commandExecution/requestApproval", (payload) =>
Effect.gen(function* () {
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
const turnId = TurnId.make(payload.turnId);
const itemId = ProviderItemId.make(payload.itemId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
@@ -999,7 +989,7 @@ export const makeCodexSessionRuntime = (
yield* client.handleServerRequest("item/fileChange/requestApproval", (payload) =>
Effect.gen(function* () {
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
const turnId = TurnId.make(payload.turnId);
const itemId = ProviderItemId.make(payload.itemId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
@@ -1055,7 +1045,7 @@ export const makeCodexSessionRuntime = (
yield* client.handleServerRequest("item/tool/requestUserInput", (payload) =>
Effect.gen(function* () {
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
const turnId = TurnId.make(payload.turnId);
const itemId = ProviderItemId.make(payload.itemId);
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
@@ -1239,11 +1229,7 @@ export const makeCodexSessionRuntime = (
status: "closed",
activeTurnId: undefined,
});
yield* emitSessionEvent("session/closed", "Session stopped").pipe(
Effect.catch((cause) =>
Effect.logError("Failed to emit Codex session closed event.", { cause }),
),
);
yield* emitSessionEvent("session/closed", "Session stopped");
yield* Scope.close(runtimeScope, Exit.void);
yield* Queue.shutdown(serverNotifications);
yield* Queue.shutdown(events);
+145 -185
View File
@@ -22,7 +22,6 @@ import {
TurnId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Crypto from "effect/Crypto";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -31,13 +30,13 @@ import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PubSub from "effect/PubSub";
import * as Random from "effect/Random";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as SynchronizedRef from "effect/SynchronizedRef";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as EffectAcpErrors from "effect-acp/errors";
import type * as EffectAcpSchema from "effect-acp/schema";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
@@ -63,7 +62,7 @@ import {
type AcpSessionModeState,
parsePermissionRequest,
} from "../acp/AcpRuntimeModel.ts";
import { makeAcpNativeLoggerFactory } from "../acp/AcpNativeLogging.ts";
import { makeAcpNativeLoggers } from "../acp/AcpNativeLogging.ts";
import { applyCursorAcpModelSelection, makeCursorAcpRuntime } from "../acp/CursorAcpSupport.ts";
import {
CursorAskQuestionRequest,
@@ -315,7 +314,6 @@ export function makeCursorAdapter(
const path = yield* Path.Path;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverConfig = yield* Effect.service(ServerConfig);
const crypto = yield* Crypto.Crypto;
const nativeEventLogger =
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
@@ -325,36 +323,14 @@ export function makeCursorAdapter(
: undefined);
const managedNativeEventLogger =
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
const makeAcpNativeLoggers = yield* makeAcpNativeLoggerFactory();
const sessions = new Map<ThreadId, CursorSessionContext>();
const threadLocksRef = yield* SynchronizedRef.make(new Map<string, Semaphore.Semaphore>());
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "crypto/randomUUIDv4",
detail: "Failed to generate Cursor runtime identifier.",
cause,
}),
),
);
const nextEventId = Effect.map(randomUUIDv4, (id) => EventId.make(id));
const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.make(id));
const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });
const mapExtensionFailure = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(
Effect.mapError(
(cause) =>
new EffectAcpErrors.AcpTransportError({
detail: "Failed to process Cursor ACP extension event.",
cause,
}),
),
);
const offerRuntimeEvent = (event: ProviderRuntimeEvent) =>
PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid);
@@ -393,7 +369,7 @@ export function makeCursorAdapter(
{
observedAt,
event: {
id: yield* randomUUIDv4,
id: yield* Random.nextUUIDv4,
kind: "notification",
provider: PROVIDER,
createdAt: observedAt,
@@ -548,167 +524,159 @@ export function makeCursorAdapter(
);
const started = yield* Effect.gen(function* () {
yield* acp.handleExtRequest("cursor/ask_question", CursorAskQuestionRequest, (params) =>
mapExtensionFailure(
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/ask_question",
params,
"acp.cursor.extension",
);
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const runtimeRequestId = RuntimeRequestId.make(requestId);
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
pendingUserInputs.set(requestId, { answers });
yield* offerRuntimeEvent({
type: "user-input.requested",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
payload: { questions: extractAskQuestions(params) },
raw: {
source: "acp.cursor.extension",
method: "cursor/ask_question",
payload: params,
},
});
const resolved = yield* Deferred.await(answers);
pendingUserInputs.delete(requestId);
yield* offerRuntimeEvent({
type: "user-input.resolved",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
payload: { answers: resolved },
});
return { answers: resolved };
}),
),
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/ask_question",
params,
"acp.cursor.extension",
);
const requestId = ApprovalRequestId.make(crypto.randomUUID());
const runtimeRequestId = RuntimeRequestId.make(requestId);
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
pendingUserInputs.set(requestId, { answers });
yield* offerRuntimeEvent({
type: "user-input.requested",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
payload: { questions: extractAskQuestions(params) },
raw: {
source: "acp.cursor.extension",
method: "cursor/ask_question",
payload: params,
},
});
const resolved = yield* Deferred.await(answers);
pendingUserInputs.delete(requestId);
yield* offerRuntimeEvent({
type: "user-input.resolved",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
payload: { answers: resolved },
});
return { answers: resolved };
}),
);
yield* acp.handleExtRequest("cursor/create_plan", CursorCreatePlanRequest, (params) =>
mapExtensionFailure(
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/create_plan",
params,
"acp.cursor.extension",
);
yield* offerRuntimeEvent({
type: "turn.proposed.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
payload: { planMarkdown: extractPlanMarkdown(params) },
raw: {
source: "acp.cursor.extension",
method: "cursor/create_plan",
payload: params,
},
});
return { accepted: true } as const;
}),
),
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/create_plan",
params,
"acp.cursor.extension",
);
yield* offerRuntimeEvent({
type: "turn.proposed.completed",
...(yield* makeEventStamp()),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
payload: { planMarkdown: extractPlanMarkdown(params) },
raw: {
source: "acp.cursor.extension",
method: "cursor/create_plan",
payload: params,
},
});
return { accepted: true } as const;
}),
);
yield* acp.handleExtNotification(
"cursor/update_todos",
CursorUpdateTodosRequest,
(params) =>
mapExtensionFailure(
Effect.gen(function* () {
yield* logNative(
input.threadId,
"cursor/update_todos",
params,
"acp.cursor.extension",
);
if (ctx) {
yield* emitPlanUpdate(
ctx,
extractTodosAsPlan(params),
params,
"acp.cursor.extension",
"cursor/update_todos",
);
}
}),
),
);
yield* acp.handleRequestPermission((params) =>
mapExtensionFailure(
Effect.gen(function* () {
yield* logNative(
input.threadId,
"session/request_permission",
"cursor/update_todos",
params,
"acp.jsonrpc",
"acp.cursor.extension",
);
if (input.runtimeMode === "full-access") {
const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);
if (autoApprovedOptionId !== undefined) {
return {
outcome: {
outcome: "selected" as const,
optionId: autoApprovedOptionId,
},
};
}
if (ctx) {
yield* emitPlanUpdate(
ctx,
extractTodosAsPlan(params),
params,
"acp.cursor.extension",
"cursor/update_todos",
);
}
const permissionRequest = parsePermissionRequest(params);
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
const runtimeRequestId = RuntimeRequestId.make(requestId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
pendingApprovals.set(requestId, {
decision,
kind: permissionRequest.kind,
});
yield* offerRuntimeEvent(
makeAcpRequestOpenedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
detail:
permissionRequest.detail ??
encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??
"[unserializable params]",
args: params,
source: "acp.jsonrpc",
method: "session/request_permission",
rawPayload: params,
}),
);
const resolved = yield* Deferred.await(decision);
pendingApprovals.delete(requestId);
yield* offerRuntimeEvent(
makeAcpRequestResolvedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
decision: resolved,
}),
);
return {
outcome:
resolved === "cancel"
? ({ outcome: "cancelled" } as const)
: {
outcome: "selected" as const,
optionId: acpPermissionOutcome(resolved),
},
};
}),
),
);
yield* acp.handleRequestPermission((params) =>
Effect.gen(function* () {
yield* logNative(
input.threadId,
"session/request_permission",
params,
"acp.jsonrpc",
);
if (input.runtimeMode === "full-access") {
const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);
if (autoApprovedOptionId !== undefined) {
return {
outcome: {
outcome: "selected" as const,
optionId: autoApprovedOptionId,
},
};
}
}
const permissionRequest = parsePermissionRequest(params);
const requestId = ApprovalRequestId.make(crypto.randomUUID());
const runtimeRequestId = RuntimeRequestId.make(requestId);
const decision = yield* Deferred.make<ProviderApprovalDecision>();
pendingApprovals.set(requestId, {
decision,
kind: permissionRequest.kind,
});
yield* offerRuntimeEvent(
makeAcpRequestOpenedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
detail:
permissionRequest.detail ??
encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??
"[unserializable params]",
args: params,
source: "acp.jsonrpc",
method: "session/request_permission",
rawPayload: params,
}),
);
const resolved = yield* Deferred.await(decision);
pendingApprovals.delete(requestId);
yield* offerRuntimeEvent(
makeAcpRequestResolvedEvent({
stamp: yield* makeEventStamp(),
provider: PROVIDER,
threadId: input.threadId,
turnId: ctx?.activeTurnId,
requestId: runtimeRequestId,
permissionRequest,
decision: resolved,
}),
);
return {
outcome:
resolved === "cancel"
? ({ outcome: "cancelled" } as const)
: {
outcome: "selected" as const,
optionId: acpPermissionOutcome(resolved),
},
};
}),
);
return yield* acp.start();
}).pipe(
@@ -842,12 +810,7 @@ export function makeCursorAdapter(
}
}),
),
).pipe(
Effect.catch((cause) =>
Effect.logError("Failed to process Cursor runtime notification.", { cause }),
),
Effect.forkChild,
);
).pipe(Effect.forkChild);
ctx.notificationFiber = nf;
sessions.set(input.threadId, ctx);
@@ -882,7 +845,7 @@ export function makeCursorAdapter(
const sendTurn: CursorAdapterShape["sendTurn"] = (input) =>
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
const turnId = TurnId.make(yield* randomUUIDv4);
const turnId = TurnId.make(crypto.randomUUID());
const turnModelSelection =
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
const model = turnModelSelection?.model ?? ctx.session.model;
@@ -1093,9 +1056,6 @@ export function makeCursorAdapter(
yield* Effect.addFinalizer(() =>
Effect.forEach(sessions.values(), stopSessionInternal, { discard: true }).pipe(
Effect.catch((cause) =>
Effect.logError("Failed to emit Cursor session shutdown event.", { cause }),
),
Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)),
Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),
),
@@ -13,11 +13,11 @@ import {
type UserInputQuestion,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Queue from "effect/Queue";
import * as Random from "effect/Random";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
@@ -134,14 +134,40 @@ const toProcessError = (threadId: ThreadId, cause: unknown): ProviderAdapterProc
cause,
});
type EventBaseInput = {
const buildEventBase = (input: {
readonly threadId: ThreadId;
readonly turnId?: TurnId | undefined;
readonly itemId?: string | undefined;
readonly requestId?: string | undefined;
readonly createdAt?: string | undefined;
readonly raw?: unknown;
};
}): Effect.Effect<
Pick<
ProviderRuntimeEvent,
"eventId" | "provider" | "threadId" | "createdAt" | "turnId" | "itemId" | "requestId" | "raw"
>
> =>
Effect.gen(function* () {
const uuid = yield* Random.nextUUIDv4;
const createdAt = input.createdAt ?? (yield* nowIso);
return {
eventId: EventId.make(uuid),
provider: PROVIDER,
threadId: input.threadId,
createdAt,
...(input.turnId ? { turnId: input.turnId } : {}),
...(input.itemId ? { itemId: RuntimeItemId.make(input.itemId) } : {}),
...(input.requestId ? { requestId: RuntimeRequestId.make(input.requestId) } : {}),
...(input.raw !== undefined
? {
raw: {
source: "opencode.sdk.event",
payload: input.raw,
},
}
: {}),
};
});
function toToolLifecycleItemType(toolName: string): ToolLifecycleItemType {
const normalized = toolName.toLowerCase();
@@ -431,7 +457,6 @@ export function makeOpenCodeAdapter(
const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("opencode");
const serverConfig = yield* ServerConfig;
const openCodeRuntime = yield* OpenCodeRuntime;
const crypto = yield* Crypto.Crypto;
const nativeEventLogger =
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
@@ -445,40 +470,6 @@ export function makeOpenCodeAdapter(
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
const sessions = new Map<ThreadId, OpenCodeSessionContext>();
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "crypto/randomUUIDv4",
detail: "Failed to generate OpenCode runtime identifier.",
cause,
}),
),
);
const buildEventBase = (input: EventBaseInput) =>
Effect.all({
eventId: randomUUIDv4.pipe(Effect.map(EventId.make)),
createdAt: input.createdAt === undefined ? nowIso : Effect.succeed(input.createdAt),
}).pipe(
Effect.map(({ eventId, createdAt }) => ({
eventId,
provider: PROVIDER,
threadId: input.threadId,
createdAt,
...(input.turnId ? { turnId: input.turnId } : {}),
...(input.itemId ? { itemId: RuntimeItemId.make(input.itemId) } : {}),
...(input.requestId ? { requestId: RuntimeRequestId.make(input.requestId) } : {}),
...(input.raw !== undefined
? {
raw: {
source: "opencode.sdk.event" as const,
payload: input.raw,
},
}
: {}),
})),
);
// Layer-level finalizer: when the adapter layer shuts down, stop every
// session. Each session's `Scope.close` tears down its spawned OpenCode
@@ -1151,7 +1142,7 @@ export function makeOpenCodeAdapter(
const sendTurn: OpenCodeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {
const context = ensureSessionContext(sessions, input.threadId);
const turnId = TurnId.make(`opencode-turn-${yield* randomUUIDv4}`);
const turnId = TurnId.make(`opencode-turn-${yield* Random.nextUUIDv4}`);
const modelSelection =
input.modelSelection ??
(context.session.model
@@ -1410,7 +1410,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
);
assert.strictEqual(
status.message,
"Claude Code v2.1.110 is too old for Claude Opus 4.8. Upgrade to v2.1.111 or newer to access it.",
"Claude Code v2.1.110 is too old for Claude Opus 4.7. Upgrade to v2.1.111 or newer to access it.",
);
}).pipe(
Effect.provide(
@@ -1,13 +1,40 @@
import type { ProviderDriverKind, ThreadId } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Random from "effect/Random";
import type * as EffectAcpProtocol from "effect-acp/protocol";
import type { EventNdjsonLogger } from "../Layers/EventNdjsonLogger.ts";
import type { AcpSessionRequestLogEvent, AcpSessionRuntimeOptions } from "./AcpSessionRuntime.ts";
function writeNativeAcpLog(input: {
readonly nativeEventLogger: EventNdjsonLogger | undefined;
readonly provider: ProviderDriverKind;
readonly threadId: ThreadId;
readonly kind: "request" | "protocol";
readonly payload: unknown;
}): Effect.Effect<void, never> {
return Effect.gen(function* () {
if (!input.nativeEventLogger) return;
const observedAt = DateTime.formatIso(yield* DateTime.now);
yield* input.nativeEventLogger.write(
{
observedAt,
event: {
id: yield* Random.nextUUIDv4,
kind: input.kind,
provider: input.provider,
createdAt: observedAt,
threadId: input.threadId,
payload: input.payload,
},
},
input.threadId,
);
});
}
function formatRequestLogPayload(event: AcpSessionRequestLogEvent) {
return {
method: event.method,
@@ -18,63 +45,35 @@ function formatRequestLogPayload(event: AcpSessionRequestLogEvent) {
};
}
export const makeAcpNativeLoggerFactory = Effect.fn("makeAcpNativeLoggerFactory")(function* () {
const crypto = yield* Crypto.Crypto;
return (input: {
readonly nativeEventLogger: EventNdjsonLogger | undefined;
readonly provider: ProviderDriverKind;
readonly threadId: ThreadId;
}): Pick<AcpSessionRuntimeOptions, "requestLogger" | "protocolLogging"> => {
const writeNativeAcpLog = (logInput: {
readonly kind: "request" | "protocol";
readonly payload: unknown;
}) =>
Effect.gen(function* () {
if (!input.nativeEventLogger) return;
const observedAt = DateTime.formatIso(yield* DateTime.now);
yield* input.nativeEventLogger.write(
{
observedAt,
event: {
id: yield* crypto.randomUUIDv4,
kind: logInput.kind,
provider: input.provider,
createdAt: observedAt,
threadId: input.threadId,
payload: logInput.payload,
},
},
input.threadId,
);
}).pipe(
Effect.catch((cause) =>
Effect.logWarning("Failed to write native ACP event log.", {
cause,
provider: input.provider,
threadId: input.threadId,
}),
),
);
return {
requestLogger: (event: AcpSessionRequestLogEvent) =>
writeNativeAcpLog({
kind: "request",
payload: formatRequestLogPayload(event),
}),
...(input.nativeEventLogger
? {
protocolLogging: {
logIncoming: true,
logOutgoing: true,
logger: (event: EffectAcpProtocol.AcpProtocolLogEvent) =>
writeNativeAcpLog({
kind: "protocol",
payload: event,
}),
} satisfies NonNullable<AcpSessionRuntimeOptions["protocolLogging"]>,
}
: {}),
};
export function makeAcpNativeLoggers(input: {
readonly nativeEventLogger: EventNdjsonLogger | undefined;
readonly provider: ProviderDriverKind;
readonly threadId: ThreadId;
}): Pick<AcpSessionRuntimeOptions, "requestLogger" | "protocolLogging"> {
return {
requestLogger: (event) =>
writeNativeAcpLog({
nativeEventLogger: input.nativeEventLogger,
provider: input.provider,
threadId: input.threadId,
kind: "request",
payload: formatRequestLogPayload(event),
}),
...(input.nativeEventLogger
? {
protocolLogging: {
logIncoming: true,
logOutgoing: true,
logger: (event: EffectAcpProtocol.AcpProtocolLogEvent) =>
writeNativeAcpLog({
nativeEventLogger: input.nativeEventLogger,
provider: input.provider,
threadId: input.threadId,
kind: "protocol",
payload: event,
}),
} satisfies NonNullable<AcpSessionRuntimeOptions["protocolLogging"]>,
}
: {}),
};
});
}
@@ -1,12 +1,12 @@
// @effect-diagnostics nodeBuiltinImport:off
import { afterEach, expect, it } from "@effect/vitest";
import { afterEach, describe, expect, it } from "@effect/vitest";
import { chmodSync, mkdirSync, symlinkSync, writeFileSync } from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import os from "node:os";
import path from "node:path";
import { ProviderDriverKind } from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Random from "effect/Random";
import {
clearLatestProviderVersionCacheForTests,
createProviderVersionAdvisory,
@@ -18,11 +18,10 @@ import {
} from "./providerMaintenance.ts";
const driver = (value: string) => ProviderDriverKind.make(value);
const makeTempDir = (name: string) =>
Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomUUIDv4),
Effect.map((id) => path.join(os.tmpdir(), `${name}-${id}`)),
);
const makeTempDir = Effect.fn("makeTempDir")(function* (name: string) {
const id = yield* Random.nextUUIDv4;
return path.join(os.tmpdir(), `${name}-${id}`);
});
const isNativeTestCommandPath =
(expectedPathSegment: string) =>
(commandPath: string): boolean =>
@@ -69,7 +68,7 @@ afterEach(() => {
clearLatestProviderVersionCacheForTests();
});
it.layer(NodeServices.layer)("providerMaintenance", (it) => {
describe("providerMaintenance", () => {
it("marks providers with unknown current versions as unknown", () => {
expect(
createProviderVersionAdvisory({
@@ -405,7 +404,7 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {
env: {
PATH: "",
},
});
}).pipe(Effect.provide(NodeServices.layer));
expect(capabilities).toEqual({
provider: driver("packageTool"),
@@ -453,7 +452,7 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {
env: {
PATH: "",
},
});
}).pipe(Effect.provide(NodeServices.layer));
expect(capabilities).toEqual({
provider: driver("packageTool"),
+15 -17
View File
@@ -1,9 +1,9 @@
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Random from "effect/Random";
import * as Schema from "effect/Schema";
import * as Crypto from "node:crypto";
import { homedir } from "node:os";
import { ServerConfig } from "../config.ts";
@@ -23,17 +23,14 @@ class IdentifyUserError extends Schema.TaggedErrorClass<IdentifyUserError>()("Id
}) {}
const hash = (value: string) =>
Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.digest("SHA-256", new TextEncoder().encode(value))),
Effect.map(Encoding.encodeHex),
Effect.mapError(
(cause) =>
new IdentifyUserError({
message: "Failed to hash identifier",
cause,
}),
),
);
Effect.try({
try: () => Crypto.createHash("sha256").update(value).digest("hex"),
catch: (error) =>
new IdentifyUserError({
message: "Failed to hash identifier",
cause: error,
}),
});
const getCodexAccountId = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -67,10 +64,11 @@ const upsertAnonymousId = Effect.gen(function* () {
const anonymousId = yield* fileSystem.readFileString(anonymousIdPath).pipe(
Effect.catch(() =>
Crypto.Crypto.pipe(
Effect.flatMap((crypto) => crypto.randomUUIDv4),
Effect.tap((randomId) => fileSystem.writeFileString(anonymousIdPath, randomId)),
),
Effect.gen(function* () {
const randomId = yield* Random.nextUUIDv4;
yield* fileSystem.writeFileString(anonymousIdPath, randomId);
return randomId;
}),
),
);
@@ -40,7 +40,7 @@ const TelemetryEnvConfig = Config.all({
});
const makeAnalyticsService = Effect.gen(function* () {
const telemetryConfig = yield* TelemetryEnvConfig;
const telemetryConfig = yield* TelemetryEnvConfig.asEffect();
const httpClient = yield* HttpClient.HttpClient;
const serverConfig = yield* ServerConfig;
const identifier = yield* getTelemetryIdentifier;
@@ -2,6 +2,7 @@ import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Random from "effect/Random";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
@@ -78,9 +79,10 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
content: string,
): Effect.Effect<string, TextGenerationError, Scope.Scope> => {
return Effect.gen(function* () {
const tempFileId = yield* Random.nextUUIDv4;
return yield* fileSystem
.makeTempFileScoped({
prefix: `t3code-${prefix}-${process.pid}-`,
prefix: `t3code-${prefix}-${process.pid}-${tempFileId}.tmp`,
})
.pipe(Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)));
}).pipe(
@@ -1,7 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off
import fsPromises from "node:fs/promises";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, afterEach, describe, expect, vi } from "@effect/vitest";
import { assert, describe, expect, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
@@ -13,7 +13,7 @@ import { ServerConfig } from "../../config.ts";
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../../vcs/VcsProcess.ts";
import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts";
import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts";
import { makeWorkspaceEntries, WorkspaceEntriesLive } from "./WorkspaceEntries.ts";
import { WorkspacePathsLive } from "./WorkspacePaths.ts";
const TestLayer = Layer.empty.pipe(
@@ -29,6 +29,28 @@ const TestLayer = Layer.empty.pipe(
Layer.provideMerge(NodeServices.layer),
);
const makeWorkspaceEntriesWithFileSystem = (
makeFileSystem: (fileSystem: FileSystem.FileSystem) => FileSystem.FileSystem,
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return yield* makeWorkspaceEntries.pipe(
Effect.provideService(FileSystem.FileSystem, makeFileSystem(fileSystem)),
);
});
const makeWorkspaceEntriesWithReadDirectory = (
onReadDirectory: (
path: string,
run: () => Effect.Effect<Array<string>, PlatformError.PlatformError>,
) => Effect.Effect<Array<string>, PlatformError.PlatformError>,
) =>
makeWorkspaceEntriesWithFileSystem((fileSystem) => ({
...fileSystem,
readDirectory: (inputPath, options) =>
onReadDirectory(inputPath, () => fileSystem.readDirectory(inputPath, options)),
}));
const makeTempDir = Effect.fn(function* (opts?: { prefix?: string; git?: boolean }) {
const fileSystem = yield* FileSystem.FileSystem;
const dir = yield* fileSystem.makeTempDirectoryScoped({
@@ -80,10 +102,6 @@ const appendSeparator = (input: string) =>
: `${input}${process.platform === "win32" ? "\\" : "/"}`;
it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
afterEach(() => {
vi.restoreAllMocks();
});
describe("search", () => {
it.effect("returns files and directories relative to cwd", () =>
Effect.gen(function* () {
@@ -227,26 +245,22 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
yield* writeTextFile(cwd, "src/components/Composer.tsx");
let rootReadCount = 0;
let releaseRootRead: (() => void) | undefined;
const rootReadGate = new Promise<void>((resolve) => {
releaseRootRead = resolve;
});
const originalReaddir = fsPromises.readdir.bind(fsPromises);
vi.spyOn(fsPromises, "readdir").mockImplementation((async (
...args: Parameters<typeof fsPromises.readdir>
) => {
if (args[0] === cwd) {
rootReadCount += 1;
await rootReadGate;
}
return originalReaddir(...args);
}) as typeof fsPromises.readdir);
const rootReadGate = yield* Deferred.make<void>();
const workspaceEntries = yield* makeWorkspaceEntriesWithReadDirectory((inputPath, run) =>
inputPath === cwd
? Effect.gen(function* () {
rootReadCount += 1;
yield* Deferred.await(rootReadGate);
return yield* run();
})
: run(),
);
const searches = yield* Effect.all(
[
searchWorkspaceEntries({ cwd, query: "", limit: 100 }),
searchWorkspaceEntries({ cwd, query: "comp", limit: 100 }),
searchWorkspaceEntries({ cwd, query: "src", limit: 100 }),
workspaceEntries.search({ cwd, query: "", limit: 100 }),
workspaceEntries.search({ cwd, query: "comp", limit: 100 }),
workspaceEntries.search({ cwd, query: "src", limit: 100 }),
],
{ concurrency: "unbounded" },
).pipe(Effect.forkScoped);
@@ -256,10 +270,10 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
}
yield* Effect.yieldNow;
}
releaseRootRead?.();
yield* Deferred.succeed(rootReadGate, undefined);
yield* Fiber.join(searches);
expect(rootReadCount).toBe(1);
assert.equal(rootReadCount, 1);
}),
);
@@ -274,41 +288,37 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
let activeReads = 0;
let peakReads = 0;
let releaseReads: (() => void) | undefined;
const readsGate = new Promise<void>((resolve) => {
releaseReads = resolve;
});
const originalReaddir = fsPromises.readdir.bind(fsPromises);
vi.spyOn(fsPromises, "readdir").mockImplementation((async (
...args: Parameters<typeof fsPromises.readdir>
) => {
const target = args[0];
if (typeof target === "string" && target.startsWith(cwd)) {
activeReads += 1;
peakReads = Math.max(peakReads, activeReads);
await readsGate;
try {
return await originalReaddir(...args);
} finally {
activeReads -= 1;
}
}
return originalReaddir(...args);
}) as typeof fsPromises.readdir);
const search = yield* searchWorkspaceEntries({ cwd, query: "", limit: 200 }).pipe(
Effect.forkScoped,
const readsGate = yield* Deferred.make<void>();
const workspaceEntries = yield* makeWorkspaceEntriesWithReadDirectory((inputPath, run) =>
inputPath !== cwd && inputPath.startsWith(cwd)
? Effect.gen(function* () {
activeReads += 1;
peakReads = Math.max(peakReads, activeReads);
yield* Deferred.await(readsGate);
return yield* run().pipe(
Effect.ensuring(
Effect.sync(() => {
activeReads -= 1;
}),
),
);
})
: run(),
);
const search = yield* workspaceEntries
.search({ cwd, query: "", limit: 200 })
.pipe(Effect.forkScoped);
for (let attempt = 0; attempt < 50; attempt += 1) {
if (activeReads > 0) {
break;
}
yield* Effect.yieldNow;
}
releaseReads?.();
yield* Deferred.succeed(readsGate, undefined);
yield* Fiber.join(search);
expect(peakReads).toBeLessThanOrEqual(32);
assert.isAtMost(peakReads, 32);
}),
);
});
@@ -1,14 +1,14 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as OS from "node:os";
import fsPromises from "node:fs/promises";
import type { Dirent } from "node:fs";
import * as Cache from "effect/Cache";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import { type FilesystemBrowseInput, type ProjectEntry } from "@t3tools/contracts";
@@ -56,6 +56,11 @@ interface SearchableWorkspaceEntry extends ProjectEntry {
normalizedName: string;
}
interface DirectoryEntry {
readonly name: string;
readonly kind: ProjectEntry["kind"];
}
type RankedWorkspaceEntry = RankedSearchResult<SearchableWorkspaceEntry>;
function toPosixPath(input: string): string {
@@ -180,6 +185,7 @@ const resolveBrowseTarget = (
});
export const makeWorkspaceEntries = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const vcsRegistry = yield* VcsDriverRegistry;
const workspacePaths = yield* WorkspacePaths;
@@ -269,30 +275,64 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
},
);
const readDirectoryEntry = Effect.fn("WorkspaceEntries.readDirectoryEntry")(function* (
absoluteDir: string,
name: string,
): Effect.fn.Return<Option.Option<DirectoryEntry>, never> {
const absolutePath = path.join(absoluteDir, name);
const linkTarget = yield* fileSystem.readLink(absolutePath).pipe(Effect.option);
if (Option.isSome(linkTarget)) {
return Option.none();
}
return yield* fileSystem.stat(absolutePath).pipe(
Effect.map((info) =>
info.type === "Directory"
? Option.some({ name, kind: "directory" as const })
: info.type === "File"
? Option.some({ name, kind: "file" as const })
: Option.none<DirectoryEntry>(),
),
Effect.catch(() => Effect.succeed(Option.none<DirectoryEntry>())),
);
});
const readDirectoryEntries = Effect.fn("WorkspaceEntries.readDirectoryEntries")(function* (
cwd: string,
relativeDir: string,
): Effect.fn.Return<
{ readonly relativeDir: string; readonly dirents: Dirent[] | null },
{
readonly relativeDir: string;
readonly entries: Option.Option<ReadonlyArray<DirectoryEntry>>;
},
WorkspaceEntriesError
> {
return yield* Effect.tryPromise({
try: async () => {
const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
const dirents = await fsPromises.readdir(absoluteDir, { withFileTypes: true });
return { relativeDir, dirents };
},
catch: (cause) =>
new WorkspaceEntriesError({
cwd,
operation: "workspaceEntries.readDirectoryEntries",
detail: cause instanceof Error ? cause.message : String(cause),
cause,
}),
}).pipe(
const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
return yield* fileSystem.readDirectory(absoluteDir).pipe(
Effect.flatMap((names) =>
Effect.forEach(
names.toSorted((left, right) => left.localeCompare(right)),
(name) => readDirectoryEntry(absoluteDir, name),
{ concurrency: "unbounded" },
),
),
Effect.map((entries) => ({
relativeDir,
entries: Option.some(entries.filter(Option.isSome).map((entry) => entry.value)),
})),
Effect.mapError(
(cause) =>
new WorkspaceEntriesError({
cwd,
operation: "workspaceEntries.readDirectoryEntries",
detail: cause.message,
cause,
}),
),
Effect.catchIf(
() => relativeDir.length > 0,
() => Effect.succeed({ relativeDir, dirents: null }),
() =>
Effect.succeed({ relativeDir, entries: Option.none<ReadonlyArray<DirectoryEntry>>() }),
),
);
});
@@ -317,29 +357,26 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
);
const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => {
const { relativeDir, dirents } = directoryEntry;
if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>;
const { relativeDir, entries } = directoryEntry;
if (Option.isNone(entries))
return [] as Array<{ entry: DirectoryEntry; relativePath: string }>;
dirents.sort((left, right) => left.name.localeCompare(right.name));
const candidates: Array<{ dirent: Dirent; relativePath: string }> = [];
for (const dirent of dirents) {
if (!dirent.name || dirent.name === "." || dirent.name === "..") {
const candidates: Array<{ entry: DirectoryEntry; relativePath: string }> = [];
for (const entry of entries.value) {
if (!entry.name || entry.name === "." || entry.name === "..") {
continue;
}
if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) {
continue;
}
if (!dirent.isDirectory() && !dirent.isFile()) {
if (entry.kind === "directory" && IGNORED_DIRECTORY_NAMES.has(entry.name)) {
continue;
}
const relativePath = toPosixPath(
relativeDir ? path.join(relativeDir, dirent.name) : dirent.name,
relativeDir ? path.join(relativeDir, entry.name) : entry.name,
);
if (isPathInIgnoredDirectory(relativePath)) {
continue;
}
candidates.push({ dirent, relativePath });
candidates.push({ entry, relativePath });
}
return candidates;
});
@@ -359,12 +396,12 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
const entry = toSearchableWorkspaceEntry({
path: candidate.relativePath,
kind: candidate.dirent.isDirectory() ? "directory" : "file",
kind: candidate.entry.kind,
parentPath: parentPathOf(candidate.relativePath),
});
entries.push(entry);
if (candidate.dirent.isDirectory()) {
if (candidate.entry.kind === "directory") {
pendingDirectories.push(candidate.relativePath);
}
@@ -442,33 +479,40 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
const dirents = yield* Effect.tryPromise({
try: () => fsPromises.readdir(parentPath, { withFileTypes: true }),
catch: (cause) =>
new WorkspaceEntriesBrowseError({
cwd: input.cwd,
partialPath: input.partialPath,
operation: "workspaceEntries.browse.readDirectory",
detail: `Unable to browse '${parentPath}': ${cause instanceof Error ? cause.message : String(cause)}`,
cause,
const entries = yield* fileSystem.readDirectory(parentPath).pipe(
Effect.flatMap((names) =>
Effect.forEach(names, (name) => readDirectoryEntry(parentPath, name), {
concurrency: "unbounded",
}),
});
),
Effect.map((entries) => entries.filter(Option.isSome).map((entry) => entry.value)),
Effect.mapError(
(cause) =>
new WorkspaceEntriesBrowseError({
cwd: input.cwd,
partialPath: input.partialPath,
operation: "workspaceEntries.browse.readDirectory",
detail: `Unable to browse '${parentPath}': ${cause.message}`,
cause,
}),
),
);
const showHidden = endsWithSeparator || prefix.startsWith(".");
const lowerPrefix = prefix.toLowerCase();
return {
parentPath,
entries: dirents
entries: entries
.filter(
(dirent) =>
dirent.isDirectory() &&
dirent.name.toLowerCase().startsWith(lowerPrefix) &&
(showHidden || !dirent.name.startsWith(".")),
(entry) =>
entry.kind === "directory" &&
entry.name.toLowerCase().startsWith(lowerPrefix) &&
(showHidden || !entry.name.startsWith(".")),
)
.map((dirent) => ({
name: dirent.name,
fullPath: path.join(parentPath, dirent.name),
.map((entry) => ({
name: entry.name,
fullPath: path.join(parentPath, entry.name),
}))
.toSorted((left, right) => left.name.localeCompare(right.name)),
};
+2 -2
View File
@@ -105,7 +105,7 @@ import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings"
import PlanSidebar from "./PlanSidebar";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
import { ChevronDownIcon, TriangleAlertIcon, WifiOffIcon } from "lucide-react";
import { cn, randomHex, randomUUID } from "~/lib/utils";
import { cn, randomUUID } from "~/lib/utils";
import { stackedThreadToast, toastManager } from "./ui/toast";
import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
import { type NewProjectScriptInput } from "./ProjectScriptsControl";
@@ -2846,7 +2846,7 @@ export default function ChatView(props: ChatViewProps) {
prepareWorktree: {
projectCwd: activeProject.cwd,
baseBranch: baseBranchForWorktree,
branch: buildTemporaryWorktreeBranchName(randomHex),
branch: buildTemporaryWorktreeBranchName(),
},
runSetupScript: true,
}
+6 -10
View File
@@ -1,7 +1,8 @@
import { CommandId, MessageId, ProjectId, ThreadId } from "@t3tools/contracts";
import { type CxOptions, cx } from "class-variance-authority";
import * as Encoding from "effect/Encoding";
import { twMerge } from "tailwind-merge";
import * as Random from "effect/Random";
import * as Effect from "effect/Effect";
import { DraftId } from "../composerDraftStore";
export function cn(...inputs: CxOptions) {
@@ -20,16 +21,11 @@ export function isLinuxPlatform(platform: string): boolean {
return /linux/i.test(platform);
}
export function randomHex(byteLength: number): string {
return Encoding.encodeHex(globalThis.crypto.getRandomValues(new Uint8Array(byteLength)));
}
export function randomUUID(): string {
const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
bytes[6] = (bytes[6]! & 0x0f) | 0x40;
bytes[8] = (bytes[8]! & 0x3f) | 0x80;
const hex = Encoding.encodeHex(bytes);
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
if (typeof crypto.randomUUID === "function") {
return crypto.randomUUID();
}
return Effect.runSync(Random.nextUUIDv4);
}
export const newCommandId = (): CommandId => CommandId.make(randomUUID());
+33 -33
View File
@@ -17,7 +17,7 @@
},
"apps/desktop": {
"name": "@t3tools/desktop",
"version": "0.0.24",
"version": "0.0.23",
"dependencies": {
"@effect/platform-node": "catalog:",
"@t3tools/contracts": "workspace:*",
@@ -50,7 +50,7 @@
},
"apps/server": {
"name": "t3",
"version": "0.0.24",
"version": "0.0.23",
"bin": {
"t3": "./dist/bin.mjs",
},
@@ -83,7 +83,7 @@
},
"apps/web": {
"name": "@t3tools/web",
"version": "0.0.24",
"version": "0.0.23",
"dependencies": {
"@base-ui/react": "^1.4.1",
"@dnd-kit/core": "^6.3.1",
@@ -165,7 +165,7 @@
},
"packages/contracts": {
"name": "@t3tools/contracts",
"version": "0.0.24",
"version": "0.0.23",
"dependencies": {
"effect": "catalog:",
},
@@ -272,7 +272,7 @@
"node-pty",
],
"patchedDependencies": {
"[email protected].73": "patches/[email protected].73.patch",
"[email protected].59": "patches/[email protected].59.patch",
},
"overrides": {
"@effect/atom-react": "catalog:",
@@ -285,18 +285,18 @@
"vite": "^8.0.0",
},
"catalog": {
"@effect/atom-react": "4.0.0-beta.73",
"@effect/atom-react": "4.0.0-beta.59",
"@effect/language-service": "0.84.2",
"@effect/openapi-generator": "4.0.0-beta.73",
"@effect/platform-bun": "4.0.0-beta.73",
"@effect/platform-node": "4.0.0-beta.73",
"@effect/platform-node-shared": "4.0.0-beta.73",
"@effect/sql-sqlite-bun": "4.0.0-beta.73",
"@effect/vitest": "4.0.0-beta.73",
"@effect/openapi-generator": "4.0.0-beta.59",
"@effect/platform-bun": "4.0.0-beta.59",
"@effect/platform-node": "4.0.0-beta.59",
"@effect/platform-node-shared": "4.0.0-beta.59",
"@effect/sql-sqlite-bun": "4.0.0-beta.59",
"@effect/vitest": "4.0.0-beta.59",
"@pierre/diffs": "1.1.20",
"@types/bun": "^1.3.11",
"@types/node": "^24.10.13",
"effect": "4.0.0-beta.73",
"effect": "4.0.0-beta.59",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0",
@@ -384,21 +384,21 @@
"@dnd-kit/utilities": ["@dnd-kit/[email protected]", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0" } }, "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg=="],
"@effect/atom-react": ["@effect/[email protected].73", "", { "peerDependencies": { "effect": "^4.0.0-beta.73", "react": "^19.2.4", "scheduler": "*" } }, "sha512-RjNqEMV3z3iEFRBtJ1RVuxBNFMYxhDo2iRwck3kBYjrBuXWrKIRyqnunWJdL2KX97Gqp0orxaujG7qnIA5aIEA=="],
"@effect/atom-react": ["@effect/[email protected].59", "", { "peerDependencies": { "effect": "^4.0.0-beta.59", "react": "^19.2.4", "scheduler": "*" } }, "sha512-VkznQz5c+Z/BLxX+hQNPzPOyUnLQjnbppFSNP7tbPru7HKR4ihzCDC6Xjbx87156MOrZ+JOa6shTMbmvGT5W0w=="],
"@effect/language-service": ["@effect/[email protected]", "", { "bin": { "effect-language-service": "cli.js" } }, "sha512-l04qNxpiA8rY5yXWckRPJ7Mk5MNerXuNymSFf+IdflfI5i8jgL1bpBNLuP6ijg7wgjdHc/KmTnCj2kT0SCntuA=="],
"@effect/openapi-generator": ["@effect/[email protected].73", "", { "peerDependencies": { "@effect/platform-node": "^4.0.0-beta.73", "effect": "^4.0.0-beta.73" }, "bin": { "openapigen": "dist/bin.js" } }, "sha512-tN1mKreMo6kypkuPy8Jt3eGoI0DberzD2/5XxEh17lTdyLg7/SUZv3LssRxtzO5+uIYzLNIHfT2zESz7gjCnwA=="],
"@effect/openapi-generator": ["@effect/[email protected].59", "", { "peerDependencies": { "@effect/platform-node": "^4.0.0-beta.59", "effect": "^4.0.0-beta.59" }, "bin": { "openapigen": "dist/bin.js" } }, "sha512-y1KF6mEb3pA5AdQsNGeWxV42Xi1uBt9Wzo5xMsp06j/WkOM2vWFmvSXw6xvwINAUi1HVjdOLo3xnTXtSv9YdRg=="],
"@effect/platform-bun": ["@effect/[email protected].73", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.73" }, "peerDependencies": { "effect": "^4.0.0-beta.73" } }, "sha512-AQcE89eEVp0xA3SafaswiHPfo6V2YPg7T6PQbQqYK4/S2Sia5cadCm/6y7pfRmuOd4jkWI6VMbNtEDkM0NOBpw=="],
"@effect/platform-bun": ["@effect/[email protected].59", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.59" }, "peerDependencies": { "effect": "^4.0.0-beta.59" } }, "sha512-1jXCIx34X80ojiK9ACO9Q7RST9CXudRmlAbsP4kPqjUo6aqOuGSWXq9ueBO4LbaIZiioRxtTciom35U9ldfTkQ=="],
"@effect/platform-node": ["@effect/[email protected].73", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.73", "mime": "^4.1.0", "undici": "^8.2.0" }, "peerDependencies": { "effect": "^4.0.0-beta.73", "ioredis": "^5.7.0" } }, "sha512-YYkUnmcs6EiRk8K/xNCU3l3jl1YbrhCHCJp+y32DWlKhhZot24/hvw0zYw0aymAtuI9dzAdPryVZkksH4+7ovw=="],
"@effect/platform-node": ["@effect/[email protected].59", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.59", "mime": "^4.1.0", "undici": "^8.0.2" }, "peerDependencies": { "effect": "^4.0.0-beta.59", "ioredis": "^5.7.0" } }, "sha512-jHRW0l953FjYNhQHexr48jFiBu5iGEZH5nmKD6Ha+lPtm1MrKG2V4njfWA3Fv0nUmd3VN87eBJ557wU0twN1Hg=="],
"@effect/platform-node-shared": ["@effect/[email protected].73", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.20.0" }, "peerDependencies": { "effect": "^4.0.0-beta.73" } }, "sha512-/7L8eftDS40VWgLx2GVtBtb8x97Vx4OF5IlRJfh14L5xDFdb9MZXxOuHfHAi+71d90pkbFpOFVtQCSOBWKRAWg=="],
"@effect/platform-node-shared": ["@effect/[email protected].59", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.20.0" }, "peerDependencies": { "effect": "^4.0.0-beta.59" } }, "sha512-fGwFJuG0Te9U/ZeqeDZ2HcSKZBhX5wLjX2/Rxb5+yaOkvvFAN9MvIh05R0QQK5DCcERvnbhHSl1CjSIAN4aEwQ=="],
"@effect/sql-sqlite-bun": ["@effect/[email protected].73", "", { "peerDependencies": { "effect": "^4.0.0-beta.73" } }, "sha512-dkTDDeBLjaKo7h1IE049Oj2BDKQOT+Kc57KbBVaSk36dRdsEmVspRMP7OGbZj3etJU3lL1GJi1BIfnb4N3uMRw=="],
"@effect/sql-sqlite-bun": ["@effect/[email protected].59", "", { "peerDependencies": { "effect": "^4.0.0-beta.59" } }, "sha512-qZWt2HeLgSY8ygEfwbldK9lJ5xg/WP4lgCp1VLlyE8BImSB5g1h+UbhitXr+pOIf+ry4Xmc4ycp7YwTBOFH5/A=="],
"@effect/vitest": ["@effect/[email protected].73", "", { "peerDependencies": { "effect": "^4.0.0-beta.73", "vitest": "^3.0.0 || ^4.0.0" } }, "sha512-HIZa0aekh0ak1YfzCv8GTN75Vbvxp8g+W+z9KczvtUT+LvitX3i9nhLWZLKRrUP1LaJFLPJS2UG9ZGXjxgbjBg=="],
"@effect/vitest": ["@effect/[email protected].59", "", { "peerDependencies": { "effect": "^4.0.0-beta.59", "vitest": "^3.0.0 || ^4.0.0" } }, "sha512-jhpJbpDs1ED58SmFzcfmqLXxle84fiexaMEhV8SBl8WC2GM3FT5DW0WJYFjbZIH5/735brp3iGdjY5/uAxS7Bg=="],
"@electron/get": ["@electron/[email protected]", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ=="],
@@ -608,17 +608,17 @@
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ=="],
"@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/[email protected].4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-LCkGo6JDfaBhgST7UpPWgNgLINpcpabaHfyz5OBx75nUYxBsaEPxjnyNjWpeb/xBup/682QnBfRBy2/LvPutZQ=="],
"@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/[email protected].3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-QZHtlVgbAdy2zAqNA9Gu1UpIuI8Xvsd1v8ic6B2pZmeFnFcMWiPLfWXh7TVw4eGEZ/C9TH281KwhVoeQUKbyjw=="],
"@msgpackr-extract/msgpackr-extract-darwin-x64": ["@msgpackr-extract/[email protected].4", "", { "os": "darwin", "cpu": "x64" }, "sha512-zExlW9zUJKZH/tOtVMttwjKa4Xm/3KcNjnE3dPN92uCktwavMxpgCA3MoJK/DOnTWsQgo224OaST27/mPNAf+w=="],
"@msgpackr-extract/msgpackr-extract-darwin-x64": ["@msgpackr-extract/[email protected].3", "", { "os": "darwin", "cpu": "x64" }, "sha512-mdzd3AVzYKuUmiWOQ8GNhl64/IoFGol569zNRdkLReh6LRLHOXxU4U8eq0JwaD8iFHdVGqSy4IjFL4reoWCDFw=="],
"@msgpackr-extract/msgpackr-extract-linux-arm": ["@msgpackr-extract/[email protected].4", "", { "os": "linux", "cpu": "arm" }, "sha512-Tg3yX65f5GbtXLkrYEHE5oibZG9epyYWas7FogTTEJeDEF9JlXJzKgXaNhT3UXlTOeA+AfZpYZYZ0uPj7Cfquw=="],
"@msgpackr-extract/msgpackr-extract-linux-arm": ["@msgpackr-extract/[email protected].3", "", { "os": "linux", "cpu": "arm" }, "sha512-fg0uy/dG/nZEXfYilKoRe7yALaNmHoYeIoJuJ7KJ+YyU2bvY8vPv27f7UKhGRpY6euFYqEVhxCFZgAUNQBM3nw=="],
"@msgpackr-extract/msgpackr-extract-linux-arm64": ["@msgpackr-extract/[email protected].4", "", { "os": "linux", "cpu": "arm64" }, "sha512-dgX0P/9wGPJeHFBG+ZmhgE6bmtMt7NP5CRBGyyktpopdk/mW4POnrpQsSLtKI1dwpc+pPLuXHDh6vvskyQE/sw=="],
"@msgpackr-extract/msgpackr-extract-linux-arm64": ["@msgpackr-extract/[email protected].3", "", { "os": "linux", "cpu": "arm64" }, "sha512-YxQL+ax0XqBJDZiKimS2XQaf+2wDGVa1enVRGzEvLLVFeqa5kx2bWbtcSXgsxjQB7nRqqIGFIcLteF/sHeVtQg=="],
"@msgpackr-extract/msgpackr-extract-linux-x64": ["@msgpackr-extract/[email protected].4", "", { "os": "linux", "cpu": "x64" }, "sha512-8TNXMEjJc3QEy7R/x1INhgiU+XakDAFUzBhaz7+Rbrs8NH5UQeHQxxmzsSBJGyV6I1jW79undiQm8tOI+D+8FQ=="],
"@msgpackr-extract/msgpackr-extract-linux-x64": ["@msgpackr-extract/[email protected].3", "", { "os": "linux", "cpu": "x64" }, "sha512-cvwNfbP07pKUfq1uH+S6KJ7dT9K8WOE4ZiAcsrSes+UY55E/0jLYc+vq+DO7jlmqRb5zAggExKm0H7O/CBaesg=="],
"@msgpackr-extract/msgpackr-extract-win32-x64": ["@msgpackr-extract/[email protected].4", "", { "os": "win32", "cpu": "x64" }, "sha512-CmCXPQrkbwExx3j946/PtHWHbYJiCRBRDl4BlkRQcJB/YOwQxJRTpoo7aTsortjgoJ1x7opzTSxn7C+ASSLVjQ=="],
"@msgpackr-extract/msgpackr-extract-win32-x64": ["@msgpackr-extract/[email protected].3", "", { "os": "win32", "cpu": "x64" }, "sha512-x0fWaQtYp4E6sktbsdAqnehxDgEc/VwM7uLsRCYWaiGu0ykYdZPiS8zCWdnjHwyiumousxfBm4SO31eXqwEZhQ=="],
"@mswjs/interceptors": ["@mswjs/[email protected]", "", { "dependencies": { "@open-draft/deferred-promise": "^2.2.0", "@open-draft/logger": "^0.3.0", "@open-draft/until": "^2.0.0", "is-node-process": "^1.2.0", "outvariant": "^1.4.3", "strict-event-emitter": "^0.5.1" } }, "sha512-cXu86tF4VQVfwz8W1SPbhoRyHJkti6mjH/XJIxp40jhO4j2k1m4KYrEykxqWPkFF3vrK4rgQppBh//AwyGSXPA=="],
@@ -1160,7 +1160,7 @@
"ee-first": ["[email protected]", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],
"effect": ["[email protected].73", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.8.0", "find-my-way-ts": "^0.1.6", "ini": "^7.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^2.0.1", "multipasta": "^0.2.7", "toml": "^4.1.1", "uuid": "^14.0.0", "yaml": "^2.9.0" } }, "sha512-rL7jjpT31JhxNiZ0X4sgu+WSJi7uwKTX2jz2OW7PrPLfz5DPjT9iXxxVrekxwpfGdgo92bvxbCc5kBlXgusQJw=="],
"effect": ["[email protected].59", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.6.0", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.9", "multipasta": "^0.2.7", "toml": "^4.1.1", "uuid": "^13.0.0", "yaml": "^2.8.3" } }, "sha512-xyUDLeHSe8d6lWGOvR6Fgn2HL6gYeTZ/S4Jzk9uc4ZUxMPPsNZlNXrvk0C7/utQFzeX7uAWcVnG2BjbA0SRoAA=="],
"effect-acp": ["effect-acp@workspace:packages/effect-acp"],
@@ -1230,7 +1230,7 @@
"extract-zip": ["[email protected]", "", { "dependencies": { "debug": "^4.1.1", "get-stream": "^5.1.0", "yauzl": "^2.10.0" }, "optionalDependencies": { "@types/yauzl": "^2.9.1" }, "bin": { "extract-zip": "cli.js" } }, "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg=="],
"fast-check": ["fast-check@4.8.0", "", { "dependencies": { "pure-rand": "^8.0.0" } }, "sha512-GOJ158CUMnN6cSahsv4+ExARvIDuzzinFjkp0E9WtiBa5zcVeLozVkWaE4IzFcc+Y48Wp1EDlUZsXRyAztQcSg=="],
"fast-check": ["fast-check@4.6.0", "", { "dependencies": { "pure-rand": "^8.0.0" } }, "sha512-h7H6Dm0Fy+H4ciQYFxFjXnXkzR2kr9Fb22c0UBpHnm59K2zpr2t13aPTHlltFiNT6zuxp6HMPAVVvgur4BLdpA=="],
"fast-deep-equal": ["[email protected]", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
@@ -1346,7 +1346,7 @@
"inherits": ["[email protected]", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
"ini": ["ini@7.0.0", "", {}, "sha512-ifK0CgjALofS5bkrcTy4RaQ9Vx2Knf/eLeIO+NaswQEpH1UblrtTSCIvN71qQDMq0PeQ/SSPojvEJp9vvvfr+w=="],
"ini": ["ini@6.0.0", "", {}, "sha512-IBTdIkzZNOpqm7q3dRqJvMaldXjDHWkEDfrwGEQTs5eaQMWV+djAhR+wahyNNMAa+qpbDUhBMVt4ZKNwpPm7xQ=="],
"inline-style-parser": ["[email protected]", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="],
@@ -1590,9 +1590,9 @@
"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"msgpackr": ["msgpackr@2.0.2", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.4" } }, "sha512-c5hYOXFbP79Slh6Dzd2wzk+jnV7mX1UxfMYtilnY1NmalXPqG8DGb5cYCMBrW4AsH3zekBBZd4QrKz9NhtvYLQ=="],
"msgpackr": ["msgpackr@1.11.9", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.2" } }, "sha512-FkoAAyyA6HM8wL882EcEyFZ9s7hVADSwG9xrVx3dxxNQAtgADTrJoEWivID82Iv1zWDsv/OtbrrcZAzGzOMdNw=="],
"msgpackr-extract": ["[email protected].4", "", { "dependencies": { "node-gyp-build-optional-packages": "5.2.2" }, "optionalDependencies": { "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.4", "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.4", "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.4" }, "bin": { "download-msgpackr-prebuilds": "bin/download-prebuilds.js" } }, "sha512-4kmO/MdyUIkLIvTPr8VHLil4AtoKIoniWPIEk5+CDy0xnWC84azhSFmuJ7PxZdsYtiP5kEeQsORAVIeMgxT+Hw=="],
"msgpackr-extract": ["[email protected].3", "", { "dependencies": { "node-gyp-build-optional-packages": "5.2.2" }, "optionalDependencies": { "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.3", "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.3", "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.3", "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.3" }, "bin": { "download-msgpackr-prebuilds": "bin/download-prebuilds.js" } }, "sha512-P0efT1C9jIdVRefqjzOQ9Xml57zpOXnIuS+csaB4MdZbTdmGDLo8XhzBG1N7aO11gKDDkJvBLULeFTo46wwreA=="],
"msw": ["[email protected]", "", { "dependencies": { "@inquirer/confirm": "^5.0.0", "@mswjs/interceptors": "^0.41.2", "@open-draft/deferred-promise": "^2.2.0", "@types/statuses": "^2.0.6", "cookie": "^1.0.2", "graphql": "^16.12.0", "headers-polyfill": "^4.0.2", "is-node-process": "^1.2.0", "outvariant": "^1.4.3", "path-to-regexp": "^6.3.0", "picocolors": "^1.1.1", "rettime": "^0.10.1", "statuses": "^2.0.2", "strict-event-emitter": "^0.5.1", "tough-cookie": "^6.0.0", "type-fest": "^5.2.0", "until-async": "^3.0.2", "yargs": "^17.7.2" }, "peerDependencies": { "typescript": ">= 4.8.x" }, "optionalPeers": ["typescript"], "bin": { "msw": "cli/index.js" } }, "sha512-dVg20zi2I2EvnwH/+WupzsOC2mCa7qsIhyMAWtfRikn6RKtwL9+7SaF1IQ5LyZry4tlUtf6KyTVhnlQiZXozTQ=="],
@@ -2022,7 +2022,7 @@
"use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
"uuid": ["uuid@14.0.0", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-Qo+uWgilfSmAhXCMav1uYFynlQO7fMFiMVZsQqZRMIXp0O7rR7qjkj+cPvBHLgBqi960QCoo/PH2/6ZtVqKvrg=="],
"uuid": ["uuid@13.0.0", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w=="],
"vary": ["[email protected]", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="],
@@ -2096,7 +2096,7 @@
"yallist": ["[email protected]", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
"yaml": ["yaml@2.9.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="],
"yaml": ["yaml@2.8.3", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-AvbaCLOO2Otw/lW5bmh9d/WEdcDFdQp2Z2ZUH3pX9U2ihyUY0nvLv7J6TrWowklRGPYbB/IuIMfYgxaCPg5Bpg=="],
"yaml-language-server": ["[email protected]", "", { "dependencies": { "@vscode/l10n": "^0.0.18", "ajv": "^8.17.1", "ajv-draft-04": "^1.0.0", "prettier": "^3.5.0", "request-light": "^0.5.7", "vscode-json-languageservice": "4.1.8", "vscode-languageserver": "^9.0.0", "vscode-languageserver-textdocument": "^1.0.1", "vscode-languageserver-types": "^3.16.0", "vscode-uri": "^3.0.2", "yaml": "2.7.1" }, "bin": { "yaml-language-server": "bin/yaml-language-server" } }, "sha512-qhjK/bzSRZ6HtTvgeFvjNPJGWdZ0+x5NREV/9XZWFjIGezew2b4r5JPy66IfOhd5OA7KeFwk1JfmEbnTvev0cA=="],
+9 -9
View File
@@ -9,14 +9,14 @@
"scripts"
],
"catalog": {
"effect": "4.0.0-beta.73",
"@effect/atom-react": "4.0.0-beta.73",
"@effect/openapi-generator": "4.0.0-beta.73",
"@effect/platform-bun": "4.0.0-beta.73",
"@effect/platform-node": "4.0.0-beta.73",
"@effect/platform-node-shared": "4.0.0-beta.73",
"@effect/sql-sqlite-bun": "4.0.0-beta.73",
"@effect/vitest": "4.0.0-beta.73",
"effect": "4.0.0-beta.59",
"@effect/atom-react": "4.0.0-beta.59",
"@effect/openapi-generator": "4.0.0-beta.59",
"@effect/platform-bun": "4.0.0-beta.59",
"@effect/platform-node": "4.0.0-beta.59",
"@effect/platform-node-shared": "4.0.0-beta.59",
"@effect/sql-sqlite-bun": "4.0.0-beta.59",
"@effect/vitest": "4.0.0-beta.59",
"@effect/language-service": "0.84.2",
"@pierre/diffs": "1.1.20",
"@types/bun": "^1.3.11",
@@ -91,7 +91,7 @@
]
},
"patchedDependencies": {
"[email protected].73": "patches/[email protected].73.patch"
"[email protected].59": "patches/[email protected].59.patch"
},
"trustedDependencies": [
"node-pty",
+1 -8
View File
@@ -55,14 +55,7 @@ describe("parseGitHubRepositoryNameWithOwnerFromRemoteUrl", () => {
describe("isTemporaryWorktreeBranch", () => {
it("matches the generated temporary worktree refName format", () => {
expect(
isTemporaryWorktreeBranch(
buildTemporaryWorktreeBranchName((byteLength) => {
expect(byteLength).toBe(4);
return "DEADBEEF";
}),
),
).toBe(true);
expect(isTemporaryWorktreeBranch(buildTemporaryWorktreeBranchName())).toBe(true);
});
it("matches generated temporary worktree refs", () => {
+4 -4
View File
@@ -6,6 +6,8 @@ import type {
VcsStatusResult,
VcsStatusStreamEvent,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Random from "effect/Random";
import { detectSourceControlProviderFromRemoteUrl } from "./sourceControl.ts";
export const WORKTREE_BRANCH_PREFIX = "t3code";
@@ -84,10 +86,8 @@ export function deriveLocalBranchNameFromRemoteRef(branchName: string): string {
return branchName.slice(firstSeparatorIndex + 1);
}
export function buildTemporaryWorktreeBranchName(
randomHex: (byteLength: number) => string,
): string {
const token = randomHex(4).toLowerCase();
export function buildTemporaryWorktreeBranchName(): string {
const token = Effect.runSync(Random.nextUUIDv4).replace(/-/g, "").slice(0, 8).toLowerCase();
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
}
@@ -1,5 +1,5 @@
diff --git a/dist/unstable/rpc/RpcClient.d.ts b/dist/unstable/rpc/RpcClient.d.ts
index b0f61df..ead663e 100644
index 7c5970042df67a25b4145df017960b3e6febed9c..7af3374632d53ad59f24e80835aa6741853b1f2b 100644
--- a/dist/unstable/rpc/RpcClient.d.ts
+++ b/dist/unstable/rpc/RpcClient.d.ts
@@ -2,6 +2,7 @@ import * as Cause from "../../Cause.ts";
@@ -10,7 +10,7 @@ index b0f61df..ead663e 100644
import * as Layer from "../../Layer.ts";
import * as Queue from "../../Queue.ts";
import * as Schedule from "../../Schedule.ts";
@@ -260,9 +261,40 @@ export declare const layerProtocolWorker: (options: {
@@ -192,9 +193,40 @@ export declare const layerProtocolWorker: (options: {
readonly targetUtilization?: number | undefined;
readonly timeToLive: Duration.Input;
}) => Layer.Layer<Protocol, WorkerError, Worker.WorkerPlatform | Worker.Spawner>;
@@ -50,19 +50,12 @@ index b0f61df..ead663e 100644
+ readonly onPingTimeout?: Effect.Effect<void> | undefined;
}>;
/**
* Represents optional client protocol hooks that run when a transport connects
@@ -279,4 +311,4 @@ declare const ConnectionHooks_base: Context.ServiceClass<ConnectionHooks, "effec
export declare class ConnectionHooks extends ConnectionHooks_base {
}
export {};
-//# sourceMappingURL=RpcClient.d.ts.map
\ No newline at end of file
+//# sourceMappingURL=RpcClient.d.ts.map
* @since 4.0.0
diff --git a/dist/unstable/rpc/RpcClient.js b/dist/unstable/rpc/RpcClient.js
index 811a8a8..f9cf2eb 100644
index 951dfc2d667a9136cfa714dcd3195e6575917fde..599c0345873bedd72bc93afe80eab0c676319421 100644
--- a/dist/unstable/rpc/RpcClient.js
+++ b/dist/unstable/rpc/RpcClient.js
@@ -46,6 +46,7 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
@@ -42,6 +42,7 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
const services = yield* Effect.context();
const scope = Context.get(services, Scope.Scope);
const entries = new Map();
@@ -70,7 +63,7 @@ index 811a8a8..f9cf2eb 100644
let isShutdown = false;
yield* Scope.addFinalizer(scope, Effect.withFiber(parent => {
isShutdown = true;
@@ -83,6 +84,11 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
@@ -79,6 +80,11 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
return Effect.interrupt;
}
const id = generateRequestId();
@@ -82,7 +75,7 @@ index 811a8a8..f9cf2eb 100644
const send = middleware(message => options.onFromClient({
message,
context,
@@ -100,7 +106,7 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
@@ -96,7 +102,7 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
headers: Headers.merge(parentFiber.getRef(CurrentHeaders), headers)
});
if (discard) {
@@ -91,7 +84,7 @@ index 811a8a8..f9cf2eb 100644
}
let fiber;
return Effect.onInterrupt(Effect.callback(resume => {
@@ -118,7 +124,7 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
@@ -114,7 +120,7 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
}
};
entries.set(id, entry);
@@ -100,7 +93,7 @@ index 811a8a8..f9cf2eb 100644
captureStackTrace: false
}) : identity, Effect.runForkWith(parentFiber.context));
fiber.addObserver(exit => {
@@ -127,8 +133,9 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
@@ -123,8 +129,9 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
}
});
}), interruptors => {
@@ -111,7 +104,7 @@ index 811a8a8..f9cf2eb 100644
});
});
const onStreamRequest = Effect.fnUntraced(function* (rpc, middleware, payload, headers, streamBufferSize, context) {
@@ -140,11 +147,17 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
@@ -136,11 +143,17 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
});
const fiber = Fiber.getCurrent();
const id = generateRequestId();
@@ -131,7 +124,7 @@ index 811a8a8..f9cf2eb 100644
});
const queue = yield* Queue.bounded(streamBufferSize);
entries.set(id, {
@@ -152,9 +165,10 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
@@ -148,9 +161,10 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
rpc,
queue,
scope,
@@ -144,7 +137,7 @@ index 811a8a8..f9cf2eb 100644
message,
context,
discard: false
@@ -169,7 +183,7 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
@@ -165,7 +179,7 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
sampled: span.sampled
} : {}),
headers: Headers.merge(fiber.getRef(CurrentHeaders), headers)
@@ -153,7 +146,7 @@ index 811a8a8..f9cf2eb 100644
captureStackTrace: false
}) : identity, Effect.catchCause(error => Queue.failCause(queue, error)), Effect.interruptible, Effect.forkIn(scope, {
startImmediately: true
@@ -199,7 +213,10 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
@@ -195,7 +209,10 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
});
};
};
@@ -165,7 +158,7 @@ index 811a8a8..f9cf2eb 100644
const parentFiber = Fiber.getCurrent();
const fiber = options.onFromClient({
message: {
@@ -213,7 +230,7 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
@@ -209,7 +226,7 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
fiber.addObserver(() => {
resume(Effect.void);
});
@@ -174,7 +167,7 @@ index 811a8a8..f9cf2eb 100644
const write = message => {
switch (message._tag) {
case "Chunk":
@@ -221,7 +238,13 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
@@ -217,7 +234,13 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
const requestId = message.requestId;
const entry = entries.get(requestId);
if (!entry || entry._tag !== "Queue") return Effect.void;
@@ -189,7 +182,7 @@ index 811a8a8..f9cf2eb 100644
message: {
_tag: "Ack",
requestId: message.requestId
@@ -236,11 +259,18 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
@@ -232,11 +255,18 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
const entry = entries.get(requestId);
if (!entry) return Effect.void;
entries.delete(requestId);
@@ -211,7 +204,7 @@ index 811a8a8..f9cf2eb 100644
}
case "Defect":
{
@@ -568,7 +598,7 @@ export const makeProtocolSocket = options => Protocol.make(Effect.fnUntraced(fun
@@ -530,7 +560,7 @@ export const makeProtocolSocket = options => Protocol.make(Effect.fnUntraced(fun
const requestClientMap = new Map();
const write = yield* socket.writer;
let parser = serialization.makeUnsafe();
@@ -220,7 +213,7 @@ index 811a8a8..f9cf2eb 100644
let currentError;
const onOpen = Effect.suspend(() => {
currentError = undefined;
@@ -588,8 +618,7 @@ export const makeProtocolSocket = options => Protocol.make(Effect.fnUntraced(fun
@@ -550,8 +580,7 @@ export const makeProtocolSocket = options => Protocol.make(Effect.fnUntraced(fun
body: () => {
const response = responses[i++];
if (response._tag === "Pong") {
@@ -230,7 +223,7 @@ index 811a8a8..f9cf2eb 100644
}
if ("requestId" in response) {
const clientId = requestClientMap.get(response.requestId);
@@ -617,12 +646,12 @@ export const makeProtocolSocket = options => Protocol.make(Effect.fnUntraced(fun
@@ -579,12 +608,12 @@ export const makeProtocolSocket = options => Protocol.make(Effect.fnUntraced(fun
}
}, {
onOpen
@@ -245,7 +238,7 @@ index 811a8a8..f9cf2eb 100644
}).pipe(Effect.flatMap(() => Effect.fail(new Socket.SocketError({
reason: new Socket.SocketCloseError({
code: 1000
@@ -664,20 +693,20 @@ export const makeProtocolSocket = options => Protocol.make(Effect.fnUntraced(fun
@@ -626,20 +655,20 @@ export const makeProtocolSocket = options => Protocol.make(Effect.fnUntraced(fun
};
}));
const defaultRetryPolicy = /*#__PURE__*/Schedule.exponential(500, 1.5).pipe(/*#__PURE__*/Schedule.either(/*#__PURE__*/Schedule.spaced(5000)));
@@ -270,8 +263,8 @@ index 811a8a8..f9cf2eb 100644
}).pipe(Effect.delay("5 seconds"), Effect.ignore, Effect.forever, Effect.interruptible, Effect.forkScoped);
return {
timeout: latch.await,
@@ -820,6 +849,11 @@ export const makeProtocolWorker = options => Protocol.make(Effect.fnUntraced(fun
* @since 4.0.0
@@ -773,6 +802,11 @@ export const makeProtocolWorker = options => Protocol.make(Effect.fnUntraced(fun
* @category protocol
*/
export const layerProtocolWorker = /*#__PURE__*/flow(makeProtocolWorker, /*#__PURE__*/Layer.effect(Protocol));
+/**
@@ -280,12 +273,5 @@ index 811a8a8..f9cf2eb 100644
+ */
+export class RequestHooks extends /*#__PURE__*/Context.Service()("effect/rpc/RpcClient/RequestHooks") {}
/**
* Represents optional client protocol hooks that run when a transport connects
* and disconnects.
@@ -835,4 +869,4 @@ export const layerProtocolWorker = /*#__PURE__*/flow(makeProtocolWorker, /*#__PU
export class ConnectionHooks extends /*#__PURE__*/Context.Service()("effect/rpc/RpcClient/ConnectionHooks") {}
// internal
const decodeDefect = /*#__PURE__*/Schema.decodeSync(Schema.Defect);
-//# sourceMappingURL=RpcClient.js.map
\ No newline at end of file
+//# sourceMappingURL=RpcClient.js.map
* @since 4.0.0
* @category ConnectionHooks
+1 -1
View File
@@ -278,7 +278,7 @@ export const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (
) {
const path = yield* Path.Path;
const repoRoot = yield* RepoRoot;
const env = yield* BuildEnvConfig;
const env = yield* BuildEnvConfig.asEffect();
const platform = mergeOptions(
input.platform,
+1 -1
View File
@@ -385,7 +385,7 @@ interface DevRunnerCliInput {
export function runDevRunnerWithInput(input: DevRunnerCliInput) {
return Effect.gen(function* () {
const { portOffset, devInstance } = yield* OffsetConfig.pipe(
const { portOffset, devInstance } = yield* OffsetConfig.asEffect().pipe(
Effect.mapError(
(cause) =>
new DevRunnerError({
+1 -1
View File
@@ -24,7 +24,7 @@ const resolveMockUpdateServerConfig = Effect.gen(function* () {
root: Config.string("T3CODE_DESKTOP_MOCK_UPDATE_SERVER_ROOT").pipe(
Config.withDefault("../release-mock"),
),
});
}).asEffect();
const resolvedRoot = path.resolve(import.meta.dirname, config.root);