Compare commits

...
Author SHA1 Message Date
Cursor Agent a4a2302607 refactor: extract encodeJsonStringForDiagnostics into @t3tools/shared/schemaJson
The identical helper function was duplicated across ClaudeAdapter.ts,
CursorAdapter.ts, and opencodeRuntime.ts. Consolidate into the shared
schemaJson module and import from there.
2026-05-08 18:57:39 +00:00
Julius Marmingeandcodex e9f549048b Fix release smoke workspace fixture
Co-authored-by: codex <[email protected]>
2026-05-08 11:45:46 -07:00
Julius Marmingeandcodex f0dc3c5ac9 Harden schema runtime decoding
Co-authored-by: codex <[email protected]>
2026-05-08 11:42:37 -07:00
Julius Marmingeandcodex 3dd82e21b0 Add t3code oxlint schema compile rule
Co-authored-by: codex <[email protected]>
2026-05-08 11:27:39 -07:00
Julius Marminge 06c2b010c6 Refine oxlint rule harness effect types
- Switch to explicit Effect module imports
- Encode Oxlint config with Schema
- Simplify test assertions and harness signatures
2026-05-08 11:01:45 -07:00
Julius Marmingeandcodex b9fad2305e Add oxlint rule for inline schema compilers
- Introduce a t3code oxlint plugin and wire it into repo linting

- Flag Effect Schema compiler calls inside function bodies

- Add fixture-based tests for valid and invalid cases

Co-authored-by: codex <[email protected]>
2026-05-08 10:51:20 -07:00
87 changed files with 1112 additions and 435 deletions

No files matched your search

