Skip to content
TypeScript

fix(server): Pi thread titles use linked PR context (#16210)

Julius Marminge4ae976dbae39
diff --git a/apps/server/src/textGeneration/AntigravityTextGeneration.ts b/apps/server/src/textGeneration/AntigravityTextGeneration.ts
index 86125e1a825..27144025c0b 100644
--- a/apps/server/src/textGeneration/AntigravityTextGeneration.ts
+++ b/apps/server/src/textGeneration/AntigravityTextGeneration.ts
@@ -1,10 +1,4 @@
-import {
- type ModelSelection,
- type ProviderSetupError,
- TextGenerationError,
-} from "@t3tools/contracts";
-import { formatGeneratedBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
-import { extractJsonObject } from "@t3tools/shared/schemaJson";
+import { type ProviderSetupError, TextGenerationError } from "@t3tools/contracts";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -20,18 +14,7 @@ import { type AcpError, AcpRequestError } from "effect-acp/errors";
import { applyAntigravityAcpModelSelection } from "../provider/acp/AntigravityAcpSupport.ts";
import { removeAntigravitySessionFiles } from "../provider/acp/AntigravitySessionFiles.ts";
import type { AcpSessionRuntime } from "../provider/acp/AcpSessionRuntime.ts";
-import type * as TextGeneration from "./TextGeneration.ts";
-import {
- buildBranchNamePrompt,
- buildCommitMessagePrompt,
- buildPrContentPrompt,
- buildThreadTitlePrompt,
-} from "./TextGenerationPrompts.ts";
-import {
- sanitizeCommitSubject,
- sanitizePrTitle,
- sanitizeThreadTitle,
-} from "./TextGenerationUtils.ts";
+import * as TextGenerationOperations from "./TextGenerationOperations.ts";
const ANTIGRAVITY_TIMEOUT_MS = 180_000;
const MAX_OUTPUT_CHARS = 128_000;
@@ -119,13 +102,9 @@ export const makeAntigravityTextGeneration = Effect.fn("makeAntigravityTextGener
Effect.provideService(Path.Path, path),
);
+ // Ignores `cwd`: the helper runs in an empty temp directory, away from the project.
const runAntigravityJson = Effect.fn("AntigravityTextGeneration.runJson")(
- function* <S extends Schema.Top>(input: {
- readonly operation: keyof TextGeneration.TextGeneration["Service"];
- readonly prompt: string;
- readonly outputSchema: S;
- readonly modelSelection: ModelSelection;
- }) {
+ function* <S extends Schema.Top>(input: TextGenerationOperations.Request<S>) {
const { operation } = input;
const scope = yield* Scope.make();
yield* Effect.addFinalizer((exit) => Scope.close(scope, exit));
@@ -290,17 +269,7 @@ export const makeAntigravityTextGeneration = Effect.fn("makeAntigravityTextGener
detail: "Antigravity returned empty text generation output.",
});
}
- const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(input.outputSchema));
- return yield* decodeOutput(extractJsonObject(rawResult)).pipe(
- Effect.mapError(
- (cause) =>
- new TextGenerationError({
- operation,
- detail: "Antigravity returned invalid structured output.",
- cause,
- }),
- ),
- );
+ return yield* TextGenerationOperations.decodeJsonReply(input, "Antigravity", rawResult);
}).pipe(
Effect.scoped,
Effect.timeoutOption(ANTIGRAVITY_TIMEOUT_MS),
@@ -337,82 +306,5 @@ export const makeAntigravityTextGeneration = Effect.fn("makeAntigravityTextGener
),
);
- const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
- Effect.fn("AntigravityTextGeneration.generateCommitMessage")(function* (input) {
- const generated = yield* runAntigravityJson({
- operation: "generateCommitMessage",
- ...buildCommitMessagePrompt({
- branch: input.branch,
- stagedSummary: input.stagedSummary,
- stagedPatch: input.stagedPatch,
- includeBranch: input.includeBranch === true,
- policy: input.policy,
- }),
- modelSelection: input.modelSelection,
- });
- return {
- subject: sanitizeCommitSubject(generated.subject),
- body: generated.body.trim(),
- ...("branch" in generated && typeof generated.branch === "string"
- ? { branch: sanitizeFeatureBranchName(generated.branch) }
- : {}),
- };
- });
-
- const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
- Effect.fn("AntigravityTextGeneration.generatePrContent")(function* (input) {
- const generated = yield* runAntigravityJson({
- operation: "generatePrContent",
- ...buildPrContentPrompt({
- baseBranch: input.baseBranch,
- headBranch: input.headBranch,
- commitSummary: input.commitSummary,
- diffSummary: input.diffSummary,
- diffPatch: input.diffPatch,
- policy: input.policy,
- changeRequestTemplate: input.changeRequestTemplate,
- }),
- modelSelection: input.modelSelection,
- });
- return { title: sanitizePrTitle(generated.title), body: generated.body.trim() };
- });
-
- const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
- Effect.fn("AntigravityTextGeneration.generateBranchName")(function* (input) {
- const generated = yield* runAntigravityJson({
- operation: "generateBranchName",
- ...buildBranchNamePrompt({
- message: input.message,
- attachments: input.attachments,
- naming: input.naming,
- }),
- modelSelection: input.modelSelection,
- });
- return { branch: formatGeneratedBranchName(generated.branch, input.naming) };
- });
-
- const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
- Effect.fn("AntigravityTextGeneration.generateThreadTitle")(function* (input) {
- const generated = yield* runAntigravityJson({
- operation: "generateThreadTitle",
- ...buildThreadTitlePrompt({
- message: input.message,
- previousTitle: input.previousTitle,
- linkedContext: input.linkedContext,
- attachments: input.attachments,
- }),
- modelSelection: input.modelSelection,
- });
- return {
- title: sanitizeThreadTitle(generated.title),
- ...(generated.needsRefinement ? { needsRefinement: true } : {}),
- };
- });
-
- return {
- generateCommitMessage,
- generatePrContent,
- generateBranchName,
- generateThreadTitle,
- } satisfies TextGeneration.TextGeneration["Service"];
+ return TextGenerationOperations.fromRunner("AntigravityTextGeneration", runAntigravityJson);
});
diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.ts
index 28694dc15f4..5140ce3cdc3 100644
--- a/apps/server/src/textGeneration/ClaudeTextGeneration.ts
+++ b/apps/server/src/textGeneration/ClaudeTextGeneration.ts
@@ -14,25 +14,11 @@ import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
-import { type ClaudeSettings, type ModelSelection } from "@t3tools/contracts";
-import { formatGeneratedBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
+import { type ClaudeSettings, TextGenerationError } from "@t3tools/contracts";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
-import { TextGenerationError } from "@t3tools/contracts";
-import * as TextGeneration from "./TextGeneration.ts";
-import {
- buildBranchNamePrompt,
- buildCommitMessagePrompt,
- buildPrContentPrompt,
- buildThreadTitlePrompt,
-} from "./TextGenerationPrompts.ts";
-import {
- normalizeCliError,
- sanitizeCommitSubject,
- sanitizePrTitle,
- sanitizeThreadTitle,
- toJsonSchemaObject,
-} from "./TextGenerationUtils.ts";
+import * as TextGenerationOperations from "./TextGenerationOperations.ts";
+import { normalizeCliError, toJsonSchemaObject } from "./TextGenerationUtils.ts";
import {
getModelSelectionStringOptionValue,
getProviderOptionDescriptors,
@@ -98,11 +84,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
);
const encodeJsonForOperation = (
- operation:
- | "generateCommitMessage"
- | "generatePrContent"
- | "generateBranchName"
- | "generateThreadTitle",
+ operation: TextGenerationOperations.Operation,
value: unknown,
detail: string,
): Effect.Effect<string, TextGenerationError> =>
@@ -125,19 +107,13 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
operation,
cwd,
prompt,
- outputSchemaJson,
+ outputSchema: outputSchemaJson,
modelSelection,
- }: {
- operation:
- | "generateCommitMessage"
- | "generatePrContent"
- | "generateBranchName"
- | "generateThreadTitle";
- cwd: string;
- prompt: string;
- outputSchemaJson: S;
- modelSelection: ModelSelection;
- }): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
+ }: TextGenerationOperations.Request<S>): Effect.fn.Return<
+ S["Type"],
+ TextGenerationError,
+ S["DecodingServices"]
+ > {
const catalog = yield* scopedModelCatalog;
const resolvedModelSelection = {
...modelSelection,
@@ -310,111 +286,5 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
);
});
- // ---------------------------------------------------------------------------
- // TextGeneration service methods
- // ---------------------------------------------------------------------------
-
- const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
- Effect.fn("ClaudeTextGeneration.generateCommitMessage")(function* (input) {
- const { prompt, outputSchema } = buildCommitMessagePrompt({
- branch: input.branch,
- stagedSummary: input.stagedSummary,
- stagedPatch: input.stagedPatch,
- includeBranch: input.includeBranch === true,
- policy: input.policy,
- });
-
- const generated = yield* runClaudeJson({
- operation: "generateCommitMessage",
- cwd: input.cwd,
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- });
-
- return {
- subject: sanitizeCommitSubject(generated.subject),
- body: generated.body.trim(),
- ...("branch" in generated && typeof generated.branch === "string"
- ? { branch: sanitizeFeatureBranchName(generated.branch) }
- : {}),
- };
- });
-
- const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
- Effect.fn("ClaudeTextGeneration.generatePrContent")(function* (input) {
- const { prompt, outputSchema } = buildPrContentPrompt({
- baseBranch: input.baseBranch,
- headBranch: input.headBranch,
- commitSummary: input.commitSummary,
- diffSummary: input.diffSummary,
- diffPatch: input.diffPatch,
- policy: input.policy,
- changeRequestTemplate: input.changeRequestTemplate,
- });
-
- const generated = yield* runClaudeJson({
- operation: "generatePrContent",
- cwd: input.cwd,
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- });
-
- return {
- title: sanitizePrTitle(generated.title),
- body: generated.body.trim(),
- };
- });
-
- const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
- Effect.fn("ClaudeTextGeneration.generateBranchName")(function* (input) {
- const { prompt, outputSchema } = buildBranchNamePrompt({
- message: input.message,
- attachments: input.attachments,
- naming: input.naming,
- });
-
- const generated = yield* runClaudeJson({
- operation: "generateBranchName",
- cwd: input.cwd,
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- });
-
- return {
- branch: formatGeneratedBranchName(generated.branch, input.naming),
- };
- });
-
- const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
- Effect.fn("ClaudeTextGeneration.generateThreadTitle")(function* (input) {
- const { prompt, outputSchema } = buildThreadTitlePrompt({
- message: input.message,
- previousTitle: input.previousTitle,
- linkedContext: input.linkedContext,
- attachments: input.attachments,
- });
-
- const generated = yield* runClaudeJson({
- operation: "generateThreadTitle",
- cwd: input.cwd,
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- });
-
- return {
- title: sanitizeThreadTitle(generated.title),
- ...(generated.needsRefinement ? { needsRefinement: true } : {}),
- };
- });
-
- return {
- generateCommitMessage,
- generatePrContent,
- generateBranchName,
- generateThreadTitle,
- } satisfies TextGeneration.TextGeneration["Service"];
+ return TextGenerationOperations.fromRunner("ClaudeTextGeneration", runClaudeJson);
});
diff --git a/apps/server/src/textGeneration/CodexTextGeneration.ts b/apps/server/src/textGeneration/CodexTextGeneration.ts
index 2cbaaef19d8..25b4578bead 100644
--- a/apps/server/src/textGeneration/CodexTextGeneration.ts
+++ b/apps/server/src/textGeneration/CodexTextGeneration.ts
@@ -10,31 +10,17 @@ import { ChildProcess, ChildProcessSpawner } from "effect/process";
import {
type CodexSettings,
DEFAULT_TEXT_GENERATION_REASONING_EFFORT,
- type ModelSelection,
type ServerProviderModel,
TextGenerationError,
} from "@t3tools/contracts";
-import { formatGeneratedBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import { resolveAttachmentPath } from "../attachmentStore.ts";
import * as ServerConfig from "../config.ts";
import { expandHomePath } from "../pathExpansion.ts";
import { codexExecLaunchArgs, resolveCodexLaunchArgs } from "../provider/codexLaunchArgs.ts";
-import * as TextGeneration from "./TextGeneration.ts";
-import {
- buildBranchNamePrompt,
- buildCommitMessagePrompt,
- buildPrContentPrompt,
- buildThreadTitlePrompt,
-} from "./TextGenerationPrompts.ts";
-import {
- normalizeCliError,
- sanitizeCommitSubject,
- sanitizePrTitle,
- sanitizeThreadTitle,
- toJsonSchemaObject,
-} from "./TextGenerationUtils.ts";
+import * as TextGenerationOperations from "./TextGenerationOperations.ts";
+import { normalizeCliError, toJsonSchemaObject } from "./TextGenerationUtils.ts";
import { codexModelFamily, getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { getCodexServiceTierOptionValue } from "../codexModelOptions.ts";
@@ -60,10 +46,6 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
const serverConfig = yield* Effect.service(ServerConfig.ServerConfig);
const resolvedEnvironment = environment ?? process.env;
- type MaterializedImageAttachments = {
- readonly imagePaths: ReadonlyArray<string>;
- };
-
const readStreamAsString = <E>(
operation: string,
stream: Stream.Stream<Uint8Array, E>,
@@ -79,9 +61,6 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
),
);
- const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
- fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
-
const removeTempFileDir = (filePath: string): Effect.Effect<void, never> =>
fileSystem
.remove(path.dirname(filePath), { recursive: true })
@@ -117,11 +96,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
);
const encodeJsonForOperation = (
- operation:
- | "generateCommitMessage"
- | "generatePrContent"
- | "generateBranchName"
- | "generateThreadTitle",
+ operation: TextGenerationOperations.Operation,
value: unknown,
): Effect.Effect<string, TextGenerationError> =>
encodeJsonString(value).pipe(
@@ -136,15 +111,10 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
);
const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
- _operation:
- | "generateCommitMessage"
- | "generatePrContent"
- | "generateBranchName"
- | "generateThreadTitle",
- attachments: TextGeneration.BranchNameGenerationInput["attachments"],
- ): Effect.fn.Return<MaterializedImageAttachments, TextGenerationError> {
+ attachments: TextGenerationOperations.Request<Schema.Top>["attachments"],
+ ) {
if (!attachments || attachments.length === 0) {
- return { imagePaths: [] };
+ return [];
}
const imagePaths: string[] = [];
@@ -166,30 +136,22 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
}
imagePaths.push(resolvedPath);
}
- return { imagePaths };
+ return imagePaths;
});
const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
operation,
cwd,
prompt,
- outputSchemaJson,
- imagePaths = [],
- cleanupPaths = [],
+ outputSchema: outputSchemaJson,
modelSelection,
- }: {
- operation:
- | "generateCommitMessage"
- | "generatePrContent"
- | "generateBranchName"
- | "generateThreadTitle";
- cwd: string;
- prompt: string;
- outputSchemaJson: S;
- imagePaths?: ReadonlyArray<string>;
- cleanupPaths?: ReadonlyArray<string>;
- modelSelection: ModelSelection;
- }): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
+ attachments,
+ }: TextGenerationOperations.Request<S>): Effect.fn.Return<
+ S["Type"],
+ TextGenerationError,
+ S["DecodingServices"]
+ > {
+ const imagePaths = yield* materializeImageAttachments(attachments);
const schemaJson = yield* encodeJsonForOperation(
operation,
toJsonSchemaObject(outputSchemaJson),
@@ -294,16 +256,9 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
}
});
- const cleanup = Effect.all(
- [
- removeTempFileDir(schemaPath),
- removeTempFileDir(outputPath),
- ...cleanupPaths.map((filePath) => safeUnlink(filePath)),
- ],
- {
- concurrency: "unbounded",
- },
- ).pipe(Effect.asVoid);
+ const cleanup = Effect.all([removeTempFileDir(schemaPath), removeTempFileDir(outputPath)], {
+ concurrency: "unbounded",
+ }).pipe(Effect.asVoid);
return yield* Effect.gen(function* () {
yield* runCodexCommand().pipe(
@@ -346,117 +301,5 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
}).pipe(Effect.ensuring(cleanup));
});
- const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
- Effect.fn("CodexTextGeneration.generateCommitMessage")(function* (input) {
- const { prompt, outputSchema } = buildCommitMessagePrompt({
- branch: input.branch,
- stagedSummary: input.stagedSummary,
- stagedPatch: input.stagedPatch,
- includeBranch: input.includeBranch === true,
- policy: input.policy,
- });
-
- const generated = yield* runCodexJson({
- operation: "generateCommitMessage",
- cwd: input.cwd,
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- });
-
- return {
- subject: sanitizeCommitSubject(generated.subject),
- body: generated.body.trim(),
- ...("branch" in generated && typeof generated.branch === "string"
- ? { branch: sanitizeFeatureBranchName(generated.branch) }
- : {}),
- };
- });
-
- const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
- Effect.fn("CodexTextGeneration.generatePrContent")(function* (input) {
- const { prompt, outputSchema } = buildPrContentPrompt({
- baseBranch: input.baseBranch,
- headBranch: input.headBranch,
- commitSummary: input.commitSummary,
- diffSummary: input.diffSummary,
- diffPatch: input.diffPatch,
- policy: input.policy,
- changeRequestTemplate: input.changeRequestTemplate,
- });
-
- const generated = yield* runCodexJson({
- operation: "generatePrContent",
- cwd: input.cwd,
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- });
-
- return {
- title: sanitizePrTitle(generated.title),
- body: generated.body.trim(),
- };
- });
-
- const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
- Effect.fn("CodexTextGeneration.generateBranchName")(function* (input) {
- const { imagePaths } = yield* materializeImageAttachments(
- "generateBranchName",
- input.attachments,
- );
- const { prompt, outputSchema } = buildBranchNamePrompt({
- message: input.message,
- attachments: input.attachments,
- naming: input.naming,
- });
-
- const generated = yield* runCodexJson({
- operation: "generateBranchName",
- cwd: input.cwd,
- prompt,
- outputSchemaJson: outputSchema,
- imagePaths,
- modelSelection: input.modelSelection,
- });
-
- return {
- branch: formatGeneratedBranchName(generated.branch, input.naming),
- };
- });
-
- const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
- Effect.fn("CodexTextGeneration.generateThreadTitle")(function* (input) {
- const { imagePaths } = yield* materializeImageAttachments(
- "generateThreadTitle",
- input.attachments,
- );
- const { prompt, outputSchema } = buildThreadTitlePrompt({
- message: input.message,
- previousTitle: input.previousTitle,
- linkedContext: input.linkedContext,
- attachments: input.attachments,
- });
-
- const generated = yield* runCodexJson({
- operation: "generateThreadTitle",
- cwd: input.cwd,
- prompt,
- outputSchemaJson: outputSchema,
- imagePaths,
- modelSelection: input.modelSelection,
- });
-
- return {
- title: sanitizeThreadTitle(generated.title),
- ...(generated.needsRefinement ? { needsRefinement: true } : {}),
- } satisfies TextGeneration.ThreadTitleGenerationResult;
- });
-
- return {
- generateCommitMessage,
- generatePrContent,
- generateBranchName,
- generateThreadTitle,
- } satisfies TextGeneration.TextGeneration["Service"];
+ return TextGenerationOperations.fromRunner("CodexTextGeneration", runCodexJson);
});
diff --git a/apps/server/src/textGeneration/CursorTextGeneration.ts b/apps/server/src/textGeneration/CursorTextGeneration.ts
index 65985e3c7dc..a147d2f1ae4 100644
--- a/apps/server/src/textGeneration/CursorTextGeneration.ts
+++ b/apps/server/src/textGeneration/CursorTextGeneration.ts
@@ -9,36 +9,17 @@ import * as Schema from "effect/Schema";
import {
type CursorSettings,
- type ModelSelection,
type ProviderSetupError,
+ TextGenerationError,
} from "@t3tools/contracts";
-import { formatGeneratedBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
-import { extractJsonObject } from "@t3tools/shared/schemaJson";
-import { TextGenerationError } from "@t3tools/contracts";
-import * as TextGeneration from "./TextGeneration.ts";
-import {
- buildBranchNamePrompt,
- buildCommitMessagePrompt,
- buildPrContentPrompt,
- buildThreadTitlePrompt,
-} from "./TextGenerationPrompts.ts";
-import {
- sanitizeCommitSubject,
- sanitizePrTitle,
- sanitizeThreadTitle,
-} from "./TextGenerationUtils.ts";
+import * as TextGenerationOperations from "./TextGenerationOperations.ts";
import { cursorSdkModelSelection } from "../provider/cursorSdkModel.ts";
import type { CursorAuth } from "../provider/CursorAuth.ts";
const CURSOR_TIMEOUT_MS = 180_000;
const isTextGenerationError = Schema.is(TextGenerationError);
-type CursorTextGenerationOperation =
- | "generateCommitMessage"
- | "generatePrContent"
- | "generateBranchName"
- | "generateThreadTitle";
function cursorSdkResultDetail(result: RunResult): string {
switch (result.status) {
@@ -82,7 +63,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
const fs = yield* FileSystem.FileSystem;
const resolvedEnvironment = environment ?? process.env;
- const resolveCursorApiKey = (operation: CursorTextGenerationOperation) =>
+ const resolveCursorApiKey = (operation: TextGenerationOperations.Operation) =>
Effect.gen(function* () {
if (!cursorSettings.enabled) {
return yield* new TextGenerationError({
@@ -104,18 +85,10 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
return apiKey;
});
- const runCursorJson = <S extends Schema.Top>({
- operation,
- prompt,
- outputSchemaJson,
- modelSelection,
- }: {
- operation: CursorTextGenerationOperation;
- prompt: string;
- outputSchemaJson: S;
- modelSelection: ModelSelection;
- }): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
- Effect.gen(function* () {
+ // Ignores `cwd`: the agent runs in an empty temp directory, away from the project.
+ const runCursorJson: TextGenerationOperations.Runner = (input) => {
+ const { operation, prompt, modelSelection } = input;
+ return Effect.gen(function* () {
const apiKey = yield* resolveCursorApiKey(operation);
// The SDK loads sandbox.json independently of settingSources and lets it
// expand the writable paths. Its public API cannot override that policy.
@@ -211,19 +184,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
});
}
- const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
- return yield* decodeOutput(extractJsonObject(rawResult)).pipe(
- Effect.catchTags({
- SchemaError: (cause) =>
- Effect.fail(
- new TextGenerationError({
- operation,
- detail: "Cursor SDK returned invalid structured output.",
- cause,
- }),
- ),
- }),
- );
+ return yield* TextGenerationOperations.decodeJsonReply(input, "Cursor SDK", rawResult);
}).pipe(
(effect) => (withAccess ? withAccess(effect) : effect),
Effect.scoped,
@@ -237,104 +198,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
}),
),
);
+ };
- const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
- Effect.fn("CursorTextGeneration.generateCommitMessage")(function* (input) {
- const { prompt, outputSchema } = buildCommitMessagePrompt({
- branch: input.branch,
- stagedSummary: input.stagedSummary,
- stagedPatch: input.stagedPatch,
- includeBranch: input.includeBranch === true,
- policy: input.policy,
- });
-
- const generated = yield* runCursorJson({
- operation: "generateCommitMessage",
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- });
-
- return {
- subject: sanitizeCommitSubject(generated.subject),
- body: generated.body.trim(),
- ...("branch" in generated && typeof generated.branch === "string"
- ? { branch: sanitizeFeatureBranchName(generated.branch) }
- : {}),
- };
- });
-
- const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
- Effect.fn("CursorTextGeneration.generatePrContent")(function* (input) {
- const { prompt, outputSchema } = buildPrContentPrompt({
- baseBranch: input.baseBranch,
- headBranch: input.headBranch,
- commitSummary: input.commitSummary,
- diffSummary: input.diffSummary,
- diffPatch: input.diffPatch,
- policy: input.policy,
- changeRequestTemplate: input.changeRequestTemplate,
- });
-
- const generated = yield* runCursorJson({
- operation: "generatePrContent",
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- });
-
- return {
- title: sanitizePrTitle(generated.title),
- body: generated.body.trim(),
- };
- });
-
- const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
- Effect.fn("CursorTextGeneration.generateBranchName")(function* (input) {
- const { prompt, outputSchema } = buildBranchNamePrompt({
- message: input.message,
- attachments: input.attachments,
- naming: input.naming,
- });
-
- const generated = yield* runCursorJson({
- operation: "generateBranchName",
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- });
-
- return {
- branch: formatGeneratedBranchName(generated.branch, input.naming),
- };
- });
-
- const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
- Effect.fn("CursorTextGeneration.generateThreadTitle")(function* (input) {
- const { prompt, outputSchema } = buildThreadTitlePrompt({
- message: input.message,
- previousTitle: input.previousTitle,
- linkedContext: input.linkedContext,
- attachments: input.attachments,
- });
-
- const generated = yield* runCursorJson({
- operation: "generateThreadTitle",
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- });
-
- return {
- title: sanitizeThreadTitle(generated.title),
- ...(generated.needsRefinement ? { needsRefinement: true } : {}),
- } satisfies TextGeneration.ThreadTitleGenerationResult;
- });
-
- return {
- generateCommitMessage,
- generatePrContent,
- generateBranchName,
- generateThreadTitle,
- } satisfies TextGeneration.TextGeneration["Service"];
+ return TextGenerationOperations.fromRunner("CursorTextGeneration", runCursorJson);
});
diff --git a/apps/server/src/textGeneration/GrokTextGeneration.ts b/apps/server/src/textGeneration/GrokTextGeneration.ts
index b6f51d45c43..77f252c45d1 100644
--- a/apps/server/src/textGeneration/GrokTextGeneration.ts
+++ b/apps/server/src/textGeneration/GrokTextGeneration.ts
@@ -6,24 +6,10 @@ import * as Schema from "effect/Schema";
import { ChildProcessSpawner } from "effect/process";
import type * as EffectAcpErrors from "effect-acp/errors";
-import { type GrokSettings, type ModelSelection } from "@t3tools/contracts";
-import { formatGeneratedBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
+import { type GrokSettings, TextGenerationError } from "@t3tools/contracts";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
-import { extractJsonObject } from "@t3tools/shared/schemaJson";
-import { TextGenerationError } from "@t3tools/contracts";
-import * as TextGeneration from "./TextGeneration.ts";
-import {
- buildBranchNamePrompt,
- buildCommitMessagePrompt,
- buildPrContentPrompt,
- buildThreadTitlePrompt,
-} from "./TextGenerationPrompts.ts";
-import {
- sanitizeCommitSubject,
- sanitizePrTitle,
- sanitizeThreadTitle,
-} from "./TextGenerationUtils.ts";
+import * as TextGenerationOperations from "./TextGenerationOperations.ts";
import {
applyGrokAcpModelSelection,
currentGrokModelIdFromSessionSetup,
@@ -43,24 +29,9 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
const crypto = yield* Crypto.Crypto;
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const runGrokJson = <S extends Schema.Top>({
- operation,
- cwd,
- prompt,
- outputSchemaJson,
- modelSelection,
- }: {
- operation:
- | "generateCommitMessage"
- | "generatePrContent"
- | "generateBranchName"
- | "generateThreadTitle";
- cwd: string;
- prompt: string;
- outputSchemaJson: S;
- modelSelection: ModelSelection;
- }): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
- Effect.gen(function* () {
+ const runGrokJson: TextGenerationOperations.Runner = (request) => {
+ const { operation, cwd, prompt, modelSelection } = request;
+ return Effect.gen(function* () {
const outputRef = yield* Ref.make("");
const runtime = yield* makeGrokAcpRuntime({
grokSettings,
@@ -140,19 +111,7 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
});
}
- const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
- return yield* decodeOutput(extractJsonObject(trimmed)).pipe(
- Effect.catchTags({
- SchemaError: (cause) =>
- Effect.fail(
- new TextGenerationError({
- operation,
- detail: "Grok Agent returned invalid structured output.",
- cause,
- }),
- ),
- }),
- );
+ return yield* TextGenerationOperations.decodeJsonReply(request, "Grok Agent", trimmed);
}).pipe(
Effect.mapError((cause) =>
isTextGenerationError(cause)
@@ -165,108 +124,7 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
),
Effect.scoped,
);
+ };
- const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
- Effect.fn("GrokTextGeneration.generateCommitMessage")(function* (input) {
- const { prompt, outputSchema } = buildCommitMessagePrompt({
- branch: input.branch,
- stagedSummary: input.stagedSummary,
- stagedPatch: input.stagedPatch,
- includeBranch: input.includeBranch === true,
- policy: input.policy,
- });
-
- const generated = yield* runGrokJson({
- operation: "generateCommitMessage",
- cwd: input.cwd,
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- });
-
- return {
- subject: sanitizeCommitSubject(generated.subject),
- body: generated.body.trim(),
- ...("branch" in generated && typeof generated.branch === "string"
- ? { branch: sanitizeFeatureBranchName(generated.branch) }
- : {}),
- };
- });
-
- const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
- Effect.fn("GrokTextGeneration.generatePrContent")(function* (input) {
- const { prompt, outputSchema } = buildPrContentPrompt({
- baseBranch: input.baseBranch,
- headBranch: input.headBranch,
- commitSummary: input.commitSummary,
- diffSummary: input.diffSummary,
- diffPatch: input.diffPatch,
- policy: input.policy,
- changeRequestTemplate: input.changeRequestTemplate,
- });
-
- const generated = yield* runGrokJson({
- operation: "generatePrContent",
- cwd: input.cwd,
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- });
-
- return {
- title: sanitizePrTitle(generated.title),
- body: generated.body.trim(),
- };
- });
-
- const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
- Effect.fn("GrokTextGeneration.generateBranchName")(function* (input) {
- const { prompt, outputSchema } = buildBranchNamePrompt({
- message: input.message,
- attachments: input.attachments,
- naming: input.naming,
- });
-
- const generated = yield* runGrokJson({
- operation: "generateBranchName",
- cwd: input.cwd,
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- });
-
- return {
- branch: formatGeneratedBranchName(generated.branch, input.naming),
- };
- });
-
- const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
- Effect.fn("GrokTextGeneration.generateThreadTitle")(function* (input) {
- const { prompt, outputSchema } = buildThreadTitlePrompt({
- message: input.message,
- previousTitle: input.previousTitle,
- linkedContext: input.linkedContext,
- attachments: input.attachments,
- });
-
- const generated = yield* runGrokJson({
- operation: "generateThreadTitle",
- cwd: input.cwd,
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- });
-
- return {
- title: sanitizeThreadTitle(generated.title),
- ...(generated.needsRefinement ? { needsRefinement: true } : {}),
- } satisfies TextGeneration.ThreadTitleGenerationResult;
- });
-
- return {
- generateCommitMessage,
- generatePrContent,
- generateBranchName,
- generateThreadTitle,
- } satisfies TextGeneration.TextGeneration["Service"];
+ return TextGenerationOperations.fromRunner("GrokTextGeneration", runGrokJson);
});
diff --git a/apps/server/src/textGeneration/OpenCode2TextGeneration.ts b/apps/server/src/textGeneration/OpenCode2TextGeneration.ts
index a30619e2ad6..e0557a3a131 100644
--- a/apps/server/src/textGeneration/OpenCode2TextGeneration.ts
+++ b/apps/server/src/textGeneration/OpenCode2TextGeneration.ts
@@ -9,7 +9,6 @@
import { AbsolutePath, Location, Model, Provider, Session } from "@opencode/client/effect";
import { TextGenerationError } from "@t3tools/contracts";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
-import { extractJsonObject } from "@t3tools/shared/schemaJson";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
@@ -20,7 +19,7 @@ import { resolveAttachmentPath } from "../attachmentStore.ts";
import type { OpenCode2Connection } from "../provider/opencode2/OpenCode2Server.ts";
import * as OpenCode2Server from "../provider/opencode2/OpenCode2Server.ts";
import { parseOpenCodeModelSlug } from "../provider/opencodeRuntime.ts";
-import { makeOpenCodeOperations, type OpenCodeJsonRunner } from "./OpenCodeTextGeneration.ts";
+import * as TextGenerationOperations from "./TextGenerationOperations.ts";
const isTextGenerationError = Schema.is(TextGenerationError);
@@ -42,7 +41,7 @@ type Outcome =
const runOnServer = (
connection: OpenCode2Connection,
- input: Parameters<OpenCodeJsonRunner>[0],
+ input: TextGenerationOperations.Request<Schema.Top>,
attachmentsDir: string,
) =>
Effect.gen(function* () {
@@ -188,10 +187,8 @@ const runOnServer = (
export const make = Effect.fn("OpenCode2TextGeneration.make")(function* () {
const server = yield* OpenCode2Server.OpenCode2Server;
const { attachmentsDir } = yield* ServerConfig.ServerConfig;
- const run: OpenCodeJsonRunner = (input) => {
- // Each operation has its own output schema, as in 1.x.
- const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(input.outputSchemaJson));
- return server
+ const run: TextGenerationOperations.Runner = (input) =>
+ server
.withConnection((connection) => runOnServer(connection, input, attachmentsDir))
.pipe(
Effect.mapError((cause) =>
@@ -203,19 +200,7 @@ export const make = Effect.fn("OpenCode2TextGeneration.make")(function* () {
cause,
}),
),
- Effect.flatMap((raw) =>
- decodeOutput(extractJsonObject(raw)).pipe(
- Effect.mapError(
- (cause) =>
- new TextGenerationError({
- operation: input.operation,
- detail: "OpenCode returned invalid structured output.",
- cause,
- }),
- ),
- ),
- ),
+ Effect.flatMap((raw) => TextGenerationOperations.decodeJsonReply(input, "OpenCode", raw)),
);
- };
- return makeOpenCodeOperations(run);
+ return TextGenerationOperations.fromRunner("OpenCode2TextGeneration", run);
});
diff --git a/apps/server/src/textGeneration/OpenCodeTextGeneration.ts b/apps/server/src/textGeneration/OpenCodeTextGeneration.ts
index ba97ec3006f..b47a020715c 100644
--- a/apps/server/src/textGeneration/OpenCodeTextGeneration.ts
+++ b/apps/server/src/textGeneration/OpenCodeTextGeneration.ts
@@ -1,31 +1,12 @@
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
-import {
- NonNegativeInt,
- TextGenerationError,
- type ChatAttachment,
- type ModelSelection,
- type OpenCodeSettings,
-} from "@t3tools/contracts";
-import { formatGeneratedBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
+import { NonNegativeInt, TextGenerationError, type OpenCodeSettings } from "@t3tools/contracts";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
-import { extractJsonObject } from "@t3tools/shared/schemaJson";
import * as ServerConfig from "../config.ts";
import { resolveAttachmentPath } from "../attachmentStore.ts";
-import {
- buildBranchNamePrompt,
- buildCommitMessagePrompt,
- buildPrContentPrompt,
- buildThreadTitlePrompt,
-} from "./TextGenerationPrompts.ts";
-import * as TextGeneration from "./TextGeneration.ts";
-import {
- sanitizeCommitSubject,
- sanitizePrTitle,
- sanitizeThreadTitle,
-} from "./TextGenerationUtils.ts";
+import * as TextGenerationOperations from "./TextGenerationOperations.ts";
import * as OpenCodeRuntime from "../provider/opencodeRuntime.ts";
import * as OpenCodeServerOwner from "../provider/OpenCodeServerOwner.ts";
@@ -36,8 +17,6 @@ const OpenCodeTextGenerationOperation = Schema.Literals([
"generateThreadTitle",
]);
-type OpenCodeTextGenerationOperation = typeof OpenCodeTextGenerationOperation.Type;
-
const openCodeTextGenerationErrorContext = {
operation: OpenCodeTextGenerationOperation,
cwd: Schema.String,
@@ -177,14 +156,9 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
const serverOwner = yield* OpenCodeServerOwner.OpenCodeServerOwner;
- const runOpenCodeJson = Effect.fn("runOpenCodeJson")(function* <S extends Schema.Top>(input: {
- readonly operation: OpenCodeTextGenerationOperation;
- readonly cwd: string;
- readonly prompt: string;
- readonly outputSchemaJson: S;
- readonly modelSelection: ModelSelection;
- readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
- }) {
+ const runOpenCodeJson = Effect.fn("runOpenCodeJson")(function* <S extends Schema.Top>(
+ input: TextGenerationOperations.Request<S>,
+ ) {
const parsedModel = OpenCodeRuntime.parseOpenCodeModelSlug(input.modelSelection.model);
if (!parsedModel) {
return yield* new TextGenerationError({
@@ -344,137 +318,8 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
}),
);
- const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(input.outputSchemaJson));
- return yield* decodeOutput(extractJsonObject(rawOutput)).pipe(
- Effect.catchTags({
- SchemaError: (cause) =>
- Effect.fail(
- new TextGenerationError({
- operation: input.operation,
- detail: "OpenCode returned invalid structured output.",
- cause,
- }),
- ),
- }),
- );
+ return yield* TextGenerationOperations.decodeJsonReply(input, "OpenCode", rawOutput);
});
- return makeOpenCodeOperations(runOpenCodeJson);
+ return TextGenerationOperations.fromRunner("OpenCodeTextGeneration", runOpenCodeJson);
});
-
-/** Runs one prompt and decodes its reply as `outputSchemaJson`, for either OpenCode runtime. */
-export type OpenCodeJsonRunner = <S extends Schema.Top>(input: {
- readonly operation: OpenCodeTextGenerationOperation;
- readonly cwd: string;
- readonly prompt: string;
- readonly outputSchemaJson: S;
- readonly modelSelection: ModelSelection;
- readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
-}) => Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]>;
-
-/** The four text generation operations over an OpenCode prompt runner. */
-export function makeOpenCodeOperations(
- runOpenCodeJson: OpenCodeJsonRunner,
-): TextGeneration.TextGeneration["Service"] {
- const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
- Effect.fn("OpenCodeTextGeneration.generateCommitMessage")(function* (input) {
- const { prompt, outputSchema } = buildCommitMessagePrompt({
- branch: input.branch,
- stagedSummary: input.stagedSummary,
- stagedPatch: input.stagedPatch,
- includeBranch: input.includeBranch === true,
- policy: input.policy,
- });
- const generated = yield* runOpenCodeJson({
- operation: "generateCommitMessage",
- cwd: input.cwd,
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- });
-
- return {
- subject: sanitizeCommitSubject(generated.subject),
- body: generated.body.trim(),
- ...("branch" in generated && typeof generated.branch === "string"
- ? { branch: sanitizeFeatureBranchName(generated.branch) }
- : {}),
- };
- });
-
- const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
- Effect.fn("OpenCodeTextGeneration.generatePrContent")(function* (input) {
- const { prompt, outputSchema } = buildPrContentPrompt({
- baseBranch: input.baseBranch,
- headBranch: input.headBranch,
- commitSummary: input.commitSummary,
- diffSummary: input.diffSummary,
- diffPatch: input.diffPatch,
- policy: input.policy,
- changeRequestTemplate: input.changeRequestTemplate,
- });
- const generated = yield* runOpenCodeJson({
- operation: "generatePrContent",
- cwd: input.cwd,
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- });
-
- return {
- title: sanitizePrTitle(generated.title),
- body: generated.body.trim(),
- };
- });
-
- const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
- Effect.fn("OpenCodeTextGeneration.generateBranchName")(function* (input) {
- const { prompt, outputSchema } = buildBranchNamePrompt({
- message: input.message,
- attachments: input.attachments,
- naming: input.naming,
- });
- const generated = yield* runOpenCodeJson({
- operation: "generateBranchName",
- cwd: input.cwd,
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- attachments: input.attachments,
- });
-
- return {
- branch: formatGeneratedBranchName(generated.branch, input.naming),
- };
- });
-
- const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
- Effect.fn("OpenCodeTextGeneration.generateThreadTitle")(function* (input) {
- const { prompt, outputSchema } = buildThreadTitlePrompt({
- message: input.message,
- previousTitle: input.previousTitle,
- linkedContext: input.linkedContext,
- attachments: input.attachments,
- });
- const generated = yield* runOpenCodeJson({
- operation: "generateThreadTitle",
- cwd: input.cwd,
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- attachments: input.attachments,
- });
-
- return {
- title: sanitizeThreadTitle(generated.title),
- ...(generated.needsRefinement ? { needsRefinement: true } : {}),
- };
- });
-
- return {
- generateCommitMessage,
- generatePrContent,
- generateBranchName,
- generateThreadTitle,
- } satisfies TextGeneration.TextGeneration["Service"];
-}
diff --git a/apps/server/src/textGeneration/PiTextGeneration.test.ts b/apps/server/src/textGeneration/PiTextGeneration.test.ts
new file mode 100644
index 00000000000..336e110a9ff
--- /dev/null
+++ b/apps/server/src/textGeneration/PiTextGeneration.test.ts
@@ -0,0 +1,89 @@
+import { assert, it } from "@effect/vitest";
+import { ProviderInstanceId } from "@t3tools/contracts";
+import { createModelSelection } from "@t3tools/shared/model";
+import * as Cause from "effect/Cause";
+import * as Effect from "effect/Effect";
+import * as Queue from "effect/Queue";
+import * as Schema from "effect/Schema";
+import * as Sink from "effect/Sink";
+import * as Stream from "effect/Stream";
+import { ChildProcessSpawner } from "effect/process";
+
+import { makePiTextGeneration } from "./PiTextGeneration.ts";
+
+const decodeJsonLine = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
+const encodeJsonLine = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
+
+/**
+ * In-process `pi --mode rpc` that answers one prompt with `reply`. Every
+ * record written to its stdin lands in `received`.
+ */
+const makeFakePi = (reply: string) =>
+ Effect.gen(function* () {
+ const stdout = yield* Queue.unbounded<Uint8Array, Cause.Done>();
+ const received: Array<Record<string, unknown>> = [];
+ const emit = (record: Record<string, unknown>) =>
+ Queue.offer(stdout, new TextEncoder().encode(`${encodeJsonLine(record)}\n`));
+ let buffered = "";
+ const onStdin = (chunk: Uint8Array) =>
+ Effect.gen(function* () {
+ buffered += new TextDecoder().decode(chunk);
+ const lines = buffered.split("\n");
+ buffered = lines.pop() ?? "";
+ for (const line of lines.filter((candidate) => candidate.length > 0)) {
+ const record = decodeJsonLine(line) as Record<string, unknown>;
+ received.push(record);
+ const response = { type: "response", id: record["id"], command: record["type"] };
+ if (record["type"] === "prompt") {
+ yield* emit({ ...response, success: true });
+ yield* emit({ type: "agent_settled" });
+ } else if (record["type"] === "get_last_assistant_text") {
+ yield* emit({ ...response, success: true, data: { text: reply } });
+ } else {
+ yield* emit({ ...response, success: true });
+ }
+ }
+ });
+ const spawner = ChildProcessSpawner.make(() =>
+ Effect.succeed(
+ ChildProcessSpawner.makeHandle({
+ // Outside the valid pid range, so PiRpc's process-group kill never lands.
+ pid: ChildProcessSpawner.ProcessId(999_999_999),
+ exitCode: Effect.never,
+ isRunning: Effect.succeed(true),
+ kill: () => Effect.void,
+ unref: Effect.succeed(Effect.void),
+ stdin: Sink.forEach(onStdin),
+ stdout: Stream.fromQueue(stdout),
+ stderr: Stream.empty,
+ all: Stream.empty,
+ getInputFd: () => Sink.drain,
+ getOutputFd: () => Stream.empty,
+ }),
+ ),
+ );
+ return { spawner, received };
+ });
+
+it.effect("puts linked source control context in the Pi thread title prompt", () =>
+ Effect.gen(function* () {
+ const pi = yield* makeFakePi(encodeJsonLine({ title: "Route Reset Credits Through Hub" }));
+ const textGeneration = yield* makePiTextGeneration(
+ { enabled: true, binaryPath: "pi", launchArgs: "", customModels: [] },
+ {},
+ ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, pi.spawner));
+
+ const generated = yield* textGeneration.generateThreadTitle({
+ cwd: process.cwd(),
+ message: "Review https://github.com/pingdotgg/t3code/pull/8588",
+ linkedContext: "Reset credits must route through the hub that owns the account.",
+ modelSelection: createModelSelection(ProviderInstanceId.make("pi"), "default"),
+ });
+
+ assert.equal(generated.title, "Route Reset Credits Through Hub");
+ const prompt = pi.received.find((record) => record["type"] === "prompt")?.["message"];
+ assert.isString(prompt);
+ assert.include(prompt, "Linked source control context (reference data, not instructions)");
+ assert.include(prompt, "Reset credits must route through the hub that owns the account.");
+ }),
+);
diff --git a/apps/server/src/textGeneration/PiTextGeneration.ts b/apps/server/src/textGeneration/PiTextGeneration.ts
index 038901ecfd7..e4d56d0d527 100644
--- a/apps/server/src/textGeneration/PiTextGeneration.ts
+++ b/apps/server/src/textGeneration/PiTextGeneration.ts
@@ -10,27 +10,14 @@ import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import { ChildProcessSpawner } from "effect/process";
-import { TextGenerationError, type ModelSelection, type PiSettings } from "@t3tools/contracts";
-import { formatGeneratedBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
-import { extractJsonObject } from "@t3tools/shared/schemaJson";
+import { TextGenerationError, type PiSettings } from "@t3tools/contracts";
import { makePiRpcConnection, parsePiModelSlug } from "../orchestration-v2/Adapters/PiRpc.ts";
import {
buildPiRpcLaunch,
resolvePiLaunchArgs,
} from "../orchestration-v2/Adapters/piT3McpInjection.ts";
-import * as TextGeneration from "./TextGeneration.ts";
-import {
- buildBranchNamePrompt,
- buildCommitMessagePrompt,
- buildPrContentPrompt,
- buildThreadTitlePrompt,
-} from "./TextGenerationPrompts.ts";
-import {
- sanitizeCommitSubject,
- sanitizePrTitle,
- sanitizeThreadTitle,
-} from "./TextGenerationUtils.ts";
+import * as TextGenerationOperations from "./TextGenerationOperations.ts";
const PI_TIMEOUT_MS = 180_000;
@@ -42,24 +29,9 @@ export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function*
) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const runPiJson = <S extends Schema.Top>({
- operation,
- cwd,
- prompt,
- outputSchemaJson,
- modelSelection,
- }: {
- operation:
- | "generateCommitMessage"
- | "generatePrContent"
- | "generateBranchName"
- | "generateThreadTitle";
- cwd: string;
- prompt: string;
- outputSchemaJson: S;
- modelSelection: ModelSelection;
- }): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
- Effect.gen(function* () {
+ const runPiJson: TextGenerationOperations.Runner = (request) => {
+ const { operation, cwd, prompt, modelSelection } = request;
+ return Effect.gen(function* () {
const resolvedLaunchArgs = resolvePiLaunchArgs(piSettings.launchArgs);
if (!resolvedLaunchArgs.ok) {
return yield* new TextGenerationError({
@@ -126,19 +98,7 @@ export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function*
detail: "Pi returned empty output.",
});
}
- const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));
- return yield* decodeOutput(extractJsonObject(text)).pipe(
- Effect.catchTags({
- SchemaError: (cause) =>
- Effect.fail(
- new TextGenerationError({
- operation,
- detail: "Pi returned invalid structured output.",
- cause,
- }),
- ),
- }),
- );
+ return yield* TextGenerationOperations.decodeJsonReply(request, "Pi", text);
}).pipe(
Effect.timeoutOption(PI_TIMEOUT_MS),
Effect.flatMap(
@@ -159,98 +119,7 @@ export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function*
),
Effect.scoped,
);
+ };
- const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
- Effect.fn("PiTextGeneration.generateCommitMessage")(function* (input) {
- const { prompt, outputSchema } = buildCommitMessagePrompt({
- branch: input.branch,
- stagedSummary: input.stagedSummary,
- stagedPatch: input.stagedPatch,
- includeBranch: input.includeBranch === true,
- policy: input.policy,
- });
- const generated = yield* runPiJson({
- operation: "generateCommitMessage",
- cwd: input.cwd,
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- });
- return {
- subject: sanitizeCommitSubject(generated.subject),
- body: generated.body.trim(),
- ...("branch" in generated && typeof generated.branch === "string"
- ? { branch: sanitizeFeatureBranchName(generated.branch) }
- : {}),
- };
- });
-
- const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
- Effect.fn("PiTextGeneration.generatePrContent")(function* (input) {
- const { prompt, outputSchema } = buildPrContentPrompt({
- baseBranch: input.baseBranch,
- headBranch: input.headBranch,
- commitSummary: input.commitSummary,
- diffSummary: input.diffSummary,
- diffPatch: input.diffPatch,
- policy: input.policy,
- changeRequestTemplate: input.changeRequestTemplate,
- });
- const generated = yield* runPiJson({
- operation: "generatePrContent",
- cwd: input.cwd,
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- });
- return {
- title: sanitizePrTitle(generated.title),
- body: generated.body.trim(),
- };
- });
-
- const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
- Effect.fn("PiTextGeneration.generateBranchName")(function* (input) {
- const { prompt, outputSchema } = buildBranchNamePrompt({
- message: input.message,
- attachments: input.attachments,
- naming: input.naming,
- });
- const generated = yield* runPiJson({
- operation: "generateBranchName",
- cwd: input.cwd,
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- });
- return {
- branch: formatGeneratedBranchName(generated.branch, input.naming),
- };
- });
-
- const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
- Effect.fn("PiTextGeneration.generateThreadTitle")(function* (input) {
- const { prompt, outputSchema } = buildThreadTitlePrompt({
- message: input.message,
- previousTitle: input.previousTitle,
- attachments: input.attachments,
- });
- const generated = yield* runPiJson({
- operation: "generateThreadTitle",
- cwd: input.cwd,
- prompt,
- outputSchemaJson: outputSchema,
- modelSelection: input.modelSelection,
- });
- return {
- title: sanitizeThreadTitle(generated.title),
- } satisfies TextGeneration.ThreadTitleGenerationResult;
- });
-
- return {
- generateCommitMessage,
- generatePrContent,
- generateBranchName,
- generateThreadTitle,
- } satisfies TextGeneration.TextGeneration["Service"];
+ return TextGenerationOperations.fromRunner("PiTextGeneration", runPiJson);
});
diff --git a/apps/server/src/textGeneration/TextGenerationOperations.ts b/apps/server/src/textGeneration/TextGenerationOperations.ts
new file mode 100644
index 00000000000..b1fc905cae0
--- /dev/null
+++ b/apps/server/src/textGeneration/TextGenerationOperations.ts
@@ -0,0 +1,153 @@
+/**
+ * The text generation operations every provider shares. A provider supplies a
+ * runner that sends one prompt and decodes the reply; prompts, linked source
+ * control context, and output sanitizing live here so providers cannot drift
+ * on them.
+ *
+ * @module textGeneration/TextGenerationOperations
+ */
+import * as Effect from "effect/Effect";
+import * as Schema from "effect/Schema";
+
+import { type ChatAttachment, type ModelSelection, TextGenerationError } from "@t3tools/contracts";
+import { formatGeneratedBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
+import { extractJsonObject } from "@t3tools/shared/schemaJson";
+
+import type * as TextGeneration from "./TextGeneration.ts";
+import {
+ buildBranchNamePrompt,
+ buildCommitMessagePrompt,
+ buildPrContentPrompt,
+ buildThreadTitlePrompt,
+} from "./TextGenerationPrompts.ts";
+import {
+ sanitizeCommitSubject,
+ sanitizePrTitle,
+ sanitizeThreadTitle,
+} from "./TextGenerationUtils.ts";
+
+export type Operation = keyof TextGeneration.TextGeneration["Service"];
+
+/** One prompt for a provider to run. */
+export interface Request<S extends Schema.Top> {
+ readonly operation: Operation;
+ readonly cwd: string;
+ readonly prompt: string;
+ readonly outputSchema: S;
+ readonly modelSelection: ModelSelection;
+ /** The user's attachments, already listed in the prompt. Providers that accept images send them. */
+ readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
+}
+
+/** Runs one request and decodes the reply as its `outputSchema`. */
+export type Runner = <S extends Schema.Top>(
+ request: Request<S>,
+) => Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]>;
+
+/** Decodes the JSON object in a text reply, which models often wrap in prose. */
+export const decodeJsonReply = <S extends Schema.Top>(
+ request: Pick<Request<S>, "operation" | "outputSchema">,
+ provider: string,
+ text: string,
+) => {
+ // Each request builds its own output schema, so the decoder cannot be hoisted.
+ const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(request.outputSchema));
+ return decodeOutput(extractJsonObject(text)).pipe(
+ Effect.mapError(
+ (cause) =>
+ new TextGenerationError({
+ operation: request.operation,
+ detail: `${provider} returned invalid structured output.`,
+ cause,
+ }),
+ ),
+ );
+};
+
+/** The text generation service over `run`. `name` prefixes each operation's span. */
+export function fromRunner(name: string, run: Runner): TextGeneration.TextGeneration["Service"] {
+ const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
+ Effect.fn(`${name}.generateCommitMessage`)(function* (input) {
+ const generated = yield* run({
+ operation: "generateCommitMessage",
+ cwd: input.cwd,
+ modelSelection: input.modelSelection,
+ ...buildCommitMessagePrompt({
+ branch: input.branch,
+ stagedSummary: input.stagedSummary,
+ stagedPatch: input.stagedPatch,
+ includeBranch: input.includeBranch === true,
+ policy: input.policy,
+ }),
+ });
+ return {
+ subject: sanitizeCommitSubject(generated.subject),
+ body: generated.body.trim(),
+ ...("branch" in generated && typeof generated.branch === "string"
+ ? { branch: sanitizeFeatureBranchName(generated.branch) }
+ : {}),
+ };
+ });
+
+ const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
+ Effect.fn(`${name}.generatePrContent`)(function* (input) {
+ const generated = yield* run({
+ operation: "generatePrContent",
+ cwd: input.cwd,
+ modelSelection: input.modelSelection,
+ ...buildPrContentPrompt({
+ baseBranch: input.baseBranch,
+ headBranch: input.headBranch,
+ commitSummary: input.commitSummary,
+ diffSummary: input.diffSummary,
+ diffPatch: input.diffPatch,
+ policy: input.policy,
+ changeRequestTemplate: input.changeRequestTemplate,
+ }),
+ });
+ return { title: sanitizePrTitle(generated.title), body: generated.body.trim() };
+ });
+
+ const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
+ Effect.fn(`${name}.generateBranchName`)(function* (input) {
+ const generated = yield* run({
+ operation: "generateBranchName",
+ cwd: input.cwd,
+ modelSelection: input.modelSelection,
+ attachments: input.attachments,
+ ...buildBranchNamePrompt({
+ message: input.message,
+ attachments: input.attachments,
+ naming: input.naming,
+ }),
+ });
+ return { branch: formatGeneratedBranchName(generated.branch, input.naming) };
+ });
+
+ const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
+ Effect.fn(`${name}.generateThreadTitle`)(function* (input) {
+ const generated = yield* run({
+ operation: "generateThreadTitle",
+ cwd: input.cwd,
+ modelSelection: input.modelSelection,
+ attachments: input.attachments,
+ ...buildThreadTitlePrompt({
+ message: input.message,
+ previousTitle: input.previousTitle,
+ linkedContext: input.linkedContext,
+ attachments: input.attachments,
+ }),
+ });
+ return {
+ title: sanitizeThreadTitle(generated.title),
+ ...(generated.needsRefinement ? { needsRefinement: true } : {}),
+ };
+ });
+
+ return {
+ generateCommitMessage,
+ generatePrContent,
+ generateBranchName,
+ generateThreadTitle,
+ } satisfies TextGeneration.TextGeneration["Service"];
+}