UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

185 lines • 8.39 kB
/** * WHICH environment variables a daemon this machine starts is allowed to see. * * A shared daemon outlives the shell that started it and serves every client on the machine, so * "whatever the ensuring process happened to have" is the wrong scope for its environment: a CI * token, a database URL or a one-off secret exported in one terminal would be inherited by a * process that then answers other clients for hours. The daemon therefore receives an ALLOWLIST - * the names a coding agent genuinely needs (the shell's own wiring, the locale, the brand's own * `SENPI_`/`OMO_`/`PI_` lane, proxy settings and provider credentials) - plus whatever the launch * spec states explicitly. Everything else is dropped, by NAME, without ever reading its value. * * The allowlist is matched case-sensitively on POSIX, where `PATH` and `Path` are two different * variables, and case-insensitively on win32, where they are one - and where a daemon stripped of * `SystemRoot`, `ComSpec` or `PATHEXT` cannot spawn a child at all. */ import { join } from "node:path"; import { providerCredentialEnvNames } from "@earendil-works/pi-ai"; import { envSlotVarNames } from "../../core/credential-pool/env-slots.js"; import { HOST_HANDOFF_ENV_NAMES, HOST_STARTUP_EVENTS_ENV, isHostHandoffEnvName, ORIGIN_HOST_INSTANCE_ENV, } from "./host-identity-env.js"; import { parseJson, readFileOrUndefined, writeStateFile } from "./host-daemon-state.js"; /** Names a daemon may inherit from the process that ensures it. */ const ALLOWED_ENV_NAMES = [ /^(PATH|HOME|USER|LOGNAME|SHELL|TMPDIR|TERM|LANG)$/u, /^(LC|XDG)_/u, /^(SENPI|OMO|PI)_/u, /^BSK_(HOME|BIN)$/u, /^(HTTPS?_PROXY|NO_PROXY)$/u, /^[A-Z0-9_]+_API_KEY$/u, /^(ANTHROPIC|OPENAI|GOOGLE|GEMINI|AZURE|AWS|OPENROUTER|XAI|MISTRAL|DEEPSEEK|GROQ|CEREBRAS|MINIMAX)_/u, ]; /** * The exact credential names the engine's own provider lookup reads (`getEnvApiKey`, numbered env * slots, `CLAUDE_CODE_OAUTH_TOKEN`), derived from that lookup so a daemon and a direct process can * never disagree about which credentials exist (senpi#3531). Exact names only, no new prefix. */ const PROVIDER_CREDENTIAL_ENV_NAMES = new Set([ ...providerCredentialEnvNames(), ...envSlotVarNames(), ]); /** * win32 wiring no process can run without. Dropping `SystemRoot` alone makes every subsequent * `spawn` fail, so these are allowed in addition to the list above on that platform only. */ const WINDOWS_SYSTEM_ENV_NAMES = new Set([ "SYSTEMROOT", "SYSTEMDRIVE", "WINDIR", "COMSPEC", "PATHEXT", "TEMP", "TMP", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "PROGRAMFILES", "PROGRAMFILES(X86)", "PROGRAMDATA", "HOMEDRIVE", "HOMEPATH", "NUMBER_OF_PROCESSORS", "PROCESSOR_ARCHITECTURE", "OS", ]); /** * Values that identify one session, one eval kernel, or the lifecycle of the calling host. * They are namespaced like ordinary configuration, so the broad product-lane allowlist alone * cannot distinguish them. A new daemon must receive its own forced host identity instead. */ const TRANSIENT_ENV_NAMES = new Set([ "PI_SESSION_ID", "PI_SESSION_FILE", "PI_SESSION_CWD", "PI_GOAL_STORE_FILE", "PI_PROVIDER", "PI_MODEL", "PI_REASONING_LEVEL", "OMO_BROWSER_ENGINE", "PI_PROMPT_CACHE_SAFE_WAIT_SECONDS", "SENPI_PY_KERNEL_PARENT_PID", // A supervisor's whole hand-off to its own host child, from the one list its other readers share // (senpi#5635). A daemon ensured BY a host child would otherwise inherit its parent's lane: with the // key sentinel set and no key on its stdin, it exits "internal_key_unavailable" before it listens // (senpi#4528). The origin attribution names the ensuring host, which a separate daemon is not. ...HOST_HANDOFF_ENV_NAMES, ORIGIN_HOST_INSTANCE_ENV, // A coordinated launch's startup-event binding (senpi#4602): it names one attempt's pipe, which a // separately ensured daemon does not report on. HOST_STARTUP_EVENTS_ENV, // Engine trust launch plumbing: a daemon gets the generation only through its forced hand-off. "SENPI_ENGINE_TRUST", "SENPI_ENGINE_TRUST_HOP", ]); /** A name one session or one host generation owns; a caller may never pass it to a child either (senpi#4381). */ export function isTransientDaemonEnvName(name) { return TRANSIENT_ENV_NAMES.has(name); } export function daemonEnvIsAllowed(name, platform = process.platform) { const upper = name.toUpperCase(); if (TRANSIENT_ENV_NAMES.has(platform === "win32" ? upper : name) || isHostHandoffEnvName(name, platform)) return false; if (platform !== "win32") { return PROVIDER_CREDENTIAL_ENV_NAMES.has(name) || ALLOWED_ENV_NAMES.some((pattern) => pattern.test(name)); } return (WINDOWS_SYSTEM_ENV_NAMES.has(upper) || PROVIDER_CREDENTIAL_ENV_NAMES.has(upper) || ALLOWED_ENV_NAMES.some((pattern) => pattern.test(upper))); } /** * The `env` an ensure hands the daemon: every name it may NOT inherit mapped to `null` (which * removes it), then the launch spec's daemon-safe entries. Values are never inspected - a variable * is kept or dropped by its name alone - and an allowed spec entry wins because it was intentional. */ export function daemonEnvOverrides(processEnv, specEnv = {}, platform = process.platform) { const overrides = {}; for (const name of Object.keys(processEnv)) { if (!daemonEnvIsAllowed(name, platform)) overrides[name] = null; } for (const [name, value] of Object.entries(specEnv)) { if (daemonEnvIsAllowed(name, platform)) overrides[name] = value; } return overrides; } /** * The complete environment passed to a daemon spawn. It starts from the allowlisted process/system * scope, applies explicit launch overrides only when those names are daemon-safe, then applies the * generation's forced identity last. Building from an empty object means a transient value cannot * survive merely because a direct lifecycle caller bypassed `host-runner`. */ export function daemonEnvironment(processEnv, overrides = {}, forced = {}, platform = process.platform) { const env = {}; for (const [name, value] of Object.entries(processEnv)) { if (value !== undefined && daemonEnvIsAllowed(name, platform)) env[name] = value; } for (const [name, value] of Object.entries(overrides)) { if (!daemonEnvIsAllowed(name, platform)) continue; deleteEnvironmentName(env, name, platform); if (value !== null) env[name] = value; } for (const [name, value] of Object.entries(forced)) { deleteEnvironmentName(env, name, platform); env[name] = value; } return env; } /** The names the daemon ends up with, sorted. Names only: a value never leaves this process. */ export function daemonEnvKeys(processEnv, specEnv = {}, platform = process.platform) { const kept = Object.keys(processEnv).filter((name) => daemonEnvIsAllowed(name, platform)); const explicit = Object.keys(specEnv).filter((name) => daemonEnvIsAllowed(name, platform)); return [...new Set([...kept, ...explicit])].sort(); } /** * Records the granted NAMES beside the daemon's other state, so `senpi host status` can report the * scope a running daemon was started with. Written by whichever client spawned the generation; * absent for a daemon started by a client that predates this file, which reads as "unknown scope". */ export async function writeDaemonEnvKeys(paths, keys) { await writeStateFile(daemonEnvKeysFile(paths), { env_keys: keys }); } export async function readDaemonEnvKeys(paths) { const parsed = parseJson(await readFileOrUndefined(daemonEnvKeysFile(paths))); const keys = parsed?.env_keys; if (!Array.isArray(keys)) return []; return keys.filter((key) => typeof key === "string"); } function daemonEnvKeysFile(paths) { return join(paths.dir, "env-keys.json"); } function deleteEnvironmentName(env, name, platform) { if (platform !== "win32") { delete env[name]; return; } const upper = name.toUpperCase(); for (const existing of Object.keys(env)) { if (existing.toUpperCase() === upper) delete env[existing]; } } //# sourceMappingURL=host-daemon-env.js.map