From 0ac59d569d6df6568e5750f056a53ad32fd678b1 Mon Sep 17 00:00:00 2001
From: Lars Nieuwenhuis <35393046+lnieuwenhuis@users.noreply.github.com>
Date: Wed, 1 Apr 2026 17:19:12 +0200
Subject: [PATCH 01/17] Feat: Added Trae IDE support for opening current
working directory (#1656)
---
apps/server/src/open.test.ts | 21 ++++++++-
apps/web/src/components/ChatView.browser.tsx | 46 +++++++++++++++++++
apps/web/src/components/Icons.tsx | 14 ++++++
apps/web/src/components/chat/OpenInPicker.tsx | 7 ++-
packages/contracts/src/editor.ts | 1 +
5 files changed, 87 insertions(+), 2 deletions(-)
diff --git a/apps/server/src/open.test.ts b/apps/server/src/open.test.ts
index 947a60ac2a..c612922fea 100644
--- a/apps/server/src/open.test.ts
+++ b/apps/server/src/open.test.ts
@@ -31,6 +31,15 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
args: ["/tmp/workspace"],
});
+ const traeLaunch = yield* resolveEditorLaunch(
+ { cwd: "/tmp/workspace", editor: "trae" },
+ "darwin",
+ );
+ assert.deepEqual(traeLaunch, {
+ command: "trae",
+ args: ["/tmp/workspace"],
+ });
+
const vscodeLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "vscode" },
"darwin",
@@ -89,6 +98,15 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
+ const traeLineAndColumn = yield* resolveEditorLaunch(
+ { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "trae" },
+ "darwin",
+ );
+ assert.deepEqual(traeLineAndColumn, {
+ command: "trae",
+ args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
+ });
+
const vscodeLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
"darwin",
@@ -256,6 +274,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
+ yield* fs.writeFileString(path.join(dir, "trae.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
@@ -263,7 +282,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
});
- assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
+ assert.deepEqual(editors, ["trae", "vscode-insiders", "vscodium", "file-manager"]);
}),
);
});
diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx
index 33b9b62859..0e5f573d54 100644
--- a/apps/web/src/components/ChatView.browser.tsx
+++ b/apps/web/src/components/ChatView.browser.tsx
@@ -1407,6 +1407,52 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
+ it("opens the project cwd with Trae when it is the only available editor", async () => {
+ setDraftThreadWithoutWorktree();
+
+ const mounted = await mountChatView({
+ viewport: DEFAULT_VIEWPORT,
+ snapshot: createDraftOnlySnapshot(),
+ configureFixture: (nextFixture) => {
+ nextFixture.serverConfig = {
+ ...nextFixture.serverConfig,
+ availableEditors: ["trae"],
+ };
+ },
+ });
+
+ try {
+ await waitForServerConfigToApply();
+ const openButton = await waitForElement(
+ () =>
+ Array.from(document.querySelectorAll("button")).find(
+ (button) => button.textContent?.trim() === "Open",
+ ) as HTMLButtonElement | null,
+ "Unable to find Open button.",
+ );
+ await vi.waitFor(() => {
+ expect(openButton.disabled).toBe(false);
+ });
+ openButton.click();
+
+ await vi.waitFor(
+ () => {
+ const openRequest = wsRequests.find(
+ (request) => request._tag === WS_METHODS.shellOpenInEditor,
+ );
+ expect(openRequest).toMatchObject({
+ _tag: WS_METHODS.shellOpenInEditor,
+ cwd: "/repo/project",
+ editor: "trae",
+ });
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+ } finally {
+ await mounted.cleanup();
+ }
+ });
+
it("filters the open picker menu and opens VSCodium from the menu", async () => {
setDraftThreadWithoutWorktree();
diff --git a/apps/web/src/components/Icons.tsx b/apps/web/src/components/Icons.tsx
index 7d210fa173..3f4844af80 100644
--- a/apps/web/src/components/Icons.tsx
+++ b/apps/web/src/components/Icons.tsx
@@ -20,6 +20,20 @@ export const CursorIcon: Icon = (props) => (
);
+export const TraeIcon: Icon = (props) => (
+
+);
+
export const VisualStudioCode: Icon = (props) => {
const id = useId();
const maskId = `${id}-vscode-a`;
diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsx
index 6a956f6f42..bb5362439e 100644
--- a/apps/web/src/components/chat/OpenInPicker.tsx
+++ b/apps/web/src/components/chat/OpenInPicker.tsx
@@ -6,7 +6,7 @@ import { ChevronDownIcon, FolderClosedIcon } from "lucide-react";
import { Button } from "../ui/button";
import { Group, GroupSeparator } from "../ui/group";
import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "../ui/menu";
-import { AntigravityIcon, CursorIcon, Icon, VisualStudioCode, Zed } from "../Icons";
+import { AntigravityIcon, CursorIcon, Icon, TraeIcon, VisualStudioCode, Zed } from "../Icons";
import { isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { readNativeApi } from "~/nativeApi";
@@ -17,6 +17,11 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray
Date: Wed, 1 Apr 2026 08:35:54 -0700
Subject: [PATCH 02/17] [codex] migrate Effect.fn in
apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts (#1622)
Co-authored-by: codex
---
.../server/src/checkpointing/Layers/CheckpointDiffQuery.ts | 7 ++++---
1 file changed, 4 insertions(+), 3 deletions(-)
diff --git a/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts b/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts
index 5cf26c86da..bbb5a42931 100644
--- a/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts
+++ b/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts
@@ -21,8 +21,8 @@ const make = Effect.gen(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const checkpointStore = yield* CheckpointStore;
- const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = (input) =>
- Effect.gen(function* () {
+ const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
+ function* (input) {
const operation = "CheckpointDiffQuery.getTurnDiff";
if (input.fromTurnCount === input.toTurnCount) {
@@ -149,7 +149,8 @@ const make = Effect.gen(function* () {
}
return turnDiff;
- });
+ },
+ );
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
input: OrchestrationGetFullThreadDiffInput,
From 15f0be848df55ce27a9c24e622cd58e987886240 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 1 Apr 2026 08:39:23 -0700
Subject: [PATCH 03/17] [codex] migrate Effect.fn in
apps/server/src/checkpointing/Layers/CheckpointStore.ts (#1623)
Co-authored-by: codex
---
.../checkpointing/Layers/CheckpointStore.ts | 265 +++++++++---------
1 file changed, 134 insertions(+), 131 deletions(-)
diff --git a/apps/server/src/checkpointing/Layers/CheckpointStore.ts b/apps/server/src/checkpointing/Layers/CheckpointStore.ts
index 0a1d7abb9d..184ec96323 100644
--- a/apps/server/src/checkpointing/Layers/CheckpointStore.ts
+++ b/apps/server/src/checkpointing/Layers/CheckpointStore.ts
@@ -86,139 +86,140 @@ const makeCheckpointStore = Effect.gen(function* () {
Effect.catch(() => Effect.succeed(false)),
);
- const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = (input) =>
- Effect.gen(function* () {
- const operation = "CheckpointStore.captureCheckpoint";
+ const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
+ "captureCheckpoint",
+ )(function* (input) {
+ const operation = "CheckpointStore.captureCheckpoint";
- yield* Effect.acquireUseRelease(
- fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
- (tempDir) =>
- Effect.gen(function* () {
- const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
- const commitEnv: NodeJS.ProcessEnv = {
- ...process.env,
- GIT_INDEX_FILE: tempIndexPath,
- GIT_AUTHOR_NAME: "T3 Code",
- GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com",
- GIT_COMMITTER_NAME: "T3 Code",
- GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com",
- };
+ yield* Effect.acquireUseRelease(
+ fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
+ Effect.fn("captureCheckpoint.withTempDirectory")(function* (tempDir) {
+ const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
+ const commitEnv: NodeJS.ProcessEnv = {
+ ...process.env,
+ GIT_INDEX_FILE: tempIndexPath,
+ GIT_AUTHOR_NAME: "T3 Code",
+ GIT_AUTHOR_EMAIL: "t3code@users.noreply.github.com",
+ GIT_COMMITTER_NAME: "T3 Code",
+ GIT_COMMITTER_EMAIL: "t3code@users.noreply.github.com",
+ };
- const headExists = yield* hasHeadCommit(input.cwd);
- if (headExists) {
- yield* git.execute({
- operation,
- cwd: input.cwd,
- args: ["read-tree", "HEAD"],
- env: commitEnv,
- });
- }
+ const headExists = yield* hasHeadCommit(input.cwd);
+ if (headExists) {
+ yield* git.execute({
+ operation,
+ cwd: input.cwd,
+ args: ["read-tree", "HEAD"],
+ env: commitEnv,
+ });
+ }
- yield* git.execute({
- operation,
- cwd: input.cwd,
- args: ["add", "-A", "--", "."],
- env: commitEnv,
- });
+ yield* git.execute({
+ operation,
+ cwd: input.cwd,
+ args: ["add", "-A", "--", "."],
+ env: commitEnv,
+ });
- const writeTreeResult = yield* git.execute({
- operation,
- cwd: input.cwd,
- args: ["write-tree"],
- env: commitEnv,
- });
- const treeOid = writeTreeResult.stdout.trim();
- if (treeOid.length === 0) {
- return yield* new GitCommandError({
- operation,
- command: "git write-tree",
- cwd: input.cwd,
- detail: "git write-tree returned an empty tree oid.",
- });
- }
+ const writeTreeResult = yield* git.execute({
+ operation,
+ cwd: input.cwd,
+ args: ["write-tree"],
+ env: commitEnv,
+ });
+ const treeOid = writeTreeResult.stdout.trim();
+ if (treeOid.length === 0) {
+ return yield* new GitCommandError({
+ operation,
+ command: "git write-tree",
+ cwd: input.cwd,
+ detail: "git write-tree returned an empty tree oid.",
+ });
+ }
- const message = `t3 checkpoint ref=${input.checkpointRef}`;
- const commitTreeResult = yield* git.execute({
- operation,
- cwd: input.cwd,
- args: ["commit-tree", treeOid, "-m", message],
- env: commitEnv,
- });
- const commitOid = commitTreeResult.stdout.trim();
- if (commitOid.length === 0) {
- return yield* new GitCommandError({
- operation,
- command: "git commit-tree",
- cwd: input.cwd,
- detail: "git commit-tree returned an empty commit oid.",
- });
- }
+ const message = `t3 checkpoint ref=${input.checkpointRef}`;
+ const commitTreeResult = yield* git.execute({
+ operation,
+ cwd: input.cwd,
+ args: ["commit-tree", treeOid, "-m", message],
+ env: commitEnv,
+ });
+ const commitOid = commitTreeResult.stdout.trim();
+ if (commitOid.length === 0) {
+ return yield* new GitCommandError({
+ operation,
+ command: "git commit-tree",
+ cwd: input.cwd,
+ detail: "git commit-tree returned an empty commit oid.",
+ });
+ }
- yield* git.execute({
- operation,
- cwd: input.cwd,
- args: ["update-ref", input.checkpointRef, commitOid],
- });
- }),
- (tempDir) => fs.remove(tempDir, { recursive: true }),
- ).pipe(
- Effect.catchTags({
- PlatformError: (error) =>
- Effect.fail(
- new CheckpointInvariantError({
- operation: "CheckpointStore.captureCheckpoint",
- detail: "Failed to capture checkpoint.",
- cause: error,
- }),
- ),
- }),
- );
- });
+ yield* git.execute({
+ operation,
+ cwd: input.cwd,
+ args: ["update-ref", input.checkpointRef, commitOid],
+ });
+ }),
+ (tempDir) => fs.remove(tempDir, { recursive: true }),
+ ).pipe(
+ Effect.catchTags({
+ PlatformError: (error) =>
+ Effect.fail(
+ new CheckpointInvariantError({
+ operation: "CheckpointStore.captureCheckpoint",
+ detail: "Failed to capture checkpoint.",
+ cause: error,
+ }),
+ ),
+ }),
+ );
+ });
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
Effect.map((commit) => commit !== null),
);
- const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = (input) =>
- Effect.gen(function* () {
- const operation = "CheckpointStore.restoreCheckpoint";
+ const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = Effect.fn(
+ "restoreCheckpoint",
+ )(function* (input) {
+ const operation = "CheckpointStore.restoreCheckpoint";
- let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
+ let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
- if (!commitOid && input.fallbackToHead === true) {
- commitOid = yield* resolveHeadCommit(input.cwd);
- }
+ if (!commitOid && input.fallbackToHead === true) {
+ commitOid = yield* resolveHeadCommit(input.cwd);
+ }
- if (!commitOid) {
- return false;
- }
+ if (!commitOid) {
+ return false;
+ }
- yield* git.execute({
- operation,
- cwd: input.cwd,
- args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
- });
- yield* git.execute({
- operation,
- cwd: input.cwd,
- args: ["clean", "-fd", "--", "."],
- });
-
- const headExists = yield* hasHeadCommit(input.cwd);
- if (headExists) {
- yield* git.execute({
- operation,
- cwd: input.cwd,
- args: ["reset", "--quiet", "--", "."],
- });
- }
-
- return true;
+ yield* git.execute({
+ operation,
+ cwd: input.cwd,
+ args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
+ });
+ yield* git.execute({
+ operation,
+ cwd: input.cwd,
+ args: ["clean", "-fd", "--", "."],
});
- const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = (input) =>
- Effect.gen(function* () {
+ const headExists = yield* hasHeadCommit(input.cwd);
+ if (headExists) {
+ yield* git.execute({
+ operation,
+ cwd: input.cwd,
+ args: ["reset", "--quiet", "--", "."],
+ });
+ }
+
+ return true;
+ });
+
+ const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")(
+ function* (input) {
const operation = "CheckpointStore.diffCheckpoints";
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
@@ -247,24 +248,26 @@ const makeCheckpointStore = Effect.gen(function* () {
});
return result.stdout;
- });
+ },
+ );
- const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = (input) =>
- Effect.gen(function* () {
- const operation = "CheckpointStore.deleteCheckpointRefs";
+ const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn(
+ "deleteCheckpointRefs",
+ )(function* (input) {
+ const operation = "CheckpointStore.deleteCheckpointRefs";
- yield* Effect.forEach(
- input.checkpointRefs,
- (checkpointRef) =>
- git.execute({
- operation,
- cwd: input.cwd,
- args: ["update-ref", "-d", checkpointRef],
- allowNonZeroExit: true,
- }),
- { discard: true },
- );
- });
+ yield* Effect.forEach(
+ input.checkpointRefs,
+ (checkpointRef) =>
+ git.execute({
+ operation,
+ cwd: input.cwd,
+ args: ["update-ref", "-d", checkpointRef],
+ allowNonZeroExit: true,
+ }),
+ { discard: true },
+ );
+ });
return {
isGitRepository,
From c542ce336965261dd01c6e670b603434596e3527 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 1 Apr 2026 08:44:38 -0700
Subject: [PATCH 04/17] [codex] migrate Effect.fn in
apps/server/src/git/Layers/ClaudeTextGeneration.ts (#1625)
Co-authored-by: codex
---
.../src/git/Layers/ClaudeTextGeneration.ts | 216 +++++++++---------
1 file changed, 105 insertions(+), 111 deletions(-)
diff --git a/apps/server/src/git/Layers/ClaudeTextGeneration.ts b/apps/server/src/git/Layers/ClaudeTextGeneration.ts
index 7d620be3a6..99ca21b06d 100644
--- a/apps/server/src/git/Layers/ClaudeTextGeneration.ts
+++ b/apps/server/src/git/Layers/ClaudeTextGeneration.ts
@@ -66,7 +66,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
* Spawn the Claude CLI with structured JSON output and return the parsed,
* schema-validated result.
*/
- const runClaudeJson = ({
+ const runClaudeJson = Effect.fn("runClaudeJson")(function* ({
operation,
cwd,
prompt,
@@ -82,131 +82,125 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
prompt: string;
outputSchemaJson: S;
modelSelection: ClaudeModelSelection;
- }): Effect.Effect =>
- Effect.gen(function* () {
- const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
- const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
- getClaudeModelCapabilities(modelSelection.model),
- modelSelection.options,
- );
- const settings = {
- ...(typeof normalizedOptions?.thinking === "boolean"
- ? { alwaysThinkingEnabled: normalizedOptions.thinking }
- : {}),
- ...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
- };
+ }): Effect.fn.Return {
+ const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
+ const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
+ getClaudeModelCapabilities(modelSelection.model),
+ modelSelection.options,
+ );
+ const settings = {
+ ...(typeof normalizedOptions?.thinking === "boolean"
+ ? { alwaysThinkingEnabled: normalizedOptions.thinking }
+ : {}),
+ ...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
+ };
- const claudeSettings = yield* Effect.map(
- serverSettingsService.getSettings,
- (settings) => settings.providers.claudeAgent,
- ).pipe(Effect.catch(() => Effect.undefined));
+ const claudeSettings = yield* Effect.map(
+ serverSettingsService.getSettings,
+ (settings) => settings.providers.claudeAgent,
+ ).pipe(Effect.catch(() => Effect.undefined));
- const runClaudeCommand = Effect.gen(function* () {
- const command = ChildProcess.make(
- claudeSettings?.binaryPath || "claude",
- [
- "-p",
- "--output-format",
- "json",
- "--json-schema",
- jsonSchemaStr,
- "--model",
- resolveApiModelId(modelSelection),
- ...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
- ...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
- "--dangerously-skip-permissions",
- ],
- {
- cwd,
- shell: process.platform === "win32",
- stdin: {
- stream: Stream.encodeText(Stream.make(prompt)),
- },
+ const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
+ const command = ChildProcess.make(
+ claudeSettings?.binaryPath || "claude",
+ [
+ "-p",
+ "--output-format",
+ "json",
+ "--json-schema",
+ jsonSchemaStr,
+ "--model",
+ resolveApiModelId(modelSelection),
+ ...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
+ ...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
+ "--dangerously-skip-permissions",
+ ],
+ {
+ cwd,
+ shell: process.platform === "win32",
+ stdin: {
+ stream: Stream.encodeText(Stream.make(prompt)),
},
+ },
+ );
+
+ const child = yield* commandSpawner
+ .spawn(command)
+ .pipe(
+ Effect.mapError((cause) =>
+ normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
+ ),
);
- const child = yield* commandSpawner
- .spawn(command)
- .pipe(
+ const [stdout, stderr, exitCode] = yield* Effect.all(
+ [
+ readStreamAsString(operation, child.stdout),
+ readStreamAsString(operation, child.stderr),
+ child.exitCode.pipe(
Effect.mapError((cause) =>
- normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
+ normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
),
- );
+ ),
+ ],
+ { concurrency: "unbounded" },
+ );
- const [stdout, stderr, exitCode] = yield* Effect.all(
- [
- readStreamAsString(operation, child.stdout),
- readStreamAsString(operation, child.stderr),
- child.exitCode.pipe(
- Effect.mapError((cause) =>
- normalizeCliError(
- "claude",
- operation,
- cause,
- "Failed to read Claude CLI exit code",
- ),
- ),
+ if (exitCode !== 0) {
+ const stderrDetail = stderr.trim();
+ const stdoutDetail = stdout.trim();
+ const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
+ return yield* new TextGenerationError({
+ operation,
+ detail:
+ detail.length > 0
+ ? `Claude CLI command failed: ${detail}`
+ : `Claude CLI command failed with code ${exitCode}.`,
+ });
+ }
+
+ return stdout;
+ });
+
+ const rawStdout = yield* runClaudeCommand().pipe(
+ Effect.scoped,
+ Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
+ Effect.flatMap(
+ Option.match({
+ onNone: () =>
+ Effect.fail(
+ new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
),
- ],
- { concurrency: "unbounded" },
- );
+ onSome: (value) => Effect.succeed(value),
+ }),
+ ),
+ );
- if (exitCode !== 0) {
- const stderrDetail = stderr.trim();
- const stdoutDetail = stdout.trim();
- const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
- return yield* new TextGenerationError({
+ const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
+ rawStdout,
+ ).pipe(
+ Effect.catchTag("SchemaError", (cause) =>
+ Effect.fail(
+ new TextGenerationError({
operation,
- detail:
- detail.length > 0
- ? `Claude CLI command failed: ${detail}`
- : `Claude CLI command failed with code ${exitCode}.`,
- });
- }
-
- return stdout;
- });
-
- const rawStdout = yield* runClaudeCommand.pipe(
- Effect.scoped,
- Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
- Effect.flatMap(
- Option.match({
- onNone: () =>
- Effect.fail(
- new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
- ),
- onSome: (value) => Effect.succeed(value),
+ detail: "Claude CLI returned unexpected output format.",
+ cause,
}),
),
- );
+ ),
+ );
- const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
- rawStdout,
- ).pipe(
- Effect.catchTag("SchemaError", (cause) =>
- Effect.fail(
- new TextGenerationError({
- operation,
- detail: "Claude CLI returned unexpected output format.",
- cause,
- }),
- ),
+ return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
+ Effect.catchTag("SchemaError", (cause) =>
+ Effect.fail(
+ new TextGenerationError({
+ operation,
+ detail: "Claude returned invalid structured output.",
+ cause,
+ }),
),
- );
-
- return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
- Effect.catchTag("SchemaError", (cause) =>
- Effect.fail(
- new TextGenerationError({
- operation,
- detail: "Claude returned invalid structured output.",
- cause,
- }),
- ),
- ),
- );
- });
+ ),
+ );
+ });
// ---------------------------------------------------------------------------
// TextGenerationShape methods
From 3488ca3570060449d3855eeba79a40e1f9938f9c Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 1 Apr 2026 08:44:49 -0700
Subject: [PATCH 05/17] [codex] migrate Effect.fn in
apps/server/src/persistence/Migrations.ts (#1632)
Co-authored-by: codex
---
apps/server/src/persistence/Migrations.ts | 27 ++++++++++++-----------
1 file changed, 14 insertions(+), 13 deletions(-)
diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts
index c759665f06..47102471ac 100644
--- a/apps/server/src/persistence/Migrations.ts
+++ b/apps/server/src/persistence/Migrations.ts
@@ -92,19 +92,20 @@ export interface RunMigrationsOptions {
*
* @returns Effect containing array of executed migrations
*/
-export const runMigrations = ({ toMigrationInclusive }: RunMigrationsOptions = {}) =>
- Effect.gen(function* () {
- yield* Effect.log(
- toMigrationInclusive === undefined
- ? "Running all migrations..."
- : `Running migrations 1 through ${toMigrationInclusive}...`,
- );
- const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
- yield* Effect.log("Migrations ran successfully").pipe(
- Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }),
- );
- return executedMigrations;
- });
+export const runMigrations = Effect.fn("runMigrations")(function* ({
+ toMigrationInclusive,
+}: RunMigrationsOptions = {}) {
+ yield* Effect.log(
+ toMigrationInclusive === undefined
+ ? "Running all migrations..."
+ : `Running migrations 1 through ${toMigrationInclusive}...`,
+ );
+ const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
+ yield* Effect.log("Migrations ran successfully").pipe(
+ Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }),
+ );
+ return executedMigrations;
+});
/**
* Layer that runs migrations when the layer is built.
From a58290ed79061f4bad98336419d8f9e405963f8f Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 1 Apr 2026 08:53:25 -0700
Subject: [PATCH 06/17] [codex] migrate Effect.fn in
apps/server/src/git/Layers/CodexTextGeneration.ts (#1624)
Co-authored-by: codex
---
.../src/git/Layers/CodexTextGeneration.ts | 306 +++++++++---------
1 file changed, 152 insertions(+), 154 deletions(-)
diff --git a/apps/server/src/git/Layers/CodexTextGeneration.ts b/apps/server/src/git/Layers/CodexTextGeneration.ts
index 9bd838773b..52ddf55453 100644
--- a/apps/server/src/git/Layers/CodexTextGeneration.ts
+++ b/apps/server/src/git/Layers/CodexTextGeneration.ts
@@ -85,44 +85,43 @@ const makeCodexTextGeneration = Effect.gen(function* () {
const safeUnlink = (filePath: string): Effect.Effect =>
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
- const materializeImageAttachments = (
+ const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
_operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle",
attachments: BranchNameGenerationInput["attachments"],
- ): Effect.Effect =>
- Effect.gen(function* () {
- if (!attachments || attachments.length === 0) {
- return { imagePaths: [] };
+ ): Effect.fn.Return {
+ if (!attachments || attachments.length === 0) {
+ return { imagePaths: [] };
+ }
+
+ const imagePaths: string[] = [];
+ for (const attachment of attachments) {
+ if (attachment.type !== "image") {
+ continue;
}
- const imagePaths: string[] = [];
- for (const attachment of attachments) {
- if (attachment.type !== "image") {
- continue;
- }
-
- const resolvedPath = resolveAttachmentPath({
- attachmentsDir: serverConfig.attachmentsDir,
- attachment,
- });
- if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
- continue;
- }
- const fileInfo = yield* fileSystem
- .stat(resolvedPath)
- .pipe(Effect.catch(() => Effect.succeed(null)));
- if (!fileInfo || fileInfo.type !== "File") {
- continue;
- }
- imagePaths.push(resolvedPath);
+ const resolvedPath = resolveAttachmentPath({
+ attachmentsDir: serverConfig.attachmentsDir,
+ attachment,
+ });
+ if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
+ continue;
}
- return { imagePaths };
- });
+ const fileInfo = yield* fileSystem
+ .stat(resolvedPath)
+ .pipe(Effect.catch(() => Effect.succeed(null)));
+ if (!fileInfo || fileInfo.type !== "File") {
+ continue;
+ }
+ imagePaths.push(resolvedPath);
+ }
+ return { imagePaths };
+ });
- const runCodexJson = ({
+ const runCodexJson = Effect.fn("runCodexJson")(function* ({
operation,
cwd,
prompt,
@@ -142,138 +141,137 @@ const makeCodexTextGeneration = Effect.gen(function* () {
imagePaths?: ReadonlyArray;
cleanupPaths?: ReadonlyArray;
modelSelection: CodexModelSelection;
- }): Effect.Effect =>
- Effect.gen(function* () {
- const schemaPath = yield* writeTempFile(
- operation,
- "codex-schema",
- JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
+ }): Effect.fn.Return {
+ const schemaPath = yield* writeTempFile(
+ operation,
+ "codex-schema",
+ JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
+ );
+ const outputPath = yield* writeTempFile(operation, "codex-output", "");
+
+ const codexSettings = yield* Effect.map(
+ serverSettingsService.getSettings,
+ (settings) => settings.providers.codex,
+ ).pipe(Effect.catch(() => Effect.undefined));
+
+ const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
+ const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
+ getCodexModelCapabilities(modelSelection.model),
+ modelSelection.options,
);
- const outputPath = yield* writeTempFile(operation, "codex-output", "");
-
- const codexSettings = yield* Effect.map(
- serverSettingsService.getSettings,
- (settings) => settings.providers.codex,
- ).pipe(Effect.catch(() => Effect.undefined));
-
- const runCodexCommand = Effect.gen(function* () {
- const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
- getCodexModelCapabilities(modelSelection.model),
- modelSelection.options,
- );
- const reasoningEffort =
- modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
- const command = ChildProcess.make(
- codexSettings?.binaryPath || "codex",
- [
- "exec",
- "--ephemeral",
- "-s",
- "read-only",
- "--model",
- modelSelection.model,
- "--config",
- `model_reasoning_effort="${reasoningEffort}"`,
- ...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
- "--output-schema",
- schemaPath,
- "--output-last-message",
- outputPath,
- ...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
- "-",
- ],
- {
- env: {
- ...process.env,
- ...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
- },
- cwd,
- shell: process.platform === "win32",
- stdin: {
- stream: Stream.encodeText(Stream.make(prompt)),
- },
- },
- );
-
- const child = yield* commandSpawner
- .spawn(command)
- .pipe(
- Effect.mapError((cause) =>
- normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
- ),
- );
-
- const [stdout, stderr, exitCode] = yield* Effect.all(
- [
- readStreamAsString(operation, child.stdout),
- readStreamAsString(operation, child.stderr),
- child.exitCode.pipe(
- Effect.mapError((cause) =>
- normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
- ),
- ),
- ],
- { concurrency: "unbounded" },
- );
-
- if (exitCode !== 0) {
- const stderrDetail = stderr.trim();
- const stdoutDetail = stdout.trim();
- const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
- return yield* new TextGenerationError({
- operation,
- detail:
- detail.length > 0
- ? `Codex CLI command failed: ${detail}`
- : `Codex CLI command failed with code ${exitCode}.`,
- });
- }
- });
-
- const cleanup = Effect.all(
- [schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
+ const reasoningEffort =
+ modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
+ const command = ChildProcess.make(
+ codexSettings?.binaryPath || "codex",
+ [
+ "exec",
+ "--ephemeral",
+ "-s",
+ "read-only",
+ "--model",
+ modelSelection.model,
+ "--config",
+ `model_reasoning_effort="${reasoningEffort}"`,
+ ...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
+ "--output-schema",
+ schemaPath,
+ "--output-last-message",
+ outputPath,
+ ...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
+ "-",
+ ],
{
- concurrency: "unbounded",
+ env: {
+ ...process.env,
+ ...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
+ },
+ cwd,
+ shell: process.platform === "win32",
+ stdin: {
+ stream: Stream.encodeText(Stream.make(prompt)),
+ },
},
- ).pipe(Effect.asVoid);
+ );
- return yield* Effect.gen(function* () {
- yield* runCodexCommand.pipe(
- Effect.scoped,
- Effect.timeoutOption(CODEX_TIMEOUT_MS),
- Effect.flatMap(
- Option.match({
- onNone: () =>
- Effect.fail(
- new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
- ),
- onSome: () => Effect.void,
+ const child = yield* commandSpawner
+ .spawn(command)
+ .pipe(
+ Effect.mapError((cause) =>
+ normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
+ ),
+ );
+
+ const [stdout, stderr, exitCode] = yield* Effect.all(
+ [
+ readStreamAsString(operation, child.stdout),
+ readStreamAsString(operation, child.stderr),
+ child.exitCode.pipe(
+ Effect.mapError((cause) =>
+ normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
+ ),
+ ),
+ ],
+ { concurrency: "unbounded" },
+ );
+
+ if (exitCode !== 0) {
+ const stderrDetail = stderr.trim();
+ const stdoutDetail = stdout.trim();
+ const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
+ return yield* new TextGenerationError({
+ operation,
+ detail:
+ detail.length > 0
+ ? `Codex CLI command failed: ${detail}`
+ : `Codex CLI command failed with code ${exitCode}.`,
+ });
+ }
+ });
+
+ const cleanup = Effect.all(
+ [schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
+ {
+ concurrency: "unbounded",
+ },
+ ).pipe(Effect.asVoid);
+
+ return yield* Effect.gen(function* () {
+ yield* runCodexCommand().pipe(
+ Effect.scoped,
+ Effect.timeoutOption(CODEX_TIMEOUT_MS),
+ Effect.flatMap(
+ Option.match({
+ onNone: () =>
+ Effect.fail(
+ new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
+ ),
+ onSome: () => Effect.void,
+ }),
+ ),
+ );
+
+ return yield* fileSystem.readFileString(outputPath).pipe(
+ Effect.mapError(
+ (cause) =>
+ new TextGenerationError({
+ operation,
+ detail: "Failed to read Codex output file.",
+ cause,
+ }),
+ ),
+ Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
+ Effect.catchTag("SchemaError", (cause) =>
+ Effect.fail(
+ new TextGenerationError({
+ operation,
+ detail: "Codex returned invalid structured output.",
+ cause,
}),
),
- );
-
- return yield* fileSystem.readFileString(outputPath).pipe(
- Effect.mapError(
- (cause) =>
- new TextGenerationError({
- operation,
- detail: "Failed to read Codex output file.",
- cause,
- }),
- ),
- Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
- Effect.catchTag("SchemaError", (cause) =>
- Effect.fail(
- new TextGenerationError({
- operation,
- detail: "Codex returned invalid structured output.",
- cause,
- }),
- ),
- ),
- );
- }).pipe(Effect.ensuring(cleanup));
- });
+ ),
+ );
+ }).pipe(Effect.ensuring(cleanup));
+ });
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
"CodexTextGeneration.generateCommitMessage",
From ddffdfc0957315b422ae7bc092d4c2145866d3a2 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 1 Apr 2026 08:53:55 -0700
Subject: [PATCH 07/17] [codex] migrate Effect.fn in
apps/server/src/telemetry/Layers/AnalyticsService.ts (#1642)
Co-authored-by: codex
---
.../src/telemetry/Layers/AnalyticsService.ts | 53 ++++++++++---------
1 file changed, 27 insertions(+), 26 deletions(-)
diff --git a/apps/server/src/telemetry/Layers/AnalyticsService.ts b/apps/server/src/telemetry/Layers/AnalyticsService.ts
index 297776f9db..06ecfd0237 100644
--- a/apps/server/src/telemetry/Layers/AnalyticsService.ts
+++ b/apps/server/src/telemetry/Layers/AnalyticsService.ts
@@ -70,34 +70,35 @@ const makeAnalyticsService = Effect.gen(function* () {
}),
);
- const sendBatch = (events: ReadonlyArray) =>
- Effect.gen(function* () {
- if (!telemetryConfig.enabled || !identifier) return;
+ const sendBatch = Effect.fn("sendBatch")(function* (
+ events: ReadonlyArray,
+ ) {
+ if (!telemetryConfig.enabled || !identifier) return;
- const payload = {
- api_key: telemetryConfig.posthogKey,
- batch: events.map((event) => ({
- event: event.event,
- distinct_id: identifier,
- properties: {
- ...event.properties,
- $process_person_profile: false,
- platform: process.platform,
- wsl: process.env.WSL_DISTRO_NAME,
- arch: process.arch,
- t3CodeVersion: version,
- clientType,
- },
- timestamp: event.capturedAt,
- })),
- };
+ const payload = {
+ api_key: telemetryConfig.posthogKey,
+ batch: events.map((event) => ({
+ event: event.event,
+ distinct_id: identifier,
+ properties: {
+ ...event.properties,
+ $process_person_profile: false,
+ platform: process.platform,
+ wsl: process.env.WSL_DISTRO_NAME,
+ arch: process.arch,
+ t3CodeVersion: version,
+ clientType,
+ },
+ timestamp: event.capturedAt,
+ })),
+ };
- yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(
- HttpClientRequest.bodyJson(payload),
- Effect.flatMap(httpClient.execute),
- Effect.flatMap(HttpClientResponse.filterStatusOk),
- );
- });
+ yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(
+ HttpClientRequest.bodyJson(payload),
+ Effect.flatMap(httpClient.execute),
+ Effect.flatMap(HttpClientResponse.filterStatusOk),
+ );
+ });
const flush: AnalyticsServiceShape["flush"] = Effect.gen(function* () {
while (true) {
From 6d9b21c5d042ff992b26493563096459cb9158ac Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 1 Apr 2026 08:56:04 -0700
Subject: [PATCH 08/17] [codex] migrate Effect.fn in
apps/server/src/provider/Layers/CodexProvider.ts (#1635)
Co-authored-by: codex
---
.../src/provider/Layers/CodexProvider.ts | 27 +++++++++----------
1 file changed, 13 insertions(+), 14 deletions(-)
diff --git a/apps/server/src/provider/Layers/CodexProvider.ts b/apps/server/src/provider/Layers/CodexProvider.ts
index 499d4c6ffd..667bdf048b 100644
--- a/apps/server/src/provider/Layers/CodexProvider.ts
+++ b/apps/server/src/provider/Layers/CodexProvider.ts
@@ -306,21 +306,20 @@ const probeCodexCapabilities = (input: {
}),
);
-const runCodexCommand = (args: ReadonlyArray) =>
- Effect.gen(function* () {
- const settingsService = yield* ServerSettingsService;
- const codexSettings = yield* settingsService.getSettings.pipe(
- Effect.map((settings) => settings.providers.codex),
- );
- const command = ChildProcess.make(codexSettings.binaryPath, [...args], {
- shell: process.platform === "win32",
- env: {
- ...process.env,
- ...(codexSettings.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
- },
- });
- return yield* spawnAndCollect(codexSettings.binaryPath, command);
+const runCodexCommand = Effect.fn("runCodexCommand")(function* (args: ReadonlyArray) {
+ const settingsService = yield* ServerSettingsService;
+ const codexSettings = yield* settingsService.getSettings.pipe(
+ Effect.map((settings) => settings.providers.codex),
+ );
+ const command = ChildProcess.make(codexSettings.binaryPath, [...args], {
+ shell: process.platform === "win32",
+ env: {
+ ...process.env,
+ ...(codexSettings.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
+ },
});
+ return yield* spawnAndCollect(codexSettings.binaryPath, command);
+});
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
resolveAccount?: (input: {
From 67ca528fea4a90638811105929248fe565d0a27e Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 1 Apr 2026 08:57:31 -0700
Subject: [PATCH 09/17] [codex] migrate Effect.fn in
apps/server/src/provider/Layers/ClaudeProvider.ts (#1634)
Co-authored-by: codex
---
.../src/provider/Layers/ClaudeProvider.ts | 19 +++++++++----------
1 file changed, 9 insertions(+), 10 deletions(-)
diff --git a/apps/server/src/provider/Layers/ClaudeProvider.ts b/apps/server/src/provider/Layers/ClaudeProvider.ts
index 158a9ef25a..761b795fe5 100644
--- a/apps/server/src/provider/Layers/ClaudeProvider.ts
+++ b/apps/server/src/provider/Layers/ClaudeProvider.ts
@@ -427,17 +427,16 @@ const probeClaudeCapabilities = (binaryPath: string) => {
);
};
-const runClaudeCommand = (args: ReadonlyArray) =>
- Effect.gen(function* () {
- const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
- Effect.flatMap((service) => service.getSettings),
- Effect.map((settings) => settings.providers.claudeAgent),
- );
- const command = ChildProcess.make(claudeSettings.binaryPath, [...args], {
- shell: process.platform === "win32",
- });
- return yield* spawnAndCollect(claudeSettings.binaryPath, command);
+const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (args: ReadonlyArray) {
+ const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
+ Effect.flatMap((service) => service.getSettings),
+ Effect.map((settings) => settings.providers.claudeAgent),
+ );
+ const command = ChildProcess.make(claudeSettings.binaryPath, [...args], {
+ shell: process.platform === "win32",
});
+ return yield* spawnAndCollect(claudeSettings.binaryPath, command);
+});
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
resolveSubscriptionType?: (binaryPath: string) => Effect.Effect,
From a9e5a84c03fbec2934777a0c718bcabec161863e Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 1 Apr 2026 08:58:04 -0700
Subject: [PATCH 10/17] [codex] migrate Effect.fn in
apps/server/src/provider/Layers/ProviderAdapterRegistry.ts (#1637)
Co-authored-by: codex
---
.../Layers/ProviderAdapterRegistry.ts | 43 ++++++++++---------
1 file changed, 22 insertions(+), 21 deletions(-)
diff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts
index 23ef8d1b9b..b6c987c64c 100644
--- a/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts
+++ b/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts
@@ -22,30 +22,31 @@ export interface ProviderAdapterRegistryLiveOptions {
readonly adapters?: ReadonlyArray>;
}
-const makeProviderAdapterRegistry = (options?: ProviderAdapterRegistryLiveOptions) =>
- Effect.gen(function* () {
- const adapters =
- options?.adapters !== undefined
- ? options.adapters
- : [yield* CodexAdapter, yield* ClaudeAdapter];
- const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
+const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* (
+ options?: ProviderAdapterRegistryLiveOptions,
+) {
+ const adapters =
+ options?.adapters !== undefined
+ ? options.adapters
+ : [yield* CodexAdapter, yield* ClaudeAdapter];
+ const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
- const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
- const adapter = byProvider.get(provider);
- if (!adapter) {
- return Effect.fail(new ProviderUnsupportedError({ provider }));
- }
- return Effect.succeed(adapter);
- };
+ const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
+ const adapter = byProvider.get(provider);
+ if (!adapter) {
+ return Effect.fail(new ProviderUnsupportedError({ provider }));
+ }
+ return Effect.succeed(adapter);
+ };
- const listProviders: ProviderAdapterRegistryShape["listProviders"] = () =>
- Effect.sync(() => Array.from(byProvider.keys()));
+ const listProviders: ProviderAdapterRegistryShape["listProviders"] = () =>
+ Effect.sync(() => Array.from(byProvider.keys()));
- return {
- getByProvider,
- listProviders,
- } satisfies ProviderAdapterRegistryShape;
- });
+ return {
+ getByProvider,
+ listProviders,
+ } satisfies ProviderAdapterRegistryShape;
+});
export const ProviderAdapterRegistryLive = Layer.effect(
ProviderAdapterRegistry,
From c6ff7c0d5b79e7dca8fcb675751e88187862b004 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 1 Apr 2026 09:03:08 -0700
Subject: [PATCH 11/17] [codex] migrate Effect.fn in
apps/server/src/provider/makeManagedServerProvider.ts (#1640)
Co-authored-by: codex
---
.../src/provider/makeManagedServerProvider.ts | 116 +++++++++---------
1 file changed, 59 insertions(+), 57 deletions(-)
diff --git a/apps/server/src/provider/makeManagedServerProvider.ts b/apps/server/src/provider/makeManagedServerProvider.ts
index 4c1d0878fc..59aeac1ab5 100644
--- a/apps/server/src/provider/makeManagedServerProvider.ts
+++ b/apps/server/src/provider/makeManagedServerProvider.ts
@@ -5,68 +5,70 @@ import * as Semaphore from "effect/Semaphore";
import type { ServerProviderShape } from "./Services/ServerProvider";
import { ServerSettingsError } from "@t3tools/contracts";
-export function makeManagedServerProvider(input: {
+export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(function* <
+ Settings,
+>(input: {
readonly getSettings: Effect.Effect;
readonly streamSettings: Stream.Stream;
readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
readonly checkProvider: Effect.Effect;
readonly refreshInterval?: Duration.Input;
-}): Effect.Effect {
- return Effect.gen(function* () {
- const refreshSemaphore = yield* Semaphore.make(1);
- const changesPubSub = yield* Effect.acquireRelease(
- PubSub.unbounded(),
- PubSub.shutdown,
- );
- const initialSettings = yield* input.getSettings;
- const initialSnapshot = yield* input.checkProvider;
- const snapshotRef = yield* Ref.make(initialSnapshot);
- const settingsRef = yield* Ref.make(initialSettings);
+}): Effect.fn.Return {
+ const refreshSemaphore = yield* Semaphore.make(1);
+ const changesPubSub = yield* Effect.acquireRelease(
+ PubSub.unbounded(),
+ PubSub.shutdown,
+ );
+ const initialSettings = yield* input.getSettings;
+ const initialSnapshot = yield* input.checkProvider;
+ const snapshotRef = yield* Ref.make(initialSnapshot);
+ const settingsRef = yield* Ref.make(initialSettings);
- const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>
- refreshSemaphore.withPermits(1)(
- Effect.gen(function* () {
- const forceRefresh = options?.forceRefresh === true;
- const previousSettings = yield* Ref.get(settingsRef);
- if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) {
- yield* Ref.set(settingsRef, nextSettings);
- return yield* Ref.get(snapshotRef);
- }
+ const applySnapshotBase = Effect.fn("applySnapshot")(function* (
+ nextSettings: Settings,
+ options?: { readonly forceRefresh?: boolean },
+ ) {
+ const forceRefresh = options?.forceRefresh === true;
+ const previousSettings = yield* Ref.get(settingsRef);
+ if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) {
+ yield* Ref.set(settingsRef, nextSettings);
+ return yield* Ref.get(snapshotRef);
+ }
- const nextSnapshot = yield* input.checkProvider;
- yield* Ref.set(settingsRef, nextSettings);
- yield* Ref.set(snapshotRef, nextSnapshot);
- yield* PubSub.publish(changesPubSub, nextSnapshot);
- return nextSnapshot;
- }),
- );
-
- const refreshSnapshot = Effect.gen(function* () {
- const nextSettings = yield* input.getSettings;
- return yield* applySnapshot(nextSettings, { forceRefresh: true });
- });
-
- yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
- Effect.asVoid(applySnapshot(nextSettings)),
- ).pipe(Effect.forkScoped);
-
- yield* Effect.forever(
- Effect.sleep(input.refreshInterval ?? "60 seconds").pipe(
- Effect.flatMap(() => refreshSnapshot),
- Effect.ignoreCause({ log: true }),
- ),
- ).pipe(Effect.forkScoped);
-
- return {
- getSnapshot: input.getSettings.pipe(
- Effect.flatMap(applySnapshot),
- Effect.tapError(Effect.logError),
- Effect.orDie,
- ),
- refresh: refreshSnapshot.pipe(Effect.tapError(Effect.logError), Effect.orDie),
- get streamChanges() {
- return Stream.fromPubSub(changesPubSub);
- },
- } satisfies ServerProviderShape;
+ const nextSnapshot = yield* input.checkProvider;
+ yield* Ref.set(settingsRef, nextSettings);
+ yield* Ref.set(snapshotRef, nextSnapshot);
+ yield* PubSub.publish(changesPubSub, nextSnapshot);
+ return nextSnapshot;
});
-}
+ const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>
+ refreshSemaphore.withPermits(1)(applySnapshotBase(nextSettings, options));
+
+ const refreshSnapshot = Effect.fn("refreshSnapshot")(function* () {
+ const nextSettings = yield* input.getSettings;
+ return yield* applySnapshot(nextSettings, { forceRefresh: true });
+ });
+
+ yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
+ Effect.asVoid(applySnapshot(nextSettings)),
+ ).pipe(Effect.forkScoped);
+
+ yield* Effect.forever(
+ Effect.sleep(input.refreshInterval ?? "60 seconds").pipe(
+ Effect.flatMap(() => refreshSnapshot()),
+ Effect.ignoreCause({ log: true }),
+ ),
+ ).pipe(Effect.forkScoped);
+
+ return {
+ getSnapshot: input.getSettings.pipe(
+ Effect.flatMap(applySnapshot),
+ Effect.tapError(Effect.logError),
+ Effect.orDie,
+ ),
+ refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),
+ get streamChanges() {
+ return Stream.fromPubSub(changesPubSub);
+ },
+ } satisfies ServerProviderShape;
+});
From 9f6686a13d308289c187c9da369f4874f0b5acc5 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 1 Apr 2026 09:14:26 -0700
Subject: [PATCH 12/17] [codex] migrate Effect.fn in
apps/server/src/persistence/Layers/Sqlite.ts (#1631)
Co-authored-by: codex
---
apps/server/src/persistence/Layers/Sqlite.ts | 30 ++++++++++----------
1 file changed, 15 insertions(+), 15 deletions(-)
diff --git a/apps/server/src/persistence/Layers/Sqlite.ts b/apps/server/src/persistence/Layers/Sqlite.ts
index 2dddfc3bfa..07cbf44794 100644
--- a/apps/server/src/persistence/Layers/Sqlite.ts
+++ b/apps/server/src/persistence/Layers/Sqlite.ts
@@ -16,15 +16,14 @@ const defaultSqliteClientLoaders = {
node: () => import("../NodeSqliteClient.ts"),
} satisfies Record Promise>;
-const makeRuntimeSqliteLayer = (
+const makeRuntimeSqliteLayer = Effect.fn("makeRuntimeSqliteLayer")(function* (
config: RuntimeSqliteLayerConfig,
-): Layer.Layer =>
- Effect.gen(function* () {
- const runtime = process.versions.bun !== undefined ? "bun" : "node";
- const loader = defaultSqliteClientLoaders[runtime];
- const clientModule = yield* Effect.promise(loader);
- return clientModule.layer(config);
- }).pipe(Layer.unwrap);
+) {
+ const runtime = process.versions.bun !== undefined ? "bun" : "node";
+ const loader = defaultSqliteClientLoaders[runtime];
+ const clientModule = yield* Effect.promise(loader);
+ return clientModule.layer(config);
+}, Layer.unwrap);
const setup = Layer.effectDiscard(
Effect.gen(function* () {
@@ -35,14 +34,15 @@ const setup = Layer.effectDiscard(
}),
);
-export const makeSqlitePersistenceLive = (dbPath: string) =>
- Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
+export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(function* (
+ dbPath: string,
+) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
- return Layer.provideMerge(setup, makeRuntimeSqliteLayer({ filename: dbPath }));
- }).pipe(Layer.unwrap);
+ return Layer.provideMerge(setup, makeRuntimeSqliteLayer({ filename: dbPath }));
+}, Layer.unwrap);
export const SqlitePersistenceMemory = Layer.provideMerge(
setup,
From d15075b32d5a0670ae76e32d8e1c85f8a913dd7e Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 1 Apr 2026 09:14:55 -0700
Subject: [PATCH 13/17] [codex] migrate Effect.fn in
apps/server/src/provider/Layers/EventNdjsonLogger.ts (#1636)
Co-authored-by: codex
---
.../src/provider/Layers/EventNdjsonLogger.ts | 320 +++++++++---------
1 file changed, 158 insertions(+), 162 deletions(-)
diff --git a/apps/server/src/provider/Layers/EventNdjsonLogger.ts b/apps/server/src/provider/Layers/EventNdjsonLogger.ts
index 28b7ecf611..a4fd6f235d 100644
--- a/apps/server/src/provider/Layers/EventNdjsonLogger.ts
+++ b/apps/server/src/provider/Layers/EventNdjsonLogger.ts
@@ -74,184 +74,180 @@ function resolveStreamLabel(stream: EventNdjsonStream): string {
}
}
-function toLogMessage(event: unknown): Effect.Effect {
- return Effect.gen(function* () {
- const serialized = yield* Effect.sync(() => {
- try {
- return { ok: true as const, value: JSON.stringify(event) };
- } catch (error) {
- return { ok: false as const, error };
- }
- });
-
- if (!serialized.ok) {
- yield* logWarning("failed to serialize provider event log record", {
- error: serialized.error,
- });
- return undefined;
+const toLogMessage = Effect.fn("toLogMessage")(function* (
+ event: unknown,
+): Effect.fn.Return {
+ const serialized = yield* Effect.sync(() => {
+ try {
+ return { ok: true as const, value: JSON.stringify(event) };
+ } catch (error) {
+ return { ok: false as const, error };
}
-
- if (typeof serialized.value !== "string") {
- return undefined;
- }
-
- return serialized.value;
});
-}
-function makeThreadWriter(input: {
+ if (!serialized.ok) {
+ yield* logWarning("failed to serialize provider event log record", {
+ error: serialized.error,
+ });
+ return undefined;
+ }
+
+ if (typeof serialized.value !== "string") {
+ return undefined;
+ }
+
+ return serialized.value;
+});
+
+const makeThreadWriter = Effect.fn("makeThreadWriter")(function* (input: {
readonly filePath: string;
readonly maxBytes: number;
readonly maxFiles: number;
readonly batchWindowMs: number;
readonly streamLabel: string;
-}): Effect.Effect {
- return Effect.gen(function* () {
- const sinkResult = yield* Effect.sync(() => {
- try {
- return {
- ok: true as const,
- sink: new RotatingFileSink({
- filePath: input.filePath,
- maxBytes: input.maxBytes,
- maxFiles: input.maxFiles,
- throwOnError: true,
- }),
- };
- } catch (error) {
- return { ok: false as const, error };
- }
- });
-
- if (!sinkResult.ok) {
- yield* logWarning("failed to initialize provider thread log file", {
- filePath: input.filePath,
- error: sinkResult.error,
- });
- return undefined;
- }
-
- const sink = sinkResult.sink;
- const scope = yield* Scope.make();
- const lineLogger = makeLineLogger(input.streamLabel);
- const batchedLogger = yield* Logger.batched(lineLogger, {
- window: input.batchWindowMs,
- flush: (messages) =>
- Effect.gen(function* () {
- const flushResult = yield* Effect.sync(() => {
- try {
- for (const message of messages) {
- sink.write(message);
- }
- return { ok: true as const };
- } catch (error) {
- return { ok: false as const, error };
- }
- });
-
- if (!flushResult.ok) {
- yield* logWarning("provider event log batch flush failed", {
- filePath: input.filePath,
- error: flushResult.error,
- });
- }
+}): Effect.fn.Return {
+ const sinkResult = yield* Effect.sync(() => {
+ try {
+ return {
+ ok: true as const,
+ sink: new RotatingFileSink({
+ filePath: input.filePath,
+ maxBytes: input.maxBytes,
+ maxFiles: input.maxFiles,
+ throwOnError: true,
}),
- }).pipe(Effect.provideService(Scope.Scope, scope));
-
- const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
-
- return {
- writeMessage(message: string) {
- return Effect.log(message).pipe(Effect.provide(loggerLayer));
- },
- close() {
- return Scope.close(scope, Exit.void);
- },
- } satisfies ThreadWriter;
+ };
+ } catch (error) {
+ return { ok: false as const, error };
+ }
});
-}
-export function makeEventNdjsonLogger(
+ if (!sinkResult.ok) {
+ yield* logWarning("failed to initialize provider thread log file", {
+ filePath: input.filePath,
+ error: sinkResult.error,
+ });
+ return undefined;
+ }
+
+ const sink = sinkResult.sink;
+ const scope = yield* Scope.make();
+ const lineLogger = makeLineLogger(input.streamLabel);
+ const batchedLogger = yield* Logger.batched(lineLogger, {
+ window: input.batchWindowMs,
+ flush: Effect.fn("makeThreadWriter.flush")(function* (messages) {
+ const flushResult = yield* Effect.sync(() => {
+ try {
+ for (const message of messages) {
+ sink.write(message);
+ }
+ return { ok: true as const };
+ } catch (error) {
+ return { ok: false as const, error };
+ }
+ });
+
+ if (!flushResult.ok) {
+ yield* logWarning("provider event log batch flush failed", {
+ filePath: input.filePath,
+ error: flushResult.error,
+ });
+ }
+ }),
+ }).pipe(Effect.provideService(Scope.Scope, scope));
+
+ const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
+
+ return {
+ writeMessage(message: string) {
+ return Effect.log(message).pipe(Effect.provide(loggerLayer));
+ },
+ close() {
+ return Scope.close(scope, Exit.void);
+ },
+ } satisfies ThreadWriter;
+});
+
+export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function* (
filePath: string,
options: EventNdjsonLoggerOptions,
-): Effect.Effect {
- return Effect.gen(function* () {
- const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
- const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
- const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS;
- const streamLabel = resolveStreamLabel(options.stream);
+): Effect.fn.Return {
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
+ const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
+ const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS;
+ const streamLabel = resolveStreamLabel(options.stream);
- const directoryReady = yield* Effect.sync(() => {
- try {
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
- return true;
- } catch (error) {
- return { ok: false as const, error };
- }
+ const directoryReady = yield* Effect.sync(() => {
+ try {
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ return true;
+ } catch (error) {
+ return { ok: false as const, error };
+ }
+ });
+ if (directoryReady !== true) {
+ yield* logWarning("failed to create provider event log directory", {
+ filePath,
+ error: directoryReady.error,
});
- if (directoryReady !== true) {
- yield* logWarning("failed to create provider event log directory", {
- filePath,
- error: directoryReady.error,
- });
+ return undefined;
+ }
+
+ const threadWriters = new Map();
+ const failedSegments = new Set();
+
+ const resolveThreadWriter = Effect.fn("resolveThreadWriter")(function* (
+ threadSegment: string,
+ ): Effect.fn.Return {
+ if (failedSegments.has(threadSegment)) {
+ return undefined;
+ }
+ const existing = threadWriters.get(threadSegment);
+ if (existing) {
+ return existing;
+ }
+
+ const writer = yield* makeThreadWriter({
+ filePath: path.join(path.dirname(filePath), `${threadSegment}.log`),
+ maxBytes,
+ maxFiles,
+ batchWindowMs,
+ streamLabel,
+ });
+ if (!writer) {
+ failedSegments.add(threadSegment);
return undefined;
}
- const threadWriters = new Map();
- const failedSegments = new Set();
-
- const resolveThreadWriter = (threadSegment: string): Effect.Effect =>
- Effect.gen(function* () {
- if (failedSegments.has(threadSegment)) {
- return undefined;
- }
- const existing = threadWriters.get(threadSegment);
- if (existing) {
- return existing;
- }
-
- const writer = yield* makeThreadWriter({
- filePath: path.join(path.dirname(filePath), `${threadSegment}.log`),
- maxBytes,
- maxFiles,
- batchWindowMs,
- streamLabel,
- });
- if (!writer) {
- failedSegments.add(threadSegment);
- return undefined;
- }
-
- threadWriters.set(threadSegment, writer);
- return writer;
- });
-
- return {
- filePath,
- write(event: unknown, threadId: ThreadId | null) {
- return Effect.gen(function* () {
- const threadSegment = resolveThreadSegment(threadId);
- const message = yield* toLogMessage(event);
- if (!message) {
- return;
- }
-
- const writer = yield* resolveThreadWriter(threadSegment);
- if (!writer) {
- return;
- }
-
- yield* writer.writeMessage(message);
- });
- },
- close() {
- return Effect.gen(function* () {
- for (const writer of threadWriters.values()) {
- yield* writer.close();
- }
- threadWriters.clear();
- });
- },
- } satisfies EventNdjsonLogger;
+ threadWriters.set(threadSegment, writer);
+ return writer;
});
-}
+
+ const write = Effect.fn("write")(function* (event: unknown, threadId: ThreadId | null) {
+ const threadSegment = resolveThreadSegment(threadId);
+ const message = yield* toLogMessage(event);
+ if (!message) {
+ return;
+ }
+
+ const writer = yield* resolveThreadWriter(threadSegment);
+ if (!writer) {
+ return;
+ }
+
+ yield* writer.writeMessage(message);
+ });
+
+ const close = Effect.fn("close")(function* () {
+ for (const writer of threadWriters.values()) {
+ yield* writer.close();
+ }
+ threadWriters.clear();
+ });
+
+ return {
+ filePath,
+ write,
+ close,
+ } satisfies EventNdjsonLogger;
+});
From 80b282ece7be0b8c32c8d0573bc6569d3b7ecbe1 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 1 Apr 2026 09:19:36 -0700
Subject: [PATCH 14/17] [codex] migrate Effect.fn in
apps/server/src/provider/Layers/ProviderRegistry.ts (#1638)
Co-authored-by: codex
---
.../src/provider/Layers/ProviderRegistry.ts | 55 ++++++++++---------
1 file changed, 29 insertions(+), 26 deletions(-)
diff --git a/apps/server/src/provider/Layers/ProviderRegistry.ts b/apps/server/src/provider/Layers/ProviderRegistry.ts
index 1e66ce8ff5..fb2f33c293 100644
--- a/apps/server/src/provider/Layers/ProviderRegistry.ts
+++ b/apps/server/src/provider/Layers/ProviderRegistry.ts
@@ -40,18 +40,19 @@ export const ProviderRegistryLive = Layer.effect(
yield* loadProviders(codexProvider, claudeProvider),
);
- const syncProviders = (options?: { readonly publish?: boolean }) =>
- Effect.gen(function* () {
- const previousProviders = yield* Ref.get(providersRef);
- const providers = yield* loadProviders(codexProvider, claudeProvider);
- yield* Ref.set(providersRef, providers);
+ const syncProviders = Effect.fn("syncProviders")(function* (options?: {
+ readonly publish?: boolean;
+ }) {
+ const previousProviders = yield* Ref.get(providersRef);
+ const providers = yield* loadProviders(codexProvider, claudeProvider);
+ yield* Ref.set(providersRef, providers);
- if (options?.publish !== false && haveProvidersChanged(previousProviders, providers)) {
- yield* PubSub.publish(changesPubSub, providers);
- }
+ if (options?.publish !== false && haveProvidersChanged(previousProviders, providers)) {
+ yield* PubSub.publish(changesPubSub, providers);
+ }
- return providers;
- });
+ return providers;
+ });
yield* Stream.runForEach(codexProvider.streamChanges, () => syncProviders()).pipe(
Effect.forkScoped,
@@ -60,28 +61,30 @@ export const ProviderRegistryLive = Layer.effect(
Effect.forkScoped,
);
+ const refresh = Effect.fn("refresh")(function* (provider?: ProviderKind) {
+ switch (provider) {
+ case "codex":
+ yield* codexProvider.refresh;
+ break;
+ case "claudeAgent":
+ yield* claudeProvider.refresh;
+ break;
+ default:
+ yield* Effect.all([codexProvider.refresh, claudeProvider.refresh], {
+ concurrency: "unbounded",
+ });
+ break;
+ }
+ return yield* syncProviders();
+ });
+
return {
getProviders: syncProviders({ publish: false }).pipe(
Effect.tapError(Effect.logError),
Effect.orElseSucceed(() => []),
),
refresh: (provider?: ProviderKind) =>
- Effect.gen(function* () {
- switch (provider) {
- case "codex":
- yield* codexProvider.refresh;
- break;
- case "claudeAgent":
- yield* claudeProvider.refresh;
- break;
- default:
- yield* Effect.all([codexProvider.refresh, claudeProvider.refresh], {
- concurrency: "unbounded",
- });
- break;
- }
- return yield* syncProviders();
- }).pipe(
+ refresh(provider).pipe(
Effect.tapError(Effect.logError),
Effect.orElseSucceed(() => []),
),
From 556a195c9de5554a6de978422a0160d01585a906 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 1 Apr 2026 09:19:38 -0700
Subject: [PATCH 15/17] [codex] migrate Effect.fn in
apps/server/src/provider/Layers/ProviderService.ts (#1639)
Co-authored-by: codex
---
.../src/provider/Layers/ProviderService.ts | 916 +++++++++---------
1 file changed, 457 insertions(+), 459 deletions(-)
diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts
index 0137152e83..f348829598 100644
--- a/apps/server/src/provider/Layers/ProviderService.ts
+++ b/apps/server/src/provider/Layers/ProviderService.ts
@@ -131,472 +131,470 @@ function readPersistedCwd(
return trimmed.length > 0 ? trimmed : undefined;
}
-const makeProviderService = (options?: ProviderServiceLiveOptions) =>
- Effect.gen(function* () {
- const analytics = yield* Effect.service(AnalyticsService);
- const serverSettings = yield* ServerSettingsService;
- const canonicalEventLogger =
- options?.canonicalEventLogger ??
- (options?.canonicalEventLogPath !== undefined
- ? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, {
- stream: "canonical",
- })
- : undefined);
+const makeProviderService = Effect.fn("makeProviderService")(function* (
+ options?: ProviderServiceLiveOptions,
+) {
+ const analytics = yield* Effect.service(AnalyticsService);
+ const serverSettings = yield* ServerSettingsService;
+ const canonicalEventLogger =
+ options?.canonicalEventLogger ??
+ (options?.canonicalEventLogPath !== undefined
+ ? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, {
+ stream: "canonical",
+ })
+ : undefined);
- const registry = yield* ProviderAdapterRegistry;
- const directory = yield* ProviderSessionDirectory;
- const runtimeEventQueue = yield* Queue.unbounded();
- const runtimeEventPubSub = yield* PubSub.unbounded();
+ const registry = yield* ProviderAdapterRegistry;
+ const directory = yield* ProviderSessionDirectory;
+ const runtimeEventQueue = yield* Queue.unbounded();
+ const runtimeEventPubSub = yield* PubSub.unbounded();
- const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect =>
- Effect.succeed(event).pipe(
- Effect.tap((canonicalEvent) =>
- canonicalEventLogger ? canonicalEventLogger.write(canonicalEvent, null) : Effect.void,
- ),
- Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
- Effect.asVoid,
- );
-
- const upsertSessionBinding = (
- session: ProviderSession,
- threadId: ThreadId,
- extra?: {
- readonly modelSelection?: unknown;
- readonly lastRuntimeEvent?: string;
- readonly lastRuntimeEventAt?: string;
- },
- ) =>
- directory.upsert({
- threadId,
- provider: session.provider,
- runtimeMode: session.runtimeMode,
- status: toRuntimeStatus(session),
- ...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
- runtimePayload: toRuntimePayloadFromSession(session, extra),
- });
-
- const providers = yield* registry.listProviders();
- const adapters = yield* Effect.forEach(providers, (provider) =>
- registry.getByProvider(provider),
- );
- const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect =>
- publishRuntimeEvent(event);
-
- const worker = Effect.forever(
- Queue.take(runtimeEventQueue).pipe(Effect.flatMap(processRuntimeEvent)),
- );
- yield* Effect.forkScoped(worker);
-
- yield* Effect.forEach(adapters, (adapter) =>
- Stream.runForEach(adapter.streamEvents, (event) =>
- Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid),
- ).pipe(Effect.forkScoped),
- ).pipe(Effect.asVoid);
-
- const recoverSessionForThread = (input: {
- readonly binding: ProviderRuntimeBinding;
- readonly operation: string;
- }) =>
- Effect.gen(function* () {
- const adapter = yield* registry.getByProvider(input.binding.provider);
- const hasResumeCursor =
- input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;
- const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);
- if (hasActiveSession) {
- const activeSessions = yield* adapter.listSessions();
- const existing = activeSessions.find(
- (session) => session.threadId === input.binding.threadId,
- );
- if (existing) {
- yield* upsertSessionBinding(existing, input.binding.threadId);
- yield* analytics.record("provider.session.recovered", {
- provider: existing.provider,
- strategy: "adopt-existing",
- hasResumeCursor: existing.resumeCursor !== undefined,
- });
- return { adapter, session: existing } as const;
- }
- }
-
- if (!hasResumeCursor) {
- return yield* toValidationError(
- input.operation,
- `Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
- );
- }
-
- const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
- const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
-
- const resumed = yield* adapter.startSession({
- threadId: input.binding.threadId,
- provider: input.binding.provider,
- ...(persistedCwd ? { cwd: persistedCwd } : {}),
- ...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
- ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
- runtimeMode: input.binding.runtimeMode ?? "full-access",
- });
- if (resumed.provider !== adapter.provider) {
- return yield* toValidationError(
- input.operation,
- `Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
- );
- }
-
- yield* upsertSessionBinding(resumed, input.binding.threadId);
- yield* analytics.record("provider.session.recovered", {
- provider: resumed.provider,
- strategy: "resume-thread",
- hasResumeCursor: resumed.resumeCursor !== undefined,
- });
- return { adapter, session: resumed } as const;
- });
-
- const resolveRoutableSession = (input: {
- readonly threadId: ThreadId;
- readonly operation: string;
- readonly allowRecovery: boolean;
- }) =>
- Effect.gen(function* () {
- const bindingOption = yield* directory.getBinding(input.threadId);
- const binding = Option.getOrUndefined(bindingOption);
- if (!binding) {
- return yield* toValidationError(
- input.operation,
- `Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
- );
- }
- const adapter = yield* registry.getByProvider(binding.provider);
-
- const hasRequestedSession = yield* adapter.hasSession(input.threadId);
- if (hasRequestedSession) {
- return { adapter, threadId: input.threadId, isActive: true } as const;
- }
-
- if (!input.allowRecovery) {
- return { adapter, threadId: input.threadId, isActive: false } as const;
- }
-
- const recovered = yield* recoverSessionForThread({ binding, operation: input.operation });
- return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const;
- });
-
- const startSession: ProviderServiceShape["startSession"] = (threadId, rawInput) =>
- Effect.gen(function* () {
- const parsed = yield* decodeInputOrValidationError({
- operation: "ProviderService.startSession",
- schema: ProviderSessionStartInput,
- payload: rawInput,
- });
-
- const input = {
- ...parsed,
- threadId,
- provider: parsed.provider ?? "codex",
- };
- const settings = yield* serverSettings.getSettings.pipe(
- Effect.mapError((error) =>
- toValidationError(
- "ProviderService.startSession",
- `Failed to load provider settings: ${error.message}`,
- error,
- ),
- ),
- );
- if (!settings.providers[input.provider].enabled) {
- return yield* toValidationError(
- "ProviderService.startSession",
- `Provider '${input.provider}' is disabled in T3 Code settings.`,
- );
- }
- const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
- const effectiveResumeCursor =
- input.resumeCursor ??
- (persistedBinding?.provider === input.provider
- ? persistedBinding.resumeCursor
- : undefined);
- const adapter = yield* registry.getByProvider(input.provider);
- const session = yield* adapter.startSession({
- ...input,
- ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
- });
-
- if (session.provider !== adapter.provider) {
- return yield* toValidationError(
- "ProviderService.startSession",
- `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
- );
- }
-
- yield* upsertSessionBinding(session, threadId, {
- modelSelection: input.modelSelection,
- });
- yield* analytics.record("provider.session.started", {
- provider: session.provider,
- runtimeMode: input.runtimeMode,
- hasResumeCursor: session.resumeCursor !== undefined,
- hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0,
- hasModel:
- typeof input.modelSelection?.model === "string" &&
- input.modelSelection.model.trim().length > 0,
- });
-
- return session;
- });
-
- const sendTurn: ProviderServiceShape["sendTurn"] = (rawInput) =>
- Effect.gen(function* () {
- const parsed = yield* decodeInputOrValidationError({
- operation: "ProviderService.sendTurn",
- schema: ProviderSendTurnInput,
- payload: rawInput,
- });
-
- const input = {
- ...parsed,
- attachments: parsed.attachments ?? [],
- };
- if (!input.input && input.attachments.length === 0) {
- return yield* toValidationError(
- "ProviderService.sendTurn",
- "Either input text or at least one attachment is required",
- );
- }
- const routed = yield* resolveRoutableSession({
- threadId: input.threadId,
- operation: "ProviderService.sendTurn",
- allowRecovery: true,
- });
- const turn = yield* routed.adapter.sendTurn(input);
- yield* directory.upsert({
- threadId: input.threadId,
- provider: routed.adapter.provider,
- status: "running",
- ...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
- runtimePayload: {
- ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
- activeTurnId: turn.turnId,
- lastRuntimeEvent: "provider.sendTurn",
- lastRuntimeEventAt: new Date().toISOString(),
- },
- });
- yield* analytics.record("provider.turn.sent", {
- provider: routed.adapter.provider,
- model: input.modelSelection?.model,
- interactionMode: input.interactionMode,
- attachmentCount: input.attachments.length,
- hasInput: typeof input.input === "string" && input.input.trim().length > 0,
- });
- return turn;
- });
-
- const interruptTurn: ProviderServiceShape["interruptTurn"] = (rawInput) =>
- Effect.gen(function* () {
- const input = yield* decodeInputOrValidationError({
- operation: "ProviderService.interruptTurn",
- schema: ProviderInterruptTurnInput,
- payload: rawInput,
- });
- const routed = yield* resolveRoutableSession({
- threadId: input.threadId,
- operation: "ProviderService.interruptTurn",
- allowRecovery: true,
- });
- yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);
- yield* analytics.record("provider.turn.interrupted", {
- provider: routed.adapter.provider,
- });
- });
-
- const respondToRequest: ProviderServiceShape["respondToRequest"] = (rawInput) =>
- Effect.gen(function* () {
- const input = yield* decodeInputOrValidationError({
- operation: "ProviderService.respondToRequest",
- schema: ProviderRespondToRequestInput,
- payload: rawInput,
- });
- const routed = yield* resolveRoutableSession({
- threadId: input.threadId,
- operation: "ProviderService.respondToRequest",
- allowRecovery: true,
- });
- yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
- yield* analytics.record("provider.request.responded", {
- provider: routed.adapter.provider,
- decision: input.decision,
- });
- });
-
- const respondToUserInput: ProviderServiceShape["respondToUserInput"] = (rawInput) =>
- Effect.gen(function* () {
- const input = yield* decodeInputOrValidationError({
- operation: "ProviderService.respondToUserInput",
- schema: ProviderRespondToUserInputInput,
- payload: rawInput,
- });
- const routed = yield* resolveRoutableSession({
- threadId: input.threadId,
- operation: "ProviderService.respondToUserInput",
- allowRecovery: true,
- });
- yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
- });
-
- const stopSession: ProviderServiceShape["stopSession"] = (rawInput) =>
- Effect.gen(function* () {
- const input = yield* decodeInputOrValidationError({
- operation: "ProviderService.stopSession",
- schema: ProviderStopSessionInput,
- payload: rawInput,
- });
- const routed = yield* resolveRoutableSession({
- threadId: input.threadId,
- operation: "ProviderService.stopSession",
- allowRecovery: false,
- });
- if (routed.isActive) {
- yield* routed.adapter.stopSession(routed.threadId);
- }
- yield* directory.remove(input.threadId);
- yield* analytics.record("provider.session.stopped", {
- provider: routed.adapter.provider,
- });
- });
-
- const listSessions: ProviderServiceShape["listSessions"] = () =>
- Effect.gen(function* () {
- const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) =>
- adapter.listSessions(),
- );
- const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);
- const persistedBindings = yield* directory.listThreadIds().pipe(
- Effect.flatMap((threadIds) =>
- Effect.forEach(
- threadIds,
- (threadId) =>
- directory
- .getBinding(threadId)
- .pipe(Effect.orElseSucceed(() => Option.none())),
- { concurrency: "unbounded" },
- ),
- ),
- Effect.orElseSucceed(() => [] as Array>),
- );
- const bindingsByThreadId = new Map();
- for (const bindingOption of persistedBindings) {
- const binding = Option.getOrUndefined(bindingOption);
- if (binding) {
- bindingsByThreadId.set(binding.threadId, binding);
- }
- }
-
- return activeSessions.map((session) => {
- const binding = bindingsByThreadId.get(session.threadId);
- if (!binding) {
- return session;
- }
-
- const overrides: {
- resumeCursor?: ProviderSession["resumeCursor"];
- runtimeMode?: ProviderSession["runtimeMode"];
- } = {};
- if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
- overrides.resumeCursor = binding.resumeCursor;
- }
- if (binding.runtimeMode !== undefined) {
- overrides.runtimeMode = binding.runtimeMode;
- }
- return Object.assign({}, session, overrides);
- });
- });
-
- const getCapabilities: ProviderServiceShape["getCapabilities"] = (provider) =>
- registry.getByProvider(provider).pipe(Effect.map((adapter) => adapter.capabilities));
-
- const rollbackConversation: ProviderServiceShape["rollbackConversation"] = (rawInput) =>
- Effect.gen(function* () {
- const input = yield* decodeInputOrValidationError({
- operation: "ProviderService.rollbackConversation",
- schema: ProviderRollbackConversationInput,
- payload: rawInput,
- });
- if (input.numTurns === 0) {
- return;
- }
- const routed = yield* resolveRoutableSession({
- threadId: input.threadId,
- operation: "ProviderService.rollbackConversation",
- allowRecovery: true,
- });
- yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
- yield* analytics.record("provider.conversation.rolled_back", {
- provider: routed.adapter.provider,
- turns: input.numTurns,
- });
- });
-
- const runStopAll = () =>
- Effect.gen(function* () {
- const threadIds = yield* directory.listThreadIds();
- const activeSessions = yield* Effect.forEach(adapters, (adapter) =>
- adapter.listSessions(),
- ).pipe(
- Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)),
- );
- yield* Effect.forEach(activeSessions, (session) =>
- upsertSessionBinding(session, session.threadId, {
- lastRuntimeEvent: "provider.stopAll",
- lastRuntimeEventAt: new Date().toISOString(),
- }),
- ).pipe(Effect.asVoid);
- yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid);
- yield* Effect.forEach(threadIds, (threadId) =>
- directory.getProvider(threadId).pipe(
- Effect.flatMap((provider) =>
- directory.upsert({
- threadId,
- provider,
- status: "stopped",
- runtimePayload: {
- activeTurnId: null,
- lastRuntimeEvent: "provider.stopAll",
- lastRuntimeEventAt: new Date().toISOString(),
- },
- }),
- ),
- ),
- ).pipe(Effect.asVoid);
- yield* analytics.record("provider.sessions.stopped_all", {
- sessionCount: threadIds.length,
- });
- yield* analytics.flush;
- });
-
- yield* Effect.addFinalizer(() =>
- Effect.catch(runStopAll(), (cause) =>
- Effect.logWarning("failed to stop provider service", { cause }),
+ const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect =>
+ Effect.succeed(event).pipe(
+ Effect.tap((canonicalEvent) =>
+ canonicalEventLogger ? canonicalEventLogger.write(canonicalEvent, null) : Effect.void,
),
+ Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
+ Effect.asVoid,
);
- return {
- startSession,
- sendTurn,
- interruptTurn,
- respondToRequest,
- respondToUserInput,
- stopSession,
- listSessions,
- getCapabilities,
- rollbackConversation,
- // Each access creates a fresh PubSub subscription so that multiple
- // consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
- // independently receive all runtime events.
- get streamEvents(): ProviderServiceShape["streamEvents"] {
- return Stream.fromPubSub(runtimeEventPubSub);
- },
- } satisfies ProviderServiceShape;
+ const upsertSessionBinding = (
+ session: ProviderSession,
+ threadId: ThreadId,
+ extra?: {
+ readonly modelSelection?: unknown;
+ readonly lastRuntimeEvent?: string;
+ readonly lastRuntimeEventAt?: string;
+ },
+ ) =>
+ directory.upsert({
+ threadId,
+ provider: session.provider,
+ runtimeMode: session.runtimeMode,
+ status: toRuntimeStatus(session),
+ ...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
+ runtimePayload: toRuntimePayloadFromSession(session, extra),
+ });
+
+ const providers = yield* registry.listProviders();
+ const adapters = yield* Effect.forEach(providers, (provider) => registry.getByProvider(provider));
+ const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect =>
+ publishRuntimeEvent(event);
+
+ const worker = Effect.forever(
+ Queue.take(runtimeEventQueue).pipe(Effect.flatMap(processRuntimeEvent)),
+ );
+ yield* Effect.forkScoped(worker);
+
+ yield* Effect.forEach(adapters, (adapter) =>
+ Stream.runForEach(adapter.streamEvents, (event) =>
+ Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid),
+ ).pipe(Effect.forkScoped),
+ ).pipe(Effect.asVoid);
+
+ const recoverSessionForThread = Effect.fn("recoverSessionForThread")(function* (input: {
+ readonly binding: ProviderRuntimeBinding;
+ readonly operation: string;
+ }) {
+ const adapter = yield* registry.getByProvider(input.binding.provider);
+ const hasResumeCursor =
+ input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;
+ const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);
+ if (hasActiveSession) {
+ const activeSessions = yield* adapter.listSessions();
+ const existing = activeSessions.find(
+ (session) => session.threadId === input.binding.threadId,
+ );
+ if (existing) {
+ yield* upsertSessionBinding(existing, input.binding.threadId);
+ yield* analytics.record("provider.session.recovered", {
+ provider: existing.provider,
+ strategy: "adopt-existing",
+ hasResumeCursor: existing.resumeCursor !== undefined,
+ });
+ return { adapter, session: existing } as const;
+ }
+ }
+
+ if (!hasResumeCursor) {
+ return yield* toValidationError(
+ input.operation,
+ `Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
+ );
+ }
+
+ const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
+ const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
+
+ const resumed = yield* adapter.startSession({
+ threadId: input.binding.threadId,
+ provider: input.binding.provider,
+ ...(persistedCwd ? { cwd: persistedCwd } : {}),
+ ...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
+ ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
+ runtimeMode: input.binding.runtimeMode ?? "full-access",
+ });
+ if (resumed.provider !== adapter.provider) {
+ return yield* toValidationError(
+ input.operation,
+ `Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
+ );
+ }
+
+ yield* upsertSessionBinding(resumed, input.binding.threadId);
+ yield* analytics.record("provider.session.recovered", {
+ provider: resumed.provider,
+ strategy: "resume-thread",
+ hasResumeCursor: resumed.resumeCursor !== undefined,
+ });
+ return { adapter, session: resumed } as const;
});
+ const resolveRoutableSession = Effect.fn("resolveRoutableSession")(function* (input: {
+ readonly threadId: ThreadId;
+ readonly operation: string;
+ readonly allowRecovery: boolean;
+ }) {
+ const bindingOption = yield* directory.getBinding(input.threadId);
+ const binding = Option.getOrUndefined(bindingOption);
+ if (!binding) {
+ return yield* toValidationError(
+ input.operation,
+ `Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
+ );
+ }
+ const adapter = yield* registry.getByProvider(binding.provider);
+
+ const hasRequestedSession = yield* adapter.hasSession(input.threadId);
+ if (hasRequestedSession) {
+ return { adapter, threadId: input.threadId, isActive: true } as const;
+ }
+
+ if (!input.allowRecovery) {
+ return { adapter, threadId: input.threadId, isActive: false } as const;
+ }
+
+ const recovered = yield* recoverSessionForThread({ binding, operation: input.operation });
+ return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const;
+ });
+
+ const startSession: ProviderServiceShape["startSession"] = Effect.fn("startSession")(
+ function* (threadId, rawInput) {
+ const parsed = yield* decodeInputOrValidationError({
+ operation: "ProviderService.startSession",
+ schema: ProviderSessionStartInput,
+ payload: rawInput,
+ });
+
+ const input = {
+ ...parsed,
+ threadId,
+ provider: parsed.provider ?? "codex",
+ };
+ const settings = yield* serverSettings.getSettings.pipe(
+ Effect.mapError((error) =>
+ toValidationError(
+ "ProviderService.startSession",
+ `Failed to load provider settings: ${error.message}`,
+ error,
+ ),
+ ),
+ );
+ if (!settings.providers[input.provider].enabled) {
+ return yield* toValidationError(
+ "ProviderService.startSession",
+ `Provider '${input.provider}' is disabled in T3 Code settings.`,
+ );
+ }
+ const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
+ const effectiveResumeCursor =
+ input.resumeCursor ??
+ (persistedBinding?.provider === input.provider ? persistedBinding.resumeCursor : undefined);
+ const adapter = yield* registry.getByProvider(input.provider);
+ const session = yield* adapter.startSession({
+ ...input,
+ ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
+ });
+
+ if (session.provider !== adapter.provider) {
+ return yield* toValidationError(
+ "ProviderService.startSession",
+ `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
+ );
+ }
+
+ yield* upsertSessionBinding(session, threadId, {
+ modelSelection: input.modelSelection,
+ });
+ yield* analytics.record("provider.session.started", {
+ provider: session.provider,
+ runtimeMode: input.runtimeMode,
+ hasResumeCursor: session.resumeCursor !== undefined,
+ hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0,
+ hasModel:
+ typeof input.modelSelection?.model === "string" &&
+ input.modelSelection.model.trim().length > 0,
+ });
+
+ return session;
+ },
+ );
+
+ const sendTurn: ProviderServiceShape["sendTurn"] = Effect.fn("sendTurn")(function* (rawInput) {
+ const parsed = yield* decodeInputOrValidationError({
+ operation: "ProviderService.sendTurn",
+ schema: ProviderSendTurnInput,
+ payload: rawInput,
+ });
+
+ const input = {
+ ...parsed,
+ attachments: parsed.attachments ?? [],
+ };
+ if (!input.input && input.attachments.length === 0) {
+ return yield* toValidationError(
+ "ProviderService.sendTurn",
+ "Either input text or at least one attachment is required",
+ );
+ }
+ const routed = yield* resolveRoutableSession({
+ threadId: input.threadId,
+ operation: "ProviderService.sendTurn",
+ allowRecovery: true,
+ });
+ const turn = yield* routed.adapter.sendTurn(input);
+ yield* directory.upsert({
+ threadId: input.threadId,
+ provider: routed.adapter.provider,
+ status: "running",
+ ...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
+ runtimePayload: {
+ ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
+ activeTurnId: turn.turnId,
+ lastRuntimeEvent: "provider.sendTurn",
+ lastRuntimeEventAt: new Date().toISOString(),
+ },
+ });
+ yield* analytics.record("provider.turn.sent", {
+ provider: routed.adapter.provider,
+ model: input.modelSelection?.model,
+ interactionMode: input.interactionMode,
+ attachmentCount: input.attachments.length,
+ hasInput: typeof input.input === "string" && input.input.trim().length > 0,
+ });
+ return turn;
+ });
+
+ const interruptTurn: ProviderServiceShape["interruptTurn"] = Effect.fn("interruptTurn")(
+ function* (rawInput) {
+ const input = yield* decodeInputOrValidationError({
+ operation: "ProviderService.interruptTurn",
+ schema: ProviderInterruptTurnInput,
+ payload: rawInput,
+ });
+ const routed = yield* resolveRoutableSession({
+ threadId: input.threadId,
+ operation: "ProviderService.interruptTurn",
+ allowRecovery: true,
+ });
+ yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);
+ yield* analytics.record("provider.turn.interrupted", {
+ provider: routed.adapter.provider,
+ });
+ },
+ );
+
+ const respondToRequest: ProviderServiceShape["respondToRequest"] = Effect.fn("respondToRequest")(
+ function* (rawInput) {
+ const input = yield* decodeInputOrValidationError({
+ operation: "ProviderService.respondToRequest",
+ schema: ProviderRespondToRequestInput,
+ payload: rawInput,
+ });
+ const routed = yield* resolveRoutableSession({
+ threadId: input.threadId,
+ operation: "ProviderService.respondToRequest",
+ allowRecovery: true,
+ });
+ yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
+ yield* analytics.record("provider.request.responded", {
+ provider: routed.adapter.provider,
+ decision: input.decision,
+ });
+ },
+ );
+
+ const respondToUserInput: ProviderServiceShape["respondToUserInput"] = Effect.fn(
+ "respondToUserInput",
+ )(function* (rawInput) {
+ const input = yield* decodeInputOrValidationError({
+ operation: "ProviderService.respondToUserInput",
+ schema: ProviderRespondToUserInputInput,
+ payload: rawInput,
+ });
+ const routed = yield* resolveRoutableSession({
+ threadId: input.threadId,
+ operation: "ProviderService.respondToUserInput",
+ allowRecovery: true,
+ });
+ yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
+ });
+
+ const stopSession: ProviderServiceShape["stopSession"] = Effect.fn("stopSession")(
+ function* (rawInput) {
+ const input = yield* decodeInputOrValidationError({
+ operation: "ProviderService.stopSession",
+ schema: ProviderStopSessionInput,
+ payload: rawInput,
+ });
+ const routed = yield* resolveRoutableSession({
+ threadId: input.threadId,
+ operation: "ProviderService.stopSession",
+ allowRecovery: false,
+ });
+ if (routed.isActive) {
+ yield* routed.adapter.stopSession(routed.threadId);
+ }
+ yield* directory.remove(input.threadId);
+ yield* analytics.record("provider.session.stopped", {
+ provider: routed.adapter.provider,
+ });
+ },
+ );
+
+ const listSessions: ProviderServiceShape["listSessions"] = Effect.fn("listSessions")(
+ function* () {
+ const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) =>
+ adapter.listSessions(),
+ );
+ const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);
+ const persistedBindings = yield* directory.listThreadIds().pipe(
+ Effect.flatMap((threadIds) =>
+ Effect.forEach(
+ threadIds,
+ (threadId) =>
+ directory
+ .getBinding(threadId)
+ .pipe(Effect.orElseSucceed(() => Option.none())),
+ { concurrency: "unbounded" },
+ ),
+ ),
+ Effect.orElseSucceed(() => [] as Array>),
+ );
+ const bindingsByThreadId = new Map();
+ for (const bindingOption of persistedBindings) {
+ const binding = Option.getOrUndefined(bindingOption);
+ if (binding) {
+ bindingsByThreadId.set(binding.threadId, binding);
+ }
+ }
+
+ return activeSessions.map((session) => {
+ const binding = bindingsByThreadId.get(session.threadId);
+ if (!binding) {
+ return session;
+ }
+
+ const overrides: {
+ resumeCursor?: ProviderSession["resumeCursor"];
+ runtimeMode?: ProviderSession["runtimeMode"];
+ } = {};
+ if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
+ overrides.resumeCursor = binding.resumeCursor;
+ }
+ if (binding.runtimeMode !== undefined) {
+ overrides.runtimeMode = binding.runtimeMode;
+ }
+ return Object.assign({}, session, overrides);
+ });
+ },
+ );
+
+ const getCapabilities: ProviderServiceShape["getCapabilities"] = (provider) =>
+ registry.getByProvider(provider).pipe(Effect.map((adapter) => adapter.capabilities));
+
+ const rollbackConversation: ProviderServiceShape["rollbackConversation"] = Effect.fn(
+ "rollbackConversation",
+ )(function* (rawInput) {
+ const input = yield* decodeInputOrValidationError({
+ operation: "ProviderService.rollbackConversation",
+ schema: ProviderRollbackConversationInput,
+ payload: rawInput,
+ });
+ if (input.numTurns === 0) {
+ return;
+ }
+ const routed = yield* resolveRoutableSession({
+ threadId: input.threadId,
+ operation: "ProviderService.rollbackConversation",
+ allowRecovery: true,
+ });
+ yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
+ yield* analytics.record("provider.conversation.rolled_back", {
+ provider: routed.adapter.provider,
+ turns: input.numTurns,
+ });
+ });
+
+ const runStopAll = Effect.fn("runStopAll")(function* () {
+ const threadIds = yield* directory.listThreadIds();
+ const activeSessions = yield* Effect.forEach(adapters, (adapter) =>
+ adapter.listSessions(),
+ ).pipe(Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)));
+ yield* Effect.forEach(activeSessions, (session) =>
+ upsertSessionBinding(session, session.threadId, {
+ lastRuntimeEvent: "provider.stopAll",
+ lastRuntimeEventAt: new Date().toISOString(),
+ }),
+ ).pipe(Effect.asVoid);
+ yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid);
+ yield* Effect.forEach(threadIds, (threadId) =>
+ directory.getProvider(threadId).pipe(
+ Effect.flatMap((provider) =>
+ directory.upsert({
+ threadId,
+ provider,
+ status: "stopped",
+ runtimePayload: {
+ activeTurnId: null,
+ lastRuntimeEvent: "provider.stopAll",
+ lastRuntimeEventAt: new Date().toISOString(),
+ },
+ }),
+ ),
+ ),
+ ).pipe(Effect.asVoid);
+ yield* analytics.record("provider.sessions.stopped_all", {
+ sessionCount: threadIds.length,
+ });
+ yield* analytics.flush;
+ });
+
+ yield* Effect.addFinalizer(() =>
+ Effect.catch(runStopAll(), (cause) =>
+ Effect.logWarning("failed to stop provider service", { cause }),
+ ),
+ );
+
+ return {
+ startSession,
+ sendTurn,
+ interruptTurn,
+ respondToRequest,
+ respondToUserInput,
+ stopSession,
+ listSessions,
+ getCapabilities,
+ rollbackConversation,
+ // Each access creates a fresh PubSub subscription so that multiple
+ // consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
+ // independently receive all runtime events.
+ get streamEvents(): ProviderServiceShape["streamEvents"] {
+ return Stream.fromPubSub(runtimeEventPubSub);
+ },
+ } satisfies ProviderServiceShape;
+});
+
export const ProviderServiceLive = Layer.effect(ProviderService, makeProviderService());
export function makeProviderServiceLive(options?: ProviderServiceLiveOptions) {
From b9c7ea0581e171d2d4aad716f8391c670d5e3276 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 1 Apr 2026 09:26:52 -0700
Subject: [PATCH 16/17] [codex] migrate Effect.fn in
apps/server/src/orchestration/Layers/ProviderCommandReactor.ts (#1629)
Co-authored-by: codex
---
.../Layers/ProviderCommandReactor.ts | 61 ++++++++++---------
1 file changed, 31 insertions(+), 30 deletions(-)
diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
index d4f13ec727..8e2a19bcd1 100644
--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
@@ -724,39 +724,40 @@ const make = Effect.gen(function* () {
});
});
- const processDomainEvent = (event: ProviderIntentEvent) =>
- Effect.gen(function* () {
- switch (event.type) {
- case "thread.runtime-mode-set": {
- const thread = yield* resolveThread(event.payload.threadId);
- if (!thread?.session || thread.session.status === "stopped") {
- return;
- }
- const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
- yield* ensureSessionForThread(
- event.payload.threadId,
- event.occurredAt,
- cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {},
- );
+ const processDomainEvent = Effect.fn("processDomainEvent")(function* (
+ event: ProviderIntentEvent,
+ ) {
+ switch (event.type) {
+ case "thread.runtime-mode-set": {
+ const thread = yield* resolveThread(event.payload.threadId);
+ if (!thread?.session || thread.session.status === "stopped") {
return;
}
- case "thread.turn-start-requested":
- yield* processTurnStartRequested(event);
- return;
- case "thread.turn-interrupt-requested":
- yield* processTurnInterruptRequested(event);
- return;
- case "thread.approval-response-requested":
- yield* processApprovalResponseRequested(event);
- return;
- case "thread.user-input-response-requested":
- yield* processUserInputResponseRequested(event);
- return;
- case "thread.session-stop-requested":
- yield* processSessionStopRequested(event);
- return;
+ const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
+ yield* ensureSessionForThread(
+ event.payload.threadId,
+ event.occurredAt,
+ cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {},
+ );
+ return;
}
- });
+ case "thread.turn-start-requested":
+ yield* processTurnStartRequested(event);
+ return;
+ case "thread.turn-interrupt-requested":
+ yield* processTurnInterruptRequested(event);
+ return;
+ case "thread.approval-response-requested":
+ yield* processApprovalResponseRequested(event);
+ return;
+ case "thread.user-input-response-requested":
+ yield* processUserInputResponseRequested(event);
+ return;
+ case "thread.session-stop-requested":
+ yield* processSessionStopRequested(event);
+ return;
+ }
+ });
const processDomainEventSafely = (event: ProviderIntentEvent) =>
processDomainEvent(event).pipe(
From 9132c37c86cf5c382391dc65f4703ad407e8717e Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 1 Apr 2026 09:34:52 -0700
Subject: [PATCH 17/17] [codex] migrate Effect.fn in
apps/server/src/persistence/NodeSqliteClient.ts (#1633)
Co-authored-by: codex
---
.../src/persistence/NodeSqliteClient.ts | 261 +++++++++---------
1 file changed, 127 insertions(+), 134 deletions(-)
diff --git a/apps/server/src/persistence/NodeSqliteClient.ts b/apps/server/src/persistence/NodeSqliteClient.ts
index 78dbe8a1a9..77c316e8ca 100644
--- a/apps/server/src/persistence/NodeSqliteClient.ts
+++ b/apps/server/src/persistence/NodeSqliteClient.ts
@@ -72,160 +72,153 @@ const checkNodeSqliteCompat = () => {
return Effect.void;
};
-const makeWithDatabase = (
+const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
options: SqliteClientConfig,
openDatabase: () => DatabaseSync,
-): Effect.Effect =>
- Effect.gen(function* () {
- yield* checkNodeSqliteCompat();
+): Effect.fn.Return {
+ yield* checkNodeSqliteCompat();
- const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
- const transformRows = options.transformResultNames
- ? Statement.defaultTransforms(options.transformResultNames).array
- : undefined;
+ const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
+ const transformRows = options.transformResultNames
+ ? Statement.defaultTransforms(options.transformResultNames).array
+ : undefined;
- const makeConnection = Effect.gen(function* () {
- const scope = yield* Effect.scope;
- const db = openDatabase();
- yield* Scope.addFinalizer(
- scope,
- Effect.sync(() => db.close()),
- );
+ const makeConnection = Effect.gen(function* () {
+ const scope = yield* Effect.scope;
+ const db = openDatabase();
+ yield* Scope.addFinalizer(
+ scope,
+ Effect.sync(() => db.close()),
+ );
- const statementReaderCache = new WeakMap();
- const hasRows = (statement: StatementSync): boolean => {
- const cached = statementReaderCache.get(statement);
- if (cached !== undefined) {
- return cached;
- }
- const value = statement.columns().length > 0;
- statementReaderCache.set(statement, value);
- return value;
- };
+ const statementReaderCache = new WeakMap();
+ const hasRows = (statement: StatementSync): boolean => {
+ const cached = statementReaderCache.get(statement);
+ if (cached !== undefined) {
+ return cached;
+ }
+ const value = statement.columns().length > 0;
+ statementReaderCache.set(statement, value);
+ return value;
+ };
- const prepareCache = yield* Cache.make({
- capacity: options.prepareCacheSize ?? 200,
- timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
- lookup: (sql: string) =>
- Effect.try({
- try: () => db.prepare(sql),
- catch: (cause) =>
- new SqlError({
- reason: classifySqliteError(cause, {
- message: "Failed to prepare statement",
- operation: "prepare",
- }),
+ const prepareCache = yield* Cache.make({
+ capacity: options.prepareCacheSize ?? 200,
+ timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
+ lookup: (sql: string) =>
+ Effect.try({
+ try: () => db.prepare(sql),
+ catch: (cause) =>
+ new SqlError({
+ reason: classifySqliteError(cause, {
+ message: "Failed to prepare statement",
+ operation: "prepare",
}),
- }),
+ }),
+ }),
+ });
+
+ const runStatement = (statement: StatementSync, params: ReadonlyArray, raw: boolean) =>
+ Effect.withFiber, SqlError>((fiber) => {
+ statement.setReadBigInts(Boolean(ServiceMap.get(fiber.services, Client.SafeIntegers)));
+ try {
+ if (hasRows(statement)) {
+ return Effect.succeed(statement.all(...(params as any)));
+ }
+ const result = statement.run(...(params as any));
+ return Effect.succeed(raw ? (result as unknown as ReadonlyArray) : []);
+ } catch (cause) {
+ return Effect.fail(
+ new SqlError({
+ reason: classifySqliteError(cause, {
+ message: "Failed to execute statement",
+ operation: "execute",
+ }),
+ }),
+ );
+ }
});
- const runStatement = (
- statement: StatementSync,
- params: ReadonlyArray,
- raw: boolean,
- ) =>
- Effect.withFiber, SqlError>((fiber) => {
- statement.setReadBigInts(Boolean(ServiceMap.get(fiber.services, Client.SafeIntegers)));
- try {
- if (hasRows(statement)) {
- return Effect.succeed(statement.all(...(params as any)));
- }
- const result = statement.run(...(params as any));
- return Effect.succeed(raw ? (result as unknown as ReadonlyArray) : []);
- } catch (cause) {
- return Effect.fail(
+ const run = (sql: string, params: ReadonlyArray, raw = false) =>
+ Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw));
+
+ const runValues = (sql: string, params: ReadonlyArray) =>
+ Effect.acquireUseRelease(
+ Cache.get(prepareCache, sql),
+ (statement) =>
+ Effect.try({
+ try: () => {
+ if (hasRows(statement)) {
+ statement.setReturnArrays(true);
+ // Safe to cast to array after we've setReturnArrays(true)
+ return statement.all(...(params as any)) as unknown as ReadonlyArray<
+ ReadonlyArray
+ >;
+ }
+ statement.run(...(params as any));
+ return [];
+ },
+ catch: (cause) =>
new SqlError({
reason: classifySqliteError(cause, {
message: "Failed to execute statement",
operation: "execute",
}),
}),
- );
- }
- });
-
- const run = (sql: string, params: ReadonlyArray, raw = false) =>
- Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw));
-
- const runValues = (sql: string, params: ReadonlyArray) =>
- Effect.acquireUseRelease(
- Cache.get(prepareCache, sql),
- (statement) =>
- Effect.try({
- try: () => {
- if (hasRows(statement)) {
- statement.setReturnArrays(true);
- // Safe to cast to array after we've setReturnArrays(true)
- return statement.all(...(params as any)) as unknown as ReadonlyArray<
- ReadonlyArray
- >;
- }
- statement.run(...(params as any));
- return [];
- },
- catch: (cause) =>
- new SqlError({
- reason: classifySqliteError(cause, {
- message: "Failed to execute statement",
- operation: "execute",
- }),
- }),
- }),
- (statement) =>
- Effect.sync(() => {
- if (hasRows(statement)) {
- statement.setReturnArrays(false);
- }
- }),
- );
-
- return identity({
- execute(sql, params, rowTransform) {
- return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
- },
- executeRaw(sql, params) {
- return run(sql, params, true);
- },
- executeValues(sql, params) {
- return runValues(sql, params);
- },
- executeUnprepared(sql, params, rowTransform) {
- const effect = runStatement(db.prepare(sql), params ?? [], false);
- return rowTransform ? Effect.map(effect, rowTransform) : effect;
- },
- executeStream(_sql, _params) {
- return Stream.die("executeStream not implemented");
- },
- });
- });
-
- const semaphore = yield* Semaphore.make(1);
- const connection = yield* makeConnection;
-
- const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));
- const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
- const fiber = Fiber.getCurrent()!;
- const scope = ServiceMap.getUnsafe(fiber.services, Scope.Scope);
- return Effect.as(
- Effect.tap(restore(semaphore.take(1)), () =>
- Scope.addFinalizer(scope, semaphore.release(1)),
- ),
- connection,
+ }),
+ (statement) =>
+ Effect.sync(() => {
+ if (hasRows(statement)) {
+ statement.setReturnArrays(false);
+ }
+ }),
);
- });
- return yield* Client.make({
- acquirer,
- compiler,
- transactionAcquirer,
- spanAttributes: [
- ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
- [ATTR_DB_SYSTEM_NAME, "sqlite"],
- ],
- transformRows,
+ return identity({
+ execute(sql, params, rowTransform) {
+ return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
+ },
+ executeRaw(sql, params) {
+ return run(sql, params, true);
+ },
+ executeValues(sql, params) {
+ return runValues(sql, params);
+ },
+ executeUnprepared(sql, params, rowTransform) {
+ const effect = runStatement(db.prepare(sql), params ?? [], false);
+ return rowTransform ? Effect.map(effect, rowTransform) : effect;
+ },
+ executeStream(_sql, _params) {
+ return Stream.die("executeStream not implemented");
+ },
});
});
+ const semaphore = yield* Semaphore.make(1);
+ const connection = yield* makeConnection;
+
+ const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));
+ const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
+ const fiber = Fiber.getCurrent()!;
+ const scope = ServiceMap.getUnsafe(fiber.services, Scope.Scope);
+ return Effect.as(
+ Effect.tap(restore(semaphore.take(1)), () => Scope.addFinalizer(scope, semaphore.release(1))),
+ connection,
+ );
+ });
+
+ return yield* Client.make({
+ acquirer,
+ compiler,
+ transactionAcquirer,
+ spanAttributes: [
+ ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
+ [ATTR_DB_SYSTEM_NAME, "sqlite"],
+ ],
+ transformRows,
+ });
+});
+
const make = (
options: SqliteClientConfig,
): Effect.Effect =>