agentSdkChildEnvironment function

Map<String, String> agentSdkChildEnvironment({
  1. required Map<String, String> parent,
  2. required String nodeExecutable,
  3. Set<String> scrubbed = const {},
  4. ({String apiKey, String configDirectory})? credential,
})

The environment the standalone server child is started with: parent — the app's own — with nodeExecutable's directory at the front of PATH, and without the variables in scrubbed — credentials the app was handed for itself, such as a session token it was launched with.

The credential. With no credential the child keeps the parent's Anthropic and Claude Code variables, and the Agent SDK uses whatever it finds: an exported ANTHROPIC_API_KEY, or the machine's Claude Code login. With a credential the key it carries is the only one the child can use. Every inherited variable whose name starts with ANTHROPIC_ or CLAUDE is dropped — another key, an auth token, a base URL, an OAuth token, a configuration directory, the markers of a parent Claude Code session — and CLAUDE_CONFIG_DIR names the credential's own empty directory. That last part is what removes the ambient login: the Claude Code CLI keeps its login under its configuration directory and on macOS names its keychain item after it, so a directory nobody logged in from holds none. Without it the SDK answered with the machine's login while the user believed their key was in use — billed to and identified as someone else, and with a wrong key never reported as wrong.

Why those are scrubbed. A token the user handed the app for one session is the app's to use, not the AI server's to inherit: the server runs Anthropic's Agent SDK, which runs tools, and a credential in a tool-running process's environment is one a tool can read. The Anthropic key is the one credential that process exists to hold; nothing else the app was given travels with it.

Why PATH is not cosmetic. The Agent SDK does not run in the server process: it spawns the Claude Code CLI as a grandchild, and it spawns it as the bare name node. So the grandchild resolves its interpreter from PATH, not from the Node that the app chose. On a machine whose PATH still points at an older Node — an nvm default of v16 is the case this was measured on — the grandchild fails to parse the CLI bundle and dies with a syntax error, while the server it was launched from is running happily on the Node 20 it was given. The symptom is a completion that reports "the Claude Code process exited with code 1" and names no cause.

Prepending rather than replacing keeps everything else the SDK looks up on PATH reachable, and prepending rather than appending is what makes it win over the stale entry that caused the problem.

A bare executable name is left alone: it was itself resolved through PATH, so the grandchild would find the same one anyway. (A discovered Node is always an absolute path; only a vouched-for one can be bare.)

Variable names are compared case-insensitively, as Windows compares them.

A top-level function over a plain map rather than a method over Platform.environment, so what the child is handed can be asserted without spawning one.

Implementation

Map<String, String> agentSdkChildEnvironment({
  required Map<String, String> parent,
  required String nodeExecutable,
  Set<String> scrubbed = const {},
  ({String apiKey, String configDirectory})? credential,
}) {
  bool claudeOrAnthropic(String name) {
    final upper = name.toUpperCase();
    return upper.startsWith('ANTHROPIC_') || upper.startsWith('CLAUDE');
  }

  final environment = <String, String>{
    for (final entry in parent.entries)
      if (!scrubbed.contains(entry.key) &&
          !(credential != null && claudeOrAnthropic(entry.key)))
        entry.key: entry.value,
  };
  if (credential != null) {
    environment['ANTHROPIC_API_KEY'] = credential.apiKey;
    environment['CLAUDE_CONFIG_DIR'] = credential.configDirectory;
  }
  if (nodeExecutable.contains(Platform.pathSeparator)) {
    final nodeDir = File(nodeExecutable).parent.path;
    final separator = Platform.isWindows ? ';' : ':';
    // The variable as the parent spells it: Windows environments are
    // case-insensitive and commonly carry `Path`, and a second spelling would
    // be two variables to a map and one to the child.
    final pathKey =
        environment.keys.where((k) => k.toUpperCase() == 'PATH').firstOrNull ??
        'PATH';
    final inherited = environment[pathKey] ?? '';
    environment[pathKey] = inherited.isEmpty
        ? nodeDir
        : '$nodeDir$separator$inherited';
  }
  return environment;
}