Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions packages/coding-agent/src/core/agent-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,7 @@ export class AgentSession {

// Extension system
private _extensionRunner!: ExtensionRunner;
private _execEnvProvider?: () => Record<string, string> | undefined;
private _turnIndex = 0;

private _resourceLoader: ResourceLoader;
Expand Down Expand Up @@ -3193,6 +3194,17 @@ export class AgentSession {
return this.settingsManager.getCompactionEnabled();
}

/**
* Set the provider for extra env vars merged over process.env in extension
* pi.exec() subprocesses. The function is read at exec time, so a host (e.g.
* the daemon) can update the underlying value per attach without rebinding.
*/
setExecEnvProvider(provider: (() => Record<string, string> | undefined) | undefined): void {
Comment thread
macroscopeapp[bot] marked this conversation as resolved.
Resolved
this._execEnvProvider = provider;
const extensions = this._resourceLoader.getExtensions();
extensions.runtime.getExecEnv = provider;
}

async bindExtensions(bindings: ExtensionBindings): Promise<void> {
if (bindings.uiContext !== undefined) {
this._extensionUIContext = bindings.uiContext;
Expand Down Expand Up @@ -3541,6 +3553,12 @@ export class AgentSession {
extensionsResult.runtime.flagValues.set(name, value);
}
}
// Re-apply on (re)build so the provider survives /reload. Guarded: the
// runtime object can be shared across sessions from one ResourceLoader
// (RLM children), so a provider-less session must not wipe the owner's.
if (this._execEnvProvider) {
extensionsResult.runtime.getExecEnv = this._execEnvProvider;
}

this._extensionRunner = new ExtensionRunner(
extensionsResult.extensions,
Expand Down
5 changes: 5 additions & 0 deletions packages/coding-agent/src/core/exec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ export interface ExecOptions {
timeout?: number;
/** Working directory */
cwd?: string;
/** Extra env vars merged over the parent process env for this command. */
env?: Record<string, string>;
}

/**
Expand Down Expand Up @@ -42,6 +44,9 @@ export async function execCommand(
cwd,
shell: false,
stdio: ["ignore", "pipe", "pipe"],
// Merge per-call env over the parent env so callers can scope vars
// (e.g. herdr pane identity) without mutating the shared process.env.
env: options?.env ? { ...process.env, ...options.env } : undefined,
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
});

let stdout = "";
Expand Down
6 changes: 5 additions & 1 deletion packages/coding-agent/src/core/extensions/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,11 @@ function createExtensionAPI(

exec(command: string, args: string[], options?: ExecOptions) {
runtime.assertActive();
return execCommand(command, args, options?.cwd ?? cwd, options);
// Read the host-supplied env at call time so per-session vars (e.g.
// herdr pane identity) are current, then let an explicit options.env win.
const sessionEnv = runtime.getExecEnv?.();
const env = sessionEnv || options?.env ? { ...sessionEnv, ...options?.env } : undefined;
return execCommand(command, args, options?.cwd ?? cwd, { ...options, env });
},

getActiveTools(): string[] {
Expand Down
7 changes: 7 additions & 0 deletions packages/coding-agent/src/core/extensions/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1376,6 +1376,13 @@ export type SetLabelHandler = (entryId: string, label: string | undefined) => vo
*/
export interface ExtensionRuntimeState {
flagValues: Map<string, boolean | string>;
/**
* Extra env vars merged over process.env for pi.exec() subprocesses. Read at
* call time (not load time) so a host can scope per-session vars — e.g. the
* daemon supplying each session's herdr pane identity — without mutating the
* shared process.env. Returns undefined to use the parent env unchanged.
*/
getExecEnv?: () => Record<string, string> | undefined;
/** Provider registrations queued during extension loading, processed when runner binds */
pendingProviderRegistrations: Array<{ name: string; config: ProviderConfig; extensionPath: string }>;
/** Throws when this extension instance is stale after runtime replacement. */
Expand Down
2 changes: 2 additions & 0 deletions packages/coding-agent/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import { SessionManager } from "./core/session-manager.js";
import { SettingsManager } from "./core/settings-manager.js";
import { printTimings, resetTimings, time } from "./core/timings.js";
import { runMigrations, showDeprecationWarnings } from "./migrations.js";
import { collectDaemonClientEnv } from "./modes/daemon/daemon-protocol.js";
import {
type AgentConnection,
createInteractiveModeLocalSessionHost,
Expand Down Expand Up @@ -972,6 +973,7 @@ async function createDaemonInteractiveConnection(options: {
config: options.config,
sessionPath: options.sessionPath,
continueRecent: options.continueRecent,
env: collectDaemonClientEnv(),
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
});
if (!response.success) {
throw new Error(response.error);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ export interface ActiveSessionState {
unsubscribe?: () => void;
/** Latest background status summary, surfaced in the agents view. */
summaryState?: AgentStatus;
/**
* Client env (e.g. herdr pane identity), merged over process.env for this
* session's pi.exec() subprocesses. Bound at create; attaches never rebind
* it (watchers also attach). Subagents inherit the parent's.
*/
clientEnv?: Record<string, string>;
}

export interface ActiveSessionExtensionUiRequest {
Expand Down
67 changes: 67 additions & 0 deletions packages/coding-agent/src/modes/daemon/daemon-client-env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { DAEMON_CLIENT_ENV_KEYS } from "./daemon-protocol.js";

/** Re-filter client-sent env to the allowlist; the socket peer is untrusted. */
export function filterClientEnv(env?: Record<string, string>): Record<string, string> | undefined {
if (!env) {
return undefined;
}
const filtered: Record<string, string> = {};
for (const key of DAEMON_CLIENT_ENV_KEYS) {
if (env[key] !== undefined) {
filtered[key] = env[key];
}
}
return Object.keys(filtered).length > 0 ? filtered : undefined;
}

// Shared/exclusive lock: env windows are exclusive (they mutate process.env),
// env-less loads are shared — they run concurrently with each other but never
// inside an env window, so they can't capture another session's identity.
let lastExclusive: Promise<unknown> = Promise.resolve();
const activeShared = new Set<Promise<unknown>>();

/**
* Run fn with the client's env applied to process.env, restoring afterwards.
* Extensions capture vars like HERDR_PANE_ID synchronously at module load, so
* they must be in process.env while the session loads its extensions; after
* this window the session's exec env covers subprocess reads.
*/
export async function withClientEnv<T>(env: Record<string, string> | undefined, fn: () => Promise<T>): Promise<T> {
if (!env) {
const gate = lastExclusive;
const run = (async () => {
await gate.catch(() => undefined);
return fn();
})();
const tracked = run.catch(() => undefined);
activeShared.add(tracked);
void tracked.then(() => activeShared.delete(tracked));
return run;
}
const prior = lastExclusive;
// Snapshot synchronously: shareds arriving later gate on this window via
// lastExclusive, so waiting for them here would deadlock.
const sharedAtRequest = [...activeShared];
const run = (async () => {
await prior.catch(() => undefined);
await Promise.all(sharedAtRequest);
const previous = new Map<string, string | undefined>();
for (const [key, value] of Object.entries(env)) {
previous.set(key, process.env[key]);
process.env[key] = value;
}
Comment thread
macroscopeapp[bot] marked this conversation as resolved.
Resolved
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
try {
return await fn();
} finally {
for (const [key, value] of previous) {
if (value === undefined) {
delete process.env[key];
} else {
process.env[key] = value;
}
}
}
})();
lastExclusive = run.catch(() => undefined);
return run;
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type { SubagentRuntimeHost } from "../../core/rlm-runtime.js";
import { createAgentConnectionState } from "../agent-connection/snapshot.js";
import { type Theme, theme } from "../interactive/theme/theme.js";
import type { ActiveSessionState } from "./active-session-state.js";
import { withClientEnv } from "./daemon-client-env.js";
import {
type DaemonExtensionUIResponse,
type DaemonOutbound,
Expand Down Expand Up @@ -48,6 +49,9 @@ export async function bindActiveSessionState(
): Promise<void> {
const session = state.runtime.session;

// Read live so attach updates to state.clientEnv apply without rebinding.
session.setExecEnvProvider(() => state.clientEnv);

state.unsubscribe?.();
state.runtime.setSubagentRuntimeHost(callbacks.subagentRuntimeHost);
state.unsubscribe = session.subscribe((event) => {
Expand Down Expand Up @@ -103,7 +107,9 @@ function createCommandContextActions(state: ActiveSessionState): ExtensionComman
},
switchSession: async (sessionPath, options) => state.runtime.switchSession(sessionPath, options),
reload: async () => {
await state.runtime.session.reload();
// Reload re-evaluates extension modules, which capture client env
// (e.g. herdr pane identity) synchronously at load.
await withClientEnv(state.clientEnv, () => state.runtime.session.reload());
},
};
}
Expand Down
Loading