JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(agent): prewarm sessions and centralize allocation
douran5e2b56d01c0d
diff --git a/.doc_project_maintainer/INDEX.md b/.doc_project_maintainer/INDEX.mdindex be07930491..dae1ac083e 100644--- a/.doc_project_maintainer/INDEX.md+++ b/.doc_project_maintainer/INDEX.md@@ -32,6 +32,12 @@ Status: partial. A 2026-07-15 semantic-hash scan at `10afedf2` found 0 expired a- [AgentServer Plan Mode Exit](project/flows/agentserver-plan-mode-exit.md)- [AgentServer Scheduled Auto-Harness](project/flows/agentserver-schedule-auto-harness.md)- [AgentServer History Stream](project/flows/agentserver-history-stream.md)+- [Session Prewarm And Allocation](project/flows/session-prewarm-allocation.md)++## Decisions And Recent Changes++- [ADR-0001](decisions/ADR-0001-agentserver-owned-prewarmed-sessions.md): AgentServer owns prewarmed session identity.+- [CHG-20260731-001](changes/records/CHG-20260731-001-session-prewarm-allocation.md): session allocation and DeepAgent prewarming.## Priority Code Symbolsdiff --git a/.doc_project_maintainer/changes/records/CHG-20260731-001-session-prewarm-allocation.md b/.doc_project_maintainer/changes/records/CHG-20260731-001-session-prewarm-allocation.mdnew file mode 100644index 0000000000..a86f01cb02--- /dev/null+++ b/.doc_project_maintainer/changes/records/CHG-20260731-001-session-prewarm-allocation.md@@ -0,0 +1,38 @@+---+id: CHG-20260731-001+date: 2026-07-31+title: Add AgentServer-owned session allocation and DeepAgent prewarming+confidence: confirmed+modules:+ - agentserver-runtime+ - gateway-and-channels+ - agent-harness+flows:+ - session-prewarm-allocation+decisions:+ - ADR-0001+---++# Add AgentServer-Owned Session Allocation And DeepAgent Prewarming++## Change++Added a process-local `AgentWarmPool`, `agent.prewarm.sync`, AgentServer ID allocation with `create_token` idempotency, DeepAdapter `prepare_session`, asynchronous configuration reconciliation, and first-chat waiting on the shared initialization task.++Web, TUI, controlled IM channels, ACP, A2A, SSH, fork, and single-Agent Cron now consume AgentServer-returned IDs. Team/Swarm modes bypass prewarming. Prewarm markers are hidden from normal session metadata/listing and isolated by boot ID.++## Compatibility++`session.create` no longer accepts a caller-provided new ID. Existing sessions must use `session.switch`. `/new [id]` is removed; TUI `--session` restores only.++## Verification++- Warm-pool and Cron focused unit tests: 68 passed.+- Web creation tests: 5 passed.+- Web production build: passed.+- TUI TypeScript typecheck: passed.+- Cron scheduler suite updated for the two-step create/send contract.+- Session allocation contract suites for AgentServer ACP/plan mode, Web identity, project binding, and TUI forwarding/KVC ownership: 139 passed.+- Full Python unit suite on Windows: 3,791 passed, 4 skipped, and 14 unrelated failures. The remaining failures depend on POSIX shell/path assumptions, including one cleanup test that hand-builds a non-normalized POSIX cache key, or on occupied local ports.+- Web creation preserves authenticated connection ownership by replacing any request-body `user_id` before forwarding `session.create`.+- CodeCheck follow-up removed unreachable pre-AgentServer Web/TUI creation code, extracted warm-pool safety/revision predicates, and added a public DeepAdapter stable-config boundary. The expanded focused suite passed 166 tests.diff --git a/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_session_create.md b/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_session_create.mdindex c9b5675d29..7ff5c4b504 100644--- a/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_session_create.md+++ b/.doc_project_maintainer/code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_session_create.md@@ -24,14 +24,14 @@ health:observability: partialperformance_risk: mediumaudit:- status: agent_audited+ status: audit_expiredauditor: codexaudited_at: 2026-07-14T11:39:39Zaudited_commit: 39feee89e00dc6b0b6a6b16ca80a527beb631bd7audited_source_hash: sha256:5fbbae5104a1791ca98014aeed0b81fea243b57dcd2faac3f8f37886833c4fa5audited_symbol_hash: sha256:33487351f0a252dd739869feacd05acef75371d18829a892b7f4d27be460572econfidence: confirmed- expired_reason: null+ expired_reason: "Implementation changed on 2026-07-31 for AgentServer-owned IDs, create_token idempotency, project-first validation, and warm-pool claims; no independent symbol health re-audit was performed."issues:- id: ISSUE-001dimension: boundary_safety@@ -67,7 +67,7 @@ issues:## Actual Role-The reviewed behavior, contracts, side effects, callers, callees, tests, and documentation evidence are preserved in the linked detail pages.+Validates project/work-mode binding, rejects explicit new IDs, claims an AgentServer-owned warm or warming session, writes metadata, and returns prewarm status. The linked audit details describe the previous implementation and remain historical until re-audited.## Audit Detailsdiff --git a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter.configure_session_runtime.md b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter.configure_session_runtime.mdnew file mode 100644index 0000000000..0753612183--- /dev/null+++ b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter.configure_session_runtime.md@@ -0,0 +1,26 @@+---+symbol: JiuWenSwarmDeepAdapter.configure_session_runtime+kind: method+source: jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+class: JiuWenSwarmDeepAdapter+source_role: runtime_source+audit_scope: default_health_audit+confidence: confirmed+health:+ overall: unknown+audit:+ status: unaudited+---++# JiuWenSwarmDeepAdapter.configure_session_runtime++## Actual Role++Builds the adapter's internal runtime-config bundle from stable session identity, channel, mode, and project inputs, then applies it without binding request-scoped capabilities.++## Key Signals++- Input: prepared session identity and stable workspace context.+- Output: no value; mutates the session-scoped adapter runtime configuration.+- Boundary: public façade used by `prepare_session`, avoiding cross-instance access to protected implementation details.+- Verification: covered indirectly by the DeepAdapter reload and warm-pool preparation suites.diff --git a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter.prepare_session.md b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter.prepare_session.mdnew file mode 100644index 0000000000..312c134df0--- /dev/null+++ b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter.prepare_session.md@@ -0,0 +1,14 @@+---+symbol: JiuWenSwarmDeepAdapter.prepare_session+kind: method+source: jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+class: JiuWenSwarmDeepAdapter+audit:+ status: unaudited+---++# JiuWenSwarmDeepAdapter.prepare_session++## Actual Role++Creates or reuses the session-scoped adapter, completes `create_instance` and `start_interaction`, then delegates stable workspace, rails, tools, and prompt configuration through the child's public `configure_session_runtime` boundary. It does not attach output or send input.diff --git a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.claim.md b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.claim.mdnew file mode 100644index 0000000000..630eedb27c--- /dev/null+++ b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.claim.md@@ -0,0 +1,14 @@+---+symbol: AgentWarmPool.claim+kind: method+source: jiuwenswarm/server/runtime/agent_warm_pool.py+class: AgentWarmPool+audit:+ status: unaudited+---++# AgentWarmPool.claim++## Actual Role++Atomically removes a READY slot or creates one claimed-session initialization task. READY claims retain the root pin until the first AgentServer request and schedule a replacement slot.diff --git a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.sync.md b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.sync.mdnew file mode 100644index 0000000000..ef372bfb55--- /dev/null+++ b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.sync.md@@ -0,0 +1,14 @@+---+symbol: AgentWarmPool.sync+kind: method+source: jiuwenswarm/server/runtime/agent_warm_pool.py+class: AgentWarmPool+audit:+ status: unaudited+---++# AgentWarmPool.sync++## Actual Role++Builds desired keys from enabled channels and visible/default projects, advances the config fingerprint revision, stales old slots/tasks, schedules missing targets, and returns non-blocking pool statistics.diff --git a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/Class AgentWarmPool.md b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/Class AgentWarmPool.mdnew file mode 100644index 0000000000..8f08a13fd5--- /dev/null+++ b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/Class AgentWarmPool.md@@ -0,0 +1,27 @@+---+symbol: AgentWarmPool+kind: class+source: jiuwenswarm/server/runtime/agent_warm_pool.py+source_role: runtime_source+audit_scope: default_health_audit+health:+ overall: unknown+audit:+ status: unaudited+ confidence: confirmed+---++# AgentWarmPool++## Actual Role++Maintains one unclaimed READY session per desired channel/project/work-mode key, prevents obsolete configuration revisions from publishing, and hands claimed initialization Futures to the chat path.++## Key Contracts++- Only single-Agent keys enter READY.+- A claim is atomic and immediately schedules replenishment.+- Preparation failure cannot publish READY.+- Markers never create normal user metadata.++Health remains unaudited; see the build plan for the pending audit slice.diff --git a/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/agent_warm_pool.py.md b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/agent_warm_pool.py.mdnew file mode 100644index 0000000000..a316660ccd--- /dev/null+++ b/.doc_project_maintainer/code/jiuwenswarm/server/runtime/agent_warm_pool.py/agent_warm_pool.py.md@@ -0,0 +1,24 @@+---+source: jiuwenswarm/server/runtime/agent_warm_pool.py+source_role: runtime_source+audit_scope: default_health_audit+language: python+confidence: confirmed+last_updated: 2026-08-01+---++# `agent_warm_pool.py`++## Actual Role++Owns process-local reconciliation and atomic claiming of session-bound READY DeepAgents. It defines immutable warm identity/revision records, guarded marker cleanup, bounded background initialization, stale revision disposal, claimed-session waiting, and root-agent pinning.++## Symbol Inventory++- Records: `WarmKey`, `WarmRevision`, `WarmSlot`, `WarmClaim`.+- Runtime class: `AgentWarmPool`.+- Key methods documented for this scoped change: `sync`, `claim`, `wait_for_session`, and `close`.++## Health++Audit status: `unaudited`. Focused behavior tests exist, but no independent symbol health audit was performed.diff --git a/.doc_project_maintainer/decisions/ADR-0001-agentserver-owned-prewarmed-sessions.md b/.doc_project_maintainer/decisions/ADR-0001-agentserver-owned-prewarmed-sessions.mdnew file mode 100644index 0000000000..658fd89f63--- /dev/null+++ b/.doc_project_maintainer/decisions/ADR-0001-agentserver-owned-prewarmed-sessions.md@@ -0,0 +1,39 @@+---+id: ADR-0001+title: AgentServer Owns Prewarmed Session Identity+status: accepted+date: 2026-07-31+confidence: confirmed+modules:+ - agentserver-runtime+ - gateway-and-channels+ - agent-harness+flows:+ - session-prewarm-allocation+---++# ADR-0001: AgentServer Owns Prewarmed Session Identity++## Context++DeepAgent construction and interaction startup are expensive on the first message. Channel-generated IDs also create two owners for session identity and make a preinitialized, session-bound runtime impossible to claim safely.++## Decision++AgentServer is the sole allocator for new and fork target IDs. It maintains one READY single-Agent slot for each enabled channel/project/work-mode key. Slots already carry their final session ID because OpenJiuwen runtime state depends on that identity. Channels obtain the ID through `session.create`; external protocol IDs are aliases.++Configuration validity uses a full SHA-256 fingerprint and a per-process boot ID. Warm misses return immediately and initialize in the background; the first real message awaits the same task. Team/Swarm modes remain outside this optimization.++## Consequences++- Warm hits remove DeepAgent construction/startup from the first-message critical path.+- All creation callers require an AgentServer connection; Web/TUI local creation fallback is intentionally unavailable.+- Idempotency is process-local through `create_token`.+- Resource use scales with enabled channels times visible/default projects times two single-Agent work modes.+- Channel trajectory prediction and pool-size reduction can be layered later without changing identity ownership.++## Alternatives Rejected++- Rebinding a prewarmed runtime to a channel-generated ID: runtime state already depends on the original ID.+- Prewarming without `start_interaction`: leaves the expensive readiness boundary on `chat.send`.+- Sharing a generic runtime across projects: project workspace, rails, tools, and prompt state are part of initialization.diff --git a/.doc_project_maintainer/manifest.yaml b/.doc_project_maintainer/manifest.yamlindex 887f701b13..79bbb83650 100644--- a/.doc_project_maintainer/manifest.yaml+++ b/.doc_project_maintainer/manifest.yaml@@ -1,6 +1,6 @@version: 0.0.1artifact_root: .doc_project_maintainer-last_updated: '2026-07-15'+last_updated: '2026-07-31'sync:status: partiallast_scanned_commit: 10afedf222bcd6db98b24347a28f75e4613b3c87@@ -31,6 +31,8 @@ sync:flows: []code_symbols:- jiuwenswarm/server/agent_ws_server.py+ - jiuwenswarm/server/runtime/agent_warm_pool.py+ - jiuwenswarm/server/runtime/agent_adapter/interface_deep.pycreated: '2026-07-07'project:name: JiuwenSwarm@@ -73,6 +75,7 @@ modules:- agentserver-plan-mode-exit- agentserver-schedule-auto-harness- agentserver-history-stream+ - session-prewarm-allocationcoverage:status: partiallast_scanned: '2026-07-13'@@ -93,6 +96,7 @@ modules:- agentserver-plan-mode-exit- agentserver-schedule-auto-harness- agentserver-history-stream+ - session-prewarm-allocationcoverage:status: plannedlast_scanned: '2026-07-07'@@ -110,6 +114,7 @@ modules:- agentserver-sandbox-runtime- agentserver-plan-mode-exit- agentserver-schedule-auto-harness+ - session-prewarm-allocationcoverage:status: plannedlast_scanned: '2026-07-07'@@ -285,6 +290,26 @@ flows:code_symbols:- AgentWebSocketServer.get_conversation_history- AgentWebSocketServer._handle_history_get_stream+- id: session-prewarm-allocation+ name: Session Prewarm And Allocation+ summary: Gateway syncs live channels; AgentServer prepares, claims, and replenishes session-bound single-Agent runtimes.+ confidence: confirmed+ doc: project/flows/session-prewarm-allocation.md+ modules:+ - agentserver-runtime+ - gateway-and-channels+ - agent-harness+ directories:+ - jiuwenswarm/server+ - jiuwenswarm/gateway+ - jiuwenswarm/channels+ code_symbols:+ - AgentWarmPool+ - AgentWarmPool.sync+ - AgentWarmPool.claim+ - AgentWebSocketServer._handle_session_create+ - JiuWenSwarmDeepAdapter.prepare_session+ - JiuWenSwarmDeepAdapter.configure_session_runtimecode_symbols:- symbol: _runkind: function@@ -314,6 +339,34 @@ code_symbols:kind: methodsource: jiuwenswarm/server/agent_ws_server.pydoc: code/jiuwenswarm/server/agent_ws_server.py/Class AgentWebSocketServer/AgentWebSocketServer._handle_sandbox_enable.md+- symbol: AgentWarmPool+ kind: class+ source: jiuwenswarm/server/runtime/agent_warm_pool.py+ doc: code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/Class AgentWarmPool.md+- symbol: AgentWarmPool.sync+ kind: method+ source: jiuwenswarm/server/runtime/agent_warm_pool.py+ doc: code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.sync.md+- symbol: AgentWarmPool.claim+ kind: method+ source: jiuwenswarm/server/runtime/agent_warm_pool.py+ doc: code/jiuwenswarm/server/runtime/agent_warm_pool.py/Class AgentWarmPool/AgentWarmPool.claim.md+- symbol: JiuWenSwarmDeepAdapter.prepare_session+ kind: method+ source: jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+ doc: code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter.prepare_session.md+- symbol: JiuWenSwarmDeepAdapter.configure_session_runtime+ kind: method+ source: jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+ doc: code/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py/JiuWenSwarmDeepAdapter.configure_session_runtime.md+decisions:+- id: ADR-0001+ title: AgentServer Owns Prewarmed Session Identity+ doc: decisions/ADR-0001-agentserver-owned-prewarmed-sessions.md+changes:+- id: CHG-20260731-001+ title: Add AgentServer-owned session allocation and DeepAgent prewarming+ doc: changes/records/CHG-20260731-001-session-prewarm-allocation.mdcode_symbol_inventory:generated_by: scripts/inventory_symbols.pysource_symbol_inventory: project/source-symbol-inventory.jsondiff --git a/.doc_project_maintainer/modules/agent-harness/README.md b/.doc_project_maintainer/modules/agent-harness/README.mdindex 5da4bc7939..76939713fe 100644--- a/.doc_project_maintainer/modules/agent-harness/README.md+++ b/.doc_project_maintainer/modules/agent-harness/README.md@@ -2,7 +2,7 @@id: agent-harnessname: Agent Harnessconfidence: inferred-last_updated: 2026-07-13+last_updated: 2026-08-01read_when: "Working on agent adapters, rails, tools, team runtime, skills, memory, or AutoHarness execution."---@@ -21,12 +21,15 @@ Provides the agent execution machinery behind AgentServer: adapters, rails, memoAgentServer calls this module family through `AgentManager`, adapter methods such as `process_message` and `process_message_stream`, team manager helpers, scheduler services, ACP output callbacks, and sandbox runtime patches.+`JiuWenSwarmDeepAdapter.prepare_session` now creates the session-scoped child, starts the real OpenJiuwen interaction, and calls the child's public `configure_session_runtime` boundary without attaching output or sending input. Request-scoped permissions, paths, ACP capabilities, output attachment, and input remain on the real chat path.+## Related Flows- `agentserver-command-mcp`: adapter MCP reconciliation after persisted config changes.- `agentserver-sandbox-runtime`: Agent recreation, sys-operation policy, and runtime hot patching.- `agentserver-plan-mode-exit`: plan approval rails and checkpoint-backed mode restoration.- `agentserver-schedule-auto-harness`: durable scheduler tasks and autonomous Harness execution.+- `session-prewarm-allocation`: session-stable DeepAgent preparation and request-bound runtime binding.## Pendingdiff --git a/.doc_project_maintainer/modules/agentserver-runtime/README.md b/.doc_project_maintainer/modules/agentserver-runtime/README.mdindex d90dcc63a8..875efb0541 100644--- a/.doc_project_maintainer/modules/agentserver-runtime/README.md+++ b/.doc_project_maintainer/modules/agentserver-runtime/README.md@@ -2,7 +2,7 @@id: agentserver-runtimename: AgentServer Runtimeconfidence: confirmed-last_updated: 2026-07-15+last_updated: 2026-08-01read_when: "Working on AgentServer startup, Gateway WebSocket handling, sessions, commands, server push, ACP, scheduler, sandbox, or runtime services."---@@ -23,6 +23,7 @@ Hosts the standalone AgentServer process and the WebSocket RPC surface used by G- `jiuwenswarm/server/agent_ws_server.py`: WebSocket server, E2A/legacy request parsing, method dispatch, session/command handlers, stream/cancel logic, server push.- `jiuwenswarm/server/gateway_push/wire.py`: converts server-originated push messages into E2A response wire frames.- `jiuwenswarm/server/runtime/agent_manager.py`: creates, initializes, reloads, and retrieves agent instances.+- `jiuwenswarm/server/runtime/agent_warm_pool.py`: reconciles and atomically claims session-bound READY DeepAgents.- `jiuwenswarm/server/runtime/proactive_adapter.py`: attaches proactive recommendation engine to the AgentServer instance.## Related Flows@@ -35,6 +36,7 @@ Hosts the standalone AgentServer process and the WebSocket RPC surface used by G- `agentserver-plan-mode-exit`: approval, checkpoint restoration, stale re-entry protection, and client notification.- `agentserver-schedule-auto-harness`: scheduler startup, durable tasks, autonomous execution identity, and logs.- `agentserver-history-stream`: persisted history paging, sanitization, streamed events, and frontend reconstruction.+- `session-prewarm-allocation`: Gateway channel sync, pool reconciliation, AgentServer allocation, and first-chat readiness.## Related Code Symbols@@ -49,9 +51,11 @@ Hosts the standalone AgentServer process and the WebSocket RPC surface used by G- `tests/unit_tests/test_app_agentserver.py` checks startup/shutdown does not delete agent team directories.- `tests/unit_tests/agentserver/test_agentserver_modes.py` covers mode resolution, project directory resolution, and stream/mode behavior.-- `tests/unit_tests/agentserver/test_agentserver_acp.py` covers ACP initialization, sessions, team delete, capabilities, and tool response paths.+- `tests/unit_tests/agentserver/test_agentserver_acp.py` covers ACP initialization, AgentServer-owned session allocation, explicit-ID rejection, team delete, capabilities, and tool response paths.- `tests/unit_tests/agentserver/test_agentserver_cli_commands.py` covers slash-command handlers.- `tests/unit_tests/agentserver/test_agent_ws_connection_close.py` covers disconnect cleanup behavior.+- `tests/unit_tests/agentserver/test_agent_warm_pool.py` covers READY targets, concurrent claims, replenishment, revision replacement, and failure isolation.+- The focused session-allocation contract run passed 139 tests across AgentServer, Web, project binding, and TUI ownership surfaces on 2026-08-01.## Known Gapsdiff --git a/.doc_project_maintainer/modules/agentserver-runtime/changes.md b/.doc_project_maintainer/modules/agentserver-runtime/changes.mdindex fdf076674d..e071a2ec88 100644--- a/.doc_project_maintainer/modules/agentserver-runtime/changes.md+++ b/.doc_project_maintainer/modules/agentserver-runtime/changes.md@@ -1,3 +1,4 @@# AgentServer Runtime Changes- [CHG-20260713-001: Close AgentWebSocketServer method audit delivery](../../changes/records/CHG-20260713-001-agentserver-method-closure.md) records the knowledge-model change that closed 128 method audits, refreshed the session flow, and added five AgentServer flows. It does not describe a product-code change.+- [CHG-20260731-001: AgentServer-owned session prewarming](../../changes/records/CHG-20260731-001-session-prewarm-allocation.md) adds session allocation, warm-pool reconciliation, and channel ownership changes.diff --git a/.doc_project_maintainer/modules/gateway-and-channels/README.md b/.doc_project_maintainer/modules/gateway-and-channels/README.mdindex 2d6a52e6f3..4178617998 100644--- a/.doc_project_maintainer/modules/gateway-and-channels/README.md+++ b/.doc_project_maintainer/modules/gateway-and-channels/README.md@@ -2,7 +2,7 @@id: gateway-and-channelsname: Gateway And Channelsconfidence: inferred-last_updated: 2026-07-13+last_updated: 2026-08-01read_when: "Working on Gateway routing, channel adapters, frontend/TUI command forwarding, or AgentServer client behavior."---@@ -22,6 +22,8 @@ Accepts user/channel/front-end input, normalizes it into E2A or legacy-compatibl- `jiuwenswarm/gateway/routing/agent_client.py` receives AgentServer frames, routes normal responses by request ID, and treats server-push frames as out-of-band events.- `docs/en/E2A-protocol.md` describes Gateway -> AgentServer E2A field contracts.- Tests outside the AgentServer directory cover AgentServer client queueing, reconnect/close behavior, stream tail grace, and timeout policy.+- Gateway reports live channel IDs through `agent.prewarm.sync`. Web/TUI local session creation now proxies AgentServer, IM first contact and `/new_session` allocate before forwarding, and ACP/A2A/SSH retain external IDs only as aliases.+- Web session creation derives `user_id` from the authenticated connection and overwrites any request-body value before forwarding to AgentServer.## Related Flows@@ -30,7 +32,8 @@ Accepts user/channel/front-end input, normalizes it into E2A or legacy-compatibl- `agentserver-plan-mode-exit`- `agentserver-schedule-auto-harness`- `agentserver-history-stream`+- `session-prewarm-allocation`## Pending-Document the remaining Gateway message handlers and channel-specific identity/ownership rules; the new flow docs trace only the AgentServer-facing paths needed for the scoped delivery.+Full channel integration remains pending, but new-session identity ownership for Web, TUI, controlled IM, ACP, A2A, SSH, and Cron is traced in `session-prewarm-allocation`. The synchronized AgentServer/Web/project/TUI contract suites passed 139 tests on 2026-08-01.diff --git a/.doc_project_maintainer/project/build-plan.md b/.doc_project_maintainer/project/build-plan.mdindex 6b036fac04..0237359385 100644--- a/.doc_project_maintainer/project/build-plan.md+++ b/.doc_project_maintainer/project/build-plan.md@@ -1,5 +1,5 @@----last_updated: 2026-07-15+last_updated: 2026-07-31sync_status: partialcoverage_status: partialflow_coverage_status: partial@@ -14,13 +14,14 @@ code_symbol_coverage_status: partial- Latest expiration check: the 2026-07-15 normalized-AST scan at `10afedf2` found 0 expired audits among the 128 existing `AgentWebSocketServer` method reviews. No method card or audit signature required refresh, and no previously unaudited symbol was promoted.- Flow delivery: eight AgentServer flows are documented, including MCP, sandbox, plan exit, scheduled Auto-Harness, and history streaming.- Project status remains partial: most modules, directories, source symbol entry docs, cross-layer flows, and default-health audits are still pending.+- The 2026-07-31 scoped feature sync added `session-prewarm-allocation`, ADR-0001, and CHG-20260731-001 without widening repository coverage or claiming a health audit.- Actionable repository queues remain 298 coverage slices and 167 default-health audit slices.-- Every stable source file inventoried: yes, by the 2026-07-15 UTC `inventory_symbols.py --verify-docs` scan; its full output was used as comparison evidence rather than replacing the frozen authoritative ledger.+- Every stable source file inventoried: yes, by the 2026-07-15 `inventory_symbols.py --verify-docs` scan.- Every required symbol documented or out of scope: no.- Every requested-scope audit symbol closure eligible or out of scope: no; 0 AgentWebSocketServer method audits are source-expired, while 69 records currently have entry-document hash mismatches and broader repository audits remain pending.- Inventory extractor summary: 1,023 `python_ast`, 252 `heuristic`; heuristic files require review.- Coverage map recommended mode: multi-agent.-- Git head for the latest AgentWebSocketServer expiration scan: `10afedf222bcd6db98b24347a28f75e4613b3c87`. The authoritative repository inventory and method queue were intentionally not widened during this scoped update.+- Latest scanned git head: `10afedf222bcd6db98b24347a28f75e4613b3c87`; this scoped update did not widen the authoritative inventory.## Inventory Summary@@ -31,7 +32,6 @@ code_symbol_coverage_status: partial- Default-health audit statuses: 8,912 unaudited, 128 agent audited, 0 expired.- Audit integrity: 59 trusted, 0 provisional, 0 suspicious, 69 invalid because entry-document hashes differ from their signed state; 128 unique signature batches and 59 closure-eligible records. This does not change the source-expiration result: all 128 existing method hashes remain current.- Open symbol issue records: 492.-- Full authoritative ledgers and the integrity report are compressed under `ledger-archive/*.full.json.gz`; `project/*.json` contains navigable summaries.- AgentServer method queue: the frozen queue remains 823 methods under `jiuwenswarm/server/`; 128 documented and `agent_audited`, 59 currently closure eligible, 695 unaudited, and 0 source-expired. The fresh scan observed 829 server methods, including 6 additional unaudited methods that were not added to this scoped delivery.## Completed Slices@@ -40,10 +40,11 @@ code_symbol_coverage_status: partial- 2026-07-13: normalized-AST migration, 52 legacy-expiration re-audits, all 128 method cards, and five additional flows.- 2026-07-14: `agentserver-rebase-expiration-reaudit` - re-reviewed exactly the 64 existing AgentWebSocketServer methods expired by the rebase at `39feee89`; all 64 are trusted, with no new unaudited symbol added or promoted.- 2026-07-15: `agentserver-expiration-scan` - scanned `10afedf2`; all 128 existing AgentWebSocketServer method audits remain source-current, 0 expired, and 6 newly observed unaudited server methods were left outside the frozen queue.+- 2026-07-31: AgentServer-owned session allocation and one-slot DeepAgent prewarming across enabled channels/projects; Web, TUI, IM, ACP, A2A, SSH, fork, and single-Agent Cron creation paths were aligned.## Completed AgentServer Flow Slices-- `gateway-agentserver-e2a-chat`, `agentserver-session-lifecycle`, `agentserver-server-push`, `agentserver-command-mcp`, `agentserver-sandbox-runtime`, `agentserver-plan-mode-exit`, `agentserver-schedule-auto-harness`, `agentserver-history-stream`.+- `gateway-agentserver-e2a-chat`, `agentserver-session-lifecycle`, `agentserver-server-push`, `agentserver-command-mcp`, `agentserver-sandbox-runtime`, `agentserver-plan-mode-exit`, `agentserver-schedule-auto-harness`, `agentserver-history-stream`, `session-prewarm-allocation`.## Pending Code And Audit Slices@@ -55,10 +56,11 @@ code_symbol_coverage_status: partial- `jiuwenswarm/agents/harness/team`: distributed team lifecycle and remote member bootstrap.- `jiuwenswarm/channels/web`, `jiuwenswarm/channels/tui`, and `jiuwenbox`: UI state, command consumers, and sandbox service boundaries.- `tests/unit_tests/agentserver`: repository-coverage-only test symbols remain largely undocumented.+- Session prewarming: new `AgentWarmPool` symbols, `AgentManager` pool methods, `JiuWenSwarmDeepAdapter.prepare_session` and runtime split methods, Gateway/Channel allocators, and Cron allocation remain unaudited. `AgentWebSocketServer._handle_session_create` changed after its prior audit and must be treated as `audit_expired`; `_handle_agent_prewarm_sync` is unaudited.## Highest-Risk Findings To Carry Forward-- Session IDs reach filesystem-backed helpers without confirmed containment; scheduled work lacks durable channel/project/Agent identity.+- Existing-session IDs still reach filesystem-backed helpers without confirmed containment. New session and Cron identity now originate in AgentServer, but create-token durability and warm resource bounds need follow-up.- MCP, agent, extension, harness-package, and sandbox mutations lack transactional rollback; extension import also accepts executable host folders.- ACP responses use process-wide correlation without confirmed connection/session ownership; server push and global managers also have under-specified ownership.- Model caching collapses same-name providers and lacks a config fingerprint, allowing partial or stale initialization.diff --git a/.doc_project_maintainer/project/flows/agentserver-session-lifecycle.md b/.doc_project_maintainer/project/flows/agentserver-session-lifecycle.mdindex 1cb38f3c1e..81b0e6b485 100644--- a/.doc_project_maintainer/project/flows/agentserver-session-lifecycle.md+++ b/.doc_project_maintainer/project/flows/agentserver-session-lifecycle.md@@ -3,7 +3,7 @@ id: agentserver-session-lifecyclename: AgentServer Session Lifecyclestatus: partialconfidence: confirmed-last_updated: 2026-07-13+last_updated: 2026-07-31user_visible_surface: "Session create, switch, list, fork, rewind, delete, history, and team session operations."source_of_truth:- "agent session directories"@@ -27,11 +27,11 @@ entrypoints:## Outcome-User and team session operations are exposed for create, switch, list, rename, delete, fork, rewind, compact, and history. Static analysis confirms the RPC paths but also shows that `session.create` does not itself reserve or persist a unique session and that caller-provided IDs reach later filesystem-backed operations.+User and team session operations are exposed for create, switch, list, rename, delete, fork, rewind, compact, and history. New IDs and fork targets are now allocated by AgentServer; explicit new IDs are rejected and restoration uses `session.switch`.## Causal Path-`_handle_message` routes session and history `ReqMethod` values to local handlers before generic chat handling. Session create chooses or accepts an ID and may prepare team switching, but does not durably reserve the ID. Fork copies filesystem session state, history/context, and DeepAgent state through multiple non-atomic steps. History handlers read persisted records, filter restorable records, enforce per-record/page limits, and encode sanitized records. Delete and team delete handlers cross metadata, filesystem, and active runtime state.+`_handle_message` routes session and history `ReqMethod` values to local handlers before generic chat handling. Session create validates project binding, claims or initializes a server-owned ID, and writes metadata; single-Agent claims can consume a prepared DeepAgent. Fork requests omit the target ID and AgentServer allocates it before copying filesystem and runtime state. History, rewind, delete, and team operations retain their existing stores and behavior.## State Classification@@ -45,12 +45,12 @@ History paging rereads the full persisted history, filters restorable records, r## Contract-Handlers take `AgentRequest.params` fields such as `session_id`, `source_session_id`, `target_session_id`, `title`, page parameters, and mode hints. Responses are `AgentResponse` payloads encoded as E2A wire. A strict normalized `sess_*` identifier and resolved-path containment contract was not found at the AgentWebSocketServer boundary.+`session.create` takes project/work/mode identity plus `create_token`; it returns `session_id`, normalized project binding, `prewarm_hit`, and `prewarm_status`. It rejects explicit `session_id`. Other handlers still accept existing IDs and therefore retain their path-boundary review requirements.## Verification-Tests cover ACP/session creation and switching, session/team delete, history payload limits, session operations, and AgentServer modes. The session-create success test is mock-heavy; direct hostile-ID containment, duplicate reservation, partial fork failure, wrong Agent variant, send failure, and full rewind/restore coverage remain missing.+Focused warm-pool and Web create-token tests cover allocation mechanics. Existing ACP/session, delete, history, and mode tests remain relevant, but the ACP suite was not runnable in this environment because an OpenJiuwen team-runtime dependency is missing.## Known Gaps-Caller-controlled absolute or `..` session IDs can reach path composition in history/session helpers without a confirmed containment check. Create may report success without durable creation or uniqueness; fork can leave partial state while later failure is normalized ambiguously. Detailed downstream audits for rewind, metadata stores, history storage, checkpointer state, and team teardown remain pending.+Existing-session operations can still receive hostile IDs and require containment review. `create_token` idempotency is process-local, and fork can still leave partial state after later copy failure. Detailed downstream audits for metadata, history, checkpointer state, warm-resource limits, and team teardown remain pending.diff --git a/.doc_project_maintainer/project/flows/gateway-agentserver-e2a-chat.md b/.doc_project_maintainer/project/flows/gateway-agentserver-e2a-chat.mdindex b690197298..7a9fda74b5 100644--- a/.doc_project_maintainer/project/flows/gateway-agentserver-e2a-chat.md+++ b/.doc_project_maintainer/project/flows/gateway-agentserver-e2a-chat.md@@ -3,7 +3,7 @@ id: gateway-agentserver-e2a-chatname: Gateway AgentServer E2A Chatstatus: partialconfidence: confirmed-last_updated: 2026-07-07+last_updated: 2026-07-31user_visible_surface: "Channel, TUI, CLI, ACP, and web responses produced from AgentServer output."source_of_truth: []modules:@@ -34,6 +34,8 @@ Gateway `WebSocketAgentServerClient` connects to AgentServer, waits for `connectRequests with special methods go to local handlers. Other requests go to `_handle_stream` or `_handle_unary`, which resolve mode and agent state through `AgentManager`, call `process_message_stream` or `process_message`, encode responses through E2A wire helpers, and send them under the connection send lock.+For newly allocated single-Agent sessions, adapter resolution first awaits the warm-pool preparation Future. A READY claim has already completed DeepAgent creation and interaction startup; a miss shares the background initialization task with the first chat.+## State Classification- Transient runtime state: WebSocket connection, per-request tasks, `_session_stream_tasks`, send lock, ACP client capability cache.diff --git a/.doc_project_maintainer/project/flows/session-prewarm-allocation.md b/.doc_project_maintainer/project/flows/session-prewarm-allocation.mdnew file mode 100644index 0000000000..291c659787--- /dev/null+++ b/.doc_project_maintainer/project/flows/session-prewarm-allocation.md@@ -0,0 +1,82 @@+---+id: session-prewarm-allocation+name: Session Prewarm And Allocation+status: partial+confidence: confirmed+last_updated: 2026-08-01+user_visible_surface: "Low-latency creation of single-Agent work/code sessions across enabled channels."+source_of_truth:+ - "AgentServer session metadata"+ - "AgentServer process-local warm pool"+modules:+ - agentserver-runtime+ - gateway-and-channels+ - agent-harness+directories:+ - jiuwenswarm/server+ - jiuwenswarm/gateway+ - jiuwenswarm/channels+code_symbols:+ - AgentWarmPool+ - AgentWarmPool.sync+ - AgentWarmPool.claim+ - AgentWebSocketServer._handle_agent_prewarm_sync+ - AgentWebSocketServer._handle_session_create+ - JiuWenSwarmDeepAdapter.prepare_session+ - JiuWenSwarmDeepAdapter.configure_session_runtime+entrypoints:+ - jiuwenswarm/gateway/app_gateway.py+ - jiuwenswarm/server/agent_ws_server.py+---++# Session Prewarm And Allocation++## Outcome++For each enabled channel and visible/default project, AgentServer maintains one unclaimed, session-bound READY DeepAgent for single-Agent work or code mode. A new session receives its ID from AgentServer. A warm hit avoids `create_instance` and `start_interaction` on the first `chat.send`; a miss returns an ID immediately, initializes in the background, and makes the first message await that same task.++Team, `code.team`, and Swarm creation bypass the warm pool.++## Causal Path++1. Gateway finishes channel registration and sends `agent.prewarm.sync` with the deduplicated live channel IDs. Configuration/channel changes trigger another non-blocking sync; a periodic scan is the fallback.+2. AgentServer resolves visible projects and default work/code projects into `WarmKey` values. `AgentWarmPool` reconciles one READY slot per key with bounded initialization concurrency.+3. Preparation gets the root adapter, creates the session-scoped DeepAdapter, runs `create_instance`, applies session-stable rails/tools/workspace through `configure_session_runtime`, and calls `start_interaction(session_id)`. It never calls `attach_output` or `send_input`.+4. `session.create` validates project/work-mode binding before allocation. `create_token` retries reuse the same claim. A READY slot is atomically removed and replenished; a miss starts one claimed-session preparation task.+5. AgentServer writes normal metadata only after claim. The prewarm marker is retained through the claim and removed only after metadata commits, closing the crash gap without exposing blank slots in normal session listings.+6. `_resolve_adapter`, unary chat, and streaming chat await the claimed session's preparation task. Request IDs, input, attachments, skills, permissions, request workspace/trusted dirs, ACP capabilities, output attachment, and real input remain request-bound.+7. Web, TUI, IM, ACP, A2A, SSH, and single-Agent Cron use the returned ID. ACP/A2A/SSH retain protocol IDs as Gateway aliases. Fork IDs are also AgentServer allocated but do not consume blank warm slots.++## State And Identity++- Source of truth: claimed session metadata and history under AgentServer ownership.+- Cache: READY slots, preparation tasks, `create_token` results, and external-channel aliases are process-local.+- Disposable state: `.prewarm/<session_id>.json` markers identify unclaimed slots and include `boot_id`.+- Revision: `boot_id + SHA-256(config/env) + sequence`; only matching current fingerprints may publish READY.+- ID format: `<channel>_<timestamp/random>`.++On startup, old-boot markers and unclaimed metadata-less directories are removed. Claimed/history sessions are not removed. Configuration changes stale only unclaimed slots; active sessions continue through existing reload behavior.++## Failure, Ordering, And Idempotency++- Project validation precedes allocation.+- Explicit IDs are rejected by `session.create`; existing-session restoration uses `session.switch`.+- `create_token` is required by adapted frontends and enables response-loss retry.+- Gateway-owned Web creation overwrites any request-body `user_id` with the authenticated connection identity before forwarding to AgentServer.+- Initialization exceptions are logged and never publish READY.+- Continuous reconciles cancel superseded warm tasks; late old-revision completion cannot enter the pool.+- A READY root stays pinned until the claimed session reaches its first AgentServer request, preventing idle retirement in the create-to-send gap.++## Verification++- `tests/unit_tests/agentserver/test_agent_warm_pool.py`: key normalization, one READY slot, atomic concurrent claims, replenishment, config replacement, failed preparation, marker activation, and boot cleanup.+- Web `test:create-conversation-session`: AgentServer response ID and stable-token retry.+- Web production build and TUI typecheck cover channel call-site contracts.+- `tests/unit_tests/gateway/test_cron_scheduler.py`: single-Agent Cron performs `session.create` before chat and uses the returned ID.+- AgentServer ACP/plan-mode, Web identity, project binding, and TUI forwarding/KVC ownership suites: 139 passed together.+- The full Windows unit run completed with 3,791 passed, 4 skipped, and 14 failures outside this flow's changed surfaces.+- CodeCheck cleanup removed obsolete local Web/TUI creation fallbacks, reduced warm-pool condition complexity without changing guards, and replaced protected child access with a public stable-config boundary; 166 related tests passed.++## Known Gaps++The pool is process-local and does not preserve idempotency tokens across AgentServer restart. Full live multi-channel integration, load/resource limits, checkpointer cleanup validation, long-lived unclaimed-claim pin expiry, and real OpenJiuwen timing metrics remain pending. The repository-wide symbol audit was not expanded; changed symbols remain unaudited or audit-expired.diff --git a/jiuwenswarm/channels/tui/frontend/src/app-state.ts b/jiuwenswarm/channels/tui/frontend/src/app-state.tsindex f721eaa945..ad3c3f74fa 100644--- a/jiuwenswarm/channels/tui/frontend/src/app-state.ts+++ b/jiuwenswarm/channels/tui/frontend/src/app-state.ts@@ -20,7 +20,6 @@ import {mergeHistoryMessagesForRestore,parseHistoryFrame,} from "./core/history-parser.js";-import { generateSessionId } from "./core/session-state.js";import { getToolGroupIds } from "./core/transcript-timeline.js";import {handleIncomingFrame,@@ -637,7 +636,7 @@ export class CliPiAppState {uiLifecycle?: UiLifecyclePort | null;},) {- this.sessionId = cliSession || generateSessionId();+ this.sessionId = cliSession || "new";this.bootSessionId = cliSession ? cliSession : null;const config = loadTuiConfig();if (config.theme) {@@ -3332,7 +3331,7 @@ export class CliPiAppState {const previousMode = this.mode;void (async () => {try {- await this.request("session.create", {+ await this.request("session.switch", {session_id: target,previous_session_id: "",previous_mode: previousMode,@@ -3366,7 +3365,7 @@ export class CliPiAppState {}} else {// 非已存在错误:降级仅拉历史,不阻断- this.lastError = `session.create failed: ${message}`;+ this.lastError = `session.switch failed: ${message}`;this.emitChange();}} finally {diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/branch.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/branch.tsindex a562296d5b..fb10b0bfac 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/branch.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/branch.ts@@ -1,4 +1,3 @@-import { generateSessionId } from "../../session-state.js";import { addCommandEcho, addError, addInfo } from "../helpers.js";import { CommandKind, type SlashCommand } from "../types.js";@@ -40,16 +39,14 @@ export function createBranchCommand(): SlashCommand {}const customTitle = args.trim();- const targetId = generateSessionId();-try {const payload = await ctx.request<SessionForkPayload>("session.fork", {source_session_id: ctx.sessionId,- target_session_id: targetId,title: customTitle || undefined,});- const forkSessionId = payload.session_id || targetId;+ const forkSessionId = payload.session_id;+ if (!forkSessionId) throw new Error("session.fork did not return a session id");const originalSessionId = ctx.sessionId;ctx.updateSession(forkSessionId);diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/clear.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/clear.tsindex b0b40bfff6..76fc1ebe39 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/clear.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/clear.ts@@ -1,4 +1,4 @@-import { generateSessionId } from "../../session-state.js";+import { generateCreateToken } from "../../session-state.js";import { addCommandEcho, addError, addInfo } from "../helpers.js";import { CommandKind, type SlashCommand } from "../types.js";@@ -18,17 +18,17 @@ export function createClearCommand(): SlashCommand {return;}- const nextId = generateSessionId();- try {- await ctx.request("session.create", {- session_id: nextId,+ const created = await ctx.request<{ session_id?: string; sessionId?: string }>(+ "session.create",+ {+ create_token: generateCreateToken(),previous_session_id: ctx.sessionId,previous_mode: ctx.mode,mode: ctx.mode,- });- } catch {- // Some backends may create the session lazily on first message.- }+ },+ );+ const nextId = created.session_id ?? created.sessionId;+ if (!nextId) throw new Error("session.create did not return a session id");ctx.updateSession(nextId);ctx.setSessionTitle("");diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/new.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/new.tsindex 78441278e1..b0ad0fcfe5 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/new.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/new.ts@@ -1,4 +1,4 @@-import { generateSessionId } from "../../session-state.js";+import { generateCreateToken } from "../../session-state.js";import { makeItem } from "../helpers.js";import { CommandKind, type SlashCommand } from "../types.js";@@ -6,22 +6,25 @@ export function createNewCommand(): SlashCommand {return {name: "new",description: "Create and switch to a session",- usage: "/new [id]",- example: "/new trip-plan",+ usage: "/new",+ example: "/new",kind: CommandKind.BUILT_IN,- takesArgs: true,- action: async (ctx, args) => {+ action: async (ctx) => {if (ctx.isProcessing) {ctx.addItem(makeItem(ctx.sessionId, "error", "session is busy"));return;}- const nextId = args.trim() || generateSessionId();- await ctx.request("session.create", {- session_id: nextId,- previous_session_id: ctx.sessionId,- previous_mode: ctx.mode,- mode: ctx.mode,- });+ const created = await ctx.request<{ session_id?: string; sessionId?: string }>(+ "session.create",+ {+ create_token: generateCreateToken(),+ previous_session_id: ctx.sessionId,+ previous_mode: ctx.mode,+ mode: ctx.mode,+ },+ );+ const nextId = created.session_id ?? created.sessionId;+ if (!nextId) throw new Error("session.create did not return a session id");ctx.updateSession(nextId);ctx.clearEntries();ctx.addItem(makeItem(nextId, "info", `Switched to session ${nextId}`, "i"));diff --git a/jiuwenswarm/channels/tui/frontend/src/core/session-state.ts b/jiuwenswarm/channels/tui/frontend/src/core/session-state.tsindex 885ab75245..ef052bc008 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/session-state.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/session-state.ts@@ -1,7 +1,5 @@import crypto from "node:crypto";-export function generateSessionId(): string {- const ts = Math.floor(Date.now() / 1000).toString(16);- const suffix = crypto.randomBytes(3).toString("hex");- return `tui_${ts}_${suffix}`;+export function generateCreateToken(): string {+ return crypto.randomUUID();}diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsxindex 44033b61cf..988295d59f 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -232,12 +232,6 @@ function ErrorFallback({ error }: { error: Error | null }) {);}-function generateSessionId(): string {- const ts = Date.now().toString(16);- const rand = generateUuidV4().replaceAll('-', '').slice(0, 12);- return `sess_${ts}_${rand}`;-}-function downloadDataUrl(dataUrl: string, filename: string): void {const link = document.createElement('a');link.href = dataUrl;@@ -1598,7 +1592,6 @@ function AppContent() {if (creatingSessionRef.current) return;creatingSessionRef.current = true;useChatStore.getState().setProcessing(NEW_CONVERSATION_ID, true);- const newSid = generateSessionId();const newRuntime = useSessionStore.getState().getRuntime(NEW_CONVERSATION_ID);const runtimeSettings = {mode: newRuntime?.mode ?? mode,@@ -1614,8 +1607,9 @@ function AppContent() {};try {const createParams: Record<string, unknown> = {- session_id: newSid,+ create_token: generateUuidV4(),mode: runtimeSettings.mode,+ is_swarm: runtimeSettings.mode === 'team',title: createConversationTitle(content).slice(0, 100),work_mode: workContext.work_mode,};@@ -1625,7 +1619,7 @@ function AppContent() {createParams.previous_mode = previousSession.mode;}if (runtimeSettings.selectedModelName) {- createParams.model = runtimeSettings.selectedModelName;+ createParams.model_name = runtimeSettings.selectedModelName;}if (workContext.project_id) {createParams.project_id = workContext.project_id;@@ -1633,7 +1627,8 @@ function AppContent() {if (workContext.project_dir) {createParams.project_dir = workContext.project_dir;}- const created = await createConversationSession(request, createParams, newSid);+ const created = await createConversationSession(request, createParams);+ const newSid = created.session_id;const createdSession = registerCreatedConversation(created.session_id,runtimeSettings,diff --git a/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsxindex 600df9fdd9..3318793ae0 100644--- a/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/SessionsPanel/index.tsx@@ -97,9 +97,10 @@ function parseSessionDisplayLabel(sessionId: string, t: (key: string, options?:}// 处理以 sess_、cron_、feishu_、wechat_、xiaoyi_、dingtalk_、tui_ 开头的会话ID- const prefixes = ['sess_', 'cron_', 'feishu_', 'wechat_', 'xiaoyi_', 'dingtalk_', 'wecom_', 'tui_'];+ const prefixes = ['sess_', 'web_', 'cron_', 'feishu_', 'wechat_', 'xiaoyi_', 'dingtalk_', 'wecom_', 'tui_'];const prefixMap: Record<string, string> = {'sess_': t('sessions.prefixes.session'),+ 'web_': t('sessions.prefixes.session'),'cron_': t('sessions.prefixes.cron'),'feishu_': t('sessions.prefixes.feishu'),'wechat_': t('sessions.prefixes.wechat'),@@ -465,13 +466,15 @@ export function SessionsPanel({() => (selectedSessionId ? parseSessionDisplayLabel(selectedSessionId, t) : t('sessions.noneSelected')),[selectedSessionId, t]);- const canRestoreSelectedSession =- Boolean(selectedSessionId?.startsWith('sess_')) && isConnected && !isProcessing;+ const isWebSession = Boolean(+ selectedSessionId?.startsWith('sess_') || selectedSessionId?.startsWith('web_')+ );+ const canRestoreSelectedSession = isWebSession && isConnected && !isProcessing;const restoreButtonTitle = !isConnected? t('sessions.restoreDisabledNotConnected'): isProcessing? t('sessions.restoreDisabledProcessing')- : !selectedSessionId?.startsWith('sess_')+ : !isWebSession? t('sessions.restoreDisabledUnsupported'): t('sessions.restore');diff --git a/jiuwenswarm/channels/web/frontend/src/components/ToolPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ToolPanel/index.tsxindex 0abb55ecbe..4dca04088d 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ToolPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ToolPanel/index.tsx@@ -281,7 +281,12 @@ export function ToolPanel({}, [isConnected, setMemoryUsage]);useEffect(() => {- if (mode !== 'team' || !isConnected || !sessionId?.startsWith('sess_')) {+ if (+ mode !== 'team'+ || !isConnected+ || !sessionId+ || !(sessionId.startsWith('sess_') || sessionId.startsWith('web_'))+ ) {if (sessionId) setTeamHistoryMessages(sessionId, []);hydratedTeamHistorySessionRef.current = null;loadingTeamHistorySessionRef.current = null;diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex 5c0d4e1671..e675280fdb 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -466,7 +466,7 @@"restore": "Restore session","restoreDisabledNotConnected": "Disconnected: cannot restore session","restoreDisabledProcessing": "Assistant is busy: wait until idle to restore a session",- "restoreDisabledUnsupported": "Only web frontend sessions (sess_) can be restored",+ "restoreDisabledUnsupported": "Only Web frontend sessions (sess_ / web_) can be restored","restoreEmpty": "This session has no restorable messages (empty or filtered). You can still chat from here.","delete": "Delete session","teamLabel": "Team: {{team}}",diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex 5ca291edac..9656445ed2 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -467,7 +467,7 @@"restore": "恢复会话","restoreDisabledNotConnected": "连接断开,无法恢复会话","restoreDisabledProcessing": "助手处理中,请结束当前任务后再恢复会话",- "restoreDisabledUnsupported": "仅支持恢复 web 前端会话(sess_)",+ "restoreDisabledUnsupported": "仅支持恢复 Web 前端会话(sess_ / web_)","restoreEmpty": "该会话没有可恢复的消息(为空或均被过滤)。仍可在此继续对话。","delete": "删除会话","teamLabel": "团队:{{team}}",diff --git a/jiuwenswarm/channels/web/frontend/src/multi-session/state/createConversationSession.ts b/jiuwenswarm/channels/web/frontend/src/multi-session/state/createConversationSession.tsindex e96ccd0c2d..81259258c4 100644--- a/jiuwenswarm/channels/web/frontend/src/multi-session/state/createConversationSession.ts+++ b/jiuwenswarm/channels/web/frontend/src/multi-session/state/createConversationSession.ts@@ -1,18 +1,10 @@-/**- * session.create 创建会话:加长超时,并在超时后按同一 session_id 做幂等恢复。- *- * 背景:前端默认 RPC 超时 15s,而 Gateway→AgentServer unary 可达 600s。- * create 超时后 pending 被丢弃,后端却可能已落盘,导致前后端会话分叉。- */+/** session.create: AgentServer allocates the ID; timeout retries use create_token. */import type { WorkMode } from '../../features/workspace/projectTypes';export const SESSION_CREATE_TIMEOUT_MS = 60_000;--/** 超时后轮询 metadata 的次数(含首次立即查询)。 */+/** Kept under the old export names for source compatibility. */export const SESSION_CREATE_METADATA_POLL_ATTEMPTS = 5;--/** 轮询间隔;给仍在飞行的 create 留出落盘时间,降低并发重试 create 的概率。 */export const SESSION_CREATE_METADATA_POLL_INTERVAL_MS = 500;export type SessionCreateRequestFn = <T = unknown>(@@ -66,123 +58,56 @@ export function isAlreadyExistsError(error: unknown): boolean {export function resolveCreatedSessionId(payload: SessionCreatePayload | null | undefined,): string | undefined {- if (!payload) return undefined;- const direct = payload.session_id ?? payload.sessionId;- if (typeof direct === 'string' && direct.trim()) {- return direct.trim();- }- return undefined;+ const direct = payload?.session_id ?? payload?.sessionId;+ return typeof direct === 'string' && direct.trim() ? direct.trim() : undefined;}-function normalizeCreatedSession(- expectedSessionId: string,- payload?: SessionCreatePayload | null,-): CreatedConversationSession {+function normalizeCreatedSession(payload: SessionCreatePayload): CreatedConversationSession {+ const sessionId = resolveCreatedSessionId(payload);+ if (!sessionId) throw new Error('session.create did not return a session id');return {- session_id: expectedSessionId,- project_id: payload?.project_id ?? payload?.projectId,- project_dir: payload?.project_dir ?? payload?.projectDir,- work_mode: normalizeWorkMode(payload?.work_mode ?? payload?.workMode),+ session_id: sessionId,+ project_id: payload.project_id ?? payload.projectId,+ project_dir: payload.project_dir ?? payload.projectDir,+ work_mode: normalizeWorkMode(payload.work_mode ?? payload.workMode),};}function defaultSleep(ms: number): Promise<void> {- return new Promise((resolve) => {- setTimeout(resolve, ms);- });+ return new Promise((resolve) => setTimeout(resolve, ms));}async function invokeSessionCreate(request: SessionCreateRequestFn,createParams: Record<string, unknown>,- expectedSessionId: string,): Promise<CreatedConversationSession> {const payload = await request<SessionCreatePayload>('session.create', createParams, {timeoutMs: SESSION_CREATE_TIMEOUT_MS,});- const createdSessionId = resolveCreatedSessionId(payload);- if (createdSessionId !== expectedSessionId) {- throw new Error('session.create returned an unexpected session id');- }- return normalizeCreatedSession(expectedSessionId, payload);-}--async function tryLoadCreatedSessionMetadata(- request: SessionCreateRequestFn,- expectedSessionId: string,-): Promise<CreatedConversationSession | undefined> {- try {- const meta = await request<SessionCreatePayload>(- 'session.get_metadata',- { session_id: expectedSessionId },- { timeoutMs: SESSION_CREATE_TIMEOUT_MS },- );- const existingId = resolveCreatedSessionId(meta) ?? expectedSessionId;- if (existingId === expectedSessionId) {- return normalizeCreatedSession(expectedSessionId, meta);- }- } catch {- // metadata 尚未就绪或查询失败时继续轮询- }- return undefined;+ return normalizeCreatedSession(payload);}-async function recoverAfterCreateTimeout(+export async function createConversationSession(request: SessionCreateRequestFn,createParams: Record<string, unknown>,- expectedSessionId: string,options: CreateConversationSessionOptions = {},): Promise<CreatedConversationSession> {- const pollAttempts = Math.max(- 1,- options.metadataPollAttempts ?? SESSION_CREATE_METADATA_POLL_ATTEMPTS,- );- const pollIntervalMs = Math.max(+ if (typeof createParams.create_token !== 'string' || !createParams.create_token.trim()) {+ throw new Error('session.create requires create_token');+ }+ const attempts = Math.max(1, options.metadataPollAttempts ?? SESSION_CREATE_METADATA_POLL_ATTEMPTS);+ const intervalMs = Math.max(0,options.metadataPollIntervalMs ?? SESSION_CREATE_METADATA_POLL_INTERVAL_MS,);const sleep = options.sleep ?? defaultSleep;-- for (let attempt = 0; attempt < pollAttempts; attempt += 1) {- if (attempt > 0 && pollIntervalMs > 0) {- await sleep(pollIntervalMs);- }- const recovered = await tryLoadCreatedSessionMetadata(request, expectedSessionId);- if (recovered) {- return recovered;- }- }-- // 轮询仍未见到落盘时,再同 id 重试;ALREADY_EXISTS 视为并发 create 已成功。- try {- return await invokeSessionCreate(request, createParams, expectedSessionId);- } catch (retryError) {- if (isAlreadyExistsError(retryError)) {- const lateMeta = await tryLoadCreatedSessionMetadata(request, expectedSessionId);- if (lateMeta) {- return lateMeta;- }- return normalizeCreatedSession(expectedSessionId);- }- throw retryError;- }-}--/**- * 创建会话。超时后先轮询 metadata,再同 session_id 重试;ALREADY_EXISTS 视为成功。- */-export async function createConversationSession(- request: SessionCreateRequestFn,- createParams: Record<string, unknown>,- expectedSessionId: string,- options: CreateConversationSessionOptions = {},-): Promise<CreatedConversationSession> {- try {- return await invokeSessionCreate(request, createParams, expectedSessionId);- } catch (error) {- if (!isRequestTimeoutError(error)) {- throw error;+ for (let attempt = 0; attempt < attempts; attempt += 1) {+ if (attempt > 0 && intervalMs > 0) await sleep(intervalMs);+ try {+ return await invokeSessionCreate(request, createParams);+ } catch (error) {+ if (!isRequestTimeoutError(error) || attempt === attempts - 1) throw error;}- return recoverAfterCreateTimeout(request, createParams, expectedSessionId, options);}+ throw new Error('session.create retry exhausted');}diff --git a/jiuwenswarm/channels/web/frontend/tests/createConversationSession.test.mjs b/jiuwenswarm/channels/web/frontend/tests/createConversationSession.test.mjsindex 9540787355..42d0c46fa7 100644--- a/jiuwenswarm/channels/web/frontend/tests/createConversationSession.test.mjs+++ b/jiuwenswarm/channels/web/frontend/tests/createConversationSession.test.mjs@@ -11,176 +11,75 @@ import {resolveCreatedSessionId,} from '../node_modules/.cache/create-conversation-session/multi-session/state/createConversationSession.js';-const fastRecoverOptions = {+const fastRetryOptions = {metadataPollAttempts: 3,metadataPollIntervalMs: 0,sleep: async () => {},};-test('SESSION_CREATE_TIMEOUT_MS is longer than the default 15s RPC timeout', () => {+test('session.create constants and response ID normalization', () => {assert.equal(SESSION_CREATE_TIMEOUT_MS, 60_000);assert.equal(SESSION_CREATE_METADATA_POLL_ATTEMPTS, 5);assert.equal(SESSION_CREATE_METADATA_POLL_INTERVAL_MS, 500);+ assert.equal(resolveCreatedSessionId({ session_id: 'web_a' }), 'web_a');+ assert.equal(resolveCreatedSessionId({ sessionId: 'web_b' }), 'web_b');});-test('resolveCreatedSessionId accepts snake_case and camelCase', () => {- assert.equal(resolveCreatedSessionId({ session_id: 'sess_a' }), 'sess_a');- assert.equal(resolveCreatedSessionId({ sessionId: 'sess_b' }), 'sess_b');- assert.equal(resolveCreatedSessionId({}), undefined);-});--test('isRequestTimeoutError / isAlreadyExistsError read error.code', () => {+test('error helpers read error.code', () => {assert.equal(isRequestTimeoutError({ code: 'REQUEST_TIMEOUT' }), true);- assert.equal(isRequestTimeoutError({ code: 'WS_NOT_READY' }), false);assert.equal(isAlreadyExistsError({ code: 'ALREADY_EXISTS' }), true);- assert.equal(isAlreadyExistsError(new Error('x')), false);});-test('createConversationSession succeeds on first create', async () => {+test('uses the AgentServer-returned ID', async () => {const calls = [];const request = async (method, params, options) => {calls.push({ method, params, options });- return { sessionId: 'sess_new', projectId: 'default', workMode: 'work' };+ return { sessionId: 'web_real', projectId: 'default', workMode: 'work' };};-- const created = await createConversationSession(- request,- { session_id: 'sess_new', mode: 'agent' },- 'sess_new',- );-- assert.deepEqual(created, {- session_id: 'sess_new',- project_id: 'default',- project_dir: undefined,- work_mode: 'work',+ const created = await createConversationSession(request, {+ create_token: 'stable-token',+ mode: 'agent',});- assert.equal(calls.length, 1);- assert.equal(calls[0].method, 'session.create');+ assert.equal(created.session_id, 'web_real');+ assert.equal(calls[0].params.session_id, undefined);assert.equal(calls[0].options.timeoutMs, SESSION_CREATE_TIMEOUT_MS);});-test('createConversationSession recovers via get_metadata after REQUEST_TIMEOUT', async () => {- const calls = [];- const request = async (method, params, options) => {- calls.push({ method, params, options });- if (method === 'session.create') {- const err = new Error('timeout');- err.code = 'REQUEST_TIMEOUT';- throw err;- }- if (method === 'session.get_metadata') {- return { session_id: 'sess_recover', project_id: 'default', work_mode: 'work' };- }- throw new Error(`unexpected method ${method}`);- };-- const created = await createConversationSession(- request,- { session_id: 'sess_recover', mode: 'agent' },- 'sess_recover',- fastRecoverOptions,- );-- assert.equal(created.session_id, 'sess_recover');- assert.deepEqual(- calls.map((c) => c.method),- ['session.create', 'session.get_metadata'],- );-});--test('createConversationSession polls metadata before retrying create', async () => {+test('response-loss retry reuses the same create_token', async () => {const calls = [];- let metaCount = 0;- const request = async (method) => {- calls.push(method);- if (method === 'session.create') {- const err = new Error('timeout');- err.code = 'REQUEST_TIMEOUT';- throw err;- }- if (method === 'session.get_metadata') {- metaCount += 1;- if (metaCount < 3) {- const missing = new Error('not found');- missing.code = 'NOT_FOUND';- throw missing;- }- return { session_id: 'sess_poll', project_id: 'default', work_mode: 'work' };+ const request = async (method, params) => {+ calls.push({ method, params: { ...params } });+ if (calls.length === 1) {+ const error = new Error('timeout');+ error.code = 'REQUEST_TIMEOUT';+ throw error;}- throw new Error(`unexpected method ${method}`);+ return { session_id: 'web_retry' };};-const created = await createConversationSession(request,- { session_id: 'sess_poll', mode: 'agent' },- 'sess_poll',- fastRecoverOptions,+ { create_token: 'retry-token', mode: 'agent' },+ fastRetryOptions,);-- assert.equal(created.session_id, 'sess_poll');- assert.deepEqual(calls, [- 'session.create',- 'session.get_metadata',- 'session.get_metadata',- 'session.get_metadata',+ assert.equal(created.session_id, 'web_retry');+ assert.deepEqual(calls.map((call) => call.params.create_token), [+ 'retry-token',+ 'retry-token',]);});-test('createConversationSession retries create and treats ALREADY_EXISTS as success', async () => {- const calls = [];- let createCount = 0;- const request = async (method, params, options) => {- calls.push({ method, params, options });- if (method === 'session.create') {- createCount += 1;- if (createCount === 1) {- const err = new Error('timeout');- err.code = 'REQUEST_TIMEOUT';- throw err;- }- const exists = new Error('session already exists');- exists.code = 'ALREADY_EXISTS';- throw exists;- }- if (method === 'session.get_metadata') {- const missing = new Error('not found');- missing.code = 'NOT_FOUND';- throw missing;- }- throw new Error(`unexpected method ${method}`);- };-- const created = await createConversationSession(- request,- { session_id: 'sess_exists', mode: 'agent' },- 'sess_exists',- fastRecoverOptions,- );-- assert.equal(created.session_id, 'sess_exists');- assert.deepEqual(- calls.map((c) => c.method),- [- 'session.create',- 'session.get_metadata',- 'session.get_metadata',- 'session.get_metadata',- 'session.create',- 'session.get_metadata',- ],+test('requires create_token and does not swallow non-timeout errors', async () => {+ await assert.rejects(+ () => createConversationSession(async () => ({}), { mode: 'agent' }),+ /requires create_token/,);-});--test('non-timeout errors are not swallowed', async () => {- const request = async () => {- const err = new Error('bad request');- err.code = 'BAD_REQUEST';- throw err;- };-await assert.rejects(- () => createConversationSession(request, { session_id: 'sess_x' }, 'sess_x'),+ () =>+ createConversationSession(async () => {+ const error = new Error('bad request');+ error.code = 'BAD_REQUEST';+ throw error;+ }, { create_token: 'x' }),(error) => error.code === 'BAD_REQUEST',);});diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.pyindex f23134b4af..20d6956e7f 100644--- a/jiuwenswarm/common/schema/message.py+++ b/jiuwenswarm/common/schema/message.py@@ -65,6 +65,7 @@ class ReqMethod(Enum):CONFIG_CACHE_CLEAR = "config.cache_clear"AGENT_RELOAD_CONFIG = "agent.reload_config"+ AGENT_PREWARM_SYNC = "agent.prewarm.sync"MEMORY_COMPUTE = "memory.compute"diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.pyindex a965ae6b66..5098abb837 100644--- a/jiuwenswarm/gateway/app_gateway.py+++ b/jiuwenswarm/gateway/app_gateway.py@@ -1597,6 +1597,29 @@ async def _run(message_handler.set_channel_manager(channel_manager)updater_service = UpdaterService()+ async def _sync_agent_prewarm_channels() -> None:+ try:+ env = e2a_from_agent_fields(+ request_id=f"agent-prewarm-sync-{uuid_module.uuid4().hex[:8]}",+ channel_id="",+ req_method=ReqMethod.AGENT_PREWARM_SYNC,+ params={+ "enabled_channels": sorted(set(channel_manager.enabled_channels)),+ },+ )+ resp = await client.send_request(env)+ if not getattr(resp, "ok", False):+ raise RuntimeError(+ f"agent.prewarm.sync rejected: {getattr(resp, 'payload', None)}"+ )+ except Exception as exc: # noqa: BLE001 - prewarm never blocks Gateway config+ logger.warning("[App] agent.prewarm.sync failed (non-fatal): %s", exc)++ async def _periodic_agent_prewarm_sync() -> None:+ while True:+ await asyncio.sleep(60)+ await _sync_agent_prewarm_channels()+async def _on_config_saved(updated_env_keys: set[str] | None = None,*,@@ -1655,6 +1678,11 @@ async def _run(return Falseraise RuntimeError(f"agent.reload_config rejected: {err_msg}")+ asyncio.create_task(+ _sync_agent_prewarm_channels(),+ name="agent-prewarm-sync-after-config",+ )+if updated_env_keys and (browser_runtime_keys & set(updated_env_keys)):restart_env = e2a_from_agent_fields(request_id=f"browser-restart-{uuid_module.uuid4().hex[:8]}",@@ -2482,8 +2510,21 @@ async def _run(else:logger.info("[App] channels.ssh missing or invalid, SshChannel disabled")+ asyncio.create_task(+ _sync_agent_prewarm_channels(),+ name="agent-prewarm-sync-after-channel-change",+ )+channel_manager.set_config_callback(_apply_channel_config)await channel_manager.set_config(initial_channels_conf)+ asyncio.create_task(+ _sync_agent_prewarm_channels(),+ name="agent-prewarm-sync-after-startup",+ )+ prewarm_sync_task = asyncio.create_task(+ _periodic_agent_prewarm_sync(),+ name="agent-prewarm-periodic-sync",+ )await channel_manager.start_dispatch()# cron jobs 的 work_mode 补全已改为惰性迁移:scheduler.start() → reload() →@@ -2528,6 +2569,11 @@ async def _run(except asyncio.CancelledError:passfinally:+ prewarm_sync_task.cancel()+ try:+ await prewarm_sync_task+ except asyncio.CancelledError:+ passif a2a_task is not None:a2a_task.cancel()try:diff --git a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.pyindex 9d9ca820a4..1b50830255 100644--- a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py+++ b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py@@ -6,6 +6,7 @@ import asyncioimport inspectimport loggingimport os+import secretsimport shutilimport sysimport time@@ -37,7 +38,6 @@ from jiuwenswarm.common.config import (update_config,)from jiuwenswarm.common.reasoning_injector import build_reasoning_model_request_kwargs-from jiuwenswarm.common.work_mode import DEFAULT_PROJECT_ID_CODEfrom jiuwenswarm.gateway.routing.route_binding import GatewayRouteBindingfrom jiuwenswarm.common.version import __version__from jiuwenswarm.common.utils import get_user_workspace_dir@@ -1478,170 +1478,54 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:)async def _session_create(ws, req_id, params, session_id, user_id=None):- from jiuwenswarm.common.utils import get_agent_sessions_dir- from jiuwenswarm.server.runtime.session.session_metadata import (- get_session_metadata,- init_session_metadata,- )-if not isinstance(params, dict):await channel.send_response(ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST")return- target = str(params.get("session_id") or "").strip()- if not target:- await channel.send_response(- ws, req_id, ok=False, error="session_id is required", code="BAD_REQUEST"- )- return- # TUI 前置归属解析(设计文档 §4.1.6):按 cwd/project_dir 固定 work_mode="code"- # 查找/创建 code 项目并绑定真实 project_id;无目录或解析失败归 default_code- resolved_project_id = ""- resolved_project_dir = ""- work_mode = "code"- try:- from jiuwenswarm.server.runtime.session.project_store import (- find_or_create_code_project_for_tui_params,- )- proj = find_or_create_code_project_for_tui_params(params)- if proj is not None:- resolved_project_id = proj.project_id- resolved_project_dir = proj.project_dir- work_mode = proj.work_mode or "code"- except Exception: # noqa: BLE001- # 解析失败(冲突/权限等)不阻断会话创建,会话归 default_code- logger.warning(- "[TUI] session.create project pre-resolution failed: "- "session_id=%s project_dir=%r cwd=%r",- target,- params.get("project_dir") if isinstance(params, dict) else None,- params.get("cwd") if isinstance(params, dict) else None,- exc_info=True,- )- workspace_session_dir = get_agent_sessions_dir()- workspace_session_dir.mkdir(parents=True, exist_ok=True)- session_dir = workspace_session_dir / target- if session_dir.exists():+ real_client = _resolve_agent_client(agent_client)+ if real_client is None:await channel.send_response(ws,req_id,ok=False,- error="session already exists",- code="ALREADY_EXISTS",+ error="AgentServer is unavailable",+ code="SERVICE_UNAVAILABLE",)return- session_dir.mkdir()- # 初始化元数据(与 web channel 对齐);同步写入 channel_metadata,- # 避免 /clear 后立刻 /resume(current dir)因缺少路径而被过滤(Issue #2503)- channel_meta = build_tui_session_create_channel_metadata(- params, resolved_project_dir- )- # 预解析失败但请求仍带路径时,顶层 project_dir 也用请求路径,便于读侧回退- top_project_dir = resolved_project_dir or (- (channel_meta or {}).get("project_dir") or ""- )- init_session_metadata(- session_id=target,- channel_id="tui",- title=str(params.get("title") or "").strip(),- mode=params.get("mode", "code.normal"),- project_dir=top_project_dir,- project_id=resolved_project_id,- work_mode=work_mode,- channel_metadata=channel_meta,- )- # 触发 SessionStart hook- mh = bind.message_handler- if mh:- mh.trigger_session_start_hook(target, source="tui")- # TUI /new and /clear switch away from the previous product session- # through this local handler. Prefer the canonical AgentServer owner- # dispatch so Plan and Team follow the same lifecycle as Web.- previous_session_id = str(params.get("previous_session_id") or "").strip()- lifecycle_forwarded = False- real_client = (- agent_client.get("value")- if isinstance(agent_client, dict)- else agent_client- )- if real_client is not None:- try:- from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields- from jiuwenswarm.common.schema.message import ReqMethod-- lifecycle_params = dict(params)- lifecycle_params["session_id"] = target- env = e2a_from_agent_fields(- request_id=req_id,- channel_id="tui",- session_id=target,- req_method=ReqMethod.SESSION_SWITCH,- params=lifecycle_params,- is_stream=False,- timestamp=time.time(),- user_id=user_id or getattr(ws, "_gateway_user_id", None),- )- response = await real_client.send_request(env)- lifecycle_forwarded = bool(response.ok)- if not response.ok:- logger.warning(- "[cli session.create] session.switch lifecycle forward rejected; "- "falling back locally: target_session_id=%s previous_session_id=%s",- target,- previous_session_id,- )- except Exception as exc:- logger.warning(- "[cli session.create] session.switch lifecycle forward failed; "- "falling back locally: target_session_id=%s error=%s",- target,- exc,- )+ from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields+ from jiuwenswarm.common.schema.message import ReqMethod- previous_session_changed = (- bool(previous_session_id)- and previous_session_id not in {"new", target}+ create_params = dict(params)+ create_params.pop("session_id", None)+ create_params.setdefault("create_token", secrets.token_hex(16))+ env = e2a_from_agent_fields(+ request_id=req_id,+ channel_id="tui",+ req_method=ReqMethod.SESSION_CREATE,+ params=create_params,+ is_stream=False,+ timestamp=time.time(),+ user_id=user_id or getattr(ws, "_gateway_user_id", None),)- if not lifecycle_forwarded and previous_session_changed:- from jiuwenswarm.server.runtime.session.kv_cache_affinity_lifecycle import (- dispatch_offload_session_kv_cache,- is_kv_cache_affinity_enabled,+ try:+ response = await _send_tui_agent_request(+ real_client, env, label="session.create")-- try:- affinity_enabled = is_kv_cache_affinity_enabled()- except Exception as exc:- affinity_enabled = False- logger.warning(- "[cli session.create] affinity gate failed; KVC hook skipped: "- "previous_session_id=%s error=%s",- previous_session_id,- exc,- )- if affinity_enabled:- try:- previous_metadata = get_session_metadata(previous_session_id)- previous_mode = str(previous_metadata.get("mode") or "").strip().lower()- if previous_mode not in {"team", "team.plan", "code.team"}:- dispatch_offload_session_kv_cache(- session_id=previous_session_id,- parent_session_id=previous_session_id,- )- except Exception as exc:- logger.warning(- "[cli session.create] Plan KVC hook failed; continuing: "- "previous_session_id=%s error=%s",- previous_session_id,- exc,- )- # 响应带最终归属(设计文档 §4.1.6):未绑定真实项目时归 default_code- await channel.send_response(ws, req_id, ok=True, payload={- "session_id": target,- "project_id": resolved_project_id or DEFAULT_PROJECT_ID_CODE,- "project_dir": top_project_dir,- "work_mode": work_mode,- })+ except Exception as exc: # noqa: BLE001+ await channel.send_response(+ ws, req_id, ok=False, error=str(exc), code="SERVICE_UNAVAILABLE"+ )+ return+ payload = dict(response.payload or {}) if isinstance(response.payload, dict) else {}+ await channel.send_response(+ ws,+ req_id,+ ok=bool(response.ok),+ payload=payload if response.ok else None,+ error=None if response.ok else str(payload.get("error") or "session.create failed"),+ code=None if response.ok else str(payload.get("code") or "SESSION_CREATE_FAILED"),+ )async def _session_delete(ws, req_id, params, session_id, user_id=None):from jiuwenswarm.server.runtime.session.session_metadata import get_session_metadatadiff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex 5d0889b638..05d325fd85 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -1537,6 +1537,40 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:name=f"{name}.clear_agent_config_cache",)+ def _schedule_agent_prewarm_sync(name: str) -> None:+ """Reconcile project-derived warm keys without delaying the Web RPC."""++ async def _sync() -> None:+ try:+ from jiuwenswarm.common.e2a.gateway_normalize import (+ e2a_from_agent_fields,+ )+ from jiuwenswarm.common.schema.message import ReqMethod++ real_client = _resolve(agent_client)+ if real_client is None:+ return+ cm = _resolve(channel_manager)+ enabled_channels = list(getattr(cm, "enabled_channels", []) or [])+ env = e2a_from_agent_fields(+ request_id=f"agent-prewarm-project-{uuid.uuid4().hex[:8]}",+ channel_id="web",+ req_method=ReqMethod.AGENT_PREWARM_SYNC,+ params={"enabled_channels": sorted(set(enabled_channels))},+ is_stream=False,+ timestamp=time.time(),+ )+ response = await real_client.send_request(env)+ if not getattr(response, "ok", False):+ logger.warning(+ "[Project] agent.prewarm.sync rejected: %s",+ getattr(response, "payload", None),+ )+ except Exception as exc: # noqa: BLE001 - maintenance is non-blocking+ logger.warning("[Project] agent.prewarm.sync failed: %s", exc)++ asyncio.create_task(_sync(), name=f"{name}.agent_prewarm_sync")+def _resolve_env_vars(value: Any) -> Any:"""Recursively resolve environment variables in config values."""if isinstance(value, str):@@ -2700,96 +2734,53 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST",)return- session_id_to_create = params.get("session_id")- if not isinstance(session_id_to_create, str) or not session_id_to_create.strip():- await channel.send_response(- ws, req_id, ok=False, error="session_id is required", code="BAD_REQUEST",- )- return- session_id_to_create = session_id_to_create.strip()-- # Step 1: 归一化 work_mode / project_id / project_dir 三元组- from jiuwenswarm.server.runtime.session.work_mode import resolve_session_work_mode_params- binding = resolve_session_work_mode_params(params, channel_id=channel.channel_id)- if binding.error:+ resolved_agent_client = _resolve(agent_client)+ if resolved_agent_client is None:await channel.send_response(- ws, req_id, ok=False, error=binding.error, code=binding.code,+ ws,+ req_id,+ ok=False,+ error="AgentServer is unavailable",+ code="SERVICE_UNAVAILABLE",)return+ from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields+ from jiuwenswarm.common.schema.message import ReqMethod- # Step 2: 校验 project_id / project_dir 绑定关系(存在性、路径一致性)- project_id, project_dir, p_err, p_code = project_store.resolve_session_project_binding(- binding.project_id, binding.project_dir+ create_params = dict(params)+ create_params.pop("session_id", None)+ authenticated_user_id = str(user_id or "").strip()+ if authenticated_user_id:+ create_params["user_id"] = authenticated_user_id+ else:+ create_params.pop("user_id", None)+ create_params.setdefault("create_token", secrets.token_hex(16))+ env = e2a_from_agent_fields(+ request_id=req_id,+ channel_id=channel.channel_id,+ req_method=ReqMethod.SESSION_CREATE,+ params=create_params,+ is_stream=False,+ timestamp=time.time(),+ user_id=authenticated_user_id or None,)- if p_err:+ try:+ response = await resolved_agent_client.send_request(env)+ except Exception as exc: # noqa: BLE001await channel.send_response(- ws, req_id, ok=False, error=p_err, code=p_code,+ ws, req_id, ok=False, error=str(exc), code="SERVICE_UNAVAILABLE")return-- # Step 3: 确定最终 work_mode- # 对真实 project_id: 最终 work_mode 以 Project 记录为准;若请求显式传了- # work_mode 且与 Project 不一致 → BAD_REQUEST(设计文档 §4.1.6)- # 对默认项目: 使用 binding 归一化的 work_mode- # has_explicit_work_mode 由 resolve_session_work_mode_params 统一计算,- # 不再从 params 直接判定(避免 gateway 注入通道默认值后被误判为显式)- if not is_default_project_id(project_id):- proj = project_store.get_project_by_id(project_id, cache_bust=True)- if proj is not None:- project_work_mode = proj.work_mode or DEFAULT_WEB_WORK_MODE- if binding.has_explicit_work_mode and project_work_mode != binding.work_mode:- await channel.send_response(- ws, req_id, ok=False,- error=f"work_mode mismatch: project is '{project_work_mode}' \- but request specified '{binding.work_mode}'",- code="BAD_REQUEST",- )- return- final_work_mode = project_work_mode- else:- # 竞态: project 已被其他进程删除/隐藏。- # 不创建指向不存在项目的会话,返回 NOT_FOUND 由调用方决定回退策略。- await channel.send_response(- ws, req_id, ok=False,- error=f"project not found: {project_id}",- code="NOT_FOUND",- )- return- else:- final_work_mode = binding.work_mode-- workspace_session_dir = get_agent_sessions_dir()- if not workspace_session_dir.exists():- workspace_session_dir.mkdir(parents=True)- session_dir = workspace_session_dir / session_id_to_create- if session_dir.exists():- await channel.send_response(- ws, req_id, ok=False, error="session already exists", code="ALREADY_EXISTS",- )- return- session_dir.mkdir()-- # 初始化会话元数据- from jiuwenswarm.server.runtime.session.session_metadata import init_session_metadata- # User identity comes exclusively from the authenticated WebSocket handshake.- init_session_metadata(- session_id=session_id_to_create,- channel_id=params.get("channel_id", ""),- user_id=str(user_id or "").strip(),- title=params.get("title", ""),- mode=params.get("mode", "unknown"),- project_dir=project_dir,- project_id=project_id,- work_mode=final_work_mode,+ payload = dict(response.payload or {}) if isinstance(response.payload, dict) else {}+ await channel.send_response(+ ws,+ req_id,+ ok=bool(response.ok),+ payload=payload if response.ok else None,+ error=None if response.ok else str(payload.get("error") or "session.create failed"),+ code=None if response.ok else str(payload.get("code") or "SESSION_CREATE_FAILED"),)- await channel.send_response(ws, req_id, ok=True, payload={- "session_id": session_id_to_create,- "project_id": project_id,- "project_dir": project_dir,- "work_mode": final_work_mode,- })-async def _session_rename(ws, req_id, params, session_id):"""重命名会话标题(查询/设置/清除三种语义),复用 apply_session_rename。@@ -3384,6 +3375,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:proj.project_id, proj.project_dir, exc,)project_payload = _project_info_payload(proj)+ _schedule_agent_prewarm_sync("project.create")await channel.send_response(ws, req_id, ok=True, payload={"project_id": proj.project_id,"project_dir": proj.project_dir,@@ -3569,6 +3561,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:if registry is not None:registry.cleanup_project(project_id)project_store.reindex_project_pin_orders()+ _schedule_agent_prewarm_sync("project.remove")await channel.send_response(ws, req_id, ok=True, payload={"project_id": project_id,@@ -3645,6 +3638,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:ws, req_id, ok=False, error="project is not hidden", code="CONFLICT",)return+ _schedule_agent_prewarm_sync("project.restore")await channel.send_response(ws, req_id, ok=True, payload={"project_id": restored.project_id,diff --git a/jiuwenswarm/gateway/cron/scheduler.py b/jiuwenswarm/gateway/cron/scheduler.pyindex 0f6a8d3761..ed58b33c43 100644--- a/jiuwenswarm/gateway/cron/scheduler.py+++ b/jiuwenswarm/gateway/cron/scheduler.py@@ -559,6 +559,42 @@ class CronSchedulerService:)return "__cron__", f"cron_{ts}_{job.id}"+ async def _allocate_single_agent_session(+ self,+ job: CronJob,+ *,+ mode: str,+ project_dir: str,+ run_id: str,+ ) -> str:+ env = e2a_from_agent_fields(+ request_id=f"cron-session-create-{run_id}",+ channel_id="__cron__",+ req_method=ReqMethod.SESSION_CREATE,+ params={+ "create_token": f"cron:{run_id}",+ "mode": mode,+ "is_swarm": False,+ "project_id": job.project_id or "",+ "project_dir": project_dir,+ "work_mode": job.work_mode or DEFAULT_WEB_WORK_MODE,+ "model_name": job.model_name or None,+ "cron_id": job.id,+ },+ is_stream=False,+ timestamp=self._now_fn(),+ )+ response = await self._agent_client.send_request(env)+ payload = dict(response.payload or {}) if isinstance(response.payload, dict) else {}+ if not response.ok:+ raise RuntimeError(str(payload.get("error") or "cron session.create failed"))+ session_id = str(+ payload.get("session_id") or payload.get("sessionId") or ""+ ).strip()+ if not session_id:+ raise RuntimeError("cron session.create returned empty session_id")+ return session_id+def _schedule_event(self, at_dt: datetime, kind: str, job_id: str, run_id: str) -> None:at_ts = float(at_dt.timestamp())self._seq += 1@@ -903,6 +939,7 @@ class CronSchedulerService:mode = CRON_JOB_DEFAULT_MODEchannel_id = ""exec_session_id = ""+ envelope = Nonetry:mode = str(job.mode or CRON_JOB_DEFAULT_MODE).strip() or CRON_JOB_DEFAULT_MODEif state.exec_channel_id and state.exec_session_id:@@ -921,6 +958,15 @@ class CronSchedulerService:"[Cron] resolve project_dir failed job=%s: %s", job.id, pdir_exc,)exec_project_dir = ""+ if not is_team_cron_mode(mode):+ exec_session_id = await self._allocate_single_agent_session(+ job,+ mode=mode,+ project_dir=exec_project_dir,+ run_id=run_id,+ )+ state.exec_channel_id = "__cron__"+ state.exec_session_id = exec_session_idcron_meta = {"job_id": job.id,"job_name": job.name,diff --git a/jiuwenswarm/gateway/message_handler/message_handler.py b/jiuwenswarm/gateway/message_handler/message_handler.pyindex a5c998dcaf..dc09ce4cb5 100644--- a/jiuwenswarm/gateway/message_handler/message_handler.py+++ b/jiuwenswarm/gateway/message_handler/message_handler.py@@ -64,6 +64,7 @@ _TUI_DISCONNECT_CANCEL_GRACE_SECONDS = 60.0_DEFAULT_INLINE_FILE_SIZE_LIMIT = 128 * 1024_KNOWN_JIUWENSWARM_SESSION_PREFIXES = ("sess_",+ "web_","tui_","acp_","cron_",@@ -221,6 +222,8 @@ class MessageHandler(ABC):self._session_last_originator: dict[str, tuple[str, str]] = {}self._acp_session_aliases: dict[str, str] = {} # external_session_id -> internal_session_idself._acp_session_alias_lock = asyncio.Lock()+ self._external_session_aliases: dict[tuple[str, str], str] = {}+ self._external_session_alias_lock = asyncio.Lock()# per-channel 控制状态:支持 \new_session / \mode 指令。# 使用 ChannelType 的 value 作为标准键,避免散落的硬编码字符串。@@ -562,9 +565,6 @@ class MessageHandler(ABC):ch_cfg = channels_cfg.get(channel_id) or {}sid_raw = ch_cfg.get("default_session_id") or ""sid = str(sid_raw).strip() or None- # 若未在 config 中指定默认 session_id,为该 channel 生成一个带时间戳的新 session_id- if not sid:- sid = self._generate_channel_session_id(channel_id)mode_raw = str(ch_cfg.get("default_mode") or "agent").strip().lower()mode_map = {"agent": ChannelMode.AGENT,@@ -605,7 +605,7 @@ class MessageHandler(ABC):state = self._get_channel_default_state(ch)identity_key = self._extract_identity_tuple(msg)if identity_key and self._channel_id_matches_session_map_types(str(ch or "")):- state.session_id = self._session_map.get_session_id(*identity_key)+ state.session_id = self._session_map.find_session_id(*identity_key)self._channel_states[key] = statereturn state@@ -622,11 +622,72 @@ class MessageHandler(ABC):},)- def _generate_channel_session_id(self, channel_id: str) -> str:- """为指定 channel 生成新的 session_id."""- ts = format(int(time.time() * 1000), "x")- suffix = secrets.token_hex(3)- return f"{channel_id}_{ts}_{suffix}"+ async def _allocate_channel_session(+ self,+ msg: "Message",+ state: ChannelControlState,+ ) -> str:+ """Allocate and persist a real AgentServer-owned session for a channel."""+ from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields+ from jiuwenswarm.common.schema.message import ReqMethod++ channel_type = self._resolve_control_channel_type(msg)+ mode = state.mode.value+ params = dict(msg.params or {})+ create_params = {+ "create_token": secrets.token_hex(16),+ "mode": mode,+ "is_swarm": ChannelMode.is_team_mode(mode),+ }+ for name in ("project_id", "project_dir", "work_mode", "model_name"):+ if params.get(name) is not None:+ create_params[name] = params[name]+ env = e2a_from_agent_fields(+ request_id=f"session-create-{int(time.time() * 1000):x}-{secrets.token_hex(3)}",+ channel_id=channel_type,+ req_method=ReqMethod.SESSION_CREATE,+ params=create_params,+ is_stream=False,+ timestamp=time.time(),+ )+ resp = await self._send_non_stream_agent_request(env)+ payload = dict(resp.payload or {}) if isinstance(resp.payload, dict) else {}+ if not resp.ok:+ raise RuntimeError(str(payload.get("error") or "session.create failed"))+ sid = str(payload.get("session_id") or payload.get("sessionId") or "").strip()+ if not sid:+ raise RuntimeError("session.create returned empty session_id")+ state.session_id = sid+ identity_key = self._extract_identity_tuple(msg)+ if identity_key and self._channel_id_matches_session_map_types(str(msg.channel_id or "")):+ self._session_map.set_session_id(*identity_key, sid)+ return sid++ async def _resolve_external_channel_session(self, msg: "Message") -> None:+ """Map A2A/SSH protocol IDs onto AgentServer-owned product Sessions."""+ channel_id = str(msg.channel_id or "").strip()+ external_id = str(msg.session_id or "").strip()+ if channel_id not in {"a2a", "ssh"} or not external_id:+ return+ key = (channel_id, external_id)+ resolved = self._external_session_aliases.get(key)+ if resolved is None:+ async with self._external_session_alias_lock:+ resolved = self._external_session_aliases.get(key)+ if resolved is None:+ raw_mode = str((msg.params or {}).get("mode") or "agent")+ try:+ mode = ChannelMode(raw_mode)+ except ValueError:+ mode = ChannelMode.AGENT+ resolved = await self._allocate_channel_session(+ msg, ChannelControlState(mode=mode)+ )+ self._external_session_aliases[key] = resolved+ metadata = dict(msg.metadata or {})+ metadata.setdefault("external_session_id", external_id)+ msg.metadata = metadata+ msg.session_id = resolved@staticmethoddef _extract_identity_tuple(msg: "Message") -> tuple[str, str, str, str] | None:@@ -1401,13 +1462,20 @@ class MessageHandler(ABC):if parsed.action is ParsedControlAction.NEW_SESSION_OK:old_sid = state.session_id- cid = str(getattr(msg, "channel_id", "") or "")- identity_key = self._extract_identity_tuple(msg)- if identity_key and self._channel_id_matches_session_map_types(cid):- new_sid = self._session_map.get_session_id(*identity_key, rotate=True)- else:- new_sid = self._generate_channel_session_id(channel_type)- state.session_id = new_sid+ try:+ state.session_id = None+ new_sid = await self._allocate_channel_session(msg, state)+ except Exception as exc: # noqa: BLE001+ state.session_id = old_sid+ asyncio.create_task(+ self.send_channel_notice(+ user_infos,+ ch,+ msg.session_id,+ {"error": f"创建新会话失败:{exc}"},+ )+ )+ return True# 触发 SessionStart hookif self._gateway_hook_handler:asyncio.create_task(@@ -1840,7 +1908,6 @@ class MessageHandler(ABC):returnchannel_type = self._resolve_control_channel_type(msg)- new_sid = self._generate_channel_session_id(channel_type)try:env = e2a_from_agent_fields(@@ -1850,7 +1917,6 @@ class MessageHandler(ABC):req_method=ReqMethod.SESSION_FORK,params={"source_session_id": source_sid,- "target_session_id": new_sid,"title": branch_name,},is_stream=False,@@ -1862,7 +1928,9 @@ class MessageHandler(ABC):raise ValueError(str(payload.get("error") or "session.fork failed"))result = dict(resp.payload or {}) if isinstance(resp.payload, dict) else {}- fork_sid = result.get("session_id", new_sid)+ fork_sid = str(result.get("session_id") or "").strip()+ if not fork_sid:+ raise ValueError("session.fork returned empty session_id")fork_title = result.get("title", branch_name or "Branched conversation")old_sid = state.session_id@@ -2039,11 +2107,16 @@ class MessageHandler(ABC):cid = str(getattr(msg, "channel_id", "") or "")identity_key = self._extract_identity_tuple(msg)if identity_key and self._channel_id_matches_session_map_types(cid):- sid = self._session_map.get_session_id(*identity_key)- state.session_id = sid- msg.session_id = sid+ sid = self._session_map.find_session_id(*identity_key)+ if sid:+ state.session_id = sid+ msg.session_id = sid+ else:+ msg.session_id = Noneelif state.session_id:msg.session_id = state.session_id+ else:+ msg.session_id = None# 将 mode 写入 params,后续 E2A / Agent 侧从 params["mode"] 读取if msg.params is None:@@ -2238,16 +2311,19 @@ class MessageHandler(ABC):return Truereturn cls._is_session_map_style_session_id(sid)- async def _ensure_acp_agent_session(self, session_id: str) -> str:+ async def _ensure_acp_agent_session(self) -> str:from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fieldsfrom jiuwenswarm.common.schema.message import ReqMethodenv = e2a_from_agent_fields(request_id=f"acp-session-create-{int(time.time() * 1000):x}-{secrets.token_hex(3)}",channel_id=_ACP_CHANNEL_ID,- session_id=session_id,req_method=ReqMethod.SESSION_CREATE,- params={"session_id": session_id},+ params={+ "create_token": secrets.token_hex(16),+ "mode": "agent",+ "is_swarm": False,+ },is_stream=False,timestamp=time.time(),)@@ -2256,7 +2332,7 @@ class MessageHandler(ABC):payload = dict(resp.payload or {}) if isinstance(resp.payload, dict) else {}raise RuntimeError(str(payload.get("error") or "acp session.create failed"))payload = dict(resp.payload or {}) if isinstance(resp.payload, dict) else {}- resolved = payload.get("sessionId") or payload.get("session_id") or session_id+ resolved = payload.get("sessionId") or payload.get("session_id")resolved_str = str(resolved or "").strip()if not resolved_str:raise RuntimeError("acp session.create returned empty session_id")@@ -2279,12 +2355,7 @@ class MessageHandler(ABC):if cached:return cached, cached != external- desired = (- external- if self._is_known_jiuwenswarm_session_id(external)- else self._generate_channel_session_id(_ACP_CHANNEL_ID)- )- ensured = await self._ensure_acp_agent_session(desired)+ ensured = await self._ensure_acp_agent_session()self._acp_session_aliases[external] = ensuredreturn ensured, ensured != external@@ -3344,7 +3415,15 @@ class MessageHandler(ABC):continue# 将当前 Channel 的控制状态应用到消息上+ await self._resolve_external_channel_session(msg)self._apply_channel_state(msg)+ channel_type = self._resolve_control_channel_type(msg)+ if (+ channel_type in self._control_channel_types+ and not str(msg.session_id or "").strip()+ ):+ state = self.get_or_create_channel_state(msg)+ msg.session_id = await self._allocate_channel_session(msg, state)# V2: _apply_channel_state has resolved msg.session_id to the real team# session_id and injected params.mode; register GodView now so it landsdiff --git a/jiuwenswarm/gateway/routing/session_map.py b/jiuwenswarm/gateway/routing/session_map.pyindex a5b4b56349..c790251a86 100644--- a/jiuwenswarm/gateway/routing/session_map.py+++ b/jiuwenswarm/gateway/routing/session_map.py@@ -1,8 +1,6 @@from __future__ import annotationsimport json-import secrets-import timefrom enum import Enumfrom pathlib import Path@@ -45,20 +43,6 @@ def _make_key(return f"{provider}::{chat_id}::{bot_id}::{user_id}"-def _make_session_id(- scope: SessionMapScope,- provider: str,- chat_id: str,- bot_id: str,- user_id: str,-) -> str:- ts = format(int(time.time() * 1000), "x")- suffix = secrets.token_hex(3)- if scope == SessionMapScope.PER_CHAT_BOT:- return f"{provider}::{chat_id}::{bot_id}::{ts}::{suffix}"- return f"{provider}::{chat_id}::{bot_id}::{user_id}::{ts}::{suffix}"--class SessionMap:"""Map stable identity (per config scope) -> rotating agent ``session_id``."""@@ -100,10 +84,32 @@ class SessionMap:existing = self._mapping.get(key)if existing and not rotate:return existing+ raise RuntimeError(+ "SessionMap cannot allocate session IDs; use AgentServer session.create"+ )++ def find_session_id(+ self,+ provider: str,+ chat_id: str,+ bot_id: str,+ user_id: str,+ ) -> str | None:+ key = _make_key(self._scope, provider, chat_id, bot_id, user_id)+ return self._mapping.get(key)- sid = _make_session_id(self._scope, provider, chat_id, bot_id, user_id)- if existing == sid:- return sid- self._mapping[key] = sid- self._save()- return sid+ def set_session_id(+ self,+ provider: str,+ chat_id: str,+ bot_id: str,+ user_id: str,+ session_id: str,+ ) -> None:+ key = _make_key(self._scope, provider, chat_id, bot_id, user_id)+ sid = str(session_id).strip()+ if not sid:+ raise ValueError("session_id is required")+ if self._mapping.get(key) != sid:+ self._mapping[key] = sid+ self._save()diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex cce29edcf8..5aad2254aa 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -1478,6 +1478,9 @@ class AgentWebSocketServer:if request.req_method == ReqMethod.AGENT_RELOAD_CONFIG:await self._handle_agent_reload_config(ws, request, send_lock)return+ if request.req_method == ReqMethod.AGENT_PREWARM_SYNC:+ await self._handle_agent_prewarm_sync(ws, request, send_lock)+ returnif request.req_method == ReqMethod.EXTENSIONS_LIST:await self._handle_extensions_list(ws, request, send_lock)return@@ -2085,6 +2088,7 @@ class AgentWebSocketServer:request.metadata = dict(request.metadata or {})request.metadata["project_dir"] = project_dir+ await self._agent_manager.wait_for_session_prewarm(request.session_id)agent = await self._agent_manager.get_agent(channel_id=channel_id,mode=agent_mode,@@ -4543,7 +4547,10 @@ class AgentWebSocketServer:request_id=request.request_id,channel_id=request.channel_id,ok=False,- payload={"error": str(e)},+ payload={+ "error": str(e),+ "code": "BAD_REQUEST" if isinstance(e, ValueError) else "SESSION_CREATE_FAILED",+ },)wire = encode_agent_response_for_wire(resp, response_id=request.request_id)async with send_lock:@@ -6969,6 +6976,35 @@ class AgentWebSocketServer:async with send_lock:await send_wire_payload(ws, wire)+ async def _handle_agent_prewarm_sync(+ self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock+ ) -> None:+ """Reconcile background prewarming for the Gateway's live channels."""+ params = request.params if isinstance(request.params, dict) else {}+ raw_channels = params.get("enabled_channels")+ if not isinstance(raw_channels, list):+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={"error": "enabled_channels must be a list", "code": "BAD_REQUEST"},+ )+ else:+ stats = await self._agent_manager.sync_prewarm_channels(+ [str(channel) for channel in raw_channels],+ config=params.get("config"),+ env=params.get("env"),+ )+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload=stats,+ )+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)+ async with send_lock:+ await send_wire_payload(ws, wire)+async def _handle_agent_reload_config(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:try:params = request.params or {}@@ -7380,10 +7416,10 @@ class AgentWebSocketServer:mode, _, canonical_mode = resolve_agent_request_mode(params.get("mode", "agent"))explicit_session_id = params.get("session_id")previous_session_id = str(params.get("previous_session_id") or "").strip()- session_id = await self._agent_manager.create_session(- channel_id=channel_id,- session_id=str(explicit_session_id).strip() if isinstance(explicit_session_id, str) else None,- )+ if isinstance(explicit_session_id, str) and explicit_session_id.strip():+ raise ValueError(+ "session.create no longer accepts session_id; use session.switch to restore"+ )# Step 1: 归一化 work_mode / project_id / project_dir 三元组# (与 web _session_create 共用同一 helper,保持主路径/fallback 一致)from jiuwenswarm.server.runtime.session.work_mode import resolve_session_work_mode_params@@ -7482,9 +7518,54 @@ class AgentWebSocketServer:params["project_dir"] = project_dirparams["work_mode"] = final_work_mode+ is_swarm = bool(params.get("is_swarm")) or canonical_mode in {+ "team",+ "team.plan",+ "code.team",+ }+ prewarm_eligible = (+ not is_swarm+ and canonical_mode in {"agent", "code", "code.normal"}+ )+ create_token = str(params.get("create_token") or "").strip()+ if not create_token:+ raise ValueError("create_token is required")+ claim = await self._agent_manager.claim_prewarmed_session(+ channel_id=channel_id,+ project_id=project_id,+ project_dir=project_dir,+ work_mode=final_work_mode,+ is_swarm=is_swarm,+ prewarm_eligible=prewarm_eligible,+ create_token=create_token,+ )+ session_id = claim.session_id+# 会话目录已存在则拒绝,避免覆盖既有会话元数据(与 web 本地 handler 一致)session_dir = get_agent_sessions_dir() / session_id- if session_dir.exists():+ if (session_dir / "metadata.json").is_file():+ self._agent_manager.activate_session_prewarm(session_id)+ if create_token:+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload={+ "sessionId": session_id,+ "session_id": session_id,+ "projectId": project_id,+ "projectDir": project_dir,+ "workMode": final_work_mode,+ "prewarm_hit": claim.prewarm_hit,+ "prewarm_status": claim.prewarm_status,+ },+ )+ wire = encode_agent_response_for_wire(+ resp, response_id=request.request_id+ )+ async with send_lock:+ await send_wire_payload(ws, wire)+ returnresp = AgentResponse(request_id=request.request_id,channel_id=request.channel_id,@@ -7507,7 +7588,9 @@ class AgentWebSocketServer:project_dir=project_dir,project_id=project_id,work_mode=final_work_mode,+ cron_id=str(params.get("cron_id") or "").strip(),)+ self._agent_manager.activate_session_prewarm(session_id)# team prepare 必须在 ack 前完成,避免首条 chat.send 与分布式切换竞态;# 可选 KVC 信号放到回包后异步,避免拖慢 create RPC。@@ -7537,6 +7620,8 @@ class AgentWebSocketServer:"projectId": project_id,"projectDir": project_dir,"workMode": final_work_mode,+ "prewarm_hit": claim.prewarm_hit,+ "prewarm_status": claim.prewarm_status,},)wire = encode_agent_response_for_wire(resp, response_id=request.request_id)@@ -7564,6 +7649,9 @@ class AgentWebSocketServer:except Exception as e:logger.exception("[AgentServer] session.create failed: %s", e)+ await self._agent_manager.release_session_prewarm_claim(+ locals().get("session_id")+ )resp = AgentResponse(request_id=request.request_id,channel_id=request.channel_id,@@ -7604,7 +7692,7 @@ class AgentWebSocketServer:if not source:raise ValueError("source_session_id is required")if not target:- raise ValueError("target_session_id is required")+ target = await self._agent_manager.create_session(channel_id=channel_id)# 1. Filesystem fork (copies history.json, writes metadata)result = fork_session(diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex e202b91d2f..b712c8b23f 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -980,6 +980,26 @@ class JiuWenSwarm:asyncio.create_task(adapter.try_start_dreaming(busy_checker=lambda: sm.has_active_tasks(),))+ async def prepare_session(+ self,+ *,+ session_id: str,+ channel_id: str,+ mode: str,+ project_dir: str | None = None,+ ) -> None:+ """Initialize and start the session-owned DeepAgent without sending input."""+ adapter = self._ensure_adapter(mode="code" if mode.startswith("code") else "agent")+ prepare = getattr(adapter, "prepare_session", None)+ if not callable(prepare):+ raise RuntimeError("active adapter does not support session prewarming")+ await prepare(+ session_id=session_id,+ channel_id=channel_id,+ mode=mode,+ project_dir=project_dir,+ )+def build_inputs(self, request: AgentRequest) -> Tuple[dict[str, Any], str, str]:"""构建 adapter 所需的 inputs 字典(公共接口)."""return self._build_inputs(request)diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 44931b8807..c41edea0e0 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -5367,8 +5367,40 @@ class JiuWenSwarmDeepAdapter:project_dir: str | None = Nonesupports_user_interaction: bool = True+ async def configure_session_runtime(+ self,+ *,+ session_id: str,+ channel_id: str,+ mode: str,+ project_dir: str | None = None,+ ) -> None:+ """Apply session-stable runtime state without request-bound capabilities."""+ await self._apply_runtime_config(+ self._RuntimeConfig(+ session_id=session_id,+ mode=mode,+ request_id=None,+ channel_id=channel_id,+ request_metadata=None,+ project_dir=project_dir,+ cwd=project_dir,+ workspace=project_dir,+ supports_user_interaction=True,+ ),+ bind_request=False,+ )+async def _update_runtime_config(self, runtime_config: "_RuntimeConfig") -> None:- """Register per-request tools for current agent execution."""+ """Bind request-scoped runtime state immediately before real input."""+ await self._apply_runtime_config(runtime_config, bind_request=True)++ async def _apply_runtime_config(+ self,+ runtime_config: "_RuntimeConfig",+ *,+ bind_request: bool,+ ) -> None:if self._instance is None:raise RuntimeError("JiuWenSwarmDeepAdapter 未初始化,请先调用 create_instance()")@@ -5392,7 +5424,9 @@ class JiuWenSwarmDeepAdapter:if self._runtime_prompt_rail:self._runtime_prompt_rail.set_language(resolved_language)self._runtime_prompt_rail.set_channel(resolved_channel)- self._runtime_prompt_rail.set_trusted_dirs(runtime_config.trusted_dirs)+ self._runtime_prompt_rail.set_trusted_dirs(+ runtime_config.trusted_dirs if bind_request else None+ )self._runtime_prompt_rail.set_runtime_paths(cwd=task_cwd,project_dir=runtime_config.project_dir or self._project_dir,@@ -5406,7 +5440,7 @@ class JiuWenSwarmDeepAdapter:# 检查将这些子树视为 internal 而跳过 ask/deny(与 RuntimePromptRail 对齐)。# 用 getattr 兼容绕过 __init__ 的测试构造(_permission_rail 仅在 rail 构建流程赋值)。permission_rail = getattr(self, "_permission_rail", None)- if permission_rail is not None:+ if permission_rail is not None and bind_request:try:permission_rail.set_trusted_dirs(runtime_config.trusted_dirs)except Exception:@@ -5438,18 +5472,19 @@ class JiuWenSwarmDeepAdapter:runtime_config.request_id,channel_id=runtime_config.channel_id,)- self._refresh_acp_runtime_tools(- runtime_config.session_id,- runtime_config.request_id,- runtime_config.channel_id,- runtime_config.request_metadata,- )+ if bind_request:+ self._refresh_acp_runtime_tools(+ runtime_config.session_id,+ runtime_config.request_id,+ runtime_config.channel_id,+ runtime_config.request_metadata,+ )self._update_prompt_for_mode(runtime_config.mode, resolved_language)# 处理两种场景的记忆工具移除:# 1. 群聊数字分身模式(group_digital_avatar=True + avatar_mode=True):移除写入工具,但保留读取工具# 2. 记忆完全禁用(enable_memory=False + group_digital_avatar=True + avatar_mode=True):移除所有记忆工具(读取和写入)- perm_ctx = TOOL_PERMISSION_CONTEXT.get()+ perm_ctx = TOOL_PERMISSION_CONTEXT.get() if bind_request else Noneif perm_ctx is not None:# 判断是否为群聊数字分身模式is_group_digital_avatar = perm_ctx.group_digital_avatar and perm_ctx.avatar_mode@@ -5516,31 +5551,43 @@ class JiuWenSwarmDeepAdapter:async def start_interaction(self, session_id: str) -> None:"""Bind a product Session and start this adapter's DeepAgent interaction loop.- Public entry for the facade/session-pool path. No-op when- ``create_instance`` has not produced an underlying agent yet. Failures- are logged and swallowed — same contract as the former inline start.+ Public entry for the facade/session-pool path. A missing instance or+ failed readiness check propagates so the warm pool cannot publish a+ partially initialized slot."""if self._instance is None:- return- try:- from openjiuwen.core.session.agent import create_agent_session+ raise RuntimeError("DeepAgent instance is not initialized")+ from openjiuwen.core.session.agent import create_agent_session- session = create_agent_session(- session_id=session_id,- card=getattr(self._instance, "card", None),- )- await session.pre_run(inputs={})- await self._instance.start(session=session)- logger.info(- "[JiuWenSwarmDeepAdapter] start completed: session_id=%s",- session_id,- )- except Exception as exc:- logger.warning(- "[JiuWenSwarmDeepAdapter] start failed: session_id=%s error=%s",- session_id,- exc,- )+ session = create_agent_session(+ session_id=session_id,+ card=getattr(self._instance, "card", None),+ )+ await session.pre_run(inputs={})+ await self._instance.start(session=session)+ if getattr(self._instance, "_interaction_started", True) is not True:+ raise RuntimeError(f"DeepAgent interaction did not become ready: {session_id}")+ logger.info(+ "[JiuWenSwarmDeepAdapter] start completed: session_id=%s",+ session_id,+ )++ async def prepare_session(+ self,+ *,+ session_id: str,+ channel_id: str,+ mode: str,+ project_dir: str | None = None,+ ) -> None:+ """Create a session child and apply stable runtime state without input."""+ adapter = await self._get_or_create_session_adapter(session_id)+ await adapter.configure_session_runtime(+ session_id=session_id,+ channel_id=channel_id,+ mode=mode,+ project_dir=project_dir,+ )async def stop_interaction(self) -> None:"""Stop this adapter's DeepAgent interaction loop if it was started."""diff --git a/jiuwenswarm/server/runtime/agent_manager.py b/jiuwenswarm/server/runtime/agent_manager.pyindex a787d2d32b..52247a80ff 100644--- a/jiuwenswarm/server/runtime/agent_manager.py+++ b/jiuwenswarm/server/runtime/agent_manager.py@@ -8,6 +8,7 @@ import asyncioimport jsonimport loggingimport os+import timeimport uuidfrom typing import Any, TYPE_CHECKINGfrom weakref import WeakValueDictionary@@ -91,6 +92,7 @@ class AgentManager:# reload 串行锁: 防止并发 reload 叠加导致内存爆炸self._reload_lock: asyncio.Lock = asyncio.Lock()self._last_reload_fingerprint: str | None = None+ self._latest_effective_config: dict[str, Any] | None = None# A cached root may be returned before its first session processor or# child adapter exists. Track the request task that borrowed it so# disconnect cleanup cannot tear it down in that gap.@@ -104,6 +106,11 @@ class AgentManager:# 上一次默认模型的连接身份快照 (diff_key -> ModelClientConfig), 用于# 模型热更新后关闭"已被删除/改掉凭证"的 LLM 连接 (增量关闭)。self._last_model_conn_configs: dict[tuple, Any] = {}+ self._session_create_tokens: dict[tuple[str, str], tuple[Any, Any]] = {}+ self._session_create_token_lock = asyncio.Lock()+ from jiuwenswarm.server.runtime.agent_warm_pool import AgentWarmPool++ self.warm_pool = AgentWarmPool(self)def _get_agent_create_lock(self,@@ -575,11 +582,91 @@ class AgentManager:logger.info("[AgentManager] session ensured: channel_id=%s session_id=%s", channel_id, explicit_session_id)return explicit_session_idchannel_key = _normalize_channel_id(channel_id)- if channel_key == "acp":- session_id = f"acp_{uuid.uuid4().hex[:8]}"- logger.info("[AgentManager] ACP session created: session_id=%s", session_id)- return session_id- return "default"+ session_id = (+ f"{channel_key}_{int(time.time() * 1000):x}_"+ f"{uuid.uuid4().hex[:12]}"+ )+ logger.info(+ "[AgentManager] session id allocated: channel_id=%s session_id=%s",+ channel_key,+ session_id,+ )+ return session_id++ async def sync_prewarm_channels(+ self,+ enabled_channels: list[str],+ *,+ config: Any | None = None,+ env: Any = None,+ ) -> dict[str, int]:+ return await self.warm_pool.sync(+ enabled_channels,+ config=(+ config+ if config is not None+ else self._latest_effective_config or get_config()+ ),+ env=env if env is not None else self._latest_env_overrides,+ )++ async def claim_prewarmed_session(+ self,+ *,+ channel_id: str,+ project_id: str,+ project_dir: str | None,+ work_mode: str,+ is_swarm: bool,+ prewarm_eligible: bool = True,+ create_token: str | None = None,+ ):+ token = str(create_token or "").strip()+ key = self.warm_pool.make_key(+ channel_id=channel_id,+ project_id=project_id,+ project_dir=project_dir,+ work_mode=work_mode,+ is_swarm=is_swarm,+ )+ create_signature = (key, bool(prewarm_eligible))+ token_key = (key.channel_id, token)+ async with self._session_create_token_lock:+ if token:+ existing = self._session_create_tokens.get(token_key)+ if existing is not None:+ existing_key, claim = existing+ if existing_key != create_signature:+ raise ValueError(+ "create_token was already used with different session parameters"+ )+ return claim+ if prewarm_eligible and not is_swarm:+ claim = await self.warm_pool.claim(key)+ else:+ from jiuwenswarm.server.runtime.agent_warm_pool import WarmClaim++ claim = WarmClaim(+ await self.create_session(channel_id=channel_id),+ False,+ "bypassed",+ )+ if token:+ self._session_create_tokens[token_key] = (create_signature, claim)+ return claim++ async def wait_for_session_prewarm(self, session_id: str | None) -> None:+ if session_id:+ await self.warm_pool.wait_for_session(session_id)++ def activate_session_prewarm(self, session_id: str | None) -> None:+ """Mark a claimed prewarm workspace as a normal persisted session."""+ if session_id:+ self.warm_pool.clear_marker(session_id)++ async def release_session_prewarm_claim(self, session_id: str | None) -> None:+ if session_id:+ await self.warm_pool.release_claim_pin(session_id)async def get_agent(self,@@ -870,6 +957,15 @@ class AgentManager:logger.info(f"channel {channel_id} reload agent config success.")if reload_completed:self._last_reload_fingerprint = fingerprint+ if isinstance(effective_config, dict):+ self._latest_effective_config = dict(effective_config)+ asyncio.create_task(+ self.warm_pool.refresh(+ config=effective_config,+ env=self._latest_env_overrides,+ ),+ name="agent-prewarm-config-refresh",+ )# 模型配置变更时, 关闭已被删除/改掉凭证的旧 LLM 连接 (增量关闭)。if model_scope:await self._evict_stale_llm_clients(effective_config)@@ -1020,6 +1116,7 @@ class AgentManager:AgentResponse 对象"""try:+ await self.wait_for_session_prewarm(getattr(request, "session_id", None))channel_id = getattr(request, "channel_id", "")params = getattr(request, "params", {}) if isinstance(getattr(request, "params", {}), dict) else {}mode_full = params.get("mode", "agent")@@ -1049,6 +1146,7 @@ class AgentManager:AgentResponseChunk 对象"""try:+ await self.wait_for_session_prewarm(getattr(request, "session_id", None))channel_id = getattr(request, "channel_id", "")params = getattr(request, "params", {}) if isinstance(getattr(request, "params", {}), dict) else {}mode_full = params.get("mode", "agent")@@ -1072,6 +1170,7 @@ class AgentManager:async def cleanup(self) -> None:"""清理所有 agent 实例."""+ await self.warm_pool.close()retirement_tasks = [taskfor task in self._retirement_tasks.values()@@ -1089,6 +1188,7 @@ class AgentManager:del self.agents[key]self._agent_create_params.clear()self._client_capabilities_by_channel.clear()+ self._session_create_tokens.clear()self._agent_borrowers.clear()self._agent_pins.clear()self._pending_tui_retirements.clear()diff --git a/jiuwenswarm/server/runtime/agent_warm_pool.py b/jiuwenswarm/server/runtime/agent_warm_pool.pynew file mode 100644index 0000000000..8cc17041e2--- /dev/null+++ b/jiuwenswarm/server/runtime/agent_warm_pool.py@@ -0,0 +1,499 @@+"""Process-local pool of session-bound, ready-to-run DeepAgent instances."""++from __future__ import annotations++import asyncio+import hashlib+import json+import logging+import os+import secrets+import shutil+import time+import uuid+from dataclasses import dataclass+from pathlib import Path+from typing import Any, TYPE_CHECKING++from jiuwenswarm.common.utils import get_agent_sessions_dir+from jiuwenswarm.common.work_mode import (+ DEFAULT_PROJECT_ID_CODE,+ DEFAULT_PROJECT_ID_WORK,+)+from jiuwenswarm.server.runtime.session import project_store++if TYPE_CHECKING:+ from jiuwenswarm.server.runtime.agent_manager import AgentManager+ from jiuwenswarm.server.runtime.agent_adapter.interface import JiuWenSwarm+++logger = logging.getLogger(__name__)+++def _normalize_project_dir(value: str | None) -> str:+ raw = str(value or "").strip()+ if not raw:+ return ""+ return os.path.normcase(os.path.abspath(os.path.expanduser(raw)))+++@dataclass(frozen=True, slots=True)+class WarmKey:+ channel_id: str+ project_id: str+ project_dir: str+ work_mode: str+ is_swarm: bool = False++ @property+ def agent_mode(self) -> str:+ return "code" if self.work_mode == "code" else "agent"+++@dataclass(frozen=True, slots=True)+class WarmRevision:+ boot_id: str+ config_fingerprint: str+ sequence: int+++@dataclass(slots=True)+class WarmSlot:+ key: WarmKey+ session_id: str+ revision: WarmRevision+ agent: "JiuWenSwarm"+ ready_at: float+++@dataclass(frozen=True, slots=True)+class WarmClaim:+ session_id: str+ prewarm_hit: bool+ prewarm_status: str+++class AgentWarmPool:+ """Own one unclaimed, initialized session per enabled channel/project key."""++ def __init__(self, manager: "AgentManager", *, max_concurrency: int = 2) -> None:+ self._manager = manager+ self._boot_id = uuid.uuid4().hex+ self._sequence = 0+ self._revision = WarmRevision(self._boot_id, "", 0)+ self._enabled_channels: set[str] = set()+ self._slots: dict[WarmKey, WarmSlot] = {}+ self._tasks: dict[WarmKey, asyncio.Task[None]] = {}+ self._task_revisions: dict[WarmKey, WarmRevision] = {}+ self._session_tasks: dict[str, asyncio.Task[None]] = {}+ self._claimed_pins: dict[str, "JiuWenSwarm"] = {}+ self._pin_release_tasks: set[asyncio.Task[None]] = set()+ self._failed: dict[WarmKey, str] = {}+ self._lock = asyncio.Lock()+ self._semaphore = asyncio.Semaphore(max(1, int(max_concurrency)))+ self._closed = False+ self._marker_dir = get_agent_sessions_dir() / ".prewarm"+ self._cleanup_stale_markers()++ @property+ def boot_id(self) -> str:+ return self._boot_id++ @staticmethod+ def make_key(+ *,+ channel_id: str,+ project_id: str,+ project_dir: str | None,+ work_mode: str,+ is_swarm: bool = False,+ ) -> WarmKey:+ return WarmKey(+ channel_id=str(channel_id or "default").strip() or "default",+ project_id=str(project_id or "").strip(),+ project_dir=_normalize_project_dir(project_dir),+ work_mode="code" if str(work_mode).strip().lower() == "code" else "work",+ is_swarm=bool(is_swarm),+ )++ @staticmethod+ def config_fingerprint(config: Any, env: Any = None) -> str:+ payload = json.dumps(+ {"config": config, "env": env if isinstance(env, dict) else {}},+ sort_keys=True,+ ensure_ascii=False,+ default=repr,+ separators=(",", ":"),+ ).encode("utf-8")+ return hashlib.sha256(payload).hexdigest()++ def _next_revision(self, config: Any, env: Any = None) -> WarmRevision:+ self._sequence += 1+ return WarmRevision(+ self._boot_id,+ self.config_fingerprint(config, env),+ self._sequence,+ )++ @staticmethod+ def _new_session_id(channel_id: str) -> str:+ prefix = str(channel_id or "default").strip() or "default"+ return f"{prefix}_{int(time.time() * 1000):x}_{secrets.token_hex(6)}"++ def _marker_path(self, session_id: str) -> Path:+ return self._marker_dir / f"{session_id}.json"++ def _write_marker(self, session_id: str, key: WarmKey) -> None:+ self._marker_dir.mkdir(parents=True, exist_ok=True)+ payload = {+ "boot_id": self._boot_id,+ "session_id": session_id,+ "key": {+ "channel_id": key.channel_id,+ "project_id": key.project_id,+ "project_dir": key.project_dir,+ "work_mode": key.work_mode,+ "is_swarm": key.is_swarm,+ },+ }+ self._marker_path(session_id).write_text(+ json.dumps(payload, ensure_ascii=False), encoding="utf-8"+ )++ def clear_marker(self, session_id: str) -> None:+ try:+ self._marker_path(session_id).unlink(missing_ok=True)+ except OSError:+ logger.warning("Failed to remove prewarm marker: session_id=%s", session_id)++ def _cleanup_stale_markers(self) -> None:+ if not self._marker_dir.exists():+ return+ for marker in self._marker_dir.glob("*.json"):+ try:+ payload = json.loads(marker.read_text(encoding="utf-8"))+ if payload.get("boot_id") != self._boot_id:+ session_id = str(payload.get("session_id") or "").strip()+ session_dir = (get_agent_sessions_dir() / session_id).resolve()+ sessions_root = get_agent_sessions_dir().resolve()+ has_valid_path = (+ bool(session_id) and session_dir.parent == sessions_root+ )+ is_uninitialized = session_dir.is_dir() and not (+ session_dir / "metadata.json"+ ).exists()+ if has_valid_path and is_uninitialized:+ shutil.rmtree(session_dir)+ marker.unlink(missing_ok=True)+ except (OSError, ValueError, TypeError):+ logger.warning("Invalid prewarm marker left in place: %s", marker)++ def _desired_keys(self) -> set[WarmKey]:+ projects = list(project_store.list_projects(cache_bust=True))+ records = [+ (p.project_id, p.project_dir, p.work_mode)+ for p in projects+ if not p.hidden+ ]+ records.extend(+ [+ (DEFAULT_PROJECT_ID_WORK, "", "work"),+ (DEFAULT_PROJECT_ID_CODE, "", "code"),+ ]+ )+ return {+ self.make_key(+ channel_id=channel,+ project_id=project_id,+ project_dir=project_dir,+ work_mode=work_mode,+ )+ for channel in self._enabled_channels+ for project_id, project_dir, work_mode in records+ }++ async def sync(+ self,+ enabled_channels: list[str],+ *,+ config: Any,+ env: Any = None,+ ) -> dict[str, int]:+ channels = {+ str(channel).strip()+ for channel in enabled_channels+ if str(channel).strip()+ }+ revision = self._next_revision(config, env)+ async with self._lock:+ if self._closed:+ return {+ "target": 0,+ "ready": 0,+ "warming": 0,+ "failed": 0,+ "stale": 0,+ }+ config_changed = (+ self._revision.config_fingerprint != revision.config_fingerprint+ )+ self._enabled_channels = channels+ self._revision = revision+ desired = self._desired_keys()+ if config_changed:+ self._failed.clear()+ else:+ self._failed = {+ key: error+ for key, error in self._failed.items()+ if key in desired+ }+ stale_slots = [+ slot+ for key, slot in list(self._slots.items())+ if key not in desired or slot.revision.config_fingerprint != revision.config_fingerprint+ ]+ for slot in stale_slots:+ self._slots.pop(slot.key, None)+ for key, task in list(self._tasks.items()):+ task_revision = self._task_revisions.get(key)+ if (+ key not in desired+ or task_revision is None+ or task_revision.config_fingerprint != revision.config_fingerprint+ ):+ if not task.done():+ task.cancel()+ self._tasks.pop(key, None)+ self._task_revisions.pop(key, None)+ for key in desired:+ slot = self._slots.get(key)+ if slot is None and key not in self._tasks:+ self._schedule_prepare_locked(key, revision)+ for slot in stale_slots:+ asyncio.create_task(self._dispose_slot(slot))+ return await self.stats()++ async def refresh(self, *, config: Any, env: Any = None) -> dict[str, int]:+ return await self.sync(+ sorted(self._enabled_channels),+ config=config,+ env=env,+ )++ def _schedule_prepare_locked(+ self,+ key: WarmKey,+ revision: WarmRevision,+ *,+ session_id: str | None = None,+ keep_as_slot: bool = True,+ ) -> tuple[str, asyncio.Task[None]]:+ sid = session_id or self._new_session_id(key.channel_id)+ task = asyncio.create_task(+ self._prepare(key, sid, revision, keep_as_slot=keep_as_slot),+ name=f"agent-prewarm-{sid}",+ )+ if keep_as_slot:+ self._tasks[key] = task+ self._task_revisions[key] = revision+ self._session_tasks[sid] = task+ return sid, task++ async def _prepare(+ self,+ key: WarmKey,+ session_id: str,+ revision: WarmRevision,+ *,+ keep_as_slot: bool,+ ) -> None:+ agent: "JiuWenSwarm | None" = None+ pinned = False+ published = False+ if keep_as_slot:+ self._write_marker(session_id, key)+ try:+ async with self._semaphore:+ agent = await self._manager.get_agent(+ channel_id=key.channel_id,+ mode=key.agent_mode,+ project_dir=key.project_dir or None,+ )+ if agent is None:+ raise RuntimeError("agent creation returned None")+ await agent.prepare_session(+ session_id=session_id,+ channel_id=key.channel_id,+ mode="code.normal" if key.work_mode == "code" else "agent",+ project_dir=key.project_dir or None,+ )+ if not keep_as_slot:+ return+ self._manager.pin_agent(agent)+ pinned = True+ async with self._lock:+ current = self._revision+ revision_changed = (+ current.boot_id != revision.boot_id+ or current.config_fingerprint != revision.config_fingerprint+ )+ stale = (+ self._closed+ or revision_changed+ or key not in self._desired_keys()+ )+ if not stale:+ self._slots[key] = WarmSlot(+ key=key,+ session_id=session_id,+ revision=revision,+ agent=agent,+ ready_at=time.time(),+ )+ published = True+ self._failed.pop(key, None)+ if stale:+ await self._dispose_runtime(+ agent, key.channel_id, session_id, pinned=True+ )+ pinned = False+ except asyncio.CancelledError:+ if agent is not None:+ await self._dispose_runtime(+ agent, key.channel_id, session_id, pinned=pinned+ )+ raise+ except Exception as exc:+ logger.exception("Agent prewarm failed: key=%s session_id=%s", key, session_id)+ if agent is not None:+ await self._dispose_runtime(+ agent, key.channel_id, session_id, pinned=pinned+ )+ async with self._lock:+ self._failed[key] = str(exc)+ finally:+ if keep_as_slot and not published:+ self.clear_marker(session_id)+ async with self._lock:+ current_task = asyncio.current_task()+ if self._tasks.get(key) is current_task:+ self._tasks.pop(key, None)+ self._task_revisions.pop(key, None)+ if self._session_tasks.get(session_id) is current_task:+ self._session_tasks.pop(session_id, None)++ async def claim(self, key: WarmKey) -> WarmClaim:+ if key.is_swarm:+ return WarmClaim(self._new_session_id(key.channel_id), False, "bypassed")+ async with self._lock:+ if self._closed:+ raise RuntimeError("agent warm pool is closed")+ is_desired = key in self._desired_keys()+ slot = self._slots.pop(key, None)+ if slot is not None:+ self._claimed_pins[slot.session_id] = slot.agent+ pin_task = asyncio.create_task(+ self._release_claim_pin_after(slot.session_id, 300),+ name=f"agent-prewarm-claim-pin-timeout-{slot.session_id}",+ )+ self._pin_release_tasks.add(pin_task)+ pin_task.add_done_callback(self._pin_release_tasks.discard)+ if key not in self._tasks:+ self._schedule_prepare_locked(key, self._revision)+ return WarmClaim(slot.session_id, True, "ready")+ if key in self._tasks:+ # Keep the target slot intact and initialize this claimed session+ # independently; its per-session adapter lock deduplicates chat.send.+ sid, _ = self._schedule_prepare_locked(+ key, self._revision, keep_as_slot=False+ )+ else:+ sid, _ = self._schedule_prepare_locked(+ key, self._revision, keep_as_slot=False+ )+ if is_desired:+ self._schedule_prepare_locked(key, self._revision)+ return WarmClaim(sid, False, "warming")++ async def wait_for_session(self, session_id: str) -> None:+ async with self._lock:+ task = self._session_tasks.get(str(session_id))+ try:+ if task is not None:+ await asyncio.shield(task)+ finally:+ async with self._lock:+ pinned_agent = self._claimed_pins.pop(str(session_id), None)+ if pinned_agent is not None:+ self._manager.unpin_agent(pinned_agent)++ async def release_claim_pin(self, session_id: str) -> None:+ async with self._lock:+ pinned_agent = self._claimed_pins.pop(str(session_id), None)+ if pinned_agent is not None:+ self._manager.unpin_agent(pinned_agent)++ async def _release_claim_pin_after(+ self, session_id: str, delay_seconds: float+ ) -> None:+ await asyncio.sleep(delay_seconds)+ await self.release_claim_pin(session_id)++ async def _dispose_runtime(+ self,+ agent: "JiuWenSwarm",+ channel_id: str,+ session_id: str,+ *,+ pinned: bool,+ ) -> None:+ try:+ await agent.cleanup_session_runtime(session_id)+ finally:+ if pinned:+ self._manager.unpin_agent(agent)+ self.clear_marker(session_id)++ async def _dispose_slot(self, slot: WarmSlot) -> None:+ await self._dispose_runtime(+ slot.agent, slot.key.channel_id, slot.session_id, pinned=True+ )++ async def stats(self) -> dict[str, int]:+ async with self._lock:+ desired = self._desired_keys()+ return {+ "target": len(desired),+ "ready": len(self._slots),+ "warming": len(self._tasks),+ "failed": len(self._failed),+ "stale": max(0, len(self._slots) - len(desired)),+ }++ async def close(self) -> None:+ async with self._lock:+ self._closed = True+ tasks = list(+ {+ *self._tasks.values(),+ *self._session_tasks.values(),+ *self._pin_release_tasks,+ }+ )+ slots = list(self._slots.values())+ claimed_agents = list(self._claimed_pins.values())+ self._tasks.clear()+ self._task_revisions.clear()+ self._session_tasks.clear()+ self._slots.clear()+ self._claimed_pins.clear()+ self._pin_release_tasks.clear()+ for task in tasks:+ task.cancel()+ if tasks:+ await asyncio.gather(*tasks, return_exceptions=True)+ for slot in slots:+ await self._dispose_slot(slot)+ for agent in claimed_agents:+ self._manager.unpin_agent(agent)diff --git a/tests/unit_tests/agentserver/test_agent_warm_pool.py b/tests/unit_tests/agentserver/test_agent_warm_pool.pynew file mode 100644index 0000000000..0fc21a9597--- /dev/null+++ b/tests/unit_tests/agentserver/test_agent_warm_pool.py@@ -0,0 +1,173 @@+from __future__ import annotations++import asyncio+from pathlib import Path++import pytest++from jiuwenswarm.server.runtime.agent_warm_pool import AgentWarmPool+++class _FakeRootAgent:+ def __init__(self, *, fail: bool = False) -> None:+ self.fail = fail+ self.prepared: list[str] = []+ self.cleaned: list[str] = []++ async def prepare_session(self, *, session_id: str, **_kwargs) -> None:+ await asyncio.sleep(0)+ if self.fail:+ raise RuntimeError("prepare failed")+ self.prepared.append(session_id)++ async def cleanup_session_runtime(self, session_id: str) -> bool:+ self.cleaned.append(session_id)+ return True+++class _FakeManager:+ def __init__(self, agent: _FakeRootAgent) -> None:+ self.agent = agent+ self.pins = 0++ async def get_agent(self, **_kwargs):+ return self.agent++ def pin_agent(self, _agent) -> None:+ self.pins += 1++ def unpin_agent(self, _agent) -> None:+ self.pins -= 1+++async def _wait_until(predicate, *, attempts: int = 100) -> None:+ for _ in range(attempts):+ if predicate():+ return+ await asyncio.sleep(0.01)+ raise AssertionError("condition did not become true")+++def isolated_pool(monkeypatch, tmp_path: Path):+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.agent_warm_pool.get_agent_sessions_dir",+ lambda: tmp_path,+ )+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.agent_warm_pool.project_store.list_projects",+ lambda **_kwargs: [],+ )++ def factory(agent: _FakeRootAgent) -> AgentWarmPool:+ return AgentWarmPool(_FakeManager(agent), max_concurrency=4)++ yield factory+++def test_warm_key_normalizes_project_directory(tmp_path: Path) -> None:+ key = AgentWarmPool.make_key(+ channel_id=" web ",+ project_id="project-a",+ project_dir=str(tmp_path / ".." / tmp_path.name),+ work_mode="CODE",+ )+ assert key.channel_id == "web"+ assert key.project_dir == str(tmp_path.resolve()).lower()+ assert key.agent_mode == "code"+++async def test_one_ready_slot_per_key_and_atomic_claim(isolated_pool) -> None:+ agent = _FakeRootAgent()+ pool = isolated_pool(agent)+ stats = await pool.sync(["web"], config={"model": "a"})+ assert stats["target"] == 2+ await _wait_until(lambda: len(pool._slots) == 2)++ work_key = pool.make_key(+ channel_id="web",+ project_id="default",+ project_dir="",+ work_mode="work",+ )+ claims = await asyncio.gather(pool.claim(work_key), pool.claim(work_key))+ assert len({claim.session_id for claim in claims}) == 2+ assert sum(claim.prewarm_hit for claim in claims) == 1+ assert {claim.prewarm_status for claim in claims} == {"ready", "warming"}+ await _wait_until(lambda: work_key in pool._slots)+ assert len([key for key in pool._slots if key == work_key]) == 1+ await pool.close()+++async def test_config_revision_replaces_unclaimed_slots(isolated_pool) -> None:+ agent = _FakeRootAgent()+ pool = isolated_pool(agent)+ await pool.sync(["web"], config={"model": "old"})+ await _wait_until(lambda: len(pool._slots) == 2)+ old_ids = {slot.session_id for slot in pool._slots.values()}++ await pool.sync(["web"], config={"model": "new"})+ await _wait_until(+ lambda: len(pool._slots) == 2+ and not old_ids.intersection(slot.session_id for slot in pool._slots.values())+ )+ assert old_ids.issubset(set(agent.cleaned))+ await pool.close()+++async def test_failed_prepare_never_becomes_ready(isolated_pool) -> None:+ pool = isolated_pool(_FakeRootAgent(fail=True))+ await pool.sync(["web"], config={"model": "broken"})+ await _wait_until(lambda: not pool._tasks)+ stats = await pool.stats()+ assert stats["ready"] == 0+ assert stats["failed"] == 2+ await pool.close()+++async def test_claim_marker_survives_until_metadata_activation(isolated_pool) -> None:+ pool = isolated_pool(_FakeRootAgent())+ await pool.sync(["web"], config={"model": "ready"})+ await _wait_until(lambda: len(pool._slots) == 2)+ key = pool.make_key(+ channel_id="web",+ project_id="default",+ project_dir="",+ work_mode="work",+ )++ claim = await pool.claim(key)+ marker = pool._marker_path(claim.session_id)+ assert claim.prewarm_hit is True+ assert marker.is_file()++ pool.clear_marker(claim.session_id)+ assert not marker.exists()+ await pool.close()+++def test_new_boot_cleans_only_metadata_less_marked_workspace(+ isolated_pool, tmp_path: Path+) -> None:+ old_pool = isolated_pool(_FakeRootAgent())+ key = old_pool.make_key(+ channel_id="web",+ project_id="default",+ project_dir="",+ work_mode="work",+ )+ stale_id = "web_stale"+ persisted_id = "web_persisted"+ for session_id in (stale_id, persisted_id):+ (tmp_path / session_id).mkdir()+ old_pool._write_marker(session_id, key)+ (tmp_path / persisted_id / "metadata.json").write_text("{}", encoding="utf-8")++ isolated_pool(_FakeRootAgent())++ assert not (tmp_path / stale_id).exists()+ assert (tmp_path / persisted_id / "metadata.json").is_file()diff --git a/tests/unit_tests/agentserver/test_agentserver_acp.py b/tests/unit_tests/agentserver/test_agentserver_acp.pyindex a68411a1c7..184315836f 100644--- a/tests/unit_tests/agentserver/test_agentserver_acp.py+++ b/tests/unit_tests/agentserver/test_agentserver_acp.py@@ -35,7 +35,9 @@ class FakeAgentManager:self.session_id = session_idself.client_capabilities = client_capabilities or {}self.initialize_calls = []- self.create_session_calls = []+ self.claim_session_calls = []+ self.activated_sessions = []+ self.released_sessions = []async def initialize(self, channel_id="", extra_config=None):self.initialize_calls.append(@@ -43,9 +45,22 @@ class FakeAgentManager:)return self.capabilities- async def create_session(self, channel_id="", session_id=None):- self.create_session_calls.append({"channel_id": channel_id, "session_id": session_id})- return session_id or self.session_id+ async def claim_prewarmed_session(self, **kwargs):+ self.claim_session_calls.append(kwargs)+ eligible = bool(kwargs.get("prewarm_eligible")) and not bool(+ kwargs.get("is_swarm")+ )+ return types.SimpleNamespace(+ session_id=self.session_id,+ prewarm_hit=eligible,+ prewarm_status="ready" if eligible else "bypassed",+ )++ def activate_session_prewarm(self, session_id):+ self.activated_sessions.append(session_id)++ async def release_session_prewarm_claim(self, session_id):+ self.released_sessions.append(session_id)def get_client_capabilities(self, channel_id=""):return dict(self.client_capabilities)@@ -768,12 +783,14 @@ async def test_handle_session_create_returns_session_id(monkeypatch, tmp_path):request_id="req-session-create",channel_id="acp",req_method=ReqMethod.SESSION_CREATE,- params={},+ params={"create_token": "create-acp-001"},)await server.handle_session_create_for_test(fake_ws, request, asyncio.Lock())- assert fake_manager.create_session_calls == [{"channel_id": "acp", "session_id": None}]+ assert len(fake_manager.claim_session_calls) == 1+ assert fake_manager.claim_session_calls[0]["channel_id"] == "acp"+ assert fake_manager.claim_session_calls[0]["create_token"] == "create-acp-001"metadata = json.loads((sessions_root / "acp_session_001" / "metadata.json").read_text(encoding="utf-8"))assert metadata["mode"] == "agent"assert fake_ws.sent == [@@ -785,6 +802,8 @@ async def test_handle_session_create_returns_session_id(monkeypatch, tmp_path):"projectId": "default","projectDir": "","workMode": "work",+ "prewarm_hit": True,+ "prewarm_status": "ready",},"ok": True,}@@ -792,7 +811,7 @@ async def test_handle_session_create_returns_session_id(monkeypatch, tmp_path):@pytest.mark.asyncio-async def test_handle_session_create_returns_explicit_session_id(monkeypatch, tmp_path):+async def test_handle_session_create_rejects_explicit_session_id(monkeypatch, tmp_path):server = AgentWebSocketServerHarness()fake_manager = FakeAgentManager(session_id="unused-default")server.set_agent_manager_for_test(fake_manager)@@ -810,25 +829,25 @@ async def test_handle_session_create_returns_explicit_session_id(monkeypatch, tmrequest_id="req-session-create-explicit",channel_id="acp",req_method=ReqMethod.SESSION_CREATE,- params={"session_id": "sess_explicit_001"},+ params={+ "session_id": "sess_explicit_001",+ "create_token": "create-explicit-001",+ },)await server.handle_session_create_for_test(fake_ws, request, asyncio.Lock())- assert fake_manager.create_session_calls == [- {"channel_id": "acp", "session_id": "sess_explicit_001"}- ]+ assert fake_manager.claim_session_calls == []assert fake_ws.sent == [{"response_id": "req-session-create-explicit","payload": {- "sessionId": "sess_explicit_001",- "session_id": "sess_explicit_001",- "projectId": "default",- "projectDir": "",- "workMode": "work",+ "error": (+ "session.create no longer accepts session_id; "+ "use session.switch to restore"+ ),},- "ok": True,+ "ok": False,}]@@ -881,6 +900,7 @@ async def test_handle_session_create_injected_default_work_mode_does_not_mismatc"project_id": "proj_code","work_mode": "work","_work_mode_explicit": False,+ "create_token": "create-code-project",},)@@ -895,6 +915,8 @@ async def test_handle_session_create_injected_default_work_mode_does_not_mismatc"projectId": "proj_code","projectDir": code_project.project_dir,"workMode": "code",+ "prewarm_hit": True,+ "prewarm_status": "ready",},"ok": True,}@@ -905,7 +927,7 @@ async def test_handle_session_create_injected_default_work_mode_does_not_mismatcasync def test_handle_session_create_acks_before_async_kvc(monkeypatch, tmp_path):"""session.create 在 team prepare 后回包;可选 KVC 异步,避免拖慢前端超时窗口。"""server = AgentWebSocketServerHarness()- fake_manager = FakeAgentManager(session_id="unused-default")+ fake_manager = FakeAgentManager(session_id="sess_async_kvc_001")server.set_agent_manager_for_test(fake_manager)fake_ws = FakeWebSocket()prepare_calls = []@@ -935,7 +957,7 @@ async def test_handle_session_create_acks_before_async_kvc(monkeypatch, tmp_pathrequest_id="req-session-create-async-kvc",channel_id="web",req_method=ReqMethod.SESSION_CREATE,- params={"session_id": "sess_async_kvc_001", "mode": "agent"},+ params={"mode": "agent", "create_token": "create-async-kvc"},)create_task = asyncio.create_task(@@ -954,6 +976,8 @@ async def test_handle_session_create_acks_before_async_kvc(monkeypatch, tmp_path"projectId": "default","projectDir": "","workMode": "work",+ "prewarm_hit": True,+ "prewarm_status": "ready",},"ok": True,}@@ -970,7 +994,7 @@ async def test_handle_session_create_acks_before_async_kvc(monkeypatch, tmp_pathasync def test_handle_session_create_prepares_team_before_ack(monkeypatch, tmp_path):"""team prepare 必须在 create 成功回包前完成,避免与首条 chat.send 竞态。"""server = AgentWebSocketServerHarness()- fake_manager = FakeAgentManager(session_id="unused-default")+ fake_manager = FakeAgentManager(session_id="team_sess_001")fake_team_manager = FakeTeamManager()server.set_agent_manager_for_test(fake_manager)fake_ws = FakeWebSocket()@@ -1001,7 +1025,7 @@ async def test_handle_session_create_prepares_team_before_ack(monkeypatch, tmp_prequest_id="req-session-create-team",channel_id="web",req_method=ReqMethod.SESSION_CREATE,- params={"mode": "team", "session_id": "team_sess_001"},+ params={"mode": "team", "create_token": "create-team-001"},)create_task = asyncio.create_task(@@ -1021,13 +1045,15 @@ async def test_handle_session_create_prepares_team_before_ack(monkeypatch, tmp_p"projectId": "default","projectDir": "","workMode": "work",+ "prewarm_hit": False,+ "prewarm_status": "bypassed",},"ok": True,}]- assert fake_manager.create_session_calls == [- {"channel_id": "web", "session_id": "team_sess_001"}- ]+ assert len(fake_manager.claim_session_calls) == 1+ assert fake_manager.claim_session_calls[0]["channel_id"] == "web"+ assert fake_manager.claim_session_calls[0]["prewarm_eligible"] is Falseassert fake_team_manager.prepare_session_switch_calls == [{"session_id": "team_sess_001", "reason": "session.create switch: "}]diff --git a/tests/unit_tests/agentserver/test_plan_mode_orchestration.py b/tests/unit_tests/agentserver/test_plan_mode_orchestration.pyindex d452f20319..ceffcd5daf 100644--- a/tests/unit_tests/agentserver/test_plan_mode_orchestration.py+++ b/tests/unit_tests/agentserver/test_plan_mode_orchestration.py@@ -52,6 +52,7 @@ async def test_prepare_code_mode_chat_turn_resolves_mode_and_agent() -> None:agent = MagicMock()manager = MagicMock()manager.get_agent = AsyncMock(return_value=agent)+ manager.wait_for_session_prewarm = AsyncMock()server = AgentWebSocketServer.__new__(AgentWebSocketServer)server._agent_manager = manager@@ -67,6 +68,7 @@ async def test_prepare_code_mode_chat_turn_resolves_mode_and_agent() -> None:assert sub_mode == "plan"assert resolved_agent is agentmanager.get_agent.assert_awaited_once()+ manager.wait_for_session_prewarm.assert_awaited_once_with(session_id)@pytest.mark.asyncio@@ -80,6 +82,7 @@ async def test_prepare_team_chat_turn_propagates_locked_project_dir() -> None:agent = MagicMock()manager = MagicMock()manager.get_agent = AsyncMock(return_value=agent)+ manager.wait_for_session_prewarm = AsyncMock()server = AgentWebSocketServer.__new__(AgentWebSocketServer)server._agent_manager = manager@@ -109,6 +112,7 @@ async def test_prepare_team_chat_turn_propagates_locked_project_dir() -> None:project_dir="/tmp/locked-project",sub_mode=None,)+ manager.wait_for_session_prewarm.assert_awaited_once_with("sess_team_project")@pytest.mark.asyncio@@ -294,6 +298,7 @@ async def test_prepare_chat_turn_skips_approval_for_interrupt_resume() -> None:agent = MagicMock()manager = MagicMock()manager.get_agent = AsyncMock(return_value=agent)+ manager.wait_for_session_prewarm = AsyncMock()server = AgentWebSocketServer.__new__(AgentWebSocketServer)server._agent_manager = manager@@ -315,6 +320,7 @@ async def test_prepare_chat_turn_skips_approval_for_interrupt_resume() -> None:assert mode == "code"assert sub_mode == "plan"manager.get_agent.assert_awaited_once()+ manager.wait_for_session_prewarm.assert_awaited_once_with(session_id)@pytest.mark.asynciodiff --git a/tests/unit_tests/channel/test_web_channel_user_id.py b/tests/unit_tests/channel/test_web_channel_user_id.pyindex 35ee7a301d..2bae59ebb4 100644--- a/tests/unit_tests/channel/test_web_channel_user_id.py+++ b/tests/unit_tests/channel/test_web_channel_user_id.py@@ -1,6 +1,7 @@# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.import json+from types import SimpleNamespacefrom typing import Anyimport pytest@@ -86,6 +87,27 @@ class FakeWebChannelForHandlers:)+class FakeSessionCreateClient:+ def __init__(self, session_id: str) -> None:+ self.session_id = session_id+ self.requests: list[Any] = []++ async def send_request(self, request: Any) -> Any:+ self.requests.append(request)+ return SimpleNamespace(+ ok=True,+ payload={+ "session_id": self.session_id,+ "sessionId": self.session_id,+ "projectId": "default",+ "projectDir": "",+ "workMode": "work",+ "prewarm_hit": True,+ "prewarm_status": "ready",+ },+ )++def test_extract_query_user_id():assert WebChannel._extract_query_user_id({"user_id": "alice"}) == "alice"assert WebChannel._extract_query_user_id({"user_id": " bob "}) == "bob"@@ -302,70 +324,47 @@ async def test_openai_account_unexpected_error_uses_method_dispatcher(monkeypatc@pytest.mark.asyncioasync def test_session_create_uses_connection_user_id(tmp_path, monkeypatch):channel = FakeWebChannelForHandlers()- sessions_dir = tmp_path / "sessions"- sessions_dir.mkdir()-- monkeypatch.setattr(- "jiuwenswarm.server.runtime.session.session_metadata.get_agent_sessions_dir",- lambda: sessions_dir,- )- monkeypatch.setattr(- "jiuwenswarm.common.utils.get_agent_sessions_dir",- lambda: sessions_dir,- )- monkeypatch.setattr(- "jiuwenswarm.gateway.channel_manager.web.app_web_handlers.get_agent_sessions_dir",- lambda: sessions_dir,+ agent_client = FakeSessionCreateClient("web_allocated_1")+ _register_web_handlers(+ WebHandlersBindParams(channel=channel, agent_client=agent_client))- _register_web_handlers(WebHandlersBindParams(channel=channel))ws = FakeWebSocket(query_user_id="alice")await channel.methods["session.create"](ws,"req-create",- {"session_id": "sess_create_1", "mode": "agent"},- "sess_create_1",+ {"mode": "agent", "create_token": "web-create-1"},+ "new",user_id="alice",)assert channel.responses[-1]["ok"] is True- meta_path = sessions_dir / "sess_create_1" / "metadata.json"- assert meta_path.exists()- data = json.loads(meta_path.read_text(encoding="utf-8"))- assert data["user_id"] == "alice"+ assert channel.responses[-1]["payload"]["session_id"] == "web_allocated_1"+ assert agent_client.requests[-1].user_id == "alice"+ assert agent_client.requests[-1].params["user_id"] == "alice"@pytest.mark.asyncioasync def test_session_create_ignores_params_user_id(tmp_path, monkeypatch):channel = FakeWebChannelForHandlers()- sessions_dir = tmp_path / "sessions"- sessions_dir.mkdir()-- monkeypatch.setattr(- "jiuwenswarm.server.runtime.session.session_metadata.get_agent_sessions_dir",- lambda: sessions_dir,- )- monkeypatch.setattr(- "jiuwenswarm.common.utils.get_agent_sessions_dir",- lambda: sessions_dir,+ agent_client = FakeSessionCreateClient("web_allocated_2")+ _register_web_handlers(+ WebHandlersBindParams(channel=channel, agent_client=agent_client))- monkeypatch.setattr(- "jiuwenswarm.gateway.channel_manager.web.app_web_handlers.get_agent_sessions_dir",- lambda: sessions_dir,- )- _register_web_handlers(WebHandlersBindParams(channel=channel))ws = FakeWebSocket(query_user_id="alice")await channel.methods["session.create"](ws,"req-create",- {"session_id": "sess_create_2", "mode": "agent", "user_id": "victim"},- "sess_create_2",+ {+ "mode": "agent",+ "user_id": "victim",+ "create_token": "web-create-2",+ },+ "new",user_id="alice",)assert channel.responses[-1]["ok"] is True- data = json.loads(- (sessions_dir / "sess_create_2" / "metadata.json").read_text(encoding="utf-8")- )- assert data["user_id"] == "alice"+ assert agent_client.requests[-1].user_id == "alice"+ assert agent_client.requests[-1].params["user_id"] == "alice"diff --git a/tests/unit_tests/gateway/test_cron_scheduler.py b/tests/unit_tests/gateway/test_cron_scheduler.pyindex 5651e04177..534a66cf9b 100644--- a/tests/unit_tests/gateway/test_cron_scheduler.py+++ b/tests/unit_tests/gateway/test_cron_scheduler.py@@ -174,6 +174,13 @@ class FakeAgentClient:async def send_request(self, envelope, *a, **kw):self.unary_requests.append(envelope)+ if envelope.method == "session.create":+ return AgentResponse(+ request_id=envelope.request_id or "",+ channel_id=envelope.channel or "",+ ok=True,+ payload={"session_id": "cron_agentserver_allocated"},+ )return AgentResponse(request_id=envelope.request_id or "",channel_id=envelope.channel or "",@@ -206,6 +213,8 @@ class FakeAgentClient:class FailingAgentClient(FakeAgentClient):async def send_request(self, envelope, *a, **kw):+ if envelope.method == "session.create":+ return await super().send_request(envelope, *a, **kw)self.unary_requests.append(envelope)raise RuntimeError("agent unavailable")@@ -287,7 +296,7 @@ class TestCronLastSessionId:assert stored is not Noneassert stored.last_session_idassert stored.last_session_id.startswith("cron_")- assert stored.last_session_id.endswith(f"_{job.id}")+ assert stored.last_session_id == "cron_agentserver_allocated"@pytest.mark.asyncioasync def test_run_now_info_returns_current_execution_session_id(self, tmp_path):@@ -994,12 +1003,14 @@ class TestTeamModeWake:assert task is not Noneawait task- assert len(agent.unary_requests) == 1+ assert len(agent.unary_requests) == 2assert len(agent.stream_requests) == 0- env = agent.unary_requests[0]+ create_env, env = agent.unary_requests+ assert create_env.method == "session.create"+ assert "session_id" not in create_env.paramsassert env.is_stream is Falseassert env.channel == "__cron__"- assert env.session_id.startswith("cron_") and env.session_id.endswith(f"_{job.id}")+ assert env.session_id == "cron_agentserver_allocated"state = svc.runs[run_id]assert state.status == "succeeded"@@ -1020,7 +1031,7 @@ class TestTeamModeWake:assert task is not Noneawait task- env = agent.unary_requests[0]+ env = agent.unary_requests[1]assert env.params["model_name"] == "fast-model"assert "model" not in env.paramsdiff --git a/tests/unit_tests/gateway/test_tui_session_project_path.py b/tests/unit_tests/gateway/test_tui_session_project_path.pyindex 9359512b29..f6f1eeec78 100644--- a/tests/unit_tests/gateway/test_tui_session_project_path.py+++ b/tests/unit_tests/gateway/test_tui_session_project_path.py@@ -149,11 +149,11 @@ class TestInitSessionMetadataChannelMetadata:@pytest.mark.asyncio-async def test_session_create_seeds_channel_metadata_for_resume(+async def test_session_create_uses_server_allocated_project_path_for_resume(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,) -> None:- """/clear 等价路径:create 后 metadata 含 channel_metadata,current-dir 可匹配。"""+ """AgentServer-owned create keeps a top-level project path usable by /resume."""sessions_root = tmp_path / "sessions"sessions_root.mkdir()project = tmp_path / "workspace"@@ -176,34 +176,48 @@ async def test_session_create_seeds_channel_metadata_for_resume(lambda _path: "HEAD",)- fake_project = SimpleNamespace(- project_id="proj_code_1",- project_dir=project_dir,- work_mode="code",- )-- monkeypatch.setattr(- "jiuwenswarm.server.runtime.session.project_store.find_or_create_code_project_for_tui_params",- lambda _params: fake_project,- )- monkeypatch.setattr(- "jiuwenswarm.server.runtime.session.kv_cache_affinity_lifecycle.is_kv_cache_affinity_enabled",- lambda: False,- )+ class _CreateAgentClient:+ def __init__(self) -> None:+ self.requests = []++ async def send_request(self, env):+ self.requests.append(env)+ from jiuwenswarm.server.runtime.session.session_metadata import init_session_metadata++ init_session_metadata(+ session_id="tui_6a601aa3_f4ed87",+ channel_id="tui",+ project_dir=env.params["project_dir"],+ project_id="proj_code_1",+ work_mode="code",+ mode=env.params["mode"],+ )+ return SimpleNamespace(+ ok=True,+ payload={+ "session_id": "tui_6a601aa3_f4ed87",+ "projectId": "proj_code_1",+ "projectDir": env.params["project_dir"],+ "workMode": "code",+ "prewarm_hit": True,+ "prewarm_status": "ready",+ },+ )channel = _TuiChannel()+ agent_client = _CreateAgentClient()register_cli_handlers(- CliHandlersBindParams(channel=channel, agent_client=None, path="/tui")+ CliHandlersBindParams(channel=channel, agent_client=agent_client, path="/tui"))await channel.local_handlers["/tui"]["session.create"](object(),"req-create",{- "session_id": "tui_6a601aa3_f4ed87","cwd": project_dir,"project_dir": project_dir,"mode": "code.normal",+ "create_token": "tui-project-path-create",},"previous",)@@ -212,8 +226,9 @@ async def test_session_create_seeds_channel_metadata_for_resume(meta_path = sessions_root / "tui_6a601aa3_f4ed87" / "metadata.json"data = json.loads(meta_path.read_text(encoding="utf-8"))assert data["project_dir"] == project_dir- assert data["channel_metadata"]["project_dir"] == project_dir- assert data["channel_metadata"]["cwd"] == project_dir+ assert agent_client.requests[0].method == "session.create"+ assert agent_client.requests[0].params["cwd"] == project_dir+ assert "session_id" not in agent_client.requests[0].params# 模拟 /resume current-dir:刚创建会话应命中(排除当前 sid 的逻辑由 list handler 负责)assert tui_session_matches_project_dir(data, project_dir) is Truediff --git a/tests/unit_tests/test_project_handlers.py b/tests/unit_tests/test_project_handlers.pyindex 1117d00007..c25a6fb817 100644--- a/tests/unit_tests/test_project_handlers.py+++ b/tests/unit_tests/test_project_handlers.py@@ -7,6 +7,7 @@ remove / restore / pinned_sessions + session.pin + 兼容性(session.create / refrom __future__ import annotationsimport os+from types import SimpleNamespaceimport pytest@@ -33,6 +34,73 @@ class _FakeWebChannel:)+class _FakeSessionCreateAgentClient:+ """AgentServer boundary fake backed by the production binding helpers."""++ def __init__(self) -> None:+ self.requests: list[object] = []+ self._sequence = 0++ async def send_request(self, request):+ self.requests.append(request)+ params = dict(request.params or {})++ from jiuwenswarm.common.work_mode import DEFAULT_WEB_WORK_MODE, is_default_project_id+ from jiuwenswarm.server.runtime.session import project_store+ from jiuwenswarm.server.runtime.session.session_metadata import init_session_metadata+ from jiuwenswarm.server.runtime.session.work_mode import resolve_session_work_mode_params++ binding = resolve_session_work_mode_params(params, channel_id="web")+ if binding.error:+ return SimpleNamespace(+ ok=False,+ payload={"error": binding.error, "code": binding.code},+ )+ project_id, project_dir, error, code = project_store.resolve_session_project_binding(+ binding.project_id, binding.project_dir+ )+ if error:+ return SimpleNamespace(ok=False, payload={"error": error, "code": code})++ work_mode = binding.work_mode+ if not is_default_project_id(project_id):+ project = project_store.get_project_by_id(project_id, cache_bust=True)+ if project is None:+ return SimpleNamespace(+ ok=False,+ payload={+ "error": f"project not found: {project_id}",+ "code": "NOT_FOUND",+ },+ )+ work_mode = project.work_mode or DEFAULT_WEB_WORK_MODE++ self._sequence += 1+ session_id = f"web_test_{self._sequence:03d}"+ init_session_metadata(+ session_id=session_id,+ channel_id="web",+ user_id=str(params.get("user_id") or ""),+ title=str(params.get("title") or ""),+ mode=str(params.get("mode") or "agent"),+ project_dir=project_dir,+ project_id=project_id,+ work_mode=work_mode,+ )+ return SimpleNamespace(+ ok=True,+ payload={+ "sessionId": session_id,+ "session_id": session_id,+ "projectId": project_id,+ "projectDir": project_dir,+ "workMode": work_mode,+ "prewarm_hit": True,+ "prewarm_status": "ready",+ },+ )++@pytest.fixture()def sessions_dir(tmp_path, monkeypatch):d = tmp_path / "sessions"@@ -71,7 +139,10 @@ def registered_channel(sessions_dir, project_store_dir):_register_web_handlers,)channel = _FakeWebChannel()- _register_web_handlers(WebHandlersBindParams(channel=channel))+ channel.agent_client = _FakeSessionCreateAgentClient()+ _register_web_handlers(+ WebHandlersBindParams(channel=channel, agent_client=channel.agent_client)+ )return channel@@ -672,20 +743,26 @@ class TestCompat:"""不传 project_dir → 归入默认项目,project_dir="" 兜底,行为不变。"""resp = await _call(registered_channel, "session.create",- {"session_id": "sess_compat_1", "title": "兼容", "mode": "code.normal", "channel_id": "web"},+ {+ "title": "兼容",+ "mode": "code.normal",+ "channel_id": "web",+ "create_token": "compat-create-1",+ },)assert resp["ok"] is True- assert resp["payload"]["session_id"] == "sess_compat_1"+ allocated_id = resp["payload"]["session_id"]+ assert allocated_id.startswith("web_test_")# metadata 中 project_dir 为空from jiuwenswarm.server.runtime.session.session_metadata import get_session_metadata- meta = get_session_metadata("sess_compat_1", cache_bust=True)+ meta = get_session_metadata(allocated_id, cache_bust=True)assert meta["project_dir"] == ""# 该会话出现在默认项目resp2 = await _call(registered_channel, "project.get_sessions", {"project_id": "default"})ids = [s["session_id"] for s in resp2["payload"]["sessions"]]- assert "sess_compat_1" in ids+ assert allocated_id in ids# ===========================================================================@@ -772,14 +849,19 @@ class TestSessionCreateProjectIdValidation:proj = _make_project("P", pa)resp = await _call(registered_channel, "session.create",- {"session_id": "s_valid", "project_id": proj.project_id, "channel_id": "web"},+ {+ "project_id": proj.project_id,+ "channel_id": "web",+ "create_token": "valid-project-create",+ },)assert resp["ok"] is True+ allocated_id = resp["payload"]["session_id"]# 归属到该项目r = await _call(registered_channel, "project.get_sessions", {"project_id": proj.project_id})- assert [s["session_id"] for s in r["payload"]["sessions"]] == ["s_valid"]+ assert [s["session_id"] for s in r["payload"]["sessions"]] == [allocated_id]@staticmethod@pytest.mark.asyncio@@ -789,24 +871,21 @@ class TestSessionCreateProjectIdValidation:])async def test_create_with_invalid_project_id(registered_channel, tmp_path, sessions_dir, scenario):"""传无效 project_id(不存在 / 已隐藏)→ NOT_FOUND,不创建会话。"""- from jiuwenswarm.server.runtime.session.session_metadata import get_session_metadataif scenario == "nonexistent":target_id = "proj_nonexistent"- target_sid = "s_nope"else: # hiddenpa = _abspath(tmp_path, "app")proj = _make_project("P", pa, hidden=True)target_id = proj.project_id- target_sid = "s_hidden"resp = await _call(registered_channel, "session.create",- {"session_id": target_sid, "project_id": target_id},+ {"project_id": target_id, "create_token": f"invalid-{scenario}"},)assert resp["ok"] is Falseassert resp["code"] == "NOT_FOUND"# 会话目录不应被创建(metadata 为空)- assert not get_session_metadata(target_sid, cache_bust=True)+ assert not any(sessions_dir.iterdir())# ===========================================================================@@ -828,17 +907,21 @@ class TestSessionCreateProjectDirConsistency:# 仅 project_id → 自动补齐resp1 = await _call(registered_channel, "session.create",- {"session_id": "s_autofill", "project_id": proj.project_id},+ {"project_id": proj.project_id, "create_token": "autofill-create"},)assert resp1["ok"] is Truefrom jiuwenswarm.server.runtime.session.session_metadata import get_session_metadata- meta = get_session_metadata("s_autofill", cache_bust=True)+ meta = get_session_metadata(resp1["payload"]["session_id"], cache_bust=True)assert meta.get("project_id") == proj.project_idassert meta.get("project_dir") == pa# project_id + 一致 path → 成功resp2 = await _call(registered_channel, "session.create",- {"session_id": "s_match", "project_id": proj.project_id, "project_dir": pa},+ {+ "project_id": proj.project_id,+ "project_dir": pa,+ "create_token": "matching-create",+ },)assert resp2["ok"] is True@@ -855,17 +938,15 @@ class TestSessionCreateProjectDirConsistency:other = _abspath(tmp_path, "other")if scenario == "mismatched":proj = _make_project("P", pa)- sid = "s_mismatch"- params = {"session_id": sid, "project_id": proj.project_id, "project_dir": other}+ params = {"project_id": proj.project_id, "project_dir": other}elif scenario == "path_only":- sid = "s_pathonly"- params = {"session_id": sid, "project_dir": pa}+ params = {"project_dir": pa}else: # default_with_path- sid = "s_def_path"- params = {"session_id": sid, "project_id": "default", "project_dir": pa}+ params = {"project_id": "default", "project_dir": pa}++ params["create_token"] = f"inconsistent-{scenario}"resp = await _call(registered_channel, "session.create", params)assert resp["ok"] is Falseassert resp["code"] == "BAD_REQUEST"- from jiuwenswarm.server.runtime.session.session_metadata import get_session_metadata- assert not get_session_metadata(sid, cache_bust=True)+ assert not any(sessions_dir.iterdir())diff --git a/tests/unit_tests/test_tui_kv_cache_session_lifecycle.py b/tests/unit_tests/test_tui_kv_cache_session_lifecycle.pyindex 268a20b65a..8ac8ea0987 100644--- a/tests/unit_tests/test_tui_kv_cache_session_lifecycle.py+++ b/tests/unit_tests/test_tui_kv_cache_session_lifecycle.py@@ -27,12 +27,24 @@ class _TuiChannel:class _SuccessfulAgentClient:- def __init__(self) -> None:+ def __init__(self, session_id: str = "tui_allocated") -> None:+ self.session_id = session_idself.requests: list[object] = []async def send_request(self, request):self.requests.append(request)- return SimpleNamespace(ok=True, payload={})+ return SimpleNamespace(+ ok=True,+ payload={+ "sessionId": self.session_id,+ "session_id": self.session_id,+ "projectId": "default_code",+ "projectDir": "",+ "workMode": "code",+ "prewarm_hit": True,+ "prewarm_status": "ready",+ },+ )def test_session_switch_is_forwarded_without_a_tui_local_handler() -> None:@@ -47,13 +59,14 @@ def test_session_switch_is_forwarded_without_a_tui_local_handler() -> None:@pytest.mark.asyncio-async def test_session_create_dispatches_previous_plan_root_offload(+async def test_session_create_forwards_previous_plan_root_to_agentserver(monkeypatch: pytest.MonkeyPatch,tmp_path,) -> None:sessions_root = tmp_path / "sessions"sessions_root.mkdir()channel = _TuiChannel()+ agent_client = _SuccessfulAgentClient("new-plan-root")calls: list[dict] = []monkeypatch.setattr("jiuwenswarm.common.utils.get_agent_sessions_dir", lambda: sessions_root)@@ -74,26 +87,25 @@ async def test_session_create_dispatches_previous_plan_root_offload(lambda: True,)register_cli_handlers(- CliHandlersBindParams(channel=channel, agent_client=None, path="/tui")+ CliHandlersBindParams(channel=channel, agent_client=agent_client, path="/tui"))await channel.local_handlers["/tui"]["session.create"](object(),"create-tui",{- "session_id": "new-plan-root","previous_session_id": "old-plan-root",+ "create_token": "tui-plan-create",},"old-plan-root",)- assert calls == [- {- "session_id": "old-plan-root",- "parent_session_id": "old-plan-root",- }- ]- assert (sessions_root / "new-plan-root").is_dir()+ assert calls == []+ assert len(agent_client.requests) == 1+ assert agent_client.requests[0].method == "session.create"+ assert agent_client.requests[0].params["previous_session_id"] == "old-plan-root"+ assert "session_id" not in agent_client.requests[0].params+ assert channel.responses[-1]["payload"]["session_id"] == "new-plan-root"assert channel.responses[-1]["ok"] is True@@ -105,6 +117,7 @@ async def test_session_create_does_not_apply_plan_root_action_to_team_owner(sessions_root = tmp_path / "sessions"sessions_root.mkdir()channel = _TuiChannel()+ agent_client = _SuccessfulAgentClient("new-team-root")calls: list[dict] = []monkeypatch.setattr("jiuwenswarm.common.utils.get_agent_sessions_dir", lambda: sessions_root)@@ -125,20 +138,23 @@ async def test_session_create_does_not_apply_plan_root_action_to_team_owner(lambda: True,)register_cli_handlers(- CliHandlersBindParams(channel=channel, agent_client=None, path="/tui")+ CliHandlersBindParams(channel=channel, agent_client=agent_client, path="/tui"))await channel.local_handlers["/tui"]["session.create"](object(),"create-tui-team-owner",{- "session_id": "new-plan-root","previous_session_id": "old-team-root",+ "mode": "team",+ "create_token": "tui-team-create",},"old-team-root",)assert calls == []+ assert agent_client.requests[0].method == "session.create"+ assert agent_client.requests[0].params["mode"] == "team"assert channel.responses[-1]["ok"] is True@@ -150,6 +166,7 @@ async def test_session_create_skips_kvc_metadata_when_affinity_disabled(sessions_root = tmp_path / "sessions"sessions_root.mkdir()channel = _TuiChannel()+ agent_client = _SuccessfulAgentClient("new-plan-root")monkeypatch.setattr("jiuwenswarm.common.utils.get_agent_sessions_dir", lambda: sessions_root)monkeypatch.setattr(@@ -169,20 +186,21 @@ async def test_session_create_skips_kvc_metadata_when_affinity_disabled(lambda **kwargs: pytest.fail("disabled affinity must not dispatch offload"),)register_cli_handlers(- CliHandlersBindParams(channel=channel, agent_client=None, path="/tui")+ CliHandlersBindParams(channel=channel, agent_client=agent_client, path="/tui"))await channel.local_handlers["/tui"]["session.create"](object(),"create-tui-disabled",{- "session_id": "new-plan-root","previous_session_id": "old-plan-root",+ "create_token": "tui-affinity-disabled",},"old-plan-root",)- assert (sessions_root / "new-plan-root").is_dir()+ assert not (sessions_root / "new-plan-root").exists()+ assert agent_client.requests[0].method == "session.create"assert channel.responses[-1]["ok"] is True@@ -194,6 +212,7 @@ async def test_session_create_contains_kvc_metadata_failure(sessions_root = tmp_path / "sessions"sessions_root.mkdir()channel = _TuiChannel()+ agent_client = _SuccessfulAgentClient("new-plan-root")monkeypatch.setattr("jiuwenswarm.common.utils.get_agent_sessions_dir", lambda: sessions_root)monkeypatch.setattr(@@ -209,20 +228,21 @@ async def test_session_create_contains_kvc_metadata_failure(lambda: True,)register_cli_handlers(- CliHandlersBindParams(channel=channel, agent_client=None, path="/tui")+ CliHandlersBindParams(channel=channel, agent_client=agent_client, path="/tui"))await channel.local_handlers["/tui"]["session.create"](object(),"create-tui-kvc-failure",{- "session_id": "new-plan-root","previous_session_id": "old-plan-root",+ "create_token": "tui-kvc-failure",},"old-plan-root",)- assert (sessions_root / "new-plan-root").is_dir()+ assert not (sessions_root / "new-plan-root").exists()+ assert agent_client.requests[0].method == "session.create"assert channel.responses[-1]["ok"] is True@@ -234,7 +254,7 @@ async def test_session_create_prefers_canonical_switch_owner_dispatch(sessions_root = tmp_path / "sessions"sessions_root.mkdir()channel = _TuiChannel()- agent_client = _SuccessfulAgentClient()+ agent_client = _SuccessfulAgentClient("new-team-root")monkeypatch.setattr("jiuwenswarm.common.utils.get_agent_sessions_dir", lambda: sessions_root)monkeypatch.setattr(@@ -253,19 +273,20 @@ async def test_session_create_prefers_canonical_switch_owner_dispatch(object(),"create-tui-forwarded",{- "session_id": "new-team-root","previous_session_id": "old-team-root","mode": "team","previous_mode": "team",+ "create_token": "tui-forwarded-team",},"old-team-root",)assert len(agent_client.requests) == 1request = agent_client.requests[0]- assert request.method == "session.switch"- assert request.params["session_id"] == "new-team-root"+ assert request.method == "session.create"+ assert "session_id" not in request.paramsassert request.params["previous_session_id"] == "old-team-root"assert request.params["mode"] == "team"assert request.params["previous_mode"] == "team"assert channel.responses[-1]["ok"] is True+ assert channel.responses[-1]["payload"]["session_id"] == "new-team-root"