UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

938 lines (937 loc) • 47 kB
import { createHash } from "node:crypto"; import { types } from "node:util"; import { CREDENTIAL_MIN_CHARS, envNameView, envValueView, isSensitiveHeaderName, splitCamelCase } from "@sema-agent/primitives"; import { DEFAULT_INHERITED_ENV_VARS } from "@modelcontextprotocol/client/stdio"; import { deliverEngineNotice } from "./engine-notice.js"; import { optionKeys, receiveMembers } from "./own-property-receipt.js"; import { callerKey } from "./caller-text.js"; import { describeRejectedValue } from "./tool-search-setting.js"; import { authSchemeCredentials } from "./protocol-http-auth.js"; import { declarationSubject, isToolAxesSurface, toolAxesSurfaceList } from "./declaration-words.js"; import { principalNameOf } from "./principal-name.js"; import { ANONYMOUS_SCOPE } from "./isolation-scope.js"; const GIT_CONFIG_ENV_RE = /^GIT_CONFIG_(?:COUNT|PARAMETERS|(?:KEY|VALUE)_[0-9]+)$/; const PROXY_ENV_RE = /^(?:(?:https?|ftp|all|no)_proxy|npm_config_(?:https?_)?proxy|npm_config_noproxy|yarn_proxy|(?:yarn|global_agent|docker|claude_code)_(?:https?|no)_proxy|cloudsdk_proxy_[a-z]+|electron_get_use_proxy)$/i; function isExemptEnvName(name) { return GIT_CONFIG_ENV_RE.test(name) || PROXY_ENV_RE.test(name); } const ENV_NAMES = envNameView(); const ENV_VALUES = envValueView(); const OTEL_ENV_RE = /^(?:INPUT_)?OTEL_/i; const SEMA_NAMESPACE_SECRET_RE = ENV_NAMES.anySegmentUnder("SEMA_"); export function isNamespaceCredentialName(name) { return SEMA_NAMESPACE_SECRET_RE.test(name); } const BUNDLER_SETTINGS = ["BUILD", "LOCAL", "MIRROR", "PATH", "WITH", "WITHOUT", "CACHE", "DISABLE", "IGNORE", "ONLY"]; const BUNDLER_HOST = "(?:[A-Za-z0-9]+(?:___[A-Za-z0-9]+)*__)+[A-Za-z]{2}[A-Za-z]*"; const BUNDLER_CREDENTIAL_RE = new RegExp(`^(?:INPUT_)?BUNDLE_(?!(?:${BUNDLER_SETTINGS.join("|")})__(?!${BUNDLER_HOST}$))\\w*__`, "i"); const PUBLISHER_PREFIX_RE = /^(?:INPUT_|ORG_GRADLE_PROJECT_|POETRY_PYPI_TOKEN_|POETRY_HTTP_BASIC_|CARGO_REGISTRIES_|CONAN_LOGIN_USERNAME_|CONAN_PASSWORD_)/i; const PUBLISHER_LOGIN_PREFIX_RE = /^(?:INPUT_)?(?:POETRY_HTTP_BASIC_|CONAN_LOGIN_USERNAME_)/i; const USER_NAME_TAIL_RE = /USER(?:_?NAME)?_?[0-9]*$/i; function nameShapeHolds(name) { const words = name.replace(ENV_NAMES.nonCredentialPrefix, "").replace(/-/g, "_"); const split = splitCamelCase(words); const { credentialWord, connectionStringName } = ENV_NAMES; const shaped = credentialWord.test(words) || credentialWord.test(split) || connectionStringName.test(words) || connectionStringName.test(split) || BUNDLER_CREDENTIAL_RE.test(words); return shaped && !ENV_NAMES.nonSecretNameShape.test(name); } function nameIsCredentialShaped(name) { if (BUNDLER_CREDENTIAL_RE.test(name) || nameShapeHolds(name)) return true; const words = name.replace(/-/g, "_"); return PUBLISHER_PREFIX_RE.test(words) && (PUBLISHER_LOGIN_PREFIX_RE.test(words) || USER_NAME_TAIL_RE.test(words) || nameShapeHolds(words)); } const VALUE_SCAN_LIMIT = 8192; function looksLikeToken(user) { return ENV_VALUES.tokenHead.test(user) || (user.length >= 20 && /[0-9]/.test(user) && /[a-z]/i.test(user)); } const HOST_RE = /^(?:localhost|[a-z0-9_-]+(?:\.[a-z0-9_-]+)*\.(?=[a-z0-9-]*[a-z])[a-z0-9-]+|[a-z0-9_.-]+(?=:\d+(?:[/?#]|$))|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[[0-9a-f:.]+\])(?::\d+)?(?:[/?#]|$)/i; const HOSTLIKE_RE = /^(?:(?=[a-z0-9._-]*[a-z])[a-z0-9._-]+|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[[0-9a-f:.]+\])(?::\d+)?(?:[/?#]|$)/i; function isHostPortPathBeforeAt(before, after) { const hostPort = /^([a-z0-9_-]+(?:\.[a-z0-9_-]+)*):\d+([/?#].*)$/is.exec(before); if (!hostPort) return false; if (/[?#&]/.test(hostPort[2] ?? "")) return true; if (HOST_RE.test(after)) return false; if (before.endsWith("/")) return true; if (/^(?:v?\d|sha\d*:)/i.test(after)) return true; return !HOSTLIKE_RE.test(after); } function authorityCarriesCredential(rest) { const blank = rest.search(/\s/); const word = blank === -1 ? rest : rest.slice(0, blank); const at = word.lastIndexOf("@"); if (at === -1) return false; const userinfo = word.slice(0, at); if (isHostPortPathBeforeAt(userinfo, word.slice(at + 1))) return false; return userinfo.includes(":") || (!/[/?#]/.test(userinfo) && looksLikeToken(userinfo)); } const URL_USERINFO = ENV_VALUES.urlUserinfo; function carriesFrontlessUserinfo(text) { for (const m of text.matchAll(URL_USERINFO)) { if ((m[1] ?? "").endsWith("//")) continue; const userinfo = (m[2] ?? "").slice(0, -1); if (userinfo.includes(":") || (!/[?#]/.test(userinfo) && looksLikeToken(userinfo))) return true; } return false; } export function looksLikeCredentialValue(value) { const text = value.length > VALUE_SCAN_LIMIT ? value.slice(0, VALUE_SCAN_LIMIT) : value; for (let at = text.indexOf("://"); at !== -1; at = text.indexOf("://", at + 3)) { if (at > 0 && /[a-z0-9+.-]/i.test(text[at - 1] ?? "") && authorityCarriesCredential(text.slice(at + 3))) return true; } if (text.startsWith("//") && authorityCarriesCredential(text.slice(2))) return true; return carriesFrontlessUserinfo(text) || ENV_VALUES.forms.some((form) => form.re.test(text)); } const OWN_CREDENTIAL = "the engine's own service credential"; const SECRET_ENV_KIND_CONFIDENCE = { "exact-name": "high", "prefix-rule": "high", "value-rule": "high", "peer-held": "high", "own-credential": "high", "name-rule": "medium", "namespace-rule": "medium", }; function sensitiveNameKind(name) { if (ENV_NAMES.exactNames.has(name.toUpperCase().replace(/-/g, "_"))) return "exact-name"; if (OTEL_ENV_RE.test(name)) return "prefix-rule"; if (isNamespaceCredentialName(name)) return "namespace-rule"; return !ENV_NAMES.nonSecretExactNames.has(name.toUpperCase()) && nameIsCredentialShaped(name) ? "name-rule" : undefined; } export function isSensitiveName(key) { return sensitiveNameKind(key) !== undefined; } function classifySecretEnvEntry(name, value) { if (isExemptEnvName(name)) return undefined; const named = sensitiveNameKind(name); if (named !== undefined) return named; return value !== undefined && looksLikeCredentialValue(typeof value === "string" ? value : String(value)) ? "value-rule" : undefined; } export function entryLooksLikeCredential(name, value) { return classifySecretEnvEntry(name, value) !== undefined; } function judgeInheritedEntries(policy, entries) { const shaped = entries.map(([name, value]) => (policy === "all" ? (isNamespaceCredentialName(name) ? "namespace-rule" : undefined) : Array.isArray(policy) ? undefined : classifySecretEnvEntry(name, value))); const isOwn = ownCredentialJudge(); const peerHeld = policy === "all" || Array.isArray(policy) ? undefined : peerHeldOf(); return entries.map(([name, value], i) => shaped[i] ?? (isOwn !== undefined && isOwn(name, value) ? "own-credential" : peerHeld?.has(envNameKey(name)) === true ? "peer-held" : undefined)); } export function isSecretEnvKey(key, value) { return judgeInheritedEntries("scrub", [[key, value]])[0] !== undefined; } export function scrubSecretEnv(env, findings) { return withholdEntries(env, "scrub", findings); } function withholdEntries(env, policy, findings) { const entries = Object.keys(env).map((key) => [key, env[key]]); const kinds = judgeInheritedEntries(policy, entries); const kept = []; for (const [i, [key, value]] of entries.entries()) { const kind = kinds[i]; if (kind === undefined) kept.push([key, value]); else findings?.push({ key, kind, confidence: SECRET_ENV_KIND_CONFIDENCE[kind], source: "secret-env" }); } return Object.fromEntries(kept); } function envNameKey(name) { return envNameKeyOn(name, process.platform); } export function envNameKeyOn(name, platform) { return platform === "win32" ? name.toUpperCase() : name; } const UNPAIRED_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/; function isDeclarableVariableName(k) { return typeof k === "string" && k.length > 0 && !/[=\0\s]/.test(k) && !UNPAIRED_SURROGATE_RE.test(k); } function variableNameListProblem(label, value) { const bad = value.findIndex((k) => !isDeclarableVariableName(k)); if (bad === -1) return undefined; const k = value[bad]; const why = typeof k !== "string" ? typeof k : k === "" ? "an empty string" : `a name holding ${k.includes("=") ? "\"=\"" : k.includes("\0") ? "a NUL" : /\s/.test(k) ? "whitespace" : "an unpaired surrogate"}`; return `${label}[${bad}] is not a variable name (got ${why})`; } const WINDOWS_REQUIRED_ENV = Object.freeze(["HOMEDRIVE", "HOMEPATH", "LOGONSERVER", "PATH", "SYSTEMDRIVE", "SYSTEMROOT", "TEMP", "USERDOMAIN", "USERNAME", "USERPROFILE", "WINDIR"]); function runtimeSuppliedEnv() { return ["NODE_V8_COVERAGE", ...DEFAULT_INHERITED_ENV_VARS, ...(process.platform === "win32" ? WINDOWS_REQUIRED_ENV : [])]; } const valueDigest = (value) => createHash("sha256").update(value, "utf16le").digest("base64"); const indexHas = (index, value) => { const digests = index.get(value.length); return digests !== undefined && digests.has(valueDigest(value)); }; const indexAdd = (index, value) => { const digests = index.get(value.length); if (digests === undefined) index.set(value.length, new Set([valueDigest(value)])); else digests.add(valueDigest(value)); }; const WITHHELD_ENV = Symbol.for("sema.core.withheldEnvTable"); const NOTHING_NAMED = Object.freeze([]); const isWithheldEnvTable = (t) => typeof t === "object" && t !== null && Array.isArray(t.names) && t.declared instanceof Map && t.held instanceof Map; const withheldEnvOf = () => { const slot = Reflect.get(globalThis, WITHHELD_ENV); if (isWithheldEnvTable(slot)) return slot; const fresh = { names: NOTHING_NAMED, declared: new Map(), held: new Map() }; Reflect.set(globalThis, WITHHELD_ENV, fresh); return fresh; }; const PEER_HELD_ENV = Symbol.for("sema.core.peerHeldEnvNames"); const peerHeldOf = () => { const slot = Reflect.get(globalThis, PEER_HELD_ENV); if (slot instanceof Map) return slot; const fresh = new Map(); Reflect.set(globalThis, PEER_HELD_ENV, fresh); return fresh; }; const PEER_HELD_AUDIENCES = Symbol.for("sema.core.peerHeldEnvAudiences"); const peerHeldAudiencesOf = () => { const slot = Reflect.get(globalThis, PEER_HELD_AUDIENCES); if (typeof slot === "object" && slot !== null && slot.named instanceof Map) return slot; const fresh = { named: new Map() }; Reflect.set(globalThis, PEER_HELD_AUDIENCES, fresh); return fresh; }; const WITHHELD_ENV_TABLE_KEYS = optionKeys()({ names: 0, values: 0 }); const kindOf = (v) => (v === null ? "null" : Array.isArray(v) ? "an array" : typeof v); function listCopy(label, list, owner = "declareWithheldEnv") { if (types.isProxy(list)) throw new Error(`${owner}: ${label} must be a plain array, not a Proxy`); const copy = []; try { for (let i = 0, n = list.length; i < n; i++) copy[i] = list[i]; } catch { throw new Error(`${owner}: an element of ${label} threw while it was read — refused`); } return Object.freeze(copy); } const CANNOT_BE_WITHHELD = "which a child is handed from this process's environment whatever the spawn passes (by Node, the MCP stdio transport or Windows) — it cannot be withheld"; function runtimeSuppliedHolderOf(value, supplied = suppliedInProcess()) { return Object.keys(supplied).find((k) => supplied[k] === value); } const suppliedIn = (env) => namedIn(runtimeSuppliedEnv(), env); const suppliedInProcess = () => suppliedIn(process.env); const PLACEHOLDER_KEY_WORDS = new Set([...ENV_VALUES.flagWords, ...ENV_VALUES.placeholderWords]); export function isOneCharacterRepeated(text) { const first = text.codePointAt(0); if (first === undefined) return false; const unit = String.fromCodePoint(first); if (!/^\S$/u.test(unit) || text.length < 3 * unit.length || text.length % unit.length !== 0) return false; return text === unit.repeat(text.length / unit.length); } export function isBlankCredential(value) { return value.trim() === ""; } function notACredentialReason(value) { if (isBlankCredential(value)) return "white space only, which every blank variable equals"; const text = value.trim(); if (text.length < CREDENTIAL_MIN_CHARS) return `a string of fewer than ${CREDENTIAL_MIN_CHARS} characters, which names no secret`; if (PLACEHOLDER_KEY_WORDS.has(text.toLowerCase())) return "a flag or placeholder word, which names no secret"; if (isOneCharacterRepeated(text.replace(ENV_VALUES.tokenHead, ""))) return "one character repeated, which names no secret"; return undefined; } export function namesASecret(value) { return notACredentialReason(value) === undefined; } function notVariableValueReason(v) { if (typeof v !== "string") return kindOf(v); if (v === "") return "an empty string, which every variable set to nothing equals"; if (v.includes("\0") || UNPAIRED_SURROGATE_RE.test(v)) return `a value holding ${v.includes("\0") ? "a NUL" : "an unpaired surrogate"}, which no variable can hold`; return undefined; } function credentialValueProblem(v) { return notVariableValueReason(v) ?? notACredentialReason(v); } function firstRefusedValue(value) { for (const [index, v] of value.entries()) { const why = credentialValueProblem(v); if (why !== undefined) return { index, why }; } return undefined; } function readWithheldDeclaration(given, supplied, told) { const seen = { valueProblems: [] }; try { const kept = readWithheldDeclarationOrThrow(given, supplied, told, seen); return { ok: true, names: kept.names, values: kept.values, valueProblems: seen.valueProblems }; } catch (thrown) { return { ok: false, thrown, valueProblems: seen.valueProblems }; } } function refusalText(thrown) { try { if (types.isNativeError(thrown)) { const message = thrown.message; if (typeof message === "string") return message; } } catch { } return "declareWithheldEnv: the declaration could not be read — refused"; } export function credentialValueProblemOf(v) { try { return credentialValueProblem(v); } catch { return "a value that could not be read"; } } function readWithheldDeclarationOrThrow(given, suppliedNow, told, seen) { if (given === null || typeof given !== "object" || Array.isArray(given)) { throw new Error(`declareWithheldEnv: the declaration must be a table { names, values } (got ${Array.isArray(given) ? "an array — a names-only list is no longer a declaration: pass { names, values }" : kindOf(given)})`); } const received = receiveMembers(given, { subject: "declareWithheldEnv's table", unit: "member", moment: "at the declaration" }, WITHHELD_ENV_TABLE_KEYS, (_, [stray]) => new Error(`declareWithheldEnv: the table has a member ${callerKey(stray)} — it holds names and values only`)); const givenNames = received.names; if (!Array.isArray(givenNames)) throw new Error(`declareWithheldEnv: names must be an array of variable names (got ${kindOf(givenNames)})`); const names = listCopy("names", givenNames); const problem = variableNameListProblem("names", names); if (problem !== undefined) throw new Error(`declareWithheldEnv: ${problem}`); const supplied = new Set(runtimeSuppliedEnv().map(envNameKey)); const unwithholdable = names.findIndex((k) => supplied.has(envNameKey(k))); if (unwithholdable !== -1) throw new Error(`declareWithheldEnv: names[${unwithholdable}] is ${String(names[unwithholdable])}, ${CANNOT_BE_WITHHELD}`); const givenValues = received.values; if (!Array.isArray(givenValues)) throw new Error(`declareWithheldEnv: values must be an array of credential values (got ${kindOf(givenValues)})`); const values = listCopy("values", givenValues); seen.valueProblems = values.map(credentialValueProblemOf); const refused = firstRefusedValue(values); if (refused !== undefined) { const toldValue = values[refused.index]; if (typeof toldValue === "string" && notVariableValueReason(toldValue) === undefined && !isBlankCredential(toldValue)) told?.(toldValue); throw new Error(`declareWithheldEnv: values[${refused.index}] is not a credential value (got ${refused.why})`); } const layerSupplied = values.length > 0 ? suppliedNow() : {}; for (const [i, v] of values.entries()) { const holder = runtimeSuppliedHolderOf(v, layerSupplied); if (holder !== undefined) throw new Error(`declareWithheldEnv: values[${i}] is the value of ${holder}, ${CANNOT_BE_WITHHELD}`); } return { names: names, values: values }; } export function declareWithheldEnv(table) { const read = readWithheldDeclaration(table, suppliedInProcess, noteIntakeSaid); if (!read.ok) throw read.thrown; const declared = new Map(); for (const v of read.values) indexAdd(declared, v); Reflect.set(globalThis, WITHHELD_ENV, { names: read.names, declared, held: withheldEnvOf().held }); } export const WITHHELD_ENV_ANSWERS = Object.freeze(["name", "value", "none", "malformed_name"]); export function judgeWithheldEnv(candidate, env) { const impossibleVariableName = (name) => typeof name !== "string" || name.length === 0 || /[=\0]/.test(name) || UNPAIRED_SURROGATE_RE.test(name); let copy; const snapshot = () => (copy ??= Object.fromEntries(Object.entries(env).filter((entry) => typeof entry[1] === "string"))); const read = readWithheldDeclaration(candidate, () => suppliedIn(snapshot())); const answerNone = (name) => (impossibleVariableName(name) ? "malformed_name" : "none"); if (!read.ok) return Object.freeze({ refusal: refusalText(read.thrown), valueProblems: read.valueProblems, answer: answerNone }); const own = new Set(read.names.map(envNameKey)); const declared = new Map(); for (const v of read.values) indexAdd(declared, v); const held = new Map(); for (const [k, v] of Object.entries(snapshot())) if (v !== undefined && !held.has(envNameKey(k))) held.set(envNameKey(k), v); return Object.freeze({ valueProblems: read.valueProblems, answer: (name) => { if (impossibleVariableName(name)) return "malformed_name"; if (own.has(envNameKey(name))) return "name"; const exact = snapshot(); const value = Object.hasOwn(exact, name) ? exact[name] : held.get(envNameKey(name)); return value !== undefined && indexHas(declared, value) ? "value" : "none"; }, }); } export function holdPeerHeldNames(names, entry) { for (const name of names) { const admitted = admitPeerHeld(name, entry); if (admitted.taken && takingIn !== undefined) addEntry(takingIn, admitted.key, entry); } } function admitPeerHeld(name, entry) { const reason = peerHeldEntryRefusal(name); if (reason !== undefined) return { taken: false, reason }; const peerHeld = peerHeldOf(); const key = envNameKey(name); const isNew = !peerHeld.has(key); addEntry(peerHeld, key, entry); return { taken: true, key, isNew }; } export const PEER_HELD_ENV_NOT_TAKEN_REASONS = Object.freeze(["handed_every_child", "not_a_variable_name"]); function peerHeldEntryRefusal(name) { if (!isDeclarableVariableName(name)) return "not_a_variable_name"; return runtimeSuppliedEnv().some((k) => envNameKey(k) === envNameKey(name)) ? "handed_every_child" : undefined; } const PEER_HELD_DECLARATION_KEYS = optionKeys()({ names: 0, entry: 0, namedTo: 0 }); const PEER_HELD_ENTRY_KEYS = optionKeys()({ surface: 0, name: 0 }); const PEER_HELD_SCOPE_KEYS = optionKeys()({ isolationScope: 0 }); const DECLARE_PEER_HELD = "declarePeerHeldEnv"; function peerHeldMembers(given, subject, keys, shape) { if (given === null || typeof given !== "object" || Array.isArray(given)) throw new Error(`${DECLARE_PEER_HELD}: ${subject} must be ${shape} (got ${kindOf(given)})`); const received = receiveMembers(given, { subject: `${DECLARE_PEER_HELD}'s ${subject}`, unit: "member", moment: "at the declaration" }, keys, (_, [stray]) => new Error(`${DECLARE_PEER_HELD}: ${subject} has a member ${callerKey(stray)} — it holds ${keys.join(" and ")} only`)); return Object.fromEntries(keys.map((k) => [k, Object.hasOwn(received, k) ? received[k] : undefined])); } function readPeerHeldDeclaration(given) { const received = peerHeldMembers(given, "declaration", PEER_HELD_DECLARATION_KEYS, "a table { names, entry, namedTo? }"); const givenNames = received.names; if (!Array.isArray(givenNames)) throw new Error(`${DECLARE_PEER_HELD}: names must be an array of variable names (got ${kindOf(givenNames)})`); const names = listCopy("names", givenNames, DECLARE_PEER_HELD); const notString = names.findIndex((k) => typeof k !== "string"); if (notString !== -1) throw new Error(`${DECLARE_PEER_HELD}: names[${notString}] is not a string (got ${kindOf(names[notString])})`); const entry = peerHeldMembers(received.entry, "entry", PEER_HELD_ENTRY_KEYS, "a table { surface, name }"); const surface = entry.surface; if (!isToolAxesSurface(surface)) throw new Error(`${DECLARE_PEER_HELD}: entry.surface must be a surface a peer entry is declared on, ${toolAxesSurfaceList()} (got ${typeof surface === "string" ? "another string" : kindOf(surface)})`); const entryName = entry.name; if (typeof entryName !== "string") throw new Error(`${DECLARE_PEER_HELD}: entry.name must be a string — the entry's name as the host's configuration holds it, whatever it holds (got ${kindOf(entryName)})`); const namedTo = received.namedTo; let audience; if (namedTo === "every_leg") audience = "every_leg"; else if (namedTo !== undefined) { if (typeof namedTo !== "object" || namedTo === null) throw new Error(`${DECLARE_PEER_HELD}: namedTo must be "every_leg" or { isolationScope } (got ${typeof namedTo === "string" ? "another string" : kindOf(namedTo)})`); const scope = principalNameOf(peerHeldMembers(namedTo, "namedTo", PEER_HELD_SCOPE_KEYS, '"every_leg" or { isolationScope }').isolationScope); if (scope === undefined) throw new Error(`${DECLARE_PEER_HELD}: namedTo.isolationScope is not a name (the rule TaskSpec.isolationScope is judged by)`); audience = { isolationScope: scope }; } return { names: names, entry: declarationSubject(surface, entryName), audience }; } export function declarePeerHeldEnv(declaration) { const read = readPeerHeldDeclaration(declaration); const notTaken = []; const audiences = peerHeldAudiencesOf(); const heldLate = []; for (const name of read.names) { const admitted = admitPeerHeld(name, read.entry); if (!admitted.taken) { notTaken.push({ name, reason: admitted.reason }); continue; } const { key, isNew } = admitted; if (isNew && audiences.childSpawned === true && Object.hasOwn(process.env, spellingIn(process.env, name)) && !heldLate.includes(name)) heldLate.push(name); if (read.audience !== undefined) { let entries = audiences.named.get(key); if (entries === undefined) audiences.named.set(key, (entries = new Map())); let to = entries.get(read.entry); if (to === undefined) entries.set(read.entry, (to = { every: false, scopes: new Set() })); if (read.audience === "every_leg") to.every = true; else to.scopes.add(read.audience.isolationScope); } } return Object.freeze({ notTaken: Object.freeze(notTaken.map((n) => Object.freeze(n))), heldLate: Object.freeze(heldLate) }); } function addEntry(table, key, entry) { const entries = table.get(key); if (entries === undefined) table.set(key, new Set([entry])); else entries.add(entry); } let takingIn; export function peerEntriesTakenIn(receive) { const outer = takingIn; const entries = (takingIn = new Map()); try { return { value: receive(), entries }; } finally { takingIn = outer; } } export function holdOwnCredentialValues(values, onNotice) { const given = [...values].filter((v) => typeof v === "string" && !isBlankCredential(v)); const notTaken = new Map(); const taken = given.filter((v) => { const why = notACredentialReason(v); if (why !== undefined) notTaken.set(v, why); return why === undefined; }); try { for (const v of taken) { const holder = runtimeSuppliedHolderOf(v); if (holder !== undefined) throw Object.assign(new Error(`a credential the engine was handed is the value of ${holder}, ${CANNOT_BE_WITHHELD}; the credential is refused`), { code: "config.invalid_argument" }); } const { held } = withheldEnvOf(); for (const v of taken) indexAdd(held, v); } finally { for (const [v, why] of notTaken) sayNotTaken(v, why, onNotice); } } const SCHEMED_HEADER_RE = /^(?:proxy-)?authorization$/i; export function isCredentialHeaderName(name) { return isSensitiveHeaderName(name); } export function isSchemedCredentialHeader(name) { return SCHEMED_HEADER_RE.test(name); } export function credentialHeaderValues(headers) { const out = []; for (const [name, value] of Object.entries(headers ?? {})) { if (typeof value !== "string" || !(isCredentialHeaderName(name) || looksLikeCredentialValue(value))) continue; const credentials = authSchemeCredentials(value); if (credentials !== undefined && isSchemedCredentialHeader(name) && notACredentialReason(credentials) !== undefined) { out.push(credentials); continue; } out.push(value); if (credentials !== undefined) out.push(credentials); } return out; } const intakeSaid = new Set(); function noteIntakeSaid(value) { const key = valueDigest(value.trim()); if (intakeSaid.has(key)) return false; intakeSaid.add(key); return true; } function sayNotTaken(value, why, onNotice) { if (!noteIntakeSaid(value)) return; deliverEngineNotice(onNotice, { code: "config.credential_not_withheld", message: `a credential the engine was handed is ${why} — it is used as given, but a variable holding the same string is not withheld from a spawned child (said once per value; the value is not repeated)`, detail: { reason: why }, }); } export function __resetWithheldEnv() { Reflect.set(globalThis, WITHHELD_ENV, { names: NOTHING_NAMED, declared: new Map(), held: new Map() }); Reflect.set(globalThis, PEER_HELD_ENV, new Map()); Reflect.set(globalThis, PEER_HELD_AUDIENCES, { named: new Map() }); intakeSaid.clear(); } function ownCredentialJudge() { const table = withheldEnvOf(); if (table.names.length === 0 && table.declared.size === 0 && table.held.size === 0) return undefined; const own = new Set(table.names.map(envNameKey)); return (key, value) => own.has(envNameKey(key)) || (typeof value === "string" && (indexHas(table.declared, value) || indexHas(table.held, value))); } function policyShapeProblem(value) { if (value === undefined || value === "all" || value === "scrub") return undefined; if (Array.isArray(value)) return variableNameListProblem("inheritEnv", value); return `inheritEnv must be "scrub", "all" or a list of variable names (got ${describeRejectedValue(value)})`; } function inheritedOver(policy, settings, findings) { const problem = inheritEnvPolicyProblem(policy); if (problem !== undefined) throw new Error(problem); const settingsNames = new Set(); let base = process.env; if (settings !== undefined) { const layered = new Map(); for (const entry of Object.entries(process.env)) layered.set(envNameKey(entry[0]), entry); layInto(layered, settings); for (const [name, value] of settings) if (value === undefined) settingsNames.delete(envNameKey(name)); else settingsNames.add(envNameKey(name)); base = Object.fromEntries([...layered.values()].filter((entry) => entry[1] !== undefined)); } const found = []; const inherited = policyArm(policy, base, found); for (const f of found) findings?.push(settingsNames.has(envNameKey(f.key)) ? { ...f, layer: "settingsEnv" } : f); return inherited; } export function inheritedHostEnv(policy, findings) { return inheritedOver(policy, undefined, findings); } export function composedUnderScrub(policy) { return policy !== "all" && !Array.isArray(policy); } export function recordChildSpawned(underScrub) { if (!underScrub) return; try { peerHeldAudiencesOf().childSpawned = true; } catch { } } const NOTE_CHILD_SPAWNED = "noteChildSpawned"; function unpolicyKind(value) { if (value === null) return "null"; if (typeof value === "string") return `a string of ${value.length} character${value.length === 1 ? "" : "s"} that is no policy word`; return typeof value === "object" ? "an object" : `a ${typeof value}`; } export function noteChildSpawned(policy) { const given = policy; if (types.isProxy(given)) throw new Error(`${NOTE_CHILD_SPAWNED}: inheritEnv must be "scrub", "all" or a plain array of variable names, not a Proxy`); const problem = Array.isArray(given) ? variableNameListProblem("inheritEnv", listCopy("inheritEnv", given, NOTE_CHILD_SPAWNED)) : given === undefined || given === "all" || given === "scrub" ? undefined : `inheritEnv must be "scrub", "all" or a list of variable names (got ${unpolicyKind(given)})`; if (problem !== undefined) throw new Error(`${NOTE_CHILD_SPAWNED}: ${problem}`); recordChildSpawned(composedUnderScrub(policy)); } const HOST_CHILD_INHERITANCE_KEYS = optionKeys()({ policy: 0, settingsEnv: 0 }); function layInto(entries, layer) { for (const [name, value] of layer) entries.set(envNameKey(name), [entries.get(envNameKey(name))?.[0] ?? name, value]); } const unkeptCharacter = (text) => (text.includes("\0") ? "a NUL" : UNPAIRED_SURROGATE_RE.test(text) ? "an unpaired surrogate" : undefined); export function readEnvLayer(layer, label) { try { if (typeof layer !== "object" || layer === null || Array.isArray(layer)) return `${label} must be an object of variable names to strings (got ${kindOf(layer)})`; const entries = Object.entries(layer); for (const [name, value] of entries) { const unkept = name.includes("=") ? "\"=\"" : unkeptCharacter(name); const badName = name === "" ? "an empty string" : unkept && `one holding ${unkept}`; if (badName) return `${label} holds a key that is not a variable name (${badName})`; if (value !== undefined && typeof value !== "string") return `${label}: ${name} must be a string (got ${kindOf(value)})`; const badValue = value === undefined ? undefined : unkeptCharacter(value); if (badValue !== undefined) return `${label}: the value of ${name} holds ${badValue}`; } return entries; } catch { return `${label} threw while it was read — refused`; } } function readInheritance(inherit) { let isPolicy; try { isPolicy = typeof inherit !== "object" || inherit === null || Array.isArray(inherit); } catch { return "inheritEnv threw while it was read — refused"; } if (isPolicy) return { policy: inherit, settings: undefined }; let table; try { table = receiveMembers(inherit, { subject: "the inheritance table", unit: "member", moment: "at the composition" }, HOST_CHILD_INHERITANCE_KEYS); } catch (e) { return e instanceof Error ? e.message : "the inheritance table could not be read — refused"; } return { policy: table.policy, settings: table.settingsEnv === undefined ? undefined : readEnvLayer(table.settingsEnv, "settingsEnv") }; } function composeHostChildEnv(inherit, grants) { const read = readInheritance(inherit); if (typeof read === "string") return read; let problem; try { problem = inheritEnvPolicyProblem(read.policy); } catch { problem = "inheritEnv threw while it was read — refused"; } if (problem !== undefined) return problem; if (typeof read.settings === "string") return read.settings; const findings = []; const entries = new Map(); for (const entry of Object.entries(inheritedOver(read.policy, read.settings, findings))) entries.set(envNameKey(entry[0]), entry); for (let i = 0; i < grants.length; i++) { if (grants[i] === undefined) continue; const layer = readEnvLayer(grants[i], `env grant ${i + 1}`); if (typeof layer === "string") return layer; layInto(entries, layer); } const env = Object.fromEntries(entries.values()); return { env, withheld: findings.filter((f) => entries.get(envNameKey(f.key))?.[1] === undefined) }; } export function hostChildEnvProblem(inherit, ...grants) { const composed = composeHostChildEnv(inherit, grants); return typeof composed === "string" ? composed : undefined; } export function hostChildEnv(inherit, ...grants) { const composed = composeHostChildEnv(inherit, grants); if (typeof composed === "string") throw new Error(composed); return composed; } function policyArm(policy, base, findings) { if (composedUnderScrub(policy)) return scrubSecretEnv(base, findings); if (policy === "all") return withholdEntries(base, policy, findings); return withholdEntries(namedIn(policy, base), policy, findings); } function namedIn(names, base) { const arm = []; for (const k of names) { const name = spellingIn(base, k); const value = Object.hasOwn(base, name) ? base[name] : undefined; if (value !== undefined) arm.push([k, value]); } return Object.fromEntries(arm); } function spellingIn(base, name) { if (process.platform !== "win32" || Object.hasOwn(base, name)) return name; return Object.keys(base).find((k) => envNameKey(k) === envNameKey(name)) ?? name; } export function inheritEnvPolicyProblem(value) { return policyShapeProblem(value) ?? declaredInheritEntry(value)?.refusal; } export function declaredInheritEntry(value) { const { names } = withheldEnvOf(); if (!Array.isArray(value) || names.length === 0) return undefined; const list = value; const own = new Set(names.map(envNameKey)); const index = list.findIndex((k) => own.has(envNameKey(k))); const name = list[index]; if (name === undefined) return undefined; return { index, name, refusal: `inheritEnv[${index}] names ${name}, which this process has declared (declareWithheldEnv) to be ${OWN_CREDENTIAL}, so a child cannot inherit it (a configuration error: no retry succeeds until the policy or the declaration changes)` }; } let secretEnvScrubNoticeAnnounced = false; export function __resetSecretEnvScrubNoticeAnnouncement() { secretEnvScrubNoticeAnnounced = false; } export function withheldEnvNames(findings) { const names = [...new Set(findings.map((f) => f.key))]; const isOwn = ownCredentialJudge(); const ownCredentials = isOwn === undefined ? [] : names.filter((k) => isOwn(k, process.env[k])); return { names, ownCredentials }; } export function announceSecretEnvScrub(onNotice, findings) { if (findings.length === 0 || secretEnvScrubNoticeAnnounced) return; secretEnvScrubNoticeAnnounced = true; const { names, ownCredentials } = withheldEnvNames(findings); const own = ownCredentials.length > 0 ? `; ${ownCredentials.length} of them ${OWN_CREDENTIAL}(s) (${ownCredentials.join(", ")})` : ""; deliverEngineNotice(onNotice, { code: "config.secret_env_scrubbed", message: `secret_env_scrubbed: ${names.length} env key(s) withheld from a spawned child's environment (${names.join(", ")})${own} — once per process; wire onNotice for the structured form`, detail: { names, ...(ownCredentials.length > 0 ? { ownCredentials } : {}) }, }); } export const WITHHELD_ENV_REMEDY_KINDS = Object.freeze(["inherit_env", "execution_environment"]); export const INHERIT_ENV_FORMS = Object.freeze(["scrub", "all", "list"]); const INHERIT_ENV_FORM_SET = new Set(INHERIT_ENV_FORMS); export function readInheritEnvForms(value) { if (value === undefined) return { ok: true, forms: undefined }; if (types.isProxy(value)) return { ok: false, valueType: "Proxy" }; if (!Array.isArray(value)) return { ok: false, valueType: value === null ? "null" : typeof value }; const len = value.length; const copied = []; const seen = new Set(); for (let i = 0; i < len; i++) { if (!Object.hasOwn(value, i)) return { ok: false, valueType: "sparse array" }; let item; try { item = Reflect.get(value, i); } catch { return { ok: false, valueType: "unreadable array element" }; } if (typeof item !== "string" || !INHERIT_ENV_FORM_SET.has(item)) return { ok: false, valueType: "array holding a non-form" }; const form = item; if (seen.has(form)) return { ok: false, valueType: "array holding a duplicate form" }; seen.add(form); copied.push(form); } return { ok: true, forms: Object.freeze(copied) }; } function othersExitClause(needWord, one, hasList, hasAll) { if (hasList && hasAll) return `if a command needs ${needWord}, name it among the variables the run inherits, or let the run inherit all of them`; if (hasAll) return `if a command needs ${needWord}, let the run inherit all of them`; if (hasList) return `if a command needs ${needWord}, name it among the variables the run inherits`; return `this host does not accept an environment-inheritance form that hands ${one ? "it" : "them"} on`; } function slotsExitClause(needWord, one, hasList, hasAll) { const explicit = "have the host hand it to the shell explicitly, through the shell's own environment or the environment of a single execution"; const lead = hasList ? `name it among the variables the run inherits, or ${explicit}` : explicit; const allNote = hasAll ? ` — letting the run inherit everything does not hand ${one ? "it" : "them"} on` : ""; return `if a command needs ${needWord}, ${lead}${allNote}`; } function peerHeldExitClause(one, hasList, hasAll) { const explicit = "have the host hand it to the shell explicitly, through the shell's own environment or the environment of a single execution"; const lead = hasList ? `name it among the variables the run inherits, or ${explicit}` : explicit; if (hasAll && hasList) { return `if a command needs ${one ? "it" : "one of them"}, ${lead}; letting the run inherit all of them hands it on as well, but once the engine has started connecting to that peer neither that nor a list is sure to, since a credential value the engine took in for it is held back whatever the run inherits`; } if (hasAll) { return `if a command needs ${one ? "it" : "one of them"}, ${lead}; letting the run inherit all of them hands it on as well, but once the engine has started connecting to that peer that is not sure to, since a credential value the engine took in for it is held back whatever the run inherits`; } if (hasList) { return `if a command needs ${one ? "it" : "one of them"}, ${lead}; once the engine has started connecting to that peer a list is not sure to, since a credential value the engine took in for it is held back whatever the run inherits`; } return `if a command needs ${one ? "it" : "one of them"}, ${lead}`; } function peerHeldEntries(peers, mine, isolationScope) { const held = peerHeldOf(); const audiences = peerHeldAudiencesOf().named; const out = new Map(); for (const name of peers) { const key = envNameKey(name); const own = new Set(mine?.get(key) ?? []); for (const [entry, to] of audiences.get(key) ?? []) if (to.every || (isolationScope !== undefined && to.scopes.has(isolationScope))) own.add(entry); if (own.size > 0) out.set(name, [...own]); else if (held.has(key)) out.set(name, "another"); } return out; } function peerHeldHalf(peers, entries, hasList, hasAll) { const entriesOf = (name) => { const e = entries.get(name); return e === undefined ? undefined : e === "another" ? "another entry in this process" : e.join(", "); }; const one = peers.length === 1; const named = one ? entriesOf(peers[0]) : peers.flatMap((k) => (entriesOf(k) === undefined ? [] : [`${k}: ${entriesOf(k)}`])).join("; "); return (`${peers.join(", ")} — held back because the credential reference of an MCP server or A2A peer names ${one ? "it" : "each of them"}${named ? ` (${named})` : ""}: ` + `the engine holds ${one ? "it" : "them"} for that peer (${peerHeldExitClause(one, hasList, hasAll)})`); } function noticeReaderScope(delegated, isolationScope, deliveredScope) { if (!delegated) return isolationScope; return deliveredScope !== ANONYMOUS_SCOPE && isolationScope !== undefined && isolationScope === deliveredScope ? isolationScope : undefined; } export function withheldEnvUserNotice(...args) { return mintWithheldEnvUserNotice(...args)?.notice; } export function mintWithheldEnvUserNotice(withheld, at, mine, isolationScope, deliveredScope, inheritEnvForms) { const parsedForms = readInheritEnvForms(inheritEnvForms); if (!parsedForms.ok) throw new TypeError(`withheldEnvUserNotice: invalid inheritEnvForms (${parsedForms.valueType})`); const hasList = parsedForms.forms === undefined || parsedForms.forms.includes("list"); const hasAll = parsedForms.forms === undefined || parsedForms.forms.includes("all"); const route = { sessionId: at.sessionId, ...(at.sourceSessionId !== undefined ? { sourceSessionId: at.sourceSessionId } : {}), ...(at.agentId !== undefined ? { agentId: at.agentId } : {}), ...(at.runId !== undefined ? { runId: at.runId } : {}) }; const delegated = at.sourceSessionId !== undefined; const readerScope = noticeReaderScope(delegated, isolationScope, deliveredScope); const shell = delegated ? "the tool shell of a delegated agent in this session" : "the tool shell in this session"; const subject = delegated ? "A delegated agent's tool shell in this session" : "The tool shell in this session"; const leg = at.sourceSessionId ?? null; if (withheld === "unknown") { const notice = { code: "inherit_env.names_withheld", message: `The engine could not tell which of its environment variables ${shell} can see: the execution environment does not say. Nothing is needed from you unless a command finds a variable unset — then set that variable in the execution environment itself.`, detail: { state: "unknown", remedies: [{ kind: "execution_environment" }], ...route }, }; return { notice, fact: JSON.stringify({ state: "unknown", leg }) }; } const { names, ownCredentials } = withheldEnvNames(withheld); if (names.length === 0) return undefined; const scrubbed = names.filter((k) => !ownCredentials.includes(k)); const slotNames = new Set(withheld.filter((f) => f.kind === "namespace-rule").map((f) => f.key)); const peerNames = new Set(withheld.filter((f) => f.kind === "peer-held").map((f) => f.key)); const slots = scrubbed.filter((k) => slotNames.has(k)); const peers = scrubbed.filter((k) => peerNames.has(k) && !slotNames.has(k)); const others = scrubbed.filter((k) => !slotNames.has(k) && !peerNames.has(k)); const needs = (list) => (list.length === 1 ? "it" : "one of them"); const peerEntries = peerHeldEntries(peers, mine, readerScope); const halves = [ ...(others.length > 0 ? [`${others.join(", ")} — held back because ${others.length === 1 ? "it looks like a credential" : "they look like credentials"} (${othersExitClause(needs(others), others.length === 1, hasList, hasAll)})`] : []), ...(peers.length > 0 ? [peerHeldHalf(peers, peerEntries, hasList, hasAll)] : []), ...(slots.length > 0 ? [`${slots.join(", ")} — held back because ${slots.length === 1 ? "it is named" : "they are named"} like the engine's own credential slots (${slotsExitClause(needs(slots), slots.length === 1, hasList, hasAll)})`] : []), ...(ownCredentials.length > 0 ? [`${ownCredentials.join(", ")} — ${OWN_CREDENTIAL}(s), never handed on, whatever the run's environment inheritance says`] : []), ]; const notice = { code: "inherit_env.names_withheld", message: `${subject} does not see ${names.length} of the engine's environment variable(s). This is a protection: nothing is needed from you${scrubbed.length > 0 ? " unless a command needs one of them" : ""}. ${halves.join("; ")}. Values are never shown.`, detail: { state: "withheld", names, ...(ownCredentials.length > 0 ? { ownCredentials } : {}), ...(scrubbed.length > 0 ? { remedies: [{ kind: "inherit_env" }] } : {}), ...route }, }; const sorted = (xs) => [...xs].sort(); const peerFacts = sorted(peers).map((k) => { const e = peerEntries.get(k); return [k, e === undefined ? null : e === "another" ? e : sorted(e)]; }); const ways = scrubbed.length > 0 ? { ways: { list: hasList, all: hasAll } } : {}; return { notice, fact: JSON.stringify({ state: "withheld", leg, look: sorted(others), peer: peerFacts, slot: sorted(slots), own: sorted(ownCredentials), ...ways }) }; }