Skip to content

Commit 889fb67

Browse files
authored
feat(core): add a cancel tool for background work (#68207)
1 parent 3bb9ae3 commit 889fb67

9 files changed

Lines changed: 245 additions & 68 deletions

File tree

‎packages/core/src/job.ts‎

Lines changed: 38 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,8 @@ export type Info = {
7979
error?: string
8080
metadata?: Record<string, unknown>
8181
notificationID?: SessionMessage.ID
82+
/** Cancelled with `quiet`: the caller reported the cancel itself, so no completion notice follows. */
83+
quiet?: true
8284
}
8385

8486
type Active = {
@@ -174,8 +176,10 @@ export interface Interface {
174176
readonly block: (input: BlockInput) => Effect.Effect<BlockResult | undefined>
175177
readonly background: (id: string) => Effect.Effect<Info | undefined>
176178
readonly backgroundAll: (input: BackgroundAllInput) => Effect.Effect<Info[]>
177-
readonly cancel: (id: string) => Effect.Effect<Info | undefined>
178-
readonly cancelSession: (sessionID: SessionSchema.ID) => Effect.Effect<Info[]>
179+
/** With `quiet`, no completion notice follows and the job's outbox row is removed. */
180+
readonly cancel: (id: string, options?: { readonly quiet?: boolean }) => Effect.Effect<Info | undefined>
181+
/** With `quiet`, like a quiet `cancel` for each job: none of them sends a notice. */
182+
readonly cancelSession: (sessionID: SessionSchema.ID, options?: { readonly quiet?: boolean }) => Effect.Effect<Info[]>
179183
readonly pendingBackground: Effect.Effect<readonly Background[]>
180184
readonly runningBackground: Effect.Effect<readonly Recovery[]>
181185
readonly backgroundJobs: Effect.Effect<readonly JobList.Item[]>
@@ -437,7 +441,7 @@ export const make = Effect.gen(function* () {
437441
const wait: Interface["wait"] = Effect.fn("Job.wait")(function* (input) {
438442
const job = (yield* SynchronizedRef.get(state.jobs)).get(input.id)
439443
if (!job) return { timedOut: false }
440-
return yield* Effect.gen(function* () {
444+
return yield* Effect.gen(function* (): Effect.fn.Return<WaitResult> {
441445
if (job.info.status !== "running") return { info: snapshot(job), timedOut: false }
442446
if (input.timeout === undefined) return { info: yield* Deferred.await(job.done), timedOut: false }
443447
if (input.timeout <= 0) return { info: snapshot(job), timedOut: true }
@@ -449,6 +453,8 @@ export const make = Effect.gen(function* () {
449453
Effect.tap((result) =>
450454
result.info?.status === "running" || job.recovery ? Effect.void : consume(input.id, job.scope),
451455
),
456+
// A quietly cancelled job is gone, as if it had been acknowledged: its caller reported it, so no one else does.
457+
Effect.map((result) => (result.info?.quiet ? { timedOut: false } : result)),
452458
)
453459
})
454460

@@ -556,26 +562,34 @@ export const make = Effect.gen(function* () {
556562
return result.map((item) => item.info)
557563
})
558564

559-
const cancelInternal = Effect.fnUntraced(function* (id: string, persist = true) {
565+
// "caller" saves a cancelled outbox row for its notice, "quiet" leaves no row and no entry because the caller
566+
// reports the cancel itself, and "teardown" (cancelSession) only stops the work.
567+
// Uninterruptible: once the entry says cancelled, the rest must run, or waiters hang and the work keeps going.
568+
const cancelInternal = Effect.fnUntraced(function* (id: string, mode: "caller" | "quiet" | "teardown") {
569+
const quiet = mode === "quiet"
560570
const completed_at = yield* Clock.currentTimeMillis
561571
const result = yield* SynchronizedRef.modifyEffect(
562572
state.jobs,
563573
Effect.fnUntraced(function* (jobs): Effect.fn.Return<readonly [FinishResult, Map<string, Active>]> {
564574
const job = jobs.get(id)
565575
if (!job) return [{}, jobs]
566576
if (job.info.status !== "running") return [{ info: snapshot(job), generation: job.scope }, jobs]
577+
// Settling work is already reporting its outcome, so a quiet cancel can't keep it from notifying.
578+
if (quiet && job.settling) return [{ info: snapshot(job) }, jobs]
567579
const next = {
568580
...job,
569581
blockingSessions: new Map<SessionSchema.ID, number>(),
570-
cancelledByCaller: persist,
582+
cancelledByCaller: mode !== "teardown",
571583
info: {
572584
...job.info,
573585
status: "cancelled" as const,
574586
completed_at,
587+
...(quiet ? { quiet: true as const } : {}),
575588
},
576589
}
577590
// Settling work owns its outbox row: the settlement commit writes or deletes it.
578-
if (persist && !job.settling) yield* persistBackground(next)
591+
if (quiet && job.info.notificationID) yield* deleteBackgroundRow(job.info.notificationID)
592+
else if (mode === "caller" && !job.settling) yield* persistBackground(next)
579593
return [
580594
{
581595
info: snapshot(next),
@@ -589,21 +603,34 @@ export const make = Effect.gen(function* () {
589603
]
590604
}),
591605
)
592-
if (result.cancel) yield* result.cancel
606+
// A failing hook must not keep the job from settling.
607+
if (result.cancel) yield* Effect.ignoreCause(result.cancel)
593608
if (result.info && result.done) yield* Deferred.succeed(result.done, result.info)
594609
if (result.done) yield* updated(result.listed)
595610
if (result.scope) yield* Scope.close(result.scope, Exit.void)
596611
if (result.generation) yield* consume(id, result.generation)
612+
// Nothing acknowledges a quiet cancel, so its entry goes now. Notifiers already waiting got its info above.
613+
if (result.info?.quiet && result.scope) {
614+
const scope = result.scope
615+
yield* SynchronizedRef.update(state.jobs, (jobs) => {
616+
if (jobs.get(id)?.scope !== scope) return jobs
617+
const next = new Map(jobs)
618+
next.delete(id)
619+
return next
620+
})
621+
}
597622
return result.info
598-
})
623+
}, Effect.uninterruptible)
599624

600-
const cancel: Interface["cancel"] = Effect.fn("Job.cancel")((id) => cancelInternal(id, true))
625+
const cancel: Interface["cancel"] = Effect.fn("Job.cancel")((id, options) =>
626+
cancelInternal(id, options?.quiet ? "quiet" : "caller"),
627+
)
601628

602-
const cancelSession: Interface["cancelSession"] = Effect.fn("Job.cancelSession")(function* (sessionID) {
629+
const cancelSession: Interface["cancelSession"] = Effect.fn("Job.cancelSession")(function* (sessionID, options) {
603630
const ids = [...(yield* SynchronizedRef.get(state.jobs)).values()]
604631
.filter((job) => job.info.status === "running" && matchesSession(job, sessionID))
605632
.map((job) => job.info.id)
606-
const cancelled = yield* Effect.forEach(ids, (id) => cancelInternal(id, false))
633+
const cancelled = yield* Effect.forEach(ids, (id) => cancelInternal(id, options?.quiet ? "quiet" : "teardown"))
607634
yield* db
608635
.delete(JobTable)
609636
.where(or(eq(JobTable.session_id, sessionID), eq(JobTable.child_session_id, sessionID)))

‎packages/core/src/plugin/internal.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ import { ReadTool } from "../tool/plugin/read.js"
8888
import { ArtifactTools } from "../tool/plugin/artifact.js"
8989
import { AutomationTools } from "../tool/plugin/automation.js"
9090
import { SessionInterruptTool } from "../tool/plugin/session-interrupt.js"
91+
import { CancelTool } from "../tool/plugin/cancel.js"
9192
import { SessionSearchTools } from "../tool/plugin/session-search.js"
9293
import { ShellTool } from "../tool/plugin/shell.js"
9394
import { SkillTool } from "../tool/plugin/skill.js"
@@ -235,6 +236,7 @@ const pre = [
235236
ReadTool.Plugin,
236237
ArtifactTools.Plugin,
237238
AutomationTools.Plugin,
239+
CancelTool.Plugin,
238240
CdTool.Plugin,
239241
MachineTools.Plugin,
240242
SessionInterruptTool.Plugin,
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
export * as SessionStopTree from "./stop-tree.js"
2+
3+
import { Effect } from "effect"
4+
import { CodeModeAgents } from "../codemode/agents.js"
5+
import type { Job } from "../job.js"
6+
import type { Session } from "../session.js"
7+
import type { SessionSchema } from "./schema.js"
8+
9+
export const make = (sessions: Session.Interface, jobs: Job.Interface) => {
10+
const cancelPendingInbox = (sessionID: SessionSchema.ID) =>
11+
Effect.gen(function* () {
12+
const pending = yield* sessions.inbox(sessionID).pipe(Effect.orElseSucceed(() => []))
13+
yield* Effect.forEach(
14+
pending,
15+
(item) => sessions.cancelInbox({ sessionID, inboxID: item.id }).pipe(Effect.ignore),
16+
{ discard: true },
17+
)
18+
})
19+
20+
// Stops and joins everything a worker owns: queued inbox items, background jobs, its active execution, and any
21+
// descendants. Marks children stopping before cancelling their jobs so no late settlement reports to a parent, and
22+
// cancels jobs quietly so a notifier that runs after the marks are gone still sends nothing.
23+
const stopTree = (sessionID: SessionSchema.ID): Effect.Effect<void> =>
24+
Effect.gen(function* () {
25+
CodeModeAgents.markStopping(sessionID)
26+
return yield* Effect.gen(function* () {
27+
const stoppedChildren = new Set<SessionSchema.ID>()
28+
while (true) {
29+
yield* cancelPendingInbox(sessionID)
30+
const knownChildren = yield* sessions.list({ parentID: sessionID, limit: 1000 }).pipe(Effect.orDie)
31+
for (const item of knownChildren.data) CodeModeAgents.markStopping(item.id)
32+
yield* Effect.gen(function* () {
33+
yield* jobs.cancelSession(sessionID, { quiet: true })
34+
yield* sessions.interrupt(sessionID)
35+
yield* sessions.wait(sessionID).pipe(Effect.catchTag("Session.NotFoundError", () => Effect.void))
36+
yield* jobs.cancelSession(sessionID, { quiet: true })
37+
const children = yield* sessions.list({ parentID: sessionID, limit: 1000 }).pipe(Effect.orDie)
38+
for (const item of children.data) {
39+
stoppedChildren.add(item.id)
40+
yield* stopTree(item.id)
41+
}
42+
}).pipe(
43+
Effect.ensuring(
44+
Effect.sync(() => {
45+
for (const item of knownChildren.data) CodeModeAgents.unmarkStopping(item.id)
46+
}),
47+
),
48+
)
49+
const remainingInbox = yield* sessions.inbox(sessionID).pipe(Effect.orElseSucceed(() => []))
50+
const stillActive = (yield* sessions.active).has(sessionID)
51+
const nextChildren = yield* sessions.list({ parentID: sessionID, limit: 1000 }).pipe(Effect.orDie)
52+
const hasNewChild = nextChildren.data.some((item) => !stoppedChildren.has(item.id))
53+
if (remainingInbox.length === 0 && !stillActive && !hasNewChild) return
54+
}
55+
}).pipe(Effect.ensuring(Effect.sync(() => CodeModeAgents.unmarkStopping(sessionID))))
56+
})
57+
58+
return { cancelPendingInbox, stopTree }
59+
}
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
export * as CancelTool from "./cancel.js"
2+
3+
import type { Context } from "@opencode/plugin/effect/plugin"
4+
import { Effect, Option, Schema } from "effect"
5+
import { Flag } from "../../flag.js"
6+
import { Job } from "../../job.js"
7+
import type { JobList } from "../../job/list.js"
8+
import { Session } from "../../session.js"
9+
import { SessionStopTree } from "../../session/stop-tree.js"
10+
import { SessionBackground } from "../../session/background.js"
11+
import { CodeModeAgents } from "../../codemode/agents.js"
12+
import { Automation } from "@opencode/schema/automation"
13+
14+
export const name = "cancel"
15+
16+
export const Input = Schema.Struct({
17+
ids: Schema.Array(Schema.String)
18+
.check(Schema.isMinLength(1))
19+
.annotate({ description: "Ids of the background work to cancel." }),
20+
})
21+
22+
const description = [
23+
"Cancel background work by the id from its <background-result> tag or the call that started it.",
24+
"A cancelled job sends no <background-result>; this call's result is the last word on it.",
25+
].join(" ")
26+
27+
const lines = {
28+
cancelled: (id: string) => `Cancelled ${id}.`,
29+
finished: (id: string) => `${id} had already finished.`,
30+
missing: (id: string) => `No running background work with id ${id}.`,
31+
}
32+
33+
export const Plugin = {
34+
id: "opencode.tool.cancel",
35+
effect: Effect.fn("CancelTool.Plugin")(function* (ctx: Context) {
36+
const jobs = yield* Job.Service
37+
const sessions = yield* Session.Service
38+
const flags = yield* Flag.Service
39+
const { stopTree } = SessionStopTree.make(sessions, jobs)
40+
41+
// Only the caller's own running work; another session's jobs read as missing.
42+
const cancelJob = Effect.fnUntraced(function* (job: JobList.Item) {
43+
const info = yield* jobs.cancel(job.id, { quiet: true })
44+
// It finished, started reporting or was cancelled by someone else first, so its <background-result> still follows.
45+
return info?.quiet ? ("cancelled" as const) : ("finished" as const)
46+
})
47+
48+
// A subagent is a child session of the caller. Its job entry goes once it reports while its own work still runs, so
49+
// it's found by session too. Stopping it stops its jobs and subagents, waits until they're idle, and keeps every
50+
// report in the tree from reaching the caller, as `w.close()` does.
51+
const stopSubagent = Effect.fnUntraced(function* (callerID: Session.ID, id: string) {
52+
const sessionID = Schema.decodeUnknownOption(Session.ID)(id)
53+
if (Option.isNone(sessionID)) return "missing" as const
54+
const found = yield* sessions.get(sessionID.value).pipe(Effect.option)
55+
if (Option.isNone(found) || found.value.parentID !== callerID) return "missing" as const
56+
const child = found.value
57+
// An agent() worker belongs to its script, and an automation run to its automation.
58+
if (Automation.isRunSession(child.id) || CodeModeAgents.sessionMarker(child.id, child.metadata) !== undefined)
59+
return "missing" as const
60+
const active = yield* sessions.active
61+
const lookup = {
62+
get: (id: Session.ID) => sessions.get(id).pipe(Effect.option, Effect.map(Option.getOrUndefined)),
63+
}
64+
const busy =
65+
active.has(child.id) || (yield* SessionBackground.outstanding(jobs, lookup, child.id, active)).length > 0
66+
if (!busy) return "finished" as const
67+
yield* stopTree(child.id)
68+
// Stopping marks the tree first, so a report not yet admitted is dropped. One admitted earlier still waits in the
69+
// caller's inbox while this call runs.
70+
const inbox = yield* sessions.inbox(callerID).pipe(Effect.orElseSucceed(() => []))
71+
const reported = inbox.some((item) => item.type === "synthetic" && item.payload.metadata?.childID === child.id)
72+
return reported ? ("finished" as const) : ("cancelled" as const)
73+
})
74+
75+
yield* ctx.tool
76+
.transform((editor) => {
77+
if (!flags.current().full_codemode.enabled) return
78+
editor.add({
79+
name,
80+
description,
81+
input: Input,
82+
output: Schema.String,
83+
options: { codemode: false },
84+
execute: (input, context) =>
85+
Effect.gen(function* () {
86+
// Read per id: an earlier id's stop can take a while, and work finishes meanwhile.
87+
const outcome = Effect.fnUntraced(function* (id: string) {
88+
const job = (yield* jobs.backgroundJobs).find(
89+
(job) => job.id === id && job.sessionID === context.sessionID && job.status === "running",
90+
)
91+
if (job && job.kind !== "subagent") return yield* cancelJob(job)
92+
return yield* stopSubagent(context.sessionID, id)
93+
})
94+
const output = yield* Effect.forEach([...new Set(input.ids)], (id) =>
95+
outcome(id).pipe(Effect.map((result) => lines[result](id))),
96+
)
97+
return { output: output.join("\n") }
98+
}),
99+
})
100+
})
101+
.pipe(Effect.orDie)
102+
}),
103+
}

‎packages/core/src/tool/plugin/codemode-agents.ts‎

Lines changed: 4 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import type { SessionMessage } from "../../session/message.js"
1919
import { SessionSchema } from "../../session/schema.js"
2020
import { SubagentCompletion } from "../../session/subagent-completion.js"
2121
import { SubagentDepth } from "../../session/subagent-depth.js"
22+
import { SessionStopTree } from "../../session/stop-tree.js"
2223
import { toSessionError } from "../../session/to-session-error.js"
2324
import { Skill } from "../../skill.js"
2425
import { CodeModeWorker } from "./codemode-worker.js"
@@ -103,52 +104,7 @@ export const Plugin = {
103104
yield* ctx.session.hook("compaction", shape)
104105
yield* ctx.session.hook("generate", shape)
105106

106-
const cancelPendingInbox = (sessionID: SessionSchema.ID) =>
107-
Effect.gen(function* () {
108-
const pending = yield* sessions.inbox(sessionID).pipe(Effect.orElseSucceed(() => []))
109-
yield* Effect.forEach(
110-
pending,
111-
(item) => sessions.cancelInbox({ sessionID, inboxID: item.id }).pipe(Effect.ignore),
112-
{ discard: true },
113-
)
114-
})
115-
116-
// Stops and joins everything a worker owns: queued inbox items, background jobs, its active execution, and any
117-
// descendants. Marks children stopping before cancelling their jobs so no late settlement reports to a parent.
118-
const stopTree = (sessionID: SessionSchema.ID): Effect.Effect<void> =>
119-
Effect.gen(function* () {
120-
CodeModeAgents.markStopping(sessionID)
121-
return yield* Effect.gen(function* () {
122-
const stoppedChildren = new Set<SessionSchema.ID>()
123-
while (true) {
124-
yield* cancelPendingInbox(sessionID)
125-
const knownChildren = yield* sessions.list({ parentID: sessionID, limit: 1000 }).pipe(Effect.orDie)
126-
for (const item of knownChildren.data) CodeModeAgents.markStopping(item.id)
127-
yield* Effect.gen(function* () {
128-
yield* jobs.cancelSession(sessionID)
129-
yield* sessions.interrupt(sessionID)
130-
yield* sessions.wait(sessionID).pipe(Effect.catchTag("Session.NotFoundError", () => Effect.void))
131-
yield* jobs.cancelSession(sessionID)
132-
const children = yield* sessions.list({ parentID: sessionID, limit: 1000 }).pipe(Effect.orDie)
133-
for (const item of children.data) {
134-
stoppedChildren.add(item.id)
135-
yield* stopTree(item.id)
136-
}
137-
}).pipe(
138-
Effect.ensuring(
139-
Effect.sync(() => {
140-
for (const item of knownChildren.data) CodeModeAgents.unmarkStopping(item.id)
141-
}),
142-
),
143-
)
144-
const remainingInbox = yield* sessions.inbox(sessionID).pipe(Effect.orElseSucceed(() => []))
145-
const stillActive = (yield* sessions.active).has(sessionID)
146-
const nextChildren = yield* sessions.list({ parentID: sessionID, limit: 1000 }).pipe(Effect.orDie)
147-
const hasNewChild = nextChildren.data.some((item) => !stoppedChildren.has(item.id))
148-
if (remainingInbox.length === 0 && !stillActive && !hasNewChild) return
149-
}
150-
}).pipe(Effect.ensuring(Effect.sync(() => CodeModeAgents.unmarkStopping(sessionID))))
151-
})
107+
const { cancelPendingInbox, stopTree } = SessionStopTree.make(sessions, jobs)
152108

153109
const closeAgent = (childID: SessionSchema.ID) =>
154110
Effect.gen(function* () {
@@ -169,11 +125,7 @@ export const Plugin = {
169125
})
170126

171127
// Only inspects assistant messages created after `afterID`, so a later ask() never reads a prior turn's output.
172-
const recordedOutput = (
173-
childID: SessionSchema.ID,
174-
output: CodeModeAgents.Output,
175-
afterID?: SessionMessage.ID,
176-
) =>
128+
const recordedOutput = (childID: SessionSchema.ID, output: CodeModeAgents.Output, afterID?: SessionMessage.ID) =>
177129
sessions.messages({ sessionID: childID, order: "desc", type: "assistant" }).pipe(
178130
Effect.map((messages) => {
179131
for (const message of messages) {
@@ -380,10 +332,7 @@ export const Plugin = {
380332
metadata: { ...(parent.metadata ?? {}), [CodeModeAgents.METADATA_KEY]: markerFor(undefined) },
381333
// Deny-by-default subagents such as `explore` strip tools outside their allowlist; let workers return
382334
// structured answers on any ask() turn.
383-
permissions: [
384-
...(parent.permissions ?? []),
385-
{ action: OUTPUT_TOOL, resource: "*", effect: "allow" },
386-
],
335+
permissions: [...(parent.permissions ?? []), { action: OUTPUT_TOOL, resource: "*", effect: "allow" }],
387336
})
388337
const workerScope = yield* Scope.fork(pluginScope)
389338
CodeModeAgents.openWorker(child.id)

0 commit comments

Comments
 (0)