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 "--disable-slash-commands",
257 ...(noSessionPersistence ? [NO_SESSION_PERSISTENCE] : []),
258 // managed-mcp.json already isolates servers and makes Claude reject this flag.
259 ...(managedMcpConfig ? [] : ["--strict-mcp-config"]),
260 "--permission-mode",
261 "dontAsk",
262 ],
263 { env: claudeEnvironment },
264 );
265 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
266 env: claudeEnvironment,
267 cwd: workingDirectory,
268 shell: spawnCommand.shell,
269 stdin: {
270 stream: Stream.encodeText(Stream.make(prompt)),
271 },
272 forceKillAfter: "1 second",
273 });
274
275 const child = yield* commandSpawner
276 .spawn(command)
277 .pipe(
278 Effect.mapError((cause) =>
279 normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
280 ),
281 );
282
283 const [stdout, stderr, exitCode] = yield* Effect.all(
284 [
285 readStreamAsString(operation, child.stdout),
286 readStreamAsString(operation, child.stderr),
287 child.exitCode.pipe(
288 Effect.mapError((cause) =>
289 normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
290 ),
291 ),
292 ],
293 { concurrency: "unbounded" },
294 );
295
296 return { stdout, stderr, exitCode };
297 });
298
299 const rawStdout = yield* runClaudeCommand(true).pipe(
300 Effect.filterOrElse(
301 (result) =>
302 result.exitCode === 0 || !result.stderr.includes(NO_SESSION_PERSISTENCE_REJECTED),
303 () => runClaudeCommand(false),
304 ),
305 Effect.flatMap(({ stdout, stderr, exitCode }) => {
306 if (exitCode === 0) return Effect.succeed(stdout);
307 const stderrDetail = stderr.trim();
308 const stdoutDetail = stdout.trim();
309 const detail =
310 claudeErrorResult(stdoutDetail) ??
311 (stderrDetail.length > 0 ? stderrDetail : stdoutDetail);
312 return Effect.fail(
313 new TextGenerationError({
314 operation,
315 detail:
316 detail.length > 0
317 ? `Claude CLI command failed: ${detail}`
318 : `Claude CLI command failed with code ${exitCode}.`,
319 }),
320 );
321 }),
322 Effect.scoped,
323 Effect.timeoutOption(investigate?.timeoutMs ?? CLAUDE_TIMEOUT_MS),
324 Effect.flatMap(
325 Option.match({
326 onNone: () =>
327 Effect.fail(
328 new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
329 ),
330 onSome: (value) => Effect.succeed(value),
331 }),
332 ),
333 );
334
335 const output = yield* decodeClaudeOutput(rawStdout).pipe(
336 Effect.catchTags({
337 SchemaError: (cause) =>
338 Effect.fail(
339 new TextGenerationError({
340 operation,
341 detail: "Claude CLI returned unexpected output format.",
342 cause,
343 }),
344 ),
345 }),
346 );
347 const envelope = isClaudeOutputEnvelope(output)
348 ? output
349 : output.findLast((message) => message.type === "result");
350
351 const decodeOutput = Schema.decodeEffect(outputSchemaJson);
352 return yield* decodeOutput(envelope?.structured_output).pipe(
353 Effect.catchTags({
354 SchemaError: (cause) =>
355 Effect.fail(
356 new TextGenerationError({
357 operation,
358 detail: "Claude returned invalid structured output.",
359 cause,
360 }),
361 ),
362 }),
363 );
364 });
365
366 return TextGenerationOperations.fromRunner(
367 "ClaudeTextGeneration",
368 <S extends Schema.Top>(request: TextGenerationOperations.Request<S>) =>
369 Effect.scoped(runClaudeJson(request)),
370 );
371});