@devries-cameron20 / t3code Mirror · read-only / commits / 5a906583fe
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: Effect.try calls map failures to typed errors (#31217)

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

Julius Marminge committed Nov 4, 2026 at 19:47 UTC 5a906583fed3fa41dc806f2a19bd9d095537ed3e
62 files changed +949 -453
apps/desktop/src/app/DesktopCliCommand.ts
+4 -1
@@ -140,7 +140,10 @@ export const make = Effect.gen(function* () {
140 const isExecutableFile = Effect.fn("DesktopCliCommand.isExecutableFile")(
141 function* (target: string) {
142 if ((yield* fs.stat(target)).type !== "File") return false;
143 - yield* Effect.tryPromise(() => NodeFSP.access(target, NodeFSP.constants.X_OK));
143 + yield* Effect.tryPromise({
144 + try: () => NodeFSP.access(target, NodeFSP.constants.X_OK),
145 + catch: () => fail(`${target} is not executable.`),
146 + });
147 return true;
148 },
149 Effect.orElseSucceed(() => false),
apps/desktop/src/electron/ElectronProtocol.ts
+1 -3
@@ -216,9 +216,7 @@ const serveDesktopAsset = Effect.fn("desktop.protocol.serveAsset")(function* (
216 if (request.method !== "GET" && request.method !== "HEAD") {
217 return new Response(null, { status: 405 });
218 }
219 - const pathname = yield* Effect.try(() => decodeURIComponent(url.pathname)).pipe(
220 - Effect.orElseSucceed(() => null),
221 - );
219 + const pathname = Option.getOrNull(Option.liftThrowable(decodeURIComponent)(url.pathname));
220 if (pathname === null || pathname.includes("\0")) return new Response(null, { status: 400 });
221 const root = path.resolve(assetDirectory);
222 const assetPath = path.resolve(root, `.${pathname}`);
apps/desktop/src/ipc/methods/window.ts
+27 -18
@@ -314,6 +314,12 @@ export const openExternal = DesktopIpc.makeIpcMethod({
314
315 const READ_MEDIA_MAX_BYTES = 256 * 1024 * 1024;
316
317 +// No URL field: media URLs can carry signed query tokens.
318 +class MediaReadError extends Schema.TaggedError<MediaReadError>()("MediaReadError", {
319 + message: Schema.String,
320 + cause: Schema.Defect(),
321 +}) {}
322 +
323 // The renderer can display media it cannot fetch(); reading here keeps Save and Copy working for it.
324 export const readMedia = DesktopIpc.makeIpcMethod({
325 channel: IpcChannels.READ_MEDIA_CHANNEL,
@@ -330,25 +336,28 @@ export const readMedia = DesktopIpc.makeIpcMethod({
336 return null;
337 }
338 const session = window.value.webContents.session;
333 - return yield* Effect.tryPromise(async () => {
334 - // Like an <img>, send the session's cookies.
335 - const response = await session.fetch(url, { credentials: "include" });
336 - const mimeType = response.headers.get("content-type") ?? "";
337 - if (!response.ok || !response.body) {
338 - await response.body?.cancel();
339 - return { status: response.status, mimeType, data: new Uint8Array() };
340 - }
341 - // The whole body crosses IPC, so stop before a huge file can exhaust main-process memory.
342 - const chunks: Uint8Array[] = [];
343 - let size = 0;
344 - for await (const chunk of response.body) {
345 - size += chunk.byteLength;
346 - if (size > READ_MEDIA_MAX_BYTES) {
347 - return { status: 413, mimeType, data: new Uint8Array() };
339 + return yield* Effect.tryPromise({
340 + try: async () => {
341 + // Like an <img>, send the session's cookies.
342 + const response = await session.fetch(url, { credentials: "include" });
343 + const mimeType = response.headers.get("content-type") ?? "";
344 + if (!response.ok || !response.body) {
345 + await response.body?.cancel();
346 + return { status: response.status, mimeType, data: new Uint8Array() };
347 }
349 - chunks.push(chunk);
350 - }
351 - return { status: response.status, mimeType, data: Buffer.concat(chunks) };
348 + // The whole body crosses IPC, so stop before a huge file can exhaust main-process memory.
349 + const chunks: Uint8Array[] = [];
350 + let size = 0;
351 + for await (const chunk of response.body) {
352 + size += chunk.byteLength;
353 + if (size > READ_MEDIA_MAX_BYTES) {
354 + return { status: 413, mimeType, data: new Uint8Array() };
355 + }
356 + chunks.push(chunk);
357 + }
358 + return { status: response.status, mimeType, data: Buffer.concat(chunks) };
359 + },
360 + catch: (cause) => new MediaReadError({ message: "Could not read media.", cause }),
361 }).pipe(Effect.orElseSucceed(() => null));
362 }),
363 });
apps/desktop/src/permissions/MacPermissions.ts
+21 -9
@@ -2,6 +2,7 @@ import * as Context from "effect/Context";
2 import * as Effect from "effect/Effect";
3 import * as Layer from "effect/Layer";
4 import * as Path from "effect/Path";
5 +import * as Schema from "effect/Schema";
6 import * as Electron from "electron";
7 import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
8 import { MacPermissionHelper } from "./MacPermissionHelper.ts";
@@ -18,6 +19,15 @@ export class MacPermissions extends Context.Service<
19 }
20 >()("@t3tools/desktop/permissions/MacPermissions") {}
21
22 +class MacPermissionHelperError extends Schema.TaggedError<MacPermissionHelperError>()(
23 + "MacPermissionHelperError",
24 + { cause: Schema.Defect() },
25 +) {
26 + override get message(): string {
27 + return "Could not show the permission helper.";
28 + }
29 +}
30 +
31 export const layer = Layer.effect(
32 MacPermissions,
33 Effect.gen(function* () {
@@ -28,15 +38,17 @@ export const layer = Layer.effect(
38 return MacPermissions.of({
39 showHelper: Effect.fn("MacPermissions.showHelper")(function* (permission, owner, isGranted) {
40 if (environment.platform !== "darwin" || !environment.isPackaged) return;
31 - yield* Effect.tryPromise(() =>
32 - helper.show(
33 - permission,
34 - path.join(environment.dirname, "mac-permission-preload.cjs"),
35 - owner,
36 - environment.resolveResourcePathCandidates("icon.png"),
37 - isGranted,
38 - ),
39 - ).pipe(
41 + yield* Effect.tryPromise({
42 + try: () =>
43 + helper.show(
44 + permission,
45 + path.join(environment.dirname, "mac-permission-preload.cjs"),
46 + owner,
47 + environment.resolveResourcePathCandidates("icon.png"),
48 + isGranted,
49 + ),
50 + catch: (cause) => new MacPermissionHelperError({ cause }),
51 + }).pipe(
52 Effect.catch((cause) => Effect.logWarning("Could not show permission helper", cause)),
53 );
54 }),
apps/desktop/src/preview/BrowserImport/BrowserImport.ts
+13 -1
@@ -92,6 +92,15 @@ export const checkBrowserImportPolicy = Effect.fn("BrowserImport.checkPolicy")(f
92 }
93 });
94
95 +class BrowserCookieFlushError extends Schema.TaggedError<BrowserCookieFlushError>()(
96 + "BrowserCookieFlushError",
97 + { cause: Schema.Defect() },
98 +) {
99 + override get message(): string {
100 + return "Imported cookies could not be flushed to disk.";
101 + }
102 +}
103 +
104 export class BrowserCookieWriteError extends Schema.TaggedError<BrowserCookieWriteError>()(
105 "BrowserCookieWriteError",
106 {
@@ -183,7 +192,10 @@ export const writeCookies = Effect.fn("BrowserImport.writeCookies")(function* (
192 }
193 // Cookie writes settle in memory; flush to disk before reporting a durable import.
194 if (imported > 0) {
186 - yield* Effect.tryPromise(() => session.cookies.flushStore()).pipe(
195 + yield* Effect.tryPromise({
196 + try: () => session.cookies.flushStore(),
197 + catch: (cause) => new BrowserCookieFlushError({ cause }),
198 + }).pipe(
199 Effect.tapError((error) =>
200 Effect.logWarning("Imported cookies could not be flushed to disk", { cause: error.cause }),
201 ),
apps/desktop/src/snapShot/DesktopSnapShot.ts
+85 -51
@@ -167,6 +167,17 @@ export class DesktopSnapShotError extends Schema.TaggedError<DesktopSnapShotErro
167
168 const isDesktopSnapShotError = Schema.is(DesktopSnapShotError);
169
170 +class SnapShotShortcutError extends Schema.TaggedError<SnapShotShortcutError>()(
171 + "SnapShotShortcutError",
172 + { cause: Schema.Defect() },
173 +) {
174 + override get message(): string {
175 + return "Could not register the SnapShot shortcut.";
176 + }
177 +}
178 +
179 +const shortcutFailure = (cause: unknown) => new SnapShotShortcutError({ cause });
180 +
181 function captureFailure(cause: unknown, captureId?: string): DesktopSnapShotError {
182 if (isDesktopSnapShotError(cause)) return cause;
183 const operation = cause instanceof CaptureSetupRequiredError ? "setup-required" : "capture";
@@ -1068,13 +1079,15 @@ export const make = Effect.gen(function* () {
1079 if (mode === "portal") {
1080 return { available: false, message: WAYLAND_MODIFIER_PAIR_UNAVAILABLE_MESSAGE };
1081 }
1071 - const available = yield* Effect.tryPromise(() =>
1072 - startPairShortcutProcess(
1073 - snapShotShortcutModifierPair(shortcut),
1074 - () => undefined,
1075 - () => undefined,
1076 - ),
1077 - ).pipe(
1082 + const available = yield* Effect.tryPromise({
1083 + try: () =>
1084 + startPairShortcutProcess(
1085 + snapShotShortcutModifierPair(shortcut),
1086 + () => undefined,
1087 + () => undefined,
1088 + ),
1089 + catch: shortcutFailure,
1090 + }).pipe(
1091 Effect.tap((stop) => Effect.sync(stop)),
1092 Effect.as(true),
1093 Effect.orElseSucceed(() => false),
@@ -1089,7 +1102,10 @@ export const make = Effect.gen(function* () {
1102 const systemConflict = snapShotShortcutSystemConflict(shortcut);
1103 if (systemConflict) return { available: false, message: systemConflict };
1104 if (mode === "portal") {
1092 - return yield* Effect.try(() => portalShortcutTrigger(shortcut)).pipe(
1105 + return yield* Effect.try({
1106 + try: () => portalShortcutTrigger(shortcut),
1107 + catch: shortcutFailure,
1108 + }).pipe(
1109 Effect.match({
1110 onSuccess: () => ({
1111 available: true,
@@ -1199,13 +1215,16 @@ export const make = Effect.gen(function* () {
1215 return;
1216 }
1217 if (mode === "portal" && niriSocketPath()) {
1202 - const registered = yield* Effect.tryPromise(async () => {
1203 - const { startNiriCaptureShortcut } = await import("./NiriCaptureShortcut.ts");
1204 - return startNiriCaptureShortcut(linuxAppId, onCurrentShortcut, () => {
1205 - void runPromise(
1206 - setShortcutFailure("The Niri capture endpoint disconnected. Restart T3 Code."),
1207 - ).catch(() => undefined);
1208 - });
1218 + const registered = yield* Effect.tryPromise({
1219 + try: async () => {
1220 + const { startNiriCaptureShortcut } = await import("./NiriCaptureShortcut.ts");
1221 + return startNiriCaptureShortcut(linuxAppId, onCurrentShortcut, () => {
1222 + void runPromise(
1223 + setShortcutFailure("The Niri capture endpoint disconnected. Restart T3 Code."),
1224 + ).catch(() => undefined);
1225 + });
1226 + },
1227 + catch: shortcutFailure,
1228 }).pipe(
1229 Effect.tap((stop) =>
1230 Effect.sync(() => {
@@ -1249,29 +1268,32 @@ export const make = Effect.gen(function* () {
1268 shortcutMessage: null,
1269 message: null,
1270 });
1252 - yield* Effect.tryPromise(async () => {
1253 - const { PortalCaptureShortcut } = await import("./PortalCaptureShortcut.ts");
1254 - return new PortalCaptureShortcut(
1255 - linuxAppId,
1256 - isModifierPairShortcut(shortcut)
1257 - ? {
1258 - key: "2",
1259 - ctrlKey: true,
1260 - modKey: false,
1261 - altKey: false,
1262 - shiftKey: true,
1263 - metaKey: false,
1264 - }
1265 - : shortcut,
1266 - onCurrentShortcut,
1267 - () => {
1268 - if (generation !== shortcutGeneration) return;
1269 - shortcutVerified = false;
1270 - void runPromise(emit({ type: "shortcut-changed" })).catch(() => undefined);
1271 - },
1272 - undefined,
1273 - hyprland,
1274 - );
1271 + yield* Effect.tryPromise({
1272 + try: async () => {
1273 + const { PortalCaptureShortcut } = await import("./PortalCaptureShortcut.ts");
1274 + return new PortalCaptureShortcut(
1275 + linuxAppId,
1276 + isModifierPairShortcut(shortcut)
1277 + ? {
1278 + key: "2",
1279 + ctrlKey: true,
1280 + modKey: false,
1281 + altKey: false,
1282 + shiftKey: true,
1283 + metaKey: false,
1284 + }
1285 + : shortcut,
1286 + onCurrentShortcut,
1287 + () => {
1288 + if (generation !== shortcutGeneration) return;
1289 + shortcutVerified = false;
1290 + void runPromise(emit({ type: "shortcut-changed" })).catch(() => undefined);
1291 + },
1292 + undefined,
1293 + hyprland,
1294 + );
1295 + },
1296 + catch: shortcutFailure,
1297 }).pipe(
1298 Effect.tap((registration) =>
1299 Effect.sync(() => {
@@ -1293,15 +1315,21 @@ export const make = Effect.gen(function* () {
1315
1316 let registered = false;
1317 if (isModifierPairShortcut(shortcut)) {
1296 - registered = yield* Effect.tryPromise(() =>
1297 - startPairShortcutProcess(snapShotShortcutModifierPair(shortcut), onCurrentShortcut, () => {
1298 - void pipe(
1299 - snapShotShortcutRegistrationFailureMessage(shortcut, environment.platform),
1300 - setShortcutFailure,
1301 - runPromise,
1302 - ).catch(() => undefined);
1303 - }),
1304 - ).pipe(
1318 + registered = yield* Effect.tryPromise({
1319 + try: () =>
1320 + startPairShortcutProcess(
1321 + snapShotShortcutModifierPair(shortcut),
1322 + onCurrentShortcut,
1323 + () => {
1324 + void pipe(
1325 + snapShotShortcutRegistrationFailureMessage(shortcut, environment.platform),
1326 + setShortcutFailure,
1327 + runPromise,
1328 + ).catch(() => undefined);
1329 + },
1330 + ),
1331 + catch: shortcutFailure,
1332 + }).pipe(
1333 Effect.tap((stop) =>
1334 Effect.sync(() => {
1335 stopShiftShortcut = stop;
@@ -1489,7 +1517,10 @@ export const make = Effect.gen(function* () {
1517 if (action === "retry-shortcut") {
1518 const currentPortal = portalShortcut;
1519 if (currentPortal?.hasSession && !currentPortal.state.shortcutPending) {
1492 - yield* Effect.tryPromise(() => currentPortal.configure()).pipe(
1520 + yield* Effect.tryPromise({
1521 + try: () => currentPortal.configure(),
1522 + catch: shortcutFailure,
1523 + }).pipe(
1524 Effect.mapError(
1525 (error) =>
1526 new DesktopSnapShotSetupError({
@@ -1583,9 +1614,12 @@ export const make = Effect.gen(function* () {
1614 state: Ref.get(stateRef).pipe(
1615 Effect.flatMap((state) =>
1616 state.mode === "portal"
1586 - ? Effect.tryPromise(async () => {
1587 - const { getLinuxCaptureSupport } = await import("./LinuxSnapShot.ts");
1588 - return getLinuxCaptureSupport(linuxAppId);
1617 + ? Effect.tryPromise({
1618 + try: async () => {
1619 + const { getLinuxCaptureSupport } = await import("./LinuxSnapShot.ts");
1620 + return getLinuxCaptureSupport(linuxAppId);
1621 + },
1622 + catch: (cause) => new DesktopSnapShotError({ operation: "unsupported", cause }),
1623 }).pipe(
1624 Effect.map((support) => ({ ...state, ...support })),
1625 Effect.catch((error) =>
apps/desktop/src/window/DesktopWindow.ts
+14 -3
@@ -5,6 +5,7 @@ import * as Fiber from "effect/Fiber";
5 import * as Layer from "effect/Layer";
6 import * as Option from "effect/Option";
7 import * as Ref from "effect/Ref";
8 +import * as Schema from "effect/Schema";
9 import * as Semaphore from "effect/Semaphore";
10
11 import * as Electron from "electron";
@@ -39,6 +40,15 @@ import { makeQuitShortcutHandler } from "./QuitHold.ts";
40 import { copyContextMenuImage } from "./ContextMenuImage.ts";
41
42 const TITLEBAR_HEIGHT = 40;
43 +
44 +class ContextMenuImageCopyError extends Schema.TaggedError<ContextMenuImageCopyError>()(
45 + "ContextMenuImageCopyError",
46 + { cause: Schema.Defect() },
47 +) {
48 + override get message(): string {
49 + return "Could not copy the context-menu image.";
50 + }
51 +}
52 // Match --workspace-topbar-height in apps/web/src/index.css; native macOS buttons stay 14 points at any zoom.
53 const MACOS_WORKSPACE_TOPBAR_HEIGHT = 52;
54 const MACOS_WINDOW_BUTTON_RADIUS = 7;
@@ -580,9 +590,10 @@ export const make = Effect.gen(function* () {
590 label: "Copy Image",
591 click: () => {
592 void runPromise(
583 - Effect.tryPromise(() => copyContextMenuImage(contents, params)).pipe(
584 - Effect.catch(() => logWindowWarning("failed to copy context-menu image")),
585 - ),
593 + Effect.tryPromise({
594 + try: () => copyContextMenuImage(contents, params),
595 + catch: (cause) => new ContextMenuImageCopyError({ cause }),
596 + }).pipe(Effect.catch(() => logWindowWarning("failed to copy context-menu image"))),
597 );
598 },
599 });
apps/mobile/src/features/agent-awareness/remoteRegistration.ts
+6 -3
@@ -62,6 +62,7 @@ const AgentAwarenessOperation = Schema.Literals([
62 "list-active-live-activities",
63 "load-live-activity-prime-preferences",
64 "prime-live-activity",
65 + "load-registration-record",
66 ]);
67
68 export class AgentAwarenessOperationError extends Schema.TaggedError<AgentAwarenessOperationError>()(
@@ -345,9 +346,11 @@ const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWith
346 }
347
348 const identity = relayTokenProviderIdentity ?? "";
348 - const persisted = yield* Effect.tryPromise(() => loadAgentAwarenessRegistrationRecord()).pipe(
349 - Effect.orElseSucceed(() => null),
350 - );
349 + const persisted = yield* Effect.tryPromise({
350 + try: () => loadAgentAwarenessRegistrationRecord(),
351 + catch: (cause) =>
352 + new AgentAwarenessOperationError({ operation: "load-registration-record", cause }),
353 + }).pipe(Effect.orElseSucceed(() => null));
354 if (expectedGeneration !== deviceRegistrationGeneration) {
355 // Signed out while the record loaded — do not resurrect the cleared
356 // record or report the previous account's registration as current.
apps/mobile/src/features/diagnostics/SettingsDiagnosticsRouteScreen.tsx
+13 -1
@@ -6,6 +6,7 @@ import * as Updates from "expo-updates";
6 import { useAtomSet, useAtomValue } from "@effect/atom-react";
7 import * as Effect from "effect/Effect";
8 import * as Exit from "effect/Exit";
9 +import * as Schema from "effect/Schema";
10 import { AsyncResult, Atom } from "effect/reactivity";
11 import { useState } from "react";
12 import { View } from "react-native";
@@ -34,9 +35,20 @@ type CrashLogState =
35 | { readonly status: "unavailable" }
36 | { readonly status: "ready"; readonly records: ReadonlyArray<StartupCrashRecord> };
37
38 +class CrashLogReadError extends Schema.TaggedError<CrashLogReadError>()("CrashLogReadError", {
39 + cause: Schema.Defect(),
40 +}) {
41 + override get message(): string {
42 + return "Could not read the expo-updates log.";
43 + }
44 +}
45 +
46 // Not kept alive: each visit to the screen re-reads the log.
47 const crashLogAtom = Atom.make(
39 - Effect.tryPromise(() => Updates.readLogEntriesAsync(LOG_WINDOW_MS)).pipe(
48 + Effect.tryPromise({
49 + try: () => Updates.readLogEntriesAsync(LOG_WINDOW_MS),
50 + catch: (cause) => new CrashLogReadError({ cause }),
51 + }).pipe(
52 Effect.map((entries): CrashLogState => ({
53 status: "ready",
54 records: parseStartupCrashRecords(entries),
apps/mobile/src/features/pull-requests/usePullRequestDiff.test.tsx
+6 -4
@@ -1,6 +1,6 @@
1 import { RegistryContext } from "@effect/atom-react";
2 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3 -import type { PullRequestDiffResult } from "@t3tools/contracts";
3 +import { PullRequestOperationError, type PullRequestDiffResult } from "@t3tools/contracts";
4 import * as Effect from "effect/Effect";
5 import { Atom, AtomRegistry } from "effect/reactivity";
6 import { act, useLayoutEffect, useState } from "react";
@@ -32,12 +32,14 @@ function setup() {
32 }[] = [];
33 const queries = Atom.family((cursor: string | null) =>
34 Atom.make(
35 - Effect.tryPromise(
36 - () =>
35 + Effect.tryPromise({
36 + try: () =>
37 new Promise<PullRequestDiffResult>((resolve, reject) => {
38 requests.push({ cursor, resolve, reject });
39 }),
40 - ),
40 + catch: (cause) =>
41 + new PullRequestOperationError({ operation: "diff", detail: "Connection lost", cause }),
42 + }),
43 ).pipe(Atom.keepAlive),
44 );
45 mocks.diff.mockImplementation((target: { input: { cursor?: string } }) =>
apps/mobile/src/lib/composerImagePreview.ts
+14 -1
@@ -1,6 +1,7 @@
1 import * as Effect from "effect/Effect";
2 import * as Equal from "effect/Equal";
3 import * as Hash from "effect/Hash";
4 +import * as Schema from "effect/Schema";
5 import { Atom } from "effect/reactivity";
6
7 import type { DraftComposerImageAttachment } from "./composerImages";
@@ -31,6 +32,15 @@ async function materializeDataUrlPreview(id: string, dataUrl: string): Promise<s
32 return file.uri;
33 }
34
35 +class ImagePreviewCacheError extends Schema.TaggedError<ImagePreviewCacheError>()(
36 + "ImagePreviewCacheError",
37 + { cause: Schema.Defect() },
38 +) {
39 + override get message(): string {
40 + return "Could not cache an image preview.";
41 + }
42 +}
43 +
44 /**
45 * Keyed by attachment id only: the cached file is named by id, and an upload
46 * reference landing on the same draft must not restart materialization and
@@ -48,7 +58,10 @@ export class MaterializedPreviewKey implements Equal.Equal {
58
59 export const materializedPreviewAtom = Atom.family(({ attachment }: MaterializedPreviewKey) =>
60 Atom.make(
51 - Effect.tryPromise(() => materializeDataUrlPreview(attachment.id, attachment.previewUri)).pipe(
61 + Effect.tryPromise({
62 + try: () => materializeDataUrlPreview(attachment.id, attachment.previewUri),
63 + catch: (cause) => new ImagePreviewCacheError({ cause }),
64 + }).pipe(
65 Effect.catch((error) =>
66 Effect.logWarning("[composer-attachments] could not cache an image preview", error).pipe(
67 Effect.as(null),
apps/mobile/src/native/ProjectChipIconImages.tsx
+16 -4
@@ -1,5 +1,6 @@
1 import type { ProjectIconColor } from "@t3tools/contracts";
2 import * as Effect from "effect/Effect";
3 +import * as Schema from "effect/Schema";
4 import { Atom } from "effect/reactivity";
5 import { useRef, useSyncExternalStore } from "react";
6 import { Platform, View } from "react-native";
@@ -68,11 +69,22 @@ function subscribe(listener: () => void) {
69 return () => listeners.delete(listener);
70 }
71
72 +class ProjectGlyphRasterizeError extends Schema.TaggedError<ProjectGlyphRasterizeError>()(
73 + "ProjectGlyphRasterizeError",
74 + { key: Schema.String, cause: Schema.Defect() },
75 +) {
76 + override get message(): string {
77 + return `Could not rasterize the project glyph ${this.key}.`;
78 + }
79 +}
80 +
81 export const projectGlyphImageAtom = Atom.family((key: string) =>
72 - Atom.make(Effect.tryPromise(() => rasterize(key))).pipe(
73 - Atom.keepAlive,
74 - Atom.withLabel(`mobile-project-glyph-image:${key}`),
75 - ),
82 + Atom.make(
83 + Effect.tryPromise({
84 + try: () => rasterize(key),
85 + catch: (cause) => new ProjectGlyphRasterizeError({ key, cause }),
86 + }),
87 + ).pipe(Atom.keepAlive, Atom.withLabel(`mobile-project-glyph-image:${key}`)),
88 );
89
90 export function ProjectChipIconRasterizer() {
apps/server/scripts/record-fx-acp-replay-fixture.ts
+5 -7
@@ -34,6 +34,7 @@ import { ORCHESTRATOR_REPLAY_FIXTURES } from "../src/orchestration-v2/testkit/fi
34 import { materializeFixtureInput } from "../src/orchestration-v2/testkit/fixtures/shared.ts";
35 import { runOrchestratorV2Scenario } from "../src/orchestration-v2/testkit/OrchestratorScenario.ts";
36 import * as ProviderReplayHarness from "../src/orchestration-v2/testkit/ProviderReplayHarness.ts";
37 +import * as Result from "effect/Result";
38
39 const wallClock = Clock.Clock.defaultValue();
40 const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
@@ -502,11 +503,8 @@ const recordScenario = Effect.fn("recordFxScenario")(function* (fixtureName: str
503 };
504
505 const outputPath = readArgValues("--out")[0] ?? (yield* path.fromFileUrl(variant.transcriptFile));
505 - const liveFailure = yield* Effect.try(() => variant.assertOutput(result, transcript)).pipe(
506 - Effect.flip,
507 - Effect.option,
508 - );
509 - if (liveFailure._tag === "Some") {
506 + const liveFailure = Result.try(() => variant.assertOutput(result, transcript));
507 + if (Result.isFailure(liveFailure)) {
508 const dumpPath = path.join(
509 recorderEnv.TMPDIR ?? "/tmp",
510 `fx-replay-${fixtureName}-failed.json`,
@@ -514,9 +512,9 @@ const recordScenario = Effect.fn("recordFxScenario")(function* (fixtureName: str
512 yield* fs.writeFileString(dumpPath, encodeJson(transcript));
513 yield* Console.log(
514 `Live orchestration failed ${fixtureName} assertions; left ${outputPath} unchanged. Dump: ${dumpPath}`,
517 - liveFailure.value,
515 + liveFailure.failure,
516 );
519 - return yield* Effect.die(liveFailure.value);
517 + return yield* Effect.die(liveFailure.failure);
518 }
519
520 const { entries: transcriptEntries, ...header } = transcript;
apps/server/scripts/record-grok-acp-replay-fixture.ts
+4 -6
@@ -35,6 +35,7 @@ import * as ProviderReplayHarness from "../src/orchestration-v2/testkit/Provider
35 import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
36 import { makeGrokAcpRuntime } from "@t3tools/provider-grok/testing";
37 import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
38 +import * as Result from "effect/Result";
39
40 const wallClock = Clock.Clock.defaultValue();
41 const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
@@ -554,12 +555,9 @@ const recordScenario = Effect.fn("recordGrokScenario")(function* (fixtureName: s
555 );
556 yield* Console.log(`Wrote ${transcriptEntries.length} Grok ACP replay entries to ${outputPath}`);
557
557 - const liveFailure = yield* Effect.try(() => variant.assertOutput(result, transcript)).pipe(
558 - Effect.flip,
559 - Effect.option,
560 - );
561 - if (liveFailure._tag === "Some") {
562 - yield* Console.log(`Live orchestration failed ${fixtureName} assertions:`, liveFailure.value);
558 + const liveFailure = Result.try(() => variant.assertOutput(result, transcript));
559 + if (Result.isFailure(liveFailure)) {
560 + yield* Console.log(`Live orchestration failed ${fixtureName} assertions:`, liveFailure.failure);
561 }
562 });
563
apps/server/src/auth/McpOAuth.ts
+1 -1
@@ -283,7 +283,7 @@ const make = Effect.gen(function* () {
283 if (!body || !signature || extra !== undefined) return undefined;
284 const verified = yield* signer.verify(`mcp-client-id.${body}`, signature);
285 if (!verified) return undefined;
286 - const json = yield* Effect.try(() => base64UrlDecodeUtf8(body)).pipe(Effect.option);
286 + const json = Option.liftThrowable(base64UrlDecodeUtf8)(body);
287 if (Option.isNone(json)) return undefined;
288 return Option.getOrUndefined(
289 decodeClientIdPayload(json.value).pipe(
apps/server/src/auth/http.test.ts
+1 -1
@@ -94,7 +94,7 @@ it.effect("sets the selected browser session cookies through the HTTP route", ()
94 ] as const,
95 ),
96 ([environmentA, environmentB]) =>
97 - Effect.tryPromise(async () => {
97 + Effect.promise(async () => {
98 const devResponse = await environmentA.handler(
99 postJson("/api/auth/browser-session", { credential: DEV_TOKEN }),
100 requestContext,
apps/server/src/cloud/ManagedEndpointRuntime.ts
+14 -4
@@ -1,5 +1,5 @@
1 import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
2 -import { RotatingFileSink } from "@t3tools/shared/logging";
2 +import { RotatingFileSink, RotatingFileSinkError } from "@t3tools/shared/logging";
3 import * as HostProcess from "@t3tools/shared/HostProcess";
4 import * as RelayClient from "@t3tools/shared/relayClient";
5 import * as Clock from "effect/Clock";
@@ -100,6 +100,8 @@ interface ActiveConnector {
100 }
101
102 // An instantly failing relay client otherwise respawns ~100 times/sec and exhausts V8 via tracing.
103 +const isRotatingFileSinkError = Schema.is(RotatingFileSinkError);
104 +
105 const RELAY_RESTART_STABLE_UPTIME_MS = 30_000;
106 const RELAY_RESTART_BACKOFF_BASE_MS = 1_000;
107 const RELAY_RESTART_BACKOFF_MAX_MS = 60_000;
@@ -252,15 +254,23 @@ export const make = Effect.gen(function* () {
254 // Synchronous appends avoid a flush timer for this low-volume log.
255 const fallbackLoggers = yield* Effect.service(Logger.CurrentLoggers);
256 let writeFailureReported = false;
255 - const relayClientLog = yield* Effect.try(
256 - () =>
257 + const relayClientLog = yield* Effect.try({
258 + try: () =>
259 new RotatingFileSink({
260 filePath: relayClientLogPath,
261 maxBytes: 1024 * 1024,
262 maxFiles: 2,
263 throwOnError: true,
264 }),
263 - ).pipe(
265 + catch: (cause) =>
266 + isRotatingFileSinkError(cause)
267 + ? cause
268 + : new RotatingFileSinkError({
269 + operation: "initialize",
270 + filePath: relayClientLogPath,
271 + cause,
272 + }),
273 + }).pipe(
274 Effect.map((sink) =>
275 Logger.make((options) => {
276 try {
apps/server/src/compileCache.ts
+17 -4
@@ -1,9 +1,22 @@
1 import * as NodeModule from "node:module";
2 import * as Effect from "effect/Effect";
3 +import * as Schema from "effect/Schema";
4
4 -// Windows force-kills on quit; persist the cache after startup.
5 -export const flushCompileCache = Effect.try(() => {
6 - if (!Reflect.get(globalThis, Symbol.for("t3code.preparedServerCache"))) {
7 - NodeModule.flushCompileCache();
5 +class CompileCacheFlushError extends Schema.TaggedError<CompileCacheFlushError>()(
6 + "CompileCacheFlushError",
7 + { cause: Schema.Defect() },
8 +) {
9 + override get message(): string {
10 + return "Could not flush the module compile cache.";
11 }
12 +}
13 +
14 +// Windows force-kills on quit; persist the cache after startup.
15 +export const flushCompileCache = Effect.try({
16 + try: () => {
17 + if (!Reflect.get(globalThis, Symbol.for("t3code.preparedServerCache"))) {
18 + NodeModule.flushCompileCache();
19 + }
20 + },
21 + catch: (cause) => new CompileCacheFlushError({ cause }),
22 }).pipe(Effect.ignore);
apps/server/src/device/localSshDeviceHost.ts
+5 -1
@@ -5,6 +5,7 @@ import * as NodeOS from "node:os";
5 import * as Context from "effect/Context";
6 import { runSshCommand } from "@t3tools/ssh/command";
7 import * as Effect from "effect/Effect";
8 +import { HostnameLookupError } from "@t3tools/shared/HostProcess";
9
10 export const LocalDeviceHostAddresses = Context.Reference<ReadonlySet<string>>(
11 "LocalDeviceHostAddresses",
@@ -45,7 +46,10 @@ export const isLocalSshDeviceHost = Effect.fn("isLocalSshDeviceHost")(function*
46 if (!hostname) return false;
47 const addresses = NodeNet.isIP(hostname)
48 ? [hostname]
48 - : yield* Effect.tryPromise(() => NodeDnsPromises.lookup(hostname, { all: true })).pipe(
49 + : yield* Effect.tryPromise({
50 + try: () => NodeDnsPromises.lookup(hostname, { all: true }),
51 + catch: (cause) => new HostnameLookupError({ hostname, cause }),
52 + }).pipe(
53 Effect.map((entries) => entries.map((entry) => entry.address)),
54 Effect.timeout("2 seconds"),
55 Effect.orElseSucceed(() => [] as string[]),
apps/server/src/mcp/AcpMcpStdioBridge.ts
+12 -7
@@ -4,7 +4,8 @@ import * as NodeReadline from "node:readline";
4
5 import * as Cause from "effect/Cause";
6 import * as Effect from "effect/Effect";
7 -import * as Result from "effect/Result";
7 +import * as Option from "effect/Option";
8 +import * as Schema from "effect/Schema";
9 import * as Fiber from "effect/Fiber";
10 import * as Scope from "effect/Scope";
11 import * as Stream from "effect/Stream";
@@ -21,6 +22,8 @@ const bridgeError = (cause: unknown): AcpMcpBridgeError =>
22 ? cause
23 : new AcpMcpBridgeError(cause instanceof Error ? cause.message : String(cause), { cause });
24
25 +const decodeJsonLine = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
26 +
27 interface JsonRpcEnvelope {
28 readonly id?: unknown;
29 readonly method?: unknown;
@@ -132,9 +135,11 @@ export const mcpToolSession = (
135 const terminate = Effect.suspend(() =>
136 sessionId === null
137 ? Effect.void
135 - : Effect.tryPromise(() =>
136 - fetchImplementation(options.endpoint, { method: "DELETE", headers: headers() }),
137 - ).pipe(Effect.flatMap(discardResponseBody), Effect.ignore),
138 + : Effect.tryPromise({
139 + try: () =>
140 + fetchImplementation(options.endpoint, { method: "DELETE", headers: headers() }),
141 + catch: bridgeError,
142 + }).pipe(Effect.flatMap(discardResponseBody), Effect.ignore),
143 );
144
145 // Registered before the handshake so a session the server opened is ended
@@ -274,11 +279,11 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.
279 line: string,
280 ): Effect.fn.Return<void> {
281 if (line.trim().length === 0) return;
277 - const parsed = yield* Effect.try((): unknown => JSON.parse(line)).pipe(Effect.result);
278 - if (Result.isFailure(parsed)) {
282 + const parsed = decodeJsonLine(line);
283 + if (Option.isNone(parsed)) {
284 return yield* respondWithError(null, "Parse error", -32700);
285 }
281 - const envelope = asEnvelope(parsed.success);
286 + const envelope = asEnvelope(parsed.value);
287 if (envelope === null) return;
288 const isResponse = envelope.id !== undefined && ("result" in envelope || "error" in envelope);
289 const isSessionHandshake =
apps/server/src/observability/EventLoopMonitor.ts
+21 -5
@@ -3,7 +3,7 @@ import * as NodeOS from "node:os";
3 import * as NodePerfHooks from "node:perf_hooks";
4
5 import type { ServerEventLoopStall } from "@t3tools/contracts";
6 -import { RotatingFileSink } from "@t3tools/shared/logging";
6 +import { RotatingFileSink, RotatingFileSinkError } from "@t3tools/shared/logging";
7 import * as Context from "effect/Context";
8 import * as DateTime from "effect/DateTime";
9 import * as Effect from "effect/Effect";
@@ -150,15 +150,21 @@ const layerWith = (
150 const latestNoticeableStall = yield* Ref.make<
151 { readonly stall: ServerEventLoopStall; readonly detectedAtMs: number } | undefined
152 >(undefined);
153 - const stallSink = yield* Effect.try(
154 - () =>
153 + const stallSink = yield* Effect.try({
154 + try: () =>
155 new RotatingFileSink({
156 filePath: stallLog.filePath,
157 maxBytes: stallLog.maxBytes,
158 maxFiles: 1,
159 throwOnError: true,
160 }),
161 - ).pipe(
161 + catch: (cause) =>
162 + new RotatingFileSinkError({
163 + operation: "initialize",
164 + filePath: stallLog.filePath,
165 + cause,
166 + }),
167 + }).pipe(
168 Effect.catch(() =>
169 Effect.logWarning("event loop stall log unavailable", {
170 filePath: stallLog.filePath,
@@ -201,7 +207,17 @@ const layerWith = (
207 );
208 if (stallSink !== undefined) {
209 yield* encodeStallLine({ time: detectedAt, ...attributes }).pipe(
204 - Effect.flatMap((line) => Effect.try(() => stallSink.write(`${line}\n`))),
210 + Effect.flatMap((line) =>
211 + Effect.try({
212 + try: () => stallSink.write(`${line}\n`),
213 + catch: (cause) =>
214 + new RotatingFileSinkError({
215 + operation: "write",
216 + filePath: stallLog.filePath,
217 + cause,
218 + }),
219 + }),
220 + ),
221 Effect.catch(() =>
222 Effect.logWarning("event loop stall log write failed", {
223 filePath: stallLog.filePath,
apps/server/src/observability/HeapSnapshot.ts
+14 -3
@@ -7,18 +7,29 @@ import * as DateTime from "effect/DateTime";
7 import * as Effect from "effect/Effect";
8 import * as FileSystem from "effect/FileSystem";
9 import * as Layer from "effect/Layer";
10 +import * as Schema from "effect/Schema";
11
12 import * as ServerConfig from "../config.ts";
13
14 +class HeapSnapshotWriteError extends Schema.TaggedError<HeapSnapshotWriteError>()(
15 + "HeapSnapshotWriteError",
16 + { path: Schema.String, cause: Schema.Defect() },
17 +) {
18 + override get message(): string {
19 + return `Could not write a heap snapshot to ${this.path}.`;
20 + }
21 +}
22 +
23 const writeHeapSnapshot = Effect.fn("server.heapSnapshot", { root: true })(
24 function* (logsDir: string) {
25 const fs = yield* FileSystem.FileSystem;
26 const timestamp = DateTime.formatIso(yield* DateTime.now).replaceAll(":", "-");
27 const path = NodePath.join(logsDir, `server-${process.pid}-${timestamp}.heapsnapshot`);
28 yield* Effect.annotateCurrentSpan({ path });
19 - yield* Effect.try(() => NodeV8.writeHeapSnapshot(path)).pipe(
20 - Effect.tapError(() => fs.remove(path, { force: true }).pipe(Effect.ignore)),
21 - );
29 + yield* Effect.try({
30 + try: () => NodeV8.writeHeapSnapshot(path),
31 + catch: (cause) => new HeapSnapshotWriteError({ path, cause }),
32 + }).pipe(Effect.tapError(() => fs.remove(path, { force: true }).pipe(Effect.ignore)));
33 yield* Effect.logInfo("Wrote heap snapshot.", { path });
34 },
35 Effect.catch((cause) => Effect.logWarning("Failed to write heap snapshot.", { cause })),
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+25 -17
@@ -1285,9 +1285,10 @@ export const layerQueryRunner: Layer.Layer<
1285 Effect.gen(function* () {
1286 if (mcpServers !== undefined) {
1287 // Errors and mcp_status can echo headers; log only server names.
1288 - const failed = yield* Effect.tryPromise(() =>
1289 - queryRuntime.setMcpServers(mcpServers),
1290 - ).pipe(
1288 + const failed = yield* Effect.tryPromise({
1289 + try: () => queryRuntime.setMcpServers(mcpServers),
1290 + catch: (cause) => queryRunnerError(cause, "setMcpServers"),
1291 + }).pipe(
1292 Effect.map((result) => Object.keys(result.errors)),
1293 Effect.orElseSucceed(() => Object.keys(mcpServers)),
1294 Effect.timeoutOrElse({
@@ -1583,7 +1584,10 @@ export const layerQueryRunner: Layer.Layer<
1584 ForkSessionResult & { readonly headMessageId?: string },
1585 unknown
1586 > = usesHostConfig
1586 - ? Effect.tryPromise(() => forkClaudeSession(input.sessionId, input.options))
1587 + ? Effect.tryPromise({
1588 + try: () => forkClaudeSession(input.sessionId, input.options),
1589 + catch: (cause) => queryRunnerError(cause, "forkSession"),
1590 + })
1591 : forkClaudeSessionInWorker(input).pipe(
1592 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1593 Effect.provideService(Path.Path, path),
@@ -4886,13 +4890,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4890 const home = customHome
4891 ? yield* readBypassSettings(path.join(homePath, "settings.json"))
4892 : {};
4889 - const resolved = yield* Effect.tryPromise(() =>
4890 - resolveClaudeSettings({
4891 - ...(cwd === null ? {} : { cwd }),
4892 - settingSources: customHome ? ["project", "local"] : ["user", "project", "local"],
4893 - serverManagedSettings: claudeSdkBypassSettings(remote),
4894 - }),
4895 - );
4893 + const resolved = yield* Effect.tryPromise({
4894 + try: () =>
4895 + resolveClaudeSettings({
4896 + ...(cwd === null ? {} : { cwd }),
4897 + settingSources: customHome ? ["project", "local"] : ["user", "project", "local"],
4898 + serverManagedSettings: claudeSdkBypassSettings(remote),
4899 + }),
4900 + catch: (cause) => queryRunnerError(cause, "resolveSettings"),
4901 + });
4902 const launchArgSettings = yield* readClaudeLaunchArgSettings({
4903 settings: adapterOptions.settings,
4904 cwd,
@@ -4916,12 +4922,14 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4922 adapterOptions.environment.CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL,
4923 );
4924 if (Option.isSome(fromEnvironment)) return fromEnvironment.value;
4919 - const resolved = yield* Effect.tryPromise(() =>
4920 - resolveClaudeSettings({
4921 - ...(cwd === null ? {} : { cwd }),
4922 - settingSources: customHome ? ["project", "local"] : ["user", "project", "local"],
4923 - }),
4924 - ).pipe(Effect.orElseSucceed(() => undefined));
4925 + const resolved = yield* Effect.tryPromise({
4926 + try: () =>
4927 + resolveClaudeSettings({
4928 + ...(cwd === null ? {} : { cwd }),
4929 + settingSources: customHome ? ["project", "local"] : ["user", "project", "local"],
4930 + }),
4931 + catch: (cause) => queryRunnerError(cause, "resolveSettings"),
4932 + }).pipe(Effect.orElseSucceed(() => undefined));
4933 const home = customHome
4934 ? yield* fileSystem.readFileString(path.join(homePath, "settings.json")).pipe(
4935 Effect.flatMap(decodeClaudeSubagentCacheSettings),
apps/server/src/orchestration-v2/http.ts
+2 -4
@@ -246,11 +246,9 @@ export const layer = HttpApiBuilder.group(
246 Effect.fn("environment.orchestration.threadHistoryPage")(function* (args) {
247 yield* annotateEnvironmentRequest(args.endpoint.name);
248 yield* requireEnvironmentScope(AuthOrchestrationReadScope);
249 - const decoded = yield* Effect.try(() =>
250 - decodeThreadHistoryCursor(args.query.cursor),
251 - ).pipe(Effect.result);
249 + const decoded = Result.try(() => decodeThreadHistoryCursor(args.query.cursor));
250 if (Result.isFailure(decoded)) {
253 - const cause = decoded.failure.cause;
251 + const cause = decoded.failure;
252 if (cause instanceof InvalidThreadHistoryCursorError)
253 return yield* failEnvironmentInvalidRequest("invalid_history_cursor");
254 return yield* failEnvironmentInternal("orchestration_thread_history_failed", cause);
apps/server/src/persistence/initializeV2Database.test.ts
+3 -1
@@ -11,6 +11,7 @@ import { ThreadId } from "@t3tools/contracts";
11 import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
12 import * as Effect from "effect/Effect";
13 import * as Layer from "effect/Layer";
14 +import * as Predicate from "effect/Predicate";
15 import * as SqlClient from "effect/sql/SqlClient";
16
17 import * as ServerConfig from "../config.ts";
@@ -124,7 +125,8 @@ it.effect("includes committed WAL data and does not publish a failed snapshot",
125 const destinationPath = NodePath.join(directory, "statev2.sqlite");
126 return Effect.gen(function* () {
127 NodeFS.writeFileSync(sourcePath, "invalid SQLite");
127 - assert.isTrue((yield* Effect.result(initializeV2Database(destinationPath)))._tag === "Failure");
128 + const failure = yield* Effect.flip(initializeV2Database(destinationPath));
129 + assert.isFalse(Predicate.isTagged(failure.cause, "V2DatabaseImportError"));
130 assert.isFalse(NodeFS.existsSync(destinationPath));
131 NodeFS.unlinkSync(sourcePath);
132 const source = new NodeSqlite.DatabaseSync(sourcePath);
apps/server/src/persistence/initializeV2Database.ts
+17 -8
@@ -14,6 +14,8 @@ export class V2DatabaseImportError extends Schema.TaggedError<V2DatabaseImportEr
14 }
15 }
16
17 +const isV2DatabaseImportError = Schema.is(V2DatabaseImportError);
18 +
19 const isProcessAlive = (pid: number): boolean => {
20 if (!Number.isInteger(pid) || pid <= 0) return false;
21 try {
@@ -58,13 +60,16 @@ export const initializeV2Database = Effect.fn("initializeV2Database")(function*
60 prefix: `.v2-import-${process.pid}-`,
61 });
62 const snapshotPath = path.join(temporaryDirectory, "snapshot.sqlite");
61 - yield* Effect.tryPromise(async () => {
62 - const database = new NodeSqlite.DatabaseSync(sourcePath, { readOnly: true });
63 - try {
64 - await NodeSqlite.backup(database, snapshotPath);
65 - } finally {
66 - database.close();
67 - }
63 + yield* Effect.tryPromise({
64 + try: async () => {
65 + const database = new NodeSqlite.DatabaseSync(sourcePath, { readOnly: true });
66 + try {
67 + await NodeSqlite.backup(database, snapshotPath);
68 + } finally {
69 + database.close();
70 + }
71 + },
72 + catch: (cause) => new V2DatabaseImportError({ sourcePath, destinationPath, cause }),
73 });
74 // Publish only a complete snapshot, without replacing an existing V2 database.
75 yield* fs.link(snapshotPath, destinationPath).pipe(
@@ -75,6 +80,10 @@ export const initializeV2Database = Effect.fn("initializeV2Database")(function*
80 );
81 }).pipe(
82 Effect.scoped,
78 - Effect.mapError((cause) => new V2DatabaseImportError({ sourcePath, destinationPath, cause })),
83 + Effect.mapError((cause) =>
84 + isV2DatabaseImportError(cause)
85 + ? cause
86 + : new V2DatabaseImportError({ sourcePath, destinationPath, cause }),
87 + ),
88 );
89 });
apps/server/src/preview/ServerBrowser.ts
+13 -1
@@ -147,6 +147,15 @@ const isHostSetupError = Schema.is(
147 ]),
148 );
149
150 +class ServerBrowserDownloadsCleanupError extends Schema.TaggedError<ServerBrowserDownloadsCleanupError>()(
151 + "ServerBrowserDownloadsCleanupError",
152 + { cause: Schema.Defect() },
153 +) {
154 + override get message(): string {
155 + return "The server preview could not clear earlier downloads.";
156 + }
157 +}
158 +
159 export class ServerBrowserLaunchError extends Schema.TaggedError<ServerBrowserLaunchError>()(
160 "ServerBrowserLaunchError",
161 { cause: Schema.Defect() },
@@ -1034,7 +1043,10 @@ const make = Effect.gen(function* () {
1043
1044 const downloadsRoot = NodePath.join(config.stateDir, "server-browser", "downloads");
1045 // Saved downloads are indexed in memory, so an earlier run's files can never be opened again.
1037 - yield* Effect.tryPromise(() => NodeFSP.rm(downloadsRoot, { recursive: true, force: true })).pipe(
1046 + yield* Effect.tryPromise({
1047 + try: () => NodeFSP.rm(downloadsRoot, { recursive: true, force: true }),
1048 + catch: (cause) => new ServerBrowserDownloadsCleanupError({ cause }),
1049 + }).pipe(
1050 Effect.catch((cause) =>
1051 Effect.logWarning("server preview could not clear earlier downloads", { cause }),
1052 ),
apps/server/src/project/AgentSessionScanner.ts
+32 -13
@@ -46,6 +46,15 @@ import {
46 } from "./AgentSessionJson.ts";
47
48 const TRANSCRIPT_PREFIX_BYTES = 32 * 1024;
49 +
50 +class TranscriptParseError extends Schema.TaggedError<TranscriptParseError>()(
51 + "TranscriptParseError",
52 + { filePath: Schema.String, cause: Schema.Defect() },
53 +) {
54 + override get message(): string {
55 + return `Could not parse the transcript at ${this.filePath}.`;
56 + }
57 +}
58 const METADATA_READ_BYTES = 8 * 1024;
59 const MAX_TRANSCRIPT_SCAN_BYTES = 1024 * 1024;
60 const MAX_CODEX_SESSION_INDEX_BYTES = 1024 * 1024;
@@ -1071,23 +1080,33 @@ export const make = Effect.gen(function* () {
1080 }
1081
1082 bytesRead += next.value.byteLength;
1074 - const withinBudget = yield* Effect.try(() => {
1075 - let start = 0;
1076 - while (start < next.value.byteLength) {
1077 - const newline = next.value.indexOf(10, start);
1078 - const end = newline === -1 ? next.value.byteLength : newline;
1079 - recordStarted = true;
1080 - reader.write(decoder.decode(next.value.subarray(start, end), { stream: true }));
1081 - if (newline === -1) break;
1082 - if (!finishRecord()) return false;
1083 - start = newline + 1;
1084 - }
1085 - return true;
1083 + const withinBudget = yield* Effect.try({
1084 + try: () => {
1085 + let start = 0;
1086 + while (start < next.value.byteLength) {
1087 + const newline = next.value.indexOf(10, start);
1088 + const end = newline === -1 ? next.value.byteLength : newline;
1089 + recordStarted = true;
1090 + reader.write(decoder.decode(next.value.subarray(start, end), { stream: true }));
1091 + if (newline === -1) break;
1092 + if (!finishRecord()) return false;
1093 + start = newline + 1;
1094 + }
1095 + return true;
1096 + },
1097 + catch: (cause) => new TranscriptParseError({ filePath, cause }),
1098 });
1099 if (!withinBudget) return null;
1100 }
1101
1090 - if (recordStarted && !(yield* Effect.try(finishRecord))) return null;
1102 + if (
1103 + recordStarted &&
1104 + !(yield* Effect.try({
1105 + try: finishRecord,
1106 + catch: (cause) => new TranscriptParseError({ filePath, cause }),
1107 + }))
1108 + )
1109 + return null;
1110 return sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat))
1111 ? { records, cwd, claudeFields }
1112 : null;
apps/server/src/provider/AntigravityInstallation.ts
+4 -3
@@ -497,9 +497,10 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma
497 return;
498 }
499
500 - const available = yield* Effect.tryPromise(() =>
501 - NodeFSP.statfs(versionsDirectory, { bigint: true }),
502 - ).pipe(Effect.option);
500 + const available = yield* Effect.tryPromise({
501 + try: () => NodeFSP.statfs(versionsDirectory, { bigint: true }),
502 + catch: (cause) => installationError("download", "Could not check free disk space.", cause),
503 + }).pipe(Effect.option);
504 const required =
505 asset.archiveBytes + asset.executable.bytes + asset.harness.bytes + FREE_SPACE_MARGIN;
506 if (
apps/server/src/provider/ClaudeProvider.ts
+36 -19
@@ -13,6 +13,7 @@ import * as Option from "effect/Option";
13 import * as Path from "effect/Path";
14 import * as Ref from "effect/Ref";
15 import * as Result from "effect/Result";
16 +import * as Schema from "effect/Schema";
17 import { ChildProcess, ChildProcessSpawner } from "effect/process";
18 import { createModelCapabilities } from "@t3tools/shared/model";
19 import { resolveSpawnCommand } from "@t3tools/shared/shell";
@@ -335,6 +336,15 @@ function claudeGatewayDiscoveryGraceMs(environment: Readonly<Record<string, unkn
336 return Number.isFinite(configured) && configured > 0 ? configured : 3_000;
337 }
338
339 +class ClaudeCapabilitiesProbeSdkError extends Schema.TaggedError<ClaudeCapabilitiesProbeSdkError>()(
340 + "ClaudeCapabilitiesProbeSdkError",
341 + { operation: Schema.Literals(["initialize", "usage"]), cause: Schema.Defect() },
342 +) {
343 + override get message(): string {
344 + return `Claude capability probe ${this.operation} failed.`;
345 + }
346 +}
347 +
348 /** A never-yielding prompt allows local initialization IPC without sending an Anthropic request. */
349 const probeClaudeCapabilities = (
350 claudeSettings: ClaudeSettings,
@@ -360,22 +370,25 @@ const probeClaudeCapabilities = (
370 ...(yield* readClaudeSettingsEnv(claudeSettings, cwd, claudeEnvironment)),
371 })
372 : 0;
363 - return yield* Effect.tryPromise(async () => {
364 - const q = claudeQuery({
365 - // oxlint-disable-next-line require-yield -- never yields, so no prompt reaches the API
366 - prompt: (async function* (): AsyncGenerator<SDKUserMessage> {
367 - await waitForAbortSignal(abort.signal);
368 - })(),
369 - options: buildClaudeCapabilitiesProbeQueryOptions({
370 - executablePath,
371 - abortController: abort,
372 - environment: claudeEnvironment,
373 - cwd,
374 - managedMcpConfig,
375 - }),
376 - });
377 - const init = await q.initializationResult();
378 - return { q, init, graceMs };
373 + return yield* Effect.tryPromise({
374 + try: async () => {
375 + const q = claudeQuery({
376 + // oxlint-disable-next-line require-yield -- never yields, so no prompt reaches the API
377 + prompt: (async function* (): AsyncGenerator<SDKUserMessage> {
378 + await waitForAbortSignal(abort.signal);
379 + })(),
380 + options: buildClaudeCapabilitiesProbeQueryOptions({
381 + executablePath,
382 + abortController: abort,
383 + environment: claudeEnvironment,
384 + cwd,
385 + managedMcpConfig,
386 + }),
387 + });
388 + const init = await q.initializationResult();
389 + return { q, init, graceMs };
390 + },
391 + catch: (cause) => new ClaudeCapabilitiesProbeSdkError({ operation: "initialize", cause }),
392 });
393 }).pipe(
394 Effect.timeout(CAPABILITIES_PROBE_TIMEOUT_MS),
@@ -386,9 +399,13 @@ const probeClaudeCapabilities = (
399 // `behaviors`: with a few GB of transcripts it outlasts the deadline.
400 const usageCheckedAt = DateTime.formatIso(yield* DateTime.now);
401 const usageResult = includeUsage
389 - ? yield* Effect.tryPromise(() =>
390 - q.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true }),
391 - ).pipe(Effect.timeout(DEFAULT_TIMEOUT_MS), Effect.result)
402 + ? yield* Effect.tryPromise({
403 + try: () =>
404 + q.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({
405 + skipBehaviors: true,
406 + }),
407 + catch: (cause) => new ClaudeCapabilitiesProbeSdkError({ operation: "usage", cause }),
408 + }).pipe(Effect.timeout(DEFAULT_TIMEOUT_MS), Effect.result)
409 : undefined;
410 const usage =
411 usageResult && Result.isSuccess(usageResult)
apps/server/src/provider/CodexChatGptAuth.test.ts
+7 -2
@@ -1640,8 +1640,13 @@ it.effect(
1640 const callback = new URL(
1641 new URL(state.authorizationUrl!).searchParams.get("redirect_uri")!,
1642 );
1643 - const request = yield* Effect.tryPromise(() => fetch(callback)).pipe(Effect.result);
1644 - assert.strictEqual(request._tag, "Failure");
1643 + const rejected = yield* Effect.promise(() =>
1644 + fetch(callback).then(
1645 + () => false,
1646 + () => true,
1647 + ),
1648 + );
1649 + assert.isTrue(rejected);
1650 assert.isTrue(Option.isNone(yield* h.auth.read));
1651 }),
1652 ),
apps/server/src/provider/Drivers/antigravityUsageReader.ts
+4 -1
@@ -414,7 +414,10 @@ export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function*
414 if (visited.has(canonical)) return null;
415 visited.add(canonical);
416 const fingerprintOf = (file: string) =>
417 - Effect.tryPromise(() => NodeFSP.stat(file)).pipe(
417 + Effect.tryPromise({
418 + try: () => NodeFSP.stat(file),
419 + catch: (cause) => new AntigravityDatabaseDecodeError({ path: file, cause }),
420 + }).pipe(
421 Effect.map((stat) => ({ stat, part: `${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}` })),
422 );
423 const { stat, part } = yield* fingerprintOf(path);
apps/server/src/provider/acp/AntigravityTurnOutcome.ts
+50 -31
@@ -8,6 +8,7 @@ import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
8 import * as DateTime from "effect/DateTime";
9 import * as Effect from "effect/Effect";
10 import * as Option from "effect/Option";
11 +import * as Schema from "effect/Schema";
12 import type * as EffectAcpSchema from "effect-acp/compat";
13
14 import { antigravityManagedPath, antigravityProfileRoot } from "./AntigravityProfilePaths.ts";
@@ -41,19 +42,33 @@ interface LastStep {
42 readonly payload: Uint8Array | null;
43 }
44
45 +class AntigravitySessionLogError extends Schema.TaggedError<AntigravitySessionLogError>()(
46 + "AntigravitySessionLogError",
47 + { cause: Schema.Defect() },
48 +) {
49 + override get message(): string {
50 + return "Could not read the Antigravity session log.";
51 + }
52 +}
53 +
54 +const sessionLogError = (cause: unknown) => new AntigravitySessionLogError({ cause });
55 +
56 const readSteps = <A>(file: string, read: (database: NodeSqlite.DatabaseSync) => A) =>
45 - Effect.try(() => {
46 - const database = new NodeSqlite.DatabaseSync(file, { readOnly: true });
47 - try {
48 - database.exec("PRAGMA busy_timeout = 100");
49 - const hasSteps =
50 - database
51 - .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'steps'")
52 - .get() !== undefined;
53 - return hasSteps ? read(database) : undefined;
54 - } finally {
55 - database.close();
56 - }
57 + Effect.try({
58 + try: () => {
59 + const database = new NodeSqlite.DatabaseSync(file, { readOnly: true });
60 + try {
61 + database.exec("PRAGMA busy_timeout = 100");
62 + const hasSteps =
63 + database
64 + .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'steps'")
65 + .get() !== undefined;
66 + return hasSteps ? read(database) : undefined;
67 + } finally {
68 + database.close();
69 + }
70 + },
71 + catch: sessionLogError,
72 });
73
74 const lastStepIndex = (database: NodeSqlite.DatabaseSync) => {
@@ -142,22 +157,25 @@ export const watchAntigravityPromptOutcome = Effect.fn("AntigravityTurnOutcome.w
157 DateTime.now.pipe(Effect.map((now) => turnFailure(result.stopReason, undefined, now)));
158 if (!NATIVE_SESSION_ID.test(sessionId)) return typedOnly;
159 const segments = [...conversationSegments, `${sessionId}.db`];
145 - const before = yield* Effect.tryPromise(async () => {
146 - const root = await antigravityProfileRoot(profileDirectory);
147 - if (root === undefined) return undefined;
148 - if ((await antigravityManagedPath(root, conversationSegments, "directory")) === undefined) {
149 - return undefined;
150 - }
151 - const database = await antigravityManagedPath(root, segments, "file");
152 - // A path that exists but fails the proof is a link or other foreign entry.
153 - if (database === undefined) {
154 - const present = await NodeFSP.lstat(NodePath.join(root, ...segments)).then(
155 - () => true,
156 - () => false,
157 - );
158 - return present ? undefined : { root, identity: undefined, startIndex: -1 };
159 - }
160 - return { root, identity: database.info, startIndex: undefined };
160 + const before = yield* Effect.tryPromise({
161 + try: async () => {
162 + const root = await antigravityProfileRoot(profileDirectory);
163 + if (root === undefined) return undefined;
164 + if ((await antigravityManagedPath(root, conversationSegments, "directory")) === undefined) {
165 + return undefined;
166 + }
167 + const database = await antigravityManagedPath(root, segments, "file");
168 + // A path that exists but fails the proof is a link or other foreign entry.
169 + if (database === undefined) {
170 + const present = await NodeFSP.lstat(NodePath.join(root, ...segments)).then(
171 + () => true,
172 + () => false,
173 + );
174 + return present ? undefined : { root, identity: undefined, startIndex: -1 };
175 + }
176 + return { root, identity: database.info, startIndex: undefined };
177 + },
178 + catch: sessionLogError,
179 }).pipe(Effect.orElseSucceed(() => undefined));
180 if (before === undefined) {
181 yield* Effect.logWarning("The Antigravity session log is not this session's own file.");
@@ -177,9 +195,10 @@ export const watchAntigravityPromptOutcome = Effect.fn("AntigravityTurnOutcome.w
195 result: EffectAcpSchema.PromptResponse,
196 ) {
197 // The same file as before the prompt, or one this prompt created, still unlinked.
180 - const after = yield* Effect.tryPromise(() =>
181 - antigravityManagedPath(before.root, segments, "file"),
182 - ).pipe(Effect.orElseSucceed(() => undefined));
198 + const after = yield* Effect.tryPromise({
199 + try: () => antigravityManagedPath(before.root, segments, "file"),
200 + catch: sessionLogError,
201 + }).pipe(Effect.orElseSucceed(() => undefined));
202 const sameFile =
203 after !== undefined &&
204 (before.identity === undefined ||
apps/server/src/provider/antigravityAuthSupport.ts
+17 -4
@@ -230,6 +230,15 @@ function antigravityEnvironment(
230 };
231 }
232
233 +class AntigravitySkillLinkError extends Schema.TaggedError<AntigravitySkillLinkError>()(
234 + "AntigravitySkillLinkError",
235 + { link: Schema.String, cause: Schema.Defect() },
236 +) {
237 + override get message(): string {
238 + return `Could not link Antigravity user skills at ${this.link}.`;
239 + }
240 +}
241 +
242 /** Private GEMINI_HOME isolates credentials/hooks/MCP; link global skills from the real ~/.gemini. */
243 const linkAntigravityUserSkills = Effect.fn("linkAntigravityUserSkills")(function* (input: {
244 readonly profileDirectory: string;
@@ -260,7 +269,10 @@ const linkAntigravityUserSkills = Effect.fn("linkAntigravityUserSkills")(functio
269 // An empty folder is the harness's placeholder from a launch without the link.
270 // rmdir refuses a non-empty folder, so content added meanwhile is never deleted.
271 Effect.catch((error) =>
263 - Effect.tryPromise(() => NodeFSP.rmdir(link)).pipe(
272 + Effect.tryPromise({
273 + try: () => NodeFSP.rmdir(link),
274 + catch: (cause) => new AntigravitySkillLinkError({ link, cause }),
275 + }).pipe(
276 Effect.as(undefined),
277 Effect.mapError(() => error),
278 ),
@@ -271,9 +283,10 @@ const linkAntigravityUserSkills = Effect.fn("linkAntigravityUserSkills")(functio
283 yield* fs.remove(link);
284 }
285 yield* fs.makeDirectory(path.dirname(link), { recursive: true });
274 - yield* Effect.tryPromise(() =>
275 - NodeFSP.symlink(target, link, input.platform === "win32" ? "junction" : "dir"),
276 - );
286 + yield* Effect.tryPromise({
287 + try: () => NodeFSP.symlink(target, link, input.platform === "win32" ? "junction" : "dir"),
288 + catch: (cause) => new AntigravitySkillLinkError({ link, cause }),
289 + });
290 }).pipe(
291 Effect.catch((error) =>
292 Effect.logWarning("Antigravity user skills are not linked into the profile.", {
apps/server/src/storageCleanup.ts
+15 -1
@@ -67,6 +67,15 @@ const decodePnpmModulesManifest = Schema.decodeUnknownEffect(
67 }),
68 );
69
70 +class PnpmModulesManifestParseError extends Schema.TaggedError<PnpmModulesManifestParseError>()(
71 + "PnpmModulesManifestParseError",
72 + { cause: Schema.Defect() },
73 +) {
74 + override get message(): string {
75 + return "Could not parse the pnpm modules manifest.";
76 + }
77 +}
78 +
79 const DAY_MS = 86_400_000;
80 // Give settle scripts time to open terminals that protect the worktree.
81 const SETTLE_SCRIPT_GRACE_MS = 60_000;
@@ -341,7 +350,12 @@ const make = Effect.gen(function* () {
350 function* (root: string) {
351 const nodeModules = path.join(root, "node_modules");
352 const text = yield* fs.readFileString(path.join(nodeModules, ".modules.yaml"));
344 - const manifest = yield* decodePnpmModulesManifest(yield* Effect.try(() => parseYaml(text)));
353 + const manifest = yield* decodePnpmModulesManifest(
354 + yield* Effect.try({
355 + try: () => parseYaml(text),
356 + catch: (cause) => new PnpmModulesManifestParseError({ cause }),
357 + }),
358 + );
359 // An agent can write this manifest, and statting a network path makes
360 // Windows sign in to its host with the user's NTLM credentials.
361 if (isNetworkPath(manifest.storeDir) || isNetworkPath(manifest.virtualStoreDir ?? "")) {
apps/server/src/terminal/NodePtyAdapter.ts
+24 -12
@@ -24,6 +24,15 @@ export class NodePtyModuleLoadError extends Schema.TaggedError<NodePtyModuleLoad
24 }
25 }
26
27 +class NodePtyCancelError extends Schema.TaggedError<NodePtyCancelError>()("NodePtyCancelError", {
28 + terminalPid: Schema.Number,
29 + cause: Schema.Defect(),
30 +}) {
31 + override get message(): string {
32 + return `Failed to cancel Windows terminal startup for ${this.terminalPid}.`;
33 + }
34 +}
35 +
36 type NodePtyModuleLoader = () => Promise<typeof import("node-pty")>;
37
38 // node-pty's native addon stays external; single-executables need require to resolve disk modules and spawn helpers.
@@ -134,18 +143,21 @@ const waitForWindowsPid = (
143
144 // The private agent cancels pending connections before a child exists; public kill waits for first output.
145 const killStartingWindowsPty = (process: import("node-pty").IPty) =>
137 - Effect.try(() => {
138 - if (
139 - "_agent" in process &&
140 - typeof process._agent === "object" &&
141 - process._agent !== null &&
142 - "kill" in process._agent &&
143 - typeof process._agent.kill === "function"
144 - ) {
145 - process._agent.kill();
146 - } else {
147 - process.kill();
148 - }
146 + Effect.try({
147 + try: () => {
148 + if (
149 + "_agent" in process &&
150 + typeof process._agent === "object" &&
151 + process._agent !== null &&
152 + "kill" in process._agent &&
153 + typeof process._agent.kill === "function"
154 + ) {
155 + process._agent.kill();
156 + } else {
157 + process.kill();
158 + }
159 + },
160 + catch: (cause) => new NodePtyCancelError({ terminalPid: process.pid, cause }),
161 }).pipe(
162 Effect.catch((error) =>
163 Effect.logWarning("failed to cancel Windows terminal startup", {
apps/server/src/usage/UsageService.test.ts
+14 -8
@@ -56,14 +56,20 @@ import { MuseUsageHome } from "@t3tools/provider-muse/server";
56 import { makeScanCacheWriter, SCAN_CACHE_FILE_NAME } from "./usageScanCache.ts";
57
58 vi.mock("node:fs/promises", { spy: true });
59 -vi.mock("../../../../packages/provider-muse/src/server/sdk.ts", async (importOriginal) => ({
60 - ...(await importOriginal<typeof MuseSdk>()),
61 - createMuseSdkHostEffect: vi.fn(() =>
62 - Effect.try(() => {
63 - throw new Error("Muse is not installed in this test");
64 - }),
65 - ),
66 -}));
59 +vi.mock("../../../../packages/provider-muse/src/server/sdk.ts", async (importOriginal) => {
60 + const original = await importOriginal<typeof MuseSdk>();
61 + return {
62 + ...original,
63 + createMuseSdkHostEffect: vi.fn(() =>
64 + Effect.fail(
65 + new original.MuseSdkError({
66 + operation: "start",
67 + cause: new Error("Muse is not installed in this test"),
68 + }),
69 + ),
70 + ),
71 + };
72 +});
73
74 const encodeUnknownJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
75 const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
apps/server/src/vcs/GitVcsDriverCore.ts
+2 -3
@@ -1,5 +1,4 @@
1 import * as Cache from "effect/Cache";
2 -import * as Cause from "effect/Cause";
2 import * as Clock from "effect/Clock";
3 import * as Data from "effect/Data";
4 import * as Digest from "effect/crypto/Digest";
@@ -42,7 +41,7 @@ import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
41 import { resolveProjectFileBackedSetting } from "@t3tools/shared/projectSettings";
42 import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts";
43 import * as GitVcsDriver from "./GitVcsDriver.ts";
45 -import { removeEmptyDirectory } from "./removeEmptyDirectory.ts";
44 +import { removeEmptyDirectory, type RemoveEmptyDirectoryError } from "./removeEmptyDirectory.ts";
45 import { explicitBareRepositoryEnv, gitConfigEnv } from "./VcsProcess.ts";
46 import { removeLinkedWorktree } from "./worktreeRemoval.ts";
47 import { resolveWorktreesDirectory } from "../worktreesDirectory.ts";
@@ -4732,7 +4731,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4731 // Recursive filesystem traversal can visit many entries; removeWorktree owns the operation span.
4732 const removeLeftoverLinks = Effect.fnUntraced(function* (
4733 target: string,
4735 - ): Effect.fn.Return<boolean, PlatformError.PlatformError | Cause.UnknownError> {
4734 + ): Effect.fn.Return<boolean, PlatformError.PlatformError | RemoveEmptyDirectoryError> {
4735 if (Option.isSome(yield* fileSystem.readLink(target).pipe(Effect.option))) {
4736 yield* fileSystem.remove(target);
4737 return true;
apps/server/src/vcs/removeEmptyDirectory.ts
+14 -1
@@ -2,6 +2,16 @@
2 import * as NodeFSP from "node:fs/promises";
3
4 import * as Effect from "effect/Effect";
5 +import * as Schema from "effect/Schema";
6 +
7 +export class RemoveEmptyDirectoryError extends Schema.TaggedError<RemoveEmptyDirectoryError>()(
8 + "RemoveEmptyDirectoryError",
9 + { path: Schema.String, cause: Schema.Defect() },
10 +) {
11 + override get message(): string {
12 + return `Could not remove the directory ${this.path}.`;
13 + }
14 +}
15
16 /**
17 * Removes `path` only while it is an empty directory. Succeeds with false when
@@ -9,7 +19,10 @@ import * as Effect from "effect/Effect";
19 * Other failures, such as a permission error, stay errors.
20 */
21 export const removeEmptyDirectory = (path: string) =>
12 - Effect.tryPromise(() => NodeFSP.rmdir(path)).pipe(
22 + Effect.tryPromise({
23 + try: () => NodeFSP.rmdir(path),
24 + catch: (cause) => new RemoveEmptyDirectoryError({ path, cause }),
25 + }).pipe(
26 Effect.as(true),
27 Effect.catchIf(
28 (error) => (error.cause as NodeJS.ErrnoException | undefined)?.code === "ENOTEMPTY",
apps/web/src/components/device/deviceHubAtoms.ts
+14 -1
@@ -1,6 +1,7 @@
1 import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
2 import * as Effect from "effect/Effect";
3 import * as Schedule from "effect/Schedule";
4 +import * as Schema from "effect/Schema";
5 import * as Stream from "effect/Stream";
6 import { AsyncResult, Atom } from "effect/reactivity";
7
@@ -40,11 +41,23 @@ export const deviceEventLogAtom = Atom.family((target: DeviceHubTarget) =>
41 }).pipe(Atom.withLabel(`device-event-log:${target.deviceId}`)),
42 );
43
44 +class DeviceAxTreeFetchError extends Schema.TaggedError<DeviceAxTreeFetchError>()(
45 + "DeviceAxTreeFetchError",
46 + { cause: Schema.Defect() },
47 +) {
48 + override get message(): string {
49 + return "Could not read the device accessibility tree.";
50 + }
51 +}
52 +
53 // A failed poll keeps the last frames on screen; the next poll replaces them.
54 export const deviceAxElementsAtom = Atom.family((target: DeviceHubTarget) =>
55 Atom.make(
56 Stream.fromEffectSchedule(
47 - Effect.tryPromise((signal) => fetchDeviceAxTree(target, signal)).pipe(
57 + Effect.tryPromise({
58 + try: (signal) => fetchDeviceAxTree(target, signal),
59 + catch: (cause) => new DeviceAxTreeFetchError({ cause }),
60 + }).pipe(
61 Effect.map((tree): ReadonlyArray<DeviceAxElement> | null => tree.elements),
62 Effect.orElseSucceed(() => null),
63 ),
apps/web/src/connection/platform.ts
+9 -7
@@ -313,13 +313,15 @@ const ANALYTICS_DEVICE_ID_KEY = "t3code:analytics-device-id";
313
314 // Lives as long as this browser profile's site data. Storage can be blocked, which only drops the id.
315 const analyticsDevice = {
316 - id: Effect.try(() => {
317 - const existing = window.localStorage.getItem(ANALYTICS_DEVICE_ID_KEY);
318 - if (existing) return existing;
319 - const created = randomUUID();
320 - window.localStorage.setItem(ANALYTICS_DEVICE_ID_KEY, created);
321 - return created;
322 - }).pipe(Effect.option),
316 + id: Effect.sync(
317 + Option.liftThrowable(() => {
318 + const existing = window.localStorage.getItem(ANALYTICS_DEVICE_ID_KEY);
319 + if (existing) return existing;
320 + const created = randomUUID();
321 + window.localStorage.setItem(ANALYTICS_DEVICE_ID_KEY, created);
322 + return created;
323 + }),
324 + ),
325 };
326
327 const layerCapabilities = Layer.effectContext(
evals/mcp-tool-use/run.ts
+40 -23
@@ -112,6 +112,15 @@ const isPricedModel = (model: ShellModel): model is PricedModel => model in PRIC
112 const T3_PREFIX = "mcp__t3-code__";
113 const RUNTIME_MARKER = "<runtime_info>";
114 const TOOL_LOADED = "Tool loaded.";
115 +
116 +class EvalToolCallError extends Schema.TaggedError<EvalToolCallError>()("EvalToolCallError", {
117 + tool: Schema.String,
118 + cause: Schema.Defect(),
119 +}) {
120 + override get message(): string {
121 + return `The ${this.tool} tool call failed.`;
122 + }
123 +}
124 const DEFERRED_LIST =
125 /(The following deferred tools are now available via ToolSearch\.[^\n]*\n)((?:[^\n]+\n)*)/;
126 const MODEL_LINE = /You are powered by the model named .+?\. The exact model ID is [\w.-]+\./;
@@ -2063,24 +2072,27 @@ const runSample = Effect.fn("evaluateMcpToolUse.runSample")(function* (
2072 runPromise,
2073 );
2074 };
2066 - return yield* Effect.tryPromise(async () => {
2067 - const output =
2068 - use.name === "exec"
2069 - ? await executeCodex(
2070 - valueText(use.input),
2071 - codexCatalog(base),
2072 - answer,
2073 - sample.codeStore,
2074 - )
2075 - : await answer(use.name, use.input, false);
2076 - const item = {
2077 - type: use.name === "exec" ? "custom_tool_call_output" : "function_call_output",
2078 - call_id: use.id,
2079 - output: valueText(output),
2080 - };
2081 - input.push(item);
2082 - transcript.push(item);
2083 - return toolResult(use.id, output);
2075 + return yield* Effect.tryPromise({
2076 + try: async () => {
2077 + const output =
2078 + use.name === "exec"
2079 + ? await executeCodex(
2080 + valueText(use.input),
2081 + codexCatalog(base),
2082 + answer,
2083 + sample.codeStore,
2084 + )
2085 + : await answer(use.name, use.input, false);
2086 + const item = {
2087 + type: use.name === "exec" ? "custom_tool_call_output" : "function_call_output",
2088 + call_id: use.id,
2089 + output: valueText(output),
2090 + };
2091 + input.push(item);
2092 + transcript.push(item);
2093 + return toolResult(use.id, output);
2094 + },
2095 + catch: (cause) => new EvalToolCallError({ tool: use.name, cause }),
2096 });
2097 }),
2098 );
@@ -2429,11 +2441,16 @@ const main = Effect.gen(function* () {
2441 // Only a case that passed every baseline sample can stop a run; flaky ones are just reported.
2442 const passedBefore = (id: string) => baseline.get(id) === 1;
2443 // Before the paid runs, so a missing git cannot lose their results.
2432 - const commit = yield* Effect.try(() =>
2433 - NodeChildProcess.execFileSync("git", ["describe", "--always", "--dirty"], {
2434 - encoding: "utf8",
2435 - }).trim(),
2436 - ).pipe(Effect.orElseSucceed(() => "unknown"));
2444 + const commit = yield* Effect.sync(() =>
2445 + Option.getOrElse(
2446 + Option.liftThrowable(() =>
2447 + NodeChildProcess.execFileSync("git", ["describe", "--always", "--dirty"], {
2448 + encoding: "utf8",
2449 + }).trim(),
2450 + )(),
2451 + () => "unknown",
2452 + ),
2453 + );
2454 const inFlight = yield* Semaphore.make(flags.concurrency);
2455 const runOne = (testCase: McpToolUseCase) => {
2456 const { id, kind, pattern } = testCase;
infra/relay/scripts/android-push-watch.ts
+13 -1
@@ -42,7 +42,19 @@ const Connection = Schema.Struct({
42 wsUrl: Schema.NonEmptyString,
43 bearerToken: Schema.NonEmptyString,
44 });
45 -const readFile = (path: string) => Effect.tryPromise(() => NodeFSP.readFile(path, "utf8"));
45 +class WatchReadFileError extends Schema.TaggedError<WatchReadFileError>()("WatchReadFileError", {
46 + path: Schema.String,
47 + cause: Schema.Defect(),
48 +}) {
49 + override get message() {
50 + return `Could not read ${this.path}`;
51 + }
52 +}
53 +const readFile = (path: string) =>
54 + Effect.tryPromise({
55 + try: () => NodeFSP.readFile(path, "utf8"),
56 + catch: (cause) => new WatchReadFileError({ path, cause }),
57 + });
58 const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
59 class WatchUnregisteredDeviceError extends Schema.TaggedError<WatchUnregisteredDeviceError>()(
60 "WatchUnregisteredDeviceError",
infra/task-cache/src/developerAuth.ts
+2 -1
@@ -1,4 +1,5 @@
1 import * as Effect from "effect/Effect";
2 +import * as Option from "effect/Option";
3 import * as Schema from "effect/Schema";
4
5 const Keys = Schema.fromJsonString(Schema.Record(Schema.String, Schema.String));
@@ -13,7 +14,7 @@ export const developerIdentity = Effect.fn("TaskCache.developerIdentity")(functi
14 if (!authorization?.toLowerCase().startsWith("basic ")) return undefined;
15 if (!encodedKeys || authorization.length > 1024) return null;
16
16 - const decoded = yield* Effect.try(() => atob(authorization.slice(6))).pipe(Effect.option);
17 + const decoded = Option.liftThrowable(atob)(authorization.slice(6));
18 if (decoded._tag === "None") return null;
19 const keys = yield* decodeKeys(encodedKeys).pipe(Effect.option);
20 if (keys._tag === "None") return null;
packages/provider-acp/src/server/AcpSessionRuntime.ts
+6 -6
@@ -484,18 +484,18 @@ export function terminateLinuxCgroupLease(
484 let lastRemovalFailure: { readonly cause: unknown } | null = null;
485 for (let attempt = 0; attempt < 200; attempt += 1) {
486 if (!lease.exists()) return;
487 - const killed = yield* Effect.try(() => lease.kill()).pipe(Effect.result);
487 + const killed = Result.try(() => lease.kill());
488 if (Result.isFailure(killed)) {
489 - const cause = killed.failure.cause;
489 + const cause = killed.failure;
490 const code = (cause as NodeJS.ErrnoException | undefined)?.code;
491 if (code !== "ENOENT") return yield* failure("kill", cause);
492 if (!lease.exists()) return;
493 yield* Effect.sleep("10 millis");
494 continue;
495 }
496 - const populated = yield* Effect.try(() => lease.populated()).pipe(Effect.result);
496 + const populated = Result.try(() => lease.populated());
497 if (Result.isFailure(populated)) {
498 - const cause = populated.failure.cause;
498 + const cause = populated.failure;
499 const code = (cause as NodeJS.ErrnoException | undefined)?.code;
500 if (code === "ENOENT" && !lease.exists()) return;
501 if (code === "ENOENT") {
@@ -509,9 +509,9 @@ export function terminateLinuxCgroupLease(
509 yield* Effect.sleep("10 millis");
510 continue;
511 }
512 - const removed = yield* Effect.try(() => lease.remove()).pipe(Effect.result);
512 + const removed = Result.try(() => lease.remove());
513 if (Result.isFailure(removed)) {
514 - const cause = removed.failure.cause;
514 + const cause = removed.failure;
515 const code = (cause as NodeJS.ErrnoException | undefined)?.code;
516 if (code === "ENOENT" && !lease.exists()) return;
517 if (code !== "EBUSY" && code !== "ENOTEMPTY" && code !== "ENOENT") {
packages/provider-cursor/src/server/CursorAgentSdk.ts
+17 -14
@@ -357,20 +357,23 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu
357 if (yield* Ref.getAndSet(sandboxSupportPrimeStarted, true)) {
358 return yield* Deferred.await(sandboxSupportPrimed);
359 }
360 - yield* Effect.tryPromise(async () => {
361 - const cwd = typeof options.local?.cwd === "string" ? options.local.cwd : undefined;
362 - const platform = await sdk
363 - .load()
364 - .createAgentPlatform(cwd === undefined ? {} : { workspaceRef: cwd });
365 - const release = await platform.prewarmLocalWorkspace({
366 - ...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),
367 - local: {
368 - ...(cwd === undefined ? {} : { cwd }),
369 - settingSources: [],
370 - sandboxOptions: { enabled: true },
371 - },
372 - });
373 - await release();
360 + yield* Effect.tryPromise({
361 + try: async () => {
362 + const cwd = typeof options.local?.cwd === "string" ? options.local.cwd : undefined;
363 + const platform = await sdk
364 + .load()
365 + .createAgentPlatform(cwd === undefined ? {} : { workspaceRef: cwd });
366 + const release = await platform.prewarmLocalWorkspace({
367 + ...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),
368 + local: {
369 + ...(cwd === undefined ? {} : { cwd }),
370 + settingSources: [],
371 + sandboxOptions: { enabled: true },
372 + },
373 + });
374 + await release();
375 + },
376 + catch: (cause) => runnerError(cause, "prewarmLocalWorkspace"),
377 }).pipe(Effect.ignore, Effect.ensuring(Deferred.succeed(sandboxSupportPrimed, undefined)));
378 },
379 );
packages/provider-cursor/src/server/credentialStore.test.ts
+11 -11
@@ -56,7 +56,7 @@ it.effect.each([
56 yield* (yield* host.credentials("cursor", instanceId)).set(new TextEncoder().encode(stored));
57 }
58 const migrated = yield* makeCursorCredentialStore(instanceId, legacyFile);
59 - assert.strictEqual((yield* Effect.tryPromise(() => migrated.store.load()))?.apiKey, expected);
59 + assert.strictEqual((yield* Effect.promise(() => migrated.store.load()))?.apiKey, expected);
60 assert.isFalse(yield* fileSystem.exists(legacyFile));
61 }).pipe(Effect.scoped, Effect.provide(layerHost)),
62 );
@@ -77,21 +77,21 @@ it.effect(
77 apiKeyExpiresAtMs: 1000,
78 email: "test@example.com",
79 };
80 - yield* Effect.tryPromise(() => personal.store.save(credentials));
81 - yield* Effect.tryPromise(() =>
80 + yield* Effect.promise(() => personal.store.save(credentials));
81 + yield* Effect.promise(() =>
82 work.store.save({ ...credentials, apiKey: "test-only-work-key" }),
83 );
84 const restored = yield* makeStore("personal");
85 - assert.deepEqual(yield* Effect.tryPromise(() => restored.store.load()), credentials);
85 + assert.deepEqual(yield* Effect.promise(() => restored.store.load()), credentials);
86 yield* (yield* host.credentials("cursor", "personal")).set(
87 new TextEncoder().encode("damaged credential"),
88 );
89 - assert.isUndefined(yield* Effect.tryPromise(() => restored.store.load()));
90 - yield* Effect.tryPromise(() => restored.store.save(credentials));
91 - yield* Effect.tryPromise(() => restored.store.clear());
92 - assert.isUndefined(yield* Effect.tryPromise(() => personal.store.load()));
89 + assert.isUndefined(yield* Effect.promise(() => restored.store.load()));
90 + yield* Effect.promise(() => restored.store.save(credentials));
91 + yield* Effect.promise(() => restored.store.clear());
92 + assert.isUndefined(yield* Effect.promise(() => personal.store.load()));
93 assert.strictEqual(
94 - (yield* Effect.tryPromise(() => work.store.load()))?.apiKey,
94 + (yield* Effect.promise(() => work.store.load()))?.apiKey,
95 "test-only-work-key",
96 );
97 }).pipe(Effect.provide(layerHost)),
@@ -131,10 +131,10 @@ it.effect.each([
131 const credentials = { ...requiredFields };
132 // Match the SDK's runtime values without relying on its stricter declarations.
133 Object.assign(credentials, optionalFields);
134 - yield* Effect.tryPromise(() => store.save(credentials));
134 + yield* Effect.promise(() => store.save(credentials));
135
136 const restored = yield* makeCursorCredentialStore(instanceId);
137 - assert.deepEqual(yield* Effect.tryPromise(() => restored.store.load()), {
137 + assert.deepEqual(yield* Effect.promise(() => restored.store.load()), {
138 ...requiredFields,
139 ...expectedFields,
140 });
packages/provider-cursor/src/server/textGeneration.ts
+52 -35
@@ -86,7 +86,12 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
86 const { operation, prompt, modelSelection } = input;
87
88 const apiKey = yield* resolveCursorApiKey(operation);
89 - const { Agent } = yield* Effect.try(sdk.load);
89 + const sdkFailure = (detail: string) => (cause: unknown) =>
90 + new TextGenerationError({ operation, detail, cause });
91 + const { Agent } = yield* Effect.try({
92 + try: sdk.load,
93 + catch: sdkFailure("Cursor SDK could not be loaded."),
94 + });
95 // sandbox.json expands writable paths independently of settingSources; the public API cannot override it.
96 if (yield* fs.exists(`${yield* HostProcess.HomeDirectory}/.cursor/sandbox.json`)) {
97 return yield* new TextGenerationError({
@@ -99,10 +104,15 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
104 // Only store disposal releases SDK SQLite handles; keep state outside the empty workspace.
105 const stateRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-text-state-" });
106 const store = yield* Effect.acquireRelease(
102 - Effect.tryPromise(() =>
103 - sdk.loadSqlite().SqliteLocalAgentStore.open({ workspaceRef: cwd, stateRoot }),
104 - ),
105 - (store) => Effect.tryPromise(() => store.dispose()).pipe(Effect.ignore({ log: true })),
107 + Effect.tryPromise({
108 + try: () => sdk.loadSqlite().SqliteLocalAgentStore.open({ workspaceRef: cwd, stateRoot }),
109 + catch: sdkFailure("Cursor SDK agent store could not be opened."),
110 + }),
111 + (store) =>
112 + Effect.tryPromise({
113 + try: () => store.dispose(),
114 + catch: sdkFailure("Cursor SDK agent store could not be disposed."),
115 + }).pipe(Effect.ignore({ log: true })),
116 );
117 const agentOptions = {
118 apiKey,
@@ -118,22 +128,24 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
128 },
129 } satisfies AgentOptions;
130 const createCursorAgent = (sandboxEnabled: boolean) =>
121 - Effect.tryPromise((signal) =>
122 - Agent.create(
123 - sandboxEnabled
124 - ? agentOptions
125 - : {
126 - ...agentOptions,
127 - local: {
128 - ...agentOptions.local,
129 - sandboxOptions: { enabled: false },
131 + Effect.tryPromise({
132 + try: (signal) =>
133 + Agent.create(
134 + sandboxEnabled
135 + ? agentOptions
136 + : {
137 + ...agentOptions,
138 + local: {
139 + ...agentOptions.local,
140 + sandboxOptions: { enabled: false },
141 + },
142 },
131 - },
132 - ).then((agent) => {
133 - if (signal.aborted) agent.close();
134 - return agent;
135 - }),
136 - );
143 + ).then((agent) => {
144 + if (signal.aborted) agent.close();
145 + return agent;
146 + }),
147 + catch: sdkFailure("Cursor SDK agent could not be created."),
148 + });
149
150 const request = Effect.gen(function* () {
151 // Empty cwd and setting sources isolate the run from user projects even if sandboxing fails.
@@ -142,27 +154,32 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
154 Effect.catchIf(cursorSandboxUnsupported, () => createCursorAgent(false)),
155 ),
156 (agent) =>
145 - Effect.tryPromise(() => agent[Symbol.asyncDispose]()).pipe(
146 - Effect.timeout("5 seconds"),
147 - Effect.ignore({ log: true }),
148 - ),
157 + Effect.tryPromise({
158 + try: () => agent[Symbol.asyncDispose](),
159 + catch: sdkFailure("Cursor SDK agent could not be disposed."),
160 + }).pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true })),
161 { interruptible: true },
162 );
151 - const run = yield* Effect.tryPromise((signal) =>
152 - agent.send(prompt).then((run) => {
153 - if (signal.aborted) void run.cancel().catch(() => undefined);
154 - return run;
155 - }),
156 - );
163 + const run = yield* Effect.tryPromise({
164 + try: (signal) =>
165 + agent.send(prompt).then((run) => {
166 + if (signal.aborted) void run.cancel().catch(() => undefined);
167 + return run;
168 + }),
169 + catch: sdkFailure("Cursor SDK request could not be sent."),
170 + });
171 yield* Effect.addFinalizer(() =>
172 run.status === "running"
159 - ? Effect.tryPromise(() => run.cancel()).pipe(
160 - Effect.timeout("5 seconds"),
161 - Effect.ignore({ log: true }),
162 - )
173 + ? Effect.tryPromise({
174 + try: () => run.cancel(),
175 + catch: sdkFailure("Cursor SDK run could not be cancelled."),
176 + }).pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true }))
177 : Effect.void,
178 );
165 - return yield* Effect.tryPromise(() => run.wait());
179 + return yield* Effect.tryPromise({
180 + try: () => run.wait(),
181 + catch: sdkFailure("Cursor SDK run failed."),
182 + });
183 }).pipe(Effect.scoped);
184 const promptResult = yield* request.pipe(
185 Effect.timeoutOption(CURSOR_TIMEOUT_MS),
packages/provider-muse/src/server/MuseUsageHome.ts
+6 -2
@@ -5,7 +5,7 @@ import * as Effect from "effect/Effect";
5 import * as Exit from "effect/Exit";
6 import * as Layer from "effect/Layer";
7
8 -import { createMuseSdkHostEffect } from "./sdk.ts";
8 +import { createMuseSdkHostEffect, MuseSdkError } from "./sdk.ts";
9
10 export class MuseUsageHome extends Context.Service<
11 MuseUsageHome,
@@ -26,7 +26,11 @@ const make = Effect.gen(function* () {
26 Effect.gen(function* () {
27 const host = yield* Effect.acquireRelease(
28 createMuseSdkHostEffect({ ...input, readOnly: true, startupTimeoutMs: 5_000 }),
29 - (host) => Effect.tryPromise(() => host.close()).pipe(Effect.ignore),
29 + (host) =>
30 + Effect.tryPromise({
31 + try: () => host.close(),
32 + catch: (cause) => new MuseSdkError({ operation: "close", cause }),
33 + }).pipe(Effect.ignore),
34 { interruptible: true },
35 );
36 return host.initializeResult.museHome;
packages/provider-muse/src/server/adapter.ts
+13 -6
@@ -64,6 +64,7 @@ import {
64 import { isMuseUsageLimitFailure, museUsageLimitResetAt } from "./usageLimits.ts";
65 import {
66 createMuseSdkHostEffect,
67 + MuseSdkError,
68 museApprovalMode,
69 museCanonicalPath,
70 musePermissionProfile,
@@ -1069,7 +1070,10 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
1070 }
1071 yield* settleObservedChildren("failed");
1072 if (turn) yield* Queue.fail(events, protocolError(detail, cause));
1072 - yield* Effect.tryPromise(() => failed.close()).pipe(Effect.ignore, Effect.forkIn(scope));
1073 + yield* Effect.tryPromise({
1074 + try: () => failed.close(),
1075 + catch: (cause) => new MuseSdkError({ operation: "close", cause }),
1076 + }).pipe(Effect.ignore, Effect.forkIn(scope));
1077 });
1078 const owns = (turn: ActiveTurn, turnId: string) =>
1079 turnId === turn.nativeId || turn.joined.has(turnId);
@@ -1724,7 +1728,10 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
1728 closed = true;
1729 hostEpoch++;
1730 }
1727 - const close = Effect.tryPromise(() => created.close());
1731 + const close = Effect.tryPromise({
1732 + try: () => created.close(),
1733 + catch: (cause) => new MuseSdkError({ operation: "close", cause }),
1734 + });
1735 // SDK shutdown sends SIGKILL after 10s + 2s, but inherited pipes can
1736 // keep its close promise pending. Let the scope reap those holders.
1737 yield* (
@@ -2258,10 +2265,10 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
2265 Effect.gen(function* () {
2266 if (active !== turn) return;
2267 hostEpoch++;
2261 - yield* Effect.tryPromise(() => host.close()).pipe(
2262 - Effect.mapError((cause) => protocolError("Cannot stop Muse compaction", cause)),
2263 - Effect.onError(failHost),
2264 - );
2268 + yield* Effect.tryPromise({
2269 + try: () => host.close(),
2270 + catch: (cause) => protocolError("Cannot stop Muse compaction", cause),
2271 + }).pipe(Effect.onError(failHost));
2272 broken = true;
2273 yield* finish(turn, "interrupted", undefined, "broken");
2274 yield* settleObservedChildren("interrupted");
packages/provider-muse/src/server/modelCatalog.ts
+10 -2
@@ -4,7 +4,12 @@ import { MuseSettings } from "../settings.ts";
4 import { createModelCapabilities, getProviderOptionDescriptors } from "@t3tools/shared/model";
5 import * as Effect from "effect/Effect";
6 import * as Schema from "effect/Schema";
7 -import { createMuseSdkHost, createMuseSdkHostEffect, type MuseSdkHost } from "./sdk.ts";
7 +import {
8 + createMuseSdkHost,
9 + createMuseSdkHostEffect,
10 + MuseSdkError,
11 + type MuseSdkHost,
12 +} from "./sdk.ts";
13
14 type MuseReasoningEffort = NonNullable<SendUserTurnOptions<never>["reasoningEffort"]>;
15
@@ -113,7 +118,10 @@ export const discoverMuseModels = Effect.fn("discoverMuseModels")(function* (
118 (host: MuseSdkHost) => Effect.promise(() => host.close()),
119 { interruptible: true },
120 );
116 - const result = yield* Effect.tryPromise(() => host.connection.request("model/list", {}));
121 + const result = yield* Effect.tryPromise({
122 + try: () => host.connection.request("model/list", {}),
123 + catch: (cause) => new MuseSdkError({ operation: "model/list", cause }),
124 + });
125 const catalog = yield* decodeModelList(result);
126 if (catalog.providerId !== "meta") {
127 return yield* new MuseCatalogError({ detail: "Muse returned a catalog for another provider." });
packages/provider-muse/src/server/sdk.ts
+24 -7
@@ -13,6 +13,16 @@ import type { RuntimeMode } from "@t3tools/contracts";
13 import * as HostProcess from "@t3tools/shared/HostProcess";
14 import { SpawnExecutableResolution } from "@t3tools/shared/shell";
15 import * as Effect from "effect/Effect";
16 +import * as Schema from "effect/Schema";
17 +
18 +export class MuseSdkError extends Schema.TaggedError<MuseSdkError>()("MuseSdkError", {
19 + operation: Schema.String,
20 + cause: Schema.Defect(),
21 +}) {
22 + override get message(): string {
23 + return `Muse SDK ${this.operation} failed.`;
24 + }
25 +}
26
27 export interface MuseSdkHost {
28 readonly connection: Pick<
@@ -72,15 +82,19 @@ export function museVerbatimPath(path: string): string {
82
83 // Native realpath corrects filesystem case as well as resolving symlinks.
84 export const museCanonicalPath = Effect.fn("museCanonicalPath")(function* (path: string) {
75 - return yield* Effect.tryPromise(() => NodeFSP.realpath(path)).pipe(
76 - Effect.orElseSucceed(() => path),
77 - );
85 + return yield* Effect.tryPromise({
86 + try: () => NodeFSP.realpath(path),
87 + catch: (cause) => new MuseSdkError({ operation: "realpath", cause }),
88 + }).pipe(Effect.orElseSucceed(() => path));
89 });
90
91 // Windows turn roots need verbatim form; launch cmd.exe with the plain canonical path.
92 export const museWorkspaceRoot = Effect.fn("museWorkspaceRoot")(function* (path: string) {
93 if ((yield* HostProcess.Platform) !== "win32") return yield* museCanonicalPath(path);
83 - const canonical = yield* Effect.tryPromise(() => NodeFSP.realpath(path)).pipe(
94 + const canonical = yield* Effect.tryPromise({
95 + try: () => NodeFSP.realpath(path),
96 + catch: (cause) => new MuseSdkError({ operation: "realpath", cause }),
97 + }).pipe(
98 // A verbatim path takes `/` literally, so an unresolved root needs Windows separators.
99 Effect.orElseSucceed(() => path.replaceAll("/", "\\")),
100 );
@@ -214,9 +228,12 @@ export const createMuseSdkHostEffect = Effect.fn("createMuseSdkHostEffect")(func
228 ) {
229 const launch = options.launch ?? (yield* museLaunch(options.binaryPath, options.environment));
230 let startup: Promise<MuseSdkHost> | undefined;
217 - return yield* Effect.tryPromise((signal) => {
218 - startup = createHost({ ...options, launch, signal });
219 - return startup;
231 + return yield* Effect.tryPromise({
232 + try: (signal) => {
233 + startup = createHost({ ...options, launch, signal });
234 + return startup;
235 + },
236 + catch: (cause) => new MuseSdkError({ operation: "start", cause }),
237 }).pipe(
238 Effect.onInterrupt(() =>
239 Effect.promise(async () => {
packages/provider-muse/src/server/textGeneration.ts
+18 -11
@@ -14,7 +14,12 @@ import * as FileSystem from "effect/FileSystem";
14 import * as Option from "effect/Option";
15 import * as Schema from "effect/Schema";
16
17 -import { createMuseSdkHost, createMuseSdkHostEffect, type MuseSdkHost } from "./sdk.ts";
17 +import {
18 + createMuseSdkHost,
19 + createMuseSdkHostEffect,
20 + MuseSdkError,
21 + type MuseSdkHost,
22 +} from "./sdk.ts";
23 import { museModelCapabilities, resolveMuseReasoningEffort } from "./modelCatalog.ts";
24 import type { ProviderTextGeneration } from "@t3tools/provider-core/server/textGeneration";
25 import { investigationUnsupported } from "@t3tools/provider-core/server/textGenerationOperations";
@@ -250,16 +255,18 @@ export const makeMuseTextGeneration = Effect.fn("makeMuseTextGeneration")(functi
255 (host: MuseSdkHost) => Effect.promise(() => host.close()),
256 { interruptible: true },
257 );
253 - return yield* Effect.tryPromise((signal) =>
254 - generateMuseText(
255 - host,
256 - cwd,
257 - `${input.prompt}\n\nReturn only a JSON object matching this schema, with no markdown fences. Do not use tools or ask questions.\n${jsonSchema}`,
258 - modelId,
259 - reasoningEffort,
260 - signal,
261 - ),
262 - );
258 + return yield* Effect.tryPromise({
259 + try: (signal) =>
260 + generateMuseText(
261 + host,
262 + cwd,
263 + `${input.prompt}\n\nReturn only a JSON object matching this schema, with no markdown fences. Do not use tools or ask questions.\n${jsonSchema}`,
264 + modelId,
265 + reasoningEffort,
266 + signal,
267 + ),
268 + catch: (cause) => new MuseSdkError({ operation: "generate text", cause }),
269 + });
270 }).pipe(
271 Effect.scoped,
272 Effect.mapError(
packages/provider-muse/src/server/usage.test.ts
+10 -8
@@ -236,11 +236,13 @@ describe("Muse history discovery", () => {
236
237 it.effect("does not guess a directory when initialization fails", () =>
238 Effect.gen(function* () {
239 - using _create = vi.spyOn(MuseSdk, "createMuseSdkHostEffect").mockReturnValue(
240 - Effect.try(() => {
241 - throw new Error("not installed");
242 - }),
243 - );
239 + using _create = vi
240 + .spyOn(MuseSdk, "createMuseSdkHostEffect")
241 + .mockReturnValue(
242 + Effect.fail(
243 + new MuseSdk.MuseSdkError({ operation: "start", cause: new Error("not installed") }),
244 + ),
245 + );
246 if (museUsageReader.kind !== "transcripts") throw new Error("Expected a transcript reader");
247 const directories = yield* museUsageReader.directories({
248 instanceId: ProviderInstanceId.make("muse"),
@@ -381,9 +383,9 @@ describe("Muse history discovery", () => {
383 using create = vi
384 .spyOn(MuseSdk, "createMuseSdkHostEffect")
385 .mockReturnValueOnce(
384 - Effect.try(() => {
385 - throw new Error("not installed");
386 - }),
386 + Effect.fail(
387 + new MuseSdk.MuseSdkError({ operation: "start", cause: new Error("not installed") }),
388 + ),
389 )
390 .mockReturnValue(
391 Effect.succeed({
packages/provider-opencode/src/server/usageLimits.ts
+36 -24
@@ -43,32 +43,44 @@ const UsageResponse = Schema.Struct({
43
44 // Select before decoding so an OAuth or self-hosted connection cannot fall
45 // through to another stored account. NULL-active rows predate the selection flag.
46 +class OpenCodeCredentialReadError extends Schema.TaggedError<OpenCodeCredentialReadError>()(
47 + "OpenCodeCredentialReadError",
48 + { databasePath: Schema.String, cause: Schema.Defect() },
49 +) {
50 + override get message(): string {
51 + return `Could not read OpenCode credentials from ${this.databasePath}.`;
52 + }
53 +}
54 +
55 const readStoredApiKey = (databasePath: string, integrationId: "opencode" | "opencode-go") =>
47 - Effect.try(() => {
48 - const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });
49 - try {
50 - database.exec("PRAGMA busy_timeout = 100");
51 - const row = database
52 - .prepare(
53 - `SELECT value FROM credential
54 - WHERE integration_id = ? AND active IS NOT 0
55 - ORDER BY active DESC, time_created DESC, id DESC LIMIT 1`,
56 - )
57 - .get(integrationId);
58 - const stored =
59 - typeof row?.value === "string"
60 - ? Option.getOrUndefined(decodeStoredKey(row.value))
61 - : undefined;
62 - const server = stored?.metadata?.server;
63 - if (typeof server === "string") {
64 - const url = new URL(server);
65 - if (`${url.origin}${url.pathname.replace(/\/+$/, "")}` !== "https://opencode.ai/console")
66 - return undefined;
56 + Effect.try({
57 + try: () => {
58 + const database = new NodeSqlite.DatabaseSync(databasePath, { readOnly: true });
59 + try {
60 + database.exec("PRAGMA busy_timeout = 100");
61 + const row = database
62 + .prepare(
63 + `SELECT value FROM credential
64 + WHERE integration_id = ? AND active IS NOT 0
65 + ORDER BY active DESC, time_created DESC, id DESC LIMIT 1`,
66 + )
67 + .get(integrationId);
68 + const stored =
69 + typeof row?.value === "string"
70 + ? Option.getOrUndefined(decodeStoredKey(row.value))
71 + : undefined;
72 + const server = stored?.metadata?.server;
73 + if (typeof server === "string") {
74 + const url = new URL(server);
75 + if (`${url.origin}${url.pathname.replace(/\/+$/, "")}` !== "https://opencode.ai/console")
76 + return undefined;
77 + }
78 + return stored?.key.trim();
79 + } finally {
80 + database.close();
81 }
68 - return stored?.key.trim();
69 - } finally {
70 - database.close();
71 - }
82 + },
83 + catch: (cause) => new OpenCodeCredentialReadError({ databasePath, cause }),
84 }).pipe(Effect.orElseSucceed(() => undefined));
85
86 /** External OpenCode servers own their credentials; never read the host's account for them. */
packages/shared/src/HostProcess.ts
+15 -3
@@ -1,5 +1,6 @@
1 import * as Context from "effect/Context";
2 import * as Effect from "effect/Effect";
3 +import * as Schema from "effect/Schema";
4 import * as NodeDns from "node:dns";
5 import * as NodeOS from "node:os";
6 import * as NodeSea from "node:sea";
@@ -73,6 +74,15 @@ export const IsExecutable = Context.Reference<boolean>("@t3tools/shared/HostProc
74 defaultValue: () => NodeSea.isSea(),
75 });
76
77 +export class HostnameLookupError extends Schema.TaggedError<HostnameLookupError>()(
78 + "HostnameLookupError",
79 + { hostname: Schema.String, cause: Schema.Defect() },
80 +) {
81 + override get message(): string {
82 + return `Could not resolve ${this.hostname}.`;
83 + }
84 +}
85 +
86 /** Includes hostname-resolved addresses absent from interfaces, such as Debian's 127.0.1.1 used by Firefox locks. */
87 export const Addresses = Context.Reference<Effect.Effect<ReadonlySet<string>>>(
88 "@t3tools/shared/HostProcess/Addresses",
@@ -82,9 +92,11 @@ export const Addresses = Context.Reference<Effect.Effect<ReadonlySet<string>>>(
92 const interfaces = Object.values(NodeOS.networkInterfaces())
93 .flat()
94 .flatMap((entry) => (entry ? [entry.address] : []));
85 - const resolved = yield* Effect.tryPromise(() =>
86 - NodeDns.promises.lookup(NodeOS.hostname(), { all: true }),
87 - ).pipe(
95 + const hostname = NodeOS.hostname();
96 + const resolved = yield* Effect.tryPromise({
97 + try: () => NodeDns.promises.lookup(hostname, { all: true }),
98 + catch: (cause) => new HostnameLookupError({ hostname, cause }),
99 + }).pipe(
100 Effect.map((entries) => entries.map((entry) => entry.address)),
101 Effect.orElseSucceed(() => [] as ReadonlyArray<string>),
102 );
packages/shared/src/nodeSqliteClient.ts
+3 -3
@@ -637,7 +637,7 @@ const startCheckpointWorker = Effect.fnUntraced(function* (
637 }
638 const frames = writer.prepare("PRAGMA wal_checkpoint(NOOP)");
639 const sizeLimit = writer.prepare("PRAGMA journal_size_limit");
640 - const started = yield* Effect.try(
640 + const started = Result.try(
641 () =>
642 new NodeWorkerThreads.Worker(checkpointWorkerSource, {
643 eval: true,
@@ -648,9 +648,9 @@ const startCheckpointWorker = Effect.fnUntraced(function* (
648 idleMs: CHECKPOINT_IDLE_MS,
649 },
650 }),
651 - ).pipe(Effect.result);
651 + );
652 if (Result.isFailure(started)) {
653 - yield* warn(String(started.failure.cause));
653 + yield* warn(String(started.failure));
654 return undefined;
655 }
656 const worker = started.success;
packages/shared/src/relayClient.ts
+14 -1
@@ -21,6 +21,7 @@ import * as Option from "effect/Option";
21 import * as Path from "effect/Path";
22 import type * as PlatformError from "effect/PlatformError";
23 import * as Schedule from "effect/Schedule";
24 +import * as Schema from "effect/Schema";
25 import * as Semaphore from "effect/Semaphore";
26 import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
27 import { ChildProcess, ChildProcessSpawner } from "effect/process";
@@ -56,6 +57,15 @@ export type RelayClientStatus =
57
58 export type AvailableRelayClient = Extract<RelayClientStatus, { readonly status: "available" }>;
59
60 +class RelayClientLockRemoveError extends Schema.TaggedError<RelayClientLockRemoveError>()(
61 + "RelayClientLockRemoveError",
62 + { lockPath: Schema.String, cause: Schema.Defect() },
63 +) {
64 + override get message(): string {
65 + return `Could not remove the relay client lock ${this.lockPath}.`;
66 + }
67 +}
68 +
69 export class RelayClientInstallError extends Data.TaggedError("RelayClientInstallError")<{
70 readonly reason:
71 | "download_failed"
@@ -486,7 +496,10 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function
496 });
497
498 const removeEmptyLock = (lockPath: string) =>
489 - Effect.tryPromise(() => NodeFSP.rmdir(lockPath)).pipe(Effect.ignore);
499 + Effect.tryPromise({
500 + try: () => NodeFSP.rmdir(lockPath),
501 + catch: (cause) => new RelayClientLockRemoveError({ lockPath, cause }),
502 + }).pipe(Effect.ignore);
503
504 const releaseOwnedLock = Effect.fn("cloudflared.releaseOwnedLock")(function* (
505 lockPath: string,
packages/shared/src/shell.test.ts
+4 -4
@@ -341,7 +341,7 @@ describe("readEnvironmentFromWindowsShell", () => {
341
342 expect(
343 yield* readEnvironmentFromWindowsShell(["PATH"], {}, (...args) =>
344 - Effect.try(() => execFile(...args)).pipe(Effect.option),
344 + Effect.sync(() => Option.liftThrowable(execFile)(...args)),
345 ),
346 ).toEqual({
347 PATH: "C:\\Users\\testuser\\AppData\\Roaming\\npm",
@@ -369,7 +369,7 @@ describe("readEnvironmentFromWindowsShell", () => {
369
370 expect(
371 yield* readEnvironmentFromWindowsShell(["FNM_DIR"], {}, (...args) =>
372 - Effect.try(() => execFile(...args)).pipe(Effect.option),
372 + Effect.sync(() => Option.liftThrowable(execFile)(...args)),
373 ),
374 ).toEqual({
375 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
@@ -389,7 +389,7 @@ describe("readEnvironmentFromWindowsShell", () => {
389
390 expect(
391 yield* readEnvironmentFromWindowsShell(["PATH"], { loadProfile: true }, (...args) =>
392 - Effect.try(() => execFile(...args)).pipe(Effect.option),
392 + Effect.sync(() => Option.liftThrowable(execFile)(...args)),
393 ),
394 ).toEqual({
395 PATH: "C:\\Tools",
@@ -420,7 +420,7 @@ describe("readEnvironmentFromWindowsShell", () => {
420
421 expect(
422 yield* readEnvironmentFromWindowsShell(["PATH"], {}, (...args) =>
423 - Effect.try(() => execFile(...args)).pipe(Effect.option),
423 + Effect.sync(() => Option.liftThrowable(execFile)(...args)),
424 ),
425 ).toEqual({
426 PATH: "C:\\Tools",
scripts/build-cli-archive.ts
+13 -1
@@ -62,6 +62,15 @@ const RepoRoot = Effect.service(Path.Path).pipe(
62 Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
63 );
64
65 +export class CliArchiveLinuxArm64PageError extends Schema.TaggedError<CliArchiveLinuxArm64PageError>()(
66 + "CliArchiveLinuxArm64PageError",
67 + { executablePath: Schema.String, cause: Schema.Defect() },
68 +) {
69 + override get message(): string {
70 + return `${this.executablePath} is not page-compatible with Linux arm64.`;
71 + }
72 +}
73 +
74 export class CliArchiveCommandFailedError extends Schema.TaggedError<CliArchiveCommandFailedError>()(
75 "CliArchiveCommandFailedError",
76 { command: Schema.String, exitCode: Schema.Int },
@@ -537,7 +546,10 @@ const buildCliArchive = Effect.fn("buildCliArchive")(function* (input: {
546 // TEMPORARY one-time Node fix. Remove when fixed: https://github.com/nodejs/node/issues/67048
547 if (input.platform === "linux" && input.arch === "arm64") {
548 const bytes = yield* fs.readFile(executablePath);
540 - yield* Effect.try(() => assertLinuxArm64PageCompatibility(bytes));
549 + yield* Effect.try({
550 + try: () => assertLinuxArm64PageCompatibility(bytes),
551 + catch: (cause) => new CliArchiveLinuxArm64PageError({ executablePath, cause }),
552 + });
553 }
554 if (input.platform === "mac") {
555 yield* signMacArchiveContents({ repoRoot, contentDir, executablePath });
scripts/build-desktop-artifact.ts
+25 -15
@@ -685,6 +685,15 @@ export class DesktopBuildDistDirectoryMissingError extends Schema.TaggedError<De
685 }
686 }
687
688 +export class DesktopBuildArtifactCopyError extends Schema.TaggedError<DesktopBuildArtifactCopyError>()(
689 + "DesktopBuildArtifactCopyError",
690 + { from: Schema.String, to: Schema.String, cause: Schema.Defect() },
691 +) {
692 + override get message(): string {
693 + return `Failed to copy build artifact ${this.from} to ${this.to}.`;
694 + }
695 +}
696 +
697 export class DesktopBuildNoArtifactsProducedError extends Schema.TaggedError<DesktopBuildNoArtifactsProducedError>()(
698 "DesktopBuildNoArtifactsProducedError",
699 {
@@ -2095,7 +2104,7 @@ const NativeMarkerManifest = Schema.Struct({
2104 dependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
2105 optionalDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
2106 });
2098 -const decodeNativeMarkerManifest = Schema.decodeUnknownSync(
2107 +const decodeNativeMarkerManifest = Schema.decodeUnknownOption(
2108 Schema.fromJsonString(NativeMarkerManifest),
2109 );
2110
@@ -2135,13 +2144,12 @@ const hasNativeLoaderMarkers = Effect.fn("hasNativeLoaderMarkers")(function* (pa
2144 if (!(yield* exists(manifestPath))) return false;
2145 const source = yield* fs.readFileString(manifestPath).pipe(Effect.orElseSucceed(() => ""));
2146 if (source === "") return false;
2138 - const manifest = yield* Effect.try(() => decodeNativeMarkerManifest(source)).pipe(
2139 - Effect.orElseSucceed(() => null),
2140 - );
2141 - if (manifest === null) return false;
2142 - return Object.keys({ ...manifest.dependencies, ...manifest.optionalDependencies }).some(
2143 - (dependency) => dependency.startsWith("node-gyp-build"),
2144 - );
2147 + const manifest = decodeNativeMarkerManifest(source);
2148 + if (Option.isNone(manifest)) return false;
2149 + return Object.keys({
2150 + ...manifest.value.dependencies,
2151 + ...manifest.value.optionalDependencies,
2152 + }).some((dependency) => dependency.startsWith("node-gyp-build"));
2153 });
2154
2155 export const copyDirectoryPreservingSymlinks = Effect.fn("copyDirectoryPreservingSymlinks")(
@@ -4107,13 +4115,15 @@ export const copyDesktopBuildArtifacts = Effect.fn("copyDesktopBuildArtifacts")(
4115 // overwrite a directory with a file or a file with a directory, and only merges into
4116 // an existing directory, so a stale entry of either type must go first.
4117 yield* fs.remove(to, { recursive: true, force: true });
4110 - yield* Effect.tryPromise(() =>
4111 - NodeFSP.cp(from, to, {
4112 - recursive: true,
4113 - force: true,
4114 - verbatimSymlinks: true,
4115 - }),
4116 - );
4118 + yield* Effect.tryPromise({
4119 + try: () =>
4120 + NodeFSP.cp(from, to, {
4121 + recursive: true,
4122 + force: true,
4123 + verbatimSymlinks: true,
4124 + }),
4125 + catch: (cause) => new DesktopBuildArtifactCopyError({ from, to, cause }),
4126 + });
4127 copiedArtifacts.push(to);
4128 }
4129
tsconfig.effect.json
+1
@@ -96,6 +96,7 @@
96 "timeoutCatchTagToTimeoutOrElse": "error",
97 "unnecessaryPipe": "error",
98 "unnecessaryTypeofType": "error",
99 + "effectTryWithoutCatch": "error",
100 "processEnvInEffect": "error",
101 "schemaNumber": "off"
102 },