Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

textGeneration.ts

125 lines5.2 KB

1import { TextGenerationError } from "@t3tools/contracts";
2import { readCustomModelEntries } from "@t3tools/shared/model";
3import * as SecureRandom from "effect/crypto/SecureRandom";
4import * as FileSystem from "effect/FileSystem";
5import * as Effect from "effect/Effect";
6import * as Ref from "effect/Ref";
7import * as Schema from "effect/Schema";
8import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
9​
10import type { ProviderTextGeneration } from "@t3tools/provider-core/server/textGeneration";
11import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations";
12import { findModelConfigOption } from "@t3tools/provider-acp/server/runtimeModel";
13import { flattenSelectChoices } from "@t3tools/provider-acp/server/sessionConfig";
14​
15import * as AcpRegistrySupport from "./AcpRegistrySupport.ts";
16import {
17 makeAcpRegistryManagementRuntime,
18 type AcpRegistryConfigurationProbeInput,
19} from "./probe.ts";
20​
21const TIMEOUT = "3 minutes";
22const isTextGenerationError = Schema.is(TextGenerationError);
23​
24export const makeAcpRegistryTextGeneration = Effect.fn("AcpRegistryTextGeneration.make")(function* (
25 input: Omit<AcpRegistryConfigurationProbeInput, "cwd">,
26) {
27 const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
28 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
29 const random = yield* SecureRandom.SecureRandom;
30 const fs = yield* FileSystem.FileSystem;
31 const run: TextGenerationOperations.Runner = Effect.fn("AcpRegistryTextGeneration.run")(
32 function* (request) {
33 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-acp-text-" });
34 const runtime = yield* makeAcpRegistryManagementRuntime({ ...input, cwd });
35 const output = yield* Ref.make("");
36 yield* runtime.handleSessionUpdate(({ update }) => {
37 if (update.sessionUpdate === "agent_message" && update.content != null) {
38 return Ref.set(
39 output,
40 update.content.map((block) => (block.type === "text" ? block.text : "")).join(""),
41 );
42 }
43 if (update.sessionUpdate !== "agent_message_chunk" || update.content.type !== "text") {
44 return Effect.void;
45 }
46 const chunk = update.content.text;
47 return Ref.update(output, (text) => text + chunk);
48 });
49 // A hidden session must never act on the checkout.
50 yield* runtime.handleRequestPermission(() =>
51 Effect.succeed({ outcome: { outcome: "cancelled" } } as const),
52 );
53 const started = yield* runtime.start();
54 yield* Effect.addFinalizer(() =>
55 runtime
56 .deleteSession(started.sessionId)
57 .pipe(Effect.interruptible, Effect.timeout("5 seconds"), Effect.ignore),
58 );
59 const model = request.modelSelection.model;
60 const modelOption = findModelConfigOption(yield* runtime.getConfigOptions);
61 if (model.length > 0 && model !== "default" && modelOption?.currentValue !== model) {
62 const modelState = started.sessionSetupResult.models;
63 const isCustomModel = readCustomModelEntries(input.settings.customModels).some(
64 (entry) => entry.slug === model,
65 );
66 if (modelOption !== undefined) {
67 if (
68 isCustomModel ||
69 flattenSelectChoices(modelOption.options).some((choice) => choice.value === model)
70 ) {
71 yield* runtime.setConfigOption(modelOption.id, model, {
72 allowUnlistedValue: isCustomModel,
73 });
74 }
75 } else if (
76 modelState != null &&
77 modelState.currentModelId !== model &&
78 (isCustomModel || modelState.availableModels.some((choice) => choice.modelId === model))
79 ) {
80 yield* runtime.setSessionModel(model);
81 }
82 }
83 yield* runtime.prompt({ prompt: [{ type: "text", text: request.prompt }] });
84 const text = (yield* Ref.get(output)).trim();
85 if (text.length === 0) {
86 return yield* new TextGenerationError({
87 operation: request.operation,
88 detail: "The ACP agent returned no text.",
89 });
90 }
91 return yield* TextGenerationOperations.decodeJsonReply(request, "ACP agent", text);
92 },
93 (effect, request) =>
94 effect.pipe(
95 Effect.scoped,
96 Effect.timeoutOrElse({
97 duration: TIMEOUT,
98 orElse: () =>
99 Effect.fail(
100 new TextGenerationError({
101 operation: request.operation,
102 detail: "The ACP agent did not answer in time.",
103 }),
104 ),
105 }),
106 Effect.mapError((cause) =>
107 isTextGenerationError(cause)
108 ? cause
109 : new TextGenerationError({
110 operation: request.operation,
111 detail: "The ACP text generation request failed.",
112 cause,
113 }),
114 ),
115 Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
116 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
117 Effect.provideService(SecureRandom.SecureRandom, random),
118 Effect.provideService(FileSystem.FileSystem, fs),
119 ),
120 );
121 return TextGenerationOperations.fromRunner(
122 "AcpRegistryTextGeneration",
123 TextGenerationOperations.withoutInvestigation("ACP Registry", run),
124 ) satisfies ProviderTextGeneration;
125});