Skip to content

Commit 243568a

Browse files
committed
fix(claude): gate the shell hook on an installed Claude Code CLI
The .zshrc hook was appended whenever system-env injection succeeded, so a user who never installed Claude Code still got an OpenCodex-owned block sourcing a file for a CLI they do not have, and a stale block survived uninstalling it. Write the hook only when an executable claude is discoverable on PATH, and reconcile rather than append: when Claude Code or system-env integration is gone, remove the OpenCodex-owned block and leave every user line untouched. Empty PATH segments are ignored so a workspace-local file is never mistaken for a durable installation, and a failed removal is reported as failed instead of reported as absent. Carries @lilinxiong's #2105 implementation and tests. Added a note on the intended failure direction: "installed" is answered from the PATH of the calling process, so a service context with a stripped PATH can remove a hook an interactive shell would have kept. That is reversible on the next foreground ocx start, whereas a hook pointing at an uninstalled CLI is the stale state this reconciliation exists to clear. Closes #2105
1 parent cd8f9b8 commit 243568a

11 files changed

Lines changed: 235 additions & 19 deletions

File tree

‎docs-site/src/content/docs/fr/guides/claude-code.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,10 @@ par le proxy sans nécessiter le wrapper `ocx claude`. Les shells déjà ouverts
142142

143143
`ocx stop` et l'arrêt du proxy **suppriment les variables injectées** (ils ne restaurent pas les valeurs précédentes —
144144
seules les clés injectées par opencodex sont supprimées). Le proxy écrit également `~/.opencodex/claude-env.sh` ;
145-
`ocx start` installe un hook source `.zshrc` qui le charge automatiquement.
145+
`ocx start` installe le hook source `.zshrc` uniquement lorsqu’un exécutable Claude Code CLI est
146+
présent dans le `PATH`. Au démarrage et avec `ocx ensure`, le hook appartenant à OpenCodex est supprimé
147+
si aucun exécutable du CLI Claude Code n’est trouvé dans le `PATH` ou si l’intégration de l’environnement
148+
système est inactive. Claude Desktop utilise son propre profil et ne déclenche pas l’installation du hook shell.
146149

147150
Désactivez cette intégration avec `claudeCode.systemEnv: false` dans la configuration ou avec le commutateur de l'interface.
148151
La fonctionnalité est réservée à macOS ; sur les autres plateformes, utilisez `ocx claude`.

‎docs-site/src/content/docs/guides/claude-code.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,10 @@ requiring the `ocx claude` wrapper. Already-open shells are unaffected and must
142142

143143
`ocx stop` and proxy shutdown **unset the injected keys** (it does not restore previous values —
144144
only the keys opencodex injected are removed). The proxy also writes `~/.opencodex/claude-env.sh`;
145-
`ocx start` installs a `.zshrc` source hook that loads it automatically.
145+
`ocx start` installs a `.zshrc` source hook that loads it automatically only when an executable
146+
Claude Code CLI is present on `PATH`. Startup and `ocx ensure` remove the OpenCodex-owned hook when
147+
Claude Code is absent or system environment integration is inactive. Claude Desktop uses its
148+
separate profile and does not cause shell-hook installation.
146149

147150
Disable with `claudeCode.systemEnv: false` in the configuration or with the GUI toggle. This
148151
feature is macOS-only; on other platforms, use `ocx claude`.

‎docs-site/src/content/docs/ja/guides/claude-code.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,9 @@ ocx claude
3737

3838
`ocx stop` とプロキシ終了は**注入されたキーを解除します**。以前の値を復元せず、opencodex が
3939
注入したキーのみ削除します。プロキシは `~/.opencodex/claude-env.sh` も書き出し、`ocx start` はこのファイルを
40-
自動で読み込む `.zshrc` source hook をインストールします。
40+
自動で読み込む `.zshrc` source hook を、実行可能な Claude Code CLI が `PATH` にある場合にのみインストールします。
41+
Claude Code が存在しない場合、またはシステム環境連携が無効な場合、起動処理と `ocx ensure` は OpenCodex が追加した
42+
hook を削除します。Claude Desktop は独立した profile を使用し、shell hook のインストールを引き起こしません。
4143

4244
設定で `claudeCode.systemEnv: false` に指定するか GUI トグルでオフにできます。この機能は macOS
4345
専用で、他のプラットフォームでは `ocx claude` を使ってください。

