Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ClaudeHome.ts

186 lines8.3 KB

1import type { ClaudeSettings, ProviderInstanceEnvironment } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Path from "effect/Path";
5import * as Schema from "effect/Schema";
6​
7import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
8import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10​
11import { parseGitfileTarget } from "../../project/worktreeContainer.ts";
12import { readClaudeSettingsEnv } from "./ClaudeSkills.ts";
13​
14const quotePath = Schema.encodeSync(Schema.fromJsonString(Schema.String));
15​
16export const resolveClaudeHomePath = Effect.fn("resolveClaudeHomePath")(function* (
17 config: Pick<ClaudeSettings, "homePath">,
18 environment?: NodeJS.ProcessEnv,
19): Effect.fn.Return<string, never, Path.Path> {
20 const path = yield* Path.Path;
21 const home = yield* HostProcess.HomeDirectory;
22 const homePath = config.homePath.trim();
23 if (homePath.length > 0) {
24 return path.resolve(expandHomePath(homePath, home));
25 }
26 // Inherited env vars are not shell-expanded, so a literal `~` stays literal.
27 const inherited = environment?.CLAUDE_CONFIG_DIR?.trim() ?? "";
28 if (inherited.length > 0) {
29 return path.resolve(inherited);
30 }
31 return path.resolve(path.join(home, ".claude"));
32});
33​
34export const makeClaudeEnvironment = Effect.fn("makeClaudeEnvironment")(function* (
35 config: Pick<ClaudeSettings, "homePath">,
36 baseEnv?: NodeJS.ProcessEnv,
37): Effect.fn.Return<NodeJS.ProcessEnv, never, Path.Path> {
38 const resolvedBaseEnv = baseEnv ?? process.env;
39 const homePath = config.homePath.trim();
40 if (homePath.length === 0) return resolvedBaseEnv;
41 const resolvedHomePath = yield* resolveClaudeHomePath(config);
42 return {
43 ...resolvedBaseEnv,
44 // Changing HOME hides macOS Keychain credentials; use CLAUDE_CONFIG_DIR to keep login access.
45 CLAUDE_CONFIG_DIR: resolvedHomePath,
46 };
47});
48​
49// A Claude Code session that launched T3 exports these. A claude spawned with them acts as part of
50// that session: its session id, messaging socket and token, and effort.
51const CLAUDE_HOST_SESSION_VARIABLES = [
52 "CLAUDECODE",
53 "CLAUDE_CODE_SESSION_ID",
54 "CLAUDE_CODE_HOST_SESSION_ID",
55 "CLAUDE_CODE_CHILD_SESSION",
56 "CLAUDE_CODE_SESSION_ATTENDED",
57 "CLAUDE_CODE_MESSAGING_SOCKET",
58 "CLAUDE_CODE_MESSAGING_TOKEN",
59 "CLAUDE_CODE_EXECPATH",
60 "CLAUDE_CODE_DESKTOP_APP_VERSION",
61 "CLAUDE_EFFORT",
62 "CLAUDE_PID",
63 "CLAUDE_AGENT_SDK_VERSION",
64];
65​
66/**
67 * Base env for the Claude processes T3 Code runs, before `makeClaudeEnvironment`.
68 * Claude Code reads its entrypoint from the process env, not its settings `env`, so T3 Code applies that override itself.
69 */
70export const mergeClaudeProcessEnvironment = Effect.fn("mergeClaudeProcessEnvironment")(function* (
71 config: Pick<ClaudeSettings, "homePath" | "enabled">,
72 instanceEnvironment: ProviderInstanceEnvironment | undefined,
73 hostEnvironment: NodeJS.ProcessEnv,
74) {
75 const baseEnvironment: NodeJS.ProcessEnv = {
76 ...hostEnvironment,
77 CLAUDE_CODE_ENTRYPOINT: "t3-code",
78 };
79 for (const name of CLAUDE_HOST_SESSION_VARIABLES) delete baseEnvironment[name];
80 // The desktop runs the server as Node through Electron. Commands Claude runs inherit its env, so
81 // an Electron app they start (T3 Code itself, VS Code) would run as Node and exit.
82 delete baseEnvironment.ELECTRON_RUN_AS_NODE;
83 const environment = yield* mergeProviderInstanceEnvironment(instanceEnvironment, baseEnvironment);
84 // A turned-off Claude never runs, so its settings stay unread.
85 if (!config.enabled) return environment;
86 const settingsEntrypoint = (yield* readClaudeSettingsEnv(config, undefined, environment))
87 .CLAUDE_CODE_ENTRYPOINT;
88 return settingsEntrypoint
89 ? { ...environment, CLAUDE_CODE_ENTRYPOINT: settingsEntrypoint }
90 : environment;
91});
92​
93/** managed-mcp.json excludes other MCP config and forbids --strict-mcp-config; omit the flag when present. */
94export const hasClaudeManagedMcpConfig = Effect.fn("hasClaudeManagedMcpConfig")(function* () {
95 const fileSystem = yield* FileSystem.FileSystem;
96 const platform = yield* HostProcess.Platform;
97 const managedMcpConfigPath =
98 platform === "darwin"
99 ? "/Library/Application Support/ClaudeCode/managed-mcp.json"
100 : platform === "win32"
101 ? "C:\\Program Files\\ClaudeCode\\managed-mcp.json"
102 : "/etc/claude-code/managed-mcp.json";
103 return yield* fileSystem.exists(managedMcpConfigPath).pipe(Effect.orElseSucceed(() => false));
104});
105​
106// A worktree's .git file points at <main>/.git/worktrees/<name>, whose commondir leads back to
107// <main>/.git. A bare repository has no main checkout, so its worktree keeps its own file.
108// Untraced because claudeLocalSettingsDirectory already owns the span.
109const mainCheckoutRoot = Effect.fnUntraced(function* (checkout: string) {
110 const fileSystem = yield* FileSystem.FileSystem;
111 const path = yield* Path.Path;
112 return yield* fileSystem.readFileString(path.join(checkout, ".git")).pipe(
113 Effect.flatMap((pointer) => {
114 const gitDir = parseGitfileTarget(pointer);
115 if (gitDir === undefined) return Effect.succeed(checkout);
116 const worktreeGitDir = path.resolve(checkout, gitDir);
117 return fileSystem.readFileString(path.join(worktreeGitDir, "commondir")).pipe(
118 Effect.map((commonDir) => {
119 const common = path.resolve(worktreeGitDir, commonDir.trim());
120 return path.basename(common) === ".git" ? path.dirname(common) : checkout;
121 }),
122 );
123 }),
124 Effect.orElseSucceed(() => checkout),
125 );
126});
127​
128// Claude Code keeps .claude/settings.local.json at the repository root, or in cwd outside a
129// repository, on Windows, or when the root is home. Its owner check is skipped, so callers must
130// stay safe when Claude Code ignores the root file.
131export const claudeLocalSettingsDirectory = Effect.fn("claudeLocalSettingsDirectory")(function* (
132 cwd: string,
133) {
134 const fileSystem = yield* FileSystem.FileSystem;
135 const path = yield* Path.Path;
136 if ((yield* HostProcess.Platform) === "win32") return cwd;
137 for (let directory = cwd; ; directory = path.dirname(directory)) {
138 const isCheckout = yield* fileSystem
139 .exists(path.join(directory, ".git"))
140 .pipe(Effect.orElseSucceed(() => false));
141 if (isCheckout) {
142 const root = yield* mainCheckoutRoot(directory);
143 return root === (yield* HostProcess.HomeDirectory) ? cwd : root;
144 }
145 if (path.dirname(directory) === directory) return cwd;
146 }
147});
148​
149export const makeClaudeContinuationGroupKey = Effect.fn("makeClaudeContinuationGroupKey")(
150 function* (
151 config: Pick<ClaudeSettings, "homePath">,
152 environment?: NodeJS.ProcessEnv,
153 ): Effect.fn.Return<string, never, Path.Path | FileSystem.FileSystem> {
154 const fileSystem = yield* FileSystem.FileSystem;
155 const resolvedHomePath = yield* resolveClaudeHomePath(config, environment);
156 // Two instances that reach one Claude home through a symlink share sessions, so they can resume.
157 // Only the key uses the real path: the spawn keeps the literal path, which names the Keychain login.
158 const canonicalHomePath = yield* fileSystem
159 .realPath(resolvedHomePath)
160 .pipe(Effect.orElseSucceed(() => resolvedHomePath));
161 return `claude:home:${canonicalHomePath}`;
162 },
163);
164​
165export const makeClaudeCapabilitiesCacheKey = Effect.fn("makeClaudeCapabilitiesCacheKey")(
166 function* (
167 config: Pick<ClaudeSettings, "binaryPath" | "homePath">,
168 cwd?: string,
169 environment?: NodeJS.ProcessEnv,
170 ): Effect.fn.Return<string, never, Path.Path> {
171 const resolvedHomePath = yield* resolveClaudeHomePath(config, environment);
172 return `${config.binaryPath}\0${resolvedHomePath}\0${cwd ?? ""}`;
173 },
174);
175​
176/** Separate spawn env from login commands to preserve literal paths, including relative inherited values. */
177export const claudeSignedOutMessage = (input: {
178 readonly configDir: string | undefined;
179 readonly cwd: string;
180}): string => {
181 const configuration =
182 input.configDir !== undefined
183 ? ` from ${quotePath(input.cwd)}, with CLAUDE_CONFIG_DIR set to ${quotePath(input.configDir)}`
184 : "";
185 return `Claude could not authenticate. For subscription login, run \`claude auth login\` on this environment's machine${configuration}, then start a new thread. For API-key authentication, check this instance's configured credentials.`;
186};