Skip to content

Commit 763d08f

Browse files
authored
Merge pull request #70 from 7nohe/fix/claude-code-subscription
fix(claude-code): subscription mode silently generates empty docs when bypassPermissions is unavailable
2 parents a9de7d0 + 999767c commit 763d08f

1 file changed

Lines changed: 115 additions & 2 deletions

File tree

‎codewiki/src/be/caw_backend.py‎

Lines changed: 115 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,90 @@ def _patched(self) -> list[str]:
120120
# --- end stopgap --------------------------------------------------------------
121121

122122

123+
# --- claude-code allowedTools stopgap -----------------------------------------
124+
# Custom MCP-server tools (added via `--mcp-config`) are not auto-approved under
125+
# `acceptEdits`, and `bypassPermissions` may be disabled by an org managed
126+
# policy (see the cwd note below), so caw's `--dangerously-skip-permissions`
127+
# alone is not enough: CodeWiki's own toolkit (str_replace_editor,
128+
# read_code_components, generate_sub_module_documentation) gets denied
129+
# ("you haven't granted it yet"), the agent writes nothing, and the run
130+
# "succeeds" with an empty module tree. Grant the toolkit explicitly with
131+
# `--allowedTools` using the permission rule syntax:
132+
# https://code.claude.com/docs/en/settings#permission-rule-syntax
133+
# `--allowedTools` flag: https://code.claude.com/docs/en/cli-reference
134+
# caw's ClaudeCodeSession only ever emits `--disallowedTools`, so rewrite its
135+
# `claude` command to add `--allowedTools mcp__<server>` for every server in
136+
# the --mcp-config. The patch swaps the `subprocess` module reference INSIDE
137+
# caw.providers.claude_code for a thin proxy — the global subprocess.Popen
138+
# class stays untouched (isinstance / subclass safe) and no other claude
139+
# invocation in this process is affected. Belongs upstream in caw; remove
140+
# once it grows a first-class allowed_tools knob for its toolkit servers.
141+
_CLAUDE_ALLOWED_PATCH_APPLIED = False
142+
143+
144+
def _with_allowed_tools(cmd):
145+
"""Append ``--allowedTools mcp__<server>,...`` to a ``claude`` command.
146+
147+
Pure ``list -> list`` transform. Applies only when *cmd* is a claude
148+
invocation carrying ``--mcp-config`` and no explicit allow-list already;
149+
otherwise (or on any error) *cmd* is returned unchanged.
150+
"""
151+
import json
152+
153+
try:
154+
if not (
155+
isinstance(cmd, (list, tuple))
156+
and cmd
157+
and os.path.basename(str(cmd[0])) == "claude"
158+
and "--mcp-config" in cmd
159+
and "--allowedTools" not in cmd
160+
and "--allowed-tools" not in cmd
161+
):
162+
return cmd
163+
# caw emits a single `--mcp-config <path>`; only the first occurrence
164+
# is considered.
165+
cfg_path = cmd[list(cmd).index("--mcp-config") + 1]
166+
with open(cfg_path) as f:
167+
servers = list(json.load(f).get("mcpServers", {}).keys())
168+
if not servers:
169+
return cmd
170+
allowed = ",".join(f"mcp__{s}" for s in servers)
171+
logger.info("Injected --allowedTools for MCP servers: %s", servers)
172+
return list(cmd) + ["--allowedTools", allowed]
173+
except Exception as e: # never break the spawn on a patch hiccup
174+
logger.warning("claude allowedTools patch skipped: %s", e)
175+
return cmd
176+
177+
178+
def _patch_claude_allowed_tools() -> None:
179+
global _CLAUDE_ALLOWED_PATCH_APPLIED
180+
if _CLAUDE_ALLOWED_PATCH_APPLIED:
181+
return
182+
import subprocess
183+
184+
from caw.providers import claude_code as _caw_claude
185+
186+
class _SubprocessProxy:
187+
"""``subprocess`` stand-in that rewrites Popen commands.
188+
189+
Every other attribute (PIPE, run, ...) delegates to the real module.
190+
"""
191+
192+
@staticmethod
193+
def Popen(cmd, *args, **kwargs):
194+
return subprocess.Popen(_with_allowed_tools(cmd), *args, **kwargs)
195+
196+
def __getattr__(self, name):
197+
return getattr(subprocess, name)
198+
199+
_caw_claude.subprocess = _SubprocessProxy()
200+
_CLAUDE_ALLOWED_PATCH_APPLIED = True
201+
202+
203+
_patch_claude_allowed_tools()
204+
# --- end stopgap --------------------------------------------------------------
205+
206+
123207
class CawBackend(LLMBackend):
124208
"""Routes LLM operations through the claude / codex CLI subscription."""
125209

@@ -128,6 +212,10 @@ def __init__(self, config: Config) -> None:
128212
self._caw_provider = _resolve_caw_provider(config.provider)
129213
# main_model is passed straight through; empty string → caw default.
130214
self._model: str | None = config.main_model or None
215+
# Resolve once, before any agent-run chdir can move the cwd —
216+
# os.path.abspath is cwd-relative and _run_module_agent_sync recurses
217+
# (via generate_sub_module_documentation) while the cwd is pinned.
218+
self._repo_root = str(os.path.abspath(config.repo_path))
131219

132220
# Fail loudly here rather than producing a confusing caw error mid-run.
133221
cli = _CLI_BINARY[config.provider]
@@ -264,7 +352,7 @@ def _run_module_agent_sync(
264352

265353
deps = CodeWikiDeps(
266354
absolute_docs_path=working_dir,
267-
absolute_repo_path=str(os.path.abspath(config.repo_path)),
355+
absolute_repo_path=self._repo_root,
268356
registry={},
269357
components=components,
270358
path_to_current_module=list(module_path),
@@ -304,9 +392,34 @@ def _run_module_agent_sync(
304392
# they're cwd-independent. Safe to mutate process-wide cwd because
305393
# documentation_generator processes modules sequentially and recursive
306394
# _run_module_agent_sync calls chdir to the same absolute_docs_path.
395+
# caw runs claude with `--dangerously-skip-permissions`, expecting
396+
# bypassPermissions ("Everything" runs without asking). But an org
397+
# managed policy can DISABLE bypass mode, in which case the flag is
398+
# downgraded to `acceptEdits` — observed here: both
399+
# `--dangerously-skip-permissions` and `--permission-mode
400+
# bypassPermissions` report permissionMode=acceptEdits.
401+
# permission modes: https://code.claude.com/docs/en/permission-modes
402+
# (see #skip-all-checks-with-bypasspermissions-mode and its
403+
# disableBypassPermissionsMode managed setting).
404+
# Under acceptEdits, auto-approval is limited to reads/edits INSIDE the
405+
# working directory or additionalDirectories; paths outside that scope
406+
# still prompt (== denied in non-interactive `-p`):
407+
# https://code.claude.com/docs/en/permission-modes#auto-approve-file-edits-with-acceptedits-mode
408+
# caw chdir's into the output subdir (for codex's native file_change),
409+
# so the source tree in the PARENT repo is out-of-scope and every
410+
# source Read is denied -> empty docs. claude writes via CodeWiki's
411+
# str_replace_editor (absolute deps path), so it does NOT need cwd
412+
# pinned to the output dir. Pin cwd to the repo root so BOTH the source
413+
# tree and the output dir fall inside the workspace (alt: --add-dir,
414+
# https://code.claude.com/docs/en/cli-reference). Codex keeps the
415+
# output-dir chdir because its file_change resolves relative paths.
307416
original_cwd = os.getcwd()
417+
if self._caw_provider == "codex":
418+
run_cwd = working_dir
419+
else:
420+
run_cwd = self._repo_root
308421
try:
309-
os.chdir(working_dir)
422+
os.chdir(run_cwd)
310423
try:
311424
traj = agent.completion(user_prompt)
312425
finally:

0 commit comments

Comments
 (0)