Skip to content

Commit 4cb2aea

Browse files
committed
feat(core): session.stop ends a session until it is given work again: its turn, its background work and queued input, and its parent hears it cancelled once
1 parent eb39956 commit 4cb2aea

19 files changed

Lines changed: 216 additions & 8 deletions

‎packages/core/src/job.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,11 @@ export interface Interface {
167167
readonly backgroundAll: (input: BackgroundAllInput) => Effect.Effect<Info[]>
168168
readonly cancel: (id: string) => Effect.Effect<Info | undefined>
169169
readonly cancelSession: (sessionID: SessionSchema.ID) => Effect.Effect<Info[]>
170+
/**
171+
* Cancels each running job the Session owns, as `cancel` does one: its shells, images and its own subagents' jobs.
172+
* Its own subagent job, which its parent owns and whose settlement reports to that parent, is left running.
173+
*/
174+
readonly cancelOwned: (sessionID: SessionSchema.ID) => Effect.Effect<Info[]>
170175
readonly pendingBackground: Effect.Effect<readonly Background[]>
171176
readonly runningBackground: Effect.Effect<readonly Recovery[]>
172177
readonly backgroundJobs: Effect.Effect<readonly JobList.Item[]>
@@ -579,6 +584,20 @@ export const make = Effect.gen(function* () {
579584
return cancelled.filter((info): info is Info => info !== undefined)
580585
})
581586

587+
const cancelOwned: Interface["cancelOwned"] = Effect.fn("Job.cancelOwned")(function* (sessionID) {
588+
const ids = [...(yield* SynchronizedRef.get(state.jobs)).values()]
589+
.filter(
590+
(job) =>
591+
job.info.status === "running" &&
592+
job.info.id !== sessionID &&
593+
(job.info.metadata?.sessionID === sessionID ||
594+
(job.recovery !== undefined && ownerSessionID(job.recovery) === sessionID)),
595+
)
596+
.map((job) => job.info.id)
597+
const cancelled = yield* Effect.forEach(ids, (id) => cancelInternal(id, true))
598+
return cancelled.filter((info): info is Info => info !== undefined)
599+
})
600+
582601
const pendingBackground: Interface["pendingBackground"] = Effect.gen(function* () {
583602
const rows = yield* db
584603
.select()
@@ -715,6 +734,7 @@ export const make = Effect.gen(function* () {
715734
backgroundAll,
716735
cancel,
717736
cancelSession,
737+
cancelOwned,
718738
pendingBackground,
719739
runningBackground,
720740
backgroundJobs: JobList.read(db, state.jobs),

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -610,6 +610,7 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: Pick<Interfa
610610
.interrupt(input.sessionID, { resume: input.resume })
611611
.pipe(Effect.map((interrupted) => ({ interrupted }))),
612612
wait: (input) => sessions.wait(input.sessionID),
613+
stop: (input) => sessions.stop(input.sessionID).pipe(Effect.map((interrupted) => ({ interrupted }))),
613614
context: (input) => sessions.context(input.sessionID),
614615
instructions: {
615616
entry: {

‎packages/core/src/session.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,12 @@ export interface Interface {
245245
readonly background: (sessionID: SessionSchema.ID) => Effect.Effect<void, NotFoundError>
246246
readonly resume: (sessionID: SessionSchema.ID) => Effect.Effect<void, NotFoundError | SessionRunner.RunError>
247247
readonly interrupt: (sessionID: SessionSchema.ID, options?: { readonly resume?: boolean }) => Effect.Effect<boolean>
248+
/**
249+
* Stops the Session until it is given work again (SessionExecution.stop): its active work, the background work it
250+
* owns, and its queued input end; a subagent child reports cancelled to its parent once, and nothing after.
251+
* Returns whether active work was interrupted. Experimental.
252+
*/
253+
readonly stop: (sessionID: SessionSchema.ID) => Effect.Effect<boolean, NotFoundError>
248254
readonly synthetic: (
249255
input: Parameters<Session.Handle["synthetic"]>[0] & { sessionID: SessionSchema.ID },
250256
) => ReturnType<Session.Handle["synthetic"]>
@@ -545,6 +551,24 @@ const layer = Layer.effect(
545551
resume: (sessionID) => sessions.forSession(sessionID).resume(),
546552
synthetic: (input) => sessions.forSession(input.sessionID).synthetic(input),
547553
interrupt: (sessionID, options) => sessions.forSession(sessionID).interrupt(options),
554+
stop: Effect.fn("Session.stop")(function* (sessionID) {
555+
yield* result.get(sessionID)
556+
const interrupted = yield* execution.stop(sessionID)
557+
// Queued input would run at its next task as if still wanted: it goes with the stop.
558+
yield* Effect.forEach(
559+
yield* result.inbox(sessionID),
560+
(item) =>
561+
result
562+
.cancelInbox({ sessionID, inboxID: item.id })
563+
.pipe(
564+
Effect.catchCause((cause) =>
565+
Effect.logWarning("stop: queued input not cancelled", { sessionID, cause }),
566+
),
567+
),
568+
{ discard: true },
569+
)
570+
return interrupted
571+
}),
548572
revert: {
549573
stage: (input) => sessions.forSession(input.sessionID).revert.stage(input),
550574
clear: (sessionID) => sessions.forSession(sessionID).revert.clear(),

‎packages/core/src/session/execution.ts‎

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { Bus } from "../bus.js"
55
import { Database } from "../database/database.js"
66
import { Job } from "../job.js"
77
import { Instance } from "../instance/service.js"
8+
import { KV } from "../kv.js"
89
import { makeGlobalNode } from "@opencode/util/effect/app-node"
910
import { SessionEvent } from "./event.js"
1011
import { SessionInbox } from "./inbox.js"
@@ -38,8 +39,22 @@ export interface Interface {
3839
) => Effect.Effect<boolean>
3940
/** Resolves once this process owns no active execution for the Session. Returns immediately when idle and never starts work. */
4041
readonly awaitIdle: (sessionID: SessionSchema.ID) => Effect.Effect<void>
42+
/**
43+
* Stops the Session until it is given work again: marks it stopped (durably), cancels the background work it owns
44+
* (its shells, its own subagents' jobs; not its own subagent job), interrupts its active work and waits for that
45+
* to settle. A running subagent child settles as cancelled and reports that to its parent once. While stopped, a
46+
* notice admitted to it does not wake it, and a later period of it (its owner prompting it) reports nothing to its
47+
* parent. A `resume` (a parent's subagent tool giving it a new task) ends the stop. Returns whether active work was
48+
* interrupted. Queued input is the Session's to drop (`Session.stop`).
49+
*/
50+
readonly stop: (sessionID: SessionSchema.ID) => Effect.Effect<boolean>
51+
/** Whether the Session was stopped and not resumed since. */
52+
readonly stopped: (sessionID: SessionSchema.ID) => Effect.Effect<boolean>
4153
}
4254

55+
/** The KV key prefix of a stopped Session's mark. */
56+
const STOPPED = "session.stopped:"
57+
4358
/** Routes execution from a Session ID to its selected instance's runner. */
4459
export class Service extends Context.Service<Service, Interface>()("@opencode/SessionExecution") {}
4560

@@ -70,6 +85,9 @@ export const layer = Layer.effect(
7085
const jobs = yield* Job.Service
7186
const inbox = yield* SessionInbox.Service
7287
const db = (yield* Database.Service).db
88+
const kv = yield* KV.Service
89+
const stopped = (sessionID: SessionSchema.ID) =>
90+
kv.get(STOPPED + sessionID).pipe(Effect.map((mark) => mark !== undefined))
7391
const reportLifecycle = <A>(sessionID: SessionSchema.ID, effect: Effect.Effect<A>) =>
7492
effect.pipe(
7593
Effect.tapCause((cause) =>
@@ -103,6 +121,7 @@ export const layer = Layer.effect(
103121
draining: Effect.suspend<ReadonlySet<SessionSchema.ID>, never, never>(() =>
104122
holder.coordinator ? holder.coordinator.draining : Effect.succeed(new Set<SessionSchema.ID>()),
105123
),
124+
stopped,
106125
})
107126
// Why a Session's execution is being interrupted, read from the coordinator once it exists.
108127
let interruption: (sessionID: SessionSchema.ID) => InterruptReason | undefined = () => undefined
@@ -208,9 +227,20 @@ export const layer = Layer.effect(
208227
yield* coordinator.wake(sessionID, "steer")
209228
return interrupted
210229
}),
211-
resume: coordinator.run,
230+
// New work ends a stop: the mark goes before the run starts, so its period reports as any other.
231+
resume: (sessionID) => kv.remove(STOPPED + sessionID).pipe(Effect.andThen(coordinator.run(sessionID))),
212232
wake: coordinator.wake,
213233
awaitIdle: coordinator.awaitIdle,
234+
stop: (sessionID) =>
235+
Effect.gen(function* () {
236+
// Marked first: a notice its cancelled work admits, or a report of its own subagents, must not wake it.
237+
yield* kv.set(STOPPED + sessionID, true)
238+
yield* jobs.cancelOwned(sessionID)
239+
const interrupted = yield* coordinator.interrupt(sessionID, "user")
240+
yield* coordinator.awaitIdle(sessionID)
241+
return interrupted
242+
}),
243+
stopped,
214244
})
215245
}),
216246
)
@@ -232,7 +262,7 @@ function publishTerminal(
232262
export const node = makeGlobalNode({
233263
service: Service,
234264
layer,
235-
deps: [SessionStore.node, Instance.node, Bus.node, Database.node, Job.node, SessionInbox.node],
265+
deps: [SessionStore.node, Instance.node, Bus.node, Database.node, Job.node, SessionInbox.node, KV.node],
236266
})
237267

238268
/** Low-level compatibility layer for callers that only need durable Session recording. */
@@ -245,5 +275,7 @@ export const noopLayer = Layer.succeed(
245275
wake: () => Effect.void,
246276
interrupt: () => Effect.succeed(false),
247277
awaitIdle: () => Effect.void,
278+
stop: () => Effect.succeed(false),
279+
stopped: () => Effect.succeed(false),
248280
}),
249281
)

‎packages/core/src/session/execution/restart.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ export const layer = (options?: Options) =>
8989

9090
const wake = Effect.fnUntraced(function* (sessionID: SessionSchema.ID) {
9191
const owner = yield* store.get(sessionID)
92-
if (owner && !owner.revert) yield* execution.wake(sessionID)
92+
if (owner && !owner.revert && !(yield* execution.stopped(sessionID))) yield* execution.wake(sessionID)
9393
})
9494

9595
const prepareResume = Effect.fnUntraced(function* (sessionID: SessionSchema.ID) {

‎packages/core/src/session/execution/subagent-report.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@ export type Deps = {
2525
readonly inbox: Inbox
2626
readonly wake: (sessionID: SessionSchema.ID) => Effect.Effect<void>
2727
readonly draining: Effect.Effect<ReadonlySet<SessionSchema.ID>>
28+
/**
29+
* Whether the Session was stopped (`SessionExecution.stop`) and not given work since. A stopped child reports to
30+
* its parent only what a Job promised (the stop's own cancelled settlement), and a report does not wake it.
31+
*/
32+
readonly stopped: (sessionID: SessionSchema.ID) => Effect.Effect<boolean>
2833
}
2934

3035
/** Narrow inbox admission so delivery does not depend on the full lifecycle service shape. */
@@ -124,7 +129,7 @@ export const make = (deps: Deps) => {
124129
)
125130
if (!delivered) return
126131
const parent = yield* deps.store.get(parentID)
127-
if (parent && !parent.revert) yield* deps.wake(parentID)
132+
if (parent && !parent.revert && !(yield* deps.stopped(parentID))) yield* deps.wake(parentID)
128133
})
129134

130135
const prepare = Effect.fnUntraced(function* (
@@ -135,7 +140,8 @@ export const make = (deps: Deps) => {
135140
periods.delete(sessionID)
136141
const jobState = yield* deps.jobs.prepareSubagentReport(sessionID, period?.boundGeneration)
137142
const initial = yield* deps.store.get(sessionID)
138-
if (!initial?.parentID && jobState.mode === "none") {
143+
// A stopped child's later periods, woken by its owner or a stray notice, are not its parent's to hear.
144+
if (jobState.mode === "none" && (!initial?.parentID || (yield* deps.stopped(sessionID)))) {
139145
return {
140146
commit: () => deps.store.release(sessionID),
141147
deliver: Effect.void,

‎packages/core/src/session/session.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,9 @@ export const make = Effect.fn("Session.make")(function* () {
321321
() => new SyntheticConflictError({ sessionID, inputID }),
322322
),
323323
)
324-
if (input.resume !== false && !(yield* get(sessionID)).revert) yield* execution.wake(sessionID)
324+
// A stopped Session keeps a notice for its next task instead of running on it (SessionExecution.stop).
325+
if (input.resume !== false && !(yield* get(sessionID)).revert && !(yield* execution.stopped(sessionID)))
326+
yield* execution.wake(sessionID)
325327
return admitted
326328
}),
327329
),

‎packages/core/test/plugin/host.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,7 @@ export function host(overrides: Overrides = {}): Plugin.Context {
192192
move: overrides.session?.move ?? (() => Effect.die("unused session.move")),
193193
synthetic: overrides.session?.synthetic ?? (() => Effect.die("unused session.synthetic")),
194194
interrupt: overrides.session?.interrupt ?? (() => Effect.die("unused session.interrupt")),
195+
stop: overrides.session?.stop ?? (() => Effect.die("unused session.stop")),
195196
wait: overrides.session?.wait ?? (() => Effect.die("unused session.wait")),
196197
context: overrides.session?.context ?? (() => Effect.die("unused session.context")),
197198
instructions: overrides.session?.instructions ?? {

‎packages/core/test/schedule.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ const execution = Layer.succeed(
7171
return effect
7272
}),
7373
awaitIdle: () => Effect.void,
74+
stop: () => Effect.succeed(false),
75+
stopped: () => Effect.succeed(false),
7476
}),
7577
)
7678
const enabledEntries = [

‎packages/core/test/session-owned.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,8 @@ const setup = Effect.fnUntraced(function* (options?: {
104104
resumes.push(id)
105105
}),
106106
awaitIdle: () => Effect.void,
107+
stop: () => Effect.succeed(false),
108+
stopped: () => Effect.succeed(false),
107109
interrupt: () => Effect.succeed(false),
108110
wake: (id) =>
109111
Effect.gen(function* () {
@@ -637,6 +639,8 @@ describe("Session-owned handles", () => {
637639
}),
638640
wake: coordinator.wake,
639641
awaitIdle: coordinator.awaitIdle,
642+
stop: () => Effect.succeed(false),
643+
stopped: () => Effect.succeed(false),
640644
interrupt: (id, options) =>
641645
Effect.sync(() => void interrupts.push({ sessionID: id, options })).pipe(
642646
Effect.andThen(coordinator.interrupt(id)),

0 commit comments

Comments
 (0)