Skip to content

session.environment is not applied to subagent (child) sessions #55228

Open

Description

@StepharoAgent

Description

Version: 2.0.28

PUT /api/session/{id}/environment sets variables for the shell tool of that session (works, replace semantics,
in-memory only). Child sessions created by the subagent tool (also background: true) do not inherit it: their
shell runs with the service process environment (e.g. a different HOME/PATH).

Expected: children inherit the parent's session environment (they act on the parent's behalf), or a documented
way to set it for children (e.g. a session.created hook or an environment field on the subagent config).

Workaround: listen for session.created with a parentID from our tree and PUT the environment before the
child's first tool call (an LLM step precedes it, so this wins in practice).

OpenCode version

2.0.28

Operating System

Linux x64 (Ubuntu)

Activity

  1. opencode-agent commented on Oct 13, 2026

    @opencode-agent
    Contributor

    Thanks for the clear report. I could reproduce this on 2.0.28, and it still happens on the latest dev (1163e6c).

    Steps (with a simulated model):

    1. Set {PATH, HOME, MARKER: "from-parent"} on the root session with session.environment.
    2. Run echo MARKER=${MARKER:-unset} with the shell tool in the parent. It prints MARKER=from-parent.
    3. Spawn a general subagent that runs the same command. It prints MARKER=unset, because the child's shell gets the service process environment.

    I only tested a foreground subagent, not background: true. The script below reproduces it, and the recording shows the run. Your workaround of listening for session.created and setting the environment on the child looks like the right stopgap for now.

    recording.mp4
    Reproduction script (drive.ts)
    // Reproduces #55228: session.environment set on a parent session is not applied
    // to the shell of a child session created by the `subagent` tool.
    import { Effect, Schedule } from "effect"
    import { Llm, OpenCodeDriver } from "opencode-drive"
    
    const echo = "echo MARKER=${MARKER:-unset}"
    
    export default OpenCodeDriver.use(
      {
        ...(process.env.OC_DEV ? { opencode: { dev: process.env.OC_DEV } } : {}),
        tui: { recording: true },
      },
      ({ ui, llm, opencode }) =>
        Effect.gen(function* () {
          yield* ui.submit("Run echo, then ask a general subagent to run echo too")
    
          // Root session now exists; set its environment (replace semantics, keep PATH/HOME).
          const root = yield* opencode.session.list({}).pipe(
            Effect.flatMap((r) => {
              const found = r.data.find((s) => !s.parentID)
              return found ? Effect.succeed(found) : Effect.fail("no session yet")
            }),
            Effect.retry({ times: 100, schedule: Schedule.spaced("100 millis") }),
          )
          yield* opencode.session.environment({
            sessionID: root.id,
            variables: { PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: process.env.HOME ?? "/tmp", MARKER: "from-parent" },
          })
    
          // Parent: shell echo
          yield* llm.send(
            Llm.toolCall({ index: 0, id: "call_parent_shell", name: "shell", input: { command: echo, description: "parent echo" } }),
            Llm.finish("tool-calls"),
          )
          // Parent: spawn subagent
          yield* llm.send(
            Llm.toolCall({
              index: 0,
              id: "call_subagent",
              name: "subagent",
              input: { agent: "general", description: "echo marker", prompt: "Run echo MARKER" },
            }),
            Llm.finish("tool-calls"),
          )
          // Child: shell echo
          yield* llm.send(
            Llm.toolCall({ index: 0, id: "call_child_shell", name: "shell", input: { command: echo, description: "child echo" } }),
            Llm.finish("tool-calls"),
          )
          yield* llm.send(Llm.text("Child done."))
          yield* llm.send(Llm.text("Parent done."))
          yield* ui.waitFor("Parent done.")
    
          const children = yield* opencode.session.list({}).pipe(Effect.map((r) => ({ data: r.data.filter((c) => c.parentID === root.id) })))
          for (const s of [root, ...children.data]) {
            const messages = yield* opencode.message.list({ sessionID: s.id })
            const text = JSON.stringify(messages)
            const found = [...new Set(text.match(/MARKER=[A-Za-z-]+/g) ?? [])]
            yield* Effect.log(`${s.parentID ? "CHILD " : "PARENT"} ${s.id}: ${found.join(" ")}`)
          }
          yield* ui.screenshot("after")
        }),
    )

    Run it with opencode-drive: opencode-drive run ./drive.ts. It drives opencode from your PATH; set OC_DEV to the path of an OpenCode checkout to run that from source instead.

  2. argszero commented on Oct 13, 2026

    @argszero
    Contributor

    I'd like to work on this.

    I re-derived the cause from the source rather than taking it from the report, and it is where you pointed. SessionEnvironment is a plain map keyed by session id (packages/core/src/session/environment.ts), and the shell resolves it per session with

    (Schema.is(SessionSchema.ID)(sessionID) ? yield* environments.get(sessionID) : undefined) ?? process.env

    (packages/core/src/shell.ts:262) — so a session with no stored variables silently gets the service process environment, which is exactly the MARKER=unset you saw.

    The child is created by the subagent tool with

    yield* sessions.create({ parentID: context.sessionID, title: input.description, agent: ..., model })

    (packages/core/src/tool/plugin/subagent.ts:187), and Session.create copies the parent's location, metadata and permissions — its own comment says "Children inherit metadata and permissions the way they inherit location, so host policies that read them treat the family uniformly" (packages/core/src/session.ts:285) — but never the parent's environment. Nothing else in the subagent path sets it either.

    So I plan to make a child session inherit its parent's variables when it is created, in the same place the other inherited fields are decided, rather than special-casing the subagent tool: that covers the other child-creation paths too, and keeps one rule for what a child inherits. Covered by a test that sets variables on a parent, creates a child, and asserts the child resolves them (plus that an explicit set on the child still wins).

    One note on scope: experimental.subagent_fork (#47576) is open against Session.create and the subagent tool. It forks history, not the environment, so the two do not overlap in behaviour, though they touch the same functions and test files — I'll base on the current dev and say so in the PR.

  3. Finn763 commented on Oct 13, 2026

    @Finn763
    Contributor

    Taking this one. Children already inherit location/metadata/permissions at Session.create; the environment service misses the same inheritance -- I'll wire the parent's variables into the child at creation and pin it with a test in session-environment.test.ts.

  4. Finn763 commented on Oct 13, 2026

    @Finn763
    Contributor

    PR is up: #55257 — Session.create now copies the parent's in-memory session environment onto children (snapshot at creation), the same way location/metadata/permissions are already inherited. subagent children finally see the parent's session.environment variables. Covered by a new case in session-create.test.ts (red on base).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions