GeezerVison is showing github.com — fix(runner): wait for background subagents (X31); reopen the steer wi… · rphang/opencode-workflows@e46d9ca
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: README.md +1-1Lines changed: 1 addition & 1 deletion - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -508,7 +508,7 @@ Set them in the environment of the opencode server. They work with every install | 508 | 508 | | `MAX_STRUCTURED_OUTPUT_RETRIES` (or `OPENCODE_WORKFLOW_MAX_STRUCTURED_OUTPUT_RETRIES`) | `5` | Attempts a schema agent gets before `agent()` throws. | | 509 | 509 | | `OPENCODE_WORKFLOW_FREEFORM` | unset (on) | `0`, `false`, `no` or `off` registers no `workflow_script` tool, like the `freeformTool: false` option. | | 510 | 510 | | `OPENCODE_WORKFLOW_RPC_CONTROL` | unset (on) | `0`, `false`, `no` or `off` makes the live tree's RPC read-only, like the `rpcControl: false` option. | | 511 | | -| `OPENCODE_WORKFLOW_IDLE_HOOK` | unset (on) | `0`, `false`, `no` or `off` registers no `experimental.idle` hook (opencode 2.3+). Without it, a steering message that lands as an agent finishes still reaches it through an extra turn, and a schema agent that forgot `workflow_submit` is re-prompted in a new turn instead of nudged in the same one. | | | 511 | +| `OPENCODE_WORKFLOW_IDLE_HOOK` | unset (on) | `0`, `false`, `no` or `off` registers no `experimental.idle` hook (opencode 2.3+). Without it, a steering message that lands as an agent finishes still reaches it through an extra turn, and a schema agent that forgot `workflow_submit` is re-prompted in a new turn instead of nudged in the same one. It also turns off waiting for an agent's background subagents (opencode 2.3 runs them in the background): an agent that launched one is then read as soon as its turn ends. | | 512 | 512 | | `OPENCODE_WORKFLOW_DATA_DIR` | `$XDG_DATA_HOME/opencode/workflows`, else `%LOCALAPPDATA%\opencode\workflows` (Windows) or `~/.local/share/opencode/workflows` | Run transcripts, stored as `<dir>/<sessionID>/<runId>/`. The `dataDir` plugin option wins over it. | | 513 | 513 |
| 514 | 514 | ## How it compares to Claude Code | |
Collapse file Copy file name to clipboardExpand all lines: docs/OPENCODE-API-NOTES.md +11-2Lines changed: 11 additions & 2 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -30,7 +30,12 @@ the 2.3.0 packages and `tsc` is clean against their types. | 30 | 30 | posts a `<subagent>` report with its last reply into the parent's inbox (steer) after **every** | 31 | 31 | completed round and wakes the parent (#63209; the opt-out was removed in #63413). The runner | 32 | 32 | therefore keeps creating root sessions (and P63 stays). Upstream's own `subagent` tool is now | 33 | | - always background (#63391). | | 33 | + always background (#63391): the call returns at once with the child's sessionID, the caller's | | 34 | + turn may end, and the job's `<subagent>` report wakes the caller later | | 35 | + (`core/tool/plugin/subagent.ts`). `session.wait()` is `awaitIdle` over executions only | | 36 | + (`core/session/run-coordinator.ts`), so it resolves while the job runs; the job is visible to a | | 37 | + plugin only in the `experimental.idle` event's `background` list. A workflow child that uses the | | 38 | + tool would be read too early: the runner waits for such jobs through the idle hook (X31). | 34 | 39 | - **Failure text:** the `{type:"idle", outcome:"failed"}` context message carries | 35 | 40 | `error: {type, message, status?}` (#53826). An interrupted step keeps its closed text and its | 36 | 41 | assistant message gets `error: {type:"aborted", message:"Step interrupted"}` (#60674). Tokens of an | @@ -182,7 +187,11 @@ at setup (unless `OPENCODE_WORKFLOW_IDLE_HOOK=0`) and keeps a map of its live ch | 182 | 187 | → mailbox, schema, stopping). When a child is about to go idle the hook stops its mailbox | 183 | 188 | (`finishing`), awaits sends in flight, and returns with the window reopened when a sent message is | 184 | 189 | not in `context()` yet: it waits in the inbox, so opencode continues the same execution with it. | 185 | | -A later message is refused `finishing` rather than parked. For a schema agent without an accepted | | 190 | +A later message is refused `finishing` rather than parked; if the execution goes on anyway (another | | 191 | +plugin's idle hook, a user prompt, the cap), the session `context` hook, which runs before every | | 192 | +model request, reopens the window the hook closed. While the child's own subagent or image job | | 193 | +runs, the hook only records it (`workflow-jobs/<sessionID>` in `ctx.storage`) and the runner keeps | | 194 | +waiting after `wait()` until a report lists none (X31). For a schema agent without an accepted | 186 | 195 | submission it then sends the re-prompt text as a `resume:false` steer (a nudge, counted in the P21 | 187 | 196 | budget through the submit registry). The verification and wake above stay as the fallback for | 188 | 197 | 2.0.15, worktree children (their hook runs in the worktree instance, which has no mailbox; it can | |
Collapse file Copy file name to clipboardExpand all lines: docs/PARITY.md +4-3Lines changed: 4 additions & 3 deletions - Display the source diff
- Display the rich diff
Large diffs are not rendered by default. Collapse file Copy file name to clipboardExpand all lines: docs/design/steering-and-live-tree.md +8Lines changed: 8 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -253,6 +253,14 @@ unchanged as the fallback: the hook never fires on 2.0.15, a worktree child's ho | 253 | 253 | instance without the mailbox, and a hook that exceeds its 3 s cap or a turn that was interrupted | 254 | 254 | does nothing. | 255 | 255 |
| | 256 | +Review follow-up. `reopen()` undoes only `quiesce()`: it does nothing once the runner has called | | 257 | +`close()`, `open()` or `seal()`. Besides the hook's own continuation, the session `context` hook | | 258 | +(before every model request) calls it, so a window does not stay `finishing` when something else | | 259 | +continues the execution (another plugin's idle hook, a user prompt in the child, the hook's cap). | | 260 | +While the child's own subagent or image job runs (opencode 2.3's `subagent` tool is always | | 261 | +background), the hook records the job, leaves the window open and sends no nudge; the runner waits | | 262 | +after `wait()` until a report lists no job (X31, `src/opencode/background.ts`). | | 263 | + | 256 | 264 | ## A.5 Engine and host changes | 257 | 265 |
| 258 | 266 | - `LiveAgent` gets `mailbox: AgentMailbox`, created at `callAgent` time in state `pending`, and it | |
Collapse file Copy file name to clipboardExpand all lines: src/mailbox.ts +21-1Lines changed: 21 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -88,6 +88,8 @@ export class AgentMailbox { | 88 | 88 | private deferred: { msg: AgentMessage; resolve: (r: PostResult) => void }[] = [] | 89 | 89 | private readonly inflight = new Set<Promise<unknown>>() | 90 | 90 | private windowSent: SentMessage[] = [] | | 91 | + /** quiesce() closed the window and the runner has not touched it since (reopen() may undo it). */ | | 92 | + private quiesced = false | 91 | 93 | private reserved = 0 | 92 | 94 | private send?: MessageSender | 93 | 95 | private guard?: MessageGuard | @@ -158,6 +160,7 @@ export class AgentMailbox { | 158 | 160 | /** Runner side: a turn's prompt has been sent; messages go out right away until close(). */ | 159 | 161 | open(): void { | 160 | 162 | if (this._state === "closed") return | | 163 | + this.quiesced = false | 161 | 164 | this._state = "open" | 162 | 165 | const waiting = this.deferred | 163 | 166 | this.deferred = [] | @@ -169,6 +172,7 @@ export class AgentMailbox { | 169 | 172 | * Resolves, once every send started in this window has settled, with the messages sent in it. | 170 | 173 | */ | 171 | 174 | async close(): Promise<SentMessage[]> { | | 175 | + this.quiesced = false // the runner owns the window from here: reopen() no longer applies | 172 | 176 | if (this._state !== "closed") this._state = "finishing" | 173 | 177 | while (this.inflight.size) await Promise.all([...this.inflight]) | 174 | 178 | const sent = this.windowSent | @@ -183,11 +187,26 @@ export class AgentMailbox { | 183 | 187 | * with the messages sent in this window so far. | 184 | 188 | */ | 185 | 189 | async quiesce(): Promise<SentMessage[]> { | 186 | | - if (this._state === "open") this._state = "finishing" | | 190 | + if (this._state === "open") { | | 191 | + this._state = "finishing" | | 192 | + this.quiesced = true | | 193 | + } | 187 | 194 | while (this.inflight.size) await Promise.all([...this.inflight]) | 188 | 195 | return this.windowSent.map((s) => ({ ...s })) | 189 | 196 | } | 190 | 197 |
| | 198 | + /** | | 199 | + * Hook side (X22): reopens a window that quiesce() closed, as long as the runner has not taken | | 200 | + * it over since (close(), open() or seal()). Used when the execution goes on after all: the idle | | 201 | + * hook's own continuation, or the next model step (another plugin's hook or a user prompt | | 202 | + * continued it). Returns whether it reopened. | | 203 | + */ | | 204 | + reopen(): boolean { | | 205 | + if (!this.quiesced || this._state !== "finishing") return false | | 206 | + this.open() | | 207 | + return true | | 208 | + } | | 209 | + | 191 | 210 | /** Runner side: confirms (or not) that a held or sent message reached the agent. */ | 192 | 211 | report(id: string, status: "delivered" | "undelivered"): void { | 193 | 212 | const e = this.entries.find((x) => x.id === id) | @@ -198,6 +217,7 @@ export class AgentMailbox { | 198 | 217 |
| 199 | 218 | /** The agent settled (or was stopped): every later message is refused with `finished`. */ | 200 | 219 | seal(): void { | | 220 | + this.quiesced = false | 201 | 221 | this._state = "closed" | 202 | 222 | const waiting = this.deferred | 203 | 223 | this.deferred = [] | |
Collapse file Copy file name to clipboard +124Lines changed: 124 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +// Background jobs of a workflow child (opencode 2.3+; PARITY X31). | | 2 | +// | | 3 | +// opencode 2.3's `subagent` tool always runs in the background: the call returns at once, the | | 4 | +// child's turn can end, and the job's `<subagent>` report wakes the child later into a new | | 5 | +// execution (core/tool/plugin/subagent.ts). session.wait() awaits executions, not jobs, and a job | | 6 | +// is visible to a plugin only in the `experimental.idle` event's `background` list. So the idle hook | | 7 | +// reports the child's own jobs here and the runner keeps waiting after wait() while the latest | | 8 | +// report lists any, then reads the reply that followed the report. | | 9 | +// | | 10 | +// Reports go to ctx.storage (shared by every instance of the plugin) because a worktree child's | | 11 | +// hook runs in the worktree instance. The runner opens a record when the child exists and removes | | 12 | +// it when the agent settles; a hook only writes a record that exists, so a report that wakes the | | 13 | +// child after it settled leaves nothing behind. | | 14 | +// | | 15 | +// Only subagent and image jobs are waited for: they finish and report. A background shell (a dev | | 16 | +// server, a watcher) may run for good; it is listed for information only, as core/plugin/goal.ts does. | | 17 | + | | 18 | +import type { StorageLike } from "./submit.ts" | | 19 | + | | 20 | +export const JOBS_STORAGE_PREFIX = "workflow-jobs/" | | 21 | + | | 22 | +/** Default cap on how long the runner waits for an agent's background jobs. */ | | 23 | +export const BACKGROUND_WAIT_MS = 30 * 60_000 | | 24 | + | | 25 | +/** The job kinds whose completion report wakes the child (and that therefore end). */ | | 26 | +export const AWAITED_JOB_KINDS: readonly string[] = ["subagent", "image"] | | 27 | + | | 28 | +export interface BackgroundJob { | | 29 | + kind: string | | 30 | + /** subagent: its description; image: its path. */ | | 31 | + label?: string | | 32 | +} | | 33 | + | | 34 | +export interface JobReport { | | 35 | + /** Bumped by every report; 0 = opened by the runner, nothing reported yet. */ | | 36 | + seq: number | | 37 | + jobs: BackgroundJob[] | | 38 | +} | | 39 | + | | 40 | +export interface JobTracker { | | 41 | + /** Runner: the child exists; the hook's reports count from now on. */ | | 42 | + open(sessionID: string): Promise<void> | | 43 | + /** | | 44 | + * Hook: the child's own jobs as the execution ends. A child this instance does not run (`live` | | 45 | + * false) is only reported while its record exists. | | 46 | + */ | | 47 | + report(sessionID: string, jobs: BackgroundJob[], live: boolean): Promise<void> | | 48 | + read(sessionID: string): Promise<JobReport | undefined> | | 49 | + /** Runner: the agent settled. */ | | 50 | + close(sessionID: string): Promise<void> | | 51 | +} | | 52 | + | | 53 | +/** The awaited own jobs of `sessionID` in an `experimental.idle` event's `background` list. */ | | 54 | +export function ownJobs(sessionID: string, background: ReadonlyArray<Record<string, unknown>> | undefined): BackgroundJob[] { | | 55 | + const out: BackgroundJob[] = [] | | 56 | + for (const w of background ?? []) { | | 57 | + if (!w || w.sessionID !== sessionID || !AWAITED_JOB_KINDS.includes(String(w.kind))) continue | | 58 | + const label = typeof w.description === "string" ? w.description : typeof w.path === "string" ? w.path : undefined | | 59 | + out.push({ kind: String(w.kind), ...(label ? { label: label.slice(0, 120) } : {}) }) | | 60 | + } | | 61 | + return out | | 62 | +} | | 63 | + | | 64 | +function isReport(v: unknown): v is JobReport { | | 65 | + return typeof v === "object" && v !== null && typeof (v as JobReport).seq === "number" && Array.isArray((v as JobReport).jobs) | | 66 | +} | | 67 | + | | 68 | +export function createJobTracker(storage?: StorageLike): JobTracker { | | 69 | + const mem = new Map<string, JobReport>() | | 70 | + const key = (id: string) => JOBS_STORAGE_PREFIX + id | | 71 | + | | 72 | + async function stored(sessionID: string): Promise<{ readable: boolean; report?: JobReport }> { | | 73 | + if (!storage) return { readable: false } | | 74 | + try { | | 75 | + const v = await storage.get(key(sessionID)) | | 76 | + return { readable: true, report: isReport(v) ? v : undefined } | | 77 | + } catch { | | 78 | + return { readable: false } | | 79 | + } | | 80 | + } | | 81 | + | | 82 | + async function write(sessionID: string, report: JobReport) { | | 83 | + mem.set(sessionID, report) | | 84 | + if (!storage) return | | 85 | + try { | | 86 | + await storage.set(key(sessionID), JSON.parse(JSON.stringify(report))) | | 87 | + } catch { | | 88 | + // best effort: this instance's memory still has it | | 89 | + } | | 90 | + } | | 91 | + | | 92 | + async function read(sessionID: string): Promise<JobReport | undefined> { | | 93 | + const local = mem.get(sessionID) | | 94 | + const s = await stored(sessionID) | | 95 | + if (s.readable && !s.report) { | | 96 | + mem.delete(sessionID) | | 97 | + return undefined | | 98 | + } | | 99 | + const best = !s.report ? local : !local || s.report.seq >= local.seq ? s.report : local | | 100 | + return best ? structuredClone(best) : undefined | | 101 | + } | | 102 | + | | 103 | + return { | | 104 | + async open(sessionID) { | | 105 | + await write(sessionID, { seq: 0, jobs: [] }) | | 106 | + }, | | 107 | + async report(sessionID, jobs, live) { | | 108 | + const prev = live && mem.has(sessionID) ? mem.get(sessionID) : await read(sessionID) | | 109 | + if (!prev) return // not a running agent's child any more (or never opened) | | 110 | + if (!jobs.length && !prev.jobs.length) return // nothing new | | 111 | + await write(sessionID, { seq: prev.seq + 1, jobs }) | | 112 | + }, | | 113 | + read, | | 114 | + async close(sessionID) { | | 115 | + mem.delete(sessionID) | | 116 | + if (!storage) return | | 117 | + try { | | 118 | + await storage.remove(key(sessionID)) | | 119 | + } catch { | | 120 | + // best effort | | 121 | + } | | 122 | + }, | | 123 | + } | | 124 | +} |
|