‎docs-site/src/content/docs/ko/guides/claude-code.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,9 @@ macOS의 자동 연결(`claudeCode.systemEnv`)도 같은 방식으로 판단하
6262

6363
`ocx stop`과 프록시 종료는 **주입된 키를 해제해요**. 이전 값을 복원하지는 않고 opencodex가
6464
주입한 키만 제거해요. 프록시는 `~/.opencodex/claude-env.sh`도 작성하고, `ocx start`는 이 파일을
65-
자동으로 불러오는 `.zshrc` source hook을 설치해요.
65+
자동으로 불러오는 `.zshrc` source hook을 실행 가능한 Claude Code CLI가 `PATH`에 있을 때만 설치해요.
66+
Claude Code가 없거나 시스템 환경 연동이 비활성화되어 있으면 시작 과정과 `ocx ensure`가 OpenCodex가 추가한
67+
hook을 제거해요. Claude Desktop은 별도 profile을 사용하며 shell hook 설치를 유발하지 않아요.
6668

6769
설정에서 `claudeCode.systemEnv: false`로 지정하거나 GUI 토글로 끌 수 있어요. 이 기능은 macOS
6870
전용이며, 다른 플랫폼에서는 `ocx claude`를 사용하세요.

‎docs-site/src/content/docs/ru/guides/claude-code.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,10 @@ ocx claude
3939

4040
`ocx stop` и остановка прокси **снимают внедрённые ключи** (прежние значения не восстанавливаются —
4141
удаляются только ключи, внедрённые opencodex). Прокси также записывает `~/.opencodex/claude-env.sh`;
42-
`ocx start` устанавливает source-хук в `.zshrc`, который загружает этот файл автоматически.
42+
`ocx start` устанавливает source-хук в `.zshrc` только когда исполняемый Claude Code CLI найден в
43+
`PATH`. При запуске и выполнении `ocx ensure` хук, принадлежащий OpenCodex, удаляется, если файл Claude
44+
Code CLI не найден в `PATH`, не имеет права на выполнение или системная интеграция окружения выключена.
45+
Claude Desktop использует отдельный профиль и не вызывает установку shell-хука.
4346

4447
Отключить можно параметром `claudeCode.systemEnv: false` в конфигурации или переключателем в GUI.
4548
Функция доступна только на macOS; на других платформах используйте `ocx claude`.

‎docs-site/src/content/docs/tr/guides/claude-code.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -172,8 +172,11 @@ olan kabuklar etkilenmez ve yeniden açılmalıdır.
172172
`ocx stop` ve proxy'nin kapatılması **enjekte edilen anahtarları kaldırır**
173173
(önceki değerleri geri yüklemez — yalnızca opencodex'in enjekte ettiği
174174
anahtarlar kaldırılır). Proxy ayrıca `~/.opencodex/claude-env.sh` dosyasını
175-
yazar; `ocx start`, bunu otomatik olarak yükleyen bir `.zshrc` kaynak kancası
176-
kurar.
175+
yazar; `ocx start`, bunu otomatik olarak yükleyen `.zshrc` kaynak kancasını
176+
yalnızca çalıştırılabilir Claude Code CLI `PATH` içinde bulunduğunda kurar.
177+
Claude Code yoksa veya sistem ortamı entegrasyonu etkin değilse başlangıç işlemi
178+
ve `ocx ensure`, OpenCodex tarafından eklenen kancayı kaldırır. Claude Desktop ayrı
179+
bir profil kullanır ve shell kancasının kurulmasını tetiklemez.
177180

178181
Yapılandırmada `claudeCode.systemEnv: false` ile veya GUI anahtarıyla devre dışı
179182
bırakın. Bu özellik yalnızca macOS içindir; diğer platformlarda `ocx claude`
@@ -605,4 +608,3 @@ aracının `model` argümanını değil, `<!-- ocx-route: ... -->` yönergelerin
605608
kullanır. Yönergenin hedeflenen rotayla eşleştiğinden emin olun. Model yer
606609
tutucusu olarak `"haiku"` iletin.
607610

608-

‎docs-site/src/content/docs/zh-cn/guides/claude-code.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,9 @@ shell 不受影响,必须重新打开。
3737

