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