fix(cloud): read the cloud session env without sync fs (watched in-memory copy)

This commit is contained in:
Neil
2026-11-10 17:03:49 -08:00
parent 9942c75b86
commit beca015919
4 changed files with 110 additions and 45 deletions
@@ -6,7 +6,10 @@ import { dropInheritedOrcaFishHistory } from '../../pty/history/fish-history-ses
import { removeAppImageRuntimeEnv } from '../../pty/shell-startup/appimage-terminal-env'
import { removeChromiumDisabledSessionBus } from '../../pty/shell-startup/chromium-session-bus-env'
import { stripInheritedBuildModeEnv } from '../../pty/shell-startup/build-mode-env'
import { withCloudSessionEnv } from '../../runtime/secrets/cloud-session-env'
import {
applyCloudSessionEnv,
cachedCloudSessionEnv
} from '../../runtime/secrets/cloud-session-env'
import { stripPiProcessOwnerEnv } from '../../pty/shell-startup/pi-process-owner-env'
import { dropIncoherentCondaActivationEnv } from '../../pty/shell-startup/conda-activation-env'
import { stripLegacyTerminalShimEnv } from '../../pty/shell-startup/legacy-terminal-shim-dir'
@@ -184,7 +187,10 @@ export function createDaemonPtyEnvironment(opts: PtySubprocessOptions): Record<s
const env: Record<string, string> = {
// Orca Cloud: the daemon's env is from orcad's start; lay the live session env over it, under the
// launch's own values and before its requested deletions (an account strip must win).
...mergeGitConfigEnvProtocol(withCloudSessionEnv(inheritedEnv), opts.env),
...mergeGitConfigEnvProtocol(
applyCloudSessionEnv(inheritedEnv, cachedCloudSessionEnv(inheritedEnv)),
opts.env
),
TERM: 'xterm-256color',
COLORTERM: 'truecolor',
TERM_PROGRAM: 'Orca',
@@ -1,5 +1,5 @@
import { agentModelCatalogStore } from '../../../native-chat/agent-model-catalog/agent-model-catalog-store'
import { withCloudSessionEnv } from '../../secrets/cloud-session-env'
import { applyCloudSessionEnv, liveCloudSessionEnv } from '../../secrets/cloud-session-env'
import { resolveLoginShellEnvironment } from '../../../startup/login-shell-environment'
import { refreshAtRestCommandContext } from '../../../native-chat/agent-session-wire/options/at-rest-command-context'
import {
@@ -206,14 +206,14 @@ export function createStructuredAgentEnvironmentResolvers(
}
// Orca Cloud: the shell capture is from orcad's start; the live session env (secrets, account
// placeholders) is reread for every launch.
const resolveBase = async (cachedOnly = false): Promise<Record<string, string>> =>
withCloudSessionEnv(
structuredAgentBaseEnvironment({
shellEnv: await shellEnvironment(cachedOnly),
policy: sources.resolveShellEnvironmentPolicy?.() ?? nativeChatShellEnvironmentPolicy(null),
processEnv: sources.processEnvironment
})
)
const resolveBase = async (cachedOnly = false): Promise<Record<string, string>> => {
const base = structuredAgentBaseEnvironment({
shellEnv: await shellEnvironment(cachedOnly),
policy: sources.resolveShellEnvironmentPolicy?.() ?? nativeChatShellEnvironmentPolicy(null),
processEnv: sources.processEnvironment
})
return applyCloudSessionEnv(base, await liveCloudSessionEnv(base))
}
return {
refreshAfterMissingProgram: injected
? async () => {}
@@ -4,7 +4,7 @@
* Empty remote selectors to mask the parent env; explicit flags still work, and login profiles can re-export selectors.
* Omit pane identity: hooks and mobile status assume a live PTY leaf. Resolve worker identity at every spawn, including recovery and clear. */
import { cloudSessionEnv } from '../../secrets/cloud-session-env'
import { cachedCloudSessionEnv } from '../../secrets/cloud-session-env'
import { getAppEnvironment, hasAppEnvironment } from '../../../../shared/app-environment'
import {
ORCA_AGENT_SESSION_ID_ENV,
@@ -43,7 +43,9 @@ export function sealStructuredSessionChild(input: {
const named = new Set([...Object.keys(identity.commandEnv), ORCA_AGENT_SESSION_SPAWN_TOKEN_ENV])
// Orca Cloud: orcad's own env still holds values the live session env has since dropped (a revoked
// account placeholder, a deleted secret); the child must not inherit them.
const dropped = (cloudSessionEnv(process.env)?.unset ?? []).filter((key) => !(key in paired))
const dropped = (cachedCloudSessionEnv(process.env)?.unset ?? []).filter(
(key) => !(key in paired)
)
return {
env: { ...identity.env, [ORCA_AGENT_SESSION_SPAWN_TOKEN_ENV]: input.spawnToken },
envToDelete: [...input.inheritedEnvToDelete, ...dropped].filter((key) => !named.has(key)),
+89 -32
View File
@@ -3,7 +3,12 @@
// profile hook, but orcad's own process env and its cached login-shell capture are frozen at start, so
// anything orcad spawns directly (chat agents, PTYs launched without a shell) must lay the current file
// over the env it built. Same rules as the hook (image/vm/orca-session-env.sh).
import { readFileSync } from 'node:fs'
//
// The file is kept in memory and reread when its directory changes (a watch, no polling), so spawn paths
// read it without blocking on disk.
import { watch, type FSWatcher } from 'node:fs'
import { readFile } from 'node:fs/promises'
import { dirname } from 'node:path'
import { isCloudWorkspaceOrcad, sessionEnvFilePath } from './session-env-names'
const NAME = /^[A-Z_][A-Z0-9_]*$/
@@ -25,28 +30,12 @@ export type CloudSessionEnv = {
unset: string[]
}
export type CloudSessionEnvOptions = {
processEnv?: NodeJS.ProcessEnv
uid?: number
read?: (path: string) => string
}
/** Null outside a cloud workspace's orcad, or before the file exists (then nothing changes, as in the hook). */
export function cloudSessionEnv(
/** The overlay for `base` from the file's text; null text (no file) changes nothing, as in the hook. */
export function cloudSessionEnvFromText(
base: Readonly<Record<string, string | undefined>>,
options: CloudSessionEnvOptions = {}
text: string | null
): CloudSessionEnv | null {
if (!isCloudWorkspaceOrcad(options.processEnv ?? process.env)) {
return null
}
const uid = options.uid ?? process.getuid?.()
if (uid === undefined) {
return null
}
let text: string
try {
text = (options.read ?? ((path: string) => readFileSync(path, 'utf8')))(sessionEnvFilePath(uid))
} catch {
if (text === null) {
return null
}
const set: Record<string, string> = {}
@@ -65,26 +54,94 @@ export function cloudSessionEnv(
return { set: { ...set, ORCA_SESSION_ENV_NAMES: names.join(' ') }, unset }
}
/** `env` with the current cloud session env laid over it and dropped names removed. */
export function withCloudSessionEnv(
/** `env` with `overlay` laid over it and dropped names removed. */
export function applyCloudSessionEnv(
env: Record<string, string>,
options?: CloudSessionEnvOptions
overlay: CloudSessionEnv | null
): Record<string, string>
export function withCloudSessionEnv(
export function applyCloudSessionEnv(
env: NodeJS.ProcessEnv,
options?: CloudSessionEnvOptions
overlay: CloudSessionEnv | null
): NodeJS.ProcessEnv
export function withCloudSessionEnv(
export function applyCloudSessionEnv(
env: Record<string, string | undefined>,
options: CloudSessionEnvOptions = {}
overlay: CloudSessionEnv | null
): Record<string, string | undefined> {
const current = cloudSessionEnv(env, options)
if (!current) {
if (!overlay) {
return env
}
const next: Record<string, string | undefined> = { ...env }
for (const name of current.unset) {
for (const name of overlay.unset) {
delete next[name]
}
return Object.assign(next, current.set)
return Object.assign(next, overlay.set)
}
type Cache = { path: string; text: string | null; loaded: Promise<void>; watcher: FSWatcher | null }
let cache: Cache | null = null
async function reload(into: Cache): Promise<void> {
try {
into.text = await readFile(into.path, 'utf8')
} catch {
into.text = null
}
}
/** Starts the in-memory copy once per process; null outside a cloud workspace's orcad. */
function cloudCache(): Cache | null {
if (cache) {
return cache
}
const uid = process.getuid?.()
if (!isCloudWorkspaceOrcad() || uid === undefined) {
return null
}
const created: Cache = {
path: sessionEnvFilePath(uid),
text: null,
loaded: Promise.resolve(),
watcher: null
}
created.loaded = reload(created)
try {
// orca-sandbox-env replaces the file by rename, so watch the directory.
created.watcher = watch(dirname(created.path), { persistent: false }, () => {
created.loaded = reload(created)
})
created.watcher.on('error', () => {})
} catch {
// No directory yet: async reads go to disk each time instead.
created.watcher = null
}
cache = created
return created
}
/** The live overlay for `base`, read fresh when unwatched (async paths: structured agent launches). */
export async function liveCloudSessionEnv(
base: Readonly<Record<string, string | undefined>>
): Promise<CloudSessionEnv | null> {
const current = cloudCache()
if (!current) {
return null
}
if (!current.watcher) {
current.loaded = reload(current)
}
await current.loaded
return cloudSessionEnvFromText(base, current.text)
}
/** The last-read overlay for `base`, without waiting (sync spawn paths). */
export function cachedCloudSessionEnv(
base: Readonly<Record<string, string | undefined>>
): CloudSessionEnv | null {
const current = cloudCache()
return current ? cloudSessionEnvFromText(base, current.text) : null
}
export function resetCloudSessionEnvCacheForTests(): void {
cache?.watcher?.close()
cache = null
}