Repository navigation
feat(codemode): add scoped worker handles and read-only closed workers - #67411
Conversation
There was a problem hiding this comment.
The design hangs together, and the PR's tests and type checks pass. I couldn't drive an agents.start() script end to end: the simulated model's execute call never showed up in the TUI before I ran out of time. The one test failure I saw also fails on the base.
Public API:
- Adds
ConflictError(HTTP 409) to the sessionskillandshellendpoints in the OpenAPI spec and client. It is also returned, unchanged in the spec, for prompts and compaction on a closed Code Mode worker session. - Adds the
Session.ClosedErrorexport in core. - Script globals (behind the
codemode_agentsflag): addsagents.start().
This is additive for clients. The change for users is that some sessions now reject prompts they used to accept (see the first point below).
Concerns:
- Whether a worker is closed comes from a process-local
Setplus the permanentcodemodeAgentmarker. Effects:- Every existing
agent()child, including ones created before this change, becomes permanently read-only after upgrade or restart. - The docs used to say users could open and continue these children.
- A second server process sharing the database treats another process's live workers as closed.
- Every existing
- The shell-notice change in
shell.tsisn't limited to workers.cancelSessioncancellations stop posting the "Cancelled" notice for every session, which the description says stays the same for non-worker sessions. - The worker mailbox in
codemode-agents.tsis about 370 lines of hand-rolled state built on manyDeferred.makeUnsafecalls, all insidestart. A smallWorkermodule built from Effect parts (a queue, or a semaphore plus a fiber handle per turn) would be easier to reason about and test. codemode-agents-e2e.test.tsgrows by about 320 lines. Please cut it down to the core cases: one-shot cleanup, FIFO ask, stop, close, and closed-session rejection.
Related: #66691
| // Process-local registries for live worker handles and sessions currently being torn down. | ||
| // A worker session accepts turns only while present in `openWorkers`; once released (or after a restart), | ||
| // its durable `METADATA_KEY` marks it permanently closed (read-only). | ||
| const openWorkers = new Set<string>() |
There was a problem hiding this comment.
A session counts as "closed" when it has the durable marker but isn't in this in-memory Set. Every agent() child ever created, including those from before this change, becomes read-only (409) once its script ends or the server restarts. Users can no longer continue them from the TUI, which the old docs allowed. A second server process sharing the database (see #51213) also sees every live worker as closed and rejects its turns.
Could close() write a durable closed: true on the marker, with the read-only check keyed on that? The startup cleanup in restart.ts can still treat unclosed workers with no surviving script as dead.
There was a problem hiding this comment.
Fixed in 09ef80b:
- Added optional
closed?: booleantoCodeModeAgents.SessionMarker(decoded bysessionMarker) and keyedCodeModeAgents.isClosedWorker(sessionID, metadata)strictly onmarker?.closed === truerather than absence from process-localopenWorkers. close()synchronously markschild.idstopping (markStopping), persists{ childID, structured: false, closed: true }durably viasessions.setMetadata, then cancels jobs, interrupts/waits execution, recursively stops descendants, and unmarks stopping.Sessionturn guards (prompt,resume,compact,shell,skill) checkisClosedWorker || isStopping, so historical pre-upgradeagent()children and live workers owned by a second server process sharing the DB are no longer falsely rejected.restart.tsstill treats bothmarker.closed === trueand orphaned unclosed workers (neither active nor locally open) in pending jobs / suspended claims as dead worker trees, cleans up their jobs/daemon shells/claims, and durably persistsclosed: trueon orphaned workers.- Updated
codemode-agents.md/ inline guide and added unit + e2e regression tests covering persistedclosed: true, unclosed markers from another process, and restart cleanup.
There was a problem hiding this comment.
The fix in 09ef80b resolves this thread, and I found no regressions.
- Read-only check: it now depends only on the stored flag.
isClosedWorkerreturnssessionMarker(...)?.closed === true(agents.ts:69-71). Children from before the upgrade never gotclosed, so they stay writable. So do workers that a second process holds open. close(): the worker drops out ofopenWorkersand is marked stopping synchronously (codemode-worker.ts:172-173).onClosethen savesclosed: truebeforestopTreeruns (codemode-agents.ts:369-373). The per-asksetMarker(undefined)is skipped onceisClosing()is true (line 315), so a turn that finishes late can't wipe the flag. One-shotagent()closes throughacquireUseRelease, so those children also become read-only once the script ends. That is the intended behaviour.- Session guards:
requireOpenchecksisClosedWorker || isStopping(session.ts:60-63).
One leftover in the shared-database case from #51213: restart.ts treats a worker as orphaned when it is not in this process's active set or openWorkers. Meanwhile jobs.pendingBackground reads every row in the job table (job.ts:621). So if process B restarts while process A has a live worker with a running background job, B will cancel that worker's jobs and save closed: true on it. Restart recovery already reads the whole table for other sessions too, so this isn't new and shouldn't block the PR. It's worth knowing if multi-process support gets picked up.
What I ran: I checked out pr/head in a temporary worktree and ran test/codemode/agents.test.ts, test/codemode-agents-e2e.test.ts, test/shell-restart.test.ts and test/session-execution.test.ts: 80 pass, 0 fail. I didn't run typecheck or the full suite. I removed the worktree afterwards and didn't touch repo/. The bun.lock change in repo/ was already there before I started.
| const info = (yield* jobs.wait({ id: input.id })).info | ||
| if (!info || info.status === "running") return | ||
| // Session teardown (`cancelSession`) cancels jobs without emitting cancel notices. | ||
| if (info.status === "cancelled" && !(yield* jobs.isCancelled(input.id))) return |
There was a problem hiding this comment.
This check isn't limited to workers. Any job cancelled through Job.cancelSession (the interrupt tool, session removal) now posts no "Cancelled" notice in any session. The description says non-worker shell text stays byte-for-byte identical. If dropping the notice everywhere is intended, it's worth saying so and adding a test; otherwise gate it on input.worker.
There was a problem hiding this comment.
Fixed in 09ef80b:
- Gated the
cancelSessionnotice suppression inpackages/core/src/tool/plugin/shell.tsstrictly oninput.worker(if (input.worker && info.status === "cancelled" && !(yield* jobs.isCancelled(input.id))) return), leaving non-worker shell behavior unchanged. - Added regression tests in
packages/core/test/tool-shell.test.tsverifying thatJob.cancelSessionstill emits the"Cancelled"notice for non-worker sessions while suppressing it for worker sessions.
There was a problem hiding this comment.
The fix in 09ef80b is correct. Line 181 of packages/core/src/tool/plugin/shell.ts now only drops the notice when input.worker is true. A non-worker shell job cancelled through Job.cancelSession (the interrupt tool or session removal) gets its "Cancelled" notice again, as it does on base.
What I checked, on a temporary worktree at pr/head (the shared repo/ checkout is still on a35ac7c, so I didn't touch it):
- Both new tests pass:
bun run test test/tool-shell.test.ts -t "Job.cancelSession"gives 2 pass, 0 fail. - The worker test actually exercises the new check: I deleted line 181 and the worker-session test failed on the
pendingBackground/inboxassertions, while the non-worker test still passed. Restoring the line fixes it. So it isn't passing only because the worker is closed, which a separate check already handles. - The non-worker test asserts the old behaviour: it checks the synthetic inbox item contains "Cancelled" and that its metadata has
state: "cancelled".
One small thing, not blocking: the worker test checks that no notice arrived after two Effect.yieldNows. That works today, but it depends on scheduling. If it turns flaky, waiting on the notifier fiber or the job's settled state would make it deterministic.
I made no changes. The temporary worktree has been removed.
6d29a4f to
a35ac7c
Compare
There was a problem hiding this comment.
The new push is a rebase onto dev: the quiet-report and compaction changes now come in through #67226, and nothing else in the PR changed. The nearest Code Mode agents, subagent-report, compaction and shell-restart tests still pass (98 pass), and tsc in packages/core is clean.
Neither earlier thread is addressed yet:
- A worker still counts as closed when it isn't in the in-memory
openWorkersset. - The
cancelSessioncancel-notice check inshell.tsstill applies to every session, not only workers.
The public API impact is unchanged from my last review.
There was a problem hiding this comment.
Both earlier points are addressed:
- Sessions are now read-only only when their marker has
closed: true.close()writes it, and so does restart for orphaned workers, so olderagent()children and live workers in another process are no longer rejected. - Skipping the cancel notice in
shell.tsnow applies only to worker sessions.
Moving the worker handle into codemode-worker.ts, on an Effect Queue, also reads more simply. I found nothing new that blocks a merge.
The nearest tests pass apart from one shell test that also fails on the base, and tsc in packages/core is clean. I didn't run an agents.start() script end to end.
The public API impact is unchanged from my earlier review.
09ef80b to
c1c0f1c
Compare
There was a problem hiding this comment.
Both earlier points still hold after the rebase:
- Read-only depends only on a durable
closed: truein the session's marker. - The shell cancel-notice skip still applies only to workers.
The nearest tests pass apart from one shell test that also fails on the base, and tsc is clean in packages/core and packages/codemode. I didn't run a script end to end.
The rebase onto #67628 (durable agent()) needs another look where the two meet:
- The startup cleanup in
restart.tsnow marks durableagent()children closed and kills their shells (see inline). - A wait on a child that is already closed returns its last reply as a success (see inline).
The description also no longer matches the code: it says agent() is built on agents.start() with acquireUseRelease, but it now uses dev's durable start/wait/cancel plus closeAgent.
The public API impact is unchanged from my earlier reviews.
| dead = true | ||
| break | ||
| } | ||
| if (!active.has(session.id) && !CodeModeAgents.isOpenWorker(session.id)) { |
There was a problem hiding this comment.
Since #67628, agent() children are durable: a wait reconnects to the child by childSessionID. They carry the same codemodeAgent marker but are never added to openWorkers. So at startup every unfinished agent() child is treated here as an orphaned worker: its shells are killed, its claim is released, and it is persisted as closed: true.
On dev these children were only released, and a resumed wait could still prompt them again for a retry or reminder. With this change, that prompt gets a ClosedError. Could this only target agents.start() workers, for example with a kind on the marker, or leave agent() children to closeAgent?
| // and limit detection use the child's durable outcome rather than the transient resume error. | ||
| const resumed = yield* Effect.result(sessions.resume(childID)) | ||
| const resumed = yield* Effect.result( | ||
| sessions.resume(childID).pipe(Effect.catchTag("Session.ClosedError", () => Effect.void)), |
There was a problem hiding this comment.
If the child is already closed (by restart above, or by a closeAgent that ran earlier), swallowing ClosedError makes attempt read the child's last assistant message and return it as a successful result. That message may be stale or incomplete. A closed child should probably fail the wait (or be read only when it actually finished), rather than resolving agent() with whatever text was last written.
- interrupt always silences the doorbell (idle, stopping or running) and always reaches the coordinator, which bumps interruptEpoch first - a start overtaken by an interrupt takes nothing: unforced starts roll back as Silenced, forced ones only claim; joiners get the interrupt exit - abandonSubtrees seeds every agent() child (unless a running follow-up Job owns it), excludes keep inside the CTE, and writes in SQL - automation rewake pokes instead of ringing over a user stop - migration test for the wake_on_restart -> doorbell backfill - abandonSubtrees treats every Code Mode worker not held open as dead, matching #67411's closed-worker model (its restart sweep runs first)
- interrupt always silences the doorbell (idle, stopping or running) and always reaches the coordinator, which bumps interruptEpoch first - a start overtaken by an interrupt takes nothing: unforced starts roll back as Silenced, forced ones only claim; joiners get the interrupt exit - abandonSubtrees seeds every agent() child (unless a running follow-up Job owns it), excludes keep inside the CTE, and writes in SQL - automation rewake pokes instead of ringing over a user stop - migration test for the wake_on_restart -> doorbell backfill - abandonSubtrees treats every Code Mode worker not held open as dead, matching #67411's closed-worker model (its restart sweep runs first)
Summary
Adds reusable Code Mode worker handles (
agents.start()), scoped teardown, and read-only closed workers — guarded behind the existingcodemode_agentsfeature flag.Key Changes
packages/codemode): Scopesprogram().run()/resume().run()withEffect.scopedso extension finalizers run on return, throw, timeout, suspend, or interruption.packages/core/src/codemode/agents.ts,packages/core/src/tool/plugin/codemode-agents.ts):await agents.start({ agent?, model?, effort?, label? })returning{ id, ask, jobs, stop, close }, and implements one-shotagent()cleanly on top viaEffect.acquireUseRelease.w.ask(message, { schema?, retries? })with per-turnstructured_outputisolation and sharedrun.stoppedusage/rate-limit circuit breaker (no hardcoded limits or semaphores).w.jobs()reports currently runningshellandcodemodebackground jobs owned by the worker.w.stop()cancels the active turn and queued asks while keeping the handle open.w.close()idempotently releases the worker from the live registry, marks it stopping, cancels its jobs and descendants cleanly without parent or worker notices, and closes its scope.packages/core/src/session/session.ts,error.ts,packages/server,packages/protocol,packages/client):codemodeAgentmetadata permanently on worker sessions.prompt,shell,skill,compact,resume) on closed workers withSession.ClosedError(mapped to HTTP 409ConflictError) while keeping reads/inspection/removal working.session/execution.tsandsession/run-coordinator.tsuntouched.restart.ts: Drops orphaned dead-worker background jobs, stops any daemon shells they left running, and releases dead-worker and descendant claims before recovery.subagent-report.ts&compaction-subagents.ts: Suppresses<background-result>reports for Code Mode workers, stopping children, and descendants of closed/stopping workers; excludes Code Mode children from compaction subagent lists.shell.ts&codemode/job.ts: SuppressesJob.cancelSessioncancel notices viajobs.isCancelled(id)while keeping non-worker shell text byte-for-byte identical.agents.start()and scoped auto-close in the inline guide andcodemode-agents.md.agent()/agents.start()instructions insession/context.tswhen the session policy deniessubagent.{ action: "wait", resource: "*", effect: "allow" }on worker children so deny-by-default workers can calltools.wait.Compatibility Notes
codemode_agentsfeature flag.tools.wait) and fix(codemode): keep agent() children quiet in subagent reports and compaction #67226 (quiet parent reports & compaction).agents.startwill becomeagent.startoncepsychoscript#147lands and is bumped.Verification
bun typecheckandbun run typecheck:tscinpackages/codemodeandpackages/corebun run checkacross all 37 packagesbun run check:generatedinpackages/protocolandpackages/clientbun run test test/codemode/agents.test.ts test/codemode-agents-e2e.test.ts test/subagent-report.test.ts test/session-compaction.test.ts test/shell-restart.test.ts test/session-execution.test.ts(146 pass, 0 fail)bun run test test/codemode-agents-e2e.test.ts --rerun-each 5(60 pass, 0 fail)bun run --cwd packages/codemode test(325 pass, 0 fail)Added by the opencode bot (AI-generated).
Related: #66691
Public API: adds ConflictError (409) to the session skill/shell endpoints and returns it for prompts on closed Code Mode worker sessions; adds the agents.start() script global behind codemode_agents (additive for clients)