Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
de766bac62 | ||
|
|
5341a44fda | ||
|
|
7f1949ec9f | ||
|
|
cf07d06321 | ||
|
|
31268945f8 | ||
|
|
6b3050ee74 | ||
|
|
83f0cc9e31 | ||
|
|
e6330ead82 |
No files matched your search
@@ -46,6 +46,14 @@ 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
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"dev:electron": "node scripts/dev-electron.mjs",
|
||||
"build": "tsdown",
|
||||
"start": "node scripts/start-electron.mjs",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"typecheck": "tsgo --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
},
|
||||
@@ -25,11 +25,9 @@
|
||||
"electron-updater": "^6.6.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
},
|
||||
"productName": "T3 Code (Alpha)"
|
||||
|
||||
@@ -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,7 +26,8 @@ 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 = Random.nextUUIDv4.pipe(
|
||||
const makeDesktopRunId = Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomUUIDv4),
|
||||
Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
|
||||
);
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ export interface DesktopAppIdentityShape {
|
||||
export class DesktopAppIdentity extends Context.Service<
|
||||
DesktopAppIdentity,
|
||||
DesktopAppIdentityShape
|
||||
>()("t3/desktop/AppIdentity") {}
|
||||
>()("@t3tools/desktop/app/DesktopAppIdentity") {}
|
||||
|
||||
const normalizeCommitHash = (value: string): Option.Option<string> => {
|
||||
const trimmed = value.trim();
|
||||
|
||||
@@ -18,7 +18,7 @@ export interface DesktopAssetsShape {
|
||||
}
|
||||
|
||||
export class DesktopAssets extends Context.Service<DesktopAssets, DesktopAssetsShape>()(
|
||||
"t3/desktop/Assets",
|
||||
"@t3tools/desktop/app/DesktopAssets",
|
||||
) {}
|
||||
|
||||
const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(function* (
|
||||
|
||||
@@ -32,9 +32,7 @@ const makeEnvironment = (
|
||||
overrides: Partial<DesktopEnvironment.MakeDesktopEnvironmentInput> = {},
|
||||
env: Record<string, string | undefined> = {},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
return yield* DesktopEnvironment.DesktopEnvironment;
|
||||
}).pipe(Effect.provide(makeEnvironmentLayer(overrides, env)));
|
||||
DesktopEnvironment.DesktopEnvironment.pipe(Effect.provide(makeEnvironmentLayer(overrides, env)));
|
||||
|
||||
describe("DesktopEnvironment", () => {
|
||||
it.effect("derives state paths and development identity inside Effect", () =>
|
||||
|
||||
@@ -78,7 +78,7 @@ export interface DesktopEnvironmentShape {
|
||||
export class DesktopEnvironment extends Context.Service<
|
||||
DesktopEnvironment,
|
||||
DesktopEnvironmentShape
|
||||
>()("t3/desktop/Environment") {}
|
||||
>()("@t3tools/desktop/app/DesktopEnvironment") {}
|
||||
|
||||
const APP_BASE_NAME = "T3 Code";
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ export interface DesktopShutdownShape {
|
||||
}
|
||||
|
||||
export class DesktopShutdown extends Context.Service<DesktopShutdown, DesktopShutdownShape>()(
|
||||
"t3/desktop/Shutdown",
|
||||
"@t3tools/desktop/app/DesktopLifecycle/DesktopShutdown",
|
||||
) {}
|
||||
|
||||
const makeShutdown = Effect.gen(function* () {
|
||||
@@ -61,8 +61,11 @@ export interface DesktopLifecycleShape {
|
||||
readonly register: Effect.Effect<void, never, Scope.Scope | DesktopLifecycleRuntimeServices>;
|
||||
}
|
||||
|
||||
/**
|
||||
* @effect-expect-leaking DesktopEnvironment | DesktopShutdown | DesktopState | DesktopWindow | ElectronApp | ElectronTheme
|
||||
*/
|
||||
export class DesktopLifecycle extends Context.Service<DesktopLifecycle, DesktopLifecycleShape>()(
|
||||
"t3/desktop/Lifecycle",
|
||||
"@t3tools/desktop/app/DesktopLifecycle",
|
||||
) {}
|
||||
|
||||
const { logInfo: logLifecycleInfo, logError: logLifecycleError } =
|
||||
|
||||
@@ -43,7 +43,7 @@ export interface DesktopBackendOutputLogShape {
|
||||
export class DesktopBackendOutputLog extends Context.Service<
|
||||
DesktopBackendOutputLog,
|
||||
DesktopBackendOutputLogShape
|
||||
>()("t3/desktop/BackendOutputLog") {}
|
||||
>()("@t3tools/desktop/app/DesktopObservability/DesktopBackendOutputLog") {}
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
|
||||
@@ -9,7 +9,7 @@ export interface DesktopStateShape {
|
||||
}
|
||||
|
||||
export class DesktopState extends Context.Service<DesktopState, DesktopStateShape>()(
|
||||
"t3/desktop/State",
|
||||
"@t3tools/desktop/app/DesktopState",
|
||||
) {}
|
||||
|
||||
export const layer = Layer.effect(
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
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 Random from "effect/Random";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
|
||||
import * as DesktopBackendManager from "./DesktopBackendManager.ts";
|
||||
@@ -13,13 +15,16 @@ import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
|
||||
|
||||
export interface DesktopBackendConfigurationShape {
|
||||
readonly resolve: Effect.Effect<DesktopBackendManager.DesktopBackendStartConfig>;
|
||||
readonly resolve: Effect.Effect<
|
||||
DesktopBackendManager.DesktopBackendStartConfig,
|
||||
PlatformError.PlatformError
|
||||
>;
|
||||
}
|
||||
|
||||
export class DesktopBackendConfiguration extends Context.Service<
|
||||
DesktopBackendConfiguration,
|
||||
DesktopBackendConfigurationShape
|
||||
>()("t3/desktop/BackendConfiguration") {}
|
||||
>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
|
||||
|
||||
interface BackendObservabilitySettings {
|
||||
readonly otlpTracesUrl: Option.Option<string>;
|
||||
@@ -80,23 +85,6 @@ 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;
|
||||
@@ -148,11 +136,22 @@ 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(tokenRef);
|
||||
const bootstrapToken = yield* getOrCreateBootstrapToken;
|
||||
const observabilitySettings = yield* readPersistedBackendObservabilitySettings.pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
|
||||
@@ -116,7 +116,7 @@ export interface DesktopBackendManagerShape {
|
||||
export class DesktopBackendManager extends Context.Service<
|
||||
DesktopBackendManager,
|
||||
DesktopBackendManagerShape
|
||||
>()("t3/desktop/BackendManager") {}
|
||||
>()("@t3tools/desktop/backend/DesktopBackendManager") {}
|
||||
|
||||
const { logWarning: logBackendManagerWarning, logError: logBackendManagerError } =
|
||||
DesktopObservability.makeComponentLogger("desktop-backend-manager");
|
||||
@@ -329,9 +329,19 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
}
|
||||
|
||||
yield* Ref.set(desktopState.backendReady, false);
|
||||
const config = yield* configuration.resolve;
|
||||
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 entryExists = yield* fileSystem
|
||||
.exists(config.entryPath)
|
||||
.exists(config.value.entryPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
|
||||
yield* cancelRestart;
|
||||
@@ -339,11 +349,11 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
...latest,
|
||||
desiredRunning: true,
|
||||
ready: false,
|
||||
config: Option.some(config),
|
||||
config: Option.some(config.value),
|
||||
}));
|
||||
|
||||
if (!entryExists) {
|
||||
yield* scheduleRestart(`missing server entry at ${config.entryPath}`);
|
||||
yield* scheduleRestart(`missing server entry at ${config.value.entryPath}`);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -425,7 +435,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
});
|
||||
|
||||
const program = runBackendProcess({
|
||||
...config,
|
||||
...config.value,
|
||||
onStarted: Effect.fn("desktop.backendManager.onStarted")(function* (pid) {
|
||||
yield* updateActiveRun(runId, (run) => ({
|
||||
...run,
|
||||
@@ -433,7 +443,7 @@ const makeDesktopBackendManager = Effect.fn("makeDesktopBackendManager")(functio
|
||||
}));
|
||||
yield* backendOutputLog.writeSessionBoundary({
|
||||
phase: "START",
|
||||
details: `pid=${pid} port=${config.bootstrap.port} cwd=${config.cwd}`,
|
||||
details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
|
||||
});
|
||||
}),
|
||||
onReady: Effect.fn("desktop.backendManager.onReady")(function* () {
|
||||
|
||||
@@ -275,7 +275,7 @@ export interface DesktopServerExposureShape {
|
||||
export class DesktopServerExposure extends Context.Service<
|
||||
DesktopServerExposure,
|
||||
DesktopServerExposureShape
|
||||
>()("t3/desktop/ServerExposure") {}
|
||||
>()("@t3tools/desktop/backend/DesktopServerExposure") {}
|
||||
|
||||
export interface DesktopNetworkInterfacesServiceShape {
|
||||
readonly read: Effect.Effect<DesktopNetworkInterfaces>;
|
||||
@@ -284,7 +284,7 @@ export interface DesktopNetworkInterfacesServiceShape {
|
||||
export class DesktopNetworkInterfacesService extends Context.Service<
|
||||
DesktopNetworkInterfacesService,
|
||||
DesktopNetworkInterfacesServiceShape
|
||||
>()("t3/desktop/ServerExposure/NetworkInterfaces") {}
|
||||
>()("@t3tools/desktop/backend/DesktopServerExposure/DesktopNetworkInterfacesService") {}
|
||||
|
||||
interface RuntimeState {
|
||||
readonly requestedMode: DesktopServerExposureMode;
|
||||
|
||||
@@ -39,7 +39,7 @@ export interface ElectronAppShape {
|
||||
}
|
||||
|
||||
export class ElectronApp extends Context.Service<ElectronApp, ElectronAppShape>()(
|
||||
"t3/desktop/electron/App",
|
||||
"@t3tools/desktop/electron/ElectronApp",
|
||||
) {}
|
||||
|
||||
const addScopedAppListener = <Args extends ReadonlyArray<unknown>>(
|
||||
|
||||
@@ -29,7 +29,7 @@ export interface ElectronDialogShape {
|
||||
}
|
||||
|
||||
export class ElectronDialog extends Context.Service<ElectronDialog, ElectronDialogShape>()(
|
||||
"t3/desktop/electron/Dialog",
|
||||
"@t3tools/desktop/electron/ElectronDialog",
|
||||
) {}
|
||||
|
||||
const make = ElectronDialog.of({
|
||||
|
||||
@@ -33,7 +33,7 @@ export interface ElectronMenuShape {
|
||||
}
|
||||
|
||||
export class ElectronMenu extends Context.Service<ElectronMenu, ElectronMenuShape>()(
|
||||
"t3/desktop/electron/Menu",
|
||||
"@t3tools/desktop/electron/ElectronMenu",
|
||||
) {}
|
||||
|
||||
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
|
||||
|
||||
@@ -52,7 +52,7 @@ export interface ElectronProtocolShape {
|
||||
}
|
||||
|
||||
export class ElectronProtocol extends Context.Service<ElectronProtocol, ElectronProtocolShape>()(
|
||||
"t3/desktop/electron/Protocol",
|
||||
"@t3tools/desktop/electron/ElectronProtocol",
|
||||
) {}
|
||||
|
||||
export function normalizeDesktopProtocolPathname(rawPath: string): Option.Option<string> {
|
||||
|
||||
@@ -48,7 +48,7 @@ export interface ElectronSafeStorageShape {
|
||||
export class ElectronSafeStorage extends Context.Service<
|
||||
ElectronSafeStorage,
|
||||
ElectronSafeStorageShape
|
||||
>()("@t3tools/desktop/ElectronSafeStorage") {}
|
||||
>()("@t3tools/desktop/electron/ElectronSafeStorage") {}
|
||||
|
||||
const make = ElectronSafeStorage.of({
|
||||
isEncryptionAvailable: Effect.try({
|
||||
|
||||
@@ -26,7 +26,7 @@ export interface ElectronShellShape {
|
||||
}
|
||||
|
||||
export class ElectronShell extends Context.Service<ElectronShell, ElectronShellShape>()(
|
||||
"t3/desktop/electron/Shell",
|
||||
"@t3tools/desktop/electron/ElectronShell",
|
||||
) {}
|
||||
|
||||
const make = ElectronShell.of({
|
||||
|
||||
@@ -13,7 +13,7 @@ export interface ElectronThemeShape {
|
||||
}
|
||||
|
||||
export class ElectronTheme extends Context.Service<ElectronTheme, ElectronThemeShape>()(
|
||||
"t3/desktop/electron/Theme",
|
||||
"@t3tools/desktop/electron/ElectronTheme",
|
||||
) {}
|
||||
|
||||
const make = ElectronTheme.of({
|
||||
|
||||
@@ -67,7 +67,7 @@ export interface ElectronUpdaterShape {
|
||||
}
|
||||
|
||||
export class ElectronUpdater extends Context.Service<ElectronUpdater, ElectronUpdaterShape>()(
|
||||
"t3/desktop/electron/Updater",
|
||||
"@t3tools/desktop/electron/ElectronUpdater",
|
||||
) {}
|
||||
|
||||
export const layer = Layer.succeed(ElectronUpdater, {
|
||||
|
||||
@@ -33,7 +33,7 @@ export interface ElectronWindowShape {
|
||||
}
|
||||
|
||||
export class ElectronWindow extends Context.Service<ElectronWindow, ElectronWindowShape>()(
|
||||
"t3/desktop/electron/Window",
|
||||
"@t3tools/desktop/electron/ElectronWindow",
|
||||
) {}
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
|
||||
@@ -42,7 +42,9 @@ export interface DesktopIpcShape {
|
||||
) => Effect.Effect<void, never, R | Scope.Scope>;
|
||||
}
|
||||
|
||||
export class DesktopIpc extends Context.Service<DesktopIpc, DesktopIpcShape>()("t3/desktop/Ipc") {}
|
||||
export class DesktopIpc extends Context.Service<DesktopIpc, DesktopIpcShape>()(
|
||||
"@t3tools/desktop/ipc/DesktopIpc",
|
||||
) {}
|
||||
|
||||
export const make = (ipcMain: DesktopIpcMain): DesktopIpcShape =>
|
||||
DesktopIpc.of({
|
||||
|
||||
@@ -6,6 +6,7 @@ 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";
|
||||
@@ -13,7 +14,6 @@ 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";
|
||||
|
||||
@@ -89,7 +89,7 @@ export interface DesktopAppSettingsShape {
|
||||
export class DesktopAppSettings extends Context.Service<
|
||||
DesktopAppSettings,
|
||||
DesktopAppSettingsShape
|
||||
>()("t3/desktop/AppSettings") {}
|
||||
>()("@t3tools/desktop/settings/DesktopAppSettings") {}
|
||||
|
||||
export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings {
|
||||
return {
|
||||
@@ -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 suffix = (yield* Random.nextUUIDv4).replace(/-/g, "");
|
||||
const tempPath = `${input.settingsPath}.${process.pid}.${suffix}.tmp`;
|
||||
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeDesktopSettingsJson(
|
||||
toDesktopSettingsDocument(input.settings, input.defaultSettings),
|
||||
);
|
||||
@@ -240,6 +240,7 @@ 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 = (
|
||||
@@ -251,13 +252,18 @@ export const layer = Layer.effect(
|
||||
return Effect.succeed([settingsChange(settings, false), settings] as const);
|
||||
}
|
||||
|
||||
return writeSettings({
|
||||
fileSystem,
|
||||
path,
|
||||
settingsPath: environment.desktopSettingsPath,
|
||||
settings: nextSettings,
|
||||
defaultSettings: environment.defaultDesktopSettings,
|
||||
}).pipe(
|
||||
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,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => new DesktopSettingsWriteError({ cause })),
|
||||
Effect.as([settingsChange(nextSettings, true), nextSettings] as const),
|
||||
);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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";
|
||||
@@ -8,7 +9,6 @@ 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";
|
||||
|
||||
@@ -49,7 +49,7 @@ export interface DesktopClientSettingsShape {
|
||||
export class DesktopClientSettings extends Context.Service<
|
||||
DesktopClientSettings,
|
||||
DesktopClientSettingsShape
|
||||
>()("t3/desktop/ClientSettings") {}
|
||||
>()("@t3tools/desktop/settings/DesktopClientSettings") {}
|
||||
|
||||
const readClientSettings = (
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
@@ -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 suffix = (yield* Random.nextUUIDv4).replace(/-/g, "");
|
||||
const tempPath = `${input.settingsPath}.${process.pid}.${suffix}.tmp`;
|
||||
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeClientSettingsJson(input.settings);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
|
||||
@@ -90,18 +90,24 @@ 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) =>
|
||||
writeClientSettings({
|
||||
fileSystem,
|
||||
path,
|
||||
settingsPath: environment.clientSettingsPath,
|
||||
settings,
|
||||
}).pipe(
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.map((uuid) => uuid.replace(/-/g, "")),
|
||||
Effect.flatMap((suffix) =>
|
||||
writeClientSettings({
|
||||
fileSystem,
|
||||
path,
|
||||
settingsPath: environment.clientSettingsPath,
|
||||
settings,
|
||||
suffix,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) => new DesktopClientSettingsWriteError({ cause })),
|
||||
Effect.withSpan("desktop.clientSettings.set"),
|
||||
),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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";
|
||||
@@ -9,7 +10,6 @@ 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";
|
||||
|
||||
@@ -121,7 +121,7 @@ export interface DesktopSavedEnvironmentsShape {
|
||||
export class DesktopSavedEnvironments extends Context.Service<
|
||||
DesktopSavedEnvironments,
|
||||
DesktopSavedEnvironmentsShape
|
||||
>()("t3/desktop/SavedEnvironments") {}
|
||||
>()("@t3tools/desktop/settings/DesktopSavedEnvironments") {}
|
||||
|
||||
function toPersistedSavedEnvironmentRecord(
|
||||
record: PersistedSavedEnvironmentStorageRecord,
|
||||
@@ -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 suffix = (yield* Random.nextUUIDv4).replace(/-/g, "");
|
||||
const tempPath = `${input.registryPath}.${process.pid}.${suffix}.tmp`;
|
||||
const tempPath = `${input.registryPath}.${process.pid}.${input.suffix}.tmp`;
|
||||
const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document);
|
||||
yield* input.fileSystem.makeDirectory(directory, { recursive: true });
|
||||
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`);
|
||||
@@ -247,14 +247,22 @@ 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) =>
|
||||
writeRegistryDocument({
|
||||
fileSystem,
|
||||
path,
|
||||
registryPath: environment.savedEnvironmentRegistryPath,
|
||||
document,
|
||||
}).pipe(Effect.mapError((cause) => new DesktopSavedEnvironmentsWriteError({ cause })));
|
||||
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 })),
|
||||
);
|
||||
|
||||
return DesktopSavedEnvironments.of({
|
||||
getRegistry: readRegistryDocument(fileSystem, environment.savedEnvironmentRegistryPath).pipe(
|
||||
|
||||
@@ -26,7 +26,7 @@ export interface DesktopShellEnvironmentShape {
|
||||
export class DesktopShellEnvironment extends Context.Service<
|
||||
DesktopShellEnvironment,
|
||||
DesktopShellEnvironmentShape
|
||||
>()("t3/desktop/ShellEnvironment") {}
|
||||
>()("@t3tools/desktop/shell/DesktopShellEnvironment") {}
|
||||
|
||||
const LOGIN_SHELL_ENV_NAMES = [
|
||||
"PATH",
|
||||
|
||||
@@ -68,7 +68,7 @@ export interface DesktopSshEnvironmentShape {
|
||||
export class DesktopSshEnvironment extends Context.Service<
|
||||
DesktopSshEnvironment,
|
||||
DesktopSshEnvironmentShape
|
||||
>()("t3/desktop/SshEnvironment") {}
|
||||
>()("@t3tools/desktop/ssh/DesktopSshEnvironment") {}
|
||||
|
||||
export interface DesktopSshEnvironmentLayerOptions {
|
||||
readonly resolveCliPackageSpec?: () => string;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
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";
|
||||
@@ -86,6 +87,7 @@ 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,6 +2,7 @@ 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";
|
||||
@@ -9,7 +10,6 @@ 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";
|
||||
@@ -129,7 +129,7 @@ export interface DesktopSshPasswordPromptsShape {
|
||||
export class DesktopSshPasswordPrompts extends Context.Service<
|
||||
DesktopSshPasswordPrompts,
|
||||
DesktopSshPasswordPromptsShape
|
||||
>()("t3/desktop/SshPasswordPrompts") {}
|
||||
>()("@t3tools/desktop/ssh/DesktopSshPasswordPrompts") {}
|
||||
|
||||
interface PendingSshPasswordPrompt {
|
||||
readonly requestId: string;
|
||||
@@ -163,6 +163,7 @@ 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;
|
||||
@@ -230,7 +231,11 @@ const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (options: La
|
||||
});
|
||||
}
|
||||
|
||||
const requestId = yield* Random.nextUUIDv4;
|
||||
const requestId = yield* crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
() => new DesktopSshPromptUnavailableError({ reason: "Secure randomness is unavailable." }),
|
||||
),
|
||||
);
|
||||
const now = yield* DateTime.now;
|
||||
const expiresAt = DateTime.formatIso(
|
||||
DateTime.add(now, { milliseconds: passwordPromptTimeoutMs }),
|
||||
|
||||
@@ -53,7 +53,7 @@ export interface DesktopSshRemoteApiShape {
|
||||
export class DesktopSshRemoteApi extends Context.Service<
|
||||
DesktopSshRemoteApi,
|
||||
DesktopSshRemoteApiShape
|
||||
>()("t3/desktop/SshRemoteApi") {}
|
||||
>()("@t3tools/desktop/ssh/DesktopSshRemoteApi") {}
|
||||
|
||||
const decodeExecutionEnvironmentDescriptor = Schema.decodeUnknownEffect(
|
||||
ExecutionEnvironmentDescriptor,
|
||||
|
||||
@@ -100,7 +100,7 @@ export interface DesktopUpdatesShape {
|
||||
}
|
||||
|
||||
export class DesktopUpdates extends Context.Service<DesktopUpdates, DesktopUpdatesShape>()(
|
||||
"t3/desktop/Updates",
|
||||
"@t3tools/desktop/updates/DesktopUpdates",
|
||||
) {}
|
||||
|
||||
const {
|
||||
|
||||
@@ -21,7 +21,7 @@ export interface DesktopApplicationMenuShape {
|
||||
export class DesktopApplicationMenu extends Context.Service<
|
||||
DesktopApplicationMenu,
|
||||
DesktopApplicationMenuShape
|
||||
>()("t3/desktop/ApplicationMenu") {}
|
||||
>()("@t3tools/desktop/window/DesktopApplicationMenu") {}
|
||||
|
||||
type DesktopApplicationMenuRuntimeServices =
|
||||
| DesktopUpdates.DesktopUpdates
|
||||
|
||||
@@ -62,7 +62,7 @@ export interface DesktopWindowShape {
|
||||
}
|
||||
|
||||
export class DesktopWindow extends Context.Service<DesktopWindow, DesktopWindowShape>()(
|
||||
"t3/desktop/Window",
|
||||
"@t3tools/desktop/window/DesktopWindow",
|
||||
) {}
|
||||
|
||||
const { logInfo: logWindowInfo, logWarning: logWindowWarning } =
|
||||
|
||||
@@ -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,6 +226,7 @@ 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>();
|
||||
@@ -241,6 +242,18 @@ 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* () {
|
||||
@@ -309,7 +322,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
for (const fixtureEvent of response.events) {
|
||||
const rawEvent: Record<string, unknown> = {
|
||||
...(fixtureEvent as Record<string, unknown>),
|
||||
eventId: yield* Random.nextUUIDv4,
|
||||
eventId: yield* randomUUIDv4(input.threadId),
|
||||
provider,
|
||||
sessionId: RuntimeSessionId.make(String(input.threadId)),
|
||||
};
|
||||
@@ -366,7 +379,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
if (deferredTurnCompletedEvents.length === 0) {
|
||||
yield* emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make(yield* Random.nextUUIDv4),
|
||||
eventId: EventId.make(yield* randomUUIDv4(input.threadId)),
|
||||
provider,
|
||||
createdAt: nowIso(),
|
||||
threadId: state.snapshot.threadId,
|
||||
|
||||
@@ -19,11 +19,11 @@
|
||||
"build": "node scripts/cli.ts build",
|
||||
"build:bundle": "tsdown",
|
||||
"start": "node dist/bin.mjs",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"typecheck": "tsgo --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.111",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.154",
|
||||
"@effect/platform-bun": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/platform-node-shared": "catalog:",
|
||||
@@ -34,7 +34,6 @@
|
||||
"node-pty": "^1.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
@@ -45,7 +44,6 @@
|
||||
"effect-acp": "workspace:*",
|
||||
"effect-codex-app-server": "workspace:*",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
},
|
||||
"engines": {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
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;
|
||||
@@ -11,7 +10,6 @@ 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 });
|
||||
@@ -19,7 +17,7 @@ export const writeFileStringAtomically = (input: {
|
||||
directory: targetDirectory,
|
||||
prefix: `${path.basename(input.filePath)}.`,
|
||||
});
|
||||
const tempPath = path.join(tempDirectory, `${tempFileId}.tmp`);
|
||||
const tempPath = path.join(tempDirectory, "contents.tmp");
|
||||
|
||||
yield* fs.writeFileString(tempPath, input.contents);
|
||||
yield* fs.rename(tempPath, input.filePath);
|
||||
|
||||
@@ -64,11 +64,16 @@ export const makeAuthControlPlane = Effect.gen(function* () {
|
||||
|
||||
const listPairingLinks: AuthControlPlaneShape["listPairingLinks"] = (input) =>
|
||||
bootstrapCredentials.listActive().pipe(
|
||||
Effect.map((pairingLinks) =>
|
||||
pairingLinks
|
||||
.filter((pairingLink) => (input?.role ? pairingLink.role === input.role : true))
|
||||
.filter((pairingLink) => !input?.excludeSubjects?.includes(pairingLink.subject))
|
||||
.map((pairingLink) =>
|
||||
Effect.map((pairingLinks) => {
|
||||
const activeLinks: Array<AuthPairingLink> = [];
|
||||
for (const pairingLink of pairingLinks) {
|
||||
if (input?.role && pairingLink.role !== input.role) {
|
||||
continue;
|
||||
}
|
||||
if (input?.excludeSubjects?.includes(pairingLink.subject)) {
|
||||
continue;
|
||||
}
|
||||
activeLinks.push(
|
||||
pairingLink.label
|
||||
? ({
|
||||
id: pairingLink.id,
|
||||
@@ -87,11 +92,12 @@ export const makeAuthControlPlane = Effect.gen(function* () {
|
||||
createdAt: pairingLink.createdAt,
|
||||
expiresAt: pairingLink.expiresAt,
|
||||
} satisfies AuthPairingLink),
|
||||
)
|
||||
.toSorted(
|
||||
(left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return activeLinks.toSorted(
|
||||
(left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
|
||||
);
|
||||
}),
|
||||
Effect.mapError(toAuthControlPlaneError("Failed to list pairing links.")),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { AuthPairingLink } from "@t3tools/contracts";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -46,6 +47,7 @@ const generatePairingToken = (): string => {
|
||||
};
|
||||
|
||||
export const makeBootstrapCredentialService = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const config = yield* ServerConfig;
|
||||
const pairingLinks = yield* AuthPairingLinkRepository;
|
||||
const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
|
||||
@@ -141,7 +143,7 @@ export const makeBootstrapCredentialService = Effect.gen(function* () {
|
||||
|
||||
const issueOneTimeToken: BootstrapCredentialServiceShape["issueOneTimeToken"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const id = crypto.randomUUID();
|
||||
const id = yield* crypto.randomUUIDv4;
|
||||
const credential = generatePairingToken();
|
||||
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
|
||||
const now = yield* DateTime.now;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "@t3tools/contracts";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -90,6 +91,7 @@ function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthCli
|
||||
}
|
||||
|
||||
export const makeSessionCredentialService = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
const authSessions = yield* AuthSessionRepository;
|
||||
@@ -203,7 +205,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {
|
||||
const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
|
||||
const issue: SessionCredentialServiceShape["issue"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const sessionId = AuthSessionId.make(crypto.randomUUID());
|
||||
const sessionId = AuthSessionId.make(yield* crypto.randomUUIDv4);
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
|
||||
|
||||
@@ -69,5 +69,5 @@ export interface AuthControlPlaneShape {
|
||||
}
|
||||
|
||||
export class AuthControlPlane extends Context.Service<AuthControlPlane, AuthControlPlaneShape>()(
|
||||
"t3/AuthControlPlane",
|
||||
"t3/auth/Services/AuthControlPlane",
|
||||
) {}
|
||||
@@ -1,4 +1,4 @@
|
||||
// @effect-diagnostics-next-line nodeBuiltinImport:off - NodeHttpServer.layer takes `NodeHttp.createServer` as arg
|
||||
// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises Node HTTP and filesystem boundaries.
|
||||
import * as NodeHttp from "node:http";
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
|
||||
@@ -5,6 +5,7 @@ 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";
|
||||
@@ -58,6 +59,16 @@ 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(
|
||||
@@ -260,7 +271,7 @@ const runProjectMutation = Effect.fn("runProjectMutation")(function* (
|
||||
}) => Effect.Effect<
|
||||
string,
|
||||
Error,
|
||||
FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | WorkspacePaths
|
||||
Crypto.Crypto | FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | WorkspacePaths
|
||||
>,
|
||||
) {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
@@ -343,10 +354,10 @@ const projectAddCommand = Command.make("add", {
|
||||
}
|
||||
|
||||
const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
|
||||
const projectId = ProjectId.make(crypto.randomUUID());
|
||||
const projectId = ProjectId.make(yield* projectCommandUuid);
|
||||
yield* dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
commandId: CommandId.make(yield* projectCommandUuid),
|
||||
projectId,
|
||||
title,
|
||||
workspaceRoot,
|
||||
@@ -384,7 +395,7 @@ const projectRemoveCommand = Command.make("remove", {
|
||||
});
|
||||
yield* dispatch({
|
||||
type: "project.delete",
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
commandId: CommandId.make(yield* projectCommandUuid),
|
||||
projectId: project.id,
|
||||
});
|
||||
return `Removed project ${project.id} (${project.title}).`;
|
||||
@@ -424,7 +435,7 @@ const projectRenameCommand = Command.make("rename", {
|
||||
|
||||
yield* dispatch({
|
||||
type: "project.meta.update",
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
commandId: CommandId.make(yield* projectCommandUuid),
|
||||
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,6 +39,7 @@ 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
|
||||
@@ -64,7 +65,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
|
||||
return persisted;
|
||||
}
|
||||
|
||||
const generated = yield* Random.nextUUIDv4;
|
||||
const generated = yield* crypto.randomUUIDv4;
|
||||
yield* persistEnvironmentId(generated);
|
||||
return generated;
|
||||
});
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
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";
|
||||
@@ -532,32 +531,39 @@ 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,
|
||||
) => {
|
||||
const actionId = options?.actionId ?? randomUUID();
|
||||
const reporter = options?.progressReporter;
|
||||
) =>
|
||||
(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 emit = (event: GitActionProgressPayload) =>
|
||||
reporter
|
||||
? reporter.publish({
|
||||
actionId,
|
||||
cwd: input.cwd,
|
||||
action: input.action,
|
||||
...event,
|
||||
} as GitActionProgressEvent)
|
||||
: Effect.void;
|
||||
|
||||
return {
|
||||
actionId,
|
||||
emit,
|
||||
};
|
||||
};
|
||||
return {
|
||||
actionId,
|
||||
emit,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
const configurePullRequestHeadUpstreamBase = Effect.fn("configurePullRequestHeadUpstream")(
|
||||
function* (
|
||||
@@ -1301,7 +1307,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
modelSelection,
|
||||
});
|
||||
|
||||
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
|
||||
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${yield* randomUUIDv4}.md`);
|
||||
yield* fileSystem
|
||||
.writeFileString(bodyFile, generated.body)
|
||||
.pipe(
|
||||
@@ -1591,7 +1597,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
|
||||
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fn("runStackedAction")(
|
||||
function* (input, options) {
|
||||
const progress = createProgressEmitter(input, options);
|
||||
const progress = yield* createProgressEmitter(input, options);
|
||||
const currentPhase = yield* Ref.make<Option.Option<GitActionProgressPhase>>(Option.none());
|
||||
|
||||
const runAction = Effect.fn("runStackedAction.runAction")(function* (): Effect.fn.Return<
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
export function parseRemoteNamesInGitOrder(stdout: string): ReadonlyArray<string> {
|
||||
return stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0);
|
||||
const remoteNames: Array<string> = [];
|
||||
for (const line of stdout.split("\n")) {
|
||||
const remoteName = line.trim();
|
||||
if (remoteName.length > 0) {
|
||||
remoteNames.push(remoteName);
|
||||
}
|
||||
}
|
||||
return remoteNames;
|
||||
}
|
||||
|
||||
export function parseRemoteNames(stdout: string): ReadonlyArray<string> {
|
||||
|
||||
@@ -35,10 +35,13 @@ export function parseBase64DataUrl(
|
||||
const match = /^data:([^,]+),([a-z0-9+/=\r\n ]+)$/i.exec(dataUrl.trim());
|
||||
if (!match) return null;
|
||||
|
||||
const headerParts = (match[1] ?? "")
|
||||
.split(";")
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part.length > 0);
|
||||
const headerParts: Array<string> = [];
|
||||
for (const part of (match[1] ?? "").split(";")) {
|
||||
const trimmed = part.trim();
|
||||
if (trimmed.length > 0) {
|
||||
headerParts.push(trimmed);
|
||||
}
|
||||
}
|
||||
if (headerParts.length < 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Predicate from "effect/Predicate";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SchemaIssue from "effect/SchemaIssue";
|
||||
import * as SchemaTransformation from "effect/SchemaTransformation";
|
||||
@@ -538,9 +539,11 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const matchingDefaults = DEFAULT_KEYBINDINGS.filter((defaultRule) =>
|
||||
customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule)),
|
||||
).map((rule) => rule.command);
|
||||
const matchingDefaults = Array.filterMap(DEFAULT_KEYBINDINGS, (defaultRule) =>
|
||||
customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule))
|
||||
? Result.succeed(defaultRule.command)
|
||||
: Result.failVoid,
|
||||
);
|
||||
if (matchingDefaults.length > 0) {
|
||||
yield* Effect.logWarning("default keybinding rule already defined in user config", {
|
||||
path: keybindingsConfigPath,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
CommandId,
|
||||
type CheckpointRef,
|
||||
EventId,
|
||||
MessageId,
|
||||
type ProjectId,
|
||||
@@ -9,10 +10,12 @@ import {
|
||||
type ProviderRuntimeEvent,
|
||||
} 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 Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import type * as PlatformError from "effect/PlatformError";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
|
||||
@@ -69,10 +72,12 @@ function checkpointStatusFromRuntime(status: string | undefined): "ready" | "mis
|
||||
}
|
||||
}
|
||||
|
||||
const serverCommandId = (tag: string): CommandId =>
|
||||
CommandId.make(`server:${tag}:${crypto.randomUUID()}`);
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const randomUUID = crypto.randomUUIDv4;
|
||||
const serverEventId = randomUUID.pipe(Effect.map(EventId.make));
|
||||
const serverCommandId = (tag: string) =>
|
||||
randomUUID.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const providerService = yield* ProviderService;
|
||||
@@ -87,24 +92,31 @@ const make = Effect.gen(function* () {
|
||||
readonly detail: string;
|
||||
readonly createdAt: string;
|
||||
}) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
Effect.all({
|
||||
commandId: serverCommandId("checkpoint-revert-failure"),
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: EventId.make(crypto.randomUUID()),
|
||||
tone: "error",
|
||||
kind: "checkpoint.revert.failed",
|
||||
summary: "Checkpoint revert failed",
|
||||
payload: {
|
||||
turnCount: input.turnCount,
|
||||
detail: input.detail,
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
activityId: serverEventId,
|
||||
}).pipe(
|
||||
Effect.flatMap(({ commandId, activityId }) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId,
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: activityId,
|
||||
tone: "error",
|
||||
kind: "checkpoint.revert.failed",
|
||||
summary: "Checkpoint revert failed",
|
||||
payload: {
|
||||
turnCount: input.turnCount,
|
||||
detail: input.detail,
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const appendCaptureFailureActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
@@ -112,23 +124,30 @@ const make = Effect.gen(function* () {
|
||||
readonly detail: string;
|
||||
readonly createdAt: string;
|
||||
}) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
Effect.all({
|
||||
commandId: serverCommandId("checkpoint-capture-failure"),
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: EventId.make(crypto.randomUUID()),
|
||||
tone: "error",
|
||||
kind: "checkpoint.capture.failed",
|
||||
summary: "Checkpoint capture failed",
|
||||
payload: {
|
||||
detail: input.detail,
|
||||
},
|
||||
turnId: input.turnId,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
activityId: serverEventId,
|
||||
}).pipe(
|
||||
Effect.flatMap(({ commandId, activityId }) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId,
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: activityId,
|
||||
tone: "error",
|
||||
kind: "checkpoint.capture.failed",
|
||||
summary: "Checkpoint capture failed",
|
||||
payload: {
|
||||
detail: input.detail,
|
||||
},
|
||||
turnId: input.turnId,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* (
|
||||
threadId: ThreadId,
|
||||
@@ -281,7 +300,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: serverCommandId("checkpoint-turn-diff-complete"),
|
||||
commandId: yield* serverCommandId("checkpoint-turn-diff-complete"),
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
completedAt: input.createdAt,
|
||||
@@ -311,10 +330,10 @@ const make = Effect.gen(function* () {
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: serverCommandId("checkpoint-captured-activity"),
|
||||
commandId: yield* serverCommandId("checkpoint-captured-activity"),
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: EventId.make(crypto.randomUUID()),
|
||||
id: EventId.make(yield* randomUUID),
|
||||
tone: "info",
|
||||
kind: "checkpoint.captured",
|
||||
summary: "Checkpoint captured",
|
||||
@@ -683,9 +702,12 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const staleCheckpointRefs = thread.checkpoints
|
||||
.filter((checkpoint) => checkpoint.checkpointTurnCount > event.payload.turnCount)
|
||||
.map((checkpoint) => checkpoint.checkpointRef);
|
||||
const staleCheckpointRefs: Array<CheckpointRef> = [];
|
||||
for (const checkpoint of thread.checkpoints) {
|
||||
if (checkpoint.checkpointTurnCount > event.payload.turnCount) {
|
||||
staleCheckpointRefs.push(checkpoint.checkpointRef);
|
||||
}
|
||||
}
|
||||
|
||||
if (staleCheckpointRefs.length > 0) {
|
||||
yield* checkpointStore.deleteCheckpointRefs({
|
||||
@@ -697,7 +719,7 @@ const make = Effect.gen(function* () {
|
||||
yield* orchestrationEngine
|
||||
.dispatch({
|
||||
type: "thread.revert.complete",
|
||||
commandId: serverCommandId("checkpoint-revert-complete"),
|
||||
commandId: yield* serverCommandId("checkpoint-revert-complete"),
|
||||
threadId: event.payload.threadId,
|
||||
turnCount: event.payload.turnCount,
|
||||
createdAt: now,
|
||||
@@ -787,7 +809,11 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const processInput = (
|
||||
input: ReactorInput,
|
||||
): Effect.Effect<void, CheckpointStoreError | OrchestrationDispatchError, never> =>
|
||||
): Effect.Effect<
|
||||
void,
|
||||
CheckpointStoreError | OrchestrationDispatchError | PlatformError.PlatformError,
|
||||
never
|
||||
> =>
|
||||
input.source === "domain" ? processDomainEvent(input.event) : processRuntimeEvent(input.event);
|
||||
|
||||
const processInputSafely = (input: ReactorInput) =>
|
||||
|
||||
@@ -211,6 +211,7 @@ describe("OrchestrationEngine", () => {
|
||||
Layer.provide(Layer.succeed(OrchestrationEventStore, eventStore)),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const runtime = ManagedRuntime.make(layer);
|
||||
|
||||
@@ -7,6 +7,7 @@ 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";
|
||||
@@ -81,6 +82,7 @@ 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);
|
||||
@@ -151,7 +153,18 @@ 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(
|
||||
|
||||
@@ -537,12 +537,15 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
projectionPendingApprovalRepository.listByThreadId({ threadId }),
|
||||
]);
|
||||
|
||||
const latestUserMessageAt =
|
||||
messages
|
||||
.filter((message) => message.role === "user")
|
||||
.map((message) => message.createdAt)
|
||||
.toSorted()
|
||||
.at(-1) ?? null;
|
||||
let latestUserMessageAt: string | null = null;
|
||||
for (const message of messages) {
|
||||
if (
|
||||
message.role === "user" &&
|
||||
(latestUserMessageAt === null || message.createdAt > latestUserMessageAt)
|
||||
) {
|
||||
latestUserMessageAt = message.createdAt;
|
||||
}
|
||||
}
|
||||
|
||||
const pendingApprovalCount = pendingApprovals.filter(
|
||||
(approval) => approval.status === "pending",
|
||||
|
||||
@@ -24,9 +24,11 @@ import {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Struct from "effect/Struct";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
@@ -1488,34 +1490,36 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
|
||||
const snapshot = {
|
||||
snapshotSequence: computeSnapshotSequence(stateRows),
|
||||
projects: projectRows
|
||||
.filter((row) => row.deletedAt === null)
|
||||
.map((row) =>
|
||||
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
|
||||
),
|
||||
threads: threadRows
|
||||
.filter((row) => row.deletedAt === null)
|
||||
.map(
|
||||
(row): OrchestrationThreadShell => ({
|
||||
id: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
modelSelection: row.modelSelection,
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
hasPendingUserInput: row.pendingUserInputCount > 0,
|
||||
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
|
||||
}),
|
||||
),
|
||||
projects: Arr.filterMap(projectRows, (row) =>
|
||||
row.deletedAt === null
|
||||
? Result.succeed(
|
||||
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
|
||||
)
|
||||
: Result.failVoid,
|
||||
),
|
||||
threads: Arr.filterMap(threadRows, (row) =>
|
||||
row.deletedAt === null
|
||||
? Result.succeed({
|
||||
id: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
modelSelection: row.modelSelection,
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
hasPendingUserInput: row.pendingUserInputCount > 0,
|
||||
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
|
||||
} satisfies OrchestrationThreadShell)
|
||||
: Result.failVoid,
|
||||
),
|
||||
updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
|
||||
};
|
||||
|
||||
@@ -1621,11 +1625,13 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
|
||||
const snapshot = {
|
||||
snapshotSequence: computeSnapshotSequence(stateRows),
|
||||
projects: projectRows
|
||||
.filter((row) => row.deletedAt === null && activeProjectIds.has(row.projectId))
|
||||
.map((row) =>
|
||||
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
|
||||
),
|
||||
projects: Arr.filterMap(projectRows, (row) =>
|
||||
row.deletedAt === null && activeProjectIds.has(row.projectId)
|
||||
? Result.succeed(
|
||||
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
|
||||
)
|
||||
: Result.failVoid,
|
||||
),
|
||||
threads: threadRows.map(
|
||||
(row): OrchestrationThreadShell => ({
|
||||
id: row.threadId,
|
||||
|
||||
@@ -15,6 +15,7 @@ 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";
|
||||
@@ -81,9 +82,6 @@ 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";
|
||||
@@ -178,6 +176,7 @@ 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;
|
||||
@@ -185,6 +184,9 @@ 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,
|
||||
@@ -214,24 +216,31 @@ const make = Effect.gen(function* () {
|
||||
readonly createdAt: string;
|
||||
readonly requestId?: string;
|
||||
}) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
Effect.all({
|
||||
commandId: serverCommandId("provider-failure-activity"),
|
||||
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,
|
||||
});
|
||||
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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const formatFailureDetail = (cause: Cause.Cause<unknown>): string => {
|
||||
const failReason = cause.reasons.find(Cause.isFailReason);
|
||||
@@ -249,13 +258,17 @@ const make = Effect.gen(function* () {
|
||||
readonly session: OrchestrationSession;
|
||||
readonly createdAt: string;
|
||||
}) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: serverCommandId("provider-session-set"),
|
||||
threadId: input.threadId,
|
||||
session: input.session,
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
serverCommandId("provider-session-set").pipe(
|
||||
Effect.flatMap((commandId) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId,
|
||||
threadId: input.threadId,
|
||||
session: input.session,
|
||||
createdAt: input.createdAt,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const setThreadSessionErrorOnTurnStartFailure = Effect.fnUntraced(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
@@ -610,7 +623,7 @@ const make = Effect.gen(function* () {
|
||||
const renamed = yield* gitWorkflow.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: serverCommandId("worktree-branch-rename"),
|
||||
commandId: yield* serverCommandId("worktree-branch-rename"),
|
||||
threadId: input.threadId,
|
||||
branch: renamed.branch,
|
||||
worktreePath: cwd,
|
||||
@@ -657,7 +670,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: serverCommandId("thread-title-rename"),
|
||||
commandId: yield* serverCommandId("thread-title-rename"),
|
||||
threadId: input.threadId,
|
||||
title: generated.title,
|
||||
});
|
||||
|
||||
@@ -19,6 +19,7 @@ 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";
|
||||
@@ -39,8 +40,6 @@ 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;
|
||||
@@ -607,11 +606,16 @@ 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,
|
||||
@@ -848,7 +852,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.delta",
|
||||
commandId: providerCommandId(input.event, input.commandTag),
|
||||
commandId: yield* providerCommandId(input.event, input.commandTag),
|
||||
threadId: input.threadId,
|
||||
messageId: input.messageId,
|
||||
delta: bufferedText,
|
||||
@@ -915,7 +919,7 @@ const make = Effect.gen(function* () {
|
||||
if (hasRenderableText) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.delta",
|
||||
commandId: providerCommandId(input.event, input.finalDeltaCommandTag),
|
||||
commandId: yield* providerCommandId(input.event, input.finalDeltaCommandTag),
|
||||
threadId: input.threadId,
|
||||
messageId: input.messageId,
|
||||
delta: text,
|
||||
@@ -927,7 +931,7 @@ const make = Effect.gen(function* () {
|
||||
if (input.hasProjectedMessage || hasRenderableText) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.complete",
|
||||
commandId: providerCommandId(input.event, input.commandTag),
|
||||
commandId: yield* providerCommandId(input.event, input.commandTag),
|
||||
threadId: input.threadId,
|
||||
messageId: input.messageId,
|
||||
...(input.turnId ? { turnId: input.turnId } : {}),
|
||||
@@ -1003,7 +1007,7 @@ const make = Effect.gen(function* () {
|
||||
const existingPlan = findProposedPlanById(input.threadProposedPlans, input.planId);
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.proposed-plan.upsert",
|
||||
commandId: providerCommandId(input.event, "proposed-plan-upsert"),
|
||||
commandId: yield* providerCommandId(input.event, "proposed-plan-upsert"),
|
||||
threadId: input.threadId,
|
||||
proposedPlan: {
|
||||
id: input.planId,
|
||||
@@ -1159,10 +1163,11 @@ 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}:${crypto.randomUUID()}`,
|
||||
`provider:source-proposed-plan-implemented:${implementationThreadId}:${commandUuid}`,
|
||||
),
|
||||
threadId: sourceThread.id,
|
||||
proposedPlan: {
|
||||
@@ -1296,7 +1301,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: providerCommandId(event, "thread-session-set"),
|
||||
commandId: yield* providerCommandId(event, "thread-session-set"),
|
||||
threadId: thread.id,
|
||||
session: {
|
||||
threadId: thread.id,
|
||||
@@ -1342,7 +1347,7 @@ const make = Effect.gen(function* () {
|
||||
if (spillChunk.length > 0) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.delta",
|
||||
commandId: providerCommandId(event, "assistant-delta-buffer-spill"),
|
||||
commandId: yield* providerCommandId(event, "assistant-delta-buffer-spill"),
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
delta: spillChunk,
|
||||
@@ -1353,7 +1358,7 @@ const make = Effect.gen(function* () {
|
||||
} else {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.delta",
|
||||
commandId: providerCommandId(event, "assistant-delta"),
|
||||
commandId: yield* providerCommandId(event, "assistant-delta"),
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
delta: assistantDelta,
|
||||
@@ -1546,7 +1551,7 @@ const make = Effect.gen(function* () {
|
||||
if (shouldApplyRuntimeError) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: providerCommandId(event, "runtime-error-session-set"),
|
||||
commandId: yield* providerCommandId(event, "runtime-error-session-set"),
|
||||
threadId: thread.id,
|
||||
session: {
|
||||
threadId: thread.id,
|
||||
@@ -1568,7 +1573,7 @@ const make = Effect.gen(function* () {
|
||||
if (event.type === "thread.metadata.updated" && event.payload.name) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: providerCommandId(event, "thread-meta-update"),
|
||||
commandId: yield* providerCommandId(event, "thread-meta-update"),
|
||||
threadId: thread.id,
|
||||
title: event.payload.name,
|
||||
});
|
||||
@@ -1596,7 +1601,7 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: providerCommandId(event, "thread-turn-diff-complete"),
|
||||
commandId: yield* providerCommandId(event, "thread-turn-diff-complete"),
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
completedAt: now,
|
||||
@@ -1613,13 +1618,17 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const activities = runtimeEventToActivities(event);
|
||||
yield* Effect.forEach(activities, (activity) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: providerCommandId(event, "thread-activity-append"),
|
||||
threadId: thread.id,
|
||||
activity,
|
||||
createdAt: activity.createdAt,
|
||||
}),
|
||||
providerCommandId(event, "thread-activity-append").pipe(
|
||||
Effect.flatMap((commandId) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId,
|
||||
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 { describe, expect, it } from "vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
import { createEmptyReadModel, projectEvent } from "./projector.ts";
|
||||
@@ -20,93 +20,87 @@ const asEventId = (value: string): EventId => EventId.make(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
|
||||
|
||||
async function seedReadModel(): Promise<OrchestrationReadModel> {
|
||||
const seedReadModel = Effect.gen(function* () {
|
||||
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",
|
||||
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 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 = 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,
|
||||
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",
|
||||
},
|
||||
}),
|
||||
);
|
||||
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,
|
||||
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",
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
type PlannedEvent = Omit<OrchestrationEvent, "sequence">;
|
||||
|
||||
@@ -142,12 +136,11 @@ function normalizeDeleteEvent(event: PlannedEvent | ReadonlyArray<PlannedEvent>)
|
||||
});
|
||||
}
|
||||
|
||||
describe("decider deletion flows", () => {
|
||||
it("rejects deleting a non-empty project without force", async () => {
|
||||
const readModel = await seedReadModel();
|
||||
|
||||
await expect(
|
||||
Effect.runPromise(
|
||||
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(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "project.delete",
|
||||
@@ -156,72 +149,69 @@ describe("decider deletion flows", () => {
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("cannot be deleted without force=true");
|
||||
});
|
||||
);
|
||||
expect(error.message).toContain("cannot be deleted without 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,
|
||||
};
|
||||
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,
|
||||
};
|
||||
|
||||
const forcedResult = await Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
const forcedResult = yield* 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 = await Effect.runPromise(
|
||||
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 = yield* decideOrchestrationCommand({
|
||||
command: nextCommand,
|
||||
readModel: sequentialReadModel,
|
||||
}),
|
||||
);
|
||||
const nextEvents = Array.isArray(decided) ? decided : [decided];
|
||||
sequentialEvents.push(...nextEvents);
|
||||
for (const nextEvent of nextEvents) {
|
||||
nextSequence += 1;
|
||||
sequentialReadModel = await Effect.runPromise(
|
||||
projectEvent(sequentialReadModel, {
|
||||
});
|
||||
const nextEvents = Array.isArray(decided) ? decided : [decided];
|
||||
sequentialEvents.push(...nextEvents);
|
||||
for (const nextEvent of nextEvents) {
|
||||
nextSequence += 1;
|
||||
sequentialReadModel = yield* projectEvent(sequentialReadModel, {
|
||||
...nextEvent,
|
||||
sequence: nextSequence,
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expect(normalizeDeleteEvent(forcedResult)).toEqual(normalizeDeleteEvent(sequentialEvents));
|
||||
});
|
||||
expect(normalizeDeleteEvent(forcedResult)).toEqual(normalizeDeleteEvent(sequentialEvents));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -8,8 +8,9 @@ import {
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { expect, it } from "@effect/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";
|
||||
@@ -17,14 +18,13 @@ 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);
|
||||
|
||||
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({
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("cmd-project-create-scripts"),
|
||||
@@ -34,19 +34,19 @@ describe("decider project scripts", () => {
|
||||
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("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, {
|
||||
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, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create-scripts"),
|
||||
aggregateKind: "project",
|
||||
@@ -66,21 +66,19 @@ describe("decider project scripts", () => {
|
||||
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 = await Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "project.meta.update",
|
||||
commandId: CommandId.make("cmd-project-update-scripts"),
|
||||
@@ -88,19 +86,19 @@ describe("decider project scripts", () => {
|
||||
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("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, {
|
||||
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, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create"),
|
||||
aggregateKind: "project",
|
||||
@@ -120,10 +118,8 @@ describe("decider project scripts", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const readModel = await Effect.runPromise(
|
||||
projectEvent(withProject, {
|
||||
});
|
||||
const readModel = yield* projectEvent(withProject, {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-thread-create"),
|
||||
aggregateKind: "thread",
|
||||
@@ -149,11 +145,9 @@ describe("decider project scripts", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const result = await Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start"),
|
||||
@@ -173,35 +167,35 @@ describe("decider project scripts", () => {
|
||||
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("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, {
|
||||
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, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create"),
|
||||
aggregateKind: "project",
|
||||
@@ -221,10 +215,8 @@ describe("decider project scripts", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const readModel = await Effect.runPromise(
|
||||
projectEvent(withProject, {
|
||||
});
|
||||
const readModel = yield* projectEvent(withProject, {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-thread-create"),
|
||||
aggregateKind: "thread",
|
||||
@@ -250,11 +242,9 @@ describe("decider project scripts", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const result = await Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.make("cmd-runtime-mode-set"),
|
||||
@@ -263,27 +253,27 @@ describe("decider project scripts", () => {
|
||||
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("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, {
|
||||
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, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create"),
|
||||
aggregateKind: "project",
|
||||
@@ -303,10 +293,8 @@ describe("decider project scripts", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const readModel = await Effect.runPromise(
|
||||
projectEvent(withProject, {
|
||||
});
|
||||
const readModel = yield* projectEvent(withProject, {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-thread-create"),
|
||||
aggregateKind: "thread",
|
||||
@@ -332,11 +320,9 @@ describe("decider project scripts", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const result = await Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
const result = yield* decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.interaction-mode.set",
|
||||
commandId: CommandId.make("cmd-interaction-mode-set"),
|
||||
@@ -345,19 +331,19 @@ describe("decider project scripts", () => {
|
||||
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",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,10 +1,13 @@
|
||||
import type {
|
||||
OrchestrationCommand,
|
||||
OrchestrationEvent,
|
||||
OrchestrationReadModel,
|
||||
import {
|
||||
EventId,
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationEvent,
|
||||
type 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 {
|
||||
@@ -27,17 +30,27 @@ function withEventBase(
|
||||
readonly occurredAt: string;
|
||||
readonly metadata?: OrchestrationEvent["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 ?? {},
|
||||
};
|
||||
): 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 ?? {},
|
||||
})),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
type PlannedOrchestrationEvent = Omit<OrchestrationEvent, "sequence">;
|
||||
@@ -52,7 +65,11 @@ const decideCommandSequence = Effect.fn("decideCommandSequence")(function* ({
|
||||
}: {
|
||||
readonly commands: ReadonlyArray<OrchestrationCommand>;
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
}): Effect.fn.Return<ReadonlyArray<PlannedOrchestrationEvent>, OrchestrationCommandInvariantError> {
|
||||
}): Effect.fn.Return<
|
||||
ReadonlyArray<PlannedOrchestrationEvent>,
|
||||
OrchestrationCommandInvariantError | PlatformError.PlatformError,
|
||||
Crypto.Crypto
|
||||
> {
|
||||
let nextReadModel = readModel;
|
||||
let nextSequence = readModel.snapshotSequence;
|
||||
const plannedEvents: PlannedOrchestrationEvent[] = [];
|
||||
@@ -82,7 +99,11 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
}: {
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
}): Effect.fn.Return<DecideOrchestrationCommandResult, OrchestrationCommandInvariantError> {
|
||||
}): Effect.fn.Return<
|
||||
DecideOrchestrationCommandResult,
|
||||
OrchestrationCommandInvariantError | PlatformError.PlatformError,
|
||||
Crypto.Crypto
|
||||
> {
|
||||
switch (command.type) {
|
||||
case "project.create": {
|
||||
yield* requireProjectAbsent({
|
||||
@@ -92,12 +113,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
});
|
||||
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "project",
|
||||
aggregateId: command.projectId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
})),
|
||||
type: "project.created",
|
||||
payload: {
|
||||
projectId: command.projectId,
|
||||
@@ -119,12 +140,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "project",
|
||||
aggregateId: command.projectId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
})),
|
||||
type: "project.meta-updated",
|
||||
payload: {
|
||||
projectId: command.projectId,
|
||||
@@ -176,12 +197,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "project",
|
||||
aggregateId: command.projectId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
})),
|
||||
type: "project.deleted" as const,
|
||||
payload: {
|
||||
projectId: command.projectId,
|
||||
@@ -202,12 +223,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
})),
|
||||
type: "thread.created",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -232,12 +253,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
})),
|
||||
type: "thread.deleted",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -254,12 +275,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
})),
|
||||
type: "thread.archived",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -277,12 +298,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
})),
|
||||
type: "thread.unarchived",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -299,12 +320,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
})),
|
||||
type: "thread.meta-updated",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -327,12 +348,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
})),
|
||||
type: "thread.runtime-mode-set",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -350,12 +371,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
});
|
||||
const occurredAt = yield* nowIso;
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
})),
|
||||
type: "thread.interaction-mode-set",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -396,12 +417,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
});
|
||||
}
|
||||
const userMessageEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
})),
|
||||
type: "thread.message-sent",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -416,12 +437,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
},
|
||||
};
|
||||
const turnStartRequestedEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
})),
|
||||
causationEventId: userMessageEvent.eventId,
|
||||
type: "thread.turn-start-requested",
|
||||
payload: {
|
||||
@@ -447,12 +468,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
})),
|
||||
type: "thread.turn-interrupt-requested",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -469,7 +490,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
@@ -477,7 +498,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
metadata: {
|
||||
requestId: command.requestId,
|
||||
},
|
||||
}),
|
||||
})),
|
||||
type: "thread.approval-response-requested",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -495,7 +516,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
@@ -503,7 +524,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
metadata: {
|
||||
requestId: command.requestId,
|
||||
},
|
||||
}),
|
||||
})),
|
||||
type: "thread.user-input-response-requested",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -521,12 +542,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
})),
|
||||
type: "thread.checkpoint-revert-requested",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -543,12 +564,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
})),
|
||||
type: "thread.session-stop-requested",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -564,13 +585,13 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
metadata: {},
|
||||
}),
|
||||
})),
|
||||
type: "thread.session-set",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -586,12 +607,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
})),
|
||||
type: "thread.message-sent",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -613,12 +634,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
})),
|
||||
type: "thread.message-sent",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -640,12 +661,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
})),
|
||||
type: "thread.proposed-plan-upserted",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -661,12 +682,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
})),
|
||||
type: "thread.turn-diff-completed",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -688,12 +709,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
})),
|
||||
type: "thread.reverted",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
@@ -717,13 +738,13 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
.requestId as OrchestrationEvent["metadata"]["requestId"])
|
||||
: undefined;
|
||||
return {
|
||||
...withEventBase({
|
||||
...(yield* withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
...(requestId !== undefined ? { metadata: { requestId } } : {}),
|
||||
}),
|
||||
})),
|
||||
type: "thread.activity-appended",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
|
||||
@@ -58,8 +58,10 @@ export const orchestrationSnapshotRouteLayer = HttpRouter.add(
|
||||
status: 200,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.catchTag("OrchestrationDispatchCommandError", respondToOrchestrationHttpError),
|
||||
Effect.catchTag("OrchestrationGetSnapshotError", respondToOrchestrationHttpError),
|
||||
Effect.catchTags({
|
||||
OrchestrationDispatchCommandError: respondToOrchestrationHttpError,
|
||||
OrchestrationGetSnapshotError: respondToOrchestrationHttpError,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ const AuthSessionDbRow = Schema.Struct({
|
||||
revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
|
||||
});
|
||||
|
||||
function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): typeof AuthSessionRecord.Type {
|
||||
function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): AuthSessionRecord {
|
||||
return {
|
||||
sessionId: row.sessionId,
|
||||
subject: row.subject,
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
yield* SqlClient.SqlClient;
|
||||
});
|
||||
export default Effect.asVoid(SqlClient.SqlClient);
|
||||
@@ -252,14 +252,12 @@ export const layerConfig = (
|
||||
config: Config.Wrap<SqliteClientConfig>,
|
||||
): Layer.Layer<Client.SqlClient, Config.ConfigError> =>
|
||||
Layer.effectContext(
|
||||
Config.unwrap(config)
|
||||
.asEffect()
|
||||
.pipe(
|
||||
Effect.flatMap(make),
|
||||
Effect.map((client) =>
|
||||
Context.make(SqliteClient, client).pipe(Context.add(Client.SqlClient, client)),
|
||||
),
|
||||
Config.unwrap(config).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,7 +651,9 @@ 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* Random.nextUUIDv4}`,
|
||||
command: `t3code-no-such-command-${yield* Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomUUIDv4),
|
||||
)}`,
|
||||
args: [],
|
||||
}).pipe(Effect.provide(spawnerLayer), Effect.result);
|
||||
assert.equal(result._tag, "Failure");
|
||||
|
||||
@@ -257,7 +257,7 @@ export interface ExternalLauncherShape {
|
||||
* ExternalLauncher - Service tag for browser/editor launch operations.
|
||||
*/
|
||||
export class ExternalLauncher extends Context.Service<ExternalLauncher, ExternalLauncherShape>()(
|
||||
"t3/process/ExternalLauncher",
|
||||
"t3/process/externalLauncher",
|
||||
) {}
|
||||
|
||||
// ==============================
|
||||
|
||||
@@ -90,7 +90,7 @@ export interface ProcessRunnerShape {
|
||||
}
|
||||
|
||||
export class ProcessRunner extends Context.Service<ProcessRunner, ProcessRunnerShape>()(
|
||||
"t3/process/ProcessRunner",
|
||||
"t3/processRunner",
|
||||
) {}
|
||||
|
||||
const DEFAULT_TIMEOUT = "60 seconds";
|
||||
|
||||
@@ -41,4 +41,4 @@ export interface ProjectSetupScriptRunnerShape {
|
||||
export class ProjectSetupScriptRunner extends Context.Service<
|
||||
ProjectSetupScriptRunner,
|
||||
ProjectSetupScriptRunnerShape
|
||||
>()("t3/project/ProjectSetupScriptRunner") {}
|
||||
>()("t3/project/Services/ProjectSetupScriptRunner") {}
|
||||
@@ -15,6 +15,7 @@
|
||||
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";
|
||||
@@ -77,6 +78,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
|
||||
export type ClaudeDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
*/
|
||||
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";
|
||||
@@ -69,6 +70,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
*/
|
||||
export type CodexDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
*/
|
||||
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";
|
||||
@@ -61,6 +62,7 @@ const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
|
||||
export type CursorDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| Path.Path
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
*/
|
||||
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";
|
||||
@@ -73,6 +74,7 @@ const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
|
||||
export type OpenCodeDriverEnv =
|
||||
| ChildProcessSpawner.ChildProcessSpawner
|
||||
| Crypto.Crypto
|
||||
| FileSystem.FileSystem
|
||||
| HttpClient.HttpClient
|
||||
| OpenCodeRuntime
|
||||
|
||||
@@ -42,7 +42,7 @@ const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
|
||||
|
||||
// Test-local service tag so the rest of the file can keep using `yield* ClaudeAdapter`.
|
||||
class ClaudeAdapter extends Context.Service<ClaudeAdapter, ClaudeAdapterShape>()(
|
||||
"test/ClaudeAdapter",
|
||||
"t3/provider/Layers/ClaudeAdapter.test/ClaudeAdapter",
|
||||
) {}
|
||||
|
||||
class FakeClaudeQuery implements AsyncIterable<SDKMessage> {
|
||||
|
||||
@@ -52,6 +52,7 @@ 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";
|
||||
@@ -60,7 +61,6 @@ 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";
|
||||
@@ -70,6 +70,7 @@ import { ServerConfig } from "../../config.ts";
|
||||
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
|
||||
import {
|
||||
getClaudeModelCapabilities,
|
||||
isClaudeUltracodeEffort,
|
||||
normalizeClaudeCliEffort,
|
||||
resolveClaudeApiModelId,
|
||||
resolveClaudeEffort,
|
||||
@@ -244,9 +245,13 @@ function toProcessError(
|
||||
function normalizeClaudeStreamMessages(
|
||||
cause: Cause.Cause<{ readonly message: string }>,
|
||||
): ReadonlyArray<string> {
|
||||
const errors = Cause.prettyErrors(cause)
|
||||
.map((error) => error.message.trim())
|
||||
.filter((message) => message.length > 0);
|
||||
const errors: Array<string> = [];
|
||||
for (const error of Cause.prettyErrors(cause)) {
|
||||
const message = error.message.trim();
|
||||
if (message.length > 0) {
|
||||
errors.push(message);
|
||||
}
|
||||
}
|
||||
if (errors.length > 0) {
|
||||
return errors;
|
||||
}
|
||||
@@ -255,8 +260,11 @@ function normalizeClaudeStreamMessages(
|
||||
return squashed.length > 0 ? [squashed] : [];
|
||||
}
|
||||
|
||||
function getEffectiveClaudeAgentEffort(effort: string | null | undefined): ClaudeSdkEffort | null {
|
||||
const normalized = normalizeClaudeCliEffort(effort);
|
||||
function getEffectiveClaudeAgentEffort(
|
||||
effort: string | null | undefined,
|
||||
model: string | null | undefined,
|
||||
): ClaudeSdkEffort | null {
|
||||
const normalized = normalizeClaudeCliEffort(effort, model);
|
||||
return normalized ? (normalized as ClaudeSdkEffort) : null;
|
||||
}
|
||||
|
||||
@@ -998,6 +1006,7 @@ 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),
|
||||
);
|
||||
@@ -1024,7 +1033,18 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.make(id));
|
||||
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 makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });
|
||||
|
||||
const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
@@ -1048,7 +1068,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
id:
|
||||
"uuid" in message && typeof message.uuid === "string"
|
||||
? message.uuid
|
||||
: yield* Random.nextUUIDv4,
|
||||
: yield* randomUUIDv4,
|
||||
kind: "notification",
|
||||
provider: PROVIDER,
|
||||
createdAt: observedAt,
|
||||
@@ -1132,7 +1152,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
}
|
||||
|
||||
const block: AssistantTextBlockState = {
|
||||
itemId: yield* Random.nextUUIDv4,
|
||||
itemId: yield* randomUUIDv4,
|
||||
blockIndex,
|
||||
emittedTextDelta: false,
|
||||
fallbackText: options?.fallbackText ?? "",
|
||||
@@ -1965,7 +1985,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* Random.nextUUIDv4);
|
||||
const turnId = TurnId.make(yield* randomUUIDv4);
|
||||
const startedAt = yield* nowIso;
|
||||
context.turnState = {
|
||||
turnId,
|
||||
@@ -2378,7 +2398,17 @@ 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)),
|
||||
Stream.runForEach((message) =>
|
||||
handleSdkMessage(context, message).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
toProcessError(
|
||||
cause,
|
||||
"Failed to process Claude runtime event.",
|
||||
context.session.threadId,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const handleStreamExit = Effect.fn("handleStreamExit")(function* (
|
||||
@@ -2552,8 +2582,7 @@ 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* Random.nextUUIDv4 : undefined;
|
||||
const newSessionId = existingResumeSessionId === undefined ? yield* randomUUIDv4 : undefined;
|
||||
const sessionId = existingResumeSessionId ?? newSessionId;
|
||||
|
||||
const runtimeContext = yield* Effect.context<never>();
|
||||
@@ -2588,7 +2617,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
readonly toolUseID?: string;
|
||||
},
|
||||
) {
|
||||
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
|
||||
// Parse questions from the SDK's AskUserQuestion input.
|
||||
// `id` MUST equal the full question text — Claude SDK >= 2.1.121 looks
|
||||
@@ -2758,7 +2787,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
} satisfies PermissionResult;
|
||||
}
|
||||
|
||||
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
const requestType = classifyRequestType(toolName);
|
||||
const detail = summarizeToolRequest(toolName, toolInput);
|
||||
const decisionDeferred = yield* Deferred.make<ProviderApprovalDecision>();
|
||||
@@ -2887,7 +2916,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const thinking = thinkingSupported
|
||||
? getModelSelectionBooleanOptionValue(modelSelection, "thinking")
|
||||
: undefined;
|
||||
const effectiveEffort = getEffectiveClaudeAgentEffort(effort);
|
||||
const ultracode = isClaudeUltracodeEffort(effort);
|
||||
const effectiveEffort = getEffectiveClaudeAgentEffort(effort, modelSelection?.model);
|
||||
const runtimeModeToPermission: Record<string, PermissionMode> = {
|
||||
"auto-accept-edits": "acceptEdits",
|
||||
"full-access": "bypassPermissions",
|
||||
@@ -2896,6 +2926,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const settings = {
|
||||
...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
...(ultracode ? { ultracode: true } : {}),
|
||||
};
|
||||
const queryOptions: ClaudeQueryOptions = {
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
@@ -2903,8 +2934,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
pathToClaudeCodeExecutable: claudeBinaryPath,
|
||||
systemPrompt: { type: "preset", preset: "claude_code" },
|
||||
settingSources: [...CLAUDE_SETTING_SOURCES],
|
||||
// The SDK type lags the CLI here: Opus 4.7 accepts `xhigh` even though
|
||||
// the published `Options["effort"]` union currently stops at `max`.
|
||||
// `ultracode` is a Claude Code setting, not an API effort level. It is
|
||||
// normalized to `xhigh` above and paired with `settings.ultracode`.
|
||||
...(effectiveEffort
|
||||
? {
|
||||
effort: effectiveEffort as unknown as NonNullable<ClaudeQueryOptions["effort"]>,
|
||||
@@ -3059,7 +3090,11 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
if (context.streamFiber === streamFiber) {
|
||||
context.streamFiber = undefined;
|
||||
}
|
||||
return handleStreamExit(context, exit);
|
||||
return handleStreamExit(context, exit).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logError("Failed to close Claude runtime stream.", { cause }),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -3120,7 +3155,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
});
|
||||
}
|
||||
|
||||
const turnId = TurnId.make(yield* Random.nextUUIDv4);
|
||||
const turnId = TurnId.make(yield* randomUUIDv4);
|
||||
const turnState: ClaudeTurnState = {
|
||||
turnId,
|
||||
startedAt: yield* nowIso,
|
||||
@@ -3269,7 +3304,12 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
emitExitEvent: false,
|
||||
}),
|
||||
{ discard: true },
|
||||
).pipe(Effect.tap(() => Queue.shutdown(runtimeEventQueue))),
|
||||
).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logError("Failed to emit Claude session shutdown event.", { cause }),
|
||||
),
|
||||
Effect.tap(() => Queue.shutdown(runtimeEventQueue)),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@@ -48,8 +48,73 @@ const CLAUDE_PRESENTATION = {
|
||||
displayName: "Claude",
|
||||
showInteractionModeToggle: true,
|
||||
} as const;
|
||||
const MINIMUM_CLAUDE_OPUS_4_8_VERSION = "2.1.154";
|
||||
const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
|
||||
|
||||
const CLAUDE_EFFORT_OPTIONS = {
|
||||
opus48: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultracode", label: "Ultracode" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
opus47: [
|
||||
{ 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" },
|
||||
],
|
||||
opus46: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
sonnet46: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
opus45: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
],
|
||||
} as const;
|
||||
|
||||
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: CLAUDE_EFFORT_OPTIONS.opus48,
|
||||
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",
|
||||
@@ -59,14 +124,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
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" },
|
||||
],
|
||||
options: CLAUDE_EFFORT_OPTIONS.opus47,
|
||||
promptInjectedValues: ["ultrathink"],
|
||||
}),
|
||||
buildSelectOptionDescriptor({
|
||||
@@ -89,13 +147,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
options: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
options: CLAUDE_EFFORT_OPTIONS.opus46,
|
||||
promptInjectedValues: ["ultrathink"],
|
||||
}),
|
||||
buildBooleanOptionDescriptor({
|
||||
@@ -122,12 +174,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
options: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
],
|
||||
options: CLAUDE_EFFORT_OPTIONS.opus45,
|
||||
}),
|
||||
buildBooleanOptionDescriptor({
|
||||
id: "fastMode",
|
||||
@@ -145,12 +192,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
buildSelectOptionDescriptor({
|
||||
id: "effort",
|
||||
label: "Reasoning",
|
||||
options: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
options: CLAUDE_EFFORT_OPTIONS.sonnet46,
|
||||
promptInjectedValues: ["ultrathink"],
|
||||
}),
|
||||
buildSelectOptionDescriptor({
|
||||
@@ -179,6 +221,10 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
},
|
||||
];
|
||||
|
||||
function supportsClaudeOpus48(version: string | null | undefined): boolean {
|
||||
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_4_8_VERSION) >= 0 : false;
|
||||
}
|
||||
|
||||
function supportsClaudeOpus47(version: string | null | undefined): boolean {
|
||||
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_4_7_VERSION) >= 0 : false;
|
||||
}
|
||||
@@ -186,10 +232,20 @@ function supportsClaudeOpus47(version: string | null | undefined): boolean {
|
||||
function getBuiltInClaudeModelsForVersion(
|
||||
version: string | null | undefined,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
if (supportsClaudeOpus47(version)) {
|
||||
return BUILT_IN_MODELS;
|
||||
}
|
||||
return BUILT_IN_MODELS.filter((model) => model.slug !== "claude-opus-4-7");
|
||||
return BUILT_IN_MODELS.filter((model) => {
|
||||
if (model.slug === "claude-opus-4-8") {
|
||||
return supportsClaudeOpus48(version);
|
||||
}
|
||||
if (model.slug === "claude-opus-4-7") {
|
||||
return supportsClaudeOpus47(version);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
function formatClaudeOpus48UpgradeMessage(version: string | null): string {
|
||||
const versionLabel = version ? `v${version}` : "the installed version";
|
||||
return `Claude Code ${versionLabel} is too old for Claude Opus 4.8. Upgrade to v${MINIMUM_CLAUDE_OPUS_4_8_VERSION} or newer to access it.`;
|
||||
}
|
||||
|
||||
function formatClaudeOpus47UpgradeMessage(version: string | null): string {
|
||||
@@ -223,21 +279,34 @@ export function resolveClaudeEffort(
|
||||
* CLI's `--effort` flag.
|
||||
*
|
||||
* Mirrors the mapping used when invoking the Claude Agent SDK
|
||||
* ({@link getEffectiveClaudeAgentEffort} in ClaudeAdapter): the Opus 4.7
|
||||
* capability `"xhigh"` is rewritten to the accepted CLI value `"max"`, and
|
||||
* `"ultrathink"` is filtered out because it is a prompt-prefix mode rather
|
||||
* than a CLI-effort value. Returns `undefined` when no flag should be passed.
|
||||
* ({@link getEffectiveClaudeAgentEffort} in ClaudeAdapter): `ultracode` is a
|
||||
* Claude Code setting that pairs with `xhigh`, `ultrathink` is filtered out
|
||||
* because it is a prompt-prefix mode, and older model compatibility mappings
|
||||
* are preserved for current Claude Code behavior.
|
||||
*/
|
||||
export function normalizeClaudeCliEffort(effort: string | null | undefined): string | undefined {
|
||||
export function normalizeClaudeCliEffort(
|
||||
effort: string | null | undefined,
|
||||
model: string | null | undefined,
|
||||
): string | undefined {
|
||||
if (!effort || effort === "ultrathink") {
|
||||
return undefined;
|
||||
}
|
||||
if (effort === "xhigh") {
|
||||
if (effort === "ultracode") {
|
||||
return "xhigh";
|
||||
}
|
||||
if (effort === "xhigh" && model !== "claude-opus-4-8") {
|
||||
return "max";
|
||||
}
|
||||
if (effort === "max" && model === "claude-sonnet-4-6") {
|
||||
return "high";
|
||||
}
|
||||
return effort;
|
||||
}
|
||||
|
||||
export function isClaudeUltracodeEffort(effort: string | null | undefined): boolean {
|
||||
return effort === "ultracode";
|
||||
}
|
||||
|
||||
export function resolveClaudeApiModelId(modelSelection: ModelSelection): string {
|
||||
switch (getModelSelectionStringOptionValue(modelSelection, "contextWindow")) {
|
||||
case "1m":
|
||||
@@ -248,11 +317,13 @@ export function resolveClaudeApiModelId(modelSelection: ModelSelection): string
|
||||
}
|
||||
|
||||
function toTitleCaseWords(value: string): string {
|
||||
return value
|
||||
.split(/[\s_-]+/g)
|
||||
.filter(Boolean)
|
||||
.map((part) => part[0]!.toUpperCase() + part.slice(1).toLowerCase())
|
||||
.join(" ");
|
||||
const parts: Array<string> = [];
|
||||
for (const part of value.split(/[\s_-]+/g)) {
|
||||
if (part.length > 0) {
|
||||
parts.push(part[0]!.toUpperCase() + part.slice(1).toLowerCase());
|
||||
}
|
||||
}
|
||||
return parts.join(" ");
|
||||
}
|
||||
|
||||
function claudeSubscriptionLabel(subscriptionType: string | undefined): string | undefined {
|
||||
@@ -617,9 +688,11 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
claudeSettings.customModels,
|
||||
DEFAULT_CLAUDE_MODEL_CAPABILITIES,
|
||||
);
|
||||
const opus47UpgradeMessage = supportsClaudeOpus47(parsedVersion)
|
||||
const versionUpgradeMessage = supportsClaudeOpus48(parsedVersion)
|
||||
? undefined
|
||||
: formatClaudeOpus47UpgradeMessage(parsedVersion);
|
||||
: supportsClaudeOpus47(parsedVersion)
|
||||
? formatClaudeOpus48UpgradeMessage(parsedVersion)
|
||||
: formatClaudeOpus47UpgradeMessage(parsedVersion);
|
||||
|
||||
const capabilities = resolveCapabilities
|
||||
? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
|
||||
@@ -663,7 +736,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
...(capabilities.email ? { email: capabilities.email } : {}),
|
||||
...(authMetadata ? authMetadata : {}),
|
||||
},
|
||||
...(opus47UpgradeMessage ? { message: opus47UpgradeMessage } : {}),
|
||||
...(versionUpgradeMessage ? { message: versionUpgradeMessage } : {}),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -50,7 +50,7 @@ const decodeCodexSettings = Schema.decodeSync(CodexSettings);
|
||||
|
||||
// Test-local service tag so the rest of the file can keep using `yield* CodexAdapter`.
|
||||
class CodexAdapter extends Context.Service<CodexAdapter, CodexAdapterShape>()(
|
||||
"test/CodexAdapter",
|
||||
"t3/provider/Layers/CodexAdapter.test/CodexAdapter",
|
||||
) {}
|
||||
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
|
||||
|
||||
@@ -25,6 +25,7 @@ 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";
|
||||
@@ -1349,6 +1350,7 @@ 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 ??
|
||||
@@ -1406,6 +1408,7 @@ 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({
|
||||
|
||||
@@ -319,16 +319,21 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
|
||||
} satisfies CodexAppServerProviderSnapshot;
|
||||
});
|
||||
|
||||
const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>
|
||||
codexSettings.customModels
|
||||
.map((model) => model.trim())
|
||||
.filter((model, index, models) => model.length > 0 && models.indexOf(model) === index)
|
||||
.map((model) => ({
|
||||
slug: model,
|
||||
name: model,
|
||||
isCustom: true,
|
||||
capabilities: null,
|
||||
}));
|
||||
const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] => {
|
||||
const models = new Set<string>();
|
||||
for (const model of codexSettings.customModels) {
|
||||
const trimmed = model.trim();
|
||||
if (trimmed.length > 0) {
|
||||
models.add(trimmed);
|
||||
}
|
||||
}
|
||||
return Array.from(models, (model) => ({
|
||||
slug: model,
|
||||
name: model,
|
||||
isCustom: true,
|
||||
capabilities: null,
|
||||
}));
|
||||
};
|
||||
|
||||
const makePendingCodexProvider = (
|
||||
codexSettings: CodexSettings,
|
||||
|
||||
@@ -17,6 +17,7 @@ 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";
|
||||
@@ -25,7 +26,6 @@ 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,11 +697,12 @@ export const makeCodexSessionRuntime = (
|
||||
): Effect.Effect<
|
||||
CodexSessionRuntimeShape,
|
||||
CodexErrors.CodexAppServerError,
|
||||
ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
|
||||
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | 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>());
|
||||
@@ -746,6 +747,15 @@ 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 = {
|
||||
@@ -765,7 +775,7 @@ export const makeCodexSessionRuntime = (
|
||||
|
||||
const emitEvent = (event: Omit<ProviderEvent, "id" | "provider" | "createdAt">) =>
|
||||
Effect.gen(function* () {
|
||||
const id = yield* Random.nextUUIDv4;
|
||||
const id = yield* randomUUIDv4;
|
||||
return yield* offerEvent({
|
||||
id: EventId.make(id),
|
||||
provider: PROVIDER,
|
||||
@@ -933,7 +943,7 @@ export const makeCodexSessionRuntime = (
|
||||
|
||||
yield* client.handleServerRequest("item/commandExecution/requestApproval", (payload) =>
|
||||
Effect.gen(function* () {
|
||||
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
const turnId = TurnId.make(payload.turnId);
|
||||
const itemId = ProviderItemId.make(payload.itemId);
|
||||
const decision = yield* Deferred.make<ProviderApprovalDecision>();
|
||||
@@ -989,7 +999,7 @@ export const makeCodexSessionRuntime = (
|
||||
|
||||
yield* client.handleServerRequest("item/fileChange/requestApproval", (payload) =>
|
||||
Effect.gen(function* () {
|
||||
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
const turnId = TurnId.make(payload.turnId);
|
||||
const itemId = ProviderItemId.make(payload.itemId);
|
||||
const decision = yield* Deferred.make<ProviderApprovalDecision>();
|
||||
@@ -1045,7 +1055,7 @@ export const makeCodexSessionRuntime = (
|
||||
|
||||
yield* client.handleServerRequest("item/tool/requestUserInput", (payload) =>
|
||||
Effect.gen(function* () {
|
||||
const requestId = ApprovalRequestId.make(yield* Random.nextUUIDv4);
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
const turnId = TurnId.make(payload.turnId);
|
||||
const itemId = ProviderItemId.make(payload.itemId);
|
||||
const answers = yield* Deferred.make<ProviderUserInputAnswers>();
|
||||
@@ -1229,7 +1239,11 @@ export const makeCodexSessionRuntime = (
|
||||
status: "closed",
|
||||
activeTurnId: undefined,
|
||||
});
|
||||
yield* emitSessionEvent("session/closed", "Session stopped");
|
||||
yield* emitSessionEvent("session/closed", "Session stopped").pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logError("Failed to emit Codex session closed event.", { cause }),
|
||||
),
|
||||
);
|
||||
yield* Scope.close(runtimeScope, Exit.void);
|
||||
yield* Queue.shutdown(serverNotifications);
|
||||
yield* Queue.shutdown(events);
|
||||
|
||||
@@ -32,7 +32,7 @@ const decodeCursorSettings = Schema.decodeSync(CursorSettings);
|
||||
|
||||
// Test-local service tag so the rest of the file can keep using `yield* CursorAdapter`.
|
||||
class CursorAdapter extends Context.Service<CursorAdapter, CursorAdapterShape>()(
|
||||
"test/CursorAdapter",
|
||||
"t3/provider/Layers/CursorAdapter.test/CursorAdapter",
|
||||
) {}
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
@@ -22,6 +22,7 @@ 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";
|
||||
@@ -30,13 +31,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";
|
||||
@@ -62,7 +63,7 @@ import {
|
||||
type AcpSessionModeState,
|
||||
parsePermissionRequest,
|
||||
} from "../acp/AcpRuntimeModel.ts";
|
||||
import { makeAcpNativeLoggers } from "../acp/AcpNativeLogging.ts";
|
||||
import { makeAcpNativeLoggerFactory } from "../acp/AcpNativeLogging.ts";
|
||||
import { applyCursorAcpModelSelection, makeCursorAcpRuntime } from "../acp/CursorAcpSupport.ts";
|
||||
import {
|
||||
CursorAskQuestionRequest,
|
||||
@@ -96,7 +97,7 @@ export interface CursorAdapterLiveOptions {
|
||||
* Selections are honored when `modelSelection.instanceId` matches this value.
|
||||
* Defaults to the legacy built-in instance id (`cursor`).
|
||||
*/
|
||||
readonly instanceId?: typeof ProviderInstanceId.Type;
|
||||
readonly instanceId?: ProviderInstanceId;
|
||||
/**
|
||||
* Optional per-session settings resolver. When provided the adapter yields
|
||||
* this effect at the start of every session and uses the result instead of
|
||||
@@ -314,6 +315,7 @@ 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
|
||||
@@ -323,14 +325,36 @@ 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 nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.make(id));
|
||||
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 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);
|
||||
@@ -369,7 +393,7 @@ export function makeCursorAdapter(
|
||||
{
|
||||
observedAt,
|
||||
event: {
|
||||
id: yield* Random.nextUUIDv4,
|
||||
id: yield* randomUUIDv4,
|
||||
kind: "notification",
|
||||
provider: PROVIDER,
|
||||
createdAt: observedAt,
|
||||
@@ -524,159 +548,167 @@ export function makeCursorAdapter(
|
||||
);
|
||||
const started = yield* Effect.gen(function* () {
|
||||
yield* acp.handleExtRequest("cursor/ask_question", CursorAskQuestionRequest, (params) =>
|
||||
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 };
|
||||
}),
|
||||
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 };
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* acp.handleExtRequest("cursor/create_plan", CursorCreatePlanRequest, (params) =>
|
||||
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;
|
||||
}),
|
||||
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;
|
||||
}),
|
||||
),
|
||||
);
|
||||
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,
|
||||
"cursor/update_todos",
|
||||
"session/request_permission",
|
||||
params,
|
||||
"acp.cursor.extension",
|
||||
"acp.jsonrpc",
|
||||
);
|
||||
if (ctx) {
|
||||
yield* emitPlanUpdate(
|
||||
ctx,
|
||||
extractTodosAsPlan(params),
|
||||
params,
|
||||
"acp.cursor.extension",
|
||||
"cursor/update_todos",
|
||||
);
|
||||
}
|
||||
}),
|
||||
);
|
||||
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)
|
||||
: {
|
||||
if (input.runtimeMode === "full-access") {
|
||||
const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);
|
||||
if (autoApprovedOptionId !== undefined) {
|
||||
return {
|
||||
outcome: {
|
||||
outcome: "selected" as const,
|
||||
optionId: acpPermissionOutcome(resolved),
|
||||
optionId: autoApprovedOptionId,
|
||||
},
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
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),
|
||||
},
|
||||
};
|
||||
}),
|
||||
),
|
||||
);
|
||||
return yield* acp.start();
|
||||
}).pipe(
|
||||
@@ -810,7 +842,12 @@ export function makeCursorAdapter(
|
||||
}
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
).pipe(
|
||||
Effect.catch((cause) =>
|
||||
Effect.logError("Failed to process Cursor runtime notification.", { cause }),
|
||||
),
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
ctx.notificationFiber = nf;
|
||||
sessions.set(input.threadId, ctx);
|
||||
@@ -845,7 +882,7 @@ export function makeCursorAdapter(
|
||||
const sendTurn: CursorAdapterShape["sendTurn"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(input.threadId);
|
||||
const turnId = TurnId.make(crypto.randomUUID());
|
||||
const turnId = TurnId.make(yield* randomUUIDv4);
|
||||
const turnModelSelection =
|
||||
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
|
||||
const model = turnModelSelection?.model ?? ctx.session.model;
|
||||
@@ -1056,6 +1093,9 @@ 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),
|
||||
),
|
||||
|
||||
@@ -596,11 +596,12 @@ export const discoverCursorModelCapabilitiesViaAcp = (
|
||||
);
|
||||
}
|
||||
|
||||
const targetModelSlugs = new Set(
|
||||
existingModels
|
||||
.filter((model) => !model.isCustom && !hasCursorModelCapabilities(model))
|
||||
.map((model) => model.slug),
|
||||
);
|
||||
const targetModelSlugs = new Set<string>();
|
||||
for (const model of existingModels) {
|
||||
if (!model.isCustom && !hasCursorModelCapabilities(model)) {
|
||||
targetModelSlugs.add(model.slug);
|
||||
}
|
||||
}
|
||||
if (targetModelSlugs.size === 0) {
|
||||
return buildCursorDiscoveredModels(
|
||||
modelChoices.map((modelChoice) => ({
|
||||
@@ -721,9 +722,13 @@ export interface CursorAboutResult {
|
||||
}
|
||||
|
||||
function joinProviderMessages(...messages: ReadonlyArray<string | undefined>): string | undefined {
|
||||
const parts = messages
|
||||
.map((message) => message?.trim())
|
||||
.filter((message): message is string => Boolean(message));
|
||||
const parts: Array<string> = [];
|
||||
for (const message of messages) {
|
||||
const trimmed = message?.trim();
|
||||
if (trimmed) {
|
||||
parts.push(trimmed);
|
||||
}
|
||||
}
|
||||
return parts.length > 0 ? parts.join(" ") : undefined;
|
||||
}
|
||||
|
||||
@@ -790,11 +795,13 @@ export function parseCursorCliConfigChannel(raw: string): string | undefined {
|
||||
}
|
||||
|
||||
function toTitleCaseWords(value: string): string {
|
||||
return value
|
||||
.split(/[\s_-]+/g)
|
||||
.filter((part) => part.length > 0)
|
||||
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
|
||||
.join(" ");
|
||||
const parts: Array<string> = [];
|
||||
for (const part of value.split(/[\s_-]+/g)) {
|
||||
if (part.length > 0) {
|
||||
parts.push(part.charAt(0).toUpperCase() + part.slice(1).toLowerCase());
|
||||
}
|
||||
}
|
||||
return parts.join(" ");
|
||||
}
|
||||
|
||||
function cursorSubscriptionLabel(subscriptionType: string | undefined): string | undefined {
|
||||
|
||||
@@ -14,6 +14,7 @@ import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Logger from "effect/Logger";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
@@ -24,6 +25,7 @@ const DEFAULT_MAX_FILES = 10;
|
||||
const DEFAULT_BATCH_WINDOW_MS = 200;
|
||||
const GLOBAL_THREAD_SEGMENT = "_global";
|
||||
const LOG_SCOPE = "provider-observability";
|
||||
const encodeUnknownJsonString = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
|
||||
export type EventNdjsonStream = "native" | "canonical" | "orchestration";
|
||||
|
||||
@@ -87,26 +89,13 @@ function resolveStreamLabel(stream: EventNdjsonStream): string {
|
||||
const toLogMessage = Effect.fn("toLogMessage")(function* (
|
||||
event: unknown,
|
||||
): Effect.fn.Return<string | undefined> {
|
||||
const serialized = yield* Effect.sync(() => {
|
||||
try {
|
||||
return { ok: true as const, value: JSON.stringify(event) };
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
});
|
||||
|
||||
if (!serialized.ok) {
|
||||
yield* logWarning("failed to serialize provider event log record", {
|
||||
error: serialized.error,
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (typeof serialized.value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return serialized.value;
|
||||
return yield* encodeUnknownJsonString(event).pipe(
|
||||
Effect.catch((error) =>
|
||||
logWarning("failed to serialize provider event log record", { error }).pipe(
|
||||
Effect.as(undefined),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const makeThreadWriter = Effect.fn("makeThreadWriter")(function* (input: {
|
||||
|
||||
@@ -37,7 +37,7 @@ import {
|
||||
|
||||
// Test-local service tag so the rest of the file can keep using `yield* OpenCodeAdapter`.
|
||||
class OpenCodeAdapter extends Context.Service<OpenCodeAdapter, OpenCodeAdapterShape>()(
|
||||
"test/OpenCodeAdapter",
|
||||
"t3/provider/Layers/OpenCodeAdapter.test/OpenCodeAdapter",
|
||||
) {}
|
||||
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
|
||||
|
||||
@@ -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,40 +134,14 @@ const toProcessError = (threadId: ThreadId, cause: unknown): ProviderAdapterProc
|
||||
cause,
|
||||
});
|
||||
|
||||
const buildEventBase = (input: {
|
||||
type EventBaseInput = {
|
||||
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();
|
||||
@@ -457,6 +431,7 @@ 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
|
||||
@@ -470,6 +445,40 @@ 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
|
||||
@@ -1142,7 +1151,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* Random.nextUUIDv4}`);
|
||||
const turnId = TurnId.make(`opencode-turn-${yield* randomUUIDv4}`);
|
||||
const modelSelection =
|
||||
input.modelSelection ??
|
||||
(context.session.model
|
||||
@@ -1357,12 +1366,15 @@ export function makeOpenCodeAdapter(
|
||||
}),
|
||||
).pipe(Effect.mapError(toRequestError));
|
||||
|
||||
const turns = (messages.data ?? [])
|
||||
.filter((entry) => entry.info.role === "assistant")
|
||||
.map((entry) => ({
|
||||
id: TurnId.make(entry.info.id),
|
||||
items: [entry.info, ...entry.parts],
|
||||
}));
|
||||
const turns: Array<OpenCodeTurnSnapshot> = [];
|
||||
for (const entry of messages.data ?? []) {
|
||||
if (entry.info.role === "assistant") {
|
||||
turns.push({
|
||||
id: TurnId.make(entry.info.id),
|
||||
items: [entry.info, ...entry.parts],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
threadId,
|
||||
|
||||
@@ -137,11 +137,13 @@ function formatOpenCodeProbeError(input: {
|
||||
}
|
||||
|
||||
function titleCaseSlug(value: string): string {
|
||||
return value
|
||||
.split(/[-_/]+/)
|
||||
.filter((segment) => segment.length > 0)
|
||||
.map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
|
||||
.join(" ");
|
||||
const segments: Array<string> = [];
|
||||
for (const segment of value.split(/[-_/]+/)) {
|
||||
if (segment.length > 0) {
|
||||
segments.push(segment.charAt(0).toUpperCase() + segment.slice(1));
|
||||
}
|
||||
}
|
||||
return segments.join(" ");
|
||||
}
|
||||
|
||||
function inferDefaultVariant(
|
||||
@@ -408,35 +410,25 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
|
||||
const inventoryExit = yield* Effect.exit(
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const server = yield* openCodeRuntime
|
||||
.connectToOpenCodeServer({
|
||||
binaryPath: openCodeSettings.binaryPath,
|
||||
serverUrl: openCodeSettings.serverUrl,
|
||||
environment,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
|
||||
),
|
||||
);
|
||||
return yield* openCodeRuntime
|
||||
.loadOpenCodeInventory(
|
||||
openCodeRuntime.createOpenCodeSdkClient({
|
||||
baseUrl: server.url,
|
||||
directory: cwd,
|
||||
...(isExternalServer && openCodeSettings.serverPassword
|
||||
? { serverPassword: openCodeSettings.serverPassword }
|
||||
: {}),
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
|
||||
),
|
||||
);
|
||||
}),
|
||||
const server = yield* openCodeRuntime.connectToOpenCodeServer({
|
||||
binaryPath: openCodeSettings.binaryPath,
|
||||
serverUrl: openCodeSettings.serverUrl,
|
||||
environment,
|
||||
});
|
||||
return yield* openCodeRuntime.loadOpenCodeInventory(
|
||||
openCodeRuntime.createOpenCodeSdkClient({
|
||||
baseUrl: server.url,
|
||||
directory: cwd,
|
||||
...(isExternalServer && openCodeSettings.serverPassword
|
||||
? { serverPassword: openCodeSettings.serverPassword }
|
||||
: {}),
|
||||
}),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (inventoryExit._tag === "Failure") {
|
||||
|
||||
@@ -50,7 +50,7 @@ export interface ProviderEventLoggersShape {
|
||||
export class ProviderEventLoggers extends Context.Service<
|
||||
ProviderEventLoggers,
|
||||
ProviderEventLoggersShape
|
||||
>()("t3/provider/ProviderEventLoggers") {}
|
||||
>()("t3/provider/Layers/ProviderEventLoggers") {}
|
||||
|
||||
/**
|
||||
* Constant value used by tests / boot layers that want to opt out of native
|
||||
|
||||
@@ -346,9 +346,7 @@ it.effect("ProviderServiceLive catches stopAll failures during shutdown", () =>
|
||||
const scope = yield* Scope.make();
|
||||
const runtimeServices = yield* Layer.build(providerLayer).pipe(Scope.provide(scope));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
yield* ProviderService;
|
||||
}).pipe(Effect.provide(runtimeServices));
|
||||
yield* ProviderService.pipe(Effect.provide(runtimeServices));
|
||||
const closeExit = yield* Scope.close(scope, Exit.void).pipe(Effect.exit);
|
||||
|
||||
assert.equal(Exit.isSuccess(closeExit), true);
|
||||
@@ -636,9 +634,7 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (
|
||||
Layer.provide(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
yield* ProviderService;
|
||||
}).pipe(Effect.provide(providerLayer));
|
||||
yield* ProviderService.pipe(Effect.provide(providerLayer));
|
||||
|
||||
const persistedProvider = yield* Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
|
||||
@@ -1,40 +1,13 @@
|
||||
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,
|
||||
@@ -45,35 +18,63 @@ function formatRequestLogPayload(event: AcpSessionRequestLogEvent) {
|
||||
};
|
||||
}
|
||||
|
||||
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"]>,
|
||||
}
|
||||
: {}),
|
||||
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"]>,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
};
|
||||
}
|
||||
});
|
||||
@@ -126,19 +126,20 @@ export function parseSessionModeState(
|
||||
if (!currentModeId) {
|
||||
return undefined;
|
||||
}
|
||||
const availableModes = modes.availableModes
|
||||
.map((mode) => {
|
||||
const id = mode.id.trim();
|
||||
const name = mode.name.trim();
|
||||
if (!id || !name) {
|
||||
return undefined;
|
||||
}
|
||||
const description = mode.description?.trim() || undefined;
|
||||
return description !== undefined
|
||||
const availableModes: Array<AcpSessionMode> = [];
|
||||
for (const mode of modes.availableModes) {
|
||||
const id = mode.id.trim();
|
||||
const name = mode.name.trim();
|
||||
if (!id || !name) {
|
||||
continue;
|
||||
}
|
||||
const description = mode.description?.trim() || undefined;
|
||||
availableModes.push(
|
||||
description !== undefined
|
||||
? ({ id, name, description } satisfies AcpSessionMode)
|
||||
: ({ id, name } satisfies AcpSessionMode);
|
||||
})
|
||||
.filter((mode): mode is AcpSessionMode => mode !== undefined);
|
||||
: ({ id, name } satisfies AcpSessionMode),
|
||||
);
|
||||
}
|
||||
if (availableModes.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
@@ -186,9 +187,15 @@ function normalizeCommandValue(value: unknown): string | undefined {
|
||||
if (!Array.isArray(value)) {
|
||||
return undefined;
|
||||
}
|
||||
const parts = value
|
||||
.map((entry) => (typeof entry === "string" && entry.trim().length > 0 ? entry.trim() : null))
|
||||
.filter((entry): entry is string => entry !== null);
|
||||
const parts: Array<string> = [];
|
||||
for (const entry of value) {
|
||||
if (typeof entry === "string") {
|
||||
const part = entry.trim();
|
||||
if (part.length > 0) {
|
||||
parts.push(part);
|
||||
}
|
||||
}
|
||||
}
|
||||
return parts.length > 0 ? parts.join(" ") : undefined;
|
||||
}
|
||||
|
||||
@@ -222,18 +229,20 @@ function extractTextContentFromToolCallContent(
|
||||
content: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined,
|
||||
): string | undefined {
|
||||
if (!content) return undefined;
|
||||
const chunks = content
|
||||
.map((entry) => {
|
||||
if (entry.type !== "content") {
|
||||
return undefined;
|
||||
}
|
||||
const nestedContent = entry.content;
|
||||
if (nestedContent.type !== "text") {
|
||||
return undefined;
|
||||
}
|
||||
return nestedContent.text.trim().length > 0 ? nestedContent.text.trim() : undefined;
|
||||
})
|
||||
.filter((entry): entry is string => entry !== undefined);
|
||||
const chunks: Array<string> = [];
|
||||
for (const entry of content) {
|
||||
if (entry.type !== "content") {
|
||||
continue;
|
||||
}
|
||||
const nestedContent = entry.content;
|
||||
if (nestedContent.type !== "text") {
|
||||
continue;
|
||||
}
|
||||
const text = nestedContent.text.trim();
|
||||
if (text.length > 0) {
|
||||
chunks.push(text);
|
||||
}
|
||||
}
|
||||
return chunks.length > 0 ? chunks.join("\n") : undefined;
|
||||
}
|
||||
|
||||
|
||||
@@ -544,7 +544,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
export class OpenCodeRuntime extends Context.Service<OpenCodeRuntime, OpenCodeRuntimeShape>()(
|
||||
"t3/provider/OpenCodeRuntime",
|
||||
"t3/provider/opencodeRuntime",
|
||||
) {}
|
||||
|
||||
export const OpenCodeRuntimeLive = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe(
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import { afterEach, describe, expect, it } from "@effect/vitest";
|
||||
import { afterEach, 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,10 +18,11 @@ import {
|
||||
} from "./providerMaintenance.ts";
|
||||
|
||||
const driver = (value: string) => ProviderDriverKind.make(value);
|
||||
const makeTempDir = Effect.fn("makeTempDir")(function* (name: string) {
|
||||
const id = yield* Random.nextUUIDv4;
|
||||
return path.join(os.tmpdir(), `${name}-${id}`);
|
||||
});
|
||||
const makeTempDir = (name: string) =>
|
||||
Crypto.Crypto.pipe(
|
||||
Effect.flatMap((crypto) => crypto.randomUUIDv4),
|
||||
Effect.map((id) => path.join(os.tmpdir(), `${name}-${id}`)),
|
||||
);
|
||||
const isNativeTestCommandPath =
|
||||
(expectedPathSegment: string) =>
|
||||
(commandPath: string): boolean =>
|
||||
@@ -68,7 +69,7 @@ afterEach(() => {
|
||||
clearLatestProviderVersionCacheForTests();
|
||||
});
|
||||
|
||||
describe("providerMaintenance", () => {
|
||||
it.layer(NodeServices.layer)("providerMaintenance", (it) => {
|
||||
it("marks providers with unknown current versions as unknown", () => {
|
||||
expect(
|
||||
createProviderVersionAdvisory({
|
||||
@@ -404,7 +405,7 @@ describe("providerMaintenance", () => {
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}).pipe(Effect.provide(NodeServices.layer));
|
||||
});
|
||||
|
||||
expect(capabilities).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
@@ -452,7 +453,7 @@ describe("providerMaintenance", () => {
|
||||
env: {
|
||||
PATH: "",
|
||||
},
|
||||
}).pipe(Effect.provide(NodeServices.layer));
|
||||
});
|
||||
|
||||
expect(capabilities).toEqual({
|
||||
provider: driver("packageTool"),
|
||||
|
||||
@@ -53,7 +53,7 @@ export interface ProviderMaintenanceRunnerShape {
|
||||
export class ProviderMaintenanceRunner extends Context.Service<
|
||||
ProviderMaintenanceRunner,
|
||||
ProviderMaintenanceRunnerShape
|
||||
>()("t3/provider/ProviderMaintenanceRunner") {}
|
||||
>()("t3/provider/providerMaintenanceRunner") {}
|
||||
|
||||
class ProviderMaintenanceCommandError extends Data.TaggedError("ProviderMaintenanceCommandError")<{
|
||||
readonly message: string;
|
||||
@@ -214,13 +214,15 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
|
||||
instanceId: ProviderInstanceId,
|
||||
): Effect.Effect<VerifiedProviderRefresh> =>
|
||||
providerRegistry.getProviders.pipe(
|
||||
Effect.map((providers) =>
|
||||
providers
|
||||
.filter(
|
||||
(candidate) => candidate.driver === provider && candidate.instanceId === instanceId,
|
||||
)
|
||||
.map((candidate) => candidate.instanceId),
|
||||
),
|
||||
Effect.map((providers) => {
|
||||
const instanceIds: Array<ProviderInstanceId> = [];
|
||||
for (const candidate of providers) {
|
||||
if (candidate.driver === provider && candidate.instanceId === instanceId) {
|
||||
instanceIds.push(candidate.instanceId);
|
||||
}
|
||||
}
|
||||
return instanceIds;
|
||||
}),
|
||||
Effect.flatMap((instanceIds) =>
|
||||
instanceIds.length === 0
|
||||
? providerRegistry.refreshInstance(instanceId)
|
||||
|
||||
+126
-221
@@ -40,6 +40,7 @@ import * as Path from "effect/Path";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import {
|
||||
Cookies,
|
||||
FetchHttpClient,
|
||||
HttpBody,
|
||||
HttpClient,
|
||||
@@ -780,13 +781,6 @@ const appendSessionCookieToWsUrl = (url: string, sessionCookieHeader: string) =>
|
||||
return isAbsoluteUrl ? next.toString() : `${next.pathname}${next.search}${next.hash}`;
|
||||
};
|
||||
|
||||
const getHttpServerUrl = (pathname = "") =>
|
||||
Effect.gen(function* () {
|
||||
const server = yield* HttpServer.HttpServer;
|
||||
const address = server.address as HttpServer.TcpAddress;
|
||||
return `http://127.0.0.1:${address.port}${pathname}`;
|
||||
});
|
||||
|
||||
const bootstrapBrowserSession = (
|
||||
credential = defaultDesktopBootstrapToken,
|
||||
options?: {
|
||||
@@ -794,20 +788,11 @@ const bootstrapBrowserSession = (
|
||||
},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const bootstrapUrl = yield* getHttpServerUrl("/api/auth/bootstrap");
|
||||
const response = yield* Effect.promise(() =>
|
||||
fetch(bootstrapUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
...options?.headers,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
credential,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const body = (yield* Effect.promise(() => response.json())) as {
|
||||
const response = yield* HttpClient.post("/api/auth/bootstrap", {
|
||||
headers: options?.headers,
|
||||
body: yield* HttpBody.json({ credential }),
|
||||
});
|
||||
const body = (yield* response.json) as {
|
||||
readonly authenticated: boolean;
|
||||
readonly sessionMethod: string;
|
||||
readonly expiresAt: string;
|
||||
@@ -815,7 +800,7 @@ const bootstrapBrowserSession = (
|
||||
return {
|
||||
response,
|
||||
body,
|
||||
cookie: response.headers.get("set-cookie"),
|
||||
cookie: Cookies.toSetCookieHeaders(response.cookies)[0] ?? null,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -826,20 +811,11 @@ const bootstrapBearerSession = (
|
||||
},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const bootstrapUrl = yield* getHttpServerUrl("/api/auth/bootstrap/bearer");
|
||||
const response = yield* Effect.promise(() =>
|
||||
fetch(bootstrapUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
...options?.headers,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
credential,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const body = (yield* Effect.promise(() => response.json())) as {
|
||||
const response = yield* HttpClient.post("/api/auth/bootstrap/bearer", {
|
||||
headers: options?.headers,
|
||||
body: yield* HttpBody.json({ credential }),
|
||||
});
|
||||
const body = (yield* response.json) as {
|
||||
readonly authenticated: boolean;
|
||||
readonly sessionMethod: string;
|
||||
readonly expiresAt: string;
|
||||
@@ -859,7 +835,7 @@ class AuthenticationGetterError extends Data.TaggedError("AuthenticationGetterEr
|
||||
const getAuthenticatedSessionCookieHeader = (credential = defaultDesktopBootstrapToken) =>
|
||||
Effect.gen(function* () {
|
||||
const { response, cookie } = yield* bootstrapBrowserSession(credential);
|
||||
if (!response.ok) {
|
||||
if (response.status !== 200) {
|
||||
return yield* new AuthenticationGetterError({
|
||||
message: `Expected bootstrap session response to succeed, got ${response.status}`,
|
||||
});
|
||||
@@ -877,7 +853,7 @@ const getAuthenticatedSessionCookieHeader = (credential = defaultDesktopBootstra
|
||||
const getAuthenticatedBearerSessionToken = (credential = defaultDesktopBootstrapToken) =>
|
||||
Effect.gen(function* () {
|
||||
const { response, body } = yield* bootstrapBearerSession(credential);
|
||||
if (!response.ok) {
|
||||
if (response.status !== 200) {
|
||||
return yield* new AuthenticationGetterError({
|
||||
message: `Expected bearer bootstrap response to succeed, got ${response.status}`,
|
||||
});
|
||||
@@ -908,14 +884,14 @@ const splitHeaderTokens = (value: string | null) =>
|
||||
.filter((token) => token.length > 0)
|
||||
.toSorted();
|
||||
|
||||
const assertBrowserApiCorsHeaders = (headers: Headers) => {
|
||||
assert.equal(headers.get("access-control-allow-origin"), "*");
|
||||
assert.deepEqual(splitHeaderTokens(headers.get("access-control-allow-methods")), [
|
||||
const assertBrowserApiCorsHeaders = (headers: Readonly<Record<string, string | undefined>>) => {
|
||||
assert.equal(headers["access-control-allow-origin"], "*");
|
||||
assert.deepEqual(splitHeaderTokens(headers["access-control-allow-methods"] ?? null), [
|
||||
"GET",
|
||||
"OPTIONS",
|
||||
"POST",
|
||||
]);
|
||||
assert.deepEqual(splitHeaderTokens(headers.get("access-control-allow-headers")), [
|
||||
assert.deepEqual(splitHeaderTokens(headers["access-control-allow-headers"] ?? null), [
|
||||
"authorization",
|
||||
"b3",
|
||||
"content-type",
|
||||
@@ -964,14 +940,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
config: { devUrl: new URL("http://127.0.0.1:5173") },
|
||||
});
|
||||
|
||||
const url = yield* getHttpServerUrl("/foo/bar?token=test-token");
|
||||
const response = yield* Effect.promise(() => fetch(url, { redirect: "manual" }));
|
||||
const response = yield* HttpClient.get("/foo/bar?token=test-token").pipe(
|
||||
Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }),
|
||||
);
|
||||
|
||||
assert.equal(response.status, 302);
|
||||
assert.equal(
|
||||
response.headers.get("location"),
|
||||
"http://127.0.0.1:5173/foo/bar?token=test-token",
|
||||
);
|
||||
assert.equal(response.headers.location, "http://127.0.0.1:5173/foo/bar?token=test-token");
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
@@ -1034,11 +1008,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const url = yield* getHttpServerUrl("/.well-known/t3/environment");
|
||||
const response = yield* Effect.promise(() => fetch(url));
|
||||
const body = (yield* Effect.promise(() =>
|
||||
response.json(),
|
||||
)) as typeof testEnvironmentDescriptor;
|
||||
const response = yield* HttpClient.get("/.well-known/t3/environment");
|
||||
const body = (yield* response.json) as typeof testEnvironmentDescriptor;
|
||||
|
||||
assert.equal(response.status, 200);
|
||||
assert.deepEqual(body, testEnvironmentDescriptor);
|
||||
@@ -1049,17 +1020,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const url = yield* getHttpServerUrl("/.well-known/t3/environment");
|
||||
const response = yield* Effect.promise(() =>
|
||||
fetch(url, {
|
||||
headers: {
|
||||
origin: crossOriginClientOrigin,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const body = (yield* Effect.promise(() =>
|
||||
response.json(),
|
||||
)) as typeof testEnvironmentDescriptor;
|
||||
const response = yield* HttpClient.get("/.well-known/t3/environment", {
|
||||
headers: {
|
||||
origin: crossOriginClientOrigin,
|
||||
},
|
||||
});
|
||||
const body = (yield* response.json) as typeof testEnvironmentDescriptor;
|
||||
|
||||
assert.equal(response.status, 200);
|
||||
assertBrowserApiCorsHeaders(response.headers);
|
||||
@@ -1071,9 +1037,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const url = yield* getHttpServerUrl("/api/auth/session");
|
||||
const response = yield* Effect.promise(() => fetch(url));
|
||||
const body = (yield* Effect.promise(() => response.json())) as {
|
||||
const response = yield* HttpClient.get("/api/auth/session");
|
||||
const body = (yield* response.json) as {
|
||||
readonly authenticated: boolean;
|
||||
readonly auth: {
|
||||
readonly policy: string;
|
||||
@@ -1111,15 +1076,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
assert.isUndefined((bootstrapBody as { readonly sessionToken?: string }).sessionToken);
|
||||
assert.isDefined(setCookie);
|
||||
|
||||
const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
|
||||
const sessionResponse = yield* Effect.promise(() =>
|
||||
fetch(sessionUrl, {
|
||||
headers: {
|
||||
cookie: setCookie?.split(";")[0] ?? "",
|
||||
},
|
||||
}),
|
||||
);
|
||||
const sessionBody = (yield* Effect.promise(() => sessionResponse.json())) as {
|
||||
const sessionResponse = yield* HttpClient.get("/api/auth/session", {
|
||||
headers: {
|
||||
cookie: setCookie?.split(";")[0] ?? "",
|
||||
},
|
||||
});
|
||||
const sessionBody = (yield* sessionResponse.json) as {
|
||||
readonly authenticated: boolean;
|
||||
readonly sessionMethod?: string;
|
||||
};
|
||||
@@ -1145,15 +1107,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
assert.equal(typeof bootstrapBody.sessionToken, "string");
|
||||
assert.isTrue((bootstrapBody.sessionToken?.length ?? 0) > 0);
|
||||
|
||||
const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
|
||||
const sessionResponse = yield* Effect.promise(() =>
|
||||
fetch(sessionUrl, {
|
||||
headers: {
|
||||
authorization: `Bearer ${bootstrapBody.sessionToken ?? ""}`,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const sessionBody = (yield* Effect.promise(() => sessionResponse.json())) as {
|
||||
const sessionResponse = yield* HttpClient.get("/api/auth/session", {
|
||||
headers: {
|
||||
authorization: `Bearer ${bootstrapBody.sessionToken ?? ""}`,
|
||||
},
|
||||
});
|
||||
const sessionBody = (yield* sessionResponse.json) as {
|
||||
readonly authenticated: boolean;
|
||||
readonly sessionMethod?: string;
|
||||
};
|
||||
@@ -1169,16 +1128,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const bearerToken = yield* getAuthenticatedBearerSessionToken();
|
||||
const wsTokenUrl = yield* getHttpServerUrl("/api/auth/ws-token");
|
||||
const wsTokenResponse = yield* Effect.promise(() =>
|
||||
fetch(wsTokenUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
authorization: `Bearer ${bearerToken}`,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const wsTokenBody = (yield* Effect.promise(() => wsTokenResponse.json())) as {
|
||||
const wsTokenResponse = yield* HttpClient.post("/api/auth/ws-token", {
|
||||
headers: {
|
||||
authorization: `Bearer ${bearerToken}`,
|
||||
},
|
||||
});
|
||||
const wsTokenBody = (yield* wsTokenResponse.json) as {
|
||||
readonly token: string;
|
||||
readonly expiresAt: string;
|
||||
};
|
||||
@@ -1207,16 +1162,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
assert.equal(bootstrapBody.authenticated, true);
|
||||
assert.equal(typeof bootstrapBody.sessionToken, "string");
|
||||
|
||||
const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
|
||||
const sessionResponse = yield* Effect.promise(() =>
|
||||
fetch(sessionUrl, {
|
||||
headers: {
|
||||
authorization: `Bearer ${bootstrapBody.sessionToken ?? ""}`,
|
||||
origin,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const sessionBody = (yield* Effect.promise(() => sessionResponse.json())) as {
|
||||
const sessionResponse = yield* HttpClient.get("/api/auth/session", {
|
||||
headers: {
|
||||
authorization: `Bearer ${bootstrapBody.sessionToken ?? ""}`,
|
||||
origin,
|
||||
},
|
||||
});
|
||||
const sessionBody = (yield* sessionResponse.json) as {
|
||||
readonly authenticated: boolean;
|
||||
readonly sessionMethod?: string;
|
||||
};
|
||||
@@ -1226,17 +1178,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
assert.equal(sessionBody.authenticated, true);
|
||||
assert.equal(sessionBody.sessionMethod, "bearer-session-token");
|
||||
|
||||
const wsTokenUrl = yield* getHttpServerUrl("/api/auth/ws-token");
|
||||
const wsTokenResponse = yield* Effect.promise(() =>
|
||||
fetch(wsTokenUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
authorization: `Bearer ${bootstrapBody.sessionToken ?? ""}`,
|
||||
origin,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const wsTokenBody = (yield* Effect.promise(() => wsTokenResponse.json())) as {
|
||||
const wsTokenResponse = yield* HttpClient.post("/api/auth/ws-token", {
|
||||
headers: {
|
||||
authorization: `Bearer ${bootstrapBody.sessionToken ?? ""}`,
|
||||
origin,
|
||||
},
|
||||
});
|
||||
const wsTokenBody = (yield* wsTokenResponse.json) as {
|
||||
readonly token: string;
|
||||
};
|
||||
|
||||
@@ -1252,17 +1200,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const wsTokenUrl = yield* getHttpServerUrl("/api/auth/ws-token");
|
||||
const response = yield* Effect.promise(() =>
|
||||
fetch(wsTokenUrl, {
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
origin: crossOriginClientOrigin,
|
||||
"access-control-request-method": "POST",
|
||||
"access-control-request-headers": "authorization",
|
||||
},
|
||||
}),
|
||||
);
|
||||
const response = yield* HttpClient.options("/api/auth/ws-token", {
|
||||
headers: {
|
||||
origin: crossOriginClientOrigin,
|
||||
"access-control-request-method": "POST",
|
||||
"access-control-request-headers": "authorization",
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(response.status, 204);
|
||||
assertBrowserApiCorsHeaders(response.headers);
|
||||
@@ -1273,16 +1217,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const wsTokenUrl = yield* getHttpServerUrl("/api/auth/ws-token");
|
||||
const response = yield* Effect.promise(() =>
|
||||
fetch(wsTokenUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
origin: crossOriginClientOrigin,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const body = (yield* Effect.promise(() => response.json())) as {
|
||||
const response = yield* HttpClient.post("/api/auth/ws-token", {
|
||||
headers: {
|
||||
origin: crossOriginClientOrigin,
|
||||
},
|
||||
});
|
||||
const body = (yield* response.json) as {
|
||||
readonly error?: string;
|
||||
};
|
||||
|
||||
@@ -1357,17 +1297,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
readonly credential: string;
|
||||
}>;
|
||||
|
||||
const revokeUrl = yield* getHttpServerUrl("/api/auth/pairing-links/revoke");
|
||||
const revokeResponse = yield* Effect.promise(() =>
|
||||
fetch(revokeUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
cookie: ownerCookie,
|
||||
"content-type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ id: createdBody.id }),
|
||||
}),
|
||||
);
|
||||
const revokeResponse = yield* HttpClient.post("/api/auth/pairing-links/revoke", {
|
||||
headers: {
|
||||
cookie: ownerCookie,
|
||||
},
|
||||
body: yield* HttpBody.json({ id: createdBody.id }),
|
||||
});
|
||||
const revokedBootstrap = yield* bootstrapBrowserSession(createdBody.credential);
|
||||
|
||||
assert.equal(createdResponse.status, 200);
|
||||
@@ -1420,20 +1355,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
});
|
||||
|
||||
const ownerCookie = yield* getAuthenticatedSessionCookieHeader();
|
||||
const pairingTokenUrl = yield* getHttpServerUrl("/api/auth/pairing-token");
|
||||
const ownerPairingResponse = yield* Effect.promise(() =>
|
||||
fetch(pairingTokenUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
cookie: ownerCookie,
|
||||
"content-type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
label: "Julius iPhone",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const ownerPairingBody = (yield* Effect.promise(() => ownerPairingResponse.json())) as {
|
||||
const ownerPairingResponse = yield* HttpClient.post("/api/auth/pairing-token", {
|
||||
headers: {
|
||||
cookie: ownerCookie,
|
||||
},
|
||||
body: yield* HttpBody.json({ label: "Julius iPhone" }),
|
||||
});
|
||||
const ownerPairingBody = (yield* ownerPairingResponse.json) as {
|
||||
readonly credential: string;
|
||||
readonly label?: string;
|
||||
};
|
||||
@@ -1448,17 +1376,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
assert.isDefined(pairedSessionCookie);
|
||||
|
||||
const pairedSessionCookieHeader = pairedSessionCookie ?? "";
|
||||
const listClientsUrl = yield* getHttpServerUrl("/api/auth/clients");
|
||||
const listBeforeResponse = yield* Effect.promise(() =>
|
||||
fetch(listClientsUrl, {
|
||||
headers: {
|
||||
cookie: ownerCookie,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const clientsBefore = (yield* Effect.promise(() =>
|
||||
listBeforeResponse.json(),
|
||||
)) as ReadonlyArray<{
|
||||
const listBeforeResponse = yield* HttpClient.get("/api/auth/clients", {
|
||||
headers: {
|
||||
cookie: ownerCookie,
|
||||
},
|
||||
});
|
||||
const clientsBefore = (yield* listBeforeResponse.json) as ReadonlyArray<{
|
||||
readonly sessionId: string;
|
||||
readonly current: boolean;
|
||||
readonly client: {
|
||||
@@ -1555,17 +1478,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
const pairedSessionId = clients.find((entry) => !entry.current)?.sessionId;
|
||||
assert.isDefined(pairedSessionId);
|
||||
|
||||
const revokeUrl = yield* getHttpServerUrl("/api/auth/clients/revoke");
|
||||
const revokeResponse = yield* Effect.promise(() =>
|
||||
fetch(revokeUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
cookie: ownerCookie,
|
||||
"content-type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ sessionId: pairedSessionId }),
|
||||
}),
|
||||
);
|
||||
const revokeResponse = yield* HttpClient.post("/api/auth/clients/revoke", {
|
||||
headers: {
|
||||
cookie: ownerCookie,
|
||||
},
|
||||
body: yield* HttpBody.json({ sessionId: pairedSessionId }),
|
||||
});
|
||||
const pairedClientPairingResponse = yield* HttpClient.post("/api/auth/pairing-token", {
|
||||
headers: {
|
||||
cookie: pairedSessionCookie,
|
||||
@@ -1665,16 +1583,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const bearerToken = yield* getAuthenticatedBearerSessionToken();
|
||||
const wsTokenUrl = yield* getHttpServerUrl("/api/auth/ws-token");
|
||||
const wsTokenResponse = yield* Effect.promise(() =>
|
||||
fetch(wsTokenUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
authorization: `Bearer ${bearerToken}`,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const wsTokenBody = (yield* Effect.promise(() => wsTokenResponse.json())) as {
|
||||
const wsTokenResponse = yield* HttpClient.post("/api/auth/ws-token", {
|
||||
headers: {
|
||||
authorization: `Bearer ${bearerToken}`,
|
||||
},
|
||||
});
|
||||
const wsTokenBody = (yield* wsTokenResponse.json) as {
|
||||
readonly token: string;
|
||||
};
|
||||
const wsUrl = `${yield* getWsServerUrl("/ws", { authenticated: false })}?wsToken=${encodeURIComponent(wsTokenBody.token)}`;
|
||||
@@ -1876,8 +1790,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
"content-type": "application/json",
|
||||
origin: "http://localhost:5733",
|
||||
},
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
body: HttpBody.text(JSON.stringify(payload), "application/json"),
|
||||
body: yield* HttpBody.json(payload),
|
||||
});
|
||||
|
||||
assert.equal(response.status, 204);
|
||||
@@ -1934,31 +1847,24 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
const url = yield* getHttpServerUrl("/api/observability/v1/traces");
|
||||
const response = yield* Effect.promise(() =>
|
||||
fetch(url, {
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
origin: "http://localhost:5733",
|
||||
"access-control-request-method": "POST",
|
||||
"access-control-request-headers": "content-type",
|
||||
},
|
||||
}),
|
||||
);
|
||||
const response = yield* HttpClient.options("/api/observability/v1/traces", {
|
||||
headers: {
|
||||
origin: "http://localhost:5733",
|
||||
"access-control-request-method": "POST",
|
||||
"access-control-request-headers": "content-type",
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(response.status, 204);
|
||||
assert.equal(response.headers.get("access-control-allow-origin"), "*");
|
||||
assert.deepEqual(splitHeaderTokens(response.headers.get("access-control-allow-methods")), [
|
||||
"GET",
|
||||
"OPTIONS",
|
||||
"POST",
|
||||
]);
|
||||
assert.deepEqual(splitHeaderTokens(response.headers.get("access-control-allow-headers")), [
|
||||
"authorization",
|
||||
"b3",
|
||||
"content-type",
|
||||
"traceparent",
|
||||
]);
|
||||
assert.equal(response.headers["access-control-allow-origin"], "*");
|
||||
assert.deepEqual(
|
||||
splitHeaderTokens(response.headers["access-control-allow-methods"] ?? null),
|
||||
["GET", "OPTIONS", "POST"],
|
||||
);
|
||||
assert.deepEqual(
|
||||
splitHeaderTokens(response.headers["access-control-allow-headers"] ?? null),
|
||||
["authorization", "b3", "content-type", "traceparent"],
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
@@ -1995,8 +1901,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
cookie: yield* getAuthenticatedSessionCookieHeader(),
|
||||
"content-type": "application/json",
|
||||
},
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
body: HttpBody.text(JSON.stringify(payload), "application/json"),
|
||||
body: yield* HttpBody.json(payload),
|
||||
});
|
||||
|
||||
assert.equal(response.status, 204);
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { DEFAULT_MODEL, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
@@ -222,3 +224,54 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
|
||||
assert.deepStrictEqual(yield* Ref.get(dispatchCalls), ["project.create", "thread.create"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const uuidError = PlatformError.systemError({
|
||||
_tag: "Unknown",
|
||||
module: "Crypto",
|
||||
method: "randomUUIDv4",
|
||||
description: "UUID generation unavailable",
|
||||
});
|
||||
const dispatchCalls = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
|
||||
const error = yield* resolveAutoBootstrapWelcomeTargets.pipe(
|
||||
Effect.provideService(ServerConfig, {
|
||||
cwd: "/tmp/startup-project",
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
} as never),
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () => Effect.die("unused"),
|
||||
getSnapshot: () => Effect.die("unused"),
|
||||
getShellSnapshot: () => Effect.die("unused"),
|
||||
getArchivedShellSnapshot: () => Effect.die("unused"),
|
||||
getSnapshotSequence: () => Effect.die("unused"),
|
||||
getCounts: () => Effect.die("unused"),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.die("unused"),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.die("unused"),
|
||||
getThreadDetailById: () => Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(OrchestrationEngineService, {
|
||||
readEvents: () => Stream.empty,
|
||||
dispatch: (command) =>
|
||||
Ref.update(dispatchCalls, (calls) => [...calls, command.type]).pipe(
|
||||
Effect.as({ sequence: 1 }),
|
||||
),
|
||||
streamDomainEvents: Stream.empty,
|
||||
} satisfies OrchestrationEngineShape),
|
||||
Effect.provideService(Crypto.Crypto, {
|
||||
...crypto,
|
||||
randomUUIDv4: Effect.fail(uuidError),
|
||||
}),
|
||||
Effect.flip,
|
||||
);
|
||||
|
||||
assert.strictEqual(error, uuidError);
|
||||
assert.deepStrictEqual(yield* Ref.get(dispatchCalls), []);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
@@ -19,6 +19,7 @@ import * as Ref from "effect/Ref";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
import { ServerConfig } from "./config.ts";
|
||||
@@ -170,6 +171,8 @@ export const resolveWelcomeBase = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const randomUUID = crypto.randomUUIDv4;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
@@ -188,12 +191,12 @@ export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
|
||||
|
||||
if (Option.isNone(existingProject)) {
|
||||
const createdAt = DateTime.formatIso(yield* DateTime.now);
|
||||
nextProjectId = ProjectId.make(crypto.randomUUID());
|
||||
nextProjectId = ProjectId.make(yield* randomUUID);
|
||||
const bootstrapProjectTitle = path.basename(serverConfig.cwd) || "project";
|
||||
nextProjectDefaultModelSelection = getAutoBootstrapDefaultModelSelection();
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
commandId: CommandId.make(yield* randomUUID),
|
||||
projectId: nextProjectId,
|
||||
title: bootstrapProjectTitle,
|
||||
workspaceRoot: serverConfig.cwd,
|
||||
@@ -210,10 +213,10 @@ export const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {
|
||||
yield* projectionReadModelQuery.getFirstActiveThreadIdByProjectId(nextProjectId);
|
||||
if (Option.isNone(existingThreadId)) {
|
||||
const createdAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const createdThreadId = ThreadId.make(crypto.randomUUID());
|
||||
const createdThreadId = ThreadId.make(yield* randomUUID);
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
commandId: CommandId.make(yield* randomUUID),
|
||||
threadId: createdThreadId,
|
||||
projectId: nextProjectId,
|
||||
title: "New thread",
|
||||
|
||||
@@ -16,6 +16,9 @@ import * as Schema from "effect/Schema";
|
||||
import { ServerConfig } from "./config.ts";
|
||||
import { ServerSettingsLive, ServerSettingsService } from "./serverSettings.ts";
|
||||
|
||||
const decodeSettingsPatch = Schema.decodeUnknownEffect(ServerSettingsPatch);
|
||||
const decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings);
|
||||
|
||||
const makeServerSettingsLayer = () =>
|
||||
ServerSettingsLive.pipe(
|
||||
Layer.provideMerge(
|
||||
@@ -29,15 +32,16 @@ const makeServerSettingsLayer = () =>
|
||||
|
||||
it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
it.effect("decodes nested settings patches", () =>
|
||||
Effect.sync(() => {
|
||||
const decodePatch = Schema.decodeUnknownSync(ServerSettingsPatch);
|
||||
|
||||
assert.deepEqual(decodePatch({ providers: { codex: { binaryPath: "/tmp/codex" } } }), {
|
||||
providers: { codex: { binaryPath: "/tmp/codex" } },
|
||||
});
|
||||
Effect.gen(function* () {
|
||||
assert.deepEqual(
|
||||
yield* decodeSettingsPatch({ providers: { codex: { binaryPath: "/tmp/codex" } } }),
|
||||
{
|
||||
providers: { codex: { binaryPath: "/tmp/codex" } },
|
||||
},
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
decodePatch({
|
||||
yield* decodeSettingsPatch({
|
||||
textGenerationModelSelection: {
|
||||
options: [{ id: "fastMode", value: false }],
|
||||
},
|
||||
@@ -54,10 +58,8 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
it.effect(
|
||||
"decodes legacy object-shaped textGenerationModelSelection.options from settings.json",
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
const decode = Schema.decodeUnknownSync(ServerSettings);
|
||||
|
||||
const decoded = decode({
|
||||
Effect.gen(function* () {
|
||||
const decoded = yield* decodeServerSettings({
|
||||
textGenerationModelSelection: {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
model: "gpt-5.4-mini",
|
||||
|
||||
@@ -94,7 +94,7 @@ export interface AzureDevOpsCliShape {
|
||||
}
|
||||
|
||||
export class AzureDevOpsCli extends Context.Service<AzureDevOpsCli, AzureDevOpsCliShape>()(
|
||||
"t3/source-control/AzureDevOpsCli",
|
||||
"t3/sourceControl/AzureDevOpsCli",
|
||||
) {}
|
||||
|
||||
function errorText(error: VcsError | unknown): string {
|
||||
@@ -208,10 +208,13 @@ function parseRepositorySpecifier(repository: string): {
|
||||
readonly project: string | null;
|
||||
readonly name: string;
|
||||
} {
|
||||
const parts = repository
|
||||
.split("/")
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part.length > 0);
|
||||
const parts: Array<string> = [];
|
||||
for (const part of repository.split("/")) {
|
||||
const trimmed = part.trim();
|
||||
if (trimmed.length > 0) {
|
||||
parts.push(trimmed);
|
||||
}
|
||||
}
|
||||
return {
|
||||
project: parts.length > 1 ? (parts.at(-2) ?? null) : null,
|
||||
name: parts.at(-1) ?? repository.trim(),
|
||||
|
||||
@@ -154,7 +154,7 @@ export interface BitbucketApiShape {
|
||||
}
|
||||
|
||||
export class BitbucketApi extends Context.Service<BitbucketApi, BitbucketApiShape>()(
|
||||
"t3/source-control/BitbucketApi",
|
||||
"t3/sourceControl/BitbucketApi",
|
||||
) {}
|
||||
|
||||
function nonEmpty(value: string | undefined): Option.Option<string> {
|
||||
|
||||
@@ -93,7 +93,7 @@ export interface GitHubCliShape {
|
||||
}
|
||||
|
||||
export class GitHubCli extends Context.Service<GitHubCli, GitHubCliShape>()(
|
||||
"t3/source-control/GitHubCli",
|
||||
"t3/sourceControl/GitHubCli",
|
||||
) {}
|
||||
|
||||
function errorText(error: VcsError | unknown): string {
|
||||
|
||||
@@ -97,7 +97,7 @@ export interface GitLabCliShape {
|
||||
}
|
||||
|
||||
export class GitLabCli extends Context.Service<GitLabCli, GitLabCliShape>()(
|
||||
"t3/source-control/GitLabCli",
|
||||
"t3/sourceControl/GitLabCli",
|
||||
) {}
|
||||
|
||||
function isVcsProcessSpawnError(error: unknown): boolean {
|
||||
@@ -247,10 +247,13 @@ function parseRepositoryPath(repository: string): {
|
||||
readonly namespacePath: string | null;
|
||||
readonly projectPath: string;
|
||||
} {
|
||||
const parts = repository
|
||||
.split("/")
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part.length > 0);
|
||||
const parts: Array<string> = [];
|
||||
for (const part of repository.split("/")) {
|
||||
const trimmed = part.trim();
|
||||
if (trimmed.length > 0) {
|
||||
parts.push(trimmed);
|
||||
}
|
||||
}
|
||||
const projectPath = parts.at(-1) ?? repository.trim();
|
||||
const namespacePath = parts.length > 1 ? parts.slice(0, -1).join("/") : null;
|
||||
return { namespacePath, projectPath };
|
||||
|
||||
@@ -64,7 +64,7 @@ export interface SourceControlDiscoveryShape {
|
||||
export class SourceControlDiscovery extends Context.Service<
|
||||
SourceControlDiscovery,
|
||||
SourceControlDiscoveryShape
|
||||
>()("t3/source-control/SourceControlDiscovery") {}
|
||||
>()("t3/sourceControl/SourceControlDiscovery") {}
|
||||
|
||||
export const layer = Layer.effect(
|
||||
SourceControlDiscovery,
|
||||
|
||||
Loaded 100 of 196 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user