opencode icon indicating copy to clipboard operation
opencode copied to clipboard

[BUG] Subagent terminates prematurely mid-execution but reports completed

Open YoungJurry opened this issue 5 months ago • 2 comments

Description

Subagent terminates before completing its work, but the task tool reports it as "completed". The parent agent receives partial/incomplete output. The output size is well under the 50KB/2000-line truncation limit.

Observed behavior

  1. Primary agent calls task(subagent_type="explore", prompt="...") to explore a codebase
  2. Subagent starts working (reading files, searching with glob/grep)
  3. Subagent stops mid-way through exploration — only examined some of the requested files/directories
  4. Task tool returns the partial result as "completed"
  5. Parent agent receives incomplete information, unaware that the subagent didn't finish

Key details

  • Output size is minimal (far below 50KB/2000-line limit)
  • No error is surfaced
  • Subagent status shows "completed"
  • Issue is NOT about text truncation (the output is fully delivered but incomplete)
  • Issue is about the subagent execution being cut short

Related issues

  • #6792: Task Tool Timeouts & Early Termination (similar root cause — subagent termination)
  • #11903: Task tool truncation drops session_id metadata
  • #11865: Tasks/Subagents with Codex / OpenAI are frequently getting stuck
  • #24342: Main & Sub-agents Randomly Freeze Indefinitely

Suspected causes

  1. Hardcoded timeout in Task tool (~30-60s) killing the subagent session
  2. LLM provider response timing out mid-conversation
  3. Tool call (grep/glob/read) hanging and aborting the subagent loop

Expected behavior

  • Subagent should complete all tool calls and analysis before returning
  • If terminated early, should report "error" or "timeout" instead of "completed"
  • Parent agent should be informed when subagent did not fully complete

Environment

  • opencode version: latest
  • Platform: linux
  • Subagent type: explore

YoungJurry avatar Jun 13 '26 01:06 YoungJurry

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

  • #6792: Task Tool Timeouts & Early Termination — covers the same root cause of subagents terminating early, including timeout and LLM-provider timing scenarios
  • #24342: Main & Sub-agents Randomly Freeze Indefinitely — overlaps on premature agent termination with no error surfaced

If your issue is distinct (e.g., specifically about the incorrect "completed" status being reported instead of an error/timeout), please clarify the difference from the above issues so maintainers can track it separately.

github-actions[bot] avatar Jun 13 '26 01:06 github-actions[bot]

Confirmed deterministic reproduction + root cause + a minimal patch below. This is the same bug as #29209 viewed from the parent agent's side (parent sees completed with empty output; the child DB row shows the actual Tool execution aborted truth).

Indicator chain (5/5 match)

Field Value
part.tool bash (or whatever streaming tool was in flight)
part.state.status error
part.state.error "Tool execution aborted"
part.state.input {} ← payload lost
part.metadata.interrupted true
message.finish "unknown"
message.tokens.total 0

If you query opencode.db after a "completed-but-empty" subagent return, you will find a row matching all five fields.

Root cause — packages/opencode/src/session/processor.ts:892-924

Two issues compound in the cleanup path on session abort:

(a) The grace timeout for in-flight tool calls is hardcoded at 250 ms:

yield* Effect.forEach(
  Object.values(ctx.toolcalls),
  (call) => Deferred.await(call.done).pipe(Effect.timeout("250 millis"), Effect.ignore),
  { concurrency: "unbounded" },
)

That window was tuned for completed-tool execution races. For reasoning models like gpt-5.5 that emit multi-kilobyte tool arguments via SSE deltas, the streaming window is routinely tens of seconds, so the timeout always trips.

(b) Once the timeout trips, the cleanup discards ctx.toolcalls[id].raw (the accumulated streaming bytes) and writes the part with state.input = {}:

yield* session.updatePart({
  ...part,
  state: {
    ...part.state,
    status: "error",
    error: "Tool execution aborted",
    metadata: { ...metadata, interrupted: true },
    time: { start: ..., end },
  },
})

The streamed raw never makes it to disk, so parent agents and downstream tooling can't reconstruct what the model was about to invoke — which is exactly the "completed but empty" symptom this issue describes.

Deterministic repro (no source patches needed)

  1. Launch a background subagent that asks gpt-5.5 (or any reasoning model with slow tool-args streaming) to emit one bash tool call with a command argument 4000+ characters long. Suggested prompt: "emit one bash one-liner that runs a complex jq filter against every .ts file under packages/opencode/src; the jq filter must reference every field explicitly; no temp files, no heredoc, no splitting."
  2. Wait ~30–40s while the model finishes reasoning and starts streaming the tool-input deltas.
  3. Cancel the subagent (Esc Esc / background_cancel / parent abort).
  4. Inspect the child session's last tool part in opencode.db. You will see the 5-field indicator chain above.

