|
| 1 | +/** |
| 2 | + * v5-native environment injection for AgentV project config. |
| 3 | + * |
| 4 | + * `env_path` loads dotenv-style files and `env_from` runs argv commands and |
| 5 | + * parses their stdout, both injecting into `process.env` before validation |
| 6 | + * and eval so target `{{ env.* }}` interpolation can see the values. This is |
| 7 | + * the replacement path for the deprecated `hooks.before_session`. |
| 8 | + * |
| 9 | + * Existing `process.env` values always win — neither source overwrites a key |
| 10 | + * that is already set. Values are never printed; only file paths, commands, |
| 11 | + * and counts are logged. |
| 12 | + * |
| 13 | + * @module |
| 14 | + */ |
| 15 | + |
| 16 | +import { spawnSync } from 'node:child_process'; |
| 17 | +import { readFile } from 'node:fs/promises'; |
| 18 | +import path from 'node:path'; |
| 19 | + |
| 20 | +import type { EnvFromEntry, EnvFromFormat } from './loaders/config-loader.js'; |
| 21 | + |
| 22 | +const ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/; |
| 23 | + |
| 24 | +/** |
| 25 | + * Parse `KEY=value` / `export KEY=value` lines, shared by `env_path` dotenv |
| 26 | + * files and `env_from` `shell_exports` output. Quotes are stripped; blank |
| 27 | + * lines, comments, and non-matching lines are skipped. |
| 28 | + */ |
| 29 | +export function parseShellExportsEnv(content: string): Record<string, string> { |
| 30 | + const result: Record<string, string> = {}; |
| 31 | + |
| 32 | + for (const line of content.split('\n')) { |
| 33 | + const trimmed = line.trim(); |
| 34 | + if (!trimmed || trimmed.startsWith('#')) continue; |
| 35 | + |
| 36 | + const match = trimmed.match(/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/); |
| 37 | + if (!match) continue; |
| 38 | + |
| 39 | + const key = match[1]; |
| 40 | + let value = match[2]; |
| 41 | + if ( |
| 42 | + (value.startsWith('"') && value.endsWith('"')) || |
| 43 | + (value.startsWith("'") && value.endsWith("'")) |
| 44 | + ) { |
| 45 | + value = value.slice(1, -1); |
| 46 | + } |
| 47 | + |
| 48 | + result[key] = value; |
| 49 | + } |
| 50 | + |
| 51 | + return result; |
| 52 | +} |
| 53 | + |
| 54 | +/** |
| 55 | + * Parse a flat JSON object of string values for `env_from` `format: json`. |
| 56 | + * Throws on invalid JSON, non-object shapes, invalid env var names, or |
| 57 | + * non-string values. |
| 58 | + */ |
| 59 | +export function parseJsonEnv(content: string): Record<string, string> { |
| 60 | + let parsed: unknown; |
| 61 | + try { |
| 62 | + parsed = JSON.parse(content); |
| 63 | + } catch { |
| 64 | + // Do not include the parser's message: JS engines embed a snippet of the |
| 65 | + // offending content in JSON syntax errors, which could leak a secret |
| 66 | + // value from malformed env_from output. |
| 67 | + throw new Error('invalid JSON'); |
| 68 | + } |
| 69 | + |
| 70 | + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { |
| 71 | + throw new Error('expected a flat JSON object of string values'); |
| 72 | + } |
| 73 | + |
| 74 | + const result: Record<string, string> = {}; |
| 75 | + for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) { |
| 76 | + if (!ENV_NAME_PATTERN.test(key)) { |
| 77 | + throw new Error(`invalid environment variable name "${key}"`); |
| 78 | + } |
| 79 | + if (typeof value !== 'string') { |
| 80 | + throw new Error(`value for "${key}" must be a string`); |
| 81 | + } |
| 82 | + result[key] = value; |
| 83 | + } |
| 84 | + |
| 85 | + return result; |
| 86 | +} |
| 87 | + |
| 88 | +/** Injects vars into process.env; existing keys and invalid names are skipped. Returns injected count. */ |
| 89 | +function injectEnv(vars: Record<string, string>): number { |
| 90 | + let injected = 0; |
| 91 | + for (const [key, value] of Object.entries(vars)) { |
| 92 | + if (!ENV_NAME_PATTERN.test(key)) continue; |
| 93 | + if (process.env[key] === undefined) { |
| 94 | + process.env[key] = value; |
| 95 | + injected++; |
| 96 | + } |
| 97 | + } |
| 98 | + return injected; |
| 99 | +} |
| 100 | + |
| 101 | +export type EnvPathLoadResult = { |
| 102 | + readonly loaded: readonly string[]; |
| 103 | + readonly missing: readonly string[]; |
| 104 | + readonly injectedCount: number; |
| 105 | +}; |
| 106 | + |
| 107 | +/** |
| 108 | + * Load one or more dotenv-style files and inject their variables into |
| 109 | + * `process.env`. Relative paths resolve against `baseDir`. A missing file |
| 110 | + * warns and is skipped rather than failing the command. |
| 111 | + */ |
| 112 | +export async function loadEnvPathFiles( |
| 113 | + envPaths: readonly string[], |
| 114 | + baseDir: string, |
| 115 | +): Promise<EnvPathLoadResult> { |
| 116 | + const loaded: string[] = []; |
| 117 | + const missing: string[] = []; |
| 118 | + let injectedCount = 0; |
| 119 | + |
| 120 | + for (const envPath of envPaths) { |
| 121 | + const resolvedPath = path.isAbsolute(envPath) ? envPath : path.join(baseDir, envPath); |
| 122 | + |
| 123 | + let content: string; |
| 124 | + try { |
| 125 | + content = await readFile(resolvedPath, 'utf8'); |
| 126 | + } catch (error) { |
| 127 | + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { |
| 128 | + missing.push(resolvedPath); |
| 129 | + logWarning(`env_path file not found: ${resolvedPath}`); |
| 130 | + continue; |
| 131 | + } |
| 132 | + throw new Error(`Could not read env_path file ${resolvedPath}: ${(error as Error).message}`); |
| 133 | + } |
| 134 | + |
| 135 | + injectedCount += injectEnv(parseShellExportsEnv(content)); |
| 136 | + loaded.push(resolvedPath); |
| 137 | + } |
| 138 | + |
| 139 | + if (injectedCount > 0) { |
| 140 | + console.log( |
| 141 | + `env_path injected ${injectedCount} environment variable(s) from ${loaded.length} file(s).`, |
| 142 | + ); |
| 143 | + } |
| 144 | + |
| 145 | + return { loaded, missing, injectedCount }; |
| 146 | +} |
| 147 | + |
| 148 | +export type EnvFromRunResult = { |
| 149 | + readonly injectedCount: number; |
| 150 | +}; |
| 151 | + |
| 152 | +function parseEnvFromOutput(stdout: string, format: EnvFromFormat): Record<string, string> { |
| 153 | + return format === 'json' ? parseJsonEnv(stdout) : parseShellExportsEnv(stdout); |
| 154 | +} |
| 155 | + |
| 156 | +/** |
| 157 | + * Run one or more `env_from` argv commands and inject their parsed stdout |
| 158 | + * into `process.env`. A non-zero exit, spawn failure, or unparseable output |
| 159 | + * throws — command failures must fail the invoking command. stdout is never |
| 160 | + * logged or included in error messages since it may carry secret values. |
| 161 | + */ |
| 162 | +export async function runEnvFromEntries( |
| 163 | + entries: readonly EnvFromEntry[], |
| 164 | + options: { readonly cwd: string }, |
| 165 | +): Promise<EnvFromRunResult> { |
| 166 | + let injectedCount = 0; |
| 167 | + |
| 168 | + for (const entry of entries) { |
| 169 | + const [command, ...args] = entry.command; |
| 170 | + const commandLabel = entry.command.join(' '); |
| 171 | + console.log(`Running env_from command: ${commandLabel}`); |
| 172 | + |
| 173 | + const result = spawnSync(command, args, { |
| 174 | + cwd: options.cwd, |
| 175 | + encoding: 'utf8', |
| 176 | + stdio: ['ignore', 'pipe', 'pipe'], |
| 177 | + }); |
| 178 | + |
| 179 | + if (result.stderr) { |
| 180 | + process.stderr.write(result.stderr); |
| 181 | + } |
| 182 | + |
| 183 | + if (result.error) { |
| 184 | + throw new Error(`env_from command failed to start: ${commandLabel}: ${result.error.message}`); |
| 185 | + } |
| 186 | + if (result.status !== 0) { |
| 187 | + throw new Error( |
| 188 | + `env_from command exited with code ${result.status ?? 'unknown'}: ${commandLabel}`, |
| 189 | + ); |
| 190 | + } |
| 191 | + |
| 192 | + const format = entry.format ?? 'shell_exports'; |
| 193 | + let vars: Record<string, string>; |
| 194 | + try { |
| 195 | + vars = parseEnvFromOutput(result.stdout ?? '', format); |
| 196 | + } catch (error) { |
| 197 | + throw new Error( |
| 198 | + `env_from command produced invalid ${format} output: ${commandLabel}: ${(error as Error).message}`, |
| 199 | + ); |
| 200 | + } |
| 201 | + |
| 202 | + injectedCount += injectEnv(vars); |
| 203 | + } |
| 204 | + |
| 205 | + if (injectedCount > 0) { |
| 206 | + console.log(`env_from injected ${injectedCount} environment variable(s).`); |
| 207 | + } |
| 208 | + |
| 209 | + return { injectedCount }; |
| 210 | +} |
| 211 | + |
| 212 | +function logWarning(message: string): void { |
| 213 | + console.warn(`Warning: ${message}`); |
| 214 | +} |
0 commit comments