Repository navigation
refactor(orchestration): resolve every caller and target to one orchestration party, keyed by the Orca session id - #22555
Conversation
There was a problem hiding this comment.
ℹ️ No critical issues — minor suggestions inline.
Reviewed changes
The host-side half of the structured-chat orchestration stack (stacked on #22522), reviewed at bbf398d6 against 9d8e5734. Nothing sends the new field yet.
- One resolver at both dispatch entries.
orchestration-session-caller.tsresolvesorchestrationCompatibilityEvidence.agentSessionIdonce, after the migration fence and before params parse / the unary-streaming split, inRpcDispatcher.dispatchandRpcStreamingDispatcher.dispatch. It refuses the paired route and SSH/WSL stamps, validates the Orca id (naming it when handed a provider id), requires a live lease, maps a structured worker's session to its minted handle and pane, then rebinds the declared caller and reduces the evidence to{ agentSessionId }. - Every caller becomes one
OrchestrationCallerIdentity(address/terminalHandle/paneKey/actor) rather than a bare pane key. Run lookup moves fromgetCurrentRunForPanetogetCurrentRunForCoordinatorin run-create/use/current, check, send, group send, worker-start and run-scope. - Run binding and mail routing become actor-aware.
coordinator_actor/assignee_actor/creator_actorare written on bind/create/assign/claim/authority attach; the stale-actor "handle wins" rule governs matching;activeDispatchOwnsAddressSqlwidens the three ownership matchers. - Receipts fold the resolved actor into the payload hash, leaving terminal hashes byte-identical.
- Tests: three new suites (74 tests), a shared fixture, targeted updates to the #22522 suites, and 34 documented ablations.
I traced the actor binding, the stale-actor rule, the two new mail-routing branches and the receipt hash myself, and confirmed the two partial indexes behind INDEXED BY idx_dispatch_assignee_actor / idx_messages_undelivered_direct_run are eligible and hit (reproduced against SQLite). I could not construct a sequence that misroutes mail or takes over a Run without a fence.
ℹ️ The session id is a broader credential than the handle and pane key it replaces
The resolver's only checks on agentSessionId are format, local non-WSL host, a live lease, and existence in the local store — no token, signature, fence or per-call nonce. For a structured worker it then injects that worker's random handle and paneKey. Those two were made random on purpose because the session id is not secret, so resolving the id into them is strictly more permissive than the terminal path this PR preserves. This looks like the intended same-user threat model, but it is worth an explicit confirmation before the next PR makes the field reachable.
Technical details
# Session id as a bearer credential
## Where the id is accepted
- `src/main/runtime/rpc/orchestration-session-caller.ts:82-119` — format (`sessionOrchestrationActor`), local host, live lease (`agentSessionLeaseAdmitsWriter`), store hit. For a structured worker the resolved caller then carries the worker's random `handle`/`paneKey` (`:110-118`).
## Where a same-host non-owner can read the id
- `orchestration.dispatchShow` returns the raw dispatch row (`src/main/runtime/rpc/methods/orchestration/runs/dispatch-methods.ts:195,218` — `db.getDispatchContext`, a `SELECT *`), now including `assignee_actor = session:<id>`; `orchestration.workerShow` / `worker-list` publish `processIncarnation = structured:<id>` (`worker-observation.ts:196`, `worker-list-projection.ts:39`), and `sessionIdFromStructuredWorkerIncarnation` strips the prefix. Neither handler consults caller identity.
- Tab ids embed the id verbatim (`structuredAgentSessionTabId`, `src/shared/structured-agent-session-projection.ts:220`); the tree already notes this exposure (`src/main/runtime/structured-worker-identity.ts:13,61-69`).
- `<userData>/orchestration.db` and `agent-sessions.json` are `0600`, which does not separate same-UID processes.
## Required outcome
- A conscious answer, not a code change: either "any same-host process may act as any live session" (a design-doc note suffices), or the resolver should carry the same per-call attestation terminal callers still obtain.
## Open questions for the human
- Is the same-user, session-id-as-identity model the intended end state, or an artifact of porting from #19949 with the credential rule dropped?ℹ️ Nitpicks
bindDeclaredCallerbuildsnamesincludingcaller.terminalHandle, which isnullfor a handle-less chat, so{ from: null }passes the fence and is then overwritten by the address (orchestration-session-caller.ts:216-224). Harmless, but filtering nulls would make the fence literally mean "the declared caller must name this session".
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| export function claimsOrchestrationSession(request: RpcRequest): boolean { | ||
| return ( | ||
| request.method.startsWith('orchestration.') && | ||
| request.orchestrationCompatibilityEvidence?.agentSessionId !== undefined |
There was a problem hiding this comment.
agentSessionId is client-controlled wire data and is not schema-validated (only params go through parseRpcRequestParams), so !== undefined makes a null/''/0/false field count as a session claim: every orchestration.* method is then refused with session_caller_unknown before the handler runs. A client that serializes an unset optional as null (env.ORCA_AGENT_SESSION_ID ?? null) would break all orchestration verbs once the next PR wires injection. Gate on a non-empty string, matching the resolver's own typeof claimed === 'string' check.
| request.orchestrationCompatibilityEvidence?.agentSessionId !== undefined | |
| typeof request.orchestrationCompatibilityEvidence?.agentSessionId === 'string' && | |
| request.orchestrationCompatibilityEvidence.agentSessionId.length > 0 |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Re-reviewed the delta since the prior pullfrog review at bbf398d6 — one commit, 22f54f28, on the second PR of the structured-chat orchestration stack.
- Every-open repair of the unbind residue.
backfillStructuredWorkerActorsnow clearscoordinator_actoron handle-less, pane-less Runs whose actor this host recorded as a structured worker, leaving a chat coordinator's binding intact. - Refuse a worker session whose identity is gone. The resolver throws
session_caller_not_livewhen a session has a recorded worker Dispatch but no resolvable worker identity, so it can never bind handle-less and split one worker into two identities. - New coverage. The residue is shown matching as the worker session's binding before repair and cleared after (never the chat's); a
runCreatefor the abandoned worker session is refused with no Run written.
Both changes are scoped to the only current-binary shape that produces this residue (unbindOtherRunsForCoordinator clears all three columns; adoptLegacyRunIfNeeded clears handle/pane without an actor), and the new tests fail without their fixes. structured-worker-actor-backfill.test.ts passes 5/5 locally.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
22f54f2 to
3ace023
Compare
f5aee23 to
f06e716
Compare
f771efd to
6746bb5
Compare
There was a problem hiding this comment.
✅ No new issues found. All substantive feedback from the prior reviews is addressed; the one open inline suggestion is unchanged and left for the author.
Reviewed changes
Re-reviewed the delta since the prior pullfrog review at 22f54f28 — the three architecture-review commits on the second PR of the structured-chat orchestration stack (f771efd6..6746bb52a4).
- A Run's coordinator actor now counts only at its write generation.
currentRunCoordinatorActor/currentRunCoordinatorActorSqlgate the actor oncoordinator_actor_generation === consumer_generation;createRun,bindRun(rebind and same-coordinator correction) andunbindOtherRunsForCoordinatorwrite the matching generation, andrunBoundToCoordinatormatches through it. D1's "actor beside its own handle" rule, the open-time unbind-repair and their tests are deleted in favour of the one rule; the resolver's worker-identity refusal moves next to the worker lookup. - One owner for a party's addresses.
addressSpellingsOfandrunCoordinatorKeyreplace the hand-listed handle+actor pairs increateRun,bindRun,unbindOtherRunsForCoordinatorand the declared-caller fence;isRecordedStructuredWorkerSessionreplaces the backfill-local worker probe. - Wording and comment fixes. A released lease now reads "is not running right now" (wakeable) instead of "has ended"; the pane-key comment scopes its credential claim to requests that name no session.
- Tests. New generation/stale-actor cases in
run-coordinator-actor-binding.test.ts, a same-coordinator correction case, the both-addresses reroute cases, and the declared-self cases inorchestration-session-caller.test.ts; the migration fixture restores main's handle-only routing trigger.
I traced the generation rule end to end: every writer on runs.consumer_generation either sets coordinator_actor_generation in the same statement or leaves the actor counting only when the generations agree; the one raw-actor read (RUNS_BOUND_TO_COORDINATOR_SQL) is a candidate prefilter behind the generation-aware JS predicate; no reader re-persists a stale actor; and a same-session rebind is not wrongly fenced or over-bumped. run-coordinator-actor-binding, run-coordinator-actor-address, structured-worker-actor-backfill and orchestration-actor-column-migration pass 32/32 locally.
ℹ️ The historical mailbox-owner cache is generation-blind, so a multi-Run handle-less coordinator can be unaddressable
run_coordinator_handles records every address a party ever coordinated under, and nothing prunes it. The generation rule stops a stale actor from matching as the coordinator, but the mailbox-owner path (getRunMailboxOwnerIdsForHandle, the routing trigger, and recipient-routing.ts) never consults consumer_generation. Actors newly populate that cache via createRun/bindRun, so a live handle-less coordinator with more than one past Run now resolves to multiple owners; selectHistoricalRun returns undefined and a sender with no Run of its own gets recipient_ambiguous at that coordinator's session:<id> address. The PR documents the "former coordinator's address stays remembered" half as intended, and this mirrors existing terminal-handle semantics, but the multi-owner side effect is untested.
Technical details
# Generation-blind historical address cache
## Affected sites
- `src/main/runtime/orchestration/db/runs/run-lookup.ts:55-79` — `getRunMailboxOwnerIdsForHandle` joins `run_coordinator_handles -> runs` with `runs.legacy = 0`, no generation predicate.
- `src/main/runtime/orchestration/db/runs/run-coordinator-mail-routing.ts:41-67` — the INSERT trigger matches the cached address by string equality only.
- `src/main/runtime/rpc/methods/orchestration/messaging/recipient-routing.ts:79-86` and `selectHistoricalRun:128-139` — multiple owners with no explicit/sender Run becomes `recipient_ambiguous`.
- `src/main/runtime/orchestration/db/runs/run-create.ts:35-37` and `run-binding.ts:124-131` — the delta is what puts actor addresses into the cache.
- `src/main/runtime/orchestration/db/runs/run-coordinator-actor-address.test.ts:155-157` — pins the intended "stays remembered" half.
## Required outcome
- A conscious call, not necessarily a code change: either accept the ambiguity (a design note plus a test pinning the multi-Run outcome), or prune/replace the prior owner row for a party when a new Run supersedes it.
## Open questions for the human
- Should `getRunMailboxOwnerIdsForHandle` return only the Run a party currently coordinates once it has one, so a live coordinator is not ambiguous at its own address?DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
b183a5c to
19218ab
Compare
8dac986 to
a77c7a4
Compare
There was a problem hiding this comment.
ℹ️ No new issues in this delta. The new commits retype the caller identity from the
session:<id>address to a bare brandedOrcaSessionIdand align with #22522's renamed columns; the net change is a rename plus type hardening, not new behavior. The previously opened inline thread onclaimsOrchestrationSessionis unchanged by these commits, so this is a non-approving review.
Reviewed changes
Re-reviewed the net delta since the prior pullfrog review at 6746bb52a4 (content-identical 8dac986). The branch had been rebased onto #22522's rename, so the delta was isolated with the range-diff.
- Caller identity is a bare branded
OrcaSessionId.OrchestrationCallerIdentity,OrchestrationCoordinatorKey,RunRow/DispatchContextRow, and every writer/reader carryorcaSessionIdinstead of anactoraddress.isOrcaSessionIdis now a type guard;parseOrcaSessionAddressreturns the bare id;formatOrcaSessionAddressowns thesession:<id>spelling and rejects a non-Orca id. Noascasts on the brand exist. - DB fields renamed to
*_orca_session_id.coordinator_orca_session_id(+_generation),assignee_orca_session_id,creator_orca_session_id, matching #22522. Thedispatch-row-writer.tsINSERT column/value counts, and the worker-authority and failed-start writers, are aligned. - One SQL-side address formatter. New
orca-session-address-sql.ts#orcaSessionAddressSqlformats the id side of a comparison (('session:' || id)), soactiveDispatchOwnsAddressSqlandcurrentRunCoordinatorSessionAddressSqlnever string-match a bare id against a handle orrun:address. - Dispatch creator kind
actor→session. Receipts fold the bare id under__orcaCallerOrcaSessionId; the provider-id refusal carriesdata.orcaSessionId;taskCreate/worker-start record no terminal handle for a handle-less session. - Worker-start takes the resolved coordinator/session;
resolveDispatchCallerWorktreeIduses the session record's workspace. - Tests retargeted to the new vocabulary, plus a case pinning that an assigned worker keeps direct mail at its session address.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…ry and bind it by actor WIP: entry resolver on both dispatchers, caller identity through run scope, actor-keyed Run binding and unbind, actor writes on bind/create/assign, and actor-aware mail ownership exclusions.
…nce and actor mail ownership Keeps the non-session dispatch path synchronous so terminal and session-tab streams reach their handler without an extra async hop.
…pin every verb on both routes A session caller need not name itself in a param that requires a caller: the entry binds the declared caller to the session before the schema runs. Session refusal codes pass through the RPC error map, and DB row reads added here carry their SAFETY rationale.
…t binding without a caller param Drops the actor clause from self-dispatch detection: a creator and assignee can only share an actor when they already share a handle or pane.
…s and the assignee-only mail sweep
…ves, and refuse a worker without its identity An older binary unbinds a structured worker's Run by clearing handle and pane, which leaves the actor looking like a handle-less chat binding. The every-open repair clears that shape for actors recorded as structured workers only, and the resolver refuses a worker session whose worker identity is gone, so this binary never writes the shape itself.
…eneration, and give a party's addresses one owner The coordinator actor now counts only at the consumer generation it was written at, so a Run binding matches a session by that rule alone. It replaces two mechanisms for the same fact: the rule that an actor beside a handle it did not bind with never matches, and the open-time repair that cleared a structured worker's actor an older binary's unbind left. Every write of an older binary that rebinds or unbinds bumps the generation, so both shapes stop counting by themselves, including a chat's actor after a rebind then an unbind, which neither old mechanism caught. createRun and the same-coordinator actor correction write the generation in the statement that writes the actor. The resolver still refuses a structured worker whose worker identity is gone; its predicate moves next to the worker identity lookup. addressSpellingsOf is the one owner of the addresses a party is reachable at (a structured worker's handle and session actor). createRun, bindRun, the coordinator unbind and the declared-caller check use it instead of hand-built sets, and each has a test at both of a worker's addresses.
…the pane-key credential claim to requests without a session A released lease is evicted, not ended: a user turn resumes the session, so the refusal now says it is not running right now instead of that it has ended. The worker pane-key comment claimed the random leaf is what stops anyone who learns a session id from acting as the worker. On the same-host socket route the session id now names the worker with no token by design; the pane key still matters where a request names no session (a PTY agent's, or the paired-client route, which refuses session ids).
…ration write on a row an older binary wrote
…sion id, typed apart from its address Carries the Orca session id rename into caller resolution, Run binding and Dispatch creation. The caller identity holds the bare `orcaSessionId`; the `session:<id>` spelling is derived by formatOrcaSessionAddress wherever mail needs it. `OrcaSessionId` and `OrcaSessionAddress` are distinct branded strings. Only isOrcaSessionId and parseOrcaSessionAddress produce an id, and only formatOrcaSessionAddress produces an address, so comparing the two is a type error. The Orca session id columns on the row types carry the id type. Every reader that compares a stored id with a mail address now compares like with like: the active-Dispatch ownership check formats the stored id (orcaSessionAddressSql), and the stray-mail sweep, the creator nesting lookup and the recorded-worker check bind a parsed or typed bare id. The Run-mailbox ownership check keeps its existing handle comparison beside the session one.
a77c7a4 to
abe5c3d
Compare
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (22)
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review. 📝 WalkthroughWalkthroughOrchestration requests can now resolve a caller from an Orca session ID and pass that identity through Run, task, messaging, gate, dispatch, and worker operations. Run binding and lookup can use session IDs as well as terminal handles and pane keys. Mail routing resolves session addresses to parties and routes messages to Run, Dispatch, or direct mailboxes. Dispatch records now store creator and assignee session IDs. Tests cover caller validation, Run coordination, address routing, and Dispatch identity. Priority: ➖ Normal Merge Risk: 🔵 Low · up to Session-based caller resolution works for the tested paths. One known edge case remains: a session request with no parameters is not bound to the session's identity. That request can then read the wrong mailbox or fail. The CLI does not send session IDs yet, so this should be fixed before or together with the follow-up that enables it. Security Architecture ReviewSecurity architecture risk: 🟠 High · up to A local caller may be able to act under another session’s identity. A separate path accepts a structured worker’s session address without checking whether that worker still has a live owner. Those identities can affect Runs, Dispatches, and mail. Retained concerns
Security review detailsSecurity Blast Radius
Security Findings and Attack Paths
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 5c7c73ba-6443-43b8-a5e5-20f636cd75cf
📒 Files selected for processing (58)
src/main/runtime/orchestration/db/dispatch-context/dispatch-context-store.tssrc/main/runtime/orchestration/db/dispatch-depth.tssrc/main/runtime/orchestration/db/dispatch-row-writer.tssrc/main/runtime/orchestration/db/messages/direct-mailbox-routing.tssrc/main/runtime/orchestration/db/messages/foreign-direct-mailbox-routing.tssrc/main/runtime/orchestration/db/orca-session-address-sql.tssrc/main/runtime/orchestration/db/runs/run-binding.tssrc/main/runtime/orchestration/db/runs/run-coordinator-mail-routing.tssrc/main/runtime/orchestration/db/runs/run-coordinator-orca-session-binding.test.tssrc/main/runtime/orchestration/db/runs/run-coordinator-orca-session.tssrc/main/runtime/orchestration/db/runs/run-create.tssrc/main/runtime/orchestration/db/runs/run-lookup.tssrc/main/runtime/orchestration/db/schema/structured-worker-orca-session-backfill.test.tssrc/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-authority.tssrc/main/runtime/orchestration/db/worker-terminal/failed-start-dispatch-identity.tssrc/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.tssrc/main/runtime/orchestration/orchestration-caller-identity.tssrc/main/runtime/orchestration/orchestration-orca-session-column-migration.test.tssrc/main/runtime/orchestration/run-coordinator-orca-session-address.test.tssrc/main/runtime/orchestration/structured-worker-group-addressing.test.tssrc/main/runtime/orchestration/types.tssrc/main/runtime/rpc/core.tssrc/main/runtime/rpc/dispatcher-unary-method-invocation.tssrc/main/runtime/rpc/dispatcher.tssrc/main/runtime/rpc/errors.tssrc/main/runtime/rpc/methods/orchestration-caller-workspace.tssrc/main/runtime/rpc/methods/orchestration-structured-worker-start-failure.test.tssrc/main/runtime/rpc/methods/orchestration/federation/federated-worker-start.tssrc/main/runtime/rpc/methods/orchestration/gates/gates.tssrc/main/runtime/rpc/methods/orchestration/messaging/check-methods.tssrc/main/runtime/rpc/methods/orchestration/messaging/check-run.tssrc/main/runtime/rpc/methods/orchestration/messaging/message-methods.tssrc/main/runtime/rpc/methods/orchestration/messaging/send-group.tssrc/main/runtime/rpc/methods/orchestration/messaging/send-methods.tssrc/main/runtime/rpc/methods/orchestration/routing.tssrc/main/runtime/rpc/methods/orchestration/runs/dispatch-creator.tssrc/main/runtime/rpc/methods/orchestration/runs/dispatch-methods.tssrc/main/runtime/rpc/methods/orchestration/runs/run-receipt.test.tssrc/main/runtime/rpc/methods/orchestration/runs/run-scope.tssrc/main/runtime/rpc/methods/orchestration/runs/runs.tssrc/main/runtime/rpc/methods/orchestration/worker/explicit-worker-terminal-validation.tssrc/main/runtime/rpc/methods/orchestration/worker/local-worker-start.tssrc/main/runtime/rpc/methods/orchestration/worker/workers.tssrc/main/runtime/rpc/orchestration-mutation-executor.tssrc/main/runtime/rpc/orchestration-mutation-receipt.tssrc/main/runtime/rpc/orchestration-session-caller-test-fixture.tssrc/main/runtime/rpc/orchestration-session-caller.test.tssrc/main/runtime/rpc/orchestration-session-caller.tssrc/main/runtime/rpc/orchestration-session-coordinator.test.tssrc/main/runtime/rpc/rpc-streaming-dispatcher.tssrc/main/runtime/structured-worker-authority.tssrc/main/runtime/structured-worker-identity.tssrc/main/ssh/ssh-remote-orca-cli.test.tssrc/shared/orca-session-address-test-fixture.tssrc/shared/orca-session-address.test.tssrc/shared/orca-session-address.tssrc/shared/orchestration-compatibility-evidence.tssrc/shared/orchestration-session-caller-codes.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
| if (!name || !params || typeof params !== 'object' || Array.isArray(params)) { | ||
| return params | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Bind the caller even when the request omits params.
parseRpcRequestParams accepts an omitted params and parses request.params ?? {}. bindDeclaredCaller returns undefined unchanged in that case, so the caller field is never set to caller.address.
This causes wrong behavior in the handlers:
orchestration.checkfalls back tohandle = 'unknown'. With no bound Run, it reads theunknowndirect mailbox, not the session's mailbox.resolveRunScopethrowsrun_requiredforgateList,taskList, and similar methods, becausecallerTerminalHandleis missing.
Treat an omitted params as an empty object for the listed methods.
🐛 Proposed fix
const name = ORCHESTRATION_CALLER_PARAM[method]
- if (!name || !params || typeof params !== 'object' || Array.isArray(params)) {
+ const source = params ?? {}
+ if (!name || !source || typeof source !== 'object' || Array.isArray(source)) {
return params
}
- const values: Record<string, unknown> = { ...params }
+ const values: Record<string, unknown> = { ...source }…nator is reachable at A worker's preamble names its coordinator as `session:<id>` when the coordinator is a structured session, but ask only accepted `run:<id>` or the coordinator's terminal handle. A chat coordinator has no handle, and a coordinating structured worker has two addresses, so ask --to the session address was refused as dispatch_run_mismatch. The check now takes the Run's current coordinator addresses from addressSpellingsOf(runCoordinatorKey(run)).
… be handed the resolved session The resolved session parameter was optional on resolveRunScope, resolveOrchestrationCaller, orchestrationCallerIdentity, resolveDispatchCreator and resolveDispatchCallerWorktreeId, so a method that forgot to pass it would compile and silently treat a chat's session address as a terminal handle. It is now required and typed `OrchestrationSessionCaller | undefined`, so leaving it out is a type error. Every call site already passed it; no behavior changes.
There was a problem hiding this comment.
ℹ️ No new issues in this delta. The two new commits generalize one target check and make the resolved-session parameter required; both are clean and verified by typecheck, lint and the coordinator suite. The previously opened inline thread on
claimsOrchestrationSessionis unchanged by these commits, so this is a non-approving review.
Reviewed changes
Re-reviewed the delta since the prior pullfrog review at a77c7a42a6 (abe5c3dc was a content-identical rebase onto #22522). Two commits, five files.
askaccepts every address its coordinator is reachable at. The worker's target is now validated againstaddressSpellingsOf(runCoordinatorKey(run))instead ofrun.coordinator_handlealone, so a handle-less chat coordinator is reachable at thesession:<id>spelling its worker preamble names. A terminal-coordinated Run keeps the exact handle comparison.- Resolved-session parameters are required.
resolveDispatchCallerWorktreeId,resolveDispatchCreator,orchestrationCallerIdentity,resolveRunScopeandresolveOrchestrationCallernow takecallerSession: OrchestrationSessionCaller | undefined, so forgetting to thread the resolved session is a type error rather than a silent terminal-handle fallback. Every call site already passed it; no behavior change. - Tests. Two cases pin the worker→coordinator
askat a chat's session address and at a structured worker coordinator's handle and session address.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…lbox that session reads A send to session:<id> was resolved like a terminal handle: no live pane, so a chat's current Run was missed (two Runs read as ambiguous), a Run-less chat was refused though it reads its direct mailbox, and a structured worker's session address never reached its Dispatch. Resolve a worker's session address as its handle, a chat's by its bound Run, and fall back to the chat's durable direct mailbox while it runs on this host.
There was a problem hiding this comment.
ℹ️ No new issues in this delta. The one new commit makes a
sendtosession:<id>resolve to the mailbox that session actually reads, and its tests fail without it. The previously opened inline thread onclaimsOrchestrationSessionis unchanged by this commit, so this stays non-approving.
Reviewed changes
Re-reviewed the delta since the prior pullfrog review at a44c26e8ee — one commit, 47eef51619, on the second PR of the structured-chat orchestration stack.
- A send to
session:<id>now resolves to the mailbox that session reads.resolveBareOrchestrationRecipientparses the session address and, in order: maps a structured worker's session to its minted handle and recurses (so its Dispatch is reached), routes a coordinating session to its current Run viagetCurrentRunForCoordinator, and — for a Run-less session whose record runs on this host — delivers to its durable direct mailbox. Every other case keeps the existingterminal_not_found. - The live-coordinator ambiguity the prior review flagged is gone for sessions. The new
getCurrentRunForCoordinator({ orcaSessionId })lookup runs before the generation-blind historical-owner cache, so a handle-less coordinator with several past Runs resolves to its current Run instead ofrecipient_ambiguous. - Terminal behaviour is untouched. A plain handle or a
run:/dispatch:address does not parse as a session address, sopaneKey/boundRunand the rest of the function run exactly as before. - Tests. New
orchestration-session-recipient.test.ts(4 cases): a chat's current Run, a Run-less chat's direct mailbox, a remote/unknown session refused, and a structured worker's session address reaching its Dispatch.
I traced each new branch against the terminal path and the mail-routing sweep (routeForeignDirectMessagesToOwnedMailboxes, whose session-address branch moves a durable session:<id> message into the Dispatch it owns, so the direct-mail fallback is not a dead letter). orchestration-session-recipient (4), orchestration-session-coordinator (22), orchestration-session-caller (47) and structured-worker-group-addressing (9) pass locally; oxlint is clean on the changed files.
ℹ️ Nitpicks
- The PR body's "Out of scope" note still says "a send to any other session address is refused at recipient routing", but this commit now delivers a Run-less local session's direct mail. Worth updating so the next PR in the stack is not read against a stale contract.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…h one mailbox address A structured worker is reachable at its handle and at its session address, and a chat only at its session address. Callers and targets were each compared or resolved at their own site, some against one spelling and some against every spelling, and the sites that did neither refused or misrouted. Add orchestration-party: resolveOrchestrationParty (and resolveOrcaSessionParty for a bare id) is now the only place an address becomes a party. The session caller, the declared-caller check, ask's target and inbox's filter all resolve through it, so caller and recipient resolution cannot disagree, including on a recorded worker whose identity this host lost. Every session-to-party step passes through canonicalOrcaSessionId, the seam later lineage canonicalization plugs into. mailboxAddressOf replaces addressSpellingsOf: a party has one mailbox address (a worker's handle today), and Run binding remembers and reroutes only that. A request with no session id that declares a session address as its caller now gets the party it names: a worker's handle, as if it had named it, or a session_caller_chat_not_declarable refusal for a chat, which is identified only by the session id its own environment sends.
… they name dispatch --to a worker's session address stored that address as the assignee handle, so the worker, which reads by its handle, never saw the Dispatch. The assignee now resolves through the party resolver: a worker's either spelling assigns its handle and records its Orca session id. A chat cannot receive a dispatch yet, so dispatch --to a chat is refused with session_chat_not_dispatchable before any row is written. Recipient routing resolves the party once and, for any session-backed party, finds its Run by its durable binding rather than by a live pane. A structured worker that coordinates a child Run while assigned in its parent got mail at its parent Dispatch mailbox whenever its session was evicted, which it never reads while bound to the child Run. Terminal handles keep the same live-pane lookup.
…d spelling With every caller and target resolved to one mailbox address, no writer stores mail under a structured worker's session address: sends resolve it to the handle, a declared session caller is rewritten to the handle or refused, replies answer a stored canonical sender, and questions, answers, escalations, federation and legacy mail write run:, dispatch: or handle addresses (legacy rows are legacy_direct, which these queries never read). The branches that matched that spelling were unreachable and are removed: - the session-address OR in activeDispatchOwnsAddressSql, back to the assignee handle alone; - the session branches in routeForeignDirectMessagesToOwnedMailboxes and findActiveDispatchForDirectMessageOwner, which return to the base-branch form. Tests that inserted such rows directly now pin the behaviour through the verbs: both spellings of a worker land in the one mailbox it reads.
… caller and target - every target param in ORCHESTRATION_TARGET_PARAM, for a worker's handle and session address and a chat's session address: send, ask, dispatch (a chat refused with no row) and inbox; - a declared session-address caller on a request with no session id: a worker acts as its handle, a chat is refused; - a worker that coordinates a child Run while assigned in its parent gets mail in the child Run with no live pane; - no mail writer stores to_handle or from_handle as a worker's session address; - the caller a session id resolves to and the recipient its address resolves to agree in every party state, and every session-to-party step goes through canonicalOrcaSessionId.
Brings in the removal of the structured-chat terminal handoff (#22783): an agent session is now owned natively only, and the agent-session PTY write gate is gone. The next commit removes this branch's remnants of that handoff.
…iew handoff remnants The structured-chat terminal handoff is gone from the base branch: a session is owned natively only. - the lease rule no longer speaks of either owner or a handoff keeping identity; - an in-progress owner change (new-owner-proving, recovering, manual-recovery, which the base branch still produces) is refused as changing owners, not as switching between chat and terminal view; - the native to terminal-view to native identity test is deleted, and the terminal-evidence test no longer describes that evidence as a terminal view's.
There was a problem hiding this comment.
ℹ️ No new issues in this delta. The six commits (one an
origin/mainmerge) replace the "two spellings per party" model with a singleorchestration-party.tsresolver and one mailbox address; every changed behavior is pinned by a test that fails without it. The previously opened inline thread onneedsOrchestrationCallerResolution(agentSessionId !== undefinedacceptsnull) is unchanged by these commits, so this stays non-approving.
Reviewed changes
Re-reviewed the delta since the prior pullfrog review at 47eef51619 — six commits on the second PR of the structured-chat orchestration stack. Isolated with the range-diff (the branch carries a large origin/main merge). Locally: the four new/changed RPC suites (92 tests) and all of src/main/runtime/orchestration (943 tests) pass.
- One resolver, one mailbox address. New
orchestration-party.tsis the only address→party resolver;addressSpellingsOfis replaced bymailboxAddressOf(the handle if present, elsesession:<id>).resolveDeclaredCallerPartyandresolveDispatchAssigneePartyadd the two chat refusals (session_caller_chat_not_declarable,session_chat_not_dispatchable),ORCHESTRATION_TARGET_PARAMnames the four target methods, andcanonical-orca-session-id.tsis the seam for later/clear-lineage canonicalization. - The SQL that matched a worker's second spelling is deleted.
activeDispatchOwnsAddressSqlnow matchesassignee_handleonly, andforeign-direct-mailbox-routing.tsloses its session branch. Safe because every target canonicalizes a worker'ssession:<id>to its handle before any mail is written; the new "no writer stores a structured worker under its session address" test pins the invariant. - Targets route through the party they name.
send/ask/dispatch/inboxresolve their target param through the resolver;dispatchresolves its assignee before the dry-run and refuses a chat with no row written;resolveMessageRuntakes asenderidentity instead of a bare handle/pane pair. - A declared
session:<id>caller with no evidence is resolved at the entry (bindDeclaredSessionAddress): a worker's address maps to its handle, a chat's is refused as not declarable, with no effects. - Handoff remnants dropped. The
claimsOrchestrationSession→needsOrchestrationCallerResolutionrename, the "is changing owners" lease wording, and the removal of the native→terminal-view→native test follow the base's handoff-machinery deletion.
ℹ️ The PR description still describes the two-spelling mechanics these commits deleted
Two current-state claims in the body no longer match the final head, and the next PR in the stack reads against this body. Worth refreshing before #22568 so its author does not design to a contract that is no longer there.
Technical details
# Stale PR-description claims
## Affected sites
- PR body, "#22522's four obligations" §2 — "All three readers … now also match `assignee_actor`, through one SQL fragment `activeDispatchOwnsAddressSql`". At head, `activeDispatchOwnsAddressSql` (`src/main/runtime/orchestration/db/runs/run-coordinator-mail-routing.ts:5-12`) matches `assignee_handle` only; the `assignee_orca_session_id` branch was removed by `fb30709461`. The "What Changed" §"Actor-aware mail matchers" repeats the same wording.
- PR body §3 — "`createRun` and `bindRun` remember both its handle and its actor in the coordinator-address cache". `createRun`/`bindRun` now call `mailboxAddressOf`, so a worker is remembered at its handle only (`run-create.ts`, `run-binding.ts`); its `session:<id>` stays reachable through `resolveOrchestrationParty`, not through a cache entry.
## Required outcome
- The body should state the final mechanism: one mailbox address per party (handle wins), with session-address reachability provided by `orchestration-party.ts` canonicalization rather than by a second stored spelling or a SQL actor match.
## Open questions for the human
- None; documentation only. The behavior (a worker reachable at both spellings) is preserved and tested.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
Review status: ready for review (head
|
| Scenario | Result |
|---|---|
| Terminal agent: run-create, run-current, send, check (unchanged) | Pass |
| Native chat: run-create, run-current, send, check as itself; Run stored with the bare Orca session id and no handle | Pass |
| Unknown id, provider id (names the Orca id), declared caller naming someone else | Refused, no effects |
| Released chat | "is not running right now…", no effects; after it is revived the same Run is still bound |
dispatch --to a chat |
session_chat_not_dispatchable, no dispatch row written |
Terminal agent sends to session:<chat>, for a chat with a Run and a chat without one |
Delivered; the chat's check reads it |
Terminal names a chat's session: address as its own caller |
session_caller_chat_not_declarable, no effects |
Native chat used for the session-id requests, then its Run created, used, mailed and read by session id:


Refusals: unknown id, provider id, someone else's caller:

Dispatch to a chat refused, with no rows written:

Mail to a coordinating chat, and to a chat with no Run:


A chat's address named as a caller without its id:

Not exercised live: the paired-client, SSH and WSL refusals, and the WebSocket transport. Automated tests cover them.
Seen during QA, not caused by this PR
- A chat closed and reopened from Agent Session History can't send: "Claude couldn't restart: provider close unproven" until the app restarts. This PR touches no native-chat code. The fix, fix(claude): let a Claude chat start again after its root exited with unverifiable descendants #22802, merged to main after round-1 QA; round-2 QA ran on a build that includes it but did not re-test this path.
- A chat shows nothing when orchestration mail arrives. It sees the mail only when it runs
check. feat(orchestration): deliver worker results to a structured chat coordinator #22631 delivers a note into the chat that starts a turn. - Agent Session History marks a folder-workspace chat "Unavailable worktree" even though the workspace is open. This is outside this PR and wasn't investigated.
Carried to later PRs in the stack
/clearlineage plugs intocanonicalOrcaSessionId(feat(orchestration): deliver worker results to a structured chat coordinator #22631). The dispatch-row writers'assignee_orca_session_idshould go through the same hook.- Right after an app restart, before anything has started the agent-session host,
send --to session:<chat with no Run>is refused with "does not run on this host". Chat delivery (feat(orchestration): deliver worker results to a structured chat coordinator #22631) should start the host first. - Dispatching to a chat gets its own PR, together with a delivery path for it.
CI
All green on e24f0e4318: 24 passed and 13 skipped, including static analysis, typecheck, all 8 test shards, cross-version wire compatibility and verify.
Resolve check-methods.ts against the orchestration party refactor (stablyai#22555): keep the session-keyed caller identity and pass callerSession through the Run mailbox path. Dispatch-recipient routing now uses the same session-before-pane precedence as bare-handle routing. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01N6uaiT75LTfJ9Lx54bgnRW



ELI5
Orchestration can only recognize an agent by its terminal. A native chat has no terminal, so it cannot create or use a Run, send mail as itself, or read its own mail. This PR teaches the Orca host to recognize a chat by the session id Orca gave it. The host checks that id once, where every request comes in, and from then on the chat is one orchestration party with one mailbox address,
session:<id>. Nothing sends the id yet: #22568, the next PR in this stack, makes the CLI send it. Terminal agents behave exactly as before.Merge order
Second PR of the structured-chat orchestration stack: #22522 (merged: the Orca session id columns) → this PR → #22568 (the CLI sends the id) → #22631 (worker results delivered to a chat coordinator) → #22636 (agents told their own address).
What Changed
Host side only: no CLI, UI or delivery change.
Before / after, as an agent experiences it (once #22568 sends the id)
orca orchestration run-create,send,check,dispatch, gates or tasks is refused, or worse, is mistaken for whatever terminal evidence it inherited.check. Mail sent tosession:<id>reaches the mailbox that chat reads.structworker_handle, also works when it sends its session id or is addressed assession:<id>. Both names reach the same mailbox.Wire contract (what #22568 sends)
orchestrationCompatibilityEvidence.agentSessionId: the Orca-minted id from the caller's injected environment. It is an optional field, so it is safe with mixed versions: an older host ignores it and an older CLI never sends it.session:<id>, the bare id, or a structured worker's own handle. Anything else is refused.One resolver at the entry of both dispatchers (
src/main/runtime/rpc/orchestration-session-caller.ts)RpcDispatcher.dispatch(Unix socket and Electron IPC) andRpcStreamingDispatcher.dispatch(paired WebSocket and IPC subscriptions) call it after the method lookup and migration fence, and before params parse, legacy compatibility and receipt lookup.ctx.orchestrationCaller. The declared caller param is replaced by the session's mailbox address, and the evidence is reduced to{ agentSessionId }, so inherited terminal evidence never attests anyone.ORCHESTRATION_CALLER_PARAMlists the 15 methods that consult caller identity and the param each uses (fromfor run-create/use/current, send, reply, ask, dispatch, the three gate verbs and worker-start;terminalfor check;callerTerminalHandlefor the three task verbs).One party, one address (
src/main/runtime/orchestration/orchestration-party.ts)resolveOrchestrationParty, and every party has exactly one mailbox address,mailboxAddressOf. Methods then work only with that one address.session:<id>). Both resolve to the same party, whose mailbox address is its handle, because that is what its mail and Dispatch rows are keyed by today. That direction lives in one function, so moving to session-first later is one change.canonicalOrcaSessionId, which returns the id unchanged here. feat(orchestration): deliver worker results to a structured chat coordinator #22631 plugs/clearlineage into it.ORCHESTRATION_TARGET_PARAMlists the params that name another party (sendto, askto, dispatchto, inboxterminal). A ratchet test requires every party-naming field of every orchestration method to be classified as a caller param, a target param, or an exemption with a reason, so a new field cannot skip the resolver.Refusals (
src/shared/orchestration-session-caller-codes.ts; all carry{ effectsApplied: false }and pass through the RPC error map)session_caller_host_boundarysession_caller_unknownsession_caller_provider_id/clear. The message anddata.orcaSessionIdname the Orca id to use.session_caller_not_livesession_chat_not_dispatchabledispatch --tonames a chat. A chat can't receive a dispatch yet; the refusal points toworker-start. It is lifted only together with a delivery path that makes it work, and nothing advertises it before then.session_caller_chat_not_declarableconsumer_fenced(existing)check --terminal-pane-keynames someone else.Binding a Run by Orca session id (
db/runs/)createRun,bindRunand the same-coordinator correction writecoordinator_orca_session_idand its generation in the statement that writes the binding. A Run's session id counts only at theconsumer_generationit was written at, so a rebind or unbind by an older binary (which bumps the generation but does not know the column) leaves a session id that no longer counts, with nothing needing to clear it.check --runand any waiting check fail asconsumer_fenced, and its pending coordinator mail is rerouted into the Run mailbox.assignee_orca_session_idfor structured workers andcreator_orca_session_idfor a session creator (newDispatchCreatorkindsession).Receipts. The resolved session id is folded into the payload hash, so a retry from the same session replays and the same request id from another session is
request_mismatch. Terminal callers' hashes are unchanged.Why
The failure. Orchestration identity was a terminal handle mapped to a pane, looked up separately inside each method, and Runs were bound by pane. A chat has no pane, so it could never bind or be addressed.
Why resolve once at the entry. The session check is asynchronous (it reads the session record and lease) and has to run before legacy compatibility and receipts on both transports. Doing it once means every method sees one caller and never branches on what kind of agent it is.
Why one address per party instead of matching every spelling. An earlier version of this PR let a structured worker be matched at both of its names everywhere mail was compared. Review found the same bug four times (
ask,send,dispatchand a nested coordinator), each where one site forgot one name. The PR now resolves every name to one party at the boundary and deletes the SQL that matched the second name, so no site has to remember it.Why a trusted id and no credential. Every agent on this host runs as the same user, so the checks are about getting the identity right, not about keeping anyone out. That is why the id is honoured only on the host that runs the session: a paired client, an SSH relay or a WSL shell is refused. Unlike a scheme that issues a revocable per-session token, a stopped session loses its authority because every request re-reads the live lease.
Why a live lease. Orca keeps durable per-address mailboxes, so a released session must not act as if it were running. "Released" is reported as "not running right now", not "ended": a new message or user turn revives it.
Deviation to know about. A structured worker still has two names on the way in (handle and
session:<id>), so terminal-era workers keep working. Only one of them is ever stored or compared.run_coordinator_handlesstill holds inertsession:rows written by the existing v42 triggers; nothing routes to them, and removing them needs a migration, so they stay.Also in this PR.
origin/mainis merged in. Native chats no longer have a terminal view (#22783), so the lease check is native-only and the terminal-view tests are gone.Linked Issue
None — part of the structured-chat orchestration program. Supersedes #19949 and absorbs the purpose of #16859 (coordinator takeover).
Visual Proof
Host-side only; no UI changed. Live QA screenshots of an isolated dev build are in the review comment below: a terminal agent's Run, a native chat creating and reading a Run through raw requests carrying its session id, and each refusal.
Testing
New test files:
orchestration-session-caller.test.ts(entry resolver on both transports, every refusal before any effect, the 15/target/exempt population),orchestration-session-coordinator.test.ts(the whole loop as a chat and as a structured worker, takeover fencing, older-binary rebinds, replay),orchestration-session-recipient.test.ts(send tosession:<id>for a chat with and without a Run and for a worker),orchestration-party-addressing.test.ts(every target-taking verb × chat address, worker handle, workersession:address and bare id resolves to one stored address or a refusal; no message is ever stored to a worker'ssession:address; the target-param ratchet),orchestration-party-agreement.test.ts(caller and recipient resolution agree for every party state), andrun-coordinator-orca-session-binding.test.ts(DB-level binding, unbinding, generation rule, mail rerouting).tc:node,tc:cli,tc:web,oxlint(default and anti-slop configs),check:code-quality:changed: pass. Orchestration, RPC, messaging, SSH CLI and session-address suites: pass (a few suites time out only under heavy local load and pass with a longer timeout or fail identically onmain).session:<id>for a chat with and without a Run; each refusal (unknown id, provider id, someone else's caller, released session, dispatch to a chat, naming a chat's address without its id) applying no effects. Screenshots are in the review comment. Not exercised live: the paired/SSH/WSL refusals and the WebSocket transport (covered by tests).Review
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
idx_runs_coordinator_orca_session_id,idx_dispatch_assignee_orca_session_id).Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)