diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 88563aeb43492..7fc2d486d506a 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -1751,16 +1751,22 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { returnedRunning(tool.id), ]; }; - const childReport = (inboxID: string, text: string, description = "Sleep") => + const childReport = (inboxID: string, text: string, description = "Sleep", tag = "completed") => event("session.inbox.enqueued", { inboxID, sessionID: SESSION, item: { type: "synthetic", payload: { - text: `\n${text}\n`, + text: `\n${text}\n`, description, - metadata: { source: "subagent", childID: CHILD, agent: "General", state: "completed" }, + // OpenCode tags a report "running" only in the text; its metadata still says completed. + metadata: { + source: "subagent", + childID: CHILD, + agent: "General", + state: tag === "running" ? "completed" : tag, + }, }, delivery: "steer", }, @@ -1773,11 +1779,14 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { const calls = new Map(); const callsById = new Map(); const childTurns = new Map(); + const attached = new Set(); const callsAtChildTurnStart = new Map< string, Record >(); - const state: { roster: ReadonlyArray | undefined } = { roster: undefined }; + const state: { roster: OrchestrationV2ProviderThread["pendingBackgroundTasks"] } = { + roster: undefined, + }; let wake = yield* Deferred.make(); yield* runtime.events.pipe( Stream.tap((event) => @@ -1793,6 +1802,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { status: event.subagent.status, result: event.subagent.result, }); + if (event.subagent.childThreadId !== null) attached.add(event.subagent.title); } if (event.type === "provider_thread.updated" && event.providerThread.id === thread.id) { state.roster = event.providerThread.pendingBackgroundTasks; @@ -1826,7 +1836,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { yield* until(check); }); }); - return { calls, callsById, callsAtChildTurnStart, childTurns, state, until }; + return { calls, callsById, callsAtChildTurnStart, childTurns, attached, state, until }; }); const launchedAndRunning = [ ...backgroundLaunch(CHILD), @@ -2152,6 +2162,569 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); + const childStep = (run: number) => + event("session.step.started", { + sessionID: CHILD, + assistantMessageID: `msg_child_${run}`, + agent: "general", + model: { id: "big-pickle", providerID: "opencode", variant: "default" }, + started: 1, + }); + const settled = (status: string | undefined) => status !== undefined && status !== "running"; + const STARTED = "TESTS_STARTED\n\nBackground work still running:\n- shell (sh_tests): npm test"; + // The child goes idle with its own work running, and OpenCode reports it as running. + const reportedRunning = [ + ...launchedAndRunning, + childSaid("TESTS_STARTED"), + event("session.execution.succeeded", { sessionID: CHILD }), + event("session.execution.succeeded", { sessionID: SESSION }), + childReport("msg_report_1", STARTED, "Sleep", "running"), + ]; + const finished = (labelled = false): ReadonlyArray => [ + event("session.execution.started", { sessionID: CHILD }), + childStep(2), + childSaid("TESTS_PASSED", 2), + event("session.execution.succeeded", { sessionID: CHILD }), + { ...childReport("msg_report_2", "TESTS_PASSED"), ...(labelled ? { label: "final" } : {}) }, + ]; + + it.effect( + "keeps a background subagent pending while its report says its own work still runs", + () => + Effect.gen(function* () { + const gate = makeProviderReplayGate(["final"]); + const { runtime, thread } = yield* resumed([...reportedRunning, ...finished(true)], { + replayGate: gate, + }); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + assert.isTrue(yield* Effect.promise(() => gate.waitForReached("final"))); + yield* watch.until(() => watch.childTurns.get(`${CHILD}:turn:2`) === "completed"); + assert.deepEqual(watch.calls.get("Sleep"), { status: "running", result: null }); + assert.deepEqual( + watch.state.roster?.map((task) => task.taskId), + ["call-background"], + ); + assert.isTrue(yield* runtime.hasPendingBackgroundWorkForThread!(thread)); + gate.release("final"); + yield* watch.until( + () => + watch.calls.get("Sleep")?.status === "completed" && watch.state.roster?.length === 0, + ); + assert.deepEqual(watch.calls.get("Sleep"), { status: "completed", result: "TESTS_PASSED" }); + }), + ); + + it.effect( + "settles a subagent kept by a running report when its next busy period writes nothing", + () => + Effect.gen(function* () { + const gate = makeProviderReplayGate(["idle"]); + const { runtime, thread } = yield* resumed( + [ + ...reportedRunning, + event("session.execution.started", { sessionID: CHILD }), + event("session.execution.succeeded", { sessionID: CHILD }, "idle"), + ], + { replayGate: gate }, + ); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + assert.isTrue(yield* Effect.promise(() => gate.waitForReached("idle"))); + yield* watch.until(() => watch.childTurns.get(`${CHILD}:turn:2`) === "running"); + assert.deepEqual(watch.calls.get("Sleep"), { status: "running", result: null }); + gate.release("idle"); + yield* watch.until( + () => + watch.calls.get("Sleep")?.status === "completed" && watch.state.roster?.length === 0, + ); + assert.deepEqual(watch.calls.get("Sleep"), { + status: "completed", + result: "TESTS_STARTED", + }); + }), + ); + + const reconnectedWithChildActive = [ + { type: "runtime_exit", status: "success" } as const, + out("event.subscribe"), + out("session.active"), + replyData("session.active", { [CHILD]: { type: "running" } }), + out("permission.list", { sessionID: CHILD }), + replyData("permission.list", []), + out("session.form.list", { sessionID: CHILD }), + replyData("session.form.list", []), + ]; + it.effect.each([ + { + name: "spans a reconnect", + replay: [ + event("session.execution.started", { sessionID: CHILD }), + ...reconnectedWithChildActive, + ], + }, + { name: "starts while the stream is down", replay: reconnectedWithChildActive }, + ])("settles a kept subagent whose quiet busy period $name", ({ replay }) => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed([ + ...reportedRunning, + ...replay, + event("session.execution.succeeded", { sessionID: CHILD }), + ]); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until( + () => settled(watch.calls.get("Sleep")?.status) && watch.state.roster?.length === 0, + ); + assert.deepEqual(watch.calls.get("Sleep"), { status: "completed", result: "TESTS_STARTED" }); + }), + ); + + it.effect("settles a call that joined a kept subagent with the subagent's last report", () => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed([ + ...launchedAndRunning, + childSaid("TESTS_STARTED"), + event("session.execution.succeeded", { sessionID: CHILD }), + childReport("msg_report_1", STARTED, "Sleep", "running"), + ...callAgain({ background: true }), + event("session.execution.succeeded", { sessionID: SESSION }), + event("session.execution.started", { sessionID: CHILD }), + childStep(2), + childSaid("ALSO_DONE", 2), + event("session.execution.succeeded", { sessionID: CHILD }), + childReport( + "msg_report_2", + "ALSO_DONE\n\nBackground work still running:\n- shell (sh_tests): npm test", + "Again", + "running", + ), + event("session.execution.started", { sessionID: CHILD }), + childStep(3), + childSaid("TESTS_PASSED", 3), + event("session.execution.succeeded", { sessionID: CHILD }), + childReport("msg_report_3", "TESTS_PASSED", "Again"), + ]); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until( + () => + ["Sleep", "Again"].every((title) => settled(watch.calls.get(title)?.status)) && + watch.state.roster?.length === 0, + ); + assert.deepEqual(Object.fromEntries(watch.calls), { + Sleep: { status: "completed", result: "TESTS_PASSED" }, + Again: { status: "completed", result: "TESTS_PASSED" }, + }); + }), + ); + + it.effect("settles a call whose Stop never reached its child at the child's running report", () => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed([ + ...backgroundLaunch(CHILD), + out("session.interrupt", { sessionID: CHILD }), + reply("session.interrupt", { status: 500, body: {} }), + out("session.interrupt", { sessionID: SESSION }), + reply("session.interrupt", { interrupted: true }), + event("session.execution.interrupted", { sessionID: SESSION }), + childReport("msg_report_1", STARTED, "Sleep", "running"), + ]); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until(() => watch.attached.has("Sleep")); + yield* runtime.interruptTurn({ + providerThread: thread, + providerTurnId: yield* providerTurnId, + requestRuntimeRestart: true, + }); + yield* watch.until(() => settled(watch.calls.get("Sleep")?.status)); + assert.equal(watch.calls.get("Sleep")?.status, "interrupted"); + }), + ); + + it.effect("settles a completed report whose description quotes a running state", () => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed([ + ...launchedAndRunning, + childSaid("DONE"), + event("session.execution.succeeded", { sessionID: CHILD }), + event("session.execution.succeeded", { sessionID: SESSION }), + childReport("msg_report_1", "DONE", 'Review state="running" fix'), + ]); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until( + () => settled(watch.calls.get("Sleep")?.status) && watch.state.roster?.length === 0, + ); + assert.deepEqual(watch.calls.get("Sleep"), { status: "completed", result: "DONE" }); + }), + ); + + it.effect("matches a report of a run that wrote no text to that run", () => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed([ + ...launchedAndRunning, + ...callAgain({ background: true }), + childSaid("FIRST_OK"), + event("session.execution.succeeded", { sessionID: CHILD }), + ...callAgain({ background: true }, { id: "call-later", writesRules: false }), + event("session.execution.started", { sessionID: CHILD }), + childStep(2), + event("session.execution.succeeded", { sessionID: CHILD }), + event("session.execution.succeeded", { sessionID: SESSION }), + childReport("msg_report_2", "Subagent completed without a text response.", "Again"), + ]); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until( + () => + ["call-background", "call-again", "call-later"].every( + (id) => watch.callsById.get(id)?.status === "completed", + ) && watch.state.roster?.length === 0, + ); + assert.deepEqual(Object.fromEntries(watch.callsById), { + "call-background": { status: "completed", result: "FIRST_OK" }, + "call-again": { status: "completed", result: "FIRST_OK" }, + "call-later": { + status: "completed", + result: "Subagent completed without a text response.", + }, + }); + }), + ); + + const GRAND = "ses_f1485c529ffeGrandchild00000"; + const grand = { sessionID: CHILD, assistantMessageID: "msg_child_grand", id: "call-grand" }; + const running = (body: string) => + `${body}\n\nBackground work still running:\n- shell (sh_tests): npm test`; + // The child and its own background subagent both report while the grandchild's work runs. + const keptChain = [ + ...launchedAndRunning, + event("session.tool.input.started", { ...grand, name: "subagent" }), + event("session.tool.called", { + ...grand, + name: "subagent", + input: { description: "Grand", prompt: "test", background: true }, + executed: false, + }), + event("session.created", { ...childCreated(GRAND), parentID: CHILD, title: "Grand" }), + event("session.tool.progress", { ...grand, metadata: { sessionID: GRAND, status: "running" } }), + event("session.tool.success", { + ...grand, + content: [{ type: "text", text: "The subagent is working in the background." }], + metadata: { sessionID: GRAND, status: "running" }, + executed: true, + }), + event("session.execution.started", { sessionID: GRAND }), + childSaid("CHILD_STARTED"), + event("session.execution.succeeded", { sessionID: CHILD }), + event("session.execution.succeeded", { sessionID: SESSION }), + childReport("msg_report_1", running("CHILD_STARTED"), "Sleep", "running"), + event("session.text.ended", { + sessionID: GRAND, + assistantMessageID: "msg_grand_1", + ordinal: 0, + text: "GRAND_STARTED", + }), + event("session.execution.succeeded", { sessionID: GRAND }), + event("session.inbox.enqueued", { + inboxID: "msg_grand_report", + sessionID: CHILD, + item: { + type: "synthetic", + payload: { + text: `\n${running("GRAND_STARTED")}\n`, + description: "Grand", + metadata: { source: "subagent", childID: GRAND, agent: "General", state: "completed" }, + }, + delivery: "steer", + }, + }), + event("session.execution.started", { sessionID: CHILD }), + childStep(2), + childSaid("CHILD_WAITING", 2), + event("session.execution.succeeded", { sessionID: CHILD }), + childReport("msg_report_2", running("CHILD_WAITING"), "Sleep", "running"), + ]; + const settledChain = (replay: ReadonlyArray) => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed(replay); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until( + () => + ["Sleep", "Grand"].every((title) => watch.calls.get(title)?.status === "completed") && + watch.state.roster?.length === 0, + ); + assert.deepEqual(Object.fromEntries(watch.calls), { + Sleep: { status: "completed", result: "CHILD_WAITING" }, + Grand: { status: "completed", result: "GRAND_STARTED" }, + }); + }); + + it.effect("releases kept subagents up a chain when the deepest one's work ends quietly", () => + settledChain([ + ...keptChain, + event("session.execution.started", { sessionID: GRAND }), + event("session.execution.succeeded", { sessionID: GRAND }), + ]), + ); + + it.effect("releases a kept subagent above one whose turn failed without a report", () => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed([ + ...keptChain, + event("session.execution.started", { sessionID: GRAND }), + event("session.execution.failed", { + sessionID: GRAND, + error: { type: "unknown", message: "quota" }, + }), + ]); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until( + () => + ["Sleep", "Grand"].every((title) => settled(watch.calls.get(title)?.status)) && + watch.state.roster?.length === 0, + ); + assert.equal(watch.calls.get("Grand")?.status, "failed"); + assert.deepEqual(watch.calls.get("Sleep"), { status: "completed", result: "CHILD_WAITING" }); + }), + ); + + it.effect("after a reconnect, settles a chain of kept subagents whose work all ended", () => + settledChain([ + ...keptChain, + { type: "runtime_exit", status: "success" } as const, + out("event.subscribe"), + out("session.active"), + replyData("session.active", {}), + ]), + ); + + const grandMessage = { + type: "synthetic", + text: `\nGRAND_OK\n`, + description: "Grand", + metadata: { source: "subagent", childID: GRAND, agent: "General", state: "completed" }, + }; + // A report no call here waits for; it only opens the child's next busy period. + const grandReport = event("session.inbox.enqueued", { + inboxID: "msg_grand_report", + sessionID: CHILD, + item: { + type: "synthetic", + payload: { + text: grandMessage.text, + description: grandMessage.description, + metadata: grandMessage.metadata, + }, + delivery: "steer", + }, + }); + it.effect( + "releases a subagent a reconnect kept for a grandchild whose own call had settled", + () => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed([ + ...keptChain, + event("session.inbox.enqueued", { + inboxID: "msg_grand_final", + sessionID: CHILD, + item: { + type: "synthetic", + payload: { + text: `\nGRAND_DONE\n`, + description: "Grand", + metadata: { + source: "subagent", + childID: GRAND, + agent: "General", + state: "completed", + }, + }, + delivery: "steer", + }, + }), + event("session.execution.started", { sessionID: GRAND }), + { type: "runtime_exit", status: "success" } as const, + out("event.subscribe"), + out("session.active"), + replyData("session.active", { [GRAND]: { type: "running" } }), + out("permission.list", { sessionID: GRAND }), + replyData("permission.list", []), + out("session.form.list", { sessionID: GRAND }), + replyData("session.form.list", []), + event("session.execution.succeeded", { sessionID: GRAND }), + ]); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until( + () => settled(watch.calls.get("Sleep")?.status) && watch.state.roster?.length === 0, + ); + assert.deepEqual(Object.fromEntries(watch.calls), { + Sleep: { status: "completed", result: "CHILD_WAITING" }, + Grand: { status: "completed", result: "GRAND_DONE" }, + }); + }), + ); + + const jobsBelow = (...jobs: ReadonlyArray<{ kind: string; status: string }>) => ({ + data: jobs.map((job, index) => ({ ...job, id: `job_${index}`, sessionID: CHILD })), + }); + it.effect.each([ + { + name: "a Code Mode script still runs below it", + listed: jobsBelow({ kind: "codemode", status: "running" }), + result: "TESTS_PASSED", + }, + { + name: "its quiet busy period ended unseen while a Code Mode script still runs", + listed: jobsBelow({ kind: "codemode", status: "running" }), + result: "TESTS_PASSED", + cut: true, + }, + { + name: "OpenCode lists only a stored subagent job below it", + listed: jobsBelow({ kind: "subagent", status: "running" }), + result: "TESTS_STARTED", + }, + { + name: "OpenCode's job list can't be read", + listed: { status: 500, body: {} }, + result: "TESTS_STARTED", + }, + ])( + "after a reconnect, judges a kept subagent by OpenCode's jobs when $name", + ({ listed, result, cut = false }) => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed( + [ + ...reportedRunning, + ...(cut ? [grandReport, event("session.execution.started", { sessionID: CHILD })] : []), + { type: "runtime_exit", status: "success" } as const, + out("event.subscribe"), + out("rpc.call", ""), + out("rpc.call", ""), + reply("rpc.call", { output: null }), + reply("rpc.call", { output: null }), + out("job.list", { sessionID: SESSION, kind: "shell", descendants: "true" }), + reply("job.list", { data: [] }), + out("job.list", { sessionID: CHILD, kind: "shell", descendants: "true" }), + reply("job.list", { data: [] }), + out("session.active"), + replyData("session.active", {}), + ...(cut + ? [ + out("message.list", { sessionID: CHILD, order: "desc", limit: "50" }), + reply("message.list", { + data: [ + { + id: "msg_idle_2", + time: { created: 4 }, + type: "idle", + outcome: "succeeded", + }, + { ...grandMessage, id: "msg_grand_report", time: { created: 3 } }, + ], + cursor: {}, + }), + ] + : []), + out("job.list", { sessionID: CHILD, descendants: "true" }), + reply("job.list", listed), + // The reconnect has finished before this arrives; only a call it kept takes it. + childReport("msg_report_2", "TESTS_PASSED"), + ], + { version: "2.2.6" }, + ); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until(() => settled(watch.calls.get("Sleep")?.status)); + assert.deepEqual(watch.calls.get("Sleep"), { status: "completed", result }); + }), + ); + + it.effect( + "after a reconnect, settles a kept subagent whose session holds only an unread report", + () => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed([ + ...reportedRunning, + event("session.inbox.enqueued", { + inboxID: "msg_grand_report", + sessionID: CHILD, + item: { + type: "synthetic", + payload: { + text: `\nGRAND_OK\n`, + description: "Grand", + metadata: { + source: "subagent", + childID: GRAND, + agent: "General", + state: "completed", + }, + }, + delivery: "steer", + }, + }), + { type: "runtime_exit", status: "success" } as const, + out("event.subscribe"), + out("session.active"), + replyData("session.active", {}), + ]); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until(() => settled(watch.calls.get("Sleep")?.status)); + assert.deepEqual(watch.calls.get("Sleep"), { + status: "completed", + result: "TESTS_STARTED", + }); + }), + ); + + it.effect.each([ + { name: "nothing runs below it", active: {}, result: "TESTS_STARTED" }, + { + name: "its child runs again", + active: { [CHILD]: { type: "running" } }, + result: "TESTS_PASSED", + }, + ])( + "after a reconnect, settles a subagent kept by a running report only when $name", + ({ active, result }) => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed([ + ...reportedRunning, + { type: "runtime_exit", status: "success" } as const, + out("event.subscribe"), + out("session.active"), + replyData("session.active", active), + ...(CHILD in active + ? [ + out("permission.list", { sessionID: CHILD }), + replyData("permission.list", []), + out("session.form.list", { sessionID: CHILD }), + replyData("session.form.list", []), + // Its end without a turn here would release the call on its own. + childStep(2), + childSaid("TESTS_PASSED", 2), + childReport("msg_report_2", "TESTS_PASSED"), + ] + : []), + ]); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until(() => { + const status = watch.calls.get("Sleep")?.status; + return status !== undefined && status !== "running" && watch.state.roster?.length === 0; + }); + assert.deepEqual(watch.calls.get("Sleep"), { status: "completed", result }); + }), + ); + const MIDDLE = "ses_middle0000000000000000000"; const DEEP = "ses_grandchild00000000000000"; const toolOf = (session: string, id: string) => ({ diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Client.ts b/packages/provider-opencode/src/server/v2/OpenCode2Client.ts index 1cc1190de00dc..9efc2844a4582 100644 --- a/packages/provider-opencode/src/server/v2/OpenCode2Client.ts +++ b/packages/provider-opencode/src/server/v2/OpenCode2Client.ts @@ -91,6 +91,9 @@ const NativeImageJob = Schema.Struct({ const decodeJobs = Schema.decodeUnknownEffect( Schema.Struct({ data: Schema.Array(Schema.Unknown) }), ); +const JobStatuses = Schema.Struct({ + data: Schema.Array(Schema.Struct({ kind: Schema.String, status: Schema.String })), +}); const decodeImageJob = Schema.decodeUnknownOption(NativeImageJob); /** events resolves on subscription acceptance; subscribe before work because the stream is volatile. */ @@ -102,6 +105,10 @@ export interface OpenCode2Api { readonly shellJobs?: ( sessionID: string, ) => Effect.Effect; + /** Running background jobs other than subagents owned by a session or the subagent sessions below it. */ + readonly runningJobs?: ( + sessionID: string, + ) => Effect.Effect; readonly imageJobs: ( sessionID: string, ) => Effect.Effect, OpenCode2ImageError>; @@ -291,6 +298,21 @@ export const make = Effect.gen(function* () { Effect.flatMap(HttpClientResponse.schemaBodyJson(ShellJobs)), ); }), + runningJobs: Effect.fn("OpenCode2Client.runningJobs")(function (sessionID: string) { + return authenticated + .get(`${baseUrl}/api/experimental/job`, { + urlParams: { sessionID, descendants: "true" }, + }) + .pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap(HttpClientResponse.schemaBodyJson(JobStatuses)), + Effect.map( + (page) => + page.data.filter((job) => job.kind !== "subagent" && job.status === "running") + .length, + ), + ); + }), imageJobs: (sessionID: string) => authenticated .get(`${baseUrl}/api/experimental/job`, { diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 9e14f8c4ef36b..8b7ea67595e0c 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -298,6 +298,8 @@ interface SubagentCall { run: number | undefined; /** That turn's last text once it ended, which OpenCode sends as the run's report. */ answer: string | undefined; + /** The output of a report sent while the child's own background work still ran; a later report settles the call. */ + reported: string | undefined; child: ThreadState | undefined; status: OrchestrationV2Subagent["status"]; result: string | null; @@ -605,6 +607,20 @@ const reportOutcome = (state: string | undefined) => const subagentOutput = (text: string) => /^]*>\n?([\s\S]*?)\n?<\/subagent>$/.exec(text.trim())?.[1] ?? text; +// When the child goes idle with its own background work still running, OpenCode keeps "completed" +// in the report's metadata, says "running" only in the tag's state attribute (the description +// attribute after it is not escaped) and appends the list of that work to the body. +const reportsRunningWork = (text: string) => + /^]*?\sstate="([^"]*)"/.exec(text.trimStart())?.[1] === "running"; + +const STILL_RUNNING = "\n\nBackground work still running:\n"; +// OpenCode's report body for a run that ended without text. +const NO_TEXT = "Subagent completed without a text response."; +const withoutRunningWork = (output: string) => { + const at = output.lastIndexOf(STILL_RUNNING); + return at === -1 ? output : output.slice(0, at); +}; + const isContinuation = (turnInput: ProviderAdapter.ProviderAdapterV2TurnInput) => turnInput.message.createdBy === "agent" && turnInput.message.creationSource === "provider"; @@ -1060,9 +1076,12 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr }; let replaying: Wake | undefined; - const owesWork = (state: ThreadState) => + const runsJobs = (state: ThreadState) => [...shells.values()].some((shell) => shell.state === state && shell.running) || - [...state.imageJobs.values()].some((job) => job.status === "running") || + [...state.imageJobs.values()].some((job) => job.status === "running"); + + const owesWork = (state: ThreadState) => + runsJobs(state) || state.wakes.length > 0 || state.reports.size > 0 || (state.subagent !== undefined && busy.has(state.sessionId)) || @@ -2229,6 +2248,25 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr yield* emitSubagent(call); }); + // OpenCode reports a busy period only when it wrote a new answer. A child whose work ended in a + // quiet one never reports again, nor do the idle subagents above it that were waiting on it. + // During a reconnect, reconcile settles kept calls itself once it has read OpenCode's jobs. + let reconciling = false; + const releaseQuiet = Effect.fnUntraced(function* (state: ThreadState) { + if (reconciling) return; + for ( + let current: ThreadState = state; + current.subagent !== undefined; + current = current.subagent.call.state + ) { + if (current.active !== undefined || busy.has(current.sessionId) || hasBackground(current)) + return; + for (const call of callsAttachedTo(current)) { + if (call.reported !== undefined) yield* settleCall(call, "completed", call.reported); + } + } + }); + const startChildTurn = Effect.fnUntraced(function* (child: ThreadState) { const subagent = child.subagent; if (subagent === undefined || child.active !== undefined) return; @@ -2437,6 +2475,16 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr for (const attached of callsAttachedTo(state)) { yield* settleCall(attached, terminal.status, terminal.failure.message); } + // No report follows either, so idle subagents above that were waiting on it are released. + const caller = state.subagent?.call.state; + if (caller !== undefined) yield* releaseQuiet(caller); + } else if ( + terminal.status === "completed" && + turn.answer === undefined && + // A turn that missed events may have written unseen; when unsure, release. + (turn.startedSteps === 0 || turn.missedEvents) + ) { + yield* releaseQuiet(state); } return; } @@ -2818,6 +2866,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr background: false, run: undefined, answer: undefined, + reported: undefined, child: undefined, status: "running", result: null, @@ -3221,10 +3270,19 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const childId = stringField(payload.metadata, "childID"); if (stringField(payload.metadata, "source") !== "subagent" || childId === undefined) return; strays.delete(childId); - const open = [...state.calls.values()].filter( + const outcome = reportOutcome(stringField(payload.metadata, "state")); + const stopped = state.stoppedChildren.has(childId); + const running = outcome === "completed" && !stopped && reportsRunningWork(payload.text); + const output = subagentOutput(payload.text); + const answer = running ? withoutRunningWork(output) : output; + const reporting = [...state.calls.values()].filter( (candidate) => candidate.child?.sessionId === childId, ); - const output = subagentOutput(payload.text); + // Calls an earlier running report kept wait for the child's work, not for one of its runs. + const kept = reporting.filter((candidate) => candidate.reported !== undefined); + const open = reporting.filter((candidate) => candidate.reported === undefined); + const answered = (candidate: SubagentCall) => + candidate.answer === answer || (candidate.answer === undefined && answer === NO_TEXT); const started = open .flatMap((candidate) => candidate.run === undefined ? [] : [{ call: candidate, run: candidate.run }], @@ -3233,9 +3291,9 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr // The report names only the child, and reports arrive in order. So it belongs to the oldest // open run, unless that run ended with a different text: then its own report is lost. const next = started.find( - (candidate) => candidate.call.answer === undefined || candidate.call.answer === output, + (candidate) => candidate.call.answer === undefined || answered(candidate.call), ); - const written = next?.call.answer === output ? next.run : undefined; + const written = next !== undefined && answered(next.call) ? next.run : undefined; const call = written === undefined ? open[0] : next?.call; const calls = call?.run === undefined @@ -3244,19 +3302,19 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const lost = started.flatMap((candidate) => written !== undefined && candidate.run < written ? [candidate.call] : [], ); - const outcome = reportOutcome(stringField(payload.metadata, "state")); + const named = call ?? kept[0]; state.reports.set(inboxId, { inboxId, childId, text: payload.text, report: { kind: "subagent", - label: call?.title ?? stringField(payload.metadata, "description"), - childThreadId: call?.child?.subagent?.appThread.id, - outcome, + label: named?.title ?? stringField(payload.metadata, "description"), + childThreadId: named?.child?.subagent?.appThread.id, + outcome: running ? "updated" : outcome, }, }); - const status = state.stoppedChildren.has(childId) + const status = stopped ? "interrupted" : outcome === "failed" ? "failed" @@ -3264,7 +3322,16 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ? "cancelled" : "completed"; for (const each of lost) yield* settleCall(each, "completed", each.answer); - for (const each of calls) yield* settleCall(each, status, output); + for (const each of calls) { + if (running && each.background) each.reported = answer; + else yield* settleCall(each, status, output); + } + // Calls kept earlier take the child's latest text; a report not tagged running means the + // child went idle with nothing left running. + for (const each of kept) { + if (running) each.reported = answer; + else yield* settleCall(each, status, output); + } }); const holderOf = (sessionId: string) => { @@ -3566,6 +3633,14 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const turn = state.active; if (turn === undefined) { if (started && state.subagent === undefined) return yield* onWake(state); + // A subagent busy period that began while the stream was down ends without a turn here. + if ( + state.subagent !== undefined && + (event.type === "session.execution.succeeded" || + event.type === "session.execution.failed") + ) { + return yield* releaseQuiet(state); + } return; } if (turn.awaitingStart) { @@ -3802,12 +3877,46 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr .withPermit(recoverImages(state).pipe(Effect.timeout(INVENTORY_TIMEOUT))) .pipe(Effect.ignore({ log: true })); } + // OpenCode's running jobs below a kept call other than subagents (shells, Code Mode scripts, + // images): it also lists stored subagent jobs it never closed, and subagents count by their + // sessions. A read that fails or misses the shared deadline counts as none. + const jobsBelow = new Map(); + if ( + compareSemverVersions(connection.version, "2.2.6") >= 0 && + connection.runningJobs !== undefined + ) { + const runningJobs = connection.runningJobs; + const children = new Set( + background.flatMap((state) => + runningCalls(state).flatMap((call) => + call.reported === undefined || call.child === undefined ? [] : [call.child.sessionId], + ), + ), + ); + yield* Effect.forEach( + children, + (child) => + runningJobs(child).pipe( + Effect.tap((jobs) => Effect.sync(() => jobsBelow.set(child, jobs))), + Effect.ignore, + ), + { concurrency: 4, discard: true }, + ).pipe(Effect.timeout(INVENTORY_TIMEOUT), Effect.ignore); + } yield* lock.withPermit( Effect.gen(function* () { for (const state of background) { for (const call of runningCalls(state)) { const child = call.child?.sessionId; - if (child === undefined || !(child in active)) { + if (call.reported !== undefined && call.child !== undefined) { + // Its child already reported; only a session or job still running below it keeps it. + const working = + (jobsBelow.get(call.child.sessionId) ?? 0) > 0 || + sessionsOf(call.child).some( + (session) => session.sessionId in active || runsJobs(session), + ); + if (!working) yield* settleCall(call, "completed", call.reported); + } else if (child === undefined || !(child in active)) { yield* settleCall(call, "interrupted", LOST_BACKGROUND); } } @@ -3905,9 +4014,17 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr } // An owned process's exit, rather than a read deadline, bounds recovery; the bounded retry // below then borrows a restarted server. HTTP waits stay outside the event lock so Stop can still settle. + reconciling = true; + const recovery = reconcile().pipe( + Effect.ensuring( + Effect.sync(() => { + reconciling = false; + }), + ), + ); yield* next.processExit === undefined - ? reconcile().pipe(Effect.timeout(RECONCILE_TIMEOUT)) - : whileAlive(next.processExit, reconcile()); + ? recovery.pipe(Effect.timeout(RECONCILE_TIMEOUT)) + : whileAlive(next.processExit, recovery); return stream; }).pipe( // Borrows and process exits stay bounded; only a live owned process is waited on above.