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