I just ran this with a 35-second wait and a single background_cancel call — the indicator chain reproduced exactly, with state.input = {} and a streamed raw payload silently dropped by cleanup.

Suggested fix (minimal, schema-compatible)

Two changes, both isolated to processor.ts:

+const SALVAGE_RAW_MAX = 4096
+
+function salvageStreamingToolInput(
+  raw: string | undefined,
+  fallback: Record<string, any>,
+): { input: Record<string, any>; rawSnapshot?: string } {
+  if (!raw) return { input: fallback }
+  try {
+    const parsed = JSON.parse(raw)
+    if (isRecord(parsed)) return { input: parsed }
+  } catch {
+    // streaming was interrupted mid-token; fall through to raw snapshot
+  }
+  return {
+    input: fallback,
+    rawSnapshot: raw.length > SALVAGE_RAW_MAX ? raw.slice(0, SALVAGE_RAW_MAX) + "…[truncated]" : raw,
+  }
+}
-  (call) => Deferred.await(call.done).pipe(Effect.timeout("250 millis"), Effect.ignore),
+  (call) => Deferred.await(call.done).pipe(Effect.timeout("1500 millis"), Effect.ignore),
   const metadata = "metadata" in part.state && isRecord(part.state.metadata) ? part.state.metadata : {}
+  const fallbackInput = "input" in part.state && isRecord(part.state.input) ? part.state.input : {}
+  const salvage = salvageStreamingToolInput(match.call.raw, fallbackInput)
+  const interruptedMetadata: Record<string, any> = { ...metadata, interrupted: true }
+  if (salvage.rawSnapshot !== undefined) {
+    interruptedMetadata.interruptedRawSnapshot = salvage.rawSnapshot
+  }
   yield* session.updatePart({
     ...part,
     state: {
       ...part.state,
+      input: salvage.input,
       status: "error",
       error: "Tool execution aborted",
-      metadata: { ...metadata, interrupted: true },
+      metadata: interruptedMetadata,
       time: { start: ..., end },
     },
   })

Why this is safe:

  • ToolStateError.input schema is Schema.Record(Schema.String, Schema.Any); the salvaged value is only written when JSON.parse(raw) yields an isRecord(...) object, preserving the schema contract.
  • When the stream was cut mid-token, the truncated raw bytes go to metadata.interruptedRawSnapshot (existing field, Schema.optional(Schema.Record(...)) so just add a key) instead of being silently dropped.
  • The 1.5s grace covers virtually every realistic streaming finish while still bounding cleanup.

Suggested regression test

Sit next to the existing mark pending tools as aborted on cleanup test in processor-effect.test.ts:771. Use the test LLM server to emit tool-input-start + several tool-input-delta events for a bash tool, then Fiber.interrupt(run) before sending tool-input-end. Assert:

expect(call?.state.status).toBe("error")
if (call?.state.status === "error") {
  expect(call.state.error).toBe("Tool execution aborted")
  expect(call.state.metadata?.interrupted).toBe(true)
  // The fix asserts ONE of these holds (whichever applies to the streamed raw):
  // (a) raw was a valid JSON object → input is recovered
  expect(call.state.input).toEqual({ cmd: "pwd" })
  // (b) raw was partial → metadata has the snapshot, input is fallback {}
  // expect(call.state.metadata?.interruptedRawSnapshot).toContain('"cmd":')
}

Happy to spin this into a PR if it would help — let me know if the fix shape is the right direction (vs. e.g. solving it at the SDK streaming layer or making ctx.toolcalls[id].raw mirror to part.state.raw on every delta).

cc #29209 — same root cause, different observation point.


Ultraworked with Sisyphus

cpkt9762 avatar Jun 27 '26 13:06 cpkt9762

Cross-linking a sibling case with a different mechanism, filed as #37852: provider stream drops mid-generation (no tool in flight) and the message is persisted with finish=unknown, zero usage, and no content — no error recorded anywhere, loop exits cleanly, parent gets a fully empty result. Distinct from the tool-abort path confirmed here, but same symptom family (parent sees completed-with-empty); may be worth triaging together.

fernanDOTdo avatar Jul 20 '26 04:07 fernanDOTdo