Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
73f44ca959 | ||
|
|
8368242f60 | ||
|
|
cf07d06321 | ||
|
|
31268945f8 | ||
|
|
6b3050ee74 | ||
|
|
83f0cc9e31 |
No files matched your search
@@ -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)"
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -24,7 +24,7 @@ export interface DesktopBackendConfigurationShape {
|
||||
export class DesktopBackendConfiguration extends Context.Service<
|
||||
DesktopBackendConfiguration,
|
||||
DesktopBackendConfigurationShape
|
||||
>()("t3/desktop/BackendConfiguration") {}
|
||||
>()("@t3tools/desktop/backend/DesktopBackendConfiguration") {}
|
||||
|
||||
interface BackendObservabilitySettings {
|
||||
readonly otlpTracesUrl: Option.Option<string>;
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 } =
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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) =>
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
@@ -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") {}
|
||||
@@ -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> {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -2908,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",
|
||||
@@ -2917,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 } : {}),
|
||||
@@ -2924,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"]>,
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -97,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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -1366,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
|
||||
|
||||
@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -752,7 +753,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
]);
|
||||
yield* PubSub.publish(changes, refreshedProvider);
|
||||
|
||||
let cachedProvider = yield* readProviderStatusCache(filePath);
|
||||
let cachedProvider = Option.getOrUndefined(yield* readProviderStatusCache(filePath));
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 50 && cachedProvider?.checkedAt !== refreshedProvider.checkedAt;
|
||||
@@ -760,7 +761,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
) {
|
||||
yield* TestClock.adjust("10 millis");
|
||||
yield* Effect.yieldNow;
|
||||
cachedProvider = yield* readProviderStatusCache(filePath);
|
||||
cachedProvider = Option.getOrUndefined(yield* readProviderStatusCache(filePath));
|
||||
}
|
||||
|
||||
assert.deepStrictEqual(cachedProvider, {
|
||||
|
||||
@@ -34,6 +34,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Equal from "effect/Equal";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
@@ -237,25 +238,27 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
}
|
||||
return yield* readProviderStatusCache(filePath).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.flatMap((cachedProvider) => {
|
||||
if (cachedProvider === undefined) {
|
||||
return Effect.void.pipe(Effect.as(undefined as ServerProvider | undefined));
|
||||
}
|
||||
const correlation = {
|
||||
cachedProvider,
|
||||
fallbackProvider,
|
||||
} as const;
|
||||
if (!isCachedProviderCorrelated(correlation)) {
|
||||
return Effect.logWarning("provider status cache identity mismatch, ignoring", {
|
||||
path: filePath,
|
||||
instanceId: source.instanceId,
|
||||
cachedInstanceId: cachedProvider.instanceId ?? null,
|
||||
driver: source.driverKind,
|
||||
cachedDriver: cachedProvider.driver ?? null,
|
||||
}).pipe(Effect.as(undefined as ServerProvider | undefined));
|
||||
}
|
||||
return Effect.succeed(hydrateCachedProvider(correlation));
|
||||
}),
|
||||
Effect.flatMap((cachedProvider) =>
|
||||
Option.match(cachedProvider, {
|
||||
onNone: () => Effect.succeed(undefined as ServerProvider | undefined),
|
||||
onSome: (cachedProvider) => {
|
||||
const correlation = {
|
||||
cachedProvider,
|
||||
fallbackProvider,
|
||||
} as const;
|
||||
if (!isCachedProviderCorrelated(correlation)) {
|
||||
return Effect.logWarning("provider status cache identity mismatch, ignoring", {
|
||||
path: filePath,
|
||||
instanceId: source.instanceId,
|
||||
cachedInstanceId: cachedProvider.instanceId ?? null,
|
||||
driver: source.driverKind,
|
||||
cachedDriver: cachedProvider.driver ?? null,
|
||||
}).pipe(Effect.as(undefined as ServerProvider | undefined));
|
||||
}
|
||||
return Effect.succeed(hydrateCachedProvider(correlation));
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
{ concurrency: "unbounded" },
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -9,6 +9,7 @@ import { createModelCapabilities } from "@t3tools/shared/model";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import {
|
||||
hydrateCachedProvider,
|
||||
@@ -81,9 +82,44 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => {
|
||||
provider: openCodeProvider,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(yield* readProviderStatusCache(codexPath), codexProvider);
|
||||
assert.deepStrictEqual(yield* readProviderStatusCache(claudePath), claudeProvider);
|
||||
assert.deepStrictEqual(yield* readProviderStatusCache(openCodePath), openCodeProvider);
|
||||
assert.deepStrictEqual(
|
||||
Option.getOrNull(yield* readProviderStatusCache(codexPath)),
|
||||
codexProvider,
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
Option.getOrNull(yield* readProviderStatusCache(claudePath)),
|
||||
claudeProvider,
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
Option.getOrNull(yield* readProviderStatusCache(openCodePath)),
|
||||
openCodeProvider,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns none for missing, empty, or invalid cache files", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-provider-cache-invalid-" });
|
||||
const missingPath = yield* resolveProviderStatusCachePath({
|
||||
cacheDir: tempDir,
|
||||
instanceId: defaultInstanceIdForDriver(CODEX_DRIVER),
|
||||
});
|
||||
const emptyPath = yield* resolveProviderStatusCachePath({
|
||||
cacheDir: tempDir,
|
||||
instanceId: ProviderInstanceId.make("codex_empty"),
|
||||
});
|
||||
const invalidPath = yield* resolveProviderStatusCachePath({
|
||||
cacheDir: tempDir,
|
||||
instanceId: ProviderInstanceId.make("codex_invalid"),
|
||||
});
|
||||
|
||||
yield* fs.writeFileString(emptyPath, "\n");
|
||||
yield* fs.writeFileString(invalidPath, "{ invalid json");
|
||||
|
||||
assert.strictEqual(Option.isNone(yield* readProviderStatusCache(missingPath)), true);
|
||||
assert.strictEqual(Option.isNone(yield* readProviderStatusCache(emptyPath)), true);
|
||||
assert.strictEqual(Option.isNone(yield* readProviderStatusCache(invalidPath)), true);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -4,17 +4,19 @@ import {
|
||||
type ServerProvider,
|
||||
ServerProvider as ServerProviderSchema,
|
||||
} from "@t3tools/contracts";
|
||||
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { writeFileStringAtomically } from "../atomicWrite.ts";
|
||||
|
||||
const decodeProviderStatusCache = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(ServerProviderSchema),
|
||||
);
|
||||
const ProviderStatusCacheJson = fromJsonStringPretty(ServerProviderSchema);
|
||||
const decodeProviderStatusCache = Schema.decodeUnknownEffect(ProviderStatusCacheJson);
|
||||
const encodeProviderStatusCache = Schema.encodeEffect(ProviderStatusCacheJson);
|
||||
|
||||
const mergeProviderModels = (
|
||||
fallbackModels: ReadonlyArray<ServerProvider["models"][number]>,
|
||||
@@ -120,13 +122,13 @@ export const readProviderStatusCache = (filePath: string) =>
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const exists = yield* fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));
|
||||
if (!exists) {
|
||||
return undefined;
|
||||
return Option.none<ServerProvider>();
|
||||
}
|
||||
|
||||
const raw = yield* fs.readFileString(filePath).pipe(Effect.orElseSucceed(() => ""));
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return undefined;
|
||||
return Option.none<ServerProvider>();
|
||||
}
|
||||
|
||||
return yield* decodeProviderStatusCache(trimmed).pipe(
|
||||
@@ -135,8 +137,8 @@ export const readProviderStatusCache = (filePath: string) =>
|
||||
Effect.logWarning("failed to parse provider status cache, ignoring", {
|
||||
path: filePath,
|
||||
issues: Cause.pretty(cause),
|
||||
}).pipe(Effect.as(undefined)),
|
||||
onSuccess: Effect.succeed,
|
||||
}).pipe(Effect.as(Option.none<ServerProvider>())),
|
||||
onSuccess: (provider) => Effect.succeed(Option.some(provider)),
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -146,8 +148,12 @@ export const writeProviderStatusCache = (input: {
|
||||
readonly provider: ServerProvider;
|
||||
}) => {
|
||||
const { updateState: _updateState, ...cacheableProvider } = input.provider;
|
||||
return writeFileStringAtomically({
|
||||
filePath: input.filePath,
|
||||
contents: `${JSON.stringify(cacheableProvider, null, 2)}\n`,
|
||||
});
|
||||
return encodeProviderStatusCache(cacheableProvider).pipe(
|
||||
Effect.flatMap((contents) =>
|
||||
writeFileStringAtomically({
|
||||
filePath: input.filePath,
|
||||
contents: `${contents}\n`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
+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,
|
||||
|
||||
@@ -99,4 +99,4 @@ export interface SourceControlProviderShape {
|
||||
export class SourceControlProvider extends Context.Service<
|
||||
SourceControlProvider,
|
||||
SourceControlProviderShape
|
||||
>()("t3/source-control/SourceControlProvider") {}
|
||||
>()("t3/sourceControl/SourceControlProvider") {}
|
||||
@@ -96,15 +96,24 @@ export function unknownAuth(detail?: string): SourceControlProviderAuth {
|
||||
}
|
||||
|
||||
export function combinedAuthOutput(input: SourceControlAuthProbeInput): string {
|
||||
return [input.stdout, input.stderr].filter((entry) => entry.trim().length > 0).join("\n");
|
||||
const parts: string[] = [];
|
||||
for (const entry of [input.stdout, input.stderr]) {
|
||||
if (entry.trim().length > 0) {
|
||||
parts.push(entry);
|
||||
}
|
||||
}
|
||||
return parts.join("\n");
|
||||
}
|
||||
|
||||
function sanitizedAuthLines(text: string): ReadonlyArray<string> {
|
||||
return text
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0)
|
||||
.filter((entry) => !/^[-\s]*token(?:\s+scopes?)?:/iu.test(entry));
|
||||
const lines: string[] = [];
|
||||
for (const entry of text.split(/\r?\n/)) {
|
||||
const line = entry.trim();
|
||||
if (line.length === 0) continue;
|
||||
if (/^[-\s]*token(?:\s+scopes?)?:/iu.test(line)) continue;
|
||||
lines.push(line);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
export function firstSafeAuthLine(text: string): string | undefined {
|
||||
|
||||
@@ -51,7 +51,7 @@ export interface SourceControlProviderRegistryShape {
|
||||
export class SourceControlProviderRegistry extends Context.Service<
|
||||
SourceControlProviderRegistry,
|
||||
SourceControlProviderRegistryShape
|
||||
>()("t3/source-control/SourceControlProviderRegistry") {}
|
||||
>()("t3/sourceControl/SourceControlProviderRegistry") {}
|
||||
|
||||
function unsupportedProvider(
|
||||
kind: SourceControlProviderKind,
|
||||
@@ -92,18 +92,17 @@ function selectProviderContext(
|
||||
readonly url: string;
|
||||
}>,
|
||||
): SourceControlProvider.SourceControlProviderContext | null {
|
||||
const candidates = remotes
|
||||
.map((remote) => {
|
||||
const provider = detectSourceControlProviderFromRemoteUrl(remote.url);
|
||||
return provider
|
||||
? {
|
||||
provider,
|
||||
remoteName: remote.name,
|
||||
remoteUrl: remote.url,
|
||||
}
|
||||
: null;
|
||||
})
|
||||
.filter((value): value is SourceControlProvider.SourceControlProviderContext => value !== null);
|
||||
const candidates: Array<SourceControlProvider.SourceControlProviderContext> = [];
|
||||
for (const remote of remotes) {
|
||||
const provider = detectSourceControlProviderFromRemoteUrl(remote.url);
|
||||
if (provider) {
|
||||
candidates.push({
|
||||
provider,
|
||||
remoteName: remote.name,
|
||||
remoteUrl: remote.url,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
candidates.find((candidate) => candidate.remoteName === "origin") ??
|
||||
|
||||
@@ -39,7 +39,7 @@ export interface SourceControlRepositoryServiceShape {
|
||||
export class SourceControlRepositoryService extends Context.Service<
|
||||
SourceControlRepositoryService,
|
||||
SourceControlRepositoryServiceShape
|
||||
>()("t3/source-control/SourceControlRepositoryService") {}
|
||||
>()("t3/sourceControl/SourceControlRepositoryService") {}
|
||||
|
||||
function detailFromUnknown(cause: unknown): string {
|
||||
if (typeof cause === "object" && cause !== null) {
|
||||
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
} from "@t3tools/shared/model";
|
||||
import {
|
||||
getClaudeModelCapabilities,
|
||||
isClaudeUltracodeEffort,
|
||||
normalizeClaudeCliEffort,
|
||||
resolveClaudeApiModelId,
|
||||
resolveClaudeEffort,
|
||||
@@ -132,7 +133,8 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
const findDescriptor = (id: string) => descriptors.find((descriptor) => descriptor.id === id);
|
||||
const rawEffortSelection = getModelSelectionStringOptionValue(modelSelection, "effort");
|
||||
const resolvedEffort = resolveClaudeEffort(caps, rawEffortSelection);
|
||||
const cliEffort = normalizeClaudeCliEffort(resolvedEffort);
|
||||
const cliEffort = normalizeClaudeCliEffort(resolvedEffort, modelSelection.model);
|
||||
const ultracode = isClaudeUltracodeEffort(resolvedEffort);
|
||||
const thinkingDescriptor = findDescriptor("thinking");
|
||||
const fastModeDescriptor = findDescriptor("fastMode");
|
||||
const thinking =
|
||||
@@ -142,6 +144,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
const settings = {
|
||||
...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
...(ultracode ? { ultracode: true } : {}),
|
||||
};
|
||||
const settingsJson =
|
||||
Object.keys(settings).length > 0
|
||||
|
||||
@@ -76,24 +76,22 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
operation: string,
|
||||
prefix: string,
|
||||
content: string,
|
||||
): Effect.Effect<string, TextGenerationError, Scope.Scope> => {
|
||||
return Effect.gen(function* () {
|
||||
return yield* fileSystem
|
||||
.makeTempFileScoped({
|
||||
prefix: `t3code-${prefix}-${process.pid}-`,
|
||||
})
|
||||
.pipe(Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)));
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: `Failed to write temp file`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
): Effect.Effect<string, TextGenerationError, Scope.Scope> =>
|
||||
fileSystem
|
||||
.makeTempFileScoped({
|
||||
prefix: `t3code-${prefix}-${process.pid}-`,
|
||||
})
|
||||
.pipe(
|
||||
Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: `Failed to write temp file`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
||||
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
@@ -116,7 +116,7 @@ export interface TextGenerationShape {
|
||||
* TextGeneration - Service tag for commit and PR text generation.
|
||||
*/
|
||||
export class TextGeneration extends Context.Service<TextGeneration, TextGenerationShape>()(
|
||||
"t3/text-generation/TextGeneration",
|
||||
"t3/textGeneration/TextGeneration",
|
||||
) {}
|
||||
|
||||
type TextGenerationOp =
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Cache from "effect/Cache";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
@@ -1793,61 +1794,60 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
}
|
||||
}
|
||||
|
||||
const localBranches = localBranchResult.stdout
|
||||
.split("\n")
|
||||
.map(parseBranchLine)
|
||||
.filter((refName): refName is { name: string; current: boolean } => refName !== null)
|
||||
.map((refName) => ({
|
||||
name: refName.name,
|
||||
current: refName.current,
|
||||
isRemote: false,
|
||||
isDefault: refName.name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(refName.name) ?? null,
|
||||
}))
|
||||
.toSorted((a, b) => {
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
if (aPriority !== bPriority) return aPriority - bPriority;
|
||||
const localBranches = Arr.filterMap(localBranchResult.stdout.split("\n"), (line) => {
|
||||
const refName = parseBranchLine(line);
|
||||
return refName === null
|
||||
? Result.failVoid
|
||||
: Result.succeed({
|
||||
name: refName.name,
|
||||
current: refName.current,
|
||||
isRemote: false,
|
||||
isDefault: refName.name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(refName.name) ?? null,
|
||||
});
|
||||
}).toSorted((a, b) => {
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
if (aPriority !== bPriority) return aPriority - bPriority;
|
||||
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
const remoteBranches =
|
||||
remoteBranchResult.exitCode === 0
|
||||
? remoteBranchResult.stdout
|
||||
.split("\n")
|
||||
.map(parseBranchLine)
|
||||
.filter((refName): refName is { name: string; current: boolean } => refName !== null)
|
||||
.map((refName) => {
|
||||
const parsedRemoteRef = parseRemoteRefWithRemoteNames(refName.name, remoteNames);
|
||||
const remoteBranch: {
|
||||
name: string;
|
||||
current: boolean;
|
||||
isRemote: boolean;
|
||||
remoteName?: string;
|
||||
isDefault: boolean;
|
||||
worktreePath: string | null;
|
||||
} = {
|
||||
name: refName.name,
|
||||
current: false,
|
||||
isRemote: true,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
};
|
||||
if (parsedRemoteRef) {
|
||||
remoteBranch.remoteName = parsedRemoteRef.remoteName;
|
||||
}
|
||||
return remoteBranch;
|
||||
})
|
||||
.toSorted((a, b) => {
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
})
|
||||
? Arr.filterMap(remoteBranchResult.stdout.split("\n"), (line) => {
|
||||
const refName = parseBranchLine(line);
|
||||
if (refName === null) {
|
||||
return Result.failVoid;
|
||||
}
|
||||
const parsedRemoteRef = parseRemoteRefWithRemoteNames(refName.name, remoteNames);
|
||||
const remoteBranch: {
|
||||
name: string;
|
||||
current: boolean;
|
||||
isRemote: boolean;
|
||||
remoteName?: string;
|
||||
isDefault: boolean;
|
||||
worktreePath: string | null;
|
||||
} = {
|
||||
name: refName.name,
|
||||
current: false,
|
||||
isRemote: true,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
};
|
||||
if (parsedRemoteRef) {
|
||||
remoteBranch.remoteName = parsedRemoteRef.remoteName;
|
||||
}
|
||||
return Result.succeed(remoteBranch);
|
||||
}).toSorted((a, b) => {
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
})
|
||||
: [];
|
||||
|
||||
const refs = paginateBranches({
|
||||
@@ -2106,12 +2106,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
"--no-column",
|
||||
"--format=%(refname:short)",
|
||||
]).pipe(
|
||||
Effect.map((stdout) =>
|
||||
stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0),
|
||||
),
|
||||
Effect.map((stdout) => {
|
||||
const branchNames: Array<string> = [];
|
||||
for (const line of stdout.split("\n")) {
|
||||
const branchName = line.trim();
|
||||
if (branchName.length > 0) {
|
||||
branchNames.push(branchName);
|
||||
}
|
||||
}
|
||||
return branchNames;
|
||||
}),
|
||||
);
|
||||
|
||||
return GitVcsDriver.GitVcsDriver.of({
|
||||
|
||||
@@ -221,9 +221,13 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
return null;
|
||||
}
|
||||
|
||||
const listedPaths = [...listedFiles.paths]
|
||||
.map((entry) => toPosixPath(entry))
|
||||
.filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry));
|
||||
const listedPaths: Array<string> = [];
|
||||
for (const rawEntry of listedFiles.paths) {
|
||||
const entry = toPosixPath(rawEntry);
|
||||
if (entry.length > 0 && !isPathInIgnoredDirectory(entry)) {
|
||||
listedPaths.push(entry);
|
||||
}
|
||||
}
|
||||
const filePaths = yield* vcs.driver.filterIgnoredPaths(cwd, listedPaths).pipe(
|
||||
Effect.map((paths) => [...paths]),
|
||||
Effect.catch(() => filterVcsIgnoredPaths(cwd, listedPaths)),
|
||||
@@ -456,21 +460,23 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
|
||||
const showHidden = endsWithSeparator || prefix.startsWith(".");
|
||||
const lowerPrefix = prefix.toLowerCase();
|
||||
const entries: Array<{ readonly name: string; readonly fullPath: string }> = [];
|
||||
for (const dirent of dirents) {
|
||||
if (
|
||||
dirent.isDirectory() &&
|
||||
dirent.name.toLowerCase().startsWith(lowerPrefix) &&
|
||||
(showHidden || !dirent.name.startsWith("."))
|
||||
) {
|
||||
entries.push({
|
||||
name: dirent.name,
|
||||
fullPath: path.join(parentPath, dirent.name),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
parentPath,
|
||||
entries: dirents
|
||||
.filter(
|
||||
(dirent) =>
|
||||
dirent.isDirectory() &&
|
||||
dirent.name.toLowerCase().startsWith(lowerPrefix) &&
|
||||
(showHidden || !dirent.name.startsWith(".")),
|
||||
)
|
||||
.map((dirent) => ({
|
||||
name: dirent.name,
|
||||
fullPath: path.join(parentPath, dirent.name),
|
||||
}))
|
||||
.toSorted((left, right) => left.name.localeCompare(right.name)),
|
||||
entries: entries.toSorted((left, right) => left.name.localeCompare(right.name)),
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
+49
-32
@@ -1,4 +1,5 @@
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -160,6 +161,7 @@ function toAuthAccessStreamEvent(
|
||||
const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
WsRpcGroup.toLayer(
|
||||
Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const checkpointDiffQuery = yield* CheckpointDiffQuery;
|
||||
@@ -195,8 +197,21 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
const sessions = yield* SessionCredentialService;
|
||||
const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics;
|
||||
const processResourceMonitor = yield* ProcessResourceMonitor.ProcessResourceMonitor;
|
||||
const toDispatchCommandError = (cause: unknown, fallbackMessage: string) =>
|
||||
isOrchestrationDispatchCommandError(cause)
|
||||
? cause
|
||||
: new OrchestrationDispatchCommandError({
|
||||
message: cause instanceof Error ? cause.message : fallbackMessage,
|
||||
cause,
|
||||
});
|
||||
const randomUUID = crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
toDispatchCommandError(cause, "Failed to generate orchestration command identifier."),
|
||||
),
|
||||
);
|
||||
const serverEventId = randomUUID.pipe(Effect.map(EventId.make));
|
||||
const serverCommandId = (tag: string) =>
|
||||
CommandId.make(`server:${tag}:${crypto.randomUUID()}`);
|
||||
randomUUID.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));
|
||||
|
||||
const loadAuthAccessSnapshot = () =>
|
||||
Effect.all({
|
||||
@@ -212,29 +227,28 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
readonly payload: Record<string, unknown>;
|
||||
readonly tone: "info" | "error";
|
||||
}) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
Effect.all({
|
||||
commandId: serverCommandId("setup-script-activity"),
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: EventId.make(crypto.randomUUID()),
|
||||
tone: input.tone,
|
||||
kind: input.kind,
|
||||
summary: input.summary,
|
||||
payload: input.payload,
|
||||
turnId: null,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
|
||||
const toDispatchCommandError = (cause: unknown, fallbackMessage: string) =>
|
||||
isOrchestrationDispatchCommandError(cause)
|
||||
? cause
|
||||
: new OrchestrationDispatchCommandError({
|
||||
message: cause instanceof Error ? cause.message : fallbackMessage,
|
||||
cause,
|
||||
});
|
||||
activityId: serverEventId,
|
||||
}).pipe(
|
||||
Effect.flatMap(({ commandId, activityId }) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId,
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: activityId,
|
||||
tone: input.tone,
|
||||
kind: input.kind,
|
||||
summary: input.summary,
|
||||
payload: input.payload,
|
||||
turnId: null,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const toBootstrapDispatchCommandCauseError = (cause: Cause.Cause<unknown>) => {
|
||||
const error = Cause.squash(cause);
|
||||
@@ -370,13 +384,16 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
|
||||
const cleanupCreatedThread = () =>
|
||||
createdThread
|
||||
? orchestrationEngine
|
||||
.dispatch({
|
||||
type: "thread.delete",
|
||||
commandId: serverCommandId("bootstrap-thread-delete"),
|
||||
threadId: command.threadId,
|
||||
})
|
||||
.pipe(Effect.ignoreCause({ log: true }))
|
||||
? serverCommandId("bootstrap-thread-delete").pipe(
|
||||
Effect.flatMap((commandId) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.delete",
|
||||
commandId,
|
||||
threadId: command.threadId,
|
||||
}),
|
||||
),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
)
|
||||
: Effect.void;
|
||||
|
||||
const recordSetupScriptLaunchFailure = (input: {
|
||||
@@ -499,7 +516,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
if (bootstrap?.createThread) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: serverCommandId("bootstrap-thread-create"),
|
||||
commandId: yield* serverCommandId("bootstrap-thread-create"),
|
||||
threadId: command.threadId,
|
||||
projectId: bootstrap.createThread.projectId,
|
||||
title: bootstrap.createThread.title,
|
||||
@@ -523,7 +540,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
targetWorktreePath = worktree.worktree.path;
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: serverCommandId("bootstrap-thread-meta-update"),
|
||||
commandId: yield* serverCommandId("bootstrap-thread-meta-update"),
|
||||
threadId: command.threadId,
|
||||
branch: worktree.worktree.refName,
|
||||
worktreePath: targetWorktreePath,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"types": ["node", "bun"],
|
||||
"lib": ["ESNext", "esnext.disposable"]
|
||||
},
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"typecheck": "tsgo --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"test:browser": "vitest run --config vitest.browser.config.ts",
|
||||
"test:browser:install": "playwright install --with-deps chromium"
|
||||
@@ -43,7 +43,6 @@
|
||||
"zustand": "^5.0.11"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@rolldown/plugin-babel": "^0.2.0",
|
||||
"@tailwindcss/vite": "^4.0.0",
|
||||
"@tanstack/router-plugin": "^1.161.0",
|
||||
@@ -57,7 +56,6 @@
|
||||
"msw": "2.12.11",
|
||||
"playwright": "^1.58.2",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "catalog:",
|
||||
"vite": "^8.0.0",
|
||||
"vitest": "catalog:",
|
||||
"vitest-browser-react": "^2.0.5"
|
||||
|
||||
@@ -1408,8 +1408,9 @@ export default function ChatView(props: ChatViewProps) {
|
||||
if (previewUrls.length === 0) return;
|
||||
|
||||
const previousPreviewUrls = attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? [];
|
||||
const nextPreviewUrlSet = new Set(previewUrls);
|
||||
for (const previewUrl of previousPreviewUrls) {
|
||||
if (!previewUrls.includes(previewUrl)) {
|
||||
if (!nextPreviewUrlSet.has(previewUrl)) {
|
||||
revokeBlobPreviewUrl(previewUrl);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { type KeybindingCommand, type FilesystemBrowseEntry } from "@t3tools/contracts";
|
||||
import type { SidebarThreadSortOrder } from "@t3tools/contracts/settings";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Result from "effect/Result";
|
||||
import { type ReactNode } from "react";
|
||||
import { sortThreads } from "../lib/threadSort";
|
||||
import { formatRelativeTimeLabel } from "../timestampFormat";
|
||||
@@ -252,23 +254,18 @@ export function filterCommandPaletteGroups(input: {
|
||||
}
|
||||
|
||||
return searchableGroups.flatMap((group) => {
|
||||
const items = group.items
|
||||
.map((item, index) => {
|
||||
const haystack = normalizeSearchText(item.searchTerms.join(" "));
|
||||
if (!haystack.includes(normalizedQuery)) {
|
||||
return null;
|
||||
}
|
||||
const items = Arr.filterMap(group.items, (item, index) => {
|
||||
const haystack = normalizeSearchText(item.searchTerms.join(" "));
|
||||
if (!haystack.includes(normalizedQuery)) {
|
||||
return Result.failVoid;
|
||||
}
|
||||
|
||||
return {
|
||||
item,
|
||||
index,
|
||||
rank: rankCommandPaletteItemMatch(item, normalizedQuery),
|
||||
};
|
||||
})
|
||||
.filter(
|
||||
(entry): entry is { item: (typeof group.items)[number]; index: number; rank: number } =>
|
||||
entry !== null,
|
||||
)
|
||||
return Result.succeed({
|
||||
item,
|
||||
index,
|
||||
rank: rankCommandPaletteItemMatch(item, normalizedQuery),
|
||||
});
|
||||
})
|
||||
.toSorted((left, right) => right.rank - left.rank || left.index - right.index)
|
||||
.map((entry) => entry.item);
|
||||
|
||||
|
||||
@@ -261,12 +261,14 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
[selectedCheckpointTurnCount],
|
||||
);
|
||||
const conversationCheckpointTurnCount = useMemo(() => {
|
||||
const turnCounts = orderedTurnDiffSummaries
|
||||
.map(
|
||||
(summary) =>
|
||||
summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId],
|
||||
)
|
||||
.filter((value): value is number => typeof value === "number");
|
||||
const turnCounts: Array<number> = [];
|
||||
for (const summary of orderedTurnDiffSummaries) {
|
||||
const value =
|
||||
summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId];
|
||||
if (typeof value === "number") {
|
||||
turnCounts.push(value);
|
||||
}
|
||||
}
|
||||
if (turnCounts.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -300,7 +300,7 @@ export function resolveThreadRowClassName(input: {
|
||||
isSelected: boolean;
|
||||
}): string {
|
||||
const baseClassName =
|
||||
"h-7 w-full translate-x-0 cursor-pointer justify-start px-2 text-left select-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring";
|
||||
"h-6 w-full translate-x-0 cursor-pointer justify-start px-2 text-left select-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring sm:h-7";
|
||||
|
||||
if (input.isSelected && input.isActive) {
|
||||
return cn(
|
||||
|
||||
@@ -680,11 +680,11 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
|
||||
render={
|
||||
<span
|
||||
aria-label={threadEnvironmentLabel ?? "Remote"}
|
||||
className="inline-flex h-5 items-center justify-center"
|
||||
className="inline-flex items-center justify-center"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<CloudIcon className="block size-3 text-muted-foreground/60" />
|
||||
<CloudIcon className="size-3 text-muted-foreground/40" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">{threadEnvironmentLabel}</TooltipPopup>
|
||||
</Tooltip>
|
||||
@@ -809,7 +809,7 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
|
||||
return (
|
||||
<SidebarMenuSub
|
||||
ref={attachThreadListAutoAnimateRef}
|
||||
className="mx-1 my-0 w-full translate-x-0 gap-0.5 overflow-hidden px-1.5 py-0"
|
||||
className="mx-0.5 my-0 w-full translate-x-0 gap-0.5 overflow-hidden px-1 py-0 sm:mx-1 sm:px-1.5"
|
||||
>
|
||||
{shouldShowThreadPanel && showEmptyThreadState ? (
|
||||
<SidebarMenuSubItem className="w-full" data-thread-selection-safe>
|
||||
|
||||
@@ -1323,9 +1323,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
} catch {
|
||||
const currentImageIds = new Set(composerImages.map((image) => image.id));
|
||||
const fallbackPersistedAttachments = getPersistedAttachmentsForThread();
|
||||
const fallbackPersistedIds = fallbackPersistedAttachments
|
||||
.map((attachment) => attachment.id)
|
||||
.filter((id) => currentImageIds.has(id));
|
||||
const fallbackPersistedIds: Array<string> = [];
|
||||
for (const attachment of fallbackPersistedAttachments) {
|
||||
if (currentImageIds.has(attachment.id)) {
|
||||
fallbackPersistedIds.push(attachment.id);
|
||||
}
|
||||
}
|
||||
const fallbackPersistedIdSet = new Set(fallbackPersistedIds);
|
||||
const fallbackAttachments = fallbackPersistedAttachments.filter((attachment) =>
|
||||
fallbackPersistedIdSet.has(attachment.id),
|
||||
|
||||
@@ -89,17 +89,20 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="@container/header-actions flex min-w-0 flex-1 items-center gap-2">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden sm:gap-3">
|
||||
<div className="@container/header-actions flex min-w-0 flex-1 flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-2 overflow-hidden sm:flex-1 sm:flex-nowrap sm:gap-3">
|
||||
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
|
||||
<h2
|
||||
className="min-w-0 shrink truncate text-sm font-medium text-foreground"
|
||||
className="min-w-0 flex-1 basis-40 truncate text-sm font-medium text-foreground"
|
||||
title={activeThreadTitle}
|
||||
>
|
||||
{activeThreadTitle}
|
||||
</h2>
|
||||
{activeProjectName && (
|
||||
<Badge variant="outline" className="min-w-0 shrink overflow-hidden">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="min-w-0 max-w-full shrink overflow-hidden sm:max-w-56"
|
||||
>
|
||||
<span className="min-w-0 truncate">{activeProjectName}</span>
|
||||
</Badge>
|
||||
)}
|
||||
@@ -109,7 +112,7 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center justify-end gap-2 @3xl/header-actions:gap-3">
|
||||
<div className="flex min-w-0 flex-wrap items-center justify-start gap-2 sm:shrink-0 sm:justify-end @3xl/header-actions:gap-3">
|
||||
{activeProjectScripts && (
|
||||
<ProjectScriptsControl
|
||||
scripts={activeProjectScripts}
|
||||
|
||||
@@ -272,8 +272,13 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
// ignoring sidebar selection so account-scoped searches can find a
|
||||
// model before the user chooses a specific instance rail item.
|
||||
if (props.lockedProvider !== null) {
|
||||
return rankedMatches
|
||||
.filter((rankedModel) => matchesLockedProvider(rankedModel.model))
|
||||
const lockedProviderMatches: Array<(typeof rankedMatches)[number]> = [];
|
||||
for (const rankedModel of rankedMatches) {
|
||||
if (matchesLockedProvider(rankedModel.model)) {
|
||||
lockedProviderMatches.push(rankedModel);
|
||||
}
|
||||
}
|
||||
return lockedProviderMatches
|
||||
.toSorted((a, b) => {
|
||||
const scoreDelta = a.score - b.score;
|
||||
if (scoreDelta !== 0) {
|
||||
|
||||
@@ -146,7 +146,8 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray<Editor
|
||||
value: "file-manager",
|
||||
},
|
||||
];
|
||||
return baseOptions.filter((option) => availableEditors.includes(option.value));
|
||||
const availableEditorSet = new Set(availableEditors);
|
||||
return baseOptions.filter((option) => availableEditorSet.has(option.value));
|
||||
};
|
||||
|
||||
export const OpenInPicker = memo(function OpenInPicker({
|
||||
|
||||
Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user