#12380·qwen-code

proposal(serve): Define Managed Agent dual-path architecture and staged delivery

Author: doudouOUCCreated Sep 21, 2026Updated Sep 30, 2026
Labelspriority/P2type/feature-requestcategory/corescope/session-managementroadmap/session-managementroadmap/multi-agentroadmap/platform-distributionneed-discussion

What would you like to be added?

Define a staged Managed Agent architecture that keeps the existing TypeScript agent loop, runs model inference independently of tool-environment provisioning, and gives Sessions durable ownership, Workspace bindings, recoverable tool executions, and a stable WebShell/API surface.

This proposal consolidates the integration design and release gates. It does not request one large PR or declare the architecture shipped. Detailed contracts stay in code_agent v1.13, pinned at 6891216: [architecture overview][architecture], [HTML diagrams][html], and [design index][index]. The [latest index][latest] can evolve without changing the review baseline below.

Delivery priority — 2026-09-28

Ordinary local qwen serve Managed execution is lower priority and follows the first deliverable Hosted Managed slice. Retain the merged paired-host foundation, M1 protections (#12861, #12906), M3 configuration compatibility (#12883, #12903), and the subsequently merged M4 recording slice (#12935). Defer the remaining M2 and M5–M6 work, including local engine registration and activation; reassess its schedule after Hosted tool execution, durable results, and required fault gates are accepted. Local engine completion is not a Hosted prerequisite. This does not defer Hosted Runtime workers (including local-process workers), Broker integration, output persistence, or recovery validation, and does not weaken their acceptance gates.

Track the deferred local engine in #12737; bilingual design update: https://github.com/QwenLM/qwen-code/pull/12920.

Delivery snapshot — 2026-09-29

This is a status inventory, not a production-readiness claim. W0a–W0e have merged for their stated scopes; W0e-3 (#12869) covers trusted single-host Linux reboot recovery. G2 (#12964) and the M4 recording slice (#12935) have also merged. Review and validation continue in the active PRs below; none represents a finished production rollout.

  • @wenshao: #12955 owns the first public Workspace file Turn (G0); #12868 owns Broker provider controls; #12945 measures Hosted latency; #12946 implements private MCP (H1); and #12998 settles the task event/cancel contract without serving those routes. #12995 is an M4 test follow-up, and #12965 is a Flyway CI guard; neither implements the deferred M2/M5–M6 engine or task runtime routes.
  • @doudouOUC: #12894 owns remote Shell result delivery (O2), and #12977 owns audited operator recovery after incomplete Shell capture. Both remain under review on main.
Planned work with no implementation PR found in the current open-PR inventory Boundary
Public Hosted interaction after G0 Subsequent bound Turns, public cancel/lifecycle enablement, and approval Actions remain separate from #12955. Stage D6 Actions, D7 opt-in java_durable admission, and D8 AgentDefinition are tracked in #12867.
Harness takeover/G G1's in-flight and continuation failover gates and G3's replaceable Harness/owner-affinity removal are tracked by #12952 but have no matching open implementation PR; G2 is merged, while G0 is under review.
Output and artifacts/O O3 public result/Artifact projection, range/download API and WebShell cards, plus O4 reference-aware retention/cleanup and extension adapters, have no implementation PR. O2 is still under review; #13019 separately tracks the expired-publication-candidate liveness decision.
Workspace beyond W0 W1 restore/backfill and verified mount relocation, and W2 controlled same-Workspace cwd changes, have no implementation PR. W0e does not establish cross-host, Kubernetes or hostile-writer recovery.
Extension runtime/H H2 Hooks through H6 automation, the runtime task-event/cancel routes left planned by H0c, and the outbox dispatcher have no implementation PR. H1 is under review; #12998 changes only the task contract.
Deferred ordinary host/B M2 and M5–M6, including selection and activation of a local Managed engine, remain deferred under #12737. The merged M4 slice adds no production caller.

Real private object storage, second-host recovery, MySQL/MariaDB fault matrices, product identity/ingress and capacity gates remain validation or deployment work for the capabilities selected for rollout. PostgreSQL, optional MQ transport and broader orchestration remain later design scope, not prerequisites silently added to the first Hosted slice.

Architecture and ownership

mermaid
flowchart LR
    UI[WebShell / product client] -->|Product REST and SSE| J[Java control plane]
    J -->|Session / Prompt / Resume| Q[qwen serve]
    Q --> L[Legacy engine / ACP]
    Q --> H[Managed TS Harness]
    H --> M[Model service]
    H -->|Tool requests and results| B[Embedded Runtime Broker]
    B -->|Java-initiated HTTP and SSE| R[On-demand Tool Runtime]

The Broker is embedded in the Java service in the hosted reference deployment. qwen serve keeps the common Session protocol and hosts the Legacy/Managed engines; the Harness owns the single model loop, context, compaction, and tool orchestration. The Runtime owns files, Shell, and admitted tool-side effects. It receives neither the user Prompt nor model credentials. Local Managed uses a local Runtime provider and does not require Java.

Hosted deployment starts with one Java instance plus a qwen serve sidecar and a Session-exclusive Runtime process/Pod. Model inference uses a pre-published immutable AgentBundle while Runtime provisioning proceeds in parallel; only tool execution waits for readiness. Multiple Sessions may share the Harness process without sharing their model context or permission view.

Proposed decisions

Area Proposed behavior Detailed design
Engine selection and identity Persist Legacy/Managed ownership before the first side effect. Managed failure never reruns through Legacy. Use one RFC UUID sessionId across public API, qwen authority, Harness, transcript, and Broker scope. [Engine selection][engine], [architecture][architecture]
Admission and interaction Keep qwen_confirmed for the existing product entry. Stage D may expose java_durable only with durable command delivery and original-command reconciliation. Retries retain identity; approvals/questions resolve through the original arbiter. [Admission, Actions, lifecycle][contracts]
Ordinary tools Preserve prepare, approval, preflight, execute, original-execution query, result commit/ACK, and file-history settlement. An ambiguous side effect blocks recovery instead of being replayed on a new Runtime. Cancellation is complete only with physical stop evidence. [First release][first], [tool integration][tools]
Workspace and cwd At creation, select an authorized registered Workspace and optional relative directory, defaulting to .. Commit the binding with the creation receipt. Broker resolves the physical mount from that binding; refresh, retry, default changes, and restart do not rebind the Session. [Workspace: English][workspace-en] / [中文][workspace-zh]
Storage and live delivery Accept bounded event batches and source progress in one SQL transaction, then immediately push committed events through Java SSE. Async materialization builds Items/Snapshots. Reconnect uses Session sequence plus snapshot/tail recovery; GC needs settled consumers and recovery/reader retention checks. [Storage and events][storage], [delivery contracts][contracts]
Database and MQ adapters Keep business transaction semantics behind storage interfaces: MySQL first, PostgreSQL as another implementation. Use SQL-only delivery initially; an optional EventTransport can use RocketMQ or Redis Streams for notifications/async distribution. MQ is not on the synchronous frontend path or the authority for model history. [Storage boundaries][storage]
Runtime and Harness recovery Persist Broker binding/execution facts, reconcile and attest physical Runtime identity, and fence old writers. Persisting metadata alone does not prove recovery. Full shared Session authority/checkpoint storage and replaceable Harness belong to stage G. [Broker persistence][broker], [Session storage][session-storage], [recovery][recovery]
Full tool output and artifacts Keep captured bytes, exact model-consumed results, and public previews distinct. Persist large bytes as immutable objects/segments with digests and receipts; SQL holds metadata/previews. WebShell reads bounded ranges/downloads. Execution success and capture/delivery completeness are separate states. [Tool results: English][outputs-en] / [中文][outputs-zh]
Public API and WebShell Version Session/list/query, Prompt/cancel, Actions, Turns/Items, events/replay, Workspace discovery, and artifact reads. Preserve the browser-to-Java boundary. Generate compatible DTOs from the reviewed OpenAPI and enable capabilities only after contract tests. [API contract][api], [OpenAPI v1.12][openapi]
Extensions Harness remains the model-loop owner. Add durable domain records and task projections before migrating MCP, Hooks, background Shell/Monitor, child agents/workflows/teams, Channels, and automation. Each feature needs its own admission, receipt, cancellation, quota, and recovery checks. [Extension runtime][extensions]

The event path is Harness SSE → Java bounded batch → SQL commit → Java SSE → browser. SQL delivery/Outbox work can separately notify MQ consumers and materialize history. SQL failure therefore blocks new event acceptance; this proposal does not promise unlimited buffering through a database outage. Full tool bytes do not belong in token-event rows, SSE frames, or MQ payloads.

Initial release boundary

The first hosted validation slice uses a single Java/sidecar deployment, immutable published configuration, a Session-exclusive Runtime, and Read/Write/Edit/foreground Shell. Approval, durable results/file history, cancellation cleanup, and safe continuation after clean Runtime reclamation remain required. Existing product SSE/history can serve this slice; the full public API, multi-instance takeover, and extension migration have separate gates.

W0 adds Workspace selection and fixed cwd. W1 expands restore/backfill and verified mount relocation; W2 adds controlled same-Workspace cwd changes. Arbitrary server-path registration, clone/worktree creation, and changing existing Sessions' directories are outside W0. Sessions using the same Workspace share files, so their tool turns need the existing Workspace lease/settlement discipline.

Delivery plan

These are capability stages, not one mandatory linear mega-change. A/C/E, the shared B ownership/no-fallback guarantees, and the necessary F checks form the first runnable Hosted slice; completing all of D or the deferred ordinary-host Managed engine is not a prerequisite for that slice.

Stage Deliverable and exit gate
A Freeze identities, contracts, ownership, and baseline latency measurements.
B Persist engine ownership and reject runtime engine fallback. Retain the merged paired-host foundation; remaining ordinary-host Managed engine delivery (M2, M5–M6, #12737) is deferred behind the first Hosted slice; M4 landed in #12935 without enabling a local Managed engine.
C Integrate Broker binding/execution repositories, leases, Runtime transport, and original-execution lookup.
D Deliver the public Agent API, durable admission profile, projections, replay, and compatible client contracts.
E Run the hosted sidecar profile with inference/provisioning in parallel and no local-tool fallback.
F Pass ACK-loss, SSE-gap, process crash, cancellation, output-delivery, and storage-failure tests for each enabled capability.
G Externalize authoritative Session history/checkpoints; prove writer fencing and takeover before removing owner affinity.
H Expand through H0 shared records → H1 MCP → H2 Hooks → H3 Shell/Monitor → H4 child/workflow/team → H5 Channels → H6 automation.

Workspace implementation is split into W0a contracts/Registry → W0b durable creation → W0c execution-directory wiring → W0d WebShell → W0e restart/reclamation validation. Full-output delivery is O1 capture/reference contracts → O2 hosted persistence/receipt recovery → O3 API/tool cards → O4 retention and admitted extensions. These refine the stages above rather than creating competing roadmaps.

Acceptance criteria

  • With Runtime startup delayed by 15 seconds, published-configuration model output starts first; a no-tool Turn can finish, and a tool Turn waits and continues in the same model context.
  • Sessions retain their engines after restore; a Managed failure causes no Legacy replay. Ordinary-host Legacy/Managed coexistence is an acceptance gate for the deferred local engine, not the first Hosted slice.
  • Lost create/Prompt/execute/ACK responses resolve through original identities without duplicating side effects. Unknown outcomes remain explicitly blocked.
  • Two Workspaces and different child directories execute Read/Write/Shell in the intended locations. A retry after changing defaults keeps the original binding; missing mounts or revoked access never fall back to another directory.
  • Java restart and clean Runtime reclamation retain the Session binding; physical identity is verified before reuse, and old writers cannot mutate a newer binding.
  • Committed SSE replay and Snapshot-plus-tail recovery preserve order without duplicate content. MQ delay cannot block local post-commit SSE; SQL unavailability is surfaced with bounded backpressure.
  • Large output can be read/downloaded after Runtime cleanup. WebShell distinguishes tool outcome, partial/missing capture, delivery failure, and truncated preview; storage failure never causes tool re-execution.
  • Cancellation settles admitted tools and descendant processes. Production enablement additionally requires actor/tenant isolation, capacity limits, and the fault gates for the selected deployment profile.

Why is this needed?

Hosted execution should not make the first model response wait for a tool container. Splitting the model loop from tools, however, creates ownership and recovery boundaries: a selected directory must survive process changes, an ambiguous tool call must not run twice, and a browser reconnect must recover committed progress. Permanent per-fragment storage also grows without a retention/materialization plan, while Runtime-local output disappears when the environment is reclaimed.

This proposal joins those boundaries into one implementable contract while preserving Qwen's existing agent semantics and local deployment. It gives reviewers a scoped rollout and observable exit gates instead of treating an experimental branch or a passing component test as the finished product.

Additional context

Existing work and repository scope

  • #11695 and its tracks #11696, #11697, and #11698 cover separable execution, credential boundaries, and addressable environments. This proposal describes the integration and release contract for Managed Sessions; those tracks remain independently scoped. In particular, it does not assume agreement to ship a hosted Java control plane in upstream core: upstream protocol/runtime changes and hosted reference packaging must be reviewed separately.
  • #11868 covers event/journal externalization. It aligns with stage G's authoritative Session storage, which is distinct from Java's public event/Item projection and optional MQ transport.
  • #3803 tracks the daemon's broader evolution. This proposal preserves the common Session surface and an opt-in migration path rather than replacing that roadmap.

Implementation status at this proposal's baseline

The current upstream slices are deliberately smaller than the end-to-end architecture. Table last refreshed 2026-09-30 19:20 UTC.

PR State Proposal coverage Remaining boundary
#12301 merged Stage A/C Runtime binding and Runtime Session identity, state, leases, and in-memory repositories. No persistence, provisioning, transport, or public API.
#12302 merged Stage A/B/D Managed Session record and transcript foundation. No complete hosted owner routing, durable public admission, or projections.
#12390 merged Stage C JDBC persistence for Runtime binding and Runtime Session, including database-clock leases and fencing. No Tool Execution JDBC, Runtime reconciliation, or framework wiring.
#12391 merged Stage C Tool Execution identity, dispatch claims, UNKNOWN no-replay, cancellation, and in-memory repository semantics. No Tool Execution JDBC or physical dispatch integration.
#12409 merged Stage A/E Hosted Harness private protocol version, boot identity, capability digest, and middleware foundation. The middleware is not yet mounted into a Hosted profile or connected to Java.
#12438 merged (f8c78ddf25) Stage C framework-neutral Broker service core coordinating scope resolution, provisioning claims, Runtime Session acquire/control/release, idempotent execution, cancellation, and lease renewal. No concrete Runtime provider, restart adoption/reconciliation, HTTP adapter, Hosted Harness/Qwen client integration, or Tool Execution JDBC wiring.
#12445 merged (d2e4cc74d5; review head 15d395bc40) Stage C Tool Execution JDBC persistence with database-clock leases, row-lock CAS/fencing, case-sensitive verified identifier hashes, JSON round-trip guards, a shared H2/MySQL repository contract, and the fourth schema table. The exact head passed 63 JDK 21 tests and the same contract on disposable MySQL 26.7.0 with utf8mb4_0900_ai_ci. Merged after round-3 verification marked the exact head merge-ready, two human collaborators approved it, and code CI passed. No service/framework wiring or real physical dispatch.
#12477 merged (99bf4ce86b) Stage C/F final dispatch fence: after the transition to EXECUTING, the service re-checks the claimed owner and generation before renewal or transport.execute. A deterministic takeover regression proves the stale Broker makes zero transport calls. Transport idempotency, concrete Runtime transport, and multi-process fault injection remain separate gates.
#12478 merged (34187f0d63) Stage C/F lease-clock alignment: JDBC reads database time as epoch seconds plus microseconds, independent of the connection session time zone. H2 and real MySQL tests cover UTC, +08:00, and -04:00. Schema migration, framework wiring, Runtime reconciliation, and multi-process validation remain outstanding.
#12447 merged (c822995d3a) Stage A/F v2 attestation route manifest and shared schema/fixtures, with real raw-HTTP TypeScript coverage and Java fixture consumption. The contract is not mounted in a Hosted profile; concrete Java transport, Broker reconcile/CAS gate, required cross-language CI, and process E2E remain follow-up work.
#12506 merged (4836b5e310) Stage A/F hidden attestation-only Runtime worker process: bounded closed stdin boot document, loopback-only ephemeral listener, the exact v2 attestation manifest route, a token-free stdout ready record, graceful signal shutdown, and a real child-process boot/attest/exit test. No tool execution, Hosted profile, or Java Broker wiring; those land with the execute extraction.
#12522 merged (94104d5565) Stage A/C Java attestation client: the typed v2 attestation call, strict fixture-conformant parsing, and bounded responses against the shared contract. The client is not yet driven by a provisioning flow.
#12552 merged (3c6b614b29) Stage C process adoption: the Broker starts the attestation worker, attests it, and only then records the lease ready; reuse re-attests through confirm, session verbs check liveness, and a dead process retires the binding. Tool HTTP is on the Java client; execute fails closed with a non-retryable 404. No