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