mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
fix(core): only wait on background work that wakes the session
This commit is contained in:
parent
ba8858e826
commit
a8db483efe
9 changed files with 174 additions and 69 deletions
|
|
@ -4,7 +4,6 @@ import { isContextOverflowFailure, Message } from "@opencode/ai/effect"
|
|||
import { define } from "@opencode/plugin/effect/plugin"
|
||||
import type { SessionIdleBackground } from "@opencode/plugin/effect/session"
|
||||
import type { Session } from "@opencode/schema/session"
|
||||
import type { SessionEvent } from "@opencode/schema/session-event"
|
||||
import { SessionGoal } from "@opencode/schema/session-goal"
|
||||
import { isExactRootFallback } from "@opencode/util/session-title-fallback"
|
||||
import { Cause, Clock, DateTime, Duration, Effect, FiberMap, Option, Schema, Stream } from "effect"
|
||||
|
|
@ -76,8 +75,8 @@ export const Plugin = define({
|
|||
Effect.flatMap((goal) => (goal?.status === "active" ? settle(sessionID, goal, "paused", reason) : Effect.void)),
|
||||
)
|
||||
|
||||
// One compaction per round when the reviewer's request is too large; a second overflow pauses instead. Keyed by
|
||||
// Session, so it holds one round per Session that ever overflowed.
|
||||
// One compaction per round when the reviewer's request is too large; a second overflow pauses instead. An entry
|
||||
// lives only until the reviewer answers or the goal pauses.
|
||||
const compacted = new Map<Session.ID, string>()
|
||||
|
||||
// Whether the model called any tool since the goal's last kickoff or continuation. Without that message in view,
|
||||
|
|
@ -98,9 +97,8 @@ export const Plugin = define({
|
|||
const judge = Effect.fn("GoalPlugin.judge")(function* (
|
||||
sessionID: Session.ID,
|
||||
goal: State,
|
||||
background: ReadonlyArray<SessionIdleBackground>,
|
||||
shells: ReadonlyArray<string>,
|
||||
) {
|
||||
const shells = background.flatMap((work) => (work.kind === "shell" ? [work.command] : []))
|
||||
const prompt = render(JUDGE, {
|
||||
objective: escape(goal.objective),
|
||||
background:
|
||||
|
|
@ -116,7 +114,11 @@ export const Plugin = define({
|
|||
shells.length === 0 ? "" : '{"verdict":"wait","reason":"<the running shell whose result the goal needs>"}\n',
|
||||
})
|
||||
const attempt = ctx.session.generate({ sessionID, prompt }).pipe(
|
||||
Effect.map((result) => parseVerdict(result.text)),
|
||||
Effect.map((result) => {
|
||||
const verdict = parseVerdict(result.text)
|
||||
// "wait" is only offered while a shell runs; without one, nothing would wake the Session to judge again.
|
||||
return verdict?.verdict === "wait" && shells.length === 0 ? undefined : verdict
|
||||
}),
|
||||
// The reviewer runs right after the last step, before the next step's automatic compaction, so a long final
|
||||
// step can leave more history than the model takes.
|
||||
Effect.catchIf(isContextOverflowFailure, () => Effect.succeed("overflow" as const)),
|
||||
|
|
@ -136,19 +138,28 @@ export const Plugin = define({
|
|||
if (goal?.status !== "active") return
|
||||
if (goal.boot !== boot())
|
||||
return yield* settle(sessionID, goal, "paused", "The server restarted while the goal was active")
|
||||
// A running subagent's result wakes the Session, and the hook runs again then.
|
||||
if (background.some((work) => work.kind === "subagent")) return
|
||||
// The Session's own running subagent wakes it with its report, and the hook runs again then. A grandchild reports
|
||||
// to its own parent, so it would never wake this Session.
|
||||
if (background.some((work) => work.kind === "subagent" && work.sessionID === sessionID)) return
|
||||
if (goal.rounds >= goal.maxRounds)
|
||||
return yield* settle(sessionID, goal, "paused", `Reached the limit of ${goal.maxRounds} rounds`)
|
||||
|
||||
const verdict = yield* judge(sessionID, goal, background)
|
||||
// Only the Session's own shells wake it when they finish. A subagent's leftover shell wakes the subagent, so
|
||||
// waiting on it would leave this Session idle until the wait limit pauses the goal.
|
||||
const shells = background.flatMap((work) =>
|
||||
work.kind === "shell" && work.sessionID === sessionID ? [work.command] : [],
|
||||
)
|
||||
const verdict = yield* judge(sessionID, goal, shells)
|
||||
if (verdict !== "overflow") compacted.delete(sessionID)
|
||||
// `/goal pause`, `clear` or a new goal may have landed while the reviewer ran.
|
||||
const latest = yield* read(sessionID)
|
||||
if (latest?.id !== goal.id || latest.status !== "active") return
|
||||
if (verdict === "overflow") {
|
||||
const key = `${latest.id}:${latest.rounds}`
|
||||
if (compacted.get(sessionID) === key)
|
||||
if (compacted.get(sessionID) === key) {
|
||||
compacted.delete(sessionID)
|
||||
return yield* settle(sessionID, latest, "paused", "The goal reviewer's request is too large for the model")
|
||||
}
|
||||
compacted.set(sessionID, key)
|
||||
// The runner compacts before going idle, then runs this hook again on the smaller history.
|
||||
yield* ctx.session.compact({ sessionID })
|
||||
|
|
@ -156,7 +167,7 @@ export const Plugin = define({
|
|||
}
|
||||
if (verdict === undefined)
|
||||
return yield* settle(sessionID, latest, "paused", "The goal reviewer gave no usable verdict")
|
||||
if (verdict.verdict === "wait" && background.length > 0) return
|
||||
if (verdict.verdict === "wait") return
|
||||
if (verdict.verdict === "done") return yield* settle(sessionID, latest, "complete", verdict.reason)
|
||||
if (verdict.verdict !== "continue") return yield* settle(sessionID, latest, "paused", verdict.reason)
|
||||
|
||||
|
|
@ -249,44 +260,41 @@ export const Plugin = define({
|
|||
),
|
||||
)
|
||||
|
||||
yield* ctx.event.subscribe().pipe(
|
||||
Stream.filter(
|
||||
(
|
||||
event,
|
||||
): event is
|
||||
| SessionEvent.Execution.Started
|
||||
| SessionEvent.Execution.Succeeded
|
||||
| SessionEvent.Execution.Interrupted
|
||||
| SessionEvent.Execution.Failed =>
|
||||
event.type === "session.execution.started" ||
|
||||
event.type === "session.execution.succeeded" ||
|
||||
event.type === "session.execution.interrupted" ||
|
||||
event.type === "session.execution.failed",
|
||||
),
|
||||
Stream.runForEach((event) => {
|
||||
const sessionID = event.data.sessionID
|
||||
if (event.type === "session.execution.started") return FiberMap.remove(timers, sessionID)
|
||||
if (event.type === "session.execution.succeeded")
|
||||
return watch(sessionID).pipe(
|
||||
Effect.catchCause((cause) => Effect.logWarning("failed to watch a waiting goal", { sessionID, cause })),
|
||||
yield* ctx.event
|
||||
.subscribe({
|
||||
types: [
|
||||
"session.execution.started",
|
||||
"session.execution.succeeded",
|
||||
"session.execution.interrupted",
|
||||
"session.execution.failed",
|
||||
],
|
||||
})
|
||||
.pipe(
|
||||
Stream.runForEach((event) => {
|
||||
const sessionID = event.data.sessionID
|
||||
if (event.type === "session.execution.started") return FiberMap.remove(timers, sessionID)
|
||||
if (event.type === "session.execution.succeeded")
|
||||
return watch(sessionID).pipe(
|
||||
Effect.catchCause((cause) => Effect.logWarning("failed to watch a waiting goal", { sessionID, cause })),
|
||||
)
|
||||
// Shutdown keeps the goal active; the next process sees the boot change and pauses it.
|
||||
if (event.type === "session.execution.interrupted" && event.data.reason !== "user") return Effect.void
|
||||
const reason =
|
||||
event.type === "session.execution.failed"
|
||||
? `The session failed: ${event.data.error.message}`
|
||||
: "Stopped by the user"
|
||||
return pauseActive(event.data.sessionID, reason).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("failed to pause goal", { sessionID: event.data.sessionID, cause }),
|
||||
),
|
||||
)
|
||||
// Shutdown keeps the goal active; the next process sees the boot change and pauses it.
|
||||
if (event.type === "session.execution.interrupted" && event.data.reason !== "user") return Effect.void
|
||||
const reason =
|
||||
event.type === "session.execution.failed"
|
||||
? `The session failed: ${event.data.error.message}`
|
||||
: "Stopped by the user"
|
||||
return pauseActive(event.data.sessionID, reason).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("failed to pause goal", { sessionID: event.data.sessionID, cause }),
|
||||
),
|
||||
)
|
||||
}),
|
||||
Effect.forkScoped({ startImmediately: true }),
|
||||
)
|
||||
}),
|
||||
Effect.forkScoped({ startImmediately: true }),
|
||||
)
|
||||
|
||||
// A goal an earlier process left active would show as running while nothing drives it, unless something wakes the
|
||||
// Session. Pause those among recent Sessions now; the boot check in the hook covers the rest when they wake.
|
||||
// Session. Pause those among recent Sessions now; the boot check in the hook covers the rest when they wake. This
|
||||
// assumes one server process per database: a second one would pause the first one's live goals.
|
||||
yield* ctx.session.list({ limit: SWEEP_LIMIT, order: "desc" }).pipe(
|
||||
Effect.flatMap((page) =>
|
||||
Effect.forEach(
|
||||
|
|
|
|||
|
|
@ -122,9 +122,10 @@ export const layer = Layer.effect(
|
|||
const outcome = terminal(exit, reason)
|
||||
if (outcome.type === "succeeded") {
|
||||
yield* bus.publish(SessionEvent.Execution.Succeeded, { sessionID }, releaseOnCommit(sessionID))
|
||||
// Background shells don't hold it back: a dev server would keep the Session from ever settling.
|
||||
// Background shells don't hold it back: a dev server would keep the Session from ever settling. Only the
|
||||
// Session's own subagents do, because only their reports wake it; a grandchild reports to its parent.
|
||||
const background = yield* SessionBackground.outstanding(jobs, store, sessionID)
|
||||
if (!background.some((work) => work.kind === "subagent"))
|
||||
if (!background.some((work) => work.kind === "subagent" && work.sessionID === sessionID))
|
||||
yield* bus.publish(SessionEvent.Settled, { sessionID })
|
||||
return
|
||||
}
|
||||
|
|
|
|||
|
|
@ -225,6 +225,54 @@ describe("goal plugin", () => {
|
|||
}),
|
||||
)
|
||||
|
||||
it.live("does not wait on work a descendant owns, since only the descendant is woken", () =>
|
||||
Effect.gen(function* () {
|
||||
const session = yield* project()
|
||||
const sessions = yield* Session.Service
|
||||
const jobs = yield* Job.Service
|
||||
const child = yield* sessions.create({ parentID: session.id, title: "Explore", agent: Agent.ID.make("build") })
|
||||
const grandchild = yield* sessions.create({ parentID: child.id, title: "Dig", agent: Agent.ID.make("build") })
|
||||
yield* jobs.start({
|
||||
id: grandchild.id,
|
||||
type: "subagent",
|
||||
recovery: {
|
||||
kind: "subagent",
|
||||
parentSessionID: child.id,
|
||||
childSessionID: grandchild.id,
|
||||
agent: "explore",
|
||||
description: "Dig",
|
||||
},
|
||||
run: Effect.never,
|
||||
})
|
||||
yield* jobs.background(grandchild.id)
|
||||
yield* jobs.start({
|
||||
id: "child-shell",
|
||||
type: "shell",
|
||||
recovery: { kind: "shell", sessionID: child.id, shellID: "child-shell", command: "bun run build" },
|
||||
run: Effect.never,
|
||||
})
|
||||
yield* jobs.background("child-shell")
|
||||
const prompts: string[] = []
|
||||
const verdicts = reviewer(
|
||||
'{"verdict":"wait","reason":"bun run build is still running."}',
|
||||
'{"verdict":"done","reason":"The report is written."}',
|
||||
)
|
||||
yield* serve((request) => {
|
||||
if (isReview(request)) prompts.push(JSON.stringify(request.messages.at(-1)))
|
||||
return verdicts.respond(request)
|
||||
})
|
||||
|
||||
yield* sessions.command({ sessionID: session.id, command: "goal", text: "Write the report" })
|
||||
yield* sessions.wait(session.id)
|
||||
|
||||
// The grandchild reports to the child, so the reviewer runs. With none of the Session's own shells running,
|
||||
// "wait" is not offered and counts as an unusable answer.
|
||||
expect(verdicts.asked()).toBe(2)
|
||||
expect(prompts[0]).toContain("No background shells are running.")
|
||||
expect(yield* goal(session.id)).toMatchObject({ status: "complete", reason: "The report is written." })
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("drops the reviewer's verdict when the goal is paused while it runs", () =>
|
||||
Effect.gen(function* () {
|
||||
const session = yield* project()
|
||||
|
|
|
|||
|
|
@ -271,6 +271,46 @@ describe("SessionExecution lifecycle", () => {
|
|||
}),
|
||||
)
|
||||
|
||||
it.effect("settles while a grandchild subagent runs, since it reports to its own parent", () =>
|
||||
Effect.gen(function* () {
|
||||
const database = yield* Database.Service
|
||||
const bus = yield* Bus.Service
|
||||
const jobs = yield* Job.Service
|
||||
const parent = Session.ID.make("ses_settled_root")
|
||||
const child = Session.ID.make("ses_settled_reported")
|
||||
const grandchild = Session.ID.make("ses_settled_grandchild")
|
||||
yield* seedSessions(database, [parent])
|
||||
yield* seedSessions(database, [child], { parent_id: parent })
|
||||
yield* seedSessions(database, [grandchild], { parent_id: child })
|
||||
const scope = yield* Scope.make()
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void))
|
||||
const context = yield* buildExecution(scope, () => Effect.void)
|
||||
const execution = Context.get(context, SessionExecution.Service)
|
||||
const settled: unknown[] = []
|
||||
yield* bus.listen((event) =>
|
||||
Effect.sync(() => {
|
||||
if (event.type === "session.settled") settled.push(event.data)
|
||||
}),
|
||||
)
|
||||
yield* jobs.start({
|
||||
id: grandchild,
|
||||
type: "subagent",
|
||||
recovery: {
|
||||
kind: "subagent",
|
||||
parentSessionID: child,
|
||||
childSessionID: grandchild,
|
||||
agent: "general",
|
||||
description: "Nested inspection",
|
||||
},
|
||||
run: Effect.never,
|
||||
})
|
||||
yield* jobs.background(grandchild)
|
||||
|
||||
yield* execution.resume(parent)
|
||||
expect(settled).toEqual([{ sessionID: parent }])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("does not settle after a failed or interrupted execution", () =>
|
||||
Effect.gen(function* () {
|
||||
const database = yield* Database.Service
|
||||
|
|
|
|||
|
|
@ -124,16 +124,18 @@ await ctx.session.hook("retry", (event) => {
|
|||
```
|
||||
|
||||
When a Session finishes model work with no pending input, the `idle` hook runs just before it goes idle. It does not
|
||||
run after interruption, failure, or control-only work such as a manual compaction. Input the hook admits runs in the same execution instead of the Session going idle, so a
|
||||
plugin that always admits input must bound its own loop.
|
||||
run after interruption, failure, or control-only work such as a manual compaction. Input the hook admits runs in the
|
||||
same execution instead of the Session going idle, so a plugin that always admits input must bound its own loop.
|
||||
|
||||
`event.background` lists background shells and subagents still running for the Session or its descendants. When one
|
||||
finishes, its notice wakes the Session and the hook runs again, so a plugin that waits for background work can return.
|
||||
Notices admitted with `resume: false`, such as those recovered after a restart, wait for the next wake instead:
|
||||
`event.background` lists background shells and subagents still running for the Session or its descendants. When one of
|
||||
the Session's own shells or subagents finishes, its notice wakes the Session and the hook runs again, so a plugin that
|
||||
waits for that work can return. Work a descendant owns, such as a shell a subagent left running, wakes that
|
||||
descendant instead, so it is listed for information only. Notices admitted with `resume: false`, such as those
|
||||
recovered after a restart, wait for the next wake instead:
|
||||
|
||||
```ts
|
||||
await ctx.session.hook("idle", async (event) => {
|
||||
if (event.background.some((work) => work.kind === "subagent")) return
|
||||
if (event.background.some((work) => work.kind === "subagent" && work.sessionID === event.sessionID)) return
|
||||
await ctx.session.synthetic({ sessionID: event.sessionID, text: "Run the tests and fix any failures." })
|
||||
})
|
||||
```
|
||||
|
|
|
|||
|
|
@ -126,17 +126,19 @@ yield *
|
|||
```
|
||||
|
||||
When a Session finishes model work with no pending input, the `idle` hook runs just before it goes idle. It does not
|
||||
run after interruption, failure, or control-only work such as a manual compaction. Input the hook admits runs in the same execution instead of the Session going idle, so a
|
||||
plugin that always admits input must bound its own loop.
|
||||
run after interruption, failure, or control-only work such as a manual compaction. Input the hook admits runs in the
|
||||
same execution instead of the Session going idle, so a plugin that always admits input must bound its own loop.
|
||||
|
||||
`event.background` lists background shells and subagents still running for the Session or its descendants. When one
|
||||
finishes, its notice wakes the Session and the hook runs again, so a plugin that waits for background work can return.
|
||||
Notices admitted with `resume: false`, such as those recovered after a restart, wait for the next wake instead:
|
||||
`event.background` lists background shells and subagents still running for the Session or its descendants. When one of
|
||||
the Session's own shells or subagents finishes, its notice wakes the Session and the hook runs again, so a plugin that
|
||||
waits for that work can return. Work a descendant owns, such as a shell a subagent left running, wakes that
|
||||
descendant instead, so it is listed for information only. Notices admitted with `resume: false`, such as those
|
||||
recovered after a restart, wait for the next wake instead:
|
||||
|
||||
```ts
|
||||
yield *
|
||||
ctx.session.hook("idle", (event) =>
|
||||
event.background.some((work) => work.kind === "subagent")
|
||||
event.background.some((work) => work.kind === "subagent" && work.sessionID === event.sessionID)
|
||||
? Effect.void
|
||||
: ctx.session
|
||||
.synthetic({ sessionID: event.sessionID, text: "Run the tests and fix any failures." })
|
||||
|
|
|
|||
|
|
@ -166,9 +166,11 @@ export type SessionIdleBackground =
|
|||
* Input admitted by the hook, such as a synthetic message, runs in the same execution instead
|
||||
* of the Session going idle.
|
||||
*
|
||||
* `background` lists work that is still running. When it finishes, its notice wakes the Session
|
||||
* and the hook runs again, so a plugin that waits for background work can simply return. Notices
|
||||
* admitted with `resume: false`, such as those recovered after a restart, wait for the next wake.
|
||||
* `background` lists work that is still running. When the Session's own shell or subagent finishes,
|
||||
* its notice wakes the Session and the hook runs again, so a plugin that waits for that work can
|
||||
* simply return. Work a descendant owns, such as a shell a subagent left running, wakes that
|
||||
* descendant instead, so it is listed for information only. Notices admitted with `resume: false`,
|
||||
* such as those recovered after a restart, wait for the next wake.
|
||||
*/
|
||||
export interface SessionIdle {
|
||||
readonly sessionID: Session.ID
|
||||
|
|
|
|||
|
|
@ -166,9 +166,11 @@ export type SessionIdleBackground =
|
|||
* Input admitted by the hook, such as a synthetic message, runs in the same execution instead
|
||||
* of the Session going idle.
|
||||
*
|
||||
* `background` lists work that is still running. When it finishes, its notice wakes the Session
|
||||
* and the hook runs again, so a plugin that waits for background work can simply return. Notices
|
||||
* admitted with `resume: false`, such as those recovered after a restart, wait for the next wake.
|
||||
* `background` lists work that is still running. When the Session's own shell or subagent finishes,
|
||||
* its notice wakes the Session and the hook runs again, so a plugin that waits for that work can
|
||||
* simply return. Work a descendant owns, such as a shell a subagent left running, wakes that
|
||||
* descendant instead, so it is listed for information only. Notices admitted with `resume: false`,
|
||||
* such as those recovered after a restart, wait for the next wake.
|
||||
*/
|
||||
export interface SessionIdle {
|
||||
readonly sessionID: Session.ID
|
||||
|
|
|
|||
|
|
@ -264,9 +264,9 @@ export namespace Execution {
|
|||
}
|
||||
|
||||
/**
|
||||
* Follows `session.execution.succeeded` when no background subagent of the Session or its
|
||||
* descendants is still running, so the Session has nothing more coming on its own. A running
|
||||
* subagent's result wakes the Session later, and that execution settles instead.
|
||||
* Follows `session.execution.succeeded` when none of the Session's own background subagents is
|
||||
* still running, so the Session has nothing more coming on its own. A running subagent's result
|
||||
* wakes the Session later, and that execution settles instead.
|
||||
*/
|
||||
export const Settled = Event.ephemeral({ type: "session.settled", schema: Base })
|
||||
export type Settled = typeof Settled.Type
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue