Files
gabrielvidal ddbcd1c1b0 Merge branch 'plugin-conversation-labels' into merge-4-tracks
# Conflicts:
#	backend/plugins/manifest.py
#	docs/plugins.md
#	sidecar/claude_env.py
2026-11-26 19:41:22 +01:00

123 lines
5.5 KiB
Python

"""
The environment a Claude Code process launches with, and this machine's own
Claude login — the shared plumbing the core sidecar needs whichever harness
plugins are installed: the env of every run (``_run_env``: the session id,
the notify CLI on PATH, a worker's outbox transport — the opencode / agy
drivers use it with ``account=None``), the env that selects a Claude login
(``_account_env``: its config dir, the hub's proxy pair, the API key
stripped — what the core's own ``claude`` side calls use: ``/complete``,
``claude mcp``, ``claude plugin``), where an account's transcripts live
(``_account_projects``: ``/feed``, ``/terminal``, pairing), and whether
a run bills the worker's own login (``machine_login``: ``_account_env``, the
Claude proxy).
The claude harness itself — its runs and argv, its logins, ``claude auth
status``, what this machine's own login says (``/health``'s ``ownLogin``),
the token the hub's proxy swaps in — is the harness-claude plugin's
(``sidecar/accounts.py`` / ``claude_launch.py`` there). This module never
imports a plugin.
"""
import os
import pathlib
import claude_proxy
import outbox
import pairing
import proxy_pair
from fastapi import HTTPException
from config import (ACCOUNTS, BG_WAIT_CEILING_MS, CLAUDE_PROJECTS, CLI_DIR, IS_WORKER,
LOG_DIR, RUN_ENV_STRIP, STRIP_API_KEY, config_dir, guest_shaped, guest_uid,
known_account)
def _valid_account(account: str | None) -> str:
"""The Claude login a run (or a session move) is on (unset ⇒ the default
account). An unknown id is a 400 — never a quiet fallback onto the
default account, which would bill the wrong subscription."""
from config import DEFAULT_ACCOUNT
a = (account or "").strip().lower() or DEFAULT_ACCOUNT
if not known_account(a) and not claude_proxy.proxied(a) and not machine_login(a):
raise HTTPException(400, f"unknown account: {account!r} "
f"(known: {', '.join(ACCOUNTS)}, guest-<id>)")
return a
# ── a guest's own computer: their Claude is the machine's login ─────────────
def machine_login(account: str | None) -> bool:
"""Does a run on ``account`` use this machine's own Claude login?
On a guest's own computer (a worker dialling the hub — link.py)
``guest-<uid>`` is its owner's own Claude: the login ``claude`` in its
terminal uses (``~/.claude``), never sent through the hub's proxy. The hub
picks it for a guest who bills their own Claude (backend
``users/runs.computer_account``). Nowhere else: a tailnet worker is the
owner's machine, and the host reads ``guest-<uid>`` as a config dir."""
if not (IS_WORKER and guest_shaped(account)) or claude_proxy.proxied(account):
return False
import link
return bool(link.config())
def _outbox_url() -> str:
bind = os.environ.get("SIDECAR_BIND", "127.0.0.1")
return f"http://{bind}:{os.environ.get('SIDECAR_PORT', '8790')}"
def _run_env(sid: str, account: str | None) -> dict[str, str]:
"""``_account_env`` plus what the notify CLI needs: the session id (so a
push links the right conversation without a resolver) and, on a worker,
the outbox transport."""
env = _account_env(account)
env["CLAUDE_SESSION_ID"] = sid
env["PATH"] = f"{env.get('PATH', '')}:{CLI_DIR}" if env.get("PATH") else str(CLI_DIR)
if BG_WAIT_CEILING_MS:
env["CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS"] = BG_WAIT_CEILING_MS
env["STOP_GUARD_STATE_DIR"] = str(LOG_DIR) # harness-claude's stop_guard: hold marker + mailbox
if IS_WORKER:
env["AI_AGENT_OUTBOX_URL"] = _outbox_url()
env["AI_AGENT_OUTBOX_TOKEN"] = outbox.run_token(pairing.state_dir())
return env
def _account_env(account: str | None) -> dict[str, str]:
"""The environment a run launches with: the account's config dir exported
as CLAUDE_CONFIG_DIR (the default account gets it *removed*, so a stray
value in the unit can't redirect it), and ANTHROPIC_API_KEY stripped when
accounts are declared (see STRIP_API_KEY). On a worker, an account the
hub proxies sends its model calls to the hub, which bills its own login
(claude_proxy.py). ``account`` None = a pi run, which isn't a Claude
login at all: the host env passes through as-is."""
env = {**os.environ, "CLAUDE_CODE_ENTRYPOINT": "ai-agent-sidecar"}
# The sidecar's own bearer is not the run's business: with it, any session
# could drive /spawn, /message, /interrupt and the account logins of this
# very sidecar, outside whatever scope its own launch was given.
for k in RUN_ENV_STRIP:
env.pop(k, None)
if account is None:
return env
env.pop("CLAUDE_CONFIG_DIR", None)
if STRIP_API_KEY:
env.pop("ANTHROPIC_API_KEY", None)
cfg = config_dir(account)
if cfg is not None:
env["CLAUDE_CONFIG_DIR"] = str(cfg)
if claude_proxy.proxied(account):
claude_proxy.apply_env(env, account)
elif machine_login(account):
# The guest's own login: none of the hub's pair, wherever this
# process got it from (its settings-file copy is with_settings_env's).
proxy_pair.strip_env(env, claude_proxy.own_login_leak(None, env))
return env
def _account_projects(account: str) -> pathlib.Path:
"""Where an account's transcripts live (one dir per cwd slug). A guest's
``projects`` is a link to the default account's (``provision_guest``)."""
cfg = config_dir(account)
if cfg is None or guest_uid(account):
return CLAUDE_PROJECTS
return cfg / "projects"