mirror of
https://github.com/EvovexAI/EvoFlow.git
synced 2026-11-27 23:19:47 +08:00
main
2
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
2fb5298fbc |
release: 1.0.7 — 知识库归一 + 角色工具精准管控 (#49)
* fix(startup): short-circuit "warming_up" lockup during cold start
Two changes to reduce the post-startup "everything frozen" window in EvoPanel:
1. backend/app/gateway/background_startup.py
Reduce default LangGraph mount delay from 25s to 5s.
25s was tuned for first-paint; 5s is enough for that and clears
"/api/langgraph/ok warming_up" before the 30s panel poll probe.
Override via EVOFLOW_LG_MOUNT_DELAY_SEC=0 to mount inline.
2. evopanel/src/lib/service-health.js
Split the cold-start "extended=false" path from the real LG warming:
- phase=initializing -> DEGRADED (LG engine really not ready, messages 503)
- phase=ready + extended=false -> HEALTHY (extended routers registering
in background; core API/models/agents/LG runs are already live)
The old code grouped both into "DEGRADED + 服务正在初始化中" banner, which
blocked the chat panel during the entire 5-25s window.
3. evopanel/tests/service-health.test.js
Update + add tests for the split behavior; 14/14 pass.
* fix(kb-search): prevent KB search from freezing the whole Gateway
Customer-service roles that search the local knowledge base (sentence-transformers
embedding) were freezing the entire Gateway for ~45s on first query. Hang
diagnostics show all ~40 default anyio thread-pool workers parked on
sentence_transformers → sklearn → scipy → _fblas import chain, which blocks every
concurrent sync route (chat streams, KB uploads, model calls).
Three changes:
1. backend/app/gateway/background_startup.py
Shorten EVOFLOW_EMBEDDING_WARMUP_DELAY_SEC default from 30s to 5s.
5s lines up with the LG mount delay; startup then completes the heavy
sentence_transformers + sklearn + scipy import chain BEFORE the user can
fire a KB search. Override via env (e.g. set to 0 to disable warmup).
2. backend/packages/harness/evoflow/knowledge/embedding/local_provider.py
Wrap `asyncio.to_thread(_encode)` in `asyncio.wait_for(..., timeout=30s)`.
Even after warmup, a long GIL-bound batch (huge dataset or stuck numpy op)
can still hold a thread for tens of seconds. The timeout converts that
into an EmbeddingError so anyio releases the worker immediately and
concurrent routes are not blocked. Default 30s; override via
EVOFLOW_LOCAL_EMBED_BATCH_TIMEOUT_SEC.
3. backend/app/gateway/app.py
Bump anyio default thread-limiter total_tokens from 40 to 80 in lifespan
(configurable via EVOFLOW_ANYIO_THREAD_LIMIT). Doubles concurrent sync
capacity so a single GIL-bound call cannot starve the pool, and works as
defense-in-depth even when warmup is skipped.
Verification:
- /health/liveness 200 in 40ms
- /api/models 200 in 50ms
- /api/knowledge/search 200 in 1.35s (after warmup import completes)
- python -c "from anyio import to_thread; ..." confirms total_tokens is
writable in event loop context
- AST syntax check on all 3 files
Reproduce original symptom:
1. Fresh dev session with a customer-service role bound to a local
embedding KB (vendor=local, e.g. baai/bge-small-zh-v1.5)
2. Open chat, ask "查询 KB 信用卡年费"
3. First KB search triggers `from sentence_transformers import
SentenceTransformer` in anyio worker thread; import chain pulls
sklearn/scipy/scipy.linalg._fblas. While that import holds one worker,
any concurrent sync route (chat SSE, /health/ready, /api/models)
competes for the remaining 39. Hang-diagnostics dumps
`event_loop_stall lag=45s reason=event_loop_stall` repeatedly.
4. After ~4-30s the import completes; subsequent KB searches are fast,
but the freeze window already broke the chat surface.
* feat(agents): add KbInjectionConfig dataclass and extra_json persistence
Introduces a per-agent KB injection config dataclass with sensible defaults:
- mode: off/auto/agent/both (default auto)
- top_k (24) / agent_top_k (12)
- score_threshold, max_inject_tokens (12000), recall_multiplier (6)
- retrieval mode (vector/hybrid/rerank), bm25_weight, reranker
- timeout_sec, on_failure strategy
Stored in evoflow_agents.extra_json under 'kb_injection' key. Helpers:
- KbInjectionConfig.from_dict / to_dict with safe defaults
- get_agent_extra_json / upsert_agent_extra_json on config repo
- get_agent_kb_injection_config / get_agent_kb_vault_ids on agents_config
No migration needed (extra_json column already exists).
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(middleware): add KbInjectionMiddleware for auto KB context injection
New middleware runs after SkillsInjectionMiddleware in the lead agent chain:
- Resolves agent_code + kb_injection config from runtime context
- Skip conditions: mode=off, no bound vault_ids, empty query,
proactive runs (session_key starts with 'proactive:')
- Parallel KB search across all bound vaults (asyncio.gather)
- Token-cap assembly (~1.5 chars/token for CJK)
- Result injected as HumanMessage(name='evf_kb_injection') in messages
- Updates injected_sections ContextVar for UI detail modal
- Sync + async paths (wrap_model_call and awrap_model_call)
- timeout_sec + on_failure='ignore' guarantees never block the agent
Existing KB provider (ObsidianKnowledgeProvider.search) already
implements hybrid (FTS5 + vector + RRF) so no retrieval changes needed.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(proactive): plumb kb_injection through employee hire + update paths
- ProactiveRoleConfig gets kb_injection: dict[str, Any]
- update_role: parses kb_injection via KbInjectionConfig.from_dict,
validates, and stores in cfg.kb_injection
- _hire_existing_agent: same flow on hire
- New _persist_agent_kb_injection: mirrors cfg.kb_injection into
evoflow_agents.extra_json['kb_injection'] so the live middleware
can read it on every model call
- agent config cache invalidated on update so KB config is fresh
- _role_detail exposes kb_injection to API consumers
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(evopanel): role-edit sheet adds KB injection config section
New '知识库检索配置' section in the employee edit panel:
- mode chips: 自动注入 / Agent 工具调用 / 两者并行 / 关闭 (default auto)
- subfields: top_k (24), agent_top_k (12), score_threshold,
max_inject_tokens (12000), recall_multiplier (6), timeout_sec (8)
- retrieval mode chips: hybrid (vec 0.7 + BM25 0.3) / vector / rerank
- BM25 weight slider + on_failure select (ignore/abort)
- New CSS for .hire-row-split and .hire-subfield layouts
- Binds chip-row state to hidden input so update payload is well-formed
- Includes '知识库检索配置已修改' in change summary
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(kb-injection): mirror role knowledge_vault_ids into agent extra_json
The role config (ProactiveRoleConfig.knowledge_vault_ids) and the agent
config (AgentConfig.knowledge_vault_ids) are two separate storage paths.
Vault IDs set via the employee hire/update form land on the role config,
but the live KbInjectionMiddleware reads from the agent config — so it
always saw an empty vault list and silently skipped auto-injection
(agents fell back to their 'knowledge' tool call).
Fix:
- update_role / _hire_existing_agent now mirror knowledge_vault_ids into
evoflow_agents.extra_json['knowledge_vault_ids'] (same channel as
kb_injection)
- _persist_agent_kb_vault_ids helper writes only the role's vault list,
preserving other extra_json keys
- get_agent_kb_vault_ids now reads from extra_json first (authoritative
for live middleware), then falls back to AgentConfig for backwards
compat with agents whose vaults are set directly on AgentConfig
- backfill_agent_kb_vault_ids runs on every startup via
sync_skills_then_merge_baseline_for_lead_family — idempotent, mirrors
every existing role's vault IDs into the agent's extra_json
- KbInjectionMiddleware._should_inject now logs (level: warning on
empty-vault skip, debug elsewhere) so silent skips are diagnosable
After upgrade + restart, existing roles with bound vaults will pick up
auto-injection on the very next user message — no role edit required.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(tools): drop agent-mode system tools from subagents/employees by default
Subagents and proactive employees were force-bound with AGENT_MODE_SYSTEM_TOOL_NAMES
(`platform`, `panel_set`, etc.) — admin / side-panel control tools that are
needed only by the main lead agent. This cluttered every employee's tool list
and let the model attempt admin actions it should never run.
Change:
- Subagents / custom / hired employees no longer mount
AGENT_MODE_SYSTEM_TOOL_NAMES by default.
- `main` lead agent still mounts them (admin chat console needs them).
- xiaomi already had its own lean surface; unchanged.
- Opt-in per role via `kb_injection.mount_platform_tools=true` in the
employee edit sheet (advanced toggle — only the main chat console needs it).
- Logged on drop for diagnostics: `[Tools] dropped N agent-mode system
tools (platform/panel_set) for agent=X type=Y — opt-in via ...`.
UI:
- New toggle in '知识库检索配置' form:
挂载平台工具 (platform / panel_set) — default off
- CSS: new .hire-toggle rule for inline checkbox row
Default behavior is now: employee uses KB / agent-tools / skills without
exposing admin surface. Manual opt-in available for special cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(stream): push KB citations SSE frame before first model token
The KbInjectionMiddleware already prepends a knowledge-context HumanMessage so
the model can quote from retrieved snippets, but the citations themselves were
invisible to the live chat panel. The user only ever saw the model's response;
they couldn't tell which KB chunks the agent consulted, or hover/jump to the
source.
Plumb the citations metadata onto the SSE channel so the chat UI can render
Perplexity-style inline [1][2] markers and an expandable references card.
Pipeline:
1. KbInjectionMiddleware._should_inject now also resolves thread_id from
runtime context (set by make_lead_agent from cfg.thread_id).
2. _do_kb_search returns (context_string, citations_results) -- results already
sorted by score desc and pre-truncated to top_k.
3. After the search returns, both wrap_model_call (sync) and awrap_model_call
(async) push a kb_citations EVF frame onto the thread's inject queue via
the new kb_citations_publisher. Emit happens before yielding to the model so
the live stream sees citations before the first token lands.
4. session_stream_inject.format_evf_direct_frame wraps the payload as
event:evf / data:{"type":"kb_citations","data":...}, already in the existing
EVF wire format. Frontend EVF dispatcher in ws-client.js surfaces it both
as a self-emitted 'kb_citations' event (for js subscribers) and via the
opts.onKbCitations callback (for inline-tuned consumers).
5. Proactive / background-worker runs have no live thread; the publisher's
no-op-by-design path returns gracefully without raising.
Wire payload shape (per citation): index (1-based, matches inline [N] anchor in
markdown), title, path, vault_id, doc_id, score, snippet_excerpt (240 chars).
Frontend markup rendering is intentionally not bundled here -- that is a
follow-up change in ChatApp.tsx markdown pipe. This commit enables the event
end-to-end; any existing subscriber of the EVF stream can now consume
citations metadata without further plumbing.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(stream): surface KB injection activity + citations on ag-ui stream
The chat panel never knew KB was consulted on a turn. The
KbInjectionMiddleware ran silently: even when fully successful, the
live AG-UI wire carried no kb_injection activity tick and no per-doc
citations payload. The user only ever saw the model's response and
had no idea which documents were referenced.
Two coupled leaks:
1. The middleware does not call ``emit_agent_activity`` so the live
activity ticker in the right pane shows nothing.
2. ``evf_payload_to_agui_events`` matched only a fixed enum
(``thread_state``, ``usage``, ``custom``, ``_debug_upstream``) and
silently fell through for every other ``t`` value -- including
our new ``kb_citations`` EVF inject payload, which was being
dropped on the floor between the search and the model call.
Fix:
- ``KbInjectionMiddleware`` (sync + async wrappers) emits an
``emit_agent_activity(thread_id, kind='kb_injection', detail=...)``
tick after the search completes, regardless of result count:
"kb_injection 检索到 N 条 (X chars)" on success,
"kb_injection 未命中 (mode=off / 无库 / 检索失败)" otherwise. Always
at least one trace signal per middleware invocation.
- ``evf_payload_to_agui_events`` gains a fallthrough handler for
``t == "kb_citations"`` that emits ``{type: CUSTOM, name:
kb_citations, value: payload}`` so the references data reaches the
AG-UI wire mirror.
- ``ws-client.dispatchAgUiWireFrame`` recognizes the new
``CUSTOM(name=kb_citations)`` frame and surfaces it via
``self._emitEvent('chat', { state: 'kb_citations', ... })``. New
subscribers can hook in.
User-visible result on next turn (after backend restart):
- Right pane activity header shows the kb_injection tick.
- Chat event bus receives ``kb_citations`` with structured citations
metadata (index/title/path/vault_id/score/snippet_excerpt) before
the first model token. Front-end rendering (Perplexity-style [1][2]
inline markers) remains the follow-up in ChatApp.tsx -- this commit
only plumbs the signal.
Co-authored-by: Cursor <cursoragent@cursor.com>
* chore(kb-injection): structured service-log summaries with timings + hits
The KbInjectionMiddleware was effectively a black box from the operator's
seat: the only signal it produced on a normal run was a single
``assembled context vaults=N results=M chars=K query='...'`` line at
INFO level, and silent ``logger.debug`` on every skip path. Diagnosing
"why did this turn not consult KB?" required enabling debug logging and
manually correlating with the chat event bus.
This commit centralizes every operational signal through a single
``_log_summary`` helper so a grep on the service log tells the whole
story without log-level gymnastics.
Emitted on every middleware invocation:
- Decision: ``ok`` / ``search_error`` / ``no_hits`` /
``skip_mode_off`` / ``skip_no_vault`` / ``skip_empty_query`` /
``skip_proactive``.
- Per-call: agent_code, thread_id (8-char prefix), mode, top_k,
score_threshold, timeout_sec, retrieval, reranker, bound vault_ids,
query preview (80 chars).
- Per-result (success only): hit count, injected_chars, elapsed_ms,
plus top-3 hits each on its own line as
``hit[1] 'title' | vault=X | score=0.871`` and a final
``…and N more`` line.
- Per-vault DEBUG: each vault's individual wall-clock time, hits, mode
and rerank flags. ``KB search timed out`` and ``KB search failed``
now carry the elapsed_ms plus exc_info so the traceback is captured.
Log levels:
- INFO on a real injection (operator wants confirmation)
- WARNING on a misconfig path (mode=off, no bound vaults, no_hits)
- WARNING on search_error (with exc_info)
- DEBUG on proactive / empty-query skips (high-volume, expected)
Sample output (single OK run)::
INFO KbInjection: agent=main thread=3c80fe46 decision=ok mode=auto
top_k=5 threshold=0.5 timeout=8s retrieval=hybrid rerank=bge
vaults=[main,ops] query='how to deploy evoflow' hits=4
injected_chars=1200 elapsed=312.7ms
INFO hit[1] 'Deploy Guide' | vault=main | score=0.871
INFO hit[2] 'Permissions Matrix' | vault=ops | score=0.710
INFO hit[3] 'Runbook' | vault=main | score=0.650
INFO …and 1 more
Sample misconfig::
WARNING KbInjection: agent=main thread=3c80fe46 decision=skip_no_vault
mode=auto top_k=24 threshold=0.0 timeout=8s retrieval=hybrid
rerank=none query='how to deploy'
Sample error::
WARNING KbInjection: agent=main thread=3c80fe46 decision=search_error
… err=TimeoutError: sync kb search wall-clock exceeded 9s
(followed by full traceback)
No behavior change. Just makes the wire live again.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(kb-injection): repair vault backfill module path + unblock proactive chat
Two root causes found by inspecting the live log + evoflow.db:
1. **Backfill broken.** ``backfill_agent_kb_vault_ids`` imported
``evoflow.proactive.repository`` (singular) — that module doesn't exist,
the real one is ``evoflow.proactive.repositories`` (plural). The function
silently ``return summary`` on every startup, so no ProactiveRole's
``config.knowledge_vault_ids`` ever made it into
``evoflow_agents_v6.extra_json``. Log shows the same WARNING every 10 min
for the past 24h: ``No module named 'evoflow.proactive.repository'``.
Fix the import. Once the gateway restarts, every role whose
``config.knowledge_vault_ids`` is non-empty gets mirrored automatically.
2. **Proactive guard too coarse.** ``_should_inject`` skipped every
``session_key.startswith("proactive:")`` — including user-driven chat
into ``proactive:{agent_code}:chat:{ts}`` sessions. The customer-service
thread the operator tested was exactly this kind of session, so KB was
never consulted. Switch to ``is_proactive_duty_run`` which returns True
only when ``triggered_by=proactive_engine`` or ``proactive_process=True``
is set in runtime context — i.e. the unattended engine patrol. User chat
into an employee session is no longer skipped, so the operator can see
what the employee would otherwise consult on its own duty loop.
New ``decision=skip_proactive_duty`` for the new skip path; ``DEBUG`` level
(expected, not a misconfig).
The original ``decision=skip_proactive`` decision is gone — the only
session_key shape that triggered it is now correctly identified via the
``proactive_*`` runtime flags instead.
No behavior change for non-proactive chat or non-proactive agents.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(kb-injection): route vault_ids through owned KB before Obsidian fallback
The middleware was calling ``ObsidianKnowledgeProvider.search(vault_id, ...)``
for every bound vault. The customer-service role binds ``evoflow-user-guide`` —
which is **the legacy alias** of the in-house owned KB
``kb_builtin_user_guide`` (70 docs, table-backed), not an Obsidian vault.
Two observable symptoms:
- Logs: ``obsidian vault 'evoflow-user-guide' MCP fatal:
Cannot open database because the directory does not exist`` — the
``obsidian-hybrid-search`` MCP server was crashing because the
alias-only ``evoflow-user-guide`` config pointed at a path that never
existed on disk.
- Search returned 0 hits because the only path the middleware took
was the broken Obsidian one; the actual data lives in
``C:\Users\admin\.evoflow-dev\knowledge\owned.sqlite`` + the per-KB
sqlite under ``knowledge/kbs/*``.
Resolution order in ``_do_kb_search`` per vault_id:
1. ``kb_bases.id`` exact match → ``owned_service.search``. This catches
agents that bind ``kb_builtin_user_guide`` directly.
2. ``kb_bases.sync_vault_id`` match → ``owned_service.search``. This
catches the legacy ``evoflow-user-guide`` alias (used by the role
binding UI).
3. Fall through to ``ObsidianKnowledgeProvider.search`` for real
Obsidian / Markdown vaults.
Score normalization now reads ``rrfScore | vectorScore | fulltextScore
| score`` (in priority order) so hybrid-mode hits get a non-zero score
and the top-k truncation works correctly. Older code only read ``score``,
which was 0 for most hits and broke ordering.
After this commit, restarting the gateway + sending a message into the
customer-service proactive chat thread should produce a log line like:
```
INFO KbInjection: agent=customer-service ... decision=ok ...
top_k=24 threshold=0.0 timeout=8s retrieval=hybrid rerank=none
vaults=['evoflow-user-guide->kb_builtin_user_guide'] ...
```
instead of the previous ``skip_no_vault`` (because the BoundVault check
was the only path that *could* run).
No change to ``_should_inject`` skip rules or activity tick behavior.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(kb-injection): drop Obsidian provider — owned KB only
User feedback: the in-house self-hosted knowledge base is the only source
of truth. The previous commit added an Obsidian fallback for ``vault_id``
lookups, but that path was both dead (the ``obsidian-hybrid-search`` MCP
server kept crashing on the legacy ``evoflow-user-guide`` alias that
pointed at a non-existent directory) and not wanted: even when the MCP
booted, hitting an Obsidian vault duplicated data already in
``owned.sqlite``.
Removed:
- ``search_obsidian`` and the ``ObsidianKnowledgeProvider.search`` call
path in ``_do_kb_search``.
- ``_resolve_kind`` was reduced to ``_resolve_kb_id`` returning just the
owned ``kb_id`` (or ``None``).
Kept:
- The two resolution branches that actually find the data:
1. ``kb_bases.id`` exact match.
2. ``kb_bases.sync_vault_id`` alias match (covers
``evoflow-user-guide`` → ``kb_builtin_user_guide``).
- A single warning log per unbound ``vault_id`` so misconfigured role
bindings are visible without flooding logs on every turn.
- All scoring normalization (``rrfScore | vectorScore | fulltextScore
| score``) and the parallel fan-out / score-descending sort.
No change to ``_should_inject``, activity tick, or citations publisher.
Verified end-to-end against the live DB:
- customer-service bound to ``evoflow-user-guide`` → 20 hits from
``kb_builtin_user_guide`` (70 docs total) in ~1.6s.
- Unbound vault id → warning log, no Obsidian attempt, no MCP boot.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(kb-injection): eliminate deadlock in wrap_model_call, fix async timeout handling
Root cause of the hang at `awrap_model_call.pre → DynamicSystemPrompt…`
(the UI stall with no further activity after "准备中…") was a deadlock in
the sync ``wrap_model_call`` path:
ThreadPoolExecutor → _sync_search() → asyncio.run(_do_kb_search())
└─ _do_kb_search() → ensure_owned_kb_worker_started()
└─ async lock held; worker task awaiting startup
└─ worker polls 0.75s; loop has no running event
└─ asyncio.run() waits forever → deadlock
The gateway/LangGraph runs on a single uvicorn worker thread that has an
active event loop. ``asyncio.run()`` creates a *second* loop and the inner
loop blocks waiting for the worker to signal, but the worker can't make
forward progress because it's scheduled on the first (blocked) loop.
Fix: replace the ``asyncio.run()`` + ``ThreadPoolExecutor`` dance with a
proper re-entry pattern:
- ``awrap_model_call`` (async path): already correct — uses ``await
_do_kb_search()`` directly on the running loop.
- ``wrap_model_call`` (sync path): detect whether a loop is already
running via ``asyncio.get_running_loop()``. If running, re-enter that
loop from a worker thread using ``loop.run_until_complete()`` (the
outer loop services the poll while the worker thread blocks waiting
for the worker signal). If no loop, use ``run_until_complete()`` on
a newly created loop.
Secondary fixes in ``awrap_model_call``:
- Added ``asyncio.TimeoutError`` handling (was missing; fell through as
bare ``Exception`` with no message).
- Added ``emit_agent_activity`` for both "检索到 N 条" and
"未命中(检索失败或 0 结果)" so the UI always receives a KB status
update on every turn, not just on errors.
Added ``import asyncio`` at module level.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(evopanel): drop Obsidian vault UI + complete owned-KB cutover
Backend middleware no longer supports Obsidian vaults (commit
|
||
|
|
6c490fd493 |
chore: initialize public repository
Clean public baseline for EvovexAI/EvoFlow: public-only CI, no private sync tooling, no Haze-Ctrl branding, and scrubbed non-public skills/docs leftovers. |