From 13fc765e93114956e68a2f9d9f9cf52e90ce22b4 Mon Sep 17 00:00:00 2001 From: "petar.minev" <144934217+pminev1@users.noreply.github.com> Date: Thu, 24 Sep 2026 23:27:58 +0300 Subject: [PATCH] feat(XCOD-82): background subagents as a documented setting, /tasks, lifecycle (part 2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Graduated: `"subagent": { "background": true }` (off by default) turns background subagents on; OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS still works as an alias. Every check (task tool, capabilities, session background route, run/local run) goes through backgroundEnabled(). Kept opt-in because upstream still ships it as experimental and its follow-up fixes (#29179, #30790, #31162) were model-behaviour issues. - Monitoring: GET /experimental/background[?sessionID] lists task jobs with status, elapsed, agent, resolved model and rule; POST /experimental/background/{jobID}/cancel cancels through the same run-state path as an abort. TUI /tasks (alias /background) shows the same, refreshes every second, opens a job's child session on Enter, cancels with ctrl+d. - Lifecycle written down in specs/background-subagents.md, with the tests that cover each case: abort cancels recursively, delete cancels, compaction doesn't touch jobs, process exit loses them (registry is process-local) but the child session stays and resumes via task_id. - Parity note against Claude Code in the same spec. Verified in a real terminal (pty, 140x45) against an OpenAI-compatible model server: the main agent launched "General Task (background) — survey repo"; /tasks listed "survey repo general · fake/m running · 21s"; ctrl+d → "Background subagent cancelled", status "cancelled"; Enter opened the child session, whose turn shows "interrupted". Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 6 + packages/core/src/config/subagent.ts | 4 + .../opencode/specs/background-subagents.md | 39 +++ packages/opencode/src/background/enabled.ts | 12 + packages/opencode/src/background/list.ts | 31 +++ packages/opencode/src/cli/cmd/run.ts | 5 +- packages/opencode/src/cli/cmd/run/runtime.ts | 4 +- .../instance/httpapi/groups/experimental.ts | 40 +++ .../instance/httpapi/handlers/experimental.ts | 29 ++- packages/opencode/src/tool/task.ts | 21 +- .../test/server/httpapi-exercise/index.ts | 14 ++ packages/opencode/test/tool/task.test.ts | 74 ++++++ packages/sdk/js/src/v2/gen/sdk.gen.ts | 83 ++++++ packages/sdk/js/src/v2/gen/types.gen.ts | 78 ++++++ packages/sdk/openapi.json | 236 ++++++++++++++++++ packages/tui/src/app.tsx | 11 + .../tui/src/component/dialog-background.tsx | 72 ++++++ packages/tui/src/config/keybind.ts | 2 + packages/web/src/content/docs/agents.mdx | 14 ++ 19 files changed, 761 insertions(+), 14 deletions(-) create mode 100644 packages/opencode/specs/background-subagents.md create mode 100644 packages/opencode/src/background/enabled.ts create mode 100644 packages/opencode/src/background/list.ts create mode 100644 packages/tui/src/component/dialog-background.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 35bd7ff62a54..79a557ceeea1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,12 @@ reasoning behind a change are published separately as **Lunos Notes**. ### Added +- **Background subagents are a documented, opt-in setting:** `"subagent": { "background": true }` + (the old `OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS` still works). `/tasks` in the TUI lists every + background job with its agent, model, status and elapsed time; Enter opens it and `ctrl+d` cancels + it. `GET /experimental/background` and `POST /experimental/background/{id}/cancel` expose the + same list to the app and ACP. What happens on abort, delete, compaction and exit is written down + in `specs/background-subagents.md`. - **Choose which model each subagent uses.** `agent..model` now accepts `"inherit"` and `"small"` as well as `provider/model`. The new `subagent.model` sets a default for every subagent, and `subagent.dynamic` lets the main agent pick a model per task, from a list you allow. diff --git a/packages/core/src/config/subagent.ts b/packages/core/src/config/subagent.ts index 04f41f0117b9..79dce9e888bc 100644 --- a/packages/core/src/config/subagent.ts +++ b/packages/core/src/config/subagent.ts @@ -7,6 +7,10 @@ import { Schema } from "effect" * the live config path keeps it (the XCOD-68 / XCOD-93 lesson). */ export const Info = Schema.Struct({ + background: Schema.Boolean.pipe(Schema.optional).annotate({ + description: + "Allow subagents to run in the background while the main agent keeps working (off by default). Replaces OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS, which still works", + }), model: Schema.String.pipe(Schema.optional).annotate({ description: 'Default model for every subagent without its own agent..model: "inherit" (the main agent\'s model, the default), "small" (small_model) or "provider/model"', diff --git a/packages/opencode/specs/background-subagents.md b/packages/opencode/specs/background-subagents.md new file mode 100644 index 000000000000..0885372f8c9b --- /dev/null +++ b/packages/opencode/specs/background-subagents.md @@ -0,0 +1,39 @@ +# Background subagents: defaults, lifecycle and parity (XCOD-82) + +## On or off + +**Opt-in, through a documented config key:** + +```json +{ "subagent": { "background": true } } +``` + +`OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true` still works, as an alias. + +**Why not on by default:** upstream ships this as experimental. Its follow-up fixes after the feature landed (#27084, 2026-05-14) were all prompt-quality problems: the model polling, sleeping, or asking the task for status while waiting (#29179, #30790, #31162). Those fixes are in Lunos. Whether a given model behaves well is still a per-deployment call, so it's an explicit opt-in. The model only sees the `background` parameter when it's enabled. + +## Watching and cancelling + +- **TUI:** `/tasks` (alias `/background`, or "Background subagents" in the command palette). Each job shows its title, agent, resolved model, status and elapsed time, updated every second. Enter opens the job's child session; `ctrl+d` cancels a running job. +- **Server:** `GET /experimental/background?sessionID=…` returns the same list, for the app and ACP. `POST /experimental/background/{jobID}/cancel` cancels a job. + +## Lifecycle + +| Event | What happens to running background jobs | Where / tested by | +| -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Parent session **aborted** | **Cancelled**, recursively: the job, the child's own jobs, and theirs. | `session/run-state.ts` `cancelBackgroundJobs`; `task.test.ts` "cancelling the parent run cancels running background tasks", "…recursively cancels descendant background tasks" | +| Parent session **deleted** | **Cancelled.** Deleting the child session cancels its job too. | `session/session.ts` `cancelBackgroundJobs` on remove; `task.test.ts` "removing the parent session cancels…", "removing the child task session cancels…" | +| Parent session **compacted** | **Unaffected.** Compaction doesn't touch jobs. When the job finishes, its result arrives in the parent as a new message after the compaction, so it is never summarised away. | `session/compaction.ts` has no job references; result injection: `task.test.ts` "background tasks complete through the background job service" | +| **Process exits** | **Lost, not resumable automatically.** The job registry is process-local by design (`core/src/background-job.ts`), so running work is interrupted and its status is gone. The child session and its transcript so far stay on disk, and the model can continue it with `task_id`. | `core/test/background-job.test.ts` "interrupts live work … after the owning process-local scope closes"; resume: `task.test.ts` "execute resumes an existing task session from task_id" | +| Job **cancelled** from `/tasks` or the route | Same path as aborting the job's own session (`SessionRunState.cancel`), so the job's own descendants stop too. | `task.test.ts` "lists a running background task … then cancels it" | + +## Parity with Claude Code + +| Behaviour | Claude Code | Lunos | On purpose? | +| ------------------------------- | ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | +| Launching a background subagent | The model can run a task in the background | Same, through the task tool's `background: true` | — | +| Result delivery | The main agent is notified when it finishes | Same: the result is injected into the parent session as a new message | — | +| Seeing running work | A task list with status | `/tasks` with status, elapsed time, agent **and resolved model**, plus a server route | Yes: the model column is there because model choice is a residency matter | +| Default | Available | **Opt-in** (`subagent.background`) | Yes, see above | +| Surviving a restart | Not resumed automatically | Not resumed automatically; the child session stays and can be continued with `task_id` | — | +| Model per subagent | Per-agent model in the agent file | Per call (allow-listed), per type, global default, or inherit, all checked against the residency policy before start | Yes | diff --git a/packages/opencode/src/background/enabled.ts b/packages/opencode/src/background/enabled.ts new file mode 100644 index 000000000000..72225e0d7cfb --- /dev/null +++ b/packages/opencode/src/background/enabled.ts @@ -0,0 +1,12 @@ +/** + * Whether background subagents are available (XCOD-82). Opt-in through the documented + * `subagent.background` config key. The old `OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS` + * environment variable still turns it on, so existing setups keep working. + * + * Kept opt-in rather than on by default: upstream still ships it as experimental, and its + * follow-up fixes (#29179, #30790, #31162) were all about the model polling or sleeping while + * waiting for a result. That's a prompt-quality risk worth an explicit choice. + */ +export function backgroundEnabled(flag: boolean, config: { subagent?: { background?: boolean } }) { + return flag || config.subagent?.background === true +} diff --git a/packages/opencode/src/background/list.ts b/packages/opencode/src/background/list.ts new file mode 100644 index 000000000000..d1ea130b0039 --- /dev/null +++ b/packages/opencode/src/background/list.ts @@ -0,0 +1,31 @@ +import type { BackgroundJob } from "./job" + +/** One subagent job as the monitoring surfaces (server route, TUI, app, ACP) show it (XCOD-82). */ +export function toItem(job: BackgroundJob.Info, now = Date.now()) { + const meta = (job.metadata ?? {}) as Record + const model = + meta.model && typeof meta.model === "object" ? `${meta.model.providerID}/${meta.model.modelID}` : undefined + return { + id: job.id, + title: job.title, + status: job.status, + startedAt: job.started_at, + completedAt: job.completed_at, + elapsedMs: (job.completed_at ?? now) - job.started_at, + agent: typeof meta.agent === "string" ? meta.agent : undefined, + model, + modelRule: typeof meta.modelRule === "string" ? meta.modelRule : undefined, + parentSessionID: typeof meta.parentSessionId === "string" ? meta.parentSessionId : undefined, + sessionID: typeof meta.sessionId === "string" ? meta.sessionId : undefined, + error: job.error, + } +} + +/** Task jobs only, newest first, optionally only one parent session's. */ +export function list(jobs: readonly BackgroundJob.Info[], sessionID?: string, now = Date.now()) { + return jobs + .filter((job) => job.type === "task") + .filter((job) => !sessionID || job.metadata?.parentSessionId === sessionID) + .toSorted((a, b) => b.started_at - a.started_at) + .map((job) => toItem(job, now)) +} diff --git a/packages/opencode/src/cli/cmd/run.ts b/packages/opencode/src/cli/cmd/run.ts index eb825106772d..9cc491825abc 100644 --- a/packages/opencode/src/cli/cmd/run.ts +++ b/packages/opencode/src/cli/cmd/run.ts @@ -890,6 +890,9 @@ export const RunCommand = effectCmd({ } const model = pick(args.model) + // The server answers from `subagent.background` config or the old env flag (XCOD-82). + const capabilities = await client.experimental.capabilities.get().catch(() => undefined) + const backgroundSubagents = capabilities?.data?.backgroundSubagents ?? flags.experimentalBackgroundSubagents const { runInteractiveMode } = await import("./run/runtime") try { await runInteractiveMode({ @@ -907,7 +910,7 @@ export const RunCommand = effectCmd({ initialInput, createSession: createFreshSession, thinking, - backgroundSubagents: flags.experimentalBackgroundSubagents, + backgroundSubagents, demo: args.demo, }) } catch (error) { diff --git a/packages/opencode/src/cli/cmd/run/runtime.ts b/packages/opencode/src/cli/cmd/run/runtime.ts index 90cddffa2222..910b183cf17a 100644 --- a/packages/opencode/src/cli/cmd/run/runtime.ts +++ b/packages/opencode/src/cli/cmd/run/runtime.ts @@ -739,12 +739,14 @@ export async function runInteractiveLocalMode(input: RunLocalInput): Promise | undefined + // The server answers from `subagent.background` config or the old env flag (XCOD-82). + const capabilities = await sdk.experimental.capabilities.get().catch(() => undefined) return runInteractiveRuntime({ files: input.files, initialInput: input.initialInput, thinking: input.thinking, - backgroundSubagents: input.backgroundSubagents, + backgroundSubagents: capabilities?.data?.backgroundSubagents ?? input.backgroundSubagents, replay: input.replay, replayLimit: input.replayLimit, demo: input.demo, diff --git a/packages/opencode/src/server/routes/instance/httpapi/groups/experimental.ts b/packages/opencode/src/server/routes/instance/httpapi/groups/experimental.ts index 52c714a5ae64..b0d85477ae25 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/groups/experimental.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/groups/experimental.ts @@ -29,6 +29,22 @@ const CapabilitiesResponse = Schema.Struct({ backgroundSubagents: Schema.Boolean, }).annotate({ identifier: "ExperimentalCapabilities" }) +// XCOD-82: one background subagent job, as the monitoring surfaces show it. +export const BackgroundJobItem = Schema.Struct({ + id: Schema.String, + title: Schema.optional(Schema.String), + status: Schema.Literals(["running", "completed", "error", "cancelled"]), + startedAt: Schema.Number, + completedAt: Schema.optional(Schema.Number), + elapsedMs: Schema.Number, + agent: Schema.optional(Schema.String), + model: Schema.optional(Schema.String), + modelRule: Schema.optional(Schema.String), + parentSessionID: Schema.optional(Schema.String), + sessionID: Schema.optional(Schema.String), + error: Schema.optional(Schema.String), +}).annotate({ identifier: "BackgroundJobItem" }) + const ConsoleOrgOption = Schema.Struct({ accountID: Schema.String, accountEmail: Schema.String, @@ -98,6 +114,8 @@ export const ExperimentalPaths = { worktreeReset: "/experimental/worktree/reset", session: "/experimental/session", sessionBackground: "/experimental/session/:sessionID/background", + backgroundJobs: "/experimental/background", + backgroundJobCancel: "/experimental/background/:jobID/cancel", resource: "/experimental/resource", } as const @@ -245,6 +263,28 @@ export const ExperimentalApi = HttpApi.make("experimental") "Detach any synchronous subagents currently blocking the session and continue them in the background.", }), ), + HttpApiEndpoint.get("backgroundJobs", ExperimentalPaths.backgroundJobs, { + query: Schema.Struct({ ...WorkspaceRoutingQueryFields, sessionID: Schema.optional(Schema.String) }), + success: described(Schema.Array(BackgroundJobItem), "Background subagent jobs"), + }).annotateMerge( + OpenApi.annotations({ + identifier: "experimental.background.list", + summary: "List background subagents", + description: + "List subagent jobs with status, elapsed time, agent and resolved model. Pass sessionID to list only that session's jobs.", + }), + ), + HttpApiEndpoint.post("backgroundJobCancel", ExperimentalPaths.backgroundJobCancel, { + params: { jobID: Schema.String }, + query: WorkspaceRoutingQuery, + success: described(Schema.Boolean, "Whether a running job was cancelled"), + }).annotateMerge( + OpenApi.annotations({ + identifier: "experimental.background.cancel", + summary: "Cancel a background subagent", + description: "Cancel a running background subagent job and its child session.", + }), + ), HttpApiEndpoint.get("resource", ExperimentalPaths.resource, { query: WorkspaceRoutingQuery, success: described(Schema.Record(Schema.String, MCP.Resource), "MCP resources"), diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/experimental.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/experimental.ts index b218c6040d1e..1cfd5f573279 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/experimental.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/experimental.ts @@ -1,4 +1,6 @@ import { Account } from "@/account/account" +import * as BackgroundList from "@/background/list" +import { backgroundEnabled } from "@/background/enabled" import { Agent } from "@/agent/agent" import { BackgroundJob } from "@/background/job" import { Config } from "@/config/config" @@ -7,7 +9,8 @@ import { RuntimeFlags } from "@/effect/runtime-flags" import { MCP } from "@/mcp" import { Project } from "@/project/project" import { Session } from "@/session/session" -import type { SessionID } from "@/session/schema" +import { SessionID } from "@/session/schema" +import { SessionRunState } from "@/session/run-state" import { ToolJsonSchema } from "@/tool/json-schema" import { ToolRegistry } from "@/tool/registry" import { Worktree } from "@/worktree" @@ -34,10 +37,11 @@ export const experimentalHandlers = HttpApiBuilder.group(InstanceHttpApi, "exper const worktreeSvc = yield* Worktree.Service const sessions = yield* Session.Service const background = yield* BackgroundJob.Service + const runState = yield* SessionRunState.Service const flags = yield* RuntimeFlags.Service const capabilities = Effect.fn("ExperimentalHttpApi.capabilities")(function* () { - return { backgroundSubagents: flags.experimentalBackgroundSubagents } + return { backgroundSubagents: backgroundEnabled(flags.experimentalBackgroundSubagents, yield* config.get()) } }) const getConsole = Effect.fn("ExperimentalHttpApi.console")(function* () { @@ -159,7 +163,7 @@ export const experimentalHandlers = HttpApiBuilder.group(InstanceHttpApi, "exper const sessionBackground = Effect.fn("ExperimentalHttpApi.sessionBackground")(function* (ctx: { params: { sessionID: SessionID } }) { - if (!flags.experimentalBackgroundSubagents) return false + if (!backgroundEnabled(flags.experimentalBackgroundSubagents, yield* config.get())) return false const jobs = (yield* background.list()).filter( (job) => job.type === "task" && @@ -171,6 +175,23 @@ export const experimentalHandlers = HttpApiBuilder.group(InstanceHttpApi, "exper return promoted.some((job) => job !== undefined) }) + // XCOD-82: the list the TUI, app and ACP render. Task jobs only; newest first. + const backgroundJobs = Effect.fn("ExperimentalHttpApi.backgroundJobs")(function* (ctx: { + query: { sessionID?: string } + }) { + return BackgroundList.list(yield* background.list(), ctx.query.sessionID) + }) + + const backgroundJobCancel = Effect.fn("ExperimentalHttpApi.backgroundJobCancel")(function* (ctx: { + params: { jobID: string } + }) { + const job = yield* background.get(ctx.params.jobID) + if (job?.status !== "running") return false + // Same path as aborting the job's own session: cancels the job and its descendants. + yield* runState.cancel(SessionID.make(ctx.params.jobID)) + return true + }) + const resource = Effect.fn("ExperimentalHttpApi.resource")(function* () { return yield* mcp.resources() }) @@ -188,6 +209,8 @@ export const experimentalHandlers = HttpApiBuilder.group(InstanceHttpApi, "exper .handle("worktreeReset", worktreeReset) .handle("session", session) .handle("sessionBackground", sessionBackground) + .handle("backgroundJobs", backgroundJobs) + .handle("backgroundJobCancel", backgroundJobCancel) .handle("resource", resource) }), ) diff --git a/packages/opencode/src/tool/task.ts b/packages/opencode/src/tool/task.ts index 593ecae2c77d..b0f4ba22a04e 100644 --- a/packages/opencode/src/tool/task.ts +++ b/packages/opencode/src/tool/task.ts @@ -14,6 +14,7 @@ import { Config } from "@/config/config" import { Effect, Exit, Schema, Scope } from "effect" import { EffectBridge } from "@/effect/bridge" import { RuntimeFlags } from "@/effect/runtime-flags" +import { backgroundEnabled } from "@/background/enabled" import { Database } from "@opencode-ai/core/database/database" import { Residency } from "@opencode-ai/core/residency" import { ProviderV2 } from "@opencode-ai/core/provider" @@ -127,9 +128,11 @@ export const TaskTool = Tool.define( ) { const cfg = yield* config.get() const runInBackground = params.background === true - if (runInBackground && !flags.experimentalBackgroundSubagents) { + if (runInBackground && !backgroundEnabled(flags.experimentalBackgroundSubagents, cfg)) { return yield* Effect.fail( - new Error("Background subagents require OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true"), + new Error( + 'Background subagents are off. Enable them with "subagent": { "background": true } in your Lunos config.', + ), ) } @@ -246,6 +249,7 @@ export const TaskTool = Tool.define( parentSessionId: ctx.sessionID, sessionId: nextSession.id, model, + agent: next.name, modelRule: resolved.rule, modelSource: resolved.source, @@ -421,17 +425,16 @@ export const TaskTool = Tool.define( ) }) + // Tool init can run outside an instance (tests, tool listings), where config isn't + // reachable; fall back to the env flag there. Execution re-checks with live config. + const initialConfig = yield* config.get().pipe(Effect.catchCause(() => Effect.succeed({}))) + const backgroundOn = backgroundEnabled(flags.experimentalBackgroundSubagents, initialConfig) return { - description: flags.experimentalBackgroundSubagents - ? [DESCRIPTION, BACKGROUND_DESCRIPTION].join("\n\n") - : DESCRIPTION, + description: backgroundOn ? [DESCRIPTION, BACKGROUND_DESCRIPTION].join("\n\n") : DESCRIPTION, parameters: Parameters, // `model` is never offered by default; the registry adds it, as an enum of the allowed models, // only when subagent.dynamic is enabled (withModelParameter). - jsonSchema: withModelParameter( - ToolJsonSchema.fromSchema(flags.experimentalBackgroundSubagents ? Parameters : BaseParameters), - [], - ), + jsonSchema: withModelParameter(ToolJsonSchema.fromSchema(backgroundOn ? Parameters : BaseParameters), []), execute: (params: Schema.Schema.Type, ctx: Tool.Context) => run(params, ctx).pipe(Effect.orDie), } diff --git a/packages/opencode/test/server/httpapi-exercise/index.ts b/packages/opencode/test/server/httpapi-exercise/index.ts index 33d17ce4a9b4..e47617b473d7 100644 --- a/packages/opencode/test/server/httpapi-exercise/index.ts +++ b/packages/opencode/test/server/httpapi-exercise/index.ts @@ -593,6 +593,20 @@ const scenarios: Scenario[] = [ .json(200, (body) => { check(body === false, "background route should be a no-op without running subagents") }), + http.protected.get("/experimental/background", "experimental.background.list").json(200, (body) => { + array(body) + check(body.length === 0, "no background jobs should exist in a fresh instance") + }), + http.protected + .post("/experimental/background/{jobID}/cancel", "experimental.background.cancel") + .mutating() + .at((ctx) => ({ + path: route("/experimental/background/{jobID}/cancel", { jobID: "ses_missing" }), + headers: ctx.headers(), + })) + .json(200, (body) => { + check(body === false, "cancelling an unknown job should be a no-op") + }), http.protected.get("/experimental/resource", "experimental.resource.list").json(), http.protected .post("/sync/history", "sync.history.list") diff --git a/packages/opencode/test/tool/task.test.ts b/packages/opencode/test/tool/task.test.ts index 42f46fd35d7e..6fadf472ec18 100644 --- a/packages/opencode/test/tool/task.test.ts +++ b/packages/opencode/test/tool/task.test.ts @@ -1,4 +1,5 @@ import { afterEach, describe, expect } from "bun:test" +import * as BackgroundList from "@/background/list" import { SessionV1 } from "@opencode-ai/core/v1/session" import { Database } from "@opencode-ai/core/database/database" import { LayerNode } from "@opencode-ai/core/effect/layer-node" @@ -652,6 +653,37 @@ describe("tool.task", () => { }, ) + // XCOD-82: the documented config key turns background subagents on without the env flag. + it.instance( + "subagent.background in config enables background execution without the env flag", + () => + Effect.gen(function* () { + const { chat, assistant } = yield* seed() + const tool = yield* TaskTool + const def = yield* tool.init() + const result = yield* def.execute( + { + description: "inspect bug", + prompt: "look into the cache key path", + subagent_type: "general", + background: true, + }, + { + sessionID: chat.id, + messageID: assistant.id, + agent: "build", + abort: new AbortController().signal, + extra: { promptOps: { ...stubOps(), prompt: () => Effect.never } satisfies TaskPromptOps }, + messages: [], + metadata: () => Effect.void, + ask: () => Effect.void, + }, + ) + expect(result.metadata).toMatchObject({ background: true }) + }), + { config: { subagent: { background: true } } }, + ) + it.instance("rejects background execution when the experiment is disabled", () => Effect.gen(function* () { const { chat, assistant } = yield* seed() @@ -971,6 +1003,48 @@ describe("tool.task", () => { }), ) + // XCOD-82: what the monitoring route lists for a running job, and cancelling it through the + // same run-state path the cancel route uses. + background.instance("lists a running background task with agent and resolved model, then cancels it", () => + Effect.gen(function* () { + const jobs = yield* BackgroundJob.Service + const runState = yield* SessionRunState.Service + const { chat, assistant } = yield* seed() + const tool = yield* TaskTool + const def = yield* tool.init() + const result = yield* def.execute( + { description: "inspect bug", prompt: "look", subagent_type: "general", background: true }, + { + sessionID: chat.id, + messageID: assistant.id, + agent: "build", + abort: new AbortController().signal, + extra: { promptOps: { ...stubOps(), prompt: () => Effect.never } satisfies TaskPromptOps }, + messages: [], + metadata: () => Effect.void, + ask: () => Effect.void, + }, + ) + const listed = BackgroundList.list(yield* jobs.list(), chat.id) + expect(listed).toHaveLength(1) + expect(listed[0]).toMatchObject({ + id: result.metadata.sessionId, + title: "inspect bug", + status: "running", + agent: "general", + modelRule: "inherit", + parentSessionID: chat.id, + }) + expect(listed[0].model).toContain("/") + expect(BackgroundList.list(yield* jobs.list(), "ses_other")).toEqual([]) + + yield* runState.cancel(SessionID.make(result.metadata.sessionId)) + const waited = yield* jobs.wait({ id: result.metadata.sessionId, timeout: 1_000 }) + expect(waited.info?.status).toBe("cancelled") + expect(BackgroundList.list(yield* jobs.list(), chat.id)[0].status).toBe("cancelled") + }), + ) + background.instance("removing the child task session cancels its running background task", () => Effect.gen(function* () { const jobs = yield* BackgroundJob.Service diff --git a/packages/sdk/js/src/v2/gen/sdk.gen.ts b/packages/sdk/js/src/v2/gen/sdk.gen.ts index e98e780e62ae..dd6fd79f83e5 100644 --- a/packages/sdk/js/src/v2/gen/sdk.gen.ts +++ b/packages/sdk/js/src/v2/gen/sdk.gen.ts @@ -29,6 +29,10 @@ import type { EventTuiPromptAppend, EventTuiSessionSelect, EventTuiToastShow, + ExperimentalBackgroundCancelErrors, + ExperimentalBackgroundCancelResponses, + ExperimentalBackgroundListErrors, + ExperimentalBackgroundListResponses, ExperimentalCapabilitiesGetErrors, ExperimentalCapabilitiesGetResponses, ExperimentalConsoleGetErrors, @@ -886,6 +890,80 @@ export class Session extends HeyApiClient { } } +export class Background extends HeyApiClient { + /** + * List background subagents + * + * List subagent jobs with status, elapsed time, agent and resolved model. Pass sessionID to list only that session's jobs. + */ + public list( + parameters?: { + directory?: string + workspace?: string + sessionID?: string + }, + options?: Options, + ) { + const params = buildClientParams( + [parameters], + [ + { + args: [ + { in: "query", key: "directory" }, + { in: "query", key: "workspace" }, + { in: "query", key: "sessionID" }, + ], + }, + ], + ) + return (options?.client ?? this.client).get< + ExperimentalBackgroundListResponses, + ExperimentalBackgroundListErrors, + ThrowOnError + >({ + url: "/experimental/background", + ...options, + ...params, + }) + } + + /** + * Cancel a background subagent + * + * Cancel a running background subagent job and its child session. + */ + public cancel( + parameters: { + jobID: string + directory?: string + workspace?: string + }, + options?: Options, + ) { + const params = buildClientParams( + [parameters], + [ + { + args: [ + { in: "path", key: "jobID" }, + { in: "query", key: "directory" }, + { in: "query", key: "workspace" }, + ], + }, + ], + ) + return (options?.client ?? this.client).post< + ExperimentalBackgroundCancelResponses, + ExperimentalBackgroundCancelErrors, + ThrowOnError + >({ + url: "/experimental/background/{jobID}/cancel", + ...options, + ...params, + }) + } +} + export class Resource extends HeyApiClient { /** * Get MCP resources @@ -1261,6 +1339,11 @@ export class Experimental extends HeyApiClient { return (this._session ??= new Session({ client: this.client })) } + private _background?: Background + get background(): Background { + return (this._background ??= new Background({ client: this.client })) + } + private _resource?: Resource get resource(): Resource { return (this._resource ??= new Resource({ client: this.client })) diff --git a/packages/sdk/js/src/v2/gen/types.gen.ts b/packages/sdk/js/src/v2/gen/types.gen.ts index 71a156c74ba4..cd21b256b8d0 100644 --- a/packages/sdk/js/src/v2/gen/types.gen.ts +++ b/packages/sdk/js/src/v2/gen/types.gen.ts @@ -1656,6 +1656,7 @@ export type ServerConfig = { } export type SubagentConfig = { + background?: boolean model?: string variant?: string dynamic?: { @@ -2271,6 +2272,21 @@ export type GlobalSession = { project: ProjectSummary | null } +export type BackgroundJobItem = { + id: string + title?: string + status: "running" | "completed" | "error" | "cancelled" + startedAt: number | "NaN" | "Infinity" | "-Infinity" | "Infinity" | "-Infinity" | "NaN" + completedAt?: number | "NaN" | "Infinity" | "-Infinity" | "Infinity" | "-Infinity" | "NaN" + elapsedMs: number | "NaN" | "Infinity" | "-Infinity" | "Infinity" | "-Infinity" | "NaN" + agent?: string + model?: string + modelRule?: string + parentSessionID?: string + sessionID?: string + error?: string +} + export type McpResource = { name: string uri: string @@ -7923,6 +7939,68 @@ export type ExperimentalSessionBackgroundResponses = { export type ExperimentalSessionBackgroundResponse = ExperimentalSessionBackgroundResponses[keyof ExperimentalSessionBackgroundResponses] +export type ExperimentalBackgroundListData = { + body?: never + path?: never + query?: { + directory?: string + workspace?: string + sessionID?: string + } + url: "/experimental/background" +} + +export type ExperimentalBackgroundListErrors = { + /** + * Bad request + */ + 400: BadRequestError +} + +export type ExperimentalBackgroundListError = ExperimentalBackgroundListErrors[keyof ExperimentalBackgroundListErrors] + +export type ExperimentalBackgroundListResponses = { + /** + * Background subagent jobs + */ + 200: Array +} + +export type ExperimentalBackgroundListResponse = + ExperimentalBackgroundListResponses[keyof ExperimentalBackgroundListResponses] + +export type ExperimentalBackgroundCancelData = { + body?: never + path: { + jobID: string + } + query?: { + directory?: string + workspace?: string + } + url: "/experimental/background/{jobID}/cancel" +} + +export type ExperimentalBackgroundCancelErrors = { + /** + * Bad request + */ + 400: BadRequestError +} + +export type ExperimentalBackgroundCancelError = + ExperimentalBackgroundCancelErrors[keyof ExperimentalBackgroundCancelErrors] + +export type ExperimentalBackgroundCancelResponses = { + /** + * Whether a running job was cancelled + */ + 200: boolean +} + +export type ExperimentalBackgroundCancelResponse = + ExperimentalBackgroundCancelResponses[keyof ExperimentalBackgroundCancelResponses] + export type ExperimentalResourceListData = { body?: never path?: never diff --git a/packages/sdk/openapi.json b/packages/sdk/openapi.json index 148bd1796855..97d2386f092a 100644 --- a/packages/sdk/openapi.json +++ b/packages/sdk/openapi.json @@ -1693,6 +1693,135 @@ ] } }, + "/experimental/background": { + "get": { + "tags": ["experimental"], + "operationId": "experimental.background.list", + "parameters": [ + { + "name": "directory", + "in": "query", + "schema": { + "type": "string" + }, + "required": false + }, + { + "name": "workspace", + "in": "query", + "schema": { + "type": "string" + }, + "required": false + }, + { + "name": "sessionID", + "in": "query", + "schema": { + "type": "string" + }, + "required": false + } + ], + "responses": { + "200": { + "description": "Background subagent jobs", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/BackgroundJobItem" + }, + "description": "Background subagent jobs" + } + } + } + }, + "400": { + "description": "Bad request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BadRequestError" + } + } + } + } + }, + "description": "List subagent jobs with status, elapsed time, agent and resolved model. Pass sessionID to list only that session's jobs.", + "summary": "List background subagents", + "x-codeSamples": [ + { + "lang": "js", + "source": "import { createOpencodeClient } from \"@opencode-ai/sdk\n\nconst client = createOpencodeClient()\nawait client.experimental.background.list({\n ...\n})" + } + ] + } + }, + "/experimental/background/{jobID}/cancel": { + "post": { + "tags": ["experimental"], + "operationId": "experimental.background.cancel", + "parameters": [ + { + "name": "jobID", + "in": "path", + "schema": { + "type": "string" + }, + "required": true + }, + { + "name": "directory", + "in": "query", + "schema": { + "type": "string" + }, + "required": false + }, + { + "name": "workspace", + "in": "query", + "schema": { + "type": "string" + }, + "required": false + } + ], + "responses": { + "200": { + "description": "Whether a running job was cancelled", + "content": { + "application/json": { + "schema": { + "type": "boolean", + "description": "Whether a running job was cancelled" + } + } + } + }, + "400": { + "description": "Bad request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BadRequestError" + } + } + } + } + }, + "description": "Cancel a running background subagent job and its child session.", + "summary": "Cancel a background subagent", + "x-codeSamples": [ + { + "lang": "js", + "source": "import { createOpencodeClient } from \"@opencode-ai/sdk\n\nconst client = createOpencodeClient()\nawait client.experimental.background.cancel({\n ...\n})" + } + ] + } + }, "/experimental/resource": { "get": { "tags": ["experimental"], @@ -20580,6 +20709,9 @@ "SubagentConfig": { "type": "object", "properties": { + "background": { + "type": "boolean" + }, "model": { "type": "string" }, @@ -22311,6 +22443,110 @@ "required": ["id", "slug", "projectID", "directory", "title", "version", "time", "project"], "additionalProperties": false }, + "BackgroundJobItem": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "title": { + "type": "string" + }, + "status": { + "type": "string", + "enum": ["running", "completed", "error", "cancelled"] + }, + "startedAt": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": ["NaN"] + }, + { + "type": "string", + "enum": ["Infinity"] + }, + { + "type": "string", + "enum": ["-Infinity"] + }, + { + "type": "string", + "enum": ["Infinity", "-Infinity", "NaN"] + } + ] + }, + "completedAt": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": ["NaN"] + }, + { + "type": "string", + "enum": ["Infinity"] + }, + { + "type": "string", + "enum": ["-Infinity"] + }, + { + "type": "string", + "enum": ["Infinity", "-Infinity", "NaN"] + } + ] + }, + "elapsedMs": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string", + "enum": ["NaN"] + }, + { + "type": "string", + "enum": ["Infinity"] + }, + { + "type": "string", + "enum": ["-Infinity"] + }, + { + "type": "string", + "enum": ["Infinity", "-Infinity", "NaN"] + } + ] + }, + "agent": { + "type": "string" + }, + "model": { + "type": "string" + }, + "modelRule": { + "type": "string" + }, + "parentSessionID": { + "type": "string" + }, + "sessionID": { + "type": "string" + }, + "error": { + "type": "string" + } + }, + "required": ["id", "status", "startedAt", "elapsedMs"], + "additionalProperties": false + }, "McpResource": { "type": "object", "properties": { diff --git a/packages/tui/src/app.tsx b/packages/tui/src/app.tsx index 14b79637662b..c5ef55bf696d 100644 --- a/packages/tui/src/app.tsx +++ b/packages/tui/src/app.tsx @@ -1,4 +1,5 @@ import { render, TimeToFirstDraw, useRenderer, useTerminalDimensions } from "@opentui/solid" +import { DialogBackground } from "./component/dialog-background" import { registerOpencodeSpinner } from "./component/register-spinner" import { createDefaultOpenTuiKeymap } from "@opentui/keymap/opentui" import { Deferred, Effect } from "effect" @@ -571,6 +572,16 @@ function App(props: { onSnapshot?: () => Promise; pluginHost: TuiPlugi dialog.replace(() => ) }, }, + { + name: "background.list", + title: "Background subagents", + category: "Session", + slashName: "tasks", + slashAliases: ["background"], + run: () => { + dialog.replace(() => ) + }, + }, { name: "session.new", title: "New session", diff --git a/packages/tui/src/component/dialog-background.tsx b/packages/tui/src/component/dialog-background.tsx new file mode 100644 index 000000000000..b63c5b0545fd --- /dev/null +++ b/packages/tui/src/component/dialog-background.tsx @@ -0,0 +1,72 @@ +import { createResource, createSignal, onCleanup } from "solid-js" +import { useDialog } from "../ui/dialog" +import { DialogSelect } from "../ui/dialog-select" +import { useSDK } from "../context/sdk" +import { useRoute } from "../context/route" +import { useToast } from "../ui/toast" +import { useTheme } from "../context/theme" + +function elapsed(ms: number) { + const seconds = Math.floor(ms / 1000) + if (seconds < 60) return `${seconds}s` + const minutes = Math.floor(seconds / 60) + if (minutes < 60) return `${minutes}m ${seconds % 60}s` + return `${Math.floor(minutes / 60)}h ${minutes % 60}m` +} + +/** + * Background subagents (XCOD-82): every task job with its status, elapsed time, agent, resolved + * model and title. Enter opens the job's child session; the cancel action stops a running job. + */ +export function DialogBackground() { + const dialog = useDialog() + const sdk = useSDK() + const route = useRoute() + const toast = useToast() + const { theme } = useTheme() + const [tick, setTick] = createSignal(0) + const timer = setInterval(() => setTick((value) => value + 1), 1000) + onCleanup(() => clearInterval(timer)) + + const [jobs, { refetch }] = createResource(tick, async () => { + const result = await sdk.client.experimental.background.list() + return result.data ?? [] + }) + + const options = () => + (jobs() ?? []).map((job) => ({ + title: job.title ?? job.id, + value: job.id, + description: [job.agent, job.model].filter(Boolean).join(" · "), + footer: `${job.status} · ${elapsed(Number(job.elapsedMs))}`, + bg: job.status === "error" ? theme.error : undefined, + sessionID: job.sessionID ?? job.id, + })) + + return ( + { + const job = options().find((item) => item.value === option.value) + dialog.clear() + if (job) route.navigate({ type: "session", sessionID: job.sessionID }) + }} + actions={[ + { + command: "background.cancel", + title: "cancel", + onTrigger: async (option) => { + const result = await sdk.client.experimental.background.cancel({ jobID: String(option.value) }) + toast.show({ + message: result.data ? "Background subagent cancelled" : "That job isn't running", + variant: result.data ? "success" : "info", + }) + await refetch() + }, + }, + ]} + /> + ) +} diff --git a/packages/tui/src/config/keybind.ts b/packages/tui/src/config/keybind.ts index 5bfa4efa9295..7c66954cc479 100644 --- a/packages/tui/src/config/keybind.ts +++ b/packages/tui/src/config/keybind.ts @@ -116,6 +116,7 @@ export const Definitions = { session_quick_switch_9: keybind("9", "Switch to session in quick slot 9"), stash_delete: keybind("ctrl+d", "Delete stash entry"), + background_cancel: keybind("ctrl+d", "Cancel background subagent"), model_provider_list: keybind("ctrl+a", "Open provider list from model dialog"), model_favorite_toggle: keybind("ctrl+f", "Toggle model favorite status"), model_list: keybind("m", "List available models"), @@ -336,6 +337,7 @@ export const CommandMap = { session_quick_switch_8: "session.quick_switch.8", session_quick_switch_9: "session.quick_switch.9", stash_delete: "stash.delete", + background_cancel: "background.cancel", model_provider_list: "model.dialog.provider", model_favorite_toggle: "model.dialog.favorite", model_list: "model.list", diff --git a/packages/web/src/content/docs/agents.mdx b/packages/web/src/content/docs/agents.mdx index 7ce483fae44c..2cbd596f8a04 100644 --- a/packages/web/src/content/docs/agents.mdx +++ b/packages/web/src/content/docs/agents.mdx @@ -399,6 +399,20 @@ The model ID in your Lunos config uses the format `provider/model-id`. For examp --- +### Background subagents + +Subagents can run in the background while the main agent keeps working. This is off by default; turn it on with: + +```json title="opencode.json" +{ "subagent": { "background": true } } +``` + +Then the main agent can launch a task in the background, and its result arrives in the conversation when it finishes. Run `/tasks` to see every background job with its agent, model, status and elapsed time. Press Enter to open a job's session, or `ctrl+d` to cancel a running one. + +Aborting or deleting the parent session cancels its background jobs. Compaction doesn't affect them. If Lunos exits, running jobs stop; the job's session keeps what it did so far and can be continued. Details: `packages/opencode/specs/background-subagents.md`. + +--- + ### Choosing models for subagents Every subagent gets a model from the first of these rules that applies: