diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts
index bf0d7b85df..0c92f96543 100644
--- a/apps/server/src/orchestration/projector.ts
+++ b/apps/server/src/orchestration/projector.ts
@@ -47,15 +47,14 @@ function updateThread(
}
function decodeForEvent(
- schema: Schema.Schema,
+ schema: Schema.Decoder,
value: unknown,
eventType: OrchestrationEvent["type"],
field: string,
): Effect.Effect {
- return Effect.try({
- try: () => Schema.decodeUnknownSync(schema as any)(value),
- catch: (error) => toProjectorDecodeError(`${eventType}:${field}`)(error as Schema.SchemaError),
- });
+ return Schema.decodeUnknownEffect(schema)(value).pipe(
+ Effect.mapError(toProjectorDecodeError(`${eventType}:${field}`)),
+ );
}
function retainThreadMessagesAfterRevert(
diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts
index 6b4ae4d83d..e9bd8fb7a1 100644
--- a/apps/server/src/provider/Layers/ClaudeAdapter.ts
+++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts
@@ -84,8 +84,8 @@ import {
} from "../Errors.ts";
import { type ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
-const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
-const decodeUnknownJsonString = Schema.decodeUnknownSync(Schema.UnknownFromJsonString);
+const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.UnknownFromJsonString);
+const decodeUnknownJsonStringExit = Schema.decodeUnknownExit(Schema.UnknownFromJsonString);
const PROVIDER = ProviderDriverKind.make("claudeAgent");
type ClaudeTextStreamKind = Extract;
@@ -95,6 +95,11 @@ type ClaudeToolResultStreamKind = Extract<
>;
type ClaudeSdkEffort = NonNullable;
+function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
+ const result = encodeUnknownJsonStringExit(input);
+ return Exit.isSuccess(result) ? result.value : undefined;
+}
+
type PromptQueueItem =
| {
readonly type: "message";
@@ -547,7 +552,7 @@ function summarizeToolRequest(toolName: string, input: Record):
}
}
- const serialized = encodeUnknownJsonString(input);
+ const serialized = encodeJsonStringForDiagnostics(input) ?? "[unserializable input]";
if (serialized.length <= 400) {
return `${toolName}: ${serialized}`;
}
@@ -812,22 +817,18 @@ function exitPlanCaptureKey(input: {
}
function tryParseJsonRecord(value: string): Record | undefined {
- try {
- const parsed = decodeUnknownJsonString(value);
- return parsed && typeof parsed === "object" && !Array.isArray(parsed)
- ? (parsed as Record)
- : undefined;
- } catch {
+ const result = decodeUnknownJsonStringExit(value);
+ if (!Exit.isSuccess(result)) {
return undefined;
}
+ const parsed = result.value;
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
+ ? (parsed as Record)
+ : undefined;
}
function toolInputFingerprint(input: Record): string | undefined {
- try {
- return encodeUnknownJsonString(input);
- } catch {
- return undefined;
- }
+ return encodeJsonStringForDiagnostics(input);
}
function toolResultStreamKind(itemType: CanonicalItemType): ClaudeToolResultStreamKind | undefined {
@@ -2943,8 +2944,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
"claude.query.include_partial_messages": true,
"claude.query.additional_directories": input.cwd ? [input.cwd] : [],
"claude.query.setting_sources": [...CLAUDE_SETTING_SOURCES],
- "claude.query.settings_json": encodeUnknownJsonString(settings),
- "claude.query.extra_args_json": encodeUnknownJsonString(extraArgs),
+ "claude.query.settings_json": encodeJsonStringForDiagnostics(settings) ?? "",
+ "claude.query.extra_args_json": encodeJsonStringForDiagnostics(extraArgs) ?? "",
"claude.query.path_to_executable": claudeBinaryPath,
});
diff --git a/apps/server/src/provider/Layers/CursorAdapter.ts b/apps/server/src/provider/Layers/CursorAdapter.ts
index 471f90f802..efef5f0a83 100644
--- a/apps/server/src/provider/Layers/CursorAdapter.ts
+++ b/apps/server/src/provider/Layers/CursorAdapter.ts
@@ -75,7 +75,7 @@ import {
import { type CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { resolveCursorAcpBaseModelId } from "./CursorProvider.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
-const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
+const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.UnknownFromJsonString);
const PROVIDER = ProviderDriverKind.make("cursor");
const CURSOR_RESUME_VERSION = 1 as const;
@@ -83,6 +83,11 @@ const ACP_PLAN_MODE_ALIASES = ["plan", "architect"];
const ACP_IMPLEMENT_MODE_ALIASES = ["code", "agent", "default", "chat", "implement"];
const ACP_APPROVAL_MODE_ALIASES = ["ask"];
+function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
+ const result = encodeUnknownJsonStringExit(input);
+ return Exit.isSuccess(result) ? result.value : undefined;
+}
+
export interface CursorAdapterLiveOptions {
readonly environment?: NodeJS.ProcessEnv;
readonly nativeEventLogPath?: string;
@@ -391,7 +396,7 @@ export function makeCursorAdapter(
method: string,
) =>
Effect.gen(function* () {
- const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${encodeUnknownJsonString(payload)}`;
+ const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
if (ctx.lastPlanFingerprint === fingerprint) {
return;
}
@@ -640,7 +645,9 @@ export function makeCursorAdapter(
requestId: runtimeRequestId,
permissionRequest,
detail:
- permissionRequest.detail ?? encodeUnknownJsonString(params).slice(0, 2000),
+ permissionRequest.detail ??
+ encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??
+ "[unserializable params]",
args: params,
source: "acp.jsonrpc",
method: "session/request_permission",
diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts
index 36313b68ed..8652b2cfea 100644
--- a/apps/server/src/provider/acp/AcpSessionRuntime.ts
+++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts
@@ -7,7 +7,6 @@ import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
import * as Context from "effect/Context";
-import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as EffectAcpClient from "effect-acp/client";
@@ -26,7 +25,10 @@ import {
type AcpSessionModeState,
type AcpToolCallState,
} from "./AcpRuntimeModel.ts";
-const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
+
+function formatConfigOptionValue(value: string | boolean): string {
+ return JSON.stringify(value);
+}
export interface AcpSpawnInput {
readonly command: string;
@@ -278,7 +280,7 @@ const makeAcpSessionRuntime = (
}
return yield* new EffectAcpErrors.AcpRequestError({
code: -32602,
- errorMessage: `Invalid value ${encodeUnknownJsonString(value)} for session config option "${configOption.id}": expected boolean`,
+ errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected boolean`,
data: {
configId: configOption.id,
expectedType: "boolean",
@@ -289,7 +291,7 @@ const makeAcpSessionRuntime = (
if (typeof value !== "string") {
return yield* new EffectAcpErrors.AcpRequestError({
code: -32602,
- errorMessage: `Invalid value ${encodeUnknownJsonString(value)} for session config option "${configOption.id}": expected string`,
+ errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected string`,
data: {
configId: configOption.id,
expectedType: "string",
@@ -303,7 +305,7 @@ const makeAcpSessionRuntime = (
}
return yield* new EffectAcpErrors.AcpRequestError({
code: -32602,
- errorMessage: `Invalid value ${encodeUnknownJsonString(value)} for session config option "${configOption.id}": expected one of ${allowedValues.join(", ")}`,
+ errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option "${configOption.id}": expected one of ${allowedValues.join(", ")}`,
data: {
configId: configOption.id,
allowedValues,
diff --git a/apps/server/src/provider/opencodeRuntime.ts b/apps/server/src/provider/opencodeRuntime.ts
index a966fe94f9..ddeb9f2643 100644
--- a/apps/server/src/provider/opencodeRuntime.ts
+++ b/apps/server/src/provider/opencodeRuntime.ts
@@ -31,7 +31,8 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { isWindowsCommandNotFound } from "../processRunner.ts";
import { collectStreamAsString } from "./providerSnapshot.ts";
import * as NetService from "@t3tools/shared/Net";
-const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
+const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.UnknownFromJsonString);
+const OPENCODE_EMPTY_CONFIG_CONTENT = "{}";
const OPENCODE_SERVER_READY_PREFIX = "opencode server listening";
const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 5_000;
@@ -57,6 +58,11 @@ export class OpenCodeRuntimeError extends Data.TaggedError(OPENCODE_RUNTIME_ERRO
P.isTagged(u, OPENCODE_RUNTIME_ERROR_TAG);
}
+function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
+ const result = encodeUnknownJsonStringExit(input);
+ return Exit.isSuccess(result) ? result.value : undefined;
+}
+
export function openCodeRuntimeErrorDetail(cause: unknown): string {
if (OpenCodeRuntimeError.is(cause)) return cause.detail;
if (cause instanceof Error && cause.message.trim().length > 0) return cause.message.trim();
@@ -65,10 +71,9 @@ export function openCodeRuntimeErrorDetail(cause: unknown): string {
const anyCause = cause as Record;
const status = (anyCause.response as { status?: number } | undefined)?.status;
const body = anyCause.error ?? anyCause.data ?? anyCause.body;
- try {
- return `status=${status ?? "?"} body=${encodeUnknownJsonString(body ?? cause)}`;
- } catch {
- /* fall through */
+ const encodedBody = encodeJsonStringForDiagnostics(body ?? cause);
+ if (encodedBody) {
+ return `status=${status ?? "?"} body=${encodedBody}`;
}
}
return String(cause);
@@ -337,7 +342,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
shell: process.platform === "win32",
env: {
...(input.environment ?? process.env),
- OPENCODE_CONFIG_CONTENT: encodeUnknownJsonString({}),
+ OPENCODE_CONFIG_CONTENT: OPENCODE_EMPTY_CONFIG_CONTENT,
},
}),
)
diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.ts
index 14d39ff930..3c1e8c6967 100644
--- a/apps/server/src/textGeneration/ClaudeTextGeneration.ts
+++ b/apps/server/src/textGeneration/ClaudeTextGeneration.ts
@@ -53,7 +53,7 @@ const ClaudeOutputEnvelope = Schema.Struct({
structured_output: Schema.Unknown,
});
-const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
+const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString);
const decodeClaudeOutputEnvelope = Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope));
export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(function* (
@@ -78,6 +78,26 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
),
);
+ const encodeJsonForOperation = (
+ operation:
+ | "generateCommitMessage"
+ | "generatePrContent"
+ | "generateBranchName"
+ | "generateThreadTitle",
+ value: unknown,
+ detail: string,
+ ): Effect.Effect =>
+ encodeJsonString(value).pipe(
+ Effect.mapError(
+ (cause) =>
+ new TextGenerationError({
+ operation,
+ detail,
+ cause,
+ }),
+ ),
+ );
+
/**
* Spawn the Claude CLI with structured JSON output and return the parsed,
* schema-validated result.
@@ -99,7 +119,11 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
outputSchemaJson: S;
modelSelection: ModelSelection;
}): Effect.fn.Return {
- const jsonSchemaStr = encodeUnknownJsonString(toJsonSchemaObject(outputSchemaJson));
+ const jsonSchemaStr = yield* encodeJsonForOperation(
+ operation,
+ toJsonSchemaObject(outputSchemaJson),
+ "Failed to encode structured output schema.",
+ );
const caps = getClaudeModelCapabilities(modelSelection.model);
const descriptors = getProviderOptionDescriptors({
caps,
@@ -119,6 +143,14 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
...(fastMode ? { fastMode: true } : {}),
};
+ const settingsJson =
+ Object.keys(settings).length > 0
+ ? yield* encodeJsonForOperation(
+ operation,
+ settings,
+ "Failed to encode Claude CLI settings.",
+ )
+ : undefined;
const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
const command = ChildProcess.make(
@@ -132,9 +164,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
"--model",
resolveClaudeApiModelId(modelSelection),
...(cliEffort ? ["--effort", cliEffort] : []),
- ...(Object.keys(settings).length > 0
- ? ["--settings", encodeUnknownJsonString(settings)]
- : []),
+ ...(settingsJson ? ["--settings", settingsJson] : []),
"--dangerously-skip-permissions",
],
{
diff --git a/apps/server/src/textGeneration/CodexTextGeneration.ts b/apps/server/src/textGeneration/CodexTextGeneration.ts
index a756b0e9c9..3d1637a7fc 100644
--- a/apps/server/src/textGeneration/CodexTextGeneration.ts
+++ b/apps/server/src/textGeneration/CodexTextGeneration.ts
@@ -40,7 +40,7 @@ import {
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
-const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
+const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString);
/**
* Build a Codex text-generation closure bound to a specific `CodexSettings`
* payload. See `makeCodexAdapter` for the overall per-instance rationale.
@@ -100,6 +100,25 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
const safeUnlink = (filePath: string): Effect.Effect =>
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
+ const encodeJsonForOperation = (
+ operation:
+ | "generateCommitMessage"
+ | "generatePrContent"
+ | "generateBranchName"
+ | "generateThreadTitle",
+ value: unknown,
+ ): Effect.Effect =>
+ encodeJsonString(value).pipe(
+ Effect.mapError(
+ (cause) =>
+ new TextGenerationError({
+ operation,
+ detail: "Failed to encode structured output schema.",
+ cause,
+ }),
+ ),
+ );
+
const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
_operation:
| "generateCommitMessage"
@@ -157,11 +176,11 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
cleanupPaths?: ReadonlyArray;
modelSelection: ModelSelection;
}): Effect.fn.Return {
- const schemaPath = yield* writeTempFile(
+ const schemaJson = yield* encodeJsonForOperation(
operation,
- "codex-schema",
- encodeUnknownJsonString(toJsonSchemaObject(outputSchemaJson)),
+ toJsonSchemaObject(outputSchemaJson),
);
+ const schemaPath = yield* writeTempFile(operation, "codex-schema", schemaJson);
const outputPath = yield* writeTempFile(operation, "codex-output", "");
const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
diff --git a/apps/web/src/components/settings/ProviderSettingsForm.tsx b/apps/web/src/components/settings/ProviderSettingsForm.tsx
index 07dbd8243b..83dc7d0688 100644
--- a/apps/web/src/components/settings/ProviderSettingsForm.tsx
+++ b/apps/web/src/components/settings/ProviderSettingsForm.tsx
@@ -1,6 +1,7 @@
"use client";
import { useMemo, type ReactNode } from "react";
+import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import type {
ProviderSettingsFormAnnotation,
@@ -63,13 +64,9 @@ function readProviderSettingsFormSchemaAnnotation(
function readFieldBooleanDefault(
fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
): boolean | undefined {
- try {
- const decodeDefault = Schema.decodeUnknownSync(fieldSchema as Schema.Decoder);
- const decoded = decodeDefault(undefined);
- return typeof decoded === "boolean" ? decoded : undefined;
- } catch {
- return undefined;
- }
+ const decodeDefault = Schema.decodeUnknownOption(fieldSchema as Schema.Decoder);
+ const decoded = decodeDefault(undefined);
+ return Option.isSome(decoded) && typeof decoded.value === "boolean" ? decoded.value : undefined;
}
export function deriveProviderSettingsFields(
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index fa0a741114..26a1a171cf 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -279,6 +279,7 @@ export const CursorSettings = makeProviderSettingsSchema(
},
);
export type CursorSettings = typeof CursorSettings.Type;
+
export const OpenCodeSettings = makeProviderSettingsSchema(
{
enabled: Schema.Boolean.pipe(
diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.ts
index f3cb277df4..6427129b3c 100644
--- a/packages/shared/src/serverSettings.ts
+++ b/packages/shared/src/serverSettings.ts
@@ -1,11 +1,12 @@
import { ServerSettings, type ServerSettingsPatch } from "@t3tools/contracts";
+import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { deepMerge } from "./Struct.ts";
import { fromLenientJson } from "./schemaJson.ts";
import { createModelSelection } from "./model.ts";
const ServerSettingsJson = fromLenientJson(ServerSettings);
-const decodeServerSettingsJson = Schema.decodeUnknownSync(ServerSettingsJson);
+const decodeServerSettingsJson = Schema.decodeUnknownOption(ServerSettingsJson);
export interface PersistedServerObservabilitySettings {
readonly otlpTracesUrl: string | undefined;
@@ -34,12 +35,11 @@ export function extractPersistedServerObservabilitySettings(input: {
export function parsePersistedServerObservabilitySettings(
raw: string,
): PersistedServerObservabilitySettings {
- try {
- const decoded = decodeServerSettingsJson(raw);
- return extractPersistedServerObservabilitySettings(decoded);
- } catch {
- return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
+ const decoded = decodeServerSettingsJson(raw);
+ if (Option.isSome(decoded)) {
+ return extractPersistedServerObservabilitySettings(decoded.value);
}
+ return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
}
function shouldReplaceTextGenerationModelSelection(
diff --git a/scripts/update-release-package-versions.ts b/scripts/update-release-package-versions.ts
index 498332cd3b..cebf434d0a 100644
--- a/scripts/update-release-package-versions.ts
+++ b/scripts/update-release-package-versions.ts
@@ -26,7 +26,7 @@ interface UpdateReleasePackageVersionsOptions {
const PackageJsonSchema = Schema.Record(Schema.String, Schema.Unknown);
const PackageJsonPrettyJson = fromJsonStringPretty(PackageJsonSchema);
const decodePackageJson = Schema.decodeUnknownEffect(PackageJsonPrettyJson);
-const encodePackageJson = Schema.encodeSync(PackageJsonPrettyJson);
+const encodePackageJson = Schema.encodeEffect(PackageJsonPrettyJson);
export const updateReleasePackageVersions = Effect.fn("updateReleasePackageVersions")(function* (
version: string,
@@ -44,7 +44,8 @@ export const updateReleasePackageVersions = Effect.fn("updateReleasePackageVersi
continue;
}
- yield* fs.writeFileString(filePath, `${encodePackageJson({ ...packageJson, version })}\n`);
+ const packageJsonString = yield* encodePackageJson({ ...packageJson, version });
+ yield* fs.writeFileString(filePath, `${packageJsonString}\n`);
changed = true;
}