mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-17 05:26:47 +03:00
feat(core): thread a subagent notify preference and job foreground visibility
This commit is contained in:
@@ -92,8 +92,8 @@ export const Plugin = define({
|
||||
agent: selected.id,
|
||||
description: command.description ?? name,
|
||||
}
|
||||
yield* subagents.start(recovery)
|
||||
yield* subagents.background(recovery)
|
||||
yield* subagents.start({ recovery, notify: true })
|
||||
yield* subagents.background({ recovery, notify: true })
|
||||
return
|
||||
}
|
||||
if (agent !== undefined) {
|
||||
|
||||
@@ -116,6 +116,9 @@ export type BackgroundAllInput = {
|
||||
|
||||
export interface Interface {
|
||||
readonly get: (id: string) => Effect.Effect<Info | undefined>
|
||||
// True only while a foreground caller holds a block registration for this job. Settlement,
|
||||
// cancellation and backgrounding clear it, so read it before awaiting anything else.
|
||||
readonly isBlocked: (id: string) => Effect.Effect<boolean>
|
||||
readonly start: (input: StartInput) => Effect.Effect<Info>
|
||||
readonly wait: (input: WaitInput) => Effect.Effect<WaitResult>
|
||||
readonly block: (input: BlockInput) => Effect.Effect<BlockResult | undefined>
|
||||
@@ -281,6 +284,11 @@ export const make = Effect.gen(function* () {
|
||||
return snapshot(job)
|
||||
})
|
||||
|
||||
const isBlocked: Interface["isBlocked"] = Effect.fn("Job.isBlocked")(function* (id) {
|
||||
const job = (yield* SynchronizedRef.get(state.jobs)).get(id)
|
||||
return job !== undefined && job.blockingSessions.size > 0
|
||||
})
|
||||
|
||||
const start: Interface["start"] = Effect.fnUntraced(function* (input) {
|
||||
return yield* Effect.uninterruptibleMask((restore) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -535,6 +543,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
return Service.of({
|
||||
get,
|
||||
isBlocked,
|
||||
start,
|
||||
wait,
|
||||
block,
|
||||
|
||||
@@ -6,12 +6,18 @@ import type { LayerNode } from "@opencode/util/effect/layer-node"
|
||||
import { Job } from "../job.js"
|
||||
import { Session } from "../session.js"
|
||||
import { SubagentCompletion } from "./subagent-completion.js"
|
||||
import { SubagentMetadata } from "./subagent-metadata.js"
|
||||
|
||||
type Recovery = Extract<Job.Recovery, { kind: "subagent" }>
|
||||
|
||||
export type Input = {
|
||||
readonly recovery: Recovery
|
||||
readonly notify: boolean
|
||||
}
|
||||
|
||||
export interface Interface {
|
||||
start: (recovery: Recovery) => Effect.Effect<Job.Info>
|
||||
background: (recovery: Recovery) => Effect.Effect<void>
|
||||
start: (input: Input) => Effect.Effect<Job.Info>
|
||||
background: (input: Input) => Effect.Effect<void>
|
||||
notify: (recovery: Recovery, startedAt: number) => Effect.Effect<void>
|
||||
}
|
||||
|
||||
@@ -27,13 +33,37 @@ const make: Effect.Effect<Interface, never, Session.Service | Job.Service | Scop
|
||||
// One observer per job generation, including continuations of the same child.
|
||||
const notifications = new Set<string>()
|
||||
|
||||
// Children inherit their parent's metadata (Session.create), so the per-spawn preference is
|
||||
// always written explicitly, merged over whatever the child already carries. This must run
|
||||
// before jobs.start, because that forks the child's run. A vanished child keeps the
|
||||
// never-error channel; jobs.start and the run surface a genuinely missing one.
|
||||
const writeNotify = Effect.fnUntraced(function* (recovery: Recovery, notify: boolean) {
|
||||
yield* Effect.gen(function* () {
|
||||
const session = yield* sessions.get(recovery.childSessionID)
|
||||
const metadata = SubagentMetadata.withNotify(session.metadata, notify)
|
||||
if (metadata) yield* sessions.setMetadata({ sessionID: recovery.childSessionID, metadata })
|
||||
}).pipe(Effect.catchTag("Session.NotFoundError", () => Effect.void))
|
||||
})
|
||||
|
||||
const notify = Effect.fn("SubagentJob.notify")(function* (recovery: Recovery, startedAt: number) {
|
||||
const key = `${recovery.childSessionID}:${startedAt}`
|
||||
if (notifications.has(key)) return
|
||||
notifications.add(key)
|
||||
yield* Effect.gen(function* () {
|
||||
const info = (yield* jobs.wait({ id: recovery.childSessionID })).info
|
||||
if (info) yield* SubagentCompletion.deliver(sessions, jobs, { ...info, recovery })
|
||||
if (!info) return
|
||||
// The preference belongs to the spawn call, so read it after the child settles. A silent
|
||||
// child still clears its durable marker rather than leave a row that restart recovery
|
||||
// would replay as a report the parent asked not to receive.
|
||||
const metadata = yield* sessions.get(recovery.childSessionID).pipe(
|
||||
Effect.map((session) => session.metadata),
|
||||
Effect.catchTag("Session.NotFoundError", () => Effect.succeed(undefined)),
|
||||
)
|
||||
if (!SubagentMetadata.notify(metadata)) {
|
||||
if (info.notificationID) yield* jobs.completeBackground(info.notificationID)
|
||||
return
|
||||
}
|
||||
yield* SubagentCompletion.deliver(sessions, jobs, { ...info, recovery })
|
||||
}).pipe(
|
||||
Effect.ensuring(Effect.sync(() => notifications.delete(key))),
|
||||
Effect.forkIn(scope, { startImmediately: true }),
|
||||
@@ -42,17 +72,22 @@ const make: Effect.Effect<Interface, never, Session.Service | Job.Service | Scop
|
||||
})
|
||||
|
||||
return Service.of({
|
||||
start: (recovery: Recovery) =>
|
||||
jobs
|
||||
.start({
|
||||
id: recovery.childSessionID,
|
||||
start: (input: Input) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeNotify(input.recovery, input.notify)
|
||||
return yield* jobs.start({
|
||||
id: input.recovery.childSessionID,
|
||||
type: "subagent",
|
||||
title: recovery.description,
|
||||
title: input.recovery.description,
|
||||
metadata: {},
|
||||
recovery,
|
||||
recovery: input.recovery,
|
||||
run: Effect.gen(function* () {
|
||||
yield* sessions.resume(recovery.childSessionID)
|
||||
const messages = yield* sessions.messages({ sessionID: recovery.childSessionID, order: "desc", limit: 20 })
|
||||
yield* sessions.resume(input.recovery.childSessionID)
|
||||
const messages = yield* sessions.messages({
|
||||
sessionID: input.recovery.childSessionID,
|
||||
order: "desc",
|
||||
limit: 20,
|
||||
})
|
||||
const assistant = messages.find(
|
||||
(message) =>
|
||||
message.type === "assistant" && message.time.completed !== undefined && message.error === undefined,
|
||||
@@ -60,10 +95,11 @@ const make: Effect.Effect<Interface, never, Session.Service | Job.Service | Scop
|
||||
return SubagentCompletion.text(assistant)
|
||||
}),
|
||||
})
|
||||
.pipe(Effect.setContext(context)),
|
||||
background: Effect.fn("SubagentJob.background")(function* (recovery: Recovery) {
|
||||
const info = yield* jobs.background(recovery.childSessionID)
|
||||
if (info) yield* notify(recovery, info.started_at)
|
||||
}).pipe(Effect.setContext(context)),
|
||||
background: Effect.fn("SubagentJob.background")(function* (input: Input) {
|
||||
yield* writeNotify(input.recovery, input.notify)
|
||||
const info = yield* jobs.background(input.recovery.childSessionID)
|
||||
if (info) yield* notify(input.recovery, info.started_at)
|
||||
}),
|
||||
notify,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
export * as SubagentMetadata from "./subagent-metadata.js"
|
||||
|
||||
import type { SessionSchema } from "./schema.js"
|
||||
|
||||
// Children inherit their parent's whole metadata map, so a spawn that wants the default
|
||||
// still has to write this key explicitly to override an inherited silent preference.
|
||||
const NOTIFY = "subagent.notify"
|
||||
|
||||
// Absence means report, so parents and children spawned before this key existed stay loud.
|
||||
export function notify(metadata: SessionSchema.Metadata | undefined) {
|
||||
return metadata?.[NOTIFY] !== false
|
||||
}
|
||||
|
||||
// Returns undefined when the child already carries the preference, letting callers skip a write.
|
||||
export function withNotify(metadata: SessionSchema.Metadata | undefined, value: boolean) {
|
||||
if (notify(metadata) === value) return undefined
|
||||
return { ...metadata, [NOTIFY]: value }
|
||||
}
|
||||
@@ -45,6 +45,10 @@ export const Input = Schema.Struct({
|
||||
description:
|
||||
"Run the subagent in the background and return immediately. You will be notified when it completes. DO NOT sleep, poll, or proactively check on its progress.",
|
||||
}),
|
||||
notify: Schema.optionalKey(Schema.Boolean).annotate({
|
||||
description:
|
||||
"Send you a message when the subagent goes idle. Defaults to true; set false to run it silently. The choice applies to this call only.",
|
||||
}),
|
||||
})
|
||||
|
||||
export const Output = Schema.Struct({
|
||||
@@ -59,6 +63,7 @@ export const description = [
|
||||
"Foreground (default) runs the subagent to completion and returns its final response.",
|
||||
"Background mode (background=true) launches it asynchronously and returns immediately; you are notified when it finishes.",
|
||||
"Use background only for independent work that can run while you continue elsewhere.",
|
||||
"Set notify=false to run a background subagent silently when you expect to read its session yourself later.",
|
||||
].join("\n")
|
||||
|
||||
export const Plugin = {
|
||||
@@ -198,10 +203,13 @@ export const Plugin = {
|
||||
))
|
||||
|
||||
const background = input.background === true
|
||||
const notify = input.notify !== false
|
||||
yield* context.progress({ sessionID: child.id, status: "running" })
|
||||
|
||||
// Standard prompt admission outside the job: Job.start joining a running child skips
|
||||
// its run effect, and the default wake starts an idle child or steers a running one.
|
||||
// A new child admits only, so the job owns the first drain and its foreground block
|
||||
// is registered before the child can settle; continuations keep the default wake.
|
||||
yield* sessions
|
||||
.prompt({
|
||||
sessionID: child.id,
|
||||
@@ -209,7 +217,7 @@ export const Plugin = {
|
||||
existing === undefined
|
||||
? ["You are a subagent spawned by another session.", input.prompt].join("\n")
|
||||
: input.prompt,
|
||||
...(background && existing === undefined ? { resume: false } : {}),
|
||||
...(existing === undefined ? { resume: false } : {}),
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
@@ -224,10 +232,10 @@ export const Plugin = {
|
||||
agent: agent.name,
|
||||
description: input.description,
|
||||
}
|
||||
yield* subagents.start(recovery)
|
||||
yield* subagents.start({ recovery, notify })
|
||||
|
||||
if (background) {
|
||||
yield* subagents.background(recovery)
|
||||
yield* subagents.background({ recovery, notify })
|
||||
return backgroundResult(child.id)
|
||||
}
|
||||
|
||||
@@ -239,6 +247,7 @@ export const Plugin = {
|
||||
),
|
||||
)
|
||||
if (result?.type === "backgrounded") {
|
||||
// The observer clears the durable marker even for a silent child.
|
||||
yield* subagents.notify(recovery, result.info.started_at)
|
||||
return backgroundResult(child.id)
|
||||
}
|
||||
|
||||
@@ -185,6 +185,34 @@ describe("Job", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("reports foreground visibility only while a session blocks on the job", () =>
|
||||
Effect.gen(function* () {
|
||||
const jobs = yield* Job.Service
|
||||
const latch = yield* Deferred.make<void>()
|
||||
const job = yield* jobs.start({
|
||||
id: "job_visibility",
|
||||
type: "test",
|
||||
run: Deferred.await(latch).pipe(Effect.as("done")),
|
||||
})
|
||||
|
||||
expect(yield* jobs.isBlocked(job.id)).toBe(false)
|
||||
expect(yield* jobs.isBlocked("job_missing")).toBe(false)
|
||||
|
||||
const waiting = yield* jobs
|
||||
.block({ id: job.id, sessionID: SessionSchema.ID.make("ses_visible") })
|
||||
.pipe(Effect.forkIn(yield* Scope.Scope, { startImmediately: true }))
|
||||
// The registration happens in the forked fiber; yield until it is visible, never sleep.
|
||||
yield* Effect.gen(function* () {
|
||||
while (!(yield* jobs.isBlocked(job.id))) yield* Effect.yieldNow
|
||||
}).pipe(Effect.timeout("1 second"))
|
||||
expect(yield* jobs.isBlocked(job.id)).toBe(true)
|
||||
|
||||
yield* Deferred.succeed(latch, undefined)
|
||||
expect(yield* Fiber.join(waiting)).toMatchObject({ type: "finished" })
|
||||
expect(yield* jobs.isBlocked(job.id)).toBe(false)
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("returns backgrounded from a blocking wait when background wins", () =>
|
||||
Effect.gen(function* () {
|
||||
const jobs = yield* Job.Service
|
||||
|
||||
@@ -877,4 +877,115 @@ describe("SubagentTool", () => {
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
it.live("records the notify preference explicitly instead of inheriting it", () =>
|
||||
tmpdirScoped().pipe(
|
||||
Effect.flatMap((dir) =>
|
||||
Effect.gen(function* () {
|
||||
const location = Location.Ref.make({ directory: AbsolutePath.make(dir.path) })
|
||||
const sessions = yield* Session.Service
|
||||
const parent = yield* sessions.create({
|
||||
location,
|
||||
metadata: { "subagent.notify": false, host: "keep" },
|
||||
})
|
||||
yield* withSubagent(parent.location)
|
||||
const locations = yield* LocationServiceMap.Service
|
||||
const registry = yield* Tool.Service.pipe(Effect.provide(locations.get(parent.location)))
|
||||
|
||||
const spawn = (id: string, input: Record<string, unknown>) =>
|
||||
executeTool(registry, {
|
||||
sessionID: parent.id,
|
||||
...toolIdentity,
|
||||
call: { type: "tool-call", id, name: SubagentTool.name, input },
|
||||
})
|
||||
|
||||
const loud = yield* spawn("call-notify-default", {
|
||||
agent: "reviewer",
|
||||
description: "loud review",
|
||||
prompt: "review",
|
||||
background: true,
|
||||
})
|
||||
const quiet = yield* spawn("call-notify-false", {
|
||||
agent: "reviewer",
|
||||
description: "quiet review",
|
||||
prompt: "review",
|
||||
background: true,
|
||||
notify: false,
|
||||
})
|
||||
|
||||
// The inherited false is rewritten by default, and the host key survives the merge.
|
||||
expect((yield* sessions.get(outputSessionID(loud.metadata))).metadata).toEqual({
|
||||
"subagent.notify": true,
|
||||
host: "keep",
|
||||
})
|
||||
expect((yield* sessions.get(outputSessionID(quiet.metadata))).metadata).toEqual({
|
||||
"subagent.notify": false,
|
||||
host: "keep",
|
||||
})
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
it.live("reports only the children whose spawn asked for it", () =>
|
||||
tmpdirScoped().pipe(
|
||||
Effect.flatMap((dir) =>
|
||||
Effect.gen(function* () {
|
||||
const location = Location.Ref.make({ directory: AbsolutePath.make(dir.path) })
|
||||
const sessions = yield* Session.Service
|
||||
const parent = yield* sessions.create({ location })
|
||||
yield* withSubagent(parent.location)
|
||||
const locations = yield* LocationServiceMap.Service
|
||||
const registry = yield* Tool.Service.pipe(Effect.provide(locations.get(parent.location)))
|
||||
const jobs = yield* Job.Service
|
||||
const bus = yield* Bus.Service
|
||||
const database = yield* Database.Service
|
||||
const admitted = yield* bus.subscribe(SessionEvent.InboxEnqueued).pipe(
|
||||
Stream.filter((event) => event.data.sessionID === parent.id && event.data.item.type === "synthetic"),
|
||||
Stream.take(1),
|
||||
Stream.runCollect,
|
||||
Effect.forkScoped({ startImmediately: true }),
|
||||
)
|
||||
|
||||
const spawn = (id: string, input: Record<string, unknown>) =>
|
||||
executeTool(registry, {
|
||||
sessionID: parent.id,
|
||||
...toolIdentity,
|
||||
call: { type: "tool-call", id, name: SubagentTool.name, input },
|
||||
})
|
||||
|
||||
const quiet = yield* spawn("call-silent-subagent", {
|
||||
agent: "reviewer",
|
||||
description: "quiet review",
|
||||
prompt: "review",
|
||||
background: true,
|
||||
notify: false,
|
||||
})
|
||||
const loud = yield* spawn("call-loud-subagent", {
|
||||
agent: "reviewer",
|
||||
description: "loud review",
|
||||
prompt: "review",
|
||||
background: true,
|
||||
})
|
||||
const loudID = outputSessionID(loud.metadata)
|
||||
|
||||
const admission = Array.from(yield* Fiber.join(admitted))[0]
|
||||
if (admission?.data.item.type !== "synthetic") return yield* Effect.die("Expected synthetic inbox item")
|
||||
expect(admission.data.item.payload.metadata).toMatchObject({ childID: loudID })
|
||||
|
||||
// The silent child settles without a report but still clears its durable marker.
|
||||
yield* jobs.wait({ id: outputSessionID(quiet.metadata) })
|
||||
yield* jobs.wait({ id: loudID })
|
||||
yield* jobs.pendingBackground.pipe(
|
||||
Effect.repeat({ until: (pending) => pending.length === 0 }),
|
||||
Effect.timeout("2 seconds"),
|
||||
)
|
||||
yield* SessionInbox.promote(database.db, bus, parent.id, "steer")
|
||||
const synthetic = (yield* sessions.context(parent.id)).filter((message) => message.type === "synthetic")
|
||||
expect(synthetic).toHaveLength(1)
|
||||
expect(synthetic[0]?.text).toContain(`<subagent sessionID="${loudID}" state="completed"`)
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user