+4 -1
View File
@@ -9,6 +9,7 @@
"**/routeTree.gen.ts"
],
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
"jsPlugins": ["./oxlint-plugin-t3code/index.ts"],
"categories": {
"correctness": "warn",
"suspicious": "warn",
@@ -17,6 +18,8 @@
"rules": {
"react-in-jsx-scope": "off",
"eslint/no-shadow": "off",
"eslint/no-await-in-loop": "off"
"eslint/no-await-in-loop": "off",
"eslint/no-underscore-dangle": "off",
"t3code/no-inline-schema-compile": "warn"
}
}
+2 -1
View File
@@ -16,6 +16,7 @@ const COMMIT_HASH_DISPLAY_LENGTH = 12;
const AppPackageMetadata = Schema.Struct({
t3codeCommitHash: Schema.optional(Schema.String),
});
const decodeAppPackageMetadata = Schema.decodeEffect(Schema.fromJsonString(AppPackageMetadata));
export interface DesktopAppIdentityShape {
readonly resolveUserDataPath: Effect.Effect<string>;
@@ -47,7 +48,7 @@ const make = Effect.gen(function* () {
return yield* Option.match(raw, {
onNone: () => Effect.succeed(Option.none<string>()),
onSome: (value) =>
Schema.decodeEffect(Schema.fromJsonString(AppPackageMetadata))(value).pipe(
decodeAppPackageMetadata(value).pipe(
Effect.map((parsed) =>
Option.fromNullishOr(parsed.t3codeCommitHash).pipe(Option.flatMap(normalizeCommitHash)),
),
@@ -25,6 +25,10 @@ import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
Schema.fromJsonString(DesktopBackendBootstrap),
);
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "/electron",
entryPath: "/server/bin.mjs",
@@ -94,7 +98,7 @@ const healthyHttpClientLayer = httpClientLayer((request) =>
);
function decodeBootstrap(raw: string) {
return Schema.decodeEffect(Schema.fromJsonString(DesktopBackendBootstrap))(raw);
return decodeDesktopBackendBootstrap(raw);
}
function makeManagerLayer(input: {
@@ -20,10 +20,14 @@ const ClientSettingsDocumentSchema = Schema.Struct({
const ClientSettingsJson = fromLenientJson(ClientSettingsSchema);
const LegacyClientSettingsDocumentJson = fromLenientJson(ClientSettingsDocumentSchema);
const decodeLegacyClientSettingsDocumentJson = Schema.decodeEffect(
LegacyClientSettingsDocumentJson,
);
const decodeClientSettingsJsonValue = Schema.decodeEffect(ClientSettingsJson);
const decodeClientSettingsJson = (raw: string): Effect.Effect<ClientSettings, Schema.SchemaError> =>
Schema.decodeEffect(LegacyClientSettingsDocumentJson)(raw).pipe(
decodeLegacyClientSettingsDocumentJson(raw).pipe(
Effect.map((document) => document.settings),
Effect.catch(() => Schema.decodeEffect(ClientSettingsJson)(raw)),
Effect.catch(() => decodeClientSettingsJsonValue(raw)),
);
const encodeClientSettingsJson = Schema.encodeEffect(ClientSettingsJson);
+7 -4
View File
@@ -54,6 +54,9 @@ const UpdateInfo = Schema.Struct({
const DownloadProgressInfo = Schema.Struct({
percent: Schema.Number,
});
const decodeAppUpdateYmlConfig = Schema.decodeUnknownEffect(AppUpdateYmlConfig);
const decodeUpdateInfo = Schema.decodeUnknownEffect(UpdateInfo);
const decodeDownloadProgressInfo = Schema.decodeUnknownEffect(DownloadProgressInfo);
const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
@@ -115,7 +118,7 @@ function parseAppUpdateYml(raw: string): Effect.Effect<Option.Option<AppUpdateYm
}
}
return Schema.decodeUnknownEffect(AppUpdateYmlConfig)(entries).pipe(
return decodeAppUpdateYmlConfig(entries).pipe(
Effect.map((config) => (config.provider ? Option.some(config) : Option.none())),
Effect.catch(() => Effect.succeed(Option.none<AppUpdateYmlConfig>())),
);
@@ -408,7 +411,7 @@ const make = Effect.gen(function* () {
const handleUpdateAvailable = Effect.fn("desktop.updates.handleUpdateAvailable")(function* (
raw: unknown,
) {
yield* Schema.decodeUnknownEffect(UpdateInfo)(raw).pipe(
yield* decodeUpdateInfo(raw).pipe(
Effect.flatMap(
Effect.fn("desktop.updates.applyUpdateAvailable")(function* (info) {
const state = yield* Ref.get(updateStateRef);
@@ -479,7 +482,7 @@ const make = Effect.gen(function* () {
const handleDownloadProgress = Effect.fn("desktop.updates.handleDownloadProgress")(function* (
raw: unknown,
) {
yield* Schema.decodeUnknownEffect(DownloadProgressInfo)(raw).pipe(
yield* decodeDownloadProgressInfo(raw).pipe(
Effect.flatMap(
Effect.fn("desktop.updates.applyDownloadProgress")(function* (progress) {
const state = yield* Ref.get(updateStateRef);
@@ -506,7 +509,7 @@ const make = Effect.gen(function* () {
const handleUpdateDownloaded = Effect.fn("desktop.updates.handleUpdateDownloaded")(function* (
raw: unknown,
) {
yield* Schema.decodeUnknownEffect(UpdateInfo)(raw).pipe(
yield* decodeUpdateInfo(raw).pipe(
Effect.flatMap(
Effect.fn("desktop.updates.applyUpdateDownloaded")(function* (info) {
const state = yield* Ref.get(updateStateRef);
@@ -79,6 +79,8 @@ import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "../src/git/GitWorkflowService.ts";
import * as VcsProcess from "../src/vcs/VcsProcess.ts";
const decodeCodexSettings = Schema.decodeEffect(CodexSettings);
function runGit(cwd: string, args: ReadonlyArray<string>) {
return execFileSync("git", args, {
cwd,
@@ -266,7 +268,7 @@ export const makeOrchestrationIntegrationHarness = (
const realCodexRegistry = Layer.effect(
ProviderAdapterRegistry,
Effect.gen(function* () {
const codexSettings = Schema.decodeSync(CodexSettings)({});
const codexSettings = yield* decodeCodexSettings({});
const codexAdapter = yield* makeCodexAdapter(codexSettings);
return makeAdapterRegistryMock({
[ProviderDriverKind.make("codex")]: codexAdapter,
+3 -6
View File
@@ -38,6 +38,7 @@ vi.mock("node:fs", async (importOriginal) => {
});
const TestEnvelopeSchema = Schema.Struct({ mode: Schema.String });
const encodeTestEnvelopeSchema = Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema));
it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
it.effect("uses platform-specific fd paths", () =>
@@ -55,9 +56,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
yield* fs.writeFileString(
filePath,
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
mode: "desktop",
})}\n`,
`${yield* encodeTestEnvelopeSchema({ mode: "desktop" })}\n`,
);
const fd = yield* Effect.acquireRelease(
@@ -79,9 +78,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
yield* fs.writeFileString(
filePath,
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
mode: "desktop",
})}\n`,
`${yield* encodeTestEnvelopeSchema({ mode: "desktop" })}\n`,
);
// Open without acquireRelease: the direct-stream fallback uses autoClose: true,
@@ -50,6 +50,7 @@ class ProcessDiagnosticsError extends Schema.TaggedErrorClass<ProcessDiagnostics
cause: Schema.optional(Schema.Defect),
},
) {}
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
function toProcessDiagnosticsError(message: string, cause?: unknown): ProcessDiagnosticsError {
return new ProcessDiagnosticsError({
@@ -316,7 +317,7 @@ const runProcess = Effect.fn("runProcess")(
}),
),
Effect.mapError((cause) =>
Schema.is(ProcessDiagnosticsError)(cause)
isProcessDiagnosticsError(cause)
? cause
: toProcessDiagnosticsError(input.errorMessage, cause),
),
+10 -4
View File
@@ -23,6 +23,12 @@ import {
import { KeybindingsConfigError } from "@t3tools/contracts";
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
const encodeKeybindingsConfigJson = Schema.encodeEffect(KeybindingsConfigJson);
const decodeKeybindingsConfigJson = Schema.decodeUnknownEffect(KeybindingsConfigJson);
const encodeResolvedKeybindingFromConfig = Schema.encodeEffect(ResolvedKeybindingFromConfig);
const decodeResolvedKeybindingFromConfigExit = Schema.decodeUnknownExit(
ResolvedKeybindingFromConfig,
);
const makeKeybindingsLayer = () => {
return KeybindingsLive.pipe(
Layer.provideMerge(
@@ -45,7 +51,7 @@ const writeKeybindingsConfig = (configPath: string, rules: readonly KeybindingRu
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const encoded = yield* Schema.encodeEffect(KeybindingsConfigJson)(rules);
const encoded = yield* encodeKeybindingsConfigJson(rules);
yield* fileSystem.makeDirectory(path.dirname(configPath), { recursive: true });
yield* fileSystem.writeFileString(configPath, encoded);
});
@@ -54,7 +60,7 @@ const readKeybindingsConfig = (configPath: string) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const rawConfig = yield* fileSystem.readFileString(configPath);
return yield* Schema.decodeUnknownEffect(KeybindingsConfigJson)(rawConfig);
return yield* decodeKeybindingsConfigJson(rawConfig);
});
it.layer(NodeServices.layer)("keybindings", (it) => {
@@ -111,7 +117,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
it.effect("encodes resolved plus-key shortcuts", () =>
Effect.gen(function* () {
const encoded = yield* Schema.encodeEffect(ResolvedKeybindingFromConfig)({
const encoded = yield* encodeResolvedKeybindingFromConfig({
command: "terminal.toggle",
shortcut: {
key: "+",
@@ -157,7 +163,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
it.effect("formats invalid resolved keybinding rules with the custom message", () =>
Effect.sync(() => {
const result = Schema.decodeUnknownExit(ResolvedKeybindingFromConfig)({
const result = decodeResolvedKeybindingFromConfigExit({
key: "mod+shift+d+o",
command: "terminal.new",
});
+10 -6
View File
@@ -170,6 +170,10 @@ function encodeWhenAst(node: KeybindingWhenNode): string {
const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
const KeybindingsConfigPrettyJson = fromJsonStringPretty(KeybindingsConfig);
const decodeKeybindingRuleExit = Schema.decodeUnknownExit(KeybindingRule);
const decodeResolvedKeybindingFromConfigExit = Schema.decodeExit(ResolvedKeybindingFromConfig);
const decodeRawKeybindingsEntriesExit = Schema.decodeUnknownExit(RawKeybindingsEntries);
const encodeKeybindingsConfigPrettyJson = Schema.encodeEffect(KeybindingsConfigPrettyJson);
export interface KeybindingsConfigState {
readonly keybindings: ResolvedKeybindingsConfig;
@@ -344,7 +348,7 @@ const makeKeybindings = Effect.gen(function* () {
return yield* Effect.forEach(rawConfig, (entry) =>
Effect.gen(function* () {
const decodedRule = Schema.decodeUnknownExit(KeybindingRule)(entry);
const decodedRule = decodeKeybindingRuleExit(entry);
if (decodedRule._tag === "Failure") {
yield* Effect.logWarning("ignoring invalid keybinding entry", {
path: keybindingsConfigPath,
@@ -353,7 +357,7 @@ const makeKeybindings = Effect.gen(function* () {
});
return null;
}
const resolved = Schema.decodeExit(ResolvedKeybindingFromConfig)(decodedRule.value);
const resolved = decodeResolvedKeybindingFromConfigExit(decodedRule.value);
if (resolved._tag === "Failure") {
yield* Effect.logWarning("ignoring invalid keybinding entry", {
path: keybindingsConfigPath,
@@ -379,7 +383,7 @@ const makeKeybindings = Effect.gen(function* () {
}
const rawConfig = yield* readRawConfig;
const decodedEntries = Schema.decodeUnknownExit(RawKeybindingsEntries)(rawConfig);
const decodedEntries = decodeRawKeybindingsEntriesExit(rawConfig);
if (decodedEntries._tag === "Failure") {
const detail = `expected JSON array (${Cause.pretty(decodedEntries.cause)})`;
return {
@@ -391,7 +395,7 @@ const makeKeybindings = Effect.gen(function* () {
const keybindings: KeybindingRule[] = [];
const issues: ServerConfigIssue[] = [];
for (const [index, entry] of decodedEntries.value.entries()) {
const decodedRule = Schema.decodeUnknownExit(KeybindingRule)(entry);
const decodedRule = decodeKeybindingRuleExit(entry);
if (decodedRule._tag === "Failure") {
const detail = Cause.pretty(decodedRule.cause);
issues.push(invalidEntryIssue(index, detail));
@@ -404,7 +408,7 @@ const makeKeybindings = Effect.gen(function* () {
continue;
}
const resolvedRule = Schema.decodeExit(ResolvedKeybindingFromConfig)(decodedRule.value);
const resolvedRule = decodeResolvedKeybindingFromConfigExit(decodedRule.value);
if (resolvedRule._tag === "Failure") {
const detail = Cause.pretty(resolvedRule.cause);
issues.push(invalidEntryIssue(index, detail));
@@ -423,7 +427,7 @@ const makeKeybindings = Effect.gen(function* () {
});
const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
return Schema.encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe(
return encodeKeybindingsConfigPrettyJson(rules).pipe(
Effect.map((encoded) => `${encoded}\n`),
Effect.flatMap((encoded) =>
writeFileStringAtomically({
@@ -44,6 +44,10 @@ import {
OrchestrationEngineService,
type OrchestrationEngineShape,
} from "../Services/OrchestrationEngine.ts";
const isOrchestrationCommandPreviouslyRejectedError = Schema.is(
OrchestrationCommandPreviouslyRejectedError,
);
const isOrchestrationCommandInvariantError = Schema.is(OrchestrationCommandInvariantError);
interface CommandEnvelope {
command: OrchestrationCommand;
@@ -245,7 +249,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
}
const error = Cause.squash(exit.cause) as OrchestrationDispatchError;
if (!Schema.is(OrchestrationCommandPreviouslyRejectedError)(error)) {
if (!isOrchestrationCommandPreviouslyRejectedError(error)) {
yield* reconcileReadModelAfterDispatchFailure.pipe(
Effect.catch(() =>
Effect.logWarning(
@@ -259,7 +263,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
),
);
if (Schema.is(OrchestrationCommandInvariantError)(error)) {
if (isOrchestrationCommandInvariantError(error)) {
yield* commandReceiptRepository
.upsert({
commandId: envelope.command.commandId,
@@ -39,6 +39,8 @@ import {
import { ServerSettingsService } from "../../serverSettings.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "../../git/GitWorkflowService.ts";
const isProviderAdapterRequestError = Schema.is(ProviderAdapterRequestError);
const isProviderDriverKind = Schema.is(ProviderDriverKind);
type ProviderIntentEvent = Extract<
OrchestrationEvent,
@@ -118,7 +120,7 @@ function findProviderAdapterRequestError(
cause: Cause.Cause<ProviderServiceError>,
): ProviderAdapterRequestError | undefined {
const failReason = cause.reasons.find(Cause.isFailReason);
return Schema.is(ProviderAdapterRequestError)(failReason?.error) ? failReason.error : undefined;
return isProviderAdapterRequestError(failReason?.error) ? failReason.error : undefined;
}
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
@@ -233,7 +235,7 @@ const make = Effect.gen(function* () {
const formatFailureDetail = (cause: Cause.Cause<unknown>): string => {
const failReason = cause.reasons.find(Cause.isFailReason);
const providerError = Schema.is(ProviderAdapterRequestError)(failReason?.error)
const providerError = isProviderAdapterRequestError(failReason?.error)
? failReason.error
: undefined;
if (providerError) {
@@ -361,7 +363,7 @@ const make = Effect.gen(function* () {
),
);
const desiredDriverKind = desiredInfo.driverKind;
if (!Schema.is(ProviderDriverKind)(desiredDriverKind)) {
if (!isProviderDriverKind(desiredDriverKind)) {
return yield* new ProviderAdapterRequestError({
provider: providerErrorLabel(String(desiredDriverKind)),
method: "thread.turn.start",
+4 -5
View File
@@ -47,15 +47,14 @@ function updateThread(
}
function decodeForEvent<A>(
schema: Schema.Schema<A>,
schema: Schema.Decoder<A, never>,
value: unknown,
eventType: OrchestrationEvent["type"],
field: string,
): Effect.Effect<A, OrchestrationProjectorDecodeError> {
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(
+3 -1
View File
@@ -30,6 +30,8 @@ export class PersistenceDecodeError extends Schema.TaggedErrorClass<PersistenceD
return `Decode error in ${this.operation}: ${this.issue}`;
}
}
const isPersistenceSqlError = Schema.is(PersistenceSqlError);
const isPersistenceDecodeError = Schema.is(PersistenceDecodeError);
export function toPersistenceSqlError(operation: string) {
return (cause: unknown): PersistenceSqlError =>
@@ -59,7 +61,7 @@ export function toPersistenceDecodeCauseError(operation: string) {
}
export const isPersistenceError = (u: unknown) =>
Schema.is(PersistenceSqlError)(u) || Schema.is(PersistenceDecodeError)(u);
isPersistenceSqlError(u) || isPersistenceDecodeError(u);
// ===============================
// Provider Session Repository Errors
@@ -10,6 +10,7 @@ import { PersistenceDecodeError } from "../Errors.ts";
import { OrchestrationEventStore } from "../Services/OrchestrationEventStore.ts";
import { OrchestrationEventStoreLive } from "./OrchestrationEventStore.ts";
import { SqlitePersistenceMemory } from "./Sqlite.ts";
const isPersistenceDecodeError = Schema.is(PersistenceDecodeError);
const layer = it.layer(
OrchestrationEventStoreLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
@@ -110,7 +111,7 @@ layer("OrchestrationEventStore", (it) => {
);
assert.equal(replayResult._tag, "Failure");
if (replayResult._tag === "Failure") {
assert.ok(Schema.is(PersistenceDecodeError)(replayResult.failure));
assert.ok(isPersistenceDecodeError(replayResult.failure));
assert.ok(
replayResult.failure.operation.includes(
"OrchestrationEventStore.readFromSequence:decodeRows",
@@ -48,6 +48,7 @@ import {
resolveProviderMaintenanceCapabilitiesEffect,
} from "../providerMaintenance.ts";
import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "./ClaudeHome.ts";
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
@@ -105,7 +106,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
supportsMultipleInstances: true,
},
configSchema: ClaudeSettings,
defaultConfig: (): ClaudeSettings => Schema.decodeSync(ClaudeSettings)({}),
defaultConfig: (): ClaudeSettings => decodeClaudeSettings({}),
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -51,6 +51,7 @@ import {
materializeCodexShadowHome,
resolveCodexHomeLayout,
} from "./CodexHomeLayout.ts";
const decodeCodexSettings = Schema.decodeSync(CodexSettings);
const DRIVER_KIND = ProviderDriverKind.make("codex");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
@@ -103,7 +104,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
supportsMultipleInstances: true,
},
configSchema: CodexSettings,
defaultConfig: (): CodexSettings => Schema.decodeSync(CodexSettings)({}),
defaultConfig: (): CodexSettings => decodeCodexSettings({}),
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -11,6 +11,7 @@ import {
materializeCodexShadowHome,
resolveCodexHomeLayout,
} from "./CodexHomeLayout.ts";
const decodeCodexSettingsValue = Schema.decodeSync(CodexSettings);
const decodeCodexSettings = (input: {
readonly enabled?: boolean;
@@ -18,7 +19,7 @@ const decodeCodexSettings = (input: {
readonly shadowHomePath?: string;
readonly customModels?: readonly string[];
readonly binaryPath?: string;
}): CodexSettings => Schema.decodeSync(CodexSettings)(input);
}): CodexSettings => decodeCodexSettingsValue(input);
const makeTempDir = Effect.fn("CodexHomeLayout.test.makeTempDir")(function* (prefix: string) {
const fileSystem = yield* FileSystem.FileSystem;
@@ -74,6 +74,7 @@ export class CodexShadowHomeError extends Schema.TaggedErrorClass<CodexShadowHom
return this.detail;
}
}
const isCodexShadowHomeError = Schema.is(CodexShadowHomeError);
type LinkState =
| {
@@ -88,7 +89,7 @@ type LinkState =
};
function toShadowHomeError(cause: unknown): CodexShadowHomeError {
return Schema.is(CodexShadowHomeError)(cause)
return isCodexShadowHomeError(cause)
? cause
: new CodexShadowHomeError({
detail: "Failed to materialize Codex shadow home.",
@@ -45,6 +45,7 @@ import {
makeStaticProviderMaintenanceResolver,
resolveProviderMaintenanceCapabilitiesEffect,
} from "../providerMaintenance.ts";
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
const DRIVER_KIND = ProviderDriverKind.make("cursor");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
@@ -89,7 +90,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
supportsMultipleInstances: true,
},
configSchema: CursorSettings,
defaultConfig: (): CursorSettings => Schema.decodeSync(CursorSettings)({}),
defaultConfig: (): CursorSettings => decodeCursorSettings({}),
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -46,6 +46,7 @@ import {
normalizeCommandPath,
resolveProviderMaintenanceCapabilitiesEffect,
} from "../providerMaintenance.ts";
const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
const DRIVER_KIND = ProviderDriverKind.make("opencode");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
@@ -102,7 +103,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
supportsMultipleInstances: true,
},
configSchema: OpenCodeSettings,
defaultConfig: (): OpenCodeSettings => Schema.decodeSync(OpenCodeSettings)({}),
defaultConfig: (): OpenCodeSettings => decodeOpenCodeSettings({}),
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
Effect.gen(function* () {
const openCodeRuntime = yield* OpenCodeRuntime;
@@ -38,6 +38,7 @@ import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderAdapterValidationError } from "../Errors.ts";
import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { makeClaudeAdapter, type ClaudeAdapterLiveOptions } from "./ClaudeAdapter.ts";
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
// Test-local service tag so the rest of the file can keep using `yield* ClaudeAdapter`.
class ClaudeAdapter extends Context.Service<ClaudeAdapter, ClaudeAdapterShape>()(
@@ -186,7 +187,7 @@ function makeHarness(config?: {
layer: Layer.effect(
ClaudeAdapter,
Effect.gen(function* () {
const claudeConfig = Schema.decodeSync(ClaudeSettings)(config?.claudeConfig ?? {});
const claudeConfig = decodeClaudeSettings(config?.claudeConfig ?? {});
return yield* makeClaudeAdapter(claudeConfig, adapterOptions);
}),
).pipe(
@@ -1344,7 +1345,7 @@ describe("ClaudeAdapterLive", () => {
const layer = Layer.effect(
ClaudeAdapter,
Effect.gen(function* () {
const claudeConfig = Schema.decodeSync(ClaudeSettings)({});
const claudeConfig = decodeClaudeSettings({});
return yield* makeClaudeAdapter(claudeConfig, {
createQuery: () => {
const query = new FakeClaudeQuery();
@@ -1427,7 +1428,7 @@ describe("ClaudeAdapterLive", () => {
const layer = Layer.effect(
ClaudeAdapter,
Effect.gen(function* () {
const claudeConfig = Schema.decodeSync(ClaudeSettings)({});
const claudeConfig = decodeClaudeSettings({});
return yield* makeClaudeAdapter(claudeConfig, {
createQuery: (input) => {
// Simulate the SDK consuming the prompt iterable
@@ -82,8 +82,10 @@ import {
ProviderAdapterValidationError,
type ProviderAdapterError,
} from "../Errors.ts";
import { encodeJsonStringForDiagnostics } from "@t3tools/shared/schemaJson";
import { type ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const decodeUnknownJsonStringExit = Schema.decodeUnknownExit(Schema.UnknownFromJsonString);
const PROVIDER = ProviderDriverKind.make("claudeAgent");
type ClaudeTextStreamKind = Extract<RuntimeContentStreamKind, "assistant_text" | "reasoning_text">;
@@ -545,7 +547,7 @@ function summarizeToolRequest(toolName: string, input: Record<string, unknown>):
}
}
const serialized = Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(input);
const serialized = encodeJsonStringForDiagnostics(input) ?? "[unserializable input]";
if (serialized.length <= 400) {
return `${toolName}: ${serialized}`;
}
@@ -810,22 +812,18 @@ function exitPlanCaptureKey(input: {
}
function tryParseJsonRecord(value: string): Record<string, unknown> | undefined {
try {
const parsed = Schema.decodeUnknownSync(Schema.UnknownFromJsonString)(value);
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)
: 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<string, unknown>)
: undefined;
}
function toolInputFingerprint(input: Record<string, unknown>): string | undefined {
try {
return Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(input);
} catch {
return undefined;
}
return encodeJsonStringForDiagnostics(input);
}
function toolResultStreamKind(itemType: CanonicalItemType): ClaudeToolResultStreamKind | undefined {
@@ -2941,12 +2939,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": Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(
settings,
),
"claude.query.extra_args_json": Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(
extraArgs,
),
"claude.query.settings_json": encodeJsonStringForDiagnostics(settings) ?? "",
"claude.query.extra_args_json": encodeJsonStringForDiagnostics(extraArgs) ?? "",
"claude.query.path_to_executable": claudeBinaryPath,
});
@@ -46,6 +46,7 @@ import {
type CodexThreadSnapshot,
} from "./CodexSessionRuntime.ts";
import { makeCodexAdapter } from "./CodexAdapter.ts";
const decodeCodexSettings = Schema.decodeSync(CodexSettings);
// Test-local service tag so the rest of the file can keep using `yield* CodexAdapter`.
class CodexAdapter extends Context.Service<CodexAdapter, CodexAdapterShape>()(
@@ -224,7 +225,7 @@ const validationLayer = it.layer(
Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
const codexConfig = decodeCodexSettings({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: validationRuntimeFactory.factory,
});
@@ -293,7 +294,7 @@ const sessionErrorLayer = it.layer(
Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
const codexConfig = decodeCodexSettings({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: sessionRuntimeFactory.factory,
});
@@ -364,7 +365,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
const customLayer = Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
const codexConfig = decodeCodexSettings({});
return yield* makeCodexAdapter(codexConfig, {
instanceId: customInstanceId,
makeRuntime: customRuntimeFactory.factory,
@@ -419,7 +420,7 @@ const lifecycleLayer = it.layer(
Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
const codexConfig = decodeCodexSettings({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: lifecycleRuntimeFactory.factory,
});
@@ -1034,7 +1035,7 @@ const scopedLifecycleLayer = it.layer(
Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
const codexConfig = decodeCodexSettings({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: scopedLifecycleRuntimeFactory.factory,
});
@@ -1078,7 +1079,7 @@ const scopedFailureLayer = it.layer(
Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
const codexConfig = decodeCodexSettings({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: scopedFailureRuntimeFactory.factory,
});
@@ -1127,7 +1128,7 @@ it.effect("flushes managed native logs when the adapter layer shuts down", () =>
const layer = Layer.effect(
CodexAdapter,
Effect.gen(function* () {
const codexConfig = Schema.decodeSync(CodexSettings)({});
const codexConfig = decodeCodexSettings({});
return yield* makeCodexAdapter(codexConfig, {
makeRuntime: runtimeFactory.factory,
nativeEventLogPath: basePath,
@@ -61,6 +61,12 @@ import {
type CodexSessionRuntimeShape,
} from "./CodexSessionRuntime.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const isCodexAppServerProcessExitedError = Schema.is(CodexErrors.CodexAppServerProcessExitedError);
const isCodexAppServerTransportError = Schema.is(CodexErrors.CodexAppServerTransportError);
const isCodexSessionRuntimeThreadIdMissingError = Schema.is(
CodexSessionRuntimeThreadIdMissingError,
);
const isCodexResumeCursorSchema = Schema.is(CodexResumeCursorSchema);
const PROVIDER = ProviderDriverKind.make("codex");
@@ -91,10 +97,7 @@ function mapCodexRuntimeError(
method: string,
error: CodexSessionRuntimeError,
): ProviderAdapterError {
if (
Schema.is(CodexErrors.CodexAppServerProcessExitedError)(error) ||
Schema.is(CodexErrors.CodexAppServerTransportError)(error)
) {
if (isCodexAppServerProcessExitedError(error) || isCodexAppServerTransportError(error)) {
return new ProviderAdapterSessionClosedError({
provider: PROVIDER,
threadId,
@@ -102,7 +105,7 @@ function mapCodexRuntimeError(
});
}
if (Schema.is(CodexSessionRuntimeThreadIdMissingError)(error)) {
if (isCodexSessionRuntimeThreadIdMissingError(error)) {
return new ProviderAdapterSessionNotFoundError({
provider: PROVIDER,
threadId,
@@ -134,7 +137,8 @@ function readPayload<A>(
schema: Schema.Schema<A>,
payload: ProviderEvent["payload"],
): A | undefined {
return Schema.is(schema)(payload) ? payload : undefined;
const isPayload = Schema.is(schema);
return isPayload(payload) ? payload : undefined;
}
function trimText(value: string | undefined | null): string | undefined {
@@ -1381,7 +1385,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
binaryPath: codexConfig.binaryPath,
...(options?.environment ? { environment: options.environment } : {}),
...(codexConfig.homePath ? { homePath: codexConfig.homePath } : {}),
...(Schema.is(CodexResumeCursorSchema)(input.resumeCursor)
...(isCodexResumeCursorSchema(input.resumeCursor)
? { resumeCursor: input.resumeCursor }
: {}),
runtimeMode: input.runtimeMode,
@@ -26,6 +26,7 @@ import { buildServerProvider, type ServerProviderDraft } from "../providerSnapsh
import { expandHomePath } from "../../pathExpansion.ts";
import { scopedSafeTeardown } from "./scopedSafeTeardown.ts";
import packageJson from "../../../package.json" with { type: "json" };
const isCodexAppServerSpawnError = Schema.is(CodexErrors.CodexAppServerSpawnError);
const PROVIDER_PROBE_TIMEOUT_MS = 8_000;
const CODEX_PRESENTATION = {
@@ -450,7 +451,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
if (Result.isFailure(probeResult)) {
const error = probeResult.failure;
const installed = !Schema.is(CodexErrors.CodexAppServerSpawnError)(error);
const installed = !isCodexAppServerSpawnError(error);
return buildServerProvider({
presentation: CODEX_PRESENTATION,
enabled: codexSettings.enabled,
@@ -16,6 +16,7 @@ import {
isRecoverableThreadResumeError,
openCodexThread,
} from "./CodexSessionRuntime.ts";
const isCodexAppServerRequestError = Schema.is(CodexErrors.CodexAppServerRequestError);
function makeThreadOpenResponse(
threadId: string,
@@ -269,7 +270,7 @@ describe("openCodexThread", () => {
}),
),
(error: unknown) =>
Schema.is(CodexErrors.CodexAppServerRequestError)(error) &&
isCodexAppServerRequestError(error) &&
error.errorMessage === "timed out waiting for server",
);
});
@@ -41,6 +41,7 @@ import {
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
} from "../CodexDeveloperInstructions.ts";
const decodeV2TurnStartResponse = Schema.decodeUnknownEffect(EffectCodexSchema.V2TurnStartResponse);
const PROVIDER = ProviderDriverKind.make("codex");
@@ -66,6 +67,8 @@ export const CodexResumeCursorSchema = Schema.Struct({
const CodexUserInputAnswerObject = Schema.Struct({
answers: Schema.Array(Schema.String),
});
const isCodexResumeCursorSchema = Schema.is(CodexResumeCursorSchema);
const isCodexUserInputAnswerObject = Schema.is(CodexUserInputAnswerObject);
// TODO: Verify `packages/effect-codex-app-server/scripts/generate.ts` so the generated
// `V2TurnStartParams` schema includes `collaborationMode` directly.
@@ -74,6 +77,9 @@ const CodexTurnStartParamsWithCollaborationMode = EffectCodexSchema.V2TurnStartP
collaborationMode: Schema.optionalKey(EffectCodexSchema.V2TurnStartParams__CollaborationMode),
}),
);
const decodeCodexTurnStartParamsWithCollaborationMode = Schema.decodeUnknownEffect(
CodexTurnStartParamsWithCollaborationMode,
);
export type CodexTurnStartParamsWithCollaborationMode =
typeof CodexTurnStartParamsWithCollaborationMode.Type;
@@ -248,7 +254,7 @@ function normalizeCodexModelSlug(
function readResumeCursorThreadId(
resumeCursor: ProviderSession["resumeCursor"],
): string | undefined {
return Schema.is(CodexResumeCursorSchema)(resumeCursor) ? resumeCursor.threadId : undefined;
return isCodexResumeCursorSchema(resumeCursor) ? resumeCursor.threadId : undefined;
}
function runtimeModeToThreadConfig(input: RuntimeMode): {
@@ -367,7 +373,7 @@ export function buildTurnStartParams(input: {
...(input.effort ? { effort: input.effort } : {}),
});
return Schema.decodeUnknownEffect(CodexTurnStartParamsWithCollaborationMode)({
return decodeCodexTurnStartParamsWithCollaborationMode({
threadId: input.threadId,
input: turnInput,
approvalPolicy: config.approvalPolicy,
@@ -623,7 +629,7 @@ function toCodexUserInputAnswer(
const answers = value.filter((entry): entry is string => typeof entry === "string");
return Effect.succeed({ answers });
}
if (Schema.is(CodexUserInputAnswerObject)(value)) {
if (isCodexUserInputAnswerObject(value)) {
return Effect.succeed({ answers: value.answers });
}
return Effect.fail(new CodexSessionRuntimeInvalidUserInputAnswersError({ questionId }));
@@ -1247,9 +1253,7 @@ export const makeCodexSessionRuntime = (
...(input.interactionMode ? { interactionMode: input.interactionMode } : {}),
});
const rawResponse = yield* client.raw.request("turn/start", params);
const response = yield* Schema.decodeUnknownEffect(EffectCodexSchema.V2TurnStartResponse)(
rawResponse,
).pipe(
const response = yield* decodeV2TurnStartResponse(rawResponse).pipe(
Effect.mapError((error) =>
toProtocolParseError("Invalid turn/start response payload", error),
),
@@ -28,6 +28,7 @@ import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import type { CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { makeCursorAdapter } from "./CursorAdapter.ts";
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
// Test-local service tag so the rest of the file can keep using `yield* CursorAdapter`.
class CursorAdapter extends Context.Service<CursorAdapter, CursorAdapterShape>()(
@@ -132,7 +133,7 @@ const cursorAdapterTestLayer = it.layer(
Layer.effect(
CursorAdapter,
Effect.gen(function* () {
const cursorConfig = Schema.decodeSync(CursorSettings)({});
const cursorConfig = decodeCursorSettings({});
const resolveSettings = yield* makeResolveCursorSettings;
return yield* makeCursorAdapter(cursorConfig, { resolveSettings });
}),
@@ -607,7 +608,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
Layer.effect(
CursorAdapter,
Effect.gen(function* () {
const cursorConfig = Schema.decodeSync(CursorSettings)({});
const cursorConfig = decodeCursorSettings({});
const resolveSettings = yield* makeResolveCursorSettings;
return yield* makeCursorAdapter(cursorConfig, { resolveSettings });
}),
@@ -1239,7 +1240,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
const customAdapterLayer = Layer.effect(
CursorAdapter,
Effect.gen(function* () {
const cursorConfig = Schema.decodeSync(CursorSettings)({});
const cursorConfig = decodeCursorSettings({});
const resolveSettings = yield* makeResolveCursorSettings;
return yield* makeCursorAdapter(cursorConfig, {
instanceId: customInstanceId,
@@ -72,6 +72,7 @@ import {
extractPlanMarkdown,
extractTodosAsPlan,
} from "../acp/CursorAcpExtension.ts";
import { encodeJsonStringForDiagnostics } from "@t3tools/shared/schemaJson";
import { type CursorAdapterShape } from "../Services/CursorAdapter.ts";
import { resolveCursorAcpBaseModelId } from "./CursorProvider.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
@@ -390,7 +391,7 @@ export function makeCursorAdapter(
method: string,
) =>
Effect.gen(function* () {
const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(payload)}`;
const fingerprint = `${ctx.activeTurnId ?? "no-turn"}:${encodeJsonStringForDiagnostics(payload) ?? "[unserializable payload]"}`;
if (ctx.lastPlanFingerprint === fingerprint) {
return;
}
@@ -640,7 +641,8 @@ export function makeCursorAdapter(
permissionRequest,
detail:
permissionRequest.detail ??
Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(params).slice(0, 2000),
encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??
"[unserializable params]",
args: params,
source: "acp.jsonrpc",
method: "session/request_permission",
@@ -16,6 +16,7 @@ import {
} from "../opencodeRuntime.ts";
import { checkOpenCodeProviderStatus } from "./OpenCodeProvider.ts";
import type { OpenCodeInventory } from "../opencodeRuntime.ts";
const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
const DEFAULT_VERSION_STDOUT = "opencode 1.14.19\n";
@@ -106,7 +107,7 @@ const testLayer = Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble).pipe
);
const makeOpenCodeSettings = (overrides?: Partial<OpenCodeSettings>): OpenCodeSettings =>
Schema.decodeSync(OpenCodeSettings)({
decodeOpenCodeSettings({
enabled: true,
binaryPath: "opencode",
serverUrl: "",
@@ -47,6 +47,7 @@ import type { ProviderInstance } from "../ProviderDriver.ts";
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
import { ProviderRegistry } from "../Services/ProviderRegistry.ts";
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
const decodeServerSettings = Schema.decodeSync(ServerSettings);
const defaultClaudeSettings: ClaudeSettings = Schema.decodeSync(ClaudeSettings)({});
const defaultCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({});
@@ -255,7 +256,7 @@ function makeMutableServerSettingsService(
updateSettings: (patch) =>
Effect.gen(function* () {
const current = yield* Ref.get(settingsRef);
const next = Schema.decodeSync(ServerSettings)(deepMerge(current, patch));
const next = decodeServerSettings(deepMerge(current, patch));
yield* Ref.set(settingsRef, next);
yield* PubSub.publish(changes, next);
return next;
@@ -928,7 +929,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
Effect.gen(function* () {
const missingBinary = `t3code_codex_missing_`;
const serverSettings = yield* makeMutableServerSettingsService(
Schema.decodeSync(ServerSettings)(
decodeServerSettings(
deepMerge(DEFAULT_SERVER_SETTINGS, {
providers: {
// Disable every built-in probe that would otherwise spawn
@@ -1027,7 +1028,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
const firstMissing = `t3code_codex_first_`;
const secondMissing = `t3code_codex_second_`;
const serverSettings = yield* makeMutableServerSettingsService(
Schema.decodeSync(ServerSettings)(
decodeServerSettings(
deepMerge(DEFAULT_SERVER_SETTINGS, {
providers: {
codex: { enabled: true, binaryPath: firstMissing },
@@ -1122,7 +1123,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
it.effect("includes unavailable instance snapshots in getProviders", () =>
Effect.gen(function* () {
const serverSettings = yield* makeMutableServerSettingsService(
Schema.decodeSync(ServerSettings)(
decodeServerSettings(
deepMerge(DEFAULT_SERVER_SETTINGS, {
providers: {
codex: { enabled: false },
@@ -1178,7 +1179,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
() =>
Effect.gen(function* () {
const serverSettings = yield* makeMutableServerSettingsService(
Schema.decodeSync(ServerSettings)(
decodeServerSettings(
deepMerge(DEFAULT_SERVER_SETTINGS, {
providers: {
codex: {
@@ -56,6 +56,7 @@ import {
import { type EventNdjsonLogger } from "./EventNdjsonLogger.ts";
import { ProviderEventLoggers } from "./ProviderEventLoggers.ts";
import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";
const isModelSelection = Schema.is(ModelSelection);
/**
* Hook for tests that want to override the canonical event logger pulled
@@ -87,8 +88,9 @@ const decodeInputOrValidationError = <S extends Schema.Top>(input: {
readonly operation: string;
readonly schema: S;
readonly payload: unknown;
}) =>
Schema.decodeUnknownEffect(input.schema)(input.payload).pipe(
}) => {
const decodeProviderRequestInput = Schema.decodeUnknownEffect(input.schema);
return decodeProviderRequestInput(input.payload).pipe(
Effect.mapError(
(schemaError) =>
new ProviderValidationError({
@@ -98,6 +100,7 @@ const decodeInputOrValidationError = <S extends Schema.Top>(input: {
}),
),
);
};
function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "stopped" | "error" {
switch (session.status) {
@@ -142,7 +145,7 @@ function readPersistedModelSelection(
return undefined;
}
const raw = "modelSelection" in runtimePayload ? runtimePayload.modelSelection : undefined;
return Schema.is(ModelSelection)(raw) ? raw : undefined;
return isModelSelection(raw) ? raw : undefined;
}
function readPersistedCwd(
@@ -14,6 +14,7 @@ import {
type ProviderRuntimeBindingWithMetadata,
type ProviderSessionDirectoryShape,
} from "../Services/ProviderSessionDirectory.ts";
const decodeProviderDriverKindValue = Schema.decodeUnknownEffect(ProviderDriverKind);
function toPersistenceError(operation: string) {
return (cause: unknown) =>
@@ -28,7 +29,7 @@ function decodeProviderDriverKind(
providerName: string,
operation: string,
): Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryPersistenceError> {
return Schema.decodeUnknownEffect(ProviderDriverKind)(providerName).pipe(
return decodeProviderDriverKindValue(providerName).pipe(
Effect.mapError(
(cause) =>
new ProviderSessionDirectoryPersistenceError({
@@ -11,6 +11,8 @@ import {
ProviderAdapterSessionClosedError,
type ProviderAdapterError,
} from "../Errors.ts";
const isAcpProcessExitedError = Schema.is(EffectAcpErrors.AcpProcessExitedError);
const isAcpRequestError = Schema.is(EffectAcpErrors.AcpRequestError);
export function mapAcpToAdapterError(
provider: ProviderDriverKind,
@@ -18,14 +20,14 @@ export function mapAcpToAdapterError(
method: string,
error: EffectAcpErrors.AcpError,
): ProviderAdapterError {
if (Schema.is(EffectAcpErrors.AcpProcessExitedError)(error)) {
if (isAcpProcessExitedError(error)) {
return new ProviderAdapterSessionClosedError({
provider,
threadId,
cause: error,
});
}
if (Schema.is(EffectAcpErrors.AcpRequestError)(error)) {
if (isAcpRequestError(error)) {
return new ProviderAdapterRequestError({
provider,
method,
@@ -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";
@@ -27,6 +26,10 @@ import {
type AcpToolCallState,
} from "./AcpRuntimeModel.ts";
function formatConfigOptionValue(value: string | boolean): string {
return JSON.stringify(value);
}
export interface AcpSpawnInput {
readonly command: string;
readonly args: ReadonlyArray<string>;
@@ -277,7 +280,7 @@ const makeAcpSessionRuntime = (
}
return yield* new EffectAcpErrors.AcpRequestError({
code: -32602,
errorMessage: `Invalid value ${Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(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",
@@ -288,7 +291,7 @@ const makeAcpSessionRuntime = (
if (typeof value !== "string") {
return yield* new EffectAcpErrors.AcpRequestError({
code: -32602,
errorMessage: `Invalid value ${Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(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",
@@ -302,7 +305,7 @@ const makeAcpSessionRuntime = (
}
return yield* new EffectAcpErrors.AcpRequestError({
code: -32602,
errorMessage: `Invalid value ${Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(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,
+6 -6
View File
@@ -24,13 +24,14 @@ import * as P from "effect/Predicate";
import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
import * as Scope from "effect/Scope";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { encodeJsonStringForDiagnostics } from "@t3tools/shared/schemaJson";
import { isWindowsCommandNotFound } from "../processRunner.ts";
import { collectStreamAsString } from "./providerSnapshot.ts";
import * as NetService from "@t3tools/shared/Net";
const OPENCODE_EMPTY_CONFIG_CONTENT = "{}";
const OPENCODE_SERVER_READY_PREFIX = "opencode server listening";
const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 5_000;
@@ -64,10 +65,9 @@ export function openCodeRuntimeErrorDetail(cause: unknown): string {
const anyCause = cause as Record<string, unknown>;
const status = (anyCause.response as { status?: number } | undefined)?.status;
const body = anyCause.error ?? anyCause.data ?? anyCause.body;
try {
return `status=${status ?? "?"} body=${Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(body ?? cause)}`;
} catch {
/* fall through */
const encodedBody = encodeJsonStringForDiagnostics(body ?? cause);
if (encodedBody) {
return `status=${status ?? "?"} body=${encodedBody}`;
}
}
return String(cause);
@@ -336,7 +336,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
shell: process.platform === "win32",
env: {
...(input.environment ?? process.env),
OPENCODE_CONFIG_CONTENT: Schema.encodeUnknownSync(Schema.UnknownFromJsonString)({}),
OPENCODE_CONFIG_CONTENT: OPENCODE_EMPTY_CONFIG_CONTENT,
},
}),
)
@@ -25,6 +25,7 @@ import {
makeProviderMaintenanceCapabilities,
type ProviderMaintenanceCapabilities,
} from "./providerMaintenance.ts";
const isServerProviderUpdateError = Schema.is(ServerProviderUpdateError);
const CODEX_DRIVER = ProviderDriverKind.make("codex");
const CURSOR_DRIVER = ProviderDriverKind.make("cursor");
@@ -455,8 +456,8 @@ describe("providerMaintenanceRunner", () => {
assert.strictEqual(Exit.isFailure(second), true);
if (Exit.isFailure(second)) {
const error = Cause.squash(second.cause);
assert.strictEqual(Schema.is(ServerProviderUpdateError)(error), true);
if (Schema.is(ServerProviderUpdateError)(error)) {
assert.strictEqual(isServerProviderUpdateError(error), true);
if (isServerProviderUpdateError(error)) {
assert.include(error.reason, "already running");
}
}
@@ -25,6 +25,7 @@ import { makeProviderMaintenanceCommandCoordinator } from "./providerMaintenance
import { enrichProviderSnapshotWithVersionAdvisory } from "./providerMaintenance.ts";
import type { ProviderMaintenanceCapabilities } from "./providerMaintenance.ts";
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
const isServerProviderUpdateError = Schema.is(ServerProviderUpdateError);
const UPDATE_TIMEOUT_MS = 5 * 60_000;
const UPDATE_OUTPUT_MAX_BYTES = 10_000;
@@ -397,7 +398,7 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
})
.pipe(
Effect.mapError((error) =>
Schema.is(ServerProviderUpdateError)(error)
isServerProviderUpdateError(error)
? new ServerProviderUpdateError({
provider,
reason: error.reason,
+5 -5
View File
@@ -49,6 +49,7 @@ import { fromLenientJson } from "@t3tools/shared/schemaJson";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
import { ServerSecretStore } from "./auth/Services/ServerSecretStore.ts";
const decodeServerSettings = Schema.decodeEffect(ServerSettings);
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
@@ -127,9 +128,7 @@ export class ServerSettingsService extends Context.Service<
updateSettings: (patch) =>
Ref.get(currentSettingsRef).pipe(
Effect.flatMap((currentSettings) =>
Schema.decodeEffect(ServerSettings)(
applyServerSettingsPatch(currentSettings, patch),
).pipe(
decodeServerSettings(applyServerSettingsPatch(currentSettings, patch)).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
@@ -149,6 +148,7 @@ export class ServerSettingsService extends Context.Service<
}
const ServerSettingsJson = fromLenientJson(ServerSettings);
const decodeServerSettingsJsonExit = Schema.decodeUnknownExit(ServerSettingsJson);
type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];
@@ -280,7 +280,7 @@ const makeServerSettings = Effect.gen(function* () {
}
const raw = yield* readRawConfig;
const decoded = Schema.decodeUnknownExit(ServerSettingsJson)(raw);
const decoded = decodeServerSettingsJsonExit(raw);
if (decoded._tag === "Failure") {
yield* Effect.logWarning("failed to parse settings.json, using defaults", {
path: settingsPath,
@@ -533,7 +533,7 @@ const makeServerSettings = Effect.gen(function* () {
current,
applyServerSettingsPatch(current, patch),
);
const next = yield* Schema.decodeEffect(ServerSettings)(nextPersisted).pipe(
const next = yield* decodeServerSettings(nextPersisted).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
@@ -44,6 +44,7 @@ export class BitbucketApiError extends Schema.TaggedErrorClass<BitbucketApiError
return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
}
}
const isBitbucketApiErrorValue = Schema.is(BitbucketApiError);
const RawBitbucketRepositorySchema = Schema.Struct({
full_name: TrimmedNonEmptyString,
@@ -350,7 +351,7 @@ function requestError(operation: string, cause: unknown): BitbucketApiError {
}
function isBitbucketApiError(cause: unknown): cause is BitbucketApiError {
return Schema.is(BitbucketApiError)(cause);
return isBitbucketApiErrorValue(cause);
}
function responseError(
@@ -13,6 +13,7 @@ import * as GitHubCli from "./GitHubCli.ts";
import * as GitHubPullRequests from "./gitHubPullRequests.ts";
import * as SourceControlProvider from "./SourceControlProvider.ts";
import * as SourceControlProviderDiscovery from "./SourceControlProviderDiscovery.ts";
const isSourceControlProviderError = Schema.is(SourceControlProviderError);
function providerError(
operation: string,
@@ -153,7 +154,7 @@ export const make = Effect.fn("makeGitHubSourceControlProvider")(function* () {
);
}),
Effect.mapError((error) =>
Schema.is(SourceControlProviderError)(error)
isSourceControlProviderError(error)
? error
: providerError("listChangeRequests", error),
),
@@ -22,6 +22,7 @@ import {
import { ServerConfig } from "../config.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError);
export interface SourceControlRepositoryServiceShape {
readonly lookupRepository: (
@@ -69,7 +70,7 @@ function repositoryError(input: {
function mapRepositoryError(operation: string, provider: SourceControlProviderKind) {
return Effect.mapError((cause: unknown) =>
Schema.is(SourceControlRepositoryError)(cause)
isSourceControlRepositoryError(cause)
? cause
: repositoryError({
operation,
@@ -13,6 +13,7 @@ import { ServerConfig } from "../config.ts";
import { type TextGenerationShape } from "./TextGeneration.ts";
import { sanitizeThreadTitle } from "./TextGenerationUtils.ts";
import { makeClaudeTextGeneration } from "./ClaudeTextGeneration.ts";
const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
const ClaudeTextGenerationTestLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-claude-text-generation-test-",
@@ -182,7 +183,7 @@ function withFakeClaudeEnv<A, E, R>(
}),
);
const config = Schema.decodeSync(ClaudeSettings)(input.claudeConfig ?? {});
const config = decodeClaudeSettings(input.claudeConfig ?? {});
const textGeneration = yield* makeClaudeTextGeneration(config);
return yield* effectFn(textGeneration);
}).pipe(Effect.scoped);
@@ -53,6 +53,9 @@ const ClaudeOutputEnvelope = Schema.Struct({
structured_output: Schema.Unknown,
});
const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString);
const decodeClaudeOutputEnvelope = Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope));
export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(function* (
claudeSettings: ClaudeSettings,
environment: NodeJS.ProcessEnv = process.env,
@@ -75,6 +78,26 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
),
);
const encodeJsonForOperation = (
operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle",
value: unknown,
detail: string,
): Effect.Effect<string, TextGenerationError> =>
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.
@@ -96,8 +119,10 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
outputSchemaJson: S;
modelSelection: ModelSelection;
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
const jsonSchemaStr = Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(
const jsonSchemaStr = yield* encodeJsonForOperation(
operation,
toJsonSchemaObject(outputSchemaJson),
"Failed to encode structured output schema.",
);
const caps = getClaudeModelCapabilities(modelSelection.model);
const descriptors = getProviderOptionDescriptors({
@@ -118,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(
@@ -131,9 +164,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
"--model",
resolveClaudeApiModelId(modelSelection),
...(cliEffort ? ["--effort", cliEffort] : []),
...(Object.keys(settings).length > 0
? ["--settings", Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(settings)]
: []),
...(settingsJson ? ["--settings", settingsJson] : []),
"--dangerously-skip-permissions",
],
{
@@ -197,9 +228,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
),
);
const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
rawStdout,
).pipe(
const envelope = yield* decodeClaudeOutputEnvelope(rawStdout).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
@@ -211,7 +240,8 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
),
);
return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
const decodeOutput = Schema.decodeEffect(outputSchemaJson);
return yield* decodeOutput(envelope.structured_output).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
@@ -14,6 +14,7 @@ import { CodexSettings, ProviderInstanceId, TextGenerationError } from "@t3tools
import { ServerConfig } from "../config.ts";
import { type TextGenerationShape } from "./TextGeneration.ts";
import { makeCodexTextGeneration } from "./CodexTextGeneration.ts";
const decodeCodexSettings = Schema.decodeSync(CodexSettings);
const DEFAULT_TEST_MODEL_SELECTION = createModelSelection(
ProviderInstanceId.make("codex"),
@@ -172,7 +173,7 @@ function withFakeCodexEnv<A, E, R>(
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
const config = Schema.decodeSync(CodexSettings)({ binaryPath: codexPath });
const config = decodeCodexSettings({ binaryPath: codexPath });
const textGeneration = yield* makeCodexTextGeneration(config);
return yield* effectFn(textGeneration);
}).pipe(Effect.scoped);
@@ -40,6 +40,7 @@ import {
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
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.
@@ -99,6 +100,25 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
const encodeJsonForOperation = (
operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle",
value: unknown,
): Effect.Effect<string, TextGenerationError> =>
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"
@@ -156,11 +176,11 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
cleanupPaths?: ReadonlyArray<string>;
modelSelection: ModelSelection;
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
const schemaPath = yield* writeTempFile(
const schemaJson = yield* encodeJsonForOperation(
operation,
"codex-schema",
Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(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* () {
@@ -259,6 +279,8 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
),
);
const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
return yield* fileSystem.readFileString(outputPath).pipe(
Effect.mapError(
(cause) =>
@@ -268,7 +290,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
cause,
}),
),
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
Effect.flatMap(decodeOutput),
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
@@ -19,6 +19,7 @@ import { CursorSettings, ProviderInstanceId } from "@t3tools/contracts";
import { ServerConfig } from "../config.ts";
import { type TextGenerationShape } from "./TextGeneration.ts";
import { makeCursorTextGeneration } from "./CursorTextGeneration.ts";
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../scripts/acp-mock-agent.ts");
@@ -65,7 +66,7 @@ function withFakeAcpAgent<A, E, R>(
}),
);
const agentPath = makeAcpAgentWrapper(tempDir, env);
const config = Schema.decodeSync(CursorSettings)({ binaryPath: agentPath });
const config = decodeCursorSettings({ binaryPath: agentPath });
const textGeneration = yield* makeCursorTextGeneration(config);
return yield* effectFn(textGeneration);
}).pipe(Effect.scoped);
@@ -154,9 +154,8 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
});
}
return yield* Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))(
extractJsonObject(rawResult),
).pipe(
const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
return yield* decodeOutput(extractJsonObject(rawResult)).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
@@ -352,9 +352,8 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
releaseSharedServer,
);
return yield* Schema.decodeEffect(Schema.fromJsonString(input.outputSchemaJson))(
extractJsonObject(rawOutput),
).pipe(
const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(input.outputSchemaJson));
return yield* decodeOutput(extractJsonObject(rawOutput)).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
@@ -1,6 +1,7 @@
import * as Schema from "effect/Schema";
import { TextGenerationError } from "@t3tools/contracts";
const isTextGenerationError = Schema.is(TextGenerationError);
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
export function toJsonSchemaObject(schema: Schema.Top): unknown {
@@ -127,7 +128,7 @@ export function normalizeCliError(
error: unknown,
fallback: string,
): TextGenerationError {
if (Schema.is(TextGenerationError)(error)) {
if (isTextGenerationError(error)) {
return error;
}
+2 -1
View File
@@ -28,6 +28,7 @@ import {
parseRemoteRefWithRemoteNames,
} from "../git/remoteRefs.ts";
import { ServerConfig } from "../config.ts";
const isGitCommandError = Schema.is(GitCommandError);
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
@@ -327,7 +328,7 @@ function toGitCommandError(
detail: string,
) {
return (cause: unknown) =>
Schema.is(GitCommandError)(cause)
isGitCommandError(cause)
? cause
: new GitCommandError({
operation: input.operation,
+2 -1
View File
@@ -15,6 +15,7 @@ const ProjectVcsConfig = Schema.Struct({
),
vcsKind: Schema.optional(VcsDriverKind),
});
const isProjectVcsConfig = Schema.is(ProjectVcsConfig);
interface ProjectVcsConfigFile {
readonly vcs?:
@@ -47,7 +48,7 @@ function configuredKind(config: ProjectVcsConfigFile): VcsDriverKindType | "auto
function parseConfig(raw: string): ProjectVcsConfigFile | null {
try {
const parsed = JSON.parse(raw) as unknown;
return Schema.is(ProjectVcsConfig)(parsed) ? parsed : null;
return isProjectVcsConfig(parsed) ? parsed : null;
} catch {
return null;
}
+6 -4
View File
@@ -86,6 +86,8 @@ import {
type SessionCredentialChange,
} from "./auth/Services/SessionCredentialService.ts";
import { respondToAuthError } from "./auth/http.ts";
const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);
const isWorkspacePathOutsideRootError = Schema.is(WorkspacePathOutsideRootError);
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
@@ -216,7 +218,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
});
const toDispatchCommandError = (cause: unknown, fallbackMessage: string) =>
Schema.is(OrchestrationDispatchCommandError)(cause)
isOrchestrationDispatchCommandError(cause)
? cause
: new OrchestrationDispatchCommandError({
message: cause instanceof Error ? cause.message : fallbackMessage,
@@ -225,7 +227,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
const toBootstrapDispatchCommandCauseError = (cause: Cause.Cause<unknown>) => {
const error = Cause.squash(cause);
return Schema.is(OrchestrationDispatchCommandError)(error)
return isOrchestrationDispatchCommandError(error)
? error
: new OrchestrationDispatchCommandError({
message:
@@ -637,7 +639,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
return result;
}).pipe(
Effect.mapError((cause) =>
Schema.is(OrchestrationDispatchCommandError)(cause)
isOrchestrationDispatchCommandError(cause)
? cause
: new OrchestrationDispatchCommandError({
message: "Failed to dispatch orchestration command",
@@ -918,7 +920,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
WS_METHODS.projectsWriteFile,
workspaceFileSystem.writeFile(input).pipe(
Effect.mapError((cause) => {
const message = Schema.is(WorkspacePathOutsideRootError)(cause)
const message = isWorkspacePathOutsideRootError(cause)
? "Workspace file path must stay within the project root."
: "Failed to write workspace file";
return new ProjectWriteFileError({
@@ -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,12 +64,9 @@ function readProviderSettingsFormSchemaAnnotation(
function readFieldBooleanDefault(
fieldSchema: ProviderClientDefinition["settingsSchema"]["fields"][string],
): boolean | undefined {
try {
const decoded = Schema.decodeUnknownSync(fieldSchema as Schema.Decoder<unknown>)(undefined);
return typeof decoded === "boolean" ? decoded : undefined;
} catch {
return undefined;
}
const decodeDefault = Schema.decodeUnknownOption(fieldSchema as Schema.Decoder<unknown>);
const decoded = decodeDefault(undefined);
return Option.isSome(decoded) && typeof decoded.value === "boolean" ? decoded.value : undefined;
}
export function deriveProviderSettingsFields(
+3 -2
View File
@@ -42,11 +42,12 @@ import { useShallow } from "zustand/react/shallow";
import { createDebouncedStorage, createMemoryStorage } from "./lib/storage";
import { getDefaultServerModel } from "./providerModels";
import { UnifiedSettings } from "@t3tools/contracts/settings";
const isRuntimeMode = Schema.is(RuntimeMode);
const isProviderDriverKind = Schema.is(ProviderDriverKind);
export const COMPOSER_DRAFT_STORAGE_KEY = "t3code:composer-drafts:v1";
const COMPOSER_DRAFT_STORAGE_VERSION = 6;
const DraftThreadEnvModeSchema = Schema.Literals(["local", "worktree"]);
const isRuntimeMode = Schema.is(RuntimeMode);
export type DraftThreadEnvMode = typeof DraftThreadEnvModeSchema.Type;
export const DraftId = Schema.String.pipe(Schema.brand("DraftId"));
@@ -575,7 +576,7 @@ function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
}
function normalizeProviderDriverKind(value: unknown): ProviderDriverKind | null {
return Schema.is(ProviderDriverKind)(value) ? value : null;
return isProviderDriverKind(value) ? value : null;
}
/**
+8 -4
View File
@@ -19,11 +19,15 @@ const isomorphicLocalStorage: Storage =
};
})();
const decode = <T, E>(schema: Schema.Codec<T, E>, value: string) =>
Schema.decodeSync(Schema.fromJsonString(schema))(value);
const decode = <T, E>(schema: Schema.Codec<T, E>, value: string) => {
const decodeJson = Schema.decodeSync(Schema.fromJsonString(schema));
return decodeJson(value);
};
const encode = <T, E>(schema: Schema.Codec<T, E>, value: T) =>
Schema.encodeSync(Schema.fromJsonString(schema))(value);
const encode = <T, E>(schema: Schema.Codec<T, E>, value: T) => {
const encodeJson = Schema.encodeSync(Schema.fromJsonString(schema));
return encodeJson(value);
};
export const getLocalStorageItem = <T, E>(key: string, schema: Schema.Codec<T, E>): T | null => {
const item = isomorphicLocalStorage.getItem(key);
+3 -1
View File
@@ -8,6 +8,8 @@ import * as Schema from "effect/Schema";
export const PROJECT_SCRIPT_KEYBINDING_INVALID_MESSAGE = "Invalid keybinding.";
const decodeKeybindingRule = Schema.decodeUnknownOption(KeybindingRuleSchema);
function normalizeProjectScriptKeybindingInput(
keybinding: string | null | undefined,
): string | null {
@@ -22,7 +24,7 @@ export function decodeProjectScriptKeybindingRule(input: {
const normalizedKey = normalizeProjectScriptKeybindingInput(input.keybinding);
if (!normalizedKey) return null;
const decoded = Schema.decodeUnknownOption(KeybindingRuleSchema)({
const decoded = decodeKeybindingRule({
key: normalizedKey,
command: input.command,
});
+5 -2
View File
@@ -9,6 +9,9 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { ensureEnvironmentApi } from "../environmentApi";
const decodeFullThreadDiffInput = Schema.decodeUnknownOption(OrchestrationGetFullThreadDiffInput);
const decodeTurnDiffInput = Schema.decodeUnknownOption(OrchestrationGetTurnDiffInput);
interface CheckpointDiffQueryInput {
environmentId: EnvironmentId | null;
threadId: ThreadId | null;
@@ -36,14 +39,14 @@ export const providerQueryKeys = {
function decodeCheckpointDiffRequest(input: CheckpointDiffQueryInput) {
if (input.fromTurnCount === 0) {
return Schema.decodeUnknownOption(OrchestrationGetFullThreadDiffInput)({
return decodeFullThreadDiffInput({
threadId: input.threadId,
toTurnCount: input.toTurnCount,
ignoreWhitespace: input.ignoreWhitespace,
}).pipe(Option.map((fields) => ({ kind: "fullThreadDiff" as const, input: fields })));
}
return Schema.decodeUnknownOption(OrchestrationGetTurnDiffInput)({
return decodeTurnDiffInput({
threadId: input.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
+2 -1
View File
@@ -5,6 +5,7 @@ import {
type ProjectScript,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
const isScriptRunCommand = Schema.is(SCRIPT_RUN_COMMAND_PATTERN);
function normalizeScriptId(value: string): string {
const cleaned = value
@@ -26,7 +27,7 @@ export const commandForProjectScript = (scriptId: string): KeybindingCommand =>
export function projectScriptIdFromCommand(command: string): string | null {
const trimmed = command.trim();
if (!Schema.is(SCRIPT_RUN_COMMAND_PATTERN)(trimmed)) {
if (!isScriptRunCommand(trimmed)) {
return null;
}
const [prefix, , suffix] = SCRIPT_RUN_COMMAND_PATTERN.parts;
+2 -1
View File
@@ -37,6 +37,7 @@ import {
import { resolveEnvironmentHttpUrl } from "./environments/runtime";
import { sanitizeThreadErrorMessage } from "./rpc/transportError";
import { getThreadFromEnvironmentState } from "./threadDerivation";
const isProviderDriverKindValue = Schema.is(ProviderDriverKind);
export interface EnvironmentState {
projectIds: ProjectId[];
@@ -1006,7 +1007,7 @@ function toLegacySessionStatus(
}
function toLegacyProvider(providerName: string | null): ProviderDriverKind {
if (Schema.is(ProviderDriverKind)(providerName)) {
if (isProviderDriverKindValue(providerName)) {
return providerName;
}
return ProviderDriverKind.make("codex");
+20 -20
View File
@@ -445,27 +445,27 @@ describe("uiStateStore pure functions", () => {
});
});
describe("uiStateStore persistence round-trip", () => {
function createLocalStorageStub(): Storage {
const store = new Map<string, string>();
return {
clear: () => {
store.clear();
},
getItem: (key) => store.get(key) ?? null,
key: (index) => [...store.keys()][index] ?? null,
get length() {
return store.size;
},
removeItem: (key) => {
store.delete(key);
},
setItem: (key, value) => {
store.set(key, value);
},
};
}
function createLocalStorageStub(): Storage {
const store = new Map<string, string>();
return {
clear: () => {
store.clear();
},
getItem: (key) => store.get(key) ?? null,
key: (index) => [...store.keys()][index] ?? null,
get length() {
return store.size;
},
removeItem: (key) => {
store.delete(key);
},
setItem: (key, value) => {
store.set(key, value);
},
};
}
describe("uiStateStore persistence round-trip", () => {
let localStorageStub: Storage;
beforeEach(() => {
+41 -21
View File
@@ -6,9 +6,10 @@
"name": "@t3tools/monorepo",
"devDependencies": {
"@effect/language-service": "catalog:",
"@oxlint/plugins": "^1.63.0",
"@types/node": "catalog:",
"oxfmt": "^0.40.0",
"oxlint": "^1.55.0",
"oxlint": "^1.63.0",
"turbo": "^2.3.3",
"typescript": "catalog:",
"vitest": "catalog:",
@@ -135,6 +136,21 @@
"vitest-browser-react": "^2.0.5",
},
},
"oxlint-plugin-t3code": {
"name": "@t3tools/oxlint-plugin-t3code",
"dependencies": {
"@effect/platform-node": "catalog:",
"@oxlint/plugins": "^1.63.0",
"effect": "catalog:",
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"@types/bun": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
},
},
"packages/client-runtime": {
"name": "@t3tools/client-runtime",
"version": "0.0.0-alpha.1",
@@ -667,43 +683,45 @@
"@oxfmt/binding-win32-x64-msvc": ["@oxfmt/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-/Zmj0yTYSvmha6TG1QnoLqVT7ZMRDqXvFXXBQpIjteEwx9qvUYMBH2xbiOFhDeMUJkGwC3D6fdKsFtaqUvkwNA=="],
"@oxlint/binding-android-arm-eabi": ["@oxlint/binding-android-arm-eabi@1.56.0", "", { "os": "android", "cpu": "arm" }, "sha512-IyfYPthZyiSKwAv/dLjeO18SaK8MxLI9Yss2JrRDyweQAkuL3LhEy7pwIwI7uA3KQc1Vdn20kdmj3q0oUIQL6A=="],
"@oxlint/binding-android-arm-eabi": ["@oxlint/[email protected]3.0", "", { "os": "android", "cpu": "arm" }, "sha512-A9xLtQt7i0OA1PoB/meog6kikXI9CdwEp7ZwQqmgnpKn3G3b1orvTDy8CQ6T7w1HvDrgWGB78PkFKcWgibcTCg=="],
"@oxlint/binding-android-arm64": ["@oxlint/binding-android-arm64@1.56.0", "", { "os": "android", "cpu": "arm64" }, "sha512-Ga5zYrzH6vc/VFxhn6MmyUnYEfy9vRpwTIks99mY3j6Nz30yYpIkWryI0QKPCgvGUtDSXVLEaMum5nA+WrNOSg=="],
"@oxlint/binding-android-arm64": ["@oxlint/[email protected]3.0", "", { "os": "android", "cpu": "arm64" }, "sha512-SQo+ZMvdR9l3CxZp5W5gFNxSiDxclY6lOzzNpKYLF8asESpm3Pwumx0gER5T7aHLF1/2BAAtLD3DiDkdgy4V1A=="],
"@oxlint/binding-darwin-arm64": ["@oxlint/binding-darwin-arm64@1.56.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-ogmbdJysnw/D4bDcpf1sPLpFThZ48lYp4aKYm10Z/6Nh1SON6NtnNhTNOlhEY296tDFItsZUz+2tgcSYqh8Eyw=="],
"@oxlint/binding-darwin-arm64": ["@oxlint/[email protected]3.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-6W82XjJDTmMnjg30427l0dufpnyLoq7wEukKdM6/g2VIybRVuQiBVh43EA4b+UxZ3+tLcKm+Or/pXGNgLCEU8g=="],
"@oxlint/binding-darwin-x64": ["@oxlint/binding-darwin-x64@1.56.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-x8QE1h+RAtQ2g+3KPsP6Fk/tdz6zJQUv5c7fTrJxXV3GHOo+Ry5p/PsogU4U+iUZg0rj6hS+E4xi+mnwwlDCWQ=="],
"@oxlint/binding-darwin-x64": ["@oxlint/[email protected]3.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-CnWd/YCuVG5W1BYkjJEVbJG11o526O9qAwBEQM+nh8K19CRFUkFdROXCyYkGmroHEYQe4vgQ6+lh3550Lp35Xw=="],
"@oxlint/binding-freebsd-x64": ["@oxlint/binding-freebsd-x64@1.56.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-6G+WMZvwJpMvY7my+/SHEjb7BTk/PFbePqLpmVmUJRIsJMy/UlyYqjpuh0RCgYYkPLcnXm1rUM04kbTk8yS1Yg=="],
"@oxlint/binding-freebsd-x64": ["@oxlint/[email protected]3.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-a4eZAqrmtajqcxfdAzC+l7g3PaE3V8hpAYqqeD3fTxLXOMFdK3eNTZrU80n4dDEVm0JXy1aL5PqvqWldBl6zYA=="],
"@oxlint/binding-linux-arm-gnueabihf": ["@oxlint/binding-linux-arm-gnueabihf@1.56.0", "", { "os": "linux", "cpu": "arm" }, "sha512-YYHBsk/sl7fYwQOok+6W5lBPeUEvisznV/HZD2IfZmF3Bns6cPC3Z0vCtSEOaAWTjYWN3jVsdu55jMxKlsdlhg=="],
"@oxlint/binding-linux-arm-gnueabihf": ["@oxlint/[email protected]3.0", "", { "os": "linux", "cpu": "arm" }, "sha512-tYUtU9TdbU3uXF5D62g5zXJ13iniFGhXQx5vp9cyEjGdbSAY3VdFBSaldYvyoDmgMZ0ZYuwQP1Y4t2Fhejwa0w=="],
"@oxlint/binding-linux-arm-musleabihf": ["@oxlint/binding-linux-arm-musleabihf@1.56.0", "", { "os": "linux", "cpu": "arm" }, "sha512-+AZK8rOUr78y8WT6XkDb04IbMRqauNV+vgT6f8ZLOH8wnpQ9i7Nol0XLxAu+Cq7Sb+J9wC0j6Km5hG8rj47/yQ=="],
"@oxlint/binding-linux-arm-musleabihf": ["@oxlint/[email protected]3.0", "", { "os": "linux", "cpu": "arm" }, "sha512-I5r3twFf776UZg9dmRo2xbrKt00tTkORXEVe0ctg4vdTkQvJAjiCHxnbAU2HL1AiJ9cqADA76MAliuilsAWnvg=="],
"@oxlint/binding-linux-arm64-gnu": ["@oxlint/binding-linux-arm64-gnu@1.56.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-urse2SnugwJRojUkGSSeH2LPMaje5Q50yQtvtL9HFckiyeqXzoFwOAZqD5TR29R2lq7UHidfFDM9EGcchcbb8A=="],
"@oxlint/binding-linux-arm64-gnu": ["@oxlint/[email protected]3.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-t7ltUkg6FFh4b564QyGir8xIj/QZbXu8FlcRkcyW9+ztr/mfRHlvUOFd95pJCXi9s/L5DrUeWWgpXRS+V+6igQ=="],
"@oxlint/binding-linux-arm64-musl": ["@oxlint/binding-linux-arm64-musl@1.56.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-rkTZkBfJ4TYLjansjSzL6mgZOdN5IvUnSq3oNJSLwBcNvy3dlgQtpHPrRxrCEbbcp7oQ6If0tkNaqfOsphYZ9g=="],
"@oxlint/binding-linux-arm64-musl": ["@oxlint/[email protected]3.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-Q5mmZy/XWjuYFUuQyYjOvZ5U/JkKEwnpir6hGxhh6HcdP0V/BKxLo8dqkfF/t7r7AguB17dfS/8+go5AQDRR6g=="],
"@oxlint/binding-linux-ppc64-gnu": ["@oxlint/binding-linux-ppc64-gnu@1.56.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-uqL1kMH3u69/e1CH2EJhP3CP28jw2ExLsku4o8RVAZ7fySo9zOyI2fy9pVlTAp4voBLVgzndXi3SgtdyCTa2aA=="],
"@oxlint/binding-linux-ppc64-gnu": ["@oxlint/[email protected]3.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-uBGtuZ0TzLB4x5wVa82HGNvYqY8buwDhyCnCP0R0gkk9szqVsP0MeTtD5HX7EsEuFIt+aYmYxuxeVxs3nTSwtQ=="],
"@oxlint/binding-linux-riscv64-gnu": ["@oxlint/binding-linux-riscv64-gnu@1.56.0", "", { "os": "linux", "cpu": "none" }, "sha512-j0CcMBOgV6KsRaBdsebIeiy7hCjEvq2KdEsiULf2LZqAq0v1M1lWjelhCV57LxsqaIGChXFuFJ0RiFrSRHPhSg=="],
"@oxlint/binding-linux-riscv64-gnu": ["@oxlint/[email protected]3.0", "", { "os": "linux", "cpu": "none" }, "sha512-h4s6FwxE+9MeA181o0dnDwHP32Y/bG8EiB/vrD6Ib+AMt6haigDc/0bUtI/sLmQDBMJnUfaCmtSSrEAqjtEVrA=="],
"@oxlint/binding-linux-riscv64-musl": ["@oxlint/binding-linux-riscv64-musl@1.56.0", "", { "os": "linux", "cpu": "none" }, "sha512-7VDOiL8cDG3DQ/CY3yKjbV1c4YPvc4vH8qW09Vv+5ukq3l/Kcyr6XGCd5NvxUmxqDb2vjMpM+eW/4JrEEsUetA=="],
"@oxlint/binding-linux-riscv64-musl": ["@oxlint/[email protected]3.0", "", { "os": "linux", "cpu": "none" }, "sha512-2EaNcCBR8Mcjl5ARtuN3BdEpVkX7KpjSjMGZ/mJMIeaXgTtdz5ytg2VwygMSStA/k0ixfvZFoZOfjDEcouV5vQ=="],
"@oxlint/binding-linux-s390x-gnu": ["@oxlint/binding-linux-s390x-gnu@1.56.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-JGRpX0M+ikD3WpwJ7vKcHKV6Kg0dT52BW2Eu2BupXotYeqGXBrbY+QPkAyKO6MNgKozyTNaRh3r7g+VWgyAQYQ=="],
"@oxlint/binding-linux-s390x-gnu": ["@oxlint/[email protected]3.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-p4hlf/fd7TrYYl3QrWWD0GocqJefwMu3cHQhmi2FvEB/YOvFb5DZN3SMBaPi7B1TM5DeypkEtrVib674q1KKPg=="],
"@oxlint/binding-linux-x64-gnu": ["@oxlint/binding-linux-x64-gnu@1.56.0", "", { "os": "linux", "cpu": "x64" }, "sha512-dNaICPvtmuxFP/VbqdofrLqdS3bM/AKJN3LMJD52si44ea7Be1cBk6NpfIahaysG9Uo+L98QKddU9CD5L8UHnQ=="],
"@oxlint/binding-linux-x64-gnu": ["@oxlint/[email protected]3.0", "", { "os": "linux", "cpu": "x64" }, "sha512-Vgq9rkRVcPcjbcH+ihYTfpeR7vCXfqpd+z5ItTGc0yYUV59L5ceHYN1iV4H9bKGV7Rn5hkVc7x3mSvHegduENA=="],
"@oxlint/binding-linux-x64-musl": ["@oxlint/binding-linux-x64-musl@1.56.0", "", { "os": "linux", "cpu": "x64" }, "sha512-pF1vOtM+GuXmbklM1hV8WMsn6tCNPvkUzklj/Ej98JhlanbmA2RB1BILgOpwSuCTRTIYx2MXssmEyQQ90QF5aA=="],
"@oxlint/binding-linux-x64-musl": ["@oxlint/[email protected]3.0", "", { "os": "linux", "cpu": "x64" }, "sha512-3/Lkq/ncooA61rorrC+ZQed1Bc4VpGj+WnGsp58zmxKgvZ2vhreu+dcVyr3mX8NUpq7mfZ4gDDTou/yrF1Pd7A=="],
"@oxlint/binding-openharmony-arm64": ["@oxlint/binding-openharmony-arm64@1.56.0", "", { "os": "none", "cpu": "arm64" }, "sha512-bp8NQ4RE6fDIFLa4bdBiOA+TAvkNkg+rslR+AvvjlLTYXLy9/uKAYLQudaQouWihLD/hgkrXIKKzXi5IXOewwg=="],
"@oxlint/binding-openharmony-arm64": ["@oxlint/[email protected]3.0", "", { "os": "none", "cpu": "arm64" }, "sha512-0/EdD/6hDkx5Mfd769PTjvEM8mZ/6Dfukp1dBCL/2PjlIVGEtYdNZyok6ChqYPsT9JcFnlQnUeQzO0/1L/oC9w=="],
"@oxlint/binding-win32-arm64-msvc": ["@oxlint/binding-win32-arm64-msvc@1.56.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-PxT4OJDfMOQBzo3OlzFb9gkoSD+n8qSBxyVq2wQSZIHFQYGEqIRTo9M0ZStvZm5fdhMqaVYpOnJvH2hUMEDk/g=="],
"@oxlint/binding-win32-arm64-msvc": ["@oxlint/[email protected]3.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-wb0CUkN8ngwPiRQBjD1Cj0LsHeNvm+Xt6YBHDMtj2DVQVD6Oj8Ri7g6BD+KICf6LaBqZlmzOvy6nF9E/8yyGOg=="],
"@oxlint/binding-win32-ia32-msvc": ["@oxlint/binding-win32-ia32-msvc@1.56.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-PTRy6sIEPqy2x8PTP1baBNReN/BNEFmde0L+mYeHmjXE1Vlcc9+I5nsqENsB2yAm5wLkzPoTNCMY/7AnabT4/A=="],
"@oxlint/binding-win32-ia32-msvc": ["@oxlint/[email protected]3.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-BX5iq+ovdNlVYhSn5qPMUIT0uwAwt2lmEnCnzK+Gkhw4DovIvhGb96OFhV8yzQNUnQxn/xGkOR+X+BLrLDNm8w=="],
"@oxlint/binding-win32-x64-msvc": ["@oxlint/binding-win32-x64-msvc@1.56.0", "", { "os": "win32", "cpu": "x64" }, "sha512-ZHa0clocjLmIDr+1LwoWtxRcoYniAvERotvwKUYKhH41NVfl0Y4LNbyQkwMZzwDvKklKGvGZ5+DAG58/Ik47tQ=="],
"@oxlint/binding-win32-x64-msvc": ["@oxlint/[email protected]3.0", "", { "os": "win32", "cpu": "x64" }, "sha512-QeN/WELOfsXMeYwxvfgQrl6CbVftYUCZsGXHjXQd5Trccm8+i4gmtxaOui4xbJQaiDlviF8F3yLSBloQUeFsfA=="],
"@oxlint/plugins": ["@oxlint/[email protected]", "", {}, "sha512-vZAzaUQkwgdN62RHgPFzfCsiBI6SDJMUdUlBGpJK0V++UHCMUk7UeJseygOhE/wOUSgV3ccE4ORkgab3C3MC6g=="],
"@pierre/diffs": ["@pierre/[email protected]", "", { "dependencies": { "@pierre/theme": "0.0.28", "@shikijs/transformers": "^3.0.0", "diff": "8.0.3", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-lLi+3sLCm3QDd5/aLO9pw+WbF6UzhrkWm2oTZ5WZJTGemOyUNRJ4DDhcEKmVusu4C4bXx9Nssh6fF+wQcapb5w=="],
@@ -783,6 +801,8 @@
"@t3tools/marketing": ["@t3tools/marketing@workspace:apps/marketing"],
"@t3tools/oxlint-plugin-t3code": ["@t3tools/oxlint-plugin-t3code@workspace:oxlint-plugin-t3code"],
"@t3tools/scripts": ["@t3tools/scripts@workspace:scripts"],
"@t3tools/shared": ["@t3tools/shared@workspace:packages/shared"],
@@ -1639,7 +1659,7 @@
"oxfmt": ["[email protected]", "", { "dependencies": { "tinypool": "2.1.0" }, "optionalDependencies": { "@oxfmt/binding-android-arm-eabi": "0.40.0", "@oxfmt/binding-android-arm64": "0.40.0", "@oxfmt/binding-darwin-arm64": "0.40.0", "@oxfmt/binding-darwin-x64": "0.40.0", "@oxfmt/binding-freebsd-x64": "0.40.0", "@oxfmt/binding-linux-arm-gnueabihf": "0.40.0", "@oxfmt/binding-linux-arm-musleabihf": "0.40.0", "@oxfmt/binding-linux-arm64-gnu": "0.40.0", "@oxfmt/binding-linux-arm64-musl": "0.40.0", "@oxfmt/binding-linux-ppc64-gnu": "0.40.0", "@oxfmt/binding-linux-riscv64-gnu": "0.40.0", "@oxfmt/binding-linux-riscv64-musl": "0.40.0", "@oxfmt/binding-linux-s390x-gnu": "0.40.0", "@oxfmt/binding-linux-x64-gnu": "0.40.0", "@oxfmt/binding-linux-x64-musl": "0.40.0", "@oxfmt/binding-openharmony-arm64": "0.40.0", "@oxfmt/binding-win32-arm64-msvc": "0.40.0", "@oxfmt/binding-win32-ia32-msvc": "0.40.0", "@oxfmt/binding-win32-x64-msvc": "0.40.0" }, "bin": { "oxfmt": "bin/oxfmt" } }, "sha512-g0C3I7xUj4b4DcagevM9kgH6+pUHytikxUcn3/VUkvzTNaaXBeyZqb7IBsHwojeXm4mTBEC/aBjBTMVUkZwWUQ=="],
"oxlint": ["oxlint@1.56.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.56.0", "@oxlint/binding-android-arm64": "1.56.0", "@oxlint/binding-darwin-arm64": "1.56.0", "@oxlint/binding-darwin-x64": "1.56.0", "@oxlint/binding-freebsd-x64": "1.56.0", "@oxlint/binding-linux-arm-gnueabihf": "1.56.0", "@oxlint/binding-linux-arm-musleabihf": "1.56.0", "@oxlint/binding-linux-arm64-gnu": "1.56.0", "@oxlint/binding-linux-arm64-musl": "1.56.0", "@oxlint/binding-linux-ppc64-gnu": "1.56.0", "@oxlint/binding-linux-riscv64-gnu": "1.56.0", "@oxlint/binding-linux-riscv64-musl": "1.56.0", "@oxlint/binding-linux-s390x-gnu": "1.56.0", "@oxlint/binding-linux-x64-gnu": "1.56.0", "@oxlint/binding-linux-x64-musl": "1.56.0", "@oxlint/binding-openharmony-arm64": "1.56.0", "@oxlint/binding-win32-arm64-msvc": "1.56.0", "@oxlint/binding-win32-ia32-msvc": "1.56.0", "@oxlint/binding-win32-x64-msvc": "1.56.0" }, "peerDependencies": { "oxlint-tsgolint": ">=0.15.0" }, "optionalPeers": ["oxlint-tsgolint"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-Q+5Mj5PVaH/R6/fhMMFzw4dT+KPB+kQW4kaL8FOIq7tfhlnEVp6+3lcWqFruuTNlUo9srZUW3qH7Id4pskeR6g=="],
"oxlint": ["[email protected]3.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.63.0", "@oxlint/binding-android-arm64": "1.63.0", "@oxlint/binding-darwin-arm64": "1.63.0", "@oxlint/binding-darwin-x64": "1.63.0", "@oxlint/binding-freebsd-x64": "1.63.0", "@oxlint/binding-linux-arm-gnueabihf": "1.63.0", "@oxlint/binding-linux-arm-musleabihf": "1.63.0", "@oxlint/binding-linux-arm64-gnu": "1.63.0", "@oxlint/binding-linux-arm64-musl": "1.63.0", "@oxlint/binding-linux-ppc64-gnu": "1.63.0", "@oxlint/binding-linux-riscv64-gnu": "1.63.0", "@oxlint/binding-linux-riscv64-musl": "1.63.0", "@oxlint/binding-linux-s390x-gnu": "1.63.0", "@oxlint/binding-linux-x64-gnu": "1.63.0", "@oxlint/binding-linux-x64-musl": "1.63.0", "@oxlint/binding-openharmony-arm64": "1.63.0", "@oxlint/binding-win32-arm64-msvc": "1.63.0", "@oxlint/binding-win32-ia32-msvc": "1.63.0", "@oxlint/binding-win32-x64-msvc": "1.63.0" }, "peerDependencies": { "oxlint-tsgolint": ">=0.22.1" }, "optionalPeers": ["oxlint-tsgolint"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-9TGXetdjgIHOJ9OiReomP7nnrMkV9HxC1xM2ramJSLQpzxjsAJtQwa4wqkJN2f/uCrqZuJseFuSlWDdvcruveg=="],
"p-cancelable": ["[email protected]", "", {}, "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg=="],
+12
View File
@@ -0,0 +1,12 @@
import { definePlugin } from "@oxlint/plugins";
import noInlineSchemaCompile from "./rules/no-inline-schema-compile.ts";
export default definePlugin({
meta: {
name: "t3code",
},
rules: {
"no-inline-schema-compile": noInlineSchemaCompile,
},
});
+21
View File
@@ -0,0 +1,21 @@
{
"name": "@t3tools/oxlint-plugin-t3code",
"private": true,
"type": "module",
"scripts": {
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"@effect/platform-node": "catalog:",
"@oxlint/plugins": "^1.63.0",
"effect": "catalog:"
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"@types/bun": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
}
}
@@ -0,0 +1,83 @@
import { assert, describe } from "@effect/vitest";
import { createOxlintRuleHarness } from "../test/utils.ts";
const rule = createOxlintRuleHarness("t3code/no-inline-schema-compile");
describe("t3code/no-inline-schema-compile", () => {
rule.valid(
"allows schema compilers hoisted to module scope",
`
import { Schema } from "effect";
const User = Schema.Struct({ name: Schema.String });
const decodeUser = Schema.decodeUnknownEffect(User);
export const parseUser = (input: unknown) => decodeUser(input);
`,
);
rule.valid(
"allows factory helpers that return a precompiled decoder",
`
import { Schema } from "effect";
export const makeParser = <A, I>(schema: Schema.Codec<A, I>) => {
const decode = Schema.decodeUnknownEffect(schema);
return (input: unknown) => decode(input);
};
`,
);
rule.valid(
"allows schema construction helpers that use encode transformations",
`
import { Schema } from "effect";
export const makePrettyJson = <S extends Schema.Top>(schema: S) =>
Schema.fromJsonString(schema).pipe(
Schema.encode({
decode: Schema.String,
encode: Schema.String,
}),
);
`,
);
rule.valid(
"allows dynamic schema parameters that cannot be hoisted to module scope",
`
import { Schema } from "effect";
export const parseWith = <A, I>(schema: Schema.Codec<A, I>, input: unknown) =>
Schema.decodeUnknownEffect(schema)(input);
`,
);
rule.invalid(
"reports schema compilers inside function bodies",
`
import { Schema } from "effect";
const User = Schema.Struct({ name: Schema.String });
export const parseUser = (input: unknown) => Schema.decodeUnknownEffect(User)(input);
`,
(output) => {
assert.match(output, /Hoist Schema\.decodeUnknownEffect/);
},
);
rule.invalid(
"reports inline schema literals as high confidence findings",
`
import { Schema } from "effect";
export const parseUser = (input: unknown) =>
Schema.decodeUnknownEffect(Schema.Struct({ name: Schema.String }))(input);
`,
(output) => {
assert.match(output, /inline schema literal and the compiled function/);
},
);
});
@@ -0,0 +1,150 @@
import { defineRule } from "@oxlint/plugins";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { getPropertyName, isIdentifier, unwrapExpression } from "../utils.ts";
// Effect Schema decoder/encoder APIs allocate compiled functions. Keep them
// outside function bodies so hot paths do not rebuild compilers per call.
const COMPILER_METHODS = new Set<keyof typeof Schema>([
"is",
"asserts",
"decodeEffect",
"decodeExit",
"decodeOption",
"decodePromise",
"decodeSync",
"decodeUnknownExit",
"decodeUnknownEffect",
"decodeUnknownOption",
"decodeUnknownPromise",
"decodeUnknownSync",
"encodeExit",
"encodeEffect",
"encodeOption",
"encodePromise",
"encodeSync",
"encodeUnknownExit",
"encodeUnknownEffect",
"encodeUnknownOption",
"encodeUnknownPromise",
"encodeUnknownSync",
]);
const getSchemaCompilerMethod = (callee: unknown): Option.Option<string> => {
const expression = unwrapExpression(callee);
if (Option.isNone(expression) || expression.value.type !== "MemberExpression") {
return Option.none();
}
const object = unwrapExpression(expression.value.object);
if (!isIdentifier(object, "Schema")) return Option.none();
return Option.filter(getPropertyName(expression.value.property), (method) =>
COMPILER_METHODS.has(method as keyof typeof Schema),
);
};
const isStaticSchemaReference = (node: unknown): boolean => {
const expression = unwrapExpression(node);
if (Option.isNone(expression)) return false;
if (expression.value.type === "Identifier") {
const [firstChar] = expression.value.name;
return firstChar !== undefined && firstChar.toUpperCase() === firstChar;
}
return expression.value.type === "MemberExpression";
};
const isNestedStaticSchemaCall = (node: unknown): boolean => {
const expression = unwrapExpression(node);
if (Option.isNone(expression) || expression.value.type !== "CallExpression") return false;
const callee = unwrapExpression(expression.value.callee);
if (Option.isNone(callee) || callee.value.type !== "MemberExpression") return false;
const object = unwrapExpression(callee.value.object);
if (!isIdentifier(object, "Schema")) return false;
const method = getPropertyName(callee.value.property);
if (Option.isSome(method) && method.value === "fromJsonString") {
const firstArg = expression.value.arguments[0];
return isStaticSchemaReference(firstArg) || isNestedStaticSchemaCall(firstArg);
}
return true;
};
const isImmediatelyInvoked = (node: unknown): boolean => {
const expression = unwrapExpression(node);
if (Option.isNone(expression)) return false;
const parent =
"parent" in expression.value ? unwrapExpression(expression.value.parent) : Option.none();
return (
Option.isSome(parent) &&
parent.value.type === "CallExpression" &&
unwrapExpression(parent.value.callee).pipe(
Option.exists((callee) => callee === expression.value),
)
);
};
const messageHigh = (method: string) =>
`Hoist Schema.${method}(...) to module scope: both the inline schema literal and the compiled function are rebuilt on every call. Move the compiled function to a module-level const.`;
const messageMedium = (method: string) =>
`Hoist Schema.${method}(...) to module scope: the compiled function is rebuilt on every call. Move it to a module-level const.`;
export default defineRule({
meta: {
type: "problem",
docs: {
description:
"Disallow Schema decoder/encoder compiler calls inside function bodies; hoist them to module scope.",
},
},
createOnce(context) {
let functionDepth = 0;
const resetFunctionDepth = () => {
functionDepth = 0;
};
const enterFunction = () => {
functionDepth++;
};
const exitFunction = () => {
functionDepth--;
};
return {
before: resetFunctionDepth,
FunctionDeclaration: enterFunction,
"FunctionDeclaration:exit": exitFunction,
FunctionExpression: enterFunction,
"FunctionExpression:exit": exitFunction,
ArrowFunctionExpression: enterFunction,
"ArrowFunctionExpression:exit": exitFunction,
CallExpression(node) {
if (functionDepth === 0) return;
const method = getSchemaCompilerMethod(node.callee);
if (Option.isNone(method)) return;
if (!isImmediatelyInvoked(node)) return;
const firstArg = node.arguments[0];
const high = firstArg && isNestedStaticSchemaCall(firstArg);
if (!high && !isStaticSchemaReference(firstArg)) return;
context.report({
node: node.callee,
message: high ? messageHigh(method.value) : messageMedium(method.value),
});
},
};
},
});
+152
View File
@@ -0,0 +1,152 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Predicate from "effect/Predicate";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
class OxlintFixtureFailure extends Data.TaggedError("OxlintFixtureFailure")<{
readonly exitCode: number;
readonly stdout: string;
readonly stderr: string;
}> {
static readonly is = (u: unknown): u is OxlintFixtureFailure =>
Predicate.isTagged(u, "OxlintFixtureFailure");
}
class OxlintFixtureExpectedFailure extends Data.TaggedError("OxlintFixtureExpectedFailure")<{
readonly ruleName: string;
}> {
override get message() {
return `Expected oxlint to report a failure for rule ${this.ruleName}, but it passed.`;
}
}
const encodeOxlintConfig = Schema.encodeEffect(Schema.UnknownFromJsonString);
interface RuleHarness {
readonly run: (
source: string,
) => Effect.Effect<
string,
OxlintFixtureFailure | PlatformError.PlatformError | Schema.SchemaError,
NodeServices.NodeServices
>;
readonly runAndExpectFailure: (
source: string,
) => Effect.Effect<
string,
OxlintFixtureExpectedFailure | PlatformError.PlatformError | Schema.SchemaError,
NodeServices.NodeServices
>;
readonly valid: (name: string, source: string) => void;
readonly invalid: (name: string, source: string, assertion?: (output: string) => void) => void;
}
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
stream.pipe(
Stream.decodeText(),
Stream.runFold(
() => "",
(acc, chunk) => acc + chunk,
),
);
const spawnAndCollectOutput = Effect.fnUntraced(function* (command: ChildProcess.Command) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const child = yield* spawner.spawn(command);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectStreamAsString(child.stdout),
collectStreamAsString(child.stderr),
child.exitCode.pipe(Effect.map(Number)),
],
{ concurrency: "unbounded" },
);
return { exitCode, stdout, stderr };
}, Effect.scoped);
export const createOxlintRuleHarness = (ruleName: string): RuleHarness => {
const [pluginName, shortRuleName] = ruleName.split("/");
const diagnosticRuleName =
pluginName && shortRuleName ? `${pluginName}\\(${shortRuleName}\\)` : ruleName;
const test = it.layer(NodeServices.layer);
const run: RuleHarness["run"] = Effect.fnUntraced(function* (source: string) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const fixtureDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-oxlint-" });
const configPath = path.join(fixtureDir, ".oxlintrc.json");
const sourcePath = path.join(fixtureDir, "fixture.ts");
const repoRoot = path.join(import.meta.dirname, "..", "..");
const oxlintBin = path.join(repoRoot, "node_modules", ".bin", "oxlint");
const pluginPath = path.join(repoRoot, "oxlint-plugin-t3code", "index.ts");
yield* fs.writeFileString(
configPath,
yield* encodeOxlintConfig({
jsPlugins: [{ name: "t3code", specifier: pluginPath }],
rules: { [ruleName]: "error" },
}),
);
yield* fs.writeFileString(sourcePath, source);
const output = yield* spawnAndCollectOutput(
ChildProcess.make(oxlintBin, ["--config", configPath, sourcePath], { cwd: repoRoot }),
);
if (output.exitCode !== 0) {
return yield* new OxlintFixtureFailure({
exitCode: output.exitCode,
stdout: output.stdout,
stderr: output.stderr,
});
}
return `${output.stdout}${output.stderr}`;
}, Effect.scoped);
const runAndExpectFailure: RuleHarness["runAndExpectFailure"] = (source) =>
run(source).pipe(
Effect.matchEffect({
onFailure: (error) =>
OxlintFixtureFailure.is(error)
? Effect.succeed(
`oxlint fixture failed with exit code ${error.exitCode}\n${error.stdout}\n${error.stderr}`,
)
: Effect.fail(error),
onSuccess: () => Effect.fail(new OxlintFixtureExpectedFailure({ ruleName })),
}),
);
return {
run,
runAndExpectFailure,
valid(name, source) {
test(name, (it) => {
it.effect("passes", () => run(source));
});
},
invalid(name, source, assertion) {
test(name, (it) => {
it.effect("reports the rule diagnostic", () =>
runAndExpectFailure(source).pipe(
Effect.tap((output) =>
Effect.sync(() => {
assert.match(output, new RegExp(diagnosticRuleName));
assertion?.(output);
}),
),
),
);
});
},
};
};
+9
View File
@@ -0,0 +1,9 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"types": ["bun", "node"],
"lib": ["ESNext", "esnext.disposable"]
},
"include": ["**/*.ts"]
}
+58
View File
@@ -0,0 +1,58 @@
import type { ESTree } from "@oxlint/plugins";
import * as Option from "effect/Option";
type ExpressionWrapper =
| ESTree.ChainExpression
| ESTree.ParenthesizedExpression
| ESTree.TSNonNullExpression
| ESTree.TSAsExpression
| ESTree.TSTypeAssertion;
type AstNode = ESTree.Node;
const asAstNode = (node: unknown): Option.Option<AstNode> =>
typeof node === "object" && node !== null && "type" in node && typeof node.type === "string"
? Option.some(node as AstNode)
: Option.none();
const isExpressionWrapper = (node: AstNode): node is ExpressionWrapper =>
node.type === "ChainExpression" ||
node.type === "ParenthesizedExpression" ||
node.type === "TSNonNullExpression" ||
node.type === "TSAsExpression" ||
node.type === "TSTypeAssertion";
export function unwrapExpression(node: unknown): Option.Option<AstNode> {
let current = asAstNode(node);
while (Option.isSome(current) && isExpressionWrapper(current.value)) {
current = asAstNode(current.value.expression);
}
return current;
}
export function getPropertyName(node: unknown): Option.Option<string> {
return Option.flatMap(asAstNode(node), (expression) => {
if (expression.type === "Identifier" && typeof expression.name === "string") {
return Option.some(expression.name);
}
if (expression.type === "PrivateIdentifier" && typeof expression.name === "string") {
return Option.some(expression.name);
}
if (expression.type === "Literal" && typeof expression.value === "string") {
return Option.some(expression.value);
}
return Option.none();
});
}
export function isIdentifier(node: Option.Option<AstNode>, name?: string): boolean {
if (Option.isNone(node)) return false;
const expression = node.value;
return (
expression.type === "Identifier" &&
typeof expression.name === "string" &&
(name === undefined || expression.name === name)
);
}
+3 -1
View File
@@ -4,6 +4,7 @@
"workspaces": {
"packages": [
"apps/*",
"oxlint-plugin-t3code",
"packages/*",
"scripts"
],
@@ -61,9 +62,10 @@
},
"devDependencies": {
"@effect/language-service": "catalog:",
"@oxlint/plugins": "^1.63.0",
"@types/node": "catalog:",
"oxfmt": "^0.40.0",
"oxlint": "^1.55.0",
"oxlint": "^1.63.0",
"turbo": "^2.3.3",
"typescript": "catalog:",
"vitest": "catalog:"
+2 -1
View File
@@ -38,6 +38,7 @@ const decodeThreadTurnStartRequestedPayload = Schema.decodeUnknownEffect(
const decodeOrchestrationLatestTurn = Schema.decodeUnknownEffect(OrchestrationLatestTurn);
const decodeOrchestrationProposedPlan = Schema.decodeUnknownEffect(OrchestrationProposedPlan);
const decodeOrchestrationSession = Schema.decodeUnknownEffect(OrchestrationSession);
const encodeThreadCreatedPayload = Schema.encodeEffect(ThreadCreatedPayload);
function getOptionValue(
options: ReadonlyArray<{ id: string; value: unknown }> | undefined,
@@ -485,7 +486,7 @@ it.effect(
updatedAt: "2026-01-01T00:00:00.000Z",
});
const encoded = yield* Schema.encodeEffect(ThreadCreatedPayload)(decoded);
const encoded = yield* encodeThreadCreatedPayload(decoded);
assert.deepStrictEqual(encoded.modelSelection.options, [{ id: "fastMode", value: true }]);
}),
);
+1
View File
@@ -279,6 +279,7 @@ export const CursorSettings = makeProviderSettingsSchema(
},
);
export type CursorSettings = typeof CursorSettings.Type;
export const OpenCodeSettings = makeProviderSettingsSchema(
{
enabled: Schema.Boolean.pipe(
+21 -13
View File
@@ -28,15 +28,24 @@ interface GeneratedPaths {
readonly metaOutputPath: string;
}
const UpstreamJsonSchemaSchema = Schema.Struct({
$defs: Schema.Record(Schema.String, Schema.Json),
});
const MetaJsonSchema = Schema.Struct({
agentMethods: Schema.Record(Schema.String, Schema.String),
clientMethods: Schema.Record(Schema.String, Schema.String),
version: Schema.Union([Schema.Number, Schema.String]),
});
const encodeAgentMethods = Schema.encodeEffect(
Schema.fromJsonString(MetaJsonSchema.fields.agentMethods),
);
const encodeClientMethods = Schema.encodeEffect(
Schema.fromJsonString(MetaJsonSchema.fields.clientMethods),
);
const encodeVersion = Schema.encodeEffect(Schema.fromJsonString(MetaJsonSchema.fields.version));
const UpstreamJsonSchemaSchema = Schema.Struct({
$defs: Schema.Record(Schema.String, Schema.Json),
});
const decodeUpstreamSchema = Schema.decodeEffect(Schema.fromJsonString(UpstreamJsonSchemaSchema));
const decodeMetaJson = Schema.decodeEffect(Schema.fromJsonString(MetaJsonSchema));
const getGeneratedPaths = Effect.fn("getGeneratedPaths")(function* () {
const path = yield* Path.Path;
@@ -86,12 +95,9 @@ const downloadSchemas = Effect.fn("downloadSchemas")(function* (tag: string) {
);
});
const readJsonFile = Effect.fn("readJsonFile")(function* <
S extends Schema.Top & { readonly DecodingServices: never },
>(schema: S, filePath: string) {
const readFileString = Effect.fn("readJsonFile")(function* (filePath: string) {
const fs = yield* FileSystem.FileSystem;
const raw = yield* fs.readFileString(filePath);
return yield* Schema.decodeEffect(Schema.fromJsonString(schema))(raw);
return yield* fs.readFileString(filePath);
});
const writeGeneratedFiles = Effect.fn("writeGeneratedFiles")(function* (
@@ -201,8 +207,10 @@ const generateSchemas = Effect.fn("generateSchemas")(function* (skipDownload: bo
yield* downloadSchemas(CURRENT_SCHEMA_RELEASE);
}
const upstreamSchema = yield* readJsonFile(UpstreamJsonSchemaSchema, upstreamSchemaPath);
const upstreamMeta = yield* readJsonFile(MetaJsonSchema, upstreamMetaPath);
const upstreamSchema = yield* readFileString(upstreamSchemaPath).pipe(
Effect.flatMap(decodeUpstreamSchema),
);
const upstreamMeta = yield* readFileString(upstreamMetaPath).pipe(Effect.flatMap(decodeMetaJson));
const normalizedDefinitions = Object.fromEntries(
Object.entries(upstreamSchema.$defs).map(([name, schema]) => [
name,
@@ -245,11 +253,11 @@ const generateSchemas = Effect.fn("generateSchemas")(function* (skipDownload: bo
const metaOutput = [
...prelude,
`export const AGENT_METHODS = ${yield* Schema.encodeEffect(Schema.fromJsonString(MetaJsonSchema.fields.agentMethods))(upstreamMeta.agentMethods)} as const;`,
`export const AGENT_METHODS = ${yield* encodeAgentMethods(upstreamMeta.agentMethods)} as const;`,
"",
`export const CLIENT_METHODS = ${yield* Schema.encodeEffect(Schema.fromJsonString(MetaJsonSchema.fields.clientMethods))(upstreamMeta.clientMethods)} as const;`,
`export const CLIENT_METHODS = ${yield* encodeClientMethods(upstreamMeta.clientMethods)} as const;`,
"",
`export const PROTOCOL_VERSION = ${yield* Schema.encodeEffect(Schema.fromJsonString(MetaJsonSchema.fields.version))(upstreamMeta.version)} as const;`,
`export const PROTOCOL_VERSION = ${yield* encodeVersion(upstreamMeta.version)} as const;`,
"",
].join("\n");
+4 -2
View File
@@ -5,6 +5,8 @@ import { RpcClientError } from "effect/unstable/rpc";
import * as AcpSchema from "../_generated/schema.gen.ts";
import * as AcpError from "../errors.ts";
const isError = Schema.is(AcpSchema.Error);
const isAcpRequestError = Schema.is(AcpError.AcpRequestError);
const formatSchemaIssue = SchemaIssue.makeFormatterDefault();
@@ -20,7 +22,7 @@ export const callRpc = <A>(
}),
),
),
Effect.catchIf(Schema.is(AcpSchema.Error), (error) =>
Effect.catchIf(isError, (error) =>
Effect.fail(AcpError.AcpRequestError.fromProtocolError(error)),
),
);
@@ -35,7 +37,7 @@ export const runHandler = Effect.fnUntraced(function* <A, B>(
}
return yield* handler(payload).pipe(
Effect.mapError((error) =>
Schema.is(AcpError.AcpRequestError)(error)
isAcpRequestError(error)
? error.toProtocolError()
: AcpError.AcpRequestError.internalError(error.message).toProtocolError(),
),
+6 -6
View File
@@ -34,6 +34,10 @@ const SessionCancelNotification = jsonRpcNotification(
const ExtPingNotification = jsonRpcNotification("x/ping", Schema.Struct({ count: Schema.Number }));
const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
const decodeRequestPermissionRequest = Schema.decodeEffect(
Schema.fromJsonString(RequestPermissionRequest),
);
const decodeInitializeResponse = Schema.decodeEffect(Schema.fromJsonString(InitializeResponse));
it.effect("effect-acp agent handles core agent requests and outbound client requests", () =>
Effect.gen(function* () {
@@ -83,9 +87,7 @@ it.effect("effect-acp agent handles core agent requests and outbound client requ
})
.pipe(Effect.forkScoped);
const permissionRequest = yield* Schema.decodeEffect(
Schema.fromJsonString(RequestPermissionRequest),
)(yield* Queue.take(output));
const permissionRequest = yield* decodeRequestPermissionRequest(yield* Queue.take(output));
assert.equal(permissionRequest.jsonrpc, "2.0");
assert.equal(permissionRequest.method, "session/request_permission");
assert.deepEqual(permissionRequest.params, {
@@ -136,9 +138,7 @@ it.effect("effect-acp agent handles core agent requests and outbound client requ
}),
);
const initResponse = yield* Schema.decodeEffect(Schema.fromJsonString(InitializeResponse))(
yield* Queue.take(output),
);
const initResponse = yield* decodeInitializeResponse(yield* Queue.take(output));
assert.deepEqual(initResponse, {
jsonrpc: "2.0",
id: 2,
+23 -22
View File
@@ -41,6 +41,13 @@ const RequestPermissionRequest = jsonRpcRequest(
const RequestPermissionResponse = jsonRpcResponse(AcpSchema.RequestPermissionResponse);
const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
const decodeSessionCancelNotification = Schema.decodeEffect(
Schema.fromJsonString(SessionCancelNotification),
);
const decodeExtRequest = Schema.decodeEffect(Schema.fromJsonString(ExtRequest));
const decodeRequestPermissionResponse = Schema.decodeEffect(
Schema.fromJsonString(RequestPermissionResponse),
);
const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) =>
path.join(import.meta.dirname, "../test/fixtures/acp-mock-peer.ts"),
);
@@ -79,16 +86,13 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
yield* transport.notify("session/cancel", { sessionId: "session-1" });
const outbound = yield* Queue.take(output);
assert.deepEqual(
yield* Schema.decodeEffect(Schema.fromJsonString(SessionCancelNotification))(outbound),
{
jsonrpc: "2.0",
method: "session/cancel",
params: {
sessionId: "session-1",
},
assert.deepEqual(yield* decodeSessionCancelNotification(outbound), {
jsonrpc: "2.0",
method: "session/cancel",
params: {
sessionId: "session-1",
},
);
});
yield* Queue.offer(
input,
@@ -200,7 +204,7 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
.request("x/test", { hello: "world" })
.pipe(Effect.forkScoped);
const outbound = yield* Queue.take(output);
assert.deepEqual(yield* Schema.decodeEffect(Schema.fromJsonString(ExtRequest))(outbound), {
assert.deepEqual(yield* decodeExtRequest(outbound), {
jsonrpc: "2.0",
id: 1,
method: "x/test",
@@ -288,19 +292,16 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
});
const outbound = yield* Queue.take(output);
assert.deepEqual(
yield* Schema.decodeEffect(Schema.fromJsonString(RequestPermissionResponse))(outbound),
{
jsonrpc: "2.0",
id: 0,
result: {
outcome: {
outcome: "selected",
optionId: "allow",
},
assert.deepEqual(yield* decodeRequestPermissionResponse(outbound), {
jsonrpc: "2.0",
id: 0,
result: {
outcome: {
outcome: "selected",
optionId: "allow",
},
},
);
});
}),
);
@@ -321,7 +322,7 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
.request("x/test", { hello: "world" })
.pipe(Effect.forkScoped);
const outbound = yield* Queue.take(output);
assert.deepEqual(yield* Schema.decodeEffect(Schema.fromJsonString(ExtRequest))(outbound), {
assert.deepEqual(yield* decodeExtRequest(outbound), {
jsonrpc: "2.0",
id: 1,
method: "x/test",
+4 -4
View File
@@ -16,6 +16,8 @@ import * as RpcServer from "effect/unstable/rpc/RpcServer";
import * as AcpSchema from "./_generated/schema.gen.ts";
import { CLIENT_METHODS } from "./_generated/meta.gen.ts";
import * as AcpError from "./errors.ts";
const isAcpError = Schema.is(AcpError.AcpError);
const isAcpRequestError = Schema.is(AcpError.AcpRequestError);
export interface AcpProtocolLogEvent {
readonly direction: "incoming" | "outgoing";
@@ -408,7 +410,7 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
),
Effect.matchEffect({
onFailure: (error) => {
const normalized: AcpError.AcpError = Schema.is(AcpError.AcpError)(error)
const normalized: AcpError.AcpError = isAcpError(error)
? error
: new AcpError.AcpTransportError({
detail: error instanceof Error ? error.message : String(error),
@@ -521,9 +523,7 @@ function isProtocolError(
}
function normalizeToRequestError(error: AcpError.AcpError): AcpError.AcpRequestError {
return Schema.is(AcpError.AcpRequestError)(error)
? error
: AcpError.AcpRequestError.internalError(error.message);
return isAcpRequestError(error) ? error : AcpError.AcpRequestError.internalError(error.message);
}
function toRpcClientError(error: AcpError.AcpError): RpcClientError.RpcClientError {
@@ -38,6 +38,8 @@ const JsonSchemaDocument = Schema.StructWithRest(
}),
[Schema.Record(Schema.String, Schema.Json)],
);
const decodeGithubContentEntries = Schema.decodeEffect(Schema.fromJsonString(GithubContentEntries));
const decodeJsonSchemaDocument = Schema.decodeEffect(Schema.fromJsonString(JsonSchemaDocument));
interface GeneratedPaths {
readonly generatedDir: string;
@@ -178,7 +180,7 @@ const fetchText = Effect.fn("fetchText")(function* (url: string) {
const fetchDirectoryEntries = Effect.fn("fetchDirectoryEntries")(function* (path: string) {
const raw = yield* fetchText(`${GITHUB_API_BASE}/${path}?ref=${UPSTREAM_REF}`);
return yield* Schema.decodeEffect(Schema.fromJsonString(GithubContentEntries))(raw);
return yield* decodeGithubContentEntries(raw);
});
function collectSchemaEntries(
@@ -545,7 +547,7 @@ const generateFiles = Effect.fn("generateFiles")(function* () {
for (const file of jsonSchemaFiles) {
const raw = yield* fetchText(file.downloadUrl);
const parsed = yield* Schema.decodeEffect(Schema.fromJsonString(JsonSchemaDocument))(raw);
const parsed = yield* decodeJsonSchemaDocument(raw);
const localDefinitionNames = new Map(
Object.keys(parsed.definitions ?? {}).map((definitionName) => [
definitionName,
@@ -143,9 +143,10 @@ export const CodexAppServerError = Schema.Union([
]);
export type CodexAppServerError = typeof CodexAppServerError.Type;
const isCodexAppServerRequestError = Schema.is(CodexAppServerRequestError);
export function normalizeToRequestError(error: CodexAppServerError): CodexAppServerRequestError {
return Schema.is(CodexAppServerRequestError)(error)
return isCodexAppServerRequestError(error)
? error
: CodexAppServerRequestError.internalError(error.message);
}
@@ -11,11 +11,11 @@ import { assert, it } from "@effect/vitest";
import * as CodexError from "./errors.ts";
import * as CodexProtocol from "./protocol.ts";
import { makeInMemoryStdio } from "./_internal/stdio.ts";
const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
const encoder = new TextEncoder();
const encodeJsonl = (value: unknown) =>
encoder.encode(`${Schema.encodeUnknownSync(Schema.UnknownFromJsonString)(value)}\n`);
const encodeJsonl = (value: unknown) => encoder.encode(`${encodeUnknownJsonString(value)}\n`);
const decodeJson = Schema.decodeEffect(Schema.UnknownFromJsonString);
@@ -10,6 +10,9 @@ import * as Stream from "effect/Stream";
import * as CodexError from "./errors.ts";
import { JsonRpcId, JsonRpcResponseEnvelope } from "./_internal/shared.ts";
const isJsonRpcId = Schema.is(JsonRpcId);
const isJsonRpcResponseEnvelope = Schema.is(JsonRpcResponseEnvelope);
const isCodexAppServerError = Schema.is(CodexError.CodexAppServerError);
export interface CodexAppServerProtocolLogEvent {
readonly direction: "incoming" | "outgoing";
@@ -72,7 +75,7 @@ function isIncomingRequest(value: unknown): value is CodexAppServerIncomingReque
if (!isObject(value) || typeof value.method !== "string") {
return false;
}
return Schema.is(JsonRpcId)(value.id);
return isJsonRpcId(value.id);
}
function isIncomingNotification(value: unknown): value is CodexAppServerIncomingNotification {
@@ -80,7 +83,7 @@ function isIncomingNotification(value: unknown): value is CodexAppServerIncoming
}
function isIncomingResponse(value: unknown): value is typeof JsonRpcResponseEnvelope.Type {
return Schema.is(JsonRpcResponseEnvelope)(value);
return isJsonRpcResponseEnvelope(value);
}
const encodeJsonString = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
@@ -114,7 +117,7 @@ const decodeWireMessage = (
);
const normalizeIncomingError = (error: unknown, detail: string): CodexError.CodexAppServerError =>
Schema.is(CodexError.CodexAppServerError)(error)
isCodexAppServerError(error)
? error
: new CodexError.CodexAppServerTransportError({
detail,
+164 -159
View File
@@ -80,6 +80,8 @@ const makeTestLayer = (tracePath: string) =>
Layer.succeed(References.MinimumLogLevel, "Info"),
);
const nodeServicesIt = it.layer(NodeServices.layer);
describe("observability", () => {
it("normalizes circular arrays, maps, and sets without recursing forever", () => {
const array: Array<unknown> = ["alpha"];
@@ -118,191 +120,194 @@ describe("observability", () => {
);
});
it.effect("flushes buffered trace records on close", () =>
Effect.scoped(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
const tracePath = path.join(tempDir, "shared.trace.ndjson");
nodeServicesIt("node services", (it) => {
it.effect("flushes buffered trace records on close", () =>
Effect.scoped(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
const tracePath = path.join(tempDir, "shared.trace.ndjson");
const sink = yield* makeTraceSink({
filePath: tracePath,
maxBytes: 1024,
maxFiles: 2,
batchWindowMs: 10_000,
});
const sink = yield* makeTraceSink({
filePath: tracePath,
maxBytes: 1024,
maxFiles: 2,
batchWindowMs: 10_000,
});
sink.push(makeRecord("alpha"));
sink.push(makeRecord("beta"));
yield* sink.close();
sink.push(makeRecord("alpha"));
sink.push(makeRecord("beta"));
yield* sink.close();
const lines = yield* readTraceRecords(tracePath);
const lines = yield* readTraceRecords(tracePath);
assert.equal(lines.length, 2);
assert.equal(lines[0]?.name, "alpha");
assert.equal(lines[1]?.name, "beta");
}).pipe(Effect.provide(NodeServices.layer)),
),
);
assert.equal(lines.length, 2);
assert.equal(lines[0]?.name, "alpha");
assert.equal(lines[1]?.name, "beta");
}),
),
);
it.effect("rotates the trace file when the configured max size is exceeded", () =>
Effect.scoped(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
const tracePath = path.join(tempDir, "shared.trace.ndjson");
it.effect("rotates the trace file when the configured max size is exceeded", () =>
Effect.scoped(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
const tracePath = path.join(tempDir, "shared.trace.ndjson");
const sink = yield* makeTraceSink({
filePath: tracePath,
maxBytes: 180,
maxFiles: 2,
batchWindowMs: 10_000,
});
const sink = yield* makeTraceSink({
filePath: tracePath,
maxBytes: 180,
maxFiles: 2,
batchWindowMs: 10_000,
});
for (let index = 0; index < 8; index += 1) {
sink.push(makeRecord("rotate", `${index}-${"x".repeat(48)}`));
yield* sink.flush;
}
yield* sink.close();
for (let index = 0; index < 8; index += 1) {
sink.push(makeRecord("rotate", `${index}-${"x".repeat(48)}`));
yield* sink.flush;
}
yield* sink.close();
const matchingFiles = (yield* fileSystem.readDirectory(tempDir))
.filter(
(entry) => entry === "shared.trace.ndjson" || entry.startsWith("shared.trace.ndjson."),
)
.toSorted();
const matchingFiles = (yield* fileSystem.readDirectory(tempDir))
.filter(
(entry) =>
entry === "shared.trace.ndjson" || entry.startsWith("shared.trace.ndjson."),
)
.toSorted();
assert.equal(
matchingFiles.some((entry) => entry === "shared.trace.ndjson.1"),
true,
);
assert.equal(
matchingFiles.some((entry) => entry === "shared.trace.ndjson.3"),
false,
);
}).pipe(Effect.provide(NodeServices.layer)),
),
);
assert.equal(
matchingFiles.some((entry) => entry === "shared.trace.ndjson.1"),
true,
);
assert.equal(
matchingFiles.some((entry) => entry === "shared.trace.ndjson.3"),
false,
);
}),
),
);
it.effect("drops only the invalid trace record when serialization fails", () =>
Effect.scoped(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
const tracePath = path.join(tempDir, "shared.trace.ndjson");
it.effect("drops only the invalid trace record when serialization fails", () =>
Effect.scoped(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
const tracePath = path.join(tempDir, "shared.trace.ndjson");
const sink = yield* makeTraceSink({
filePath: tracePath,
maxBytes: 1024,
maxFiles: 2,
batchWindowMs: 10_000,
});
const sink = yield* makeTraceSink({
filePath: tracePath,
maxBytes: 1024,
maxFiles: 2,
batchWindowMs: 10_000,
});
const circular: Array<unknown> = [];
circular.push(circular);
const circular: Array<unknown> = [];
circular.push(circular);
sink.push(makeRecord("alpha"));
sink.push({
...makeRecord("invalid"),
attributes: {
circular,
},
} as TraceRecord);
sink.push(makeRecord("beta"));
yield* sink.close();
sink.push(makeRecord("alpha"));
sink.push({
...makeRecord("invalid"),
attributes: {
circular,
},
} as TraceRecord);
sink.push(makeRecord("beta"));
yield* sink.close();
const lines = yield* readTraceRecords(tracePath);
const lines = yield* readTraceRecords(tracePath);
assert.deepStrictEqual(
lines.map((line) => line.name),
["alpha", "beta"],
);
}).pipe(Effect.provide(NodeServices.layer)),
),
);
assert.deepStrictEqual(
lines.map((line) => line.name),
["alpha", "beta"],
);
}),
),
);
it.effect("writes nested spans to disk and captures log messages as span events", () =>
Effect.scoped(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
const tracePath = path.join(tempDir, "shared.trace.ndjson");
it.effect("writes nested spans to disk and captures log messages as span events", () =>
Effect.scoped(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
const tracePath = path.join(tempDir, "shared.trace.ndjson");
yield* Effect.scoped(
Effect.gen(function* () {
const program = Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({
"demo.parent": true,
});
yield* Effect.logInfo("parent event");
yield* Effect.gen(function* () {
yield* Effect.scoped(
Effect.gen(function* () {
const program = Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({
"demo.child": true,
"demo.parent": true,
});
yield* Effect.logInfo("child event");
}).pipe(Effect.withSpan("child-span"));
}).pipe(Effect.withSpan("parent-span"));
yield* Effect.logInfo("parent event");
yield* Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({
"demo.child": true,
});
yield* Effect.logInfo("child event");
}).pipe(Effect.withSpan("child-span"));
}).pipe(Effect.withSpan("parent-span"));
yield* program.pipe(Effect.provide(makeTestLayer(tracePath)));
}),
);
yield* program.pipe(Effect.provide(makeTestLayer(tracePath)));
}),
);
const records = yield* readTraceRecords(tracePath);
assert.equal(records.length, 2);
const records = yield* readTraceRecords(tracePath);
assert.equal(records.length, 2);
const parent = records.find((record) => record.name === "parent-span");
const child = records.find((record) => record.name === "child-span");
const parent = records.find((record) => record.name === "parent-span");
const child = records.find((record) => record.name === "child-span");
assert.notEqual(parent, undefined);
assert.notEqual(child, undefined);
if (!parent || !child) {
return;
}
assert.notEqual(parent, undefined);
assert.notEqual(child, undefined);
if (!parent || !child) {
return;
}
assert.equal(child.parentSpanId, parent.spanId);
assert.equal(parent.attributes["demo.parent"], true);
assert.equal(child.attributes["demo.child"], true);
assert.equal(
parent.events.some((event) => event.name === "parent event"),
true,
);
assert.equal(
child.events.some((event) => event.name === "child event"),
true,
);
assert.equal(
child.events.some((event) => event.attributes["effect.logLevel"] === "INFO"),
true,
);
}).pipe(Effect.provide(NodeServices.layer)),
),
);
assert.equal(child.parentSpanId, parent.spanId);
assert.equal(parent.attributes["demo.parent"], true);
assert.equal(child.attributes["demo.child"], true);
assert.equal(
parent.events.some((event) => event.name === "parent event"),
true,
);
assert.equal(
child.events.some((event) => event.name === "child event"),
true,
);
assert.equal(
child.events.some((event) => event.attributes["effect.logLevel"] === "INFO"),
true,
);
}),
),
);
it.effect("serializes interrupted spans with an interrupted exit status", () =>
Effect.scoped(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
const tracePath = path.join(tempDir, "shared.trace.ndjson");
it.effect("serializes interrupted spans with an interrupted exit status", () =>
Effect.scoped(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
const tracePath = path.join(tempDir, "shared.trace.ndjson");
yield* Effect.scoped(
Effect.exit(
Effect.interrupt.pipe(
Effect.withSpan("interrupt-span"),
Effect.provide(makeTestLayer(tracePath)),
yield* Effect.scoped(
Effect.exit(
Effect.interrupt.pipe(
Effect.withSpan("interrupt-span"),
Effect.provide(makeTestLayer(tracePath)),
),
),
),
);
);
const records = yield* readTraceRecords(tracePath);
assert.equal(records.length, 1);
assert.equal(records[0]?.name, "interrupt-span");
assert.equal(records[0]?.exit?._tag, "Interrupted");
}).pipe(Effect.provide(NodeServices.layer)),
),
);
const records = yield* readTraceRecords(tracePath);
assert.equal(records.length, 1);
assert.equal(records[0]?.name, "interrupt-span");
assert.equal(records[0]?.exit?._tag, "Interrupted");
}),
),
);
});
});
+11
View File
@@ -84,6 +84,17 @@ export const fromLenientJsonString = new SchemaTransformation.Transformation(
SchemaGetter.stringifyJson(),
);
const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.UnknownFromJsonString);
/**
* Attempt to encode an unknown value to a JSON string for diagnostic output.
* Returns `undefined` on encoding failure instead of throwing.
*/
export function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
const result = encodeUnknownJsonStringExit(input);
return Exit.isSuccess(result) ? result.value : undefined;
}
export const prettyJsonString = SchemaGetter.parseJson<string>().compose(
SchemaGetter.stringifyJson({ space: 2 }),
);
+6 -5
View File
@@ -1,10 +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.decodeUnknownOption(ServerSettingsJson);
export interface PersistedServerObservabilitySettings {
readonly otlpTracesUrl: string | undefined;
@@ -33,12 +35,11 @@ export function extractPersistedServerObservabilitySettings(input: {
export function parsePersistedServerObservabilitySettings(
raw: string,
): PersistedServerObservabilitySettings {
try {
const decoded = Schema.decodeUnknownSync(ServerSettingsJson)(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(
+1
View File
@@ -24,6 +24,7 @@ const workspaceFiles = [
"apps/desktop/package.json",
"apps/web/package.json",
"apps/marketing/package.json",
"oxlint-plugin-t3code/package.json",
"packages/client-runtime/package.json",
"packages/contracts/package.json",
"packages/shared/package.json",
+3 -2
View File
@@ -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;
}