Skip to content

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

feat(agentserver): 支持显式 Flash 模式及独立部署环境开关

qq_528784339ea7b5c3f085
diff --git a/.env.example b/.env.example
index 3e3eeb5116..f20846366c 100644
--- a/.env.example
+++ b/.env.example
@@ -1,4 +1,19 @@
# Copy to project root .env and adjust as needed
+# 独立 jiuwenswarm:普通单 Agent 对话默认使用 Flash,无需客户端发送 mode=flash。
+# 设置时优先于 config.yaml 的 flash.enabled;不设置则回退 config(默认 false)。
+# 必须注入实际运行 Agent 的 AgentServer 进程;修改后重启服务。
+# 企业版不加载 .env,请通过容器/服务的进程环境注入。
+# OfficeClaw/PC 前台仍走显式模式;Code、Team、Plan 与已有会话绑定保持原规则。
+# 仅切换默认 Agent 实现,不开启技能检索。
+# config.yaml: enabled: ${JIUWENSWARM_FLASH_ENABLED:-false}
+# JIUWENSWARM_FLASH_ENABLED=true
+
+# Flash 技能检索独立开关,不负责选择 Agent 实现。
+# 设置 true/false 均覆盖 flash.skill_selection.enabled;未设置时回退 config(默认 false)。
+# 只覆盖运行时生效值,不改写 config 文件;同样须注入 AgentServer 进程并重启。
+# config.yaml: skill_selection.enabled: ${JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED:-false}
+# JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED=false
+
# Enterprise Claw Manager / Gateway manager_ws_client examples
# =============================================================================
# MANAGER CONFIGURATION
diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.py
index 336888afc6..c40284c8f3 100644
--- a/jiuwenswarm/common/config.py
+++ b/jiuwenswarm/common/config.py
@@ -159,6 +159,33 @@ def resolve_env_vars(value: Any) -> Any:
return value
+def _normalize_flash_config(config: dict[str, Any]) -> None:
+ """统一 Flash 布尔类型,并让旧配置无需手改即可接受部署环境变量。"""
+ flash = config.get("flash")
+ if not isinstance(flash, dict):
+ return
+ switches = (
+ (flash, "JIUWENSWARM_FLASH_ENABLED"),
+ (flash.get("skill_selection"), "JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED"),
+ )
+ for section, env_name in switches:
+ if not isinstance(section, dict):
+ continue
+ value = section.get("enabled", False)
+ if isinstance(value, bool):
+ # 旧 YAML / provider 的布尔值仅作回退;复用与模板相同的占位符解析。
+ default = str(value).lower()
+ value = resolve_env_vars("${" + env_name + ":-" + default + "}")
+ section["enabled"] = coerce_config_bool(value, default=False)
+
+
+def resolve_config_env_vars(config: dict[str, Any]) -> dict[str, Any]:
+ """解析完整配置快照;保持输入不变,并统一 Flash 开关的布尔类型。"""
+ resolved = resolve_env_vars(config)
+ _normalize_flash_config(resolved)
+ return resolved
+
+
def _normalize_config(config: dict[str, Any] | None) -> None:
"""后处理配置,将需要结构化的字符串字段解析为原生类型。
@@ -352,14 +379,14 @@ def get_config():
config_base = fill_template_defaults(
supplied, load_yaml_dict(resolve_shipped_template_config_path())
)
- config_base = resolve_env_vars(config_base)
+ config_base = resolve_config_env_vars(config_base)
_normalize_config(config_base)
except Exception:
logger.warning("config provider failed, fallback to yaml", exc_info=True)
config_base = None
if config_base is None:
config_base = get_merged_config_dict()
- config_base = resolve_env_vars(config_base)
+ config_base = resolve_config_env_vars(config_base)
_normalize_config(config_base)
with _config_lock:
diff --git a/jiuwenswarm/common/docs/specs/S_08_config-and-environment.md b/jiuwenswarm/common/docs/specs/S_08_config-and-environment.md
index b2839457ae..4782142541 100644
--- a/jiuwenswarm/common/docs/specs/S_08_config-and-environment.md
+++ b/jiuwenswarm/common/docs/specs/S_08_config-and-environment.md
@@ -7,7 +7,7 @@
| 类型 | spec |
| 编号 / slug | S_08 / config-and-environment |
| 关联模块 | jiuwenswarm/common/{config, config_provider, path_provider, local_env_config, hooks_config, http_proxy_config, kv_cache_affinity_config, mode_matrix, work_mode, context_keys}.py |
-| 最近一次修订日期 | 2026-10-13 |
+| 最近一次修订日期 | 2026-10-21 |
| 关联 feature | 暂无 |
## 范围 / 边界
@@ -20,7 +20,7 @@
## 装配关系(一句话)
入口是 `config.get_config()`:慢路径先向 `config_provider`(企业注入,fail-open 回退
-Default)要配置源,否则合并 YAML 模板 + 用户 override 并经 `resolve_env_vars` 解析
+Default)要配置源,否则合并 YAML 模板 + 用户 override 并经 `resolve_config_env_vars` 解析
`${VAR}`——变量值经 `local_env_config` 的 tip/overlay 读取,而 tip 写入反向失效 config
的 ns 缓存;`hooks_config` / `kv_cache_affinity_config` 是 config 树特定段的 schema /
规则消费者;`http_proxy_config` 消费 local_env_config 读代理;`mode_matrix` 组合
@@ -69,12 +69,26 @@ Default)要配置源,否则合并 YAML 模板 + 用户 override 并经 `reso
- **N14 work_mode 正交**:work_mode(work 办公 / code 工程)与 mode 正交;Web 默认
`work`、TUI 默认 `code`;虚拟默认项目 ID:work → `default`、code → `default_code`;
`normalize_work_mode` 宽松(非法回落 default)仅限迁移/兜底,公开入口走严格校验。
+- **N15 OfficeClaw 显式 Flash**:前台聊天与会话创建由请求 `mode=flash` 选择
+ FlashAdapter,普通 Agent 请求不受 `flash.enabled` 隐式转换影响;其它渠道与后台
+ 保留原规则。`flash` 保留独立 canonical,并纳入单 Agent 轨迹白名单;尚未实现的
+ `flash.*` 在此入口拒绝。续接结合已存 `mode` 与 `adapter_mode` 恢复,保证前台准备与租户池二次解析一致;活跃 Plan 与中断归属优先于新的默认模式。
+
+- **N16 Flash 配置占位符**:模板的 `flash.enabled` 与
+ `flash.skill_selection.enabled` 分别引用 `${JIUWENSWARM_FLASH_ENABLED:-false}`
+ 与 `${JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED:-false}`;两变量属于 Track A,
+ 沙箱启动注入后经统一配置加载解析,`get_config()` 返回布尔值,消费方不再直读环境。
+ 旧 YAML / provider 中的布尔值在运行时作为同名占位符的默认值,环境变量可双向覆盖;
+ 未注入时保留原布尔配置。非法字符串关闭开关,不改变其它字段的字符串解析语义。
+ 配置文件、实例创建/热更新快照及预热均通过 `resolve_config_env_vars` 统一解析。
+ 原始 YAML、合并缓存及 provider 输入保持不变;重启或清理配置缓存后重新解析。
+ N15 的 OfficeClaw 显式模式与既有会话绑定不受默认开关替代。
## 接口契约
| 模块 | 关键符号 | 语义要点 |
|---|---|---|
-| `config.py`(~2500 行) | `get_config` / `get_config_raw` / `get_merged_config_dict` / `resolve_env_vars` / `set_config` / `update_config` / `clear_config_cache` / `CONFIG_YAML_PATH` | N1–N4;各配置段(permissions/models/mcp/teams/hooks)读写 API |
+| `config.py`(~2500 行) | `get_config` / `get_config_raw` / `get_merged_config_dict` / `resolve_env_vars` / `resolve_config_env_vars` / `set_config` / `update_config` / `clear_config_cache` / `CONFIG_YAML_PATH` | N1–N4;各配置段(permissions/models/mcp/teams/hooks)读写 API |
| `config_provider.py` | `ConfigProvider`(Protocol)/ `register/get/reset_config_provider` / `DefaultConfigProvider` / `AgentConfigContext/Result` / `apply_enterprise_mcp` | N9;配置源由 `JIUWENSWARM_CONFIG_SOURCE` 或 `config.source` 决定 |
| `path_provider.py` | `PathCategory`(~20 类目录)/ `PathProvider`(Protocol)/ `register/get/reset_path_provider` / `current_path_context` / `bind_path_session_id` | 进程级单例 provider;请求身份 task-local(ContextVar) |
| `local_env_config.py`(~1340 行) | `SPAWN_ENV_KEYS` / `BUSINESS_MIRROR_KEYS` / `get_local_config` / `read_env[_if_set]` / `set_os_environ` / `export_agent_environ` / `bind_agent_env_ns` / `bind_task_env_overlay` / `effective_tip` | N5–N8 |
diff --git a/jiuwenswarm/common/local_env_config.py b/jiuwenswarm/common/local_env_config.py
index fcffe29cf6..5cc6c5957b 100644
--- a/jiuwenswarm/common/local_env_config.py
+++ b/jiuwenswarm/common/local_env_config.py
@@ -82,6 +82,9 @@ SPAWN_ENV_KEYS: frozenset[str] = frozenset(
"DISABLED_TOOLS",
# Code-mode generated-code co-author header switch; process shared.
"JIUWENSWARM_CODE_COAUTHOR_HEADER_ENABLED",
+ # Flash 部署开关由 config.yaml 占位符读取,任务 overlay 不应屏蔽沙箱启动值。
+ "JIUWENSWARM_FLASH_ENABLED",
+ "JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED",
# HTTP/SSE service-to-service mTLS. These values are process-scoped;
# certificate paths point to files mounted by the deployment layer.
"JIUWENSWARM_LINK_MTLS_MODE",
diff --git a/jiuwenswarm/common/mode_matrix.py b/jiuwenswarm/common/mode_matrix.py
index dd692b5d12..521196f990 100644
--- a/jiuwenswarm/common/mode_matrix.py
+++ b/jiuwenswarm/common/mode_matrix.py
@@ -114,6 +114,7 @@ TEAM_CANONICAL_MODES: frozenset[str] = frozenset(
# instead of becoming readable merely because they are not known Team modes.
SINGLE_AGENT_CANONICAL_MODES: frozenset[str] = frozenset(
{
+ "flash",
NEW_AGENT_WORK_NORMAL,
NEW_AGENT_WORK_PLAN,
NEW_AGENT_CODE_NORMAL,
diff --git a/jiuwenswarm/resources/.env.template b/jiuwenswarm/resources/.env.template
index 148f90236d..81a709a30e 100644
--- a/jiuwenswarm/resources/.env.template
+++ b/jiuwenswarm/resources/.env.template
@@ -161,3 +161,16 @@ GITCODE_ACCESS_TOKEN=
# Over-limit title/content is truncated with an inline "…(truncated, total N chars)"
# marker. Must be a positive integer; blank/invalid/non-positive falls back to 4096.
# JIUWENSWARM_TASK_TEXT_LIMIT=4096
+
+# 独立 jiuwenswarm 普通单 Agent 的默认实现;部署到实际 AgentServer 进程后重启。
+# 优先于 flash.enabled,未设置时回退 config(默认 false);不控制技能检索。
+# OfficeClaw/PC 前台显式模式、Code、Team、Plan 及已有会话绑定保持原规则。
+# 企业版请用容器/服务进程环境注入,不读取 .env 文件。
+# config.yaml: enabled: ${JIUWENSWARM_FLASH_ENABLED:-false}
+# JIUWENSWARM_FLASH_ENABLED=true
+
+# Flash 技能检索独立开关,不负责选择 Agent 实现。
+# 设置 true/false 均覆盖 flash.skill_selection.enabled;未设置时回退 config(默认 false)。
+# 只覆盖运行时生效值,不改写 config 文件;同样须注入 AgentServer 进程并重启。
+# config.yaml: skill_selection.enabled: ${JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED:-false}
+# JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED=false
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index c30ed9972f..86d5469201 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -1763,17 +1763,18 @@ modes:
# 演进)。行为定义(rail 白名单 / react 覆盖)硬编码在 JiuwenSwarmFlashAdapter
# 类常量,不在此配置。enabled 控制「是否对普通 agent 对话注入 flash」;
# skill_selection 仅配置 Flash 内可选的已安装技能检索模块。
-# 触发点在 mode 解析层(resolve_agent_request_mode):置 true 时,所有归一到
-# agent 的对话请求被改写为 flash mode(无需前端发 mode=flash,配置即触发);
-# code / team 路径不受影响。置 false(默认)时维持原 agent 行为。
+# 触发点在 mode 解析层:独立部署的普通单 Agent 请求可按此配置选择 Flash。
+# OfficeClaw/PC 前台仍按显式 mode 选择;Code、Team、显式 Plan 与已有会话绑定
+# 保持原规则。置 false(默认)时,普通单 Agent 默认走原 agent 实现。
# enabled: false(默认)— 普通对话走 DeepAdapter(全量 rail + task loop)。
# enabled: true — 普通对话注入 flash,走 FlashAdapter facade。
flash:
- enabled: false
+ # 沙箱启动时注入;缺省关闭,配置加载后为布尔值。
+ enabled: ${JIUWENSWARM_FLASH_ENABLED:-false}
# 必须在模板声明:启动清理及配置合并会删除模板中不存在的字段。
# 模块可独立删除;这些默认值不启用功能,也不影响其他 Agent mode。
skill_selection:
- enabled: false
+ enabled: ${JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED:-false}
catalog_check_interval_s: 5.0
candidate_k: 5
text_max_chars: 2000
diff --git a/jiuwenswarm/server/handlers/_default.py b/jiuwenswarm/server/handlers/_default.py
index ff774a6698..939d237f66 100644
--- a/jiuwenswarm/server/handlers/_default.py
+++ b/jiuwenswarm/server/handlers/_default.py
@@ -46,6 +46,7 @@ from jiuwenswarm.server.handlers._shared import (
_session_mode_sync_locks,
_sessions_dir_for_request,
_sync_chat_request_metadata,
+ _uses_explicit_officeclaw_mode,
_uses_tenant_pool,
resolve_request_project_dir,
resolve_request_runtime_mode,
@@ -563,13 +564,16 @@ async def _prepare_code_mode_chat_turn(
# tool_call id. Restore the original canonical mode before applying
# defaults; otherwise the request is irreversibly rewritten to
# ``agent`` and the tenant pool creates a different adapter instance.
- if is_interrupt_continuation and not explicit_mode_provided:
+ explicit_officeclaw = _uses_explicit_officeclaw_mode(request)
+ restore_session_mode = is_interrupt_continuation or explicit_officeclaw
+ keep_interrupted_mode = is_interrupt_continuation and explicit_officeclaw
+ if restore_session_mode and (not explicit_mode_provided or keep_interrupted_mode):
stored_mode = str(session_metadata.get("mode") or "").strip()
if stored_mode and stored_mode.lower() != "unknown":
params["mode"] = stored_mode
_raw_mode = stored_mode
logger.info(
- "[AgentWebSocketServer] interrupt continuation routing "
+ "[AgentWebSocketServer] session continuation routing "
"restored: session_id=%s mode=%s source=%s",
sid,
stored_mode,
@@ -653,6 +657,10 @@ async def _prepare_code_mode_chat_turn(
mode = "flash"
request.resolved_adapter_mode = "flash"
request.resolved_adapter_source = "session_sticky"
+ if _uses_explicit_officeclaw_mode(request):
+ # 租户池稍后再次解析请求,保留 Flash canonical 才不会退回 Deep。
+ canonical_mode = "flash"
+ params["mode"] = canonical_mode
logger.info(
"[_prepare_code_mode_chat_turn] Flash session affinity restored: "
"session_id=%s canonical_mode=%s",
diff --git a/jiuwenswarm/server/handlers/_shared.py b/jiuwenswarm/server/handlers/_shared.py
index 40e5585582..3e0e32c4b0 100644
--- a/jiuwenswarm/server/handlers/_shared.py
+++ b/jiuwenswarm/server/handlers/_shared.py
@@ -10,6 +10,7 @@ import logging
import os
from contextlib import asynccontextmanager
from dataclasses import replace
+from functools import partial
from typing import Any, Optional
from pathlib import Path
@@ -172,6 +173,7 @@ def resolve_agent_request_mode(
raw_mode: Any,
*,
work_mode: Any = None,
+ allow_flash_default: bool = True,
) -> tuple[str, str | None, str]:
"""Resolve request params.mode into manager mode, sub_mode, and canonical value.
@@ -180,11 +182,13 @@ def resolve_agent_request_mode(
``fast``(无 ``agent.`` 前缀,如旧 cron job 存量数据)同样归一到 ``agent``,
与 CLI ``MODE_ALIASES``、记忆配置 ``_resolve_mode_memory`` 的裸 token 处理保持一致。
- ``flash.enabled`` 配置开关:置 true 时,普通 agent 对话请求被归到 ``flash``
+ ``flash.enabled`` 由配置加载层解析环境变量占位符;为 true 时,普通 agent
+ 对话请求被归到 ``flash``
mode(独立轻量 facade:单轮、裁 rail、无 task loop),配置即触发,无需前端发
``mode=flash``。注入由函数最前面的 guard 完成,只命中 agent 类请求(agent /
plan / fast / 空,且 work_mode 非 code);``code`` / ``team`` / 显式 flash 等
其余路径不受影响,下面走原归一化逻辑。置 false(默认)时维持原 ``agent`` 行为。
+ OfficeClaw 前台入口传入 ``allow_flash_default=False``,仅接受显式选型。
注:cron / heartbeat / proactive 等后台流水线若发 agent 类 mode,同样会被
归到 flash——flash 保留 filesystem / bash / skill / 子代理能力,仅裁掉
@@ -200,7 +204,8 @@ def resolve_agent_request_mode(
# 新增 agent.* 子模式自动覆盖,无需同步维护枚举(参见 PR6431 review 次要项)。
# try/except 兜底:config 不可读时安全降级为不注入,保持原 agent 行为。
_guard_head = mode_text.split(".", 1)[0] if mode_text else ""
- if not mode_text or _guard_head in ("agent", "plan", "fast"):
+ is_agent_family = not mode_text or _guard_head in ("agent", "plan", "fast")
+ if allow_flash_default and is_agent_family:
_wm = work_mode.strip().lower() if isinstance(work_mode, str) else ""
if _wm != "code":
try:
@@ -278,10 +283,26 @@ def _request_allows_plan_entry(request: AgentRequest, params: dict) -> bool:
return True
if request.session_id and request.session_id in _plan_active_sessions:
return True
+ if _uses_explicit_officeclaw_mode(request):
+ previous_mode = canonicalize_mode_text(params.get(_SESSION_PREVIOUS_MODE_KEY))
+ if previous_mode in _PLAN_MODE_TOKENS:
+ return True
source = str(params.get("plan_entry_source") or "").strip().lower()
return source in EXPLICIT_PLAN_ENTRY_SOURCES
+def _uses_explicit_officeclaw_mode(request: AgentRequest) -> bool:
+ """OfficeClaw 前台入口由 Relay 显式选型,后台与其它渠道保留旧策略。"""
+ if str(getattr(request, "channel_id", "") or "").strip().lower() != "officeclaw":
+ return False
+ if getattr(request, "req_method", None) not in _CODE_MODE_SYNC_METHODS | {ReqMethod.SESSION_CREATE}:
+ return False
+ metadata = getattr(request, "metadata", None)
+ metadata = metadata if isinstance(metadata, dict) else {}
+ source = str(metadata.get("source") or "").strip().lower()
+ return source not in {"cron", "heartbeat", "proactive"}
+
+
def resolve_request_runtime_mode(
request: AgentRequest,
*,
@@ -294,21 +315,37 @@ def resolve_request_runtime_mode(
"""
params = request.params if isinstance(request.params, dict) else {}
mode_text = canonicalize_mode_text(params.get("mode"))
- if mode_text in _PLAN_MODE_TOKENS and not _request_allows_plan_entry(
- request, params
- ):
- params = {**params, "mode": mode_text.split(".", 1)[0]}
- resolved = resolve_request_mode(
- params,
- resolve_agent_request_mode,
- work_mode=work_mode,
+ explicit_officeclaw = _uses_explicit_officeclaw_mode(request)
+ if explicit_officeclaw and mode_text.startswith("flash."):
+ raise ValueError(f"unsupported OfficeClaw mode: {mode_text}")
+ if explicit_officeclaw and mode_text.startswith("code."):
+ # 审批恢复的具体 Code 模式不能被旧会话 work_mode=work 再次改成 Agent。
+ params = dict(params)
+ params.pop("work_mode", None)
+ work_mode = None
+ restoring_plan = False
+ if explicit_officeclaw and mode_text == "flash":
+ previous_mode = canonicalize_mode_text(params.get(_SESSION_PREVIOUS_MODE_KEY))
+ restoring_plan = previous_mode in _PLAN_MODE_TOKENS
+ if request.session_id in _plan_active_sessions:
+ restoring_plan = True
+ if restoring_plan:
+ mode_text = previous_mode if previous_mode in _PLAN_MODE_TOKENS else WEB_PLAN_AGENT
+ params = {**params, "mode": mode_text}
+ if mode_text in _PLAN_MODE_TOKENS and not restoring_plan:
+ if not _request_allows_plan_entry(request, params):
+ params = {**params, "mode": mode_text.split(".", 1)[0]}
+ legacy_resolver = partial(
+ resolve_agent_request_mode, allow_flash_default=not explicit_officeclaw,
)
+ resolved = resolve_request_mode(params, legacy_resolver, work_mode=work_mode)
# Web composition and new canonical modes bypass the legacy Flash guard.
# Apply the default only after resolving the profile, so Code, Team and
# explicit Plan requests retain their own routing and approval semantics.
if resolved.canonical_mode in {"agent", NEW_AGENT_WORK_NORMAL}:
default_mode, _, _ = resolve_agent_request_mode(
"agent", work_mode=resolved.work_mode,
+ allow_flash_default=not explicit_officeclaw,
)
if default_mode == "flash":
resolved = replace(
diff --git a/jiuwenswarm/server/handlers/bootstrap.py b/jiuwenswarm/server/handlers/bootstrap.py
index 0d243c0198..d48e739cf1 100644
--- a/jiuwenswarm/server/handlers/bootstrap.py
+++ b/jiuwenswarm/server/handlers/bootstrap.py
@@ -228,6 +228,7 @@ async def handle_session_create(ctx: RequestContext) -> None:
and canonical_mode in {
"agent",
NEW_AGENT_WORK_NORMAL,
+ "flash",
"code",
"code.normal",
}
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 1a683074b5..8159302420 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -566,7 +566,7 @@ from jiuwenswarm.common.config import (
get_ttse_enabled,
is_subagent_mirror_child_stream_enabled,
is_subagent_runtime_enabled,
- resolve_env_vars,
+ resolve_config_env_vars,
resolve_string_or_list_config,
)
from jiuwenswarm.common.mcp_config import (
@@ -1750,7 +1750,7 @@ def _resolve_instance_config_base(config_base: dict[str, Any] | None) -> dict[st
# 合并:模板补全缺失键(如 react.ttse / react.subagents),外部显式键与独有
# 键全部保留。create_instance 与 reload 共用,避免热更丢掉模板默认值。
template = load_yaml_dict(resolve_shipped_template_config_path())
- return resolve_env_vars(fill_template_defaults(config_base, template))
+ return resolve_config_env_vars(fill_template_defaults(config_base, template))
def _deep_agent_context_engine_config(react_cfg: dict[str, Any] | None) -> ContextEngineConfig:
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py b/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
index f4baa38282..8630eb894d 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
@@ -13,12 +13,12 @@ config.yaml。父类只提供通用工具工厂与生命周期扩展点,不感
一致:CodeAdapter 把 ``_FIXED_RAIL_NAMES`` / ``_is_code_agent`` 等定义硬编码为
类常量,flash 同样把行为开关、keep 白名单与工具面裁剪作为类常量/override。
-部署组合提示:``flash.enabled`` 是进程级开关,不区分 channel / 请求来源——
-officeclaw 对话与 cron / heartbeat / proactive 等后台流水线同样进入 flash。
+部署组合提示:OfficeClaw 交互请求由 Relay 显式发送 ``mode=flash`` 选型,
+不再由 ``flash.enabled`` 将普通 Agent 请求自动转换为 Flash;其它渠道和后台
+来源沿用各自的既有路由策略。具体准入与会话续接由 ``_shared`` 的模式解析负责。
flash 白名单不含 ``_llm_retry_rail`` / ``_context_overflow_recovery_rail``
等健壮性 rail,长文档 / 弱网任务的容错弱于
-normal;officeclaw 等部署开启 flash 前需评估此影响面,如需按来源豁免应在
-mode 解析 guard(``_shared.resolve_agent_request_mode``)增加 channel 过滤。
+normal,部署时仍需评估所选 Flash profile 的能力边界。
flash 行为由类常量定义:
- :data:`_FLASH_REACT_OVERRIDE` — react/evolution 覆盖(``enable_task_loop=false``
diff --git a/jiuwenswarm/server/runtime/agent_manager.py b/jiuwenswarm/server/runtime/agent_manager.py
index f1ccfaf862..0e4f4eaec1 100644
--- a/jiuwenswarm/server/runtime/agent_manager.py
+++ b/jiuwenswarm/server/runtime/agent_manager.py
@@ -1926,7 +1926,7 @@ class AgentManager:
"""解析请求的 agent 模式.
优先取 params["mode"];interrupt resume 请求(权限审批/确认/ask_user)
- 未携带 mode 时,从 session metadata 读取原始请求的 mode,避免从
+ 以及 OfficeClaw 续聊未携带 mode 时,从 session metadata 读取原始请求的 mode,避免从
code.normal 降级为 agent,导致 adapter 实例不匹配、无法恢复原
interaction;其余情况默认 "agent"。
@@ -1937,18 +1937,17 @@ class AgentManager:
Returns:
完整 mode 字符串(如 "code.normal"、"agent.plan")
"""
+ from jiuwenswarm.server.handlers._shared import _uses_explicit_officeclaw_mode
+
mode_full = params.get("mode")
- if mode_full:
+ explicit_officeclaw = _uses_explicit_officeclaw_mode(request)
+ is_interrupt_continuation = _is_interrupt_resume_request(request)
+ keep_interrupted_mode = explicit_officeclaw and is_interrupt_continuation
+ if mode_full and not keep_interrupted_mode:
return str(mode_full)
source = str(params.get("source") or "").strip()
- answers = params.get("answers")
- req_id = str(params.get("request_id") or "").strip()
- if (
- source in {"permission_interrupt", "confirm_interrupt", "ask_user_interrupt"}
- and isinstance(answers, list)
- and bool(req_id)
- ):
+ if is_interrupt_continuation or explicit_officeclaw:
sid = getattr(request, "session_id", "") or ""
if sid:
try:
@@ -1966,11 +1965,21 @@ class AgentManager:
sessions_root=sessions_root,
)
stored_mode = str(meta.get("mode") or "").strip()
+ stored_adapter = str(meta.get("adapter_mode") or "").strip().lower()
+ stored_work_mode = str(meta.get("work_mode") or "work").strip().lower()
+ normal_flash_session = (
+ stored_mode in {"agent", "agent.work.normal"}
+ and stored_adapter == "flash"
+ )
+ if explicit_officeclaw and normal_flash_session:
+ # 旧会话业务 mode 仍为 agent;审批恢复须保留已经选定的 Flash。
+ if stored_work_mode == "work":
+ stored_mode = "flash"
if stored_mode and stored_mode != "unknown":
# 回写 params,让下游 run_stream 等也能拿到正确 mode
params["mode"] = stored_mode
logger.info(
- "[AgentManager] interrupt resume mode resolved"
+ "[AgentManager] session continuation mode resolved"
" from session metadata: session_id=%s"
" mode=%s source=%s",
sid, stored_mode, source,
@@ -1981,7 +1990,7 @@ class AgentManager:
"[AgentManager] resolve mode from session metadata failed",
exc_info=True,
)
- return "agent"
+ return str(mode_full) if mode_full else "agent"
def _agent_lookup_from_request(self, request: Any) -> tuple[str, str | None, str | None]:
"""Resolve get_agent keys from a chat request.
diff --git a/jiuwenswarm/server/runtime/agent_warm_pool.py b/jiuwenswarm/server/runtime/agent_warm_pool.py
index dbca788a3e..0083c97018 100644
--- a/jiuwenswarm/server/runtime/agent_warm_pool.py
+++ b/jiuwenswarm/server/runtime/agent_warm_pool.py
@@ -20,6 +20,7 @@ from jiuwenswarm.common.work_mode import (
DEFAULT_PROJECT_ID_CODE,
DEFAULT_PROJECT_ID_WORK,
)
+from jiuwenswarm.common.config import resolve_config_env_vars
from jiuwenswarm.edition import is_enterprise
from jiuwenswarm.server.runtime.session import project_store
@@ -298,7 +299,7 @@ class AgentWarmPool:
)
flash_enabled = False
if isinstance(config, dict):
- flash_config = config.get("flash")
+ flash_config = resolve_config_env_vars(config).get("flash")
flash_enabled = bool(
flash_config.get("enabled", False)
if isinstance(flash_config, dict)
diff --git a/tests/unit_tests/agentserver/test_agent_warm_pool.py b/tests/unit_tests/agentserver/test_agent_warm_pool.py
index 47ab475076..65dda20eab 100644
--- a/tests/unit_tests/agentserver/test_agent_warm_pool.py
+++ b/tests/unit_tests/agentserver/test_agent_warm_pool.py
@@ -75,6 +75,7 @@ async def _wait_until(predicate, *, attempts: int = 100) -> None:
@pytest.fixture
def isolated_pool(monkeypatch, tmp_path: Path):
+ monkeypatch.delenv("JIUWENSWARM_FLASH_ENABLED", raising=False)
monkeypatch.setattr(
"jiuwenswarm.server.runtime.agent_warm_pool.get_agent_sessions_dir",
lambda: tmp_path,
@@ -512,3 +513,35 @@ def test_new_boot_cleans_only_metadata_less_marked_workspace(
assert not (tmp_path / stale_id).exists()
assert (tmp_path / persisted_id / "metadata.json").is_file()
+
+
[email protected]("env_value,config_enabled,expected", [
+ ("true", False, "flash"), ("false", True, "agent"), (None, True, "flash"),
+])
[email protected]("snapshot", ["raw", "resolved"])
+async def test_prewarm_uses_same_flash_environment_as_requests(
+ isolated_pool, monkeypatch, tmp_path, env_value, config_enabled, expected, snapshot,
+):
+ from jiuwenswarm.common import config as config_module
+
+ config_file = tmp_path / "config.yaml"
+ config_file.write_text(f"flash:\n enabled: {str(config_enabled).lower()}\n", encoding="utf-8")
+ monkeypatch.setattr(config_module, "get_config_file", lambda: config_file)
+ config_module.clear_config_cache()
+ monkeypatch.delenv("JIUWENSWARM_FLASH_ENABLED", raising=False)
+ if env_value is not None:
+ monkeypatch.setenv("JIUWENSWARM_FLASH_ENABLED", env_value)
+ agent = _FakeRootAgent()
+ pool = isolated_pool(agent)
+ try:
+ config = config_module.get_config_raw() if snapshot == "raw" else config_module.get_config()
+ await pool.sync(["web"], config=config)
+ await _wait_until(lambda: len(pool._slots) == 1)
+ assert pool._manager.get_agent_calls[0]["mode"] == expected
+ assert agent.prepare_calls[0]["adapter_mode"] == expected
+ desired = pool._desired_keys(config=config)
+ assert all(key.adapter_mode == "code" for key in desired if key.work_mode == "code")
+ finally:
+ await pool.close()
+ config_module.clear_config_cache()
diff --git a/tests/unit_tests/agentserver/test_agentserver_acp.py b/tests/unit_tests/agentserver/test_agentserver_acp.py
index 7e7671eb09..6244ba22e5 100644
--- a/tests/unit_tests/agentserver/test_agentserver_acp.py
+++ b/tests/unit_tests/agentserver/test_agentserver_acp.py
@@ -903,6 +903,50 @@ async def test_handle_session_create_returns_session_id(monkeypatch, tmp_path):
]
+ "wire_mode,global_enabled,expected",
+ [("flash", False, "flash"), ("agent.plan", True, "agent")],
+)
+async def test_officeclaw_session_create_persists_explicit_adapter(
+ monkeypatch, tmp_path, wire_mode, global_enabled, expected,
+):
+ from unittest.mock import AsyncMock
+ from jiuwenswarm.server.handlers import _shared
+
+ monkeypatch.setattr(_shared, "get_config", lambda: {"flash": {"enabled": global_enabled}})
+ server = AgentWebSocketServerHarness()
+ manager = FakeAgentManager(session_id="officeclaw_explicit_create")
+ server.set_agent_manager_for_test(manager)
+ prewarm = AsyncMock()
+ monkeypatch.setattr(server, "_tenant_pool", lambda: types.SimpleNamespace(
+ prewarm_session_in_background=prewarm,
+ ))
+ fake_ws = FakeWebSocket()
+ sessions_root = tmp_path / "sessions"
+ patch_shared_name(monkeypatch, "encode_agent_response_for_wire", fake_encode_agent_response_for_wire)
+ patch_session_roots(monkeypatch, sessions_root)
+ incoming = AgentRequest(
+ request_id="officeclaw-explicit-create",
+ channel_id="officeclaw",
+ req_method=ReqMethod.SESSION_CREATE,
+ params={"create_token": "explicit-create", "mode": wire_mode},
+ )
+
+ await server.handle_session_create_for_test(fake_ws, incoming, asyncio.Lock())
+ await asyncio.sleep(0)
+
+ assert fake_ws.sent[0]["ok"] is True
+ assert manager.claim_session_calls[0]["adapter_mode"] == expected
+ assert manager.claim_session_calls[0]["prewarm_eligible"] is True
+ metadata = json.loads(
+ (sessions_root / manager.session_id / "metadata.json").read_text(encoding="utf-8"),
+ )
+ assert metadata["mode"] == metadata["adapter_mode"] == expected
+ assert prewarm.await_args.kwargs["mode"] == expected
+ assert prewarm.await_args.kwargs["adapter_mode"] == expected
+
+
@pytest.mark.asyncio
async def test_handle_session_create_rejects_explicit_session_id(monkeypatch, tmp_path):
server = AgentWebSocketServerHarness()
diff --git a/tests/unit_tests/agentserver/test_facade_mode_compatibility.py b/tests/unit_tests/agentserver/test_facade_mode_compatibility.py
index 5ab6122bda..ec6447f099 100644
--- a/tests/unit_tests/agentserver/test_facade_mode_compatibility.py
+++ b/tests/unit_tests/agentserver/test_facade_mode_compatibility.py
@@ -386,14 +386,16 @@ async def test_handler_pool_manager_preserves_session_flash_binding(
assert expected._adapter.messages[0][0] is request
assert other._adapter.messages == []
assert request.resolved_adapter_mode == stored_adapter
- assert request.params["mode"] == "agent"
+ assert request.params["mode"] == stored_adapter
if stored_adapter == "flash":
assert request.resolved_adapter_source == "session_sticky"
+ # Wait for the real metadata writer before asserting durable mode.
+ await asyncio.wait_for(asyncio.to_thread(session_metadata._METADATA_QUEUE.join), timeout=5)
metadata = session_metadata.get_session_metadata(
"sticky-session", cache_bust=True, enable_writeback=False, sessions_root=tmp_path,
)
assert metadata["adapter_mode"] == stored_adapter
- assert metadata["mode"] == "agent"
+ assert metadata["mode"] == (stored_adapter if incoming_mode else "agent")
@pytest.mark.parametrize("mode,expected,sub_mode", [
@@ -409,3 +411,66 @@ def test_prepared_flash_binding_cannot_override_code_team_or_plan(mode, expected
actual_mode, actual_sub, _ = manager._agent_lookup_from_request(request)
assert (actual_mode, actual_sub) == (expected, sub_mode)
assert request.resolved_adapter_mode == ("code" if expected == "code" else "agent")
+
+
+def standalone_yaml_configuration(monkeypatch, tmp_path):
+ from jiuwenswarm.common import config as config_module
+
+ path = tmp_path / "config.yaml"
+ monkeypatch.setattr(config_module, "get_config_file", lambda: path)
+ config_module.clear_config_cache()
+ yield config_module, path
+ config_module.clear_config_cache()
+
+
[email protected]("env_value,config_enabled,expected", [
+ ("true", False, "flash"), ("false", True, "agent"),
+])
+async def test_standalone_flash_environment_reaches_stream_and_keeps_session_binding(
+ resume_routes, standalone_yaml_configuration, monkeypatch, tmp_path, env_value, config_enabled, expected,
+):
+ routes = resume_routes
+ session_metadata.init_session_metadata(
+ session_id="standalone-env", channel_id="web", mode="agent", work_mode="work",
+ adapter_mode="agent", project_dir=str(tmp_path), sessions_root=tmp_path,
+ )
+ deep = await routes.add("agent")
+ flash = await routes.add("flash")
+ routes.manager.agents["web"] = routes.manager.agents.pop("officeclaw")
+ config_module, config_file = standalone_yaml_configuration
+ config_file.write_text(f"flash:\n enabled: {str(config_enabled).lower()}\n", encoding="utf-8")
+ monkeypatch.setattr(_shared, "get_config", config_module.get_config)
+ monkeypatch.setenv("JIUWENSWARM_FLASH_ENABLED", env_value)
+
+ async def send(request_id):
+ config_module.clear_config_cache()
+ incoming = make_request(
+ "agent.work.normal", session_id="standalone-env", query="hello",
+ work_mode="work", project_dir=str(tmp_path),
+ )
+ incoming.request_id = request_id
+ incoming.channel_id = "web"
+ _, _, prepared = await _default._prepare_code_mode_chat_turn(routes.ctx, incoming, "web")
+ chunks = await _collect(routes.manager.process_message_stream(incoming))
+ assert chunks[-1].is_complete
+ assert not any((c.payload or {}).get("event_type") == "chat.error" for c in chunks)
+ assert prepared is (flash if expected == "flash" else deep)
+ assert incoming.resolved_adapter_mode == expected
+ metadata = session_metadata.get_session_metadata(
+ "standalone-env", cache_bust=True, enable_writeback=False, sessions_root=tmp_path,
+ )
+ assert metadata["adapter_mode"] == expected
+ return incoming
+
+ first = await send("env-first")
+ selected, other = (flash, deep) if expected == "flash" else (deep, flash)
+ assert selected._adapter.messages[0][0] is first
+ assert other._adapter.messages == []
+ if expected == "flash":
+ monkeypatch.setenv("JIUWENSWARM_FLASH_ENABLED", "false")
+ second = await send("env-continue")
+ assert second.resolved_adapter_source == "session_sticky"
+ assert selected._adapter.messages[1][0] is second
+ assert len(routes.created) == 2
diff --git a/tests/unit_tests/agentserver/test_flash_env_routing.py b/tests/unit_tests/agentserver/test_flash_env_routing.py
new file mode 100644
index 0000000000..42f7fc1677
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_flash_env_routing.py
@@ -0,0 +1,121 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""真实 config.yaml 加载到独立部署路由及 PC 显式模式的边界。"""
+
+import pytest
+import yaml
+
+from jiuwenswarm.agents.harness.flash.skill_selection.config import SelectionSettings
+from jiuwenswarm.common import config as config_module
+from jiuwenswarm.common import config_provider as providers
+from jiuwenswarm.common.schema.agent import AgentRequest
+from jiuwenswarm.common.schema.message import ReqMethod
+from jiuwenswarm.dotenv_early import load_dotenv_runtime
+from jiuwenswarm.server.handlers import _shared
+
+
+FLASH_ENV = "JIUWENSWARM_FLASH_ENABLED"
+SKILL_ENV = "JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED"
+
+
[email protected](autouse=True)
+def isolated_configuration(monkeypatch, tmp_path):
+ config_file = tmp_path / "config.yaml"
+ monkeypatch.setattr(config_module, "get_config_file", lambda: config_file)
+ # dotenv 会直接写 os.environ;先登记恢复动作,确保原本缺失的变量也会被清理。
+ for name in (FLASH_ENV, SKILL_ENV):
+ monkeypatch.setenv(name, "")
+ monkeypatch.delenv(name)
+ config_module.clear_config_cache()
+ providers.reset_config_provider()
+ yield config_file
+ config_module.clear_config_cache()
+ providers.reset_config_provider()
+
+
+def make_request(params, channel="web", method=ReqMethod.CHAT_SEND):
+ return AgentRequest(
+ request_id="flash-env-test", channel_id=channel, session_id="flash-env-session",
+ req_method=method, params=dict(params),
+ )
+
+
+def test_standalone_dotenv_reaches_yaml_configuration(monkeypatch, tmp_path):
+ monkeypatch.delenv("JIUWENSWARM_EDITION", raising=False)
+ dotenv = tmp_path / ".env"
+ dotenv.write_text(
+ "JIUWENSWARM_FLASH_ENABLED=true\nJIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED=false\n",
+ encoding="utf-8",
+ )
+ assert load_dotenv_runtime(dotenv)
+ config = config_module.get_config()
+ assert config.get("flash", {}).get("enabled") is True
+ assert SelectionSettings.from_config(config).enabled is False
+
+
[email protected]("method", [ReqMethod.SESSION_CREATE, ReqMethod.CHAT_SEND])
[email protected]("mode", [None, "agent", "agent.work.normal"])
+def test_standalone_creation_and_chat_use_resolved_configuration(monkeypatch, mode, method):
+ monkeypatch.setenv(FLASH_ENV, "true")
+ params = {"work_mode": "work"}
+ if mode is not None:
+ params["mode"] = mode
+ resolved = _shared.resolve_request_runtime_mode(make_request(params, method=method))
+ assert resolved.manager_mode == resolved.adapter_mode == "flash"
+ assert resolved.canonical_mode in {"agent", "agent.work.normal"}
+
+
[email protected]("params,expected", [
+ ({"mode": "agent", "work_mode": "code"}, "code"),
+ ({"mode": "code.normal"}, "code"),
+ ({"mode": "team", "work_mode": "work"}, "agent"),
+ ({"mode": "agent.plan", "work_mode": "work"}, "agent"),
+ ({"mode": "agent.work.plan", "work_mode": "work"}, "agent"),
+ ({"mode": "team.work.plan", "work_mode": "work"}, "agent"),
+])
+def test_environment_keeps_code_team_and_plan_routes(monkeypatch, params, expected):
+ monkeypatch.setenv(FLASH_ENV, "true")
+ assert _shared.resolve_request_runtime_mode(make_request(params)).adapter_mode == expected
+
+
[email protected]("enabled", ["true", "false"])
[email protected]("mode,expected", [(None, "agent"), ("agent.plan", "agent"), ("flash", "flash")])
+def test_pc_foreground_still_uses_explicit_mode(monkeypatch, enabled, mode, expected):
+ monkeypatch.setenv(FLASH_ENV, enabled)
+ request = make_request({"mode": mode, "work_mode": "work"}, channel="officeclaw")
+ assert _shared.resolve_request_runtime_mode(request).adapter_mode == expected
+
+
[email protected]("enabled", ["true", "false"])
+def test_sparse_instance_snapshot_resolves_flash_and_skill_flags(monkeypatch, enabled):
+ from jiuwenswarm.server.runtime.agent_adapter import interface_deep
+
+ monkeypatch.setenv(FLASH_ENV, enabled)
+ monkeypatch.setenv(SKILL_ENV, enabled)
+ sparse = {"react": {"max_iterations": 7}}
+ resolved = interface_deep._resolve_instance_config_base(sparse)
+ expected = enabled == "true"
+ assert resolved.get("flash", {}).get("enabled") is expected
+ assert SelectionSettings.from_config(resolved).enabled is expected
+ assert sparse == {"react": {"max_iterations": 7}}
+
+
[email protected]("channel", ["web", "officeclaw"])
+def test_explicit_flash_is_not_disabled_by_environment(monkeypatch, channel):
+ monkeypatch.setenv(FLASH_ENV, "false")
+ resolved = _shared.resolve_request_runtime_mode(make_request({"mode": "flash"}, channel=channel))
+ assert resolved.adapter_mode == "flash"
+
+
[email protected]("flash", [False, True])
[email protected]("selection", [False, True])
+def test_flash_and_skill_selection_switches_are_independent(
+ isolated_configuration, monkeypatch, flash, selection,
+):
+ monkeypatch.setenv(FLASH_ENV, str(flash).lower())
+ monkeypatch.setenv(SKILL_ENV, str(selection).lower())
+ raw = {"flash": {"enabled": not flash, "skill_selection": {"enabled": not selection}}}
+ isolated_configuration.write_text(yaml.safe_dump(raw), encoding="utf-8")
+ config = config_module.get_config()
+ resolved = _shared.resolve_request_runtime_mode(make_request({"work_mode": "work"}))
+ assert resolved.adapter_mode == ("flash" if flash else "agent")
+ assert SelectionSettings.from_config(config).enabled is selection
diff --git a/tests/unit_tests/agentserver/test_flash_mode_routing.py b/tests/unit_tests/agentserver/test_flash_mode_routing.py
index f104559f2b..becd1724d1 100644
--- a/tests/unit_tests/agentserver/test_flash_mode_routing.py
+++ b/tests/unit_tests/agentserver/test_flash_mode_routing.py
@@ -114,7 +114,7 @@ def test_explicit_plan_entry_keeps_plan_when_flash_enabled(flash_config, channel
assert resolved.is_plan
-def test_legacy_officeclaw_plan_token_obeys_flash_config(flash_config):
+def test_legacy_officeclaw_plan_token_keeps_deep_despite_flash_config(flash_config):
request = make_request(
{"mode": "agent.plan", "work_mode": "work"}, channel="officeclaw",
)
@@ -122,8 +122,8 @@ def test_legacy_officeclaw_plan_token_obeys_flash_config(flash_config):
resolved = _shared.resolve_request_runtime_mode(request)
assert resolved.canonical_mode == "agent"
- assert resolved.manager_mode == "flash"
- assert resolved.adapter_mode == "flash"
+ assert resolved.manager_mode == "agent"
+ assert resolved.adapter_mode == "agent"
assert not resolved.is_plan
@@ -209,7 +209,7 @@ async def test_officeace_request_reaches_flash_factory_and_reuses_facade(
create_instance = AsyncMock()
monkeypatch.setattr(JiuWenSwarm, "create_instance", create_instance)
request = make_request(
- {"mode": "agent", "work_mode": "work", "query": "hello"},
+ {"mode": "flash", "work_mode": "work", "query": "hello"},
channel="officeclaw",
)
@@ -225,7 +225,7 @@ async def test_officeace_request_reaches_flash_factory_and_reuses_facade(
assert facade._adapter_mode == "flash"
second_request = make_request(
- {"mode": "agent", "work_mode": "work", "query": "continue"},
+ {"mode": "flash", "work_mode": "work", "query": "continue"},
channel="officeclaw",
request_id="flash-routing-second",
)
@@ -287,7 +287,7 @@ async def test_flash_enabled_interrupt_answer_returns_to_existing_deep_owner(
selected = await manager._get_agent_for_request(request)
assert selected is deep_owner
- assert request.resolved_adapter_mode == "flash"
+ assert request.resolved_adapter_mode == "agent"
manager.get_agent.assert_not_awaited()
diff --git a/tests/unit_tests/agentserver/test_flash_skill_selection.py b/tests/unit_tests/agentserver/test_flash_skill_selection.py
index 5231d6496c..e276879c0e 100644
--- a/tests/unit_tests/agentserver/test_flash_skill_selection.py
+++ b/tests/unit_tests/agentserver/test_flash_skill_selection.py
@@ -219,13 +219,23 @@ async def test_flash_selection_survives_startup_cleanup_and_config_read(
await harness.rail.after_model_call(ctx)
-def test_shipped_flash_selection_defaults_are_disabled_and_complete():
+def test_shipped_flash_selection_defaults_are_disabled_and_complete(monkeypatch, tmp_path):
from dataclasses import asdict
from jiuwenswarm.common.utils import load_yaml_dict, resolve_shipped_template_config_path
+ from jiuwenswarm.common import config as config_module
+
template = load_yaml_dict(resolve_shipped_template_config_path())
- assert template["flash"]["skill_selection"] == asdict(SelectionSettings())
- assert not SelectionSettings.from_config(template).enabled
+ assert template["flash"]["skill_selection"]["enabled"] == "${JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED:-false}"
+ monkeypatch.setattr(config_module, "get_config_file", lambda: tmp_path / "config.yaml")
+ monkeypatch.delenv("JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED", raising=False)
+ config_module.clear_config_cache()
+ try:
+ config = config_module.get_config()
+ assert config["flash"]["skill_selection"] == asdict(SelectionSettings())
+ assert not SelectionSettings.from_config(config).enabled
+ finally:
+ config_module.clear_config_cache()
@pytest.mark.parametrize("settings", [{"enabled": "true"}, {"enabled": True, "candidate_k": 6},
@@ -1675,3 +1685,41 @@ def test_inverted_bm25_preserves_original_scores():
expected.append(score)
assert index.get_scores(terms) == pytest.approx(expected, rel=1e-14)
assert BM25Okapi([]).get_scores(terms) == []
+
+
[email protected]("enabled", [False, True])
[email protected]("environment", [None, "true", "false"])
+async def test_yaml_environment_controls_real_retrieval_without_rewriting_config(
+ harness, monkeypatch, tmp_path, enabled, environment,
+):
+ from copy import deepcopy
+ from jiuwenswarm.common import config as config_module
+
+ path = tmp_path / "config.yaml"
+ raw = {"flash": {"skill_selection": {"enabled": enabled, "candidate_k": 3}}}
+ path.write_text(yaml.safe_dump(raw), encoding="utf-8")
+ original = path.read_bytes()
+ monkeypatch.setattr(config_module, "get_config_file", lambda: path)
+ monkeypatch.delenv("JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED", raising=False)
+ if environment is not None:
+ monkeypatch.setenv("JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED", environment)
+ config_module.clear_config_cache()
+ try:
+ config = config_module.get_config()
+ harness.config.clear()
+ harness.config.update(deepcopy(config))
+ expected = enabled if environment is None else environment == "true"
+ ctx = context()
+ await harness.rail.before_model_call(ctx)
+ assert (SkillSearchTool.TOOL_NAME in harness.abilities.tools) is expected
+ if expected:
+ assert harness.rail.service.settings.candidate_k == 3
+ result = await harness.rail._search_from_model("制作演示文稿", ["slides"], ctx)
+ assert result["status"] == "candidates"
+ else:
+ assert harness.rail.service is None
+ await harness.rail.after_model_call(ctx)
+ assert path.read_bytes() == original
+ assert config_module.get_config_raw()["flash"]["skill_selection"]["enabled"] is enabled
+ finally:
+ config_module.clear_config_cache()
diff --git a/tests/unit_tests/agentserver/test_officeclaw_explicit_flash.py b/tests/unit_tests/agentserver/test_officeclaw_explicit_flash.py
new file mode 100644
index 0000000000..779a72e731
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_officeclaw_explicit_flash.py
@@ -0,0 +1,180 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""OfficeClaw 显式 Flash 的路由隔离、存量会话与恢复契约。"""
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+
+import pytest
+
+from jiuwenswarm.common.schema.agent import AgentRequest
+from jiuwenswarm.common.schema.message import ReqMethod
+from jiuwenswarm.server.handlers import _default, _shared
+from jiuwenswarm.server.runtime.agent_manager import AgentManager
+from jiuwenswarm.server.runtime.session import session_metadata
+
+
+def request(params, *, method=ReqMethod.CHAT_SEND, channel="officeclaw"):
+ return AgentRequest(
+ request_id="explicit-flash-test",
+ channel_id=channel,
+ session_id="explicit-flash-session",
+ req_method=method,
+ params=dict(params),
+ )
+
+
+def global_flash(monkeypatch):
+ config = {"flash": {"enabled": True}}
+ monkeypatch.setattr(_shared, "get_config", lambda: config)
+ return config
+
+
[email protected]("method", [
+ ReqMethod.CHAT_SEND, ReqMethod.CHAT_RESUME, ReqMethod.CHAT_ANSWER,
+ ReqMethod.SESSION_CREATE,
+])
[email protected]("params,expected", [
+ ({}, "agent"),
+ ({"mode": "agent"}, "agent"),
+ ({"mode": "agent.plan"}, "agent"),
+ ({"mode": "agent", "work_mode": "work"}, "agent"),
+ ({"mode": "agent.work.normal", "work_mode": "work"}, "agent"),
+ ({"mode": "flash"}, "flash"),
+])
+def test_foreground_mode_is_explicit(global_flash, method, params, expected):
+ resolved = _shared.resolve_request_runtime_mode(request(params, method=method))
+ assert resolved.manager_mode == expected
+ assert resolved.adapter_mode == expected
+
+
[email protected]("channel", ["web", "tui", "__cron__"])
+def test_other_channels_keep_implicit_flash(global_flash, channel):
+ resolved = _shared.resolve_request_runtime_mode(
+ request({"mode": "agent"}, channel=channel),
+ )
+ assert resolved.manager_mode == "flash"
+ assert resolved.canonical_mode == "agent"
+
+
[email protected]("source", ["cron", "heartbeat", "proactive"])
+def test_background_officeclaw_keeps_existing_strategy(global_flash, source):
+ incoming = request({"mode": "agent"})
+ incoming.metadata = {"source": source}
+ assert _shared.resolve_request_runtime_mode(incoming).manager_mode == "flash"
+
+
[email protected]("mode", ["flash.fast", "flash.normal", "flash.unknown"])
+def test_unimplemented_flash_submode_is_rejected(global_flash, mode):
+ with pytest.raises(ValueError, match="unsupported OfficeClaw mode"):
+ _shared.resolve_request_runtime_mode(request({"mode": mode}))
+
+
+def test_explicit_flash_does_not_read_global_switch(monkeypatch):
+ config = Mock(side_effect=AssertionError("global switch must not be read"))
+ monkeypatch.setattr(_shared, "get_config", config)
+ resolved = _shared.resolve_request_runtime_mode(request({"mode": "flash"}))
+ assert resolved.canonical_mode == "flash"
+ assert resolved.manager_mode == resolved.adapter_mode == "flash"
+ config.assert_not_called()
+
+
+def test_active_plan_wins_over_relay_default_flash(global_flash):
+ incoming = request({"mode": "flash", "work_mode": "work"})
+ _shared._plan_active_sessions.add(incoming.session_id)
+ try:
+ resolved = _shared.resolve_request_runtime_mode(incoming)
+ assert (resolved.manager_mode, resolved.sub_mode) == ("agent", "plan")
+ assert resolved.is_plan
+ assert resolved.adapter_mode == "agent"
+ finally:
+ _shared._plan_active_sessions.discard(incoming.session_id)
+
+
[email protected]("stored_mode,adapter,incoming_params,expected_mode,expected_sub", [
+ ("flash", "flash", {"query": "continue"}, "flash", None),
+ ("flash", "flash", {
+ "source": "permission_interrupt", "answers": [],
+ "request_id": "original-request",
+ }, "flash", None),
+ ("code.normal", "code", {
+ "source": "permission_interrupt", "answers": [],
+ "request_id": "child-request",
+ }, "code", "normal"),
+ ("agent", "flash", {"mode": "agent.plan", "query": "continue"}, "flash", None),
+ ("agent.work.plan", "agent", {"mode": "flash", "query": "continue"}, "agent", "plan"),
+ ("agent", "agent", {"mode": "agent.plan", "query": "continue"}, "agent", None),
+ ("agent", "flash", {
+ "source": "permission_interrupt", "answers": [],
+ "request_id": "old-flash-request",
+ }, "flash", None),
+ ("agent.work.normal", "flash", {
+ "mode": "flash", "source": "permission_interrupt", "answers": [],
+ "request_id": "old-flash-explicit-request",
+ }, "flash", None),
+ ("agent.work.plan", "flash", {
+ "mode": "flash", "query": "continue plan",
+ }, "agent", "plan"),
+ ("agent", "agent", {
+ "mode": "flash", "source": "permission_interrupt", "answers": [],
+ "request_id": "old-deep-request",
+ }, "agent", None),
+ ("code.normal", "code", {
+ "mode": "flash", "source": "permission_interrupt", "answers": [],
+ "request_id": "hosted-child-request",
+ }, "code", "normal"),
+])
+async def test_prepare_and_tenant_lookup_keep_same_owner_mode(
+ global_flash, monkeypatch, tmp_path, stored_mode, adapter,
+ incoming_params, expected_mode, expected_sub,
+):
+ incoming = request(incoming_params)
+ metadata = {
+ "mode": stored_mode, "adapter_mode": adapter, "work_mode": "work",
+ }
+ monkeypatch.setattr(_default, "_sessions_dir_for_request", lambda _: tmp_path)
+ monkeypatch.setattr(session_metadata, "get_session_metadata", lambda *a, **kw: metadata)
+ sync = Mock(return_value=None)
+ monkeypatch.setattr(_default, "_sync_chat_request_metadata", sync)
+ selected = object()
+ manager = SimpleNamespace(
+ wait_for_session_prewarm=AsyncMock(),
+ get_agent=AsyncMock(return_value=selected),
+ )
+ ctx = SimpleNamespace(services=SimpleNamespace(agent_manager=manager))
+
+ mode, sub, agent = await _default._prepare_code_mode_chat_turn(ctx, incoming, "officeclaw")
+ assert (mode, sub, agent) == (expected_mode, expected_sub, selected)
+ assert manager.get_agent.await_args.kwargs["mode"] == expected_mode
+
+ # 真实租户链会二次解析;旧 Flash 亲和与恢复出的 Plan 都必须保持。
+ tenant = AgentManager(agent_id="officeace", service_id="officeace", workspace_key="officeace")
+ lookup_mode, lookup_sub, _ = tenant._agent_lookup_from_request(incoming)
+ assert (lookup_mode, lookup_sub) == (expected_mode, expected_sub)
+ assert incoming.resolved_adapter_mode == expected_mode
+ if expected_mode == "flash":
+ assert incoming.params["mode"] == "flash"
+
+
+def test_manager_restores_mode_for_officeclaw_followup(global_flash, monkeypatch):
+ monkeypatch.setattr(session_metadata, "get_session_metadata", lambda *a, **kw: {
+ "mode": "flash", "adapter_mode": "flash", "work_mode": "work",
+ })
+ manager = AgentManager(agent_id="officeace", service_id="officeace", workspace_key="officeace")
+ incoming = request({"query": "continue"})
+ assert manager._agent_lookup_from_request(incoming)[:2] == ("flash", None)
+ assert incoming.params["mode"] == "flash"
+
+
+def test_stale_flash_affinity_does_not_override_code_work_mode(global_flash, monkeypatch):
+ monkeypatch.setattr(session_metadata, "get_session_metadata", lambda *a, **kw: {
+ "mode": "agent", "adapter_mode": "flash", "work_mode": "code",
+ })
+ manager = AgentManager(agent_id="officeace", service_id="officeace", workspace_key="officeace")
+ incoming = request({
+ "mode": "flash", "work_mode": "code", "source": "permission_interrupt",
+ "answers": [], "request_id": "code-request",
+ })
+ assert manager._agent_lookup_from_request(incoming)[:2] == ("code", "normal")
+ assert incoming.resolved_adapter_mode == "code"
diff --git a/tests/unit_tests/channel/test_trajectory_http.py b/tests/unit_tests/channel/test_trajectory_http.py
index 0192ae7d24..9785076545 100644
--- a/tests/unit_tests/channel/test_trajectory_http.py
+++ b/tests/unit_tests/channel/test_trajectory_http.py
@@ -716,6 +716,7 @@ async def test_http_accepts_team_sessions_with_team_name(tmp_path: Path) -> None
"agent.work.plan",
"agent.code.normal",
"agent.code.plan",
+ "flash",
],
)
async def test_http_accepts_new_single_agent_canonical_modes(
diff --git a/tests/unit_tests/common/test_flash_env_config.py b/tests/unit_tests/common/test_flash_env_config.py
new file mode 100644
index 0000000000..e4485ed71e
--- /dev/null
+++ b/tests/unit_tests/common/test_flash_env_config.py
@@ -0,0 +1,139 @@
+"""Flash 环境占位符经真实 YAML/provider 加载后统一为布尔配置。"""
+
+from copy import deepcopy
+
+import pytest
+import yaml
+
+from jiuwenswarm.common import config as config_module
+from jiuwenswarm.common import config_provider as providers
+from jiuwenswarm.common import local_env_config as env_config
+
+
+FLASH_ENV = "JIUWENSWARM_FLASH_ENABLED"
+SKILL_ENV = "JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED"
+
+
+def config_file(monkeypatch, tmp_path):
+ path = tmp_path / "config.yaml"
+ monkeypatch.setattr(config_module, "get_config_file", lambda: path)
+ monkeypatch.delenv(FLASH_ENV, raising=False)
+ monkeypatch.delenv(SKILL_ENV, raising=False)
+ providers.reset_config_provider()
+ config_module.clear_config_cache()
+ yield path
+ config_module.clear_config_cache()
+ providers.reset_config_provider()
+
+
+def switches(config):
+ flash = config.get("flash", {})
+ return flash.get("enabled"), flash.get("skill_selection", {}).get("enabled")
+
+
+def test_shipped_placeholders_resolve_to_false_without_modifying_raw_config(config_file):
+ raw = config_module.get_config_raw()
+ assert switches(raw) == (f"${{{FLASH_ENV}:-false}}", f"${{{SKILL_ENV}:-false}}")
+ resolved = config_module.get_config()
+ assert all(value is False for value in switches(resolved))
+ assert config_module.get_config_raw() == raw
+ assert not config_file.exists()
+
+
[email protected]("name", [FLASH_ENV, SKILL_ENV])
[email protected]("raw,expected", [
+ ("true", True), (" TRUE ", True), ("1", True), ("yes", True), ("on", True),
+ ("false", False), (" FALSE ", False), ("0", False), ("no", False), ("off", False),
+ ("", False), ("invalid", False),
+])
+def test_placeholder_value_is_boolean_and_other_switch_stays_off(config_file, monkeypatch, name, raw, expected):
+ monkeypatch.setenv(name, raw)
+ flash, skill = switches(config_module.get_config())
+ if name == FLASH_ENV:
+ assert flash is expected
+ assert skill is False
+ else:
+ assert flash is False
+ assert skill is expected
+
+
[email protected]("enabled", [False, True])
[email protected]("environment", [None, "true", "false"])
+def test_legacy_booleans_are_environment_fallbacks_without_disk_changes(
+ config_file, monkeypatch, enabled, environment,
+):
+ raw = {"flash": {"enabled": enabled, "skill_selection": {"enabled": enabled, "candidate_k": 3}}}
+ config_file.write_text(yaml.safe_dump(raw), encoding="utf-8")
+ original = config_file.read_bytes()
+ if environment is not None:
+ monkeypatch.setenv(FLASH_ENV, environment)
+ monkeypatch.setenv(SKILL_ENV, environment)
+ expected = enabled if environment is None else environment == "true"
+ resolved = config_module.get_config()
+ assert all(value is expected for value in switches(resolved))
+ assert resolved.get("flash", {}).get("skill_selection", {}).get("candidate_k") == 3
+ assert config_file.read_bytes() == original
+ assert all(value is enabled for value in switches(config_module.get_config_raw()))
+
+
+def test_empty_environment_preserves_legacy_true(config_file, monkeypatch):
+ config_file.write_text("flash:\n enabled: true\n skill_selection:\n enabled: true\n", encoding="utf-8")
+ monkeypatch.setenv(FLASH_ENV, "")
+ monkeypatch.setenv(SKILL_ENV, "")
+ assert all(value is True for value in switches(config_module.get_config()))
+
+
+def test_custom_placeholder_defaults_and_unrelated_strings_are_preserved(config_file, monkeypatch):
+ config_file.write_text(
+ "flash:\n enabled: ${JIUWENSWARM_FLASH_ENABLED:-true}\n"
+ " skill_selection:\n enabled: ${JIUWENSWARM_FLASH_SKILL_SELECTION_ENABLED:-false}\n",
+ encoding="utf-8",
+ )
+ assert switches(config_module.get_config()) == (True, False)
+ monkeypatch.setenv("FLASH_TEST_TEXT", "false")
+ assert config_module.resolve_env_vars("${FLASH_TEST_TEXT}") == "false"
+ assert config_module.resolve_env_vars("${FLASH_TEST_MISSING:-false}") == "false"
+ assert config_module.resolve_env_vars("${FLASH_TEST_MISSING-false}") == "false"
+
+
+def test_sandbox_values_survive_sealed_task_overlay_and_child_export(config_file, monkeypatch):
+ monkeypatch.setenv(FLASH_ENV, "true")
+ monkeypatch.setenv(SKILL_ENV, "false")
+ assert {FLASH_ENV, SKILL_ENV} <= env_config.SPAWN_ENV_KEYS
+ namespace = env_config.bind_agent_env_ns("flash-env-test", "agent")
+ overlay = env_config.bind_task_env_overlay({FLASH_ENV: "false", SKILL_ENV: "true"})
+ try:
+ assert switches(config_module.get_config()) == (True, False)
+ exported = env_config.export_agent_environ("flash-env-test", "agent")
+ assert exported.get(FLASH_ENV) == "true"
+ assert exported.get(SKILL_ENV) == "false"
+ finally:
+ env_config.reset_task_env_overlay(overlay)
+ env_config.reset_agent_env_ns(namespace)
+
+
+def test_provider_configuration_uses_same_resolution_and_keeps_input(config_file, monkeypatch):
+ supplied = {"flash": {"enabled": False, "skill_selection": {"enabled": f"${{{SKILL_ENV}:-false}}"}}}
+ original = deepcopy(supplied)
+
+ class Provider(providers.ConfigProvider):
+ def get_process_config(self):
+ return supplied
+
+ providers.register_config_provider(Provider())
+ monkeypatch.setenv(FLASH_ENV, "true")
+ monkeypatch.setenv(SKILL_ENV, "true")
+ assert all(value is True for value in switches(config_module.get_config()))
+ assert supplied == original
+
+
+def test_cache_invalidation_reloads_environment_and_retains_placeholders(config_file, monkeypatch):
+ monkeypatch.setenv(FLASH_ENV, "true")
+ monkeypatch.setenv(SKILL_ENV, "true")
+ assert all(value is True for value in switches(config_module.get_config()))
+ monkeypatch.setenv(FLASH_ENV, "false")
+ monkeypatch.setenv(SKILL_ENV, "false")
+ config_module.clear_config_cache()
+ assert all(value is False for value in switches(config_module.get_config()))
+ assert switches(config_module.get_config_raw()) == (f"${{{FLASH_ENV}:-false}}", f"${{{SKILL_ENV}:-false}}")
diff --git a/tests/unit_tests/test_mode_matrix.py b/tests/unit_tests/test_mode_matrix.py
index 6c35c571ec..bc07620f2e 100644
--- a/tests/unit_tests/test_mode_matrix.py
+++ b/tests/unit_tests/test_mode_matrix.py
@@ -1,5 +1,7 @@
"""Web 组合模式解析与 TUI 历史模式直通的回归测试。"""
+from functools import partial
+
import pytest
from jiuwenswarm.common.schema.agent import AgentRequest
@@ -27,7 +29,9 @@ from jiuwenswarm.server.agent_ws_server import (
def _resolve(params):
- return resolve_request_mode(params, resolve_agent_request_mode)
+ # 模式矩阵验证协议归一,不依赖开发机的 flash.enabled 部署配置。
+ legacy = partial(resolve_agent_request_mode, allow_flash_default=False)
+ return resolve_request_mode(params, legacy)
def test_request_uses_current_merged_agent_mode_semantics():
@@ -416,6 +420,11 @@ def test_single_agent_mode_rejects_new_team_canonical_names(mode):
assert not is_single_agent_mode(mode)
+def test_explicit_flash_is_single_agent_mode():
+ assert is_single_agent_mode("flash")
+ assert not is_single_agent_mode("flash.fast")
+
+
def test_base_mode_without_plan_is_identity_for_normal_modes():
assert base_mode_without_plan("agent") == "agent"
assert base_mode_without_plan("code.team") == "code.team"