Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7350dc32c9 |
No files matched your search
@@ -3,7 +3,7 @@
|
||||
## Task Completion Requirements
|
||||
|
||||
- All of `bun fmt`, `bun lint`, and `bun typecheck` must pass before considering tasks completed.
|
||||
- NEVER run `bun test`. Always use `bun run test` (runs Vitest)..
|
||||
- NEVER run `bun test`. Always use `bun run test` (runs Vitest).
|
||||
|
||||
## Project Snapshot
|
||||
|
||||
|
||||
@@ -21,8 +21,8 @@ const make = Effect.gen(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
|
||||
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
|
||||
function* (input) {
|
||||
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const operation = "CheckpointDiffQuery.getTurnDiff";
|
||||
|
||||
if (input.fromTurnCount === input.toTurnCount) {
|
||||
@@ -149,8 +149,7 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
return turnDiff;
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
|
||||
input: OrchestrationGetFullThreadDiffInput,
|
||||
|
||||
@@ -86,140 +86,139 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
|
||||
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
|
||||
"captureCheckpoint",
|
||||
)(function* (input) {
|
||||
const operation = "CheckpointStore.captureCheckpoint";
|
||||
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const operation = "CheckpointStore.captureCheckpoint";
|
||||
|
||||
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: "[email protected]",
|
||||
GIT_COMMITTER_NAME: "T3 Code",
|
||||
GIT_COMMITTER_EMAIL: "[email protected]",
|
||||
};
|
||||
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: "[email protected]",
|
||||
GIT_COMMITTER_NAME: "T3 Code",
|
||||
GIT_COMMITTER_EMAIL: "[email protected]",
|
||||
};
|
||||
|
||||
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"] = Effect.fn(
|
||||
"restoreCheckpoint",
|
||||
)(function* (input) {
|
||||
const operation = "CheckpointStore.restoreCheckpoint";
|
||||
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
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", "--", "."],
|
||||
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
|
||||
});
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["clean", "-fd", "--", "."],
|
||||
});
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["reset", "--quiet", "--", "."],
|
||||
});
|
||||
}
|
||||
|
||||
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")(
|
||||
function* (input) {
|
||||
return true;
|
||||
});
|
||||
|
||||
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const operation = "CheckpointStore.diffCheckpoints";
|
||||
|
||||
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
|
||||
@@ -248,26 +247,24 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
return result.stdout;
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn(
|
||||
"deleteCheckpointRefs",
|
||||
)(function* (input) {
|
||||
const operation = "CheckpointStore.deleteCheckpointRefs";
|
||||
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
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,
|
||||
|
||||
@@ -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 = Effect.fn("runClaudeJson")(function* <S extends Schema.Top>({
|
||||
const runClaudeJson = <S extends Schema.Top>({
|
||||
operation,
|
||||
cwd,
|
||||
prompt,
|
||||
@@ -82,126 +82,132 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
modelSelection: ClaudeModelSelection;
|
||||
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
||||
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 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)),
|
||||
},
|
||||
},
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
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 } : {}),
|
||||
};
|
||||
|
||||
const child = yield* commandSpawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
|
||||
),
|
||||
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 [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
readStreamAsString(operation, child.stdout),
|
||||
readStreamAsString(operation, child.stderr),
|
||||
child.exitCode.pipe(
|
||||
const child = yield* commandSpawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
|
||||
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ 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",
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ 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
|
||||
? `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),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
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}.`,
|
||||
});
|
||||
}
|
||||
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 stdout;
|
||||
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,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
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),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
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,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TextGenerationShape methods
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -85,43 +85,44 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
||||
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
|
||||
const materializeImageAttachments = (
|
||||
_operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle",
|
||||
attachments: BranchNameGenerationInput["attachments"],
|
||||
): Effect.fn.Return<MaterializedImageAttachments, TextGenerationError> {
|
||||
if (!attachments || attachments.length === 0) {
|
||||
return { imagePaths: [] };
|
||||
}
|
||||
|
||||
const imagePaths: string[] = [];
|
||||
for (const attachment of attachments) {
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
): Effect.Effect<MaterializedImageAttachments, TextGenerationError> =>
|
||||
Effect.gen(function* () {
|
||||
if (!attachments || attachments.length === 0) {
|
||||
return { imagePaths: [] };
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
return { imagePaths };
|
||||
});
|
||||
const imagePaths: string[] = [];
|
||||
for (const attachment of attachments) {
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
|
||||
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);
|
||||
}
|
||||
return { imagePaths };
|
||||
});
|
||||
|
||||
const runCodexJson = <S extends Schema.Top>({
|
||||
operation,
|
||||
cwd,
|
||||
prompt,
|
||||
@@ -141,138 +142,139 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
imagePaths?: ReadonlyArray<string>;
|
||||
cleanupPaths?: ReadonlyArray<string>;
|
||||
modelSelection: CodexModelSelection;
|
||||
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
||||
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,
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const schemaPath = yield* writeTempFile(
|
||||
operation,
|
||||
"codex-schema",
|
||||
JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
|
||||
);
|
||||
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]),
|
||||
"-",
|
||||
],
|
||||
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)),
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
|
||||
},
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdin: {
|
||||
stream: Stream.encodeText(Stream.make(prompt)),
|
||||
},
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
);
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
const child = yield* commandSpawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
|
||||
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 [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"),
|
||||
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,
|
||||
}),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ 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}.`,
|
||||
});
|
||||
}
|
||||
);
|
||||
}).pipe(Effect.ensuring(cleanup));
|
||||
});
|
||||
|
||||
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,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.ensuring(cleanup));
|
||||
});
|
||||
|
||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
|
||||
"CodexTextGeneration.generateCommitMessage",
|
||||
)(function* (input) {
|
||||
|
||||
@@ -31,15 +31,6 @@ 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",
|
||||
@@ -98,15 +89,6 @@ 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",
|
||||
@@ -274,7 +256,6 @@ 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");
|
||||
@@ -282,7 +263,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, ["trae", "vscode-insiders", "vscodium", "file-manager"]);
|
||||
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
+28
-27
@@ -220,37 +220,38 @@ export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
||||
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
|
||||
});
|
||||
|
||||
export const launchDetached = (launch: EditorLaunch) =>
|
||||
Effect.gen(function* () {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||
export const launchDetached = Effect.fn("launchDetached")(function* (
|
||||
launch: EditorLaunch,
|
||||
): Effect.fn.Return<void, OpenError> {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||
}
|
||||
|
||||
yield* Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(launch.command, [...launch.args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
|
||||
);
|
||||
}
|
||||
|
||||
yield* Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(launch.command, [...launch.args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
|
||||
);
|
||||
}
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
};
|
||||
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
};
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (cause) =>
|
||||
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
|
||||
);
|
||||
});
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (cause) =>
|
||||
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const open = yield* Effect.tryPromise({
|
||||
|
||||
@@ -724,40 +724,39 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
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") {
|
||||
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 } : {},
|
||||
);
|
||||
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;
|
||||
}
|
||||
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(
|
||||
|
||||
@@ -16,14 +16,15 @@ const defaultSqliteClientLoaders = {
|
||||
node: () => import("../NodeSqliteClient.ts"),
|
||||
} satisfies Record<string, () => Promise<Loader>>;
|
||||
|
||||
const makeRuntimeSqliteLayer = Effect.fn("makeRuntimeSqliteLayer")(function* (
|
||||
const makeRuntimeSqliteLayer = (
|
||||
config: RuntimeSqliteLayerConfig,
|
||||
) {
|
||||
const runtime = process.versions.bun !== undefined ? "bun" : "node";
|
||||
const loader = defaultSqliteClientLoaders[runtime];
|
||||
const clientModule = yield* Effect.promise<Loader>(loader);
|
||||
return clientModule.layer(config);
|
||||
}, Layer.unwrap);
|
||||
): Layer.Layer<SqlClient.SqlClient> =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = process.versions.bun !== undefined ? "bun" : "node";
|
||||
const loader = defaultSqliteClientLoaders[runtime];
|
||||
const clientModule = yield* Effect.promise<Loader>(loader);
|
||||
return clientModule.layer(config);
|
||||
}).pipe(Layer.unwrap);
|
||||
|
||||
const setup = Layer.effectDiscard(
|
||||
Effect.gen(function* () {
|
||||
@@ -34,15 +35,14 @@ const setup = Layer.effectDiscard(
|
||||
}),
|
||||
);
|
||||
|
||||
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 });
|
||||
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 });
|
||||
|
||||
return Layer.provideMerge(setup, makeRuntimeSqliteLayer({ filename: dbPath }));
|
||||
}, Layer.unwrap);
|
||||
return Layer.provideMerge(setup, makeRuntimeSqliteLayer({ filename: dbPath }));
|
||||
}).pipe(Layer.unwrap);
|
||||
|
||||
export const SqlitePersistenceMemory = Layer.provideMerge(
|
||||
setup,
|
||||
|
||||
@@ -92,20 +92,19 @@ export interface RunMigrationsOptions {
|
||||
*
|
||||
* @returns Effect containing array of executed migrations
|
||||
*/
|
||||
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;
|
||||
});
|
||||
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;
|
||||
});
|
||||
|
||||
/**
|
||||
* Layer that runs migrations when the layer is built.
|
||||
|
||||
@@ -72,153 +72,160 @@ const checkNodeSqliteCompat = () => {
|
||||
return Effect.void;
|
||||
};
|
||||
|
||||
const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
|
||||
const makeWithDatabase = (
|
||||
options: SqliteClientConfig,
|
||||
openDatabase: () => DatabaseSync,
|
||||
): Effect.fn.Return<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> {
|
||||
yield* checkNodeSqliteCompat();
|
||||
): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
|
||||
Effect.gen(function* () {
|
||||
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<StatementSync, boolean>();
|
||||
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 runStatement = (statement: StatementSync, params: ReadonlyArray<unknown>, raw: boolean) =>
|
||||
Effect.withFiber<ReadonlyArray<any>, 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<any>) : []);
|
||||
} catch (cause) {
|
||||
return Effect.fail(
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to execute statement",
|
||||
operation: "execute",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const statementReaderCache = new WeakMap<StatementSync, boolean>();
|
||||
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 run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
|
||||
Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw));
|
||||
|
||||
const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
|
||||
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<unknown>
|
||||
>;
|
||||
}
|
||||
statement.run(...(params as any));
|
||||
return [];
|
||||
},
|
||||
catch: (cause) =>
|
||||
const runStatement = (
|
||||
statement: StatementSync,
|
||||
params: ReadonlyArray<unknown>,
|
||||
raw: boolean,
|
||||
) =>
|
||||
Effect.withFiber<ReadonlyArray<any>, 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<any>) : []);
|
||||
} catch (cause) {
|
||||
return Effect.fail(
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to execute statement",
|
||||
operation: "execute",
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
(statement) =>
|
||||
Effect.sync(() => {
|
||||
if (hasRows(statement)) {
|
||||
statement.setReturnArrays(false);
|
||||
}
|
||||
}),
|
||||
);
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return identity<Connection>({
|
||||
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 run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
|
||||
Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw));
|
||||
|
||||
const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
|
||||
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<unknown>
|
||||
>;
|
||||
}
|
||||
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<Connection>({
|
||||
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 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<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
|
||||
|
||||
@@ -427,16 +427,17 @@ const probeClaudeCapabilities = (binaryPath: string) => {
|
||||
);
|
||||
};
|
||||
|
||||
const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (args: ReadonlyArray<string>) {
|
||||
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",
|
||||
const runClaudeCommand = (args: ReadonlyArray<string>) =>
|
||||
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);
|
||||
});
|
||||
return yield* spawnAndCollect(claudeSettings.binaryPath, command);
|
||||
});
|
||||
|
||||
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
|
||||
resolveSubscriptionType?: (binaryPath: string) => Effect.Effect<string | undefined>,
|
||||
|
||||
@@ -306,20 +306,21 @@ const probeCodexCapabilities = (input: {
|
||||
}),
|
||||
);
|
||||
|
||||
const runCodexCommand = Effect.fn("runCodexCommand")(function* (args: ReadonlyArray<string>) {
|
||||
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 } : {}),
|
||||
},
|
||||
const runCodexCommand = (args: ReadonlyArray<string>) =>
|
||||
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);
|
||||
});
|
||||
return yield* spawnAndCollect(codexSettings.binaryPath, command);
|
||||
});
|
||||
|
||||
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
|
||||
resolveAccount?: (input: {
|
||||
|
||||
@@ -74,180 +74,184 @@ function resolveStreamLabel(stream: EventNdjsonStream): string {
|
||||
}
|
||||
}
|
||||
|
||||
const toLogMessage = Effect.fn("toLogMessage")(function* (
|
||||
event: unknown,
|
||||
): Effect.fn.Return<string | undefined> {
|
||||
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,
|
||||
function toLogMessage(event: unknown): Effect.Effect<string | undefined> {
|
||||
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 };
|
||||
}
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (typeof serialized.value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
if (!serialized.ok) {
|
||||
yield* logWarning("failed to serialize provider event log record", {
|
||||
error: serialized.error,
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return serialized.value;
|
||||
});
|
||||
if (typeof serialized.value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const makeThreadWriter = Effect.fn("makeThreadWriter")(function* (input: {
|
||||
return serialized.value;
|
||||
});
|
||||
}
|
||||
|
||||
function makeThreadWriter(input: {
|
||||
readonly filePath: string;
|
||||
readonly maxBytes: number;
|
||||
readonly maxFiles: number;
|
||||
readonly batchWindowMs: number;
|
||||
readonly streamLabel: string;
|
||||
}): Effect.fn.Return<ThreadWriter | undefined> {
|
||||
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: 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,
|
||||
});
|
||||
}): Effect.Effect<ThreadWriter | undefined> {
|
||||
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 };
|
||||
}
|
||||
}),
|
||||
}).pipe(Effect.provideService(Scope.Scope, scope));
|
||||
});
|
||||
|
||||
const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
|
||||
if (!sinkResult.ok) {
|
||||
yield* logWarning("failed to initialize provider thread log file", {
|
||||
filePath: input.filePath,
|
||||
error: sinkResult.error,
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
writeMessage(message: string) {
|
||||
return Effect.log(message).pipe(Effect.provide(loggerLayer));
|
||||
},
|
||||
close() {
|
||||
return Scope.close(scope, Exit.void);
|
||||
},
|
||||
} satisfies ThreadWriter;
|
||||
});
|
||||
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 };
|
||||
}
|
||||
});
|
||||
|
||||
export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function* (
|
||||
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 function makeEventNdjsonLogger(
|
||||
filePath: string,
|
||||
options: EventNdjsonLoggerOptions,
|
||||
): Effect.fn.Return<EventNdjsonLogger | undefined> {
|
||||
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.Effect<EventNdjsonLogger | undefined> {
|
||||
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);
|
||||
|
||||
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,
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
});
|
||||
if (directoryReady !== true) {
|
||||
yield* logWarning("failed to create provider event log directory", {
|
||||
|
||||
const threadWriters = new Map<string, ThreadWriter>();
|
||||
const failedSegments = new Set<string>();
|
||||
|
||||
const resolveThreadWriter = (threadSegment: string): Effect.Effect<ThreadWriter | undefined> =>
|
||||
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,
|
||||
error: directoryReady.error,
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
write(event: unknown, threadId: ThreadId | null) {
|
||||
return Effect.gen(function* () {
|
||||
const threadSegment = resolveThreadSegment(threadId);
|
||||
const message = yield* toLogMessage(event);
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
|
||||
const threadWriters = new Map<string, ThreadWriter>();
|
||||
const failedSegments = new Set<string>();
|
||||
const writer = yield* resolveThreadWriter(threadSegment);
|
||||
if (!writer) {
|
||||
return;
|
||||
}
|
||||
|
||||
const resolveThreadWriter = Effect.fn("resolveThreadWriter")(function* (
|
||||
threadSegment: string,
|
||||
): Effect.fn.Return<ThreadWriter | undefined> {
|
||||
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;
|
||||
yield* writer.writeMessage(message);
|
||||
});
|
||||
},
|
||||
close() {
|
||||
return Effect.gen(function* () {
|
||||
for (const writer of threadWriters.values()) {
|
||||
yield* writer.close();
|
||||
}
|
||||
threadWriters.clear();
|
||||
});
|
||||
},
|
||||
} satisfies EventNdjsonLogger;
|
||||
});
|
||||
|
||||
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;
|
||||
});
|
||||
}
|
||||
@@ -22,31 +22,30 @@ export interface ProviderAdapterRegistryLiveOptions {
|
||||
readonly adapters?: ReadonlyArray<ProviderAdapterShape<ProviderAdapterError>>;
|
||||
}
|
||||
|
||||
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 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 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,
|
||||
|
||||
@@ -40,19 +40,18 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
yield* loadProviders(codexProvider, claudeProvider),
|
||||
);
|
||||
|
||||
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);
|
||||
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);
|
||||
|
||||
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,
|
||||
@@ -61,30 +60,28 @@ 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) =>
|
||||
refresh(provider).pipe(
|
||||
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(
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orElseSucceed(() => []),
|
||||
),
|
||||
|
||||
@@ -131,470 +131,472 @@ function readPersistedCwd(
|
||||
return trimmed.length > 0 ? trimmed : 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 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 registry = yield* ProviderAdapterRegistry;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
|
||||
const registry = yield* ProviderAdapterRegistry;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
|
||||
|
||||
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
Effect.succeed(event).pipe(
|
||||
Effect.tap((canonicalEvent) =>
|
||||
canonicalEventLogger ? canonicalEventLogger.write(canonicalEvent, null) : Effect.void,
|
||||
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
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<void> =>
|
||||
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<ProviderRuntimeBinding>())),
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
),
|
||||
Effect.orElseSucceed(() => [] as Array<Option.Option<ProviderRuntimeBinding>>),
|
||||
);
|
||||
const bindingsByThreadId = new Map<ThreadId, ProviderRuntimeBinding>();
|
||||
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 }),
|
||||
),
|
||||
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<void> =>
|
||||
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(),
|
||||
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);
|
||||
},
|
||||
});
|
||||
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;
|
||||
} satisfies ProviderServiceShape;
|
||||
});
|
||||
|
||||
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<ProviderRuntimeBinding>())),
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
),
|
||||
Effect.orElseSucceed(() => [] as Array<Option.Option<ProviderRuntimeBinding>>),
|
||||
);
|
||||
const bindingsByThreadId = new Map<ThreadId, ProviderRuntimeBinding>();
|
||||
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) {
|
||||
|
||||
@@ -5,70 +5,68 @@ import * as Semaphore from "effect/Semaphore";
|
||||
import type { ServerProviderShape } from "./Services/ServerProvider";
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(function* <
|
||||
Settings,
|
||||
>(input: {
|
||||
export function makeManagedServerProvider<Settings>(input: {
|
||||
readonly getSettings: Effect.Effect<Settings>;
|
||||
readonly streamSettings: Stream.Stream<Settings>;
|
||||
readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
|
||||
readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;
|
||||
readonly refreshInterval?: Duration.Input;
|
||||
}): Effect.fn.Return<ServerProviderShape, ServerSettingsError, Scope.Scope> {
|
||||
const refreshSemaphore = yield* Semaphore.make(1);
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ServerProvider>(),
|
||||
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.Effect<ServerProviderShape, ServerSettingsError, Scope.Scope> {
|
||||
return Effect.gen(function* () {
|
||||
const refreshSemaphore = yield* Semaphore.make(1);
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ServerProvider>(),
|
||||
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 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 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 nextSnapshot = yield* input.checkProvider;
|
||||
yield* Ref.set(settingsRef, nextSettings);
|
||||
yield* Ref.set(snapshotRef, nextSnapshot);
|
||||
yield* PubSub.publish(changesPubSub, nextSnapshot);
|
||||
return nextSnapshot;
|
||||
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 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;
|
||||
});
|
||||
}
|
||||
@@ -70,35 +70,34 @@ const makeAnalyticsService = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const sendBatch = Effect.fn("sendBatch")(function* (
|
||||
events: ReadonlyArray<BufferedAnalyticsEvent>,
|
||||
) {
|
||||
if (!telemetryConfig.enabled || !identifier) return;
|
||||
const sendBatch = (events: ReadonlyArray<BufferedAnalyticsEvent>) =>
|
||||
Effect.gen(function* () {
|
||||
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) {
|
||||
|
||||
@@ -1407,52 +1407,6 @@ 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();
|
||||
|
||||
|
||||
@@ -20,20 +20,6 @@ export const CursorIcon: Icon = (props) => (
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const TraeIcon: Icon = (props) => (
|
||||
<svg {...props} viewBox="0 0 24 24" fill="currentColor">
|
||||
{/* Back rectangle: left strip + bottom strip drawn separately — empty bottom-left corner is the gap between them */}
|
||||
<rect x="1" y="4" width="3" height="14" />
|
||||
<rect x="4" y="18" width="18" height="3" />
|
||||
{/* Front frame: top bar + right bar only — left and bottom are replaced by the back strips above */}
|
||||
<rect x="4" y="4" width="18" height="3" />
|
||||
<rect x="19" y="7" width="3" height="11" />
|
||||
{/* Two diamonds, offset slightly to the right within the open area */}
|
||||
<path d="M11 10L13 12L11 14L9 12Z" />
|
||||
<path d="M16 10L18 12L16 14L14 12Z" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const VisualStudioCode: Icon = (props) => {
|
||||
const id = useId();
|
||||
const maskId = `${id}-vscode-a`;
|
||||
|
||||
@@ -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, TraeIcon, VisualStudioCode, Zed } from "../Icons";
|
||||
import { AntigravityIcon, CursorIcon, Icon, VisualStudioCode, Zed } from "../Icons";
|
||||
import { isMacPlatform, isWindowsPlatform } from "~/lib/utils";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
|
||||
@@ -17,11 +17,6 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray<Editor
|
||||
Icon: CursorIcon,
|
||||
value: "cursor",
|
||||
},
|
||||
{
|
||||
label: "Trae",
|
||||
Icon: TraeIcon,
|
||||
value: "trae",
|
||||
},
|
||||
{
|
||||
label: "VS Code",
|
||||
Icon: VisualStudioCode,
|
||||
|
||||
@@ -3,7 +3,6 @@ import { TrimmedNonEmptyString } from "./baseSchemas";
|
||||
|
||||
export const EDITORS = [
|
||||
{ id: "cursor", label: "Cursor", command: "cursor", supportsGoto: true },
|
||||
{ id: "trae", label: "Trae", command: "trae", supportsGoto: true },
|
||||
{ id: "vscode", label: "VS Code", command: "code", supportsGoto: true },
|
||||
{
|
||||
id: "vscode-insiders",
|
||||
|
||||
Reference in new issue
Block a user