TypeScript
refactor: errors are Schema.TaggedError, not Data.TaggedError or native Error (#31216)
Julius Marminge298cb24140fd
diff --git a/apps/desktop/src/ipc/methods/sshEnvironment.ts b/apps/desktop/src/ipc/methods/sshEnvironment.tsindex 15e04f71282..b368b5581d0 100644--- a/apps/desktop/src/ipc/methods/sshEnvironment.ts+++ b/apps/desktop/src/ipc/methods/sshEnvironment.ts@@ -26,7 +26,6 @@ import {} from "@t3tools/contracts";import { SshHttpBridgeError } from "@t3tools/ssh/errors";import { resolveLoopbackSshHttpBaseUrl } from "@t3tools/ssh/tunnel";-import * as Data from "effect/Data";import * as Effect from "effect/Effect";import * as Schema from "effect/Schema";@@ -35,10 +34,12 @@ import * as DesktopIpc from "../DesktopIpc.ts";import * as DesktopSshEnvironment from "../../ssh/DesktopSshEnvironment.ts";import * as DesktopSshPasswordPrompts from "../../ssh/DesktopSshPasswordPrompts.ts";-type DesktopSshEnvironmentRequestOperation =- | "fetch-environment-descriptor"- | "bootstrap-bearer-session"- | "fetch-session-state";+const DesktopSshEnvironmentRequestOperation = Schema.Literals([+ "fetch-environment-descriptor",+ "bootstrap-bearer-session",+ "fetch-session-state",+]);+type DesktopSshEnvironmentRequestOperation = typeof DesktopSshEnvironmentRequestOperation.Type;type DesktopSshEnvironmentRequestCause = RemoteEnvironmentAuthError | SshHttpBridgeError;@@ -47,12 +48,13 @@ const isEnvironmentInternalError = Schema.is(EnvironmentInternalError);const isEnvironmentOperationForbiddenError = Schema.is(EnvironmentOperationForbiddenError);const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError);const isEnvironmentScopeRequiredError = Schema.is(EnvironmentScopeRequiredError);+const isRemoteEnvironmentAuthUndeclaredStatusError = Schema.is(+ RemoteEnvironmentAuthUndeclaredStatusError,+);+const isSshHttpBridgeError = Schema.is(SshHttpBridgeError);function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | null {- if (- cause instanceof RemoteEnvironmentAuthUndeclaredStatusError ||- cause instanceof SshHttpBridgeError- ) {+ if (isRemoteEnvironmentAuthUndeclaredStatusError(cause) || isSshHttpBridgeError(cause)) {return cause.status ?? null;}if (isEnvironmentRequestInvalidError(cause)) {@@ -73,13 +75,14 @@ function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | nreturn null;}-export class DesktopSshEnvironmentRequestError extends Data.TaggedError(+export class DesktopSshEnvironmentRequestError extends Schema.TaggedError<DesktopSshEnvironmentRequestError>()("DesktopSshEnvironmentRequestError",-)<{- readonly operation: DesktopSshEnvironmentRequestOperation;- readonly cause: DesktopSshEnvironmentRequestCause;- readonly sshHttpStatus: number | null;-}> {+ {+ operation: DesktopSshEnvironmentRequestOperation,+ cause: Schema.Defect(),+ sshHttpStatus: Schema.NullOr(Schema.Number),+ },+) {// The web client matches "[ssh_http:500]" to explain version-skewed SSH pairing.override get message() {const prefix = this.sshHttpStatus === null ? "" : `[ssh_http:${this.sshHttpStatus}] `;diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.test.ts b/apps/desktop/src/snapShot/DesktopSnapShot.test.tsindex 721f130ef5e..59d658e1eed 100644--- a/apps/desktop/src/snapShot/DesktopSnapShot.test.ts+++ b/apps/desktop/src/snapShot/DesktopSnapShot.test.ts@@ -1872,7 +1872,9 @@ it.effect("capture fails closed while snapshots are disabled", () => {it.effect("points capture setup failures at SnapShot settings", () => {vi.stubEnv("XDG_SESSION_TYPE", "wayland");- linuxCaptureMock.mockRejectedValueOnce(new CaptureSetupRequiredError("Install the helper."));+ linuxCaptureMock.mockRejectedValueOnce(+ new CaptureSetupRequiredError({ state: "Install the helper." }),+ );return Effect.scoped(Effect.gen(function* () {const service = yield* DesktopSnapShot.make;diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.ts b/apps/desktop/src/snapShot/DesktopSnapShot.tsindex ae0c2f04121..53799e15779 100644--- a/apps/desktop/src/snapShot/DesktopSnapShot.ts+++ b/apps/desktop/src/snapShot/DesktopSnapShot.ts@@ -94,6 +94,8 @@ import {import * as HostProcess from "@t3tools/shared/HostProcess";import { readImageDimensions } from "@t3tools/shared/imageDimensions";+const isCaptureSetupRequiredError = Schema.is(CaptureSetupRequiredError);+const MAX_CAPTURE_WIDTH = 2_560;const MAX_CAPTURE_HEIGHT = 1_600;const SHORTCUT_COOLDOWN_NS = 200_000_000n;@@ -180,7 +182,7 @@ const shortcutFailure = (cause: unknown) => new SnapShotShortcutError({ cause })function captureFailure(cause: unknown, captureId?: string): DesktopSnapShotError {if (isDesktopSnapShotError(cause)) return cause;- const operation = cause instanceof CaptureSetupRequiredError ? "setup-required" : "capture";+ const operation = isCaptureSetupRequiredError(cause) ? "setup-required" : "capture";return new DesktopSnapShotError({ operation, captureId, cause });}diff --git a/apps/desktop/src/snapShot/HyprlandSnapShot.ts b/apps/desktop/src/snapShot/HyprlandSnapShot.tsindex a0b8b4181cd..c40f397809d 100644--- a/apps/desktop/src/snapShot/HyprlandSnapShot.ts+++ b/apps/desktop/src/snapShot/HyprlandSnapShot.ts@@ -171,11 +171,11 @@ export async function captureHyprlandWindow(let state = await setup.state();if (state.status === "update-required") {await setup.perform("install-hyprland-helper").catch((cause: unknown) => {- throw new CaptureSetupRequiredError(state.message, { cause });+ throw new CaptureSetupRequiredError({ state: state.message, cause });});state = await setup.state();}- if (state.status !== "ready") throw new CaptureSetupRequiredError(state.message);+ if (state.status !== "ready") throw new CaptureSetupRequiredError({ state: state.message });const executable = hyprlandCaptureExecutable(paths);const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-hyprland-capture-"));const cleanup = () => NodeFSP.rm(directory, { recursive: true, force: true });diff --git a/apps/desktop/src/snapShot/KdeSnapShot.ts b/apps/desktop/src/snapShot/KdeSnapShot.tsindex 2e5723f51aa..f141bd485d0 100644--- a/apps/desktop/src/snapShot/KdeSnapShot.ts+++ b/apps/desktop/src/snapShot/KdeSnapShot.ts@@ -215,7 +215,7 @@ export async function captureKdeWindow(options?: { readonly flash: boolean; readonly animate: boolean },): Promise<LinuxWindowSnapshot> {const state = await new KdeCaptureSetup(paths).state();- if (state.status !== "ready") throw new CaptureSetupRequiredError(state.message);+ if (state.status !== "ready") throw new CaptureSetupRequiredError({ state: state.message });const { executable } = kdeCapturePaths(paths);const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-kde-capture-"));let retained = false;diff --git a/apps/desktop/src/snapShot/linuxCaptureSession.ts b/apps/desktop/src/snapShot/linuxCaptureSession.tsindex 11bf3984223..e1f7c3601ef 100644--- a/apps/desktop/src/snapShot/linuxCaptureSession.ts+++ b/apps/desktop/src/snapShot/linuxCaptureSession.ts@@ -2,15 +2,19 @@import * as NodeFSP from "node:fs/promises";import * as NodeURL from "node:url";import type { SnapShotKeyChord } from "@t3tools/contracts";+import * as Schema from "effect/Schema";import { nativeImage } from "electron";// Keep dbus-next out of desktop detection and PNG reads in the main process.export const HYPRLAND_CAPTURE_ACTION = "capture-window";-export class CaptureSetupRequiredError extends Error {- constructor(state: string, options?: ErrorOptions) {- super(`${state} Open Settings → SnapShots to continue setup.`, options);+export class CaptureSetupRequiredError extends Schema.TaggedError<CaptureSetupRequiredError>()(+ "CaptureSetupRequiredError",+ { state: Schema.String, cause: Schema.optional(Schema.Defect()) },+) {+ override get message(): string {+ return `${this.state} Open Settings → SnapShots to continue setup.`;}}export const NIRI_CAPTURE_PATH = "/com/t3tools/SnapShot";diff --git a/apps/desktop/src/ssh/DesktopSshEnvironment.ts b/apps/desktop/src/ssh/DesktopSshEnvironment.tsindex 3a3e84e03a9..7b480b36fbd 100644--- a/apps/desktop/src/ssh/DesktopSshEnvironment.ts+++ b/apps/desktop/src/ssh/DesktopSshEnvironment.ts@@ -23,6 +23,7 @@ import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Path from "effect/Path";+import * as Schema from "effect/Schema";import * as HttpClient from "effect/http/HttpClient";import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";@@ -74,11 +75,13 @@ function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) {return discoverSshHosts(input ?? {});}+const isSshPasswordPromptError = Schema.is(SshPasswordPromptError);+export function isDesktopSshPasswordPromptCancellation(error: unknown,): error is SshPasswordPromptError {return (- error instanceof SshPasswordPromptError &&+ isSshPasswordPromptError(error) &&DesktopSshPasswordPrompts.isDesktopSshPasswordPromptCancellation(error.cause));}diff --git a/apps/mobile/src/components/FilePreviewModal.tsx b/apps/mobile/src/components/FilePreviewModal.tsxindex 0d6ddaa2f26..9093507581c 100644--- a/apps/mobile/src/components/FilePreviewModal.tsx+++ b/apps/mobile/src/components/FilePreviewModal.tsx@@ -1,3 +1,4 @@+import * as Schema from "effect/Schema";import * as Dialog from "./ui/Dialog";import { useContext, useEffect, useEffectEvent, useState } from "react";import { Platform } from "react-native";@@ -21,15 +22,17 @@ export type {ResolvedFilePreviewSource,} from "./FilePreviewModal.types";-class PreviewResolutionError extends Error {- constructor(- override readonly cause: unknown,- readonly fallbackMessage: string,- ) {- super(fallbackMessage, { cause });+class PreviewResolutionError extends Schema.TaggedError<PreviewResolutionError>()(+ "PreviewResolutionError",+ { cause: Schema.Defect(), fallbackMessage: Schema.String },+) {+ override get message(): string {+ return this.fallbackMessage;}}+const isPreviewResolutionError = Schema.is(PreviewResolutionError);+interface ResolvedPreviewUri {readonly uri: string;readonly dispose?: () => void;@@ -42,7 +45,10 @@ async function resolvePreviewUri(if ("uri" in item) return { uri: item.uri };if ("attachment" in item) {return loadLocalAttachmentPreview(item.attachment, signal).catch((error: unknown) => {- throw new PreviewResolutionError(error, "Attach the file again and retry.");+ throw new PreviewResolutionError({+ cause: error,+ fallbackMessage: "Attach the file again and retry.",+ });});}// Refresh expired URLs before handing them to Quick Look or ACTION_VIEW, which retain them.@@ -52,10 +58,11 @@ async function resolvePreviewUri(return value;}).catch((error: unknown) => {- throw new PreviewResolutionError(- error,- "Reconnect to this environment and try again. The file may have been moved or deleted.",- );+ throw new PreviewResolutionError({+ cause: error,+ fallbackMessage:+ "Reconnect to this environment and try again. The file may have been moved or deleted.",+ });});return { uri: url + (item.srcFragment ?? "") };}@@ -99,9 +106,9 @@ function ResolvedFilePreview(props: {if (progressiveGallery && index !== selectedIndex) return settle(index, null);controller.abort();onResolutionError(- error instanceof PreviewResolutionError+ isPreviewResolutionError(error)? error- : new PreviewResolutionError(error, "Try again."),+ : new PreviewResolutionError({ cause: error, fallbackMessage: "Try again." }),);},);diff --git a/apps/mobile/src/features/cloud/dpop.ts b/apps/mobile/src/features/cloud/dpop.tsindex b3eaf006f3d..b427861b1e3 100644--- a/apps/mobile/src/features/cloud/dpop.ts+++ b/apps/mobile/src/features/cloud/dpop.ts@@ -1,6 +1,5 @@import * as Digest from "effect/crypto/Digest";import * as SecureRandom from "effect/crypto/SecureRandom";-import * as Data from "effect/Data";import * as Effect from "effect/Effect";import * as Base64Url from "effect/encoding/Base64Url";import * as Hex from "effect/encoding/Hex";@@ -13,10 +12,10 @@ import { DpopProof } from "@t3tools/client-runtime/relay";import { DpopPublicJwk } from "@t3tools/shared/dpopCommon";import * as Layer from "effect/Layer";-export class CloudDpopError extends Data.TaggedError("CloudDpopError")<{- readonly message: string;- readonly cause?: unknown;-}> {}+export class CloudDpopError extends Schema.TaggedError<CloudDpopError>()("CloudDpopError", {+ message: Schema.String,+ cause: Schema.optional(Schema.Defect()),+}) {}function cloudDpopError(message: string) {return (cause: unknown) => new CloudDpopError({ message, cause });diff --git a/apps/mobile/src/features/cloud/linkEnvironment.ts b/apps/mobile/src/features/cloud/linkEnvironment.tsindex 3aef6925293..f072f5c96d8 100644--- a/apps/mobile/src/features/cloud/linkEnvironment.ts+++ b/apps/mobile/src/features/cloud/linkEnvironment.ts@@ -1,4 +1,3 @@-import * as Data from "effect/Data";import * as Effect from "effect/Effect";import * as Schema from "effect/Schema";import { HttpClient } from "effect/http";@@ -26,11 +25,14 @@ function readRelayUrl(): string | null {return resolveCloudPublicConfig().relay.url;}-export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{- readonly message: string;- readonly cause?: unknown;- readonly traceId?: string;-}> {}+export class CloudEnvironmentLinkError extends Schema.TaggedError<CloudEnvironmentLinkError>()(+ "CloudEnvironmentLinkError",+ {+ message: Schema.String,+ cause: Schema.optional(Schema.Defect()),+ traceId: Schema.optional(Schema.String),+ },+) {}const isEnvironmentCloudApiError = Schema.is(Schema.Union([diff --git a/apps/mobile/src/features/files/ZipArchiveView.tsx b/apps/mobile/src/features/files/ZipArchiveView.tsxindex d36506a70e6..66290e9d6c3 100644--- a/apps/mobile/src/features/files/ZipArchiveView.tsx+++ b/apps/mobile/src/features/files/ZipArchiveView.tsx@@ -12,6 +12,7 @@ import {hostPreviewMimeTypeFromExtension,} from "@t3tools/shared/filePreview";import { LegendList } from "@legendapp/list/react-native";+import * as Schema from "effect/Schema";import { fetch } from "expo/fetch";import { File } from "expo-file-system";import { useNavigation, usePreventRemove } from "@react-navigation/native";@@ -68,11 +69,12 @@ interface ZipArchive {readonly fileCount: number;}-interface ZipFailure {- readonly title: string;- readonly detail: string;- readonly retry: boolean;-}+const ZipFailure = Schema.Struct({+ title: Schema.String,+ detail: Schema.String,+ retry: Schema.Boolean,+});+type ZipFailure = typeof ZipFailure.Type;const SAVE_ZIP_HINT = "Save the ZIP to open it in another app.";const TOO_LARGE: ZipFailure = {@@ -91,12 +93,16 @@ const NETWORK: ZipFailure = {retry: true,};-class ZipFailureError extends Error {- constructor(readonly failure: ZipFailure) {- super(failure.title);+class ZipFailureError extends Schema.TaggedError<ZipFailureError>()("ZipFailureError", {+ failure: ZipFailure,+}) {+ override get message(): string {+ return this.failure.title;}}+const isZipFailureError = Schema.is(ZipFailureError);+function errorMessage(cause: unknown, fallback: string) {return cause instanceof Error ? cause.message : fallback;}@@ -113,7 +119,7 @@ async function readArchiveBody(const { value, done } = await reader.read();if (done) break;size += value.byteLength;- if (size > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE);+ if (size > ARCHIVE_MAX_BYTES) throw new ZipFailureError({ failure: TOO_LARGE });chunks.push(value);onProgress(size);}@@ -135,9 +141,11 @@ async function openArchive(bytes: ArrayBuffer): Promise<ZipArchive> {files = await boundedZip(bytes);} catch (cause) {throw new ZipFailureError({- title: "Couldn't browse this ZIP",- detail: `${errorMessage(cause, "It may be incomplete or damaged.")} ${SAVE_ZIP_HINT}`,- retry: false,+ failure: {+ title: "Couldn't browse this ZIP",+ detail: `${errorMessage(cause, "It may be incomplete or damaged.")} ${SAVE_ZIP_HINT}`,+ retry: false,+ },});}const entries = [...files].map(([path, file]): ZipEntry => {@@ -187,15 +195,15 @@ function useZipArchive(input: {// oxlint-disable-next-line react/set-state-in-effect -- A new archive load resets its progress.setState({ status: "loading", receivedBytes: 0, timeLeft: null });void (async () => {- if (sizeBytes > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE);+ if (sizeBytes > ARCHIVE_MAX_BYTES) throw new ZipFailureError({ failure: TOO_LARGE });if (isLocal) {const file = new File(uri);- if ((file.size ?? 0) > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE);+ if ((file.size ?? 0) > ARCHIVE_MAX_BYTES) throw new ZipFailureError({ failure: TOO_LARGE });return openArchive(await file.arrayBuffer());}const url = (await refresh()) ?? uri;const response = await fetch(url, { signal: abort.signal });- if (!response.ok || !response.body) throw new ZipFailureError(NETWORK);+ if (!response.ok || !response.body) throw new ZipFailureError({ failure: NETWORK });const bytes = await readArchiveBody(response.body, (receivedBytes) =>setState({status: "loading",@@ -217,7 +225,7 @@ function useZipArchive(input: {if (!abort.signal.aborted)setState({status: "failed",- failure: cause instanceof ZipFailureError ? cause.failure : NETWORK,+ failure: isZipFailureError(cause) ? cause.failure : NETWORK,});});return () => abort.abort();diff --git a/apps/mobile/src/features/files/sourceHighlightingState.ts b/apps/mobile/src/features/files/sourceHighlightingState.tsindex 2a2db842ec4..5dcc5eff505 100644--- a/apps/mobile/src/features/files/sourceHighlightingState.ts+++ b/apps/mobile/src/features/files/sourceHighlightingState.ts@@ -1,5 +1,6 @@import * as Data from "effect/Data";import * as Effect from "effect/Effect";+import * as Schema from "effect/Schema";import { Atom } from "effect/reactivity";import { resolveHighlightLanguage } from "../../lib/highlightLanguage";@@ -15,9 +16,10 @@ export interface SourceHighlightInput {class SourceHighlightCacheKey extends Data.Class<SourceHighlightInput> {}-class SourceHighlightError extends Data.TaggedError("SourceHighlightError")<{- readonly cause: unknown;-}> {}+class SourceHighlightError extends Schema.TaggedError<SourceHighlightError>()(+ "SourceHighlightError",+ { cause: Schema.Defect() },+) {}// Highlighting is synchronous, so a cold atom resolves on its first read. The// family keeps results for files the user moves between.diff --git a/apps/mobile/src/features/threads/McpAppWebView.tsx b/apps/mobile/src/features/threads/McpAppWebView.tsxindex 473177f7068..39c69ca0beb 100644--- a/apps/mobile/src/features/threads/McpAppWebView.tsx+++ b/apps/mobile/src/features/threads/McpAppWebView.tsx@@ -69,9 +69,10 @@ const commandFailure = (result: {readonly cause: Parameters<typeof squashAtomCommandFailure>[0]["cause"];}) => {const error = squashAtomCommandFailure(result);- return new McpAppHostRefusal(- error instanceof Error && error.message.trim() !== "" ? error.message : "Request failed.",- );+ return new McpAppHostRefusal({+ message:+ error instanceof Error && error.message.trim() !== "" ? error.message : "Request failed.",+ });};const confirm = (title: string, message: string, action: string) =>@@ -320,7 +321,8 @@ export function ThreadMcpApp(props: {const { environmentId, input } = scope();const info = await latest.current.toolInfo({ environmentId, input: { ...input, name } });if (info._tag !== "Success") throw commandFailure(info);- if (!info.value.callable) throw new McpAppHostRefusal("This app cannot call that tool.");+ if (!info.value.callable)+ throw new McpAppHostRefusal({ message: "This app cannot call that tool." });if (!info.value.readOnly &&!(await confirm(@@ -329,7 +331,7 @@ export function ThreadMcpApp(props: {"Allow",))) {- throw new McpAppHostRefusal("Declined by the user.");+ throw new McpAppHostRefusal({ message: "Declined by the user." });}const result = await latest.current.callTool({environmentId,@@ -350,15 +352,15 @@ export function ThreadMcpApp(props: {openLink: async (url) => {// WebViews cannot prove user activation; confirm links to prevent timer-driven navigation out of T3.if (!(await confirm(`Open a link from ${app.server}?`, url, "Open"))) {- throw new McpAppHostRefusal("Declined by the user.");+ throw new McpAppHostRefusal({ message: "Declined by the user." });}if (!(await tryOpenExternalUrl(url, "mcp-app"))) {- throw new McpAppHostRefusal("The link could not be opened.");+ throw new McpAppHostRefusal({ message: "The link could not be opened." });}},sendMessage: async (text) => {if (!(await confirm(`Send this message from ${app.server}?`, text, "Send"))) {- throw new McpAppHostRefusal("Declined by the user.");+ throw new McpAppHostRefusal({ message: "Declined by the user." });}await enqueueThreadOutboxMessage({environmentId: latest.current.props.environmentId,@@ -422,7 +424,7 @@ export function ThreadMcpApp(props: {downloadFile: async (files) => {const names = files.map((file) => file.name).join(", ");if (!(await confirm(`Save a file from ${app.server}?`, names, "Save"))) {- throw new McpAppHostRefusal("Declined by the user.");+ throw new McpAppHostRefusal({ message: "Declined by the user." });}for (const file of files) {let bytes: Uint8Array | undefined;@@ -441,16 +443,18 @@ export function ThreadMcpApp(props: {const declared = (content as { readonly mimeType?: unknown } | undefined)?.mimeType;if (typeof declared === "string") mimeType = declared;}- if (bytes === undefined) throw new McpAppHostRefusal(`${file.name} has no contents.`);+ if (bytes === undefined)+ throw new McpAppHostRefusal({ message: `${file.name} has no contents.` });if (bytes.byteLength > MAX_DOWNLOAD_BYTES) {- throw new McpAppHostRefusal(`${file.name} is too large to save.`);+ throw new McpAppHostRefusal({ message: `${file.name} is too large to save.` });}const shared = await shareGeneratedAttachment({bytes,attachment: { name: file.name, mimeType },signal: new AbortController().signal,});- if (!shared) throw new McpAppHostRefusal("Sharing is not available on this device.");+ if (!shared)+ throw new McpAppHostRefusal({ message: "Sharing is not available on this device." });}},onRequestTeardown: () => {diff --git a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsxindex 04005284750..d510bc536e2 100644--- a/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx+++ b/apps/mobile/src/features/threads/ThreadMarkdownImage.tsx@@ -1,8 +1,8 @@import { useAtomValue } from "@effect/atom-react";import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/assets";import type { AssetResource, EnvironmentId } from "@t3tools/contracts";-import * as Data from "effect/Data";import * as Effect from "effect/Effect";+import * as Schema from "effect/Schema";import { AsyncResult, Atom } from "effect/reactivity";import { Image } from "expo-image";import { createContext, useContext, useId, useState } from "react";@@ -33,7 +33,9 @@ export const MarkdownImageAvailableWidthContext = createContext(0);type ImageSize = { readonly width: number; readonly height: number };-class SvgLoadError extends Data.TaggedError("SvgLoadError")<{ readonly cause: unknown }> {}+class SvgLoadError extends Schema.TaggedError<SvgLoadError>()("SvgLoadError", {+ cause: Schema.Defect(),+}) {}async function readSvgXml(uri: string, signal: AbortSignal): Promise<string> {if (uri.startsWith("data:image/svg+xml")) {diff --git a/apps/mobile/src/native/voiceTranscription.android.ts b/apps/mobile/src/native/voiceTranscription.android.tsindex 13e233d0ccc..3749b6d2a97 100644--- a/apps/mobile/src/native/voiceTranscription.android.ts+++ b/apps/mobile/src/native/voiceTranscription.android.ts@@ -73,14 +73,15 @@ async function runOperation<T>(throwIfVoiceTranscriptionAborted(signal);const code =typeof error === "object" && error !== null && "code" in error ? error.code : undefined;- throw new VoiceTranscriptionError(- code === "unavailable" || code === "unsupported-locale" ? code : fallbackCode,- (typeof code === "string" ? nativeErrorMessages[code] : undefined) ??+ throw new VoiceTranscriptionError({+ code: code === "unavailable" || code === "unsupported-locale" ? code : fallbackCode,+ message:+ (typeof code === "string" ? nativeErrorMessages[code] : undefined) ??(fallbackCode === "preparation-failed"? "Voice transcription could not prepare this language. Check Google speech services and try again.": "Voice transcription failed."),- { cause: error },- );+ cause: error,+ });} finally {signal.removeEventListener("abort", abort);await cancellation;diff --git a/apps/mobile/src/native/voiceTranscription.ios.ts b/apps/mobile/src/native/voiceTranscription.ios.tsindex 9f955664510..5fc6c9a0b8a 100644--- a/apps/mobile/src/native/voiceTranscription.ios.ts+++ b/apps/mobile/src/native/voiceTranscription.ios.ts@@ -1,3 +1,4 @@+import * as Schema from "effect/Schema";import AppleTranscription from "@react-native-ai/apple/src/NativeAppleTranscription";import { File } from "expo-file-system";@@ -9,6 +10,8 @@ import {type VoiceTranscriptionOptions,} from "@t3tools/client-runtime/voice-input";+const isVoiceTranscriptionError = Schema.is(VoiceTranscriptionError);+function getDeviceLocale(): string {return Intl.DateTimeFormat().resolvedOptions().locale;}@@ -18,11 +21,11 @@ function wrapError(message: string,cause: unknown,): VoiceTranscriptionError {- if (cause instanceof VoiceTranscriptionError) {+ if (isVoiceTranscriptionError(cause)) {return cause;}- return new VoiceTranscriptionError(code, message, { cause });+ return new VoiceTranscriptionError({ code, message, cause });}function getNativeErrorCode(error: unknown): string | undefined {@@ -45,10 +48,10 @@ async function prepareVoiceTranscription(): Promise<PreparedVoiceTranscription> {throwIfVoiceTranscriptionAborted(signal);if (!AppleTranscription.isAvailable(locale)) {- throw new VoiceTranscriptionError(- "unavailable",- "Voice transcription requires a supported device with iOS 26 or later.",- );+ throw new VoiceTranscriptionError({+ code: "unavailable",+ message: "Voice transcription requires a supported device with iOS 26 or later.",+ });}try {@@ -61,11 +64,11 @@ async function prepareVoiceTranscription(} catch (error) {throwIfVoiceTranscriptionAborted(signal);if (getNativeErrorCode(error) === "AppleTranscriptionUnsupportedLocale") {- throw new VoiceTranscriptionError(- "unsupported-locale",- "Voice transcription does not support this device language.",- { cause: error },- );+ throw new VoiceTranscriptionError({+ code: "unsupported-locale",+ message: "Voice transcription does not support this device language.",+ cause: error,+ });}throw wrapError(diff --git a/apps/server/src/device/DeviceService.ts b/apps/server/src/device/DeviceService.tsindex 663eaeaf726..c860f652c4f 100644--- a/apps/server/src/device/DeviceService.ts+++ b/apps/server/src/device/DeviceService.ts@@ -81,11 +81,13 @@ import * as LocalDeviceHost from "./LocalDeviceHost.ts";export const DEVICE_HUB_ROUTE_PREFIX = "/api/device-hub";+const isSshCommandError = Schema.is(SshCommandError);+const sshProbeFailureMessage = (error: DeviceHost.DeviceHostError): string => {const windows = SshDeviceHost.isSshWindowsHostError(error.cause) ? error.cause : null;const cause = windows ? windows.cause : error.cause;if (- !(cause instanceof SshCommandError) ||+ !isSshCommandError(cause) ||cause.exitCode === null ||cause.exitCode < 1 ||(cause.exitCode > 254 && cause.exitCode !== 9009)diff --git a/apps/server/src/device/SshDeviceHost.ts b/apps/server/src/device/SshDeviceHost.tsindex 8d17d4d3f3a..2dd9b21f290 100644--- a/apps/server/src/device/SshDeviceHost.ts+++ b/apps/server/src/device/SshDeviceHost.ts@@ -90,6 +90,8 @@ const bootstrap = (),);+const isSshCommandError = Schema.is(SshCommandError);+// cmd expands only %OS% and PowerShell only $env:OS; POSIX shells expand neither to Windows_NT.const explainWindowsHost = Effect.fn("SshDeviceHost.explainWindowsHost")(function* (config: SshDeviceHostConfig,@@ -98,7 +100,7 @@ const explainWindowsHost = Effect.fn("SshDeviceHost.explainWindowsHost")(functioconst cause = error.cause;// Windows ssh.exe preserves full remote exit statuses such as 9009.if (- !(cause instanceof SshCommandError) ||+ !isSshCommandError(cause) ||cause.exitCode === null ||cause.exitCode < 1 ||(cause.exitCode > 254 && cause.exitCode !== 9009)diff --git a/apps/server/src/http.ts b/apps/server/src/http.tsindex d1f7ab740e2..14270354047 100644--- a/apps/server/src/http.ts+++ b/apps/server/src/http.ts@@ -8,7 +8,6 @@ import { isDevProxiedPath } from "@t3tools/shared/devProxy";import { injectMcpAppCookieBootstrap, injectMcpAppThemeBootstrap } from "@t3tools/shared/mcpApp";import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";import * as ByteSize from "effect/ByteSize";-import * as Data from "effect/Data";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";@@ -327,9 +326,10 @@ export const layerServerEnvironmentHttpApi = HttpApiBuilder.group(}),);-class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{- readonly cause: unknown;-}> {}+class DecodeOtlpTraceRecordsError extends Schema.TaggedError<DecodeOtlpTraceRecordsError>()(+ "DecodeOtlpTraceRecordsError",+ { cause: Schema.Defect() },+) {}// Tracing once-per-second renderer exports would create more spans than it forwards.export const layerOtlpTracesProxyRoute = HttpRouter.add(diff --git a/apps/server/src/mcp/AcpMcpStdioBridge.ts b/apps/server/src/mcp/AcpMcpStdioBridge.tsindex d84873082c6..4f12497be5d 100644--- a/apps/server/src/mcp/AcpMcpStdioBridge.ts+++ b/apps/server/src/mcp/AcpMcpStdioBridge.ts@@ -5,22 +5,28 @@ import * as NodeReadline from "node:readline";import * as Cause from "effect/Cause";import * as Effect from "effect/Effect";import * as Option from "effect/Option";-import * as Schema from "effect/Schema";import * as Fiber from "effect/Fiber";+import * as Schema from "effect/Schema";import * as Scope from "effect/Scope";import * as Stream from "effect/Stream";import { discardResponseBody, responsePayloads } from "@t3tools/shared/mcpResponsePayloads";/** ACP mandates stdio MCP support; HTTP/SSE support varies. */-export class AcpMcpBridgeError extends Error {- readonly _tag = "AcpMcpBridgeError";-}+export class AcpMcpBridgeError extends Schema.TaggedError<AcpMcpBridgeError>()(+ "AcpMcpBridgeError",+ { message: Schema.String, cause: Schema.optional(Schema.Defect()) },+) {}++const isAcpMcpBridgeError = Schema.is(AcpMcpBridgeError);const bridgeError = (cause: unknown): AcpMcpBridgeError =>- cause instanceof AcpMcpBridgeError+ isAcpMcpBridgeError(cause)? cause- : new AcpMcpBridgeError(cause instanceof Error ? cause.message : String(cause), { cause });+ : new AcpMcpBridgeError({+ message: cause instanceof Error ? cause.message : String(cause),+ cause,+ });const decodeJsonLine = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));@@ -104,9 +110,9 @@ export const mcpToolSession = (sessionId = response.headers.get("mcp-session-id") ?? sessionId;if (!response.ok) {yield* discardResponseBody(response);- return yield* Effect.fail(- new AcpMcpBridgeError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`),- );+ return yield* new AcpMcpBridgeError({+ message: `T3 Code MCP endpoint responded with HTTP ${response.status}.`,+ });}const payloads = yield* Stream.runCollect(responsePayloads(response, bridgeError));for (const payload of payloads) {@@ -123,11 +129,9 @@ export const mcpToolSession = (const responses = yield* send({ jsonrpc: "2.0", id, method, params });const envelope = asEnvelope(responses.find((entry) => asEnvelope(entry)?.id === id));if (envelope === null || envelope.error !== undefined) {- return yield* Effect.fail(- new AcpMcpBridgeError(- `T3 Code MCP ${method} failed${envelope?.error === undefined ? "." : `: ${JSON.stringify(envelope.error)}`}`,- ),- );+ return yield* new AcpMcpBridgeError({+ message: `T3 Code MCP ${method} failed${envelope?.error === undefined ? "." : `: ${JSON.stringify(envelope.error)}`}`,+ });}return envelope;});diff --git a/apps/server/src/orchestration-v2/http.ts b/apps/server/src/orchestration-v2/http.tsindex 5415998619c..3bba05f7db6 100644--- a/apps/server/src/orchestration-v2/http.ts+++ b/apps/server/src/orchestration-v2/http.ts@@ -35,6 +35,8 @@ import { loadSubscriberShellSnapshot } from "./ShellStream.ts";import { boundedSnapshotResponseFields } from "./ThreadStream.ts";import { projectThreadProjectionForWire } from "./WireProjection.ts";+const isInvalidThreadHistoryCursorError = Schema.is(InvalidThreadHistoryCursorError);+const isThreadTranscriptTooLargeError = Schema.is(ThreadManagementService.ThreadTranscriptTooLargeError,);@@ -249,7 +251,7 @@ export const layer = HttpApiBuilder.group(const decoded = Result.try(() => decodeThreadHistoryCursor(args.query.cursor));if (Result.isFailure(decoded)) {const cause = decoded.failure;- if (cause instanceof InvalidThreadHistoryCursorError)+ if (isInvalidThreadHistoryCursorError(cause))return yield* failEnvironmentInvalidRequest("invalid_history_cursor");return yield* failEnvironmentInternal("orchestration_thread_history_failed", cause);}diff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.tsindex d226d21e324..abfaf0ade69 100644--- a/apps/server/src/orchestration-v2/threadHistoryPaging.ts+++ b/apps/server/src/orchestration-v2/threadHistoryPaging.ts@@ -5,6 +5,7 @@ import type {ThreadId,TurnItemId,} from "@t3tools/contracts";+import * as Schema from "effect/Schema";/*** Every window stops at the byte budget. A window that holds a user turn also@@ -84,11 +85,12 @@ export type BoundedProjectionResult = {readonly latestLocalTurnOrdinal: number | null;};-export class InvalidThreadHistoryCursorError extends Error {- readonly _tag = "InvalidThreadHistoryCursorError";- constructor(message = "Invalid thread history cursor.") {- super(message);- this.name = "InvalidThreadHistoryCursorError";+export class InvalidThreadHistoryCursorError extends Schema.TaggedError<InvalidThreadHistoryCursorError>()(+ "InvalidThreadHistoryCursorError",+ {},+) {+ override get message(): string {+ return "Invalid thread history cursor.";}}diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.tsindex 913f6dc6394..6b92e33ce96 100644--- a/apps/server/src/preview/ServerBrowser.ts+++ b/apps/server/src/preview/ServerBrowser.ts@@ -1223,22 +1223,23 @@ const make = Effect.gen(function* () {const uploadFiles = async (tab: ServerTab, input: PreviewAutomationUploadInput) => {const relative = input.paths.find((path) => !NodePath.isAbsolute(path));if (relative !== undefined)- throw new ServerBrowserPage.ServerBrowserOperationError(- "PreviewAutomationExecutionError",- `Upload paths must be absolute: ${relative}`,- );+ throw new ServerBrowserPage.ServerBrowserOperationError({+ tag: "PreviewAutomationExecutionError",+ message: `Upload paths must be absolute: ${relative}`,+ });if (await ServerBrowserPage.setInputFiles(tab.page, input)) return undefined;const open = tab.fileChooser;if (!open)- throw new ServerBrowserPage.ServerBrowserOperationError(- "PreviewAutomationExecutionError",- "No file picker is open. Click the page's upload control first, or pass the file input's locator.",- );+ throw new ServerBrowserPage.ServerBrowserOperationError({+ tag: "PreviewAutomationExecutionError",+ message:+ "No file picker is open. Click the page's upload control first, or pass the file input's locator.",+ });if (input.paths.length > 1 && !open.chooser.isMultiple())- throw new ServerBrowserPage.ServerBrowserOperationError(- "PreviewAutomationExecutionError",- "This file picker accepts one file.",- );+ throw new ServerBrowserPage.ServerBrowserOperationError({+ tag: "PreviewAutomationExecutionError",+ message: "This file picker accepts one file.",+ });if (input.paths.length > 0)await open.chooser.setFiles([...input.paths], {timeout: input.timeoutMs ?? NAVIGATION_TIMEOUT_MS,@@ -1418,10 +1419,10 @@ const make = Effect.gen(function* () {const assertTabCapacity = (agentSessionId: string) => {if (atTabLimit(agentSessionId))- throw new BrowserControlInterrupted(- `Too many server browser tabs are open (${AGENT_TAB_LIMIT} per agent session, ${SERVER_TAB_LIMIT} per server). Close one with t3_preview_close or reuse one from preview_status tabs.`,- "tabLimit",- );+ throw new BrowserControlInterrupted({+ message: `Too many server browser tabs are open (${AGENT_TAB_LIMIT} per agent session, ${SERVER_TAB_LIMIT} per server). Close one with t3_preview_close or reuse one from preview_status tabs.`,+ reason: "tabLimit",+ });};// The desktop draws its tabs in its own webview, so they never get a streamed viewer.@@ -1591,12 +1592,12 @@ const make = Effect.gen(function* () {findBrowserProfile(profiles, requested) ??profiles.find((profile) => profile.name.toLowerCase() === wanted);if (match) return match.id;- throw new ServerBrowserPage.ServerBrowserOperationError(- "PreviewAutomationUnknownProfileError",- `No browser profile is named "${requested}". Use one of: ${profiles+ throw new ServerBrowserPage.ServerBrowserOperationError({+ tag: "PreviewAutomationUnknownProfileError",+ message: `No browser profile is named "${requested}". Use one of: ${profiles.map((profile) => `${profile.name} (id ${profile.id})`).join(", ")}.`,- );+ });};const statusWithTitle = async (@@ -1692,16 +1693,16 @@ const make = Effect.gen(function* () {await navigation.catch((cause: unknown) => {const message = cause instanceof Error ? cause.message : String(cause);if (message.includes("Download is starting")) {- throw new ServerBrowserPage.ServerBrowserOperationError(- "PreviewAutomationExecutionError",- `${url} is a file this browser cannot show, so it was downloaded instead. preview_status lists it under downloads.`,- );+ throw new ServerBrowserPage.ServerBrowserOperationError({+ tag: "PreviewAutomationExecutionError",+ message: `${url} is a file this browser cannot show, so it was downloaded instead. preview_status lists it under downloads.`,+ });}if (/ERR_[A-Z_]+/.test(message)) {- throw new ServerBrowserPage.ServerBrowserOperationError(- "PreviewAutomationExecutionError",- `Navigation to ${url} failed: ${ServerBrowserPage.parseNetError(message).description}`,- );+ throw new ServerBrowserPage.ServerBrowserOperationError({+ tag: "PreviewAutomationExecutionError",+ message: `Navigation to ${url} failed: ${ServerBrowserPage.parseNetError(message).description}`,+ });}throw ServerBrowserPage.toOperationError(cause, timeout);});@@ -1804,10 +1805,10 @@ const make = Effect.gen(function* () {withCaptureLock(tab, async () => {const recording = tab.recording;if (!recording) {- throw new ServerBrowserPage.ServerBrowserOperationError(- "PreviewAutomationRecordingNotActiveError",- "No recording is active for this tab.",- );+ throw new ServerBrowserPage.ServerBrowserOperationError({+ tag: "PreviewAutomationRecordingNotActiveError",+ message: "No recording is active for this tab.",+ });}let mimeType: string | null;const chunks: Array<Buffer> = [];@@ -1821,10 +1822,10 @@ const make = Effect.gen(function* () {mimeType = stopped.mimeType;// Checked before the transfer so an oversized video never lands in this process.if (stopped.bytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {- throw new ServerBrowserPage.ServerBrowserOperationError(- "PreviewAutomationRecordingTooLargeError",- "The recording is larger than the attachment limit.",- );+ throw new ServerBrowserPage.ServerBrowserOperationError({+ tag: "PreviewAutomationRecordingTooLargeError",+ message: "The recording is larger than the attachment limit.",+ });}for (let index = 0; index < stopped.count; index += 1) {const chunk = await recording.encoder.evaluate(@@ -1839,10 +1840,10 @@ const make = Effect.gen(function* () {}const data = Buffer.concat(chunks);if (!mimeType || data.byteLength === 0) {- throw new ServerBrowserPage.ServerBrowserOperationError(- "PreviewAutomationExecutionError",- "The recording captured no frames.",- );+ throw new ServerBrowserPage.ServerBrowserOperationError({+ tag: "PreviewAutomationExecutionError",+ message: "The recording captured no frames.",+ });}const extension = mimeType.startsWith("video/mp4") ? "mp4" : "webm";@@ -1921,15 +1922,18 @@ const make = Effect.gen(function* () {const requireTab = async (request: PreviewAutomationRequest) => {if (!request.agentSessionId)- throw new BrowserControlInterrupted("The agent session is missing. Reconnect the provider.");+ throw new BrowserControlInterrupted({+ message: "The agent session is missing. Reconnect the provider.",+ });const owned = [...tabs.values()].filter((tab) => tab.threadId === request.threadId && tab.control.agentId === request.agentSessionId,);if (!request.tabIdExplicit && owned.length > 1)- throw new BrowserControlInterrupted(- "Multiple tabs belong to this agent session. Pass a tabId from preview_open or preview_status tabs.",- "tabRequired",- );+ throw new BrowserControlInterrupted({+ message:+ "Multiple tabs belong to this agent session. Pass a tabId from preview_open or preview_status tabs.",+ reason: "tabRequired",+ });const tab =request.tabId === undefined? latestThreadTab(request.threadId, request.agentSessionId)@@ -1937,16 +1941,17 @@ const make = Effect.gen(function* () {findTab(request.threadId, request.tabId).pipe(Effect.orElseSucceed(constVoid)),);if (!tab) {- throw new ServerBrowserPage.ServerBrowserOperationError(- "PreviewAutomationTabNotFoundError",- "No server preview tab is open for this thread. Call preview_open first.",- );+ throw new ServerBrowserPage.ServerBrowserOperationError({+ tag: "PreviewAutomationTabNotFoundError",+ message: "No server preview tab is open for this thread. Call preview_open first.",+ });}if (!READ_OPERATIONS.has(request.operation) && !tab.control.agentMayAct(request.agentSessionId))- throw new BrowserControlInterrupted(- "This tab belongs to another agent session. You can read it, but open your own tab to act.",- "agentMismatch",- );+ throw new BrowserControlInterrupted({+ message:+ "This tab belongs to another agent session. You can read it, but open your own tab to act.",+ reason: "agentMismatch",+ });return tab;};@@ -1976,9 +1981,9 @@ const make = Effect.gen(function* () {);case "open": {if (!request.agentSessionId)- throw new BrowserControlInterrupted(- "The agent session is missing. Reconnect the provider.",- );+ throw new BrowserControlInterrupted({+ message: "The agent session is missing. Reconnect the provider.",+ });const open = input as PreviewAutomationOpenInput;const url = open.url === undefined ? undefined : normalizePreviewUrl(open.url);const reuse = open.reuseExistingTab ?? true;@@ -1990,10 +1995,10 @@ const make = Effect.gen(function* () {tab.threadId === request.threadId && tab.control.agentId === request.agentSessionId,).length > 1)- throw new BrowserControlInterrupted(- "Multiple tabs are open. Pass tabId or reuseExistingTab=false.",- "tabRequired",- );+ throw new BrowserControlInterrupted({+ message: "Multiple tabs are open. Pass tabId or reuseExistingTab=false.",+ reason: "tabRequired",+ });const found =reuse && request.tabId !== undefined@@ -2012,12 +2017,12 @@ const make = Effect.gen(function* () {const desktop = sessions.some((session) => session.tabId === request.tabId && session.runtime !== "server",);- throw new ServerBrowserPage.ServerBrowserOperationError(- desktop ? "PreviewAutomationExecutionError" : "PreviewAutomationTabNotFoundError",- desktop+ throw new ServerBrowserPage.ServerBrowserOperationError({+ tag: desktop ? "PreviewAutomationExecutionError" : "PreviewAutomationTabNotFoundError",+ message: desktop? "This tab belongs to the desktop runtime. This environment's server browser cannot control desktop tabs. Omit tabId to open a server tab instead.": "The requested server preview tab does not exist.",- );+ });}// Reusing another session's tab requires explicit tabId; reading it grants no implicit takeover.const existing =@@ -2043,18 +2048,20 @@ const make = Effect.gen(function* () {),));if (existing?.dialog)- throw new BrowserControlInterrupted(- "A browser dialog is pending. Read preview_status and use preview_dialog first.",- "dialogPending",- );+ throw new BrowserControlInterrupted({+ message:+ "A browser dialog is pending. Read preview_status and use preview_dialog first.",+ reason: "dialogPending",+ });return tab.control.agent(request.agentSessionId,async () => {if (tab.dialog)- throw new BrowserControlInterrupted(- "A browser dialog is pending. Read preview_status and use preview_dialog first.",- "dialogPending",- );+ throw new BrowserControlInterrupted({+ message:+ "A browser dialog is pending. Read preview_status and use preview_dialog first.",+ reason: "dialogPending",+ });if (existing) {if (url) await navigate(tab, url, "load", navigationTimeout);} else {@@ -2098,10 +2105,11 @@ const make = Effect.gen(function* () {candidate.control.agentId === request.agentSessionId,).length > 1)- throw new BrowserControlInterrupted(- "Multiple tabs belong to this agent session. Pass a tabId from preview_open or preview_status tabs.",- "tabRequired",- );+ throw new BrowserControlInterrupted({+ message:+ "Multiple tabs belong to this agent session. Pass a tabId from preview_open or preview_status tabs.",+ reason: "tabRequired",+ });const recordings = [...tabs.values()].filter((candidate) =>candidate.threadId === request.threadId &&@@ -2114,10 +2122,10 @@ const make = Effect.gen(function* () {recordings.find((candidate) => candidate.tabId === targetTabId) ??(!request.tabIdExplicit && recordings.length === 1 ? recordings[0] : undefined);if (!tab) {- throw new ServerBrowserPage.ServerBrowserOperationError(- "PreviewAutomationRecordingNotActiveError",- "No recording is active for this thread.",- );+ throw new ServerBrowserPage.ServerBrowserOperationError({+ tag: "PreviewAutomationRecordingNotActiveError",+ message: "No recording is active for this thread.",+ });}// A stop cannot act twice (a retry finds no recording);// dropping a late one would leave capture running.@@ -2128,12 +2136,15 @@ const make = Effect.gen(function* () {// Closing must unblock an action waiting on a dialog, without queueing behind it.if (request.operation === "close") {if (tab.control.agentId !== request.agentSessionId)- throw new BrowserControlInterrupted(- "Only the agent session that opened this tab can close it.",- "agentMismatch",- );+ throw new BrowserControlInterrupted({+ message: "Only the agent session that opened this tab can close it.",+ reason: "agentMismatch",+ });if (tab.control.controller !== null)- throw new BrowserControlInterrupted("A human controls this tab.", "humanControl");+ throw new BrowserControlInterrupted({+ message: "A human controls this tab.",+ reason: "humanControl",+ });void tab.control.close().catch(constVoid);await runPromise(manager.close({ threadId: tab.threadId, tabId: tab.tabId }));dropTab(tab, false);@@ -2142,7 +2153,10 @@ const make = Effect.gen(function* () {// Resolve dialogs outside the queue, with ownership checked, to unblock waiting clicks.if (request.operation === "dialog") {if (tab.control.controller !== null)- throw new BrowserControlInterrupted("A human controls this tab.", "humanControl");+ throw new BrowserControlInterrupted({+ message: "A human controls this tab.",+ reason: "humanControl",+ });await resolveDialog(tab, input as PreviewAutomationDialogInput);return statusWithTitle(tab, request.agentSessionId);}@@ -2155,10 +2169,10 @@ const make = Effect.gen(function* () {) {return tab.control.observe(async () => {if (tab.dialog)- throw new BrowserControlInterrupted(- "A browser dialog is pending. Read preview_status.",- "dialogPending",- );+ throw new BrowserControlInterrupted({+ message: "A browser dialog is pending. Read preview_status.",+ reason: "dialogPending",+ });return executeTabOperation(tab, request);});}@@ -2166,10 +2180,11 @@ const make = Effect.gen(function* () {agentSessionId,async () => {if (tab.dialog)- throw new BrowserControlInterrupted(- "A browser dialog is pending. Read preview_status and use preview_dialog first.",- "dialogPending",- );+ throw new BrowserControlInterrupted({+ message:+ "A browser dialog is pending. Read preview_status and use preview_dialog first.",+ reason: "dialogPending",+ });const generation = tab.control.generation;tab.agentOperating = !READ_OPERATIONS.has(request.operation);updateFileChooserInterception(tab);diff --git a/apps/server/src/preview/ServerBrowserPage.ts b/apps/server/src/preview/ServerBrowserPage.tsindex f128bf445e6..622482cd1b8 100644--- a/apps/server/src/preview/ServerBrowserPage.ts+++ b/apps/server/src/preview/ServerBrowserPage.ts@@ -19,56 +19,69 @@ import {type PreviewAutomationWaitForInput,} from "@t3tools/contracts";import { constVoid } from "effect/Function";+import * as Schema from "effect/Schema";import type { CDPSession, ConsoleMessage, Frame, Locator, Page } from "playwright-core";import * as NodeCrypto from "node:crypto";import { BrowserControlInterrupted } from "./SessionControl.ts";+const isBrowserControlInterrupted = Schema.is(BrowserControlInterrupted);+const MAX_EVALUATION_BYTES = 64_000;const MAX_VISIBLE_TEXT_LENGTH = 20_000;const MAX_SCREENSHOT_WIDTH = 1280;const WAIT_POLL_MS = 100;export const DIAGNOSTIC_BUFFER_LIMIT = 200;-export class ServerBrowserOperationError extends Error {- readonly tag: string;- readonly detail: unknown;+export class ServerBrowserOperationError extends Schema.TaggedError<ServerBrowserOperationError>()(+ "ServerBrowserOperationError",+ {+ tag: Schema.String,+ message: Schema.String,+ detail: Schema.optional(Schema.Unknown),+ cause: Schema.optional(Schema.Defect()),+ },+) {}- constructor(tag: string, message: string, detail?: unknown, options?: ErrorOptions) {- super(message, options);- this.tag = tag;- this.detail = detail;- }-}+const isServerBrowserOperationError = Schema.is(ServerBrowserOperationError);export const toOperationError = (cause: unknown,timeoutMs?: number,): ServerBrowserOperationError => {- if (cause instanceof BrowserControlInterrupted)- return new ServerBrowserOperationError(- "PreviewAutomationControlInterruptedError",- cause.message,- cause.reason,- );- if (cause instanceof ServerBrowserOperationError) return cause;+ if (isBrowserControlInterrupted(cause))+ return new ServerBrowserOperationError({+ tag: "PreviewAutomationControlInterruptedError",+ message: cause.message,+ detail: cause.reason,+ });+ if (isServerBrowserOperationError(cause)) return cause;const message = cause instanceof Error ? cause.message : String(cause);const firstLine = message.split("\n")[0] ?? message;if (cause instanceof Error && cause.name === "TimeoutError") {- return new ServerBrowserOperationError(- "PreviewAutomationTimeoutError",- firstLine,- timeoutMs === undefined ? undefined : { timeoutMs },- );+ return new ServerBrowserOperationError({+ tag: "PreviewAutomationTimeoutError",+ message: firstLine,+ detail: timeoutMs === undefined ? undefined : { timeoutMs },+ });}if (/while parsing selector|Unknown engine|Unexpected token|strict mode violation/i.test(message)) {- return new ServerBrowserOperationError("PreviewAutomationInvalidSelectorError", firstLine);+ return new ServerBrowserOperationError({+ tag: "PreviewAutomationInvalidSelectorError",+ message: firstLine,+ });}if (/not an <input>|not editable|not an editable/i.test(message)) {- return new ServerBrowserOperationError("PreviewAutomationTargetNotEditableError", firstLine);+ return new ServerBrowserOperationError({+ tag: "PreviewAutomationTargetNotEditableError",+ message: firstLine,+ });}- return new ServerBrowserOperationError("PreviewAutomationExecutionError", firstLine);+ return new ServerBrowserOperationError({+ tag: "PreviewAutomationExecutionError",+ message: firstLine,+ });};const DEFAULT_TIMEOUT_MS = 15_000;@@ -115,11 +128,12 @@ const targetLocator = (const ref = /^\s*aria-ref\s*=\s*(\S+)\s*$/.exec(selector)?.[1];const nativeRef = ref === undefined ? undefined : pageRefs.get(page)?.refs.get(ref);if (nativeRef === undefined) {- throw new ServerBrowserOperationError(- "PreviewAutomationInvalidSelectorError",- "This element ref is stale or belongs to another tab. Take a fresh snapshot and use its locator.",- { staleRef: true },- );+ throw new ServerBrowserOperationError({+ tag: "PreviewAutomationInvalidSelectorError",+ message:+ "This element ref is stale or belongs to another tab. Take a fresh snapshot and use its locator.",+ detail: { staleRef: true },+ });}return page.locator(`aria-ref=${nativeRef}`);}@@ -229,16 +243,17 @@ const DOTTED_SCRIPT = `(() => {})()`;const pageChanged = () =>- new ServerBrowserOperationError(- "PreviewAutomationExecutionError",- "The page changed while capturing its snapshot. Take another snapshot.",- );+ new ServerBrowserOperationError({+ tag: "PreviewAutomationExecutionError",+ message: "The page changed while capturing its snapshot. Take another snapshot.",+ });const tooBusy = () =>- new ServerBrowserOperationError(- "PreviewAutomationTimeoutError",- "The page was too busy to capture a snapshot in time. Wait for it to settle and take another snapshot.",- );+ new ServerBrowserOperationError({+ tag: "PreviewAutomationTimeoutError",+ message:+ "The page was too busy to capture a snapshot in time. Wait for it to settle and take another snapshot.",+ });const VALUE_TOO_LONG = "A password field holds a value too long to hide, so no snapshot was taken.";@@ -381,7 +396,10 @@ const dottedPattern = (values: ReadonlyArray<string>) => {pattern.test("");pattern.test("\u2022");} catch {- throw new ServerBrowserOperationError("PreviewAutomationExecutionError", VALUE_TOO_LONG);+ throw new ServerBrowserOperationError({+ tag: "PreviewAutomationExecutionError",+ message: VALUE_TOO_LONG,+ });}return pattern;};@@ -673,12 +691,12 @@ const namedTargetTimeout = async (: matches === 0? `The click may have happened and removed its target or navigated; check the page before retrying. No element matches ${target} after the timeout; take a fresh snapshot and use its locator.`: `The click may have happened; check the page before retrying. ${target} still matches an element after the timeout.`;- return new ServerBrowserOperationError(- "PreviewAutomationTimeoutError",- reason,- { reason },- { cause },- );+ return new ServerBrowserOperationError({+ tag: "PreviewAutomationTimeoutError",+ message: reason,+ detail: { reason },+ cause,+ });};const clickTarget = async (@@ -756,10 +774,10 @@ export const type = async (page: Page, input: PreviewAutomationTypeInput) => {{ timeout },));if (focused !== true) {- throw new ServerBrowserOperationError(- "PreviewAutomationTargetNotEditableError",- "The target is not an enabled text field, so no text was typed.",- );+ throw new ServerBrowserOperationError({+ tag: "PreviewAutomationTargetNotEditableError",+ message: "The target is not an enabled text field, so no text was typed.",+ });}if (input.clear) {await page.keyboard.press("ControlOrMeta+A");@@ -811,10 +829,10 @@ export const select = async ()?.value ?? entry,);if (values === null)- throw new ServerBrowserOperationError(- "PreviewAutomationTargetNotEditableError",- "This element is not a <select>. Click a custom dropdown, then click its option.",- );+ throw new ServerBrowserOperationError({+ tag: "PreviewAutomationTargetNotEditableError",+ message: "This element is not a <select>. Click a custom dropdown, then click its option.",+ });return { selected: await locator.selectOption(values, { timeout }) };};@@ -872,10 +890,10 @@ export const evaluate = async (// Stops a busy script; an awaited promise is abandoned and settles unread.void cdp.send("Runtime.terminateExecution").catch(constVoid);reject(- new ServerBrowserOperationError(- "PreviewAutomationTimeoutError",- `Evaluation did not finish within ${timeoutMs}ms and was stopped.`,- ),+ new ServerBrowserOperationError({+ tag: "PreviewAutomationTimeoutError",+ message: `Evaluation did not finish within ${timeoutMs}ms and was stopped.`,+ }),);}, timeoutMs);});@@ -887,20 +905,20 @@ export const evaluate = async (void evaluation.catch(constVoid);const result = await Promise.race([evaluation, expired]).finally(() => clearTimeout(timer));if (result.exceptionDetails) {- throw new ServerBrowserOperationError(- "PreviewAutomationExecutionError",- result.exceptionDetails.exception?.description ?? result.exceptionDetails.text,- );+ throw new ServerBrowserOperationError({+ tag: "PreviewAutomationExecutionError",+ message: result.exceptionDetails.exception?.description ?? result.exceptionDetails.text,+ });}const value ="value" in result.result ? result.result.value : (result.result.description ?? null);const actualBytes = Buffer.byteLength(JSON.stringify(value ?? null), "utf8");if (actualBytes > MAX_EVALUATION_BYTES) {- throw new ServerBrowserOperationError(- "PreviewAutomationResultTooLargeError",- `Evaluation result is ${actualBytes} bytes; the limit is ${MAX_EVALUATION_BYTES}.`,- { maximumBytes: MAX_EVALUATION_BYTES },- );+ throw new ServerBrowserOperationError({+ tag: "PreviewAutomationResultTooLargeError",+ message: `Evaluation result is ${actualBytes} bytes; the limit is ${MAX_EVALUATION_BYTES}.`,+ detail: { maximumBytes: MAX_EVALUATION_BYTES },+ });}return value;};@@ -926,10 +944,10 @@ export const waitFor = async (page: Page, input: PreviewAutomationWaitForInput)const results = await Promise.all(checks.map((check) => check()));if (results.every(Boolean)) return;if (Date.now() >= deadline) {- throw new ServerBrowserOperationError(- "PreviewAutomationTimeoutError",- `Waited ${timeoutMs}ms without every condition holding.`,- );+ throw new ServerBrowserOperationError({+ tag: "PreviewAutomationTimeoutError",+ message: `Waited ${timeoutMs}ms without every condition holding.`,+ });}await new Promise((resolve) => setTimeout(resolve, WAIT_POLL_MS));}diff --git a/apps/server/src/preview/SessionControl.ts b/apps/server/src/preview/SessionControl.tsindex 57644e3be71..f19f566ed30 100644--- a/apps/server/src/preview/SessionControl.ts+++ b/apps/server/src/preview/SessionControl.ts@@ -1,15 +1,20 @@-import type { PreviewAutomationControlReason } from "@t3tools/contracts";--export class BrowserControlInterrupted extends Error {- readonly reason: PreviewAutomationControlReason;- constructor(- message = "Browser control changed. Refresh the snapshot before trying again.",- reason: PreviewAutomationControlReason = "interrupted",- ) {- super(message);- this.reason = reason;- }-}+import { PreviewAutomationControlReason } from "@t3tools/contracts";+import * as Effect from "effect/Effect";+import * as Schema from "effect/Schema";++export class BrowserControlInterrupted extends Schema.TaggedError<BrowserControlInterrupted>()(+ "BrowserControlInterrupted",+ {+ message: Schema.String.pipe(+ Schema.withConstructorDefault(+ Effect.succeed("Browser control changed. Refresh the snapshot before trying again."),+ ),+ ),+ reason: PreviewAutomationControlReason.pipe(+ Schema.withConstructorDefault(Effect.succeed("interrupted" as const)),+ ),+ },+) {}const settle = (work: Promise<unknown>) =>work.then(@@ -69,7 +74,11 @@ export class SessionControl {}private assertOpen() {- if (this.closed) throw new BrowserControlInterrupted("This browser tab is closed.", "closed");+ if (this.closed)+ throw new BrowserControlInterrupted({+ message: "This browser tab is closed.",+ reason: "closed",+ });}private changeOwner(owner: string | null) {@@ -81,7 +90,8 @@ export class SessionControl {private async action<A>(allowed: () => boolean, run: () => Promise<A>, deadlineMs?: number) {this.assertOpen();- if (!allowed()) throw new BrowserControlInterrupted("You do not control this browser tab.");+ if (!allowed())+ throw new BrowserControlInterrupted({ message: "You do not control this browser tab." });const epoch = this.epoch;return this.enqueue(async () => {this.assertOpen();@@ -103,11 +113,17 @@ export class SessionControl {agent<A>(agentId: string, run: () => Promise<A>, deadlineMs?: number) {if (!this.agentMayAct(agentId))return Promise.reject(- new BrowserControlInterrupted("This tab belongs to another agent.", "agentMismatch"),+ new BrowserControlInterrupted({+ message: "This tab belongs to another agent.",+ reason: "agentMismatch",+ }),);if (this.owner !== null)return Promise.reject(- new BrowserControlInterrupted("A human controls this tab.", "humanControl"),+ new BrowserControlInterrupted({+ message: "A human controls this tab.",+ reason: "humanControl",+ }),);return this.action(() => this.agentMayAct(agentId) && this.owner === null, run, deadlineMs);}@@ -164,7 +180,7 @@ export class SessionControl {async take(viewerId: string) {this.assertOpen();if (this.owner !== null && this.owner !== viewerId) {- throw new BrowserControlInterrupted("Another viewer controls this browser tab.");+ throw new BrowserControlInterrupted({ message: "Another viewer controls this browser tab." });}if (this.owner !== viewerId) this.changeOwner(viewerId);return this.human(viewerId, async () => {});@@ -173,9 +189,9 @@ export class SessionControl {async release(viewerId: string, afterDrain: () => Promise<void> = async () => {}) {this.assertOpen();if (this.owner !== viewerId) {- throw new BrowserControlInterrupted(- "Only the controlling viewer can release this browser tab.",- );+ throw new BrowserControlInterrupted({+ message: "Only the controlling viewer can release this browser tab.",+ });}this.changeOwner(null);await this.enqueue(async () => {diff --git a/apps/server/src/project/AgentSessionJson.test.ts b/apps/server/src/project/AgentSessionJson.test.tsindex 515aa50b1b9..ea6f31f13c8 100644--- a/apps/server/src/project/AgentSessionJson.test.ts+++ b/apps/server/src/project/AgentSessionJson.test.ts@@ -48,7 +48,7 @@ describe("transcript JSON projection", () => {it("retains the import allocation and depth limits", () => {const limited = createTranscriptJsonReader(() => {- throw new TranscriptJsonLimitError("budget");+ throw new TranscriptJsonLimitError({ message: "budget" });},() => true,);diff --git a/apps/server/src/project/AgentSessionJson.ts b/apps/server/src/project/AgentSessionJson.tsindex 84b318f0642..c9dc6baa5f5 100644--- a/apps/server/src/project/AgentSessionJson.ts+++ b/apps/server/src/project/AgentSessionJson.ts@@ -1,3 +1,4 @@+import * as Schema from "effect/Schema";import * as SchemaAST from "effect/SchemaAST";import { none, type Many } from "stream-chain/defs.js";import { Assembler } from "stream-json/core/assembler.js";@@ -40,7 +41,10 @@ export function createTranscriptJsonSelector(schema: { readonly ast: SchemaAST.Areturn (path: JsonPath) => includes(ast, path, 0);}-export class TranscriptJsonLimitError extends Error {}+export class TranscriptJsonLimitError extends Schema.TaggedError<TranscriptJsonLimitError>()(+ "TranscriptJsonLimitError",+ { message: Schema.String },+) {}export function createTranscriptJsonReader(reserve: (bytes: number) => void,@@ -150,7 +154,9 @@ export function createTranscriptJsonReader(for (const token of tokens.values) {if (token.name === "startObject" || token.name === "startArray") {if (++depth > (options?.maxDepth ?? 128))- throw new TranscriptJsonLimitError("Transcript JSON nesting exceeds the depth limit");+ throw new TranscriptJsonLimitError({+ message: "Transcript JSON nesting exceeds the depth limit",+ });} else if (token.name === "endObject" || token.name === "endArray") {if (--depth === 0) complete = true;}diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.tsindex 511728cf212..026bc6abb4d 100644--- a/apps/server/src/project/AgentSessionScanner.ts+++ b/apps/server/src/project/AgentSessionScanner.ts@@ -1026,9 +1026,9 @@ export const make = Effect.gen(function* () {const reserve = (bytes: number) => {recordBytes += bytes;if (historyBytes + recordBytes > MAX_IMPORT_HISTORY_BYTES) {- throw new TranscriptJsonLimitError(- "Transcript selected history exceeds the 32 MiB memory budget",- );+ throw new TranscriptJsonLimitError({+ message: "Transcript selected history exceeds the 32 MiB memory budget",+ });}};let reader = createTranscriptJsonReader(reserve, selectTranscriptPath);diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.tsindex 4abadfbdb17..3f9ed4f1ed2 100644--- a/apps/server/src/provider/documentTextWorker.ts+++ b/apps/server/src/provider/documentTextWorker.ts@@ -29,6 +29,7 @@ const HIDDEN = new Set(["pPr",]);+// @effect-diagnostics-next-line extendsNativeError:off - this worker loads no Effect runtime; Truncation is a local throw sentinel.class Truncation extends Error {}interface XmlNode {diff --git a/apps/server/src/provider/providerMaintenanceRunner.ts b/apps/server/src/provider/providerMaintenanceRunner.tsindex ee7709e710e..d3fe7fdf867 100644--- a/apps/server/src/provider/providerMaintenanceRunner.ts+++ b/apps/server/src/provider/providerMaintenanceRunner.ts@@ -10,7 +10,6 @@ import {import { resolveSpawnCommand } from "@t3tools/shared/shell";import * as Cause from "effect/Cause";import * as Context from "effect/Context";-import * as Data from "effect/Data";import * as DateTime from "effect/DateTime";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";@@ -79,10 +78,13 @@ export class ProviderMaintenanceRunner extends Context.Service<ProviderMaintenanceRunnerShape>()("t3/provider/providerMaintenanceRunner") {}-class ProviderMaintenanceCommandError extends Data.TaggedError("ProviderMaintenanceCommandError")<{- readonly message: string;- readonly cause?: unknown;-}> {}+class ProviderMaintenanceCommandError extends Schema.TaggedError<ProviderMaintenanceCommandError>()(+ "ProviderMaintenanceCommandError",+ {+ message: Schema.String,+ cause: Schema.optional(Schema.Defect()),+ },+) {}interface VerifiedProviderRefresh {readonly providers: ReadonlyArray<ServerProvider>;diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.tsindex 6d5e4484860..546d68c8ebe 100644--- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts@@ -31,7 +31,6 @@ import * as Context from "effect/Context";import * as Digest from "effect/crypto/Digest";import * as Mac from "effect/crypto/Mac";import * as SecureRandom from "effect/crypto/SecureRandom";-import * as Data from "effect/Data";import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";@@ -122,9 +121,10 @@ export class ScheduledTaskWebhookOrigin extends Context.Reference<Effect.Effect<},) {}-class WebhookDeliverySkipped extends Data.TaggedError("WebhookDeliverySkipped")<{- readonly reason: string;-}> {}+class WebhookDeliverySkipped extends Schema.TaggedError<WebhookDeliverySkipped>()(+ "WebhookDeliverySkipped",+ { reason: Schema.String },+) {}interface RateWindow {readonly accepted: ReadonlyArray<{ readonly at: number }>;diff --git a/apps/web/src/browser/browserViewportActions.ts b/apps/web/src/browser/browserViewportActions.tsindex c88605be577..18ea91427c8 100644--- a/apps/web/src/browser/browserViewportActions.ts+++ b/apps/web/src/browser/browserViewportActions.ts@@ -1,5 +1,6 @@import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";import type { PreviewViewportSetting, ScopedThreadRef } from "@t3tools/contracts";+import * as Schema from "effect/Schema";import { toastManager } from "~/components/ui/toast";import { updatePreviewServerSnapshot } from "~/previewStateStore";@@ -15,11 +16,12 @@ export interface BrowserViewportTarget {const BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS = 15_000;-class BrowserViewportCommitTimeoutError extends Error {- override readonly name = "BrowserViewportCommitTimeoutError";-- constructor(readonly tabId: string) {- super(`Timed out committing the browser viewport for tab ${tabId}`);+class BrowserViewportCommitTimeoutError extends Schema.TaggedError<BrowserViewportCommitTimeoutError>()(+ "BrowserViewportCommitTimeoutError",+ { tabId: Schema.String },+) {+ override get message(): string {+ return `Timed out committing the browser viewport for tab ${this.tabId}`;}}@@ -53,7 +55,7 @@ const runHandlerWithTimeout = (tabId: string, operation: Promise<void>): Promiselet timeoutId: ReturnType<typeof setTimeout> | undefined;const timeout = new Promise<never>((_resolve, reject) => {timeoutId = setTimeout(- () => reject(new BrowserViewportCommitTimeoutError(tabId)),+ () => reject(new BrowserViewportCommitTimeoutError({ tabId })),BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS,);});diff --git a/apps/web/src/browser/openFileInPreview.ts b/apps/web/src/browser/openFileInPreview.tsindex 9c4a6c803ff..a997ee2b552 100644--- a/apps/web/src/browser/openFileInPreview.ts+++ b/apps/web/src/browser/openFileInPreview.ts@@ -12,7 +12,7 @@ import {mapAtomCommandResult,} from "@t3tools/client-runtime/state/runtime";import * as Cause from "effect/Cause";-import * as Data from "effect/Data";+import * as Schema from "effect/Schema";import { AsyncResult } from "effect/reactivity";import { resolveAssetUrl } from "~/assets/assetUrls";@@ -35,20 +35,22 @@ import { resolveBrowserDefaults } from "./browserDefaults";export const isBrowserPreviewFile = (path: string): boolean =>/\.(?:html?|pdf)$/i.test(path.split(/[?#]/, 1)[0] ?? "");-export class BrowserPreviewUnavailableError extends Data.TaggedError(+export class BrowserPreviewUnavailableError extends Schema.TaggedError<BrowserPreviewUnavailableError>()("BrowserPreviewUnavailableError",-)<{- readonly message: string;-}> {}+ { message: Schema.String },+) {}-export class BrowserSettingsReadError extends Data.TaggedError("BrowserSettingsReadError")<{- readonly cause: unknown;-}> {+export class BrowserSettingsReadError extends Schema.TaggedError<BrowserSettingsReadError>()(+ "BrowserSettingsReadError",+ { cause: Schema.Defect() },+) {override get message(): string {return "Saved browser settings could not be loaded.";}}+export const isBrowserSettingsReadError = Schema.is(BrowserSettingsReadError);+export type OpenPreviewMutation<E = unknown> = (input: {readonly environmentId: EnvironmentId;readonly input: PreviewOpenInput;@@ -66,7 +68,7 @@ export async function openUrlInPreview<E>(input: {const defaults = await resolveBrowserDefaults().catch((cause: unknown) => new BrowserSettingsReadError({ cause }),);- if (defaults instanceof BrowserSettingsReadError) {+ if (isBrowserSettingsReadError(defaults)) {return AsyncResult.failure(Cause.fail(defaults));}const runtime = previewRuntimeFor(threadRef.environmentId);diff --git a/apps/web/src/browser/useOpenLink.ts b/apps/web/src/browser/useOpenLink.tsindex 6a60fcbfed5..73d880632e9 100644--- a/apps/web/src/browser/useOpenLink.ts+++ b/apps/web/src/browser/useOpenLink.ts@@ -13,7 +13,7 @@ import {resolveBrowserLinkTargetPreference,resolveLinkTarget,} from "./browserLinkTarget";-import { BrowserSettingsReadError, openUrlInPreview } from "./openFileInPreview";+import { isBrowserSettingsReadError, openUrlInPreview } from "./openFileInPreview";const NO_MODIFIER = { metaKey: false, ctrlKey: false } as const;@@ -46,7 +46,7 @@ export function useOpenLink(threadRef: ScopedThreadRef | null | undefined): (return;}const failure = squashAtomCommandFailure(result);- if (failure instanceof BrowserSettingsReadError) throw failure;+ if (isBrowserSettingsReadError(failure)) throw failure;console.error(result.cause);}const api = readLocalApi();diff --git a/apps/web/src/cloud/dpop.ts b/apps/web/src/cloud/dpop.tsindex 442f00aaacf..41a3dffb42b 100644--- a/apps/web/src/cloud/dpop.ts+++ b/apps/web/src/cloud/dpop.ts@@ -3,7 +3,6 @@ import { computeDpopJwkThumbprint, DpopPublicJwk } from "@t3tools/shared/dpop";import * as Digest from "effect/crypto/Digest";import * as SecureRandom from "effect/crypto/SecureRandom";import * as Signature from "effect/crypto/Signature";-import * as Data from "effect/Data";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Schema from "effect/Schema";@@ -14,10 +13,12 @@ export interface BrowserDpopKey {readonly thumbprint: string;}-export class BrowserDpopError extends Data.TaggedError("BrowserDpopError")<{- readonly message: string;- readonly cause?: unknown;-}> {}+export class BrowserDpopError extends Schema.TaggedError<BrowserDpopError>()("BrowserDpopError", {+ message: Schema.String,+ cause: Schema.optional(Schema.Defect()),+}) {}++const isBrowserDpopError = Schema.is(BrowserDpopError);const DPOP_DATABASE_NAME = "t3code:cloud-auth";const DPOP_DATABASE_VERSION = 1;@@ -113,9 +114,7 @@ const generateBrowserDpopKey = Effect.gen(function* () {}).pipe(Effect.flatMap((jwk) => decodeDpopPublicJwk(jwk)),Effect.mapError((cause) =>- cause instanceof BrowserDpopError- ? cause- : dpopError("Generated DPoP public key is invalid.", cause),+ isBrowserDpopError(cause) ? cause : dpopError("Generated DPoP public key is invalid.", cause),),);const privateKey = yield* Effect.tryPromise({diff --git a/apps/web/src/cloud/linkEnvironment.ts b/apps/web/src/cloud/linkEnvironment.tsindex 70fd2de055f..8673e06d20c 100644--- a/apps/web/src/cloud/linkEnvironment.ts+++ b/apps/web/src/cloud/linkEnvironment.ts@@ -1,4 +1,3 @@-import * as Data from "effect/Data";import * as Effect from "effect/Effect";import * as Option from "effect/Option";import * as Schema from "effect/Schema";@@ -36,11 +35,16 @@ function relayUrl(): string | null {return resolveCloudPublicConfig().relayUrl;}-export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{- readonly message: string;- readonly cause?: unknown;- readonly traceId?: string;-}> {}+export class CloudEnvironmentLinkError extends Schema.TaggedError<CloudEnvironmentLinkError>()(+ "CloudEnvironmentLinkError",+ {+ message: Schema.String,+ cause: Schema.optional(Schema.Defect()),+ traceId: Schema.optional(Schema.String),+ },+) {}++export const isCloudEnvironmentLinkError = Schema.is(CloudEnvironmentLinkError);const relayClientRpcError = (message: string) => (cause: unknown) =>new CloudEnvironmentLinkError({diff --git a/apps/web/src/cloud/useCloudLinkController.ts b/apps/web/src/cloud/useCloudLinkController.tsindex 9936bf888d9..0e94b0e7e7b 100644--- a/apps/web/src/cloud/useCloudLinkController.ts+++ b/apps/web/src/cloud/useCloudLinkController.ts@@ -21,7 +21,7 @@ import { toastManager } from "../components/ui/toast";import { relayEnvironmentDiscovery } from "../state/relay";import { readEnvironmentScope } from "../state/session";import { useAtomCommand } from "../state/use-atom-command";-import { CloudEnvironmentLinkError } from "./linkEnvironment";+import { isCloudEnvironmentLinkError } from "./linkEnvironment";import { refreshManagedTunnelUsage } from "./managedRelayState";import {linkEnvironment as linkEnvironmentAtom,@@ -54,7 +54,7 @@ const isManagedRelayRequestFailedError = Schema.is(ManagedRelay.ManagedRelayRequ/** The account's tunnel cap when the relay refused a new tunnel for being at it. */function tunnelLimitFromLinkFailure(cause: unknown): number | null {- if (!(cause instanceof CloudEnvironmentLinkError)) return null;+ if (!isCloudEnvironmentLinkError(cause)) return null;const relayCause = cause.cause;if (!isManagedRelayRequestFailedError(relayCause)) return null;return relayCause.relayError?._tag === "RelayEnvironmentLinkLimitExceededError"diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsxindex 3ab3148bf39..2f2cfea67fd 100644--- a/apps/web/src/components/ChatMarkdown.tsx+++ b/apps/web/src/components/ChatMarkdown.tsx@@ -185,7 +185,7 @@ import {openFileInPreview,openUrlInPreview,BrowserPreviewUnavailableError,- BrowserSettingsReadError,+ isBrowserSettingsReadError,} from "../browser/openFileInPreview";import { resolveLinkTarget } from "../browser/browserLinkTarget";import { PullRequestLinkPreview } from "./pullRequest/PullRequestLinkPreview";@@ -712,7 +712,7 @@ function useChatMarkdownState({if (result._tag === "Success") recordVisitForThread(threadRef, url);else if (!isAtomCommandInterrupted(result)) {const error = squashAtomCommandFailure(result);- if (error instanceof BrowserSettingsReadError) {+ if (isBrowserSettingsReadError(error)) {toastManager.add(stackedThreadToast({type: "error",@@ -1204,7 +1204,7 @@ const CHAT_MARKDOWN_COMPONENTS = {{ operation: "open-link-in-preview", target: href },result.cause,);- if (squashAtomCommandFailure(result) instanceof BrowserSettingsReadError) return;+ if (isBrowserSettingsReadError(squashAtomCommandFailure(result))) return;void readLocalApi()?.shell.openExternal(href);});}}diff --git a/apps/web/src/components/chat/McpAppFrame.tsx b/apps/web/src/components/chat/McpAppFrame.tsxindex d65758f08d4..fc697333d61 100644--- a/apps/web/src/components/chat/McpAppFrame.tsx+++ b/apps/web/src/components/chat/McpAppFrame.tsx@@ -40,9 +40,10 @@ const commandFailure = (result: {readonly cause: Parameters<typeof squashAtomCommandFailure>[0]["cause"];}) => {const error = squashAtomCommandFailure(result);- return new McpAppHostRefusal(- error instanceof Error && error.message.trim() !== "" ? error.message : "Request failed.",- );+ return new McpAppHostRefusal({+ message:+ error instanceof Error && error.message.trim() !== "" ? error.message : "Request failed.",+ });};const fullscreenSupported =@@ -253,7 +254,7 @@ export function McpAppFrame(props: {flushSync(() => setDisplayMode("inline"));const approved = await requestConfirmDialog(message);if (approved === undefined) {- throw new McpAppHostRefusal("T3 could not ask for approval here.");+ throw new McpAppHostRefusal({ message: "T3 could not ask for approval here." });}return approved;};@@ -272,12 +273,13 @@ export function McpAppFrame(props: {const { environmentId, input } = scope();const info = await readLive().toolInfo({ environmentId, input: { ...input, name } });if (info._tag !== "Success") throw commandFailure(info);- if (!info.value.callable) throw new McpAppHostRefusal("This app cannot call that tool.");+ if (!info.value.callable)+ throw new McpAppHostRefusal({ message: "This app cannot call that tool." });if (!info.value.readOnly) {const approved = await ask(`Allow ${app.server} to run ${info.value.title ?? name}?\n${JSON.stringify(args, null, 2)}`,);- if (approved !== true) throw new McpAppHostRefusal("Declined by the user.");+ if (approved !== true) throw new McpAppHostRefusal({ message: "Declined by the user." });}const result = await readLive().callTool({environmentId,@@ -297,15 +299,16 @@ export function McpAppFrame(props: {},openLink: async (url) => {if (document.activeElement !== frameRef.current || !navigator.userActivation?.isActive) {- throw new McpAppHostRefusal("Links open only from a click in the app.");+ throw new McpAppHostRefusal({ message: "Links open only from a click in the app." });}window.open(url, "_blank", "noopener,noreferrer");},sendMessage: async (text) => {const send = readLive().props.onSendMessage;- if (send === undefined) throw new McpAppHostRefusal("Messages are not available here.");+ if (send === undefined)+ throw new McpAppHostRefusal({ message: "Messages are not available here." });const approved = await ask(`Send this message from ${app.server}?\n${text}`);- if (approved !== true) throw new McpAppHostRefusal("Declined by the user.");+ if (approved !== true) throw new McpAppHostRefusal({ message: "Declined by the user." });await send(text);},updateModelContext: async (context) => {@@ -340,7 +343,7 @@ export function McpAppFrame(props: {downloadFile: async (files) => {const names = files.map((file) => file.name).join(", ");const approved = await ask(`Save ${names} from ${app.server}?`);- if (approved !== true) throw new McpAppHostRefusal("Declined by the user.");+ if (approved !== true) throw new McpAppHostRefusal({ message: "Declined by the user." });for (const file of files) {let bytes: Uint8Array | undefined;let mimeType = file.mimeType ?? "application/octet-stream";@@ -358,9 +361,10 @@ export function McpAppFrame(props: {const declared = (content as { readonly mimeType?: unknown } | undefined)?.mimeType;if (typeof declared === "string") mimeType = declared;}- if (bytes === undefined) throw new McpAppHostRefusal(`${file.name} has no contents.`);+ if (bytes === undefined)+ throw new McpAppHostRefusal({ message: `${file.name} has no contents.` });if (bytes.byteLength > MAX_DOWNLOAD_BYTES) {- throw new McpAppHostRefusal(`${file.name} is too large to save.`);+ throw new McpAppHostRefusal({ message: `${file.name} is too large to save.` });}saveBlob(new Blob([bytes.slice()], { type: mimeType }), file.name);}diff --git a/apps/web/src/components/chat/useRightPanelActions.ts b/apps/web/src/components/chat/useRightPanelActions.tsindex 0f8e8e3ce30..25ec5c22c2e 100644--- a/apps/web/src/components/chat/useRightPanelActions.ts+++ b/apps/web/src/components/chat/useRightPanelActions.ts@@ -22,7 +22,7 @@ import {} from "../../rightPanelStore";import { requestWorkspaceContentFocus, requestWorkspaceFocus } from "../../lib/workspaceFocus";import { setActivePreviewTab } from "../../previewStateStore";-import { BrowserSettingsReadError } from "../../browser/openFileInPreview";+import { isBrowserSettingsReadError } from "../../browser/openFileInPreview";import { addBrowserSurface } from "../preview/addBrowserSurface";import { focusActivePanelTerminal, focusTerminal } from "../../lib/terminalFocus";import { subscribePreviewAction } from "../preview/previewActionBus";@@ -119,7 +119,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) {}).then((result) => {if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;const error = squashAtomCommandFailure(result);- if (error instanceof BrowserSettingsReadError) {+ if (isBrowserSettingsReadError(error)) {toastManager.add(stackedThreadToast({type: "error",diff --git a/apps/web/src/components/device/DeviceAndroidFoldControls.tsx b/apps/web/src/components/device/DeviceAndroidFoldControls.tsxindex b680a20f1df..a6d47cba890 100644--- a/apps/web/src/components/device/DeviceAndroidFoldControls.tsx+++ b/apps/web/src/components/device/DeviceAndroidFoldControls.tsx@@ -1,3 +1,4 @@+import * as Schema from "effect/Schema";import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";import { useAtomMount, useAtomSet, useAtomValue } from "@effect/atom-react";import { useRef, useState } from "react";@@ -7,6 +8,8 @@ import { AndroidFoldError, setAndroidFold, type AndroidFoldPosture } from "./devimport { androidFoldReadAtom, androidFoldViewAtom, foldAngle, NOOP_ATOM } from "./deviceHubAtoms";import { DeviceDuoGlyph } from "./DeviceDuoGlyph";+const isAndroidFoldError = Schema.is(AndroidFoldError);+export function DeviceAndroidFoldControls(props: {readonly access: DeviceHubAccess;readonly deviceKey: string;@@ -47,7 +50,7 @@ export function DeviceAndroidFoldControls(props: {void send(props.access).catch(async (cause: unknown) => {// Hub tickets expire after a few minutes, while the panel stays open much longer.- if (!(cause instanceof AndroidFoldError && cause.status === 401)) throw cause;+ if (!(isAndroidFoldError(cause) && cause.status === 401)) throw cause;const renewed = await props.renewAccess();if (!renewed || controller.signal.aborted) throw cause;return send(renewed);diff --git a/apps/web/src/components/device/DeviceWorkspace.tsx b/apps/web/src/components/device/DeviceWorkspace.tsxindex 08ce51c1c54..21f51520ba3 100644--- a/apps/web/src/components/device/DeviceWorkspace.tsx+++ b/apps/web/src/components/device/DeviceWorkspace.tsx@@ -1,3 +1,4 @@+import * as Schema from "effect/Schema";import type { DeviceHostSummary, DeviceSummary, EnvironmentId } from "@t3tools/contracts";import { useRef, useState } from "react";import {@@ -10,6 +11,8 @@ import { DeviceStreamView } from "./DeviceStreamView";import { DeviceToolsPanel } from "./DeviceToolsPanel";import { useDeviceControls } from "./useDeviceControls";+const isDeviceScreenshotError = Schema.is(DeviceScreenshotError);+const DOWNLOAD_URL_LIFETIME_MS = 60_000;export function DeviceWorkspace(props: {@@ -59,7 +62,7 @@ export function DeviceWorkspace(props: {window.setTimeout(() => URL.revokeObjectURL(url), DOWNLOAD_URL_LIFETIME_MS);}).catch((cause: unknown) => {- if (cause instanceof DeviceScreenshotError && cause.status === 401)+ if (isDeviceScreenshotError(cause) && cause.status === 401)refreshDeviceHubAccess(props.environmentId);setScreenshotError(cause instanceof Error ? cause.message : "Screenshot capture failed. Try again.",diff --git a/apps/web/src/components/device/deviceFold.ts b/apps/web/src/components/device/deviceFold.tsindex 779e89a1252..1ad9e09c856 100644--- a/apps/web/src/components/device/deviceFold.ts+++ b/apps/web/src/components/device/deviceFold.ts@@ -1,5 +1,6 @@import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";import { withDeviceHubQuery } from "@t3tools/client-runtime/state/deviceHubAccess";+import * as Schema from "effect/Schema";export type AndroidFoldPosture = "closed" | "opened";@@ -9,14 +10,10 @@ export interface AndroidFoldState {readonly hingeAngle: number | null;}-export class AndroidFoldError extends Error {- readonly status: number;-- constructor(message: string, status: number) {- super(message);- this.status = status;- }-}+export class AndroidFoldError extends Schema.TaggedError<AndroidFoldError>()("AndroidFoldError", {+ message: Schema.String,+ status: Schema.Number,+}) {}const isRecord = (value: unknown): value is Record<string, unknown> =>typeof value === "object" && value !== null && !Array.isArray(value);@@ -63,10 +60,10 @@ const foldRequest = async (if (!response.ok) {const payload: unknown = await response.json().catch(() => null);const error = isRecord(payload) ? payload.error : null;- throw new AndroidFoldError(- typeof error === "string" ? error : `Fold command failed (${response.status}).`,- response.status,- );+ throw new AndroidFoldError({+ message: typeof error === "string" ? error : `Fold command failed (${response.status}).`,+ status: response.status,+ });}return parseFold(await response.json());};diff --git a/apps/web/src/components/device/deviceHubAtoms.ts b/apps/web/src/components/device/deviceHubAtoms.tsindex e9e6c1c66b9..345405ba3a6 100644--- a/apps/web/src/components/device/deviceHubAtoms.ts+++ b/apps/web/src/components/device/deviceHubAtoms.ts@@ -17,6 +17,8 @@ import {} from "./deviceHubApi";import { AndroidFoldError, readAndroidFold, type AndroidFoldState } from "./deviceFold";+const isAndroidFoldError = Schema.is(AndroidFoldError);+const AX_POLL_INTERVAL_MS = 2_000;const FOLD_RETRY_MS = 3_000;@@ -102,7 +104,7 @@ export const androidFoldReadAtom = Atom.family(Atom.make((get) =>Effect.tryPromise({try: (signal) => readAndroidFold(input.access, input.deviceId, signal),- catch: (cause) => ({ expired: cause instanceof AndroidFoldError && cause.status === 401 }),+ catch: (cause) => ({ expired: isAndroidFoldError(cause) && cause.status === 401 }),}).pipe(Effect.retry({while: (failure) => !failure.expired,diff --git a/apps/web/src/components/files/office/Spreadsheet.tsx b/apps/web/src/components/files/office/Spreadsheet.tsxindex 6faa42d924c..7bea259b9f0 100644--- a/apps/web/src/components/files/office/Spreadsheet.tsx+++ b/apps/web/src/components/files/office/Spreadsheet.tsx@@ -1,3 +1,4 @@+import * as Schema from "effect/Schema";import { observeResize } from "~/lib/observeResize";import { useEffect, useRef, useState } from "react";import {@@ -33,6 +34,8 @@ import {} from "./sheet-paint";import { externalUrl } from "./links";+const isSupersededError = Schema.is(SupersededError);+type Client = ReturnType<typeof createWorkerClient<SheetMethods>>;type Opened = {engine: Client;@@ -264,7 +267,7 @@ function SpreadsheetGrid(props: {schedule();}).catch((cause: unknown) => {- if (!(cause instanceof SupersededError) && !controller.signal.aborted)+ if (!isSupersededError(cause) && !controller.signal.aborted)setNotice("These cells could not be drawn.");});}diff --git a/apps/web/src/components/files/office/worker-rpc.ts b/apps/web/src/components/files/office/worker-rpc.tsindex c5471cea87c..2be77ea8938 100644--- a/apps/web/src/components/files/office/worker-rpc.ts+++ b/apps/web/src/components/files/office/worker-rpc.ts@@ -3,6 +3,8 @@// two ends of that worker's protocol: typed calls by method name, a key that lets a newer call replace a queued one// (as the markdown worker's queue does), transferable payloads, and a worker that fails every pending call when it dies.+import * as Schema from "effect/Schema";+/** What one method takes and returns. */export type Method<Input, Output> = { readonly input: Input; readonly output: Output };@@ -43,10 +45,14 @@ export class Transfer<T> {}/** A call that a newer call with the same key replaced before it ran. */-export class SupersededError extends Error {}+export class SupersededError extends Schema.TaggedError<SupersededError>()("SupersededError", {+ message: Schema.String,+}) {}/** A call made after the worker failed or was closed, or pending when that happened. */-class WorkerClosedError extends Error {}+class WorkerClosedError extends Schema.TaggedError<WorkerClosedError>()("WorkerClosedError", {+ message: Schema.String,+}) {}type CallOptions = {/** A newer call with the same key replaces this one while it waits to run. */@@ -93,10 +99,10 @@ export function createWorkerClient<M extends Methods>(worker: Worker) {});worker.addEventListener("error", (event) =>- fail(new WorkerClosedError(event.message || "The Office engine stopped")),+ fail(new WorkerClosedError({ message: event.message || "The Office engine stopped" })),);worker.addEventListener("messageerror", () =>- fail(new WorkerClosedError("The Office engine sent an unreadable reply")),+ fail(new WorkerClosedError({ message: "The Office engine sent an unreadable reply" })),);return {@@ -108,7 +114,7 @@ export function createWorkerClient<M extends Methods>(worker: Worker) {if (state.failure) return Promise.reject(state.failure);if (options.signal?.aborted)- return Promise.reject(new WorkerClosedError("The call was aborted"));+ return Promise.reject(new WorkerClosedError({ message: "The call was aborted" }));const id = ++state.next;@@ -116,16 +122,16 @@ export function createWorkerClient<M extends Methods>(worker: Worker) {const timeout = setTimeout(() =>fail(- new WorkerClosedError(- "This document took too long to preview. Open it in another app.",- ),+ new WorkerClosedError({+ message: "This document took too long to preview. Open it in another app.",+ }),),30_000,);const abort = () => {clearTimeout(timeout);pending.delete(id);- reject(new WorkerClosedError("The call was aborted"));+ reject(new WorkerClosedError({ message: "The call was aborted" }));worker.postMessage({ cancel: id } satisfies Cancel, []);};@@ -138,7 +144,7 @@ export function createWorkerClient<M extends Methods>(worker: Worker) {if (!response.ok)return reject(response.superseded- ? new SupersededError(response.message)+ ? new SupersededError({ message: response.message }): new Error(response.message),);@@ -158,7 +164,7 @@ export function createWorkerClient<M extends Methods>(worker: Worker) {},/** Stops the worker, which frees its engine's memory, and fails every pending call. */close() {- fail(new WorkerClosedError("The Office engine was closed"));+ fail(new WorkerClosedError({ message: "The Office engine was closed" }));},};}diff --git a/apps/web/src/components/guest/guestTurnItemSource.ts b/apps/web/src/components/guest/guestTurnItemSource.tsindex 5ce858251d8..72a5802e812 100644--- a/apps/web/src/components/guest/guestTurnItemSource.ts+++ b/apps/web/src/components/guest/guestTurnItemSource.ts@@ -10,7 +10,6 @@ import {OrchestrationV2GetTurnItemResult,} from "@t3tools/contracts";import * as Cause from "effect/Cause";-import * as Data from "effect/Data";import * as Effect from "effect/Effect";import * as Option from "effect/Option";import * as Queue from "effect/Queue";@@ -21,9 +20,9 @@ import { Atom } from "effect/reactivity";import type { TurnItemSource } from "../chat/timelineRowContext";/** What an expanded guest row says when it cannot read the item. */-class GuestItemReadError extends Data.TaggedError("GuestItemReadError")<{- readonly message: string;-}> {}+class GuestItemReadError extends Schema.TaggedError<GuestItemReadError>()("GuestItemReadError", {+ message: Schema.String,+}) {}const decodeDetail = Schema.decodeUnknownSync(Schema.toCodecJson(OrchestrationV2GetTurnItemResult));const decodeFrame = Schema.decodeUnknownOption(diff --git a/apps/web/src/components/preview/PreviewView.tsx b/apps/web/src/components/preview/PreviewView.tsxindex 865448e1f6d..28779191d77 100644--- a/apps/web/src/components/preview/PreviewView.tsx+++ b/apps/web/src/components/preview/PreviewView.tsx@@ -71,7 +71,7 @@ import { BrowserDeviceToolbar } from "~/browser/BrowserDeviceToolbar";import { BROWSER_DEVICE_TOOLBAR_HEIGHT } from "~/browser/browserViewportLayout";import { useBrowserLayoutZoomFactor } from "~/browser/useBrowserLayoutZoomFactor";import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";-import { BrowserSettingsReadError } from "~/browser/openFileInPreview";+import { isBrowserSettingsReadError } from "~/browser/openFileInPreview";import { PreviewFileNotShown, PreviewUnreachable } from "./PreviewUnreachable";import { revealInFileExplorerLabel } from "./fileExplorerLabel";import { shouldShowPreviewEmptyState } from "./previewEmptyStateLogic";@@ -243,7 +243,7 @@ export function PreviewView({const result = await openPreviewSession({ openPreview: open, threadRef, url: resolvedUrl });if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {const error = squashAtomCommandFailure(result);- if (error instanceof BrowserSettingsReadError) {+ if (isBrowserSettingsReadError(error)) {toastManager.add({type: "error",title: "Unable to open browser",diff --git a/apps/web/src/components/preview/openPreviewSession.ts b/apps/web/src/components/preview/openPreviewSession.tsindex 4827d004535..99dc6c3e572 100644--- a/apps/web/src/components/preview/openPreviewSession.ts+++ b/apps/web/src/components/preview/openPreviewSession.ts@@ -11,7 +11,7 @@ import * as Cause from "effect/Cause";import { AsyncResult } from "effect/reactivity";import { resolveBrowserDefaults } from "~/browser/browserDefaults";-import { BrowserSettingsReadError } from "~/browser/openFileInPreview";+import { BrowserSettingsReadError, isBrowserSettingsReadError } from "~/browser/openFileInPreview";import { previewRuntimeFor } from "~/browser/previewRuntime";import { applyPreviewServerSnapshot, rememberPreviewUrl } from "~/previewStateStore";@@ -34,7 +34,7 @@ export async function openPreviewSession<E>(const defaults = await resolveBrowserDefaults().catch((cause: unknown) => new BrowserSettingsReadError({ cause }),);- if (defaults instanceof BrowserSettingsReadError) {+ if (isBrowserSettingsReadError(defaults)) {return AsyncResult.failure(Cause.fail(defaults));}const runtime = input.runtime ?? previewRuntimeFor(input.threadRef.environmentId);diff --git a/apps/web/src/components/settings/IntegrationsSettings.tsx b/apps/web/src/components/settings/IntegrationsSettings.tsxindex b64e35db951..4d2032f9471 100644--- a/apps/web/src/components/settings/IntegrationsSettings.tsx+++ b/apps/web/src/components/settings/IntegrationsSettings.tsx@@ -40,6 +40,7 @@ import { usePrimaryManagedPolicy } from "~/state/managedPolicy";import { isValidSearchUrlTemplate } from "@t3tools/shared/preview";import { PREVIEW_VIEWPORT_PRESETS } from "@t3tools/shared/previewViewport";import { MoreVertical, Plus as PlusIcon } from "lucide-react";+import * as Schema from "effect/Schema";import { useRef, useState } from "react";import { ScreenRotationIcon } from "~/browser/ScreenRotationIcon";@@ -174,13 +175,17 @@ const zoomLabel = (zoomFactor: number) => `${Math.round(zoomFactor * 100)}%`;/** IPC carries reason tokens inside messages; treat unknown tokens as read failures without exposing raw* text. */-class ProfileLimitReachedError extends Error {- constructor() {- super("Browser profile limit reached.");- this.name = "ProfileLimitReachedError";+class ProfileLimitReachedError extends Schema.TaggedError<ProfileLimitReachedError>()(+ "ProfileLimitReachedError",+ {},+) {+ override get message(): string {+ return "Browser profile limit reached.";}}+const isProfileLimitReachedError = Schema.is(ProfileLimitReachedError);+export const importFailureReason = (cause: unknown): BrowserImportFailureReason => {const message = String((cause as { message?: unknown } | undefined)?.message ?? "");return (@@ -257,8 +262,9 @@ async function importBrowserCookiesIntoTarget(await clearBrowserProfileData(bridge, [environmentId], input.target.profileId).catch(() => undefined,);- const reason =- cause instanceof ProfileLimitReachedError ? "profileLimitReached" : "profileNotSaved";+ const reason = isProfileLimitReachedError(cause)+ ? "profileLimitReached"+ : "profileNotSaved";throw new Error(`Importing cookies from ${source.id} failed: ${reason}.`, { cause });}} else {diff --git a/apps/web/src/components/settings/OpenSourceLicenses.tsx b/apps/web/src/components/settings/OpenSourceLicenses.tsxindex df311db516c..08722738423 100644--- a/apps/web/src/components/settings/OpenSourceLicenses.tsx+++ b/apps/web/src/components/settings/OpenSourceLicenses.tsx@@ -1,7 +1,7 @@import { ChevronRightIcon, ExternalLinkIcon, SearchIcon } from "lucide-react";import { useAtomRefresh, useAtomValue } from "@effect/atom-react";import * as Cause from "effect/Cause";-import * as Data from "effect/Data";+import * as Schema from "effect/Schema";import * as Effect from "effect/Effect";import * as Option from "effect/Option";import { FetchHttpClient, HttpClient } from "effect/http";@@ -22,9 +22,10 @@ import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group"import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";import { SettingsPageContainer, SettingsSection } from "./settingsLayout";-class LicenseManifestLoadError extends Data.TaggedError("LicenseManifestLoadError")<{- readonly message: string;-}> {}+class LicenseManifestLoadError extends Schema.TaggedError<LicenseManifestLoadError>()(+ "LicenseManifestLoadError",+ { message: Schema.String },+) {}// Not keepAlive: a failed load must not stick for the session, so each visit to the page loads// the manifest again (a static asset the HTTP cache serves).diff --git a/apps/web/src/lib/resourceTelemetryState.browser.test.tsx b/apps/web/src/lib/resourceTelemetryState.browser.test.tsxindex 1ad71e6e765..981beeafdfd 100644--- a/apps/web/src/lib/resourceTelemetryState.browser.test.tsx+++ b/apps/web/src/lib/resourceTelemetryState.browser.test.tsx@@ -6,7 +6,7 @@ import {} from "@t3tools/contracts";import * as Cause from "effect/Cause";import * as DateTime from "effect/DateTime";-import * as Data from "effect/Data";+import * as Schema from "effect/Schema";import * as Effect from "effect/Effect";import * as Option from "effect/Option";import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";@@ -64,7 +64,9 @@ vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => monitor.retrimport { ResourceTelemetryDiagnostics } from "../components/settings/ResourceTelemetryDiagnostics";-class MonitorError extends Data.TaggedError("MonitorError")<{ readonly message: string }> {}+class MonitorError extends Schema.TaggedError<MonitorError>()("MonitorError", {+ message: Schema.String,+}) {}const environmentId = EnvironmentId.make("remote");const startError = "The resource monitor is not available.";diff --git a/infra/relay/src/http/Api.test.ts b/infra/relay/src/http/Api.test.tsindex 0ed73648e78..3abb8b28f4d 100644--- a/infra/relay/src/http/Api.test.ts+++ b/infra/relay/src/http/Api.test.ts@@ -15,7 +15,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices";import { describe, expect, it } from "@effect/vitest";import { vi } from "vite-plus/test";import * as Context from "effect/Context";-import * as Data from "effect/Data";import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";import * as DateTime from "effect/DateTime";import * as Deferred from "effect/Deferred";@@ -1471,7 +1470,7 @@ describe("relay routing fallback", () => {describe("relay CORS", () => {const origin = "https://app.t3.codes";- class HandlerFailed extends Data.TaggedError("HandlerFailed") {}+ class HandlerFailed extends Schema.TaggedError<HandlerFailed>()("HandlerFailed", {}) {}it.effect("adds CORS headers to handler failures and defects", () =>Effect.gen(function* () {diff --git a/infra/task-cache/vendor/vite-plus-remote-cache-cloudflare/src/errors.ts b/infra/task-cache/vendor/vite-plus-remote-cache-cloudflare/src/errors.tsindex 9b54ffce50c..19eb7c2b848 100644--- a/infra/task-cache/vendor/vite-plus-remote-cache-cloudflare/src/errors.ts+++ b/infra/task-cache/vendor/vite-plus-remote-cache-cloudflare/src/errors.ts@@ -1,3 +1,4 @@+// @effect-diagnostics-next-line extendsNativeError:off - vendored upstream code without Effect; kept as published.export class HttpError extends Error {constructor(public status: number,diff --git a/oxlint-plugin-t3code/test/utils.ts b/oxlint-plugin-t3code/test/utils.tsindex 8982a551355..7146048afab 100644--- a/oxlint-plugin-t3code/test/utils.ts+++ b/oxlint-plugin-t3code/test/utils.ts@@ -1,11 +1,9 @@import * as NodeServices from "@effect/platform-node/NodeServices";import { assert, it } from "@effect/vitest";-import * as Data from "effect/Data";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";import * as Path from "effect/Path";import * as PlatformError from "effect/PlatformError";-import * as Predicate from "effect/Predicate";import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";import { ChildProcess, ChildProcessSpawner } from "effect/process";@@ -19,18 +17,21 @@ const oxlintPackageJsonPath = NodeModule.createRequire(NodeModule.createRequire(import.meta.url).resolve("vite-plus/package.json"),).resolve("oxlint/package.json");-class OxlintFixtureFailure extends Data.TaggedError("OxlintFixtureFailure")<{- readonly exitCode: number;- readonly stdout: string;- readonly stderr: string;-}> {- static readonly is = (u: unknown): u is OxlintFixtureFailure =>- Predicate.isTagged(u, "OxlintFixtureFailure");-}--class OxlintFixtureExpectedFailure extends Data.TaggedError("OxlintFixtureExpectedFailure")<{- readonly ruleName: string;-}> {+class OxlintFixtureFailure extends Schema.TaggedError<OxlintFixtureFailure>()(+ "OxlintFixtureFailure",+ {+ exitCode: Schema.Number,+ stdout: Schema.String,+ stderr: Schema.String,+ },+) {}++const isOxlintFixtureFailure = Schema.is(OxlintFixtureFailure);++class OxlintFixtureExpectedFailure extends Schema.TaggedError<OxlintFixtureExpectedFailure>()(+ "OxlintFixtureExpectedFailure",+ { ruleName: Schema.String },+) {override get message() {return `Expected oxlint to report a failure for rule ${this.ruleName}, but it passed.`;}@@ -140,7 +141,7 @@ export const createOxlintRuleHarness = (run(source).pipe(Effect.matchEffect({onFailure: (error) =>- OxlintFixtureFailure.is(error)+ isOxlintFixtureFailure(error)? Effect.succeed(`oxlint fixture failed with exit code ${error.exitCode}\n${error.stdout}\n${error.stderr}`,)diff --git a/packages/client-runtime/src/authorization/remote.ts b/packages/client-runtime/src/authorization/remote.tsindex 135c443df3f..814bff49834 100644--- a/packages/client-runtime/src/authorization/remote.ts+++ b/packages/client-runtime/src/authorization/remote.ts@@ -13,6 +13,7 @@ import { hashTelemetryId } from "@t3tools/shared/telemetryId";import * as Effect from "effect/Effect";import * as Option from "effect/Option";import * as Redacted from "effect/Redacted";+import * as Schema from "effect/Schema";import { environmentEndpointUrl } from "../environment/endpoint.ts";import * as ClientCapabilities from "../platform/capabilities.ts";import {@@ -26,6 +27,7 @@ export { RemoteEnvironmentAuthUndeclaredStatusError } from "../rpc/http.ts";export type RemoteEnvironmentAuthError = RemoteEnvironmentRequestError;const DEFAULT_REMOTE_REQUEST_TIMEOUT_MS = 10_000;+const isUndeclaredStatusError = Schema.is(RemoteEnvironmentAuthUndeclaredStatusError);const clientMetadataTokenExchangeFields = (clientMetadata: AuthClientPresentationMetadata | undefined,@@ -205,8 +207,7 @@ const issueWebSocketTicketWithFallback = <E, R>(? issue(use): issue(use).pipe(Effect.catchIf(- (error) =>- error instanceof RemoteEnvironmentAuthUndeclaredStatusError && error.status === 404,+ (error) => isUndeclaredStatusError(error) && error.status === 404,() => issue(undefined),),);diff --git a/packages/client-runtime/src/connection/errors.test.ts b/packages/client-runtime/src/connection/errors.test.tsindex d270ed2c524..55619af5a41 100644--- a/packages/client-runtime/src/connection/errors.test.ts+++ b/packages/client-runtime/src/connection/errors.test.ts@@ -93,7 +93,10 @@ describe("mapRemoteDpopEnvironmentError", () => {message: "Failed to fetch remote environment endpoint.",cause: new TypeError("Failed to fetch"),}),- new RemoteEnvironmentAuthTimeoutError("https://environment.example.test", 10_000),+ new RemoteEnvironmentAuthTimeoutError({+ requestUrl: "https://environment.example.test",+ timeoutMs: 10_000,+ }),])("suggests another network when the relay endpoint cannot be reached: $_tag", (error) => {const mapped = mapRemoteDpopEnvironmentError(error);expect(mapped).toMatchObject({diff --git a/packages/client-runtime/src/device/screenshot.ts b/packages/client-runtime/src/device/screenshot.tsindex 922295c6984..c3d09e854f5 100644--- a/packages/client-runtime/src/device/screenshot.ts+++ b/packages/client-runtime/src/device/screenshot.ts@@ -1,13 +1,14 @@// @effect-diagnostics globalFetch:off - This browser transport runs without an Effect runtime, like the live stream.+import * as Schema from "effect/Schema";import { withDeviceHubQuery } from "./hubAccess.ts";import type { DeviceStreamTarget } from "./stream.ts";-export class DeviceScreenshotError extends Error {- readonly status: number;-- constructor(status: number) {- super(`Screenshot capture failed (${status}). Try again.`);- this.status = status;+export class DeviceScreenshotError extends Schema.TaggedError<DeviceScreenshotError>()(+ "DeviceScreenshotError",+ { status: Schema.Number },+) {+ override get message(): string {+ return `Screenshot capture failed (${this.status}). Try again.`;}}@@ -22,7 +23,7 @@ export async function captureDeviceScreenshot(target: DeviceStreamTarget, signalcredentials: target.access.credentials ? "include" : "omit",signal: AbortSignal.any([signal, AbortSignal.timeout(20_000)]),});- if (!response.ok) throw new DeviceScreenshotError(response.status);+ if (!response.ok) throw new DeviceScreenshotError({ status: response.status });const image = await response.blob();if (!image.size) throw new Error("The device returned an empty screenshot. Try again.");return image;diff --git a/packages/client-runtime/src/mcpApps/host.test.ts b/packages/client-runtime/src/mcpApps/host.test.tsindex 85887707158..898588737c3 100644--- a/packages/client-runtime/src/mcpApps/host.test.ts+++ b/packages/client-runtime/src/mcpApps/host.test.ts@@ -206,7 +206,7 @@ describe("makeMcpAppHost", () => {const { host, sent } = setup({callTool: async (input) => {if (input.name === "delete_everything")- throw new McpAppHostRefusal("Declined by the user.");+ throw new McpAppHostRefusal({ message: "Declined by the user." });return { content: [], structuredContent: { ok: true } };},});@@ -311,7 +311,7 @@ describe("makeMcpAppHost", () => {updateModelContext: async (update) => void contexts.push(update),downloadFile: async (files) => {downloads.push(files);- if (files.length > 1) throw new McpAppHostRefusal("Declined by the user.");+ if (files.length > 1) throw new McpAppHostRefusal({ message: "Declined by the user." });},});initialize(host);diff --git a/packages/client-runtime/src/mcpApps/host.ts b/packages/client-runtime/src/mcpApps/host.tsindex 5eee10af433..847771fb09d 100644--- a/packages/client-runtime/src/mcpApps/host.ts+++ b/packages/client-runtime/src/mcpApps/host.ts@@ -3,6 +3,7 @@ import { MCP_APP_PROTOCOL_VERSION, type McpAppReference } from "@t3tools/shared/import * as Base64 from "effect/encoding/Base64";import * as Predicate from "effect/Predicate";import * as Result from "effect/Result";+import * as Schema from "effect/Schema";const MAX_MESSAGE_BYTES = 256 * 1024;const MAX_PENDING_REQUESTS = 16;@@ -71,7 +72,12 @@ export interface McpAppCallToolResult {readonly _meta?: unknown;}-export class McpAppHostRefusal extends Error {}+export class McpAppHostRefusal extends Schema.TaggedError<McpAppHostRefusal>()(+ "McpAppHostRefusal",+ { message: Schema.String },+) {}++const isMcpAppHostRefusal = Schema.is(McpAppHostRefusal);export interface McpAppHostOptions {readonly app: McpAppReference;@@ -141,7 +147,7 @@ function normalizeMcpAppToolResult(result: McpAppCallToolResult): McpAppCallTool}const errorMessage = (error: unknown) =>- error instanceof McpAppHostRefusal+ isMcpAppHostRefusal(error)? error.message: error instanceof Error && error.message.trim() !== ""? error.message@@ -342,7 +348,7 @@ export function makeMcpAppHost(options: McpAppHostOptions): McpAppHost {options.downloadFile(files).then(() => ({}),(error: unknown) =>- error instanceof McpAppHostRefusal ? { isError: true } : Promise.reject(error),+ isMcpAppHostRefusal(error) ? { isError: true } : Promise.reject(error),),);return;diff --git a/packages/client-runtime/src/platform/threadCacheEncoding.ts b/packages/client-runtime/src/platform/threadCacheEncoding.tsindex b7c233942de..f993ff3ec20 100644--- a/packages/client-runtime/src/platform/threadCacheEncoding.ts+++ b/packages/client-runtime/src/platform/threadCacheEncoding.ts@@ -2,7 +2,6 @@ import {omitLocalVisibleTurnItems,restoreLocalVisibleTurnItems,} from "@t3tools/shared/orchestrationV2BoundedSnapshot";-import * as Data from "effect/Data";import * as Effect from "effect/Effect";import * as Schema from "effect/Schema";@@ -23,7 +22,10 @@ const StoredCompactThreadSnapshot = StoredOrchestrationThreadSnapshot.mapFields(})),}));-class InvalidThreadCache extends Data.TaggedError("InvalidThreadCache") {}+class InvalidThreadCache extends Schema.TaggedError<InvalidThreadCache>()(+ "InvalidThreadCache",+ {},+) {}const encodeCompact = Schema.encodeEffect(Schema.fromJsonString(StoredCompactThreadSnapshot));const decodeCompatible = Schema.decodeUnknownEffect(diff --git a/packages/client-runtime/src/relay/dpopProof.ts b/packages/client-runtime/src/relay/dpopProof.tsindex 7d9822921cd..fcab7827882 100644--- a/packages/client-runtime/src/relay/dpopProof.ts+++ b/packages/client-runtime/src/relay/dpopProof.ts@@ -5,7 +5,7 @@ import * as Cache from "effect/Cache";import * as Clock from "effect/Clock";import * as Digest from "effect/crypto/Digest";import * as SecureRandom from "effect/crypto/SecureRandom";-import * as Data from "effect/Data";+import * as Schema from "effect/Schema";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";import * as Base64Url from "effect/encoding/Base64Url";@@ -18,10 +18,10 @@ import {ManagedRelayDpopSigner,} from "./managedRelay.ts";-export class DpopProofError extends Data.TaggedError("DpopProofError")<{- readonly message: string;- readonly cause?: unknown;-}> {}+export class DpopProofError extends Schema.TaggedError<DpopProofError>()("DpopProofError", {+ message: Schema.String,+ cause: Schema.optional(Schema.Defect()),+}) {}/** A P-256 proof key. `sign` returns the raw `r‖s` ES256 signature over the JWS signing input. */export interface DpopProofKey {diff --git a/packages/client-runtime/src/relay/managedRelayState.ts b/packages/client-runtime/src/relay/managedRelayState.tsindex 983ccc87ffa..5a4b9a62a54 100644--- a/packages/client-runtime/src/relay/managedRelayState.ts+++ b/packages/client-runtime/src/relay/managedRelayState.ts@@ -2,7 +2,6 @@ import type { EnvironmentId } from "@t3tools/contracts";import { decodeRelayJwt } from "@t3tools/shared/relayJwt";import * as Cause from "effect/Cause";import * as Clock from "effect/Clock";-import * as Data from "effect/Data";import * as Effect from "effect/Effect";import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";@@ -50,10 +49,13 @@ export interface ManagedRelayQueryEvent {readonly traceId?: string | null;}-export class ManagedRelaySessionError extends Data.TaggedError("ManagedRelaySessionError")<{- readonly message: string;- readonly cause?: unknown;-}> {}+export class ManagedRelaySessionError extends Schema.TaggedError<ManagedRelaySessionError>()(+ "ManagedRelaySessionError",+ {+ message: Schema.String,+ cause: Schema.optional(Schema.Defect()),+ },+) {}export const managedRelaySessionAtom = Atom.make<ManagedRelaySession | null>(null).pipe(Atom.keepAlive,diff --git a/packages/client-runtime/src/rpc/http.ts b/packages/client-runtime/src/rpc/http.tsindex 59aee1f45ff..5f32a6c3c08 100644--- a/packages/client-runtime/src/rpc/http.ts+++ b/packages/client-runtime/src/rpc/http.ts@@ -9,7 +9,6 @@ import {type EnvironmentScopeRequiredError,} from "@t3tools/contracts";import * as HttpObservability from "@t3tools/shared/httpObservability";-import * as Data from "effect/Data";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";@@ -20,52 +19,48 @@ import * as HttpApiClient from "effect/http-api/HttpApiClient";const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);-export class RemoteEnvironmentAuthFetchError extends Data.TaggedError(+export class RemoteEnvironmentAuthFetchError extends Schema.TaggedError<RemoteEnvironmentAuthFetchError>()("RemoteEnvironmentAuthFetchError",-)<{- readonly message: string;- readonly cause: unknown;-}> {}+ {+ message: Schema.String,+ cause: Schema.Defect(),+ },+) {}-class RemoteEnvironmentAuthInvalidJsonError extends Data.TaggedError(+class RemoteEnvironmentAuthInvalidJsonError extends Schema.TaggedError<RemoteEnvironmentAuthInvalidJsonError>()("RemoteEnvironmentAuthInvalidJsonError",-)<{- readonly message: string;- readonly cause: unknown;-}> {}+ {+ message: Schema.String,+ cause: Schema.Defect(),+ },+) {}-export class RemoteEnvironmentAuthUndeclaredStatusError extends Data.TaggedError(+export class RemoteEnvironmentAuthUndeclaredStatusError extends Schema.TaggedError<RemoteEnvironmentAuthUndeclaredStatusError>()("RemoteEnvironmentAuthUndeclaredStatusError",-)<{- readonly message: string;- readonly status: number;- readonly requestUrl: string;-}> {- constructor(requestUrl: string, status: number) {- super({- message: `Remote environment endpoint ${requestUrl} returned undeclared status ${status}.`,- requestUrl,- status,- });+ {+ status: Schema.Number,+ requestUrl: Schema.String,+ },+) {+ override get message(): string {+ return `Remote environment endpoint ${this.requestUrl} returned undeclared status ${this.status}.`;}}-export class RemoteEnvironmentAuthTimeoutError extends Data.TaggedError(+export class RemoteEnvironmentAuthTimeoutError extends Schema.TaggedError<RemoteEnvironmentAuthTimeoutError>()("RemoteEnvironmentAuthTimeoutError",-)<{- readonly message: string;- readonly requestUrl: string;- readonly timeoutMs: number;-}> {- constructor(requestUrl: string, timeoutMs: number) {- super({- message: `Remote environment endpoint ${requestUrl} timed out after ${timeoutMs}ms.`,- requestUrl,- timeoutMs,- });+ {+ requestUrl: Schema.String,+ timeoutMs: Schema.Number,+ },+) {+ override get message(): string {+ return `Remote environment endpoint ${this.requestUrl} timed out after ${this.timeoutMs}ms.`;}}+const isRemoteEnvironmentAuthTimeoutError = Schema.is(RemoteEnvironmentAuthTimeoutError);+export type RemoteEnvironmentRequestError =| EnvironmentRequestInvalidError| EnvironmentAuthInvalidError@@ -122,7 +117,7 @@ const failRemoteRequest = (requestUrl: string,cause: unknown,): Effect.Effect<never, RemoteEnvironmentRequestError> => {- if (cause instanceof RemoteEnvironmentAuthTimeoutError) {+ if (isRemoteEnvironmentAuthTimeoutError(cause)) {return Effect.fail(cause);}if (isEnvironmentHttpCommonError(cause)) {@@ -140,7 +135,7 @@ const failRemoteRequest = (const response = cause.response;if (response.status < 200 || response.status >= 300) {return Effect.fail(- new RemoteEnvironmentAuthUndeclaredStatusError(requestUrl, response.status),+ new RemoteEnvironmentAuthUndeclaredStatusError({ requestUrl, status: response.status }),);}return Effect.fail(@@ -167,7 +162,7 @@ export const executeEnvironmentHttpRequest = <A, E, R>(Effect.timeoutOption(Duration.millis(timeoutMs)),Effect.flatMap(Option.match({- onNone: () => Effect.fail(new RemoteEnvironmentAuthTimeoutError(requestUrl, timeoutMs)),+ onNone: () => Effect.fail(new RemoteEnvironmentAuthTimeoutError({ requestUrl, timeoutMs })),onSome: Effect.succeed,}),),diff --git a/packages/client-runtime/src/state/environmentHttpAuth.ts b/packages/client-runtime/src/state/environmentHttpAuth.tsindex 57ec7409540..f858c895aa3 100644--- a/packages/client-runtime/src/state/environmentHttpAuth.ts+++ b/packages/client-runtime/src/state/environmentHttpAuth.ts@@ -247,7 +247,10 @@ const executeEnvironmentRequest = Effect.fnUntraced(function* <duration: input.timeoutMs,orElse: () =>Effect.fail(- new RemoteEnvironmentAuthTimeoutError(requestUrlFor(httpBaseUrl), input.timeoutMs),+ new RemoteEnvironmentAuthTimeoutError({+ requestUrl: requestUrlFor(httpBaseUrl),+ timeoutMs: input.timeoutMs,+ }),),}),);diff --git a/packages/client-runtime/src/state/peerPairingCode.ts b/packages/client-runtime/src/state/peerPairingCode.tsindex 814eeb88d54..3ae9a076ada 100644--- a/packages/client-runtime/src/state/peerPairingCode.ts+++ b/packages/client-runtime/src/state/peerPairingCode.ts@@ -4,7 +4,7 @@* It carries exactly what an agent sign-in with the chosen access needs.*/import { type AuthMcpClientAccess, mcpClientScopes } from "@t3tools/contracts";-import * as Data from "effect/Data";+import * as Schema from "effect/Schema";import * as Effect from "effect/Effect";import type * as HttpClient from "effect/http/HttpClient";import * as Option from "effect/Option";@@ -23,10 +23,13 @@ const MINT_TIMEOUT_MS = 8_000;const PEER_PAIRING_CODE_LABEL = "T3 Code link";/** Minting failed; the user can still paste a code from the other environment. */-export class PeerPairingCodeError extends Data.TaggedError("PeerPairingCodeError")<{- readonly reason: "not_allowed" | "unavailable";- readonly cause: unknown;-}> {+export class PeerPairingCodeError extends Schema.TaggedError<PeerPairingCodeError>()(+ "PeerPairingCodeError",+ {+ reason: Schema.Literals(["not_allowed", "unavailable"]),+ cause: Schema.Defect(),+ },+) {override get message(): string {return this.reason === "not_allowed"? "Your session there cannot create pairing codes. Paste a code from there instead."diff --git a/packages/client-runtime/src/state/pullRequests.test.ts b/packages/client-runtime/src/state/pullRequests.test.tsindex b182beef900..6efc11818ce 100644--- a/packages/client-runtime/src/state/pullRequests.test.ts+++ b/packages/client-runtime/src/state/pullRequests.test.ts@@ -11,7 +11,7 @@ import {type AuthSessionState,} from "@t3tools/contracts";import { expect, it } from "@effect/vitest";-import * as Data from "effect/Data";+import * as Schema from "effect/Schema";import * as Deferred from "effect/Deferred";import * as Fiber from "effect/Fiber";import * as Effect from "effect/Effect";@@ -53,7 +53,7 @@ const trustedRouting = {forget: () => Effect.void,};-class MutationRefused extends Data.TaggedError("MutationRefused") {}+class MutationRefused extends Schema.TaggedError<MutationRefused>()("MutationRefused", {}) {}for (const scenario of ["prefers the local environment with the same github account",diff --git a/packages/client-runtime/src/state/pullRequests.ts b/packages/client-runtime/src/state/pullRequests.tsindex e6566f2b7d5..64ae5ae3df5 100644--- a/packages/client-runtime/src/state/pullRequests.ts+++ b/packages/client-runtime/src/state/pullRequests.ts@@ -24,7 +24,6 @@ import {type PullRequestSummary,type VcsStatusResult,} from "@t3tools/contracts";-import * as Data from "effect/Data";import * as Effect from "effect/Effect";import * as Schema from "effect/Schema";import { persistPullRequestStats } from "./pullRequestStatsPersistence.ts";@@ -53,9 +52,10 @@ export {export * as PullRequestDiffLoader from "./pullRequestDiffHttp.ts";/** @public Required to name the error in consumers' inferred pull request results. */-export class EnvironmentHttpConnectionNotReadyError extends Data.TaggedError(+export class EnvironmentHttpConnectionNotReadyError extends Schema.TaggedError<EnvironmentHttpConnectionNotReadyError>()("EnvironmentHttpConnectionNotReadyError",-)<{ readonly message: string }> {}+ { message: Schema.String },+) {}const LINKED_PULL_REQUEST_IDLE_TTL_MS = 5_000;diff --git a/packages/client-runtime/src/state/session.ts b/packages/client-runtime/src/state/session.tsindex 90afa29f9d0..9312ae048e6 100644--- a/packages/client-runtime/src/state/session.ts+++ b/packages/client-runtime/src/state/session.ts@@ -1,6 +1,6 @@import { pipe } from "effect/Function";import type { AuthSessionState, EnvironmentId, ServerConfig } from "@t3tools/contracts";-import * as Data from "effect/Data";+import * as Schema from "effect/Schema";import * as Effect from "effect/Effect";import * as Option from "effect/Option";import * as Stream from "effect/Stream";@@ -20,8 +20,9 @@ import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAutimport { followStreamInEnvironment } from "./environmentStreams.ts";/** @public Required to name the error in consumers' inferred session results. */-export class SessionHttpClientUnavailable extends Data.TaggedError(+export class SessionHttpClientUnavailable extends Schema.TaggedError<SessionHttpClientUnavailable>()("SessionHttpClientUnavailable",+ {},) {}function initialConfigOption<E>(diff --git a/packages/client-runtime/src/voice-input/controller.test.ts b/packages/client-runtime/src/voice-input/controller.test.tsindex 4b7f9a9c3d4..52069d1bd67 100644--- a/packages/client-runtime/src/voice-input/controller.test.ts+++ b/packages/client-runtime/src/voice-input/controller.test.ts@@ -120,10 +120,10 @@ describe("VoiceInputController", () => {expect(unsupported.controller.currentState.error).toContain("not available");expect(unsupported.recorder.record).not.toHaveBeenCalled();- const reason = new VoiceTranscriptionError(- "unavailable",- "This device requires iOS 26 or later.",- );+ const reason = new VoiceTranscriptionError({+ code: "unavailable",+ message: "This device requires iOS 26 or later.",+ });const unavailable = createHarness({getTranscriber: () => ({prepare: async () => {diff --git a/packages/client-runtime/src/voice-input/controller.ts b/packages/client-runtime/src/voice-input/controller.tsindex 41576db90cf..5b057c61fab 100644--- a/packages/client-runtime/src/voice-input/controller.ts+++ b/packages/client-runtime/src/voice-input/controller.ts@@ -1,3 +1,4 @@+import * as Schema from "effect/Schema";import { replaceTextRange } from "@t3tools/shared/composerTrigger";import {@@ -6,6 +7,8 @@ import {type VoiceTranscriber,} from "./transcription.ts";+const isVoiceTranscriptionError = Schema.is(VoiceTranscriptionError);+export const VOICE_RECORDING_LIMIT_SECONDS = 5 * 60;export type VoiceInputPhase = "idle" | "preparing" | "recording" | "transcribing" | "error";@@ -171,7 +174,7 @@ function preparationErrorMessage(error: unknown): string {if (errorCode(error) === "unsupported-locale") {return "Voice transcription is not available for this language.";}- return error instanceof VoiceTranscriptionError+ return isVoiceTranscriptionError(error)? error.message: "Could not prepare voice transcription.";}@@ -180,9 +183,7 @@ function transcriptionErrorMessage(error: unknown): string {if (error instanceof Error && error.message === "voice-operation-busy") {return "Voice transcription is still finishing. Try again shortly.";}- return error instanceof VoiceTranscriptionError- ? error.message- : "Could not transcribe this recording.";+ return isVoiceTranscriptionError(error) ? error.message : "Could not transcribe this recording.";}const IDLE_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null };diff --git a/packages/client-runtime/src/voice-input/transcription.ts b/packages/client-runtime/src/voice-input/transcription.tsindex 9e927f7caa5..4a8b1ab4e28 100644--- a/packages/client-runtime/src/voice-input/transcription.ts+++ b/packages/client-runtime/src/voice-input/transcription.ts@@ -1,3 +1,5 @@+import * as Schema from "effect/Schema";+/** Cancellation is cooperative: settle only after the underlying work has stopped. */export type VoiceTranscriptionOptions = {readonly signal: AbortSignal;@@ -12,25 +14,29 @@ export type VoiceTranscriber = {readonly prepare: (options: VoiceTranscriptionOptions) => Promise<PreparedVoiceTranscription>;};-export type VoiceTranscriptionErrorCode =- | "unavailable"- | "unsupported-locale"- | "preparation-failed"- | "transcription-failed"- | "cancelled";--export class VoiceTranscriptionError extends Error {- readonly code: VoiceTranscriptionErrorCode;+const VoiceTranscriptionErrorCode = Schema.Literals([+ "unavailable",+ "unsupported-locale",+ "preparation-failed",+ "transcription-failed",+ "cancelled",+]);+export type VoiceTranscriptionErrorCode = typeof VoiceTranscriptionErrorCode.Type;- constructor(code: VoiceTranscriptionErrorCode, message: string, options?: ErrorOptions) {- super(message, options);- this.name = "VoiceTranscriptionError";- this.code = code;- }-}+export class VoiceTranscriptionError extends Schema.TaggedError<VoiceTranscriptionError>()(+ "VoiceTranscriptionError",+ {+ code: VoiceTranscriptionErrorCode,+ message: Schema.String,+ cause: Schema.optional(Schema.Defect()),+ },+) {}export function throwIfVoiceTranscriptionAborted(signal: AbortSignal): void {if (signal.aborted) {- throw new VoiceTranscriptionError("cancelled", "Voice transcription was cancelled.");+ throw new VoiceTranscriptionError({+ code: "cancelled",+ message: "Voice transcription was cancelled.",+ });}}diff --git a/packages/provider-acp/src/server/mcpOverAcpBridge.ts b/packages/provider-acp/src/server/mcpOverAcpBridge.tsindex 662ef38912c..95c3d09e08e 100644--- a/packages/provider-acp/src/server/mcpOverAcpBridge.ts+++ b/packages/provider-acp/src/server/mcpOverAcpBridge.ts@@ -1,5 +1,6 @@// @effect-diagnostics globalJsonInEffect:offimport * as Effect from "effect/Effect";+import * as Schema from "effect/Schema";import * as Semaphore from "effect/Semaphore";import * as Stream from "effect/Stream";import type * as AcpSchema from "effect-acp/compat";@@ -23,15 +24,20 @@ interface Connection {nextRequestId: number;}-export class AcpMcpOverAcpError extends Error {- readonly _tag = "AcpMcpOverAcpError";- override readonly name = "AcpMcpOverAcpError";-}+export class AcpMcpOverAcpError extends Schema.TaggedError<AcpMcpOverAcpError>()(+ "AcpMcpOverAcpError",+ { message: Schema.String, cause: Schema.optional(Schema.Defect()) },+) {}++const isAcpMcpOverAcpError = Schema.is(AcpMcpOverAcpError);const bridgeError = (cause: unknown): AcpMcpOverAcpError =>- cause instanceof AcpMcpOverAcpError+ isAcpMcpOverAcpError(cause)? cause- : new AcpMcpOverAcpError(cause instanceof Error ? cause.message : String(cause), { cause });+ : new AcpMcpOverAcpError({+ message: cause instanceof Error ? cause.message : String(cause),+ cause,+ });const asEnvelope = (value: unknown): JsonRpcEnvelope | null =>typeof value === "object" && value !== null && !Array.isArray(value)@@ -88,7 +94,11 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(funEffect.suspend(() => {const connection = connections.get(connectionId);return connection === undefined- ? Effect.fail(new AcpMcpOverAcpError(`Unknown MCP-over-ACP connection "${connectionId}".`))+ ? Effect.fail(+ new AcpMcpOverAcpError({+ message: `Unknown MCP-over-ACP connection "${connectionId}".`,+ }),+ ): Effect.succeed(connection);});@@ -107,7 +117,7 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(funEffect.gen(function* () {const body = JSON.stringify(message);if (Buffer.byteLength(body) > MAX_MESSAGE_BYTES) {- return yield* Effect.fail(new AcpMcpOverAcpError("MCP-over-ACP message exceeds 8 MiB."));+ return yield* new AcpMcpOverAcpError({ message: "MCP-over-ACP message exceeds 8 MiB." });}const response = yield* Effect.tryPromise({try: (signal) =>@@ -134,9 +144,9 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(funyield* Effect.promise(() => response.body?.cancel().catch(() => undefined) ?? Promise.resolve(),);- return yield* Effect.fail(- new AcpMcpOverAcpError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`),- );+ return yield* new AcpMcpOverAcpError({+ message: `T3 Code MCP endpoint responded with HTTP ${response.status}.`,+ });}const payloads = [...(yield* Stream.runCollect(responsePayloads(response, bridgeError)))];for (const payload of payloads) {@@ -169,11 +179,9 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(funcatch: bridgeError,});if (!response.ok && response.status !== 404) {- return yield* Effect.fail(- new AcpMcpOverAcpError(- `T3 Code MCP endpoint rejected disconnect with HTTP ${response.status}.`,- ),- );+ return yield* new AcpMcpOverAcpError({+ message: `T3 Code MCP endpoint rejected disconnect with HTTP ${response.status}.`,+ });}yield* Effect.promise(() => response.body?.cancel().catch(() => undefined) ?? Promise.resolve(),@@ -185,12 +193,12 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(funreturn {connect: Effect.fn("mcpOverAcpBridge.connect")(function* (request) {if (request.serverId !== "t3-code") {- return yield* Effect.fail(- new AcpMcpOverAcpError(`Unknown ACP MCP server "${request.serverId}".`),- );+ return yield* new AcpMcpOverAcpError({+ message: `Unknown ACP MCP server "${request.serverId}".`,+ });}if (connections.size >= MAX_CONNECTIONS) {- return yield* Effect.fail(new AcpMcpOverAcpError("Too many MCP-over-ACP connections."));+ return yield* new AcpMcpOverAcpError({ message: "Too many MCP-over-ACP connections." });}const connectionId = yield* options.allocateConnectionId;connections.set(connectionId, {@@ -213,12 +221,12 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(funconst response = payloads.find((payload) => asEnvelope(payload)?.id === id);const envelope = asEnvelope(response);if (envelope === null) {- return yield* Effect.fail(- new AcpMcpOverAcpError("MCP server did not return a matching response."),- );+ return yield* new AcpMcpOverAcpError({+ message: "MCP server did not return a matching response.",+ });}if (envelope.error !== undefined) {- return yield* Effect.fail(new AcpMcpOverAcpError(errorMessage(envelope.error)));+ return yield* new AcpMcpOverAcpError({ message: errorMessage(envelope.error) });}return (envelope.result ?? null) as AcpSchema.MessageMcpResponse;}),diff --git a/packages/provider-cursor/src/server/CursorSdk.test.ts b/packages/provider-cursor/src/server/CursorSdk.test.tsindex bf5229c9642..60daa04365c 100644--- a/packages/provider-cursor/src/server/CursorSdk.test.ts+++ b/packages/provider-cursor/src/server/CursorSdk.test.ts@@ -6,6 +6,7 @@ import { vi } from "vite-plus/test";import * as CursorSdk from "./CursorSdk.ts";// Shaped like the SDK's minified class: the constructor is not named after the error.+// @effect-diagnostics-next-line extendsNativeError:off - mimics the Cursor SDK's own native Error class.class o extends Error {override name = "WriteIterableClosedError";}diff --git a/packages/provider-cursor/src/server/sdk.test.ts b/packages/provider-cursor/src/server/sdk.test.tsindex bd6de78dc38..350598df7da 100644--- a/packages/provider-cursor/src/server/sdk.test.ts+++ b/packages/provider-cursor/src/server/sdk.test.ts@@ -1,6 +1,7 @@import { describe, expect, it, vi } from "vite-plus/test";const fixture = vi.hoisted(() => {+ // @effect-diagnostics-next-line extendsNativeError:off - stands in for the Cursor SDK's native Error classes.class SdkError extends Error {}const sdk = {CursorSdkError: SdkError,diff --git a/packages/provider-grok/src/server/adapter.ts b/packages/provider-grok/src/server/adapter.tsindex 35a8794619d..9ed1368f169 100644--- a/packages/provider-grok/src/server/adapter.ts+++ b/packages/provider-grok/src/server/adapter.ts@@ -79,6 +79,8 @@ import {type AcpAdapterV2RuntimeInput,} from "@t3tools/provider-acp/server/adapter";+const isXAiPromptFailureText = Schema.is(XAiPromptFailureText);+export const GROK_PROVIDER = ProviderDriverKind.make("grok");const GROK_DRIVER_KIND = GROK_PROVIDER;export const GROK_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(GROK_DRIVER_KIND);@@ -306,10 +308,9 @@ export function makeGrokAcpAdapterFlavor(cause,...(isAcpRequestError(cause)? {- message:- cause.cause instanceof XAiPromptFailureText- ? cause.cause.message- : cause.errorMessage,+ message: isXAiPromptFailureText(cause.cause)+ ? cause.cause.message+ : cause.errorMessage,code: String(cause.code),class: cause.code === xAiRateLimitedErrorCode ? "usage_limit" : "provider_error",}diff --git a/packages/provider-grok/src/server/xaiAcpExtension.ts b/packages/provider-grok/src/server/xaiAcpExtension.tsindex d323c7d2413..fe356d0ec04 100644--- a/packages/provider-grok/src/server/xaiAcpExtension.ts+++ b/packages/provider-grok/src/server/xaiAcpExtension.ts@@ -1285,14 +1285,19 @@ function xAiPromptFailure(code: -32603,errorMessage: "Grok ended the turn with an error.",operation: "receive-response",- ...(agentResult === undefined ? {} : { cause: new XAiPromptFailureText(agentResult) }),+ ...(agentResult === undefined+ ? {}+ : { cause: new XAiPromptFailureText({ message: agentResult }) }),});}return null;}/** Keep unbounded provider text out of structured attributes; read only at presentation. */-export class XAiPromptFailureText extends Error {}+export class XAiPromptFailureText extends Schema.TaggedError<XAiPromptFailureText>()(+ "XAiPromptFailureText",+ { message: Schema.String },+) {}const registerXAiPromptCompletionFallback = (pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,diff --git a/packages/provider-opencode/src/server/OpenCodeRuntime.ts b/packages/provider-opencode/src/server/OpenCodeRuntime.tsindex f18ab07bbe1..fffda5ff823 100644--- a/packages/provider-opencode/src/server/OpenCodeRuntime.ts+++ b/packages/provider-opencode/src/server/OpenCodeRuntime.ts@@ -13,7 +13,6 @@ import {} from "@opencode-ai/sdk/v2";import * as Cause from "effect/Cause";import * as Context from "effect/Context";-import * as Data from "effect/Data";import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";import * as Exit from "effect/Exit";@@ -102,14 +101,18 @@ export interface OpenCodeServerConnection {}const OPENCODE_RUNTIME_ERROR_TAG = "OpenCodeRuntimeError";-export class OpenCodeRuntimeError extends Data.TaggedError(OPENCODE_RUNTIME_ERROR_TAG)<{- readonly operation: string;- readonly cause?: unknown;- readonly detail: string;- readonly reason?: OpenCodeStartupFailureReason;-}> {}--export type OpenCodeStartupFailureReason = "databaseLocked";+const OpenCodeStartupFailureReason = Schema.Literal("databaseLocked");+export type OpenCodeStartupFailureReason = typeof OpenCodeStartupFailureReason.Type;++export class OpenCodeRuntimeError extends Schema.TaggedError<OpenCodeRuntimeError>()(+ OPENCODE_RUNTIME_ERROR_TAG,+ {+ operation: Schema.String,+ cause: Schema.optional(Schema.Defect()),+ detail: Schema.String,+ reason: Schema.optional(OpenCodeStartupFailureReason),+ },+) {}// Classify stderr database locks at exit so callers need not parse diagnostics.function classifyStartupExit(stderr: string): OpenCodeStartupFailureReason | undefined {diff --git a/packages/provider-opencode/src/server/status.ts b/packages/provider-opencode/src/server/status.tsindex c113bd5551e..b14333445ce 100644--- a/packages/provider-opencode/src/server/status.ts+++ b/packages/provider-opencode/src/server/status.ts@@ -6,7 +6,7 @@ import {} from "@t3tools/contracts";import type { OpenCodeSettings } from "../settings.ts";import * as Cause from "effect/Cause";-import * as Data from "effect/Data";+import * as Schema from "effect/Schema";import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";import * as Schedule from "effect/Schedule";@@ -30,10 +30,12 @@ const OPENCODE_PRESENTATION = {showInteractionModeToggle: false,} as const;-class OpenCodeProbeError extends Data.TaggedError("OpenCodeProbeError")<{- readonly cause?: unknown;- readonly detail: string;-}> {}+class OpenCodeProbeError extends Schema.TaggedError<OpenCodeProbeError>()("OpenCodeProbeError", {+ cause: Schema.optional(Schema.Defect()),+ detail: Schema.String,+}) {}++const isOpenCodeProbeError = Schema.is(OpenCodeProbeError);function normalizeProbeMessage(message: string): string | undefined {const trimmed = message.trim();@@ -50,7 +52,7 @@ function normalizeProbeMessage(message: string): string | undefined {}function normalizedErrorMessage(cause: unknown): string | undefined {- if (cause instanceof OpenCodeProbeError) {+ if (isOpenCodeProbeError(cause)) {return normalizeProbeMessage(cause.detail);}diff --git a/packages/shared/src/Net.ts b/packages/shared/src/Net.tsindex 9210b3d1392..40ef669db4e 100644--- a/packages/shared/src/Net.ts+++ b/packages/shared/src/Net.ts@@ -1,15 +1,15 @@import * as NodeNet from "node:net";-import * as Data from "effect/Data";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Context from "effect/Context";import * as Predicate from "effect/Predicate";+import * as Schema from "effect/Schema";-export class NetError extends Data.TaggedError("NetError")<{- readonly message: string;- readonly cause?: unknown;-}> {}+export class NetError extends Schema.TaggedError<NetError>()("NetError", {+ message: Schema.String,+ cause: Schema.optional(Schema.Defect()),+}) {}const isErrnoExceptionWithCode = (cause: unknown,diff --git a/packages/shared/src/managedPolicyFile.ts b/packages/shared/src/managedPolicyFile.tsindex e6faf3b7112..2f775abb8a0 100644--- a/packages/shared/src/managedPolicyFile.ts+++ b/packages/shared/src/managedPolicyFile.ts@@ -186,14 +186,16 @@ const ERROR_NO_MORE_ITEMS = 259;// Value and key names are at most 16,383 characters.const MAX_NAME_CHARS = 16_384;-class Win32Failure extends Error {- readonly code: number;- constructor(code: number) {- super(`Windows error ${code}`);- this.code = code;+class Win32Failure extends Schema.TaggedError<Win32Failure>()("Win32Failure", {+ code: Schema.Number,+}) {+ override get message(): string {+ return `Windows error ${this.code}`;}}+const isWin32Failure = Schema.is(Win32Failure);+/*** Each app passes how it loads ffi-rs: a server single-executable resolves packages on disk only* through `require`, and the desktop's CommonJS bundle loads them with `import()`.@@ -263,7 +265,7 @@ export const layerWindowsRegistry = (loadFfi: () => Promise<typeof import("ffi-rconst handle = Buffer.alloc(8);const opened = api.open(subkey, handle);if (opened === ERROR_FILE_NOT_FOUND) return undefined;- if (opened !== 0) throw new Win32Failure(opened);+ if (opened !== 0) throw new Win32Failure({ code: opened });const key = handle.readBigInt64LE();try {const name = Buffer.alloc(MAX_NAME_CHARS * 2);@@ -285,7 +287,7 @@ export const layerWindowsRegistry = (loadFfi: () => Promise<typeof import("ffi-rcode = attempt();}if (code === ERROR_NO_MORE_ITEMS) break;- if (code !== 0) throw new Win32Failure(code);+ if (code !== 0) throw new Win32Failure({ code: code });const valueName = name.subarray(0, chars.readUInt32LE() * 2).toString("utf16le");const stored = data.subarray(0, bytes.readUInt32LE());const valueType = type.readUInt32LE();@@ -306,7 +308,7 @@ export const layerWindowsRegistry = (loadFfi: () => Promise<typeof import("ffi-rchars.writeUInt32LE(MAX_NAME_CHARS);const code = api.enumKey(key, index, name, chars);if (code === ERROR_NO_MORE_ITEMS) break;- if (code !== 0) throw new Win32Failure(code);+ if (code !== 0) throw new Win32Failure({ code: code });subkeys.push(name.subarray(0, chars.readUInt32LE() * 2).toString("utf16le"));}return { values, subkeys };@@ -322,7 +324,7 @@ export const layerWindowsRegistry = (loadFfi: () => Promise<typeof import("ffi-rtry: () => readKey(api, subkey),catch: (cause) =>new WindowsRegistryError(- cause instanceof Win32Failure ? { code: cause.code, cause } : { cause },+ isWin32Failure(cause) ? { code: cause.code, cause } : { cause },),});}),diff --git a/packages/shared/src/relayClient.ts b/packages/shared/src/relayClient.tsindex 7bce72d00d4..ae48676e6e1 100644--- a/packages/shared/src/relayClient.ts+++ b/packages/shared/src/relayClient.ts@@ -66,24 +66,33 @@ class RelayClientLockRemoveError extends Schema.TaggedError<RelayClientLockRemov}}-export class RelayClientInstallError extends Data.TaggedError("RelayClientInstallError")<{- readonly reason:- | "download_failed"- | "invalid_checksum"- | "install_locked"- | "managed_by_policy"- | "override_missing"- | "unsupported_platform"- | "validation_failed"- | "write_failed";- readonly message: string;- readonly cause?: unknown;-}> {}+export class RelayClientInstallError extends Schema.TaggedError<RelayClientInstallError>()(+ "RelayClientInstallError",+ {+ reason: Schema.Literals([+ "download_failed",+ "invalid_checksum",+ "install_locked",+ "managed_by_policy",+ "override_missing",+ "unsupported_platform",+ "validation_failed",+ "write_failed",+ ]),+ message: Schema.String,+ cause: Schema.optional(Schema.Defect()),+ },+) {}-class CloudflaredCommandError extends Data.TaggedError("CloudflaredCommandError")<{- readonly command: string;- readonly exitCode: number;-}> {}+const isRelayClientInstallError = Schema.is(RelayClientInstallError);++class CloudflaredCommandError extends Schema.TaggedError<CloudflaredCommandError>()(+ "CloudflaredCommandError",+ {+ command: Schema.String,+ exitCode: Schema.Number,+ },+) {}export interface CloudflaredReleaseAsset {readonly url: string;@@ -668,7 +677,7 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function}).pipe(Effect.scoped,Effect.catchIf(- (cause) => !(cause instanceof RelayClientInstallError),+ (cause) => !isRelayClientInstallError(cause),(cause) =>Effect.fail(new RelayClientInstallError({diff --git a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts b/packages/source-control-github/src/server/GitHubSourceControlProvider.tsindex 8583797a968..0048560977c 100644--- a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts+++ b/packages/source-control-github/src/server/GitHubSourceControlProvider.ts@@ -1,5 +1,4 @@import { settingsSecretLiteral, SourceControlProviderKind } from "@t3tools/contracts";-import * as Data from "effect/Data";import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";@@ -318,10 +317,10 @@ export const makeDiscovery = Effect.gen(function* () {} satisfies SourceControlManagedCliDiscoverySpec;});-class GitHubFailure extends Data.TaggedError("GitHubFailure")<{- readonly detail: string;- readonly cause: unknown;-}> {}+class GitHubFailure extends Schema.TaggedError<GitHubFailure>()("GitHubFailure", {+ detail: Schema.String,+ cause: Schema.Defect(),+}) {}const failure = (detail: string, cause?: unknown) => new GitHubFailure({ detail, cause });diff --git a/packages/ssh/src/errors.ts b/packages/ssh/src/errors.tsindex f1ba40b560c..4199e2a2445 100644--- a/packages/ssh/src/errors.ts+++ b/packages/ssh/src/errors.ts@@ -1,47 +1,62 @@-import * as Data from "effect/Data";--export class SshHostDiscoveryError extends Data.TaggedError("SshHostDiscoveryError")<{- readonly message: string;- readonly cause: unknown;-}> {}--export class SshInvalidTargetError extends Data.TaggedError("SshInvalidTargetError")<{- readonly message: string;-}> {}--export class SshCommandError extends Data.TaggedError("SshCommandError")<{- readonly message: string;- readonly command: readonly string[];- readonly exitCode: number | null;- readonly stderr: string;- readonly stdout?: string;- readonly cause?: unknown;-}> {}--export class SshLaunchError extends Data.TaggedError("SshLaunchError")<{- readonly message: string;- readonly stdout: string;- readonly cause?: unknown;-}> {}--export class SshPairingError extends Data.TaggedError("SshPairingError")<{- readonly message: string;- readonly stdout: string;- readonly cause?: unknown;-}> {}--export class SshHttpBridgeError extends Data.TaggedError("SshHttpBridgeError")<{- readonly message: string;- readonly status?: number;- readonly cause?: unknown;-}> {}--export class SshReadinessError extends Data.TaggedError("SshReadinessError")<{- readonly message: string;- readonly cause?: unknown;-}> {}--export class SshPasswordPromptError extends Data.TaggedError("SshPasswordPromptError")<{- readonly message: string;- readonly cause?: unknown;-}> {}+import * as Schema from "effect/Schema";++export class SshHostDiscoveryError extends Schema.TaggedError<SshHostDiscoveryError>()(+ "SshHostDiscoveryError",+ {+ message: Schema.String,+ cause: Schema.Defect(),+ },+) {}++export class SshInvalidTargetError extends Schema.TaggedError<SshInvalidTargetError>()(+ "SshInvalidTargetError",+ {+ message: Schema.String,+ },+) {}++export class SshCommandError extends Schema.TaggedError<SshCommandError>()("SshCommandError", {+ message: Schema.String,+ command: Schema.Array(Schema.String),+ exitCode: Schema.NullOr(Schema.Number),+ stderr: Schema.String,+ stdout: Schema.optional(Schema.String),+ cause: Schema.optional(Schema.Defect()),+}) {}++export class SshLaunchError extends Schema.TaggedError<SshLaunchError>()("SshLaunchError", {+ message: Schema.String,+ stdout: Schema.String,+ cause: Schema.optional(Schema.Defect()),+}) {}++export class SshPairingError extends Schema.TaggedError<SshPairingError>()("SshPairingError", {+ message: Schema.String,+ stdout: Schema.String,+ cause: Schema.optional(Schema.Defect()),+}) {}++export class SshHttpBridgeError extends Schema.TaggedError<SshHttpBridgeError>()(+ "SshHttpBridgeError",+ {+ message: Schema.String,+ status: Schema.optional(Schema.Number),+ cause: Schema.optional(Schema.Defect()),+ },+) {}++export class SshReadinessError extends Schema.TaggedError<SshReadinessError>()(+ "SshReadinessError",+ {+ message: Schema.String,+ cause: Schema.optional(Schema.Defect()),+ },+) {}++export class SshPasswordPromptError extends Schema.TaggedError<SshPasswordPromptError>()(+ "SshPasswordPromptError",+ {+ message: Schema.String,+ cause: Schema.optional(Schema.Defect()),+ },+) {}diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.tsindex b0ff65cba3a..663f30fb40c 100644--- a/packages/ssh/src/tunnel.test.ts+++ b/packages/ssh/src/tunnel.test.ts@@ -8,6 +8,7 @@ import * as Effect from "effect/Effect";import * as Fiber from "effect/Fiber";import * as Layer from "effect/Layer";import * as PlatformError from "effect/PlatformError";+import * as Schema from "effect/Schema";import * as Result from "effect/Result";import * as Sink from "effect/Sink";import * as Stream from "effect/Stream";@@ -19,6 +20,8 @@ import * as SshAuth from "./auth.ts";import { SshCommandError, SshPasswordPromptError } from "./errors.ts";import * as SshTunnel from "./tunnel.ts";+const isSshCommandError = Schema.is(SshCommandError);+const makeSuccessfulProcess = (stdout: string) => {const stdoutStream = Stream.make(new TextEncoder().encode(stdout));return ChildProcessSpawner.makeHandle({@@ -202,7 +205,7 @@ describe("ssh tunnel scripts", () => {assert.isTrue(Result.isFailure(result));if (Result.isFailure(result)) {assert.instanceOf(result.failure, SshCommandError);- if (result.failure instanceof SshCommandError) {+ if (isSshCommandError(result.failure)) {assert.equal(result.failure.exitCode, 1);assert.equal(result.failure.stderr.length, 16_384);assert.isTrue(result.failure.stderr.endsWith(diagnostic));@@ -260,7 +263,7 @@ describe("ssh tunnel scripts", () => {assert.isTrue(Result.isFailure(result));if (Result.isFailure(result)) {assert.instanceOf(result.failure, SshCommandError);- if (result.failure instanceof SshCommandError) {+ if (isSshCommandError(result.failure)) {assert.equal(result.failure.exitCode, 255);assert.equal(result.failure.stderr, diagnostic);}@@ -337,7 +340,7 @@ describe("ssh tunnel scripts", () => {if (Result.isFailure(result)) {if (expectedPromptAttempts.length === 0) {assert.instanceOf(result.failure, SshCommandError);- if (result.failure instanceof SshCommandError) {+ if (isSshCommandError(result.failure)) {assert.equal(result.failure.stderr, stderr);}} else {diff --git a/scripts/mobile-e2e/device.ts b/scripts/mobile-e2e/device.tsindex 7aac025443c..f27092d35dc 100644--- a/scripts/mobile-e2e/device.ts+++ b/scripts/mobile-e2e/device.ts@@ -3,6 +3,7 @@import * as NodeChildProcess from "node:child_process";import * as NodePath from "node:path";import * as NodeProcess from "node:process";+import * as Schema from "effect/Schema";import type { Snapshot } from "./checks.ts";import type { Pose } from "./poses.ts";@@ -61,7 +62,11 @@ export interface Pool {readonly env: NodeJS.ProcessEnv;}-class AgentDeviceError extends Error {}+class AgentDeviceError extends Schema.TaggedError<AgentDeviceError>()("AgentDeviceError", {+ message: Schema.String,+}) {}++const isAgentDeviceError = Schema.is(AgentDeviceError);// A shared pool's workers drop off the gateway and stall under load for seconds at a time.const TRANSIENT =@@ -112,7 +117,7 @@ export class Device {try {return await this.agentOnce(args, options);} catch (error) {- if (attempt >= 5 || !(error instanceof AgentDeviceError) || !TRANSIENT.test(error.message))+ if (attempt >= 5 || !isAgentDeviceError(error) || !TRANSIENT.test(error.message))throw error;await delay(5_000 * attempt);}@@ -137,10 +142,14 @@ export class Device {try {parsed = JSON.parse(stdout);} catch {- throw new AgentDeviceError(`agent-device ${args[0]}: ${(stderr || stdout).slice(-400)}`);+ throw new AgentDeviceError({+ message: `agent-device ${args[0]}: ${(stderr || stdout).slice(-400)}`,+ });}if (!parsed.success)- throw new AgentDeviceError(`agent-device ${args.join(" ")}: ${parsed.error?.message}`);+ throw new AgentDeviceError({+ message: `agent-device ${args.join(" ")}: ${parsed.error?.message}`,+ });return parsed.data ?? {};}diff --git a/tsconfig.effect.json b/tsconfig.effect.jsonindex dab2c98e771..144cd46b5c9 100644--- a/tsconfig.effect.json+++ b/tsconfig.effect.json@@ -98,6 +98,8 @@"unnecessaryTypeofType": "error","effectTryWithoutCatch": "error","processEnvInEffect": "error",+ "preferSchemaTaggedError": "error",+ "extendsNativeError": "error","schemaNumber": "off"},"overrides": [