GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — `opencode2 run` and `background: true` tasks may cause premature exit · Issue #48361 · anomalyco/opencode

opencode2 run and background: true tasks may cause premature exit #48361

New issue
Copy link
New issue
Copy link
Closed
#60699
#60618
Closed
opencode2 run and background: true tasks may cause premature exit#48361
#60699
#60618
Copy link
Assignees
kitlangton
Labels
2.0reproduced

Description

@ucirello
ucirello
opened on Sep 10, 2026
Issue body actions

Description

I have a script that uses opencode2 run in which I am trying to achieve parallelization. The model decided to use background: true for the subagents/tasks.

When that happened, it correctly dispatched all the subagents, but opencode2 run terminated prematurely.

Plugins

None

OpenCode version

v0.0.0-beta-19425

Steps to reproduce

  1. Use opencode2 run with instructions to execute a lot of work in parallel and ask it to use background: true
  2. Wait for the jobs to be parallelized
  3. Observe opencode2 run ending prematurely.

Screenshot and/or share link

No response

Operating System

MacOS 26.5.2

Terminal

iTerm + tmux

Reacted by Robin

Activity

  1. github-actions
    assigned
    kitlangton
    on Sep 10, 2026
  2. github-actions commented on Sep 10, 2026

    @github-actions
    github-actionsBot
    on Sep 10, 2026 – with GitHub Actions
    Contributor
    More actions

    This issue might be a duplicate of existing issues. Please check:

    • opencode run (headless) exits 0 mid-pipeline after a parallel subagent fan-out, before the model's next turn #37548: opencode run exits 0 mid-pipeline after a parallel subagent fan-out — same symptom of premature exit after background tasks are dispatched
    • Bug: opencode run exits before background tasks (explore/librarian) complete #16380: opencode run exits before background tasks complete — same root cause where headless mode treats a model response as session completion without waiting for pending background work

    If your issue is distinct (e.g., specific to the background: true flag in task config rather than the general headless lifecycle), please add details clarifying the difference.

  3. opencode-agent
    added
    2.0
    on Sep 10, 2026
  4. opencodejr commented on Oct 28, 2026

    @opencodejr
    opencodejrBot
    on Oct 28, 2026
    Contributor
    More actions

    Thanks for the report. I could reproduce this.

    I used a mock model whose first reply starts two subagent calls with background: true. Each subagent takes about 15 seconds to answer. Then I ran opencode2 run --standalone --auto "..." on v0.0.0-beta-19425. What happened:

    • Both subagents were shown as ✓ immediately.
    • The parent printed its "waiting for them to finish" text.
    • run exited with code 0 after about 1–2 seconds.

    The subagents went on to finish about 15 seconds later, but the parent was never resumed with their results, so the final answer never appeared. It still happens on the latest dev (1e7ba46f8b99). The script below reproduces it with a built-in mock provider.

    Closely related:

    • One-shot run exits before plugin-backgrounded work completes; plugins cannot detect a headless client on the shared service #48683: the same early exit, when work is moved to the background by a plugin
    • [BUG] V2: subagent with pending background work (shell commands or subagents, background: true) marked completed early — results never collected #48826: a subagent with pending background work is reported as completed too early

    Until this is addressed, you could ask the model in your script not to use background: true. That gives up the parallelism you were after, but foreground subagents block until they finish, so run gets their results.

    Reproduction script (repro.sh)
    #!/usr/bin/env bash
    # Repro for #48361: `opencode run` exits before background subagents finish.
    # Needs: bun and `opencode` on PATH (override with OC="..."). Starts an embedded OpenAI-compatible mock on :4999.
    # The mock makes the parent call `subagent` twice with background:true; each child takes 15s to answer.
    set -u
    OC=${OC:-opencode}
    # OC_DEV=/path/to/checkout runs the CLI from source instead
    if [ -n "${OC_DEV:-}" ]; then
      OC="bun --conditions=browser --preload=$OC_DEV/packages/tui/node_modules/@opentui/solid/scripts/preload.js $OC_DEV/packages/cli/src/index.ts"
    fi
    DIR=$(mktemp -d); mkdir -p "$DIR/home" "$DIR/proj"
    export HOME=$DIR/home XDG_CONFIG_HOME=$DIR/home/.config XDG_DATA_HOME=$DIR/home/.local/share XDG_STATE_HOME=$DIR/home/.local/state XDG_CACHE_HOME=$DIR/home/.cache
    cat > "$DIR/proj/opencode.json" <<'JSON'
    { "model": "mock/mock", "permission": { "*": "allow" },
      "provider": { "mock": { "npm": "@ai-sdk/openai-compatible", "name": "Mock",
        "options": { "baseURL": "http://127.0.0.1:4999/v1", "apiKey": "x" },
        "models": { "mock": { "name": "Mock", "tool_call": true, "limit": { "context": 100000, "output": 4000 } } } } } }
    JSON
    cat > "$DIR/mock.ts" <<'MOCK'
    // Minimal OpenAI-compatible streaming mock.
    const log = (...a: unknown[]) => console.error(new Date().toISOString(), ...a)
    const text = (m: any) => typeof m.content === "string" ? m.content : (m.content ?? []).map((p: any) => p.text ?? "").join("")
    function sse(chunks: any[]) {
      const enc = new TextEncoder()
      return new Response(new ReadableStream({ start(c) {
        for (const ch of chunks) c.enqueue(enc.encode(`data: ${JSON.stringify(ch)}\n\n`))
        c.enqueue(enc.encode("data: [DONE]\n\n")); c.close()
      } }), { headers: { "content-type": "text/event-stream" } })
    }
    const base = { id: "x", object: "chat.completion.chunk", created: 0, model: "mock" }
    const say = (s: string) => sse([{ ...base, choices: [{ index: 0, delta: { role: "assistant", content: s } }] }, { ...base, choices: [{ index: 0, delta: {}, finish_reason: "stop" }] }])
    const calls = (cs: any[]) => sse([{ ...base, choices: [{ index: 0, delta: { role: "assistant", tool_calls: cs.map((c, i) => ({ index: i, id: c.id, type: "function", function: { name: c.name, arguments: JSON.stringify(c.args) } })) } }] }, { ...base, choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] }])
    Bun.serve({ port: Number(process.env.PORT ?? 4999), idleTimeout: 120, async fetch(req) {
      const url = new URL(req.url)
      if (!url.pathname.endsWith("/chat/completions")) return new Response("{}")
      const body: any = await req.json()
      const msgs = body.messages as any[]
      const all = msgs.map(text).join("\n")
      const users = msgs.filter((m) => m.role === "user").map(text)
      const tools = (body.tools ?? []).map((t: any) => t.function.name)
      if ((users[0] ?? "").includes("CHILD_TASK")) {
        const tok = users[0].match(/CHILD_TASK_(\w+)/)![1]
        log("child", tok, "-> sleeping 15s"); await Bun.sleep(15000); log("child", tok, "done")
        return say(`TOKEN_${tok}`)
      }
      if (!tools.length) { log("title/other"); return say("Title") }
      if (all.includes("PARENT")) {
        const toolMsgs = msgs.filter((m) => m.role === "tool").length
        if (/TOKEN_A/.test(all) && /TOKEN_B/.test(all)) { log("parent final"); return say("FINAL: got TOKEN_A and TOKEN_B") }
        if (toolMsgs === 0) { log("parent -> launching 2 background subagents; tools:", tools.join(",")); return calls([
          { id: "call_a", name: "subagent", args: { agent: "general", description: "child a", prompt: "CHILD_TASK_A", background: true } },
          { id: "call_b", name: "subagent", args: { agent: "general", description: "child b", prompt: "CHILD_TASK_B", background: true } },
        ]) }
        log("parent -> waiting text"); return say("Launched both subagents; waiting for them to finish.")
      }
      log("unknown"); return say("ok")
    } })
    log("mock listening")
    MOCK
    PORT=4999 bun "$DIR/mock.ts" 2>"$DIR/mock.log" & MOCK_PID=$!; sleep 1
    # the --standalone child server is spawned without the preload flag; give it a bunfig.toml
    [ -n "${OC_DEV:-}" ] && echo "preload = [\"$OC_DEV/packages/tui/node_modules/@opentui/solid/scripts/preload.js\"]" > "$DIR/proj/bunfig.toml"
    cd "$DIR/proj"
    start=$(date +%s)
    timeout 120 $OC run --standalone --auto "PARENT: launch two background subagents and report their tokens"
    echo "exit=$? wall=$(( $(date +%s)-start ))s  (expected: waits ~15s and prints FINAL: got TOKEN_A and TOKEN_B)"
    sleep 20; echo "--- mock log (children keep running after run exited; parent never resumed) ---"; cat "$DIR/mock.log"; kill $MOCK_PID

    Run it: bash repro.sh

  5. opencodejr
    added
    reproduced
    on Oct 28, 2026
  6. rekram1-node
    closed this as completedin #60699on Nov 4, 2026
  7. lfnothias commented on Nov 16, 2026

    @lfnothias
    lfnothias
    on Nov 16, 2026
    More actions

    Related data point on v2.3.0, for plugin work rather than the background-subagent case in this issue: opencode run exits right after session.execution.succeeded, so asynchronous work a plugin starts from that event never completes. This matches the note in #48683 that run finishes on session.execution.succeeded without checking for pending work.

    Setup: free model opencode/deepseek-v4.1-flash-free, isolated HOME and XDG dirs, no other plugins, opencode.json with only model and "permission": { "*": "allow" }.

    .opencode/plugins/probe.ts:

    import { appendFileSync } from "node:fs"
    const LOG = process.env.PROBE_LOG!
    const DELAY = Number(process.env.PROBE_DELAY_MS ?? 3000)
    const mark = (m: string) => appendFileSync(LOG, `${Date.now()} ${m}\n`)
    const later = async (tag: string) => {
      mark(`${tag}:sync`)
      await new Promise((r) => setTimeout(r, DELAY))
      mark(`${tag}:async-after-${DELAY}ms`)
    }
    export default {
      id: "probe",
      async setup(ctx: any) {
        mark("setup")
        await ctx.tool.hook("execute.after", async (e: any) => { await later(`tool.execute.after(${e?.tool})`) })
        void (async () => {
          for await (const ev of ctx.event.subscribe({})) {
            const t = (ev as any)?.type
            mark(`event:${t}`)
            if (t === "session.idle" || t === "session.execution.succeeded") await later(`turn-end(${t})`)
          }
        })()
      },
    }

    Command: opencode run --standalone --auto -m opencode/deepseek-v4.1-flash-free "Read the file note.txt and answer with one word: its first word." < /dev/null

    Three runs, with PROBE_DELAY_MS = 3000, 1000 and 50:

    • the tool.execute.after async step always completes (the turn waits for it);
    • for session.execution.succeeded, the sync marker is written and the async marker never is, even at 50 ms. The process exits with code 0 between 71 and 165 ms after the event, and the answer on stdout is correct, so the loss is silent.

    I understand an event subscription is fire-and-forget on the plugin side. The gap is that a plugin has no documented way to make run wait, for example a bounded drain of pending event handlers before exit, or an API to hold the process open. Plugins that record or summarise a turn at its end (logging, evaluation, memory) lose that work in headless mode only.

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

Metadata

Metadata

Assignees

  • @kitlangton
    kitlangton

Labels

2.0reproduced

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

    You are visitor 01402775 — GeezerVison does not store the pages you look up.
    Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.