Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.<type>.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.
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/config/subagent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.<name>.model: "inherit" (the main agent\'s model, the default), "small" (small_model) or "provider/model"',
Expand Down
39 changes: 39 additions & 0 deletions packages/opencode/specs/background-subagents.md
Original file line number Diff line number Diff line change
@@ -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 |
12 changes: 12 additions & 0 deletions packages/opencode/src/background/enabled.ts
Original file line number Diff line number Diff line change
@@ -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
}
31 changes: 31 additions & 0 deletions packages/opencode/src/background/list.ts
Original file line number Diff line number Diff line change
@@ -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<string, any>
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))
}
5 changes: 4 additions & 1 deletion packages/opencode/src/cli/cmd/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand All @@ -907,7 +910,7 @@ export const RunCommand = effectCmd({
initialInput,
createSession: createFreshSession,
thinking,
backgroundSubagents: flags.experimentalBackgroundSubagents,
backgroundSubagents,
demo: args.demo,
})
} catch (error) {
Expand Down
4 changes: 3 additions & 1 deletion packages/opencode/src/cli/cmd/run/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -739,12 +739,14 @@ export async function runInteractiveLocalMode(input: RunLocalInput): Promise<voi
directory: input.directory,
})
let session: Promise<ResolvedSession> | 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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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"),
Expand Down
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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"
Expand All @@ -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* () {
Expand Down Expand Up @@ -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" &&
Expand All @@ -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()
})
Expand All @@ -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)
}),
)
Loading
Loading