diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts index 6b3821d991a..3219c2c7647 100644 --- a/packages/core/src/config.ts +++ b/packages/core/src/config.ts @@ -28,11 +28,8 @@ export function latest(entries: readonly Entry[], key: K): } export interface Interface { - /** - * Returns location config documents and discovery sources from lowest to highest priority. With `project: false`, - * leaves out documents found in the location's project directories, keeping what every location shares. - */ - readonly entries: (options?: { readonly project?: boolean }) => Effect.Effect + /** Returns location config documents and discovery sources from lowest to highest priority. */ + readonly entries: () => Effect.Effect /** Compatibility roots consumed by internal compatibility plugins. */ readonly compatibility?: () => Effect.Effect<{ readonly claude: readonly AbsolutePath[] @@ -127,7 +124,6 @@ export const layer = (options?: Options) => const wellknown = yield* WellKnown.Service const processes = yield* AppProcess.Service const integrations = new Map() - const fromProject = new WeakSet() // Integrations set their documents from outside this layer, so their reloads run with its services. const context = yield* Effect.context() const reloadLock = Semaphore.makeUnsafe(1) @@ -307,7 +303,6 @@ export const layer = (options?: Options) => Effect.orDie, Effect.map((entries) => entries.flat()), ) - for (const entry of [...direct, ...projectSupplementary]) fromProject.add(entry) return [ ...managedPolicies, ...integrations.values(), @@ -434,8 +429,8 @@ export const layer = (options?: Options) => ) return Service.of({ - entries: Effect.fnUntraced(function* (options) { - return options?.project === false ? configs.filter((entry) => !fromProject.has(entry)) : configs + entries: Effect.fnUntraced(function* () { + return configs }), compatibility: () => Effect.all({ diff --git a/packages/core/src/session/execution/restart.ts b/packages/core/src/session/execution/restart.ts index 77cdbb60598..e060b83f517 100644 --- a/packages/core/src/session/execution/restart.ts +++ b/packages/core/src/session/execution/restart.ts @@ -3,10 +3,12 @@ export * as SessionRestart from "./restart.js" import { Context, Effect, Layer } from "effect" import { makeGlobalNode } from "@opencode/util/effect/app-node" import { Bus } from "../../bus.js" +import { Database } from "../../database/database.js" import { Job } from "../../job.js" import { Session } from "../../session.js" import { SessionEvent } from "../event.js" import { SessionExecution } from "../execution.js" +import { SessionInbox } from "../inbox.js" import { SessionSchema } from "../schema.js" import { SessionStore } from "../store.js" import { ImageNotice } from "../../image/notice.js" @@ -74,6 +76,7 @@ export const layer = (options?: Options) => const jobs = yield* Job.Service const sessions = yield* Session.Service const queue = yield* SubagentQueue.Service + const db = (yield* Database.Service).db const scope = yield* Effect.scope const maxAttempts = options?.maxAttempts ?? DEFAULT_MAX_ATTEMPTS @@ -200,16 +203,7 @@ export const layer = (options?: Options) => return } if (yield* execution.isActive(recovery.childSessionID)) return - // Only a child whose turn started gets the restart notice and spends a resume attempt. One still waiting - // for a queue slot never claimed a turn, so it just takes its first one. - const started = yield* store.isClaimed(recovery.childSessionID) - if (started && !(yield* prepareResume(recovery.childSessionID))) { - yield* notify({ status: "error", error: RESUME_EXHAUSTED.message }) - return - } - - const run = execution.resume(recovery.childSessionID).pipe( - Effect.andThen(store.context(recovery.childSessionID)), + const output = store.context(recovery.childSessionID).pipe( Effect.map((messages) => { const assistant = messages.findLast( (message) => @@ -218,6 +212,28 @@ export const layer = (options?: Options) => return SubagentCompletion.text(assistant) }), ) + // Only a child whose turn was in flight gets the restart notice and spends a resume attempt. + const started = yield* store.isClaimed(recovery.childSessionID) + if (started && !(yield* prepareResume(recovery.childSessionID))) { + yield* notify({ status: "error", error: RESUME_EXHAUSTED.message }) + return + } + // With no turn in flight and nothing waiting, its turn ended before the job recorded it, and resuming would + // send a conversation that ends on the assistant. Deliver that reply instead. A child with input waiting, + // such as one still in line for a slot, takes its turn below. + if (!started && !(yield* SessionInbox.has(db, recovery.childSessionID, "input"))) { + yield* notify( + yield* output.pipe( + Effect.match({ + onSuccess: (text) => ({ status: "completed" as const, output: text }), + onFailure: (error) => ({ status: "error" as const, error: error.message }), + }), + ), + ) + return + } + + const run = execution.resume(recovery.childSessionID).pipe(Effect.andThen(output)) // Recovered children, started or still queued, line up again in recovery order. const limit = yield* sessions.get(recovery.parentSessionID).pipe( Effect.flatMap(queue.limit), @@ -285,5 +301,5 @@ export const layer = (options?: Options) => export const node = makeGlobalNode({ service: Service, layer: layer(), - deps: [SessionStore.node, SessionExecution.node, Bus.node, Job.node, Session.node, SubagentQueue.node], + deps: [SessionStore.node, SessionExecution.node, Bus.node, Database.node, Job.node, Session.node, SubagentQueue.node], }) diff --git a/packages/core/src/session/subagent-queue.ts b/packages/core/src/session/subagent-queue.ts index de1ef74463d..9d661dca6a9 100644 --- a/packages/core/src/session/subagent-queue.ts +++ b/packages/core/src/session/subagent-queue.ts @@ -1,9 +1,13 @@ export * as SubagentQueue from "./subagent-queue.js" -import { Context, Deferred, Effect, Layer, Option } from "effect" +import path from "path" +import { Context, Deferred, Effect, Layer, Option, Schema } from "effect" +import { parse } from "jsonc-parser" import { makeGlobalNode } from "@opencode/util/effect/app-node" -import { Config } from "../config.js" -import { Instance } from "../instance/service.js" +import { FSUtil } from "@opencode/util/fs-util" +import { Global } from "@opencode/util/global" +import { ConfigDiscovery } from "../config/discovery.js" +import { PositiveInt } from "../schema.js" import { SessionSchema } from "./schema.js" export type HoldInput = { @@ -20,6 +24,8 @@ export interface Interface { * and only children of top-level sessions are capped: a held nested child could otherwise wait on its own ancestor. */ readonly limit: (parent: SessionSchema.Info) => Effect.Effect + /** The global config files the cap is read from, lowest priority first. */ + readonly files: ReadonlyArray /** Runs `effect` once fewer than `limit` held effects run across the server, in FIFO order, and frees the slot when it ends. */ readonly hold: (input: HoldInput, effect: Effect.Effect) => Effect.Effect /** How many wait ahead of a child that is still waiting for a slot, or undefined when it isn't waiting. */ @@ -30,11 +36,16 @@ export class Service extends Context.Service()("@opencode/Su type Waiter = { readonly sessionID: SessionSchema.ID; readonly ready: Deferred.Deferred } +const decodeCap = Schema.decodeUnknownOption( + Schema.Struct({ experimental: Schema.Struct({ subagent_concurrency: PositiveInt }) }), +) + const make = Effect.gen(function* () { - const instances = yield* Instance.Service + const fs = yield* FSUtil.Service + const global = yield* Global.Service + const files = ConfigDiscovery.names.map((name) => path.join(global.config, name)) let running = 0 const waiting: Waiter[] = [] - const warned = new Set() // Synchronous bookkeeping first, so the slot count never depends on when the deferreds resolve. const release = (limit: number) => @@ -56,25 +67,20 @@ const make = Effect.gen(function* () { return Effect.void }) + // Read straight from the global config files, so checking the cap never boots a project. const limit: Interface["limit"] = (parent) => { if (parent.parentID !== undefined) return Effect.succeed(undefined) - return Effect.gen(function* () { - const config = yield* Effect.serviceOption(Config.Service) - if (Option.isNone(config)) return undefined - const shared = yield* config.value.entries({ project: false }) - for (const entry of yield* config.value.entries()) { - if (entry.type !== "document" || shared.includes(entry)) continue - if (entry.info.experimental?.subagent_concurrency === undefined) continue - const source = entry.path ?? "project config" - if (warned.has(source)) continue - warned.add(source) - yield* Effect.logWarning("experimental.subagent_concurrency is only read from global config", { source }) - } - return Config.latest(shared, "experimental")?.subagent_concurrency - }).pipe( - instances.provide(parent), - Effect.orElseSucceed(() => undefined), - ) + return Effect.forEach(files, (file) => + fs.readFileStringSafe(file).pipe( + Effect.map((text) => + text === undefined + ? undefined + : Option.getOrUndefined(decodeCap(parse(text, [], { allowTrailingComma: true })))?.experimental + .subagent_concurrency, + ), + Effect.orElseSucceed(() => undefined), + ), + ).pipe(Effect.map((caps) => caps.findLast((cap) => cap !== undefined))) } const hold: Interface["hold"] = (input, effect) => @@ -98,9 +104,9 @@ const make = Effect.gen(function* () { return index === -1 ? undefined : index }) - return Service.of({ limit, hold, waiting: position }) + return Service.of({ limit, files, hold, waiting: position }) }) export const layer = Layer.effect(Service, make) -export const node = makeGlobalNode({ service: Service, layer, deps: [Instance.node] }) +export const node = makeGlobalNode({ service: Service, layer, deps: [FSUtil.node, Global.node] }) diff --git a/packages/core/src/tool/plugin/subagent.ts b/packages/core/src/tool/plugin/subagent.ts index bcee845c4ee..f769e5a71e7 100644 --- a/packages/core/src/tool/plugin/subagent.ts +++ b/packages/core/src/tool/plugin/subagent.ts @@ -76,6 +76,17 @@ export const Plugin = { const models = yield* Model.Service const subagents = yield* SubagentJob.Service const queue = yield* SubagentQueue.Service + const warned = new Set() + // The cap is server-wide, so a project can't set it; say so once per file that tries. + const warnIgnoredCap = Effect.fnUntraced(function* () { + for (const entry of yield* config.entries()) { + if (entry.type !== "document" || entry.info.experimental?.subagent_concurrency === undefined) continue + const source = entry.path ?? "inline config" + if (queue.files.includes(source) || warned.has(source)) continue + warned.add(source) + yield* Effect.logWarning("experimental.subagent_concurrency is only read from global config", { source }) + } + }) const resolveModel = Effect.fn("SubagentTool.resolveModel")(function* (input: string) { const ref = yield* Effect.try({ @@ -209,6 +220,7 @@ export const Plugin = { )) const background = input.background === true + if (existing === undefined && parent.parentID === undefined) yield* warnIgnoredCap() const cap = existing === undefined ? yield* queue.limit(parent) : undefined // A follow-up to a child still waiting for a slot joins its line instead of starting it. const held = diff --git a/packages/core/test/session-execution.test.ts b/packages/core/test/session-execution.test.ts index 244afdb9b81..0920cfabc31 100644 --- a/packages/core/test/session-execution.test.ts +++ b/packages/core/test/session-execution.test.ts @@ -6,8 +6,12 @@ import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" import { LayerNode } from "@opencode/util/effect/layer-node" import { Bus } from "@opencode/core/bus" import { Instance } from "@opencode/core/instance/service" +import { Agent } from "@opencode/core/agent" import { Job } from "@opencode/core/job" import { KV } from "@opencode/core/kv" +import { Model } from "@opencode/core/model" +import { Provider } from "@opencode/core/provider" +import { Money } from "@opencode/schema/money" import { LocationServiceMap } from "@opencode/core/location-service-map" import type { LocationServices } from "@opencode/core/location-services" import { Project } from "@opencode/core/project" @@ -955,6 +959,77 @@ describe("SessionRestart background recovery", () => { }), ) + it.effect("delivers a recovered subagent's finished turn instead of sending it to the model again", () => + Effect.gen(function* () { + const database = yield* Database.Service + const jobs = yield* Job.Service + const bus = yield* Bus.Service + const parent = Session.ID.make("ses_subagent_ended_parent") + const child = Session.ID.make("ses_subagent_ended_child") + yield* seedSessions(database, [parent]) + yield* seedSessions(database, [child], { parent_id: parent }) + // The child's turn ended and released its claim, but the crash came before its job recorded the result. + const assistantMessageID = SessionMessage.ID.create() + yield* bus.publish(SessionEvent.Step.Started, { + sessionID: child, + assistantMessageID, + agent: Agent.ID.make("explore"), + model: Model.Ref.make({ id: Model.ID.make("child"), providerID: Provider.ID.make("test") }), + started: 0, + }) + yield* bus.publish(SessionEvent.Text.Started, { sessionID: child, assistantMessageID, ordinal: 0 }) + yield* bus.publish(SessionEvent.Text.Ended, { + sessionID: child, + assistantMessageID, + ordinal: 0, + text: "Finished review", + }) + yield* bus.publish(SessionEvent.Step.Ended, { + sessionID: child, + assistantMessageID, + finish: "stop", + cost: Money.USD.zero, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + }) + yield* jobs.start({ + id: child, + type: "subagent", + recovery: { + kind: "subagent", + parentSessionID: parent, + childSessionID: child, + agent: "explore", + description: "Ended review", + }, + run: Effect.never, + }) + yield* jobs.background(child) + + const parentWoken = yield* Deferred.make() + const drained: Session.ID[] = [] + const scope = yield* Scope.make() + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)) + const restarted = yield* Job.make.pipe(Effect.provideService(Scope.Scope, scope)) + const context = yield* buildExecution( + scope, + ({ sessionID }) => + Effect.sync(() => void drained.push(sessionID)).pipe( + Effect.andThen(sessionID === parent ? Deferred.succeed(parentWoken, undefined) : Effect.void), + ), + undefined, + restarted, + ) + yield* Context.get(context, SessionRestart.Service).resumeSuspendedSessions + yield* Deferred.await(parentWoken) + + expect(drained).toEqual([parent]) + expect(yield* SessionInbox.list(database.db, parent)).toMatchObject([ + { payload: { text: expect.stringContaining("Finished review"), metadata: { state: "completed" } } }, + ]) + expect(yield* restarted.pendingBackground).toEqual([]) + }), + ) + it.effect("retains a subagent completion marker when synthetic admission conflicts", () => Effect.gen(function* () { const database = yield* Database.Service @@ -1422,17 +1497,7 @@ function buildExecution( Layer.provide(Layer.succeed(Bus.Service, bus)), Layer.provide(Layer.succeed(SessionStore.Service, store)), Layer.provide(Layer.succeed(Job.Service, jobs)), - // No cap here: reading it would boot each parent's full Location graph, which fetches the model catalog. - Layer.provide( - Layer.succeed( - SubagentQueue.Service, - SubagentQueue.Service.of({ - limit: () => Effect.succeed(undefined), - hold: (_, effect) => effect, - waiting: () => Effect.succeed(undefined), - }), - ), - ), + Layer.provide(AppNodeBuilder.build(SubagentQueue.node)), // Do not reuse the outer harness's selector with its already-captured Location map. Layer.provide( AppNodeBuilder.build(Instance.node, [LocationServiceMap.node.replace(locations)]).pipe(Layer.fresh), diff --git a/packages/core/test/subagent-queue.test.ts b/packages/core/test/subagent-queue.test.ts index a2c15036685..58071b5dcd6 100644 --- a/packages/core/test/subagent-queue.test.ts +++ b/packages/core/test/subagent-queue.test.ts @@ -392,8 +392,9 @@ describe("SubagentQueue", () => { const children = yield* Effect.forEach([1, 2], (n) => sessions.create({ parentID: root.id, title: `recovered ${n}`, agent: Agent.ID.make("reviewer") }), ) - // The first child was mid-turn at the restart; the second was still waiting for a slot. + // The first child was mid-turn at the restart; the second was still waiting for a slot with its prompt held. yield* (yield* SessionStore.Service).claim(children[0]!.id) + yield* sessions.prompt({ sessionID: children[1]!.id, text: "review", resume: false, delivery: "queue" }) const notices = (sessionID: Session.ID) => sessions .context(sessionID)