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
22 changes: 20 additions & 2 deletions packages/core/src/background-job.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ export type Info = {
output?: string
error?: string
metadata?: Record<string, unknown>
/**
* Set when the cancellation was part of a session's teardown — an ancestor
* session stopped and swept up the jobs beneath it — rather than a request
* that targeted this job's own session. A delivery from such a job would go
* to the session that is being torn down, so background notifications drop
* it instead of resurrecting the run.
*/
cancelledByTeardown?: boolean
}

type Active = {
Expand Down Expand Up @@ -85,6 +93,15 @@ export type WaitResult = {
timedOut: boolean
}

export type CancelOptions = {
/**
* The cancel is a consequence of an ancestor session stopping, not a request
* aimed at this job's own session. Recorded on the job so the notification
* path can drop a delivery that would prompt the session being torn down.
*/
teardown?: boolean
}

export interface Interface {
readonly list: () => Effect.Effect<Info[]>
readonly get: (id: string) => Effect.Effect<Info | undefined>
Expand All @@ -93,7 +110,7 @@ export interface Interface {
readonly wait: (input: WaitInput) => Effect.Effect<WaitResult>
readonly waitForPromotion: (id: string) => Effect.Effect<Info>
readonly promote: (id: string) => Effect.Effect<Info | undefined>
readonly cancel: (id: string) => Effect.Effect<Info | undefined>
readonly cancel: (id: string, options?: CancelOptions) => Effect.Effect<Info | undefined>
}

export class Service extends Context.Service<Service, Interface>()("@opencode/BackgroundJob") {}
Expand Down Expand Up @@ -334,7 +351,7 @@ export const make = Effect.gen(function* () {
return result.info
})

const cancel: Interface["cancel"] = Effect.fn("BackgroundJob.cancel")(function* (id) {
const cancel: Interface["cancel"] = Effect.fn("BackgroundJob.cancel")(function* (id, options) {
const completed_at = yield* Clock.currentTimeMillis
const result = yield* SynchronizedRef.modify(state.jobs, (jobs): readonly [FinishResult, Map<string, Active>] => {
const job = jobs.get(id)
Expand All @@ -348,6 +365,7 @@ export const make = Effect.gen(function* () {
...job.info,
status: "cancelled" as const,
completed_at,
...(options?.teardown ? { cancelledByTeardown: true } : {}),
},
}
return [{ info: snapshot(next), done: job.done, scope: job.scope }, new Map(jobs).set(id, next)]
Expand Down
22 changes: 22 additions & 0 deletions packages/core/src/review-loop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,24 @@ function isSynchronousReviewTask(part: ReviewHistoryPart) {
return isReviewTask(part) && inputRecord(part)?.background === false
}

function taskTerminationReason(part: ReviewHistoryPart) {
const metadata = isRecord(part.state?.metadata) ? part.state.metadata : undefined
const termination = isRecord(metadata?.termination) ? metadata.termination : undefined
return typeof termination?.reason === "string" ? termination.reason : undefined
}

/**
* A cancelled subagent delivered no review. The tool reports the cancellation as
* a completed part carrying the typed reason, so without this the evaluator
* counts a cancellation as a delivered review — and a few of them walk the turn
* to the iteration cap and disable the review gate entirely.
*/
function isCancelledReviewTask(part: ReviewHistoryPart) {
if (!isSynchronousReviewTask(part)) return false
if (part.state?.status === "cancelled") return true
return taskTerminationReason(part) === "cancelled"
}

function isFileWritingTool(part: ReviewHistoryPart) {
if (part.type !== "tool" || typeof part.tool !== "string") return false
if (part.state?.status !== "completed") return false
Expand Down Expand Up @@ -199,6 +217,10 @@ export function reviewLoopState(messages: readonly ReviewHistoryMessage[], maxIt
for (const part of current.flatMap((message) => message.parts)) {
if (isReviewTask(part)) {
if (!isSynchronousReviewTask(part)) continue
// A cancelled review is a non-event: it never delivered a verdict, so it
// neither counts toward the cap nor disturbs the verdict already on
// record.
if (isCancelledReviewTask(part)) continue

if (part.state?.status !== "completed") {
latest = undefined
Expand Down
15 changes: 15 additions & 0 deletions packages/core/test/background-job.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,21 @@ describe("BackgroundJob", () => {
}).pipe(Effect.provide(jobsLayer)),
)

it.live("records a cancellation that cascaded from an ancestor's teardown", () =>
Effect.gen(function* () {
const jobs = yield* BackgroundJob.Service
const own = yield* jobs.start({ id: "job_own", type: "test", run: Effect.never })
const descendant = yield* jobs.start({ id: "job_descendant", type: "test", run: Effect.never })

expect(yield* jobs.cancel(own.id)).toMatchObject({ status: "cancelled" })
expect(yield* jobs.get(own.id)).not.toHaveProperty("cancelledByTeardown")
expect(yield* jobs.cancel(descendant.id, { teardown: true })).toMatchObject({
status: "cancelled",
cancelledByTeardown: true,
})
}).pipe(Effect.provide(jobsLayer)),
)

it.live("interrupts live work without promising settlement after the owning process-local scope closes", () =>
Effect.gen(function* () {
const scope = yield* Scope.make()
Expand Down
3 changes: 2 additions & 1 deletion packages/opencode/src/background/job.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Effect, Layer } from "effect"

export {
Service,
type CancelOptions,
type ExtendInput,
type Info,
type Interface,
Expand All @@ -27,7 +28,7 @@ const layer = Layer.effect(
wait: (input) => InstanceState.useEffect(state, (jobs) => jobs.wait(input)),
waitForPromotion: (id) => InstanceState.useEffect(state, (jobs) => jobs.waitForPromotion(id)),
promote: (id) => InstanceState.useEffect(state, (jobs) => jobs.promote(id)),
cancel: (id) => InstanceState.useEffect(state, (jobs) => jobs.cancel(id)),
cancel: (id, options) => InstanceState.useEffect(state, (jobs) => jobs.cancel(id, options)),
})
}),
)
Expand Down
8 changes: 7 additions & 1 deletion packages/opencode/src/session/run-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,12 +132,18 @@ const cancelBackgroundJobs = Effect.fn("SessionRunState.cancelBackgroundJobs")(f
if (typeof job.metadata?.sessionId === "string" && pending.has(job.metadata.sessionId)) return true
return typeof job.metadata?.parentSessionId === "string" && pending.has(job.metadata.parentSessionId)
}
// A job is the session's own run only while it is the run that was asked to
// stop. Everything else the walk reaches - the jobs of descendants - is being
// swept up because the session that owns it is going away, and a delivery from
// those would prompt a session that is stopping.
const ownedBySession = (job: BackgroundJob.Info) =>
job.id === sessionID || job.metadata?.sessionId === sessionID
let batch = jobs.filter(matches)
while (batch.length > 0) {
yield* Effect.forEach(
batch,
(job) =>
background.cancel(job.id).pipe(
background.cancel(job.id, { teardown: !ownedBySession(job) }).pipe(
Effect.tap(() =>
Effect.sync(() => {
cancelled.add(job.id)
Expand Down
17 changes: 16 additions & 1 deletion packages/opencode/src/tool/finish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,25 @@ import { Config } from "@/config/config"
import { finishGateError, reviewLoopState } from "../session/review-loop"
import { isReviewAgent } from "../agent/review-agents"

export const Reason = Schema.Literals(["success", "subagent_wait", "failure"])
const DeclaredReasons = ["success", "subagent_wait", "failure"] as const

export const Reason = Schema.Literals(DeclaredReasons)

export type Reason = Schema.Schema.Type<typeof Reason>

/**
* The full termination contract for a finished run, as delivered to a parent
* through a `<termination reason="...">` element.
*
* The model only ever declares {@link Reason} on the finish tool; `cancelled`
* cannot be declared there. A cancelled subagent never reaches a finish call —
* the user stops it mid-run — so the runtime records the cancellation itself
* instead of forcing the reason through a tool input the model never supplied.
*/
export const TerminationReason = Schema.Literals([...DeclaredReasons, "cancelled"])

export type TerminationReason = Schema.Schema.Type<typeof TerminationReason>

export const Parameters = Schema.Struct({
reason: Reason.annotate({
description:
Expand Down
63 changes: 53 additions & 10 deletions packages/opencode/src/tool/task.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as Tool from "./tool"
import { FinishTool, readTermination, type Reason } from "@/tool/finish"
import { FinishTool, readTermination, type TerminationReason } from "@/tool/finish"
import DESCRIPTION from "./task.txt"
import { SessionV1 } from "@opencode-ai/core/v1/session"
import { ReviewReport } from "@opencode-ai/core/review-report"
Expand Down Expand Up @@ -69,23 +69,31 @@ export const Parameters = Schema.Struct({
* note: the reason is the signal, and the result text already says the work is
* done.
*/
const TERMINATION_NOTE: Record<Reason, string> = {
const TERMINATION_NOTE: Record<TerminationReason, string> = {
success: "",
subagent_wait: "Subagent stopped on a dependency and is not in flight; it will not report back on its own.",
failure: "Subagent stopped because the task could not be completed.",
cancelled: "Subagent stopped because the user cancelled it; it did not complete and its result was not delivered.",
}

/**
* Stand-in result for a cancelled run. A cancelled child never reaches a finish
* call, so there is usually no output at all; the envelope must still say what
* became of the task instead of delivering an empty result.
*/
const CANCELLED_TEXT = "The subagent was cancelled by the user before it delivered a result."

/**
* Renders the parent-facing `<task>` envelope. The termination reason is part of
* the envelope, not of the injected text, so a background notification and a
* foreground tool result carry byte-identical termination for the same run.
*/
function renderOutput(input: {
sessionID: SessionID
state: "running" | "completed" | "error"
state: "running" | "completed" | "error" | "cancelled"
summary?: string
text: string
termination?: Reason
termination?: TerminationReason
}) {
const tag = input.state === "error" ? "task_error" : "task_result"
return [
Expand Down Expand Up @@ -298,8 +306,10 @@ export const TaskTool = Tool.define(
// The child declares why it stopped on the finish tool input. Capture it
// once, where the reply is already in hand, so the background and the
// foreground delivery paths below report the same value without either
// one re-reading the child transcript.
const termination = yield* Ref.make<Reason | undefined>(undefined)
// one re-reading the child transcript. A cancelled run never made a
// finish call; that path records `cancelled` itself, so this ref holds the
// whole termination contract rather than only the declared subset.
const termination = yield* Ref.make<TerminationReason | undefined>(undefined)

const runTask = Effect.fn("TaskTool.runTask")(function* () {
const parts = yield* ops.resolvePromptParts(params.prompt)
Expand Down Expand Up @@ -374,9 +384,9 @@ export const TaskTool = Tool.define(
})

const inject = Effect.fn("TaskTool.injectBackgroundResult")(function* (
state: "completed" | "error",
state: "completed" | "error" | "cancelled",
text: string,
termination: Reason | undefined,
termination: TerminationReason | undefined,
) {
// Notifications must run in the parent session, under the parent agent -
// the same one the routing above read, not a second opinion taken when
Expand All @@ -398,7 +408,9 @@ export const TaskTool = Tool.define(
summary:
state === "completed"
? `Background task completed: ${params.description}`
: `Background task failed: ${params.description}`,
: state === "cancelled"
? `Background task cancelled: ${params.description}`
: `Background task failed: ${params.description}`,
text,
termination,
}),
Expand All @@ -420,6 +432,20 @@ export const TaskTool = Tool.define(
// reason was captured before that failure, so deliver it rather
// than reporting a bare <task_error> with no signal.
if (result.info?.status === "error") return yield* inject("error", result.info.error ?? "", reason)
// A cancelled run produced no finish call and no declared reason.
// The job outcome is the termination: deliver it so the parent
// resumes orchestration knowing the user stopped the child,
// instead of never hearing about a subagent that vanished.
//
// A cancel that cascaded from an ancestor's teardown is the
// exception: cancelling a session (Ctrl+C, or its own double-Esc)
// sweeps up every job beneath it, so delivering those would prompt
// the session that is stopping and undo the interrupt. Only a
// cancellation aimed at this job's own session is reported.
if (result.info?.status === "cancelled") {
if (result.info.cancelledByTeardown) return
return yield* inject("cancelled", result.info.output ?? CANCELLED_TEXT, "cancelled")
}
}),
),
Effect.forkIn(scope, { startImmediately: true }),
Expand Down Expand Up @@ -499,7 +525,24 @@ export const TaskTool = Tool.define(
)
if (result?.metadata?.background === true) return backgroundResult()
if (result?.status === "error") return yield* Effect.fail(new Error(result.error ?? "Task failed"))
if (result?.status === "cancelled") return yield* Effect.fail(new Error("Task cancelled"))
// Cancellation is a delivery, not a tool failure: the parent is
// blocked on this call, and a free-form failure would leave it
// re-deriving what happened from prose. The same envelope the
// background path injects carries the typed reason here.
if (result?.status === "cancelled")
return {
title: params.description,
metadata: {
...metadata,
termination: { reason: "cancelled" },
},
output: renderOutput({
sessionID: nextSession.id,
state: "cancelled",
text: result.output ?? CANCELLED_TEXT,
termination: "cancelled",
}),
} satisfies Tool.ExecuteResult
// Re-associate the delivered review report with the result metadata
// so consumers know which revision was reviewed without re-parsing
// the output. The output already carries the canonical envelope.
Expand Down
32 changes: 32 additions & 0 deletions packages/opencode/test/session/review-loop.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,38 @@ describe("runtime review gate", () => {
expect(finishGateError(state)).toBeUndefined()
})

test("ignores a cancelled review instead of counting it as a delivered one", () => {
const approved = reviewMessage("### Assessment\n\n**Ready to proceed?** Approved")
const cancelled = reviewMessage("", { metadata: { termination: { reason: "cancelled" } } })

// A cancelled review that follows an approval leaves that approval intact.
const stillApproved = reviewLoopState([
userMessage(),
toolMessage("edit", { writesFiles: true }),
approved,
cancelled,
])
expect(stillApproved.verdict).toBe("approved")
expect(stillApproved.reviews).toBe(1)
expect(finishGateError(stillApproved)).toBeUndefined()

// Cancellations must not pile up into the iteration cap and silently
// disable the gate: each one is a non-event.
const cancelledTwice = reviewLoopState(
[
userMessage(),
toolMessage("edit", { writesFiles: true }),
cancelled,
toolMessage("edit", { writesFiles: true }),
cancelled,
],
2,
)
expect(cancelledTwice.reviews).toBe(0)
expect(cancelledTwice.verdict).toBe("pending")
expect(finishGateError(cancelledTwice)).toBeInstanceOf(Error)
})

test("does not treat an incomplete or malformed review as approval", () => {
const running = reviewMessage("", { status: "running" })
const malformed = reviewMessage("review failed before producing an assessment")
Expand Down
8 changes: 8 additions & 0 deletions packages/opencode/test/tool/finish-reason.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ describe("tool.finish termination reason", () => {
})

test("rejects unknown reasons", () => {
expect(() => Schema.decodeUnknownSync(Parameters)({ reason: "aborted", result: "done" })).toThrow()
})

// Cancellation is a runtime outcome recorded by the tool, never something the
// model declares: a cancelled child is stopped mid-run and reaches no finish
// call at all. The finish input therefore still refuses it even though the
// delivered termination contract carries it.
test("rejects a runtime-only reason", () => {
expect(() => Schema.decodeUnknownSync(Parameters)({ reason: "cancelled", result: "done" })).toThrow()
})

Expand Down
Loading
Loading