3838
`ocx stop` 和代理关闭操作会**取消设置已注入的键**(不会恢复之前的值——只会移除 opencodex
3939
注入的键)。代理还会写入 `~/.opencodex/claude-env.sh`;`ocx start` 会安装一个 `.zshrc`
40-
source hook,以自动加载该文件。
40+
source hook,以自动加载该文件,但仅限 `PATH` 中存在可执行的 Claude Code CLI。Claude Code
41+
不存在或系统环境集成未启用时,启动过程和 `ocx ensure` 会移除 OpenCodex 自己写入的 hook。
42+
Claude Desktop 使用独立 profile,不会触发 shell hook 安装。
4143

4244
可以在配置中设置 `claudeCode.systemEnv: false`,或使用 GUI 开关来禁用。此功能仅适用于
4345
macOS;在其他平台上,请使用 `ocx claude`。

‎docs-site/src/content/docs/zh-tw/guides/claude-code.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,9 @@ shell 不受影響,必須重新開啟。
113113

114114
`ocx stop` 和代理關閉操作會**取消設定已注入的鍵**(不會恢復之前的值——只會移除 opencodex
115115
注入的鍵)。代理還會寫入 `~/.opencodex/claude-env.sh`;`ocx start` 會安裝一個 `.zshrc`
116-
source hook,以自動載入該檔案。
116+
source hook,以自動載入該檔案,但僅限 `PATH` 中存在可執行的 Claude Code CLI。Claude Code
117+
不存在或系統環境整合未啟用時,啟動程序和 `ocx ensure` 會移除 OpenCodex 自己寫入的 hook。
118+
Claude Desktop 使用獨立 profile,不會觸發 shell hook 安裝。
117119

118120
可以在設定中設定 `claudeCode.systemEnv: false`,或使用 GUI 開關來停用。此功能僅適用於
119121
macOS;在其他平臺上,請使用 `ocx claude`。

‎src/cli/index.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,8 @@ import { loadServiceTokenFromFile } from "../lib/service-secrets";
4646
import { diagnoseService, isServiceOwnershipError, serviceCommand, serviceEnvironmentOwnedHere, serviceStartableFromTray, serviceStatusSummary, stopServiceIfInstalled, uninstallServiceIfInstalled } from "../service";
4747
import { startupHealthSummary } from "../codex/autostart-health";
4848
import { drainAndShutdown, isRecyclingForExit, startServer } from "../server";
49-
import { injectSystemEnv, revertSystemEnv } from "../server/system-env";
49+
import { injectSystemEnv, reconcileShellHook, revertSystemEnv, uninstallShellHook } from "../server/system-env";
5050
import { buildDesktop3pRegistry } from "../claude/desktop-3p";
51-
import { installShellHook, uninstallShellHook } from "../server/system-env";
5251
import { startTokenGuardian } from "../oauth/token-guardian";
5352
import { startHistoryMigrationGuardian } from "../codex/history-migration-guardian";
5453
import { maybeShowStarPrompt } from "./star-prompt";
@@ -366,9 +365,10 @@ async function handleStart(options: { block?: boolean } = {}) {
366365

367366
// System-wide env injection AFTER signal handlers are registered (crash safety:
368367
// syncCleanup reverts even if injection itself or subsequent startup steps fail).
369-
await injectSystemEnv(port, config).catch(() => {});
370-
// Auto-install .zshrc hook (idempotent — skips if already present).
371-
installShellHook();
368+
const systemEnv = await injectSystemEnv(port, config).catch(() => ({ injected: false }));
369+
// The hook is useful only for an installed Claude Code CLI. Reconcile instead of
370+
// appending unconditionally so stale OpenCodex-owned hooks are removed as well.
371+
reconcileShellHook(systemEnv.injected);
372372

373373
await maybeShowStarPrompt(); // once-only Yes/No GitHub-star prompt on first interactive start
374374
// Post-startup sync drives the readiness gate AND the #1046 stale app-server
@@ -455,7 +455,8 @@ async function handleEnsure(options: { existingIsSuccess?: boolean } = {}): Prom
455455
});
456456
if (synced?.status === "skipped") console.log(" Codex integration OFF; startup left Codex native.");
457457
// Ensure env file exists for already-running proxy (may have been deleted or pre-dates this feature).
458-
await injectSystemEnv(live.port, config).catch(() => {});
458+
const systemEnv = await injectSystemEnv(live.port, config).catch(() => ({ injected: false }));
459+
reconcileShellHook(systemEnv.injected);
459460
// Refresh the Grok Build fence too (same contract as start). live.hostname is the
460461
// hostname the running proxy actually bound — config.hostname may have drifted.
461462
try {

‎src/server/system-env.ts‎

Lines changed: 64 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { execFileSync } from "node:child_process";
2-
import { readFileSync, writeFileSync, unlinkSync, mkdirSync } from "node:fs";
3-
import { join } from "node:path";
2+
import { accessSync, constants, readFileSync, writeFileSync, unlinkSync, mkdirSync, statSync } from "node:fs";
3+
import { delimiter, join } from "node:path";
44
import { getConfigDir } from "../config";
55
import { resolveAutoContext, type AutoContextMode } from "../claude/context-windows";
66
import { PROXY_MARKER, defaultAuthDetectDeps, detectClaudeAuth, ownAdmissionTokens } from "../claude/auth-detect";
@@ -122,11 +122,72 @@ export function uninstallShellHook(): { removed: boolean; reason?: string } {
122122
const cleaned = content.replace(/\n?# opencodex claude-env hook\n\[.*claude-env\.sh.*\n?/g, "\n");
123123
writeFileSync(zshrcPath, cleaned, { encoding: "utf8", mode: 0o644 });
124124
return { removed: true };
125-
} catch {
125+
} catch (error) {
126+
if (error && typeof error === "object" && (error as { code?: unknown }).code === "ENOENT") {
127+
return { removed: false, reason: "not installed" };
128+
}
126129
return { removed: false, reason: "read/write failed" };
127130
}
128131
}
129132

133+
/** Whether a real `claude` executable is discoverable from this process's PATH. */
134+
export function claudeCodeCliInstalled(pathValue = process.env.PATH): boolean {
135+
if (!pathValue) return false;
136+
for (const directory of pathValue.split(delimiter)) {
137+
// An empty PATH segment means the current directory. Do not let the proxy treat a
138+
// workspace-local file as a durable user installation.
139+
if (!directory) continue;
140+
const candidate = join(directory, "claude");
141+
try {
142+
if (!statSync(candidate).isFile()) continue;
143+
accessSync(candidate, constants.X_OK);
144+
return true;
145+
} catch {
146+
// Keep scanning PATH after missing, non-file, and non-executable entries.
147+
}
148+
}
149+
return false;
150+
}
151+
152+
/**
153+
* Keep the shell hook aligned with the integration that can actually consume it.
154+
* Claude Desktop uses its own profile and does not source `.zshrc`; this hook exists
155+
* only for plain Claude Code CLI launches.
156+
*
157+
* Reconciliation is PATH-sensitive by construction: "Claude Code is installed" is answered
158+
* from the PATH of whichever process calls this. A launchd/service context with a stripped
159+
* PATH can therefore fail to see a `claude` the user's interactive shell finds, and this will
160+
* remove the hook. That is the intended failure direction — removing an OpenCodex-owned block
161+
* is reversible on the next foreground `ocx start`, whereas leaving a hook pointing at an
162+
* uninstalled CLI is the stale state this reconciliation exists to clear. Only the block
163+
* carrying our own marker is ever touched; user lines are preserved.
164+
*/
165+
export function reconcileShellHook(systemEnvInjected: boolean): {
166+
changed: boolean;
167+
state: "installed" | "absent" | "failed";
168+
reason?: string;
169+
} {
170+
if (process.platform !== "darwin") return { changed: false, state: "absent", reason: "not macOS" };
171+
if (systemEnvInjected && claudeCodeCliInstalled()) {
172+
const result = installShellHook();
173+
if (result.installed) return { changed: true, state: "installed" };
174+
if (result.reason === "already installed") {
175+
return { changed: false, state: "installed", reason: result.reason };
176+
}
177+
return { changed: false, state: "failed", reason: result.reason ?? "install failed" };
178+
}
179+
180+
const result = uninstallShellHook();
181+
if (!result.removed && result.reason !== "not installed") {
182+
return { changed: false, state: "failed", reason: result.reason ?? "remove failed" };
183+
}
184+
return {
185+
changed: result.removed,
186+
state: "absent",
187+
reason: systemEnvInjected ? "Claude Code not installed" : "system environment inactive",
188+
};
189+
}
190+
130191
const SYSTEM_ENV_NAMES = [
131192
"ANTHROPIC_BASE_URL",
132193
"CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY",

0 commit comments

Comments
 (0)