Skip to content

feat(codemode): add scoped worker handles and read-only closed workers - #67411

Merged
hearnadam merged 1 commit into
devfrom
worker-handles
Dec 2, 2026
Merged

hearnadam merged 1 commit into
devfrom
worker-handles

Conversation

@hearnadam

@hearnadam hearnadam commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds reusable Code Mode worker handles (agents.start()), scoped teardown, and read-only closed workers — guarded behind the existing codemode_agents feature flag.

Key Changes

  • Scoped Code Mode runs (packages/codemode): Scopes program().run() / resume().run() with Effect.scoped so extension finalizers run on return, throw, timeout, suspend, or interruption.
  • Worker Handles (packages/core/src/codemode/agents.ts, packages/core/src/tool/plugin/codemode-agents.ts):
    • Adds await agents.start({ agent?, model?, effort?, label? }) returning { id, ask, jobs, stop, close }, and implements one-shot agent() cleanly on top via Effect.acquireUseRelease.
    • Single-mailbox FIFO w.ask(message, { schema?, retries? }) with per-turn structured_output isolation and shared run.stopped usage/rate-limit circuit breaker (no hardcoded limits or semaphores).
    • w.jobs() reports currently running shell and codemode background 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.
  • Read-Only Closed Workers (packages/core/src/session/session.ts, error.ts, packages/server, packages/protocol, packages/client):
    • Tracks live open workers in memory while keeping codemodeAgent metadata permanently on worker sessions.
    • Rejects turn mutations (prompt, shell, skill, compact, resume) on closed workers with Session.ClosedError (mapped to HTTP 409 ConflictError) while keeping reads/inspection/removal working.
    • Leaves session/execution.ts and session/run-coordinator.ts untouched.
  • Restart, Quiet Reports, Compaction & Shell Cleanup:
    • 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: Suppresses Job.cancelSession cancel notices via jobs.isCancelled(id) while keeping non-worker shell text byte-for-byte identical.
  • Instructions & Permissions:
    • Documents agents.start() and scoped auto-close in the inline guide and codemode-agents.md.
    • Hides agent() / agents.start() instructions in session/context.ts when the session policy denies subagent.
    • Grants { action: "wait", resource: "*", effect: "allow" } on worker children so deny-by-default workers can call tools.wait.

Compatibility Notes

Verification

  • bun typecheck and bun run typecheck:tsc in packages/codemode and packages/core
  • bun run check across all 37 packages
  • bun run check:generated in packages/protocol and packages/client
  • bun 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)

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 session skill and shell endpoints 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.ClosedError export in core.
  • Script globals (behind the codemode_agents flag): adds agents.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 Set plus the permanent codemodeAgent marker. 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.
  • The shell-notice change in shell.ts isn't limited to workers. cancelSession cancellations 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.ts is about 370 lines of hand-rolled state built on many Deferred.makeUnsafe calls, all inside start. A small Worker module 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.ts grows 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>()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 09ef80b:

  • Added optional closed?: boolean to CodeModeAgents.SessionMarker (decoded by sessionMarker) and keyed CodeModeAgents.isClosedWorker(sessionID, metadata) strictly on marker?.closed === true rather than absence from process-local openWorkers.
  • close() synchronously marks child.id stopping (markStopping), persists { childID, structured: false, closed: true } durably via sessions.setMetadata, then cancels jobs, interrupts/waits execution, recursively stops descendants, and unmarks stopping.
  • Session turn guards (prompt, resume, compact, shell, skill) check isClosedWorker || isStopping, so historical pre-upgrade agent() children and live workers owned by a second server process sharing the DB are no longer falsely rejected.
  • restart.ts still treats both marker.closed === true and 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 persists closed: true on orphaned workers.
  • Updated codemode-agents.md / inline guide and added unit + e2e regression tests covering persisted closed: true, unclosed markers from another process, and restart cleanup.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fix in 09ef80b resolves this thread, and I found no regressions.

  • Read-only check: it now depends only on the stored flag. isClosedWorker returns sessionMarker(...)?.closed === true (agents.ts:69-71). Children from before the upgrade never got closed, so they stay writable. So do workers that a second process holds open.
  • close(): the worker drops out of openWorkers and is marked stopping synchronously (codemode-worker.ts:172-173). onClose then saves closed: true before stopTree runs (codemode-agents.ts:369-373). The per-ask setMarker(undefined) is skipped once isClosing() is true (line 315), so a turn that finishes late can't wipe the flag. One-shot agent() closes through acquireUseRelease, so those children also become read-only once the script ends. That is the intended behaviour.
  • Session guards: requireOpen checks isClosedWorker || 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.

Comment thread packages/core/src/tool/plugin/shell.ts Outdated
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 09ef80b:

  • Gated the cancelSession notice suppression in packages/core/src/tool/plugin/shell.ts strictly on input.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.ts verifying that Job.cancelSession still emits the "Cancelled" notice for non-worker sessions while suppressing it for worker sessions.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 / inbox assertions, 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.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 openWorkers set.
  • The cancelSession cancel-notice check in shell.ts still applies to every session, not only workers.

The public API impact is unchanged from my last review.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 older agent() children and live workers in another process are no longer rejected.
  • Skipping the cancel notice in shell.ts now 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.

@hearnadam
hearnadam enabled auto-merge (squash) December 2, 2026 02:17
@hearnadam
hearnadam merged commit 1a509ad into dev Dec 2, 2026
11 checks passed
@hearnadam
hearnadam deleted the worker-handles branch December 2, 2026 02:17

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both earlier points still hold after the rebase:

  • Read-only depends only on a durable closed: true in 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.ts now marks durable agent() 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)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

jlongster added a commit that referenced this pull request Dec 2, 2026
- 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)
jlongster added a commit that referenced this pull request Dec 2, 2026
- 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)
@amrkmn amrkmn mentioned this pull request Dec 3, 2026
1 task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant