Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix: complete eight user blocker fixes and report delivery

Haozhe Wuaac03fa64dc6
diff --git a/.gitignore b/.gitignore
index fb3169f9d..a535a8750 100644
--- a/.gitignore
+++ b/.gitignore
@@ -59,6 +59,7 @@ agent/uploads/
/swarm/
/live/
/uploads/
+/generated_reports/
/imports/
/workspace/
/auth/
diff --git a/README.md b/README.md
index eefa4fe89..b5f588622 100644
--- a/README.md
+++ b/README.md
@@ -1104,6 +1104,15 @@ Copy `agent/.env.example` to `agent/.env` and uncomment the provider block you w
**Free data (no key needed):** A-shares via AKShare, HK/US/Canada/UK equities via Yahoo/yfinance, crypto via OKX, 100+ crypto exchanges via CCXT. The system automatically selects the best available source for each market.
+**PDF reports:** Ask the agent to save a report as PDF. `write_file` renders a
+`.pdf` target from Markdown/text with an embedded font; it does not need system
+Pango/Cairo or a font download. The Web chat provides an authenticated download
+link, and IM channels that support files receive the PDF as an attachment.
+External folders must be listed in `VIBE_TRADING_ALLOWED_WRITE_ROOTS`. Successful
+writes return the resolved path and byte count; a rejected path does not forbid
+other allowed folders. Generated downloads are staged under
+`~/.vibe-trading/generated_reports/` (or `VIBE_TRADING_HOME/generated_reports/`).
+
### 🎯 Recommended Models
Vibe-Trading is a tool-heavy agent — skills, backtests, memory, and swarms all flow through tool calls. Model choice directly decides whether the agent *uses* its tools or fabricates answers from training data.
diff --git a/agent/backtest/loaders/base.py b/agent/backtest/loaders/base.py
index dcbf6a6ef..c631fa9e2 100644
--- a/agent/backtest/loaders/base.py
+++ b/agent/backtest/loaders/base.py
@@ -466,8 +466,10 @@ _LOADER_CACHE_TRUE_VALUES = {"1", "true", "yes", "on"}
# persisted. v5 USD/unknown .L entries must never be served as static GBP.
# v7: tencent fqkline paginates backward (#1410) — entries cached under the
# forward walk hold tail-truncated multi-year series and must never be served.
-_LOADER_CACHE_VERSION = 7
-_LOADER_FRAME_METADATA_ATTRS = ("quote_currency", "currency_conversion")
+# v8: FMP/Tiingo keep one adjusted/raw basis and cached frames retain their
+# actual adjustment stamp. Older entries may contain artificial return jumps.
+_LOADER_CACHE_VERSION = 8
+_LOADER_FRAME_METADATA_ATTRS = ("quote_currency", "currency_conversion", "adjustment")
def loader_cache_enabled() -> bool:
diff --git a/agent/backtest/loaders/fmp_loader.py b/agent/backtest/loaders/fmp_loader.py
index 60262f438..cd888dcb3 100644
--- a/agent/backtest/loaders/fmp_loader.py
+++ b/agent/backtest/loaders/fmp_loader.py
@@ -252,17 +252,15 @@ def _parse_historical(payload: Any) -> Optional[pd.DataFrame]:
if not historical:
return None
- has_adjusted_data = any(
- isinstance(bar, dict)
- and bar.get("date") is not None
- and _adjusted_bar(bar) is not None
- for bar in historical
- )
+ dated = [bar for bar in historical if isinstance(bar, dict)
+ and isinstance(bar.get("date"), str)
+ and pd.notna(pd.to_datetime(bar["date"], errors="coerce"))]
+ if len(dated) != len(historical):
+ logger.warning("FMP: dropped %d bars with missing/invalid dates", len(historical) - len(dated))
+ has_adjusted_data = any(_adjusted_bar(bar) is not None for bar in dated)
rows = []
dropped = 0
- for bar in historical:
- if not isinstance(bar, dict) or bar.get("date") is None:
- continue
+ for bar in dated:
basis = _adjusted_bar(bar)
if basis is not None:
o, h, lo, c = basis
@@ -309,7 +307,8 @@ def _parse_historical(payload: Any) -> Optional[pd.DataFrame]:
return None
df = pd.DataFrame(rows)
- df["trade_date"] = pd.to_datetime(df["trade_date"])
+ df["trade_date"] = pd.to_datetime(df["trade_date"], errors="coerce")
+ df = df.dropna(subset=["trade_date"])
for field in _OHLCV_FIELDS:
# Cast to float (not just to_numeric) so integer volume from the API
# does not leave the column int64 and break the float-OHLCV contract.
@@ -317,6 +316,9 @@ def _parse_historical(payload: Any) -> Optional[pd.DataFrame]:
df = df.set_index("trade_date").sort_index()
df = df[list(_OHLCV_FIELDS)].dropna(subset=["open", "high", "low", "close"])
+ prices = df[["open", "high", "low", "close"]]
+ df = df.loc[((prices > 0) & (prices < float("inf"))).all(axis=1)]
if df.empty:
return None
+ df.attrs["adjustment"] = "split_dividend" if has_adjusted_data else "raw"
return df
diff --git a/agent/backtest/loaders/tiingo_loader.py b/agent/backtest/loaders/tiingo_loader.py
index e0fbcbb62..64d786b23 100644
--- a/agent/backtest/loaders/tiingo_loader.py
+++ b/agent/backtest/loaders/tiingo_loader.py
@@ -161,8 +161,11 @@ def _rows_to_frame(rows: List[dict]) -> Optional[pd.DataFrame]:
(adjusted when available), or ``None`` when no usable bar is present.
"""
dated = [
- row for row in rows if isinstance(row, dict) and row.get("date") is not None
+ row for row in rows if isinstance(row, dict) and isinstance(row.get("date"), str)
+ and pd.notna(pd.to_datetime(row["date"], utc=True, errors="coerce"))
]
+ if len(dated) != len(rows):
+ logger.warning("Tiingo: dropped %d bars with missing/invalid dates", len(rows) - len(dated))
has_adjusted_data = any(_adjusted_basis(row) is not None for row in dated)
parsed: List[dict] = []
dropped = 0
@@ -222,6 +225,7 @@ def _rows_to_frame(rows: List[dict]) -> Optional[pd.DataFrame]:
frame = frame.drop(columns=["trade_date"])
frame.index = index.normalize()
frame.index.name = "trade_date"
+ frame = frame.loc[frame.index.notna()]
frame = frame.apply(pd.to_numeric, errors="coerce")
# Coerce every OHLCV column to float64 so the schema is uniform: integer
@@ -231,6 +235,9 @@ def _rows_to_frame(rows: List[dict]) -> Optional[pd.DataFrame]:
frame["volume"] = frame["volume"].fillna(0.0)
frame = frame.loc[:, _OHLCV_COLUMNS].sort_index()
frame = frame.dropna(subset=["open", "high", "low", "close"])
+ prices = frame[["open", "high", "low", "close"]]
+ frame = frame.loc[((prices > 0) & (prices < float("inf"))).all(axis=1)]
+ frame.attrs["adjustment"] = "split_dividend" if has_adjusted_data else "raw"
return frame if not frame.empty else None
diff --git a/agent/src/agent/context.py b/agent/src/agent/context.py
index c53fa1544..cc4c86f05 100644
--- a/agent/src/agent/context.py
+++ b/agent/src/agent/context.py
@@ -23,6 +23,14 @@ logger = logging.getLogger(__name__)
_SYSTEM_PROMPT = """You are a finance research agent with {skill_count} specialist skills, {tool_count} tools, {data_source_count} data sources (with auto-fallback), and 29 multi-agent swarm teams.
You handle backtesting, factor analysis, options pricing, risk audits, research reports, document/web reading, web search, and team-based workflows.
+File operations are reported from their actual tool outcomes. A successful
+write_file result confirms the returned path and byte count; an earlier error
+for another path does not override it. A rejected path is not evidence that
+all external folders are forbidden. Use the allowed roots named in the error.
+For a requested PDF, pass Markdown/text to write_file with a .pdf path and
+include its returned download_url in the final answer. Do not save plain text
+with a .pdf extension or claim a write failed when its result says status ok.
+
## Output Principles
These six principles define what your output is. They hold for every answer in
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index ed1e53423..8529a31a9 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -593,7 +593,7 @@ def _result_data_gone(content: Any) -> bool:
return _is_cleared(content) or content == _STUB_RESULT_CONTENT
-def _context_collapse(messages: list) -> None:
+def _context_collapse(messages: list, *, preserve_tool_call_ids: Optional[set[str]] = None) -> None:
"""Layer 2: fold long text blocks in older messages without LLM call.
Preserves head + tail of large text, collapses the middle.
@@ -605,6 +605,8 @@ def _context_collapse(messages: list) -> None:
if len(messages) <= COLLAPSE_PRESERVE_RECENT + 1:
return
for msg in messages[1:-COLLAPSE_PRESERVE_RECENT]:
+ if msg.get("role") == "tool" and msg.get("tool_call_id") in (preserve_tool_call_ids or ()):
+ continue
content = msg.get("content")
if not isinstance(content, str) or len(content) <= COLLAPSE_TEXT_MIN:
continue
@@ -1256,7 +1258,7 @@ class AgentLoop:
)
tokens = estimate_tokens(messages)
if tokens > int(_token_threshold() * 0.7):
- _context_collapse(messages)
+ _context_collapse(messages, preserve_tool_call_ids=self._readonly_replay_visibility_pending)
tokens = estimate_tokens(messages)
_tok_threshold = _token_threshold()
if tokens > _tok_threshold:
@@ -3128,7 +3130,7 @@ class AgentLoop:
)
tokens = self._prompt_tokens(messages)
if tokens > budget.collapse_at:
- _context_collapse(messages)
+ _context_collapse(messages, preserve_tool_call_ids=self._readonly_replay_visibility_pending)
tokens = self._prompt_tokens(messages)
# A summary keeps the static prompt plus a ~20K-token tail, so on a
# window that small the prompt stays over the line after compacting;
@@ -3405,6 +3407,18 @@ class AgentLoop:
iteration=iteration,
)
preview = trace_result[:200]
+ artifact = None
+ if status == "ok" and tc.name in {"write_file", "render_shadow_report"}:
+ try:
+ payload = json.loads(trace_result)
+ from src.tools.report_artifacts import report_path
+ report_id = payload.get("report_id", "")
+ path = report_path(report_id) if isinstance(report_id, str) else None
+ if path is not None:
+ artifact = {"report_id": report_id, "filename": path.name,
+ "download_url": f"/api/reports/{report_id}"}
+ except (ValueError, TypeError, AttributeError, OSError):
+ pass
react_trace.append({"type": "tool_call", "tool": tc.name, "result_preview": preview})
self._emit(
"tool_result",
@@ -3414,6 +3428,7 @@ class AgentLoop:
"elapsed_ms": elapsed_ms,
"preview": preview,
"call_id": tc.id,
+ **({"artifact": artifact} if artifact else {}),
},
)
@@ -3471,6 +3486,16 @@ class AgentLoop:
logger.warning("Auto compact: nothing to compress (body too small)")
return
+ # Replayed results are owed one successful writing request. Keep the
+ # entire assistant-call/result pair out of summaries until then.
+ pending = self._readonly_replay_visibility_pending
+ leased = [msg for msg in head if (
+ msg.get("role") == "tool" and msg.get("tool_call_id") in pending
+ ) or any(call.get("id") in pending for call in msg.get("tool_calls") or [])]
+ if leased:
+ head = [msg for msg in head if all(msg is not kept for kept in leased)]
+ tail = leased + tail
+
# Build focus section
focus_section = _FOCUS_SECTION.format(topic=focus_topic) if focus_topic else ""
diff --git a/agent/src/api/uploads_routes.py b/agent/src/api/uploads_routes.py
index c78777f11..54903f2c7 100644
--- a/agent/src/api/uploads_routes.py
+++ b/agent/src/api/uploads_routes.py
@@ -93,6 +93,15 @@ def register_uploads_routes(
host = _sys.modules.get("api_server") or _sys.modules.get("agent.api_server")
return host._UPLOAD_CHUNK_SIZE if host else _UPLOAD_CHUNK_SIZE
+ @app.get("/api/reports/{report_id}", dependencies=[Depends(require_auth)])
+ async def get_generated_report(report_id: str):
+ """Download only a staged generated PDF via an opaque ID."""
+ from src.tools.report_artifacts import report_path
+ path = report_path(report_id)
+ if path is None:
+ raise HTTPException(status_code=404, detail="Report not found")
+ return FileResponse(path, media_type="application/pdf", filename=path.name)
+
@app.get("/shadow-reports/{shadow_id}", dependencies=[Depends(require_auth)])
async def get_shadow_report(shadow_id: str, format: str = "html"):
"""Serve a rendered Shadow Account report.
diff --git a/agent/src/channels/runtime.py b/agent/src/channels/runtime.py
index 27e8dfb12..6e8c52893 100644
--- a/agent/src/channels/runtime.py
+++ b/agent/src/channels/runtime.py
@@ -220,6 +220,7 @@ class ChannelRuntime:
channel=msg.channel,
chat_id=msg.chat_id,
content=reply_content,
+ media=self._report_media(reply),
metadata={
"_channel_runtime": True,
"attempt_id": attempt_id,
@@ -333,6 +334,19 @@ class ChannelRuntime:
self._save_session_map()
return session_id
+ @staticmethod
+ def _report_media(reply: Message) -> list[str]:
+ """Attach verified reports from this attempt, never model-written paths."""
+ from src.tools.report_artifacts import report_path
+ media = []
+ for report in reply.metadata.get("generated_reports", []):
+ if not isinstance(report, dict) or not isinstance(report.get("report_id"), str):
+ continue
+ path = report_path(report["report_id"])
+ if path is not None and str(path) not in media:
+ media.append(str(path))
+ return media
+
async def _wait_for_reply(self, session_id: str, attempt_id: str | None) -> Message:
deadline = time.monotonic() + self.config.reply_timeout_s
last_assistant: Message | None = None
diff --git a/agent/src/live/enforcement.py b/agent/src/live/enforcement.py
index c451616cd..73624e550 100644
--- a/agent/src/live/enforcement.py
+++ b/agent/src/live/enforcement.py
@@ -28,6 +28,7 @@ The verdict is a :class:`BreachEvent` whose ``kind`` is one of
from __future__ import annotations
import logging
+import math
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
@@ -312,7 +313,7 @@ def _positions_market_value(positions: object) -> float | None:
if value is None:
return None
total += value
- return total
+ return total if math.isfinite(total) else None
def _post_trade_gross_exposure(
@@ -340,7 +341,8 @@ def _post_trade_gross_exposure(
by_symbol[row_symbol] = by_symbol.get(row_symbol, 0.0) + signed_value
by_symbol[symbol] = by_symbol.get(symbol, 0.0) + signed_order_notional
- return sum(abs(value) for value in by_symbol.values())
+ gross = sum(abs(value) for value in by_symbol.values())
+ return gross if math.isfinite(gross) else None
def _coerce_position_rows(positions: object) -> list[dict] | None:
@@ -400,9 +402,10 @@ def _position_market_value(row: dict) -> float | None:
if key in row:
price = _as_float(row[key])
break
- if qty is None or price is None:
+ if qty is None or price is None or price <= 0:
return None
- return abs(qty) * price
+ value = abs(qty) * price
+ return value if math.isfinite(value) else None
def _position_symbol(row: dict) -> str | None:
@@ -458,12 +461,14 @@ def _account_balance_market_value(balance: object) -> float | None:
def _as_float(value: object) -> float | None:
- """Coerce ``value`` to a finite positive-or-zero float, else ``None``."""
+ """Coerce ``value`` to a finite float, else ``None`` (quantity may be signed)."""
+ if isinstance(value, bool):
+ return None
try:
out = float(value) # type: ignore[arg-type]
except (TypeError, ValueError):
return None
- if out != out: # NaN
+ if not math.isfinite(out):
return None
return out
diff --git a/agent/src/session/search.py b/agent/src/session/search.py
index cdb98974c..b1ca0e457 100644
--- a/agent/src/session/search.py
+++ b/agent/src/session/search.py
@@ -12,7 +12,9 @@ from __future__ import annotations
import json
import logging
+import re
import sqlite3
+import threading as _threading
import time
from dataclasses import dataclass
from datetime import datetime
@@ -20,12 +22,34 @@ from pathlib import Path
from typing import List, Optional
from src.config.paths import get_runtime_root
-from src.memory.search_index import MemorySearchIndex
logger = logging.getLogger(__name__)
_DB_PATH = get_runtime_root() / "sessions.db"
+# Ideographs, kana (including half-width), Hangul syllables and jamo.
+_EAST_ASIAN = "\u3400-\u4dbf\u4e00-\u9fff\u3040-\u30ff\u31f0-\u31ff\uff66-\uff9f\uac00-\ud7af\u1100-\u11ff\u3130-\u318f"
+_EAST_ASIAN_CHAR = re.compile(f"[{_EAST_ASIAN}]")
+_QUERY_TERM = re.compile(rf"[{_EAST_ASIAN}]+|[^\W_{_EAST_ASIAN}]+")
+
+
+def _prepare_search_text(text: str) -> str:
+ """Separate East Asian characters for FTS5 without changing display text."""
+ return _EAST_ASIAN_CHAR.sub(lambda match: f" {match[0]} ", text)
+
+
+def _search_snippet(content: str, query: str) -> str:
+ """Highlight query terms in the original text, never in expanded tokens."""
+ terms = sorted(set(_QUERY_TERM.findall(query)), key=len, reverse=True)
+ pattern = re.compile("|".join(re.escape(term) for term in terms), re.IGNORECASE) if terms else None
+ first = pattern.search(content) if pattern else None
+ start = max(0, first.start() - 100) if first else 0
+ end = min(len(content), start + 400)
+ excerpt = content[start:end]
+ if pattern:
+ excerpt = pattern.sub(lambda match: f">>>{match[0]}<<<", excerpt)
+ return ("..." if start else "") + excerpt + ("..." if end < len(content) else "")
+
@dataclass(frozen=True)
class SearchMatch:
@@ -109,31 +133,32 @@ class SessionSearchIndex:
CREATE INDEX IF NOT EXISTS idx_messages_session
ON messages(session_id);
""")
- # FTS5 virtual table — create separately (not inside executescript with IF NOT EXISTS
- # because FTS5 syntax varies across SQLite versions)
- try:
+ # Serialize upgrade across processes. Keep original messages for readable
+ # snippets; rebuild the derived index once, including historical rows.
+ conn.create_function("prepare_session_text", 1, _prepare_search_text, deterministic=True)
+ with conn:
+ conn.execute("BEGIN IMMEDIATE")
+ columns = {row[1] for row in conn.execute("PRAGMA table_info(messages)")}
+ migrating = "search_content" not in columns
+ if migrating:
+ for name in ("messages_ai", "messages_ad", "messages_au"):
+ conn.execute(f"DROP TRIGGER IF EXISTS {name}")
+ conn.execute("ALTER TABLE messages ADD COLUMN search_content TEXT NOT NULL DEFAULT ''")
+ conn.execute("UPDATE messages SET search_content = prepare_session_text(content)")
+ conn.execute("DROP TABLE IF EXISTS messages_fts")
conn.execute("""
CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts
- USING fts5(content, content=messages, content_rowid=id)
+ USING fts5(search_content, content=messages, content_rowid=id)
""")
- except sqlite3.OperationalError:
- pass # already exists or FTS5 not available
-
- # Auto-sync triggers
- for trigger_sql in [
- """CREATE TRIGGER IF NOT EXISTS messages_ai AFTER INSERT ON messages BEGIN
- INSERT INTO messages_fts(rowid, content) VALUES (new.id, new.content);
- END""",
- """CREATE TRIGGER IF NOT EXISTS messages_ad AFTER DELETE ON messages BEGIN
- INSERT INTO messages_fts(messages_fts, rowid, content)
- VALUES ('delete', old.id, old.content);
- END""",
- ]:
- try:
- conn.execute(trigger_sql)
- except sqlite3.OperationalError:
- pass
- conn.commit()
+ conn.execute("""CREATE TRIGGER IF NOT EXISTS messages_ai AFTER INSERT ON messages BEGIN
+ INSERT INTO messages_fts(rowid, search_content) VALUES (new.id, new.search_content);
+ END""")
+ conn.execute("""CREATE TRIGGER IF NOT EXISTS messages_ad AFTER DELETE ON messages BEGIN
+ INSERT INTO messages_fts(messages_fts, rowid, search_content)
+ VALUES ('delete', old.id, old.search_content);
+ END""")
+ if migrating:
+ conn.execute("INSERT INTO messages_fts(messages_fts) VALUES ('rebuild')")
def index_session(
self,
@@ -181,16 +206,12 @@ class SessionSearchIndex:
if not content or not content.strip():
return
conn = self._get_conn()
- # FTS5's default tokenizer has no notion of CJK word boundaries, so a
- # run of Chinese/Japanese/Korean characters indexes as one token
- # spanning the whole run. Storing it pre-split into unigrams/bigrams
- # (the same scheme _sanitize_fts_query queries with) is what makes a
- # CJK query match anything shorter than the entire message.
- prepared = MemorySearchIndex._prepare_cjk(content[:50_000])
+ content = content[:50_000]
+ prepared = _prepare_search_text(content)
conn.execute(
- "INSERT INTO messages (session_id, role, content, tool_name, timestamp) "
- "VALUES (?, ?, ?, ?, ?)",
- (session_id, role, prepared, tool_name, time.time()),
+ "INSERT INTO messages (session_id, role, content, search_content, tool_name, timestamp) "
+ "VALUES (?, ?, ?, ?, ?, ?)",
+ (session_id, role, content, prepared, tool_name, time.time()),
)
conn.execute(
"UPDATE sessions SET message_count = message_count + 1 WHERE id = ?",
@@ -202,9 +223,8 @@ class SessionSearchIndex:
def _sanitize_fts_query(query: str) -> str:
"""Sanitize a user query for FTS5 MATCH syntax.
- - Splits on non-alphanumeric/CJK to extract tokens, expanding a run
- of CJK characters into the same unigram+bigram tokens
- ``index_message`` stores content as (see ``MemorySearchIndex``)
+ - Separates Unicode words and East Asian character runs; the latter
+ become adjacent-token phrases, matching shorter text accurately
- Joins with OR so any-word-matches (not all-words-required)
- Quotes each token to prevent FTS5 operator interpretation
@@ -214,7 +234,8 @@ class SessionSearchIndex:
Returns:
FTS5-safe MATCH expression.
"""
- return MemorySearchIndex._sanitize_fts_query(query)
+ tokens = [_prepare_search_text(term).strip() for term in _QUERY_TERM.findall(query)]
+ return " OR ".join(f'"{token}"' for token in tokens) if tokens else '""'
def search(self, query: str, max_sessions: int = 3) -> List[SearchMatch]:
"""Full-text search across all sessions.
@@ -236,7 +257,7 @@ class SessionSearchIndex:
s.title,
s.started_at,
s.message_count,
- snippet(messages_fts, 0, '>>>', '<<<', '...', 64) AS snippet,
+ m.content,
rank
FROM messages_fts
JOIN messages m ON m.id = messages_fts.rowid
@@ -261,7 +282,7 @@ class SessionSearchIndex:
title=row[1] or "(untitled)",
started_at=self._format_time(row[2]),
message_count=row[3],
- snippet=MemorySearchIndex._clean_cjk(row[4] or ""),
+ snippet=_search_snippet(row[4] or "", query),
rank=row[5],
)
if len(seen) >= max_sessions:
@@ -346,8 +367,6 @@ class SessionSearchIndex:
self._conn = None
-import threading as _threading
-
_shared_index: Optional[SessionSearchIndex] = None
_shared_lock = _threading.Lock()
diff --git a/agent/src/session/service.py b/agent/src/session/service.py
index 30461bda9..a536d93ef 100644
--- a/agent/src/session/service.py
+++ b/agent/src/session/service.py
@@ -410,6 +410,15 @@ class SessionService:
# one thing a failure report needs.
tool_trail=result.get("tool_trail", []),
)
+ reports = [entry["artifact"] for entry in reply.tool_trail
+ if entry.get("status") == "ok" and isinstance(entry.get("artifact"), dict)]
+ if reports:
+ reply.metadata["generated_reports"] = reports
+ # Persist and stream the same concrete download links even if
+ # the model forgot to include them in its final answer.
+ links = [f"[{str(report['filename']).replace('[', '').replace(']', '')}]({report['download_url']})"
+ for report in reports]
+ reply.content += "\n\n" + "\n\n".join(dict.fromkeys(links))
self.store.append_message(reply)
# The append-only transcript is the user-visible source of truth.
# Commit it before attempt.json so startup recovery can finish a
@@ -421,7 +430,7 @@ class SessionService:
session.session_id,
_TERMINAL_EVENTS.get(attempt.status.value, "attempt.failed"),
{"attempt_id": attempt.attempt_id, "status": attempt.status.value,
- "summary": attempt.summary, "error": attempt.error, "run_dir": attempt.run_dir,
+ "summary": reply.content, "error": attempt.error, "run_dir": attempt.run_dir,
"started_at": wall_started_at, "ended_at": time.time(),
**{key: reply_metadata[key] for key in ("elapsed_ms", *runtime_keys) if key in reply_metadata}},
)
@@ -643,6 +652,8 @@ class SessionService:
if isinstance(elapsed_ms, (int, float)) and not isinstance(elapsed_ms, bool):
match["elapsed_ms"] = max(0, int(elapsed_ms))
match["preview"] = str(data.get("preview") or "")
+ if match["status"] == "ok" and isinstance(data.get("artifact"), dict):
+ match["artifact"] = dict(data["artifact"])
if call_id:
match["call_id"] = call_id
diff --git a/agent/src/shadow_account/assets/OFL.txt b/agent/src/shadow_account/assets/OFL.txt
new file mode 100644
index 000000000..d952d62c0
--- /dev/null
+++ b/agent/src/shadow_account/assets/OFL.txt
@@ -0,0 +1,92 @@
+This Font Software is licensed under the SIL Open Font License,
+Version 1.1.
+
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font
+creation efforts of academic and linguistic communities, and to
+provide a free and open framework in which fonts may be shared and
+improved in partnership with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply to
+any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software
+components as distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to,
+deleting, or substituting -- in part or in whole -- any of the
+components of the Original Version, by changing formats or by porting
+the Font Software to a new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed,
+modify, redistribute, and sell modified and unmodified copies of the
+Font Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components, in
+Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the
+corresponding Copyright Holder. This restriction only applies to the
+primary font name as presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created using
+the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/agent/src/shadow_account/assets/README.md b/agent/src/shadow_account/assets/README.md
new file mode 100644
index 000000000..e4b565636
--- /dev/null
+++ b/agent/src/shadow_account/assets/README.md
@@ -0,0 +1,18 @@
+# Embedded report font
+
+`VibeCJK-Regular.ttf` is a renamed, static weight-400 subset of Noto Sans CJK SC.
+It covers Latin, Greek, Cyrillic, CJK ideographs, Japanese kana and Korean Hangul
+used in reports. The renderer embeds the used glyphs in each PDF, so readers do
+not need a system font, an Asian language pack or a network font download.
+
+Upstream: [Noto CJK](https://github.com/notofonts/noto-cjk), revision
+`f8d157532fbfaeda587e826d4cd5b21a49186f7c`,
+`Sans/Variable/TTF/NotoSansCJKsc-VF.ttf`, Git blob
+`e67840913223f5c5db60570ce5bf001b0e079d42`.
+The original and this derivative are distributed under the SIL Open Font
+License 1.1, reproduced in `OFL.txt`.
+
+From the repository root, rebuild with `python tools/build_report_font.py`.
+The script verifies the source blob, freezes the variable font, selects the
+documented Unicode ranges, renames the derivative and includes its license.
+No font download happens when users generate a report.
diff --git a/agent/src/shadow_account/assets/VibeCJK-Regular.ttf b/agent/src/shadow_account/assets/VibeCJK-Regular.ttf
new file mode 100644
index 000000000..1e469ff9a
Binary files /dev/null and b/agent/src/shadow_account/assets/VibeCJK-Regular.ttf differ
diff --git a/agent/src/shadow_account/fonts.py b/agent/src/shadow_account/fonts.py
index 5eeb21800..1f7ab3e8f 100644
--- a/agent/src/shadow_account/fonts.py
+++ b/agent/src/shadow_account/fonts.py
@@ -33,7 +33,7 @@ def fonts_dir() -> Path:
def _system_cjk_candidates() -> list[Path]:
"""Enumerate locally-installed CJK fonts we can reuse without downloading."""
- candidates: list[Path] = []
+ candidates: list[Path] = [Path(__file__).parent / "assets" / "VibeCJK-Regular.ttf"]
env = os.environ
windir = env.get("WINDIR") or env.get("SystemRoot")
if windir:
@@ -45,6 +45,7 @@ def _system_cjk_candidates() -> list[Path]:
):
candidates.append(win_fonts / name)
for p in (
+ "/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
"/System/Library/Fonts/PingFang.ttc",
"/System/Library/Fonts/STHeiti Light.ttc",
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
diff --git a/agent/src/shadow_account/pdf_fallback.py b/agent/src/shadow_account/pdf_fallback.py
index 24a7d8a27..d06d7cbcc 100644
--- a/agent/src/shadow_account/pdf_fallback.py
+++ b/agent/src/shadow_account/pdf_fallback.py
@@ -37,7 +37,8 @@ def _ensure_font() -> str:
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
- for path in system_cjk_candidates():
+ bundled = Path(__file__).parent / "assets" / "VibeCJK-Regular.ttf"
+ for path in [bundled, *system_cjk_candidates()]:
try:
pdfmetrics.registerFont(TTFont(_FONT_FAMILY, str(path), subfontIndex=0))
except Exception:
@@ -46,10 +47,9 @@ def _ensure_font() -> str:
_font_family = _FONT_FAMILY
return _font_family
- logger.warning("No TrueType CJK font found; PDF fallback uses Helvetica.")
- _font_ready = True
- _font_family = "Helvetica"
- return _font_family
+ # An unembedded CID face can parse correctly yet render as a blank page
+ # in viewers without an Asian language pack. Never return such a PDF.
+ raise RuntimeError("No embeddable CJK font found; reinstall the package's bundled font asset")
def _file_uri_to_path(uri: str) -> Path | None:
@@ -102,7 +102,7 @@ def render_pdf_reportlab(
name, fontName=family, fontSize=size, leading=leading, **kw
)
- h1 = style("h1", 22, 27, spaceAfter=4 * mm)
+ h1 = style("h1", 22, 27, spaceAfter=4 * mm, keepWithNext=True)
h2 = style(
"h2",
13,
@@ -110,6 +110,7 @@ def render_pdf_reportlab(
spaceBefore=6 * mm,
spaceAfter=2.5 * mm,
textColor=colors.HexColor("#1a1a2e"),
+ keepWithNext=True,
)
body = style("body", 9.5, 14)
muted = style("muted", 8.5, 12, textColor=colors.HexColor("#777777"))
diff --git a/agent/src/skills/report-generate/SKILL.md b/agent/src/skills/report-generate/SKILL.md
index cfdc7c1a2..889270bdb 100644
--- a/agent/src/skills/report-generate/SKILL.md
+++ b/agent/src/skills/report-generate/SKILL.md
@@ -10,6 +10,19 @@ category: tool
Generate structured, professional-grade financial research reports. Follow the conventions used by securities firms and asset managers, and output complete Markdown reports that can be used directly for investment research reference.
+## Saving and Delivering a PDF
+
+When the user requests a PDF, send the complete Markdown report to `write_file`
+with a `.pdf` target (prefer `artifacts/report.pdf` under the active run directory).
+The tool renders a real, paginated PDF without requiring system Pango/Cairo.
+Check its returned `status`, `path`, and `bytes_written`; include the returned
+`download_url` as a Markdown link labelled with the report's filename. The Web
+chat downloads it with authentication and IM channels attach the generated PDF.
+A successful write is evidence that the returned path exists; another path's
+earlier rejection does not invalidate it. If rendering fails, report that tool
+error instead of claiming the PDF was created. Do not write HTML or base64 data
+as the content of a `.pdf` file.
+
## Report Types and Structure
### Type Classification
diff --git a/agent/src/tools/path_utils.py b/agent/src/tools/path_utils.py
index 579898dd8..24c7003ef 100644
--- a/agent/src/tools/path_utils.py
+++ b/agent/src/tools/path_utils.py
@@ -50,6 +50,25 @@ def _rejects_unc(p: str) -> None:
raise ValueError(f"UNC paths are not allowed: {p!r}")
+def _contained_path(candidate: Path, root: Path) -> Path | None:
+ """Resolve containment using filesystem identity for existing root aliases.
+
+ A case-insensitive filesystem can resolve ``dropbox`` and ``Dropbox`` to
+ the same directory while Path.resolve preserves the spelling. Only accept
+ such an alias when samefile proves it; never case-fold authorization paths.
+ """
+ root = root.resolve()
+ if candidate.is_relative_to(root):
+ return candidate
+ for ancestor in (candidate, *candidate.parents):
+ try:
+ if ancestor.samefile(root):
+ return root / candidate.relative_to(ancestor)
+ except OSError:
+ continue
+ return None
+
+
def safe_path(p: str, workdir: Path) -> Path:
"""Resolve `p` under `workdir` and ensure it stays inside.
@@ -74,11 +93,10 @@ def safe_path(p: str, workdir: Path) -> Path:
resolved = expanded.resolve()
else:
resolved = (base / p).resolve()
- try:
- resolved.relative_to(base)
- except ValueError as exc:
- raise ValueError(f"Path {p!r} escapes the workspace root") from exc
- return resolved
+ contained = _contained_path(resolved, base)
+ if contained is None:
+ raise ValueError(f"Path {p!r} escapes the workspace root")
+ return contained
def _agent_root() -> Path:
@@ -220,8 +238,9 @@ def resolve_safe_path(
# If safe_run_dir fails, check if the path is in allowed_roots first
candidate = Path(file_path).expanduser().resolve()
for root in allowed_roots:
- if candidate.is_relative_to(root):
- return candidate
+ contained = _contained_path(candidate, root)
+ if contained is not None:
+ return contained
raise exc
try:
@@ -230,8 +249,9 @@ def resolve_safe_path(
# Fallback to allowed roots if safe_path containment fails
candidate = Path(file_path).expanduser().resolve()
for root in allowed_roots:
- if candidate.is_relative_to(root):
- return candidate
+ contained = _contained_path(candidate, root)
+ if contained is not None:
+ return contained
raise ValueError(
f"Path {file_path!r} escapes run_dir {run_dir!r} and is not in allowed {purpose} roots.\n"
f"{_describe_roots(allowed_roots)}{hint}"
@@ -240,8 +260,9 @@ def resolve_safe_path(
# If no run_dir, path must resolve inside one of the allowed roots
candidate = Path(file_path).expanduser().resolve()
for root in allowed_roots:
- if candidate.is_relative_to(root):
- return candidate
+ contained = _contained_path(candidate, root)
+ if contained is not None:
+ return contained
raise ValueError(
f"run_dir is required to write/edit {file_path!r}, or the path must resolve inside allowed {purpose} roots.\n"
diff --git a/agent/src/tools/pdf_report.py b/agent/src/tools/pdf_report.py
new file mode 100644
index 000000000..0b16191de
--- /dev/null
+++ b/agent/src/tools/pdf_report.py
@@ -0,0 +1,99 @@
+"""Render Markdown reports to real PDFs without system rendering libraries."""
+
+from __future__ import annotations
+
+import os
+import re
+import tempfile
+from pathlib import Path
+from xml.sax.saxutils import escape
+
+
+def render_markdown_pdf(content: str, target: Path) -> None:
+ """Render a paginated report atomically, retaining an old file on failure.
+
+ Args:
+ content: Markdown or plain text, never executable HTML.
+ target: Already-authorized PDF output path.
+
+ Raises:
+ Exception: Rendering or writing failed; the target remains untouched.
+ """
+ from reportlab.lib import colors
+ from reportlab.lib.pagesizes import A4
+ from reportlab.lib.styles import ParagraphStyle
+ from reportlab.pdfbase import pdfmetrics
+ from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle
+
+ from src.shadow_account.pdf_fallback import _ensure_font
+
+ family = _ensure_font()
+ pdfmetrics.registerFontFamily(family, normal=family, bold=family, italic=family, boldItalic=family)
+ body = ParagraphStyle("report", fontName=family, fontSize=10, leading=15, wordWrap="CJK", spaceAfter=7)
+ cell = ParagraphStyle("cell", parent=body, fontSize=8, leading=12, spaceAfter=0)
+ code = ParagraphStyle("code", parent=body, backColor=colors.HexColor("#f3f1ed"), leftIndent=8)
+ headings = {level: ParagraphStyle(f"h{level}", parent=body, fontSize=22 - level * 2,
+ leading=27 - level * 2, spaceBefore=10, spaceAfter=8, keepWithNext=True)
+ for level in range(1, 5)}
+ width = A4[0] - 88
+ story = []
+
+ def inline(text: str) -> str:
+ text = escape(text)
+ text = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r"\1 (\2)", text)
+ text = re.sub(r"\*\*([^*]+)\*\*", r"<b>\1</b>", text)
+ return re.sub(r"`([^`]+)`", r"\1", text)
+
+ lines = content.splitlines()
+ position = 0
+ in_code = False
+ while position < len(lines):
+ line = lines[position].strip()
+ position += 1
+ if line.startswith("```"):
+ in_code = not in_code
+ continue
+ if in_code:
+ story.append(Paragraph(escape(lines[position - 1]).replace(" ", "&#160;"), code))
+ continue
+ if not line:
+ continue
+ if line.startswith("|") and position < len(lines) and re.fullmatch(r"[| :\-]+", lines[position].strip()):
+ rows = [[part.strip() for part in line.strip("|").split("|")]]
+ position += 1
+ while position < len(lines) and lines[position].strip().startswith("|"):
+ rows.append([part.strip() for part in lines[position].strip().strip("|").split("|")])
+ position += 1
+ columns = max(map(len, rows))
+ table = Table([[Paragraph(inline(value), cell) for value in row + [""] * (columns - len(row))]
+ for row in rows], colWidths=[width / columns] * columns, repeatRows=1,
+ splitInRow=1)
+ table.setStyle(TableStyle([
+ ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#eee7da")),
+ ("GRID", (0, 0), (-1, -1), 0.4, colors.HexColor("#d1c8b8")),
+ ("VALIGN", (0, 0), (-1, -1), "TOP"),
+ ("TOPPADDING", (0, 0), (-1, -1), 5),
+ ("BOTTOMPADDING", (0, 0), (-1, -1), 5),
+ ]))
+ story.extend([table, Spacer(1, 8)])
+ continue
+ heading = re.match(r"^(#{1,4})\s+(.+)", line)
+ if heading:
+ story.append(Paragraph(inline(heading[2]), headings[len(heading[1])]))
+ else:
+ line = re.sub(r"^[-*+]\s+", "• ", line)
+ line = re.sub(r"^>\s?", "", line)
+ story.append(Paragraph(inline(line), body))
+ if not story:
+ story.append(Paragraph("&#160;", body))
+
+ target.parent.mkdir(parents=True, exist_ok=True)
+ fd, temporary = tempfile.mkstemp(prefix=".report-", suffix=".pdf", dir=target.parent)
+ os.close(fd)
+ try:
+ document = SimpleDocTemplate(temporary, pagesize=A4, leftMargin=44, rightMargin=44,
+ topMargin=42, bottomMargin=42, title=target.stem)
+ document.build(story)
+ os.replace(temporary, target)
+ finally:
+ Path(temporary).unlink(missing_ok=True)
diff --git a/agent/src/tools/report_artifacts.py b/agent/src/tools/report_artifacts.py
new file mode 100644
index 000000000..ce22dc0cd
--- /dev/null
+++ b/agent/src/tools/report_artifacts.py
@@ -0,0 +1,49 @@
+"""Stage generated PDFs for authenticated download and channel delivery."""
+
+from __future__ import annotations
+
+import shutil
+import uuid
+from pathlib import Path
+
+from src.config.paths import get_runtime_root
+
+
+def reports_root() -> Path:
+ """Return the runtime-only generated report directory."""
+ return get_runtime_root() / "generated_reports"
+
+
+def publish_pdf(path: Path) -> dict[str, str]:
+ """Stage an actual PDF and return its opaque download handle.
+
+ Args:
+ path: Successful report output, not a model-supplied download path.
+
+ Returns:
+ Metadata for the staged file, shared by HTTP and IM transports.
+
+ Raises:
+ ValueError: The file is not a PDF.
+ """
+ with path.open("rb") as stream:
+ if stream.read(5) != b"%PDF-":
+ raise ValueError("The generated report is not a valid PDF")
+ report_id = uuid.uuid4().hex
+ directory = reports_root() / report_id
+ directory.mkdir(parents=True)
+ destination = directory / path.name
+ shutil.copyfile(path, destination)
+ return {"report_id": report_id, "download_url": f"/api/reports/{report_id}",
+ "filename": path.name, "media_type": "application/pdf"}
+
+
+def report_path(report_id: str) -> Path | None:
+ """Resolve an opaque report ID, refusing traversal and symlink escapes."""
+ if len(report_id) != 32 or any(char not in "0123456789abcdef" for char in report_id):
+ return None
+ directory = reports_root() / report_id
+ if not directory.is_dir() or directory.is_symlink():
+ return None
+ files = [path for path in directory.iterdir() if path.suffix.lower() == ".pdf" and path.is_file() and not path.is_symlink()]
+ return files[0] if len(files) == 1 else None
diff --git a/agent/src/tools/shadow_account_tool.py b/agent/src/tools/shadow_account_tool.py
index 798c795c5..447014c92 100644
--- a/agent/src/tools/shadow_account_tool.py
+++ b/agent/src/tools/shadow_account_tool.py
@@ -13,6 +13,7 @@ import json
import logging
from dataclasses import asdict
from datetime import date, timedelta
+from pathlib import Path
from typing import Any
from src.agent.tools import BaseTool
@@ -322,6 +323,8 @@ class RenderShadowReportTool(BaseTool):
"report_url": f"/shadow-reports/{profile.shadow_id}",
}
if report["pdf_path"]:
+ from src.tools.report_artifacts import publish_pdf
+ payload.update(publish_pdf(Path(report["pdf_path"])))
payload["pdf_url"] = f"/shadow-reports/{profile.shadow_id}?format=pdf"
return _ok(**payload)
diff --git a/agent/src/tools/swarm_tool.py b/agent/src/tools/swarm_tool.py
index 7bb109bea..a3b9b101c 100644
--- a/agent/src/tools/swarm_tool.py
+++ b/agent/src/tools/swarm_tool.py
@@ -8,7 +8,6 @@ from __future__ import annotations
import json
import logging
-import os
import re
import time
from typing import Any
@@ -149,6 +148,7 @@ _PRESET_KEYWORDS: list[tuple[str, list[str], float]] = [
r"\bBTC\b",
r"\bETH\b",
r"\bSOL\b",
+ r"\b(?:XRP|BNB|ADA|DOGE|AVAX|DOT|LINK|TON|LTC|MATIC)\b",
"crypto",
"bitcoin",
"加密",
@@ -198,6 +198,10 @@ _PRESET_KEYWORDS: list[tuple[str, list[str], float]] = [
"商品",
"原油",
"黄金",
+ "铜",
+ "铁矿石",
+ "白银",
+ "天然气",
],
0.9,
),
diff --git a/agent/src/tools/swarm_variables.py b/agent/src/tools/swarm_variables.py
index e0bbe6bfc..eb0757c6d 100644
--- a/agent/src/tools/swarm_variables.py
+++ b/agent/src/tools/swarm_variables.py
@@ -16,7 +16,7 @@ _MARKET_PATTERNS: list[tuple[str, list[str]]] = [
("A-shares", [r"A股", r"a股", "沪深", "上证", "深证", "创业板", "科创板", "中证", r"\bCSI\b"]),
("crypto", ["加密", r"\bcrypto\b", r"\bBTC\b", r"\bETH\b", "币", "USDT", "数字货币"]),
("Hong Kong", ["港股", "恒生", r"H股", "港交所", r"\.HK\b"]),
- ("US", ["美股", "纳斯达克", "标普", "道琼斯", r"S&P", r"\.US\b"]),
+ ("US", ["美股", "纳斯达克", "标普", "道琼斯", r"S&P", r"\.US\b", r"\bUS\s+(?:equities|stocks?|market)\b", r"\bU\.S\.\s+(?:equities|stocks?|market)\b"]),
]
# Risk tolerance for global_allocation_committee (English).
@@ -278,6 +278,37 @@ def _extract_commodity(prompt: str) -> str:
return "gold"
+def _explicit_horizon(prompt: str) -> str | None:
+ """Return the exact stated duration rather than a broader default bucket."""
+ numbers = {word: i for i, word in enumerate(
+ ("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve")
+ )}
+ numbers.update({word: i for i, word in enumerate("零一二三四五六七八九")})
+ numbers["两"] = 2
+ match = re.search(
+ r"(?<!\d)(\d{1,3}|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|[一二两三四五六七八九十]+)"
+ r"\s*(?:个)?\s*(days?|weeks?|months?|years?|天|日|周|星期|月|年)",
+ prompt, re.IGNORECASE,
+ )
+ if match:
+ token, unit = match.groups()
+ token = token.lower()
+ if token.isascii() and token.isdecimal():
+ count = int(token)
+ elif "十" in token:
+ tens, ones = token.split("十", 1)
+ count = numbers.get(tens, 1) * 10 + numbers.get(ones, 0)
+ else:
+ count = numbers.get(token, 0)
+ unit = unit.lower()
+ english = {"天": "day", "日": "day", "周": "week", "星期": "week", "月": "month", "年": "year"}.get(unit, unit.rstrip("s"))
+ if count > 0:
+ return f"{count} {english}{'' if count == 1 else 's'}"
+ if re.search(r"半年|half\s*(?:a\s*)?year", prompt, re.IGNORECASE):
+ return "6 months"
+ return None
+
+
def _extract_horizon(prompt: str) -> str:
"""Extract an investment horizon phrase such as "6 months" or "1 year".
@@ -287,19 +318,7 @@ def _extract_horizon(prompt: str) -> str:
Returns:
Horizon phrase for commodity_research_team, default 3 months.
"""
- months = re.search(r"(\d{1,3})\s*(?:个)?\s*(?:months?|月)", prompt, re.IGNORECASE)
- if months:
- count = int(months.group(1))
- return f"{count} month" if count == 1 else f"{count} months"
- years = re.search(r"(\d{1,3})\s*(?:个)?\s*(?:years?|年)", prompt, re.IGNORECASE)
- if years:
- count = int(years.group(1))
- return f"{count} year" if count == 1 else f"{count} years"
- if re.search(r"半年|half\s*(?:a\s*)?year", prompt, re.IGNORECASE):
- return "6 months"
- if re.search(r"一年|one\s+year", prompt, re.IGNORECASE):
- return "1 year"
- return "3 months"
+ return _explicit_horizon(prompt) or "3 months"
def _extract_factor_type(prompt: str) -> str:
@@ -364,7 +383,7 @@ def _extract_crypto_target(prompt: str) -> str:
symbol = match.group(1).upper() if match.group(1) else _CRYPTO_NAME_TO_SYMBOL.get(match.group(2).lower(), "")
if symbol and symbol not in found:
found.append(symbol)
- return ", ".join(found) if found else "BTC, ETH, SOL"
+ return ", ".join(found) if found else prompt.strip() or "BTC, ETH, SOL"
def _extract_timeframe(prompt: str) -> str:
@@ -376,13 +395,14 @@ def _extract_timeframe(prompt: str) -> str:
Returns:
Timeframe label, default medium-term 1-3 months.
"""
+ explicit = _explicit_horizon(prompt)
+ if explicit:
+ return explicit
for timeframe, patterns in _TIMEFRAME_PATTERNS:
for pat in patterns:
if re.search(pat, prompt, re.IGNORECASE):
return timeframe
- count_text, unit = _extract_horizon(prompt).split()
- months = int(count_text) * (12 if unit.startswith("year") else 1)
- return "medium-term 1-3 months" if months <= 3 else "long-term 3-12 months"
+ return "medium-term 1-3 months"
def _extract_fund_type(prompt: str) -> str:
@@ -491,5 +511,7 @@ def merge_variables(variables: dict[str, str], overrides: Any) -> tuple[dict[str
return variables, "variables must be an object of string values"
merged = dict(variables)
for key, value in overrides.items():
- merged[str(key)] = str(value)
+ if not isinstance(key, str) or not isinstance(value, str):
+ return variables, "variables must be an object of string values"
+ merged[key] = value
return merged, None
diff --git a/agent/src/tools/write_file_tool.py b/agent/src/tools/write_file_tool.py
index 57dae509a..5516f2add 100644
--- a/agent/src/tools/write_file_tool.py
+++ b/agent/src/tools/write_file_tool.py
@@ -15,7 +15,12 @@ class WriteFileTool(BaseTool):
"""Create or overwrite a workspace file, creating parent directories as needed."""
name = "write_file"
- description = "Write content to a file in the workspace. Creates parent directories automatically."
+ description = (
+ "Write content to a file in the workspace or configured write roots. "
+ "A .pdf path renders Markdown/text to a real PDF; other paths write UTF-8 text. "
+ "Creates parent directories automatically. Use the returned success/error as "
+ "the authoritative outcome; include the returned download URL for PDF reports."
+ )
is_readonly = False
parameters = {
"type": "object",
@@ -87,12 +92,26 @@ class WriteFileTool(BaseTool):
try:
resolved.parent.mkdir(parents=True, exist_ok=True)
- resolved.write_text(content, encoding="utf-8")
+ artifact = {}
+ if resolved.suffix.lower() == ".pdf":
+ from src.tools.pdf_report import render_markdown_pdf
+ from src.tools.report_artifacts import publish_pdf
+ render_markdown_pdf(content, resolved)
+ try:
+ artifact = publish_pdf(resolved)
+ except OSError as exc:
+ # The requested file exists: a staging failure must not
+ # falsely report that the user's write was refused.
+ artifact = {"media_type": "application/pdf", "download_error": redact_internal_paths(str(exc))}
+ else:
+ resolved.write_text(content, encoding="utf-8")
return json.dumps(
{
"status": "ok",
"path": str(resolved),
- "bytes_written": len(content.encode("utf-8")),
+ "bytes_written": resolved.stat().st_size,
+ "requested_path": str(file_path),
+ **artifact,
},
ensure_ascii=False,
)
diff --git a/agent/tests/test_auto_compact_chunked_summary.py b/agent/tests/test_auto_compact_chunked_summary.py
index eaec242d4..9856d3268 100644
--- a/agent/tests/test_auto_compact_chunked_summary.py
+++ b/agent/tests/test_auto_compact_chunked_summary.py
@@ -29,6 +29,30 @@ def _build_agent(llm: Any) -> AgentLoop:
return AgentLoop(registry=ToolRegistry(), llm=llm, max_iterations=1)
+def test_replayed_payload_and_call_pair_survive_collapse_and_summary_until_request(tmp_path):
+ from src.agent import loop as loop_mod
+ payload = "replayed evidence " + "x" * 9000
+ call = {"role": "assistant", "content": "", "tool_calls": [
+ {"id": "leased", "type": "function", "function": {"name": "probe", "arguments": "{}"}}]}
+ result = {"role": "tool", "tool_call_id": "leased", "name": "probe", "content": payload}
+ messages = [{"role": "system", "content": "system"}, {"role": "user", "content": "old goal"},
+ call, result, *[{"role": "user", "content": "tail" + "t" * 30000} for _ in range(4)]]
+ agent = _build_agent(_CompactionLLM(["Earlier work summarized."] * 10))
+ agent._readonly_replay_visibility_pending = {"leased"}
+ loop_mod._context_collapse(messages, preserve_tool_call_ids={"leased"})
+ assert result["content"] == payload
+ with_trace = TraceWriter(tmp_path / "trace")
+ try:
+ agent._auto_compact(messages, tmp_path, with_trace)
+ assert any(message.get("content") == payload for message in messages)
+ assert any(any(tc.get("id") == "leased" for tc in message.get("tool_calls", [])) for message in messages)
+ assert agent._readonly_replay_visibility_pending == {"leased"}
+ agent._consume_readonly_replay_visibility(messages, with_trace, 1)
+ assert agent._readonly_replay_visibility_pending == set()
+ finally:
+ with_trace.close()
+
+
def test_summary_chunks_single_chunk_matches_json_dumps() -> None:
"""The common one-chunk path must preserve the original prompt bytes."""
messages = [
diff --git a/agent/tests/test_channels_config_api.py b/agent/tests/test_channels_config_api.py
index a37751e51..2f26b183c 100644
--- a/agent/tests/test_channels_config_api.py
+++ b/agent/tests/test_channels_config_api.py
@@ -1336,3 +1336,19 @@ def test_put_websocket_clears_non_secret_token_issue_path(
on_disk = json.loads(path.read_text(encoding="utf-8"))["channels"]["websocket"]
assert on_disk["token_issue_path"] == ""
assert on_disk["token"] == "s3cret-value"
+def test_email_test_normalizes_blank_nullable_fields_without_persisting(tmp_path, monkeypatch):
+ client, path = _client(tmp_path, monkeypatch, channels={"email": _email_section()})
+ before = path.read_bytes()
+ seen = []
+ async def successful_probe(config):
+ seen.append(config.post_action)
+ return {"ok": True, "code": "ok", "detail": "connected", "sdk_available": True}
+ monkeypatch.setattr(email_probe, "test_connection", successful_probe)
+ response = client.post("/channels/email/test", json={"config": {"post_action": "", "max_attachments_per_email": 7}})
+ assert response.status_code == 200 and response.json()["ok"] is True
+ assert seen == [None]
+ assert path.read_bytes() == before
+ response = client.post("/channels/email/test", json={"config": {"post_action": "invalid"}})
+ assert response.status_code == 200 and response.json()["ok"] is False
+ assert response.json()["code"] == "invalid_credentials" and seen == [None]
+ assert response.json()["detail"].startswith("validation_error:")
diff --git a/agent/tests/test_session_service_lifecycle.py b/agent/tests/test_session_service_lifecycle.py
index 83af3b338..9d01ff097 100644
--- a/agent/tests/test_session_service_lifecycle.py
+++ b/agent/tests/test_session_service_lifecycle.py
@@ -211,6 +211,30 @@ def test_metrics_reach_the_attempt_and_the_reply(tmp_path, monkeypatch):
asyncio.run(scenario())
+def test_generated_report_links_persist_and_stream_identically(tmp_path, monkeypatch):
+ """A model omission must not hide a successfully generated report."""
+ async def scenario():
+ service = _service(tmp_path, monkeypatch)
+ session = service.create_session(title="report")
+ report = {"report_id": "a" * 32, "filename": "研究报告.pdf", "download_url": "/api/reports/" + "a" * 32}
+ trail = []
+ service._record_tool_trail_event(trail, "tool_result", {"tool": "write_file", "status": "ok", "artifact": report})
+ _stub_agent(service, monkeypatch, {"status": "success", "content": "Report saved.", "tool_trail": trail})
+ events = []
+ service.event_bus.emit = lambda sid, kind, data: events.append((kind, data))
+ await service.send_message(session.session_id, "create report")
+ for _ in range(100):
+ await asyncio.sleep(0.01)
+ if session.session_id not in service._inflight:
+ break
+ reply = service.store.get_messages(session.session_id)[-1]
+ assert reply.metadata["generated_reports"] == [report]
+ assert "[研究报告.pdf](/api/reports/" in reply.content
+ completed = next(data for kind, data in events if kind == "attempt.completed")
+ assert completed["summary"] == reply.content
+ asyncio.run(scenario())
+
+
def test_empty_successful_answer_says_so():
"""An empty answer must not be dressed up as a finished strategy run."""
attempt = Attempt(session_id="s" * 12, prompt="p")
diff --git a/agent/tests/test_shadow_account.py b/agent/tests/test_shadow_account.py
index 1f92dc516..5d1b108b1 100644
--- a/agent/tests/test_shadow_account.py
+++ b/agent/tests/test_shadow_account.py
@@ -1094,14 +1094,13 @@ def test_pdf_degrades_to_html_only_when_both_engines_fail(
@pytest.mark.unit
-def test_reportlab_fallback_reuses_helvetica_when_no_cjk_font(
+def test_reportlab_fallback_embeds_bundled_font_when_no_system_font(
profitable_journal: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
- """On a fontless host every render must keep using Helvetica.
+ """A fontless host embeds the bundled font on every render.
- The first probe registers nothing, so a cached "probed" flag that reports
- the CJK family name would hand platypus an unregistered font on the next
- render (CI hit exactly this on the second reportlab test in a process).
+ Both reports must use the registered embedded family; a successful parse
+ alone cannot prove that an unembedded CID font renders in a PDF reader.
"""
from src.shadow_account import pdf_fallback, reporter
@@ -1113,7 +1112,7 @@ def test_reportlab_fallback_reuses_helvetica_when_no_cjk_font(
first = reporter.render_shadow_report(profile, result, output_dir=tmp_path / "a")
assert first["engine"] == "reportlab"
- assert pdf_fallback._ensure_font() == "Helvetica"
+ assert pdf_fallback._ensure_font() == "VibeShadowCJK"
second = reporter.render_shadow_report(profile, result, output_dir=tmp_path / "b")
assert second["engine"] == "reportlab"
diff --git a/agent/tests/test_swarm_tool_variables.py b/agent/tests/test_swarm_tool_variables.py
index f53c843eb..a9b60149e 100644
--- a/agent/tests/test_swarm_tool_variables.py
+++ b/agent/tests/test_swarm_tool_variables.py
@@ -46,7 +46,7 @@ def test_crypto_target_keeps_only_the_assets_the_user_named() -> None:
)
assert variables["target"] == "ETH, SOL"
- assert variables["timeframe"] == "medium-term 1-3 months"
+ assert variables["timeframe"] == "3 months"
def test_crypto_target_maps_chinese_names_to_symbols() -> None:
diff --git a/agent/tests/test_user_blockers_followups.py b/agent/tests/test_user_blockers_followups.py
new file mode 100644
index 000000000..d26b799f4
--- /dev/null
+++ b/agent/tests/test_user_blockers_followups.py
@@ -0,0 +1,179 @@
+"""Upgrade, filesystem, price-basis and report-delivery acceptance cases."""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+
+import pytest
+from fastapi import FastAPI, HTTPException, Request
+from fastapi.testclient import TestClient
+
+from src.session.search import SessionSearchIndex
+from src.tools.path_utils import resolve_safe_path
+from src.tools.swarm_tool import _build_variables, _match_preset, _merge_variables
+from src.tools.write_file_tool import WriteFileTool
+
+
[email protected]("text,query", [
+ ("我想了解比特币价格价格及交易策略", "价格"),
+ ("ビットコインの投資について調べます", "投資"),
+ ("ビットコインについて調べます", "ビットコイン"),
+ ("비트코인의 투자 전략을 분석합니다", "투자"),
+ ("ação e análise de ações", "análise"),
+])
+def test_existing_session_database_upgrade_preserves_original_snippets(tmp_path, text, query):
+ path = tmp_path / "sessions.db"
+ with sqlite3.connect(path) as connection:
+ connection.executescript("""
+ CREATE TABLE sessions(id TEXT PRIMARY KEY,title TEXT,started_at REAL,message_count INTEGER);
+ CREATE TABLE messages(id INTEGER PRIMARY KEY AUTOINCREMENT,session_id TEXT,role TEXT,
+ content TEXT,tool_name TEXT,timestamp REAL);
+ CREATE VIRTUAL TABLE messages_fts USING fts5(content,content=messages,content_rowid=id);
+ """)
+ connection.execute("INSERT INTO sessions VALUES ('old','History',1700000000,1)")
+ connection.execute("INSERT INTO messages VALUES (1,'old','user',?,NULL,1700000000)", (text,))
+ connection.execute("INSERT INTO messages_fts(messages_fts) VALUES ('rebuild')")
+ for _ in range(2):
+ index = SessionSearchIndex(path)
+ matches = index.search(query)
+ assert [match.session_id for match in matches] == ["old"]
+ assert matches[0].snippet.replace(">>>", "").replace("<<<", "") == text
+ assert index._get_conn().execute("SELECT content FROM messages").fetchone()[0] == text
+ assert matches[0].message_count == 1
+ index.close()
+
+
+def test_cjk_query_does_not_match_unrelated_shared_character(tmp_path):
+ index = SessionSearchIndex(tmp_path / "search.db")
+ index.index_session("wrong", "Unrelated")
+ index.index_message("wrong", "user", "比大小和特长")
+ assert index.search("比特币") == []
+ index.close()
+
+
+def test_case_alias_and_symlink_paths_use_real_directory_identity(tmp_path):
+ root = tmp_path / "Dropbox"
+ root.mkdir()
+ lower = tmp_path / "dropbox"
+ if lower.exists() and lower.samefile(root):
+ output = resolve_safe_path(str(lower / "report.txt"), None, [root], purpose="write")
+ assert output == root.resolve() / "report.txt"
+ else:
+ lower.mkdir()
+ with pytest.raises(ValueError):
+ resolve_safe_path(str(lower / "report.txt"), None, [root], purpose="write")
+ alias = tmp_path / "cloud-alias"
+ alias.symlink_to(root, target_is_directory=True)
+ assert resolve_safe_path(str(alias / "report.txt"), None, [root]) == root.resolve() / "report.txt"
+ outside = tmp_path / "private"
+ outside.mkdir()
+ (root / "escape").symlink_to(outside, target_is_directory=True)
+ with pytest.raises(ValueError):
+ resolve_safe_path(str(root / "escape" / "secret.txt"), None, [root])
+
+
[email protected]("prompt,preset,asset,key,duration", [
+ ("Analyze XRP for the next 7 days", "crypto_research_lab", "XRP", "timeframe", "7 days"),
+ ("分析铜,未来两周", "commodity_research_team", "copper", "horizon", "2 weeks"),
+ ("分析铁矿石未来七天", "commodity_research_team", "iron ore", "horizon", "7 days"),
+ ("Analyze copper for the next six months", "commodity_research_team", "copper", "horizon", "6 months"),
+])
+def test_swarm_actual_worker_templates_retain_explicit_assets_and_duration(prompt, preset, asset, key, duration):
+ from src.swarm.presets import load_preset
+ assert _match_preset(prompt) == preset
+ variables = _build_variables(preset, prompt)
+ assert variables[key] == duration
+ for task in load_preset(preset)["tasks"]:
+ rendered = task["prompt_template"].format_map(variables)
+ assert asset in rendered and duration in rendered
+
+
+def test_swarm_unknown_asset_is_not_replaced_by_default_crypto_basket():
+ variables = _build_variables("crypto_research_lab", "Analyze SUI crypto for seven days")
+ assert "SUI" in variables["target"]
+ assert variables["timeframe"] == "7 days"
+ assert _merge_variables(variables, {"target": ["SUI"]})[1] is not None
+
+
[email protected]("parser", ["fmp", "tiingo"])
+def test_adjustment_gap_never_fabricates_a_doubling_return(parser, caplog):
+ from backtest.loaders.fmp_loader import _parse_historical
+ from backtest.loaders.tiingo_loader import _rows_to_frame
+ parse = (lambda rows: _parse_historical({"historical": rows})) if parser == "fmp" else _rows_to_frame
+ rows = [{"date": date, "open": 100, "high": 110, "low": 90, "close": 100, "volume": 10,
+ **adjustment} for date, adjustment in [
+ ("2024-01-02", {"adjClose": 50}), ("2024-01-03", {}), ("2024-01-04", {"adjClose": 50})]]
+ frame = parse(rows)
+ assert list(frame.close) == [50, 50]
+ assert frame.close.pct_change().dropna().tolist() == [0]
+ assert "dropped 1" in caplog.text
+ assert frame.attrs["adjustment"] == "split_dividend"
+ raw = parse([{**rows[1]}, {**rows[0], "date": "invalid"}])
+ assert list(raw.close) == [100]
+ assert raw.attrs["adjustment"] == "raw"
+ assert parse([{**rows[1], "close": float("inf")}]) is None
+
+
[email protected]("field", ["current_price", "ltp", "market_val"])
[email protected]("invalid", [float("nan"), float("inf"), float("-inf"), True, "invalid"])
+def test_sdk_aliases_still_refuse_nonfinite_or_malformed_positions(field, invalid):
+ from src.live.enforcement import _post_trade_gross_exposure
+ row = {"symbol": "AAPL", "quantity": 2, field: invalid}
+ assert _post_trade_gross_exposure([row], symbol="AAPL", signed_order_notional=50) is None
+
+
+def test_pdf_write_authenticated_download_and_im_delivery_share_real_file(tmp_path, monkeypatch):
+ from src.api.uploads_routes import register_uploads_routes
+ from src.channels.runtime import ChannelRuntime
+ from src.session.models import Message
+ from src.tools import report_artifacts
+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_WRITE_ROOTS", str(tmp_path))
+ monkeypatch.setenv("VIBE_TRADING_HOME", str(tmp_path / "runtime"))
+ from src.config.accessor import reset_env_config
+ reset_env_config()
+ payload = json.loads(WriteFileTool().execute(path=str(tmp_path / "研究报告.pdf"), content=(
+ "# 研究报告\n\n投资策略 < & >\n\n| 指标 | 观察 |\n| --- | --- |\n| 样本 | 完整 |\n")))
+ assert payload["status"] == "ok"
+ path = report_artifacts.report_path(payload["report_id"])
+ assert path.read_bytes() == (tmp_path / "研究报告.pdf").read_bytes()
+ assert path.read_bytes().startswith(b"%PDF-") and path.read_bytes().rstrip().endswith(b"%%EOF")
+ assert payload["bytes_written"] == path.stat().st_size
+ def auth(request: Request):
+ if request.headers.get("authorization") != "Bearer test-token":
+ raise HTTPException(401)
+ app = FastAPI()
+ register_uploads_routes(app, auth)
+ client = TestClient(app)
+ assert client.get(payload["download_url"]).status_code == 401
+ response = client.get(payload["download_url"], headers={"Authorization": "Bearer test-token"})
+ assert response.status_code == 200 and response.headers["content-type"] == "application/pdf"
+ assert response.content == path.read_bytes()
+ message = Message(metadata={"generated_reports": [payload, payload, {"report_id": "../secret"}]})
+ assert ChannelRuntime._report_media(message) == [str(path)]
+ path.unlink()
+ path.symlink_to(tmp_path / "研究报告.pdf")
+ assert client.get(payload["download_url"], headers={"Authorization": "Bearer test-token"}).status_code == 404
+
+
+def test_pdf_render_failure_preserves_existing_file_and_reports_error(tmp_path, monkeypatch):
+ from src.tools import pdf_report
+ monkeypatch.setattr("src.tools.write_file_tool.allowed_write_roots", lambda: [tmp_path])
+ target = tmp_path / "report.pdf"
+ target.write_bytes(b"previous version")
+ def fail(*args):
+ raise RuntimeError("render failed")
+ monkeypatch.setattr(pdf_report, "render_markdown_pdf", fail)
+ result = json.loads(WriteFileTool().execute(path=str(target), content="# A report"))
+ assert result["status"] == "error"
+ assert target.read_bytes() == b"previous version"
+
+
+def test_cache_upgrade_invalidates_old_basis_and_preserves_adjustment_stamp():
+ from backtest.loaders import base
+ import pandas as pd
+ assert base._LOADER_CACHE_VERSION >= 8
+ frame = pd.DataFrame({"close": [100.]}, index=pd.to_datetime(["2024-01-02"]))
+ frame.attrs["adjustment"] = "raw"
+ _, metadata = base._frame_for_loader_cache(frame)
+ assert metadata["frame_attrs"]["adjustment"] == "raw"
diff --git a/frontend/src/components/chat/MessageBubble.tsx b/frontend/src/components/chat/MessageBubble.tsx
index 89ae6d649..039d4bfcf 100644
--- a/frontend/src/components/chat/MessageBubble.tsx
+++ b/frontend/src/components/chat/MessageBubble.tsx
@@ -9,6 +9,7 @@ import rehypeKatex from "rehype-katex";
import "katex/dist/katex.min.css";
import { toast } from "sonner";
import { normalizeMathDelimiters } from "@/lib/markdown";
+import { downloadGeneratedReport } from "@/lib/api";
import type { AgentMessage } from "@/types/agent";
import type { StoredAgentMessage } from "@/stores/agent";
import { AgentAvatar } from "./AgentAvatar";
@@ -32,6 +33,16 @@ const markdownComponents: ReactMarkdownOptions["components"] = {
},
a: ({ node, ...props }) => {
void node;
+ const report = props.href?.match(/^\/api\/reports\/([0-9a-f]{32})$/);
+ if (report) {
+ return <a {...props} onClick={(event) => {
+ event.preventDefault();
+ const filename = event.currentTarget.textContent || "report.pdf";
+ void downloadGeneratedReport(report[1], filename).catch(() => {
+ toast.error(i18n.t("settings.unknownError"));
+ });
+ }} />;
+ }
return <a {...props} target="_blank" rel="noopener noreferrer" />;
},
};
diff --git a/frontend/src/lib/__tests__/api.test.ts b/frontend/src/lib/__tests__/api.test.ts
index ba1cb5034..e0e36db92 100644
--- a/frontend/src/lib/__tests__/api.test.ts
+++ b/frontend/src/lib/__tests__/api.test.ts
@@ -6,6 +6,24 @@ async function loadApiModule() {
return import("../api");
}
+describe("generated report download", () => {
+ afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); });
+ it("downloads PDF bytes with bearer authentication and keeps the key out of the URL", async () => {
+ vi.stubGlobal("localStorage", { getItem: vi.fn((key) => key === "vibe_trading_api_auth_key" ? "report-test-key" : "en"), setItem: vi.fn(), removeItem: vi.fn() });
+ const fetch = vi.fn().mockResolvedValue(new Response("%PDF-contents", { headers: { "content-type": "application/pdf" } }));
+ vi.stubGlobal("fetch", fetch);
+ const click = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
+ vi.stubGlobal("URL", class extends URL {
+ static createObjectURL = vi.fn(() => "blob:report");
+ static revokeObjectURL = vi.fn();
+ });
+ const { downloadGeneratedReport } = await loadApiModule();
+ await downloadGeneratedReport("a".repeat(32), "研究报告.pdf");
+ expect(fetch).toHaveBeenCalledWith(`/api/reports/${"a".repeat(32)}`, { headers: { Authorization: "Bearer report-test-key" } });
+ expect(click).toHaveBeenCalledOnce();
+ });
+});
+
describe("api request helper", () => {
beforeEach(() => {
vi.stubGlobal("localStorage", {
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index ea29e6968..dae60b398 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -8,6 +8,17 @@ import type {
const BASE = "";
+export async function downloadGeneratedReport(reportId: string, filename: string): Promise<void> {
+ const response = await fetch(`${BASE}/api/reports/${encodeURIComponent(reportId)}`, { headers: authHeaders() });
+ if (!response.ok) throw new ApiError(response.statusText, response.status);
+ const url = URL.createObjectURL(await response.blob());
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = filename;
+ link.click();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+}
+
export class ApiError extends Error {
status: number;
code?: string;
diff --git a/pyproject.toml b/pyproject.toml
index f7af0c131..ff6924de8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -110,6 +110,9 @@ include = ["src*", "backtest*", "cli*", "evals*"]
"shadow_account/templates/*.j2",
"shadow_account/templates/*.html",
"shadow_account/templates/*.css",
+ "shadow_account/assets/*.ttf",
+ "shadow_account/assets/*.txt",
+ "shadow_account/assets/*.md",
]
"evals.harness" = ["README.md", "cases/**/*.json"]
"backtest" = ["*.py"]
diff --git a/tools/build_report_font.py b/tools/build_report_font.py
new file mode 100644
index 000000000..85c0bb108
--- /dev/null
+++ b/tools/build_report_font.py
@@ -0,0 +1,41 @@
+"""Rebuild the bundled OFL report font from the pinned upstream Noto source.
+
+Run from the repository root with matplotlib's fontTools dependency installed.
+This is a development asset-generation utility, never called by the application.
+"""
+
+from pathlib import Path
+import hashlib
+import urllib.request
+import tempfile
+from fontTools.ttLib import TTFont
+from fontTools.varLib.instancer import instantiateVariableFont
+from fontTools import subset
+revision='f8d157532fbfaeda587e826d4cd5b21a49186f7c'
+base=f'https://raw.githubusercontent.com/notofonts/noto-cjk/{revision}/Sans'
+source=Path(tempfile.gettempdir())/'vibe-report-NotoSansCJKsc-VF.ttf'
+if not source.exists():
+ urllib.request.urlretrieve(base+'/Variable/TTF/NotoSansCJKsc-VF.ttf',source)
+data=source.read_bytes()
+assert hashlib.sha1(b'blob '+str(len(data)).encode()+b'\0'+data).hexdigest()=='e67840913223f5c5db60570ce5bf001b0e079d42'
+font=instantiateVariableFont(TTFont(source),{'wght':400},inplace=True)
+options=subset.Options()
+options.name_IDs=['*']
+options.name_languages=['*']
+subsetter=subset.Subsetter(options=options)
+unicodes=set()
+for start,end in ((0x20,0x250),(0x370,0x52f),(0x1100,0x11ff),(0x2000,0x26ff),(0x3000,0x318f),(0x31f0,0x31ff),(0x3400,0x9fff),(0xac00,0xd7af),(0xf900,0xfaff),(0xff00,0xffef)):
+ unicodes.update(range(start,end+1))
+subsetter.populate(unicodes=unicodes)
+subsetter.subset(font)
+for name in font['name'].names:
+ if name.nameID in (1,3,4,6,16):
+ name.string=('VibeCJK-Regular' if name.nameID==6 else 'Vibe CJK Regular').encode(name.getEncoding())
+ elif name.nameID in (2,17):
+ name.string='Regular'.encode(name.getEncoding())
+out=Path('agent/src/shadow_account/assets')
+out.mkdir(parents=True,exist_ok=True)
+font.save(out/'VibeCJK-Regular.ttf')
+with urllib.request.urlopen(base+'/LICENSE') as response:
+ (out/'OFL.txt').write_bytes(response.read())
+print({'bytes':(out/'VibeCJK-Regular.ttf').stat().st_size,'glyphs':len(font.getBestCmap()),'probe':[char in font.getBestCmap() for char in map(ord,'中国日本한국áβ')]})