@devries-cameron20 / t3code Mirror · read-only / commits / 298cb24140
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 04:30 UTC

refactor: errors are Schema.TaggedError, not Data.TaggedError or native Error (#31216)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 4, 2026 at 20:05 UTC 298cb24140fdddebfbfaedad3a097e86ff3d9d04
87 files changed +903 -673
apps/desktop/src/ipc/methods/sshEnvironment.ts
+18 -15
@@ -26,7 +26,6 @@ import {
26 } from "@t3tools/contracts";
27 import { SshHttpBridgeError } from "@t3tools/ssh/errors";
28 import { resolveLoopbackSshHttpBaseUrl } from "@t3tools/ssh/tunnel";
29 -import * as Data from "effect/Data";
29 import * as Effect from "effect/Effect";
30 import * as Schema from "effect/Schema";
31
@@ -35,10 +34,12 @@ import * as DesktopIpc from "../DesktopIpc.ts";
34 import * as DesktopSshEnvironment from "../../ssh/DesktopSshEnvironment.ts";
35 import * as DesktopSshPasswordPrompts from "../../ssh/DesktopSshPasswordPrompts.ts";
36
38 -type DesktopSshEnvironmentRequestOperation =
39 - | "fetch-environment-descriptor"
40 - | "bootstrap-bearer-session"
41 - | "fetch-session-state";
37 +const DesktopSshEnvironmentRequestOperation = Schema.Literals([
38 + "fetch-environment-descriptor",
39 + "bootstrap-bearer-session",
40 + "fetch-session-state",
41 +]);
42 +type DesktopSshEnvironmentRequestOperation = typeof DesktopSshEnvironmentRequestOperation.Type;
43
44 type DesktopSshEnvironmentRequestCause = RemoteEnvironmentAuthError | SshHttpBridgeError;
45
@@ -47,12 +48,13 @@ const isEnvironmentInternalError = Schema.is(EnvironmentInternalError);
48 const isEnvironmentOperationForbiddenError = Schema.is(EnvironmentOperationForbiddenError);
49 const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError);
50 const isEnvironmentScopeRequiredError = Schema.is(EnvironmentScopeRequiredError);
51 +const isRemoteEnvironmentAuthUndeclaredStatusError = Schema.is(
52 + RemoteEnvironmentAuthUndeclaredStatusError,
53 +);
54 +const isSshHttpBridgeError = Schema.is(SshHttpBridgeError);
55
56 function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | null {
52 - if (
53 - cause instanceof RemoteEnvironmentAuthUndeclaredStatusError ||
54 - cause instanceof SshHttpBridgeError
55 - ) {
57 + if (isRemoteEnvironmentAuthUndeclaredStatusError(cause) || isSshHttpBridgeError(cause)) {
58 return cause.status ?? null;
59 }
60 if (isEnvironmentRequestInvalidError(cause)) {
@@ -73,13 +75,14 @@ function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | n
75 return null;
76 }
77
76 -export class DesktopSshEnvironmentRequestError extends Data.TaggedError(
78 +export class DesktopSshEnvironmentRequestError extends Schema.TaggedError<DesktopSshEnvironmentRequestError>()(
79 "DesktopSshEnvironmentRequestError",
78 -)<{
79 - readonly operation: DesktopSshEnvironmentRequestOperation;
80 - readonly cause: DesktopSshEnvironmentRequestCause;
81 - readonly sshHttpStatus: number | null;
82 -}> {
80 + {
81 + operation: DesktopSshEnvironmentRequestOperation,
82 + cause: Schema.Defect(),
83 + sshHttpStatus: Schema.NullOr(Schema.Number),
84 + },
85 +) {
86 // The web client matches "[ssh_http:500]" to explain version-skewed SSH pairing.
87 override get message() {
88 const prefix = this.sshHttpStatus === null ? "" : `[ssh_http:${this.sshHttpStatus}] `;
apps/desktop/src/snapShot/DesktopSnapShot.test.ts
+3 -1
@@ -1872,7 +1872,9 @@ it.effect("capture fails closed while snapshots are disabled", () => {
1872
1873 it.effect("points capture setup failures at SnapShot settings", () => {
1874 vi.stubEnv("XDG_SESSION_TYPE", "wayland");
1875 - linuxCaptureMock.mockRejectedValueOnce(new CaptureSetupRequiredError("Install the helper."));
1875 + linuxCaptureMock.mockRejectedValueOnce(
1876 + new CaptureSetupRequiredError({ state: "Install the helper." }),
1877 + );
1878 return Effect.scoped(
1879 Effect.gen(function* () {
1880 const service = yield* DesktopSnapShot.make;
apps/desktop/src/snapShot/DesktopSnapShot.ts
+3 -1
@@ -94,6 +94,8 @@ import {
94 import * as HostProcess from "@t3tools/shared/HostProcess";
95 import { readImageDimensions } from "@t3tools/shared/imageDimensions";
96
97 +const isCaptureSetupRequiredError = Schema.is(CaptureSetupRequiredError);
98 +
99 const MAX_CAPTURE_WIDTH = 2_560;
100 const MAX_CAPTURE_HEIGHT = 1_600;
101 const SHORTCUT_COOLDOWN_NS = 200_000_000n;
@@ -180,7 +182,7 @@ const shortcutFailure = (cause: unknown) => new SnapShotShortcutError({ cause })
182
183 function captureFailure(cause: unknown, captureId?: string): DesktopSnapShotError {
184 if (isDesktopSnapShotError(cause)) return cause;
183 - const operation = cause instanceof CaptureSetupRequiredError ? "setup-required" : "capture";
185 + const operation = isCaptureSetupRequiredError(cause) ? "setup-required" : "capture";
186 return new DesktopSnapShotError({ operation, captureId, cause });
187 }
188
apps/desktop/src/snapShot/HyprlandSnapShot.ts
+2 -2
@@ -171,11 +171,11 @@ export async function captureHyprlandWindow(
171 let state = await setup.state();
172 if (state.status === "update-required") {
173 await setup.perform("install-hyprland-helper").catch((cause: unknown) => {
174 - throw new CaptureSetupRequiredError(state.message, { cause });
174 + throw new CaptureSetupRequiredError({ state: state.message, cause });
175 });
176 state = await setup.state();
177 }
178 - if (state.status !== "ready") throw new CaptureSetupRequiredError(state.message);
178 + if (state.status !== "ready") throw new CaptureSetupRequiredError({ state: state.message });
179 const executable = hyprlandCaptureExecutable(paths);
180 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-hyprland-capture-"));
181 const cleanup = () => NodeFSP.rm(directory, { recursive: true, force: true });
apps/desktop/src/snapShot/KdeSnapShot.ts
+1 -1
@@ -215,7 +215,7 @@ export async function captureKdeWindow(
215 options?: { readonly flash: boolean; readonly animate: boolean },
216 ): Promise<LinuxWindowSnapshot> {
217 const state = await new KdeCaptureSetup(paths).state();
218 - if (state.status !== "ready") throw new CaptureSetupRequiredError(state.message);
218 + if (state.status !== "ready") throw new CaptureSetupRequiredError({ state: state.message });
219 const { executable } = kdeCapturePaths(paths);
220 const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-kde-capture-"));
221 let retained = false;
apps/desktop/src/snapShot/linuxCaptureSession.ts
+7 -3
@@ -2,15 +2,19 @@
2 import * as NodeFSP from "node:fs/promises";
3 import * as NodeURL from "node:url";
4 import type { SnapShotKeyChord } from "@t3tools/contracts";
5 +import * as Schema from "effect/Schema";
6 import { nativeImage } from "electron";
7
8 // Keep dbus-next out of desktop detection and PNG reads in the main process.
9
10 export const HYPRLAND_CAPTURE_ACTION = "capture-window";
11
11 -export class CaptureSetupRequiredError extends Error {
12 - constructor(state: string, options?: ErrorOptions) {
13 - super(`${state} Open Settings → SnapShots to continue setup.`, options);
12 +export class CaptureSetupRequiredError extends Schema.TaggedError<CaptureSetupRequiredError>()(
13 + "CaptureSetupRequiredError",
14 + { state: Schema.String, cause: Schema.optional(Schema.Defect()) },
15 +) {
16 + override get message(): string {
17 + return `${this.state} Open Settings → SnapShots to continue setup.`;
18 }
19 }
20 export const NIRI_CAPTURE_PATH = "/com/t3tools/SnapShot";
apps/desktop/src/ssh/DesktopSshEnvironment.ts
+4 -1
@@ -23,6 +23,7 @@ import * as Effect from "effect/Effect";
23 import * as FileSystem from "effect/FileSystem";
24 import * as Layer from "effect/Layer";
25 import * as Path from "effect/Path";
26 +import * as Schema from "effect/Schema";
27 import * as HttpClient from "effect/http/HttpClient";
28 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
29
@@ -74,11 +75,13 @@ function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) {
75 return discoverSshHosts(input ?? {});
76 }
77
78 +const isSshPasswordPromptError = Schema.is(SshPasswordPromptError);
79 +
80 export function isDesktopSshPasswordPromptCancellation(
81 error: unknown,
82 ): error is SshPasswordPromptError {
83 return (
81 - error instanceof SshPasswordPromptError &&
84 + isSshPasswordPromptError(error) &&
85 DesktopSshPasswordPrompts.isDesktopSshPasswordPromptCancellation(error.cause)
86 );
87 }
apps/mobile/src/components/FilePreviewModal.tsx
+20 -13
@@ -1,3 +1,4 @@
1 +import * as Schema from "effect/Schema";
2 import * as Dialog from "./ui/Dialog";
3 import { useContext, useEffect, useEffectEvent, useState } from "react";
4 import { Platform } from "react-native";
@@ -21,15 +22,17 @@ export type {
22 ResolvedFilePreviewSource,
23 } from "./FilePreviewModal.types";
24
24 -class PreviewResolutionError extends Error {
25 - constructor(
26 - override readonly cause: unknown,
27 - readonly fallbackMessage: string,
28 - ) {
29 - super(fallbackMessage, { cause });
25 +class PreviewResolutionError extends Schema.TaggedError<PreviewResolutionError>()(
26 + "PreviewResolutionError",
27 + { cause: Schema.Defect(), fallbackMessage: Schema.String },
28 +) {
29 + override get message(): string {
30 + return this.fallbackMessage;
31 }
32 }
33
34 +const isPreviewResolutionError = Schema.is(PreviewResolutionError);
35 +
36 interface ResolvedPreviewUri {
37 readonly uri: string;
38 readonly dispose?: () => void;
@@ -42,7 +45,10 @@ async function resolvePreviewUri(
45 if ("uri" in item) return { uri: item.uri };
46 if ("attachment" in item) {
47 return loadLocalAttachmentPreview(item.attachment, signal).catch((error: unknown) => {
45 - throw new PreviewResolutionError(error, "Attach the file again and retry.");
48 + throw new PreviewResolutionError({
49 + cause: error,
50 + fallbackMessage: "Attach the file again and retry.",
51 + });
52 });
53 }
54 // Refresh expired URLs before handing them to Quick Look or ACTION_VIEW, which retain them.
@@ -52,10 +58,11 @@ async function resolvePreviewUri(
58 return value;
59 })
60 .catch((error: unknown) => {
55 - throw new PreviewResolutionError(
56 - error,
57 - "Reconnect to this environment and try again. The file may have been moved or deleted.",
58 - );
61 + throw new PreviewResolutionError({
62 + cause: error,
63 + fallbackMessage:
64 + "Reconnect to this environment and try again. The file may have been moved or deleted.",
65 + });
66 });
67 return { uri: url + (item.srcFragment ?? "") };
68 }
@@ -99,9 +106,9 @@ function ResolvedFilePreview(props: {
106 if (progressiveGallery && index !== selectedIndex) return settle(index, null);
107 controller.abort();
108 onResolutionError(
102 - error instanceof PreviewResolutionError
109 + isPreviewResolutionError(error)
110 ? error
104 - : new PreviewResolutionError(error, "Try again."),
111 + : new PreviewResolutionError({ cause: error, fallbackMessage: "Try again." }),
112 );
113 },
114 );
apps/mobile/src/features/cloud/dpop.ts
+4 -5
@@ -1,6 +1,5 @@
1 import * as Digest from "effect/crypto/Digest";
2 import * as SecureRandom from "effect/crypto/SecureRandom";
3 -import * as Data from "effect/Data";
3 import * as Effect from "effect/Effect";
4 import * as Base64Url from "effect/encoding/Base64Url";
5 import * as Hex from "effect/encoding/Hex";
@@ -13,10 +12,10 @@ import { DpopProof } from "@t3tools/client-runtime/relay";
12 import { DpopPublicJwk } from "@t3tools/shared/dpopCommon";
13 import * as Layer from "effect/Layer";
14
16 -export class CloudDpopError extends Data.TaggedError("CloudDpopError")<{
17 - readonly message: string;
18 - readonly cause?: unknown;
19 -}> {}
15 +export class CloudDpopError extends Schema.TaggedError<CloudDpopError>()("CloudDpopError", {
16 + message: Schema.String,
17 + cause: Schema.optional(Schema.Defect()),
18 +}) {}
19
20 function cloudDpopError(message: string) {
21 return (cause: unknown) => new CloudDpopError({ message, cause });
apps/mobile/src/features/cloud/linkEnvironment.ts
+8 -6
@@ -1,4 +1,3 @@
1 -import * as Data from "effect/Data";
1 import * as Effect from "effect/Effect";
2 import * as Schema from "effect/Schema";
3 import { HttpClient } from "effect/http";
@@ -26,11 +25,14 @@ function readRelayUrl(): string | null {
25 return resolveCloudPublicConfig().relay.url;
26 }
27
29 -export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
30 - readonly message: string;
31 - readonly cause?: unknown;
32 - readonly traceId?: string;
33 -}> {}
28 +export class CloudEnvironmentLinkError extends Schema.TaggedError<CloudEnvironmentLinkError>()(
29 + "CloudEnvironmentLinkError",
30 + {
31 + message: Schema.String,
32 + cause: Schema.optional(Schema.Defect()),
33 + traceId: Schema.optional(Schema.String),
34 + },
35 +) {}
36
37 const isEnvironmentCloudApiError = Schema.is(
38 Schema.Union([
apps/mobile/src/features/files/ZipArchiveView.tsx
+24 -16
@@ -12,6 +12,7 @@ import {
12 hostPreviewMimeTypeFromExtension,
13 } from "@t3tools/shared/filePreview";
14 import { LegendList } from "@legendapp/list/react-native";
15 +import * as Schema from "effect/Schema";
16 import { fetch } from "expo/fetch";
17 import { File } from "expo-file-system";
18 import { useNavigation, usePreventRemove } from "@react-navigation/native";
@@ -68,11 +69,12 @@ interface ZipArchive {
69 readonly fileCount: number;
70 }
71
71 -interface ZipFailure {
72 - readonly title: string;
73 - readonly detail: string;
74 - readonly retry: boolean;
75 -}
72 +const ZipFailure = Schema.Struct({
73 + title: Schema.String,
74 + detail: Schema.String,
75 + retry: Schema.Boolean,
76 +});
77 +type ZipFailure = typeof ZipFailure.Type;
78
79 const SAVE_ZIP_HINT = "Save the ZIP to open it in another app.";
80 const TOO_LARGE: ZipFailure = {
@@ -91,12 +93,16 @@ const NETWORK: ZipFailure = {
93 retry: true,
94 };
95
94 -class ZipFailureError extends Error {
95 - constructor(readonly failure: ZipFailure) {
96 - super(failure.title);
96 +class ZipFailureError extends Schema.TaggedError<ZipFailureError>()("ZipFailureError", {
97 + failure: ZipFailure,
98 +}) {
99 + override get message(): string {
100 + return this.failure.title;
101 }
102 }
103
104 +const isZipFailureError = Schema.is(ZipFailureError);
105 +
106 function errorMessage(cause: unknown, fallback: string) {
107 return cause instanceof Error ? cause.message : fallback;
108 }
@@ -113,7 +119,7 @@ async function readArchiveBody(
119 const { value, done } = await reader.read();
120 if (done) break;
121 size += value.byteLength;
116 - if (size > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE);
122 + if (size > ARCHIVE_MAX_BYTES) throw new ZipFailureError({ failure: TOO_LARGE });
123 chunks.push(value);
124 onProgress(size);
125 }
@@ -135,9 +141,11 @@ async function openArchive(bytes: ArrayBuffer): Promise<ZipArchive> {
141 files = await boundedZip(bytes);
142 } catch (cause) {
143 throw new ZipFailureError({
138 - title: "Couldn't browse this ZIP",
139 - detail: `${errorMessage(cause, "It may be incomplete or damaged.")} ${SAVE_ZIP_HINT}`,
140 - retry: false,
144 + failure: {
145 + title: "Couldn't browse this ZIP",
146 + detail: `${errorMessage(cause, "It may be incomplete or damaged.")} ${SAVE_ZIP_HINT}`,
147 + retry: false,
148 + },
149 });
150 }
151 const entries = [...files].map(([path, file]): ZipEntry => {
@@ -187,15 +195,15 @@ function useZipArchive(input: {
195 // oxlint-disable-next-line react/set-state-in-effect -- A new archive load resets its progress.
196 setState({ status: "loading", receivedBytes: 0, timeLeft: null });
197 void (async () => {
190 - if (sizeBytes > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE);
198 + if (sizeBytes > ARCHIVE_MAX_BYTES) throw new ZipFailureError({ failure: TOO_LARGE });
199 if (isLocal) {
200 const file = new File(uri);
193 - if ((file.size ?? 0) > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE);
201 + if ((file.size ?? 0) > ARCHIVE_MAX_BYTES) throw new ZipFailureError({ failure: TOO_LARGE });
202 return openArchive(await file.arrayBuffer());
203 }
204 const url = (await refresh()) ?? uri;
205 const response = await fetch(url, { signal: abort.signal });
198 - if (!response.ok || !response.body) throw new ZipFailureError(NETWORK);
206 + if (!response.ok || !response.body) throw new ZipFailureError({ failure: NETWORK });
207 const bytes = await readArchiveBody(response.body, (receivedBytes) =>
208 setState({
209 status: "loading",
@@ -217,7 +225,7 @@ function useZipArchive(input: {
225 if (!abort.signal.aborted)
226 setState({
227 status: "failed",
220 - failure: cause instanceof ZipFailureError ? cause.failure : NETWORK,
228 + failure: isZipFailureError(cause) ? cause.failure : NETWORK,
229 });
230 });
231 return () => abort.abort();
apps/mobile/src/features/files/sourceHighlightingState.ts
+5 -3
@@ -1,5 +1,6 @@
1 import * as Data from "effect/Data";
2 import * as Effect from "effect/Effect";
3 +import * as Schema from "effect/Schema";
4 import { Atom } from "effect/reactivity";
5
6 import { resolveHighlightLanguage } from "../../lib/highlightLanguage";
@@ -15,9 +16,10 @@ export interface SourceHighlightInput {
16
17 class SourceHighlightCacheKey extends Data.Class<SourceHighlightInput> {}
18
18 -class SourceHighlightError extends Data.TaggedError("SourceHighlightError")<{
19 - readonly cause: unknown;
20 -}> {}
19 +class SourceHighlightError extends Schema.TaggedError<SourceHighlightError>()(
20 + "SourceHighlightError",
21 + { cause: Schema.Defect() },
22 +) {}
23
24 // Highlighting is synchronous, so a cold atom resolves on its first read. The
25 // family keeps results for files the user moves between.
apps/mobile/src/features/threads/McpAppWebView.tsx
+16 -12
@@ -69,9 +69,10 @@ const commandFailure = (result: {
69 readonly cause: Parameters<typeof squashAtomCommandFailure>[0]["cause"];
70 }) => {
71 const error = squashAtomCommandFailure(result);
72 - return new McpAppHostRefusal(
73 - error instanceof Error && error.message.trim() !== "" ? error.message : "Request failed.",
74 - );
72 + return new McpAppHostRefusal({
73 + message:
74 + error instanceof Error && error.message.trim() !== "" ? error.message : "Request failed.",
75 + });
76 };
77
78 const confirm = (title: string, message: string, action: string) =>
@@ -320,7 +321,8 @@ export function ThreadMcpApp(props: {
321 const { environmentId, input } = scope();
322 const info = await latest.current.toolInfo({ environmentId, input: { ...input, name } });
323 if (info._tag !== "Success") throw commandFailure(info);
323 - if (!info.value.callable) throw new McpAppHostRefusal("This app cannot call that tool.");
324 + if (!info.value.callable)
325 + throw new McpAppHostRefusal({ message: "This app cannot call that tool." });
326 if (
327 !info.value.readOnly &&
328 !(await confirm(
@@ -329,7 +331,7 @@ export function ThreadMcpApp(props: {
331 "Allow",
332 ))
333 ) {
332 - throw new McpAppHostRefusal("Declined by the user.");
334 + throw new McpAppHostRefusal({ message: "Declined by the user." });
335 }
336 const result = await latest.current.callTool({
337 environmentId,
@@ -350,15 +352,15 @@ export function ThreadMcpApp(props: {
352 openLink: async (url) => {
353 // WebViews cannot prove user activation; confirm links to prevent timer-driven navigation out of T3.
354 if (!(await confirm(`Open a link from ${app.server}?`, url, "Open"))) {
353 - throw new McpAppHostRefusal("Declined by the user.");
355 + throw new McpAppHostRefusal({ message: "Declined by the user." });
356 }
357 if (!(await tryOpenExternalUrl(url, "mcp-app"))) {
356 - throw new McpAppHostRefusal("The link could not be opened.");
358 + throw new McpAppHostRefusal({ message: "The link could not be opened." });
359 }
360 },
361 sendMessage: async (text) => {
362 if (!(await confirm(`Send this message from ${app.server}?`, text, "Send"))) {
361 - throw new McpAppHostRefusal("Declined by the user.");
363 + throw new McpAppHostRefusal({ message: "Declined by the user." });
364 }
365 await enqueueThreadOutboxMessage({
366 environmentId: latest.current.props.environmentId,
@@ -422,7 +424,7 @@ export function ThreadMcpApp(props: {
424 downloadFile: async (files) => {
425 const names = files.map((file) => file.name).join(", ");
426 if (!(await confirm(`Save a file from ${app.server}?`, names, "Save"))) {
425 - throw new McpAppHostRefusal("Declined by the user.");
427 + throw new McpAppHostRefusal({ message: "Declined by the user." });
428 }
429 for (const file of files) {
430 let bytes: Uint8Array | undefined;
@@ -441,16 +443,18 @@ export function ThreadMcpApp(props: {
443 const declared = (content as { readonly mimeType?: unknown } | undefined)?.mimeType;
444 if (typeof declared === "string") mimeType = declared;
445 }
444 - if (bytes === undefined) throw new McpAppHostRefusal(`${file.name} has no contents.`);
446 + if (bytes === undefined)
447 + throw new McpAppHostRefusal({ message: `${file.name} has no contents.` });
448 if (bytes.byteLength > MAX_DOWNLOAD_BYTES) {
446 - throw new McpAppHostRefusal(`${file.name} is too large to save.`);
449 + throw new McpAppHostRefusal({ message: `${file.name} is too large to save.` });
450 }
451 const shared = await shareGeneratedAttachment({
452 bytes,
453 attachment: { name: file.name, mimeType },
454 signal: new AbortController().signal,
455 });
453 - if (!shared) throw new McpAppHostRefusal("Sharing is not available on this device.");
456 + if (!shared)
457 + throw new McpAppHostRefusal({ message: "Sharing is not available on this device." });
458 }
459 },
460 onRequestTeardown: () => {
apps/mobile/src/features/threads/ThreadMarkdownImage.tsx
+4 -2
@@ -1,8 +1,8 @@
1 import { useAtomValue } from "@effect/atom-react";
2 import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/assets";
3 import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
4 -import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 +import * as Schema from "effect/Schema";
6 import { AsyncResult, Atom } from "effect/reactivity";
7 import { Image } from "expo-image";
8 import { createContext, useContext, useId, useState } from "react";
@@ -33,7 +33,9 @@ export const MarkdownImageAvailableWidthContext = createContext(0);
33
34 type ImageSize = { readonly width: number; readonly height: number };
35
36 -class SvgLoadError extends Data.TaggedError("SvgLoadError")<{ readonly cause: unknown }> {}
36 +class SvgLoadError extends Schema.TaggedError<SvgLoadError>()("SvgLoadError", {
37 + cause: Schema.Defect(),
38 +}) {}
39
40 async function readSvgXml(uri: string, signal: AbortSignal): Promise<string> {
41 if (uri.startsWith("data:image/svg+xml")) {
apps/mobile/src/native/voiceTranscription.android.ts
+6 -5
@@ -73,14 +73,15 @@ async function runOperation<T>(
73 throwIfVoiceTranscriptionAborted(signal);
74 const code =
75 typeof error === "object" && error !== null && "code" in error ? error.code : undefined;
76 - throw new VoiceTranscriptionError(
77 - code === "unavailable" || code === "unsupported-locale" ? code : fallbackCode,
78 - (typeof code === "string" ? nativeErrorMessages[code] : undefined) ??
76 + throw new VoiceTranscriptionError({
77 + code: code === "unavailable" || code === "unsupported-locale" ? code : fallbackCode,
78 + message:
79 + (typeof code === "string" ? nativeErrorMessages[code] : undefined) ??
80 (fallbackCode === "preparation-failed"
81 ? "Voice transcription could not prepare this language. Check Google speech services and try again."
82 : "Voice transcription failed."),
82 - { cause: error },
83 - );
83 + cause: error,
84 + });
85 } finally {
86 signal.removeEventListener("abort", abort);
87 await cancellation;
apps/mobile/src/native/voiceTranscription.ios.ts
+14 -11
@@ -1,3 +1,4 @@
1 +import * as Schema from "effect/Schema";
2 import AppleTranscription from "@react-native-ai/apple/src/NativeAppleTranscription";
3 import { File } from "expo-file-system";
4
@@ -9,6 +10,8 @@ import {
10 type VoiceTranscriptionOptions,
11 } from "@t3tools/client-runtime/voice-input";
12
13 +const isVoiceTranscriptionError = Schema.is(VoiceTranscriptionError);
14 +
15 function getDeviceLocale(): string {
16 return Intl.DateTimeFormat().resolvedOptions().locale;
17 }
@@ -18,11 +21,11 @@ function wrapError(
21 message: string,
22 cause: unknown,
23 ): VoiceTranscriptionError {
21 - if (cause instanceof VoiceTranscriptionError) {
24 + if (isVoiceTranscriptionError(cause)) {
25 return cause;
26 }
27
25 - return new VoiceTranscriptionError(code, message, { cause });
28 + return new VoiceTranscriptionError({ code, message, cause });
29 }
30
31 function getNativeErrorCode(error: unknown): string | undefined {
@@ -45,10 +48,10 @@ async function prepareVoiceTranscription(
48 ): Promise<PreparedVoiceTranscription> {
49 throwIfVoiceTranscriptionAborted(signal);
50 if (!AppleTranscription.isAvailable(locale)) {
48 - throw new VoiceTranscriptionError(
49 - "unavailable",
50 - "Voice transcription requires a supported device with iOS 26 or later.",
51 - );
51 + throw new VoiceTranscriptionError({
52 + code: "unavailable",
53 + message: "Voice transcription requires a supported device with iOS 26 or later.",
54 + });
55 }
56
57 try {
@@ -61,11 +64,11 @@ async function prepareVoiceTranscription(
64 } catch (error) {
65 throwIfVoiceTranscriptionAborted(signal);
66 if (getNativeErrorCode(error) === "AppleTranscriptionUnsupportedLocale") {
64 - throw new VoiceTranscriptionError(
65 - "unsupported-locale",
66 - "Voice transcription does not support this device language.",
67 - { cause: error },
68 - );
67 + throw new VoiceTranscriptionError({
68 + code: "unsupported-locale",
69 + message: "Voice transcription does not support this device language.",
70 + cause: error,
71 + });
72 }
73
74 throw wrapError(
apps/server/src/device/DeviceService.ts
+3 -1
@@ -81,11 +81,13 @@ import * as LocalDeviceHost from "./LocalDeviceHost.ts";
81
82 export const DEVICE_HUB_ROUTE_PREFIX = "/api/device-hub";
83
84 +const isSshCommandError = Schema.is(SshCommandError);
85 +
86 const sshProbeFailureMessage = (error: DeviceHost.DeviceHostError): string => {
87 const windows = SshDeviceHost.isSshWindowsHostError(error.cause) ? error.cause : null;
88 const cause = windows ? windows.cause : error.cause;
89 if (
88 - !(cause instanceof SshCommandError) ||
90 + !isSshCommandError(cause) ||
91 cause.exitCode === null ||
92 cause.exitCode < 1 ||
93 (cause.exitCode > 254 && cause.exitCode !== 9009)
apps/server/src/device/SshDeviceHost.ts
+3 -1
@@ -90,6 +90,8 @@ const bootstrap = (
90 ),
91 );
92
93 +const isSshCommandError = Schema.is(SshCommandError);
94 +
95 // cmd expands only %OS% and PowerShell only $env:OS; POSIX shells expand neither to Windows_NT.
96 const explainWindowsHost = Effect.fn("SshDeviceHost.explainWindowsHost")(function* (
97 config: SshDeviceHostConfig,
@@ -98,7 +100,7 @@ const explainWindowsHost = Effect.fn("SshDeviceHost.explainWindowsHost")(functio
100 const cause = error.cause;
101 // Windows ssh.exe preserves full remote exit statuses such as 9009.
102 if (
101 - !(cause instanceof SshCommandError) ||
103 + !isSshCommandError(cause) ||
104 cause.exitCode === null ||
105 cause.exitCode < 1 ||
106 (cause.exitCode > 254 && cause.exitCode !== 9009)
apps/server/src/http.ts
+4 -4
@@ -8,7 +8,6 @@ import { isDevProxiedPath } from "@t3tools/shared/devProxy";
8 import { injectMcpAppCookieBootstrap, injectMcpAppThemeBootstrap } from "@t3tools/shared/mcpApp";
9 import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";
10 import * as ByteSize from "effect/ByteSize";
11 -import * as Data from "effect/Data";
11 import * as Effect from "effect/Effect";
12 import * as FileSystem from "effect/FileSystem";
13 import * as Layer from "effect/Layer";
@@ -327,9 +326,10 @@ export const layerServerEnvironmentHttpApi = HttpApiBuilder.group(
326 }),
327 );
328
330 -class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{
331 - readonly cause: unknown;
332 -}> {}
329 +class DecodeOtlpTraceRecordsError extends Schema.TaggedError<DecodeOtlpTraceRecordsError>()(
330 + "DecodeOtlpTraceRecordsError",
331 + { cause: Schema.Defect() },
332 +) {}
333
334 // Tracing once-per-second renderer exports would create more spans than it forwards.
335 export const layerOtlpTracesProxyRoute = HttpRouter.add(
apps/server/src/mcp/AcpMcpStdioBridge.ts
+18 -14
@@ -5,22 +5,28 @@ import * as NodeReadline from "node:readline";
5 import * as Cause from "effect/Cause";
6 import * as Effect from "effect/Effect";
7 import * as Option from "effect/Option";
8 -import * as Schema from "effect/Schema";
8 import * as Fiber from "effect/Fiber";
9 +import * as Schema from "effect/Schema";
10 import * as Scope from "effect/Scope";
11 import * as Stream from "effect/Stream";
12 import { discardResponseBody, responsePayloads } from "@t3tools/shared/mcpResponsePayloads";
13
14 /** ACP mandates stdio MCP support; HTTP/SSE support varies. */
15
16 -export class AcpMcpBridgeError extends Error {
17 - readonly _tag = "AcpMcpBridgeError";
18 -}
16 +export class AcpMcpBridgeError extends Schema.TaggedError<AcpMcpBridgeError>()(
17 + "AcpMcpBridgeError",
18 + { message: Schema.String, cause: Schema.optional(Schema.Defect()) },
19 +) {}
20 +
21 +const isAcpMcpBridgeError = Schema.is(AcpMcpBridgeError);
22
23 const bridgeError = (cause: unknown): AcpMcpBridgeError =>
21 - cause instanceof AcpMcpBridgeError
24 + isAcpMcpBridgeError(cause)
25 ? cause
23 - : new AcpMcpBridgeError(cause instanceof Error ? cause.message : String(cause), { cause });
26 + : new AcpMcpBridgeError({
27 + message: cause instanceof Error ? cause.message : String(cause),
28 + cause,
29 + });
30
31 const decodeJsonLine = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
32
@@ -104,9 +110,9 @@ export const mcpToolSession = (
110 sessionId = response.headers.get("mcp-session-id") ?? sessionId;
111 if (!response.ok) {
112 yield* discardResponseBody(response);
107 - return yield* Effect.fail(
108 - new AcpMcpBridgeError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`),
109 - );
113 + return yield* new AcpMcpBridgeError({
114 + message: `T3 Code MCP endpoint responded with HTTP ${response.status}.`,
115 + });
116 }
117 const payloads = yield* Stream.runCollect(responsePayloads(response, bridgeError));
118 for (const payload of payloads) {
@@ -123,11 +129,9 @@ export const mcpToolSession = (
129 const responses = yield* send({ jsonrpc: "2.0", id, method, params });
130 const envelope = asEnvelope(responses.find((entry) => asEnvelope(entry)?.id === id));
131 if (envelope === null || envelope.error !== undefined) {
126 - return yield* Effect.fail(
127 - new AcpMcpBridgeError(
128 - `T3 Code MCP ${method} failed${envelope?.error === undefined ? "." : `: ${JSON.stringify(envelope.error)}`}`,
129 - ),
130 - );
132 + return yield* new AcpMcpBridgeError({
133 + message: `T3 Code MCP ${method} failed${envelope?.error === undefined ? "." : `: ${JSON.stringify(envelope.error)}`}`,
134 + });
135 }
136 return envelope;
137 });
apps/server/src/orchestration-v2/http.ts
+3 -1
@@ -35,6 +35,8 @@ import { loadSubscriberShellSnapshot } from "./ShellStream.ts";
35 import { boundedSnapshotResponseFields } from "./ThreadStream.ts";
36 import { projectThreadProjectionForWire } from "./WireProjection.ts";
37
38 +const isInvalidThreadHistoryCursorError = Schema.is(InvalidThreadHistoryCursorError);
39 +
40 const isThreadTranscriptTooLargeError = Schema.is(
41 ThreadManagementService.ThreadTranscriptTooLargeError,
42 );
@@ -249,7 +251,7 @@ export const layer = HttpApiBuilder.group(
251 const decoded = Result.try(() => decodeThreadHistoryCursor(args.query.cursor));
252 if (Result.isFailure(decoded)) {
253 const cause = decoded.failure;
252 - if (cause instanceof InvalidThreadHistoryCursorError)
254 + if (isInvalidThreadHistoryCursorError(cause))
255 return yield* failEnvironmentInvalidRequest("invalid_history_cursor");
256 return yield* failEnvironmentInternal("orchestration_thread_history_failed", cause);
257 }
apps/server/src/orchestration-v2/threadHistoryPaging.ts
+7 -5
@@ -5,6 +5,7 @@ import type {
5 ThreadId,
6 TurnItemId,
7 } from "@t3tools/contracts";
8 +import * as Schema from "effect/Schema";
9
10 /**
11 * Every window stops at the byte budget. A window that holds a user turn also
@@ -84,11 +85,12 @@ export type BoundedProjectionResult = {
85 readonly latestLocalTurnOrdinal: number | null;
86 };
87
87 -export class InvalidThreadHistoryCursorError extends Error {
88 - readonly _tag = "InvalidThreadHistoryCursorError";
89 - constructor(message = "Invalid thread history cursor.") {
90 - super(message);
91 - this.name = "InvalidThreadHistoryCursorError";
88 +export class InvalidThreadHistoryCursorError extends Schema.TaggedError<InvalidThreadHistoryCursorError>()(
89 + "InvalidThreadHistoryCursorError",
90 + {},
91 +) {
92 + override get message(): string {
93 + return "Invalid thread history cursor.";
94 }
95 }
96
apps/server/src/preview/ServerBrowser.ts
+109 -94
@@ -1223,22 +1223,23 @@ const make = Effect.gen(function* () {
1223 const uploadFiles = async (tab: ServerTab, input: PreviewAutomationUploadInput) => {
1224 const relative = input.paths.find((path) => !NodePath.isAbsolute(path));
1225 if (relative !== undefined)
1226 - throw new ServerBrowserPage.ServerBrowserOperationError(
1227 - "PreviewAutomationExecutionError",
1228 - `Upload paths must be absolute: ${relative}`,
1229 - );
1226 + throw new ServerBrowserPage.ServerBrowserOperationError({
1227 + tag: "PreviewAutomationExecutionError",
1228 + message: `Upload paths must be absolute: ${relative}`,
1229 + });
1230 if (await ServerBrowserPage.setInputFiles(tab.page, input)) return undefined;
1231 const open = tab.fileChooser;
1232 if (!open)
1233 - throw new ServerBrowserPage.ServerBrowserOperationError(
1234 - "PreviewAutomationExecutionError",
1235 - "No file picker is open. Click the page's upload control first, or pass the file input's locator.",
1236 - );
1233 + throw new ServerBrowserPage.ServerBrowserOperationError({
1234 + tag: "PreviewAutomationExecutionError",
1235 + message:
1236 + "No file picker is open. Click the page's upload control first, or pass the file input's locator.",
1237 + });
1238 if (input.paths.length > 1 && !open.chooser.isMultiple())
1238 - throw new ServerBrowserPage.ServerBrowserOperationError(
1239 - "PreviewAutomationExecutionError",
1240 - "This file picker accepts one file.",
1241 - );
1239 + throw new ServerBrowserPage.ServerBrowserOperationError({
1240 + tag: "PreviewAutomationExecutionError",
1241 + message: "This file picker accepts one file.",
1242 + });
1243 if (input.paths.length > 0)
1244 await open.chooser.setFiles([...input.paths], {
1245 timeout: input.timeoutMs ?? NAVIGATION_TIMEOUT_MS,
@@ -1418,10 +1419,10 @@ const make = Effect.gen(function* () {
1419
1420 const assertTabCapacity = (agentSessionId: string) => {
1421 if (atTabLimit(agentSessionId))
1421 - throw new BrowserControlInterrupted(
1422 - `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.`,
1423 - "tabLimit",
1424 - );
1422 + throw new BrowserControlInterrupted({
1423 + 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.`,
1424 + reason: "tabLimit",
1425 + });
1426 };
1427
1428 // 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* () {
1592 findBrowserProfile(profiles, requested) ??
1593 profiles.find((profile) => profile.name.toLowerCase() === wanted);
1594 if (match) return match.id;
1594 - throw new ServerBrowserPage.ServerBrowserOperationError(
1595 - "PreviewAutomationUnknownProfileError",
1596 - `No browser profile is named "${requested}". Use one of: ${profiles
1595 + throw new ServerBrowserPage.ServerBrowserOperationError({
1596 + tag: "PreviewAutomationUnknownProfileError",
1597 + message: `No browser profile is named "${requested}". Use one of: ${profiles
1598 .map((profile) => `${profile.name} (id ${profile.id})`)
1599 .join(", ")}.`,
1599 - );
1600 + });
1601 };
1602
1603 const statusWithTitle = async (
@@ -1692,16 +1693,16 @@ const make = Effect.gen(function* () {
1693 await navigation.catch((cause: unknown) => {
1694 const message = cause instanceof Error ? cause.message : String(cause);
1695 if (message.includes("Download is starting")) {
1695 - throw new ServerBrowserPage.ServerBrowserOperationError(
1696 - "PreviewAutomationExecutionError",
1697 - `${url} is a file this browser cannot show, so it was downloaded instead. preview_status lists it under downloads.`,
1698 - );
1696 + throw new ServerBrowserPage.ServerBrowserOperationError({
1697 + tag: "PreviewAutomationExecutionError",
1698 + message: `${url} is a file this browser cannot show, so it was downloaded instead. preview_status lists it under downloads.`,
1699 + });
1700 }
1701 if (/ERR_[A-Z_]+/.test(message)) {
1701 - throw new ServerBrowserPage.ServerBrowserOperationError(
1702 - "PreviewAutomationExecutionError",
1703 - `Navigation to ${url} failed: ${ServerBrowserPage.parseNetError(message).description}`,
1704 - );
1702 + throw new ServerBrowserPage.ServerBrowserOperationError({
1703 + tag: "PreviewAutomationExecutionError",
1704 + message: `Navigation to ${url} failed: ${ServerBrowserPage.parseNetError(message).description}`,
1705 + });
1706 }
1707 throw ServerBrowserPage.toOperationError(cause, timeout);
1708 });
@@ -1804,10 +1805,10 @@ const make = Effect.gen(function* () {
1805 withCaptureLock(tab, async () => {
1806 const recording = tab.recording;
1807 if (!recording) {
1807 - throw new ServerBrowserPage.ServerBrowserOperationError(
1808 - "PreviewAutomationRecordingNotActiveError",
1809 - "No recording is active for this tab.",
1810 - );
1808 + throw new ServerBrowserPage.ServerBrowserOperationError({
1809 + tag: "PreviewAutomationRecordingNotActiveError",
1810 + message: "No recording is active for this tab.",
1811 + });
1812 }
1813 let mimeType: string | null;
1814 const chunks: Array<Buffer> = [];
@@ -1821,10 +1822,10 @@ const make = Effect.gen(function* () {
1822 mimeType = stopped.mimeType;
1823 // Checked before the transfer so an oversized video never lands in this process.
1824 if (stopped.bytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
1824 - throw new ServerBrowserPage.ServerBrowserOperationError(
1825 - "PreviewAutomationRecordingTooLargeError",
1826 - "The recording is larger than the attachment limit.",
1827 - );
1825 + throw new ServerBrowserPage.ServerBrowserOperationError({
1826 + tag: "PreviewAutomationRecordingTooLargeError",
1827 + message: "The recording is larger than the attachment limit.",
1828 + });
1829 }
1830 for (let index = 0; index < stopped.count; index += 1) {
1831 const chunk = await recording.encoder.evaluate(
@@ -1839,10 +1840,10 @@ const make = Effect.gen(function* () {
1840 }
1841 const data = Buffer.concat(chunks);
1842 if (!mimeType || data.byteLength === 0) {
1842 - throw new ServerBrowserPage.ServerBrowserOperationError(
1843 - "PreviewAutomationExecutionError",
1844 - "The recording captured no frames.",
1845 - );
1843 + throw new ServerBrowserPage.ServerBrowserOperationError({
1844 + tag: "PreviewAutomationExecutionError",
1845 + message: "The recording captured no frames.",
1846 + });
1847 }
1848
1849 const extension = mimeType.startsWith("video/mp4") ? "mp4" : "webm";
@@ -1921,15 +1922,18 @@ const make = Effect.gen(function* () {
1922
1923 const requireTab = async (request: PreviewAutomationRequest) => {
1924 if (!request.agentSessionId)
1924 - throw new BrowserControlInterrupted("The agent session is missing. Reconnect the provider.");
1925 + throw new BrowserControlInterrupted({
1926 + message: "The agent session is missing. Reconnect the provider.",
1927 + });
1928 const owned = [...tabs.values()].filter(
1929 (tab) => tab.threadId === request.threadId && tab.control.agentId === request.agentSessionId,
1930 );
1931 if (!request.tabIdExplicit && owned.length > 1)
1929 - throw new BrowserControlInterrupted(
1930 - "Multiple tabs belong to this agent session. Pass a tabId from preview_open or preview_status tabs.",
1931 - "tabRequired",
1932 - );
1932 + throw new BrowserControlInterrupted({
1933 + message:
1934 + "Multiple tabs belong to this agent session. Pass a tabId from preview_open or preview_status tabs.",
1935 + reason: "tabRequired",
1936 + });
1937 const tab =
1938 request.tabId === undefined
1939 ? latestThreadTab(request.threadId, request.agentSessionId)
@@ -1937,16 +1941,17 @@ const make = Effect.gen(function* () {
1941 findTab(request.threadId, request.tabId).pipe(Effect.orElseSucceed(constVoid)),
1942 );
1943 if (!tab) {
1940 - throw new ServerBrowserPage.ServerBrowserOperationError(
1941 - "PreviewAutomationTabNotFoundError",
1942 - "No server preview tab is open for this thread. Call preview_open first.",
1943 - );
1944 + throw new ServerBrowserPage.ServerBrowserOperationError({
1945 + tag: "PreviewAutomationTabNotFoundError",
1946 + message: "No server preview tab is open for this thread. Call preview_open first.",
1947 + });
1948 }
1949 if (!READ_OPERATIONS.has(request.operation) && !tab.control.agentMayAct(request.agentSessionId))
1946 - throw new BrowserControlInterrupted(
1947 - "This tab belongs to another agent session. You can read it, but open your own tab to act.",
1948 - "agentMismatch",
1949 - );
1950 + throw new BrowserControlInterrupted({
1951 + message:
1952 + "This tab belongs to another agent session. You can read it, but open your own tab to act.",
1953 + reason: "agentMismatch",
1954 + });
1955 return tab;
1956 };
1957
@@ -1976,9 +1981,9 @@ const make = Effect.gen(function* () {
1981 );
1982 case "open": {
1983 if (!request.agentSessionId)
1979 - throw new BrowserControlInterrupted(
1980 - "The agent session is missing. Reconnect the provider.",
1981 - );
1984 + throw new BrowserControlInterrupted({
1985 + message: "The agent session is missing. Reconnect the provider.",
1986 + });
1987 const open = input as PreviewAutomationOpenInput;
1988 const url = open.url === undefined ? undefined : normalizePreviewUrl(open.url);
1989 const reuse = open.reuseExistingTab ?? true;
@@ -1990,10 +1995,10 @@ const make = Effect.gen(function* () {
1995 tab.threadId === request.threadId && tab.control.agentId === request.agentSessionId,
1996 ).length > 1
1997 )
1993 - throw new BrowserControlInterrupted(
1994 - "Multiple tabs are open. Pass tabId or reuseExistingTab=false.",
1995 - "tabRequired",
1996 - );
1998 + throw new BrowserControlInterrupted({
1999 + message: "Multiple tabs are open. Pass tabId or reuseExistingTab=false.",
2000 + reason: "tabRequired",
2001 + });
2002
2003 const found =
2004 reuse && request.tabId !== undefined
@@ -2012,12 +2017,12 @@ const make = Effect.gen(function* () {
2017 const desktop = sessions.some(
2018 (session) => session.tabId === request.tabId && session.runtime !== "server",
2019 );
2015 - throw new ServerBrowserPage.ServerBrowserOperationError(
2016 - desktop ? "PreviewAutomationExecutionError" : "PreviewAutomationTabNotFoundError",
2017 - desktop
2020 + throw new ServerBrowserPage.ServerBrowserOperationError({
2021 + tag: desktop ? "PreviewAutomationExecutionError" : "PreviewAutomationTabNotFoundError",
2022 + message: desktop
2023 ? "This tab belongs to the desktop runtime. This environment's server browser cannot control desktop tabs. Omit tabId to open a server tab instead."
2024 : "The requested server preview tab does not exist.",
2020 - );
2025 + });
2026 }
2027 // Reusing another session's tab requires explicit tabId; reading it grants no implicit takeover.
2028 const existing =
@@ -2043,18 +2048,20 @@ const make = Effect.gen(function* () {
2048 ),
2049 ));
2050 if (existing?.dialog)
2046 - throw new BrowserControlInterrupted(
2047 - "A browser dialog is pending. Read preview_status and use preview_dialog first.",
2048 - "dialogPending",
2049 - );
2051 + throw new BrowserControlInterrupted({
2052 + message:
2053 + "A browser dialog is pending. Read preview_status and use preview_dialog first.",
2054 + reason: "dialogPending",
2055 + });
2056 return tab.control.agent(
2057 request.agentSessionId,
2058 async () => {
2059 if (tab.dialog)
2054 - throw new BrowserControlInterrupted(
2055 - "A browser dialog is pending. Read preview_status and use preview_dialog first.",
2056 - "dialogPending",
2057 - );
2060 + throw new BrowserControlInterrupted({
2061 + message:
2062 + "A browser dialog is pending. Read preview_status and use preview_dialog first.",
2063 + reason: "dialogPending",
2064 + });
2065 if (existing) {
2066 if (url) await navigate(tab, url, "load", navigationTimeout);
2067 } else {
@@ -2098,10 +2105,11 @@ const make = Effect.gen(function* () {
2105 candidate.control.agentId === request.agentSessionId,
2106 ).length > 1
2107 )
2101 - throw new BrowserControlInterrupted(
2102 - "Multiple tabs belong to this agent session. Pass a tabId from preview_open or preview_status tabs.",
2103 - "tabRequired",
2104 - );
2108 + throw new BrowserControlInterrupted({
2109 + message:
2110 + "Multiple tabs belong to this agent session. Pass a tabId from preview_open or preview_status tabs.",
2111 + reason: "tabRequired",
2112 + });
2113 const recordings = [...tabs.values()].filter(
2114 (candidate) =>
2115 candidate.threadId === request.threadId &&
@@ -2114,10 +2122,10 @@ const make = Effect.gen(function* () {
2122 recordings.find((candidate) => candidate.tabId === targetTabId) ??
2123 (!request.tabIdExplicit && recordings.length === 1 ? recordings[0] : undefined);
2124 if (!tab) {
2117 - throw new ServerBrowserPage.ServerBrowserOperationError(
2118 - "PreviewAutomationRecordingNotActiveError",
2119 - "No recording is active for this thread.",
2120 - );
2125 + throw new ServerBrowserPage.ServerBrowserOperationError({
2126 + tag: "PreviewAutomationRecordingNotActiveError",
2127 + message: "No recording is active for this thread.",
2128 + });
2129 }
2130 // A stop cannot act twice (a retry finds no recording);
2131 // dropping a late one would leave capture running.
@@ -2128,12 +2136,15 @@ const make = Effect.gen(function* () {
2136 // Closing must unblock an action waiting on a dialog, without queueing behind it.
2137 if (request.operation === "close") {
2138 if (tab.control.agentId !== request.agentSessionId)
2131 - throw new BrowserControlInterrupted(
2132 - "Only the agent session that opened this tab can close it.",
2133 - "agentMismatch",
2134 - );
2139 + throw new BrowserControlInterrupted({
2140 + message: "Only the agent session that opened this tab can close it.",
2141 + reason: "agentMismatch",
2142 + });
2143 if (tab.control.controller !== null)
2136 - throw new BrowserControlInterrupted("A human controls this tab.", "humanControl");
2144 + throw new BrowserControlInterrupted({
2145 + message: "A human controls this tab.",
2146 + reason: "humanControl",
2147 + });
2148 void tab.control.close().catch(constVoid);
2149 await runPromise(manager.close({ threadId: tab.threadId, tabId: tab.tabId }));
2150 dropTab(tab, false);
@@ -2142,7 +2153,10 @@ const make = Effect.gen(function* () {
2153 // Resolve dialogs outside the queue, with ownership checked, to unblock waiting clicks.
2154 if (request.operation === "dialog") {
2155 if (tab.control.controller !== null)
2145 - throw new BrowserControlInterrupted("A human controls this tab.", "humanControl");
2156 + throw new BrowserControlInterrupted({
2157 + message: "A human controls this tab.",
2158 + reason: "humanControl",
2159 + });
2160 await resolveDialog(tab, input as PreviewAutomationDialogInput);
2161 return statusWithTitle(tab, request.agentSessionId);
2162 }
@@ -2155,10 +2169,10 @@ const make = Effect.gen(function* () {
2169 ) {
2170 return tab.control.observe(async () => {
2171 if (tab.dialog)
2158 - throw new BrowserControlInterrupted(
2159 - "A browser dialog is pending. Read preview_status.",
2160 - "dialogPending",
2161 - );
2172 + throw new BrowserControlInterrupted({
2173 + message: "A browser dialog is pending. Read preview_status.",
2174 + reason: "dialogPending",
2175 + });
2176 return executeTabOperation(tab, request);
2177 });
2178 }
@@ -2166,10 +2180,11 @@ const make = Effect.gen(function* () {
2180 agentSessionId,
2181 async () => {
2182 if (tab.dialog)
2169 - throw new BrowserControlInterrupted(
2170 - "A browser dialog is pending. Read preview_status and use preview_dialog first.",
2171 - "dialogPending",
2172 - );
2183 + throw new BrowserControlInterrupted({
2184 + message:
2185 + "A browser dialog is pending. Read preview_status and use preview_dialog first.",
2186 + reason: "dialogPending",
2187 + });
2188 const generation = tab.control.generation;
2189 tab.agentOperating = !READ_OPERATIONS.has(request.operation);
2190 updateFileChooserInterception(tab);
apps/server/src/preview/ServerBrowserPage.ts
+87 -69
@@ -19,56 +19,69 @@ import {
19 type PreviewAutomationWaitForInput,
20 } from "@t3tools/contracts";
21 import { constVoid } from "effect/Function";
22 +import * as Schema from "effect/Schema";
23 import type { CDPSession, ConsoleMessage, Frame, Locator, Page } from "playwright-core";
24 import * as NodeCrypto from "node:crypto";
25 import { BrowserControlInterrupted } from "./SessionControl.ts";
26
27 +const isBrowserControlInterrupted = Schema.is(BrowserControlInterrupted);
28 +
29 const MAX_EVALUATION_BYTES = 64_000;
30 const MAX_VISIBLE_TEXT_LENGTH = 20_000;
31 const MAX_SCREENSHOT_WIDTH = 1280;
32 const WAIT_POLL_MS = 100;
33 export const DIAGNOSTIC_BUFFER_LIMIT = 200;
34
32 -export class ServerBrowserOperationError extends Error {
33 - readonly tag: string;
34 - readonly detail: unknown;
35 +export class ServerBrowserOperationError extends Schema.TaggedError<ServerBrowserOperationError>()(
36 + "ServerBrowserOperationError",
37 + {
38 + tag: Schema.String,
39 + message: Schema.String,
40 + detail: Schema.optional(Schema.Unknown),
41 + cause: Schema.optional(Schema.Defect()),
42 + },
43 +) {}
44
36 - constructor(tag: string, message: string, detail?: unknown, options?: ErrorOptions) {
37 - super(message, options);
38 - this.tag = tag;
39 - this.detail = detail;
40 - }
41 -}
45 +const isServerBrowserOperationError = Schema.is(ServerBrowserOperationError);
46
47 export const toOperationError = (
48 cause: unknown,
49 timeoutMs?: number,
50 ): ServerBrowserOperationError => {
47 - if (cause instanceof BrowserControlInterrupted)
48 - return new ServerBrowserOperationError(
49 - "PreviewAutomationControlInterruptedError",
50 - cause.message,
51 - cause.reason,
52 - );
53 - if (cause instanceof ServerBrowserOperationError) return cause;
51 + if (isBrowserControlInterrupted(cause))
52 + return new ServerBrowserOperationError({
53 + tag: "PreviewAutomationControlInterruptedError",
54 + message: cause.message,
55 + detail: cause.reason,
56 + });
57 + if (isServerBrowserOperationError(cause)) return cause;
58 const message = cause instanceof Error ? cause.message : String(cause);
59 const firstLine = message.split("\n")[0] ?? message;
60 if (cause instanceof Error && cause.name === "TimeoutError") {
57 - return new ServerBrowserOperationError(
58 - "PreviewAutomationTimeoutError",
59 - firstLine,
60 - timeoutMs === undefined ? undefined : { timeoutMs },
61 - );
61 + return new ServerBrowserOperationError({
62 + tag: "PreviewAutomationTimeoutError",
63 + message: firstLine,
64 + detail: timeoutMs === undefined ? undefined : { timeoutMs },
65 + });
66 }
67 if (
68 /while parsing selector|Unknown engine|Unexpected token|strict mode violation/i.test(message)
69 ) {
66 - return new ServerBrowserOperationError("PreviewAutomationInvalidSelectorError", firstLine);
70 + return new ServerBrowserOperationError({
71 + tag: "PreviewAutomationInvalidSelectorError",
72 + message: firstLine,
73 + });
74 }
75 if (/not an <input>|not editable|not an editable/i.test(message)) {
69 - return new ServerBrowserOperationError("PreviewAutomationTargetNotEditableError", firstLine);
76 + return new ServerBrowserOperationError({
77 + tag: "PreviewAutomationTargetNotEditableError",
78 + message: firstLine,
79 + });
80 }
71 - return new ServerBrowserOperationError("PreviewAutomationExecutionError", firstLine);
81 + return new ServerBrowserOperationError({
82 + tag: "PreviewAutomationExecutionError",
83 + message: firstLine,
84 + });
85 };
86
87 const DEFAULT_TIMEOUT_MS = 15_000;
@@ -115,11 +128,12 @@ const targetLocator = (
128 const ref = /^\s*aria-ref\s*=\s*(\S+)\s*$/.exec(selector)?.[1];
129 const nativeRef = ref === undefined ? undefined : pageRefs.get(page)?.refs.get(ref);
130 if (nativeRef === undefined) {
118 - throw new ServerBrowserOperationError(
119 - "PreviewAutomationInvalidSelectorError",
120 - "This element ref is stale or belongs to another tab. Take a fresh snapshot and use its locator.",
121 - { staleRef: true },
122 - );
131 + throw new ServerBrowserOperationError({
132 + tag: "PreviewAutomationInvalidSelectorError",
133 + message:
134 + "This element ref is stale or belongs to another tab. Take a fresh snapshot and use its locator.",
135 + detail: { staleRef: true },
136 + });
137 }
138 return page.locator(`aria-ref=${nativeRef}`);
139 }
@@ -229,16 +243,17 @@ const DOTTED_SCRIPT = `(() => {
243 })()`;
244
245 const pageChanged = () =>
232 - new ServerBrowserOperationError(
233 - "PreviewAutomationExecutionError",
234 - "The page changed while capturing its snapshot. Take another snapshot.",
235 - );
246 + new ServerBrowserOperationError({
247 + tag: "PreviewAutomationExecutionError",
248 + message: "The page changed while capturing its snapshot. Take another snapshot.",
249 + });
250
251 const tooBusy = () =>
238 - new ServerBrowserOperationError(
239 - "PreviewAutomationTimeoutError",
240 - "The page was too busy to capture a snapshot in time. Wait for it to settle and take another snapshot.",
241 - );
252 + new ServerBrowserOperationError({
253 + tag: "PreviewAutomationTimeoutError",
254 + message:
255 + "The page was too busy to capture a snapshot in time. Wait for it to settle and take another snapshot.",
256 + });
257
258 const VALUE_TOO_LONG = "A password field holds a value too long to hide, so no snapshot was taken.";
259
@@ -381,7 +396,10 @@ const dottedPattern = (values: ReadonlyArray<string>) => {
396 pattern.test("");
397 pattern.test("\u2022");
398 } catch {
384 - throw new ServerBrowserOperationError("PreviewAutomationExecutionError", VALUE_TOO_LONG);
399 + throw new ServerBrowserOperationError({
400 + tag: "PreviewAutomationExecutionError",
401 + message: VALUE_TOO_LONG,
402 + });
403 }
404 return pattern;
405 };
@@ -673,12 +691,12 @@ const namedTargetTimeout = async (
691 : matches === 0
692 ? `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.`
693 : `The click may have happened; check the page before retrying. ${target} still matches an element after the timeout.`;
676 - return new ServerBrowserOperationError(
677 - "PreviewAutomationTimeoutError",
678 - reason,
679 - { reason },
680 - { cause },
681 - );
694 + return new ServerBrowserOperationError({
695 + tag: "PreviewAutomationTimeoutError",
696 + message: reason,
697 + detail: { reason },
698 + cause,
699 + });
700 };
701
702 const clickTarget = async (
@@ -756,10 +774,10 @@ export const type = async (page: Page, input: PreviewAutomationTypeInput) => {
774 { timeout },
775 ));
776 if (focused !== true) {
759 - throw new ServerBrowserOperationError(
760 - "PreviewAutomationTargetNotEditableError",
761 - "The target is not an enabled text field, so no text was typed.",
762 - );
777 + throw new ServerBrowserOperationError({
778 + tag: "PreviewAutomationTargetNotEditableError",
779 + message: "The target is not an enabled text field, so no text was typed.",
780 + });
781 }
782 if (input.clear) {
783 await page.keyboard.press("ControlOrMeta+A");
@@ -811,10 +829,10 @@ export const select = async (
829 )?.value ?? entry,
830 );
831 if (values === null)
814 - throw new ServerBrowserOperationError(
815 - "PreviewAutomationTargetNotEditableError",
816 - "This element is not a <select>. Click a custom dropdown, then click its option.",
817 - );
832 + throw new ServerBrowserOperationError({
833 + tag: "PreviewAutomationTargetNotEditableError",
834 + message: "This element is not a <select>. Click a custom dropdown, then click its option.",
835 + });
836 return { selected: await locator.selectOption(values, { timeout }) };
837 };
838
@@ -872,10 +890,10 @@ export const evaluate = async (
890 // Stops a busy script; an awaited promise is abandoned and settles unread.
891 void cdp.send("Runtime.terminateExecution").catch(constVoid);
892 reject(
875 - new ServerBrowserOperationError(
876 - "PreviewAutomationTimeoutError",
877 - `Evaluation did not finish within ${timeoutMs}ms and was stopped.`,
878 - ),
893 + new ServerBrowserOperationError({
894 + tag: "PreviewAutomationTimeoutError",
895 + message: `Evaluation did not finish within ${timeoutMs}ms and was stopped.`,
896 + }),
897 );
898 }, timeoutMs);
899 });
@@ -887,20 +905,20 @@ export const evaluate = async (
905 void evaluation.catch(constVoid);
906 const result = await Promise.race([evaluation, expired]).finally(() => clearTimeout(timer));
907 if (result.exceptionDetails) {
890 - throw new ServerBrowserOperationError(
891 - "PreviewAutomationExecutionError",
892 - result.exceptionDetails.exception?.description ?? result.exceptionDetails.text,
893 - );
908 + throw new ServerBrowserOperationError({
909 + tag: "PreviewAutomationExecutionError",
910 + message: result.exceptionDetails.exception?.description ?? result.exceptionDetails.text,
911 + });
912 }
913 const value =
914 "value" in result.result ? result.result.value : (result.result.description ?? null);
915 const actualBytes = Buffer.byteLength(JSON.stringify(value ?? null), "utf8");
916 if (actualBytes > MAX_EVALUATION_BYTES) {
899 - throw new ServerBrowserOperationError(
900 - "PreviewAutomationResultTooLargeError",
901 - `Evaluation result is ${actualBytes} bytes; the limit is ${MAX_EVALUATION_BYTES}.`,
902 - { maximumBytes: MAX_EVALUATION_BYTES },
903 - );
917 + throw new ServerBrowserOperationError({
918 + tag: "PreviewAutomationResultTooLargeError",
919 + message: `Evaluation result is ${actualBytes} bytes; the limit is ${MAX_EVALUATION_BYTES}.`,
920 + detail: { maximumBytes: MAX_EVALUATION_BYTES },
921 + });
922 }
923 return value;
924 };
@@ -926,10 +944,10 @@ export const waitFor = async (page: Page, input: PreviewAutomationWaitForInput)
944 const results = await Promise.all(checks.map((check) => check()));
945 if (results.every(Boolean)) return;
946 if (Date.now() >= deadline) {
929 - throw new ServerBrowserOperationError(
930 - "PreviewAutomationTimeoutError",
931 - `Waited ${timeoutMs}ms without every condition holding.`,
932 - );
947 + throw new ServerBrowserOperationError({
948 + tag: "PreviewAutomationTimeoutError",
949 + message: `Waited ${timeoutMs}ms without every condition holding.`,
950 + });
951 }
952 await new Promise((resolve) => setTimeout(resolve, WAIT_POLL_MS));
953 }
apps/server/src/preview/SessionControl.ts
+36 -20
@@ -1,15 +1,20 @@
1 -import type { PreviewAutomationControlReason } from "@t3tools/contracts";
2 -
3 -export class BrowserControlInterrupted extends Error {
4 - readonly reason: PreviewAutomationControlReason;
5 - constructor(
6 - message = "Browser control changed. Refresh the snapshot before trying again.",
7 - reason: PreviewAutomationControlReason = "interrupted",
8 - ) {
9 - super(message);
10 - this.reason = reason;
11 - }
12 -}
1 +import { PreviewAutomationControlReason } from "@t3tools/contracts";
2 +import * as Effect from "effect/Effect";
3 +import * as Schema from "effect/Schema";
4 +
5 +export class BrowserControlInterrupted extends Schema.TaggedError<BrowserControlInterrupted>()(
6 + "BrowserControlInterrupted",
7 + {
8 + message: Schema.String.pipe(
9 + Schema.withConstructorDefault(
10 + Effect.succeed("Browser control changed. Refresh the snapshot before trying again."),
11 + ),
12 + ),
13 + reason: PreviewAutomationControlReason.pipe(
14 + Schema.withConstructorDefault(Effect.succeed("interrupted" as const)),
15 + ),
16 + },
17 +) {}
18
19 const settle = (work: Promise<unknown>) =>
20 work.then(
@@ -69,7 +74,11 @@ export class SessionControl {
74 }
75
76 private assertOpen() {
72 - if (this.closed) throw new BrowserControlInterrupted("This browser tab is closed.", "closed");
77 + if (this.closed)
78 + throw new BrowserControlInterrupted({
79 + message: "This browser tab is closed.",
80 + reason: "closed",
81 + });
82 }
83
84 private changeOwner(owner: string | null) {
@@ -81,7 +90,8 @@ export class SessionControl {
90
91 private async action<A>(allowed: () => boolean, run: () => Promise<A>, deadlineMs?: number) {
92 this.assertOpen();
84 - if (!allowed()) throw new BrowserControlInterrupted("You do not control this browser tab.");
93 + if (!allowed())
94 + throw new BrowserControlInterrupted({ message: "You do not control this browser tab." });
95 const epoch = this.epoch;
96 return this.enqueue(async () => {
97 this.assertOpen();
@@ -103,11 +113,17 @@ export class SessionControl {
113 agent<A>(agentId: string, run: () => Promise<A>, deadlineMs?: number) {
114 if (!this.agentMayAct(agentId))
115 return Promise.reject(
106 - new BrowserControlInterrupted("This tab belongs to another agent.", "agentMismatch"),
116 + new BrowserControlInterrupted({
117 + message: "This tab belongs to another agent.",
118 + reason: "agentMismatch",
119 + }),
120 );
121 if (this.owner !== null)
122 return Promise.reject(
110 - new BrowserControlInterrupted("A human controls this tab.", "humanControl"),
123 + new BrowserControlInterrupted({
124 + message: "A human controls this tab.",
125 + reason: "humanControl",
126 + }),
127 );
128 return this.action(() => this.agentMayAct(agentId) && this.owner === null, run, deadlineMs);
129 }
@@ -164,7 +180,7 @@ export class SessionControl {
180 async take(viewerId: string) {
181 this.assertOpen();
182 if (this.owner !== null && this.owner !== viewerId) {
167 - throw new BrowserControlInterrupted("Another viewer controls this browser tab.");
183 + throw new BrowserControlInterrupted({ message: "Another viewer controls this browser tab." });
184 }
185 if (this.owner !== viewerId) this.changeOwner(viewerId);
186 return this.human(viewerId, async () => {});
@@ -173,9 +189,9 @@ export class SessionControl {
189 async release(viewerId: string, afterDrain: () => Promise<void> = async () => {}) {
190 this.assertOpen();
191 if (this.owner !== viewerId) {
176 - throw new BrowserControlInterrupted(
177 - "Only the controlling viewer can release this browser tab.",
178 - );
192 + throw new BrowserControlInterrupted({
193 + message: "Only the controlling viewer can release this browser tab.",
194 + });
195 }
196 this.changeOwner(null);
197 await this.enqueue(async () => {
apps/server/src/project/AgentSessionJson.test.ts
+1 -1
@@ -48,7 +48,7 @@ describe("transcript JSON projection", () => {
48 it("retains the import allocation and depth limits", () => {
49 const limited = createTranscriptJsonReader(
50 () => {
51 - throw new TranscriptJsonLimitError("budget");
51 + throw new TranscriptJsonLimitError({ message: "budget" });
52 },
53 () => true,
54 );
apps/server/src/project/AgentSessionJson.ts
+8 -2
@@ -1,3 +1,4 @@
1 +import * as Schema from "effect/Schema";
2 import * as SchemaAST from "effect/SchemaAST";
3 import { none, type Many } from "stream-chain/defs.js";
4 import { Assembler } from "stream-json/core/assembler.js";
@@ -40,7 +41,10 @@ export function createTranscriptJsonSelector(schema: { readonly ast: SchemaAST.A
41 return (path: JsonPath) => includes(ast, path, 0);
42 }
43
43 -export class TranscriptJsonLimitError extends Error {}
44 +export class TranscriptJsonLimitError extends Schema.TaggedError<TranscriptJsonLimitError>()(
45 + "TranscriptJsonLimitError",
46 + { message: Schema.String },
47 +) {}
48
49 export function createTranscriptJsonReader(
50 reserve: (bytes: number) => void,
@@ -150,7 +154,9 @@ export function createTranscriptJsonReader(
154 for (const token of tokens.values) {
155 if (token.name === "startObject" || token.name === "startArray") {
156 if (++depth > (options?.maxDepth ?? 128))
153 - throw new TranscriptJsonLimitError("Transcript JSON nesting exceeds the depth limit");
157 + throw new TranscriptJsonLimitError({
158 + message: "Transcript JSON nesting exceeds the depth limit",
159 + });
160 } else if (token.name === "endObject" || token.name === "endArray") {
161 if (--depth === 0) complete = true;
162 }
apps/server/src/project/AgentSessionScanner.ts
+3 -3
@@ -1026,9 +1026,9 @@ export const make = Effect.gen(function* () {
1026 const reserve = (bytes: number) => {
1027 recordBytes += bytes;
1028 if (historyBytes + recordBytes > MAX_IMPORT_HISTORY_BYTES) {
1029 - throw new TranscriptJsonLimitError(
1030 - "Transcript selected history exceeds the 32 MiB memory budget",
1031 - );
1029 + throw new TranscriptJsonLimitError({
1030 + message: "Transcript selected history exceeds the 32 MiB memory budget",
1031 + });
1032 }
1033 };
1034 let reader = createTranscriptJsonReader(reserve, selectTranscriptPath);
apps/server/src/provider/documentTextWorker.ts
+1
@@ -29,6 +29,7 @@ const HIDDEN = new Set([
29 "pPr",
30 ]);
31
32 +// @effect-diagnostics-next-line extendsNativeError:off - this worker loads no Effect runtime; Truncation is a local throw sentinel.
33 class Truncation extends Error {}
34
35 interface XmlNode {
apps/server/src/provider/providerMaintenanceRunner.ts
+7 -5
@@ -10,7 +10,6 @@ import {
10 import { resolveSpawnCommand } from "@t3tools/shared/shell";
11 import * as Cause from "effect/Cause";
12 import * as Context from "effect/Context";
13 -import * as Data from "effect/Data";
13 import * as DateTime from "effect/DateTime";
14 import * as Duration from "effect/Duration";
15 import * as Effect from "effect/Effect";
@@ -79,10 +78,13 @@ export class ProviderMaintenanceRunner extends Context.Service<
78 ProviderMaintenanceRunnerShape
79 >()("t3/provider/providerMaintenanceRunner") {}
80
82 -class ProviderMaintenanceCommandError extends Data.TaggedError("ProviderMaintenanceCommandError")<{
83 - readonly message: string;
84 - readonly cause?: unknown;
85 -}> {}
81 +class ProviderMaintenanceCommandError extends Schema.TaggedError<ProviderMaintenanceCommandError>()(
82 + "ProviderMaintenanceCommandError",
83 + {
84 + message: Schema.String,
85 + cause: Schema.optional(Schema.Defect()),
86 + },
87 +) {}
88
89 interface VerifiedProviderRefresh {
90 readonly providers: ReadonlyArray<ServerProvider>;
apps/server/src/scheduledTasks/ScheduledTaskService.ts
+4 -4
@@ -31,7 +31,6 @@ import * as Context from "effect/Context";
31 import * as Digest from "effect/crypto/Digest";
32 import * as Mac from "effect/crypto/Mac";
33 import * as SecureRandom from "effect/crypto/SecureRandom";
34 -import * as Data from "effect/Data";
34 import * as DateTime from "effect/DateTime";
35 import * as Effect from "effect/Effect";
36 import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
@@ -122,9 +121,10 @@ export class ScheduledTaskWebhookOrigin extends Context.Reference<Effect.Effect<
121 },
122 ) {}
123
125 -class WebhookDeliverySkipped extends Data.TaggedError("WebhookDeliverySkipped")<{
126 - readonly reason: string;
127 -}> {}
124 +class WebhookDeliverySkipped extends Schema.TaggedError<WebhookDeliverySkipped>()(
125 + "WebhookDeliverySkipped",
126 + { reason: Schema.String },
127 +) {}
128
129 interface RateWindow {
130 readonly accepted: ReadonlyArray<{ readonly at: number }>;
apps/web/src/browser/browserViewportActions.ts
+8 -6
@@ -1,5 +1,6 @@
1 import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2 import type { PreviewViewportSetting, ScopedThreadRef } from "@t3tools/contracts";
3 +import * as Schema from "effect/Schema";
4
5 import { toastManager } from "~/components/ui/toast";
6 import { updatePreviewServerSnapshot } from "~/previewStateStore";
@@ -15,11 +16,12 @@ export interface BrowserViewportTarget {
16
17 const BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS = 15_000;
18
18 -class BrowserViewportCommitTimeoutError extends Error {
19 - override readonly name = "BrowserViewportCommitTimeoutError";
20 -
21 - constructor(readonly tabId: string) {
22 - super(`Timed out committing the browser viewport for tab ${tabId}`);
19 +class BrowserViewportCommitTimeoutError extends Schema.TaggedError<BrowserViewportCommitTimeoutError>()(
20 + "BrowserViewportCommitTimeoutError",
21 + { tabId: Schema.String },
22 +) {
23 + override get message(): string {
24 + return `Timed out committing the browser viewport for tab ${this.tabId}`;
25 }
26 }
27
@@ -53,7 +55,7 @@ const runHandlerWithTimeout = (tabId: string, operation: Promise<void>): Promise
55 let timeoutId: ReturnType<typeof setTimeout> | undefined;
56 const timeout = new Promise<never>((_resolve, reject) => {
57 timeoutId = setTimeout(
56 - () => reject(new BrowserViewportCommitTimeoutError(tabId)),
58 + () => reject(new BrowserViewportCommitTimeoutError({ tabId })),
59 BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS,
60 );
61 });
apps/web/src/browser/openFileInPreview.ts
+11 -9
@@ -12,7 +12,7 @@ import {
12 mapAtomCommandResult,
13 } from "@t3tools/client-runtime/state/runtime";
14 import * as Cause from "effect/Cause";
15 -import * as Data from "effect/Data";
15 +import * as Schema from "effect/Schema";
16 import { AsyncResult } from "effect/reactivity";
17
18 import { resolveAssetUrl } from "~/assets/assetUrls";
@@ -35,20 +35,22 @@ import { resolveBrowserDefaults } from "./browserDefaults";
35 export const isBrowserPreviewFile = (path: string): boolean =>
36 /\.(?:html?|pdf)$/i.test(path.split(/[?#]/, 1)[0] ?? "");
37
38 -export class BrowserPreviewUnavailableError extends Data.TaggedError(
38 +export class BrowserPreviewUnavailableError extends Schema.TaggedError<BrowserPreviewUnavailableError>()(
39 "BrowserPreviewUnavailableError",
40 -)<{
41 - readonly message: string;
42 -}> {}
40 + { message: Schema.String },
41 +) {}
42
44 -export class BrowserSettingsReadError extends Data.TaggedError("BrowserSettingsReadError")<{
45 - readonly cause: unknown;
46 -}> {
43 +export class BrowserSettingsReadError extends Schema.TaggedError<BrowserSettingsReadError>()(
44 + "BrowserSettingsReadError",
45 + { cause: Schema.Defect() },
46 +) {
47 override get message(): string {
48 return "Saved browser settings could not be loaded.";
49 }
50 }
51
52 +export const isBrowserSettingsReadError = Schema.is(BrowserSettingsReadError);
53 +
54 export type OpenPreviewMutation<E = unknown> = (input: {
55 readonly environmentId: EnvironmentId;
56 readonly input: PreviewOpenInput;
@@ -66,7 +68,7 @@ export async function openUrlInPreview<E>(input: {
68 const defaults = await resolveBrowserDefaults().catch(
69 (cause: unknown) => new BrowserSettingsReadError({ cause }),
70 );
69 - if (defaults instanceof BrowserSettingsReadError) {
71 + if (isBrowserSettingsReadError(defaults)) {
72 return AsyncResult.failure(Cause.fail(defaults));
73 }
74 const runtime = previewRuntimeFor(threadRef.environmentId);
apps/web/src/browser/useOpenLink.ts
+2 -2
@@ -13,7 +13,7 @@ import {
13 resolveBrowserLinkTargetPreference,
14 resolveLinkTarget,
15 } from "./browserLinkTarget";
16 -import { BrowserSettingsReadError, openUrlInPreview } from "./openFileInPreview";
16 +import { isBrowserSettingsReadError, openUrlInPreview } from "./openFileInPreview";
17
18 const NO_MODIFIER = { metaKey: false, ctrlKey: false } as const;
19
@@ -46,7 +46,7 @@ export function useOpenLink(threadRef: ScopedThreadRef | null | undefined): (
46 return;
47 }
48 const failure = squashAtomCommandFailure(result);
49 - if (failure instanceof BrowserSettingsReadError) throw failure;
49 + if (isBrowserSettingsReadError(failure)) throw failure;
50 console.error(result.cause);
51 }
52 const api = readLocalApi();
apps/web/src/cloud/dpop.ts
+7 -8
@@ -3,7 +3,6 @@ import { computeDpopJwkThumbprint, DpopPublicJwk } from "@t3tools/shared/dpop";
3 import * as Digest from "effect/crypto/Digest";
4 import * as SecureRandom from "effect/crypto/SecureRandom";
5 import * as Signature from "effect/crypto/Signature";
6 -import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Layer from "effect/Layer";
8 import * as Schema from "effect/Schema";
@@ -14,10 +13,12 @@ export interface BrowserDpopKey {
13 readonly thumbprint: string;
14 }
15
17 -export class BrowserDpopError extends Data.TaggedError("BrowserDpopError")<{
18 - readonly message: string;
19 - readonly cause?: unknown;
20 -}> {}
16 +export class BrowserDpopError extends Schema.TaggedError<BrowserDpopError>()("BrowserDpopError", {
17 + message: Schema.String,
18 + cause: Schema.optional(Schema.Defect()),
19 +}) {}
20 +
21 +const isBrowserDpopError = Schema.is(BrowserDpopError);
22
23 const DPOP_DATABASE_NAME = "t3code:cloud-auth";
24 const DPOP_DATABASE_VERSION = 1;
@@ -113,9 +114,7 @@ const generateBrowserDpopKey = Effect.gen(function* () {
114 }).pipe(
115 Effect.flatMap((jwk) => decodeDpopPublicJwk(jwk)),
116 Effect.mapError((cause) =>
116 - cause instanceof BrowserDpopError
117 - ? cause
118 - : dpopError("Generated DPoP public key is invalid.", cause),
117 + isBrowserDpopError(cause) ? cause : dpopError("Generated DPoP public key is invalid.", cause),
118 ),
119 );
120 const privateKey = yield* Effect.tryPromise({
apps/web/src/cloud/linkEnvironment.ts
+10 -6
@@ -1,4 +1,3 @@
1 -import * as Data from "effect/Data";
1 import * as Effect from "effect/Effect";
2 import * as Option from "effect/Option";
3 import * as Schema from "effect/Schema";
@@ -36,11 +35,16 @@ function relayUrl(): string | null {
35 return resolveCloudPublicConfig().relayUrl;
36 }
37
39 -export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
40 - readonly message: string;
41 - readonly cause?: unknown;
42 - readonly traceId?: string;
43 -}> {}
38 +export class CloudEnvironmentLinkError extends Schema.TaggedError<CloudEnvironmentLinkError>()(
39 + "CloudEnvironmentLinkError",
40 + {
41 + message: Schema.String,
42 + cause: Schema.optional(Schema.Defect()),
43 + traceId: Schema.optional(Schema.String),
44 + },
45 +) {}
46 +
47 +export const isCloudEnvironmentLinkError = Schema.is(CloudEnvironmentLinkError);
48
49 const relayClientRpcError = (message: string) => (cause: unknown) =>
50 new CloudEnvironmentLinkError({
apps/web/src/cloud/useCloudLinkController.ts
+2 -2
@@ -21,7 +21,7 @@ import { toastManager } from "../components/ui/toast";
21 import { relayEnvironmentDiscovery } from "../state/relay";
22 import { readEnvironmentScope } from "../state/session";
23 import { useAtomCommand } from "../state/use-atom-command";
24 -import { CloudEnvironmentLinkError } from "./linkEnvironment";
24 +import { isCloudEnvironmentLinkError } from "./linkEnvironment";
25 import { refreshManagedTunnelUsage } from "./managedRelayState";
26 import {
27 linkEnvironment as linkEnvironmentAtom,
@@ -54,7 +54,7 @@ const isManagedRelayRequestFailedError = Schema.is(ManagedRelay.ManagedRelayRequ
54
55 /** The account's tunnel cap when the relay refused a new tunnel for being at it. */
56 function tunnelLimitFromLinkFailure(cause: unknown): number | null {
57 - if (!(cause instanceof CloudEnvironmentLinkError)) return null;
57 + if (!isCloudEnvironmentLinkError(cause)) return null;
58 const relayCause = cause.cause;
59 if (!isManagedRelayRequestFailedError(relayCause)) return null;
60 return relayCause.relayError?._tag === "RelayEnvironmentLinkLimitExceededError"
apps/web/src/components/ChatMarkdown.tsx
+3 -3
@@ -185,7 +185,7 @@ import {
185 openFileInPreview,
186 openUrlInPreview,
187 BrowserPreviewUnavailableError,
188 - BrowserSettingsReadError,
188 + isBrowserSettingsReadError,
189 } from "../browser/openFileInPreview";
190 import { resolveLinkTarget } from "../browser/browserLinkTarget";
191 import { PullRequestLinkPreview } from "./pullRequest/PullRequestLinkPreview";
@@ -712,7 +712,7 @@ function useChatMarkdownState({
712 if (result._tag === "Success") recordVisitForThread(threadRef, url);
713 else if (!isAtomCommandInterrupted(result)) {
714 const error = squashAtomCommandFailure(result);
715 - if (error instanceof BrowserSettingsReadError) {
715 + if (isBrowserSettingsReadError(error)) {
716 toastManager.add(
717 stackedThreadToast({
718 type: "error",
@@ -1204,7 +1204,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
1204 { operation: "open-link-in-preview", target: href },
1205 result.cause,
1206 );
1207 - if (squashAtomCommandFailure(result) instanceof BrowserSettingsReadError) return;
1207 + if (isBrowserSettingsReadError(squashAtomCommandFailure(result))) return;
1208 void readLocalApi()?.shell.openExternal(href);
1209 });
1210 }}
apps/web/src/components/chat/McpAppFrame.tsx
+16 -12
@@ -40,9 +40,10 @@ const commandFailure = (result: {
40 readonly cause: Parameters<typeof squashAtomCommandFailure>[0]["cause"];
41 }) => {
42 const error = squashAtomCommandFailure(result);
43 - return new McpAppHostRefusal(
44 - error instanceof Error && error.message.trim() !== "" ? error.message : "Request failed.",
45 - );
43 + return new McpAppHostRefusal({
44 + message:
45 + error instanceof Error && error.message.trim() !== "" ? error.message : "Request failed.",
46 + });
47 };
48
49 const fullscreenSupported =
@@ -253,7 +254,7 @@ export function McpAppFrame(props: {
254 flushSync(() => setDisplayMode("inline"));
255 const approved = await requestConfirmDialog(message);
256 if (approved === undefined) {
256 - throw new McpAppHostRefusal("T3 could not ask for approval here.");
257 + throw new McpAppHostRefusal({ message: "T3 could not ask for approval here." });
258 }
259 return approved;
260 };
@@ -272,12 +273,13 @@ export function McpAppFrame(props: {
273 const { environmentId, input } = scope();
274 const info = await readLive().toolInfo({ environmentId, input: { ...input, name } });
275 if (info._tag !== "Success") throw commandFailure(info);
275 - if (!info.value.callable) throw new McpAppHostRefusal("This app cannot call that tool.");
276 + if (!info.value.callable)
277 + throw new McpAppHostRefusal({ message: "This app cannot call that tool." });
278 if (!info.value.readOnly) {
279 const approved = await ask(
280 `Allow ${app.server} to run ${info.value.title ?? name}?\n${JSON.stringify(args, null, 2)}`,
281 );
280 - if (approved !== true) throw new McpAppHostRefusal("Declined by the user.");
282 + if (approved !== true) throw new McpAppHostRefusal({ message: "Declined by the user." });
283 }
284 const result = await readLive().callTool({
285 environmentId,
@@ -297,15 +299,16 @@ export function McpAppFrame(props: {
299 },
300 openLink: async (url) => {
301 if (document.activeElement !== frameRef.current || !navigator.userActivation?.isActive) {
300 - throw new McpAppHostRefusal("Links open only from a click in the app.");
302 + throw new McpAppHostRefusal({ message: "Links open only from a click in the app." });
303 }
304 window.open(url, "_blank", "noopener,noreferrer");
305 },
306 sendMessage: async (text) => {
307 const send = readLive().props.onSendMessage;
306 - if (send === undefined) throw new McpAppHostRefusal("Messages are not available here.");
308 + if (send === undefined)
309 + throw new McpAppHostRefusal({ message: "Messages are not available here." });
310 const approved = await ask(`Send this message from ${app.server}?\n${text}`);
308 - if (approved !== true) throw new McpAppHostRefusal("Declined by the user.");
311 + if (approved !== true) throw new McpAppHostRefusal({ message: "Declined by the user." });
312 await send(text);
313 },
314 updateModelContext: async (context) => {
@@ -340,7 +343,7 @@ export function McpAppFrame(props: {
343 downloadFile: async (files) => {
344 const names = files.map((file) => file.name).join(", ");
345 const approved = await ask(`Save ${names} from ${app.server}?`);
343 - if (approved !== true) throw new McpAppHostRefusal("Declined by the user.");
346 + if (approved !== true) throw new McpAppHostRefusal({ message: "Declined by the user." });
347 for (const file of files) {
348 let bytes: Uint8Array | undefined;
349 let mimeType = file.mimeType ?? "application/octet-stream";
@@ -358,9 +361,10 @@ export function McpAppFrame(props: {
361 const declared = (content as { readonly mimeType?: unknown } | undefined)?.mimeType;
362 if (typeof declared === "string") mimeType = declared;
363 }
361 - if (bytes === undefined) throw new McpAppHostRefusal(`${file.name} has no contents.`);
364 + if (bytes === undefined)
365 + throw new McpAppHostRefusal({ message: `${file.name} has no contents.` });
366 if (bytes.byteLength > MAX_DOWNLOAD_BYTES) {
363 - throw new McpAppHostRefusal(`${file.name} is too large to save.`);
367 + throw new McpAppHostRefusal({ message: `${file.name} is too large to save.` });
368 }
369 saveBlob(new Blob([bytes.slice()], { type: mimeType }), file.name);
370 }
apps/web/src/components/chat/useRightPanelActions.ts
+2 -2
@@ -22,7 +22,7 @@ import {
22 } from "../../rightPanelStore";
23 import { requestWorkspaceContentFocus, requestWorkspaceFocus } from "../../lib/workspaceFocus";
24 import { setActivePreviewTab } from "../../previewStateStore";
25 -import { BrowserSettingsReadError } from "../../browser/openFileInPreview";
25 +import { isBrowserSettingsReadError } from "../../browser/openFileInPreview";
26 import { addBrowserSurface } from "../preview/addBrowserSurface";
27 import { focusActivePanelTerminal, focusTerminal } from "../../lib/terminalFocus";
28 import { subscribePreviewAction } from "../preview/previewActionBus";
@@ -119,7 +119,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) {
119 }).then((result) => {
120 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
121 const error = squashAtomCommandFailure(result);
122 - if (error instanceof BrowserSettingsReadError) {
122 + if (isBrowserSettingsReadError(error)) {
123 toastManager.add(
124 stackedThreadToast({
125 type: "error",
apps/web/src/components/device/DeviceAndroidFoldControls.tsx
+4 -1
@@ -1,3 +1,4 @@
1 +import * as Schema from "effect/Schema";
2 import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
3 import { useAtomMount, useAtomSet, useAtomValue } from "@effect/atom-react";
4 import { useRef, useState } from "react";
@@ -7,6 +8,8 @@ import { AndroidFoldError, setAndroidFold, type AndroidFoldPosture } from "./dev
8 import { androidFoldReadAtom, androidFoldViewAtom, foldAngle, NOOP_ATOM } from "./deviceHubAtoms";
9 import { DeviceDuoGlyph } from "./DeviceDuoGlyph";
10
11 +const isAndroidFoldError = Schema.is(AndroidFoldError);
12 +
13 export function DeviceAndroidFoldControls(props: {
14 readonly access: DeviceHubAccess;
15 readonly deviceKey: string;
@@ -47,7 +50,7 @@ export function DeviceAndroidFoldControls(props: {
50 void send(props.access)
51 .catch(async (cause: unknown) => {
52 // Hub tickets expire after a few minutes, while the panel stays open much longer.
50 - if (!(cause instanceof AndroidFoldError && cause.status === 401)) throw cause;
53 + if (!(isAndroidFoldError(cause) && cause.status === 401)) throw cause;
54 const renewed = await props.renewAccess();
55 if (!renewed || controller.signal.aborted) throw cause;
56 return send(renewed);
apps/web/src/components/device/DeviceWorkspace.tsx
+4 -1
@@ -1,3 +1,4 @@
1 +import * as Schema from "effect/Schema";
2 import type { DeviceHostSummary, DeviceSummary, EnvironmentId } from "@t3tools/contracts";
3 import { useRef, useState } from "react";
4 import {
@@ -10,6 +11,8 @@ import { DeviceStreamView } from "./DeviceStreamView";
11 import { DeviceToolsPanel } from "./DeviceToolsPanel";
12 import { useDeviceControls } from "./useDeviceControls";
13
14 +const isDeviceScreenshotError = Schema.is(DeviceScreenshotError);
15 +
16 const DOWNLOAD_URL_LIFETIME_MS = 60_000;
17
18 export function DeviceWorkspace(props: {
@@ -59,7 +62,7 @@ export function DeviceWorkspace(props: {
62 window.setTimeout(() => URL.revokeObjectURL(url), DOWNLOAD_URL_LIFETIME_MS);
63 })
64 .catch((cause: unknown) => {
62 - if (cause instanceof DeviceScreenshotError && cause.status === 401)
65 + if (isDeviceScreenshotError(cause) && cause.status === 401)
66 refreshDeviceHubAccess(props.environmentId);
67 setScreenshotError(
68 cause instanceof Error ? cause.message : "Screenshot capture failed. Try again.",
apps/web/src/components/device/deviceFold.ts
+9 -12
@@ -1,5 +1,6 @@
1 import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
2 import { withDeviceHubQuery } from "@t3tools/client-runtime/state/deviceHubAccess";
3 +import * as Schema from "effect/Schema";
4
5 export type AndroidFoldPosture = "closed" | "opened";
6
@@ -9,14 +10,10 @@ export interface AndroidFoldState {
10 readonly hingeAngle: number | null;
11 }
12
12 -export class AndroidFoldError extends Error {
13 - readonly status: number;
14 -
15 - constructor(message: string, status: number) {
16 - super(message);
17 - this.status = status;
18 - }
19 -}
13 +export class AndroidFoldError extends Schema.TaggedError<AndroidFoldError>()("AndroidFoldError", {
14 + message: Schema.String,
15 + status: Schema.Number,
16 +}) {}
17
18 const isRecord = (value: unknown): value is Record<string, unknown> =>
19 typeof value === "object" && value !== null && !Array.isArray(value);
@@ -63,10 +60,10 @@ const foldRequest = async (
60 if (!response.ok) {
61 const payload: unknown = await response.json().catch(() => null);
62 const error = isRecord(payload) ? payload.error : null;
66 - throw new AndroidFoldError(
67 - typeof error === "string" ? error : `Fold command failed (${response.status}).`,
68 - response.status,
69 - );
63 + throw new AndroidFoldError({
64 + message: typeof error === "string" ? error : `Fold command failed (${response.status}).`,
65 + status: response.status,
66 + });
67 }
68 return parseFold(await response.json());
69 };
apps/web/src/components/device/deviceHubAtoms.ts
+3 -1
@@ -17,6 +17,8 @@ import {
17 } from "./deviceHubApi";
18 import { AndroidFoldError, readAndroidFold, type AndroidFoldState } from "./deviceFold";
19
20 +const isAndroidFoldError = Schema.is(AndroidFoldError);
21 +
22 const AX_POLL_INTERVAL_MS = 2_000;
23 const FOLD_RETRY_MS = 3_000;
24
@@ -102,7 +104,7 @@ export const androidFoldReadAtom = Atom.family(
104 Atom.make((get) =>
105 Effect.tryPromise({
106 try: (signal) => readAndroidFold(input.access, input.deviceId, signal),
105 - catch: (cause) => ({ expired: cause instanceof AndroidFoldError && cause.status === 401 }),
107 + catch: (cause) => ({ expired: isAndroidFoldError(cause) && cause.status === 401 }),
108 }).pipe(
109 Effect.retry({
110 while: (failure) => !failure.expired,
apps/web/src/components/files/office/Spreadsheet.tsx
+4 -1
@@ -1,3 +1,4 @@
1 +import * as Schema from "effect/Schema";
2 import { observeResize } from "~/lib/observeResize";
3 import { useEffect, useRef, useState } from "react";
4 import {
@@ -33,6 +34,8 @@ import {
34 } from "./sheet-paint";
35 import { externalUrl } from "./links";
36
37 +const isSupersededError = Schema.is(SupersededError);
38 +
39 type Client = ReturnType<typeof createWorkerClient<SheetMethods>>;
40 type Opened = {
41 engine: Client;
@@ -264,7 +267,7 @@ function SpreadsheetGrid(props: {
267 schedule();
268 })
269 .catch((cause: unknown) => {
267 - if (!(cause instanceof SupersededError) && !controller.signal.aborted)
270 + if (!isSupersededError(cause) && !controller.signal.aborted)
271 setNotice("These cells could not be drawn.");
272 });
273 }
apps/web/src/components/files/office/worker-rpc.ts
+17 -11
@@ -3,6 +3,8 @@
3 // two ends of that worker's protocol: typed calls by method name, a key that lets a newer call replace a queued one
4 // (as the markdown worker's queue does), transferable payloads, and a worker that fails every pending call when it dies.
5
6 +import * as Schema from "effect/Schema";
7 +
8 /** What one method takes and returns. */
9 export type Method<Input, Output> = { readonly input: Input; readonly output: Output };
10
@@ -43,10 +45,14 @@ export class Transfer<T> {
45 }
46
47 /** A call that a newer call with the same key replaced before it ran. */
46 -export class SupersededError extends Error {}
48 +export class SupersededError extends Schema.TaggedError<SupersededError>()("SupersededError", {
49 + message: Schema.String,
50 +}) {}
51
52 /** A call made after the worker failed or was closed, or pending when that happened. */
49 -class WorkerClosedError extends Error {}
53 +class WorkerClosedError extends Schema.TaggedError<WorkerClosedError>()("WorkerClosedError", {
54 + message: Schema.String,
55 +}) {}
56
57 type CallOptions = {
58 /** 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) {
99 });
100
101 worker.addEventListener("error", (event) =>
96 - fail(new WorkerClosedError(event.message || "The Office engine stopped")),
102 + fail(new WorkerClosedError({ message: event.message || "The Office engine stopped" })),
103 );
104 worker.addEventListener("messageerror", () =>
99 - fail(new WorkerClosedError("The Office engine sent an unreadable reply")),
105 + fail(new WorkerClosedError({ message: "The Office engine sent an unreadable reply" })),
106 );
107
108 return {
@@ -108,7 +114,7 @@ export function createWorkerClient<M extends Methods>(worker: Worker) {
114 if (state.failure) return Promise.reject(state.failure);
115
116 if (options.signal?.aborted)
111 - return Promise.reject(new WorkerClosedError("The call was aborted"));
117 + return Promise.reject(new WorkerClosedError({ message: "The call was aborted" }));
118
119 const id = ++state.next;
120
@@ -116,16 +122,16 @@ export function createWorkerClient<M extends Methods>(worker: Worker) {
122 const timeout = setTimeout(
123 () =>
124 fail(
119 - new WorkerClosedError(
120 - "This document took too long to preview. Open it in another app.",
121 - ),
125 + new WorkerClosedError({
126 + message: "This document took too long to preview. Open it in another app.",
127 + }),
128 ),
129 30_000,
130 );
131 const abort = () => {
132 clearTimeout(timeout);
133 pending.delete(id);
128 - reject(new WorkerClosedError("The call was aborted"));
134 + reject(new WorkerClosedError({ message: "The call was aborted" }));
135 worker.postMessage({ cancel: id } satisfies Cancel, []);
136 };
137
@@ -138,7 +144,7 @@ export function createWorkerClient<M extends Methods>(worker: Worker) {
144 if (!response.ok)
145 return reject(
146 response.superseded
141 - ? new SupersededError(response.message)
147 + ? new SupersededError({ message: response.message })
148 : new Error(response.message),
149 );
150
@@ -158,7 +164,7 @@ export function createWorkerClient<M extends Methods>(worker: Worker) {
164 },
165 /** Stops the worker, which frees its engine's memory, and fails every pending call. */
166 close() {
161 - fail(new WorkerClosedError("The Office engine was closed"));
167 + fail(new WorkerClosedError({ message: "The Office engine was closed" }));
168 },
169 };
170 }
apps/web/src/components/guest/guestTurnItemSource.ts
+3 -4
@@ -10,7 +10,6 @@ import {
10 OrchestrationV2GetTurnItemResult,
11 } from "@t3tools/contracts";
12 import * as Cause from "effect/Cause";
13 -import * as Data from "effect/Data";
13 import * as Effect from "effect/Effect";
14 import * as Option from "effect/Option";
15 import * as Queue from "effect/Queue";
@@ -21,9 +20,9 @@ import { Atom } from "effect/reactivity";
20 import type { TurnItemSource } from "../chat/timelineRowContext";
21
22 /** What an expanded guest row says when it cannot read the item. */
24 -class GuestItemReadError extends Data.TaggedError("GuestItemReadError")<{
25 - readonly message: string;
26 -}> {}
23 +class GuestItemReadError extends Schema.TaggedError<GuestItemReadError>()("GuestItemReadError", {
24 + message: Schema.String,
25 +}) {}
26
27 const decodeDetail = Schema.decodeUnknownSync(Schema.toCodecJson(OrchestrationV2GetTurnItemResult));
28 const decodeFrame = Schema.decodeUnknownOption(
apps/web/src/components/preview/PreviewView.tsx
+2 -2
@@ -71,7 +71,7 @@ import { BrowserDeviceToolbar } from "~/browser/BrowserDeviceToolbar";
71 import { BROWSER_DEVICE_TOOLBAR_HEIGHT } from "~/browser/browserViewportLayout";
72 import { useBrowserLayoutZoomFactor } from "~/browser/useBrowserLayoutZoomFactor";
73 import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
74 -import { BrowserSettingsReadError } from "~/browser/openFileInPreview";
74 +import { isBrowserSettingsReadError } from "~/browser/openFileInPreview";
75 import { PreviewFileNotShown, PreviewUnreachable } from "./PreviewUnreachable";
76 import { revealInFileExplorerLabel } from "./fileExplorerLabel";
77 import { shouldShowPreviewEmptyState } from "./previewEmptyStateLogic";
@@ -243,7 +243,7 @@ export function PreviewView({
243 const result = await openPreviewSession({ openPreview: open, threadRef, url: resolvedUrl });
244 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
245 const error = squashAtomCommandFailure(result);
246 - if (error instanceof BrowserSettingsReadError) {
246 + if (isBrowserSettingsReadError(error)) {
247 toastManager.add({
248 type: "error",
249 title: "Unable to open browser",
apps/web/src/components/preview/openPreviewSession.ts
+2 -2
@@ -11,7 +11,7 @@ import * as Cause from "effect/Cause";
11 import { AsyncResult } from "effect/reactivity";
12
13 import { resolveBrowserDefaults } from "~/browser/browserDefaults";
14 -import { BrowserSettingsReadError } from "~/browser/openFileInPreview";
14 +import { BrowserSettingsReadError, isBrowserSettingsReadError } from "~/browser/openFileInPreview";
15 import { previewRuntimeFor } from "~/browser/previewRuntime";
16 import { applyPreviewServerSnapshot, rememberPreviewUrl } from "~/previewStateStore";
17
@@ -34,7 +34,7 @@ export async function openPreviewSession<E>(
34 const defaults = await resolveBrowserDefaults().catch(
35 (cause: unknown) => new BrowserSettingsReadError({ cause }),
36 );
37 - if (defaults instanceof BrowserSettingsReadError) {
37 + if (isBrowserSettingsReadError(defaults)) {
38 return AsyncResult.failure(Cause.fail(defaults));
39 }
40 const runtime = input.runtime ?? previewRuntimeFor(input.threadRef.environmentId);
apps/web/src/components/settings/IntegrationsSettings.tsx
+12 -6
@@ -40,6 +40,7 @@ import { usePrimaryManagedPolicy } from "~/state/managedPolicy";
40 import { isValidSearchUrlTemplate } from "@t3tools/shared/preview";
41 import { PREVIEW_VIEWPORT_PRESETS } from "@t3tools/shared/previewViewport";
42 import { MoreVertical, Plus as PlusIcon } from "lucide-react";
43 +import * as Schema from "effect/Schema";
44 import { useRef, useState } from "react";
45
46 import { ScreenRotationIcon } from "~/browser/ScreenRotationIcon";
@@ -174,13 +175,17 @@ const zoomLabel = (zoomFactor: number) => `${Math.round(zoomFactor * 100)}%`;
175
176 /** IPC carries reason tokens inside messages; treat unknown tokens as read failures without exposing raw
177 * text. */
177 -class ProfileLimitReachedError extends Error {
178 - constructor() {
179 - super("Browser profile limit reached.");
180 - this.name = "ProfileLimitReachedError";
178 +class ProfileLimitReachedError extends Schema.TaggedError<ProfileLimitReachedError>()(
179 + "ProfileLimitReachedError",
180 + {},
181 +) {
182 + override get message(): string {
183 + return "Browser profile limit reached.";
184 }
185 }
186
187 +const isProfileLimitReachedError = Schema.is(ProfileLimitReachedError);
188 +
189 export const importFailureReason = (cause: unknown): BrowserImportFailureReason => {
190 const message = String((cause as { message?: unknown } | undefined)?.message ?? "");
191 return (
@@ -257,8 +262,9 @@ async function importBrowserCookiesIntoTarget(
262 await clearBrowserProfileData(bridge, [environmentId], input.target.profileId).catch(
263 () => undefined,
264 );
260 - const reason =
261 - cause instanceof ProfileLimitReachedError ? "profileLimitReached" : "profileNotSaved";
265 + const reason = isProfileLimitReachedError(cause)
266 + ? "profileLimitReached"
267 + : "profileNotSaved";
268 throw new Error(`Importing cookies from ${source.id} failed: ${reason}.`, { cause });
269 }
270 } else {
apps/web/src/components/settings/OpenSourceLicenses.tsx
+5 -4
@@ -1,7 +1,7 @@
1 import { ChevronRightIcon, ExternalLinkIcon, SearchIcon } from "lucide-react";
2 import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
3 import * as Cause from "effect/Cause";
4 -import * as Data from "effect/Data";
4 +import * as Schema from "effect/Schema";
5 import * as Effect from "effect/Effect";
6 import * as Option from "effect/Option";
7 import { FetchHttpClient, HttpClient } from "effect/http";
@@ -22,9 +22,10 @@ import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group"
22 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
23 import { SettingsPageContainer, SettingsSection } from "./settingsLayout";
24
25 -class LicenseManifestLoadError extends Data.TaggedError("LicenseManifestLoadError")<{
26 - readonly message: string;
27 -}> {}
25 +class LicenseManifestLoadError extends Schema.TaggedError<LicenseManifestLoadError>()(
26 + "LicenseManifestLoadError",
27 + { message: Schema.String },
28 +) {}
29
30 // Not keepAlive: a failed load must not stick for the session, so each visit to the page loads
31 // the manifest again (a static asset the HTTP cache serves).
apps/web/src/lib/resourceTelemetryState.browser.test.tsx
+4 -2
@@ -6,7 +6,7 @@ import {
6 } from "@t3tools/contracts";
7 import * as Cause from "effect/Cause";
8 import * as DateTime from "effect/DateTime";
9 -import * as Data from "effect/Data";
9 +import * as Schema from "effect/Schema";
10 import * as Effect from "effect/Effect";
11 import * as Option from "effect/Option";
12 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
@@ -64,7 +64,9 @@ vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => monitor.retr
64
65 import { ResourceTelemetryDiagnostics } from "../components/settings/ResourceTelemetryDiagnostics";
66
67 -class MonitorError extends Data.TaggedError("MonitorError")<{ readonly message: string }> {}
67 +class MonitorError extends Schema.TaggedError<MonitorError>()("MonitorError", {
68 + message: Schema.String,
69 +}) {}
70
71 const environmentId = EnvironmentId.make("remote");
72 const startError = "The resource monitor is not available.";
infra/relay/src/http/Api.test.ts
+1 -2
@@ -15,7 +15,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
15 import { describe, expect, it } from "@effect/vitest";
16 import { vi } from "vite-plus/test";
17 import * as Context from "effect/Context";
18 -import * as Data from "effect/Data";
18 import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";
19 import * as DateTime from "effect/DateTime";
20 import * as Deferred from "effect/Deferred";
@@ -1471,7 +1470,7 @@ describe("relay routing fallback", () => {
1470 describe("relay CORS", () => {
1471 const origin = "https://app.t3.codes";
1472
1474 - class HandlerFailed extends Data.TaggedError("HandlerFailed") {}
1473 + class HandlerFailed extends Schema.TaggedError<HandlerFailed>()("HandlerFailed", {}) {}
1474
1475 it.effect("adds CORS headers to handler failures and defects", () =>
1476 Effect.gen(function* () {
infra/task-cache/vendor/vite-plus-remote-cache-cloudflare/src/errors.ts
+1
@@ -1,3 +1,4 @@
1 +// @effect-diagnostics-next-line extendsNativeError:off - vendored upstream code without Effect; kept as published.
2 export class HttpError extends Error {
3 constructor(
4 public status: number,
oxlint-plugin-t3code/test/utils.ts
+16 -15
@@ -1,11 +1,9 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, it } from "@effect/vitest";
3 -import * as Data from "effect/Data";
3 import * as Effect from "effect/Effect";
4 import * as FileSystem from "effect/FileSystem";
5 import * as Path from "effect/Path";
6 import * as PlatformError from "effect/PlatformError";
8 -import * as Predicate from "effect/Predicate";
7 import * as Schema from "effect/Schema";
8 import * as Stream from "effect/Stream";
9 import { ChildProcess, ChildProcessSpawner } from "effect/process";
@@ -19,18 +17,21 @@ const oxlintPackageJsonPath = NodeModule.createRequire(
17 NodeModule.createRequire(import.meta.url).resolve("vite-plus/package.json"),
18 ).resolve("oxlint/package.json");
19
22 -class OxlintFixtureFailure extends Data.TaggedError("OxlintFixtureFailure")<{
23 - readonly exitCode: number;
24 - readonly stdout: string;
25 - readonly stderr: string;
26 -}> {
27 - static readonly is = (u: unknown): u is OxlintFixtureFailure =>
28 - Predicate.isTagged(u, "OxlintFixtureFailure");
29 -}
30 -
31 -class OxlintFixtureExpectedFailure extends Data.TaggedError("OxlintFixtureExpectedFailure")<{
32 - readonly ruleName: string;
33 -}> {
20 +class OxlintFixtureFailure extends Schema.TaggedError<OxlintFixtureFailure>()(
21 + "OxlintFixtureFailure",
22 + {
23 + exitCode: Schema.Number,
24 + stdout: Schema.String,
25 + stderr: Schema.String,
26 + },
27 +) {}
28 +
29 +const isOxlintFixtureFailure = Schema.is(OxlintFixtureFailure);
30 +
31 +class OxlintFixtureExpectedFailure extends Schema.TaggedError<OxlintFixtureExpectedFailure>()(
32 + "OxlintFixtureExpectedFailure",
33 + { ruleName: Schema.String },
34 +) {
35 override get message() {
36 return `Expected oxlint to report a failure for rule ${this.ruleName}, but it passed.`;
37 }
@@ -140,7 +141,7 @@ export const createOxlintRuleHarness = (
141 run(source).pipe(
142 Effect.matchEffect({
143 onFailure: (error) =>
143 - OxlintFixtureFailure.is(error)
144 + isOxlintFixtureFailure(error)
145 ? Effect.succeed(
146 `oxlint fixture failed with exit code ${error.exitCode}\n${error.stdout}\n${error.stderr}`,
147 )
packages/client-runtime/src/authorization/remote.ts
+3 -2
@@ -13,6 +13,7 @@ import { hashTelemetryId } from "@t3tools/shared/telemetryId";
13 import * as Effect from "effect/Effect";
14 import * as Option from "effect/Option";
15 import * as Redacted from "effect/Redacted";
16 +import * as Schema from "effect/Schema";
17 import { environmentEndpointUrl } from "../environment/endpoint.ts";
18 import * as ClientCapabilities from "../platform/capabilities.ts";
19 import {
@@ -26,6 +27,7 @@ export { RemoteEnvironmentAuthUndeclaredStatusError } from "../rpc/http.ts";
27 export type RemoteEnvironmentAuthError = RemoteEnvironmentRequestError;
28
29 const DEFAULT_REMOTE_REQUEST_TIMEOUT_MS = 10_000;
30 +const isUndeclaredStatusError = Schema.is(RemoteEnvironmentAuthUndeclaredStatusError);
31
32 const clientMetadataTokenExchangeFields = (
33 clientMetadata: AuthClientPresentationMetadata | undefined,
@@ -205,8 +207,7 @@ const issueWebSocketTicketWithFallback = <E, R>(
207 ? issue(use)
208 : issue(use).pipe(
209 Effect.catchIf(
208 - (error) =>
209 - error instanceof RemoteEnvironmentAuthUndeclaredStatusError && error.status === 404,
210 + (error) => isUndeclaredStatusError(error) && error.status === 404,
211 () => issue(undefined),
212 ),
213 );
packages/client-runtime/src/connection/errors.test.ts
+4 -1
@@ -93,7 +93,10 @@ describe("mapRemoteDpopEnvironmentError", () => {
93 message: "Failed to fetch remote environment endpoint.",
94 cause: new TypeError("Failed to fetch"),
95 }),
96 - new RemoteEnvironmentAuthTimeoutError("https://environment.example.test", 10_000),
96 + new RemoteEnvironmentAuthTimeoutError({
97 + requestUrl: "https://environment.example.test",
98 + timeoutMs: 10_000,
99 + }),
100 ])("suggests another network when the relay endpoint cannot be reached: $_tag", (error) => {
101 const mapped = mapRemoteDpopEnvironmentError(error);
102 expect(mapped).toMatchObject({
packages/client-runtime/src/device/screenshot.ts
+8 -7
@@ -1,13 +1,14 @@
1 // @effect-diagnostics globalFetch:off - This browser transport runs without an Effect runtime, like the live stream.
2 +import * as Schema from "effect/Schema";
3 import { withDeviceHubQuery } from "./hubAccess.ts";
4 import type { DeviceStreamTarget } from "./stream.ts";
5
5 -export class DeviceScreenshotError extends Error {
6 - readonly status: number;
7 -
8 - constructor(status: number) {
9 - super(`Screenshot capture failed (${status}). Try again.`);
10 - this.status = status;
6 +export class DeviceScreenshotError extends Schema.TaggedError<DeviceScreenshotError>()(
7 + "DeviceScreenshotError",
8 + { status: Schema.Number },
9 +) {
10 + override get message(): string {
11 + return `Screenshot capture failed (${this.status}). Try again.`;
12 }
13 }
14
@@ -22,7 +23,7 @@ export async function captureDeviceScreenshot(target: DeviceStreamTarget, signal
23 credentials: target.access.credentials ? "include" : "omit",
24 signal: AbortSignal.any([signal, AbortSignal.timeout(20_000)]),
25 });
25 - if (!response.ok) throw new DeviceScreenshotError(response.status);
26 + if (!response.ok) throw new DeviceScreenshotError({ status: response.status });
27 const image = await response.blob();
28 if (!image.size) throw new Error("The device returned an empty screenshot. Try again.");
29 return image;
packages/client-runtime/src/mcpApps/host.test.ts
+2 -2
@@ -206,7 +206,7 @@ describe("makeMcpAppHost", () => {
206 const { host, sent } = setup({
207 callTool: async (input) => {
208 if (input.name === "delete_everything")
209 - throw new McpAppHostRefusal("Declined by the user.");
209 + throw new McpAppHostRefusal({ message: "Declined by the user." });
210 return { content: [], structuredContent: { ok: true } };
211 },
212 });
@@ -311,7 +311,7 @@ describe("makeMcpAppHost", () => {
311 updateModelContext: async (update) => void contexts.push(update),
312 downloadFile: async (files) => {
313 downloads.push(files);
314 - if (files.length > 1) throw new McpAppHostRefusal("Declined by the user.");
314 + if (files.length > 1) throw new McpAppHostRefusal({ message: "Declined by the user." });
315 },
316 });
317 initialize(host);
packages/client-runtime/src/mcpApps/host.ts
+9 -3
@@ -3,6 +3,7 @@ import { MCP_APP_PROTOCOL_VERSION, type McpAppReference } from "@t3tools/shared/
3 import * as Base64 from "effect/encoding/Base64";
4 import * as Predicate from "effect/Predicate";
5 import * as Result from "effect/Result";
6 +import * as Schema from "effect/Schema";
7
8 const MAX_MESSAGE_BYTES = 256 * 1024;
9 const MAX_PENDING_REQUESTS = 16;
@@ -71,7 +72,12 @@ export interface McpAppCallToolResult {
72 readonly _meta?: unknown;
73 }
74
74 -export class McpAppHostRefusal extends Error {}
75 +export class McpAppHostRefusal extends Schema.TaggedError<McpAppHostRefusal>()(
76 + "McpAppHostRefusal",
77 + { message: Schema.String },
78 +) {}
79 +
80 +const isMcpAppHostRefusal = Schema.is(McpAppHostRefusal);
81
82 export interface McpAppHostOptions {
83 readonly app: McpAppReference;
@@ -141,7 +147,7 @@ function normalizeMcpAppToolResult(result: McpAppCallToolResult): McpAppCallTool
147 }
148
149 const errorMessage = (error: unknown) =>
144 - error instanceof McpAppHostRefusal
150 + isMcpAppHostRefusal(error)
151 ? error.message
152 : error instanceof Error && error.message.trim() !== ""
153 ? error.message
@@ -342,7 +348,7 @@ export function makeMcpAppHost(options: McpAppHostOptions): McpAppHost {
348 options.downloadFile(files).then(
349 () => ({}),
350 (error: unknown) =>
345 - error instanceof McpAppHostRefusal ? { isError: true } : Promise.reject(error),
351 + isMcpAppHostRefusal(error) ? { isError: true } : Promise.reject(error),
352 ),
353 );
354 return;
packages/client-runtime/src/platform/threadCacheEncoding.ts
+4 -2
@@ -2,7 +2,6 @@ import {
2 omitLocalVisibleTurnItems,
3 restoreLocalVisibleTurnItems,
4 } from "@t3tools/shared/orchestrationV2BoundedSnapshot";
5 -import * as Data from "effect/Data";
5 import * as Effect from "effect/Effect";
6 import * as Schema from "effect/Schema";
7
@@ -23,7 +22,10 @@ const StoredCompactThreadSnapshot = StoredOrchestrationThreadSnapshot.mapFields(
22 })),
23 }));
24
26 -class InvalidThreadCache extends Data.TaggedError("InvalidThreadCache") {}
25 +class InvalidThreadCache extends Schema.TaggedError<InvalidThreadCache>()(
26 + "InvalidThreadCache",
27 + {},
28 +) {}
29
30 const encodeCompact = Schema.encodeEffect(Schema.fromJsonString(StoredCompactThreadSnapshot));
31 const decodeCompatible = Schema.decodeUnknownEffect(
packages/client-runtime/src/relay/dpopProof.ts
+5 -5
@@ -5,7 +5,7 @@ import * as Cache from "effect/Cache";
5 import * as Clock from "effect/Clock";
6 import * as Digest from "effect/crypto/Digest";
7 import * as SecureRandom from "effect/crypto/SecureRandom";
8 -import * as Data from "effect/Data";
8 +import * as Schema from "effect/Schema";
9 import * as Duration from "effect/Duration";
10 import * as Effect from "effect/Effect";
11 import * as Base64Url from "effect/encoding/Base64Url";
@@ -18,10 +18,10 @@ import {
18 ManagedRelayDpopSigner,
19 } from "./managedRelay.ts";
20
21 -export class DpopProofError extends Data.TaggedError("DpopProofError")<{
22 - readonly message: string;
23 - readonly cause?: unknown;
24 -}> {}
21 +export class DpopProofError extends Schema.TaggedError<DpopProofError>()("DpopProofError", {
22 + message: Schema.String,
23 + cause: Schema.optional(Schema.Defect()),
24 +}) {}
25
26 /** A P-256 proof key. `sign` returns the raw `r‖s` ES256 signature over the JWS signing input. */
27 export interface DpopProofKey {
packages/client-runtime/src/relay/managedRelayState.ts
+7 -5
@@ -2,7 +2,6 @@ import type { EnvironmentId } from "@t3tools/contracts";
2 import { decodeRelayJwt } from "@t3tools/shared/relayJwt";
3 import * as Cause from "effect/Cause";
4 import * as Clock from "effect/Clock";
5 -import * as Data from "effect/Data";
5 import * as Effect from "effect/Effect";
6 import * as Schema from "effect/Schema";
7 import * as Stream from "effect/Stream";
@@ -50,10 +49,13 @@ export interface ManagedRelayQueryEvent {
49 readonly traceId?: string | null;
50 }
51
53 -export class ManagedRelaySessionError extends Data.TaggedError("ManagedRelaySessionError")<{
54 - readonly message: string;
55 - readonly cause?: unknown;
56 -}> {}
52 +export class ManagedRelaySessionError extends Schema.TaggedError<ManagedRelaySessionError>()(
53 + "ManagedRelaySessionError",
54 + {
55 + message: Schema.String,
56 + cause: Schema.optional(Schema.Defect()),
57 + },
58 +) {}
59
60 export const managedRelaySessionAtom = Atom.make<ManagedRelaySession | null>(null).pipe(
61 Atom.keepAlive,
packages/client-runtime/src/rpc/http.ts
+33 -38
@@ -9,7 +9,6 @@ import {
9 type EnvironmentScopeRequiredError,
10 } from "@t3tools/contracts";
11 import * as HttpObservability from "@t3tools/shared/httpObservability";
12 -import * as Data from "effect/Data";
12 import * as Duration from "effect/Duration";
13 import * as Effect from "effect/Effect";
14 import * as Layer from "effect/Layer";
@@ -20,52 +19,48 @@ import * as HttpApiClient from "effect/http-api/HttpApiClient";
19
20 const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
21
23 -export class RemoteEnvironmentAuthFetchError extends Data.TaggedError(
22 +export class RemoteEnvironmentAuthFetchError extends Schema.TaggedError<RemoteEnvironmentAuthFetchError>()(
23 "RemoteEnvironmentAuthFetchError",
25 -)<{
26 - readonly message: string;
27 - readonly cause: unknown;
28 -}> {}
24 + {
25 + message: Schema.String,
26 + cause: Schema.Defect(),
27 + },
28 +) {}
29
30 -class RemoteEnvironmentAuthInvalidJsonError extends Data.TaggedError(
30 +class RemoteEnvironmentAuthInvalidJsonError extends Schema.TaggedError<RemoteEnvironmentAuthInvalidJsonError>()(
31 "RemoteEnvironmentAuthInvalidJsonError",
32 -)<{
33 - readonly message: string;
34 - readonly cause: unknown;
35 -}> {}
32 + {
33 + message: Schema.String,
34 + cause: Schema.Defect(),
35 + },
36 +) {}
37
37 -export class RemoteEnvironmentAuthUndeclaredStatusError extends Data.TaggedError(
38 +export class RemoteEnvironmentAuthUndeclaredStatusError extends Schema.TaggedError<RemoteEnvironmentAuthUndeclaredStatusError>()(
39 "RemoteEnvironmentAuthUndeclaredStatusError",
39 -)<{
40 - readonly message: string;
41 - readonly status: number;
42 - readonly requestUrl: string;
43 -}> {
44 - constructor(requestUrl: string, status: number) {
45 - super({
46 - message: `Remote environment endpoint ${requestUrl} returned undeclared status ${status}.`,
47 - requestUrl,
48 - status,
49 - });
40 + {
41 + status: Schema.Number,
42 + requestUrl: Schema.String,
43 + },
44 +) {
45 + override get message(): string {
46 + return `Remote environment endpoint ${this.requestUrl} returned undeclared status ${this.status}.`;
47 }
48 }
49
53 -export class RemoteEnvironmentAuthTimeoutError extends Data.TaggedError(
50 +export class RemoteEnvironmentAuthTimeoutError extends Schema.TaggedError<RemoteEnvironmentAuthTimeoutError>()(
51 "RemoteEnvironmentAuthTimeoutError",
55 -)<{
56 - readonly message: string;
57 - readonly requestUrl: string;
58 - readonly timeoutMs: number;
59 -}> {
60 - constructor(requestUrl: string, timeoutMs: number) {
61 - super({
62 - message: `Remote environment endpoint ${requestUrl} timed out after ${timeoutMs}ms.`,
63 - requestUrl,
64 - timeoutMs,
65 - });
52 + {
53 + requestUrl: Schema.String,
54 + timeoutMs: Schema.Number,
55 + },
56 +) {
57 + override get message(): string {
58 + return `Remote environment endpoint ${this.requestUrl} timed out after ${this.timeoutMs}ms.`;
59 }
60 }
61
62 +const isRemoteEnvironmentAuthTimeoutError = Schema.is(RemoteEnvironmentAuthTimeoutError);
63 +
64 export type RemoteEnvironmentRequestError =
65 | EnvironmentRequestInvalidError
66 | EnvironmentAuthInvalidError
@@ -122,7 +117,7 @@ const failRemoteRequest = (
117 requestUrl: string,
118 cause: unknown,
119 ): Effect.Effect<never, RemoteEnvironmentRequestError> => {
125 - if (cause instanceof RemoteEnvironmentAuthTimeoutError) {
120 + if (isRemoteEnvironmentAuthTimeoutError(cause)) {
121 return Effect.fail(cause);
122 }
123 if (isEnvironmentHttpCommonError(cause)) {
@@ -140,7 +135,7 @@ const failRemoteRequest = (
135 const response = cause.response;
136 if (response.status < 200 || response.status >= 300) {
137 return Effect.fail(
143 - new RemoteEnvironmentAuthUndeclaredStatusError(requestUrl, response.status),
138 + new RemoteEnvironmentAuthUndeclaredStatusError({ requestUrl, status: response.status }),
139 );
140 }
141 return Effect.fail(
@@ -167,7 +162,7 @@ export const executeEnvironmentHttpRequest = <A, E, R>(
162 Effect.timeoutOption(Duration.millis(timeoutMs)),
163 Effect.flatMap(
164 Option.match({
170 - onNone: () => Effect.fail(new RemoteEnvironmentAuthTimeoutError(requestUrl, timeoutMs)),
165 + onNone: () => Effect.fail(new RemoteEnvironmentAuthTimeoutError({ requestUrl, timeoutMs })),
166 onSome: Effect.succeed,
167 }),
168 ),
packages/client-runtime/src/state/environmentHttpAuth.ts
+4 -1
@@ -247,7 +247,10 @@ const executeEnvironmentRequest = Effect.fnUntraced(function* <
247 duration: input.timeoutMs,
248 orElse: () =>
249 Effect.fail(
250 - new RemoteEnvironmentAuthTimeoutError(requestUrlFor(httpBaseUrl), input.timeoutMs),
250 + new RemoteEnvironmentAuthTimeoutError({
251 + requestUrl: requestUrlFor(httpBaseUrl),
252 + timeoutMs: input.timeoutMs,
253 + }),
254 ),
255 }),
256 );
packages/client-runtime/src/state/peerPairingCode.ts
+8 -5
@@ -4,7 +4,7 @@
4 * It carries exactly what an agent sign-in with the chosen access needs.
5 */
6 import { type AuthMcpClientAccess, mcpClientScopes } from "@t3tools/contracts";
7 -import * as Data from "effect/Data";
7 +import * as Schema from "effect/Schema";
8 import * as Effect from "effect/Effect";
9 import type * as HttpClient from "effect/http/HttpClient";
10 import * as Option from "effect/Option";
@@ -23,10 +23,13 @@ const MINT_TIMEOUT_MS = 8_000;
23 const PEER_PAIRING_CODE_LABEL = "T3 Code link";
24
25 /** Minting failed; the user can still paste a code from the other environment. */
26 -export class PeerPairingCodeError extends Data.TaggedError("PeerPairingCodeError")<{
27 - readonly reason: "not_allowed" | "unavailable";
28 - readonly cause: unknown;
29 -}> {
26 +export class PeerPairingCodeError extends Schema.TaggedError<PeerPairingCodeError>()(
27 + "PeerPairingCodeError",
28 + {
29 + reason: Schema.Literals(["not_allowed", "unavailable"]),
30 + cause: Schema.Defect(),
31 + },
32 +) {
33 override get message(): string {
34 return this.reason === "not_allowed"
35 ? "Your session there cannot create pairing codes. Paste a code from there instead."
packages/client-runtime/src/state/pullRequests.test.ts
+2 -2
@@ -11,7 +11,7 @@ import {
11 type AuthSessionState,
12 } from "@t3tools/contracts";
13 import { expect, it } from "@effect/vitest";
14 -import * as Data from "effect/Data";
14 +import * as Schema from "effect/Schema";
15 import * as Deferred from "effect/Deferred";
16 import * as Fiber from "effect/Fiber";
17 import * as Effect from "effect/Effect";
@@ -53,7 +53,7 @@ const trustedRouting = {
53 forget: () => Effect.void,
54 };
55
56 -class MutationRefused extends Data.TaggedError("MutationRefused") {}
56 +class MutationRefused extends Schema.TaggedError<MutationRefused>()("MutationRefused", {}) {}
57
58 for (const scenario of [
59 "prefers the local environment with the same github account",
packages/client-runtime/src/state/pullRequests.ts
+3 -3
@@ -24,7 +24,6 @@ import {
24 type PullRequestSummary,
25 type VcsStatusResult,
26 } from "@t3tools/contracts";
27 -import * as Data from "effect/Data";
27 import * as Effect from "effect/Effect";
28 import * as Schema from "effect/Schema";
29 import { persistPullRequestStats } from "./pullRequestStatsPersistence.ts";
@@ -53,9 +52,10 @@ export {
52 export * as PullRequestDiffLoader from "./pullRequestDiffHttp.ts";
53
54 /** @public Required to name the error in consumers' inferred pull request results. */
56 -export class EnvironmentHttpConnectionNotReadyError extends Data.TaggedError(
55 +export class EnvironmentHttpConnectionNotReadyError extends Schema.TaggedError<EnvironmentHttpConnectionNotReadyError>()(
56 "EnvironmentHttpConnectionNotReadyError",
58 -)<{ readonly message: string }> {}
57 + { message: Schema.String },
58 +) {}
59
60 const LINKED_PULL_REQUEST_IDLE_TTL_MS = 5_000;
61
packages/client-runtime/src/state/session.ts
+3 -2
@@ -1,6 +1,6 @@
1 import { pipe } from "effect/Function";
2 import type { AuthSessionState, EnvironmentId, ServerConfig } from "@t3tools/contracts";
3 -import * as Data from "effect/Data";
3 +import * as Schema from "effect/Schema";
4 import * as Effect from "effect/Effect";
5 import * as Option from "effect/Option";
6 import * as Stream from "effect/Stream";
@@ -20,8 +20,9 @@ import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAut
20 import { followStreamInEnvironment } from "./environmentStreams.ts";
21
22 /** @public Required to name the error in consumers' inferred session results. */
23 -export class SessionHttpClientUnavailable extends Data.TaggedError(
23 +export class SessionHttpClientUnavailable extends Schema.TaggedError<SessionHttpClientUnavailable>()(
24 "SessionHttpClientUnavailable",
25 + {},
26 ) {}
27
28 function initialConfigOption<E>(
packages/client-runtime/src/voice-input/controller.test.ts
+4 -4
@@ -120,10 +120,10 @@ describe("VoiceInputController", () => {
120 expect(unsupported.controller.currentState.error).toContain("not available");
121 expect(unsupported.recorder.record).not.toHaveBeenCalled();
122
123 - const reason = new VoiceTranscriptionError(
124 - "unavailable",
125 - "This device requires iOS 26 or later.",
126 - );
123 + const reason = new VoiceTranscriptionError({
124 + code: "unavailable",
125 + message: "This device requires iOS 26 or later.",
126 + });
127 const unavailable = createHarness({
128 getTranscriber: () => ({
129 prepare: async () => {
packages/client-runtime/src/voice-input/controller.ts
+5 -4
@@ -1,3 +1,4 @@
1 +import * as Schema from "effect/Schema";
2 import { replaceTextRange } from "@t3tools/shared/composerTrigger";
3
4 import {
@@ -6,6 +7,8 @@ import {
7 type VoiceTranscriber,
8 } from "./transcription.ts";
9
10 +const isVoiceTranscriptionError = Schema.is(VoiceTranscriptionError);
11 +
12 export const VOICE_RECORDING_LIMIT_SECONDS = 5 * 60;
13
14 export type VoiceInputPhase = "idle" | "preparing" | "recording" | "transcribing" | "error";
@@ -171,7 +174,7 @@ function preparationErrorMessage(error: unknown): string {
174 if (errorCode(error) === "unsupported-locale") {
175 return "Voice transcription is not available for this language.";
176 }
174 - return error instanceof VoiceTranscriptionError
177 + return isVoiceTranscriptionError(error)
178 ? error.message
179 : "Could not prepare voice transcription.";
180 }
@@ -180,9 +183,7 @@ function transcriptionErrorMessage(error: unknown): string {
183 if (error instanceof Error && error.message === "voice-operation-busy") {
184 return "Voice transcription is still finishing. Try again shortly.";
185 }
183 - return error instanceof VoiceTranscriptionError
184 - ? error.message
185 - : "Could not transcribe this recording.";
186 + return isVoiceTranscriptionError(error) ? error.message : "Could not transcribe this recording.";
187 }
188
189 const IDLE_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null };
packages/client-runtime/src/voice-input/transcription.ts
+22 -16
@@ -1,3 +1,5 @@
1 +import * as Schema from "effect/Schema";
2 +
3 /** Cancellation is cooperative: settle only after the underlying work has stopped. */
4 export type VoiceTranscriptionOptions = {
5 readonly signal: AbortSignal;
@@ -12,25 +14,29 @@ export type VoiceTranscriber = {
14 readonly prepare: (options: VoiceTranscriptionOptions) => Promise<PreparedVoiceTranscription>;
15 };
16
15 -export type VoiceTranscriptionErrorCode =
16 - | "unavailable"
17 - | "unsupported-locale"
18 - | "preparation-failed"
19 - | "transcription-failed"
20 - | "cancelled";
21 -
22 -export class VoiceTranscriptionError extends Error {
23 - readonly code: VoiceTranscriptionErrorCode;
17 +const VoiceTranscriptionErrorCode = Schema.Literals([
18 + "unavailable",
19 + "unsupported-locale",
20 + "preparation-failed",
21 + "transcription-failed",
22 + "cancelled",
23 +]);
24 +export type VoiceTranscriptionErrorCode = typeof VoiceTranscriptionErrorCode.Type;
25
25 - constructor(code: VoiceTranscriptionErrorCode, message: string, options?: ErrorOptions) {
26 - super(message, options);
27 - this.name = "VoiceTranscriptionError";
28 - this.code = code;
29 - }
30 -}
26 +export class VoiceTranscriptionError extends Schema.TaggedError<VoiceTranscriptionError>()(
27 + "VoiceTranscriptionError",
28 + {
29 + code: VoiceTranscriptionErrorCode,
30 + message: Schema.String,
31 + cause: Schema.optional(Schema.Defect()),
32 + },
33 +) {}
34
35 export function throwIfVoiceTranscriptionAborted(signal: AbortSignal): void {
36 if (signal.aborted) {
34 - throw new VoiceTranscriptionError("cancelled", "Voice transcription was cancelled.");
37 + throw new VoiceTranscriptionError({
38 + code: "cancelled",
39 + message: "Voice transcription was cancelled.",
40 + });
41 }
42 }
packages/provider-acp/src/server/mcpOverAcpBridge.ts
+32 -24
@@ -1,5 +1,6 @@
1 // @effect-diagnostics globalJsonInEffect:off
2 import * as Effect from "effect/Effect";
3 +import * as Schema from "effect/Schema";
4 import * as Semaphore from "effect/Semaphore";
5 import * as Stream from "effect/Stream";
6 import type * as AcpSchema from "effect-acp/compat";
@@ -23,15 +24,20 @@ interface Connection {
24 nextRequestId: number;
25 }
26
26 -export class AcpMcpOverAcpError extends Error {
27 - readonly _tag = "AcpMcpOverAcpError";
28 - override readonly name = "AcpMcpOverAcpError";
29 -}
27 +export class AcpMcpOverAcpError extends Schema.TaggedError<AcpMcpOverAcpError>()(
28 + "AcpMcpOverAcpError",
29 + { message: Schema.String, cause: Schema.optional(Schema.Defect()) },
30 +) {}
31 +
32 +const isAcpMcpOverAcpError = Schema.is(AcpMcpOverAcpError);
33
34 const bridgeError = (cause: unknown): AcpMcpOverAcpError =>
32 - cause instanceof AcpMcpOverAcpError
35 + isAcpMcpOverAcpError(cause)
36 ? cause
34 - : new AcpMcpOverAcpError(cause instanceof Error ? cause.message : String(cause), { cause });
37 + : new AcpMcpOverAcpError({
38 + message: cause instanceof Error ? cause.message : String(cause),
39 + cause,
40 + });
41
42 const asEnvelope = (value: unknown): JsonRpcEnvelope | null =>
43 typeof value === "object" && value !== null && !Array.isArray(value)
@@ -88,7 +94,11 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun
94 Effect.suspend(() => {
95 const connection = connections.get(connectionId);
96 return connection === undefined
91 - ? Effect.fail(new AcpMcpOverAcpError(`Unknown MCP-over-ACP connection "${connectionId}".`))
97 + ? Effect.fail(
98 + new AcpMcpOverAcpError({
99 + message: `Unknown MCP-over-ACP connection "${connectionId}".`,
100 + }),
101 + )
102 : Effect.succeed(connection);
103 });
104
@@ -107,7 +117,7 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun
117 Effect.gen(function* () {
118 const body = JSON.stringify(message);
119 if (Buffer.byteLength(body) > MAX_MESSAGE_BYTES) {
110 - return yield* Effect.fail(new AcpMcpOverAcpError("MCP-over-ACP message exceeds 8 MiB."));
120 + return yield* new AcpMcpOverAcpError({ message: "MCP-over-ACP message exceeds 8 MiB." });
121 }
122 const response = yield* Effect.tryPromise({
123 try: (signal) =>
@@ -134,9 +144,9 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun
144 yield* Effect.promise(
145 () => response.body?.cancel().catch(() => undefined) ?? Promise.resolve(),
146 );
137 - return yield* Effect.fail(
138 - new AcpMcpOverAcpError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`),
139 - );
147 + return yield* new AcpMcpOverAcpError({
148 + message: `T3 Code MCP endpoint responded with HTTP ${response.status}.`,
149 + });
150 }
151 const payloads = [...(yield* Stream.runCollect(responsePayloads(response, bridgeError)))];
152 for (const payload of payloads) {
@@ -169,11 +179,9 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun
179 catch: bridgeError,
180 });
181 if (!response.ok && response.status !== 404) {
172 - return yield* Effect.fail(
173 - new AcpMcpOverAcpError(
174 - `T3 Code MCP endpoint rejected disconnect with HTTP ${response.status}.`,
175 - ),
176 - );
182 + return yield* new AcpMcpOverAcpError({
183 + message: `T3 Code MCP endpoint rejected disconnect with HTTP ${response.status}.`,
184 + });
185 }
186 yield* Effect.promise(
187 () => response.body?.cancel().catch(() => undefined) ?? Promise.resolve(),
@@ -185,12 +193,12 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun
193 return {
194 connect: Effect.fn("mcpOverAcpBridge.connect")(function* (request) {
195 if (request.serverId !== "t3-code") {
188 - return yield* Effect.fail(
189 - new AcpMcpOverAcpError(`Unknown ACP MCP server "${request.serverId}".`),
190 - );
196 + return yield* new AcpMcpOverAcpError({
197 + message: `Unknown ACP MCP server "${request.serverId}".`,
198 + });
199 }
200 if (connections.size >= MAX_CONNECTIONS) {
193 - return yield* Effect.fail(new AcpMcpOverAcpError("Too many MCP-over-ACP connections."));
201 + return yield* new AcpMcpOverAcpError({ message: "Too many MCP-over-ACP connections." });
202 }
203 const connectionId = yield* options.allocateConnectionId;
204 connections.set(connectionId, {
@@ -213,12 +221,12 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun
221 const response = payloads.find((payload) => asEnvelope(payload)?.id === id);
222 const envelope = asEnvelope(response);
223 if (envelope === null) {
216 - return yield* Effect.fail(
217 - new AcpMcpOverAcpError("MCP server did not return a matching response."),
218 - );
224 + return yield* new AcpMcpOverAcpError({
225 + message: "MCP server did not return a matching response.",
226 + });
227 }
228 if (envelope.error !== undefined) {
221 - return yield* Effect.fail(new AcpMcpOverAcpError(errorMessage(envelope.error)));
229 + return yield* new AcpMcpOverAcpError({ message: errorMessage(envelope.error) });
230 }
231 return (envelope.result ?? null) as AcpSchema.MessageMcpResponse;
232 }),
packages/provider-cursor/src/server/CursorSdk.test.ts
+1
@@ -6,6 +6,7 @@ import { vi } from "vite-plus/test";
6 import * as CursorSdk from "./CursorSdk.ts";
7
8 // Shaped like the SDK's minified class: the constructor is not named after the error.
9 +// @effect-diagnostics-next-line extendsNativeError:off - mimics the Cursor SDK's own native Error class.
10 class o extends Error {
11 override name = "WriteIterableClosedError";
12 }
packages/provider-cursor/src/server/sdk.test.ts
+1
@@ -1,6 +1,7 @@
1 import { describe, expect, it, vi } from "vite-plus/test";
2
3 const fixture = vi.hoisted(() => {
4 + // @effect-diagnostics-next-line extendsNativeError:off - stands in for the Cursor SDK's native Error classes.
5 class SdkError extends Error {}
6 const sdk = {
7 CursorSdkError: SdkError,
packages/provider-grok/src/server/adapter.ts
+5 -4
@@ -79,6 +79,8 @@ import {
79 type AcpAdapterV2RuntimeInput,
80 } from "@t3tools/provider-acp/server/adapter";
81
82 +const isXAiPromptFailureText = Schema.is(XAiPromptFailureText);
83 +
84 export const GROK_PROVIDER = ProviderDriverKind.make("grok");
85 const GROK_DRIVER_KIND = GROK_PROVIDER;
86 export const GROK_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(GROK_DRIVER_KIND);
@@ -306,10 +308,9 @@ export function makeGrokAcpAdapterFlavor(
308 cause,
309 ...(isAcpRequestError(cause)
310 ? {
309 - message:
310 - cause.cause instanceof XAiPromptFailureText
311 - ? cause.cause.message
312 - : cause.errorMessage,
311 + message: isXAiPromptFailureText(cause.cause)
312 + ? cause.cause.message
313 + : cause.errorMessage,
314 code: String(cause.code),
315 class: cause.code === xAiRateLimitedErrorCode ? "usage_limit" : "provider_error",
316 }
packages/provider-grok/src/server/xaiAcpExtension.ts
+7 -2
@@ -1285,14 +1285,19 @@ function xAiPromptFailure(
1285 code: -32603,
1286 errorMessage: "Grok ended the turn with an error.",
1287 operation: "receive-response",
1288 - ...(agentResult === undefined ? {} : { cause: new XAiPromptFailureText(agentResult) }),
1288 + ...(agentResult === undefined
1289 + ? {}
1290 + : { cause: new XAiPromptFailureText({ message: agentResult }) }),
1291 });
1292 }
1293 return null;
1294 }
1295
1296 /** Keep unbounded provider text out of structured attributes; read only at presentation. */
1295 -export class XAiPromptFailureText extends Error {}
1297 +export class XAiPromptFailureText extends Schema.TaggedError<XAiPromptFailureText>()(
1298 + "XAiPromptFailureText",
1299 + { message: Schema.String },
1300 +) {}
1301
1302 const registerXAiPromptCompletionFallback = (
1303 pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
packages/provider-opencode/src/server/OpenCodeRuntime.ts
+12 -9
@@ -13,7 +13,6 @@ import {
13 } from "@opencode-ai/sdk/v2";
14 import * as Cause from "effect/Cause";
15 import * as Context from "effect/Context";
16 -import * as Data from "effect/Data";
16 import * as Deferred from "effect/Deferred";
17 import * as Effect from "effect/Effect";
18 import * as Exit from "effect/Exit";
@@ -102,14 +101,18 @@ export interface OpenCodeServerConnection {
101 }
102
103 const OPENCODE_RUNTIME_ERROR_TAG = "OpenCodeRuntimeError";
105 -export class OpenCodeRuntimeError extends Data.TaggedError(OPENCODE_RUNTIME_ERROR_TAG)<{
106 - readonly operation: string;
107 - readonly cause?: unknown;
108 - readonly detail: string;
109 - readonly reason?: OpenCodeStartupFailureReason;
110 -}> {}
111 -
112 -export type OpenCodeStartupFailureReason = "databaseLocked";
104 +const OpenCodeStartupFailureReason = Schema.Literal("databaseLocked");
105 +export type OpenCodeStartupFailureReason = typeof OpenCodeStartupFailureReason.Type;
106 +
107 +export class OpenCodeRuntimeError extends Schema.TaggedError<OpenCodeRuntimeError>()(
108 + OPENCODE_RUNTIME_ERROR_TAG,
109 + {
110 + operation: Schema.String,
111 + cause: Schema.optional(Schema.Defect()),
112 + detail: Schema.String,
113 + reason: Schema.optional(OpenCodeStartupFailureReason),
114 + },
115 +) {}
116
117 // Classify stderr database locks at exit so callers need not parse diagnostics.
118 function classifyStartupExit(stderr: string): OpenCodeStartupFailureReason | undefined {
packages/provider-opencode/src/server/status.ts
+8 -6
@@ -6,7 +6,7 @@ import {
6 } from "@t3tools/contracts";
7 import type { OpenCodeSettings } from "../settings.ts";
8 import * as Cause from "effect/Cause";
9 -import * as Data from "effect/Data";
9 +import * as Schema from "effect/Schema";
10 import * as DateTime from "effect/DateTime";
11 import * as Effect from "effect/Effect";
12 import * as Schedule from "effect/Schedule";
@@ -30,10 +30,12 @@ const OPENCODE_PRESENTATION = {
30 showInteractionModeToggle: false,
31 } as const;
32
33 -class OpenCodeProbeError extends Data.TaggedError("OpenCodeProbeError")<{
34 - readonly cause?: unknown;
35 - readonly detail: string;
36 -}> {}
33 +class OpenCodeProbeError extends Schema.TaggedError<OpenCodeProbeError>()("OpenCodeProbeError", {
34 + cause: Schema.optional(Schema.Defect()),
35 + detail: Schema.String,
36 +}) {}
37 +
38 +const isOpenCodeProbeError = Schema.is(OpenCodeProbeError);
39
40 function normalizeProbeMessage(message: string): string | undefined {
41 const trimmed = message.trim();
@@ -50,7 +52,7 @@ function normalizeProbeMessage(message: string): string | undefined {
52 }
53
54 function normalizedErrorMessage(cause: unknown): string | undefined {
53 - if (cause instanceof OpenCodeProbeError) {
55 + if (isOpenCodeProbeError(cause)) {
56 return normalizeProbeMessage(cause.detail);
57 }
58
packages/shared/src/Net.ts
+5 -5
@@ -1,15 +1,15 @@
1 import * as NodeNet from "node:net";
2
3 -import * as Data from "effect/Data";
3 import * as Effect from "effect/Effect";
4 import * as Layer from "effect/Layer";
5 import * as Context from "effect/Context";
6 import * as Predicate from "effect/Predicate";
7 +import * as Schema from "effect/Schema";
8
9 -export class NetError extends Data.TaggedError("NetError")<{
10 - readonly message: string;
11 - readonly cause?: unknown;
12 -}> {}
9 +export class NetError extends Schema.TaggedError<NetError>()("NetError", {
10 + message: Schema.String,
11 + cause: Schema.optional(Schema.Defect()),
12 +}) {}
13
14 const isErrnoExceptionWithCode = (
15 cause: unknown,
packages/shared/src/managedPolicyFile.ts
+11 -9
@@ -186,14 +186,16 @@ const ERROR_NO_MORE_ITEMS = 259;
186 // Value and key names are at most 16,383 characters.
187 const MAX_NAME_CHARS = 16_384;
188
189 -class Win32Failure extends Error {
190 - readonly code: number;
191 - constructor(code: number) {
192 - super(`Windows error ${code}`);
193 - this.code = code;
189 +class Win32Failure extends Schema.TaggedError<Win32Failure>()("Win32Failure", {
190 + code: Schema.Number,
191 +}) {
192 + override get message(): string {
193 + return `Windows error ${this.code}`;
194 }
195 }
196
197 +const isWin32Failure = Schema.is(Win32Failure);
198 +
199 /**
200 * Each app passes how it loads ffi-rs: a server single-executable resolves packages on disk only
201 * through `require`, and the desktop's CommonJS bundle loads them with `import()`.
@@ -263,7 +265,7 @@ export const layerWindowsRegistry = (loadFfi: () => Promise<typeof import("ffi-r
265 const handle = Buffer.alloc(8);
266 const opened = api.open(subkey, handle);
267 if (opened === ERROR_FILE_NOT_FOUND) return undefined;
266 - if (opened !== 0) throw new Win32Failure(opened);
268 + if (opened !== 0) throw new Win32Failure({ code: opened });
269 const key = handle.readBigInt64LE();
270 try {
271 const name = Buffer.alloc(MAX_NAME_CHARS * 2);
@@ -285,7 +287,7 @@ export const layerWindowsRegistry = (loadFfi: () => Promise<typeof import("ffi-r
287 code = attempt();
288 }
289 if (code === ERROR_NO_MORE_ITEMS) break;
288 - if (code !== 0) throw new Win32Failure(code);
290 + if (code !== 0) throw new Win32Failure({ code: code });
291 const valueName = name.subarray(0, chars.readUInt32LE() * 2).toString("utf16le");
292 const stored = data.subarray(0, bytes.readUInt32LE());
293 const valueType = type.readUInt32LE();
@@ -306,7 +308,7 @@ export const layerWindowsRegistry = (loadFfi: () => Promise<typeof import("ffi-r
308 chars.writeUInt32LE(MAX_NAME_CHARS);
309 const code = api.enumKey(key, index, name, chars);
310 if (code === ERROR_NO_MORE_ITEMS) break;
309 - if (code !== 0) throw new Win32Failure(code);
311 + if (code !== 0) throw new Win32Failure({ code: code });
312 subkeys.push(name.subarray(0, chars.readUInt32LE() * 2).toString("utf16le"));
313 }
314 return { values, subkeys };
@@ -322,7 +324,7 @@ export const layerWindowsRegistry = (loadFfi: () => Promise<typeof import("ffi-r
324 try: () => readKey(api, subkey),
325 catch: (cause) =>
326 new WindowsRegistryError(
325 - cause instanceof Win32Failure ? { code: cause.code, cause } : { cause },
327 + isWin32Failure(cause) ? { code: cause.code, cause } : { cause },
328 ),
329 });
330 }),
packages/shared/src/relayClient.ts
+27 -18
@@ -66,24 +66,33 @@ class RelayClientLockRemoveError extends Schema.TaggedError<RelayClientLockRemov
66 }
67 }
68
69 -export class RelayClientInstallError extends Data.TaggedError("RelayClientInstallError")<{
70 - readonly reason:
71 - | "download_failed"
72 - | "invalid_checksum"
73 - | "install_locked"
74 - | "managed_by_policy"
75 - | "override_missing"
76 - | "unsupported_platform"
77 - | "validation_failed"
78 - | "write_failed";
79 - readonly message: string;
80 - readonly cause?: unknown;
81 -}> {}
69 +export class RelayClientInstallError extends Schema.TaggedError<RelayClientInstallError>()(
70 + "RelayClientInstallError",
71 + {
72 + reason: Schema.Literals([
73 + "download_failed",
74 + "invalid_checksum",
75 + "install_locked",
76 + "managed_by_policy",
77 + "override_missing",
78 + "unsupported_platform",
79 + "validation_failed",
80 + "write_failed",
81 + ]),
82 + message: Schema.String,
83 + cause: Schema.optional(Schema.Defect()),
84 + },
85 +) {}
86
83 -class CloudflaredCommandError extends Data.TaggedError("CloudflaredCommandError")<{
84 - readonly command: string;
85 - readonly exitCode: number;
86 -}> {}
87 +const isRelayClientInstallError = Schema.is(RelayClientInstallError);
88 +
89 +class CloudflaredCommandError extends Schema.TaggedError<CloudflaredCommandError>()(
90 + "CloudflaredCommandError",
91 + {
92 + command: Schema.String,
93 + exitCode: Schema.Number,
94 + },
95 +) {}
96
97 export interface CloudflaredReleaseAsset {
98 readonly url: string;
@@ -668,7 +677,7 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function
677 }).pipe(
678 Effect.scoped,
679 Effect.catchIf(
671 - (cause) => !(cause instanceof RelayClientInstallError),
680 + (cause) => !isRelayClientInstallError(cause),
681 (cause) =>
682 Effect.fail(
683 new RelayClientInstallError({
packages/source-control-github/src/server/GitHubSourceControlProvider.ts
+4 -5
@@ -1,5 +1,4 @@
1 import { settingsSecretLiteral, SourceControlProviderKind } from "@t3tools/contracts";
2 -import * as Data from "effect/Data";
2 import * as DateTime from "effect/DateTime";
3 import * as Effect from "effect/Effect";
4 import * as FileSystem from "effect/FileSystem";
@@ -318,10 +317,10 @@ export const makeDiscovery = Effect.gen(function* () {
317 } satisfies SourceControlManagedCliDiscoverySpec;
318 });
319
321 -class GitHubFailure extends Data.TaggedError("GitHubFailure")<{
322 - readonly detail: string;
323 - readonly cause: unknown;
324 -}> {}
320 +class GitHubFailure extends Schema.TaggedError<GitHubFailure>()("GitHubFailure", {
321 + detail: Schema.String,
322 + cause: Schema.Defect(),
323 +}) {}
324
325 const failure = (detail: string, cause?: unknown) => new GitHubFailure({ detail, cause });
326
packages/ssh/src/errors.ts
+62 -47
@@ -1,47 +1,62 @@
1 -import * as Data from "effect/Data";
2 -
3 -export class SshHostDiscoveryError extends Data.TaggedError("SshHostDiscoveryError")<{
4 - readonly message: string;
5 - readonly cause: unknown;
6 -}> {}
7 -
8 -export class SshInvalidTargetError extends Data.TaggedError("SshInvalidTargetError")<{
9 - readonly message: string;
10 -}> {}
11 -
12 -export class SshCommandError extends Data.TaggedError("SshCommandError")<{
13 - readonly message: string;
14 - readonly command: readonly string[];
15 - readonly exitCode: number | null;
16 - readonly stderr: string;
17 - readonly stdout?: string;
18 - readonly cause?: unknown;
19 -}> {}
20 -
21 -export class SshLaunchError extends Data.TaggedError("SshLaunchError")<{
22 - readonly message: string;
23 - readonly stdout: string;
24 - readonly cause?: unknown;
25 -}> {}
26 -
27 -export class SshPairingError extends Data.TaggedError("SshPairingError")<{
28 - readonly message: string;
29 - readonly stdout: string;
30 - readonly cause?: unknown;
31 -}> {}
32 -
33 -export class SshHttpBridgeError extends Data.TaggedError("SshHttpBridgeError")<{
34 - readonly message: string;
35 - readonly status?: number;
36 - readonly cause?: unknown;
37 -}> {}
38 -
39 -export class SshReadinessError extends Data.TaggedError("SshReadinessError")<{
40 - readonly message: string;
41 - readonly cause?: unknown;
42 -}> {}
43 -
44 -export class SshPasswordPromptError extends Data.TaggedError("SshPasswordPromptError")<{
45 - readonly message: string;
46 - readonly cause?: unknown;
47 -}> {}
1 +import * as Schema from "effect/Schema";
2 +
3 +export class SshHostDiscoveryError extends Schema.TaggedError<SshHostDiscoveryError>()(
4 + "SshHostDiscoveryError",
5 + {
6 + message: Schema.String,
7 + cause: Schema.Defect(),
8 + },
9 +) {}
10 +
11 +export class SshInvalidTargetError extends Schema.TaggedError<SshInvalidTargetError>()(
12 + "SshInvalidTargetError",
13 + {
14 + message: Schema.String,
15 + },
16 +) {}
17 +
18 +export class SshCommandError extends Schema.TaggedError<SshCommandError>()("SshCommandError", {
19 + message: Schema.String,
20 + command: Schema.Array(Schema.String),
21 + exitCode: Schema.NullOr(Schema.Number),
22 + stderr: Schema.String,
23 + stdout: Schema.optional(Schema.String),
24 + cause: Schema.optional(Schema.Defect()),
25 +}) {}
26 +
27 +export class SshLaunchError extends Schema.TaggedError<SshLaunchError>()("SshLaunchError", {
28 + message: Schema.String,
29 + stdout: Schema.String,
30 + cause: Schema.optional(Schema.Defect()),
31 +}) {}
32 +
33 +export class SshPairingError extends Schema.TaggedError<SshPairingError>()("SshPairingError", {
34 + message: Schema.String,
35 + stdout: Schema.String,
36 + cause: Schema.optional(Schema.Defect()),
37 +}) {}
38 +
39 +export class SshHttpBridgeError extends Schema.TaggedError<SshHttpBridgeError>()(
40 + "SshHttpBridgeError",
41 + {
42 + message: Schema.String,
43 + status: Schema.optional(Schema.Number),
44 + cause: Schema.optional(Schema.Defect()),
45 + },
46 +) {}
47 +
48 +export class SshReadinessError extends Schema.TaggedError<SshReadinessError>()(
49 + "SshReadinessError",
50 + {
51 + message: Schema.String,
52 + cause: Schema.optional(Schema.Defect()),
53 + },
54 +) {}
55 +
56 +export class SshPasswordPromptError extends Schema.TaggedError<SshPasswordPromptError>()(
57 + "SshPasswordPromptError",
58 + {
59 + message: Schema.String,
60 + cause: Schema.optional(Schema.Defect()),
61 + },
62 +) {}
packages/ssh/src/tunnel.test.ts
+6 -3
@@ -8,6 +8,7 @@ import * as Effect from "effect/Effect";
8 import * as Fiber from "effect/Fiber";
9 import * as Layer from "effect/Layer";
10 import * as PlatformError from "effect/PlatformError";
11 +import * as Schema from "effect/Schema";
12 import * as Result from "effect/Result";
13 import * as Sink from "effect/Sink";
14 import * as Stream from "effect/Stream";
@@ -19,6 +20,8 @@ import * as SshAuth from "./auth.ts";
20 import { SshCommandError, SshPasswordPromptError } from "./errors.ts";
21 import * as SshTunnel from "./tunnel.ts";
22
23 +const isSshCommandError = Schema.is(SshCommandError);
24 +
25 const makeSuccessfulProcess = (stdout: string) => {
26 const stdoutStream = Stream.make(new TextEncoder().encode(stdout));
27 return ChildProcessSpawner.makeHandle({
@@ -202,7 +205,7 @@ describe("ssh tunnel scripts", () => {
205 assert.isTrue(Result.isFailure(result));
206 if (Result.isFailure(result)) {
207 assert.instanceOf(result.failure, SshCommandError);
205 - if (result.failure instanceof SshCommandError) {
208 + if (isSshCommandError(result.failure)) {
209 assert.equal(result.failure.exitCode, 1);
210 assert.equal(result.failure.stderr.length, 16_384);
211 assert.isTrue(result.failure.stderr.endsWith(diagnostic));
@@ -260,7 +263,7 @@ describe("ssh tunnel scripts", () => {
263 assert.isTrue(Result.isFailure(result));
264 if (Result.isFailure(result)) {
265 assert.instanceOf(result.failure, SshCommandError);
263 - if (result.failure instanceof SshCommandError) {
266 + if (isSshCommandError(result.failure)) {
267 assert.equal(result.failure.exitCode, 255);
268 assert.equal(result.failure.stderr, diagnostic);
269 }
@@ -337,7 +340,7 @@ describe("ssh tunnel scripts", () => {
340 if (Result.isFailure(result)) {
341 if (expectedPromptAttempts.length === 0) {
342 assert.instanceOf(result.failure, SshCommandError);
340 - if (result.failure instanceof SshCommandError) {
343 + if (isSshCommandError(result.failure)) {
344 assert.equal(result.failure.stderr, stderr);
345 }
346 } else {
scripts/mobile-e2e/device.ts
+13 -4
@@ -3,6 +3,7 @@
3 import * as NodeChildProcess from "node:child_process";
4 import * as NodePath from "node:path";
5 import * as NodeProcess from "node:process";
6 +import * as Schema from "effect/Schema";
7
8 import type { Snapshot } from "./checks.ts";
9 import type { Pose } from "./poses.ts";
@@ -61,7 +62,11 @@ export interface Pool {
62 readonly env: NodeJS.ProcessEnv;
63 }
64
64 -class AgentDeviceError extends Error {}
65 +class AgentDeviceError extends Schema.TaggedError<AgentDeviceError>()("AgentDeviceError", {
66 + message: Schema.String,
67 +}) {}
68 +
69 +const isAgentDeviceError = Schema.is(AgentDeviceError);
70
71 // A shared pool's workers drop off the gateway and stall under load for seconds at a time.
72 const TRANSIENT =
@@ -112,7 +117,7 @@ export class Device {
117 try {
118 return await this.agentOnce(args, options);
119 } catch (error) {
115 - if (attempt >= 5 || !(error instanceof AgentDeviceError) || !TRANSIENT.test(error.message))
120 + if (attempt >= 5 || !isAgentDeviceError(error) || !TRANSIENT.test(error.message))
121 throw error;
122 await delay(5_000 * attempt);
123 }
@@ -137,10 +142,14 @@ export class Device {
142 try {
143 parsed = JSON.parse(stdout);
144 } catch {
140 - throw new AgentDeviceError(`agent-device ${args[0]}: ${(stderr || stdout).slice(-400)}`);
145 + throw new AgentDeviceError({
146 + message: `agent-device ${args[0]}: ${(stderr || stdout).slice(-400)}`,
147 + });
148 }
149 if (!parsed.success)
143 - throw new AgentDeviceError(`agent-device ${args.join(" ")}: ${parsed.error?.message}`);
150 + throw new AgentDeviceError({
151 + message: `agent-device ${args.join(" ")}: ${parsed.error?.message}`,
152 + });
153 return parsed.data ?? {};
154 }
155
tsconfig.effect.json
+2
@@ -98,6 +98,8 @@
98 "unnecessaryTypeofType": "error",
99 "effectTryWithoutCatch": "error",
100 "processEnvInEffect": "error",
101 + "preferSchemaTaggedError": "error",
102 + "extendsNativeError": "error",
103 "schemaNumber": "off"
104 },
105 "overrides": [