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