brief-lens 0.1.5 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/dist/python/prompts/briefing_sectors.md +10 -1
- package/dist/python/prompts/briefing_sectors_api.md +3 -1
- package/dist/python/src/chat_session.py +7 -0
- package/dist/python/src/claude_runner.py +131 -1
- package/dist/python/src/credentials.py +6 -0
- package/dist/python/src/generator/briefing.py +42 -22
- package/dist/python/src/generator/briefscript_notion.py +2 -2
- package/dist/python/src/generator/briefscript_render.py +8 -2
- package/dist/python/src/generator/briefscript_schema.py +23 -1
- package/dist/python/src/generator/briefscript_slides.py +8 -6
- package/dist/python/src/generator/briefscript_speech.py +3 -1
- package/dist/python/src/generator/weekly_summary.py +9 -2
- package/dist/python/src/handler.py +11 -3
- package/dist/python/src/model_rates.json +2 -1
- package/dist/python/web/routers/archive.py +52 -3
- package/dist/python/web/routers/chat.py +80 -6
- package/dist/python/web/routers/credentials.py +37 -0
- package/dist/web/.next-pack/BUILD_ID +1 -1
- package/dist/web/.next-pack/app-build-manifest.json +32 -32
- package/dist/web/.next-pack/app-path-routes-manifest.json +4 -4
- package/dist/web/.next-pack/build-manifest.json +2 -2
- package/dist/web/.next-pack/prerender-manifest.json +3 -3
- package/dist/web/.next-pack/server/app/(main)/auth/page.js +2 -2
- package/dist/web/.next-pack/server/app/(main)/auth/page.js.nft.json +1 -1
- package/dist/web/.next-pack/server/app/(main)/auth/page_client-reference-manifest.js +1 -1
- package/dist/web/.next-pack/server/app/(main)/briefing/page.js +2 -2
- package/dist/web/.next-pack/server/app/(main)/briefing/page.js.nft.json +1 -1
- package/dist/web/.next-pack/server/app/(main)/briefing/page_client-reference-manifest.js +1 -1
- package/dist/web/.next-pack/server/app/(main)/chat/page.js +2 -2
- package/dist/web/.next-pack/server/app/(main)/chat/page.js.nft.json +1 -1
- package/dist/web/.next-pack/server/app/(main)/chat/page_client-reference-manifest.js +1 -1
- package/dist/web/.next-pack/server/app/(main)/config/usage/page.js +2 -2
- package/dist/web/.next-pack/server/app/(main)/config/usage/page.js.nft.json +1 -1
- package/dist/web/.next-pack/server/app/(main)/config/usage/page_client-reference-manifest.js +1 -1
- package/dist/web/.next-pack/server/app/(main)/credentials/page.js +2 -2
- package/dist/web/.next-pack/server/app/(main)/credentials/page.js.nft.json +1 -1
- package/dist/web/.next-pack/server/app/(main)/credentials/page_client-reference-manifest.js +1 -1
- package/dist/web/.next-pack/server/app/(main)/geopolitical/page.js +2 -2
- package/dist/web/.next-pack/server/app/(main)/geopolitical/page.js.nft.json +1 -1
- package/dist/web/.next-pack/server/app/(main)/geopolitical/page_client-reference-manifest.js +1 -1
- package/dist/web/.next-pack/server/app/(main)/journal/page.js +2 -2
- package/dist/web/.next-pack/server/app/(main)/journal/page.js.nft.json +1 -1
- package/dist/web/.next-pack/server/app/(main)/journal/page_client-reference-manifest.js +1 -1
- package/dist/web/.next-pack/server/app/(main)/monitor/page.js +2 -2
- package/dist/web/.next-pack/server/app/(main)/monitor/page.js.nft.json +1 -1
- package/dist/web/.next-pack/server/app/(main)/monitor/page_client-reference-manifest.js +1 -1
- package/dist/web/.next-pack/server/app/(main)/portfolio/page.js +2 -2
- package/dist/web/.next-pack/server/app/(main)/portfolio/page.js.nft.json +1 -1
- package/dist/web/.next-pack/server/app/(main)/portfolio/page_client-reference-manifest.js +1 -1
- package/dist/web/.next-pack/server/app/(main)/run/page.js +2 -2
- package/dist/web/.next-pack/server/app/(main)/run/page.js.nft.json +1 -1
- package/dist/web/.next-pack/server/app/(main)/run/page_client-reference-manifest.js +1 -1
- package/dist/web/.next-pack/server/app/(main)/watch-sectors/page.js +2 -2
- package/dist/web/.next-pack/server/app/(main)/watch-sectors/page.js.nft.json +1 -1
- package/dist/web/.next-pack/server/app/(main)/watch-sectors/page_client-reference-manifest.js +1 -1
- package/dist/web/.next-pack/server/app/(main)/workspace/page.js +2 -2
- package/dist/web/.next-pack/server/app/(main)/workspace/page.js.nft.json +1 -1
- package/dist/web/.next-pack/server/app/(main)/workspace/page_client-reference-manifest.js +1 -1
- package/dist/web/.next-pack/server/app/_not-found/page.js.nft.json +1 -1
- package/dist/web/.next-pack/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/dist/web/.next-pack/server/app/_not-found.html +2 -2
- package/dist/web/.next-pack/server/app/_not-found.rsc +1 -1
- package/dist/web/.next-pack/server/app/api/[...path]/route.js.nft.json +1 -1
- package/dist/web/.next-pack/server/app/api/[...path]/route_client-reference-manifest.js +1 -1
- package/dist/web/.next-pack/server/app/api/attachments/[...path]/route.js.nft.json +1 -1
- package/dist/web/.next-pack/server/app/api/attachments/[...path]/route_client-reference-manifest.js +1 -1
- package/dist/web/.next-pack/server/app/api/attachments/upload/route.js.nft.json +1 -1
- package/dist/web/.next-pack/server/app/api/attachments/upload/route_client-reference-manifest.js +1 -1
- package/dist/web/.next-pack/server/app/api/images/[...path]/route.js.nft.json +1 -1
- package/dist/web/.next-pack/server/app/api/images/[...path]/route_client-reference-manifest.js +1 -1
- package/dist/web/.next-pack/server/app/api/images/upload/route.js.nft.json +1 -1
- package/dist/web/.next-pack/server/app/api/images/upload/route_client-reference-manifest.js +1 -1
- package/dist/web/.next-pack/server/app/icon.svg/route.js.nft.json +1 -1
- package/dist/web/.next-pack/server/app/page.js +1 -1
- package/dist/web/.next-pack/server/app/page.js.nft.json +1 -1
- package/dist/web/.next-pack/server/app/page_client-reference-manifest.js +1 -1
- package/dist/web/.next-pack/server/app-paths-manifest.json +4 -4
- package/dist/web/.next-pack/server/chunks/{4983.js → 2213.js} +1 -1
- package/dist/web/.next-pack/server/chunks/{8640.js → 5219.js} +2 -2
- package/dist/web/.next-pack/server/chunks/7374.js +21 -0
- package/dist/web/.next-pack/server/pages/404.html +2 -2
- package/dist/web/.next-pack/server/pages/500.html +1 -1
- package/dist/web/.next-pack/server/pages/_app.js.nft.json +1 -1
- package/dist/web/.next-pack/server/pages/_document.js.nft.json +1 -1
- package/dist/web/.next-pack/server/pages/_error.js.nft.json +1 -1
- package/dist/web/.next-pack/server/server-reference-manifest.json +1 -1
- package/dist/web/.next-pack/static/chunks/6292-64dda8c7c791b41f.js +1 -0
- package/dist/web/.next-pack/static/chunks/app/(main)/briefing/page-106e8b178dd30dc2.js +1 -0
- package/dist/web/.next-pack/static/chunks/app/(main)/layout-44701007707a325a.js +1 -0
- package/dist/web/.next-pack/static/chunks/app/page-e478eeb25eaa8664.js +1 -0
- package/lib/args.mjs +21 -1
- package/lib/home.mjs +15 -2
- package/lib/host.mjs +55 -0
- package/lib/preflight.mjs +11 -4
- package/lib/serve.mjs +16 -8
- package/package.json +2 -2
- package/dist/web/.next-pack/server/chunks/4410.js +0 -21
- package/dist/web/.next-pack/static/chunks/6292-137b6dd6a6850064.js +0 -1
- package/dist/web/.next-pack/static/chunks/app/(main)/briefing/page-e281f84f36f96ce7.js +0 -1
- package/dist/web/.next-pack/static/chunks/app/(main)/layout-3f9899440a0cbdc8.js +0 -1
- package/dist/web/.next-pack/static/chunks/app/page-0cf601f660005544.js +0 -1
- /package/dist/web/.next-pack/static/{pLc5i6XxW5YG-6IjzFPTO → bSsIsQRxqBbd4eDe1ibcc}/_buildManifest.js +0 -0
- /package/dist/web/.next-pack/static/{pLc5i6XxW5YG-6IjzFPTO → bSsIsQRxqBbd4eDe1ibcc}/_ssgManifest.js +0 -0
package/README.md
CHANGED
|
@@ -15,16 +15,17 @@ then starts the API and Web UI and opens your browser.
|
|
|
15
15
|
|
|
16
16
|
## Requirements
|
|
17
17
|
|
|
18
|
-
- Node.js 18+
|
|
18
|
+
- Node.js 18.18+ (19.x needs 19.8+)
|
|
19
19
|
- [uv](https://docs.astral.sh/uv/)
|
|
20
20
|
- [Claude Code](https://docs.claude.com/en/docs/claude-code) CLI, logged in, on a paid Claude plan (Pro/Max)
|
|
21
|
-
- macOS
|
|
21
|
+
- macOS. On Linux, use the [Docker setup](https://github.com/KazusaNakagawa/ai-agent-cli/blob/main/docs/guides/docker.md) instead
|
|
22
22
|
|
|
23
23
|
## Options
|
|
24
24
|
|
|
25
25
|
```
|
|
26
26
|
--port <n> Web UI port (default: 3000)
|
|
27
27
|
--api-port <n> API port (default: 8000)
|
|
28
|
+
--host <addr> Address the Web UI binds to (default: 127.0.0.1; for the Docker setup)
|
|
28
29
|
--home <dir> Data home (default: $BRIEF_LENS_HOME or ~/.brief-lens)
|
|
29
30
|
--no-browser Do not open the browser
|
|
30
31
|
-v, --version Print the version
|
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
あなたは株式市場アナリストです。必ず日本語で回答してください。
|
|
2
2
|
WebSearchを使って今日の最新情報を調べ、以下の監視セクター全件について動向をレポートしてください。
|
|
3
3
|
|
|
4
|
+
実行日: $today(日本時間)
|
|
5
|
+
|
|
6
|
+
## 調べ方のルール
|
|
7
|
+
- 各セクターは、そのセクターを対象にした検索を最低 1 回行う。市場全体の検索結果だけで済ませないこと。
|
|
8
|
+
- 使うのは、直前の取引日(週末や祝日の明けは、休場前の最後の取引日)から実行日までの記事だけ。休場中に出た記事も使ってよいが、直前の取引日の記事を必ず確認すること。前年以前の同じ日付の記事など、期間外の記事は根拠にしないこと。
|
|
9
|
+
- 期間内の記事が見つからないときは、クエリを変えて(英語と日本語の切り替え、企業名やティッカーでの検索など)もう一度検索する。
|
|
10
|
+
|
|
4
11
|
## 監視セクターと主要銘柄
|
|
5
12
|
各セクター全件について、今日の動きを調査してください。
|
|
6
13
|
$watch_sectors
|
|
@@ -13,7 +20,9 @@ $stocks
|
|
|
13
20
|
- `sectors` には上の監視セクターを全件、1セクター1回ずつ、セクター名をそのまま書いて入れる。
|
|
14
21
|
- 各セクターの `claims` は 0〜3 個。1つの claim は 1 文(目安 80 字以内)で、何が起きたか・なぜ動いたかを書く。
|
|
15
22
|
- **今日の株価・騰落率は書かないこと**(上の株価は動きの大小を判断する参考情報)。記事で確認した決算数値・受注額などは書いてよい。
|
|
16
|
-
-
|
|
23
|
+
- `claims` が空のセクターは、`empty_reason` に理由を必ず入れる。「監視を継続」のような中身のない claim で埋めないこと。
|
|
24
|
+
- `quiet`: 期間内の記事を確認したうえで、目立った動きがなかった(「動き限定的」とシステムが表示する)。
|
|
25
|
+
- `unverified`: 検索しても期間内の記事が見つからず、動きの有無を判断できなかった(「未確認」とシステムが表示する)。そのセクターを検索していない場合もこちら。
|
|
17
26
|
- `related_tickers` には claims に関係する銘柄のティッカーを最大 5 個入れる(なければ空)。
|
|
18
27
|
- `confidence` の付け方:
|
|
19
28
|
- `confirmed`: 記事で確認できた事実。必ず `source_ids` で出典を1つ以上挙げる。
|
|
@@ -21,7 +21,9 @@ Markdownで記述し、Notionで見やすくなるよう以下の構造を厳守
|
|
|
21
21
|
|
|
22
22
|
### 今日のセクター動向(全セクター)
|
|
23
23
|
|
|
24
|
-
|
|
24
|
+
監視セクター全件について記載する。
|
|
25
|
+
- 取得済み記事でそのセクターを確認でき、目立った動きがない場合は「動き限定的」と一言添える。
|
|
26
|
+
- 取得済み記事がそのセクターを扱っていない場合は「〔未確認〕今日の動きは確認できませんでした。」と書く。「動き限定的」にしない。
|
|
25
27
|
|
|
26
28
|
#### セクター名(例: AI・クラウド)
|
|
27
29
|
何が起きたか・なぜ動いたか(関連銘柄を括弧内に)
|
|
@@ -76,6 +76,13 @@ def build_journal_cmd(
|
|
|
76
76
|
f"{wrap_untrusted(journal_context, label='journal_entries')}\n"
|
|
77
77
|
"=== END ==="
|
|
78
78
|
)
|
|
79
|
+
if trusted_write_dirs:
|
|
80
|
+
# The working directory is read-only (#639): a bare file name would fail.
|
|
81
|
+
context += (
|
|
82
|
+
"\n\nファイルを保存できる場所は次のディレクトリの中だけです。"
|
|
83
|
+
"保存するときは、この中の絶対パスを指定してください:\n"
|
|
84
|
+
+ "\n".join(f"- {d}" for d in trusted_write_dirs)
|
|
85
|
+
)
|
|
79
86
|
return [
|
|
80
87
|
"claude",
|
|
81
88
|
"--session-id", session_id,
|
|
@@ -4,6 +4,9 @@ import shutil
|
|
|
4
4
|
import subprocess
|
|
5
5
|
import threading
|
|
6
6
|
import time
|
|
7
|
+
from collections.abc import Iterator
|
|
8
|
+
from contextlib import contextmanager
|
|
9
|
+
from contextvars import ContextVar
|
|
7
10
|
from dataclasses import dataclass
|
|
8
11
|
from datetime import datetime
|
|
9
12
|
|
|
@@ -293,6 +296,126 @@ def _warn_if_fell_back(result: _StreamResult, model: str, label: str) -> None:
|
|
|
293
296
|
)
|
|
294
297
|
|
|
295
298
|
|
|
299
|
+
class FallbackReport:
|
|
300
|
+
"""What the claude CLI did about fallbacks while a ``record_fallbacks`` scope was open.
|
|
301
|
+
|
|
302
|
+
``run_claude`` returns only text, so which model actually answered has no
|
|
303
|
+
other way out of it. Every successful call is counted, with the fallback
|
|
304
|
+
models it switched to (none for most calls), because a run made of several
|
|
305
|
+
calls can fall back on only some of them. Calls come from worker threads,
|
|
306
|
+
hence the lock.
|
|
307
|
+
"""
|
|
308
|
+
|
|
309
|
+
def __init__(self, parent: "FallbackReport | None" = None, *, deferred: bool = False) -> None:
|
|
310
|
+
self._models: list[str] = []
|
|
311
|
+
self._calls = 0
|
|
312
|
+
self._fallback_calls = 0
|
|
313
|
+
self._lock = threading.Lock()
|
|
314
|
+
self._parent = parent
|
|
315
|
+
# A deferred report keeps its calls to itself until ``commit()``, for
|
|
316
|
+
# callers that may still reject a response after run_claude returned it.
|
|
317
|
+
self._deferred = deferred
|
|
318
|
+
self._log: list[tuple[str, ...]] = []
|
|
319
|
+
|
|
320
|
+
def add_call(self, models: tuple[str, ...]) -> None:
|
|
321
|
+
"""Record one successful call and the fallback models it switched to."""
|
|
322
|
+
with self._lock:
|
|
323
|
+
self._calls += 1
|
|
324
|
+
if models:
|
|
325
|
+
self._fallback_calls += 1
|
|
326
|
+
for model in models:
|
|
327
|
+
if model not in self._models:
|
|
328
|
+
self._models.append(model)
|
|
329
|
+
self._log.append(models)
|
|
330
|
+
if self._parent is not None and not self._deferred:
|
|
331
|
+
self._parent.add_call(models)
|
|
332
|
+
|
|
333
|
+
def commit(self) -> None:
|
|
334
|
+
"""Hand the calls of a deferred report to the enclosing scope (no-op otherwise)."""
|
|
335
|
+
with self._lock:
|
|
336
|
+
if not self._deferred:
|
|
337
|
+
return
|
|
338
|
+
self._deferred = False
|
|
339
|
+
log = list(self._log)
|
|
340
|
+
if self._parent is not None:
|
|
341
|
+
for models in log:
|
|
342
|
+
self._parent.add_call(models)
|
|
343
|
+
|
|
344
|
+
@property
|
|
345
|
+
def models(self) -> tuple[str, ...]:
|
|
346
|
+
"""Distinct fallback models in the order they were first used."""
|
|
347
|
+
with self._lock:
|
|
348
|
+
return tuple(self._models)
|
|
349
|
+
|
|
350
|
+
@property
|
|
351
|
+
def partial(self) -> bool:
|
|
352
|
+
"""True when some, but not all, of the calls fell back."""
|
|
353
|
+
with self._lock:
|
|
354
|
+
return 0 < self._fallback_calls < self._calls
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
# Context-local, so two runs in one process (a briefing and a chat answer in the
|
|
358
|
+
# web server) never see each other's fallbacks. Threads started inside a scope
|
|
359
|
+
# do not inherit it on their own; see ``generator.briefing._submit``.
|
|
360
|
+
_fallback_report: ContextVar["FallbackReport | None"] = ContextVar("claude_fallback_report", default=None)
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
@contextmanager
|
|
364
|
+
def record_fallbacks() -> Iterator[FallbackReport]:
|
|
365
|
+
"""Collect the fallback models used by every ``run_claude`` call made inside.
|
|
366
|
+
|
|
367
|
+
Scopes nest: an inner scope also reports to the one around it.
|
|
368
|
+
"""
|
|
369
|
+
report = FallbackReport(parent=_fallback_report.get())
|
|
370
|
+
token = _fallback_report.set(report)
|
|
371
|
+
try:
|
|
372
|
+
yield report
|
|
373
|
+
finally:
|
|
374
|
+
_fallback_report.reset(token)
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
@contextmanager
|
|
378
|
+
def tentative_fallbacks() -> Iterator[FallbackReport]:
|
|
379
|
+
"""Like ``record_fallbacks``, but the enclosing scope only sees the calls after ``commit()``.
|
|
380
|
+
|
|
381
|
+
Use it around a call whose response the caller may still reject (schema
|
|
382
|
+
validation, retry), so a discarded attempt leaves no fallback model behind.
|
|
383
|
+
"""
|
|
384
|
+
report = FallbackReport(parent=_fallback_report.get(), deferred=True)
|
|
385
|
+
token = _fallback_report.set(report)
|
|
386
|
+
try:
|
|
387
|
+
yield report
|
|
388
|
+
finally:
|
|
389
|
+
_fallback_report.reset(token)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def describe_model(
|
|
393
|
+
primary: str, fallbacks: tuple[str, ...] | list[str] = (), *, partial: bool = False,
|
|
394
|
+
) -> str:
|
|
395
|
+
"""Name the model(s) that answered, e.g. for a footer or a log line.
|
|
396
|
+
|
|
397
|
+
- no fallback: ``primary``
|
|
398
|
+
- every call fell back: ``claude-haiku-5-5 (fallback from <primary>)``
|
|
399
|
+
- only some calls fell back (``partial``): ``<primary> (some calls fell back
|
|
400
|
+
to claude-haiku-5-5)``, so a reader does not take the whole run, the main
|
|
401
|
+
analysis included, to have come from the fallback.
|
|
402
|
+
"""
|
|
403
|
+
if not fallbacks:
|
|
404
|
+
return primary
|
|
405
|
+
names = ", ".join(fallbacks)
|
|
406
|
+
if partial:
|
|
407
|
+
return f"{primary} (some calls fell back to {names})"
|
|
408
|
+
return f"{names} (fallback from {primary})"
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _record_call(result: _StreamResult) -> None:
|
|
412
|
+
"""Count one successful call, with any fallback the CLI switched to, in the open scope."""
|
|
413
|
+
report = _fallback_report.get()
|
|
414
|
+
if report is not None:
|
|
415
|
+
# tuple() so a list (get_fallback_models() returns one) is not dropped.
|
|
416
|
+
report.add_call(tuple(getattr(result, "fallback_models", None) or ()))
|
|
417
|
+
|
|
418
|
+
|
|
296
419
|
def _backoff_delay(attempt: int) -> float:
|
|
297
420
|
"""Return the seconds to wait before the ``attempt``-th retry (1-indexed)."""
|
|
298
421
|
return RETRY_BASE_DELAY * (RETRY_BACKOFF_FACTOR ** (attempt - 1))
|
|
@@ -362,6 +485,9 @@ def run_claude(
|
|
|
362
485
|
"--output-format", "stream-json",
|
|
363
486
|
"--verbose",
|
|
364
487
|
"--include-partial-messages",
|
|
488
|
+
# --allowedTools only adds approvals, and the local settings may already
|
|
489
|
+
# allow a shell; --tools removes every other built-in tool (#639).
|
|
490
|
+
"--tools", "WebSearch",
|
|
365
491
|
"--allowedTools", "WebSearch",
|
|
366
492
|
"--model", model,
|
|
367
493
|
# Project-level settings.local.json can pre-approve Skill(*) and MCP
|
|
@@ -396,7 +522,11 @@ def run_claude(
|
|
|
396
522
|
if result.returncode == 0:
|
|
397
523
|
logger.info("claude CLI done: %s (%d chars)", label, len(result.stdout))
|
|
398
524
|
_warn_if_fell_back(result, model, label)
|
|
399
|
-
|
|
525
|
+
text = _parse_and_log_usage(result.stdout, label, structured=json_schema is not None)
|
|
526
|
+
# After parsing: a response that fails to parse is discarded and
|
|
527
|
+
# must not leave its fallback model in the report.
|
|
528
|
+
_record_call(result)
|
|
529
|
+
return text
|
|
400
530
|
|
|
401
531
|
logger.error(
|
|
402
532
|
"claude CLI error [%s] rc=%d attempt=%d/%d\nstdout=%s\nstderr=%s",
|
|
@@ -124,6 +124,12 @@ def set_credential(name: str, value: str) -> None:
|
|
|
124
124
|
_backend.set_password(service_name(), name, value)
|
|
125
125
|
|
|
126
126
|
|
|
127
|
+
def has_keychain_entry(name: str) -> bool:
|
|
128
|
+
"""True when the keychain holds ``name``; raises ``KeyringError`` if unreadable."""
|
|
129
|
+
_ensure_allowed(name)
|
|
130
|
+
return _backend.get_password(service_name(), name) is not None
|
|
131
|
+
|
|
132
|
+
|
|
127
133
|
def delete_credential(name: str) -> None:
|
|
128
134
|
_ensure_allowed(name)
|
|
129
135
|
_backend.delete_password(service_name(), name)
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import contextvars
|
|
1
2
|
import json
|
|
2
3
|
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
3
4
|
from datetime import date
|
|
@@ -6,7 +7,7 @@ from pathlib import Path
|
|
|
6
7
|
|
|
7
8
|
from pydantic import ValidationError
|
|
8
9
|
|
|
9
|
-
from src.claude_runner import run_claude
|
|
10
|
+
from src.claude_runner import run_claude, tentative_fallbacks
|
|
10
11
|
from src.config import BriefingConfig
|
|
11
12
|
from src.constants import (
|
|
12
13
|
BRIEFSCRIPT_VALIDATION_MAX_ATTEMPTS,
|
|
@@ -206,13 +207,16 @@ def _watch_sector_names(config: BriefingConfig) -> list[str]:
|
|
|
206
207
|
))
|
|
207
208
|
|
|
208
209
|
|
|
209
|
-
def generate_sectors_section(
|
|
210
|
+
def generate_sectors_section(
|
|
211
|
+
stocks: str, config: BriefingConfig, today: date | None = None,
|
|
212
|
+
) -> SectorsSection:
|
|
210
213
|
"""Run the sector sweep as validated BriefScript (#514)."""
|
|
211
214
|
sectors = _watch_sector_names(config)
|
|
212
215
|
prompt = render(
|
|
213
216
|
"briefing_sectors",
|
|
214
217
|
watch_sectors=build_watch_sectors_context(config),
|
|
215
218
|
stocks=stocks,
|
|
219
|
+
today=(today or date.today()).isoformat(),
|
|
216
220
|
)
|
|
217
221
|
return _generate_validated(
|
|
218
222
|
prompt, "セクタースイープ", TIMEOUT_BRIEFING_SECTORS, sectors_json_schema(sectors),
|
|
@@ -265,22 +269,28 @@ def _generate_validated(prompt: str, label: str, timeout: int, schema: dict, par
|
|
|
265
269
|
base_prompt = prompt
|
|
266
270
|
last_error = ""
|
|
267
271
|
for attempt in range(1, BRIEFSCRIPT_VALIDATION_MAX_ATTEMPTS + 1):
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
except (json.JSONDecodeError, ValidationError) as e:
|
|
275
|
-
last_error = str(e)
|
|
276
|
-
logger.warning(
|
|
277
|
-
"%s BriefScript failed validation (attempt %d/%d): %s",
|
|
278
|
-
label, attempt, BRIEFSCRIPT_VALIDATION_MAX_ATTEMPTS, _truncate_error(last_error),
|
|
279
|
-
)
|
|
280
|
-
prompt = (
|
|
281
|
-
f"{base_prompt}\n\n## 前回の出力のエラー\n"
|
|
282
|
-
f"前回の出力は次の検証エラーで却下されました。直して出力し直してください。\n{last_error}"
|
|
272
|
+
# An attempt's fallbacks reach the enclosing report only once its
|
|
273
|
+
# output validates, so a rejected attempt leaves no model behind.
|
|
274
|
+
with tentative_fallbacks() as attempt_report:
|
|
275
|
+
raw = run_claude(
|
|
276
|
+
prompt, label, timeout,
|
|
277
|
+
max_attempts=RETRY_MAX_ATTEMPTS_BRIEFING, json_schema=schema,
|
|
283
278
|
)
|
|
279
|
+
try:
|
|
280
|
+
parsed = parse(json.loads(raw))
|
|
281
|
+
except (json.JSONDecodeError, ValidationError) as e:
|
|
282
|
+
last_error = str(e)
|
|
283
|
+
else:
|
|
284
|
+
attempt_report.commit()
|
|
285
|
+
return parsed
|
|
286
|
+
logger.warning(
|
|
287
|
+
"%s BriefScript failed validation (attempt %d/%d): %s",
|
|
288
|
+
label, attempt, BRIEFSCRIPT_VALIDATION_MAX_ATTEMPTS, _truncate_error(last_error),
|
|
289
|
+
)
|
|
290
|
+
prompt = (
|
|
291
|
+
f"{base_prompt}\n\n## 前回の出力のエラー\n"
|
|
292
|
+
f"前回の出力は次の検証エラーで却下されました。直して出力し直してください。\n{last_error}"
|
|
293
|
+
)
|
|
284
294
|
raise BriefScriptError(f"{label} BriefScript invalid after retries: {_truncate_error(last_error)}")
|
|
285
295
|
|
|
286
296
|
|
|
@@ -345,6 +355,16 @@ def _sectors_block(section: SectorsSection, config: BriefingConfig) -> SectorsBl
|
|
|
345
355
|
return SectorsBlock(sectors=_watch_sector_names(config), content=section)
|
|
346
356
|
|
|
347
357
|
|
|
358
|
+
def _submit(executor: ThreadPoolExecutor, fn, /, *args, **kwargs):
|
|
359
|
+
"""Submit ``fn`` to run in a copy of the caller's context.
|
|
360
|
+
|
|
361
|
+
``ThreadPoolExecutor`` does not carry context variables into its workers, so
|
|
362
|
+
without this a ``record_fallbacks`` scope opened around the briefing would
|
|
363
|
+
miss every call made on the pool threads.
|
|
364
|
+
"""
|
|
365
|
+
return executor.submit(contextvars.copy_context().run, fn, *args, **kwargs)
|
|
366
|
+
|
|
367
|
+
|
|
348
368
|
def generate_briefing_document(
|
|
349
369
|
stocks: str,
|
|
350
370
|
config: BriefingConfig,
|
|
@@ -382,18 +402,18 @@ def generate_briefing_document(
|
|
|
382
402
|
)
|
|
383
403
|
with ThreadPoolExecutor(max_workers=3) as executor:
|
|
384
404
|
if briefscript:
|
|
385
|
-
main = executor
|
|
405
|
+
main = _submit(executor, generate_main_section, render("briefing_main", **main_parts), config)
|
|
386
406
|
else:
|
|
387
|
-
main =
|
|
388
|
-
run_claude, render("briefing", **main_parts), "メイン分析", TIMEOUT_BRIEFING_MAIN,
|
|
407
|
+
main = _submit(
|
|
408
|
+
executor, run_claude, render("briefing", **main_parts), "メイン分析", TIMEOUT_BRIEFING_MAIN,
|
|
389
409
|
max_attempts=RETRY_MAX_ATTEMPTS_BRIEFING,
|
|
390
410
|
)
|
|
391
411
|
futures = {
|
|
392
412
|
main: "main",
|
|
393
|
-
executor
|
|
413
|
+
_submit(executor, generate_sectors_section, stocks, config, today): "sectors",
|
|
394
414
|
}
|
|
395
415
|
if briefscript:
|
|
396
|
-
futures[executor
|
|
416
|
+
futures[_submit(executor, generate_holdings, stocks, config)] = "holdings"
|
|
397
417
|
results: dict = {}
|
|
398
418
|
errors: dict[str, str] = {}
|
|
399
419
|
for future in as_completed(futures):
|
|
@@ -19,7 +19,6 @@ from src.generator.briefscript_render import (
|
|
|
19
19
|
_FAILED_NOTE,
|
|
20
20
|
_MISSING_NOTE,
|
|
21
21
|
_MISSING_SECTOR_NOTE,
|
|
22
|
-
_QUIET_SECTOR_NOTE,
|
|
23
22
|
FX_HEADING,
|
|
24
23
|
GEOPOLITICS_HEADING,
|
|
25
24
|
HOLDINGS_HEADING,
|
|
@@ -27,6 +26,7 @@ from src.generator.briefscript_render import (
|
|
|
27
26
|
SECTORS_SECTION_HEADING,
|
|
28
27
|
STORIES_HEADING,
|
|
29
28
|
SUMMARY_HEADING,
|
|
29
|
+
_empty_sector_note,
|
|
30
30
|
_heading,
|
|
31
31
|
_number_sources,
|
|
32
32
|
_plain,
|
|
@@ -151,7 +151,7 @@ def _sectors_blocks(block: SectorsBlock) -> list[dict]:
|
|
|
151
151
|
if note is None:
|
|
152
152
|
blocks.append(_bullet(_text(_MISSING_SECTOR_NOTE)))
|
|
153
153
|
elif not note.claims:
|
|
154
|
-
blocks.append(_bullet(_text(
|
|
154
|
+
blocks.append(_bullet(_text(_empty_sector_note(note))))
|
|
155
155
|
else:
|
|
156
156
|
blocks += _claim_bullets(note.claims, numbers, section.sources)
|
|
157
157
|
tickers = [t for t in (_plain(x) for x in (note.related_tickers if note else ())) if t]
|
|
@@ -22,6 +22,7 @@ from src.generator.briefscript_schema import (
|
|
|
22
22
|
MarketSnapshot,
|
|
23
23
|
QuoteSnapshot,
|
|
24
24
|
SectorsBlock,
|
|
25
|
+
SectorNote,
|
|
25
26
|
SectorsSection,
|
|
26
27
|
Source,
|
|
27
28
|
)
|
|
@@ -47,7 +48,8 @@ _MISSING_NOTE = "〔未確認〕今日の材料は確認できませんでした
|
|
|
47
48
|
_FAILED_NOTE = "〔未確認〕本日の示唆は生成できませんでした。"
|
|
48
49
|
# Bullet for a sector with no claims: the model found no material move.
|
|
49
50
|
_QUIET_SECTOR_NOTE = "動き限定的"
|
|
50
|
-
# Bullet for a configured sector
|
|
51
|
+
# Bullet for a configured sector whose current news could not be confirmed:
|
|
52
|
+
# either nothing was returned for it, or its empty note is not marked quiet.
|
|
51
53
|
_MISSING_SECTOR_NOTE = "〔未確認〕今日の動きは確認できませんでした。"
|
|
52
54
|
|
|
53
55
|
_LEADING_HASHES = re.compile(r"^\s*#+\s*")
|
|
@@ -162,6 +164,10 @@ def render_holdings_markdown(
|
|
|
162
164
|
return "\n\n".join(blocks + _source_list(numbers, section.sources))
|
|
163
165
|
|
|
164
166
|
|
|
167
|
+
def _empty_sector_note(note: SectorNote) -> str:
|
|
168
|
+
return _QUIET_SECTOR_NOTE if note.empty_reason == "quiet" else _MISSING_SECTOR_NOTE
|
|
169
|
+
|
|
170
|
+
|
|
165
171
|
def render_sectors_markdown(section: SectorsSection, sectors: list[str]) -> str:
|
|
166
172
|
"""The sector sweep: every configured sector once, in configured order.
|
|
167
173
|
|
|
@@ -178,7 +184,7 @@ def render_sectors_markdown(section: SectorsSection, sectors: list[str]) -> str:
|
|
|
178
184
|
if note is None:
|
|
179
185
|
bullets = [f"- {_MISSING_SECTOR_NOTE}"]
|
|
180
186
|
elif not note.claims:
|
|
181
|
-
bullets = [f"- {
|
|
187
|
+
bullets = [f"- {_empty_sector_note(note)}"]
|
|
182
188
|
else:
|
|
183
189
|
bullets = [_bullet(c, numbers) for c in note.claims]
|
|
184
190
|
tickers = [t for t in (_plain(x) for x in (note.related_tickers if note else ())) if t]
|
|
@@ -24,6 +24,7 @@ from pydantic import (
|
|
|
24
24
|
ConfigDict,
|
|
25
25
|
Field,
|
|
26
26
|
HttpUrl,
|
|
27
|
+
PrivateAttr,
|
|
27
28
|
ValidationInfo,
|
|
28
29
|
field_validator,
|
|
29
30
|
model_validator,
|
|
@@ -90,8 +91,10 @@ class SectorNote(BaseModel):
|
|
|
90
91
|
model_config = _STRICT
|
|
91
92
|
|
|
92
93
|
sector: str = Field(min_length=1)
|
|
93
|
-
# Empty means no material move today; the renderer says so.
|
|
94
94
|
claims: list[Claim] = Field(default_factory=list, max_length=3)
|
|
95
|
+
# Why claims is empty (#613); ignored when there are claims. Only an explicit
|
|
96
|
+
# "quiet" is reported as a quiet day, so a missing value is not a retry.
|
|
97
|
+
empty_reason: Literal["quiet", "unverified"] | None = None
|
|
95
98
|
related_tickers: list[str] = Field(default_factory=list, max_length=5)
|
|
96
99
|
|
|
97
100
|
|
|
@@ -348,6 +351,25 @@ class BriefingDocument(BaseModel):
|
|
|
348
351
|
market: MarketSnapshot = Field(default_factory=MarketSnapshot)
|
|
349
352
|
sections: list[Section] = Field(default_factory=list)
|
|
350
353
|
|
|
354
|
+
# How this run was produced, not part of the briefing: kept out of the
|
|
355
|
+
# schema and the serialized form, and read by the deliveries for the footer.
|
|
356
|
+
_fallback_models: tuple[str, ...] = PrivateAttr(default=())
|
|
357
|
+
_fallback_partial: bool = PrivateAttr(default=False)
|
|
358
|
+
|
|
359
|
+
@property
|
|
360
|
+
def fallback_models(self) -> tuple[str, ...]:
|
|
361
|
+
"""Models the claude CLI fell back to while generating this briefing."""
|
|
362
|
+
return self._fallback_models
|
|
363
|
+
|
|
364
|
+
@property
|
|
365
|
+
def fallback_partial(self) -> bool:
|
|
366
|
+
"""True when only some of the generation calls fell back."""
|
|
367
|
+
return self._fallback_partial
|
|
368
|
+
|
|
369
|
+
def set_fallbacks(self, models: tuple[str, ...], partial: bool = False) -> None:
|
|
370
|
+
self._fallback_models = tuple(models)
|
|
371
|
+
self._fallback_partial = partial
|
|
372
|
+
|
|
351
373
|
|
|
352
374
|
def _fold(name: str, *, upper: bool) -> str:
|
|
353
375
|
# Tickers compare case-insensitively; sector names (often Japanese) only
|
|
@@ -20,7 +20,7 @@ from src.generator.briefscript_render import (
|
|
|
20
20
|
_CONFIDENCE_MARKERS,
|
|
21
21
|
_FAILED_NOTE,
|
|
22
22
|
_MISSING_NOTE,
|
|
23
|
-
|
|
23
|
+
_empty_sector_note,
|
|
24
24
|
FX_HEADING,
|
|
25
25
|
GEOPOLITICS_HEADING,
|
|
26
26
|
_heading,
|
|
@@ -118,7 +118,9 @@ def _holdings(deck: _Deck, block: HoldingsBlock, market: MarketSnapshot) -> None
|
|
|
118
118
|
|
|
119
119
|
def _sectors(deck: _Deck, block: SectorsBlock) -> None:
|
|
120
120
|
notes = {note.sector: note for note in block.content.sectors}
|
|
121
|
-
moved
|
|
121
|
+
moved: list[str] = []
|
|
122
|
+
# Sector names per empty-note label, so unconfirmed ones are not listed as quiet.
|
|
123
|
+
empty: dict[str, list[str]] = {}
|
|
122
124
|
for sector in dict.fromkeys(" ".join(s.split()) for s in block.sectors if s.strip()):
|
|
123
125
|
note = notes.get(sector)
|
|
124
126
|
if note is None:
|
|
@@ -127,10 +129,10 @@ def _sectors(deck: _Deck, block: SectorsBlock) -> None:
|
|
|
127
129
|
# One claim per sector: the deck is an overview, the page has the rest.
|
|
128
130
|
moved.append(f"- {_text(sector)}:{deck.claim(note.claims[0], block.content.sources)}")
|
|
129
131
|
else:
|
|
130
|
-
|
|
131
|
-
slides = _chunks(moved, deck.max_claims) or ([[]] if
|
|
132
|
-
if
|
|
133
|
-
slides[-1] = [*slides[-1], f"- {
|
|
132
|
+
empty.setdefault(_empty_sector_note(note), []).append(_text(sector))
|
|
133
|
+
slides = _chunks(moved, deck.max_claims) or ([[]] if empty else [])
|
|
134
|
+
if empty:
|
|
135
|
+
slides[-1] = [*slides[-1], *(f"- {label}:{', '.join(names)}" for label, names in empty.items())]
|
|
134
136
|
for lines in slides:
|
|
135
137
|
deck.add(_SECTORS_TITLE, lines)
|
|
136
138
|
|
|
@@ -35,6 +35,7 @@ _CLOSING = "以上です。"
|
|
|
35
35
|
_SPOKEN_CONFIDENCE = {"confirmed": "", "inferred": "推測ですが、", "unknown": "未確認ですが、"}
|
|
36
36
|
_QUOTE_FAILED = "株価を取得できませんでした"
|
|
37
37
|
_QUIET_SECTOR = "目立った動きはありませんでした"
|
|
38
|
+
_UNVERIFIED_SECTOR = "今日の動きを確認できませんでした"
|
|
38
39
|
|
|
39
40
|
# Written-only marks: emphasis, code, heading hashes, [n] citations and the
|
|
40
41
|
# 〔推測〕 / 〔未確認〕 markers the page versions carry.
|
|
@@ -110,7 +111,8 @@ def _sectors(block: SectorsBlock) -> list[list[str]]:
|
|
|
110
111
|
continue
|
|
111
112
|
name = _say(sector)
|
|
112
113
|
if not note.claims:
|
|
113
|
-
|
|
114
|
+
said = _QUIET_SECTOR if note.empty_reason == "quiet" else _UNVERIFIED_SECTOR
|
|
115
|
+
paragraphs.append([f"{name.rstrip('。')}は、{said}。"])
|
|
114
116
|
else:
|
|
115
117
|
paragraphs.append([name, *(_claim(c) for c in note.claims)])
|
|
116
118
|
return paragraphs
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""Generate the weekly briefing summary."""
|
|
2
2
|
from datetime import date, timedelta
|
|
3
3
|
|
|
4
|
-
from src.claude_runner import get_model, run_claude
|
|
4
|
+
from src.claude_runner import describe_model, get_model, record_fallbacks, run_claude
|
|
5
5
|
from src.constants import TIMEOUT_WEEKLY_SUMMARY
|
|
6
6
|
from src.generator.prompt import render
|
|
7
7
|
from src.logger import get_logger
|
|
@@ -39,4 +39,11 @@ def generate_weekly_summary(pages: list[dict]) -> str:
|
|
|
39
39
|
prompt = render("weekly_summary", briefings=_format_briefings(pages), week_label=week_label())
|
|
40
40
|
|
|
41
41
|
logger.info("generating weekly summary (model=%s, pages=%d)...", get_model(), len(pages))
|
|
42
|
-
|
|
42
|
+
with record_fallbacks() as fallbacks:
|
|
43
|
+
summary = run_claude(prompt, "週次サマリー生成", TIMEOUT_WEEKLY_SUMMARY)
|
|
44
|
+
# The line above names the model asked for; this one names the model that answered.
|
|
45
|
+
logger.info(
|
|
46
|
+
"weekly summary generated (model=%s)",
|
|
47
|
+
describe_model(get_model(), fallbacks.models, partial=fallbacks.partial),
|
|
48
|
+
)
|
|
49
|
+
return summary
|
|
@@ -10,7 +10,7 @@ existing tests.
|
|
|
10
10
|
from datetime import date
|
|
11
11
|
|
|
12
12
|
from src.charts.price_comparison import generate_price_comparison
|
|
13
|
-
from src.claude_runner import get_model
|
|
13
|
+
from src.claude_runner import describe_model, get_model, record_fallbacks
|
|
14
14
|
from src.config import CONFIG
|
|
15
15
|
from src.constants import (
|
|
16
16
|
BRIEFING_CHART_PERIOD,
|
|
@@ -116,12 +116,20 @@ def _briefing_md(ctx) -> str:
|
|
|
116
116
|
return render_document_markdown(ctx.results["generate"])
|
|
117
117
|
|
|
118
118
|
|
|
119
|
+
def _model_label(ctx) -> str:
|
|
120
|
+
"""The model that answered, naming any fallback the CLI switched to (#532)."""
|
|
121
|
+
doc = ctx.results["generate"]
|
|
122
|
+
return describe_model(get_model(), doc.fallback_models, partial=doc.fallback_partial)
|
|
123
|
+
|
|
124
|
+
|
|
119
125
|
def step_generate(ctx) -> BriefingDocument:
|
|
120
126
|
"""The briefing as IR (#513); deliveries render it on the way out."""
|
|
121
127
|
logger.info("generating briefing (WebSearch)...")
|
|
122
128
|
fx, fx_change_pct = ctx.results["fx"]
|
|
123
129
|
stocks, quotes = ctx.results["stocks"]
|
|
124
|
-
|
|
130
|
+
with record_fallbacks() as fallbacks:
|
|
131
|
+
doc = generate_briefing_document(stocks, CONFIG, fx, quotes=quotes, fx_change_pct=fx_change_pct)
|
|
132
|
+
doc.set_fallbacks(fallbacks.models, fallbacks.partial)
|
|
125
133
|
briefing = render_document_markdown(doc)
|
|
126
134
|
logger.debug("briefing generated (length=%d)", len(briefing))
|
|
127
135
|
|
|
@@ -235,7 +243,7 @@ def skip_notion(ctx) -> bool:
|
|
|
235
243
|
def step_deliver_notion(ctx) -> str | None:
|
|
236
244
|
logger.info("creating Notion page...")
|
|
237
245
|
briefing = _briefing_md(ctx)
|
|
238
|
-
footer = f"---\nModel: {
|
|
246
|
+
footer = f"---\nModel: {_model_label(ctx)}"
|
|
239
247
|
notion_text = f"{briefing}\n\n{footer}"
|
|
240
248
|
metrics = extract_briefing_metrics(briefing, CONFIG.portfolio.tickers)
|
|
241
249
|
page = dict(
|
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
"Cache rates follow the standard multipliers on the input rate -- 5-minute",
|
|
8
8
|
"write 1.25x, 1-hour write 2x, read 0.1x -- unless a model publishes its own,",
|
|
9
9
|
"as claude-fable-5-1 (0.025x) and claude-opus-5-5 / claude-sonnet-5-5 (0.05x) do for reads. There is no pricing API to fetch these",
|
|
10
|
-
"from
|
|
10
|
+
"from. The pricing doc is deliberately not auto-applied either (a missing rate is detectable, a wrong one is not);",
|
|
11
|
+
"see the \"Pricing\" section of docs/guides/usage-monitoring.md.",
|
|
11
12
|
"claude-haiku-5-5 is priced by prompt length; the entry holds the <=100k-token tier and is flagged \"tiered\": true,",
|
|
12
13
|
"so requests over 100k tokens are under-counted and a higher Claude Code bill is not reported as drift.",
|
|
13
14
|
"as_of is the date the table was last checked against the pricing doc (rate_check --check-upstream); the Monitor tab shows it. Bump it whenever you re-check."
|