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

ClaudeHome.ts

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