Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Option from "effect/Option";
4import * as Schema from "effect/Schema";
5import * as Stream from "effect/Stream";
6import { ChildProcess, ChildProcessSpawner } from "effect/process";
7
8import { type ClaudeSettings, TextGenerationError } from "@t3tools/contracts";
9import { resolveSpawnCommand } from "@t3tools/shared/shell";
10
11import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations";
12import {
13 normalizeCliError,
14 toJsonSchemaObject,
15} from "@t3tools/provider-core/server/textGenerationUtils";
16import {
17 getModelSelectionBooleanOptionValue,
18 getModelSelectionStringOptionValue,
19 getProviderOptionDescriptors,
20} from "@t3tools/shared/model";
21import {
22 BUNDLED_CLAUDE_MODEL_CATALOG,
23 type ClaudeModelCatalog,
24 getClaudeCatalogModelCapabilities,
25 isClaudeCatalogUltracodeEffort,
26 normalizeClaudeCatalogEffort,
27 resolveClaudeCatalogApiModelId,
28 resolveClaudeCatalogEffort,
29 resolveClaudeModelSlug,
30 scopeClaudeModelCatalog,
31} from "../provider/ClaudeModelCatalog.ts";
32import {
33 hasClaudeManagedMcpConfig,
34 makeClaudeEnvironment,
35} from "../provider/Drivers/ClaudeHome.ts";
36
37const CLAUDE_TIMEOUT_MS = 180_000;
38/** `--tools` takes bare names; patterns go in the allow list. */
39const CLAUDE_INVESTIGATION_TOOLS = "Read,Grep,Glob,Bash";
40/** In dontAsk mode every call outside this list, Bash included, is refused. */
41const CLAUDE_INVESTIGATION_ALLOWED = [
42 "Read",
43 "Grep",
44 "Glob",
45 "Bash(git diff:*)",
46 "Bash(git log:*)",
47 "Bash(git show:*)",
48].join(",");
49// Denies override allows; block git --output/-o because allowed trailing args can otherwise write anywhere.
50const CLAUDE_INVESTIGATION_DENIED = ["Bash(git * --output*)", "Bash(git * -o *)"].join(",");
51
52const ClaudeOutputEnvelope = Schema.Struct({
53 structured_output: Schema.Unknown,
54});
55const ClaudeOutputMessage = Schema.Struct({
56 type: Schema.String,
57 structured_output: Schema.optionalKey(Schema.Unknown),
58});
59const isClaudeOutputEnvelope = Schema.is(ClaudeOutputEnvelope);
60
61const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
62const decodeClaudeOutput = Schema.decodeEffect(
63 Schema.fromJsonString(Schema.Union([ClaudeOutputEnvelope, Schema.Array(ClaudeOutputMessage)])),
64);
65
66const ClaudeErrorResult = Schema.Struct({ is_error: Schema.Literal(true), result: Schema.String });
67const isClaudeErrorResult = Schema.is(ClaudeErrorResult);
68const decodeJsonOption = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
69
70// Claude reports JSON errors on stdout; stderr may contain only wrapper notices.
71function claudeErrorResult(stdout: string): string | undefined {
72 const output = Option.getOrUndefined(decodeJsonOption(stdout));
73 const messages: ReadonlyArray<unknown> = Array.isArray(output) ? output : [output];
74 return messages
75 .filter(isClaudeErrorResult)
76 .map((message) => message.result.trim())
77 .findLast((result) => result.length > 0);
78}
79
80export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(function* (
81 claudeSettings: ClaudeSettings,
82 environment?: NodeJS.ProcessEnv,
83 modelCatalog: Effect.Effect<ClaudeModelCatalog> = Effect.succeed(BUNDLED_CLAUDE_MODEL_CATALOG),
84) {
85 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
86 const fileSystem = yield* FileSystem.FileSystem;
87 const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
88 const scopedModelCatalog = modelCatalog.pipe(
89 Effect.map((catalog) => scopeClaudeModelCatalog(catalog, claudeSettings.customModels)),
90 );
91
92 const readStreamAsString = <E>(
93 operation: string,
94 stream: Stream.Stream<Uint8Array, E>,
95 ): Effect.Effect<string, TextGenerationError> =>
96 stream.pipe(
97 Stream.decodeText(),
98 Stream.runFold(
99 () => "",
100 (acc, chunk) => acc + chunk,
101 ),
102 Effect.mapError((cause) =>
103 normalizeCliError("claude", operation, cause, "Failed to collect process output"),
104 ),
105 );
106
107 const encodeJsonForOperation = (
108 operation: TextGenerationOperations.Operation,
109 value: unknown,
110 detail: string,
111 ): Effect.Effect<string, TextGenerationError> =>
112 encodeJsonString(value).pipe(
113 Effect.mapError(
114 (cause) =>
115 new TextGenerationError({
116 operation,
117 detail,
118 cause,
119 }),
120 ),
121 );
122
123 const runClaudeJson = Effect.fn("runClaudeJson")(function* <S extends Schema.Top>({
124 operation,
125 cwd,
126 prompt,
127 outputSchema: outputSchemaJson,
128 modelSelection,
129 investigate,
130 }: TextGenerationOperations.Request<S>): Effect.fn.Return<
131 S["Type"],
132 TextGenerationError,
133 S["DecodingServices"]
134 > {
135 const catalog = yield* scopedModelCatalog;
136 const resolvedModelSelection = {
137 ...modelSelection,
138 model: resolveClaudeModelSlug(catalog, modelSelection.model),
139 };
140 const jsonSchemaStr = yield* encodeJsonForOperation(
141 operation,
142 toJsonSchemaObject(outputSchemaJson),
143 "Failed to encode structured output schema.",
144 );
145 const caps = getClaudeCatalogModelCapabilities(catalog, resolvedModelSelection.model);
146 const descriptors = getProviderOptionDescriptors({
147 caps,
148 selections: resolvedModelSelection.options,
149 });
150 const findDescriptor = (id: string) => descriptors.find((descriptor) => descriptor.id === id);
151 const rawEffortSelection = getModelSelectionStringOptionValue(resolvedModelSelection, "effort");
152 const resolvedEffort = resolveClaudeCatalogEffort(
153 catalog,
154 resolvedModelSelection.model,
155 rawEffortSelection,
156 );
157 const cliEffort = normalizeClaudeCatalogEffort(
158 catalog,
159 resolvedEffort,
160 resolvedModelSelection.model,
161 );
162 const ultracode = isClaudeCatalogUltracodeEffort(resolvedEffort);
163 const thinkingDescriptor = findDescriptor("thinking");
164 const fastModeDescriptor = findDescriptor("fastMode");
165 // Only a chosen value; otherwise Claude Code's own default applies, as in chat turns.
166 const thinking =
167 thinkingDescriptor?.type === "boolean"
168 ? getModelSelectionBooleanOptionValue(resolvedModelSelection, "thinking")
169 : undefined;
170 const fastMode =
171 fastModeDescriptor?.type === "boolean" ? fastModeDescriptor.currentValue : undefined;
172 const settings = {
173 disableAllHooks: true,
174 ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
175 ...(fastMode ? { fastMode: true } : {}),
176 ...(ultracode ? { ultracode: true } : {}),
177 };
178 const settingsJson = yield* encodeJsonForOperation(
179 operation,
180 settings,
181 "Failed to encode Claude CLI settings.",
182 );
183
184 const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
185 const workingDirectory =
186 operation === "generateThreadTitle"
187 ? yield* fileSystem
188 .makeTempDirectoryScoped({ prefix: "t3code-claude-title-" })
189 .pipe(
190 Effect.mapError((cause) =>
191 normalizeCliError("claude", operation, cause, "Failed to create title directory"),
192 ),
193 )
194 : cwd;
195 const managedMcpConfig = yield* hasClaudeManagedMcpConfig();
196 const spawnCommand = yield* resolveSpawnCommand(
197 claudeSettings.binaryPath || "claude",
198 [
199 "-p",
200 "--output-format",
201 "json",
202 "--json-schema",
203 jsonSchemaStr,
204 "--model",
205 resolveClaudeCatalogApiModelId(catalog, resolvedModelSelection),
206 ...(cliEffort ? ["--effort", cliEffort] : []),
207 "--settings",
208 settingsJson,
209 ...(investigate
210 ? [
211 "--tools",
212 CLAUDE_INVESTIGATION_TOOLS,
213 "--allowedTools",
214 CLAUDE_INVESTIGATION_ALLOWED,
215 "--disallowedTools",
216 CLAUDE_INVESTIGATION_DENIED,
217 ]
218 : ["--tools", ""]),
219 "--disable-slash-commands",
220 // managed-mcp.json already isolates servers and makes Claude reject this flag.
221 ...(managedMcpConfig ? [] : ["--strict-mcp-config"]),
222 "--permission-mode",
223 "dontAsk",
224 ],
225 { env: claudeEnvironment },
226 );
227 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
228 env: claudeEnvironment,
229 cwd: workingDirectory,
230 shell: spawnCommand.shell,
231 stdin: {
232 stream: Stream.encodeText(Stream.make(prompt)),
233 },
234 forceKillAfter: "1 second",
235 });
236
237 const child = yield* commandSpawner
238 .spawn(command)
239 .pipe(
240 Effect.mapError((cause) =>
241 normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
242 ),
243 );
244
245 const [stdout, stderr, exitCode] = yield* Effect.all(
246 [
247 readStreamAsString(operation, child.stdout),
248 readStreamAsString(operation, child.stderr),
249 child.exitCode.pipe(
250 Effect.mapError((cause) =>
251 normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
252 ),
253 ),
254 ],
255 { concurrency: "unbounded" },
256 );
257
258 if (exitCode !== 0) {
259 const stderrDetail = stderr.trim();
260 const stdoutDetail = stdout.trim();
261 const detail =
262 claudeErrorResult(stdoutDetail) ??
263 (stderrDetail.length > 0 ? stderrDetail : stdoutDetail);
264 return yield* new TextGenerationError({
265 operation,
266 detail:
267 detail.length > 0
268 ? `Claude CLI command failed: ${detail}`
269 : `Claude CLI command failed with code ${exitCode}.`,
270 });
271 }
272
273 return stdout;
274 });
275
276 const rawStdout = yield* runClaudeCommand().pipe(
277 Effect.scoped,
278 Effect.timeoutOption(investigate?.timeoutMs ?? CLAUDE_TIMEOUT_MS),
279 Effect.flatMap(
280 Option.match({
281 onNone: () =>
282 Effect.fail(
283 new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
284 ),
285 onSome: (value) => Effect.succeed(value),
286 }),
287 ),
288 );
289
290 const output = yield* decodeClaudeOutput(rawStdout).pipe(
291 Effect.catchTags({
292 SchemaError: (cause) =>
293 Effect.fail(
294 new TextGenerationError({
295 operation,
296 detail: "Claude CLI returned unexpected output format.",
297 cause,
298 }),
299 ),
300 }),
301 );
302 const envelope = isClaudeOutputEnvelope(output)
303 ? output
304 : output.findLast((message) => message.type === "result");
305
306 const decodeOutput = Schema.decodeEffect(outputSchemaJson);
307 return yield* decodeOutput(envelope?.structured_output).pipe(
308 Effect.catchTags({
309 SchemaError: (cause) =>
310 Effect.fail(
311 new TextGenerationError({
312 operation,
313 detail: "Claude returned invalid structured output.",
314 cause,
315 }),
316 ),
317 }),
318 );
319 });
320
321 return TextGenerationOperations.fromRunner("ClaudeTextGeneration", runClaudeJson);
322});