diff --git a/skills/agent-reach/catalog-metadata.v1.json b/skills/agent-reach/catalog-metadata.v1.json index e369512..8a3ddd8 100644 --- a/skills/agent-reach/catalog-metadata.v1.json +++ b/skills/agent-reach/catalog-metadata.v1.json @@ -43,7 +43,7 @@ }, "reviewedAt": { "state": "known", - "value": "2026-10-19", + "value": "2026-11-24", "precision": "day" }, "upstreamObservedAt": { @@ -62,7 +62,7 @@ }, "governance": { "stewardship": "community", - "availability": "listing-only", + "availability": "installable", "license": { "state": "known", "value": "MIT", @@ -73,6 +73,13 @@ "name": "Panniantong", "url": "https://github.com/Panniantong/agent-reach", "verified": false + }, + "compliance": { + "licenseEvidencePath": "LICENSE", + "reviewedRef": "94f06c1969dfc1834001269d79d3ad0972d9dee6", + "reviewedAt": "2026-11-24", + "reviewedBy": "mashagua", + "upstreamEndorsed": false } }, "compatibility": { diff --git a/skills/ai-news-radar/LICENSE b/skills/ai-news-radar/LICENSE new file mode 100644 index 0000000..7be87c5 --- /dev/null +++ b/skills/ai-news-radar/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 LearnPrompt + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/skills/ai-news-radar/README.md b/skills/ai-news-radar/README.md new file mode 100644 index 0000000..ade6933 --- /dev/null +++ b/skills/ai-news-radar/README.md @@ -0,0 +1,3 @@ +# AI News Radar — local package + +See [English instructions](SKILL.md) or [中文说明](SKILL.zh-CN.md). Use Python 3.11+ and [the dependency list](requirements.txt). All output and private configuration must stay outside this directory. Use [the safe launcher](scripts/run_daily_brief.py), never the upstream relative-output default. The [MIT license](LICENSE) is copied verbatim; [UPSTREAM.md](UPSTREAM.md) records every imported file and its exact source commit. No historical data, private OPML, secrets, user mail or upstream deployment workflows are bundled. diff --git a/skills/ai-news-radar/SKILL.md b/skills/ai-news-radar/SKILL.md new file mode 100644 index 0000000..2c2a60d --- /dev/null +++ b/skills/ai-news-radar/SKILL.md @@ -0,0 +1,103 @@ +--- +name: ai-news-radar +description: Generate AI daily-brief JSON with a complete MIT Python package. Requires Python 3.11+, dependencies and feed + access; optional mail/API sources need separate authorization. +version: 2026.11.24 +license: MIT +type: hybrid +risk_level: medium +disable-model-invocation: true +tags: +- ai-news +- rss +- learnprompt +compatibility: Python 3.11+, requirements.txt, authorized feed access, and a private writable output directory outside this + skill. Optional email/API integrations require separate authorization and may incur service fees. +metadata: + author: LearnPrompt; DesireCore local packaging + updated_at: '2026-11-24' + i18n: + default_locale: en-US + source_locale: zh-CN + locales: + - en-US + - zh-CN + en-US: + name: AI News Radar + short_desc: Generate AI daily-brief JSON with a complete MIT Python package. Requires Python 3.11+, dependencies and + feed access; optional mail/API sources need separate authorization. + description: Optional local MIT edition based on LearnPrompt/ai-news-radar@689395109cc962a27c369bdd6fa50d1e090eb319. + Includes generation scripts, feed example, glossary, source-analysis helper, referenced docs and reader assets. Outputs + belong outside the installed skill; external services and optional credentials are separately configured. + body: ./SKILL.md + translated_by: ai:grok-bot + translated_at: '2026-11-24' + source_hash: sha256:870dccded1b7c11b + zh-CN: + name: AI 资讯雷达 + short_desc: 完整 MIT 本地包生成 AI 日报 JSON。需 Python 3.11+、依赖和信源访问;可选邮件/API 集成须独立授权。 + description: 基于 LearnPrompt/ai-news-radar@689395109cc962a27c369bdd6fa50d1e090eb319 的可选 MIT 本地版,包含生成脚本、信源示例、词表、分析工具、引用文档和阅读器资源。运行结果须写入安装目录之外;外部服务与可选凭据需单独配置。 + body: ./SKILL.zh-CN.md + translated_by: ai:grok-bot + translated_at: '2026-11-24' + source_hash: sha256:870dccded1b7c11b +market: + icon: + category: productivity + maintainer: + name: mashagua + url: https://github.com/mashagua + verified: true + channel: latest +--- + +# AI News Radar + +## Scope and provenance + +Generate AI daily-brief JSON from the complete local Python package, review public source quality, and optionally inspect the bundled reader assets. Read [package notes](README.md), [provenance and license](UPSTREAM.md), and [source intake](references/source-intake.md). This is a maintained MIT local edition based only on LearnPrompt/ai-news-radar commit `689395109cc962a27c369bdd6fa50d1e090eb319`; package version `2026.11.24` is not an upstream release. It is optional marketplace content, not an automatically installed builtin. + +## Prerequisites and boundaries + +Require Python 3.11+, `uv` or an equivalent private Python environment, the pinned packages in [requirements.txt](requirements.txt), and access to the user's selected public feeds. Dependency downloads and normal generation require network access; upstream websites can fail, change terms, or rate-limit requests. Report source failures honestly. Do not claim a live feed, authenticated service, deployment, or email test passed merely because installation or the offline fixture passed. + +Keep the installed directory read-only. Use [the safe launcher](scripts/run_daily_brief.py), which requires an absolute output directory outside the skill and suppresses bytecode writes. The unchanged [upstream generator](scripts/update_news.py) defaults to a relative output path; do not run its default command inside the skill. Never write a virtual environment, private OPML, generated data, logs, tokens, cookies, or email bodies into the installed skill or public repository. + +## Prepare a private run + +Set `SKILL_DIR` to the absolute installed directory, then choose a private working directory outside it. The following creates a fresh temporary working directory; use a private persistent directory instead when retention is wanted. + +```bash +RUN_DIR="$(mktemp -d "${TMPDIR:-/tmp}/ai-news-radar.XXXXXX")" +export SKILL_DIR RUN_DIR +cp "$SKILL_DIR/feeds/follow.example.opml" "$RUN_DIR/follow.opml" +uv run --with-requirements "$SKILL_DIR/requirements.txt" python -B "$SKILL_DIR/scripts/update_news.py" --help +``` + +Ask which sources the user wants. Edit only the private OPML copy, using the bundled [example OPML](feeds/follow.example.opml); do not collect credentials in chat. The supplied OPML is a public example, not the user's subscription list. + +## Generate the daily brief + +```bash +uv run --with-requirements "$SKILL_DIR/requirements.txt" python -B "$SKILL_DIR/scripts/run_daily_brief.py" --output-dir "$RUN_DIR/data" --window-hours 24 --rss-opml "$RUN_DIR/follow.opml" +``` + +Read the generated daily brief, latest 24-hour items, and source-status JSON in the chosen output directory. Those are generated outputs, not missing bundled resources. Empty history is supported; large upstream historical archives and translation caches are deliberately not shipped. [AI relevance](scripts/ai_relevance.py) and the optional [translation glossary](translation-glossary.txt) are included. The offline smoke test is fixture-based and does not establish current public-feed availability. + +## Review a candidate source + +Follow [source intake](references/source-intake.md) and [product method](references/v2-method.md). Prefer official RSS/Atom or public generated feeds over fragile scraping. [The overlap helper](scripts/evaluate_source_overlap.py) is included; use the generated archive in the private output directory as its baseline and save the advisory report outside the skill. A low overlap score is not proof of source quality or permission to scrape. + +## Optional local reader + +The [reader page](index.html), [reader code](assets/app.js), and [styles](assets/styles.css) are bundled with their local static dependencies. To preview, copy the page and assets into a private working site, generate its data there, and serve only that directory. Never start a server rooted in the installed skill or publish private outputs automatically. Reader screenshots and historical datasets are not runtime dependencies. The reader includes the classic view and web manifest; its optional GSAP animation script comes from jsDelivr under its separate terms and needs network access. For optional persona commentary, [the scorer](scripts/persona_score.py) and [persona definitions](personas/README.md) are included: use explicit private data and bundled persona directories. Set `PERSONA_ENABLED=0` for rules-only scoring; do not enable a paid DeepSeek API run without separate authorization and private credentials. The daily generator does not automatically run the scorer. + +## Optional private integrations + +Email, X, cookie-based sources and paid APIs are optional, separately authorized integrations, not bundled accounts or free service entitlements. Keep email disabled unless the user explicitly authorizes it (`EMAIL_DIGEST_ENABLED=1`); leave publication disabled. Use private host/vault configuration for credentials, never chat, history-token reuse, public files or logs. Obtain confirmation before any publication, email sending, account change, or charge. This skill's default task is read-only collection, not sending mail. Stop before an unavailable or unauthorized integration; do not fabricate success. + +## Reference material and validation + +The upstream [project guide](references/upstream-project-readme.md), [English guide](references/upstream-project-readme.en.md), [skill guide](references/upstream-skill-readme.md), [handoff notes](docs/GPT_HANDOFF.md), [source coverage](docs/SOURCE_COVERAGE.md), [roadmap](docs/ROADMAP.md), and [product brief](docs/V2_PRODUCT_BRIEF.md) are included as reference material. Their upstream development tests, external skill-creator tools, hosted site, GitHub Actions and publication workflows are not installed or invoked by this edition. Do not run upstream workflow/deployment instructions without a separate user request. Retain the verbatim [MIT license](LICENSE) and LearnPrompt attribution when redistributing. diff --git a/skills/ai-news-radar/SKILL.zh-CN.md b/skills/ai-news-radar/SKILL.zh-CN.md new file mode 100644 index 0000000..a33a912 --- /dev/null +++ b/skills/ai-news-radar/SKILL.zh-CN.md @@ -0,0 +1,50 @@ + + +# AI 资讯雷达 + +## 范围与来源 + +使用完整本地 Python 包生成 AI 日报 JSON、评估公开信源质量,并可查看随包阅读器资源。先读[安装说明](README.md)、[来源与许可](UPSTREAM.md)和[信源接入指南](references/source-intake.md)。这是仅基于 LearnPrompt/ai-news-radar 提交 `689395109cc962a27c369bdd6fa50d1e090eb319` 维护的 MIT 本地版;包版本 `2026.11.24` 不是上游发行版。本技能供市场可选安装,不会自动全局安装。 + +## 前提与边界 + +需要 Python 3.11+、`uv` 或等效私有 Python 环境、[requirements.txt](requirements.txt) 中固定的依赖,以及用户选定公开信源的访问条件。依赖下载和正常采集需要联网;上游网站可能失效、修改条款或限流。必须如实报告信源错误。安装成功或离线夹具通过,不代表实时信源、认证服务、部署或邮件已验收。 + +安装目录必须保持只读。使用[安全启动器](scripts/run_daily_brief.py):强制指定安装目录之外的绝对输出路径,并禁止写入字节码。未修改的[上游生成器](scripts/update_news.py) 默认使用相对输出路径;禁止在技能目录内直接运行默认命令。不得把虚拟环境、私人 OPML、生成数据、日志、token、cookies 或邮件正文写入安装目录或公共仓库。 + +## 准备私有运行目录 + +将 `SKILL_DIR` 设为实际安装目录的绝对路径,再选择其外部的私有工作目录。以下命令创建全新临时目录;需要保留结果时可改用私有持久目录。 + +```bash +RUN_DIR="$(mktemp -d "${TMPDIR:-/tmp}/ai-news-radar.XXXXXX")" +export SKILL_DIR RUN_DIR +cp "$SKILL_DIR/feeds/follow.example.opml" "$RUN_DIR/follow.opml" +uv run --with-requirements "$SKILL_DIR/requirements.txt" python -B "$SKILL_DIR/scripts/update_news.py" --help +``` + +先确认用户希望跟踪的信源。仅修改私有 OPML 副本,参考随包[示例 OPML](feeds/follow.example.opml),不要在聊天中收集凭据。随包 OPML 是公开示例,不是用户订阅清单。 + +## 生成日报 + +```bash +uv run --with-requirements "$SKILL_DIR/requirements.txt" python -B "$SKILL_DIR/scripts/run_daily_brief.py" --output-dir "$RUN_DIR/data" --window-hours 24 --rss-opml "$RUN_DIR/follow.opml" +``` + +从指定输出目录读取日报、最近 24 小时条目和信源状态 JSON。这些文件是运行产物,并非漏装资源。支持无历史数据首跑;不分发上游巨型历史归档或翻译缓存。已包含 [AI 相关性模块](scripts/ai_relevance.py)及可选[翻译词表](translation-glossary.txt)。离线冒烟仅使用夹具,不证明公开信源当前可用。 + +## 评估候选信源 + +遵循[接入指南](references/source-intake.md)和[产品方法](references/v2-method.md)。优先官方 RSS/Atom 或公开生成的 feed,避免脆弱抓取。已包含[信源重叠分析工具](scripts/evaluate_source_overlap.py);基线使用私有输出目录内生成的归档,建议报告也必须保存到技能之外。低重叠率不代表质量合格或拥有抓取授权。 + +## 可选本地阅读器 + +已包含[阅读器页面](index.html)、[阅读器代码](assets/app.js)、[样式](assets/styles.css)和本地静态依赖。预览时,把页面和资源复制到私有工作站点,在那里生成数据,且只为该目录启动服务。不得把服务根目录指向已安装技能,也不得自动公开私有结果。阅读器截图和历史数据不是运行依赖。已包含经典视图和 Web manifest;可选 GSAP 动画脚本来自 jsDelivr,需联网并遵守其独立条款。可选点评已包含[评分脚本](scripts/persona_score.py)和[人物定义](personas/README.md),须显式指定私有数据目录及随包人物目录。设置 `PERSONA_ENABLED=0` 可仅用规则评分;没有另行授权和私有凭据时不得启用收费的 DeepSeek API。日报生成器不会自动运行点评脚本。 + +## 可选私有集成 + +邮件、X、依赖 cookies 的信源及付费 API 都需独立授权,不附送账号或免费服务额度。邮件默认禁用,只有用户明确授权后才可设置 `EMAIL_DIGEST_ENABLED=1`,仍保持禁止发布。凭据只进私有主机或凭据库配置,不进入聊天、历史 token 复用、公共文件或日志。任何发布、发邮件、修改账号或收费前都须确认。本技能默认只读采集,不发送邮件。集成未就绪或未获授权时先停止,不得伪造成功。 + +## 参考资料与验证 + +随包提供上游[项目指南](references/upstream-project-readme.md)、[英文指南](references/upstream-project-readme.en.md)、[技能指南](references/upstream-skill-readme.md)、[交接说明](docs/GPT_HANDOFF.md)、[信源覆盖](docs/SOURCE_COVERAGE.md)、[路线图](docs/ROADMAP.md)和[产品简报](docs/V2_PRODUCT_BRIEF.md),仅供参考。该版本不会安装或调用上游开发测试、外部技能校验器、托管网站、GitHub Actions 或发布工作流。没有另行请求时,不得执行参考文档中的上游工作流或部署指令。再分发时保留原文 [MIT 许可](LICENSE)和 LearnPrompt 署名。 diff --git a/skills/ai-news-radar/UPSTREAM.md b/skills/ai-news-radar/UPSTREAM.md new file mode 100644 index 0000000..85563c7 --- /dev/null +++ b/skills/ai-news-radar/UPSTREAM.md @@ -0,0 +1,64 @@ +# Upstream provenance and local edition + +Source: https://github.com/LearnPrompt/ai-news-radar/tree/689395109cc962a27c369bdd6fa50d1e090eb319 +Immutable source commit: `689395109cc962a27c369bdd6fa50d1e090eb319`. Local packaging version: `2026.11.24` (not an upstream release). + +Copyright (c) 2026 LearnPrompt. The 1,068-byte upstream MIT [LICENSE](LICENSE) is preserved verbatim. This is an independently maintained market packaging, not upstream endorsement. + +## Changes and exclusions + +- Generator, relevance module, overlap helper, requirements, example feed, glossary, original references and selected reader assets (except the explicitly noted classic-page links and CSS EOF whitespace) are byte-identical to the pinned source. No files come from current upstream HEAD. +- Local bilingual SKILL/README instructions replace repository-development guidance with installed-package usage. The new safe launcher requires external absolute output and disables bytecode writes. +- Imported project/skill guides and development docs have an explanatory reference notice and immutable upstream Markdown links. They are reference material, not installed development workflows. +- All original SKILL direct runtime/doc/UI references are represented below. Private feeds, generated data, giant historical archives/caches, screenshots, upstream tests/workflows and external skill-creator tools are not installed; the local SKILL makes no claim they are. Empty history is supported by the unchanged generator. +- Output JSON paths are generated inside the explicitly selected private output directory, not pre-existing package resources. Optional email, social and paid adapters remain separately configured and authorized. + +- The classic reader service-status links are normalized for its existing base href. Optional persona scoring and its three prompt files are included; it requires separately authorized provider configuration and is not part of the offline news-generation test. Legacy reader pages are not shipped. +- The optional reader loads GSAP 3.13.0 from jsDelivr with upstream integrity metadata; this third-party CDN dependency is not vendored and requires network access. + +## Imported source manifest + +| Upstream path | Package path | Source bytes | Source SHA-256 | Changes | +|---|---|---:|---|---| +| LICENSE | LICENSE | 1068 | 1eef1394cbdc77865323cb153d3ffc241af74184246ee253ce5bcfd65b61cc0b | none | +| assets/app.js | assets/app.js | 92066 | 4ee5e351689fb88020c726affdd1bf767bb6b42aa2aa90e6f770f25f1b8eafaa | none | +| assets/icons/apple-touch-icon.png | assets/icons/apple-touch-icon.png | 27296 | 2a3dbb278f16bf538dbbe29fada7b28dddecc3d51f7506d793964e808850d1b7 | none | +| assets/icons/favicon-32.png | assets/icons/favicon-32.png | 2578 | 70a1aa71a978aafbe06ecb8a78cddf0f1f2c16644b59c5f20ec4a90b3464f6a6 | none | +| assets/icons/icon-192.png | assets/icons/icon-192.png | 28836 | 1a3075115f032bee0005ad02a50dcba0c60006e6fd130caa74816081c001df0c | none | +| assets/icons/icon-512.png | assets/icons/icon-512.png | 77149 | 6b2899f623812c35edc3f3a31a5c942229d6a2369639cd971592f827e24d757f | none | +| assets/logo.svg | assets/logo.svg | 1258 | 89c98d5e8288984f204da770eebb7f0dfc37f3e29daeb58787fd69adfbe9fafd | none | +| assets/motion.js | assets/motion.js | 1281 | b27fae1fd3990aced1c803ce619686eadd888b9059933680b4ffd8e7c5118dcd | none | +| assets/og.png | assets/og.png | 48055 | 21cb49329c88a13b1ff149603dbacd872f206ae9e018e2fc4f86fdf49034f5b1 | none | +| assets/service-status.css | assets/service-status.css | 2130 | cbb4e02f81e4f91d7b97d6c9262bccae8f53e831122d976e90cfd85dc525905d | none | +| assets/service-status.js | assets/service-status.js | 5369 | 0aa01cd32c346d778badd1ce51636da77188701f989cc2f99921a42810b7a78f | none | +| assets/styles.css | assets/styles.css | 38747 | 889a68cb3c4c1a3bca9181493612c09bc7cea31e8ebb3bfbd4477eca28e49140 | trim extra blank line at EOF only | +| assets/view-mode.js | assets/view-mode.js | 4373 | 77c2f6834fc7e64f31e0c28a302b9c57a7868aa5f6856300d36f7e8905dac8a2 | none | +| assets/view-switch.css | assets/view-switch.css | 2528 | 05b70dd29586a784674f59472f5c9aa5532ac7fe544510ee82fc711a47a0feab | none | +| feeds/follow.example.opml | feeds/follow.example.opml | 2400 | c8f61d59f098f4e0da0de35356b6eae90eb3c4a794b057afd40048bc6ba42ede | none | +| index.html | index.html | 10230 | fac7af098270897f347f46e777a1e8227863fcb2fb642d0f6eead57bce6d2c73 | none | +| requirements.txt | requirements.txt | 88 | f206ef31decbffd0ade3fbfebb513158ad27521ee541969e517535865c629ba8 | none | +| scripts/ai_relevance.py | scripts/ai_relevance.py | 13733 | 97d1ea44d04663d21af8ac60ed3b26bd9ee4b55418e6979a31baeea6df0bb4bb | none | +| scripts/evaluate_source_overlap.py | scripts/evaluate_source_overlap.py | 15274 | 9558f13ffc310d4d8523f22d77280f5a470f2e5df3c1c9d477461ac91f9d8375 | none | +| scripts/update_news.py | scripts/update_news.py | 273569 | 7cf57bb45f8ea48e731d7dd8b27392c4ec2e5844acfd7c137edf0920e03a1165 | none | +| skills/ai-news-radar/agents/openai.yaml | agents/openai.yaml | 294 | 1fbeab04768ce9d0ea35d8c1ae177f626235c2ec615cf7584688d93ca2606324 | none | +| skills/ai-news-radar/references/source-intake.md | references/source-intake.md | 6737 | 1e18da6313d647924c68b49bdc86873b829fa343c55f0dd727f240f6e820692c | none | +| skills/ai-news-radar/references/v2-method.md | references/v2-method.md | 4218 | f415f236fce6981e6f05e063f463e8a412e4cd9b964550184f1b3db7b2c4e8b7 | none | +| translation-glossary.txt | translation-glossary.txt | 1181 | 8eb25938e8436c0f989dbb9f6bc9721cba83889bb48d26fde867d385e65b8b4a | none | +| README.md | references/upstream-project-readme.md | 27963 | 660d1359c8ce8cf50e6b051a67de1158353238a4506d06579d9b0ffa5333968c | reference notice and immutable upstream Markdown links | +| README.en.md | references/upstream-project-readme.en.md | 25716 | 4ced637ac7f9040824774d25de5a0bce4bafaa3a4afcef47aa824fe1a00318ec | reference notice and immutable upstream Markdown links | +| skills/ai-news-radar/README.md | references/upstream-skill-readme.md | 14882 | cea932f854bbbc8473ec1a7fd58e5018833e338fcd7a645da2a3d9fbe1e6fa64 | reference notice and immutable upstream Markdown links; normalize trailing whitespace | +| docs/GPT_HANDOFF.md | docs/GPT_HANDOFF.md | 4650 | cea73994fee7ed4f4485ddb284d4bc66d55aa862412056ba2831ebeabf71f46e | reference notice and immutable upstream Markdown links | +| docs/ROADMAP.md | docs/ROADMAP.md | 5051 | ae5091f2fd10eed5f9e35d5471e4d5c4c70b6cf2ca445cca1db083edb8115934 | reference notice and immutable upstream Markdown links | +| docs/SOURCE_COVERAGE.md | docs/SOURCE_COVERAGE.md | 16386 | 14dc0f660bb5b4d5a89bcfa096ae4aad2d8adea876c5705cd601b9cf4ecc94f0 | reference notice and immutable upstream Markdown links | +| docs/V2_PRODUCT_BRIEF.md | docs/V2_PRODUCT_BRIEF.md | 2129 | ff52e938535276b18d70af846659adfecdf56d105310591bd4c6133a499dd2c3 | reference notice and immutable upstream Markdown links | +| site.webmanifest | site.webmanifest | 563 | 5659abfef2d7f05b9a6ace0a876ef8e4ea44e3cc00b0f82fd8b9626feea1d1b9 | none | +| classic/index.html | classic/index.html | 11772 | beeb670897d9aaadcd90b858b7faad260c4f3130cc8c505b52527bd4576f772b | normalize service-status asset links under upstream base href | +| scripts/__init__.py | scripts/__init__.py | 28 | c2bbbed5cc8ac8d07249f7d977b61fe2309393444646d0d449b6d7ce7dcf2434 | none | +| scripts/persona_score.py | scripts/persona_score.py | 16284 | 2076ac04af453de9a8c3704f83941fd8fa47b7c29bd3bc4679ec6ed47f001926 | none | +| classic/assets/app.js | classic/assets/app.js | 121340 | 08afcfe3e8184f3ab364ae7a8ae39f6e57ee2c376076b866c22aa029ad2c45a9 | none | +| classic/assets/motion.js | classic/assets/motion.js | 3185 | 90102cd08928d9389fa78dc83a666d58a423202591a3865dd67d78b1cbd95918 | none | +| classic/assets/styles.css | classic/assets/styles.css | 48135 | 1d07798dc15c4dd3360496ee2f8865611cba09db4fe3bfaded9a20b00b46cdff | none | +| personas/README.md | personas/README.md | 2379 | 3f751906d12eeec8945c6e4e903fb5407103df0c2106f2d589f1d3ac00f9dafd | none | +| personas/cynic.md | personas/cynic.md | 1611 | 72a3c6e4b8619f1568d56af45c57df8b7ff06f4fc80afd17b264df9d3903d6cb | none | +| personas/paper-police.md | personas/paper-police.md | 1679 | 12080a8c861872a214e8a250b63232dea1be53bb87263ed98ff65bd2deb64911 | none | +| personas/pragmatic.md | personas/pragmatic.md | 1674 | d61315341defc8b786aa435dadc19a3fbacd919aa5520644f68addcfd17a79b9 | none | diff --git a/skills/ai-news-radar/agents/openai.yaml b/skills/ai-news-radar/agents/openai.yaml new file mode 100644 index 0000000..e85837f --- /dev/null +++ b/skills/ai-news-radar/agents/openai.yaml @@ -0,0 +1,6 @@ +interface: + display_name: "AI News Radar" + short_description: "Review and extend AI news source coverage" + default_prompt: "Use $ai-news-radar to run a v2 source-coverage review, then add or route this AI news source safely if it fits the project." +policy: + allow_implicit_invocation: true diff --git a/skills/ai-news-radar/assets/app.js b/skills/ai-news-radar/assets/app.js new file mode 100644 index 0000000..5fc00b7 --- /dev/null +++ b/skills/ai-news-radar/assets/app.js @@ -0,0 +1,2352 @@ +const state = { + itemsAi: [], + itemsAll: [], + itemsAllRaw: [], + creatorItemsAi: [], + creatorItemsAll: [], + creatorWindowDays: 7, + statsAi: [], + totalAi: 0, + totalRaw: 0, + totalAllMode: 0, + allDedup: true, + allDataLoaded: false, + allDataUrl: "data/latest-24h-all.json", + allDataPromise: null, + siteFilter: "", + authorFilter: "", + query: "", + // 单层信息架构:category(内容 tab) x mode(精选/全量全局开关)两个维度。 + // mode=selected 主列表读 mergedStories()(AI 相关合并事件池,纯时间倒序); + // mode=all 主列表读 itemsAllRaw/itemsAll(全量原始条目池)。 + mode: "selected", + waytoagiMode: "today", + waytoagiData: null, + sourceStatus: null, + generatedAt: null, + dailyBrief: null, + top3Personas: null, + storiesMerged: null, + storiesDataUrl: "data/stories-merged.json", + // 内容 tab:单值,默认 "all"(全部,无过滤) + activeSection: "all", + mainListVisibleCount: 0, + xAuthorsExpanded: false, +}; + +// DATA_BASE_URL 数据同源开关:优先级 ?data= 查询参数 > localStorage("dataBaseUrl") > "" (相对路径,原行为) +// ?data= 命中时持久化到 localStorage,方便刷新/后续访问保持同一数据源。 +function resolveDataBaseUrl() { + let fromQuery = ""; + try { + fromQuery = new URLSearchParams(window.location.search).get("data") || ""; + } catch { + fromQuery = ""; + } + if (fromQuery) { + const normalized = fromQuery.trim().replace(/\/+$/, ""); + try { localStorage.setItem("dataBaseUrl", normalized); } catch {} + return normalized; + } + try { + const stored = localStorage.getItem("dataBaseUrl") || ""; + return stored.trim().replace(/\/+$/, ""); + } catch { + return ""; + } +} + +state.dataBaseUrl = resolveDataBaseUrl(); + +// 所有 data/*.json 抓取都必须经过这个 helper,才能让 ?data= / localStorage 覆盖生效。 +// 传入的 path 可能是 "data/xxx.json"(本地默认)或后端下发的同款相对路径; +// 一旦切换到远端 base,只拼文件名,避免拼出 base/data/xxx.json 这种双重 data/ 路径。 +function dataUrl(path) { + const base = state.dataBaseUrl; + if (!base) return path; + const file = String(path || "").split("/").pop(); + return `${base}/${file}`; +} + +const siteSelectEl = document.getElementById("siteSelect"); +const newsListEl = document.getElementById("newsList"); +const updatedAtEl = document.getElementById("updatedAt"); +const sourceStatusPillEl = document.getElementById("sourceStatusPill"); +const searchInputEl = document.getElementById("searchInput"); +const resultCountEl = document.getElementById("resultCount"); +const listTitleEl = document.getElementById("listTitle"); +const itemTpl = document.getElementById("itemTpl"); +const modeSelectedBtnEl = document.getElementById("modeSelectedBtn"); +const modeAllBtnEl = document.getElementById("modeAllBtn"); +const hotBoardWrapEl = document.getElementById("hotBoardWrap"); +const hotBoardListEl = document.getElementById("hotBoardList"); +const hotBoardMetaEl = document.getElementById("hotBoardMeta"); +const top3BoardWrapEl = document.getElementById("top3BoardWrap"); +const top3BoardListEl = document.getElementById("top3BoardList"); +const top3BoardMetaEl = document.getElementById("top3BoardMeta"); +const newsListWrapEl = document.getElementById("newsListWrap"); +const modeHintEl = document.getElementById("modeHint"); +const allDedupeWrapEl = document.getElementById("allDedupeWrap"); +const allDedupeToggleEl = document.getElementById("allDedupeToggle"); +const allDedupeLabelEl = document.getElementById("allDedupeLabel"); +const sourceHealthEl = document.getElementById("sourceHealth"); +const sourceHealthDetailsEl = document.getElementById("sourceHealthDetails"); +const sourceStatusTableEl = document.getElementById("sourceStatusTable"); +const clearFiltersBtnEl = document.getElementById("clearFiltersBtn"); +const dataSourceIndicatorEl = document.getElementById("dataSourceIndicator"); +const dataSourceIndicatorTextEl = document.getElementById("dataSourceIndicatorText"); +const dataSourceResetBtnEl = document.getElementById("dataSourceResetBtn"); + +const waytoagiWrapEl = document.querySelector(".waytoagi-wrap"); +const waytoagiUpdatedAtEl = document.getElementById("waytoagiUpdatedAt"); +const waytoagiMetaEl = document.getElementById("waytoagiMeta"); +const waytoagiListEl = document.getElementById("waytoagiList"); +const waytoagiTodayBtnEl = document.getElementById("waytoagiTodayBtn"); +const waytoagi7dBtnEl = document.getElementById("waytoagi7dBtn"); +const sectionTabsEl = document.getElementById("sectionTabs"); + +const SOURCE_KINDS = { + official_ai: { label: "官方", tone: "official" }, + curated_media: { label: "精选媒体", tone: "aihub" }, + aihot: { label: "AI HOT", tone: "hot" }, + aibreakfast: { label: "日报", tone: "newsletter" }, + followbuilders: { label: "Builders/X", tone: "builders" }, + xapi: { label: "X API", tone: "builders" }, + socialdata_x: { label: "X 搜索", tone: "builders" }, + tikhub_douyin: { label: "抖音", tone: "creator" }, + tikhub_xiaohongshu: { label: "小红书", tone: "creator" }, + techurls: { label: "聚合", tone: "aggregate" }, + buzzing: { label: "聚合", tone: "aggregate" }, + iris: { label: "聚合", tone: "aggregate" }, + bestblogs: { label: "博客", tone: "blogs" }, + zeli: { label: "聚合", tone: "aggregate" }, + hackernews: { label: "HN", tone: "aggregate" }, + aihubtoday: { label: "AI站点", tone: "aihub" }, + aibase: { label: "AI站点", tone: "aihub" }, + waytoagi: { label: "社区", tone: "builders" }, + newsnow: { label: "聚合", tone: "aggregate" }, + opmlrss: { label: "OPML", tone: "newsletter" }, +}; + +// aihotSubSource() 结果 → 卡片小标签文案/色调,色调复用既有 .category.kind-* 规则,不新增样式 +const AIHOT_SUB_LABELS = { x: "X", wechat: "公众号", hn: "HN", rss: "RSS" }; +const AIHOT_SUB_TONES = { x: "builders", wechat: "creator", hn: "aggregate", rss: "newsletter" }; + +// 单层内容 tab:全部(默认,无过滤)+ 5 个主题栏目 + 社区 + 自媒体,互斥单值。 +const SECTION_DEFS = [ + { id: "all", label: "全部", short: "全部", description: "不筛选内容栏目,查看全部信号" }, + { id: "models", label: "模型", short: "模型", description: "模型发布、能力升级、评测与开源权重" }, + { id: "products", label: "产品", short: "产品", description: "AI 应用、Agent、生成工具和用户产品更新" }, + { id: "devtools", label: "开发者", short: "开发者", description: "编程工具、API、开源项目、推理与工程实践" }, + { id: "industry", label: "行业", short: "行业", description: "公司战略、融资收购、监管、芯片与产业变化" }, + { id: "research", label: "论文", short: "论文", description: "论文、基准、方法、数据集与研究团队动态" }, + { id: "community", label: "社区", short: "社区", description: "HN、中文技术社区与社群动态" }, + { id: "creator", label: "自媒体", short: "自媒体", description: "抖音、小红书等自媒体创作者内容" }, +]; + +const SECTION_BY_ID = Object.fromEntries(SECTION_DEFS.map((section) => [section.id, section])); + +function fmtNumber(n) { + return new Intl.NumberFormat("zh-CN").format(n || 0); +} + +const UNSAFE_HARD_PATTERNS = [ + /\bcreampie\b/i, + /\bblowjob\b/i, + /\bsuck (?:your|my) (?:dick|cock)\b/i, + /中出|婊子|吸你的鸡鸡|操虚拟女友/i, +]; + +const UNSAFE_PROMO_PATTERNS = [ + /\b(?:nsfw|nudes?|porn(?:ography)?)\b/i, + /\buncensored pictures?\b/i, + /\bvirtual girlfriends?\b/i, + /\bknock her up\b/i, + /未经审查的图片|虚拟女友|色情内容|成人内容/i, +]; + +function contentSafetyText(record) { + return [ + record?.title, + record?.title_zh, + record?.title_en, + record?.title_original, + record?.source, + record?.source_name, + ].filter(Boolean).join(" "); +} + +function isUnsafeContent(record) { + const text = contentSafetyText(record); + if (!text) return false; + if (UNSAFE_HARD_PATTERNS.some((pattern) => pattern.test(text))) return true; + return UNSAFE_PROMO_PATTERNS.filter((pattern) => pattern.test(text)).length >= 2; +} + +function safeItems(items) { + return (Array.isArray(items) ? items : []).filter((item) => !isUnsafeContent(item)); +} + +function isUnsafeStory(story) { + const refs = [ + story, + story?.primary_item, + ...(Array.isArray(story?.sources) ? story.sources : []), + ...(Array.isArray(story?.items) ? story.items : []), + ].filter(Boolean); + return refs.some((ref) => isUnsafeContent(ref)); +} + +function fmtTime(iso) { + if (!iso) return "时间未知"; + const d = new Date(iso); + if (Number.isNaN(d.getTime())) return "时间未知"; + return new Intl.DateTimeFormat("zh-CN", { + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + }).format(d); +} + +function fmtDate(iso) { + if (!iso) return "未知日期"; + const d = new Date(`${iso}T00:00:00`); + if (Number.isNaN(d.getTime())) return iso; + return new Intl.DateTimeFormat("zh-CN", { + month: "2-digit", + day: "2-digit", + }).format(d); +} + +function fmtHHMM(ms) { + if (!ms) return "--:--"; + const d = new Date(ms); + if (Number.isNaN(d.getTime())) return "--:--"; + return new Intl.DateTimeFormat("zh-CN", { hour: "2-digit", minute: "2-digit", hour12: false }).format(d); +} + +function fmtRelativeTime(ms) { + if (!ms) return "时间未知"; + const diff = Date.now() - ms; + if (diff < 0) return "刚刚"; + const minutes = Math.round(diff / 60000); + if (minutes < 60) return `${Math.max(1, minutes)} 分钟前`; + const hours = Math.round(minutes / 60); + if (hours < 48) return `${hours} 小时前`; + return `${Math.round(hours / 24)} 天前`; +} + +function failedSourceCount(status = state.sourceStatus) { + const failedSites = Array.isArray(status?.failed_sites) ? status.failed_sites.length : 0; + const rss = status?.rss_opml || {}; + const failedFeeds = Array.isArray(rss.failed_feeds) ? rss.failed_feeds.length : 0; + return failedSites + failedFeeds; +} + +function renderSourceStatusPill(errorMessage = "") { + if (!sourceStatusPillEl) return; + const status = state.sourceStatus; + sourceStatusPillEl.className = "source-status-pill"; + if (!status) { + sourceStatusPillEl.textContent = errorMessage || "源状态加载中"; + if (errorMessage) sourceStatusPillEl.classList.add("bad"); + return; + } + const totalSites = Array.isArray(status.sites) ? status.sites.length : 0; + const okSites = Number(status.successful_sites || 0); + const failed = failedSourceCount(status); + sourceStatusPillEl.textContent = failed + ? `${fmtNumber(okSites)}/${fmtNumber(totalSites)} 源正常 · 失败 ${fmtNumber(failed)}` + : `${fmtNumber(okSites)}/${fmtNumber(totalSites)} 源正常`; + if (failed) sourceStatusPillEl.classList.add("warn"); +} + +// 模式文案:精选(AI 相关合并事件池,纯时间序)/ 全量(原始条目池) +function modeLabelText() { + return state.mode === "all" ? "全量" : "精选"; +} + +function sourceKind(siteId) { + return SOURCE_KINDS[siteId] || { label: "来源", tone: "default" }; +} + +function sourceSignalTone(signal) { + const text = String(signal || "").toLowerCase(); + if (text.includes("官方") || text.includes("official")) return "official"; + if (text.includes("ai hot") || text.includes("精选")) return "hot"; + if (text.includes("自媒体") || text.includes("tikhub") || text.includes("douyin") || text.includes("xiaohongshu") || text.includes("抖音") || text.includes("小红书")) return "creator"; + if (text.includes("builders") || text.includes("github") || text.includes("x")) return "builders"; + if (text.includes("aihub") || text.includes("aibase") || text.includes("媒体")) return "aihub"; + if (text.includes("hn") || text.includes("hacker") || text.includes("聚合")) return "aggregate"; + if (text.includes("opml") || text.includes("日报")) return "newsletter"; + return "default"; +} + +function sourceChip(label, tone = "default", className = "source-chip") { + const chip = document.createElement("span"); + chip.className = `${className} kind-${tone}`.trim(); + const dot = document.createElement("span"); + dot.className = "source-dot"; + dot.setAttribute("aria-hidden", "true"); + const text = document.createElement("span"); + text.className = "source-chip-label"; + text.textContent = label || "来源"; + chip.append(dot, text); + return chip; +} + +function appendSourceChip(parent, label, tone = "default", className = "source-chip") { + parent.appendChild(sourceChip(label, tone, className)); +} + +function siteRows() { + return Array.isArray(state.sourceStatus?.sites) ? state.sourceStatus.sites : []; +} + +function siteRow(siteId) { + return siteRows().find((site) => site.site_id === siteId) || null; +} + +function aiSiteStat(siteId) { + const stats = safeAiSiteStats(); + return stats.find((site) => site.site_id === siteId) || null; +} + +function safeAiSiteStats() { + const visibleStats = computeSiteStats(safeItems(state.itemsAi)); + const visibleById = new Map(visibleStats.map((site) => [site.site_id, site])); + const baseStats = Array.isArray(state.statsAi) && state.statsAi.length ? state.statsAi : visibleStats; + return baseStats.map((site) => ({ + ...site, + count: Number(visibleById.get(site.site_id)?.count || 0), + })); +} + +function siteAiPoolCount(siteId) { + return Number(aiSiteStat(siteId)?.count || 0); +} + +function activeAdjustmentCount() { + return [ + Boolean(state.query.trim()), + state.activeSection !== "all", + Boolean(state.siteFilter || state.authorFilter), + state.mode !== "selected", + state.mode === "all" && !state.allDedup, + ].filter(Boolean).length; +} + +function renderClearFiltersButton() { + if (!clearFiltersBtnEl) return; + const count = activeAdjustmentCount(); + clearFiltersBtnEl.hidden = count === 0; + clearFiltersBtnEl.textContent = count ? `清除 ${fmtNumber(count)} 项调整` : "清除筛选"; +} + +// 数据同源指示:非空 dataBaseUrl 生效时提示当前数据源 + 提供一键恢复本地相对路径的入口。 +function renderDataSourceIndicator() { + if (!dataSourceIndicatorEl) return; + const base = state.dataBaseUrl; + dataSourceIndicatorEl.hidden = !base; + if (base && dataSourceIndicatorTextEl) { + dataSourceIndicatorTextEl.textContent = `数据源:${base}`; + } +} + +function clearAllFilters() { + state.query = ""; + state.activeSection = "all"; + state.siteFilter = ""; + state.authorFilter = ""; + state.mode = "selected"; + state.allDedup = true; + state.mainListVisibleCount = MAIN_LIST_PAGE_SIZE; + state.waytoagiMode = "today"; + state.xAuthorsExpanded = false; + if (searchInputEl) searchInputEl.value = ""; + if (siteSelectEl) siteSelectEl.value = ""; + rerenderCurrentView(); +} + +function computeSiteStats(items) { + const m = new Map(); + items.forEach((item) => { + if (!m.has(item.site_id)) { + m.set(item.site_id, { site_id: item.site_id, site_name: item.site_name, count: 0, raw_count: 0 }); + } + const row = m.get(item.site_id); + row.count += 1; + row.raw_count += 1; + }); + return Array.from(m.values()).sort((a, b) => b.count - a.count || a.site_name.localeCompare(b.site_name, "zh-CN")); +} + +// 具体来源下拉/站点 pill 的统计口径跟随当前模式:精选=AI 相关池,全量=原始条目池。 +function currentSiteStats() { + if (state.mode === "all") return computeSiteStats(effectiveAllItems()); + return safeAiSiteStats().filter((site) => site.count > 0); +} + +function creatorHotScore(item) { + return normalizedPercent(item?.creator_hot_score); +} + +function highPriorityScore(item) { + if (itemSourceGroup(item) === "creator" && creatorHotScore(item)) return creatorHotScore(item); + return scorePercent(item); +} + +function isHighPriorityItem(item) { + return highPriorityScore(item) >= 75 || itemPriorityScore(item) >= 82 || item.site_id === "official_ai" || item.site_id === "aihot"; +} + +// tab 计数跟随当前模式的可见集合(忽略当前已选栏目本身,展示"如果点这个 tab 会有多少条") +function sectionTabCount(sectionId) { + if (state.mode === "all") { + const pool = mainListRawItemsBase(); + return sectionId === "all" ? pool.length : pool.filter((item) => itemSection(item) === sectionId).length; + } + const pool = mainListStoriesBase(); + return sectionId === "all" ? pool.length : pool.filter((story) => storySectionOf(story) === sectionId).length; +} + +function renderSectionTabs() { + if (!sectionTabsEl) return; + sectionTabsEl.innerHTML = ""; + SECTION_DEFS.forEach((section) => { + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = `section-tab ${state.activeSection === section.id ? "active" : ""}`; + btn.setAttribute("role", "tab"); + btn.setAttribute("aria-selected", state.activeSection === section.id ? "true" : "false"); + btn.dataset.section = section.id; + btn.innerHTML = `${section.label}${fmtNumber(sectionTabCount(section.id))}`; + btn.addEventListener("click", () => { + if (state.activeSection === section.id) return; + state.activeSection = section.id; + state.mainListVisibleCount = MAIN_LIST_PAGE_SIZE; + renderSectionTabs(); + renderModeSwitch(); + renderSiteFilters(); + renderHotBoard(); + if (state.waytoagiData) renderWaytoagi(state.waytoagiData); + renderMainList(); + }); + sectionTabsEl.appendChild(btn); + }); +} + + +function siteRatioText(siteStats) { + const count = Number(siteStats.count || 0); + const raw = Number(siteStats.raw_count ?? siteStats.count ?? 0); + if (!raw) { + const scanned = Number(siteRow(siteStats.site_id)?.item_count || 0); + if (!count && scanned) return `24h 0 · 已扫 ${fmtNumber(scanned)}`; + if (!count) return "已扫 0"; + return `${fmtNumber(count)} 条`; + } + if (raw === count) return `${fmtNumber(count)} 条`; + return `${fmtNumber(count)}/${fmtNumber(raw)} · ${Math.round((count / raw) * 100)}%AI`; +} + +function renderSiteFilters() { + const stats = currentSiteStats(); + + siteSelectEl.innerHTML = ''; + stats.forEach((s) => { + const opt = document.createElement("option"); + opt.value = s.site_id; + opt.textContent = `${s.site_name} (${siteRatioText(s)})`; + siteSelectEl.appendChild(opt); + }); + siteSelectEl.value = state.siteFilter; +} + +// 全局 精选/全量 开关:热点排行区只在精选模式显示;主列表两种模式共用同一套时间序+日期分组模板。 +function renderModeSwitch() { + if (modeSelectedBtnEl) { + modeSelectedBtnEl.classList.toggle("active", state.mode === "selected"); + modeSelectedBtnEl.setAttribute("aria-pressed", state.mode === "selected" ? "true" : "false"); + } + if (modeAllBtnEl) { + modeAllBtnEl.classList.toggle("active", state.mode === "all"); + modeAllBtnEl.setAttribute("aria-pressed", state.mode === "all" ? "true" : "false"); + } + if (hotBoardWrapEl) hotBoardWrapEl.hidden = state.mode !== "selected"; + if (allDedupeWrapEl) allDedupeWrapEl.classList.toggle("show", state.mode === "all"); + if (allDedupeToggleEl) allDedupeToggleEl.checked = state.allDedup; + if (allDedupeLabelEl) allDedupeLabelEl.textContent = state.allDedup ? "去重开" : "去重关"; + const count = mainListEntries().length; + if (modeHintEl) { + modeHintEl.textContent = `${modeLabelText()} ${fmtNumber(count)} 条`; + modeHintEl.setAttribute("aria-label", `当前${modeLabelText()}模式,${fmtNumber(count)} 条`); + } + if (listTitleEl) listTitleEl.textContent = listTitleText(); + renderClearFiltersButton(); +} + +function listTitleText() { + const section = state.activeSection !== "all" ? SECTION_BY_ID[state.activeSection] : null; + const label = modeLabelText(); + return section ? `${section.label} · ${label}` : label; +} + +// 全量模式条目池:去重开=itemsAll(已去重),去重关=itemsAllRaw(原始单条池) +function effectiveAllItems() { + return safeItems(state.allDedup ? state.itemsAll : state.itemsAllRaw); +} + +function repairDisplayedTitle(original, translated) { + let result = String(translated || "").trim(); + const source = String(original || ""); + if (/\bCodex\b/i.test(source)) result = result.replaceAll("法典", "Codex"); + if (/\bBug Bounty\b/i.test(source)) result = result.replaceAll("错误赏金", "漏洞悬赏").replaceAll("Bug 赏金", "漏洞悬赏"); + if (/\bBio Bug Bounty\b/i.test(source)) result = result.replaceAll("生物漏洞悬赏", "生物安全漏洞悬赏"); + if (/\brepositor(?:y|ies)\b/i.test(source)) result = result.replaceAll("存储库", "代码仓库"); + if (/\bdesktop app\b/i.test(source)) result = result.replaceAll("桌面应用程序", "桌面应用"); + return result; +} + +function isMostlyEnglishTitle(text) { + const value = String(text || "").trim(); + const latin = (value.match(/[A-Za-z]/g) || []).length; + const cjk = (value.match(/[㐀-鿿]/g) || []).length; + return latin >= 4 && latin > cjk * 2; +} + +function itemTitleText(item) { + const zhTitle = item.title_enhanced_zh || item.title_zh || ""; + const preferred = (zhTitle || item.title || item.title_en || "未命名更新").trim(); + const titleParts = preferred.includes(" / ") ? preferred.split(" / ") : []; + const display = !zhTitle && titleParts.length ? titleParts[0].trim() : preferred; + const original = item.title_en || item.title_original || (titleParts.length > 1 ? titleParts.slice(1).join(" / ") : ""); + return repairDisplayedTitle(original, display); +} + +function itemOriginalTitleText(item) { + const explicit = String(item?.title_en || "").trim(); + if (isMostlyEnglishTitle(explicit) && explicit !== itemTitleText(item)) return explicit; + const bilingual = String(item?.title || item?.title_bilingual || "").trim(); + if (bilingual.includes(" / ")) { + const [, ...rest] = bilingual.split(" / "); + const original = rest.join(" / ").trim(); + if (isMostlyEnglishTitle(original) && original !== itemTitleText(item)) return original; + } + const original = String(item?.title_original || "").trim(); + if (isMostlyEnglishTitle(original) && original !== itemTitleText(item)) return original; + return ""; +} + +function itemSummaryText(item, maxLength = 180) { + const text = String(item?.summary || "").replace(/\s+/g, " ").trim(); + if (!text) return ""; + return text.length > maxLength ? `${text.slice(0, maxLength - 1).trim()}…` : text; +} + +function scorePercent(item) { + const score = Number(item.ai_score ?? item.score ?? 0); + if (!Number.isFinite(score) || score <= 0) return 0; + return Math.round(score <= 1 ? score * 100 : score); +} + +function normalizedPercent(value) { + const score = Number(value); + if (!Number.isFinite(score) || score <= 0) return 0; + return Math.max(0, Math.min(100, Math.round(score <= 1 ? score * 100 : score))); +} + +function scoreTone(score) { + if (score >= 90) return "hot"; + if (score >= 75) return "strong"; + return "watch"; +} + +function itemLabelTone(item) { + const label = item.ai_label || ""; + if (item.site_id === "official_ai") return "official"; + if (item.site_id === "aihot" || label === "curated_hotlist") return "hot"; + if (itemSourceGroup(item) === "creator") return "creator"; + if (label === "model_release") return "models"; + if (label === "developer_tool" || label === "developer_tooling" || label === "infrastructure" || label === "infra_compute") return "devtools"; + if (label === "research_paper") return "research"; + if (label === "industry_business") return "industry"; + if (label === "ai_product_update" || label === "agent_workflow" || label === "robotics") return "products"; + return "default"; +} + +function itemTagTone(label) { + const text = String(label || ""); + if (text.includes("多源")) return "strong"; + if (text.includes("官方")) return "official"; + if (text.includes("精选") || text.includes("热点")) return "hot"; + if (text.includes("HN")) return "aggregate"; + if (text.includes("模型")) return "models"; + if (text.includes("开发")) return "devtools"; + if (text.includes("研究")) return "research"; + if (text.includes("自媒体")) return "creator"; + if (text.includes("社区")) return "community"; + if (text.includes("产品")) return "products"; + if (text.includes("行业")) return "industry"; + return "default"; +} + +function itemTagChip(label) { + const tag = document.createElement("span"); + tag.className = `signal-tag tone-${itemTagTone(label)}`; + tag.textContent = label; + return tag; +} + +function setSourceBadge(el, label, tone = "default", title = "") { + el.className = `source source-chip kind-${tone}`; + el.innerHTML = ""; + if (title) el.title = title; + const dot = document.createElement("span"); + dot.className = "source-dot"; + dot.setAttribute("aria-hidden", "true"); + const text = document.createElement("span"); + text.className = "source-chip-label"; + text.textContent = label || "来源"; + el.append(dot, text); +} + +function sourceTierPercent(item) { + if (item.site_id === "official_ai") return 100; + if (item.site_id === "aihot") return 90; + const rank = Number(item.source_tier_rank); + if (!Number.isFinite(rank)) return 38; + return Math.max(28, Math.min(86, 86 - rank * 9)); +} + +function editorialPercent(item) { + const aihotScore = normalizedPercent(item.aihot_score); + if (aihotScore) return aihotScore; + if (item.site_id === "official_ai") return 90; + if (item.site_id === "aihot") return 78; + const internal = scorePercent(item); + return internal ? Math.max(45, Math.round(internal * 0.72)) : 36; +} + +function freshnessPercent(item, halfLifeHours = 48) { + const ageMs = Date.now() - timelineMs(item); + if (!Number.isFinite(ageMs) || ageMs < 0) return 100; + const ageHours = ageMs / 3600000; + return Math.max(0, Math.min(100, Math.round(100 * Math.pow(0.5, ageHours / halfLifeHours)))); +} + +function itemPriorityScore(item) { + const creatorScore = creatorHotScore(item); + if (creatorScore && itemSourceGroup(item) === "creator") return creatorScore; + const internal = scorePercent(item); + const editorial = editorialPercent(item); + const source = sourceTierPercent(item); + const freshness = freshnessPercent(item); + const signal = Array.isArray(item.ai_signals) ? Math.min(100, item.ai_signals.length * 18) : 0; + return Math.round((editorial * 0.3) + (source * 0.22) + (internal * 0.2) + (freshness * 0.18) + (signal * 0.1)); +} + +function labelText(item) { + const labels = { + ai_general: "AI信号", + model_release: "模型发布", + agent_workflow: "Agent工作流", + ai_product_update: "产品更新", + developer_tooling: "开发工具", + developer_tool: "开发工具", + infrastructure: "基础设施", + infra_compute: "基础设施", + industry_business: "行业动态", + research_paper: "研究论文", + robotics: "机器人", + curated_hotlist: "热点", + ai_tech: "技术趋势", + }; + return labels[item.ai_label] || item.ai_label || "精选信号"; +} + +function itemHaystack(item) { + return [ + item.title, + item.title_zh, + item.title_en, + item.title_original, + item.source, + item.site_name, + item.site_id, + item.ai_label, + ...(Array.isArray(item.ai_signals) ? item.ai_signals : []), + ].filter(Boolean).join(" ").toLowerCase(); +} + +function matchesAny(text, patterns) { + return patterns.some((pattern) => pattern.test(text)); +} + +// 主题分类:优先用后端 ai_label,泛化标签走正则优先级(首个命中即停) +const AI_LABEL_SECTION_MAP = { + model_release: "models", + ai_product_update: "products", + agent_workflow: "products", + robotics: "products", + developer_tool: "devtools", + developer_tooling: "devtools", + infra_compute: "devtools", + research_paper: "research", + industry_business: "industry", +}; + +const SECTION_FALLBACK_RULES = [ + ["research", [ + /paper|arxiv|research|benchmark|eval|dataset|lmsys|rdi|berkeley|huggingface daily papers|论文|研究|基准|评测|数据集|训练|k-means|speculative decoding/, + ]], + ["models", [ + /gpt[-\s]?\d|claude|gemini|grok|llama|qwen|deepseek|mistral|kimi\s?k\d|glm|gemma|模型|model|weights|权重|多模态|视频生成|diffusion|sora|seedance|llm|大模型/, + ]], + ["devtools", [ + /github|cursor|codex|copilot|openrouter|api|sdk|mcp|cli|framework|inference|推理|开发者|开源|代码|编程|算力|芯片|nvidia|cloud|部署|benchmarking|token/, + ]], + ["products", [ + /app|product|agent|workflow|siri|copilot|chatgpt|perplexity|runway|suno|支付宝|产品|应用|智能体|机器人|浏览器|搜索|助手|生成工具|办公|教育/, + ]], + ["industry", [ + /funding|raised|ipo|acquire|acquisition|lawsuit|regulation|policy|white house|pentagon|nvidia|salesforce|meta|microsoft|融资|收购|上市|监管|政策|裁员|估值|债券|芯片|公司|行业|政府|五角大楼|白宫/, + ]], +]; + +// AIHOT 聚合器条目按原始平台粗分类(从 item.source 字符串推断), +// 供社区/自媒体归类与卡片小标签复用;无法识别时返回 null,不影响原有主题分类兜底。 +function aihotSubSource(item) { + if (!item || item.site_id !== "aihot") return null; + const source = String(item.source || ""); + if (source.includes("公众号")) return "wechat"; + if (/^X[::]/.test(source)) return "x"; + if (source.includes("Hacker News")) return "hn"; + if (/(RSS)\s*$/.test(source) || /\(RSS\)\s*$/.test(source)) return "rss"; + return null; +} + +// X 作者身份统一:canonical identity = @handle(大小写不敏感提取,用于筛选/去重比较)。 +// socialdata_x 的 source 本身就是裸 handle;aihot 转发的 X 帖子 source 形如 "X:Name (@handle)"。 +function itemXAuthorSource(item) { + if (!item) return null; + if (item.site_id === "socialdata_x") return String(item.source || "").trim() || null; + if (aihotSubSource(item) === "x") return String(item.source || "").trim() || null; + return null; +} + +function itemXAuthor(item) { + const source = itemXAuthorSource(item); + if (!source) return null; + const match = source.match(/@([A-Za-z0-9_]+)/); + return match ? `@${match[1]}` : null; +} + +// 展示名:socialdata_x 只有裸 handle;aihot 去掉 "X:" 前缀后是更丰富的 "Name (@handle)"。 +function itemXAuthorDisplay(item) { + if (item?.site_id === "socialdata_x") { + return String(item.source || "").trim() || null; + } + if (aihotSubSource(item) === "x") { + return String(item.source || "").replace(/^X[::]\s*/, "").trim() || null; + } + return null; +} + +// 来源形态归类:自媒体 / 社区(HN + 中文技术社区),只看来源字段,不看标题内容 +function itemSourceGroup(item) { + const siteId = item.site_id || ""; + const aihotSub = aihotSubSource(item); + if (aihotSub === "wechat") return "creator"; + if (aihotSub === "hn") return "community"; + const source = `${item.source || ""} ${item.site_name || ""}`.toLowerCase(); + if ( + siteId === "tikhub_douyin" || + siteId === "tikhub_xiaohongshu" || + source.includes("douyin") || + source.includes("xiaohongshu") || + source.includes("小红书") || + source.includes("抖音") + ) return "creator"; + if ( + siteId === "hackernews" || + siteId === "zeli" || + siteId === "waytoagi" || + siteId === "followbuilders" || + siteId === "aibase" || + source.includes("hacker news") || + source.includes("hackernews") || + source.includes("hn algolia") || + source.includes("it之家") || + source.includes("36氪") || + source.includes("掘金") || + source.includes("readhub") || + source.includes("aibase") || + source.includes("公众号") || + source.includes("宝玉") || + source.includes("小互") + ) return "community"; + return "other"; +} + +// 唯一分类入口:自媒体源 → 社区源 → 主题分类(AI_LABEL_SECTION_MAP/SECTION_FALLBACK_RULES)→ 兜底"全部" +// 每条 item 只落一个 tag;无法归入任何具体栏目的条目只在"全部"里可见,不强行塞进"行业"。 +function itemSection(item) { + const group = itemSourceGroup(item); + if (group === "creator") return "creator"; + if (group === "community") return "community"; + const label = item.ai_label || ""; + const mapped = AI_LABEL_SECTION_MAP[label]; + if (mapped) return mapped; + const hay = itemHaystack(item); + for (const [sectionId, patterns] of SECTION_FALLBACK_RULES) { + if (matchesAny(hay, patterns)) return sectionId; + } + return "all"; +} + +function itemMatchesSection(item, sectionId = state.activeSection) { + return !sectionId || sectionId === "all" || itemSection(item) === sectionId; +} + +function sectionBadgeLabel(sectionId) { + return SECTION_BY_ID[sectionId]?.short || "栏目"; +} + +// ---- 故事级辅助:按 primary_item(无则第一个 source)判定 ---- +function storyRepresentativeItem(story) { + if (!story) return null; + if (story.primary_item && (story.primary_item.title || story.primary_item.url)) { + const primary = story.primary_item; + // primary_item 常缺 site_id/site_name:从 sources 里找同 url 的补全 + if (!primary.site_id && Array.isArray(story.sources)) { + const match = story.sources.find((src) => src.url && src.url === primary.url) || story.sources[0]; + if (match) return { ...match, ...primary, site_id: match.site_id, site_name: match.site_name || match.source_name }; + } + return primary; + } + if (Array.isArray(story.sources) && story.sources.length) return story.sources[0]; + return story; +} + +function storySectionOf(story) { + const rep = storyRepresentativeItem(story); + return rep ? itemSection(rep) : "all"; +} + +function storyMatchesSection(story, sectionId = state.activeSection) { + return !sectionId || sectionId === "all" || storySectionOf(story) === sectionId; +} + +function storyMatchesQuery(story, query = state.query.trim().toLowerCase()) { + if (!query) return true; + const refs = [ + story, + story.primary_item, + ...(Array.isArray(story.sources) ? story.sources : []), + ].filter(Boolean); + return refs.some((ref) => { + const hay = `${ref.title || ""} ${ref.title_zh || ""} ${ref.title_en || ""} ${ref.source || ""} ${ref.source_name || ""} ${ref.site_name || ""}`.toLowerCase(); + return hay.includes(query); + }); +} + +// 站点等条目级筛选映射到故事:任意 source 命中即可 +function storyMatchesSiteFilter(story) { + if (!state.siteFilter && !state.authorFilter) return true; + const refs = [ + storyRepresentativeItem(story), + ...(Array.isArray(story.sources) ? story.sources : []), + ].filter(Boolean); + return refs.some((ref) => { + if (state.siteFilter && ref.site_id !== state.siteFilter) return false; + if (state.authorFilter && itemXAuthor(ref) !== state.authorFilter) return false; + return true; + }); +} + +function reasonText(item) { + const creatorScore = creatorHotScore(item); + if (creatorScore && itemSourceGroup(item) === "creator") { + const metrics = item.creator_metrics || {}; + const parts = [ + `赞 ${fmtNumber(metrics.likes)}`, + `藏 ${fmtNumber(metrics.collects)}`, + `评 ${fmtNumber(metrics.comments)}`, + `转 ${fmtNumber(metrics.shares)}`, + ]; + if (Number(item.creator_freshness_bonus || 0) > 0) parts.push("24h 加分"); + return `一周互动:${parts.join(" · ")}`; + } + const recommendReason = String(item?.recommend_reason_zh || "").trim(); + if (recommendReason) return recommendReason; + const signals = Array.isArray(item.ai_signals) ? item.ai_signals.filter(Boolean).slice(0, 3) : []; + if (signals.length) return `命中方向:${signals.join(" / ")}`; + if (item.ai_relevance_reason) return String(item.ai_relevance_reason).replaceAll("_", " "); + return "来源与标题信号通过筛选"; +} + +function timelineIso(item) { + const published = item.published_at || ""; + const seen = item.first_seen_at || ""; + const generated = state.generatedAt || ""; + if (published && generated) { + const publishedMs = new Date(published).getTime(); + const generatedMs = new Date(generated).getTime(); + if (Number.isFinite(publishedMs) && Number.isFinite(generatedMs) && publishedMs > generatedMs + 10 * 60 * 1000) { + return seen || published; + } + } + return published || seen; +} + +function timelineMs(item) { + const d = new Date(timelineIso(item)); + return Number.isNaN(d.getTime()) ? 0 : d.getTime(); +} + +function normalizedEventText(text) { + return String(text || "") + .toLowerCase() + .replace(/https?:\/\/\S+/g, "") + .replace(/[\s ]+/g, "") + .replace(/[,。、“”‘’::;;!!??()()\[\]【】《》<>·.,/\\|_-]/g, ""); +} + +function eventKey(item) { + const raw = itemTitleText(item); + const bracket = raw.match(/《([^》]{4,40})》/); + if (bracket) return `book:${normalizedEventText(bracket[1]).slice(0, 36)}`; + + const normalized = normalizedEventText(raw); + const model = normalized.match(/(bitcpmcann|deepseekv\d+(?:pro)?|grokv\d+(?:medium)?|gemini\d+(?:\.\d+)?(?:flash|pro)?|gpt\d+(?:\.\d+)?|llama\d+)/); + if (model) return `entity:${model[1]}`; + + return `title:${normalized.slice(0, 34)}`; +} + +function itemIdentityKeys(item) { + const keys = new Set(); + if (!item) return keys; + const url = item.url || item.primary_url; + if (url) keys.add(`url:${url}`); + if (item.id) keys.add(`id:${item.id}`); + const title = item.title_zh || item.title || item.title_en || item.title_original; + if (title) { + keys.add(`event:${eventKey({ ...item, title, title_zh: item.title_zh || title })}`); + keys.add(`title:${normalizedEventText(title).slice(0, 34)}`); + } + return keys; +} + +function storyIdentityKeys(story) { + const keys = new Set(); + if (!story) return keys; + const refs = [ + { id: story.story_id, title: story.title, url: story.primary_url || story.url }, + story.primary_item, + ...(Array.isArray(story.sources) ? story.sources : []), + ...(Array.isArray(story.items) ? story.items : []), + ].filter(Boolean); + refs.forEach((ref) => { + itemIdentityKeys(ref).forEach((key) => keys.add(key)); + }); + return keys; +} + +function storyHasAnyKey(story, keys) { + if (!keys || !keys.size) return false; + for (const key of storyIdentityKeys(story)) { + if (keys.has(key)) return true; + } + return false; +} + +function sourceSignal(item) { + const site = item.site_name || ""; + const source = item.source || ""; + const hay = `${site} ${source}`.toLowerCase(); + if (site === "AI HOT") return "AI HOT精选"; + if (hay.includes("hackernews") || hay.includes("hacker news")) return "HN热议"; + if (source.includes("GitHub · Trending Today") || hay.includes("github")) return "GitHub趋势"; + if (site === "Official AI Updates") return "官方更新"; + if (site === "Follow Builders") return "Builders"; + if (site === "TikHub Douyin" || hay.includes("tikhub douyin")) return "抖音自媒体"; + if (site === "TikHub Xiaohongshu" || hay.includes("tikhub xiaohongshu")) return "小红书自媒体"; + if (site === "AIbase") return "AIbase"; + if (site === "OPML RSS") return "OPML"; + return site || "来源"; +} + +function storyTimeMs(story, key) { + const iso = story && story[key]; + if (!iso) return 0; + const d = new Date(iso); + return Number.isNaN(d.getTime()) ? 0 : d.getTime(); +} + +function storyScore(story) { + const raw = (story && (story.importance_score ?? story.score ?? story.importance)) || 0; + const score = Number(raw); + if (!Number.isFinite(score) || score <= 0) return 0; + return Math.round(score <= 1 ? score * 100 : score); +} + +function storyPrimaryTitleText(story) { + const primary = (story && story.primary_item) || {}; + const explicit = String(primary.title_enhanced_zh || primary.title_zh || "").trim(); + const explicitOriginal = String(primary.title_en || primary.title_original || "").trim(); + if (explicit) return repairDisplayedTitle(explicitOriginal, explicit); + const bilingual = String(primary.title || (story && story.title) || "").trim(); + if (bilingual.includes(" / ")) { + const [zh, en] = bilingual.split(" / "); + return repairDisplayedTitle(explicitOriginal || en, (zh || en || bilingual).trim()); + } + return bilingual || "未命名更新"; +} + +function storyPrimaryEnText(story) { + const primary = (story && story.primary_item) || {}; + const explicit = String(primary.title_en || primary.title_original || "").trim(); + if (isMostlyEnglishTitle(explicit) && explicit !== storyPrimaryTitleText(story)) return explicit; + const bilingual = String(primary.title || (story && story.title) || "").trim(); + if (bilingual.includes(" / ")) { + const [, en] = bilingual.split(" / "); + const original = (en || "").trim(); + return isMostlyEnglishTitle(original) ? original : ""; + } + return ""; +} + +function storySourceCount(story) { + const sources = Array.isArray(story && story.sources) ? story.sources : []; + const explicit = Number(story && story.duplicate_count); + if (Number.isFinite(explicit) && explicit > 0) return explicit; + return Math.max(1, sources.length); +} + +// 同一事件展开:source_count>=2 的故事可以展开看每家独立报道(标题+来源+相对时间)。 +// 去重:跳过 url 与主条目重复的信源(已经在卡片主体展示过),除非去重后一条不剩—— +// 那种情况说明所有信源 url 都和主条目一致,只能保留原始 sources 列表兜底展示。 +function dedupedStorySources(row) { + const story = row && row.story; + if (!story) return []; + const sources = Array.isArray(story.sources) ? story.sources : []; + const primaryUrl = (row.item && row.item.url) || story.primary_url || story.url || ""; + const filtered = primaryUrl ? sources.filter((src) => src && src.url !== primaryUrl) : sources; + return filtered.length ? filtered : sources; +} + +function buildEventSourceRow(source) { + const row = document.createElement("div"); + row.className = "event-source-row"; + + const titleLink = document.createElement("a"); + titleLink.className = "event-source-title"; + titleLink.href = source.url || "#"; + titleLink.target = "_blank"; + titleLink.rel = "noopener noreferrer"; + titleLink.textContent = itemTitleText(source); + + const nameEl = document.createElement("span"); + nameEl.className = "event-source-name"; + nameEl.textContent = source.source_name || source.site_name || source.source || "来源"; + + const timeEl = document.createElement("span"); + timeEl.className = "event-source-time"; + timeEl.textContent = fmtRelativeTime(timelineMs(source)); + + row.append(titleLink, nameEl, timeEl); + return row; +} + +function buildEventSourceList(row) { + const sources = dedupedStorySources(row); + if (!sources.length) return null; + const list = document.createElement("div"); + list.className = "event-expand-list"; + sources.forEach((source) => list.appendChild(buildEventSourceRow(source))); + return list; +} + +const PERSONA_NAMES = { pragmatic: "实用派", cynic: "毒舌评论员", "paper-police": "较真党" }; + +// 三口味 persona 的网页展示暂时下线(2026-07-15 归档,样式待重设计,见 docs/ROADMAP.md)。 +// 数据管线(persona_score.py)与 Skill 端不受影响;置回 true 即恢复 TOP3 板块与卡片锐评行。 +const PERSONA_UI_ENABLED = false; + +// 锐评字段(persona_review/persona_id)由 persona_score.py 只写进 daily-brief.json; +// 主列表/热点榜的 story 对象来自 stories-merged.json,天然没有这两个字段, +// 必须按 story_id 回查每日精选才能拿到锐评。 +let _briefByIdCache = null; +function briefStoryById(storyId) { + if (!storyId) return null; + if (!_briefByIdCache) { + _briefByIdCache = new Map(); + briefStories().forEach((s) => { + if (s && s.story_id) _briefByIdCache.set(s.story_id, s); + }); + } + return _briefByIdCache.get(storyId) || null; +} + +function buildStoryPersonaLine(story) { + let source = story; + let reviewText = typeof story?.persona_review === "string" ? story.persona_review.trim() : ""; + if (!reviewText) { + source = briefStoryById(story?.story_id); + reviewText = typeof source?.persona_review === "string" ? source.persona_review.trim() : ""; + } + if (!reviewText) return null; + const line = document.createElement("div"); + line.className = "story-persona"; + const label = document.createElement("span"); + label.className = "story-persona-label"; + label.textContent = PERSONA_NAMES[source?.persona_id] || PERSONA_NAMES.pragmatic; + const text = document.createElement("span"); + text.className = "story-persona-text"; + text.textContent = reviewText; + line.append(label, text); + return line; +} + +function findTop3PersonaEntry(storyId) { + if (!storyId) return null; + const items = state.top3Personas?.items; + if (!Array.isArray(items) || !items.length) return null; + return items.find((entry) => entry && entry.story_id === storyId) || null; +} + +function buildPersonaPanel(entry) { + const reviews = entry?.reviews; + if (!reviews || typeof reviews !== "object") return null; + const panel = document.createElement("div"); + panel.className = "persona-panel"; + let cols = 0; + Object.keys(PERSONA_NAMES).forEach((personaId) => { + const review = reviews[personaId]; + if (!review || typeof review.review !== "string" || !review.review.trim()) return; + const col = document.createElement("div"); + col.className = "persona-col"; + col.dataset.persona = personaId; + const name = document.createElement("span"); + name.className = "persona-name"; + name.textContent = PERSONA_NAMES[personaId]; + const score = document.createElement("strong"); + score.className = "persona-score"; + score.textContent = Number.isFinite(Number(review.score)) ? String(review.score) : "-"; + const text = document.createElement("p"); + text.className = "persona-review"; + text.textContent = review.review.trim(); + col.append(name, score, text); + panel.appendChild(col); + cols += 1; + }); + return cols > 0 ? panel : null; +} + +const HOT_DECAY_HOURS = 12; +const HOT_SCORE_SCALE = 60; + +function storyHotness(story) { + const sources = storySourceCount(story); + if (sources < 2) return 0; + const latest = storyTimeMs(story, "latest_at") || storyTimeMs(story, "earliest_at"); + const ageHours = latest ? Math.max(0, (Date.now() - latest) / 3600000) : 24; + return (sources - 1) * Math.exp(-ageHours / HOT_DECAY_HOURS); +} + +function storyHotScore(story) { + const raw = storyHotness(story); + if (raw <= 0) return 0; + return Math.max(1, Math.min(100, Math.round(raw * HOT_SCORE_SCALE))); +} + +function hotStories(stories) { + return stories + .filter((story) => storyHotness(story) > 0) + .sort((a, b) => { + const byHotScore = storyHotScore(b) - storyHotScore(a); + if (byHotScore !== 0) return byHotScore; + const byHotRaw = storyHotness(b) - storyHotness(a); + if (byHotRaw !== 0) return byHotRaw; + const byEditorial = storyScore(b) - storyScore(a); + if (byEditorial !== 0) return byEditorial; + return storyTimeMs(b, "latest_at") - storyTimeMs(a, "latest_at"); + }); +} + +const HOT_BOARD_LIMIT = 20; + +function briefStories() { + return (Array.isArray(state.dailyBrief?.items) ? state.dailyBrief.items : []).filter((story) => !isUnsafeStory(story)); +} + +function mergedStories() { + return (Array.isArray(state.storiesMerged?.stories) ? state.storiesMerged.stories : []).filter((story) => !isUnsafeStory(story)); +} + +// 精选徽章:故事命中每日精选(daily-brief.json)即视为"精选"来源,与分数徽章分开显示 +let _briefIdentityKeyCache = null; +function briefIdentityKeySet() { + if (_briefIdentityKeyCache) return _briefIdentityKeyCache; + const keys = new Set(); + briefStories().forEach((story) => storyIdentityKeys(story).forEach((key) => keys.add(key))); + _briefIdentityKeyCache = keys; + return keys; +} +function isStoryCurated(story) { + return storyHasAnyKey(story, briefIdentityKeySet()); +} +function isCuratedSourceRef(ref) { + if (!ref) return false; + return ref.site_id === "official_ai" || ref.site_id === "aihot" || ref.source_tier === "official" || ref.source_tier === "curated"; +} + +// 热点排行区候选池:stories-merged 中 source_count>=2,按热度降序(不含栏目过滤,供 tab 计数复用) +function hotBoardStories() { + return hotStories(mergedStories().filter((story) => + storySourceCount(story) >= 2 && + storyMatchesSiteFilter(story) && + storyMatchesQuery(story))); +} + +function hotBoardEntries() { + if (state.mode !== "selected") return []; + return hotBoardStories() + .filter((story) => storyMatchesSection(story)) + .slice(0, HOT_BOARD_LIMIT) + .map((story, index) => storyToRow(story, index)); +} + +// ---- 主列表数据池:精选模式=mergedStories() 全量(纯时间倒序),全量模式=原始条目池 ---- + +function mainListStoriesBase() { + return mergedStories().filter((story) => storyMatchesSiteFilter(story) && storyMatchesQuery(story)); +} + +function mainListRawItemsBase() { + const q = state.query.trim().toLowerCase(); + return effectiveAllItems().filter((item) => { + if (state.siteFilter && item.site_id !== state.siteFilter) return false; + if (state.authorFilter && itemXAuthor(item) !== state.authorFilter) return false; + if (!q) return true; + return itemHaystack(item).includes(q); + }); +} + +function mainListStories() { + return mainListStoriesBase().filter((story) => storyMatchesSection(story)); +} + +function mainListRawItems() { + return mainListRawItemsBase().filter((item) => itemMatchesSection(item)); +} + +// 故事 → 统一行模型(供 renderItemNode 消费):代表条目 + 全部信源信号 + 故事引用 +function storyToRow(story, index = 0) { + const enrichStoryItem = (entry) => ({ + ...entry, + site_name: entry.site_name || entry.source_name || story.source_name || "", + }); + const item = enrichStoryItem(storyRepresentativeItem(story) || story); + const sourceItems = [ + item, + ...(Array.isArray(story.sources) ? story.sources.map(enrichStoryItem) : []), + ].filter(Boolean); + const sourceSignals = Array.from(new Set(sourceItems.map(sourceSignal))); + return { + item, + index, + story, + rows: sourceItems.map((sourceItem) => ({ item: sourceItem })), + sourceSignals, + sourceCount: storySourceCount(story), + mergedCount: Math.max(1, Number(story.duplicate_count) || sourceItems.length), + score: storyScore(story), + }; +} + +// 原始条目 → 统一行模型:无故事引用,渲染时优雅降级(不展示精选徽章/分数/为什么重要) +function itemToRow(item, index = 0) { + return { + item, + index, + story: null, + rows: [{ item }], + sourceSignals: [sourceSignal(item)], + sourceCount: 1, + mergedCount: 1, + score: 0, + }; +} + +function mainListEntries() { + if (state.mode === "all") { + return mainListRawItems().map((item, index) => { + const ms = timelineMs(item); + return { row: itemToRow(item, index), timeMs: ms }; + }).sort((a, b) => b.timeMs - a.timeMs); + } + return mainListStories().map((story, index) => { + const ms = storyTimeMs(story, "latest_at") || storyTimeMs(story, "earliest_at"); + return { row: storyToRow(story, index), timeMs: ms }; + }).sort((a, b) => b.timeMs - a.timeMs); +} + +function dateGroupKey(ms) { + if (!ms) return "unknown"; + const d = new Date(ms); + return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`; +} + +function dateGroupLabel(ms) { + if (!ms) return "时间未知"; + const d = new Date(ms); + const now = new Date(); + const sameYear = d.getFullYear() === now.getFullYear(); + return new Intl.DateTimeFormat("zh-CN", sameYear + ? { month: "long", day: "numeric" } + : { year: "numeric", month: "long", day: "numeric" }).format(d); +} + +function dateGroupWeekday(ms) { + if (!ms) return ""; + return new Intl.DateTimeFormat("zh-CN", { weekday: "long" }).format(new Date(ms)); +} + +function itemSourceRefs(item, row = null) { + const refs = []; + const seen = new Set(); + const add = (label, tone) => { + const clean = String(label || "").trim(); + if (!clean) return; + const key = `${tone}:${clean}`; + if (seen.has(key)) return; + seen.add(key); + refs.push({ label: clean, tone }); + }; + + if (row && Array.isArray(row.sourceSignals) && row.sourceSignals.length) { + row.sourceSignals.forEach((signal) => add(signal, sourceSignalTone(signal))); + } else if (row && Array.isArray(row.rows) && row.rows.length) { + row.rows.forEach((entry) => { + const sourceItem = entry.item || {}; + const kind = sourceKind(sourceItem.site_id); + add(sourceItem.source || sourceItem.site_name || kind.label, kind.tone); + }); + } else { + const kind = sourceKind(item.site_id); + add(item.source || item.site_name || kind.label, kind.tone); + } + + return refs.length ? refs : [{ label: "来源", tone: "default" }]; +} + +function rowSourceCount(row) { + const item = row.item || {}; + const refs = itemSourceRefs(item, row); + const storyCount = row.story ? storySourceCount(row.story) : 0; + return Math.max(1, refs.length, Number(row.sourceCount || 0), Number(row.mergedCount || 0), storyCount); +} + +function signalSummaryText(row) { + const item = row.item || {}; + const story = row.story || {}; + const editorialSummary = itemSummaryText(item) || itemSummaryText(story.primary_item || {}); + if (editorialSummary) return editorialSummary; + const reason = reasonText(item); + if (reason && !reason.startsWith("来源与标题")) return reason.replace(/^命中方向:/, "核心方向:"); + return ""; +} + +// 只返回真实的、条目级别的推荐理由(item.recommend_reason_zh 或 story.primary_item.recommend_reason_zh)。 +// 这类数据是预算受限的窄池,多数条目没有——没有真实理由时必须返回空字符串, +// 不再用分区/来源信号拼出通用模板句子(那类句子读起来像针对该条目的判断,实际是套话,参见调用方 renderItemNode 的隐藏逻辑)。 +function whyImportantText(row) { + const item = row.item || {}; + const story = row.story || {}; + const recommendReason = String( + item.recommend_reason_zh || story.primary_item?.recommend_reason_zh || "" + ).trim(); + return recommendReason; +} + +function feedSummaryText(item) { + const editorialSummary = itemSummaryText(item); + if (editorialSummary) return editorialSummary; + const signals = Array.isArray(item.ai_signals) ? item.ai_signals.filter(Boolean).slice(0, 2) : []; + if (signals.length) return `相关线索:${signals.join(" / ")}。`; + const reason = reasonText(item); + if (reason && !reason.startsWith("来源与标题")) return reason.replace(/^命中方向:/, "相关线索:"); + return ""; +} + +// 共享卡片组件:唯一渲染入口,主列表(精选/全量)共用同一基础变体。 +// row.story 存在时展示精选徽章/分数/为什么重要/persona 面板;row.story 为空(全量原始条目)时优雅降级,跳过这些区块。 +// 热点排行区改用 buildHotRow(单行行式渲染),不再走这个卡片模板。 +function renderItemNode(row) { + const node = itemTpl.content.firstElementChild.cloneNode(true); + const item = row.item || {}; + + const metaRow = node.querySelector(".meta-row"); + + const curatedEl = node.querySelector(".curated-badge"); + const curatedRefs = [item, ...(row.story && Array.isArray(row.story.sources) ? row.story.sources : [])]; + const curated = (row.story && isStoryCurated(row.story)) || curatedRefs.some(isCuratedSourceRef); + curatedEl.hidden = !curated; + + const siteEl = node.querySelector(".site"); + siteEl.textContent = item.source || item.site_name || ""; + + const sourceEl = node.querySelector(".source"); + const sourceLabel = sourceSignal(item); + setSourceBadge(sourceEl, sourceLabel, sourceSignalTone(sourceLabel), item.source ? `分区: ${item.source}` : ""); + if (rowSourceCount(row) > 1) { + sourceEl.title = `${sourceEl.title || ""} · 共 ${fmtNumber(rowSourceCount(row))} 个来源`.replace(/^ · /, ""); + } + + // aihot 子来源 chip(X/公众号/HN/RSS)紧跟通道 chip(.source)之后,色调复用既有 .category.kind-* 规则,不新增样式。 + let metaAnchorEl = sourceEl; + const aihotSub = aihotSubSource(item); + if (aihotSub) { + const subChip = document.createElement("span"); + subChip.className = `category kind-${AIHOT_SUB_TONES[aihotSub]}`; + subChip.textContent = AIHOT_SUB_LABELS[aihotSub]; + metaAnchorEl.insertAdjacentElement("afterend", subChip); + metaAnchorEl = subChip; + } + + // 多源 chip:source_count>=2 时出现,紧跟通道/子来源 chip 之后,同时充当"同一事件"展开/收起触发器 + // (取代旧的独立 event-expand-toggle)。子列表挂在 news-card-body 末尾,首次点击才建 DOM,之后本地 toggle。 + if (row.story && storySourceCount(row.story) >= 2) { + const bodyEl = node.querySelector(".news-card-body") || node; + const eventCount = storySourceCount(row.story); + const collapsedLabel = `多源 ${fmtNumber(eventCount)} ▸`; + const expandedLabel = `多源 ${fmtNumber(eventCount)} ▾`; + const multiChip = document.createElement("button"); + multiChip.type = "button"; + multiChip.className = "multi-chip"; + multiChip.textContent = collapsedLabel; + multiChip.setAttribute("aria-expanded", "false"); + let eventList = null; + multiChip.addEventListener("click", () => { + const expanded = multiChip.getAttribute("aria-expanded") === "true"; + if (expanded) { + if (eventList) eventList.hidden = true; + multiChip.setAttribute("aria-expanded", "false"); + multiChip.textContent = collapsedLabel; + return; + } + if (!eventList) { + eventList = buildEventSourceList(row); + if (eventList) bodyEl.appendChild(eventList); + } + if (!eventList) return; + eventList.hidden = false; + multiChip.setAttribute("aria-expanded", "true"); + multiChip.textContent = expandedLabel; + }); + metaAnchorEl.insertAdjacentElement("afterend", multiChip); + } + + const scoreEl = node.querySelector(".score-badge"); + const displayScore = row.score; + if (displayScore > 0) { + scoreEl.hidden = false; + scoreEl.textContent = `${displayScore} 分`; + scoreEl.className = `score-badge tone-${scoreTone(displayScore)}`; + } else { + scoreEl.hidden = true; + } + + // 栏目 chip(行业/模型/产品...)是 meta-row 的最后一个 chip,appendChild 保证排在 score-badge 之后、 + // 在下面的"查看原文"链接(margin-left: auto 靠右)之前。 + const sectionChip = itemTagChip(sectionBadgeLabel(itemSection(item))); + metaRow.appendChild(sectionChip); + + const titleEl = node.querySelector(".title"); + const displayTitle = row.story ? storyPrimaryTitleText(row.story) : itemTitleText(item); + const originalTitle = row.story ? storyPrimaryEnText(row.story) : itemOriginalTitleText(item); + titleEl.textContent = ""; + if (originalTitle) { + const primary = document.createElement("span"); + primary.textContent = displayTitle; + const sub = document.createElement("span"); + sub.className = "title-sub"; + sub.textContent = originalTitle; + titleEl.appendChild(primary); + titleEl.appendChild(sub); + } else { + titleEl.textContent = displayTitle; + } + titleEl.href = item.url || row.story?.primary_url || row.story?.url || "#"; + + const summaryEl = node.querySelector(".news-summary"); + if (summaryEl) { + const summaryText = row.story ? signalSummaryText(row) : feedSummaryText(item); + summaryEl.textContent = summaryText; + summaryEl.hidden = !summaryText; + } + + const whyBox = node.querySelector(".why-box"); + const whyText = row.story ? whyImportantText(row) : ""; + if (whyText) { + whyBox.hidden = false; + node.querySelector(".why-text").textContent = whyText; + } else { + whyBox.hidden = true; + } + + const personaSlot = node.querySelector(".persona-slot"); + if (row.story && PERSONA_UI_ENABLED) { + const personaEntry = findTop3PersonaEntry(row.story.story_id); + const personaPanel = buildPersonaPanel(personaEntry); + if (personaPanel) { + // TOP3 三口味面板已含默认口味整列,再显示单条锐评行就是原句重复 + personaSlot.appendChild(personaPanel); + } else { + const personaLine = buildStoryPersonaLine(row.story); + if (personaLine) personaSlot.appendChild(personaLine); + } + } + + const originalLink = document.createElement("a"); + originalLink.className = "original-link original-action"; + originalLink.href = item.url || row.story?.primary_url || row.story?.url || "#"; + originalLink.target = "_blank"; + originalLink.rel = "noopener noreferrer"; + originalLink.textContent = "查看原文 ↗"; + metaRow.appendChild(originalLink); + + return node; +} + +// 热点排行区:一行一条(rank + 标题链接 + 信源数 · 相对时间),不复用卡片模板—— +// 避免和下方精选列表的完整卡片重复展示摘要/标签/为什么重要。 +function buildHotRow(row, rank) { + const item = row.item || {}; + const el = document.createElement("div"); + el.className = "hot-row"; + + const rankEl = document.createElement("span"); + rankEl.className = "hot-row-rank"; + rankEl.textContent = `#${rank}`; + + const titleEl = document.createElement("a"); + titleEl.className = "hot-row-title"; + titleEl.target = "_blank"; + titleEl.rel = "noopener noreferrer"; + const displayTitle = row.story ? storyPrimaryTitleText(row.story) : itemTitleText(item); + titleEl.textContent = displayTitle; + titleEl.title = displayTitle; + titleEl.href = item.url || row.story?.primary_url || row.story?.url || "#"; + + const metaEl = document.createElement("span"); + metaEl.className = "hot-row-meta"; + const sourceCount = rowSourceCount(row); + const relTime = fmtRelativeTime(timelineMs(item) || storyTimeMs(row.story, "latest_at")); + + // 同一事件展开:热点行的"N 个信源"变成可点击项,点击在 .hot-row 正下方插入/移除同一份子列表组件。 + const expandable = row.story && storySourceCount(row.story) >= 2; + if (expandable) { + const sourceToggle = document.createElement("button"); + sourceToggle.type = "button"; + sourceToggle.className = "hot-row-source-toggle"; + sourceToggle.textContent = `${fmtNumber(sourceCount)} 个信源`; + sourceToggle.setAttribute("aria-expanded", "false"); + let sourceList = null; + sourceToggle.addEventListener("click", (evt) => { + evt.preventDefault(); + evt.stopPropagation(); + if (sourceList) { + sourceList.remove(); + sourceList = null; + sourceToggle.setAttribute("aria-expanded", "false"); + return; + } + sourceList = buildEventSourceList(row); + if (!sourceList) return; + sourceList.classList.add("hot-row-source-list"); + sourceToggle.setAttribute("aria-expanded", "true"); + el.insertAdjacentElement("afterend", sourceList); + }); + const sep = document.createElement("span"); + sep.textContent = " · "; + const timeEl = document.createElement("span"); + timeEl.textContent = relTime; + metaEl.append(sourceToggle, sep, timeEl); + } else { + metaEl.textContent = `${fmtNumber(sourceCount)} 个信源 · ${relTime}`; + } + + el.append(rankEl, titleEl, metaEl); + return el; +} + +function renderLoadingNotice(label, count) { + const loading = document.createElement("div"); + loading.className = "list-loading"; + loading.textContent = `正在整理 ${label} · ${fmtNumber(count)} 条`; + newsListEl.appendChild(loading); +} + +function addLoadMoreButton(parent, label, onClick) { + const moreBtn = document.createElement("button"); + moreBtn.type = "button"; + moreBtn.className = "list-more-btn"; + moreBtn.textContent = label; + moreBtn.addEventListener("click", onClick); + parent.appendChild(moreBtn); + return moreBtn; +} + +// Mobile-safe async rendering: avoid blocking the main thread on large lists. +// requestAnimationFrame 在后台标签页不触发,hidden 时降级 setTimeout,避免列表卡在加载态。 +function scheduleRender(cb) { + if (document.hidden) { + setTimeout(cb, 0); + } else { + requestAnimationFrame(cb); + } +} +let _renderListToken = 0; +const MAIN_LIST_PAGE_SIZE = 60; +state.mainListVisibleCount = MAIN_LIST_PAGE_SIZE; + +// 主列表:纯时间倒序 + 按日期分组渲染,精选/全量两种模式共用同一套模板。 +function renderMainList() { + const entries = mainListEntries(); + resultCountEl.textContent = `${fmtNumber(entries.length)} 条`; + renderClearFiltersButton(); + if (modeHintEl) { + modeHintEl.textContent = `${modeLabelText()} ${fmtNumber(entries.length)} 条`; + modeHintEl.setAttribute("aria-label", `当前${modeLabelText()}模式,${fmtNumber(entries.length)} 条`); + } + + newsListEl.innerHTML = ""; + _renderListToken += 1; + const token = _renderListToken; + + if (!entries.length) { + const empty = document.createElement("div"); + empty.className = "empty"; + const title = document.createElement("h3"); + title.textContent = "没有找到匹配内容"; + const message = document.createElement("p"); + message.textContent = "可以换个关键词,或一键恢复默认视图。"; + empty.append(title, message); + if (activeAdjustmentCount()) { + const reset = document.createElement("button"); + reset.type = "button"; + reset.className = "empty-reset-btn"; + reset.textContent = "清除筛选,查看全部"; + reset.addEventListener("click", clearAllFilters); + empty.appendChild(reset); + } + newsListEl.appendChild(empty); + return; + } + + renderLoadingNotice(listTitleText(), entries.length); + scheduleRender(() => { + if (token !== _renderListToken) return; + newsListEl.innerHTML = ""; + const visibleCount = Math.max(MAIN_LIST_PAGE_SIZE, state.mainListVisibleCount || MAIN_LIST_PAGE_SIZE); + const visible = entries.slice(0, visibleCount); + const dateGroupCounts = new Map(); + visible.forEach(({ timeMs }) => { + const key = dateGroupKey(timeMs); + dateGroupCounts.set(key, (dateGroupCounts.get(key) || 0) + 1); + }); + let lastKey = null; + const frag = document.createDocumentFragment(); + visible.forEach(({ row, timeMs }) => { + const key = dateGroupKey(timeMs); + if (key !== lastKey) { + const header = document.createElement("div"); + header.className = "date-group-header"; + const dateLabel = document.createElement("span"); + dateLabel.textContent = dateGroupLabel(timeMs); + header.appendChild(dateLabel); + const weekday = dateGroupWeekday(timeMs); + const count = dateGroupCounts.get(key) || 0; + const meta = document.createElement("span"); + meta.className = "date-group-meta"; + meta.textContent = weekday ? `· ${weekday} · ${fmtNumber(count)} 条` : `· ${fmtNumber(count)} 条`; + header.appendChild(meta); + frag.appendChild(header); + lastKey = key; + } + const timelineItem = document.createElement("div"); + timelineItem.className = "timeline-item"; + const rail = document.createElement("div"); + rail.className = "timeline-rail"; + const timeLabel = document.createElement("span"); + timeLabel.className = "timeline-time"; + timeLabel.textContent = fmtHHMM(timeMs); + const dot = document.createElement("span"); + dot.className = "timeline-dot"; + rail.append(timeLabel, dot); + timelineItem.appendChild(rail); + timelineItem.appendChild(renderItemNode(row)); + frag.appendChild(timelineItem); + }); + newsListEl.appendChild(frag); + if (entries.length > visible.length) { + addLoadMoreButton( + newsListEl, + `展开更多 ${fmtNumber(entries.length - visible.length)} 条`, + () => { + state.mainListVisibleCount = visibleCount + MAIN_LIST_PAGE_SIZE; + renderMainList(); + }, + ); + } + document.dispatchEvent(new CustomEvent("aiRadar:listRendered")); + }); +} + +function top3BoardEntries() { + if (state.mode !== "selected") return []; + const t3 = state.top3Personas?.items; + if (!Array.isArray(t3) || !t3.length) return []; + const byId = new Map(mergedStories().map((s) => [s.story_id, s])); + return t3 + .slice() + .sort((a, b) => (Number(a.rank) || 0) - (Number(b.rank) || 0)) + .map((entry) => byId.get(entry?.story_id)) + .filter(Boolean) + .map((story, index) => storyToRow(story, index)); +} + +// 今日 TOP3 板块:三口味并排锐评的固定展示入口。TOP3 卡片在主列表里按时间排序, +// 常沉在几屏之外(用户翻不到,面板等于隐身),所以命中 top3-personas.json 的故事在这里置顶再展示一次。 +function renderTop3Board() { + if (!top3BoardListEl) return; + const rows = PERSONA_UI_ENABLED ? top3BoardEntries() : []; + const show = rows.length > 0; + if (top3BoardWrapEl) top3BoardWrapEl.hidden = !show; + if (!show) return; + if (top3BoardMetaEl) top3BoardMetaEl.textContent = Object.values(PERSONA_NAMES).join(" · "); + top3BoardListEl.innerHTML = ""; + rows.forEach((row) => top3BoardListEl.appendChild(renderItemNode(row))); +} + +// 热点排行区:不设固定条数,展示条数取决于当前有多少条满足多信源热度阈值(HOT_BOARD_LIMIT 只是技术兜底)。 +function renderHotBoard() { + renderTop3Board(); + if (!hotBoardListEl) return; + const show = state.mode === "selected"; + if (hotBoardWrapEl) hotBoardWrapEl.hidden = !show; + if (!show) return; + hotBoardListEl.innerHTML = ""; + + const rows = hotBoardEntries(); + if (hotBoardMetaEl) { + hotBoardMetaEl.textContent = rows.length + ? `当前 ${fmtNumber(rows.length)} 条热点 · 按热度降序` + : "按热度排序"; + } + + if (!rows.length) { + const empty = document.createElement("div"); + empty.className = "bole-empty"; + empty.textContent = "当前筛选下没有 2 个以上信源交叉的热点,可切换筛选或查看全量。"; + hotBoardListEl.appendChild(empty); + return; + } + + rows.forEach((row, index) => { + hotBoardListEl.appendChild(buildHotRow(row, index + 1)); + }); +} + +function rerenderCurrentView() { + state.mainListVisibleCount = MAIN_LIST_PAGE_SIZE; + renderSectionTabs(); + renderModeSwitch(); + renderSiteFilters(); + renderHotBoard(); + if (state.waytoagiData) renderWaytoagi(state.waytoagiData); + renderMainList(); +} + +function waytoagiViews(waytoagi) { + const updates7d = Array.isArray(waytoagi?.updates_7d) ? waytoagi.updates_7d : []; + const latestDate = waytoagi?.latest_date || (updates7d.length ? updates7d[0].date : null); + const updatesToday = Array.isArray(waytoagi?.updates_today) && waytoagi.updates_today.length + ? waytoagi.updates_today + : (latestDate ? updates7d.filter((u) => u.date === latestDate) : []); + return { updates7d, updatesToday, latestDate }; +} + +function renderWaytoagi(waytoagi) { + // 内容 tab 已收敛为单层:WaytoAGI 面板跟随「社区」tab 显示(合并了原来源形态 cn 分组) + if (waytoagiWrapEl) { + waytoagiWrapEl.hidden = state.activeSection !== "community"; + } + if (state.activeSection !== "community") return; + const { updates7d, updatesToday, latestDate } = waytoagiViews(waytoagi); + if (waytoagiTodayBtnEl) waytoagiTodayBtnEl.classList.toggle("active", state.waytoagiMode === "today"); + if (waytoagi7dBtnEl) waytoagi7dBtnEl.classList.toggle("active", state.waytoagiMode === "7d"); + if (waytoagiTodayBtnEl) waytoagiTodayBtnEl.setAttribute("aria-pressed", state.waytoagiMode === "today" ? "true" : "false"); + if (waytoagi7dBtnEl) waytoagi7dBtnEl.setAttribute("aria-pressed", state.waytoagiMode === "7d" ? "true" : "false"); + waytoagiUpdatedAtEl.textContent = `更新时间:${fmtTime(waytoagi.generated_at)}`; + + waytoagiMetaEl.innerHTML = ""; + const rootLink = document.createElement("a"); + rootLink.href = waytoagi.root_url || "#"; + rootLink.target = "_blank"; + rootLink.rel = "noopener noreferrer"; + rootLink.textContent = "主页面"; + const historyLink = document.createElement("a"); + historyLink.href = waytoagi.history_url || "#"; + historyLink.target = "_blank"; + historyLink.rel = "noopener noreferrer"; + historyLink.textContent = "历史更新页"; + const todayCount = document.createElement("span"); + todayCount.textContent = `最近更新日(${latestDate || "--"}):${fmtNumber(waytoagi.count_today || updatesToday.length)} 条`; + const weekCount = document.createElement("span"); + weekCount.textContent = `近 7 日:${fmtNumber(waytoagi.count_7d || updates7d.length)} 条`; + [rootLink, "·", historyLink, "·", todayCount, "·", weekCount].forEach((part) => { + if (typeof part === "string") { + const sep = document.createElement("span"); + sep.textContent = part; + waytoagiMetaEl.appendChild(sep); + } else { + waytoagiMetaEl.appendChild(part); + } + }); + + waytoagiListEl.innerHTML = ""; + if (waytoagi.has_error) { + const div = document.createElement("div"); + div.className = "waytoagi-error"; + div.textContent = waytoagi.error || "WaytoAGI 数据加载失败"; + waytoagiListEl.appendChild(div); + return; + } + + const updates = state.waytoagiMode === "today" ? updatesToday : updates7d; + if (!updates.length) { + const div = document.createElement("div"); + div.className = "waytoagi-empty"; + div.textContent = state.waytoagiMode === "today" + ? "最近更新日没有更新,可切换到近7日查看。" + : (waytoagi.warning || "近 7 日没有更新"); + waytoagiListEl.appendChild(div); + return; + } + + updates.forEach((u) => { + const row = document.createElement("a"); + row.className = "waytoagi-item"; + row.href = u.url || "#"; + row.target = "_blank"; + row.rel = "noopener noreferrer"; + const dateEl = document.createElement("span"); + dateEl.className = "d"; + dateEl.textContent = fmtDate(u.date); + const titleEl = document.createElement("span"); + titleEl.className = "t"; + titleEl.textContent = u.title; + row.append(dateEl, titleEl); + waytoagiListEl.appendChild(row); + }); +} + +// 按 @handle 去重后的 X 作者列表:{ handle, display },display 优先取 aihot 的 +// "Name (@handle)" 富格式,没有的话退回 socialdata_x 的裸 handle。 +function socialdataAuthors() { + const byHandle = new Map(); + state.itemsAi.forEach((item) => { + const handle = itemXAuthor(item); + if (!handle) return; + const display = itemXAuthorDisplay(item); + if (!display) return; + const isRich = item.site_id === "aihot"; + const existing = byHandle.get(handle); + if (!existing || (isRich && !existing.rich)) { + byHandle.set(handle, { handle, display, rich: isRich }); + } + }); + return Array.from(byHandle.values()) + .map(({ handle, display }) => ({ handle, display })) + .sort((a, b) => a.display.localeCompare(b.display, "en")); +} + +function selectSocialdataAuthor(author) { + state.authorFilter = author; + // 作者身份现在横跨 socialdata_x 与 aihot-x 两个 site_id(见 itemXAuthor), + // 不能再锁死 siteFilter="socialdata_x",否则会把该作者的 aihot 转发条目过滤掉。 + // authorFilter 本身已经是跨站点的精确匹配,siteFilter 留空即可。 + state.siteFilter = ""; + // 博主筛选是条目级过滤:切到全量模式浏览该博主的原始条目池,并清空栏目选择 + state.activeSection = "all"; + state.mode = "all"; + state.mainListVisibleCount = MAIN_LIST_PAGE_SIZE; + state.xAuthorsExpanded = false; + renderSectionTabs(); + renderModeSwitch(); + renderSiteFilters(); + renderHotBoard(); + renderMainList(); + renderSourceHealth(); + document.querySelector(".list-wrap")?.scrollIntoView({ behavior: "smooth", block: "start" }); +} + +function renderSocialdataAuthorList(authors, itemCount) { + const panel = document.createElement("section"); + panel.className = "health-author-list"; + const heading = document.createElement("div"); + heading.className = "health-author-list-title"; + heading.textContent = "本轮 X 扫到的博主"; + const meta = document.createElement("div"); + meta.className = "health-author-list-meta"; + meta.textContent = `${fmtNumber(authors.length)} 位博主 · ${fmtNumber(itemCount)} 条入池内容`; + const list = document.createElement("div"); + list.className = "health-author-list-items"; + authors.forEach(({ handle, display }) => { + const item = document.createElement("button"); + item.type = "button"; + item.textContent = display; + item.title = `查看 ${display} 的 X 内容`; + item.addEventListener("click", () => selectSocialdataAuthor(handle)); + list.appendChild(item); + }); + panel.append(heading, meta, list); + return panel; +} + +function renderSourceHealthSummaryNode(status, errorMessage = "") { + const node = document.createElement("div"); + node.className = "source-health-summary"; + if (!status) { + node.classList.add(errorMessage ? "bad" : "warn"); + node.innerHTML = `${errorMessage ? "源状态异常" : "源状态未生成"}${errorMessage || "等待 source-status.json"}`; + return node; + } + const sites = Array.isArray(status.sites) ? status.sites : []; + const okSites = Number(status.successful_sites || 0); + const failed = failedSourceCount(status); + // 与 renderSourceStatusTable 同口径:pooled = 全网抓取入池(去话题过滤前), + // fetched = 原始抓取总量,aiRelevant = 24h AI 强相关合并池。 + const pooled = Number(status.items_before_topic_filter || state.totalAllMode || state.itemsAll.length || 0); + const fetched = Number(status.fetched_raw_items || state.totalRaw || pooled || 0); + const aiRelevant = safeItems(state.itemsAi).length; + node.classList.toggle("warn", failed > 0); + const segments = []; + if (fetched) segments.push(`今日采集 ${fmtNumber(fetched)} 条`); + if (pooled) segments.push(`入池 ${fmtNumber(pooled)}`); + if (aiRelevant) segments.push(`AI 强相关 ${fmtNumber(aiRelevant)}`); + segments.push(failed > 0 + ? `失败 ${fmtNumber(failed)}` + : `失败 ${fmtNumber(failed)}`); + node.innerHTML = `${fmtNumber(okSites)}/${fmtNumber(sites.length)} 源正常${segments.join(" · ")}`; + return node; +} + +// Fallback tier ranks mirroring SOURCE_TIER_BY_SITE in scripts/update_news.py. +// Items carry source_tier_rank and that data-derived value wins; this table +// only covers sites with zero loaded items (rank otherwise unknowable). +const SITE_TIER_RANK_FALLBACK = { + official_ai: 0, + aibreakfast: 1, + aihubtoday: 1, + aibase: 1, + aihot: 1, + bestblogs: 1, + curated_media: 2, + waytoagi: 2, + followbuilders: 2, + opmlrss: 3, + tikhub_douyin: 4, + tikhub_xiaohongshu: 4, + xapi: 4, + socialdata_x: 4, + techurls: 5, + buzzing: 5, + iris: 5, + zeli: 5, + hackernews: 5, + newsnow: 5, +}; + +function siteTierRankMap() { + // source_tier_rank ships on every pipeline item (items_ai / items_all); + // aggregate one rank per site from whatever is loaded so the source table + // can sort official tiers first without a duplicated constant table. + const m = new Map(); + const pools = [safeItems(state.itemsAi), safeItems(state.itemsAll), safeItems(state.itemsAllRaw)]; + pools.forEach((items) => { + items.forEach((item) => { + if (!item || !item.site_id || m.has(item.site_id)) return; + const rank = Number(item.source_tier_rank); + if (Number.isFinite(rank)) m.set(item.site_id, rank); + }); + }); + return m; +} + +function renderSourceStatusTable(status) { + if (!sourceStatusTableEl) return; + sourceStatusTableEl.innerHTML = ""; + if (!status || !Array.isArray(status.sites) || !status.sites.length) return; + + const tierRanks = siteTierRankMap(); + const rows = status.sites + .map((site) => { + const ai = aiSiteStat(site.site_id); + const aiCount = Number(ai?.count || 0); + const rawCount = Number(ai?.raw_count ?? site.item_count ?? 0); + const scanned = Number(site.item_count || rawCount || 0); + const ratioBase = rawCount || scanned; + const ratio = ratioBase ? Math.round((aiCount / ratioBase) * 100) : 0; + const tierRank = tierRanks.has(site.site_id) + ? tierRanks.get(site.site_id) + : (SITE_TIER_RANK_FALLBACK[site.site_id] ?? 9); + return { ...site, aiCount, rawCount: ratioBase, ratio, tierRank }; + }) + .sort((a, b) => + a.tierRank - b.tierRank + || b.ratio - a.ratio + || b.aiCount - a.aiCount + || String(a.site_name).localeCompare(String(b.site_name), "zh-CN")); + + const table = document.createElement("div"); + table.className = "source-table"; + const header = document.createElement("div"); + header.className = "source-table-row source-table-head"; + header.innerHTML = "来源AI / 原始AI占比状态"; + table.appendChild(header); + rows.forEach((site) => { + const row = document.createElement("div"); + row.className = "source-table-row"; + const statusText = site.ok ? "正常" : "异常"; + row.innerHTML = ` + ${site.site_name || site.site_id} + ${fmtNumber(site.aiCount)} / ${fmtNumber(site.rawCount)} + ${fmtNumber(site.ratio)}% + ${statusText} + `; + table.appendChild(row); + }); + const foot = document.createElement("div"); + foot.className = "source-table-row source-table-foot"; + foot.textContent = `共 ${fmtNumber(rows.length)} 源`; + table.appendChild(foot); + sourceStatusTableEl.appendChild(table); +} + +// 可选接入未启用/未配置的提示行 + 替换/跳过 RSS 计数(非零才显示)。 +// X 数据源已入池的数量在 source-table 的 SocialData X 行可见,这里不重复。 +function sourceHealthHintNode(status) { + const rss = status.rss_opml || {}; + const agentmail = status.agentmail || {}; + const replacedFeeds = Array.isArray(rss.replaced_feeds) ? rss.replaced_feeds : []; + const skippedFeeds = Array.isArray(rss.skipped_feeds) ? rss.skipped_feeds : []; + + const optionalBits = []; + if (!rss.enabled) optionalBits.push("RSS 未启用"); + if (!agentmail.enabled) optionalBits.push("AgentMail 未配置"); + + const parts = []; + if (optionalBits.length) parts.push(`可选接入:${optionalBits.join(" · ")}`); + if (replacedFeeds.length || skippedFeeds.length) { + parts.push(`替换/跳过 ${fmtNumber(replacedFeeds.length)}/${fmtNumber(skippedFeeds.length)}`); + } + if (!parts.length) return null; + + const node = document.createElement("div"); + node.className = "source-health-hint"; + node.textContent = parts.join(" · "); + return node; +} + +function renderSourceHealth(errorMessage = "") { + if (!sourceHealthEl) return; + sourceHealthEl.innerHTML = ""; + if (sourceHealthDetailsEl) sourceHealthDetailsEl.innerHTML = ""; + if (sourceStatusTableEl) sourceStatusTableEl.innerHTML = ""; + + const status = state.sourceStatus; + if (!status) { + sourceHealthEl.appendChild(renderSourceHealthSummaryNode(null, errorMessage)); + renderSourceStatusPill(errorMessage); + renderClearFiltersButton(); + return; + } + + sourceHealthEl.appendChild(renderSourceHealthSummaryNode(status, errorMessage)); + const detailTarget = sourceHealthDetailsEl || sourceHealthEl; + + const hint = sourceHealthHintNode(status); + if (hint) detailTarget.appendChild(hint); + + // X 博主展开列表:功能保留,从已删除的 mini-card 挪到提示行下方的小链接。 + const xAuthors = socialdataAuthors(); + if (xAuthors.length) { + // 与 socialdataAuthors() 同口径的客户端计数:socialdata_x 原生条目 + aihot 转发的 X 条目 + const socialdataDisplayCount = state.itemsAi.filter((item) => itemXAuthor(item)).length; + + const toggle = document.createElement("button"); + toggle.type = "button"; + toggle.className = "source-health-authors-toggle"; + toggle.setAttribute("aria-expanded", String(Boolean(state.xAuthorsExpanded))); + toggle.textContent = state.xAuthorsExpanded + ? "收起 X 博主列表 ▲" + : `查看本轮 X 博主 (${fmtNumber(xAuthors.length)}) ▸`; + toggle.addEventListener("click", () => { + state.xAuthorsExpanded = !state.xAuthorsExpanded; + renderSourceHealth(); + }); + detailTarget.appendChild(toggle); + + if (state.xAuthorsExpanded) { + detailTarget.appendChild(renderSocialdataAuthorList(xAuthors, socialdataDisplayCount)); + } + } + + renderSourceStatusTable(status); + renderSourceStatusPill(errorMessage); + renderClearFiltersButton(); +} + +async function loadNewsData() { + const res = await fetch(`${dataUrl("data/latest-24h.json")}?t=${Date.now()}`); + if (!res.ok) throw new Error(`加载 latest-24h.json 失败: ${res.status}`); + return res.json(); +} + +async function loadAllModeData() { + if (state.allDataLoaded) return; + if (!state.allDataPromise) { + state.allDataPromise = fetch(`${dataUrl(state.allDataUrl)}?t=${Date.now()}`) + .then((res) => { + if (!res.ok) throw new Error(`加载 latest-24h-all.json 失败: ${res.status}`); + return res.json(); + }) + .then((payload) => { + state.itemsAllRaw = payload.items_all_raw || payload.items_all || state.itemsAi; + state.itemsAll = payload.items_all || state.itemsAi; + state.totalRaw = payload.total_items_raw || state.itemsAllRaw.length; + state.totalAllMode = payload.total_items_all_mode || state.itemsAll.length; + state.allDataLoaded = true; + }) + .catch((err) => { + state.allDataPromise = null; + throw err; + }); + } + return state.allDataPromise; +} + +async function loadWaytoagiData() { + const res = await fetch(`${dataUrl("data/waytoagi-7d.json")}?t=${Date.now()}`); + if (!res.ok) throw new Error(`加载 waytoagi-7d.json 失败: ${res.status}`); + return res.json(); +} + +async function loadSourceStatusData() { + const res = await fetch(`${dataUrl("data/source-status.json")}?t=${Date.now()}`); + if (!res.ok) throw new Error(`加载 source-status.json 失败: ${res.status}`); + return res.json(); +} + +async function loadDailyBriefData() { + const res = await fetch(`${dataUrl("data/daily-brief.json")}?t=${Date.now()}`); + if (!res.ok) throw new Error(`加载 daily-brief.json 失败: ${res.status}`); + return res.json(); +} + +async function loadTop3PersonasData() { + const res = await fetch(`${dataUrl("data/top3-personas.json")}?t=${Date.now()}`); + if (!res.ok) throw new Error(`加载 top3-personas.json 失败: ${res.status}`); + return res.json(); +} + +async function loadStoriesData() { + const res = await fetch(`${dataUrl(state.storiesDataUrl)}?t=${Date.now()}`); + if (!res.ok) throw new Error(`加载 stories-merged.json 失败: ${res.status}`); + return res.json(); +} + +async function init() { + const [newsResult, waytoagiResult, statusResult, briefResult, storiesResult, personasResult] = await Promise.allSettled([ + loadNewsData(), + loadWaytoagiData(), + loadSourceStatusData(), + loadDailyBriefData(), + loadStoriesData(), + loadTop3PersonasData(), + ]); + + if (briefResult.status === "fulfilled") { + state.dailyBrief = briefResult.value; + } else { + state.dailyBrief = null; + } + _briefIdentityKeyCache = null; + + // top3-personas.json 是可选增强数据:文件缺失、请求失败或 items 为空都静默降级。 + if ( + personasResult.status === "fulfilled" && + Array.isArray(personasResult.value?.items) && + personasResult.value.items.length > 0 + ) { + state.top3Personas = personasResult.value; + } else { + state.top3Personas = null; + } + + if (storiesResult.status === "fulfilled") { + state.storiesMerged = storiesResult.value; + } else { + state.storiesMerged = null; + } + + if (newsResult.status === "fulfilled") { + const payload = newsResult.value; + const loadedStoriesDataUrl = state.storiesDataUrl; + state.itemsAi = payload.items_ai || payload.items || []; + state.itemsAllRaw = payload.items_all_raw || payload.items_all || []; + state.itemsAll = payload.items_all || []; + state.creatorItemsAi = payload.creator_items_ai || []; + state.creatorItemsAll = payload.creator_items_all || state.creatorItemsAi; + state.creatorWindowDays = Number(payload.creator_window_days || 7); + state.statsAi = payload.site_stats || []; + state.totalAi = payload.total_items || state.itemsAi.length; + state.totalRaw = payload.total_items_raw || state.itemsAllRaw.length; + state.totalAllMode = payload.total_items_all_mode || state.itemsAll.length; + state.allDataUrl = payload.all_mode_data_url || state.allDataUrl; + state.storiesDataUrl = payload.stories_data_url || state.storiesDataUrl; + if (state.storiesDataUrl !== loadedStoriesDataUrl) { + try { + state.storiesMerged = await loadStoriesData(); + } catch { + state.storiesMerged = null; + } + } + state.allDataLoaded = Boolean(payload.items_all || payload.items_all_raw); + state.generatedAt = payload.generated_at; + + renderSectionTabs(); + renderModeSwitch(); + renderSiteFilters(); + renderHotBoard(); + renderMainList(); + updatedAtEl.textContent = fmtTime(state.generatedAt); + } else { + updatedAtEl.textContent = "新闻数据加载失败"; + newsListEl.innerHTML = `
${newsResult.reason.message}
`; + } + + if (statusResult.status === "fulfilled") { + state.sourceStatus = statusResult.value; + renderSourceHealth(); + } else { + renderSourceHealth(statusResult.reason.message); + } + + if (waytoagiResult.status === "fulfilled") { + state.waytoagiData = waytoagiResult.value; + renderWaytoagi(state.waytoagiData); + } else { + if (waytoagiWrapEl) waytoagiWrapEl.hidden = state.activeSection !== "community"; + waytoagiUpdatedAtEl.textContent = "加载失败"; + waytoagiListEl.innerHTML = `
${waytoagiResult.reason.message}
`; + } + + document.dispatchEvent(new CustomEvent("aiRadar:ready")); +} + +// 搜索:精选模式按故事标题/来源过滤(storyMatchesQuery),全量模式按条目过滤(itemHaystack) +searchInputEl.addEventListener("input", (e) => { + state.query = e.target.value; + state.mainListVisibleCount = MAIN_LIST_PAGE_SIZE; + renderSectionTabs(); + renderModeSwitch(); + renderHotBoard(); + renderMainList(); +}); + +if (clearFiltersBtnEl) { + clearFiltersBtnEl.addEventListener("click", clearAllFilters); +} + +siteSelectEl.addEventListener("change", (e) => { + state.siteFilter = e.target.value; + if (state.siteFilter !== "socialdata_x") state.authorFilter = ""; + state.mainListVisibleCount = MAIN_LIST_PAGE_SIZE; + renderSiteFilters(); + renderHotBoard(); + renderMainList(); +}); + +// 全局 精选/全量 开关:替代旧的三视图切换(精选/热点榜/时间线) +if (modeSelectedBtnEl) { + modeSelectedBtnEl.addEventListener("click", () => { + if (state.mode === "selected") return; + state.mode = "selected"; + state.mainListVisibleCount = MAIN_LIST_PAGE_SIZE; + rerenderCurrentView(); + }); +} + +if (modeAllBtnEl) { + modeAllBtnEl.addEventListener("click", async () => { + if (state.mode === "all") return; + state.mode = "all"; + state.mainListVisibleCount = MAIN_LIST_PAGE_SIZE; + renderModeSwitch(); + newsListEl.innerHTML = ""; + const loading = document.createElement("div"); + loading.className = "empty"; + loading.textContent = "正在加载全量更新..."; + newsListEl.appendChild(loading); + try { + await loadAllModeData(); + rerenderCurrentView(); + } catch (err) { + newsListEl.innerHTML = ""; + const failed = document.createElement("div"); + failed.className = "empty"; + failed.textContent = err.message; + newsListEl.appendChild(failed); + } + }); +} + +if (allDedupeToggleEl) { + allDedupeToggleEl.addEventListener("change", (e) => { + state.allDedup = Boolean(e.target.checked); + state.mainListVisibleCount = MAIN_LIST_PAGE_SIZE; + rerenderCurrentView(); + }); +} + +if (waytoagiTodayBtnEl) { + waytoagiTodayBtnEl.addEventListener("click", () => { + state.waytoagiMode = "today"; + if (state.waytoagiData) renderWaytoagi(state.waytoagiData); + }); +} + +if (waytoagi7dBtnEl) { + waytoagi7dBtnEl.addEventListener("click", () => { + state.waytoagiMode = "7d"; + if (state.waytoagiData) renderWaytoagi(state.waytoagiData); + }); +} + +if (dataSourceResetBtnEl) { + dataSourceResetBtnEl.addEventListener("click", () => { + try { localStorage.removeItem("dataBaseUrl"); } catch {} + window.location.href = window.location.pathname; + }); +} + +renderDataSourceIndicator(); +init(); diff --git a/skills/ai-news-radar/assets/icons/apple-touch-icon.png b/skills/ai-news-radar/assets/icons/apple-touch-icon.png new file mode 100644 index 0000000..9739ba7 Binary files /dev/null and b/skills/ai-news-radar/assets/icons/apple-touch-icon.png differ diff --git a/skills/ai-news-radar/assets/icons/favicon-32.png b/skills/ai-news-radar/assets/icons/favicon-32.png new file mode 100644 index 0000000..7a58d71 Binary files /dev/null and b/skills/ai-news-radar/assets/icons/favicon-32.png differ diff --git a/skills/ai-news-radar/assets/icons/icon-192.png b/skills/ai-news-radar/assets/icons/icon-192.png new file mode 100644 index 0000000..f627437 Binary files /dev/null and b/skills/ai-news-radar/assets/icons/icon-192.png differ diff --git a/skills/ai-news-radar/assets/icons/icon-512.png b/skills/ai-news-radar/assets/icons/icon-512.png new file mode 100644 index 0000000..78e5093 Binary files /dev/null and b/skills/ai-news-radar/assets/icons/icon-512.png differ diff --git a/skills/ai-news-radar/assets/logo.svg b/skills/ai-news-radar/assets/logo.svg new file mode 100644 index 0000000..b16d0c7 --- /dev/null +++ b/skills/ai-news-radar/assets/logo.svg @@ -0,0 +1,22 @@ + + AI News Radar Logo + Radar-inspired mark for AI News Radar + + + + + + + + + + + + + + + + + + + diff --git a/skills/ai-news-radar/assets/motion.js b/skills/ai-news-radar/assets/motion.js new file mode 100644 index 0000000..f6918d0 --- /dev/null +++ b/skills/ai-news-radar/assets/motion.js @@ -0,0 +1,31 @@ +(function () { + if (!window.gsap) return; + + const mm = gsap.matchMedia(); + + mm.add("(prefers-reduced-motion: no-preference)", function () { + gsap.defaults({ duration: 0.55, ease: "power3.out" }); + + // Intro / list entry animations intentionally live in styles.css as + // transform-only @keyframes: any JS "from" tween that touches opacity + // strands elements invisible when the tab is hidden mid-flight, because + // the GSAP ticker freezes while rendering is paused. + + // Section scroll reveal via IntersectionObserver. Keep sections visible: + // hiding whole content blocks can leave blank viewports after responsive + // reflow or rapid mobile scrolling. + const revealEls = document.querySelectorAll(".waytoagi-wrap, .list-wrap"); + if (revealEls.length && window.IntersectionObserver) { + gsap.set(revealEls, { y: 14 }); + const observer = new IntersectionObserver(function (entries) { + entries.forEach(function (entry) { + if (entry.isIntersecting) { + gsap.to(entry.target, { y: 0, duration: 0.45, clearProps: "transform" }); + observer.unobserve(entry.target); + } + }); + }, { threshold: 0.08 }); + revealEls.forEach(function (el) { observer.observe(el); }); + } + }); +}()); diff --git a/skills/ai-news-radar/assets/og.png b/skills/ai-news-radar/assets/og.png new file mode 100644 index 0000000..c78f57c Binary files /dev/null and b/skills/ai-news-radar/assets/og.png differ diff --git a/skills/ai-news-radar/assets/service-status.css b/skills/ai-news-radar/assets/service-status.css new file mode 100644 index 0000000..2c13c91 --- /dev/null +++ b/skills/ai-news-radar/assets/service-status.css @@ -0,0 +1,117 @@ +.service-status-panel { + margin: 10px 0 14px; + padding: 11px 13px; + border: 1px solid rgba(185, 116, 24, 0.28); + border-radius: 14px; + background: linear-gradient(135deg, rgba(255, 249, 237, 0.98), rgba(255, 253, 247, 0.96)); + box-shadow: 0 8px 24px rgba(104, 67, 17, 0.06); +} + +.service-status-panel[hidden] { + display: none; +} + +.service-status-panel.has-major { + border-color: rgba(179, 52, 52, 0.32); + background: linear-gradient(135deg, rgba(255, 244, 242, 0.98), rgba(255, 250, 248, 0.96)); +} + +.service-status-heading, +.service-status-title-wrap, +.service-incident, +.service-incident-meta { + display: flex; + align-items: center; +} + +.service-status-heading { + justify-content: space-between; + gap: 10px; + margin-bottom: 7px; +} + +.service-status-title-wrap { + gap: 7px; + color: var(--ink); + font-size: 13px; +} + +.service-status-dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: #c48122; + box-shadow: 0 0 0 4px rgba(196, 129, 34, 0.12); +} + +.has-major .service-status-dot { + background: #ba4040; + box-shadow: 0 0 0 4px rgba(186, 64, 64, 0.12); +} + +.service-status-count { + color: var(--muted); + font-size: 11px; +} + +.service-incident-list { + display: grid; + gap: 5px; +} + +.service-incident { + justify-content: space-between; + gap: 10px; + min-width: 0; + padding-top: 5px; + border-top: 1px solid rgba(131, 91, 31, 0.10); +} + +.service-incident-main { + min-width: 0; +} + +.service-incident-meta { + gap: 6px; + margin-bottom: 2px; + color: var(--muted); + font-size: 9px; +} + +.service-phase { + padding: 1px 5px; + border-radius: 999px; + background: rgba(196, 129, 34, 0.10); + color: #8b5a16; +} + +.service-incident-title { + display: block; + color: var(--ink); + font-size: 12px; + font-weight: 600; + line-height: 1.35; + text-decoration: none; + overflow-wrap: anywhere; +} + +.service-incident-title:hover { + color: var(--accent); +} + +.service-incident-time { + flex: 0 0 auto; + color: var(--muted-soft); + font-size: 9px; + white-space: nowrap; +} + +@media (max-width: 560px) { + .service-incident { + align-items: flex-start; + } + + .service-incident-time { + padding-top: 14px; + } +} diff --git a/skills/ai-news-radar/assets/service-status.js b/skills/ai-news-radar/assets/service-status.js new file mode 100644 index 0000000..10d6f66 --- /dev/null +++ b/skills/ai-news-radar/assets/service-status.js @@ -0,0 +1,161 @@ +(() => { + const panel = document.getElementById("serviceStatusPanel"); + if (!panel) return; + + const STATUS_LABELS = { + investigating: "调查中", + identified: "已定位", + monitoring: "恢复监控中", + }; + + function resolveDataBaseUrl() { + try { + const fromQuery = new URLSearchParams(window.location.search).get("data") || ""; + if (fromQuery) return fromQuery.trim().replace(/\/+$/, ""); + return (localStorage.getItem("dataBaseUrl") || "").trim().replace(/\/+$/, ""); + } catch { + return ""; + } + } + + function dataUrl(path) { + const base = resolveDataBaseUrl(); + if (!base) return path; + return `${base}/${String(path || "").split("/").pop()}`; + } + + function formatTime(value) { + const date = new Date(value || ""); + if (Number.isNaN(date.getTime())) return ""; + return new Intl.DateTimeFormat("zh-CN", { + month: "numeric", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + hour12: false, + }).format(date); + } + + function providerLabel(incident) { + const components = Array.isArray(incident?.affected_components) + ? incident.affected_components + : []; + const signal = [incident?.title, incident?.title_zh, ...components] + .filter(Boolean) + .join(" ") + .toLowerCase(); + if (signal.includes("chatgpt")) return "ChatGPT"; + return incident?.provider || "OpenAI"; + } + + function incidentTitle(incident) { + if (incident?.title === "Elevated Error Rates") { + return "OpenAI 服务错误率升高"; + } + return incident?.title_zh || incident?.title || "服务异常"; + } + + function incidentNode(incident) { + const row = document.createElement("article"); + row.className = `service-incident impact-${incident.impact || "none"}`; + + const main = document.createElement("div"); + main.className = "service-incident-main"; + + const meta = document.createElement("div"); + meta.className = "service-incident-meta"; + + const provider = document.createElement("span"); + provider.className = "service-provider"; + provider.textContent = providerLabel(incident); + + const phase = document.createElement("span"); + phase.className = "service-phase"; + phase.textContent = STATUS_LABELS[incident.status] || incident.status || "处理中"; + meta.append(provider, phase); + + const title = document.createElement("a"); + title.className = "service-incident-title"; + const incidentUrl = new URL(incident.url || "", "https://status.openai.com/"); + title.href = incidentUrl.protocol === "https:" && incidentUrl.hostname === "status.openai.com" + ? incidentUrl.href : "https://status.openai.com/"; + title.target = "_blank"; + title.rel = "noopener noreferrer"; + title.textContent = incidentTitle(incident); + + main.append(meta, title); + + const time = document.createElement("time"); + time.className = "service-incident-time"; + time.dateTime = incident.updated_at || ""; + time.textContent = formatTime(incident.updated_at); + + row.append(main, time); + return row; + } + + function render(payload) { + const incidents = Array.isArray(payload?.incidents) + ? payload.incidents.filter((incident) => incident && incident.status !== "resolved") + : []; + const generatedAt = Date.parse(payload?.generated_at || ""); + const stale = !Number.isFinite(generatedAt) || Date.now() - generatedAt > 2 * 60 * 60 * 1000; + panel.replaceChildren(); + if (payload?.ok !== true || stale || incidents.length === 0) { + panel.hidden = true; + return; + } + + const heading = document.createElement("div"); + heading.className = "service-status-heading"; + + const titleWrap = document.createElement("div"); + titleWrap.className = "service-status-title-wrap"; + const dot = document.createElement("span"); + dot.className = "service-status-dot"; + dot.setAttribute("aria-hidden", "true"); + const title = document.createElement("strong"); + title.textContent = "ChatGPT / OpenAI 服务状态"; + titleWrap.append(dot, title); + + const count = document.createElement("span"); + count.className = "service-status-count"; + count.textContent = `${incidents.length} 项官方故障`; + heading.append(titleWrap, count); + + const list = document.createElement("div"); + list.className = "service-incident-list"; + incidents.slice(0, 3).forEach((incident) => list.appendChild(incidentNode(incident))); + + panel.append(heading, list); + panel.classList.toggle( + "has-major", + incidents.some((incident) => ["major", "critical"].includes(incident.impact)), + ); + panel.hidden = false; + panel.setAttribute( + "aria-label", + `ChatGPT 与 OpenAI 服务状态:${incidents.length} 项故障正在处理`, + ); + } + + const controller = new AbortController(); + const timeout = window.setTimeout(() => controller.abort(), 8000); + + fetch(dataUrl(new URL("../data/service-status.json", document.currentScript.src).href), { + cache: "no-cache", + headers: { Accept: "application/json" }, + signal: controller.signal, + }) + .then((response) => { + if (!response.ok) throw new Error(`service status ${response.status}`); + return response.json(); + }) + .then(render) + .catch(() => { + panel.hidden = true; + }) + .finally(() => { + window.clearTimeout(timeout); + }); +})(); diff --git a/skills/ai-news-radar/assets/styles.css b/skills/ai-news-radar/assets/styles.css new file mode 100644 index 0000000..c49c7aa --- /dev/null +++ b/skills/ai-news-radar/assets/styles.css @@ -0,0 +1,2074 @@ +:root { + --bg: #f6f6f2; + --bg-alt: #eeecea; + --surface: #ffffff; + --surface-soft: #fbfaf7; + --surface-alt: #f4f2ef; + --ink: #171717; + --ink-soft: #3f3d39; + --muted: #66645f; + --muted-soft: #8b8780; + --line: #d9d6ce; + --line-soft: rgba(23, 23, 23, 0.08); + --accent: #126a73; + --accent-warm: #b55231; + --good: #1f7a4d; + --warn: #9a6700; + --bad: #b42318; + --radius: 8px; +} + +* { + box-sizing: border-box; +} + +html, +body { + margin: 0; + min-height: 100%; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans SC", "Microsoft YaHei", sans-serif; + color: var(--ink); + background: var(--bg); +} + +.skip-link { + position: fixed; + top: 12px; + left: 12px; + z-index: 100; + border-radius: var(--radius); + padding: 9px 12px; + color: #f7fbfa; + background: var(--accent); + font-size: 13px; + font-weight: 760; + text-decoration: none; + transform: translateY(-160%); + transition: transform 160ms ease; +} + +.skip-link:focus { + transform: translateY(0); +} + +button, +input, +select { + font: inherit; +} + +button { + cursor: pointer; +} + +.shell { + max-width: 1160px; + margin: 0 auto; + padding: 30px 18px 56px; +} + +.hero { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: 18px 28px; + padding-bottom: 14px; + border-bottom: 1px solid var(--line-soft); +} + +.hero-main { + min-width: 0; +} + +.hero-headline { + display: flex; + gap: 14px; + align-items: center; +} + +.hero-headline > div { + min-width: 0; +} + +.hero-logo { + width: 48px; + height: 48px; + border: 1px solid rgba(18, 106, 115, 0.16); + border-radius: var(--radius); + background: var(--surface); +} + +.hero h1 { + margin: 4px 0 0; + font-size: 38px; + line-height: 1.08; + overflow-wrap: break-word; +} + +.hero-updated { + display: flex; + align-items: baseline; + gap: 6px; + margin: 4px 0 0; + font-size: 13px; + color: var(--muted); +} + +.hero-meta { + align-self: center; + display: grid; + gap: 6px; + min-width: 178px; + padding: 0; + border: 0; + border-radius: var(--radius); + background: transparent; + justify-items: end; + text-align: right; +} + +.updated-label { + color: var(--muted); + font-size: 12px; +} + +.updated { + color: var(--ink); + font-size: 13px; + font-weight: 700; +} + +.source-status-pill { + display: inline-flex; + width: max-content; + max-width: 100%; + align-items: center; + gap: 6px; + border: 1px solid rgba(31, 122, 77, 0.18); + border-radius: 999px; + padding: 5px 9px; + color: var(--good); + background: rgba(31, 122, 77, 0.07); + font-size: 12px; + font-weight: 740; +} + +.source-status-pill.warn { + color: var(--warn); + border-color: rgba(154, 103, 0, 0.22); + background: rgba(154, 103, 0, 0.08); +} + +.source-status-pill.bad { + color: var(--bad); + border-color: rgba(180, 35, 24, 0.22); + background: rgba(180, 35, 24, 0.07); +} + +.hero-links { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 6px; + margin-top: 4px; +} + +.hero-link { + display: inline-flex; + align-items: center; + justify-content: center; + min-height: 30px; + border: 1px solid rgba(18, 106, 115, 0.2); + border-radius: 999px; + padding: 5px 10px; + color: var(--accent); + background: rgba(18, 106, 115, 0.06); + font-size: 12px; + font-weight: 740; + line-height: 1; + text-decoration: none; + white-space: nowrap; +} + +.hero-link:hover { + border-color: rgba(18, 106, 115, 0.36); + background: rgba(18, 106, 115, 0.1); +} + +.section-nav-wrap { + grid-column: 1 / -1; + display: grid; + gap: 10px; + padding-top: 2px; +} + +.section-tabs { + display: flex; + gap: 4px; + align-items: center; + overflow-x: auto; + scrollbar-width: none; + -webkit-overflow-scrolling: touch; + border: 1px solid var(--line-soft); + border-radius: var(--radius); + padding: 4px; + background: rgba(255, 255, 255, 0.52); +} + +.section-tabs::-webkit-scrollbar { + display: none; +} + +.section-scroll-hint { + display: none; +} + +.section-tab { + flex: 0 0 auto; + min-height: 40px; + display: inline-flex; + align-items: center; + gap: 8px; + border: 1px solid transparent; + border-radius: var(--radius); + padding: 0 11px; + color: var(--muted); + background: transparent; + font-size: 13px; +} + +.section-tab span, +.section-tab strong { + line-height: 1; + white-space: nowrap; +} + +.section-tab strong { + min-width: 22px; + border-radius: 999px; + padding: 3px 6px; + color: var(--accent); + background: transparent; + font-size: 11px; + text-align: center; +} + +.section-tab.active { + color: #fff; + border-color: var(--accent); + background: var(--accent); + font-weight: 780; +} + +.section-tab.active strong { + color: var(--accent); + background: #fff; +} + +.primary-controls { + margin-top: 14px; + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto auto; + gap: 12px; + align-items: center; +} + +/* 清除筛选按钮 hidden 时,隐藏项仍会占用第4列的 gap track, + 导致本行右边缘比 .section-tabs 短一个 gap 宽度——收窄为 3 列补齐右边缘。 + 只在桌面生效:760px 以下 .primary-controls 是另一套 2 列/整行布局,不受此问题影响。 */ +@media (min-width: 761px) { + .primary-controls:has(> .clear-filters-btn[hidden]) { + grid-template-columns: auto minmax(0, 1fr) auto; + } +} + +input, +select { + width: 100%; + border: 1px solid var(--line); + background: var(--surface); + color: var(--ink); + border-radius: var(--radius); + padding: 11px 12px; + font-size: 14px; +} + +input:focus, +select:focus, +button:focus-visible, +summary:focus-visible { + outline: 2px solid rgba(18, 106, 115, 0.35); + outline-offset: 2px; +} + +.mode-hint { + min-height: 42px; + display: grid; + place-items: center; + border: 1px solid rgba(18, 106, 115, 0.22); + border-radius: var(--radius); + padding: 0 12px; + color: var(--accent); + background: rgba(18, 106, 115, 0.07); + font-size: 13px; + font-weight: 720; + white-space: nowrap; +} + +.clear-filters-btn, +.empty-reset-btn { + min-height: 42px; + border: 1px solid rgba(181, 82, 49, 0.28); + border-radius: var(--radius); + padding: 0 13px; + color: var(--accent-warm); + background: rgba(181, 82, 49, 0.06); + font-size: 13px; + font-weight: 720; + white-space: nowrap; +} + +.clear-filters-btn:hover, +.empty-reset-btn:hover { + border-color: rgba(181, 82, 49, 0.46); + background: rgba(181, 82, 49, 0.1); +} + +.advanced-panel { + margin-top: 12px; + border: 1px solid rgba(23, 23, 23, 0.08); + border-radius: var(--radius); + background: rgba(251, 250, 247, 0.66); +} + +.advanced-panel > summary { + position: relative; + display: flex; + justify-content: space-between; + gap: 12px; + align-items: center; + padding: 11px 14px 11px 40px; + color: var(--ink); + font-size: 14px; + font-weight: 700; + list-style: none; + cursor: pointer; +} + +.advanced-panel:not([open]) > summary { + color: var(--muted); + font-weight: 650; +} + +.advanced-panel > summary::-webkit-details-marker { + display: none; +} + +.advanced-panel > summary::before { + content: "+"; + width: 18px; + height: 18px; + position: absolute; + left: 14px; + top: 50%; + transform: translateY(-50%); + display: grid; + place-items: center; + border: 1px solid var(--line); + border-radius: 50%; + color: var(--muted); + font-weight: 700; +} + +.advanced-panel > summary > span:first-child { + min-width: 0; +} + +.advanced-panel[open] > summary::before { + content: "-"; +} + +.advanced-hint { + color: var(--muted); + font-size: 12px; + font-weight: 400; + white-space: nowrap; +} + +.advanced-content { + display: grid; + gap: 14px; + padding: 0 14px 14px; + border-top: 1px solid var(--line-soft); +} + +.advanced-controls { + display: grid; + grid-template-columns: minmax(0, 320px); + gap: 10px; + align-items: end; + padding-top: 14px; +} + +.field { + display: grid; + gap: 6px; + color: var(--muted); + font-size: 12px; +} + +.mode-switch { + display: inline-flex; + gap: 4px; + align-items: center; + border: 1px solid var(--line-soft); + border-radius: var(--radius); + padding: 4px; + background: rgba(255, 255, 255, 0.52); +} + +.mode-btn { + min-height: 40px; + border: 0; + border-radius: var(--radius); + background: transparent; + color: var(--muted); + padding: 0 14px; + font-size: 13px; +} + +.mode-btn.active { + background: var(--accent); + color: #fff; + font-weight: 780; +} + +.all-dedupe { + display: none; + min-height: 40px; + align-items: center; + gap: 8px; + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 0 12px; + font-size: 13px; + color: var(--muted); + background: var(--surface-soft); + cursor: pointer; + user-select: none; +} + +.all-dedupe.show { + display: inline-flex; +} + +.all-dedupe input { + position: absolute; + opacity: 0; + width: 0; + height: 0; +} + +.all-dedupe-dot { + width: 12px; + height: 12px; + border-radius: 50%; + border: 1px solid rgba(23, 23, 23, 0.25); + background: rgba(23, 23, 23, 0.16); +} + +.all-dedupe input:checked + .all-dedupe-dot { + border-color: rgba(18, 106, 115, 0.65); + background: var(--accent); +} + +.source-health { + display: grid; + gap: 10px; +} + +.source-health-summary { + display: flex; + min-width: 0; + align-items: center; + justify-content: space-between; + gap: 12px; + border: 1px solid rgba(31, 122, 77, 0.16); + border-radius: var(--radius); + padding: 11px 12px; + color: var(--muted); + background: rgba(31, 122, 77, 0.05); + font-size: 13px; + line-height: 1.4; +} + +.source-health-summary strong { + color: var(--good); + font-size: 15px; +} + +.source-health-summary.warn { + border-color: rgba(154, 103, 0, 0.2); + background: rgba(154, 103, 0, 0.07); +} + +.source-health-summary.warn strong { + color: var(--warn); +} + +.source-health-summary.bad { + border-color: rgba(180, 35, 24, 0.22); + background: rgba(180, 35, 24, 0.06); +} + +.source-health-summary.bad strong { + color: var(--bad); +} + +.source-health-fail-bad { + color: var(--bad); + font-weight: 700; +} + +.source-detail-panel { + border: 1px solid var(--line-soft); + border-radius: var(--radius); + background: rgba(255, 255, 255, 0.48); + overflow: hidden; +} + +.source-detail-panel > summary { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + padding: 10px 12px; + color: var(--accent); + font-size: 13px; + font-weight: 760; + cursor: pointer; + list-style: none; +} + +.source-detail-panel > summary::-webkit-details-marker { + display: none; +} + +.source-detail-panel > summary::after { + content: "+"; + color: var(--muted); + font-weight: 800; +} + +.source-detail-panel[open] > summary::after { + content: "-"; +} + +.source-health-details { + display: grid; + gap: 10px; + padding: 0 12px 12px; +} + +.source-health-hint { + color: var(--muted); + font-size: 12px; + line-height: 1.4; +} + +.source-health-authors-toggle { + align-self: start; + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 6px 10px; + color: var(--accent); + background: var(--surface-soft); + font: inherit; + font-size: 12px; + cursor: pointer; +} + +.source-health-authors-toggle:hover, +.source-health-authors-toggle:focus-visible { + border-color: var(--accent); + outline: none; +} + +.health-author-list { + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 10px 12px; + background: var(--surface-soft); +} + +.health-author-list-title { + font-size: 13px; + font-weight: 700; +} + +.health-author-list-meta { + margin-top: 3px; + color: var(--muted); + font-size: 12px; +} + +.health-author-list-items { + display: flex; + max-height: 220px; + margin-top: 9px; + gap: 6px; + overflow: auto; + flex-wrap: wrap; + align-content: flex-start; +} + +.health-author-list-items button { + border: 1px solid var(--line); + border-radius: 999px; + padding: 3px 7px; + color: var(--ink-soft); + background: var(--surface); + font: inherit; + font-size: 12px; + line-height: 1.25; + cursor: pointer; +} + +.health-author-list-items button:hover, +.health-author-list-items button:focus-visible { + border-color: var(--accent); + color: var(--accent); + outline: none; +} + +.source-status-table { + padding: 0 12px 12px; +} + +.source-table { + display: grid; + border: 1px solid var(--line-soft); + border-radius: var(--radius); + overflow: hidden; + background: var(--surface); +} + +.source-table-row { + display: grid; + grid-template-columns: minmax(160px, 1.4fr) minmax(96px, 0.8fr) minmax(64px, 0.5fr) minmax(56px, 0.4fr); + gap: 10px; + align-items: center; + border-top: 1px solid var(--line-soft); + padding: 9px 10px; + color: var(--muted); + font-size: 12px; +} + +.source-table-row:first-child { + border-top: 0; +} + +.source-table-head { + color: var(--ink-soft); + background: rgba(246, 246, 242, 0.74); + font-weight: 780; +} + +.source-table-row span { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.source-table-row .ok { + color: var(--good); + font-weight: 760; +} + +.source-table-row .bad { + color: var(--bad); + font-weight: 760; +} + +.source-table-foot { + display: block; + color: var(--ink-soft); + background: rgba(246, 246, 242, 0.74); + font-weight: 780; + text-align: right; +} + +.list-wrap, +.waytoagi-wrap { + margin-top: 18px; + border: 1px solid var(--line-soft); + border-radius: var(--radius); + background: var(--surface); + overflow: hidden; +} + +.list-wrap { + background: var(--surface); +} + +/* 双色交替:WaytoAGI 版块用深一档的底色,与伯乐精选 / AI信号流形成节奏感 */ +.waytoagi-wrap { + background: var(--bg-alt); + border-color: rgba(23, 23, 23, 0.12); +} + +.list-head, +.waytoagi-head { + padding: 16px 18px; + display: flex; + flex-wrap: nowrap; + justify-content: space-between; + align-items: center; + gap: 12px; + border-bottom: 1px solid var(--line-soft); + background: var(--surface); +} + +/* WaytoAGI header 用对应的深档底色 */ +.waytoagi-head { + background: var(--surface-alt); + border-bottom-color: rgba(23, 23, 23, 0.1); +} + +.list-head h2, +.waytoagi-head h2 { + margin: 0; + font-size: 22px; +} + +#resultCount, +#waytoagiUpdatedAt { + color: var(--muted); + font-size: 13px; + white-space: nowrap; +} + +.list-head-tools { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 10px; + min-width: 0; + flex-wrap: wrap; +} + +.bole-more-btn, +.list-more-btn { + display: block; + width: calc(100% - 32px); + margin: 0 16px 16px; + border: 1px solid var(--line); + border-radius: var(--radius); + background: var(--surface); + color: var(--accent); + cursor: pointer; + font-size: 13px; + font-weight: 760; + min-height: 38px; +} + +.bole-more-btn:hover, +.list-more-btn:hover { + border-color: rgba(18, 106, 115, 0.38); + background: rgba(18, 106, 115, 0.06); +} + +.list-more-btn { + margin-top: 12px; +} + +.bole-empty { + grid-column: 1 / -1; + border: 1px dashed var(--line); + border-radius: var(--radius); + padding: 14px; + color: var(--muted); + font-size: 13px; +} + +.intel-card-meta { + display: flex; + flex-wrap: wrap; + gap: 7px; + align-items: center; + color: var(--muted); + font-size: 12px; +} + +.intel-score { + color: var(--accent); +} + +.top-story-title, +.intel-title { + color: var(--ink); + font-weight: 790; + line-height: 1.38; + letter-spacing: 0; + overflow-wrap: anywhere; +} + +.original-action, +.original-link { + color: var(--accent); + font-size: 12px; + font-weight: 760; + text-decoration: none; +} + +.original-action { + justify-self: start; + border-bottom: 1px solid rgba(18, 106, 115, 0.3); + padding-bottom: 1px; +} + +.original-link { + margin-left: auto; +} + +.original-link:hover { + text-decoration: underline; +} + +.intel-reason { + margin: 0; + color: var(--muted); + font-size: 13px; + line-height: 1.48; + overflow-wrap: anywhere; +} + +.intel-tags, +.intel-card-sources, +.intel-sources { + display: flex; + flex-wrap: wrap; + gap: 6px; + align-items: center; +} + +.signal-tag, +.intel-tags > span, +.intel-card-sources > span, +.intel-card-sources > strong, +.intel-sources { + border: 1px solid var(--line); + border-radius: 999px; + padding: 3px 7px; + color: var(--muted); + background: rgba(255, 255, 255, 0.72); + font-size: 11px; + line-height: 1.25; +} + +.intel-tags > span { + color: var(--accent); + border-color: rgba(18, 106, 115, 0.22); + background: rgba(18, 106, 115, 0.07); + font-weight: 720; +} + +.signal-tag.tone-official, +.ai-tag.tone-official { + color: var(--good); + border-color: rgba(31, 122, 77, 0.32); + background: rgba(31, 122, 77, 0.08); +} + +.signal-tag.tone-hot, +.ai-tag.tone-hot, +.signal-tag.tone-community, +.ai-tag.tone-community { + color: var(--accent-warm); + border-color: rgba(181, 82, 49, 0.32); + background: rgba(181, 82, 49, 0.08); +} + +.signal-tag.tone-models, +.ai-tag.tone-models { + color: #2a658a; + border-color: rgba(42, 101, 138, 0.3); + background: rgba(42, 101, 138, 0.08); +} + +.signal-tag.tone-devtools, +.ai-tag.tone-devtools { + color: var(--accent); + border-color: rgba(18, 106, 115, 0.28); + background: rgba(18, 106, 115, 0.08); +} + +.signal-tag.tone-aggregate, +.ai-tag.tone-aggregate { + color: #5f6b75; + border-color: rgba(95, 107, 117, 0.28); + background: rgba(95, 107, 117, 0.08); +} + +.signal-tag.tone-research, +.ai-tag.tone-research { + color: #6b568f; + border-color: rgba(107, 86, 143, 0.3); + background: rgba(107, 86, 143, 0.08); +} + +.signal-tag.tone-products, +.ai-tag.tone-products { + color: #8a5b20; + border-color: rgba(138, 91, 32, 0.3); + background: rgba(138, 91, 32, 0.08); +} + +.signal-tag.tone-creator, +.ai-tag.tone-creator { + color: #874860; + border-color: rgba(135, 72, 96, 0.3); + background: rgba(135, 72, 96, 0.08); +} + +.signal-tag.tone-industry, +.ai-tag.tone-industry { + color: #5c6258; + border-color: rgba(92, 98, 88, 0.3); + background: rgba(92, 98, 88, 0.08); +} + +.signal-tag.tone-strong, +.ai-tag.tone-strong { + color: var(--good); + border-color: rgba(31, 122, 77, 0.28); + background: rgba(31, 122, 77, 0.08); +} + +.signal-tag.tone-default, +.ai-tag.tone-default { + color: var(--muted); + border-color: rgba(102, 100, 95, 0.26); + background: rgba(102, 100, 95, 0.06); +} + +.source-chip { + display: inline-flex; + min-width: 0; + align-items: center; + gap: 5px; +} + +.source-dot { + width: 6px; + height: 6px; + flex: 0 0 auto; + border-radius: 50%; + background: currentColor; + box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.72); +} + +.source-chip-label { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.kind-official { + color: var(--good); + border-color: rgba(31, 122, 77, 0.28); + background: rgba(31, 122, 77, 0.08); +} + +.kind-hot { + color: var(--accent-warm); + border-color: rgba(181, 82, 49, 0.3); + background: rgba(181, 82, 49, 0.08); +} + +.kind-aihub { + color: var(--accent); + border-color: rgba(18, 106, 115, 0.26); + background: rgba(18, 106, 115, 0.07); +} + +.kind-builders, +.kind-newsletter { + color: var(--warn); + border-color: rgba(154, 103, 0, 0.28); + background: rgba(154, 103, 0, 0.07); +} + +.kind-creator { + color: #874860; + border-color: rgba(135, 72, 96, 0.28); + background: rgba(135, 72, 96, 0.07); +} + +.kind-aggregate, +.kind-blogs, +.kind-default { + color: var(--muted); + border-color: rgba(102, 100, 95, 0.26); + background: rgba(102, 100, 95, 0.06); +} + +.source-chip.kind-official { + color: var(--good); + border-color: rgba(31, 122, 77, 0.28); + background: rgba(31, 122, 77, 0.08); +} + +.source-chip.kind-hot { + color: var(--accent-warm); + border-color: rgba(181, 82, 49, 0.3); + background: rgba(181, 82, 49, 0.08); +} + +.source-chip.kind-aihub { + color: var(--accent); + border-color: rgba(18, 106, 115, 0.26); + background: rgba(18, 106, 115, 0.07); +} + +.source-chip.kind-builders, +.source-chip.kind-newsletter { + color: var(--warn); + border-color: rgba(154, 103, 0, 0.28); + background: rgba(154, 103, 0, 0.07); +} + +.source-chip.kind-creator { + color: #874860; + border-color: rgba(135, 72, 96, 0.28); + background: rgba(135, 72, 96, 0.07); +} + +.source-chip.kind-aggregate, +.source-chip.kind-blogs, +.source-chip.kind-default { + color: var(--muted); + border-color: rgba(102, 100, 95, 0.26); + background: rgba(102, 100, 95, 0.06); +} + +.intel-sources { + justify-self: start; + border-radius: var(--radius); + line-height: 1.35; +} + +.news-list { + padding: 8px 18px 18px; + gap: 8px; +} + +.intel-card { + min-width: 0; + display: grid; + gap: 8px; + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 13px 14px; + background: var(--surface); + transition: transform 0.18s ease, box-shadow 0.18s ease, border-color 0.18s ease; +} + +.intel-card:hover { + border-color: rgba(18, 106, 115, 0.32); + background: #fff; +} + +.intel-card-rank { + color: var(--accent); + font-weight: 800; +} + +.intel-title { + display: block; + font-size: 16px; + text-decoration: none; +} + +.intel-title:hover { + color: var(--accent); +} + +.intel-score.hot { + color: var(--accent-warm); +} + +.intel-score.strong { + color: var(--good); +} + +.intel-card-sources { + min-width: 0; +} + +.intel-card-sources > span, +.intel-card-sources > strong { + max-width: 260px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.news-list, +.site-group-list, +.source-group-list { + display: grid; +} + +.list-loading { + padding: 18px 16px; + color: var(--muted); + font-size: 13px; + background: var(--surface-soft); +} + +.list-more-btn:focus-visible { + outline: 2px solid var(--accent); + outline-offset: -2px; +} + +.news-card { + min-width: 0; +} + +.meta-row { + display: flex; + flex-wrap: wrap; + gap: 7px; + align-items: center; + margin-top: 7px; + color: var(--muted); + font-size: 12px; +} + +.site { + font-weight: 700; + color: #3f3d39; +} + +.category, +.source, +.ai-tag, +.multi-chip, +.meta-row .signal-tag { + padding: 2px 7px; + border: 1px solid var(--line); + border-radius: 999px; + font-size: 11px; +} + +.category { + color: var(--ink); + background: var(--surface-soft); +} + +.category.kind-official { + border-color: rgba(31, 122, 77, 0.34); + color: var(--good); +} + +.category.kind-newsletter { + border-color: rgba(154, 103, 0, 0.34); + color: var(--warn); +} + +.category.kind-builders { + border-color: rgba(181, 82, 49, 0.36); + color: var(--accent-warm); +} + +.category.kind-creator { + border-color: rgba(135, 72, 96, 0.32); + color: #874860; +} + +.category.kind-aihub { + border-color: rgba(18, 106, 115, 0.28); + color: var(--accent); +} + +.category.kind-aggregate, +.category.kind-blogs { + color: var(--muted); +} + +.ai-tag { + border-color: rgba(18, 106, 115, 0.22); + background: rgba(18, 106, 115, 0.07); + color: var(--accent); + font-weight: 650; +} + +.source.source-chip { + max-width: 220px; + font-weight: 650; +} + +.ai-tag.hot { + border-color: rgba(181, 82, 49, 0.3); + background: rgba(181, 82, 49, 0.08); + color: var(--accent-warm); +} + +.ai-tag.strong { + border-color: rgba(31, 122, 77, 0.28); + background: rgba(31, 122, 77, 0.08); + color: var(--good); +} + +.ai-tag.watch { + color: var(--muted); + background: var(--surface-soft); +} + +.multi-chip { + color: var(--ink); + background: var(--surface-soft); + font-weight: 650; + cursor: pointer; + font-family: inherit; + line-height: 1.4; +} + +.multi-chip:hover { + border-color: var(--accent); + color: var(--accent); +} + +.multi-chip[aria-expanded="true"] { + border-color: var(--accent); + color: var(--accent); + background: rgba(18, 106, 115, 0.06); +} + +.title { + min-width: 0; + margin-top: 0; + display: inline-flex; + flex-direction: column; + gap: 3px; + color: var(--ink); + text-decoration: none; + font-size: 16px; + line-height: 1.42; + overflow-wrap: anywhere; +} + +.news-summary { + margin: 7px 0 0; + color: var(--muted); + font-size: 13px; + line-height: 1.45; +} + +.title-sub { + color: var(--muted); + font-size: 12px; + line-height: 1.35; + font-weight: 400; +} + +.title:hover { + color: var(--accent); +} + +.empty { + padding: 24px 16px; + color: var(--muted); + text-align: center; +} + +.empty h3 { + margin: 0; + color: var(--ink); + font-size: 17px; +} + +.empty p { + margin: 7px 0 14px; +} + +.empty-reset-btn { + min-height: 38px; +} + +.waytoagi-tools { + display: inline-flex; + align-items: center; + gap: 10px; +} + +.waytoagi-switch { + display: inline-flex; + border: 1px solid var(--line); + border-radius: var(--radius); + overflow: hidden; + background: var(--surface); +} + +.waytoagi-btn { + min-height: 32px; + border: 0; + border-left: 1px solid var(--line); + background: transparent; + color: var(--muted); + padding: 0 10px; + font-size: 12px; +} + +.waytoagi-btn:first-child { + border-left: 0; +} + +.waytoagi-btn.active { + background: var(--accent); + color: #fff; + font-weight: 700; +} + +.waytoagi-meta { + padding: 12px 16px 0; + display: flex; + flex-wrap: wrap; + gap: 8px; + font-size: 12px; + color: var(--muted); +} + +.waytoagi-meta a { + color: var(--accent); + text-decoration: none; +} + +.waytoagi-list { + padding: 12px 16px 16px; + display: grid; + gap: 8px; +} + +.waytoagi-item { + min-width: 0; + display: grid; + grid-template-columns: 76px minmax(0, 1fr); + gap: 8px; + text-decoration: none; + border: 1px solid rgba(23, 23, 23, 0.08); + border-radius: var(--radius); + padding: 8px 10px; + color: var(--ink); + background: var(--surface); /* alt 版块里卡片用纯白,形成内部层次 */ +} + +.waytoagi-item .d { + color: var(--muted); + font-size: 12px; +} + +.waytoagi-item .t { + min-width: 0; + font-size: 13px; + line-height: 1.35; + overflow-wrap: anywhere; +} + +.waytoagi-empty, +.waytoagi-error { + border-radius: var(--radius); + padding: 9px 10px; + font-size: 13px; +} + +.waytoagi-empty { + border: 1px dashed var(--line); + color: var(--muted); +} + +.waytoagi-error { + border: 1px solid rgba(180, 35, 24, 0.28); + background: rgba(180, 35, 24, 0.08); + color: var(--bad); +} + +@media (max-width: 760px) { + .shell { + padding: 18px 12px 36px; + } + + .hero, + .advanced-controls, + .waytoagi-head { + grid-template-columns: 1fr; + } + + .hero { + gap: 10px; + padding-bottom: 12px; + } + + .advanced-panel > summary { + min-height: 46px; + align-items: center; + flex-direction: row; + padding-block: 9px; + } + + .advanced-hint { + max-width: 65%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .hero h1 { + font-size: 30px; + } + + .hero-logo { + width: 48px; + height: 48px; + } + + .hero-meta { + display: flex; + flex-wrap: wrap; + justify-content: flex-start; + align-items: center; + gap: 8px; + min-width: 0; + text-align: left; + } + + .hero-links { + width: auto; + justify-content: flex-start; + } + + .updated-label { + display: none; + } + + .updated { + display: inline-flex; + align-items: center; + min-height: 30px; + border: 1px solid var(--line-soft); + border-radius: 999px; + padding: 5px 10px; + background: rgba(255, 255, 255, 0.62); + font-size: 12px; + } + + .updated::before { + content: "更新"; + margin-right: 5px; + color: var(--muted); + font-weight: 650; + } + + .source-status-pill { + min-height: 30px; + padding: 5px 10px; + font-size: 12px; + } + + .section-nav-wrap { + position: sticky; + z-index: 8; + top: 0; + margin-right: -12px; + margin-left: -12px; + padding: 7px 12px; + border-top: 1px solid rgba(23, 23, 23, 0.06); + border-bottom: 1px solid rgba(23, 23, 23, 0.08); + background: rgba(246, 246, 242, 0.96); + backdrop-filter: blur(10px); + } + + .section-tabs { + padding-bottom: 1px; + } + + .section-scroll-hint { + display: block; + margin-top: -5px; + color: var(--accent); + font-size: 11px; + font-weight: 680; + text-align: right; + } + + .section-tab { + min-height: 38px; + padding: 0 10px; + } + + .mode-hint, + .advanced-hint, + #resultCount, + #waytoagiUpdatedAt { + white-space: normal; + } + + .primary-controls { + grid-template-columns: minmax(0, 1fr) auto; + gap: 8px; + } + + .primary-controls .mode-switch { + grid-column: 1 / -1; + } + + .clear-filters-btn { + grid-column: 1 / -1; + min-height: 38px; + } + + .mode-hint { + min-height: 42px; + max-width: 112px; + padding-inline: 10px; + white-space: nowrap; + } + + .waytoagi-head { + align-items: flex-start; + flex-direction: column; + } + + .list-head { + align-items: flex-start; + flex-direction: column; + } + + .list-head-tools { + width: 100%; + justify-content: space-between; + } + + .news-list { + padding: 10px 12px 12px; + } + + .source-status-table { + overflow-x: auto; + } + + .source-table { + min-width: 580px; + } +} + +@media (max-width: 460px) { + .hero-headline { + align-items: flex-start; + } + + .source-health-summary { + align-items: flex-start; + flex-direction: column; + } + + .section-tab { + gap: 6px; + font-size: 12px; + } + + .section-tab strong { + min-width: 20px; + padding: 3px 5px; + } + + .intel-card { + padding: 12px; + } + + .intel-card-sources > span, + .intel-card-sources > strong { + max-width: 180px; + } + + .waytoagi-tools { + align-items: flex-start; + flex-direction: column; + } +} + +/* Motion layer */ +.news-card, +.intel-card { + transition: transform 0.18s ease, box-shadow 0.18s ease, border-color 0.18s ease; +} + +.news-card:hover, +.intel-card:hover { + transform: translateY(-2px); + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.07); +} + +@media (prefers-reduced-motion: reduce) { + .news-card, + .intel-card { + will-change: auto; + transition: none; + transform: none !important; + } + + .news-card:hover, + .intel-card:hover { + box-shadow: none; + } +} + +/* 入场动画只做位移、不碰透明度:后台/冻结页面里动画不启动时, + 元素最多偏移几像素但始终可见,绝不会像 opacity 动画那样被困在透明态。 */ +@media (prefers-reduced-motion: no-preference) { + @keyframes card-enter { + from { + transform: translateY(12px); + } + } + + #newsList .news-card { + animation: card-enter 0.4s ease; + } + + @keyframes nav-enter { + from { + transform: translateY(8px); + } + } + + .section-tab { + animation: nav-enter 0.3s ease; + } +} + +/* ============================================================ + Persona 三味点评(v0.8) + 只用既有变量:--accent / --ink-soft / --muted / --line / --surface + 红线:0 圆角、1px 实线边框、单一 accent 色 + ============================================================ */ + +.story-persona { + display: flex; + align-items: baseline; + gap: 7px; + min-width: 0; +} + +.story-persona-label { + flex: none; + border-left: 2px solid var(--accent); + padding-left: 6px; + color: var(--accent); + font-size: 11px; + font-weight: 760; + line-height: 1.2; +} + +.story-persona-text { + color: var(--ink-soft); + font-size: 11px; + line-height: 1.5; + overflow-wrap: anywhere; +} + +.persona-panel { + display: grid; + grid-template-columns: repeat(3, 1fr); + border: 1px solid var(--line); + border-radius: 0; + background: var(--surface); +} + +.persona-col { + display: grid; + gap: 4px; + align-content: start; + padding: 9px 10px; + min-width: 0; +} + +.persona-col + .persona-col { + border-left: 1px solid var(--line); +} + +.persona-name { + color: var(--accent); + font-size: 11px; + font-weight: 760; + line-height: 1.2; +} + +.persona-score { + color: var(--ink); + font-size: 14px; + font-weight: 790; + line-height: 1.2; +} + +.persona-review { + margin: 0; + color: var(--ink-soft); + font-size: 11px; + line-height: 1.5; + overflow-wrap: anywhere; +} + +@media (max-width: 720px) { + .persona-panel { + grid-template-columns: 1fr; + } + + .persona-col + .persona-col { + border-left: 0; + border-top: 1px solid var(--line); + } +} + +/* ---- AIHOT 式单层信息架构:热点排行区 + 共享卡片组件(v0.9 重构)---- */ +/* 红线:单强调色 var(--accent)、0 圆角、1px 边框、无渐变无阴影 */ + +.hot-board-list { + display: flex; + flex-direction: column; +} + +/* 今日 TOP3 板块:复用完整精选卡片(含三口味并排面板),卡片间留缝即可 */ +.top3-board-list { + display: flex; + flex-direction: column; + gap: 10px; +} + +/* 热点排行区:一行一条(AIHOT 式),不复用下方精选列表的完整卡片,避免摘要/标签重复展示 */ +.hot-row { + display: flex; + align-items: center; + gap: 10px; + min-height: 40px; + padding: 0 12px; + border-top: 1px solid rgba(23, 23, 23, 0.06); +} + +.hot-row:first-child { + border-top: 0; +} + +.hot-row-rank { + flex: 0 0 auto; + min-width: 24px; + color: var(--accent); + font-weight: 800; + font-variant-numeric: tabular-nums; +} + +.hot-row-title { + min-width: 0; + flex: 1 1 auto; + overflow: hidden; + color: var(--ink); + font-size: 14px; + text-decoration: none; + text-overflow: ellipsis; + white-space: nowrap; +} + +.hot-row-title:hover { + color: var(--accent); +} + +.hot-row-meta { + flex: 0 0 auto; + color: var(--muted); + font-size: 12px; + white-space: nowrap; +} + +/* 精选/全量全局开关,紧挨搜索框;min-width 与 .section-tabs 的 全部/模型 按钮宽度对齐 */ +.curation-mode-switch .mode-btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + min-width: 88px; + box-sizing: border-box; +} + +.mode-btn-icon { + opacity: 0.82; +} + +/* 日期分组条:坐在时间轴左侧,作为轴上的日期锚点;日期 + 星期/条数(弱化) */ +.date-group-header { + margin-top: 4px; + padding: 10px 12px 6px; + border-top: 1px solid rgba(23, 23, 23, 0.06); + display: flex; + align-items: baseline; + gap: 6px; + color: var(--ink); + font-size: 13px; + font-weight: 800; +} + +.date-group-header:first-child { + margin-top: 0; + border-top: 0; +} + +.date-group-meta { + color: var(--muted); + font-size: 13px; + font-weight: 400; +} + +/* 主列表时间轴:左侧 rail(时间点 + 竖线)+ 右侧卡片,精选/全量共用。 + 卡片间距用 .timeline-item 的 padding-bottom(而非卡片 margin-bottom), + 这样竖线伪元素(挂在 .timeline-item 上)top:0/bottom:0 覆盖 padding 区域, + 在卡片之间的间隙里也保持连续,不会断线。 + 父容器 #newsList 的 grid gap 是 8px,这段间隙不属于 .timeline-item 自身的盒子, + ::before 覆盖不到——用 :has(+ .timeline-item) 让竖线多探出 8px 桥接过去, + 卡片间总间距 = padding-bottom(8px) + grid gap(8px) = 16px。 */ +.timeline-item { + position: relative; + display: grid; + grid-template-columns: 72px minmax(0, 1fr); + gap: 0 10px; + padding-bottom: 8px; +} + +.timeline-item::before { + content: ""; + position: absolute; + top: 0; + bottom: 0; + left: 36px; + width: 1px; + background: var(--line); + transform: translateX(-50%); +} + +/* 同一日期分组内,前一项后面紧跟着另一项时,桥接父容器的 8px grid gap,让竖线不断 */ +.timeline-item:has(+ .timeline-item)::before { + bottom: -8px; +} + +.timeline-rail { + position: relative; + display: flex; + flex-direction: column; + align-items: center; + padding: 13px 0; +} + +.timeline-time { + position: relative; + z-index: 1; + padding: 0 4px; + color: var(--muted); + font-size: 12px; + font-variant-numeric: tabular-nums; + background: var(--surface); +} + +.timeline-dot { + position: relative; + z-index: 1; + margin-top: 6px; + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--accent); +} + +@media (max-width: 720px) { + .timeline-item { + grid-template-columns: 56px minmax(0, 1fr); + } + + .timeline-item::before { + left: 28px; + } +} + +/* 共享卡片组件:主列表基础卡片,嵌在 .timeline-item 右侧。 + AIHOT 参考图里每条是漂浮在轴线旁的独立白卡:边框 + 圆角 + 极轻阴影。 */ +.news-card { + position: relative; + display: flex; + gap: 10px; + border: 1px solid var(--line-soft); + border-radius: var(--radius); + padding: 16px 18px; + background: var(--surface); + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04); +} + +.news-card-body { + min-width: 0; + flex: 1 1 auto; + display: grid; + gap: 4px; +} + +.curated-badge { + border: 1px solid rgba(181, 82, 49, 0.32); + border-radius: 999px; + padding: 2px 7px; + color: var(--accent-warm); + background: rgba(181, 82, 49, 0.07); + font-size: 11px; + font-weight: 720; +} + +.score-badge { + border: 1px solid var(--line); + border-radius: 999px; + padding: 2px 7px; + color: var(--accent); + background: rgba(18, 106, 115, 0.06); + font-size: 11px; + font-weight: 780; +} + +.score-badge.tone-hot { + color: var(--accent-warm); + border-color: rgba(181, 82, 49, 0.3); + background: rgba(181, 82, 49, 0.08); +} + +.score-badge.tone-strong { + color: var(--good); + border-color: rgba(31, 122, 77, 0.28); + background: rgba(31, 122, 77, 0.08); +} + +.why-box { + margin-top: 2px; + border-left: 2px solid rgba(18, 106, 115, 0.28); + padding-left: 10px; + font-size: 13px; + line-height: 1.5; +} + +.why-label { + color: var(--ink); + font-weight: 820; + margin-right: 4px; +} + +.why-text { + color: var(--muted); + overflow-wrap: anywhere; +} + +.persona-slot:empty { + display: none; +} + +/* 同一事件展开:时间线卡片内联子列表 + 热点行内联子列表,共用同一套行样式。 + 触发器现在是 meta-row 里的 .multi-chip(时间线卡片)/ .hot-row-source-toggle(热点行)。 + 红线:单强调色 var(--accent)、0 圆角、1px 边框,不新增色彩。 */ +.event-expand-list { + display: grid; + gap: 6px; + margin-top: 2px; + padding-top: 8px; + border-top: 1px solid var(--line-soft); +} + +/* [hidden] 属性的优先级低于同 specificity 的作者样式(origin 优先于 specificity), + .event-expand-list 的 display: grid 会盖掉 UA 自带的 [hidden]{display:none}, + 导致 multi-chip 第二次点击设 hidden=true 后列表仍然可见。显式声明覆盖修复。 */ +.event-expand-list[hidden] { + display: none; +} + +.event-source-row { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 6px; + padding-left: 10px; + font-size: 12px; + line-height: 1.4; +} + +.event-source-title { + min-width: 0; + flex: 1 1 auto; + color: var(--ink); + text-decoration: none; + overflow-wrap: anywhere; +} + +.event-source-title:hover { + color: var(--accent); +} + +.event-source-name { + flex: 0 0 auto; + color: var(--muted); +} + +.event-source-time { + flex: 0 0 auto; + color: var(--muted-soft); + white-space: nowrap; +} + +/* 热点行的信源数变成按钮:子列表插在 .hot-row 正下方,作为独立一行,靠标题列缩进对齐 */ +.hot-row-source-toggle { + border: 0; + background: transparent; + padding: 0; + margin: 0; + color: inherit; + font: inherit; + cursor: pointer; + text-decoration: underline dotted; + text-underline-offset: 2px; +} + +.hot-row-source-toggle:hover { + color: var(--accent); +} + +.hot-row-source-list.event-expand-list { + margin: 0 0 0 34px; + padding: 8px 12px 10px; + border-top: 1px solid rgba(23, 23, 23, 0.06); +} + +/* DATA_BASE_URL 数据同源开关:非空时展示一行提示 + 恢复本地按钮 */ +.data-source-indicator { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + color: var(--muted); + font-size: 12px; + overflow-wrap: anywhere; +} + +.data-source-reset-btn { + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 2px 8px; + color: var(--muted); + background: var(--surface-soft); + font-size: 12px; + cursor: pointer; +} + +.data-source-reset-btn:hover { + color: var(--accent); + border-color: var(--accent); +} diff --git a/skills/ai-news-radar/assets/view-mode.js b/skills/ai-news-radar/assets/view-mode.js new file mode 100644 index 0000000..d92a7b4 --- /dev/null +++ b/skills/ai-news-radar/assets/view-mode.js @@ -0,0 +1,140 @@ +(function () { + "use strict"; + + const STORAGE_KEY = "aiNewsRadarViewV2"; + const LEGACY_STORAGE_KEY = "aiNewsRadarView"; + const MOBILE_OVERRIDE_KEY = "aiNewsRadarMobileViewOnce"; + const MOBILE_BREAKPOINT = "(max-width: 760px)"; + const VALID_VIEWS = new Set(["mobile", "classic"]); + const script = document.currentScript; + const rootHint = script?.dataset.root || "./"; + const rootUrl = new URL(rootHint, window.location.href); + const currentView = document.documentElement.dataset.radarView || "mobile"; + const params = new URLSearchParams(window.location.search); + const requestedView = params.get("view") || ""; + const isMobileViewport = window.matchMedia(MOBILE_BREAKPOINT).matches; + + try { + window.localStorage.removeItem(LEGACY_STORAGE_KEY); + } catch { + // Storage can be unavailable in private or hardened browser contexts. + } + + function readPreference() { + try { + const value = window.localStorage.getItem(STORAGE_KEY) || ""; + return VALID_VIEWS.has(value) ? value : ""; + } catch { + return ""; + } + } + + function writePreference(view) { + try { + if (VALID_VIEWS.has(view)) { + window.localStorage.setItem(STORAGE_KEY, view); + } else { + window.localStorage.removeItem(STORAGE_KEY); + } + } catch { + // Storage can be unavailable in private or hardened browser contexts. + } + } + + function readMobileOverride() { + try { + const value = window.sessionStorage.getItem(MOBILE_OVERRIDE_KEY) || ""; + window.sessionStorage.removeItem(MOBILE_OVERRIDE_KEY); + return VALID_VIEWS.has(value) ? value : ""; + } catch { + return ""; + } + } + + function writeMobileOverride(view) { + try { + if (VALID_VIEWS.has(view)) { + window.sessionStorage.setItem(MOBILE_OVERRIDE_KEY, view); + } else { + window.sessionStorage.removeItem(MOBILE_OVERRIDE_KEY); + } + } catch { + // Storage can be unavailable in private or hardened browser contexts. + } + } + + if (requestedView === "auto") { + writePreference(""); + writeMobileOverride(""); + } else if (!isMobileViewport && VALID_VIEWS.has(requestedView)) { + writePreference(requestedView); + } + + const mobileOverride = isMobileViewport ? readMobileOverride() : ""; + const preference = isMobileViewport + ? mobileOverride + : (requestedView === "auto" + ? "" + : (VALID_VIEWS.has(requestedView) ? requestedView : readPreference())); + const deviceDefault = "mobile"; + const targetView = preference || deviceDefault; + + function destination(view) { + const url = new URL(view === "classic" ? "classic/" : "./", rootUrl); + const passthrough = new URLSearchParams(window.location.search); + passthrough.delete("view"); + url.search = passthrough.toString(); + url.hash = window.location.hash; + return url; + } + + function cleanViewQuery() { + if (!requestedView) return; + const cleanUrl = destination(currentView); + window.history.replaceState(null, "", `${cleanUrl.pathname}${cleanUrl.search}${cleanUrl.hash}`); + } + + function chooseView(view) { + if (!VALID_VIEWS.has(view)) return; + if (isMobileViewport) writeMobileOverride(view); + else writePreference(view); + if (view === currentView) return; + window.location.assign(destination(view).href); + } + + if (targetView !== currentView) { + window.location.replace(destination(targetView).href); + return; + } + + cleanViewQuery(); + + function mountSwitches() { + document.querySelectorAll("[data-radar-view-target]").forEach((button) => { + const view = button.dataset.radarViewTarget || ""; + const active = view === currentView; + button.classList.toggle("is-active", active); + button.setAttribute("aria-pressed", active ? "true" : "false"); + if (active) button.setAttribute("aria-current", "page"); + else button.removeAttribute("aria-current"); + button.addEventListener("click", () => chooseView(view)); + }); + } + + if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", mountSwitches, { once: true }); + } else { + mountSwitches(); + } + + window.AINewsRadarView = { + current: currentView, + preference: preference || "auto", + choose: chooseView, + reset() { + writePreference(""); + writeMobileOverride(""); + window.location.replace(destination(deviceDefault).href); + }, + }; +})(); diff --git a/skills/ai-news-radar/assets/view-switch.css b/skills/ai-news-radar/assets/view-switch.css new file mode 100644 index 0000000..b8de32a --- /dev/null +++ b/skills/ai-news-radar/assets/view-switch.css @@ -0,0 +1,130 @@ +.hero-view-row { + display: flex; + min-width: 0; + flex-wrap: wrap; + align-items: center; + gap: 6px; + margin: 4px 0 0; + color: var(--muted, #66645f); + font-size: 13px; +} + +.hero-meta { + align-self: center; +} + +.view-switch { + display: inline-flex; + min-height: 30px; + flex: 0 0 auto; + align-items: center; + gap: 2px; + border: 1px solid var(--line-soft, rgba(23, 23, 23, 0.12)); + border-radius: 999px; + padding: 2px; + background: rgba(251, 250, 247, 0.78); +} + +.view-switch-label { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip: rect(0 0 0 0); + clip-path: inset(50%); + white-space: nowrap; +} + +.view-switch-btn { + min-height: 24px; + border: 0; + border-radius: 999px; + padding: 0 8px; + color: var(--muted, #66645f); + background: transparent; + font: inherit; + font-size: 12px; + font-weight: 700; + white-space: nowrap; + cursor: pointer; +} + +.view-switch-btn:hover { + color: var(--ink, #171717); + background: rgba(18, 106, 115, 0.06); +} + +.view-switch-btn.is-active { + color: #fff; + background: var(--accent, #126a73); +} + +.view-switch-btn:focus-visible { + outline: 2px solid rgba(18, 106, 115, 0.35); + outline-offset: 2px; +} + +html[data-radar-view="classic"] .data-source-indicator { + display: flex; + min-width: 0; + align-items: center; + justify-content: space-between; + gap: 10px; + border: 1px solid rgba(18, 106, 115, 0.18); + border-radius: var(--radius, 8px); + padding: 8px 10px; + color: var(--accent, #126a73); + background: rgba(18, 106, 115, 0.06); + font-size: 12px; +} + +html[data-radar-view="classic"] .data-source-indicator[hidden] { + display: none; +} + +html[data-radar-view="classic"] .data-source-indicator > span { + min-width: 0; + overflow-wrap: anywhere; +} + +html[data-radar-view="classic"] .data-source-reset-btn { + flex: 0 0 auto; + min-height: 30px; + border: 1px solid rgba(18, 106, 115, 0.24); + border-radius: calc(var(--radius, 8px) - 2px); + padding: 0 9px; + color: var(--accent, #126a73); + background: rgba(255, 255, 255, 0.72); + font: inherit; + font-weight: 700; +} + +html[data-radar-view="classic"] .data-source-reset-btn:hover { + background: #fff; +} + +html[data-radar-view="classic"] .data-source-reset-btn:focus-visible { + outline: 2px solid rgba(18, 106, 115, 0.35); + outline-offset: 2px; +} + +@media (max-width: 760px) { + .hero { + gap: 10px; + } + + .hero-links { + width: auto; + } + + .view-switch-btn { + padding: 0 7px; + font-size: 11px; + } +} + +@media (max-width: 360px) { + .view-switch-btn { + padding: 0 6px; + } +} diff --git a/skills/ai-news-radar/catalog-metadata.v1.json b/skills/ai-news-radar/catalog-metadata.v1.json index 7e9183a..9e2dc94 100644 --- a/skills/ai-news-radar/catalog-metadata.v1.json +++ b/skills/ai-news-radar/catalog-metadata.v1.json @@ -10,11 +10,13 @@ "i18n": { "en-US": { "name": "AI News Radar", - "summary": "24/7 AI news radar that curates multiple sources into storylines and delivers daily headlines with three flavors of commentary. Requires a separately configured Python environment and sources; mail access requires separate authorization." + "summary": "Generate AI daily-brief JSON with a complete MIT Python package. Requires Python 3.11+, dependencies and feed access; optional mail/API sources need separate authorization.", + "description": "Optional local MIT edition based on LearnPrompt/ai-news-radar@689395109cc962a27c369bdd6fa50d1e090eb319. Includes generation scripts, feed example, glossary, source-analysis helper, referenced docs and reader assets. Outputs belong outside the installed skill; external services and optional credentials are separately configured." }, "zh-CN": { "name": "AI 资讯雷达", - "summary": "24 小时 AI 资讯雷达:从多信源筛选要闻、合并成故事线,并用三种口味锐评每日头条。需自行配置 Python 运行环境与信源;邮件接入须另行授权。" + "summary": "完整 MIT 本地包生成 AI 日报 JSON。需 Python 3.11+、依赖和信源访问;可选邮件/API 集成须独立授权。", + "description": "基于 LearnPrompt/ai-news-radar@689395109cc962a27c369bdd6fa50d1e090eb319 的可选 MIT 本地版,包含生成脚本、信源示例、词表、分析工具、引用文档和阅读器资源。运行结果须写入安装目录之外;外部服务与可选凭据需单独配置。" } }, "category": "productivity", @@ -25,12 +27,14 @@ ] }, "release": { - "state": "unknown" + "state": "known", + "version": "2026.11.24", + "versionScheme": "calver" }, "timestamps": { "catalogUpdatedAt": { "state": "known", - "value": "2026-10-05", + "value": "2026-11-24", "precision": "day" }, "releasePublishedAt": { @@ -38,12 +42,12 @@ }, "reviewedAt": { "state": "known", - "value": "2026-10-05", + "value": "2026-11-24", "precision": "day" }, "upstreamObservedAt": { "state": "known", - "value": "2026-10-05", + "value": "2026-11-24", "precision": "day" } }, @@ -51,13 +55,12 @@ "content": { "kind": "git", "url": "https://github.com/LearnPrompt/ai-news-radar.git", - "path": "skills/ai-news-radar", "ref": "689395109cc962a27c369bdd6fa50d1e090eb319" } }, "governance": { "stewardship": "community", - "availability": "listing-only", + "availability": "installable", "license": { "state": "known", "value": "MIT", @@ -68,6 +71,19 @@ "name": "LearnPrompt", "url": "https://github.com/LearnPrompt/ai-news-radar", "verified": false + }, + "listingMaintainer": { + "name": "mashagua", + "url": "https://github.com/mashagua", + "verified": true + }, + "compliance": { + "licenseEvidencePath": "LICENSE", + "noticePath": "UPSTREAM.md", + "reviewedRef": "689395109cc962a27c369bdd6fa50d1e090eb319", + "reviewedAt": "2026-11-24", + "reviewedBy": "mashagua", + "upstreamEndorsed": false } }, "compatibility": { @@ -77,15 +93,25 @@ "requirements": [ { "kind": "runtime", - "value": "A user-configured Python environment and the dependencies declared by AI News Radar." + "value": "Python 3.11+ and the pinned packages in requirements.txt. The local package includes all required Python helpers and referenced reader assets; install dependencies in a separate environment." + }, + { + "kind": "runtime", + "value": "Use scripts/run_daily_brief.py with an absolute private output directory outside the installed skill. Historical data is intentionally excluded and generated on first run; do not write bytecode, logs or private configuration into the package." }, { "kind": "connection", - "value": "Access to the chosen public feeds. Optional mail adapters require separate credentials and explicit authorization; private message bodies must not be published or persisted as public feed content." + "value": "Normal generation needs authorized public-feed access; source availability and rate limits are external. Optional email/X/cookie/paid APIs require separate private host/vault configuration, explicit authorization and applicable service fees. No live/authenticated test is implied by fixture smoke results." + }, + { + "kind": "connection", + "value": "The optional bundled reader references the separately licensed GSAP 3.13.0 script on jsDelivr. Optional persona scoring can run rules-only with PERSONA_ENABLED=0; authenticated DeepSeek calls require separate explicit approval, private DEEPSEEK_API_KEY configuration and applicable fees. Neither is a prerequisite for the daily-brief JSON generator." } ] }, "spec": { - "kind": "skill" + "kind": "skill", + "riskLevel": "medium", + "skillType": "hybrid" } } diff --git a/skills/ai-news-radar/classic/assets/app.js b/skills/ai-news-radar/classic/assets/app.js new file mode 100644 index 0000000..195019f --- /dev/null +++ b/skills/ai-news-radar/classic/assets/app.js @@ -0,0 +1,3134 @@ +const state = { + itemsAi: [], + itemsAll: [], + itemsAllRaw: [], + creatorItemsAi: [], + creatorItemsAll: [], + creatorWindowDays: 7, + statsAi: [], + totalAi: 0, + totalRaw: 0, + totalAllMode: 0, + allDedup: true, + allDataLoaded: false, + allDataUrl: "data/latest-24h-all.json", + allDataPromise: null, + siteFilter: "", + authorFilter: "", + query: "", + mode: "ai", + waytoagiMode: "today", + waytoagiData: null, + sourceStatus: null, + generatedAt: null, + dailyBrief: null, + storiesMerged: null, + storiesDataUrl: "data/stories-merged.json", + activeSection: "hot", + boleView: "timeline", + boleExpanded: false, + listSort: "priority", + sourceTypeFilter: "", + signalLevelFilter: "", + siteGroupsExpanded: false, + xAuthorsExpanded: false, +}; + +// Keep both UI surfaces on the same snapshot. The query/local-storage contract +// mirrors the current mobile UI so switching views never silently falls back to +// another data directory. +function resolveDataBaseUrl() { + let fromQuery = ""; + try { + fromQuery = new URLSearchParams(window.location.search).get("data") || ""; + } catch { + fromQuery = ""; + } + if (fromQuery) { + const normalized = fromQuery.trim().replace(/\/+$/, ""); + try { localStorage.setItem("dataBaseUrl", normalized); } catch {} + return normalized; + } + try { + const stored = localStorage.getItem("dataBaseUrl") || ""; + return stored.trim().replace(/\/+$/, ""); + } catch { + return ""; + } +} + +state.dataBaseUrl = resolveDataBaseUrl(); + +function dataUrl(path) { + const base = state.dataBaseUrl; + if (!base) return path; + const file = String(path || "").split("/").pop(); + return `${base}/${file}`; +} + +const statsEl = document.getElementById("stats"); +const siteSelectEl = document.getElementById("siteSelect"); +const sitePillsEl = document.getElementById("sitePills"); +const newsListEl = document.getElementById("newsList"); +const updatedAtEl = document.getElementById("updatedAt"); +const sourceStatusPillEl = document.getElementById("sourceStatusPill"); +const stickySummaryTextEl = document.getElementById("stickySummaryText"); +const searchInputEl = document.getElementById("searchInput"); +const resultCountEl = document.getElementById("resultCount"); +const listTitleEl = document.getElementById("listTitle"); +const itemTpl = document.getElementById("itemTpl"); +const modeAiBtnEl = document.getElementById("modeAiBtn"); +const modeAllBtnEl = document.getElementById("modeAllBtn"); +const modeHintEl = document.getElementById("modeHint"); +const allDedupeWrapEl = document.getElementById("allDedupeWrap"); +const allDedupeToggleEl = document.getElementById("allDedupeToggle"); +const allDedupeLabelEl = document.getElementById("allDedupeLabel"); +const advancedSummaryEl = document.getElementById("advancedSummary"); +const sourceHealthEl = document.getElementById("sourceHealth"); +const sourceHealthDetailsEl = document.getElementById("sourceHealthDetails"); +const sourceStatusTableEl = document.getElementById("sourceStatusTable"); +const sectionSelectEl = document.getElementById("sectionSelect"); +const sourceTypeSelectEl = document.getElementById("sourceTypeSelect"); +const signalLevelSelectEl = document.getElementById("signalLevelSelect"); +const dataSourceIndicatorEl = document.getElementById("dataSourceIndicator"); +const dataSourceIndicatorTextEl = document.getElementById("dataSourceIndicatorText"); +const dataSourceResetBtnEl = document.getElementById("dataSourceResetBtn"); + +const waytoagiWrapEl = document.querySelector(".waytoagi-wrap"); +const waytoagiUpdatedAtEl = document.getElementById("waytoagiUpdatedAt"); +const waytoagiMetaEl = document.getElementById("waytoagiMeta"); +const waytoagiListEl = document.getElementById("waytoagiList"); +const waytoagiTodayBtnEl = document.getElementById("waytoagiTodayBtn"); +const waytoagi7dBtnEl = document.getElementById("waytoagi7dBtn"); +const coverageStripEl = document.getElementById("coverageStrip"); +const bolePicksListEl = document.getElementById("bolePicksList"); +const bolePicksMetaEl = document.getElementById("bolePicksMeta"); +const bolePicksWrapEl = document.getElementById("bolePicksWrap"); +const boleViewToggleEl = document.getElementById("boleViewToggle"); +const boleHotBtnEl = document.getElementById("boleHotBtn"); +const boleTimelineBtnEl = document.getElementById("boleTimelineBtn"); +const sectionTabsEl = document.getElementById("sectionTabs"); +const sectionSummaryEl = document.getElementById("sectionSummary"); +const topStoriesTitleEl = document.getElementById("topStoriesTitle"); +const listSortToolsEl = document.getElementById("listSortTools"); + +const SOURCE_KINDS = { + official_ai: { label: "官方", tone: "official" }, + curated_media: { label: "精选媒体", tone: "aihub" }, + aihot: { label: "AI HOT", tone: "hot" }, + aibreakfast: { label: "日报", tone: "newsletter" }, + followbuilders: { label: "Builders/X", tone: "builders" }, + xapi: { label: "X API", tone: "builders" }, + socialdata_x: { label: "X 搜索", tone: "builders" }, + tikhub_douyin: { label: "抖音", tone: "creator" }, + tikhub_xiaohongshu: { label: "小红书", tone: "creator" }, + techurls: { label: "聚合", tone: "aggregate" }, + buzzing: { label: "聚合", tone: "aggregate" }, + iris: { label: "聚合", tone: "aggregate" }, + bestblogs: { label: "博客", tone: "blogs" }, + tophub: { label: "聚合", tone: "aggregate" }, + zeli: { label: "聚合", tone: "aggregate" }, + hackernews: { label: "HN", tone: "aggregate" }, + aihubtoday: { label: "AI站点", tone: "aihub" }, + aibase: { label: "AI站点", tone: "aihub" }, + waytoagi: { label: "社区", tone: "builders" }, + newsnow: { label: "聚合", tone: "aggregate" }, + opmlrss: { label: "OPML", tone: "newsletter" }, +}; + +const SECTION_DEFS = [ + { id: "hot", label: "热点", short: "热点", description: "跨来源聚合后的优先阅读列表" }, + { id: "models", label: "模型", short: "模型", description: "模型发布、能力升级、评测与开源权重" }, + { id: "products", label: "产品", short: "产品", description: "AI 应用、Agent、生成工具和用户产品更新" }, + { id: "devtools", label: "开发者", short: "开发者", description: "编程工具、API、开源项目、推理与工程实践" }, + { id: "hn", label: "HN热议", short: "HN", description: "Hacker News 过去 24 小时的 AI 关键词讨论与高互动 story" }, + { id: "industry", label: "行业", short: "行业", description: "公司战略、融资收购、监管、芯片与产业变化" }, + { id: "research", label: "研究", short: "研究", description: "论文、基准、方法、数据集与研究团队动态" }, + { id: "creator", label: "自媒体", short: "自媒体", description: "一周内互动热度优先,24 小时新内容额外加分" }, + { id: "community", label: "社区", short: "社区", description: "WaytoAGI、中文社区、AIbase、公众号和 Builders/X 信号" }, +]; + +const SECTION_BY_ID = Object.fromEntries(SECTION_DEFS.map((section) => [section.id, section])); + +const LIST_SORT_DEFS = [ + { id: "priority", label: "综合" }, + { id: "latest", label: "最新" }, + { id: "ai", label: "高分" }, + { id: "source", label: "来源" }, +]; + +function fmtNumber(n) { + return new Intl.NumberFormat("zh-CN").format(n || 0); +} + +// The classic and mobile surfaces must apply the same last-mile safety gate. +// This protects the public page if an upstream source bypasses pipeline filters. +const UNSAFE_HARD_PATTERNS = [ + /\bcreampie\b/i, + /\bblowjob\b/i, + /\bsuck (?:your|my) (?:dick|cock)\b/i, + /中出|婊子|吸你的鸡鸡|操虚拟女友/i, +]; + +const UNSAFE_PROMO_PATTERNS = [ + /\b(?:nsfw|nudes?|porn(?:ography)?)\b/i, + /\buncensored pictures?\b/i, + /\bvirtual girlfriends?\b/i, + /\bknock her up\b/i, + /未经审查的图片|虚拟女友|色情内容|成人内容/i, +]; + +function contentSafetyText(record) { + return [ + record?.title, + record?.title_zh, + record?.title_en, + record?.title_original, + record?.source, + record?.source_name, + ].filter(Boolean).join(" "); +} + +function isUnsafeContent(record) { + const text = contentSafetyText(record); + if (!text) return false; + if (UNSAFE_HARD_PATTERNS.some((pattern) => pattern.test(text))) return true; + return UNSAFE_PROMO_PATTERNS.filter((pattern) => pattern.test(text)).length >= 2; +} + +function safeItems(items) { + return (Array.isArray(items) ? items : []).filter((item) => !isUnsafeContent(item)); +} + +function isUnsafeStory(story) { + const refs = [ + story, + story?.primary_item, + ...(Array.isArray(story?.sources) ? story.sources : []), + ...(Array.isArray(story?.items) ? story.items : []), + ].filter(Boolean); + return refs.some((ref) => isUnsafeContent(ref)); +} + +function fmtTime(iso) { + if (!iso) return "时间未知"; + const d = new Date(iso); + if (Number.isNaN(d.getTime())) return "时间未知"; + return new Intl.DateTimeFormat("zh-CN", { + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + }).format(d); +} + +function fmtDate(iso) { + if (!iso) return "未知日期"; + const d = new Date(`${iso}T00:00:00`); + if (Number.isNaN(d.getTime())) return iso; + return new Intl.DateTimeFormat("zh-CN", { + month: "2-digit", + day: "2-digit", + }).format(d); +} + +function setStats() { + statsEl.innerHTML = ""; + const items = safeItems(state.itemsAi); + const highCount = items.filter((item) => isHighPriorityItem(item)).length; + const curatedCount = briefStories().length || Math.min(20, mergedStories().filter((story) => storyScore(story) >= 75).length); + const status = state.sourceStatus; + const totalSites = Array.isArray(status?.sites) ? status.sites.length : 0; + const okSites = Number(status?.successful_sites || 0); + const health = totalSites ? `${fmtNumber(okSites)}/${fmtNumber(totalSites)}正常` : "加载中"; + const cards = [ + ["AI", `${fmtNumber(items.length)}条`], + ["高优", `${fmtNumber(highCount)}条`], + ["精选", `${fmtNumber(curatedCount)}条`], + ["源", health], + ]; + statsEl.setAttribute( + "aria-label", + `过去 24 小时:AI 信号 ${fmtNumber(items.length)} 条,高优先级 ${fmtNumber(highCount)} 条,精选 ${fmtNumber(curatedCount)} 条,源状态 ${totalSites ? `${fmtNumber(okSites)}/${fmtNumber(totalSites)} 源正常` : "加载中"}`, + ); + + const prefix = document.createElement("div"); + prefix.className = "stat-prefix"; + prefix.textContent = "过去 24 小时:"; + statsEl.appendChild(prefix); + + cards.forEach(([k, v]) => { + const node = document.createElement("div"); + node.className = "stat"; + node.innerHTML = `
${k}
${v}
`; + statsEl.appendChild(node); + }); + renderStickySummary(); + renderSourceStatusPill(); +} + +function failedSourceCount(status = state.sourceStatus) { + const failedSites = Array.isArray(status?.failed_sites) ? status.failed_sites.length : 0; + const rss = status?.rss_opml || {}; + const failedFeeds = Array.isArray(rss.failed_feeds) ? rss.failed_feeds.length : 0; + return failedSites + failedFeeds; +} + +function renderSourceStatusPill(errorMessage = "") { + if (!sourceStatusPillEl) return; + const status = state.sourceStatus; + sourceStatusPillEl.className = "source-status-pill"; + if (!status) { + sourceStatusPillEl.textContent = errorMessage || "源状态加载中"; + if (errorMessage) sourceStatusPillEl.classList.add("bad"); + return; + } + const totalSites = Array.isArray(status.sites) ? status.sites.length : 0; + const okSites = Number(status.successful_sites || 0); + const failed = failedSourceCount(status); + sourceStatusPillEl.textContent = failed + ? `${fmtNumber(okSites)}/${fmtNumber(totalSites)} 源正常 · 失败 ${fmtNumber(failed)}` + : `${fmtNumber(okSites)}/${fmtNumber(totalSites)} 源正常`; + if (failed) sourceStatusPillEl.classList.add("warn"); +} + +function renderStickySummary() { + if (!stickySummaryTextEl) return; + const filteredCount = getFilteredItems().length; + const section = SECTION_BY_ID[state.activeSection] || SECTION_BY_ID.hot; + const query = state.query.trim(); + const site = state.siteFilter + ? (currentSiteStats().find((row) => row.site_id === state.siteFilter)?.site_name || state.siteFilter) + : ""; + const sourceType = sourceTypeSelectEl?.selectedOptions?.[0]?.textContent || ""; + const signalLevel = signalLevelSelectEl?.selectedOptions?.[0]?.textContent || ""; + const filters = [ + state.activeSection === "hot" ? "" : section.label, + site, + state.sourceTypeFilter ? sourceType : "", + state.signalLevelFilter ? signalLevel : "", + query ? `搜索“${query}”` : "", + ].filter(Boolean); + const mode = state.mode === "all" ? "全量" : "AI强相关"; + stickySummaryTextEl.textContent = `${fmtNumber(filteredCount)} 条 · ${mode}${filters.length ? ` · ${filters.join(" · ")}` : ""}`; +} + +function sourceKind(siteId) { + return SOURCE_KINDS[siteId] || { label: "来源", tone: "default" }; +} + +function sourceSignalTone(signal) { + const text = String(signal || "").toLowerCase(); + if (text.includes("官方") || text.includes("official")) return "official"; + if (text.includes("ai hot") || text.includes("精选")) return "hot"; + if (text.includes("自媒体") || text.includes("tikhub") || text.includes("douyin") || text.includes("xiaohongshu") || text.includes("抖音") || text.includes("小红书")) return "creator"; + if (text.includes("builders") || text.includes("github") || text.includes("x")) return "builders"; + if (text.includes("aihub") || text.includes("aibase") || text.includes("媒体")) return "aihub"; + if (text.includes("hn") || text.includes("hacker") || text.includes("聚合")) return "aggregate"; + if (text.includes("opml") || text.includes("日报")) return "newsletter"; + return "default"; +} + +function sourceChip(label, tone = "default", className = "source-chip") { + const chip = document.createElement("span"); + chip.className = `${className} kind-${tone}`.trim(); + const dot = document.createElement("span"); + dot.className = "source-dot"; + dot.setAttribute("aria-hidden", "true"); + const text = document.createElement("span"); + text.className = "source-chip-label"; + text.textContent = label || "来源"; + chip.append(dot, text); + return chip; +} + +function appendSourceChip(parent, label, tone = "default", className = "source-chip") { + parent.appendChild(sourceChip(label, tone, className)); +} + +function siteRows() { + return Array.isArray(state.sourceStatus?.sites) ? state.sourceStatus.sites : []; +} + +function siteRow(siteId) { + return siteRows().find((site) => site.site_id === siteId) || null; +} + +function aiSiteStat(siteId) { + const stats = Array.isArray(state.statsAi) && state.statsAi.length + ? state.statsAi + : computeSiteStats(state.itemsAi || []); + return stats.find((site) => site.site_id === siteId) || null; +} + +function siteAiPoolCount(siteId) { + return Number(aiSiteStat(siteId)?.count || 0); +} + +function siteRawPoolCount(siteId) { + const stat = aiSiteStat(siteId); + return Number(stat?.raw_count ?? stat?.count ?? 0); +} + +function sourcePoolMeta(aiCount, rawCount, fallback) { + if (rawCount && rawCount !== aiCount) return `AI强相关 · 原始 ${fmtNumber(rawCount)} 条`; + return fallback; +} + +function paidSourceLabel(status, poolCount, activeLabel, idleLabel) { + const connected = Boolean(status?.enabled); + const liveCount = Number(status?.item_count || 0); + const displayCount = liveCount || Number(poolCount || 0); + if (connected) { + if (displayCount) return `${activeLabel} ${fmtNumber(displayCount)}条`; + return `${activeLabel} ${status?.skipped ? "待窗口" : "已连接暂无匹配"}`; + } + if (displayCount) return `${activeLabel} ${fmtNumber(displayCount)}条`; + return idleLabel; +} + +function renderCoverageCard(label, value, meta, tone = "") { + const node = document.createElement("div"); + node.className = `coverage-card ${tone}`.trim(); + const labelEl = document.createElement("span"); + labelEl.className = "coverage-label"; + labelEl.textContent = label; + const valueEl = document.createElement("strong"); + valueEl.textContent = value; + const metaEl = document.createElement("span"); + metaEl.className = "coverage-meta"; + metaEl.textContent = meta; + node.append(labelEl, valueEl, metaEl); + return node; +} + +function renderCoverageStrip(errorMessage = "") { + if (!coverageStripEl) return; + coverageStripEl.innerHTML = ""; + + const rows = siteRows(); + const failedSites = Array.isArray(state.sourceStatus?.failed_sites) ? state.sourceStatus.failed_sites : []; + const rss = state.sourceStatus?.rss_opml || {}; + const agentmail = state.sourceStatus?.agentmail || {}; + const xApi = state.sourceStatus?.x_api || {}; + const socialdata = state.sourceStatus?.socialdata || {}; + const allCount = Number(state.sourceStatus?.items_before_topic_filter || state.totalAllMode || state.itemsAll.length || 0); + const coverageCount = Number(state.sourceStatus?.fetched_raw_items || state.totalRaw || allCount || 0); + const officialCount = Number(siteRow("official_ai")?.item_count || 0); + const newsletterCount = Number(siteRow("aibreakfast")?.item_count || 0); + const curatedMediaCount = Number(siteRow("curated_media")?.item_count || 0); + const buildersCount = Number(siteRow("followbuilders")?.item_count || 0); + const creatorCount = state.creatorItemsAi.length || (siteAiPoolCount("tikhub_douyin") + siteAiPoolCount("tikhub_xiaohongshu")); + const creatorRawCount = state.creatorItemsAll.length || (siteRawPoolCount("tikhub_douyin") + siteRawPoolCount("tikhub_xiaohongshu")); + const socialdataPoolCount = siteAiPoolCount("socialdata_x"); + const xApiPoolCount = siteAiPoolCount("xapi"); + const xPoolCount = socialdataPoolCount + xApiPoolCount; + const mailCount = Number(agentmail.item_count || 0); + const totalSites = rows.length; + const okSites = Number(state.sourceStatus?.successful_sites || 0); + const opmlValue = rss.enabled ? `${fmtNumber(rss.ok_feeds || 0)}/${fmtNumber(rss.effective_feed_total || 0)}` : "OPML"; + const opmlMeta = rss.enabled ? "RSS示例/自定义订阅已接入" : "可用OPML批量接入RSS"; + const socialdataLabel = paidSourceLabel(socialdata, socialdataPoolCount, "SocialData", ""); + const xApiLabel = paidSourceLabel(xApi, xApiPoolCount, "X API", ""); + const xSourceLabel = socialdataLabel || xApiLabel || "X待配置"; + const mailLabel = agentmail.enabled ? `Mail ${fmtNumber(mailCount)}` : "Mail待配置"; + const advancedValue = xPoolCount || mailCount + ? `${xPoolCount ? `X ${fmtNumber(xPoolCount)}` : "X"} / ${mailCount ? `Mail ${fmtNumber(mailCount)}` : "Mail"}` + : "X / Mail"; + const advancedMeta = socialdata.enabled || xApi.enabled || agentmail.enabled || xPoolCount + ? `额度保护 · ${xSourceLabel} / ${mailLabel}` + : "X API 与 AgentMail 默认关闭"; + + const cards = [ + ["源健康", totalSites ? `${fmtNumber(okSites)}/${fmtNumber(totalSites)}` : "加载中", failedSites.length ? `${fmtNumber(failedSites.length)} 个失败源` : (errorMessage || "内置源正常"), failedSites.length ? "warn" : "ok"], + ["今日覆盖池", `${fmtNumber(coverageCount)} 条`, allCount ? `全网抓取原始信号 · ${fmtNumber(allCount)} 条入池` : "全网抓取原始信号", "signal"], + ["AI强相关", `${fmtNumber(safeItems(state.itemsAi).length)} 条`, "24小时强相关信号", "signal"], + ["官方/日报源池", `${fmtNumber(officialCount + newsletterCount)} 条`, "官方节点 + AI Breakfast", "official"], + ["精选媒体源池", `${fmtNumber(curatedMediaCount)} 条`, "The Decoder / TC / Verge / MTP 等", "signal"], + ["Builders/X源池", `${fmtNumber(buildersCount)} 条`, "Follow Builders公开feed", "builders"], + ["自媒体源池", `${fmtNumber(creatorCount)} 条`, sourcePoolMeta(creatorCount, creatorRawCount, "TikHub · 抖音 + 小红书"), "creator"], + ["RSS/OPML扩展", opmlValue, opmlMeta, "private"], + ["高级源", advancedValue, advancedMeta, "private"], + ]; + + cards.forEach(([label, value, meta, tone]) => { + coverageStripEl.appendChild(renderCoverageCard(label, value, meta, tone)); + }); +} + +function renderAdvancedSummary() { + if (!advancedSummaryEl) return; + const status = state.sourceStatus; + const filteredCount = getFilteredItems().length; + if (!status) { + advancedSummaryEl.textContent = `${fmtNumber(filteredCount)} 条结果`; + return; + } + const sites = Array.isArray(status.sites) ? status.sites : []; + const totalSites = sites.length; + const okSites = Number(status.successful_sites || 0); + const failed = failedSourceCount(status); + advancedSummaryEl.textContent = `${fmtNumber(filteredCount)} 条结果 · ${fmtNumber(okSites)}/${fmtNumber(totalSites)} 源正常${failed ? ` · 失败 ${fmtNumber(failed)}` : ""}`; +} + +function computeSiteStats(items) { + const m = new Map(); + items.forEach((item) => { + if (!m.has(item.site_id)) { + m.set(item.site_id, { site_id: item.site_id, site_name: item.site_name, count: 0, raw_count: 0 }); + } + const row = m.get(item.site_id); + row.count += 1; + row.raw_count += 1; + }); + return Array.from(m.values()).sort((a, b) => b.count - a.count || a.site_name.localeCompare(b.site_name, "zh-CN")); +} + +function safeAiSiteStats() { + const visibleStats = computeSiteStats(safeItems(state.itemsAi)); + const visibleById = new Map(visibleStats.map((site) => [site.site_id, site])); + const baseStats = Array.isArray(state.statsAi) && state.statsAi.length ? state.statsAi : visibleStats; + return baseStats.map((site) => ({ + ...site, + count: Number(visibleById.get(site.site_id)?.count || 0), + })); +} + +function currentSiteStats() { + if (state.activeSection === "creator") { + return computeSiteStats(safeItems(state.mode === "all" ? state.creatorItemsAll : state.creatorItemsAi)); + } + if (state.mode === "ai") return safeAiSiteStats(); + return computeSiteStats(safeItems(state.allDedup ? state.itemsAll : state.itemsAllRaw)); +} + +function creatorHotScore(item) { + return normalizedPercent(item?.creator_hot_score); +} + +function highPriorityScore(item) { + if (itemSections(item).has("creator") && creatorHotScore(item)) return creatorHotScore(item); + return scorePercent(item); +} + +function isHighPriorityItem(item) { + return highPriorityScore(item) >= 75 || itemPriorityScore(item) >= 82 || item.site_id === "official_ai" || item.site_id === "aihot"; +} + +function isCuratedItem(item) { + return item.site_id === "official_ai" || item.site_id === "aihot" || item.source_tier === "official" || item.source_tier === "curated"; +} + +function itemSourceType(item) { + const siteId = item.site_id || ""; + const tier = item.source_tier || ""; + if (siteId === "official_ai" || tier === "official") return "official"; + if (siteId === "curated_media" || siteId === "aibreakfast" || siteId === "aihot") return "media"; + if (siteId === "opmlrss" || tier === "user_opml") return "rss"; + if (siteId === "waytoagi" || siteId === "followbuilders" || siteId === "hackernews" || siteId === "zeli" || siteId === "aibase") return "community"; + if (siteId === "tikhub_douyin" || siteId === "tikhub_xiaohongshu") return "creator"; + if (siteId === "socialdata_x" || siteId === "xapi" || siteId === "agentmail") return "advanced"; + return "aggregate"; +} + +function multiSourceEventKeys(items) { + const map = new Map(); + (items || []).forEach((item) => { + const key = eventKey(item); + if (!map.has(key)) map.set(key, new Set()); + map.get(key).add(sourceSignal(item)); + }); + return new Set(Array.from(map.entries()) + .filter(([, sources]) => sources.size > 1) + .map(([key]) => key)); +} + +function itemMatchesSignalLevel(item, multiSourceKeys = new Set()) { + if (!state.signalLevelFilter) return true; + if (state.signalLevelFilter === "high") return isHighPriorityItem(item); + if (state.signalLevelFilter === "curated") return isCuratedItem(item); + if (state.signalLevelFilter === "multi") return multiSourceKeys.has(eventKey(item)); + return true; +} + +function sectionStats(sectionId) { + const items = sectionItems(modeItems(), sectionId); + const highCount = items.filter((item) => isHighPriorityItem(item)).length; + const sourceSet = new Set(items.map((item) => item.source || item.site_name || item.site_id).filter(Boolean)); + return { items, count: items.length, highCount, sourceCount: sourceSet.size }; +} + +function renderSectionTabs() { + if (!sectionTabsEl) return; + sectionTabsEl.innerHTML = ""; + SECTION_DEFS.forEach((section) => { + const stats = sectionStats(section.id); + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = `section-tab ${state.activeSection === section.id ? "active" : ""}`; + btn.setAttribute("role", "tab"); + btn.setAttribute("aria-selected", state.activeSection === section.id ? "true" : "false"); + btn.dataset.section = section.id; + btn.innerHTML = `${section.label}${fmtNumber(stats.count)}`; + btn.addEventListener("click", () => { + state.activeSection = section.id; + state.boleExpanded = false; + renderSectionTabs(); + renderModeSwitch(); + renderSiteFilters(); + renderBolePicks(); + if (state.waytoagiData) renderWaytoagi(state.waytoagiData); + renderList(); + }); + sectionTabsEl.appendChild(btn); + }); + renderSectionFilterSelect(); +} + +function renderSectionFilterSelect() { + if (!sectionSelectEl) return; + if (!sectionSelectEl.options.length) { + SECTION_DEFS.forEach((section) => { + const option = document.createElement("option"); + option.value = section.id; + option.textContent = section.label; + sectionSelectEl.appendChild(option); + }); + } + sectionSelectEl.value = state.activeSection; +} + +function renderSectionSummary(filteredItems = null) { + if (!sectionSummaryEl) return; + const section = SECTION_BY_ID[state.activeSection] || SECTION_BY_ID.hot; + const items = filteredItems || getFilteredItems(); + const highCount = items.filter((item) => isHighPriorityItem(item)).length; + const sources = new Set(items.map((item) => item.source || item.site_name || item.site_id).filter(Boolean)); + const modeText = state.mode === "all" ? (state.allDedup ? "全量去重" : "全量原始") : "AI强相关"; + const windowText = state.activeSection === "creator" ? `过去 ${fmtNumber(state.creatorWindowDays)} 天 · 热度优先` : "过去 24 小时"; + sectionSummaryEl.textContent = `${windowText} · ${fmtNumber(items.length)} 条${section.id === "hot" ? "" : ` ${section.label}`}信号 · ${fmtNumber(highCount)} 条高优先级 · ${fmtNumber(sources.size)} 个来源 · ${modeText}`; + renderStickySummary(); +} + +function siteRatioText(siteStats) { + const count = Number(siteStats.count || 0); + const raw = Number(siteStats.raw_count ?? siteStats.count ?? 0); + if (!raw) { + const scanned = Number(siteRow(siteStats.site_id)?.item_count || 0); + if (!count && scanned) return `24h 0 · 已扫 ${fmtNumber(scanned)}`; + if (!count) return "已扫 0"; + return `${fmtNumber(count)} 条`; + } + if (raw === count) return `${fmtNumber(count)} 条`; + return `${fmtNumber(count)}/${fmtNumber(raw)} · ${Math.round((count / raw) * 100)}%AI`; +} + +function renderSiteFilters() { + const stats = currentSiteStats(); + + siteSelectEl.innerHTML = ''; + stats.forEach((s) => { + const opt = document.createElement("option"); + opt.value = s.site_id; + opt.textContent = `${s.site_name} (${siteRatioText(s)})`; + siteSelectEl.appendChild(opt); + }); + siteSelectEl.value = state.siteFilter; + + sitePillsEl.innerHTML = ""; + const allPill = document.createElement("button"); + allPill.className = `pill ${state.siteFilter === "" ? "active" : ""}`; + allPill.textContent = "全部"; + allPill.onclick = () => { + state.siteFilter = ""; + renderSiteFilters(); + renderBolePicks(); + renderList(); + }; + sitePillsEl.appendChild(allPill); + + if (state.authorFilter) { + const authorPill = document.createElement("button"); + authorPill.type = "button"; + authorPill.className = "pill active author-filter-pill"; + authorPill.textContent = `X 博主 ${state.authorFilter} ×`; + authorPill.title = "清除博主筛选"; + authorPill.onclick = () => { + state.authorFilter = ""; + state.siteFilter = ""; + state.siteGroupsExpanded = false; + renderSiteFilters(); + renderBolePicks(); + renderList(); + }; + sitePillsEl.appendChild(authorPill); + } + + stats.forEach((s) => { + const btn = document.createElement("button"); + btn.className = `pill ${state.siteFilter === s.site_id ? "active" : ""}`; + btn.textContent = `${s.site_name} ${siteRatioText(s)}`; + btn.onclick = () => { + state.siteFilter = s.site_id; + if (s.site_id !== "socialdata_x") state.authorFilter = ""; + renderSiteFilters(); + renderBolePicks(); + renderList(); + }; + sitePillsEl.appendChild(btn); + }); +} + +function renderModeSwitch() { + modeAiBtnEl.classList.toggle("active", state.mode === "ai"); + modeAllBtnEl.classList.toggle("active", state.mode === "all"); + if (allDedupeWrapEl) allDedupeWrapEl.classList.toggle("show", state.mode === "all"); + if (allDedupeToggleEl) allDedupeToggleEl.checked = state.allDedup; + if (allDedupeLabelEl) allDedupeLabelEl.textContent = state.allDedup ? "去重开" : "去重关"; + if (state.mode === "ai") { + modeHintEl.textContent = `AI强相关 · ${fmtNumber(safeItems(state.itemsAi).length)} 条`; + } else { + const allCount = effectiveAllItems().length; + modeHintEl.textContent = `全量 · ${state.allDedup ? "去重开" : "去重关"} · ${fmtNumber(allCount)} 条`; + } + if (listTitleEl) { + listTitleEl.textContent = listTitleText(); + } + renderAdvancedSummary(); + renderSectionSummary(); +} + +function listTitleText() { + const section = SECTION_BY_ID[state.activeSection] || SECTION_BY_ID.hot; + const pool = state.mode === "all" + ? (state.allDedup ? "情报流 · 全量去重" : "情报流 · 全量原始") + : "情报流"; + return state.activeSection === "hot" ? pool : `${section.label} · ${pool}`; +} + +function renderListSortTools() { + if (!listSortToolsEl) return; + const validSort = LIST_SORT_DEFS.some((item) => item.id === state.listSort); + if (!validSort) state.listSort = "priority"; + listSortToolsEl.querySelectorAll("[data-sort]").forEach((button) => { + const active = button.dataset.sort === state.listSort; + button.classList.toggle("active", active); + button.setAttribute("aria-pressed", active ? "true" : "false"); + }); +} + +function itemSourceSortKey(item) { + return [ + sourceSignal(item), + item.site_name || item.site_id || "", + item.source || "", + ].join(" ").trim() || "来源"; +} + +function sortItemsForList(items) { + const sorted = [...items]; + if (state.listSort === "latest") { + return sorted.sort((a, b) => timelineMs(b) - timelineMs(a) || itemPriorityScore(b) - itemPriorityScore(a)); + } + if (state.listSort === "ai") { + return sorted.sort((a, b) => scorePercent(b) - scorePercent(a) || itemPriorityScore(b) - itemPriorityScore(a) || timelineMs(b) - timelineMs(a)); + } + if (state.listSort === "source") { + const counts = new Map(); + sorted.forEach((item) => { + const key = itemSourceSortKey(item); + counts.set(key, (counts.get(key) || 0) + 1); + }); + return sorted.sort((a, b) => { + const aKey = itemSourceSortKey(a); + const bKey = itemSourceSortKey(b); + const byCount = (counts.get(bKey) || 0) - (counts.get(aKey) || 0); + if (byCount !== 0) return byCount; + const bySource = aKey.localeCompare(bKey, "zh-CN"); + if (bySource !== 0) return bySource; + return itemPriorityScore(b) - itemPriorityScore(a) || timelineMs(b) - timelineMs(a); + }); + } + return sorted.sort((a, b) => itemPriorityScore(b) - itemPriorityScore(a) || timelineMs(b) - timelineMs(a)); +} + +function effectiveAllItems() { + return safeItems(state.allDedup ? state.itemsAll : state.itemsAllRaw); +} + +function modeItems() { + return state.mode === "all" ? effectiveAllItems() : safeItems(state.itemsAi); +} + +function sectionItems(items = modeItems(), sectionId = state.activeSection) { + if (sectionId === "creator") { + const creatorSource = state.mode === "all" ? state.creatorItemsAll : state.creatorItemsAi; + return safeItems(creatorSource).sort((a, b) => creatorHotScore(b) - creatorHotScore(a) || timelineMs(b) - timelineMs(a)); + } + const source = Array.isArray(items) ? items : []; + if (sectionId === "hot") { + return [...source].sort((a, b) => itemPriorityScore(b) - itemPriorityScore(a) || timelineMs(b) - timelineMs(a)); + } + return source.filter((item) => itemMatchesSection(item, sectionId)); +} + +function getFilteredItems() { + const q = state.query.trim().toLowerCase(); + const preliminary = sectionItems().filter((item) => { + if (state.siteFilter && item.site_id !== state.siteFilter) return false; + if (state.authorFilter && (item.site_id !== "socialdata_x" || item.source !== state.authorFilter)) return false; + if (state.sourceTypeFilter && itemSourceType(item) !== state.sourceTypeFilter) return false; + if (!q) return true; + const hay = `${item.title || ""} ${item.title_zh || ""} ${item.title_en || ""} ${item.site_name || ""} ${item.source || ""}`.toLowerCase(); + return hay.includes(q); + }); + const multiKeys = multiSourceEventKeys(preliminary); + return preliminary.filter((item) => itemMatchesSignalLevel(item, multiKeys)); +} + +function itemTitleText(item) { + return (item.title_zh || item.title || item.title_en || "未命名更新").trim(); +} + +function scorePercent(item) { + const score = Number(item.ai_score ?? item.score ?? 0); + if (!Number.isFinite(score) || score <= 0) return 0; + return Math.round(score <= 1 ? score * 100 : score); +} + +function normalizedPercent(value) { + const score = Number(value); + if (!Number.isFinite(score) || score <= 0) return 0; + return Math.max(0, Math.min(100, Math.round(score <= 1 ? score * 100 : score))); +} + +function scoreTone(score) { + if (score >= 90) return "hot"; + if (score >= 75) return "strong"; + return "watch"; +} + +function itemLabelTone(item) { + const label = item.ai_label || ""; + if (item.site_id === "official_ai") return "official"; + if (item.site_id === "aihot" || label === "curated_hotlist") return "hot"; + if (itemSections(item).has("creator")) return "creator"; + if (label === "model_release") return "models"; + if (label === "developer_tool" || label === "developer_tooling" || label === "infrastructure" || label === "infra_compute") return "devtools"; + if (label === "research_paper") return "research"; + if (label === "industry_business") return "industry"; + if (label === "ai_product_update" || label === "agent_workflow" || label === "robotics") return "products"; + if (itemSections(item).has("community")) return "community"; + return "default"; +} + +function itemTagTone(label) { + const text = String(label || ""); + if (text.includes("多源")) return "strong"; + if (text.includes("官方")) return "official"; + if (text.includes("精选") || text.includes("热点")) return "hot"; + if (text.includes("HN")) return "aggregate"; + if (text.includes("模型")) return "models"; + if (text.includes("开发")) return "devtools"; + if (text.includes("研究")) return "research"; + if (text.includes("自媒体")) return "creator"; + if (text.includes("社区")) return "community"; + if (text.includes("产品")) return "products"; + if (text.includes("行业")) return "industry"; + return "default"; +} + +function itemTagChip(label) { + const tag = document.createElement("span"); + tag.className = `signal-tag tone-${itemTagTone(label)}`; + tag.textContent = label; + return tag; +} + +function setSourceBadge(el, label, tone = "default", title = "") { + el.className = `source source-chip kind-${tone}`; + el.innerHTML = ""; + if (title) el.title = title; + const dot = document.createElement("span"); + dot.className = "source-dot"; + dot.setAttribute("aria-hidden", "true"); + const text = document.createElement("span"); + text.className = "source-chip-label"; + text.textContent = label || "来源"; + el.append(dot, text); +} + +function sourceTierPercent(item) { + if (item.site_id === "official_ai") return 100; + if (item.site_id === "aihot") return 90; + const rank = Number(item.source_tier_rank); + if (!Number.isFinite(rank)) return 38; + return Math.max(28, Math.min(86, 86 - rank * 9)); +} + +function editorialPercent(item) { + const aihotScore = normalizedPercent(item.aihot_score); + if (aihotScore) return aihotScore; + if (item.site_id === "official_ai") return 90; + if (item.site_id === "aihot") return 78; + const internal = scorePercent(item); + return internal ? Math.max(45, Math.round(internal * 0.72)) : 36; +} + +function freshnessPercent(item, halfLifeHours = 48) { + const ageMs = Date.now() - timelineMs(item); + if (!Number.isFinite(ageMs) || ageMs < 0) return 100; + const ageHours = ageMs / 3600000; + return Math.max(0, Math.min(100, Math.round(100 * Math.pow(0.5, ageHours / halfLifeHours)))); +} + +function itemPriorityScore(item) { + const creatorScore = creatorHotScore(item); + if (creatorScore && itemSections(item).has("creator")) return creatorScore; + const internal = scorePercent(item); + const editorial = editorialPercent(item); + const source = sourceTierPercent(item); + const freshness = freshnessPercent(item); + const signal = Array.isArray(item.ai_signals) ? Math.min(100, item.ai_signals.length * 18) : 0; + return Math.round((editorial * 0.3) + (source * 0.22) + (internal * 0.2) + (freshness * 0.18) + (signal * 0.1)); +} + +function labelText(item) { + const labels = { + ai_general: "AI信号", + model_release: "模型发布", + agent_workflow: "Agent工作流", + ai_product_update: "产品更新", + developer_tooling: "开发工具", + developer_tool: "开发工具", + infrastructure: "基础设施", + infra_compute: "基础设施", + industry_business: "行业动态", + research_paper: "研究论文", + robotics: "机器人", + curated_hotlist: "热点", + ai_tech: "技术趋势", + }; + return labels[item.ai_label] || item.ai_label || "精选信号"; +} + +function itemHaystack(item) { + return [ + item.title, + item.title_zh, + item.title_en, + item.title_original, + item.source, + item.site_name, + item.site_id, + item.ai_label, + ...(Array.isArray(item.ai_signals) ? item.ai_signals : []), + ].filter(Boolean).join(" ").toLowerCase(); +} + +function matchesAny(text, patterns) { + return patterns.some((pattern) => pattern.test(text)); +} + +function itemSections(item) { + const hay = itemHaystack(item); + const contentHay = [ + item.title, + item.title_zh, + item.title_en, + item.title_original, + item.source, + item.site_name, + item.site_id, + ...(Array.isArray(item.ai_signals) ? item.ai_signals : []), + ].filter(Boolean).join(" ").toLowerCase(); + const sections = new Set(); + const label = item.ai_label || ""; + const source = `${item.source || ""} ${item.site_name || ""}`.toLowerCase(); + const hasExplicitModelTerm = matchesAny(contentHay, [ + /gpt[-\s]?\d|claude|gemini|grok|llama|qwen|deepseek|mistral|kimi\s?k\d|glm|gemma|模型|model|weights|权重|多模态|视频生成|diffusion|sora|seedance|llm|大模型/, + ]); + const looksLikeToolOrProduct = matchesAny(hay, [ + /skill|copilot|codex|cli|api|sdk|dashboard|workflow|tool|工具|助手|应用|插件|工作流|支付宝|浏览器|搜索/, + ]); + + if ( + hasExplicitModelTerm || + (label === "model_release" && !looksLikeToolOrProduct) + ) sections.add("models"); + + if ( + label === "ai_product_update" || + label === "agent_workflow" || + label === "robotics" || + matchesAny(hay, [ + /app|product|agent|workflow|siri|copilot|chatgpt|perplexity|runway|suno|支付宝|产品|应用|智能体|机器人|浏览器|搜索|助手|生成工具|办公|教育/, + ]) + ) sections.add("products"); + + if ( + label === "developer_tool" || + label === "developer_tooling" || + label === "infra_compute" || + matchesAny(hay, [ + /github|cursor|codex|copilot|openrouter|api|sdk|mcp|cli|framework|inference|推理|开发者|开源|代码|编程|算力|芯片|nvidia|cloud|部署|benchmarking|token/, + ]) + ) sections.add("devtools"); + + if ( + item.site_id === "hackernews" || + item.site_id === "zeli" || + source.includes("hacker news") || + source.includes("hackernews") || + source.includes("hn algolia") + ) sections.add("hn"); + + if ( + label === "industry_business" || + matchesAny(hay, [ + /funding|raised|ipo|acquire|acquisition|lawsuit|regulation|policy|white house|pentagon|nvidia|salesforce|meta|microsoft|融资|收购|上市|监管|政策|裁员|估值|债券|芯片|公司|行业|政府|五角大楼|白宫/, + ]) + ) sections.add("industry"); + + if ( + label === "research_paper" || + matchesAny(hay, [ + /paper|arxiv|research|benchmark|eval|dataset|lmsys|rdi|berkeley|huggingface daily papers|论文|研究|基准|评测|数据集|训练|k-means|speculative decoding/, + ]) + ) sections.add("research"); + + if ( + item.site_id === "tikhub_douyin" || + item.site_id === "tikhub_xiaohongshu" || + source.includes("douyin") || + source.includes("xiaohongshu") || + source.includes("小红书") || + source.includes("抖音") + ) sections.add("creator"); + + if ( + item.site_id === "waytoagi" || + item.site_id === "followbuilders" || + item.site_id === "aibase" || + source.includes("it之家") || + source.includes("36氪") || + source.includes("掘金") || + source.includes("readhub") || + source.includes("aibase") || + source.includes("公众号") || + source.includes("宝玉") || + source.includes("小互") || + source.includes("ayi") || + matchesAny(hay, [ + /waytoagi|社区|公众号|阿里|通义|千问|智谱|kimi|月之暗面|minimax|字节|火山|百度|腾讯|华为|蚂蚁|讯飞|国内|中文|开源中国|少数派|虎嗅/, + ]) + ) sections.add("community"); + + if (!sections.size) sections.add("industry"); + return sections; +} + +function itemMatchesSection(item, sectionId) { + return sectionId === "hot" || itemSections(item).has(sectionId); +} + +function sectionBadgeLabel(sectionId) { + return SECTION_BY_ID[sectionId]?.short || "栏目"; +} + +function reasonText(item) { + const creatorScore = creatorHotScore(item); + if (creatorScore && itemSections(item).has("creator")) { + const metrics = item.creator_metrics || {}; + const parts = [ + `赞 ${fmtNumber(metrics.likes)}`, + `藏 ${fmtNumber(metrics.collects)}`, + `评 ${fmtNumber(metrics.comments)}`, + `转 ${fmtNumber(metrics.shares)}`, + ]; + if (Number(item.creator_freshness_bonus || 0) > 0) parts.push("24h 加分"); + return `一周互动:${parts.join(" · ")}`; + } + const signals = Array.isArray(item.ai_signals) ? item.ai_signals.filter(Boolean).slice(0, 3) : []; + if (signals.length) return `命中方向:${signals.join(" / ")}`; + if (item.ai_relevance_reason) return String(item.ai_relevance_reason).replaceAll("_", " "); + return "来源与标题信号通过筛选"; +} + +function timelineIso(item) { + const published = item.published_at || ""; + const seen = item.first_seen_at || ""; + const generated = state.generatedAt || ""; + if (published && generated) { + const publishedMs = new Date(published).getTime(); + const generatedMs = new Date(generated).getTime(); + if (Number.isFinite(publishedMs) && Number.isFinite(generatedMs) && publishedMs > generatedMs + 10 * 60 * 1000) { + return seen || published; + } + } + return published || seen; +} + +function timelineMs(item) { + const d = new Date(timelineIso(item)); + return Number.isNaN(d.getTime()) ? 0 : d.getTime(); +} + +function normalizedEventText(text) { + return String(text || "") + .toLowerCase() + .replace(/https?:\/\/\S+/g, "") + .replace(/[\s\u3000]+/g, "") + .replace(/[,。、“”‘’::;;!!??()()\[\]【】《》<>·.,/\\|_-]/g, ""); +} + +function eventKey(item) { + const raw = itemTitleText(item); + const bracket = raw.match(/《([^》]{4,40})》/); + if (bracket) return `book:${normalizedEventText(bracket[1]).slice(0, 36)}`; + + const normalized = normalizedEventText(raw); + const model = normalized.match(/(bitcpmcann|deepseekv\d+(?:pro)?|grokv\d+(?:medium)?|gemini\d+(?:\.\d+)?(?:flash|pro)?|gpt\d+(?:\.\d+)?|llama\d+)/); + if (model) return `entity:${model[1]}`; + + return `title:${normalized.slice(0, 34)}`; +} + +function itemIdentityKeys(item) { + const keys = new Set(); + if (!item) return keys; + const url = item.url || item.primary_url; + if (url) keys.add(`url:${url}`); + if (item.id) keys.add(`id:${item.id}`); + const title = item.title_zh || item.title || item.title_en || item.title_original; + if (title) { + keys.add(`event:${eventKey({ ...item, title, title_zh: item.title_zh || title })}`); + keys.add(`title:${normalizedEventText(title).slice(0, 34)}`); + } + return keys; +} + +function storyIdentityKeys(story) { + const keys = new Set(); + if (!story) return keys; + const refs = [ + { id: story.story_id, title: story.title, url: story.primary_url || story.url }, + story.primary_item, + ...(Array.isArray(story.sources) ? story.sources : []), + ...(Array.isArray(story.items) ? story.items : []), + ].filter(Boolean); + refs.forEach((ref) => { + itemIdentityKeys(ref).forEach((key) => keys.add(key)); + }); + return keys; +} + +function headlineRowIdentityKeys(row) { + const keys = new Set(); + if (!row) return keys; + const refs = [ + row.item, + ...(Array.isArray(row.rows) ? row.rows.map((entry) => entry.item).filter(Boolean) : []), + ].filter(Boolean); + refs.forEach((ref) => { + itemIdentityKeys(ref).forEach((key) => keys.add(key)); + }); + return keys; +} + +function excludedStoryKeySet(rows) { + const keys = new Set(); + rows.forEach((row) => { + headlineRowIdentityKeys(row).forEach((key) => keys.add(key)); + }); + return keys; +} + +function storyHasAnyKey(story, keys) { + if (!keys || !keys.size) return false; + for (const key of storyIdentityKeys(story)) { + if (keys.has(key)) return true; + } + return false; +} + +function sourceSignal(item) { + const site = item.site_name || ""; + const source = item.source || ""; + const hay = `${site} ${source}`.toLowerCase(); + if (site === "AI HOT") return "AI HOT精选"; + if (hay.includes("hackernews") || hay.includes("hacker news")) return "HN热议"; + if (source.includes("GitHub · Trending Today") || hay.includes("github")) return "GitHub趋势"; + if (site === "Official AI Updates") return "官方更新"; + if (site === "Follow Builders") return "Builders"; + if (site === "TikHub Douyin" || hay.includes("tikhub douyin")) return "抖音自媒体"; + if (site === "TikHub Xiaohongshu" || hay.includes("tikhub xiaohongshu")) return "小红书自媒体"; + if (site === "AIbase") return "AIbase"; + if (site === "OPML RSS") return "OPML"; + return site || "来源"; +} + +function sourcePriority(item) { + const signal = sourceSignal(item); + if (signal === "官方更新") return 100; + if (signal === "AI HOT精选") return 90; + if (signal === "AIbase") return 82; + if (signal === "Builders") return 74; + if (signal === "抖音自媒体" || signal === "小红书自媒体") return 70; + if (signal === "OPML") return 68; + if (signal === "HN热议" || signal === "GitHub趋势") return 62; + return 50; +} + +function clusterBoleEvents(rows) { + const clusters = new Map(); + rows.forEach((row) => { + const key = eventKey(row.item); + if (!clusters.has(key)) clusters.set(key, { key, rows: [], signals: new Set(), score: 0, primary: row }); + const cluster = clusters.get(key); + cluster.rows.push(row); + cluster.signals.add(sourceSignal(row.item)); + const currentPrimary = cluster.primary; + const betterPrimary = sourcePriority(row.item) - sourcePriority(currentPrimary.item) + || row.score - currentPrimary.score + || timelineMs(row.item) - timelineMs(currentPrimary.item); + if (betterPrimary > 0) cluster.primary = row; + }); + return Array.from(clusters.values()).map((cluster) => { + const signals = Array.from(cluster.signals); + const maxScore = Math.max(...cluster.rows.map((row) => row.score)); + const sourceBonus = Math.min(12, Math.max(0, signals.length - 1) * 6); + const candidateBonus = signals.some((s) => s === "AI HOT精选") ? 8 + : signals.some((s) => s === "HN热议" || s === "GitHub趋势") ? 6 + : signals.some((s) => s === "官方更新") ? 5 + : 0; + return { + item: cluster.primary.item, + index: cluster.primary.index, + rows: cluster.rows, + sourceSignals: signals, + sourceCount: signals.length, + mergedCount: cluster.rows.length, + score: Math.min(100, Math.round(maxScore + sourceBonus + candidateBonus)), + }; + }); +} + +function storyTimeMs(story, key) { + const iso = story && story[key]; + if (!iso) return 0; + const d = new Date(iso); + return Number.isNaN(d.getTime()) ? 0 : d.getTime(); +} + +function storyScore(story) { + const raw = (story && (story.importance_score ?? story.score ?? story.importance)) || 0; + const score = Number(raw); + if (!Number.isFinite(score) || score <= 0) return 0; + return Math.round(score <= 1 ? score * 100 : score); +} + +function storyImportanceTone(label) { + if (!label) return "watch"; + if (label.includes("重大")) return "hot"; + if (label.includes("官方")) return "official"; + if (label.includes("多源")) return "strong"; + if (label.includes("行业")) return "watch"; + return "watch"; +} + +function storyPrimaryTitleText(story) { + const primary = (story && story.primary_item) || {}; + const bilingual = String(primary.title || (story && story.title) || "").trim(); + if (bilingual.includes(" / ")) { + const [zh, en] = bilingual.split(" / "); + return (zh || en || bilingual).trim(); + } + return bilingual || "未命名更新"; +} + +function storyPrimaryEnText(story) { + const primary = (story && story.primary_item) || {}; + const bilingual = String(primary.title || (story && story.title) || "").trim(); + if (bilingual.includes(" / ")) { + const [, en] = bilingual.split(" / "); + return (en || "").trim(); + } + return ""; +} + +function storySourceCount(story) { + const sources = Array.isArray(story && story.sources) ? story.sources : []; + const explicit = Number(story && story.duplicate_count); + if (Number.isFinite(explicit) && explicit > 0) return explicit; + return Math.max(1, sources.length); +} + +function storyDurationLabel(earliest, latest) { + if (!earliest || !latest || earliest === latest) return ""; + const start = new Date(earliest).getTime(); + const end = new Date(latest).getTime(); + if (!Number.isFinite(start) || !Number.isFinite(end)) return ""; + const minutes = Math.round(Math.abs(end - start) / 60000); + if (minutes < 20) return "短时集中"; + if (minutes < 60) return `发酵 ${minutes} 分钟`; + const hours = Math.floor(minutes / 60); + const rest = minutes % 60; + return rest ? `发酵 ${hours}小时${rest}分` : `发酵 ${hours}小时`; +} + +function formatStoryTime(story) { + const earliest = story.earliest_at; + const latest = story.latest_at; + if (latest && earliest && latest !== earliest) { + return { latest, rangeLabel: storyDurationLabel(earliest, latest) }; + } + return { latest: latest || earliest, rangeLabel: "" }; +} + +function pickBoleItems(items) { + const ranked = [...items] + .map((item, index) => ({ item, index, score: scorePercent(item) })) + .filter((row) => row.score > 0) + .sort((a, b) => { + const byScore = b.score - a.score; + if (byScore !== 0) return byScore; + return timelineMs(b.item) - timelineMs(a.item) || a.index - b.index; + }); + + const sorted = clusterBoleEvents(ranked).sort((a, b) => { + const byMultiSource = b.sourceCount - a.sourceCount; + const byScore = b.score - a.score; + return byMultiSource || byScore || timelineMs(b.item) - timelineMs(a.item) || a.index - b.index; + }); + + const picked = []; + const addPick = (cluster) => { + if (cluster && !picked.includes(cluster) && picked.length < 8) picked.push(cluster); + }; + ["AI HOT精选", "HN热议", "GitHub趋势"].forEach((signal) => { + addPick(sorted.find((cluster) => cluster.sourceSignals.includes(signal))); + }); + sorted.forEach(addPick); + return picked; +} + +function boleReasonText(row) { + const signals = row.sourceSignals || []; + const sourceText = signals.length ? `来源命中:${signals.join(" / ")}` : "来源命中:单源"; + const mergeText = row.mergedCount > 1 ? `合并${row.mergedCount}条同事件` : "单条事件"; + return `${sourceText} · ${mergeText} · ${reasonText(row.item)}`; +} + +function buildBoleLead(row) { + const { item, score } = row; + const lead = document.createElement("a"); + lead.className = "bole-lead-card"; + lead.href = item.url || "#"; + lead.target = "_blank"; + lead.rel = "noopener noreferrer"; + + const top = document.createElement("div"); + top.className = "bole-lead-top"; + const kicker = document.createElement("span"); + kicker.className = "bole-kicker"; + kicker.textContent = `${labelText(item)} · ${fmtTime(timelineIso(item))}`; + const scoreEl = document.createElement("strong"); + scoreEl.className = `bole-score-orb ${scoreTone(score)}`; + scoreEl.innerHTML = `${score}分`; + top.append(kicker, scoreEl); + + const title = document.createElement("div"); + title.className = "bole-lead-title"; + title.textContent = itemTitleText(item); + + const reason = document.createElement("div"); + reason.className = "bole-lead-reason"; + reason.textContent = reasonText(item); + + const foot = document.createElement("div"); + foot.className = "bole-lead-foot"; + foot.innerHTML = `${item.site_name || "来源"}${item.source || "未分区"}`; + + lead.append(top, title, reason, foot); + return lead; +} + +function buildBoleTimelineRow(row, rank) { + const { item, score } = row; + const link = document.createElement("a"); + link.className = "bole-row"; + link.href = item.url || "#"; + link.target = "_blank"; + link.rel = "noopener noreferrer"; + + const time = document.createElement("time"); + time.className = "bole-row-time"; + time.textContent = fmtTime(timelineIso(item)); + + const body = document.createElement("div"); + body.className = "bole-row-body"; + const meta = document.createElement("div"); + meta.className = "bole-row-meta"; + meta.innerHTML = `#${rank}${item.site_name || "来源"}${score}分`; + (row.sourceSignals || []).slice(0, 4).forEach((signal) => { + appendSourceChip(meta, signal, sourceSignalTone(signal), "source-chip source-hit"); + }); + const title = document.createElement("div"); + title.className = "bole-row-title"; + title.textContent = itemTitleText(item); + const reason = document.createElement("div"); + reason.className = "bole-row-reason"; + reason.textContent = boleReasonText(row); + body.append(meta, title, reason); + + link.append(time, body); + return link; +} + +function buildStoryCard(story, rank) { + const link = document.createElement("a"); + link.className = "story-row"; + const primary = story.primary_item || {}; + link.href = primary.url || story.primary_url || story.url || "#"; + link.target = "_blank"; + link.rel = "noopener noreferrer"; + + const time = document.createElement("div"); + time.className = "story-time"; + const { latest, rangeLabel } = formatStoryTime(story); + const labelEl = document.createElement("span"); + labelEl.className = "story-time-label"; + labelEl.textContent = "最新"; + const latestEl = document.createElement("span"); + latestEl.className = "story-time-latest"; + latestEl.textContent = fmtTime(latest); + time.append(labelEl, latestEl); + if (rangeLabel) { + const rangeEl = document.createElement("span"); + rangeEl.className = "story-time-range"; + rangeEl.textContent = rangeLabel; + rangeEl.title = "最早来源到最新来源的时间差,不是距离现在多久。"; + time.appendChild(rangeEl); + } + + const body = document.createElement("div"); + body.className = "story-body"; + + const meta = document.createElement("div"); + meta.className = "story-meta"; + const rankEl = document.createElement("span"); + rankEl.className = "story-rank"; + rankEl.textContent = `#${rank}`; + meta.appendChild(rankEl); + if (story.importance_label) { + const imp = document.createElement("span"); + imp.className = `story-importance ${storyImportanceTone(story.importance_label)}`; + imp.textContent = story.importance_label; + meta.appendChild(imp); + } + const sourceCount = storySourceCount(story); + const countEl = document.createElement("span"); + countEl.className = "story-count"; + countEl.textContent = `${sourceCount} 个来源`; + meta.appendChild(countEl); + const displayScore = storySortScore(story); + if (displayScore > 0) { + const scoreEl = document.createElement("strong"); + scoreEl.className = `story-score ${state.boleView === "hot" ? "heat" : ""}`.trim(); + scoreEl.title = state.boleView === "hot" + ? "热度分 = 多源强度 × 时间衰减" + : "编辑重要性分"; + scoreEl.innerHTML = `${displayScore}${state.boleView === "hot" ? "热度" : "分"}`; + meta.appendChild(scoreEl); + } + body.appendChild(meta); + + const sources = Array.isArray(story.sources) ? story.sources : []; + if (sources.length) { + const sourcesEl = document.createElement("div"); + sourcesEl.className = "story-sources"; + sources.slice(0, 6).forEach((src) => { + const kind = sourceKind(src.site_id); + const label = src.source || src.source_name || "来源"; + const tag = sourceChip(label, kind.tone, "story-source-chip source-chip"); + sourcesEl.appendChild(tag); + }); + if (sources.length > 6) { + const more = document.createElement("span"); + more.className = "story-source-more"; + more.textContent = `+${sources.length - 6}`; + sourcesEl.appendChild(more); + } + body.appendChild(sourcesEl); + } + + const title = document.createElement("div"); + title.className = "story-title"; + const primaryTitle = storyPrimaryTitleText(story); + const enTitle = storyPrimaryEnText(story); + if (enTitle && enTitle !== primaryTitle) { + const zh = document.createElement("span"); + zh.className = "story-title-zh"; + zh.textContent = primaryTitle; + const sub = document.createElement("span"); + sub.className = "story-title-en"; + sub.textContent = enTitle; + title.append(zh, sub); + } else { + title.textContent = primaryTitle; + } + body.appendChild(title); + + link.append(time, body); + return link; +} + +const HOT_DECAY_HOURS = 12; +const HOT_SCORE_SCALE = 60; + +function storyHotness(story) { + const sources = storySourceCount(story); + if (sources < 2) return 0; + const latest = storyTimeMs(story, "latest_at") || storyTimeMs(story, "earliest_at"); + const ageHours = latest ? Math.max(0, (Date.now() - latest) / 3600000) : 24; + return (sources - 1) * Math.exp(-ageHours / HOT_DECAY_HOURS); +} + +function storyHotScore(story) { + const raw = storyHotness(story); + if (raw <= 0) return 0; + return Math.max(1, Math.min(100, Math.round(raw * HOT_SCORE_SCALE))); +} + +function storySortScore(story) { + return state.boleView === "hot" ? storyHotScore(story) : storyScore(story); +} + +function hotStories(stories) { + return stories + .filter((story) => storyHotness(story) > 0) + .sort((a, b) => { + const byHotScore = storyHotScore(b) - storyHotScore(a); + if (byHotScore !== 0) return byHotScore; + const byHotRaw = storyHotness(b) - storyHotness(a); + if (byHotRaw !== 0) return byHotRaw; + const byEditorial = storyScore(b) - storyScore(a); + if (byEditorial !== 0) return byEditorial; + return storyTimeMs(b, "latest_at") - storyTimeMs(a, "latest_at"); + }); +} + +function renderBoleBrief(stories) { + bolePicksListEl.innerHTML = ""; + bolePicksListEl.className = "bole-board"; + + const hot = hotStories(stories); + const hotAvailable = hot.length >= 2; + // 宁缺毋滥: the hot view only exists when there is real multi-source heat. + if (boleViewToggleEl) boleViewToggleEl.hidden = !hotAvailable; + if (!hotAvailable) state.boleView = "timeline"; + if (boleHotBtnEl) boleHotBtnEl.classList.toggle("active", state.boleView === "hot"); + if (boleTimelineBtnEl) boleTimelineBtnEl.classList.toggle("active", state.boleView !== "hot"); + + let sorted; + let metaLabel; + if (state.boleView === "hot") { + sorted = hot; + metaLabel = `当前热点 · ${fmtNumber(sorted.length)} 簇 · 按热度分排序`; + } else { + sorted = [...stories].sort((a, b) => { + const aLatest = storyTimeMs(a, "latest_at") || storyTimeMs(a, "earliest_at"); + const bLatest = storyTimeMs(b, "latest_at") || storyTimeMs(b, "earliest_at"); + if (aLatest !== bLatest) return bLatest - aLatest; + return storyScore(b) - storyScore(a); + }); + const topScore = Math.max(...sorted.map((s) => storyScore(s))); + metaLabel = topScore > 0 + ? `故事时间线 · ${fmtNumber(sorted.length)} 条 · 最高 ${topScore} 分` + : `故事时间线 · ${fmtNumber(sorted.length)} 条`; + } + + const list = document.createElement("div"); + list.className = "bole-compact-list bole-timeline"; + const defaultLimit = state.boleView === "hot" ? BOLE_HOT_LIMIT : BOLE_TIMELINE_LIMIT; + const visibleStories = state.boleExpanded ? sorted : sorted.slice(0, defaultLimit); + visibleStories.forEach((story, index) => { + list.appendChild(buildStoryCard(story, index + 1)); + }); + bolePicksListEl.appendChild(list); + + if (sorted.length > defaultLimit) { + const moreBtn = document.createElement("button"); + moreBtn.type = "button"; + moreBtn.className = "bole-more-btn"; + moreBtn.textContent = state.boleExpanded + ? "收起" + : (state.boleView === "hot" ? "展开全部热点" : "展开完整时间线"); + moreBtn.addEventListener("click", () => { + state.boleExpanded = !state.boleExpanded; + renderBolePicks(); + }); + bolePicksListEl.appendChild(moreBtn); + } + + const generatedAt = state.dailyBrief && state.dailyBrief.generated_at; + bolePicksMetaEl.textContent = generatedAt ? `${metaLabel} · ${fmtTime(generatedAt)}` : metaLabel; + document.dispatchEvent(new CustomEvent("aiRadar:briefRendered")); +} + +function renderBoleFallback(picks) { + bolePicksListEl.innerHTML = ""; + bolePicksListEl.className = "bole-board"; + + const note = document.createElement("div"); + note.className = "bole-fallback-note"; + note.textContent = "故事合并数据暂未生成,先展示伯乐候选信号。"; + bolePicksListEl.appendChild(note); + + if (!picks.length) { + const empty = document.createElement("div"); + empty.className = "bole-empty"; + empty.textContent = "当前数据里没有可展示的评分字段。"; + bolePicksListEl.appendChild(empty); + return; + } + + const timelinePicks = [...picks].sort((a, b) => { + const byTime = timelineMs(b.item) - timelineMs(a.item); + if (byTime !== 0) return byTime; + return b.score - a.score || a.index - b.index; + }); + const list = document.createElement("div"); + list.className = "bole-compact-list"; + const visiblePicks = state.boleExpanded ? timelinePicks : timelinePicks.slice(0, BOLE_TIMELINE_LIMIT); + visiblePicks.forEach((row, index) => { + list.appendChild(buildBoleTimelineRow(row, index + 1)); + }); + bolePicksListEl.appendChild(list); + if (timelinePicks.length > BOLE_TIMELINE_LIMIT) { + const moreBtn = document.createElement("button"); + moreBtn.type = "button"; + moreBtn.className = "bole-more-btn"; + moreBtn.textContent = state.boleExpanded ? "收起" : "展开完整时间线"; + moreBtn.addEventListener("click", () => { + state.boleExpanded = !state.boleExpanded; + renderBolePicks(); + }); + bolePicksListEl.appendChild(moreBtn); + } + document.dispatchEvent(new CustomEvent("aiRadar:briefRendered")); +} + +function storyMatchesFilteredItems(story, filteredItems) { + if ( + state.activeSection === "hot" && + !state.siteFilter && + !state.authorFilter && + !state.sourceTypeFilter && + !state.signalLevelFilter && + !state.query.trim() + ) return true; + const urls = new Set(filteredItems.map((item) => item.url).filter(Boolean)); + const ids = new Set(filteredItems.map((item) => item.id).filter(Boolean)); + const storyRefs = [ + story.primary_item, + ...(Array.isArray(story.sources) ? story.sources : []), + ...(Array.isArray(story.items) ? story.items : []), + ].filter(Boolean); + return storyRefs.some((ref) => (ref.url && urls.has(ref.url)) || (ref.id && ids.has(ref.id))); +} + +function briefStories() { + return (Array.isArray(state.dailyBrief?.items) ? state.dailyBrief.items : []).filter((story) => !isUnsafeStory(story)); +} + +function mergedStories() { + return (Array.isArray(state.storiesMerged?.stories) ? state.storiesMerged.stories : []).filter((story) => !isUnsafeStory(story)); +} + +function storyStableKey(story) { + if (!story) return ""; + return story.story_id || story.primary_url || story.url || story.primary_item?.url || story.title || ""; +} + +function uniqueStories(stories, excludeKeys = new Set(), excludeIdentityKeys = new Set()) { + const seen = new Set(excludeKeys); + return stories.filter((story) => { + const key = storyStableKey(story); + if (key && seen.has(key)) return false; + if (storyHasAnyKey(story, excludeIdentityKeys)) return false; + if (key) seen.add(key); + return true; + }); +} + +function currentStoryPools(filteredItems) { + if (state.activeSection === "creator") return { brief: [], merged: [], followup: [] }; + const brief = briefStories().filter((story) => storyMatchesFilteredItems(story, filteredItems)); + const merged = mergedStories().filter((story) => storyMatchesFilteredItems(story, filteredItems)); + const briefKeys = new Set(brief.map(storyStableKey).filter(Boolean)); + const briefIdentityKeys = new Set(); + brief.forEach((story) => storyIdentityKeys(story).forEach((key) => briefIdentityKeys.add(key))); + return { + brief, + merged, + followup: uniqueStories(merged, briefKeys, briefIdentityKeys), + }; +} + +function storyRowsForPool(stories) { + const source = Array.isArray(stories) ? stories : []; + const pool = state.boleView === "hot" + ? hotStories(source).slice(0, BOLE_HOT_LIMIT) + : latestStories(source).slice(0, BOLE_TIMELINE_LIMIT); + return pool.map(storyToBoleRow); +} + +function storyCandidateCounts(stories) { + const source = Array.isArray(stories) ? stories : []; + const hotTotal = hotStories(source).length; + const timelineTotal = source.length; + return { + hot: Math.min(BOLE_HOT_LIMIT, hotTotal), + timeline: Math.min(BOLE_TIMELINE_LIMIT, timelineTotal), + hotTotal, + timelineTotal, + }; +} + +function latestStories(stories) { + return [...(Array.isArray(stories) ? stories : [])].sort((a, b) => { + const aLatest = storyTimeMs(a, "latest_at") || storyTimeMs(a, "earliest_at"); + const bLatest = storyTimeMs(b, "latest_at") || storyTimeMs(b, "earliest_at"); + if (aLatest !== bLatest) return bLatest - aLatest; + return storyScore(b) - storyScore(a); + }); +} + +function renderStoryViewPanel(stories, excludedRows = []) { + const panel = document.createElement("div"); + panel.className = "bole-story-panel"; + + const hot = hotStories(stories); + let baseSorted; + let metaLabel; + if (state.boleView === "hot") { + baseSorted = hot; + metaLabel = hot.length + ? `当前热点 · ${fmtNumber(hot.length)} 簇 · 按热度分排序` + : "当前热点 · 暂无多源聚簇"; + } else { + baseSorted = [...stories].sort((a, b) => { + const aLatest = storyTimeMs(a, "latest_at") || storyTimeMs(a, "earliest_at"); + const bLatest = storyTimeMs(b, "latest_at") || storyTimeMs(b, "earliest_at"); + if (aLatest !== bLatest) return bLatest - aLatest; + return storyScore(b) - storyScore(a); + }); + metaLabel = `故事时间线 · ${fmtNumber(baseSorted.length)} 条 · 最新优先`; + } + + const excludeKeys = excludedStoryKeySet(excludedRows); + const sorted = excludeKeys.size + ? baseSorted.filter((story) => !storyHasAnyKey(story, excludeKeys)) + : baseSorted; + const skippedCount = baseSorted.length - sorted.length; + const rankOffset = skippedCount > 0 ? excludedRows.length : 0; + if (skippedCount > 0) { + metaLabel = state.boleView === "hot" + ? `当前热点 · ${fmtNumber(baseSorted.length)} 簇 · 续看 #${rankOffset + 1} 起` + : `故事时间线 · ${fmtNumber(baseSorted.length)} 条 · Top3 后续`; + } + + if (boleViewToggleEl) { + boleViewToggleEl.hidden = false; + if (boleHotBtnEl) boleHotBtnEl.classList.toggle("active", state.boleView === "hot"); + if (boleTimelineBtnEl) boleTimelineBtnEl.classList.toggle("active", state.boleView !== "hot"); + } + + const heading = document.createElement("div"); + heading.className = "bole-story-panel-head"; + heading.textContent = metaLabel; + panel.appendChild(heading); + + if (!sorted.length) { + const empty = document.createElement("div"); + empty.className = "bole-empty"; + empty.textContent = skippedCount > 0 + ? "Top3 已覆盖当前筛选下的故事,可切换筛选或时间线继续查看。" + : state.boleView === "hot" + ? "当前筛选下没有多源热点,可切换到时间线查看最新故事。" + : "当前筛选下没有可展示的故事时间线。"; + panel.appendChild(empty); + return panel; + } + + const list = document.createElement("div"); + list.className = "bole-compact-list bole-timeline"; + const defaultLimit = state.boleView === "hot" ? BOLE_HOT_LIMIT : BOLE_TIMELINE_LIMIT; + const visibleStories = state.boleExpanded ? sorted : sorted.slice(0, defaultLimit); + visibleStories.forEach((story, index) => { + list.appendChild(buildStoryCard(story, rankOffset + index + 1)); + }); + panel.appendChild(list); + + if (sorted.length > defaultLimit) { + const moreBtn = document.createElement("button"); + moreBtn.type = "button"; + moreBtn.className = "bole-more-btn"; + moreBtn.textContent = state.boleExpanded + ? "收起" + : (skippedCount > 0 + ? (state.boleView === "hot" ? "展开后续热点" : "展开后续时间线") + : (state.boleView === "hot" ? "展开全部热点" : "展开完整时间线")); + moreBtn.addEventListener("click", () => { + state.boleExpanded = !state.boleExpanded; + renderBolePicks(); + }); + panel.appendChild(moreBtn); + } + + return panel; +} + +function storyToBoleRow(story, index) { + const enrichStoryItem = (entry) => ({ + ...entry, + site_name: entry.site_name || entry.source_name || story.source_name || "", + }); + const item = enrichStoryItem(story.primary_item || story); + const sourceItems = [ + item, + ...(Array.isArray(story.sources) ? story.sources.map(enrichStoryItem) : []), + ].filter(Boolean); + const sourceSignals = Array.from(new Set(sourceItems.map(sourceSignal))); + return { + item, + index, + story, + rows: sourceItems.map((sourceItem) => ({ item: sourceItem })), + sourceSignals, + sourceCount: storySourceCount(story), + mergedCount: Math.max(1, Number(story.duplicate_count) || sourceItems.length), + score: storySortScore(story), + }; +} + +function rankedBriefRows(stories) { + const sorted = [...stories].sort((a, b) => { + const aLatest = storyTimeMs(a, "latest_at") || storyTimeMs(a, "earliest_at"); + const bLatest = storyTimeMs(b, "latest_at") || storyTimeMs(b, "earliest_at"); + if (state.boleView === "hot") { + const byHeat = storyHotScore(b) - storyHotScore(a); + if (byHeat !== 0) return byHeat; + const byScore = storyScore(b) - storyScore(a); + if (byScore !== 0) return byScore; + return bLatest - aLatest; + } + const byScore = storyScore(b) - storyScore(a); + if (byScore !== 0) return byScore; + return bLatest - aLatest; + }); + return sorted.map(storyToBoleRow); +} + +function rankedFallbackRows(items) { + const rows = rankedClustersForItems(items); + return state.boleView === "hot" + ? rows.sort((a, b) => b.sourceCount - a.sourceCount || b.score - a.score || timelineMs(b.item) - timelineMs(a.item)) + : rows.sort((a, b) => timelineMs(b.item) - timelineMs(a.item) || b.score - a.score); +} + +function buildBoleFollowupPanel(rows, topCount, usesStories) { + const remaining = rows.slice(topCount); + if (!remaining.length) return null; + + const panel = document.createElement("div"); + panel.className = "bole-story-panel"; + const heading = document.createElement("div"); + heading.className = "bole-story-panel-head"; + const viewLabel = state.boleView === "hot" ? "当前热点" : "故事时间线"; + heading.textContent = `${viewLabel} · ${fmtNumber(rows.length)} 条${usesStories ? "故事" : "候选"} · Top${topCount} 后续`; + panel.appendChild(heading); + + const list = document.createElement("div"); + list.className = "bole-compact-list bole-timeline"; + const followupLimit = 2; + const visibleRows = state.boleExpanded ? remaining : remaining.slice(0, followupLimit); + visibleRows.forEach((row, index) => { + const rank = topCount + index + 1; + list.appendChild(row.story + ? buildStoryCard(row.story, rank) + : buildBoleTimelineRow(row, rank)); + }); + panel.appendChild(list); + + if (remaining.length > followupLimit) { + const moreBtn = document.createElement("button"); + moreBtn.type = "button"; + moreBtn.className = "bole-more-btn"; + moreBtn.textContent = state.boleExpanded + ? "收起后续" + : `展开后续 ${fmtNumber(remaining.length - followupLimit)} 条`; + moreBtn.addEventListener("click", () => { + state.boleExpanded = !state.boleExpanded; + renderBolePicks(); + }); + panel.appendChild(moreBtn); + } + return panel; +} + +function renderBolePicks() { + if (!bolePicksListEl || !bolePicksMetaEl) return; + bolePicksListEl.innerHTML = ""; + bolePicksListEl.className = "top-stories-grid"; + if (boleViewToggleEl) boleViewToggleEl.hidden = true; + if (bolePicksWrapEl) bolePicksWrapEl.hidden = false; + + const section = SECTION_BY_ID[state.activeSection] || SECTION_BY_ID.hot; + const filtered = getFilteredItems(); + const storyPools = currentStoryPools(filtered); + const availableStoryPool = storyPools.brief.length + ? [...storyPools.brief, ...storyPools.followup] + : storyPools.merged; + const usesStories = availableStoryPool.length > 0; + const candidateCounts = storyCandidateCounts(availableStoryPool); + const hotAvailable = usesStories && candidateCounts.hot >= 2; + if (usesStories && !hotAvailable && state.boleView === "hot") { + state.boleView = "timeline"; + } + const defaultLimit = state.boleView === "hot" ? BOLE_HOT_LIMIT : BOLE_TIMELINE_LIMIT; + const rows = usesStories + ? storyRowsForPool(availableStoryPool) + : rankedFallbackRows(filtered).slice(0, defaultLimit); + const top = rows.slice(0, 3); + const remainingCount = Math.max(0, rows.length - top.length); + if (topStoriesTitleEl) topStoriesTitleEl.textContent = state.activeSection === "hot" ? "今日重点信号" : `${section.label}重点信号`; + const storyMeta = usesStories + ? `展示池:热点 ${fmtNumber(candidateCounts.hot)}/${fmtNumber(candidateCounts.hotTotal)} · 时间线 ${fmtNumber(candidateCounts.timeline)}/${fmtNumber(candidateCounts.timelineTotal)}` + : `展示池:${fmtNumber(rows.length)} 条`; + bolePicksMetaEl.textContent = storyMeta; + if (boleViewToggleEl) { + boleViewToggleEl.hidden = usesStories ? !hotAvailable : true; + if (boleHotBtnEl) boleHotBtnEl.classList.toggle("active", state.boleView === "hot"); + if (boleTimelineBtnEl) boleTimelineBtnEl.classList.toggle("active", state.boleView === "timeline"); + if (boleHotBtnEl) boleHotBtnEl.textContent = `当前热点 ${fmtNumber(candidateCounts.hot)}`; + if (boleTimelineBtnEl) boleTimelineBtnEl.textContent = `时间线 ${fmtNumber(candidateCounts.timeline)}`; + } + + if (!top.length) { + const empty = document.createElement("div"); + empty.className = "bole-empty"; + empty.textContent = "当前栏目和筛选条件下没有可展示的 Top 3。"; + bolePicksListEl.appendChild(empty); + } else { + top.forEach((row, index) => { + bolePicksListEl.appendChild(buildTopStoryCard(row, index + 1)); + }); + } + + const followup = buildBoleFollowupPanel(rows, top.length, usesStories); + if (followup) { + bolePicksListEl.appendChild(followup); + } + document.dispatchEvent(new CustomEvent("aiRadar:briefRendered")); +} + +function rankedClustersForItems(items) { + const rows = [...items] + .map((item, index) => ({ + item, + index, + score: state.activeSection === "creator" + ? creatorHotScore(item) + : (scorePercent(item) || Math.round(itemPriorityScore(item))), + })) + .filter((row) => row.item && (row.score > 0 || row.item.title)) + .sort((a, b) => itemPriorityScore(b.item) - itemPriorityScore(a.item) || timelineMs(b.item) - timelineMs(a.item)); + + return clusterBoleEvents(rows).sort((a, b) => { + const byHeadlineScore = headlineClusterScore(b) - headlineClusterScore(a); + if (byHeadlineScore !== 0) return byHeadlineScore; + return timelineMs(b.item) - timelineMs(a.item) || a.index - b.index; + }); +} + +function headlineClusterScore(cluster) { + const base = itemPriorityScore(cluster.item); + const sourceBoost = Math.min(18, Math.max(0, cluster.sourceCount - 1) * 9); + const mergeBoost = Math.min(8, Math.max(0, cluster.mergedCount - 1) * 4); + return Math.min(100, Math.round(base + sourceBoost + mergeBoost)); +} + +function pickTopHeadlineClusters(clusters, limit = 3) { + return [...clusters] + .sort((a, b) => headlineClusterScore(b) - headlineClusterScore(a) || timelineMs(b.item) - timelineMs(a.item) || a.index - b.index) + .slice(0, limit) + .map((cluster) => ({ ...cluster, score: headlineClusterScore(cluster) })); +} + +function itemTagLabels(item, row = null) { + const tags = []; + const sections = itemSections(item); + if (state.activeSection !== "hot") tags.push(sectionBadgeLabel(state.activeSection)); + if (row && (row.sourceCount > 1 || row.mergedCount > 1)) tags.push("多源验证"); + if (item.site_id === "official_ai") tags.push("官方"); + if (item.site_id === "aihot") tags.push("AI HOT"); + if (sections.has("models")) tags.push("模型发布"); + if (sections.has("devtools")) tags.push("开发者"); + if (sections.has("hn")) tags.push("社区热议"); + if (sections.has("research")) tags.push("研究"); + if (sections.has("creator")) tags.push("自媒体"); + if (sections.has("community")) tags.push("社区"); + return Array.from(new Set(tags)).slice(0, 3); +} + +function itemSourceRefs(item, row = null) { + const refs = []; + const seen = new Set(); + const add = (label, tone) => { + const clean = String(label || "").trim(); + if (!clean) return; + const key = `${tone}:${clean}`; + if (seen.has(key)) return; + seen.add(key); + refs.push({ label: clean, tone }); + }; + + if (row && Array.isArray(row.sourceSignals) && row.sourceSignals.length) { + row.sourceSignals.forEach((signal) => add(signal, sourceSignalTone(signal))); + } else if (row && Array.isArray(row.rows) && row.rows.length) { + row.rows.forEach((entry) => { + const sourceItem = entry.item || {}; + const kind = sourceKind(sourceItem.site_id); + add(sourceItem.source || sourceItem.site_name || kind.label, kind.tone); + }); + } else { + const kind = sourceKind(item.site_id); + add(item.source || item.site_name || kind.label, kind.tone); + } + + return refs.length ? refs : [{ label: "来源", tone: "default" }]; +} + +function priorityGrade(score) { + if (score >= 92) return "A+"; + if (score >= 82) return "A"; + if (score >= 70) return "B"; + return "C"; +} + +function rowSourceCount(row) { + const item = row.item || {}; + const refs = itemSourceRefs(item, row); + const storyCount = row.story ? storySourceCount(row.story) : 0; + return Math.max(1, refs.length, Number(row.sourceCount || 0), Number(row.mergedCount || 0), storyCount); +} + +function signalSummaryText(row) { + const item = row.item || {}; + const story = row.story || {}; + const label = story.importance_label || labelText(item); + const sourceCount = rowSourceCount(row); + const multi = row.sourceCount > 1 || row.mergedCount > 1; + if (multi && label) return `${label}信号,已被 ${fmtNumber(sourceCount)} 个来源验证,适合优先判断是否继续深挖。`; + const reason = reasonText(item); + if (reason && !reason.startsWith("来源与标题")) return reason.replace(/^命中方向:/, "核心方向:"); + return `${label}方向的新近更新,已进入 24 小时 AI 强相关池。`; +} + +// 只返回真实的、条目级别的推荐理由(item.recommend_reason_zh 或 story.primary_item.recommend_reason_zh)。 +// 这类数据是预算受限的窄池,多数条目没有——没有真实理由时必须返回空字符串, +// 不再用分区/来源信号拼出通用模板句子(那类句子读起来像针对该条目的判断,实际是套话,参见调用方 buildTopStoryCard 的隐藏逻辑)。 +function whyImportantText(row) { + const item = row.item || {}; + const story = row.story || {}; + const recommendReason = String( + item.recommend_reason_zh || story.primary_item?.recommend_reason_zh || "" + ).trim(); + return recommendReason; +} + +function impactLabels(item) { + const sections = itemSections(item); + const labels = []; + if (sections.has("devtools")) labels.push("开发者"); + if (sections.has("products")) labels.push("产品"); + if (sections.has("industry")) labels.push("企业 / 投资"); + if (sections.has("research")) labels.push("研究"); + if (sections.has("models")) labels.push("模型团队"); + if (sections.has("community") || sections.has("hn")) labels.push("社区"); + return labels.slice(0, 3).length ? labels.slice(0, 3) : ["AI 观察者"]; +} + +function buildTopStoryCard(row, rank) { + const item = row.item; + const link = document.createElement("a"); + link.className = `top-story-card ${rank === 1 ? "lead" : "secondary"}`; + link.href = item.url || "#"; + link.target = "_blank"; + link.rel = "noopener noreferrer"; + + const rankEl = document.createElement("span"); + rankEl.className = "top-rank"; + rankEl.textContent = `#${rank}`; + + const meta = document.createElement("div"); + meta.className = "intel-meta"; + const time = document.createElement("time"); + // Brief stories keep their timeline on the story object rather than repeating + // it on primary_item. Fall back to that aggregate time so Top 3 never shows + // "时间未知" when the story itself has a verified latest/earliest timestamp. + const storyTimeline = row.story?.latest_at || row.story?.earliest_at || ""; + time.textContent = fmtTime(timelineIso(item) || storyTimeline); + const primarySource = itemSourceRefs(item, row)[0]; + const score = document.createElement("strong"); + const displayScore = row.story + ? Math.max(row.score || 0, storyScore(row.story)) + : Math.max(row.score || 0, headlineClusterScore(row)); + score.className = `intel-score ${scoreTone(displayScore)}`; + score.textContent = `优先级 ${priorityGrade(displayScore)}`; + const sourceCount = document.createElement("span"); + sourceCount.className = "source-count"; + sourceCount.textContent = `${fmtNumber(rowSourceCount(row))} 个来源`; + meta.append(rankEl, sourceChip(primarySource.label, primarySource.tone, "source-chip intel-source"), sourceCount, score, time); + + const title = document.createElement("div"); + title.className = "top-story-title"; + title.textContent = itemTitleText(item); + + const summary = document.createElement("p"); + summary.className = "top-story-summary"; + summary.textContent = signalSummaryText(row); + + const whyText = whyImportantText(row); + let why = null; + if (whyText) { + why = document.createElement("div"); + why.className = "top-story-why"; + const whyLabel = document.createElement("span"); + whyLabel.textContent = "为什么重要"; + const whyP = document.createElement("p"); + whyP.textContent = whyText; + why.append(whyLabel, whyP); + } + + const tags = document.createElement("div"); + tags.className = "intel-tags"; + itemTagLabels(item, row).forEach((label) => { + tags.appendChild(itemTagChip(label)); + }); + + const impact = document.createElement("div"); + impact.className = "impact-row"; + impactLabels(item).forEach((label) => { + const chip = document.createElement("span"); + chip.textContent = label; + impact.appendChild(chip); + }); + + link.append(meta, title, summary, ...(why ? [why] : []), tags, impact); + return link; +} + +function buildIntelCard(item, rank) { + const card = document.createElement("article"); + card.className = "intel-card"; + + const meta = document.createElement("div"); + meta.className = "intel-card-meta"; + const rankEl = document.createElement("span"); + rankEl.className = "intel-card-rank"; + rankEl.textContent = `#${rank}`; + const time = document.createElement("time"); + time.textContent = fmtTime(timelineIso(item)); + const score = scorePercent(item); + const scoreEl = document.createElement("strong"); + scoreEl.className = `intel-score ${scoreTone(score)}`; + scoreEl.textContent = score ? `AI ${score}分` : "AI观察"; + meta.append(rankEl, time, scoreEl); + + const title = document.createElement("a"); + title.className = "intel-title"; + title.href = item.url || "#"; + title.target = "_blank"; + title.rel = "noopener noreferrer"; + title.textContent = itemTitleText(item); + + const reason = document.createElement("p"); + reason.className = "intel-reason"; + reason.textContent = reasonText(item); + + const tags = document.createElement("div"); + tags.className = "intel-tags"; + itemTagLabels(item).forEach((label) => { + tags.appendChild(itemTagChip(label)); + }); + + const sources = document.createElement("div"); + sources.className = "intel-card-sources"; + const refs = itemSourceRefs(item); + const count = document.createElement("strong"); + count.textContent = `${fmtNumber(refs.length)} 个来源`; + sources.appendChild(count); + refs.slice(0, 3).forEach((ref) => { + sources.appendChild(sourceChip(ref.label, ref.tone, "source-chip")); + }); + + card.append(meta, title, reason, tags, sources); + return card; +} + +function feedSummaryText(item) { + const signals = Array.isArray(item.ai_signals) ? item.ai_signals.filter(Boolean).slice(0, 2) : []; + if (signals.length) return `相关线索:${signals.join(" / ")}。`; + const reason = reasonText(item); + if (reason && !reason.startsWith("来源与标题")) return reason.replace(/^命中方向:/, "相关线索:"); + return `${labelText(item)} · AI 相关度 ${scorePercent(item) || "待评估"}。`; +} + +function renderItemNode(item, context = {}) { + const node = itemTpl.content.firstElementChild.cloneNode(true); + const metaRow = node.querySelector(".meta-row"); + const siteEl = node.querySelector(".site"); + siteEl.textContent = item.source || item.site_name; + if (context.source && context.source === item.source) { + siteEl.hidden = true; + } + const kind = sourceKind(item.site_id); + const categoryEl = node.querySelector(".category"); + categoryEl.textContent = kind.label; + categoryEl.classList.add(`kind-${kind.tone}`); + const score = scorePercent(item); + const creatorScore = creatorHotScore(item); + const tagEl = document.createElement("span"); + tagEl.className = `ai-tag tone-${itemLabelTone(item)}`; + tagEl.textContent = creatorScore && itemSections(item).has("creator") + ? `自媒体热度 · ${creatorScore}分` + : `${labelText(item)} · ${score || "?"}分`; + categoryEl.insertAdjacentElement("afterend", tagEl); + + const sourceEl = node.querySelector(".source"); + const sourceLabel = sourceSignal(item); + setSourceBadge(sourceEl, sourceLabel, sourceSignalTone(sourceLabel), item.source ? `分区: ${item.source}` : ""); + if (context.source && context.source === item.source) { + sourceEl.hidden = true; + } + + const primaryLabel = labelText(item); + itemTagLabels(item) + .filter((label) => label !== primaryLabel) + .slice(0, 3) + .forEach((label) => { + metaRow.insertBefore(itemTagChip(label), sourceEl); + }); + + node.querySelector(".time").textContent = fmtTime(item.published_at || item.first_seen_at); + + const titleEl = node.querySelector(".title"); + const zh = (item.title_zh || "").trim(); + const en = (item.title_en || "").trim(); + titleEl.textContent = ""; + if (zh && en && zh !== en) { + const primary = document.createElement("span"); + primary.textContent = zh; + const sub = document.createElement("span"); + sub.className = "title-sub"; + sub.textContent = en; + titleEl.appendChild(primary); + titleEl.appendChild(sub); + } else { + titleEl.textContent = item.title || zh || en; + } + titleEl.href = item.url; + const summaryEl = node.querySelector(".news-summary"); + if (summaryEl) summaryEl.textContent = feedSummaryText(item); + return node; +} + +const SOURCE_ITEM_INITIAL_LIMIT = 3; +const SITE_GROUP_INITIAL_LIMIT = 4; +const SITE_GROUP_LOAD_STEP = 4; +const SITE_SOURCE_GROUP_INITIAL_LIMIT = 4; +const SITE_SOURCE_GROUP_LOAD_STEP = 4; +const SOURCE_GROUP_INITIAL_LIMIT = 8; +const SOURCE_GROUP_LOAD_STEP = 8; +const BOLE_HOT_LIMIT = 10; +const BOLE_TIMELINE_LIMIT = 20; + +function buildSourceGroupNode(source, items, rawCount = items.length) { + const section = document.createElement("section"); + section.className = "source-group"; + const header = document.createElement("header"); + header.className = "source-group-head"; + const title = document.createElement("h3"); + title.textContent = source; + const count = document.createElement("span"); + count.className = "group-summary"; + count.textContent = subgroupSummary(items, rawCount); + const listEl = document.createElement("div"); + listEl.className = "source-group-list"; + header.append(title, count); + section.append(header, listEl); + + let expanded = false; + if (items.length > SOURCE_ITEM_INITIAL_LIMIT) { + const moreBtn = document.createElement("button"); + moreBtn.type = "button"; + moreBtn.className = "group-more-btn"; + const renderItems = () => { + listEl.innerHTML = ""; + const visibleItems = expanded ? items : items.slice(0, SOURCE_ITEM_INITIAL_LIMIT); + visibleItems.forEach((item) => listEl.appendChild(renderItemNode(item, { source }))); + moreBtn.textContent = expanded + ? `收起,仅看前 ${SOURCE_ITEM_INITIAL_LIMIT} 条` + : `展开剩余 ${fmtNumber(items.length - SOURCE_ITEM_INITIAL_LIMIT)} 条`; + }; + moreBtn.addEventListener("click", () => { + expanded = !expanded; + renderItems(); + }); + renderItems(); + section.append(moreBtn); + } else { + items.forEach((item) => listEl.appendChild(renderItemNode(item, { source }))); + } + return section; +} + +function displayDedupeKey(item) { + const title = normalizedEventText(itemTitleText(item)); + // Short social-post titles such as "AI小狗" still identify the same visible + // post within one creator subgroup; URL query strings often only carry a + // rotating access token and must not defeat that deduplication. + if (title) return `title:${title}`; + try { + const url = new URL(item.url || ""); + return `url:${url.origin}${url.pathname}`; + } catch { + return `url:${item.url || item.id || "untitled"}`; + } +} + +function dedupeSubgroupItems(items) { + const seen = new Set(); + return sortItemsForList(items).filter((item) => { + const key = displayDedupeKey(item); + if (seen.has(key)) return false; + seen.add(key); + return true; + }); +} + +function subgroupSortValue(items) { + if (!items.length) return 0; + if (state.listSort === "latest") return Math.max(...items.map(timelineMs)); + if (state.listSort === "ai") return Math.max(...items.map(scorePercent)); + if (state.listSort === "source") return items.length; + const leading = [...items] + .sort((a, b) => itemPriorityScore(b) - itemPriorityScore(a)) + .slice(0, 3); + return Math.round(leading.reduce((sum, item) => sum + itemPriorityScore(item), 0) / leading.length); +} + +function subgroupSummary(items, rawCount = items.length) { + const count = `${fmtNumber(items.length)} 条`; + const merged = rawCount - items.length; + let ranking = ""; + if (state.listSort === "priority") ranking = `综合 ${subgroupSortValue(items)}`; + if (state.listSort === "latest") ranking = `最新 ${fmtTime(timelineIso(items[0]))}`; + if (state.listSort === "ai") ranking = `最高 AI ${subgroupSortValue(items)}分`; + const mergedLabel = merged > 0 ? `合并 ${fmtNumber(merged)} 条重复` : ""; + return [count, ranking, mergedLabel].filter(Boolean).join(" · "); +} + +function sourceGroupEntries(items) { + const groupMap = new Map(); + items.forEach((item) => { + const key = item.source || "未分区"; + if (!groupMap.has(key)) { + groupMap.set(key, []); + } + groupMap.get(key).push(item); + }); + + return Array.from(groupMap.entries()) + .map(([source, rawItems]) => ({ + source, + rawCount: rawItems.length, + items: dedupeSubgroupItems(rawItems), + })) + .filter((group) => group.items.length) + .sort((a, b) => { + const byScore = subgroupSortValue(b.items) - subgroupSortValue(a.items); + if (byScore !== 0) return byScore; + const byCount = b.items.length - a.items.length; + if (byCount !== 0) return byCount; + return a.source.localeCompare(b.source, "zh-CN"); + }); +} + +// Mobile-safe async rendering: avoid blocking the main thread on large lists. +// We chunk site-groups and yield between each chunk so the browser can paint +// and respond to touch events while the list is being built. +let _renderListToken = 0; + +function buildSiteGroupNode(site) { + const siteSection = document.createElement("section"); + siteSection.className = "site-group"; + const header = document.createElement("header"); + header.className = "site-group-head"; + const title = document.createElement("h3"); + title.textContent = site.siteName; + const count = document.createElement("span"); + count.className = "group-summary"; + count.textContent = subgroupSummary(site.items, site.rawCount); + const siteListEl = document.createElement("div"); + siteListEl.className = "site-group-list"; + header.append(title, count); + siteSection.append(header, siteListEl); + + const sourceGroups = site.sourceGroups; + let expanded = false; + let moreBtn = null; + const renderSourceGroups = () => { + siteListEl.innerHTML = ""; + if (moreBtn) moreBtn.remove(); + const visibleGroups = expanded + ? sourceGroups + : sourceGroups.slice(0, SITE_SOURCE_GROUP_INITIAL_LIMIT); + const frag = document.createDocumentFragment(); + visibleGroups.forEach((group) => { + frag.appendChild(buildSourceGroupNode(group.source, group.items, group.rawCount)); + }); + siteListEl.appendChild(frag); + if (sourceGroups.length > SITE_SOURCE_GROUP_INITIAL_LIMIT) { + const hiddenCount = sourceGroups.length - SITE_SOURCE_GROUP_INITIAL_LIMIT; + moreBtn = addLoadMoreButton( + siteSection, + expanded + ? `收起,仅看前 ${SITE_SOURCE_GROUP_INITIAL_LIMIT} 个分区` + : `展开其余 ${fmtNumber(hiddenCount)} 个分区`, + () => { + expanded = !expanded; + renderSourceGroups(); + }, + ); + } + }; + renderSourceGroups(); + return siteSection; +} + +function renderLoadingNotice(label, count) { + const loading = document.createElement("div"); + loading.className = "list-loading"; + loading.textContent = `正在整理 ${label} · ${fmtNumber(count)} 条`; + newsListEl.appendChild(loading); +} + +function currentFilterLabel(filtered) { + if (state.authorFilter) return `${listTitleText()} · X 博主 ${state.authorFilter}`; + if (state.siteFilter) { + const item = filtered[0]; + const stat = currentSiteStats().find((s) => s.site_id === state.siteFilter); + return `${listTitleText()} · ${item?.site_name || stat?.site_name || state.siteFilter}`; + } + return listTitleText(); +} + +function groupedSites(items) { + const siteMap = new Map(); + items.forEach((item) => { + if (!siteMap.has(item.site_id)) { + siteMap.set(item.site_id, { siteName: item.site_name || item.site_id, rawItems: [] }); + } + siteMap.get(item.site_id).rawItems.push(item); + }); + + return Array.from(siteMap.entries()) + .map(([siteId, site]) => { + const sourceGroups = sourceGroupEntries(site.rawItems); + return [siteId, { + siteName: site.siteName, + rawCount: site.rawItems.length, + sourceGroups, + items: sourceGroups.flatMap((group) => group.items), + }]; + }) + .filter(([, site]) => site.items.length) + .sort((a, b) => { + const byScore = subgroupSortValue(b[1].items) - subgroupSortValue(a[1].items); + if (byScore !== 0) return byScore; + const byCount = b[1].items.length - a[1].items.length; + if (byCount !== 0) return byCount; + return a[1].siteName.localeCompare(b[1].siteName, "zh-CN"); + }); +} + +function addLoadMoreButton(parent, label, onClick) { + const moreBtn = document.createElement("button"); + moreBtn.type = "button"; + moreBtn.className = "list-more-btn"; + moreBtn.textContent = label; + moreBtn.addEventListener("click", onClick); + parent.appendChild(moreBtn); + return moreBtn; +} + +function renderSiteGroups(items) { + const groups = groupedSites(items); + const visibleGroups = state.siteGroupsExpanded + ? groups + : groups.slice(0, SITE_GROUP_INITIAL_LIMIT); + visibleGroups.forEach(([, site]) => { + newsListEl.appendChild(buildSiteGroupNode(site)); + }); + + if (groups.length > SITE_GROUP_INITIAL_LIMIT) { + const hiddenCount = groups.length - SITE_GROUP_INITIAL_LIMIT; + addLoadMoreButton( + newsListEl, + state.siteGroupsExpanded + ? `收起,仅看前 ${SITE_GROUP_INITIAL_LIMIT} 个来源` + : `展开其余 ${fmtNumber(hiddenCount)} 个来源`, + () => { + state.siteGroupsExpanded = !state.siteGroupsExpanded; + renderList(); + }, + ); + } + document.dispatchEvent(new CustomEvent("aiRadar:listRendered")); +} + +function renderList() { + const filtered = getFilteredItems(); + renderListSortTools(); + resultCountEl.textContent = `${fmtNumber(filtered.length)} 条`; + renderSectionSummary(filtered); + + newsListEl.innerHTML = ""; + _renderListToken += 1; // invalidate any in-flight render + const token = _renderListToken; + + if (!filtered.length) { + const empty = document.createElement("div"); + empty.className = "empty"; + empty.textContent = "当前筛选条件下没有结果。"; + newsListEl.appendChild(empty); + return; + } + + renderLoadingNotice(currentFilterLabel(filtered), filtered.length); + requestAnimationFrame(() => { + if (token !== _renderListToken) return; // stale render, abort + const sorted = sortItemsForList(filtered); + newsListEl.innerHTML = ""; + renderSiteGroups(sorted); + }); +} + +function rerenderCurrentView() { + state.boleExpanded = false; + state.siteGroupsExpanded = false; + renderSectionTabs(); + renderModeSwitch(); + renderSiteFilters(); + renderBolePicks(); + if (state.waytoagiData) renderWaytoagi(state.waytoagiData); + renderList(); +} + +function waytoagiViews(waytoagi) { + const updates7d = Array.isArray(waytoagi?.updates_7d) ? waytoagi.updates_7d : []; + const latestDate = waytoagi?.latest_date || (updates7d.length ? updates7d[0].date : null); + const updatesToday = Array.isArray(waytoagi?.updates_today) && waytoagi.updates_today.length + ? waytoagi.updates_today + : (latestDate ? updates7d.filter((u) => u.date === latestDate) : []); + return { updates7d, updatesToday, latestDate }; +} + +function renderWaytoagi(waytoagi) { + if (waytoagiWrapEl) { + waytoagiWrapEl.hidden = state.activeSection !== "community"; + } + if (state.activeSection !== "community") return; + const { updates7d, updatesToday, latestDate } = waytoagiViews(waytoagi); + if (waytoagiTodayBtnEl) waytoagiTodayBtnEl.classList.toggle("active", state.waytoagiMode === "today"); + if (waytoagi7dBtnEl) waytoagi7dBtnEl.classList.toggle("active", state.waytoagiMode === "7d"); + waytoagiUpdatedAtEl.textContent = `更新时间:${fmtTime(waytoagi.generated_at)}`; + + waytoagiMetaEl.innerHTML = ""; + const rootLink = document.createElement("a"); + rootLink.href = waytoagi.root_url || "#"; + rootLink.target = "_blank"; + rootLink.rel = "noopener noreferrer"; + rootLink.textContent = "主页面"; + const historyLink = document.createElement("a"); + historyLink.href = waytoagi.history_url || "#"; + historyLink.target = "_blank"; + historyLink.rel = "noopener noreferrer"; + historyLink.textContent = "历史更新页"; + const todayCount = document.createElement("span"); + todayCount.textContent = `最近更新日(${latestDate || "--"}):${fmtNumber(waytoagi.count_today || updatesToday.length)} 条`; + const weekCount = document.createElement("span"); + weekCount.textContent = `近 7 日:${fmtNumber(waytoagi.count_7d || updates7d.length)} 条`; + [rootLink, "·", historyLink, "·", todayCount, "·", weekCount].forEach((part) => { + if (typeof part === "string") { + const sep = document.createElement("span"); + sep.textContent = part; + waytoagiMetaEl.appendChild(sep); + } else { + waytoagiMetaEl.appendChild(part); + } + }); + + waytoagiListEl.innerHTML = ""; + if (waytoagi.has_error) { + const div = document.createElement("div"); + div.className = "waytoagi-error"; + div.textContent = waytoagi.error || "WaytoAGI 数据加载失败"; + waytoagiListEl.appendChild(div); + return; + } + + const updates = state.waytoagiMode === "today" ? updatesToday : updates7d; + if (!updates.length) { + const div = document.createElement("div"); + div.className = "waytoagi-empty"; + div.textContent = state.waytoagiMode === "today" + ? "最近更新日没有更新,可切换到近7日查看。" + : (waytoagi.warning || "近 7 日没有更新"); + waytoagiListEl.appendChild(div); + return; + } + + updates.forEach((u) => { + const row = document.createElement("a"); + row.className = "waytoagi-item"; + row.href = u.url || "#"; + row.target = "_blank"; + row.rel = "noopener noreferrer"; + const dateEl = document.createElement("span"); + dateEl.className = "d"; + dateEl.textContent = fmtDate(u.date); + const titleEl = document.createElement("span"); + titleEl.className = "t"; + titleEl.textContent = u.title; + row.append(dateEl, titleEl); + waytoagiListEl.appendChild(row); + }); +} + +function renderMetric(label, value, tone = "", options = {}) { + const interactive = typeof options.onClick === "function"; + const node = document.createElement(interactive ? "button" : "div"); + node.className = `health-metric ${interactive ? "health-metric-button" : ""} ${tone}`.trim(); + if (interactive) { + node.type = "button"; + node.title = options.title || "查看详情"; + node.setAttribute("aria-expanded", String(Boolean(options.expanded))); + node.addEventListener("click", options.onClick); + } + const labelEl = document.createElement("span"); + labelEl.className = "health-label"; + labelEl.textContent = label; + const valueEl = document.createElement("strong"); + valueEl.textContent = value; + node.append(labelEl, valueEl); + return node; +} + +function socialdataAuthors() { + return Array.from(new Set( + state.itemsAi + .filter((item) => item.site_id === "socialdata_x") + .map((item) => String(item.source || "").trim()) + .filter(Boolean), + )).sort((a, b) => a.localeCompare(b, "en")); +} + +function selectSocialdataAuthor(author) { + state.authorFilter = author; + state.siteFilter = "socialdata_x"; + state.activeSection = "hot"; + state.boleExpanded = false; + state.siteGroupsExpanded = false; + state.xAuthorsExpanded = false; + renderSectionTabs(); + renderModeSwitch(); + renderSiteFilters(); + renderBolePicks(); + renderList(); + renderSourceHealth(); + document.querySelector(".list-wrap")?.scrollIntoView({ behavior: "smooth", block: "start" }); +} + +function renderSocialdataAuthorList(authors, itemCount) { + const panel = document.createElement("section"); + panel.className = "health-author-list"; + const heading = document.createElement("div"); + heading.className = "health-author-list-title"; + heading.textContent = "本轮 X 扫到的博主"; + const meta = document.createElement("div"); + meta.className = "health-author-list-meta"; + meta.textContent = `${fmtNumber(authors.length)} 位博主 · ${fmtNumber(itemCount)} 条入池内容`; + const list = document.createElement("div"); + list.className = "health-author-list-items"; + authors.forEach((author) => { + const item = document.createElement("button"); + item.type = "button"; + item.textContent = author; + item.title = `查看 ${author} 的 X 内容`; + item.addEventListener("click", () => selectSocialdataAuthor(author)); + list.appendChild(item); + }); + panel.append(heading, meta, list); + return panel; +} + +function renderIssueList(title, items) { + const wrap = document.createElement("div"); + wrap.className = "health-issue"; + const titleEl = document.createElement("div"); + titleEl.className = "health-issue-title"; + titleEl.textContent = title; + const list = document.createElement("ul"); + items.slice(0, 6).forEach((item) => { + const li = document.createElement("li"); + li.textContent = typeof item === "string" ? item : JSON.stringify(item); + list.appendChild(li); + }); + if (items.length > 6) { + const li = document.createElement("li"); + li.textContent = `另有 ${fmtNumber(items.length - 6)} 项`; + list.appendChild(li); + } + wrap.append(titleEl, list); + return wrap; +} + +function renderSourceHealthSummaryNode(status, errorMessage = "") { + const node = document.createElement("div"); + node.className = "source-health-summary"; + if (!status) { + node.classList.add(errorMessage ? "bad" : "warn"); + node.innerHTML = `${errorMessage ? "源状态异常" : "源状态未生成"}${errorMessage || "等待 source-status.json"}`; + return node; + } + const sites = Array.isArray(status.sites) ? status.sites : []; + const okSites = Number(status.successful_sites || 0); + const failed = failedSourceCount(status); + const fetched = Number(status.fetched_raw_items || state.totalRaw || status.items_before_topic_filter || 0); + node.classList.toggle("warn", failed > 0); + node.innerHTML = `${fmtNumber(okSites)}/${fmtNumber(sites.length)} 源正常今日采集 ${fmtNumber(fetched)} 条 · 失败 ${fmtNumber(failed)}`; + return node; +} + +function renderSourceStatusTable(status) { + if (!sourceStatusTableEl) return; + sourceStatusTableEl.innerHTML = ""; + if (!status || !Array.isArray(status.sites) || !status.sites.length) return; + + const rows = status.sites + .map((site) => { + const ai = aiSiteStat(site.site_id); + const aiCount = Number(ai?.count || 0); + const rawCount = Number(ai?.raw_count ?? site.item_count ?? 0); + const scanned = Number(site.item_count || rawCount || 0); + const ratioBase = rawCount || scanned; + const ratio = ratioBase ? Math.round((aiCount / ratioBase) * 100) : 0; + return { ...site, aiCount, rawCount: ratioBase, ratio }; + }) + .sort((a, b) => b.aiCount - a.aiCount || b.rawCount - a.rawCount || String(a.site_name).localeCompare(String(b.site_name), "zh-CN")) + .slice(0, 12); + + const table = document.createElement("div"); + table.className = "source-table"; + const header = document.createElement("div"); + header.className = "source-table-row source-table-head"; + header.innerHTML = "来源AI / 原始AI占比状态"; + table.appendChild(header); + rows.forEach((site) => { + const row = document.createElement("div"); + row.className = "source-table-row"; + const statusText = site.ok ? "正常" : "异常"; + row.innerHTML = ` + ${site.site_name || site.site_id} + ${fmtNumber(site.aiCount)} / ${fmtNumber(site.rawCount)} + ${fmtNumber(site.ratio)}% + ${statusText} + `; + table.appendChild(row); + }); + sourceStatusTableEl.appendChild(table); +} + +function renderSourceHealth(errorMessage = "") { + if (!sourceHealthEl) return; + sourceHealthEl.innerHTML = ""; + if (sourceHealthDetailsEl) sourceHealthDetailsEl.innerHTML = ""; + if (sourceStatusTableEl) sourceStatusTableEl.innerHTML = ""; + + const status = state.sourceStatus; + if (!status) { + sourceHealthEl.appendChild(renderSourceHealthSummaryNode(null, errorMessage)); + renderSourceStatusPill(errorMessage); + renderAdvancedSummary(); + setStats(); + return; + } + + const sites = Array.isArray(status.sites) ? status.sites : []; + const failedSites = Array.isArray(status.failed_sites) ? status.failed_sites : []; + const zeroSites = Array.isArray(status.zero_item_sites) ? status.zero_item_sites : []; + const rss = status.rss_opml || {}; + const agentmail = status.agentmail || {}; + const xApi = status.x_api || {}; + const socialdata = status.socialdata || {}; + const emptyAdvanced = Array.isArray(status.empty_advanced_sources) ? status.empty_advanced_sources : []; + const failedFeeds = Array.isArray(rss.failed_feeds) ? rss.failed_feeds : []; + const skippedFeeds = Array.isArray(rss.skipped_feeds) ? rss.skipped_feeds : []; + const replacedFeeds = Array.isArray(rss.replaced_feeds) ? rss.replaced_feeds : []; + // Paid sources run on a protected interval. A skipped refresh can still have + // usable records from the last successful run in today's data pool, so don't + // hide them behind a misleading "待窗口" status. + const socialdataLiveCount = Number(socialdata.item_count || 0); + const socialdataPoolCount = siteAiPoolCount("socialdata_x"); + const socialdataDisplayCount = socialdataLiveCount || socialdataPoolCount; + const xApiLiveCount = Number(xApi.item_count || 0); + const xApiPoolCount = siteAiPoolCount("xapi"); + const xApiDisplayCount = xApiLiveCount || xApiPoolCount; + const xDisplayCount = socialdataDisplayCount + xApiDisplayCount; + const xAuthors = socialdataAuthors(); + + const xMetricValue = xDisplayCount + ? `已入池 ${fmtNumber(xDisplayCount)}条` + : socialdata.enabled + ? (socialdataDisplayCount + ? "成功" + : (socialdata.skipped ? "待窗口" : "已连接,暂无匹配")) + : (xApi.enabled + ? (xApiDisplayCount + ? "成功" + : (xApi.skipped ? "待窗口" : "已连接,暂无匹配")) + : "未启用"); + const xMetricTone = socialdata.error || xApi.error ? "bad" : (xDisplayCount ? "ok" : (emptyAdvanced.length ? "warn" : "")); + + const metricGrid = document.createElement("div"); + metricGrid.className = "health-grid"; + metricGrid.append( + renderMetric("内置源", `${fmtNumber(status.successful_sites || 0)}/${fmtNumber(sites.length)}`, failedSites.length ? "warn" : "ok"), + renderMetric("RSS", rss.enabled ? `${fmtNumber(rss.ok_feeds || 0)}/${fmtNumber(rss.effective_feed_total || 0)}` : "未启用"), + renderMetric("X数据源", xMetricValue, xMetricTone, xAuthors.length ? { + expanded: state.xAuthorsExpanded, + title: "查看本轮扫描到的 X 博主", + onClick: () => { + state.xAuthorsExpanded = !state.xAuthorsExpanded; + renderSourceHealth(); + }, + } : {}), + renderMetric("AgentMail", agentmail.enabled ? `${fmtNumber(agentmail.item_count || 0)}封` : "未启用", agentmail.error ? "bad" : ""), + renderMetric("失败源", fmtNumber(failedSites.length + failedFeeds.length), failedSites.length || failedFeeds.length ? "bad" : "ok"), + renderMetric("替换/跳过", `${fmtNumber(replacedFeeds.length)}/${fmtNumber(skippedFeeds.length)}`) + ); + sourceHealthEl.appendChild(renderSourceHealthSummaryNode(status, errorMessage)); + const detailTarget = sourceHealthDetailsEl || sourceHealthEl; + detailTarget.appendChild(metricGrid); + if (state.xAuthorsExpanded && xAuthors.length) { + detailTarget.appendChild(renderSocialdataAuthorList(xAuthors, socialdataDisplayCount)); + } + + const issues = document.createElement("div"); + issues.className = "health-issues"; + if (failedSites.length) issues.appendChild(renderIssueList("失败站点", failedSites)); + if (zeroSites.length) issues.appendChild(renderIssueList("零结果站点", zeroSites)); + if (emptyAdvanced.length) { + issues.appendChild(renderIssueList("高级源暂无匹配", emptyAdvanced.map((item) => `${item.site_name || item.site_id} · 已连接,暂无匹配结果`))); + } + if (failedFeeds.length) issues.appendChild(renderIssueList("失败 RSS", failedFeeds)); + if (skippedFeeds.length) { + issues.appendChild(renderIssueList("跳过 RSS", skippedFeeds.map((item) => `${item.feed_url} · ${item.reason || "skipped"}`))); + } + + if (issues.childElementCount) { + detailTarget.appendChild(issues); + } else { + const ok = document.createElement("div"); + ok.className = "health-ok"; + ok.textContent = "详细源状态正常"; + detailTarget.appendChild(ok); + } + renderSourceStatusTable(status); + renderSourceStatusPill(errorMessage); + renderAdvancedSummary(); + setStats(); +} + +async function loadNewsData() { + const res = await fetch(`${dataUrl("data/latest-24h.json")}?t=${Date.now()}`); + if (!res.ok) throw new Error(`加载 latest-24h.json 失败: ${res.status}`); + return res.json(); +} + +async function loadAllModeData() { + if (state.allDataLoaded) return; + if (!state.allDataPromise) { + state.allDataPromise = fetch(`${dataUrl(state.allDataUrl)}?t=${Date.now()}`) + .then((res) => { + if (!res.ok) throw new Error(`加载 latest-24h-all.json 失败: ${res.status}`); + return res.json(); + }) + .then((payload) => { + state.itemsAllRaw = payload.items_all_raw || payload.items_all || state.itemsAi; + state.itemsAll = payload.items_all || state.itemsAi; + state.totalRaw = payload.total_items_raw || state.itemsAllRaw.length; + state.totalAllMode = payload.total_items_all_mode || state.itemsAll.length; + state.allDataLoaded = true; + }) + .catch((err) => { + state.allDataPromise = null; + throw err; + }); + } + return state.allDataPromise; +} + +async function loadWaytoagiData() { + const res = await fetch(`${dataUrl("data/waytoagi-7d.json")}?t=${Date.now()}`); + if (!res.ok) throw new Error(`加载 waytoagi-7d.json 失败: ${res.status}`); + return res.json(); +} + +async function loadSourceStatusData() { + const res = await fetch(`${dataUrl("data/source-status.json")}?t=${Date.now()}`); + if (!res.ok) throw new Error(`加载 source-status.json 失败: ${res.status}`); + return res.json(); +} + +async function loadDailyBriefData() { + const res = await fetch(`${dataUrl("data/daily-brief.json")}?t=${Date.now()}`); + if (!res.ok) throw new Error(`加载 daily-brief.json 失败: ${res.status}`); + return res.json(); +} + +async function loadStoriesData() { + const res = await fetch(`${dataUrl(state.storiesDataUrl)}?t=${Date.now()}`); + if (!res.ok) throw new Error(`加载 stories-merged.json 失败: ${res.status}`); + return res.json(); +} + +async function init() { + const [newsResult, waytoagiResult, statusResult, briefResult, storiesResult] = await Promise.allSettled([ + loadNewsData(), + loadWaytoagiData(), + loadSourceStatusData(), + loadDailyBriefData(), + loadStoriesData(), + ]); + + if (briefResult.status === "fulfilled") { + state.dailyBrief = briefResult.value; + } else { + state.dailyBrief = null; + } + + if (storiesResult.status === "fulfilled") { + state.storiesMerged = storiesResult.value; + } else { + state.storiesMerged = null; + } + + if (newsResult.status === "fulfilled") { + const payload = newsResult.value; + const loadedStoriesDataUrl = state.storiesDataUrl; + state.itemsAi = payload.items_ai || payload.items || []; + state.itemsAllRaw = payload.items_all_raw || payload.items_all || []; + state.itemsAll = payload.items_all || []; + state.creatorItemsAi = payload.creator_items_ai || []; + state.creatorItemsAll = payload.creator_items_all || state.creatorItemsAi; + state.creatorWindowDays = Number(payload.creator_window_days || 7); + state.statsAi = payload.site_stats || []; + state.totalAi = payload.total_items || state.itemsAi.length; + state.totalRaw = payload.total_items_raw || state.itemsAllRaw.length; + state.totalAllMode = payload.total_items_all_mode || state.itemsAll.length; + state.allDataUrl = payload.all_mode_data_url || state.allDataUrl; + state.storiesDataUrl = payload.stories_data_url || state.storiesDataUrl; + if (state.storiesDataUrl !== loadedStoriesDataUrl) { + try { + state.storiesMerged = await loadStoriesData(); + } catch { + state.storiesMerged = null; + } + } + state.allDataLoaded = Boolean(payload.items_all || payload.items_all_raw); + state.generatedAt = payload.generated_at; + + setStats(); + renderSectionTabs(); + renderModeSwitch(); + renderListSortTools(); + renderCoverageStrip(); + renderSiteFilters(); + renderBolePicks(); + renderList(); + updatedAtEl.textContent = fmtTime(state.generatedAt); + } else { + updatedAtEl.textContent = "新闻数据加载失败"; + newsListEl.innerHTML = `
${newsResult.reason.message}
`; + renderCoverageStrip(newsResult.reason.message); + } + + if (statusResult.status === "fulfilled") { + state.sourceStatus = statusResult.value; + renderSourceHealth(); + renderCoverageStrip(); + } else { + renderSourceHealth(statusResult.reason.message); + renderCoverageStrip(statusResult.reason.message); + } + + if (waytoagiResult.status === "fulfilled") { + state.waytoagiData = waytoagiResult.value; + renderWaytoagi(state.waytoagiData); + } else { + if (waytoagiWrapEl) waytoagiWrapEl.hidden = state.activeSection !== "community"; + waytoagiUpdatedAtEl.textContent = "加载失败"; + waytoagiListEl.innerHTML = `
${waytoagiResult.reason.message}
`; + } + + document.dispatchEvent(new CustomEvent("aiRadar:ready")); +} + +searchInputEl.addEventListener("input", (e) => { + state.query = e.target.value; + renderBolePicks(); + renderList(); +}); + +siteSelectEl.addEventListener("change", (e) => { + state.siteFilter = e.target.value; + if (state.siteFilter !== "socialdata_x") state.authorFilter = ""; + state.siteGroupsExpanded = false; + renderSiteFilters(); + renderBolePicks(); + renderList(); +}); + +if (sectionSelectEl) { + sectionSelectEl.addEventListener("change", (e) => { + state.activeSection = e.target.value || "hot"; + rerenderCurrentView(); + }); +} + +if (sourceTypeSelectEl) { + sourceTypeSelectEl.addEventListener("change", (e) => { + state.sourceTypeFilter = e.target.value; + state.siteFilter = ""; + state.authorFilter = ""; + rerenderCurrentView(); + }); +} + +if (signalLevelSelectEl) { + signalLevelSelectEl.addEventListener("change", (e) => { + state.signalLevelFilter = e.target.value; + rerenderCurrentView(); + }); +} + +modeAiBtnEl.addEventListener("click", () => { + state.mode = "ai"; + rerenderCurrentView(); +}); + +modeAllBtnEl.addEventListener("click", async () => { + state.mode = "all"; + renderModeSwitch(); + newsListEl.innerHTML = ""; + const loading = document.createElement("div"); + loading.className = "empty"; + loading.textContent = "正在加载全量更新..."; + newsListEl.appendChild(loading); + try { + await loadAllModeData(); + rerenderCurrentView(); + } catch (err) { + newsListEl.innerHTML = ""; + const failed = document.createElement("div"); + failed.className = "empty"; + failed.textContent = err.message; + newsListEl.appendChild(failed); + } +}); + +if (allDedupeToggleEl) { + allDedupeToggleEl.addEventListener("change", (e) => { + state.allDedup = Boolean(e.target.checked); + rerenderCurrentView(); + }); +} + +if (listSortToolsEl) { + listSortToolsEl.addEventListener("click", (event) => { + const target = event.target; + const button = target instanceof Element ? target.closest("[data-sort]") : null; + if (!button || !listSortToolsEl.contains(button)) return; + const nextSort = button.dataset.sort; + if (!LIST_SORT_DEFS.some((item) => item.id === nextSort) || nextSort === state.listSort) return; + state.listSort = nextSort; + renderListSortTools(); + renderList(); + }); +} + +if (waytoagiTodayBtnEl) { + waytoagiTodayBtnEl.addEventListener("click", () => { + state.waytoagiMode = "today"; + if (state.waytoagiData) renderWaytoagi(state.waytoagiData); + }); +} + +if (waytoagi7dBtnEl) { + waytoagi7dBtnEl.addEventListener("click", () => { + state.waytoagiMode = "7d"; + if (state.waytoagiData) renderWaytoagi(state.waytoagiData); + }); +} + +if (boleHotBtnEl) { + boleHotBtnEl.addEventListener("click", () => { + state.boleView = "hot"; + state.boleExpanded = false; + renderBolePicks(); + }); +} + +if (boleTimelineBtnEl) { + boleTimelineBtnEl.addEventListener("click", () => { + state.boleView = "timeline"; + state.boleExpanded = false; + renderBolePicks(); + }); +} + +if (dataSourceResetBtnEl) { + dataSourceResetBtnEl.addEventListener("click", () => { + try { localStorage.removeItem("dataBaseUrl"); } catch {} + window.location.href = window.location.pathname; + }); +} + +function renderDataSourceIndicator() { + if (!dataSourceIndicatorEl) return; + const base = state.dataBaseUrl; + dataSourceIndicatorEl.hidden = !base; + if (base && dataSourceIndicatorTextEl) { + dataSourceIndicatorTextEl.textContent = `数据源:${base}`; + } +} + +renderDataSourceIndicator(); +init(); diff --git a/skills/ai-news-radar/classic/assets/motion.js b/skills/ai-news-radar/classic/assets/motion.js new file mode 100644 index 0000000..d8879ec --- /dev/null +++ b/skills/ai-news-radar/classic/assets/motion.js @@ -0,0 +1,63 @@ +(function () { + if (!window.gsap) return; + + const mm = gsap.matchMedia(); + + mm.add("(prefers-reduced-motion: no-preference)", function () { + gsap.defaults({ duration: 0.55, ease: "power3.out" }); + + // Stats and section tabs are data-driven. Wait until app.js has rendered + // them so GSAP never tries to animate missing targets on first load. + document.addEventListener("aiRadar:ready", function () { + const tl = gsap.timeline(); + const addFrom = function (selector, vars, position) { + if (document.querySelector(selector)) tl.from(selector, vars, position); + }; + // Keep the identity header stationary across view switches. The update + // time and view control live inside `.hero-headline`, so animating that + // container makes the control visibly jump after navigation. + addFrom(".stat", { autoAlpha: 0, y: 14, scale: 0.98, stagger: 0.06, duration: 0.45 }); + addFrom(".section-tab", { autoAlpha: 0, y: 10, stagger: 0.045, duration: 0.4 }, "-=0.2"); + addFrom(".section-summary", { autoAlpha: 0, y: 8, duration: 0.35 }, "-=0.25"); + addFrom(".primary-controls", { autoAlpha: 0, y: 8, duration: 0.4 }, "-=0.15"); + addFrom(".advanced-panel", { autoAlpha: 0, y: 8, duration: 0.4 }, "-=0.3"); + }, { once: true }); + + // Top stories render after data loads; keep legacy selectors for old data views. + document.addEventListener("aiRadar:briefRendered", function () { + const brief = document.querySelector(".bole-picks-wrap"); + const cards = Array.from(document.querySelectorAll(".top-story-card, .story-row, .bole-row")).slice(0, 24); + if (brief) { + gsap.fromTo(brief, { y: 12 }, { y: 0, duration: 0.35, clearProps: "transform" }); + } + if (!cards.length) return; + gsap.killTweensOf(cards); + gsap.set(cards, { clearProps: "transform" }); + gsap.from(cards, { autoAlpha: 0, stagger: 0.035, duration: 0.28, clearProps: "opacity,visibility" }); + }); + + // List: animate first 30 visible cards on render/mode switch + document.addEventListener("aiRadar:listRendered", function () { + const cards = Array.from(document.querySelectorAll(".intel-card, .news-card")).slice(0, 30); + if (!cards.length) return; + gsap.from(cards, { autoAlpha: 0, y: 12, stagger: 0.03, duration: 0.4, clearProps: "transform,opacity,visibility" }); + }); + + // Section scroll reveal via IntersectionObserver. Keep sections visible: + // hiding whole content blocks can leave blank viewports after responsive + // reflow or rapid mobile scrolling. + const revealEls = document.querySelectorAll(".bole-picks-wrap, .waytoagi-wrap, .list-wrap"); + if (revealEls.length && window.IntersectionObserver) { + gsap.set(revealEls, { y: 14 }); + const observer = new IntersectionObserver(function (entries) { + entries.forEach(function (entry) { + if (entry.isIntersecting) { + gsap.to(entry.target, { y: 0, duration: 0.45, clearProps: "transform" }); + observer.unobserve(entry.target); + } + }); + }, { threshold: 0.08 }); + revealEls.forEach(function (el) { observer.observe(el); }); + } + }); +}()); diff --git a/skills/ai-news-radar/classic/assets/styles.css b/skills/ai-news-radar/classic/assets/styles.css new file mode 100644 index 0000000..f785d60 --- /dev/null +++ b/skills/ai-news-radar/classic/assets/styles.css @@ -0,0 +1,2784 @@ +:root { + --bg: #f6f6f2; + --bg-alt: #eeecea; + --surface: #ffffff; + --surface-soft: #fbfaf7; + --surface-alt: #f4f2ef; + --ink: #171717; + --ink-soft: #3f3d39; + --muted: #66645f; + --muted-soft: #8b8780; + --line: #d9d6ce; + --line-soft: rgba(23, 23, 23, 0.08); + --accent: #126a73; + --accent-warm: #b55231; + --good: #1f7a4d; + --warn: #9a6700; + --bad: #b42318; + --radius: 8px; +} + +* { + box-sizing: border-box; +} + +html, +body { + margin: 0; + min-height: 100%; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans SC", "Microsoft YaHei", sans-serif; + color: var(--ink); + background: var(--bg); +} + +button, +input, +select { + font: inherit; +} + +button { + cursor: pointer; +} + +.shell { + max-width: 1160px; + margin: 0 auto; + padding: 30px 18px 56px; +} + +.hero { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: 18px 28px; + padding-bottom: 14px; + border-bottom: 1px solid var(--line-soft); +} + +.hero-main { + min-width: 0; +} + +.hero-headline { + display: flex; + gap: 14px; + align-items: center; +} + +.hero-headline > div { + min-width: 0; +} + +.hero-logo { + width: 48px; + height: 48px; + border: 1px solid rgba(18, 106, 115, 0.16); + border-radius: var(--radius); + background: var(--surface); +} + +.hero-tag { + margin: 0; + font-size: 12px; + letter-spacing: 0; + color: var(--muted); + font-weight: 720; +} + +.hero h1 { + margin: 4px 0 0; + font-size: 38px; + line-height: 1.08; + overflow-wrap: break-word; +} + +.hero-meta { + align-self: start; + display: grid; + gap: 6px; + min-width: 178px; + padding: 0; + border: 0; + border-radius: var(--radius); + background: transparent; + justify-items: end; + text-align: right; +} + +.updated-label { + color: var(--muted); + font-size: 12px; +} + +.updated { + color: var(--ink); + font-size: 13px; + font-weight: 700; +} + +.source-status-pill { + display: inline-flex; + width: max-content; + max-width: 100%; + align-items: center; + gap: 6px; + border: 1px solid rgba(31, 122, 77, 0.18); + border-radius: 999px; + padding: 5px 9px; + color: var(--good); + background: rgba(31, 122, 77, 0.07); + font-size: 12px; + font-weight: 740; +} + +.source-status-pill.warn { + color: var(--warn); + border-color: rgba(154, 103, 0, 0.22); + background: rgba(154, 103, 0, 0.08); +} + +.source-status-pill.bad { + color: var(--bad); + border-color: rgba(180, 35, 24, 0.22); + background: rgba(180, 35, 24, 0.07); +} + +.hero-links { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 6px; + margin-top: 4px; +} + +.hero-link { + display: inline-flex; + align-items: center; + justify-content: center; + min-height: 30px; + border: 1px solid rgba(18, 106, 115, 0.2); + border-radius: 999px; + padding: 5px 10px; + color: var(--accent); + background: rgba(18, 106, 115, 0.06); + font-size: 12px; + font-weight: 740; + line-height: 1; + text-decoration: none; + white-space: nowrap; +} + +.hero-link:hover { + border-color: rgba(18, 106, 115, 0.36); + background: rgba(18, 106, 115, 0.1); +} + +.stats { + grid-column: 1 / -1; + display: flex; + min-width: 0; + flex-wrap: nowrap; + align-items: center; + gap: clamp(6px, 1.2vw, 14px); + margin-top: 2px; + border: 1px solid rgba(18, 106, 115, 0.12); + border-radius: var(--radius); + padding: 10px 14px; + background: rgba(255, 255, 255, 0.58); + overflow: hidden; + white-space: nowrap; +} + +.section-nav-wrap { + grid-column: 1 / -1; + display: grid; + gap: 10px; + padding-top: 2px; +} + +.section-tabs { + display: flex; + gap: 4px; + align-items: center; + overflow-x: auto; + scrollbar-width: none; + -webkit-overflow-scrolling: touch; + border: 1px solid var(--line-soft); + border-radius: var(--radius); + padding: 4px; + background: rgba(255, 255, 255, 0.52); +} + +.section-tabs::-webkit-scrollbar { + display: none; +} + +.section-tab { + flex: 0 0 auto; + min-height: 40px; + display: inline-flex; + align-items: center; + gap: 8px; + border: 1px solid transparent; + border-radius: var(--radius); + padding: 0 11px; + color: var(--muted); + background: transparent; + font-size: 13px; +} + +.section-tab span, +.section-tab strong { + line-height: 1; + white-space: nowrap; +} + +.section-tab strong { + min-width: 22px; + border-radius: 999px; + padding: 3px 6px; + color: var(--accent); + background: transparent; + font-size: 11px; + text-align: center; +} + +.section-tab.active { + color: #fff; + border-color: var(--accent); + background: var(--accent); + font-weight: 780; +} + +.section-tab.active strong { + color: var(--accent); + background: #fff; +} + +.section-summary { + min-width: 0; + border: 0; + border-radius: 0; + padding: 0 2px; + color: var(--muted); + background: transparent; + font-size: 13px; + line-height: 1.45; + overflow-wrap: anywhere; +} + +.stat { + min-width: 0; + display: inline-flex; + flex: 0 1 auto; + align-items: center; + gap: 4px; + border: 0; + background: transparent; + border-radius: 0; + padding: 0; +} + +.stat-prefix { + flex: 0 0 auto; + color: var(--ink); + font-size: clamp(13px, 1.35vw, 15px); + line-height: 1; + font-weight: 780; + white-space: nowrap; +} + +.stat .k { + font-size: 12px; + line-height: 1; + color: var(--muted); + white-space: nowrap; +} + +.stat .v { + margin-top: 0; + font-size: clamp(15px, 1.65vw, 19px); + line-height: 1; + font-weight: 820; + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.stat + .stat::before { + content: "·"; + color: var(--muted-soft); + margin-right: 0; +} + +.coverage-strip { + grid-column: 1 / -1; + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 8px; + padding: 0 12px 12px; +} + +.coverage-card { + min-width: 0; + display: grid; + gap: 4px; + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 10px 11px; + background: var(--surface-soft); +} + +.coverage-card strong { + min-width: 0; + color: var(--ink); + font-size: 17px; + line-height: 1.15; + overflow-wrap: anywhere; +} + +.coverage-label, +.coverage-meta { + min-width: 0; + color: var(--muted); + font-size: 11px; + line-height: 1.3; + overflow-wrap: anywhere; +} + +.coverage-card.ok strong { + color: var(--good); +} + +.coverage-card.warn strong { + color: var(--warn); +} + +.coverage-card.signal { + border-color: rgba(18, 106, 115, 0.3); +} + +.coverage-card.official { + border-color: rgba(31, 122, 77, 0.28); +} + +.coverage-card.builders { + border-color: rgba(181, 82, 49, 0.32); +} + +.coverage-card.creator { + border-color: rgba(135, 72, 96, 0.3); +} + +.coverage-card.aggregate { + border-color: rgba(102, 100, 95, 0.32); +} + +.coverage-card.private { + border-color: rgba(154, 103, 0, 0.3); +} + +.primary-controls { + margin-top: 14px; + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: 12px; + align-items: center; +} + +input, +select { + width: 100%; + border: 1px solid var(--line); + background: var(--surface); + color: var(--ink); + border-radius: var(--radius); + padding: 11px 12px; + font-size: 14px; +} + +input:focus, +select:focus, +button:focus-visible, +summary:focus-visible { + outline: 2px solid rgba(18, 106, 115, 0.35); + outline-offset: 2px; +} + +.mode-hint { + color: var(--muted); + font-size: 13px; + white-space: nowrap; +} + +.sticky-summary-bar { + position: sticky; + z-index: 9; + top: 0; + display: flex; + min-width: 0; + align-items: center; + justify-content: space-between; + gap: 12px; + margin: 12px -2px 0; + border: 1px solid rgba(23, 23, 23, 0.08); + border-radius: var(--radius); + padding: 8px 10px; + color: var(--muted); + background: rgba(246, 246, 242, 0.88); + backdrop-filter: blur(12px); + font-size: 12px; +} + +.sticky-summary-bar strong { + flex: 0 0 auto; + color: var(--ink); + font-size: 12px; +} + +.sticky-summary-bar span { + min-width: 0; + overflow: hidden; + text-align: right; + text-overflow: ellipsis; + white-space: nowrap; +} + +.advanced-panel { + margin-top: 12px; + border: 1px solid rgba(23, 23, 23, 0.08); + border-radius: var(--radius); + background: rgba(251, 250, 247, 0.66); +} + +.advanced-panel > summary { + position: relative; + display: flex; + justify-content: space-between; + gap: 12px; + align-items: center; + padding: 11px 14px 11px 40px; + color: var(--ink); + font-size: 14px; + font-weight: 700; + list-style: none; + cursor: pointer; +} + +.advanced-panel:not([open]) > summary { + color: var(--muted); + font-weight: 650; +} + +.advanced-panel > summary::-webkit-details-marker { + display: none; +} + +.advanced-panel > summary::before { + content: "+"; + width: 18px; + height: 18px; + position: absolute; + left: 14px; + top: 50%; + transform: translateY(-50%); + display: grid; + place-items: center; + border: 1px solid var(--line); + border-radius: 50%; + color: var(--muted); + font-weight: 700; +} + +.advanced-panel > summary > span:first-child { + min-width: 0; +} + +.advanced-panel[open] > summary::before { + content: "-"; +} + +.advanced-summary { + color: var(--muted); + font-size: 12px; + font-weight: 400; + white-space: nowrap; +} + +.advanced-content { + display: grid; + gap: 14px; + padding: 0 14px 14px; + border-top: 1px solid var(--line-soft); +} + +.advanced-controls { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 10px; + align-items: end; + padding-top: 14px; +} + +.field { + display: grid; + gap: 6px; + color: var(--muted); + font-size: 12px; +} + +.mode-switch { + display: inline-flex; + border: 1px solid var(--line); + border-radius: var(--radius); + overflow: hidden; + background: var(--surface-soft); +} + +.mode-btn { + min-height: 40px; + border: 0; + border-left: 1px solid var(--line); + background: transparent; + color: var(--muted); + padding: 0 13px; + font-size: 13px; +} + +.mode-btn:first-child { + border-left: 0; +} + +.mode-btn.active { + background: var(--accent); + color: #fff; + font-weight: 700; +} + +.all-dedupe { + display: none; + min-height: 40px; + align-items: center; + gap: 8px; + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 0 12px; + font-size: 13px; + color: var(--muted); + background: var(--surface-soft); + cursor: pointer; + user-select: none; +} + +.all-dedupe.show { + display: inline-flex; +} + +.all-dedupe input { + position: absolute; + opacity: 0; + width: 0; + height: 0; +} + +.all-dedupe-dot { + width: 12px; + height: 12px; + border-radius: 50%; + border: 1px solid rgba(23, 23, 23, 0.25); + background: rgba(23, 23, 23, 0.16); +} + +.all-dedupe input:checked + .all-dedupe-dot { + border-color: rgba(18, 106, 115, 0.65); + background: var(--accent); +} + +.source-health { + display: grid; + gap: 10px; +} + +.source-health-summary { + display: flex; + min-width: 0; + align-items: center; + justify-content: space-between; + gap: 12px; + border: 1px solid rgba(31, 122, 77, 0.16); + border-radius: var(--radius); + padding: 11px 12px; + color: var(--muted); + background: rgba(31, 122, 77, 0.05); + font-size: 13px; + line-height: 1.4; +} + +.source-health-summary strong { + color: var(--good); + font-size: 15px; +} + +.source-health-summary.warn { + border-color: rgba(154, 103, 0, 0.2); + background: rgba(154, 103, 0, 0.07); +} + +.source-health-summary.warn strong { + color: var(--warn); +} + +.source-health-summary.bad { + border-color: rgba(180, 35, 24, 0.22); + background: rgba(180, 35, 24, 0.06); +} + +.source-health-summary.bad strong { + color: var(--bad); +} + +.source-detail-panel { + border: 1px solid var(--line-soft); + border-radius: var(--radius); + background: rgba(255, 255, 255, 0.48); + overflow: hidden; +} + +.source-detail-panel > summary { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + padding: 10px 12px; + color: var(--accent); + font-size: 13px; + font-weight: 760; + cursor: pointer; + list-style: none; +} + +.source-detail-panel > summary::-webkit-details-marker { + display: none; +} + +.source-detail-panel > summary::after { + content: "+"; + color: var(--muted); + font-weight: 800; +} + +.source-detail-panel[open] > summary::after { + content: "-"; +} + +.source-health-details { + display: grid; + gap: 10px; + padding: 0 12px 12px; +} + +.health-grid { + display: grid; + grid-template-columns: repeat(6, minmax(0, 1fr)); + gap: 8px; +} + +.health-metric { + display: grid; + gap: 3px; + min-width: 0; + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 9px 10px; + background: var(--surface-soft); +} + +.health-metric-button { + width: 100%; + color: inherit; + font: inherit; + text-align: left; + cursor: pointer; +} + +.health-metric-button:hover, +.health-metric-button:focus-visible { + border-color: var(--accent); + outline: none; +} + +.health-metric strong { + font-size: 18px; +} + +.health-label { + color: var(--muted); + font-size: 12px; +} + +.health-metric.ok strong { + color: var(--good); +} + +.health-metric.warn strong { + color: var(--warn); +} + +.health-metric.bad strong { + color: var(--bad); +} + +.health-empty, +.health-ok { + border: 1px dashed var(--line); + border-radius: var(--radius); + padding: 10px 12px; + color: var(--muted); + font-size: 13px; +} + +.health-ok { + color: var(--good); + border-style: solid; + background: rgba(31, 122, 77, 0.06); +} + +.health-issues { + display: grid; + gap: 8px; +} + +.health-author-list { + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 10px 12px; + background: var(--surface-soft); +} + +.health-author-list-title { + font-size: 13px; + font-weight: 700; +} + +.health-author-list-meta { + margin-top: 3px; + color: var(--muted); + font-size: 12px; +} + +.health-author-list-items { + display: flex; + max-height: 220px; + margin-top: 9px; + gap: 6px; + overflow: auto; + flex-wrap: wrap; + align-content: flex-start; +} + +.health-author-list-items button { + border: 1px solid var(--line); + border-radius: 999px; + padding: 3px 7px; + color: var(--ink-soft); + background: var(--surface); + font: inherit; + font-size: 12px; + line-height: 1.25; + cursor: pointer; +} + +.health-author-list-items button:hover, +.health-author-list-items button:focus-visible { + border-color: var(--accent); + color: var(--accent); + outline: none; +} + +.health-issue { + border: 1px solid rgba(180, 35, 24, 0.22); + border-radius: var(--radius); + padding: 10px 12px; + background: rgba(180, 35, 24, 0.04); +} + +.health-issue-title { + color: var(--bad); + font-size: 13px; + font-weight: 700; +} + +.health-issue ul { + margin: 7px 0 0; + padding-left: 18px; + color: var(--muted); + font-size: 12px; + line-height: 1.45; +} + +.source-status-table { + padding: 0 12px 12px; +} + +.source-table { + display: grid; + border: 1px solid var(--line-soft); + border-radius: var(--radius); + overflow: hidden; + background: var(--surface); +} + +.source-table-row { + display: grid; + grid-template-columns: minmax(160px, 1.4fr) minmax(96px, 0.8fr) minmax(64px, 0.5fr) minmax(56px, 0.4fr); + gap: 10px; + align-items: center; + border-top: 1px solid var(--line-soft); + padding: 9px 10px; + color: var(--muted); + font-size: 12px; +} + +.source-table-row:first-child { + border-top: 0; +} + +.source-table-head { + color: var(--ink-soft); + background: rgba(246, 246, 242, 0.74); + font-weight: 780; +} + +.source-table-row span { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.source-table-row .ok { + color: var(--good); + font-weight: 760; +} + +.source-table-row .bad { + color: var(--bad); + font-weight: 760; +} + +.site-pills { + display: flex; + flex-wrap: wrap; + gap: 8px; + padding: 0 12px 12px; +} + +.pill { + border: 1px solid var(--line); + background: var(--surface-soft); + color: var(--ink); + border-radius: 999px; + padding: 6px 11px; + cursor: pointer; + font-size: 12px; +} + +.pill.active { + background: rgba(18, 106, 115, 0.11); + border-color: rgba(18, 106, 115, 0.5); + color: var(--accent); + font-weight: 700; +} + +.bole-picks-wrap, +.list-wrap, +.waytoagi-wrap { + margin-top: 18px; + border: 1px solid var(--line-soft); + border-radius: var(--radius); + background: var(--surface); + overflow: hidden; +} + +.list-wrap { + background: var(--surface); +} + +/* 双色交替:WaytoAGI 版块用深一档的底色,与伯乐精选 / AI信号流形成节奏感 */ +.waytoagi-wrap { + background: var(--bg-alt); + border-color: rgba(23, 23, 23, 0.12); +} + +.bole-picks-head, +.list-head, +.waytoagi-head { + padding: 16px 18px; + display: flex; + flex-wrap: nowrap; + justify-content: space-between; + align-items: center; + gap: 12px; + border-bottom: 1px solid var(--line-soft); + background: var(--surface); +} + +/* WaytoAGI header 用对应的深档底色 */ +.waytoagi-head { + background: var(--surface-alt); + border-bottom-color: rgba(23, 23, 23, 0.1); +} + +.bole-picks-head h2, +.list-head h2, +.waytoagi-head h2 { + margin: 0; + font-size: 22px; +} + +#bolePicksMeta, +#resultCount, +#waytoagiUpdatedAt { + color: var(--muted); + font-size: 13px; + white-space: nowrap; +} + +#bolePicksMeta { + display: none; +} + +.list-head-tools { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 10px; + min-width: 0; + flex-wrap: wrap; +} + +.list-sort-tools { + display: inline-flex; + max-width: 100%; + border: 1px solid var(--line); + border-radius: var(--radius); + overflow: hidden; + background: var(--surface); +} + +.list-sort-btn { + min-height: 32px; + border: 0; + border-left: 1px solid var(--line); + padding: 0 10px; + background: transparent; + color: var(--muted); + cursor: pointer; + font-size: 12px; + white-space: nowrap; +} + +.list-sort-btn:first-child { + border-left: 0; +} + +.list-sort-btn.active { + background: var(--accent); + color: #fff; + font-weight: 780; +} + +.section-eyebrow { + margin: 0 0 4px; + color: var(--accent); + font-size: 11px; + font-weight: 800; + letter-spacing: 0.1em; +} + +.bole-picks-wrap { + position: relative; + border-color: var(--line); + background: var(--surface); + box-shadow: none; +} + +.bole-picks-head { + position: relative; + border-bottom-color: var(--line); + background: var(--surface-soft); +} + +.bole-picks-head > div:first-child { + flex: 0 0 auto; + min-width: max-content; +} + +.bole-picks-head h2 { + font-size: 20px; + letter-spacing: 0; + white-space: nowrap; +} + +.bole-head-tools { + display: flex; + align-items: center; + gap: 10px; + min-width: 0; + flex-wrap: nowrap; + justify-content: flex-end; + flex: 1 1 auto; + overflow: hidden; +} + +.bole-view-toggle { + flex: 0 0 auto; + display: flex; + border: 1px solid var(--line); + border-radius: var(--radius); + overflow: hidden; + background: var(--surface); +} + +.bole-view-toggle .mode-btn { + min-height: 32px; + font-size: 12.5px; + cursor: pointer; +} + +.bole-view-toggle[hidden] { + display: none; +} + +.bole-more-btn, +.list-more-btn { + display: block; + width: calc(100% - 32px); + margin: 0 16px 16px; + border: 1px solid var(--line); + border-radius: var(--radius); + background: var(--surface); + color: var(--accent); + cursor: pointer; + font-size: 13px; + font-weight: 760; + min-height: 38px; +} + +.bole-more-btn:hover, +.list-more-btn:hover { + border-color: rgba(18, 106, 115, 0.38); + background: rgba(18, 106, 115, 0.06); +} + +.list-more-btn { + margin-top: 12px; +} + +.bole-board { + display: grid; + grid-template-columns: minmax(320px, 1.02fr) minmax(360px, 0.98fr); + gap: 12px; + padding: 14px 16px 16px; +} + +.bole-lead-wrap { + position: relative; + min-width: 0; +} + +.bole-ribbon { + position: absolute; + z-index: 2; + top: 12px; + left: 12px; + border: 1px solid rgba(18, 106, 115, 0.22); + border-radius: 999px; + padding: 4px 8px; + color: var(--accent); + background: rgba(255, 255, 255, 0.9); + font-size: 11px; + font-weight: 800; +} + +.bole-lead-card { + min-height: 220px; + height: 100%; + display: grid; + align-content: start; + gap: 12px; + padding: 72px 18px 18px; + border: 1px solid rgba(18, 106, 115, 0.2); + border-radius: var(--radius); + color: var(--ink); + text-decoration: none; + background: linear-gradient(180deg, #ffffff 0%, var(--surface-soft) 100%); + transition: border-color 180ms ease, background 180ms ease; +} + +.bole-lead-card:hover { + border-color: rgba(18, 106, 115, 0.5); + background: #fff; +} + +.bole-lead-top { + position: absolute; + top: 13px; + right: 13px; + left: 13px; + display: flex; + justify-content: space-between; + gap: 12px; + align-items: flex-start; +} + +.bole-kicker { + max-width: calc(100% - 76px); + color: var(--muted); + font-size: 12px; + line-height: 1.35; +} + +.bole-score-orb { + width: 58px; + height: 58px; + flex: 0 0 auto; + display: grid; + place-items: center; + border: 1px solid rgba(18, 106, 115, 0.24); + border-radius: 50%; + color: var(--accent); + background: rgba(18, 106, 115, 0.08); +} + +.bole-score-orb span { + margin-top: 6px; + font-size: 20px; + line-height: 1; + font-weight: 900; +} + +.bole-score-orb small { + margin-top: -13px; + font-size: 10px; + opacity: 0.82; +} + +.bole-lead-title { + max-width: 96%; + font-size: clamp(21px, 2.35vw, 28px); + line-height: 1.2; + letter-spacing: -0.035em; + font-weight: 820; + overflow-wrap: anywhere; +} + +.bole-lead-reason { + max-width: 76ch; + color: var(--muted); + font-size: 13px; + line-height: 1.5; +} + +.bole-lead-foot { + display: flex; + flex-wrap: wrap; + gap: 7px; +} + +.bole-lead-foot span, +.bole-row-meta > span, +.bole-row-meta > strong { + border: 1px solid var(--line); + border-radius: 999px; + padding: 3px 7px; + background: var(--surface); + color: var(--muted); + font-size: 11px; + line-height: 1.2; +} + +.bole-side-list { + position: relative; + display: grid; + gap: 8px; + min-width: 0; +} + +.bole-side-list::before { + content: ""; + position: absolute; + top: 8px; + bottom: 8px; + left: 76px; + width: 1px; + background: rgba(18, 106, 115, 0.22); +} + +.bole-row { + position: relative; + display: grid; + grid-template-columns: 62px minmax(0, 1fr); + gap: 22px; + align-items: stretch; + color: var(--ink); + text-decoration: none; +} + +.bole-row::before { + content: ""; + position: absolute; + left: 72px; + top: 18px; + z-index: 1; + width: 9px; + height: 9px; + border: 2px solid var(--accent); + border-radius: 50%; + background: var(--surface); +} + +.bole-row-time { + padding-top: 11px; + color: var(--muted); + font-size: 11px; + line-height: 1.25; + text-align: right; +} + +.bole-row-body { + min-width: 0; + display: grid; + gap: 6px; + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 10px 11px; + background: var(--surface-soft); + transition: border-color 160ms ease, background 160ms ease; +} + +.bole-row:hover .bole-row-body { + border-color: rgba(18, 106, 115, 0.42); + background: #fff; +} + +.bole-row-meta { + display: flex; + flex-wrap: wrap; + gap: 6px; + align-items: center; +} + +.bole-row-meta > strong { + color: var(--accent); + background: rgba(18, 106, 115, 0.08); +} + +.bole-row-meta .source-hit { + font-weight: 720; +} + +.bole-row-title { + color: var(--ink); + font-size: 14px; + font-weight: 760; + line-height: 1.42; + overflow-wrap: anywhere; +} + +.bole-row-reason { + color: var(--muted); + font-size: 12px; + line-height: 1.4; + overflow: hidden; + display: -webkit-box; + -webkit-line-clamp: 1; + -webkit-box-orient: vertical; +} + +.bole-empty { + grid-column: 1 / -1; + border: 1px dashed var(--line); + border-radius: var(--radius); + padding: 14px; + color: var(--muted); + font-size: 13px; +} + +.bole-board { + display: block; + padding: 12px 16px 16px; +} + +.top-stories-grid { + display: grid; + grid-template-columns: minmax(0, 1.15fr) minmax(300px, 0.85fr); + gap: 12px; + align-items: stretch; + padding: 14px 18px 18px; +} + +.top-stories-grid > .top-story-card.lead { + grid-row: span 2; +} + +.bole-story-panel { + grid-column: 1 / -1; + display: grid; + gap: 10px; + margin-top: 2px; + border-top: 1px solid var(--line); + padding-top: 12px; +} + +.bole-story-panel-head { + color: var(--muted); + font-size: 12px; + font-weight: 760; +} + +.top-story-card { + position: relative; + min-width: 0; + display: flex; + flex-direction: column; + gap: 11px; + min-height: 0; + border: 1px solid var(--line-soft); + border-radius: var(--radius); + padding: 15px; + color: var(--ink); + background: #fff; + text-decoration: none; + transition: border-color 160ms ease, background 160ms ease, transform 0.18s ease, box-shadow 0.18s ease; +} + +.top-story-card.lead { + min-height: 350px; + padding: 20px; + border-color: rgba(18, 106, 115, 0.22); + background: linear-gradient(180deg, #fff 0%, rgba(18, 106, 115, 0.035) 100%); +} + +.top-story-card:hover { + border-color: rgba(18, 106, 115, 0.42); + background: #fff; +} + +.top-rank, +.source-count { + width: max-content; + border: 1px solid rgba(18, 106, 115, 0.26); + border-radius: 999px; + padding: 3px 7px; + color: var(--accent); + background: rgba(18, 106, 115, 0.07); + font-size: 11px; + font-weight: 840; +} + +.intel-meta, +.intel-card-meta { + display: flex; + flex-wrap: wrap; + gap: 7px; + align-items: center; + color: var(--muted); + font-size: 12px; +} + +.intel-meta strong, +.intel-score { + color: var(--accent); +} + +.intel-meta .source-chip { + border: 1px solid var(--line); + border-radius: 999px; + padding: 3px 7px; + background: rgba(255, 255, 255, 0.72); + font-size: 11px; + line-height: 1.25; +} + +.top-story-title, +.intel-title { + color: var(--ink); + font-weight: 790; + line-height: 1.38; + letter-spacing: 0; + overflow-wrap: anywhere; +} + +.top-story-title { + display: -webkit-box; + font-size: 18px; + min-height: 0; + overflow: hidden; + -webkit-line-clamp: 3; + -webkit-box-orient: vertical; +} + +.top-story-card.lead .top-story-title { + font-size: 25px; + line-height: 1.24; + -webkit-line-clamp: 4; +} + +.top-story-summary, +.intel-reason { + margin: 0; + color: var(--muted); + font-size: 13px; + line-height: 1.48; + overflow-wrap: anywhere; +} + +.top-story-summary { + display: -webkit-box; + min-height: 0; + overflow: hidden; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; +} + +.top-story-card.lead .top-story-summary { + font-size: 14px; + -webkit-line-clamp: 3; +} + +.top-story-why { + display: grid; + gap: 5px; + border-left: 2px solid rgba(18, 106, 115, 0.28); + padding-left: 10px; +} + +.top-story-why span { + color: var(--ink); + font-size: 12px; + font-weight: 820; +} + +.top-story-why p { + margin: 0; + color: var(--muted); + font-size: 13px; + line-height: 1.5; +} + +.top-story-card.secondary .top-story-why p { + display: -webkit-box; + overflow: hidden; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; +} + +.intel-tags, +.intel-card-sources, +.intel-sources { + display: flex; + flex-wrap: wrap; + gap: 6px; + align-items: center; +} + +.signal-tag, +.intel-tags > span, +.intel-card-sources > span, +.intel-card-sources > strong, +.intel-sources { + border: 1px solid var(--line); + border-radius: 999px; + padding: 3px 7px; + color: var(--muted); + background: rgba(255, 255, 255, 0.72); + font-size: 11px; + line-height: 1.25; +} + +.intel-tags > span { + color: var(--accent); + border-color: rgba(18, 106, 115, 0.22); + background: rgba(18, 106, 115, 0.07); + font-weight: 720; +} + +.signal-tag.tone-official, +.ai-tag.tone-official { + color: var(--good); + border-color: rgba(31, 122, 77, 0.32); + background: rgba(31, 122, 77, 0.08); +} + +.signal-tag.tone-hot, +.ai-tag.tone-hot, +.signal-tag.tone-community, +.ai-tag.tone-community { + color: var(--accent-warm); + border-color: rgba(181, 82, 49, 0.32); + background: rgba(181, 82, 49, 0.08); +} + +.signal-tag.tone-models, +.ai-tag.tone-models { + color: #2a658a; + border-color: rgba(42, 101, 138, 0.3); + background: rgba(42, 101, 138, 0.08); +} + +.signal-tag.tone-devtools, +.ai-tag.tone-devtools { + color: var(--accent); + border-color: rgba(18, 106, 115, 0.28); + background: rgba(18, 106, 115, 0.08); +} + +.signal-tag.tone-aggregate, +.ai-tag.tone-aggregate { + color: #5f6b75; + border-color: rgba(95, 107, 117, 0.28); + background: rgba(95, 107, 117, 0.08); +} + +.signal-tag.tone-research, +.ai-tag.tone-research { + color: #6b568f; + border-color: rgba(107, 86, 143, 0.3); + background: rgba(107, 86, 143, 0.08); +} + +.signal-tag.tone-products, +.ai-tag.tone-products { + color: #8a5b20; + border-color: rgba(138, 91, 32, 0.3); + background: rgba(138, 91, 32, 0.08); +} + +.signal-tag.tone-creator, +.ai-tag.tone-creator { + color: #874860; + border-color: rgba(135, 72, 96, 0.3); + background: rgba(135, 72, 96, 0.08); +} + +.signal-tag.tone-industry, +.ai-tag.tone-industry { + color: #5c6258; + border-color: rgba(92, 98, 88, 0.3); + background: rgba(92, 98, 88, 0.08); +} + +.signal-tag.tone-strong, +.ai-tag.tone-strong { + color: var(--good); + border-color: rgba(31, 122, 77, 0.28); + background: rgba(31, 122, 77, 0.08); +} + +.signal-tag.tone-default, +.ai-tag.tone-default { + color: var(--muted); + border-color: rgba(102, 100, 95, 0.26); + background: rgba(102, 100, 95, 0.06); +} + +.top-story-card .intel-tags { + align-items: flex-end; + align-content: flex-end; + margin-top: auto; + min-height: 28px; + max-height: 28px; + overflow: hidden; +} + +.impact-row { + display: flex; + flex-wrap: wrap; + gap: 6px; + align-items: center; + color: var(--muted); + font-size: 11px; +} + +.impact-row span { + border: 1px solid var(--line-soft); + border-radius: 999px; + padding: 3px 7px; + background: rgba(246, 246, 242, 0.72); +} + +.source-chip { + display: inline-flex; + min-width: 0; + align-items: center; + gap: 5px; +} + +.source-dot { + width: 6px; + height: 6px; + flex: 0 0 auto; + border-radius: 50%; + background: currentColor; + box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.72); +} + +.source-chip-label { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.kind-official { + color: var(--good); + border-color: rgba(31, 122, 77, 0.28); + background: rgba(31, 122, 77, 0.08); +} + +.kind-hot { + color: var(--accent-warm); + border-color: rgba(181, 82, 49, 0.3); + background: rgba(181, 82, 49, 0.08); +} + +.kind-aihub { + color: var(--accent); + border-color: rgba(18, 106, 115, 0.26); + background: rgba(18, 106, 115, 0.07); +} + +.kind-builders, +.kind-newsletter { + color: var(--warn); + border-color: rgba(154, 103, 0, 0.28); + background: rgba(154, 103, 0, 0.07); +} + +.kind-creator { + color: #874860; + border-color: rgba(135, 72, 96, 0.28); + background: rgba(135, 72, 96, 0.07); +} + +.kind-aggregate, +.kind-blogs, +.kind-default { + color: var(--muted); + border-color: rgba(102, 100, 95, 0.26); + background: rgba(102, 100, 95, 0.06); +} + +.source-chip.kind-official { + color: var(--good); + border-color: rgba(31, 122, 77, 0.28); + background: rgba(31, 122, 77, 0.08); +} + +.source-chip.kind-hot { + color: var(--accent-warm); + border-color: rgba(181, 82, 49, 0.3); + background: rgba(181, 82, 49, 0.08); +} + +.source-chip.kind-aihub { + color: var(--accent); + border-color: rgba(18, 106, 115, 0.26); + background: rgba(18, 106, 115, 0.07); +} + +.source-chip.kind-builders, +.source-chip.kind-newsletter { + color: var(--warn); + border-color: rgba(154, 103, 0, 0.28); + background: rgba(154, 103, 0, 0.07); +} + +.source-chip.kind-creator { + color: #874860; + border-color: rgba(135, 72, 96, 0.28); + background: rgba(135, 72, 96, 0.07); +} + +.source-chip.kind-aggregate, +.source-chip.kind-blogs, +.source-chip.kind-default { + color: var(--muted); + border-color: rgba(102, 100, 95, 0.26); + background: rgba(102, 100, 95, 0.06); +} + +.intel-sources { + justify-self: start; + border-radius: var(--radius); + line-height: 1.35; +} + +.news-list { + padding: 8px 18px 18px; + gap: 8px; +} + +.intel-card { + min-width: 0; + display: grid; + gap: 8px; + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 13px 14px; + background: var(--surface); + transition: transform 0.18s ease, box-shadow 0.18s ease, border-color 0.18s ease; +} + +.intel-card:hover { + border-color: rgba(18, 106, 115, 0.32); + background: #fff; +} + +.intel-card-rank { + color: var(--accent); + font-weight: 800; +} + +.intel-title { + display: block; + font-size: 16px; + text-decoration: none; +} + +.intel-title:hover { + color: var(--accent); +} + +.intel-score.hot { + color: var(--accent-warm); +} + +.intel-score.strong { + color: var(--good); +} + +.intel-card-sources { + min-width: 0; +} + +.intel-card-sources > span, +.intel-card-sources > strong { + max-width: 260px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.bole-compact-list { + position: relative; + display: grid; + grid-template-columns: 1fr; + gap: 8px; +} + +.bole-compact-list::before { + content: ""; + position: absolute; + top: 12px; + bottom: 12px; + left: 82px; + width: 1px; + background: rgba(18, 106, 115, 0.22); +} + +.bole-compact-list .bole-row { + grid-template-columns: 68px minmax(0, 1fr); + gap: 28px; +} + +.bole-compact-list .bole-row::before { + display: block; + left: 76px; + top: 18px; +} + +.bole-compact-list .bole-row-time { + padding-top: 10px; + text-align: right; +} + +.bole-compact-list .bole-row-body { + min-height: 0; + background: var(--surface-soft); +} + +.bole-fallback-note { + border: 1px dashed rgba(18, 106, 115, 0.28); + border-radius: 14px; + padding: 10px 12px; + color: var(--muted); + background: rgba(18, 106, 115, 0.05); + font-size: 13px; + line-height: 1.5; +} + +.bole-timeline { + gap: 10px; +} + +.story-row { + position: relative; + display: grid; + grid-template-columns: 78px minmax(0, 1fr); + gap: 26px; + color: var(--ink); + text-decoration: none; +} + +.story-row::before { + content: ""; + position: absolute; + z-index: 1; + top: 18px; + left: 77px; + width: 10px; + height: 10px; + border: 2px solid var(--accent); + border-radius: 50%; + background: var(--surface); +} + +.story-time { + display: grid; + align-content: start; + gap: 4px; + padding-top: 10px; + color: var(--muted); + font-size: 11px; + line-height: 1.25; + text-align: right; +} + +.story-time-label { + color: var(--muted); + font-size: 10px; + font-weight: 760; +} + +.story-time-latest { + color: var(--ink); + font-weight: 750; +} + +.story-time-range { + opacity: 0.78; +} + +.story-body { + min-width: 0; + display: grid; + gap: 8px; + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 12px 13px; + background: linear-gradient(180deg, #fff 0%, var(--surface-soft) 100%); + transition: border-color 160ms ease, background 160ms ease; +} + +.story-row:hover .story-body { + border-color: rgba(18, 106, 115, 0.42); + background: #fff; +} + +.story-meta, +.story-sources { + display: flex; + flex-wrap: wrap; + gap: 6px; + align-items: center; +} + +.story-importance, +.story-count, +.story-rank, +.story-source-chip, +.story-source-more { + border: 1px solid var(--line); + border-radius: 999px; + padding: 3px 7px; + color: var(--muted); + background: var(--surface); + font-size: 11px; + line-height: 1.2; +} + +.story-rank { + color: var(--accent); + border-color: rgba(18, 106, 115, 0.24); + background: rgba(18, 106, 115, 0.07); + font-weight: 820; +} + +.story-importance { + color: var(--accent); + background: rgba(18, 106, 115, 0.08); + font-weight: 800; +} + +.story-importance.hot { + border-color: rgba(181, 82, 49, 0.36); + color: var(--accent-warm); + background: rgba(181, 82, 49, 0.08); +} + +.story-importance.official { + border-color: rgba(31, 122, 77, 0.36); + color: var(--good); + background: rgba(31, 122, 77, 0.08); +} + +.story-importance.strong { + border-color: rgba(18, 106, 115, 0.36); +} + +.story-score { + margin-left: auto; + display: inline-flex; + align-items: baseline; + gap: 2px; + color: var(--accent); + font-weight: 900; +} + +.story-score.heat { + color: var(--accent-warm); +} + +.story-score small { + color: var(--muted); + font-size: 10px; + font-weight: 700; +} + +.story-title { + display: grid; + gap: 3px; + color: var(--ink); + font-size: 15px; + font-weight: 790; + line-height: 1.42; + letter-spacing: 0; + overflow-wrap: anywhere; +} + +.story-title-en { + color: var(--muted); + font-size: 12px; + font-weight: 560; + line-height: 1.35; +} + +.story-sources { + gap: 5px; +} + +.story-source-chip { + max-width: 180px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + background: rgba(255, 255, 255, 0.72); +} + +.story-source-chip.kind-official { + color: var(--good); + border-color: rgba(31, 122, 77, 0.26); +} + +.story-source-chip.kind-newsletter, +.story-source-chip.kind-builders { + color: var(--warn); + border-color: rgba(154, 103, 0, 0.26); +} + +.story-source-chip.kind-creator { + color: #874860; + border-color: rgba(135, 72, 96, 0.26); +} + +.story-source-more { + color: var(--accent); + font-weight: 760; +} + +.news-list, +.site-group-list, +.source-group-list { + display: grid; +} + +.group-more-btn { + display: block; + width: 100%; + padding: 9px 12px; + border: 0; + border-top: 1px dashed var(--line); + background: var(--surface-soft); + color: var(--muted); + font-size: 12.5px; + cursor: pointer; + text-align: center; +} + +.group-more-btn:hover { + color: var(--ink); + background: var(--surface); +} + +.site-group { + min-width: 0; + border-top: 1px solid rgba(23, 23, 23, 0.07); + /* Isolate layout recalculation to within each site group */ + contain: content; +} + +.site-group:first-child { + border-top: 0; +} + +.list-loading { + padding: 18px 16px; + color: var(--muted); + font-size: 13px; + background: var(--surface-soft); +} + +.site-group-head, +.source-group-head { + display: flex; + justify-content: space-between; + align-items: center; + gap: 10px; + padding: 11px 12px; + border-bottom: 1px solid rgba(23, 23, 23, 0.06); +} + +.site-group-head { + background: transparent; +} + +.source-group-head { + background: rgba(246, 246, 242, 0.72); +} + +.site-group-head h3, +.source-group-head h3 { + margin: 0; + min-width: 0; +} + +.site-group-head h3 { + font-size: 16px; +} + +.source-group-head h3 { + font-size: 14px; +} + +.site-group-head span, +.source-group-head span { + color: var(--muted); + font-size: 12px; + white-space: nowrap; +} + +.group-summary { + font-variant-numeric: tabular-nums; +} + +.group-more-btn:focus-visible, +.list-more-btn:focus-visible { + outline: 2px solid var(--accent); + outline-offset: -2px; +} + +.source-group { + min-width: 0; + border-top: 1px solid rgba(23, 23, 23, 0.06); +} + +.source-group:first-child { + border-top: 0; +} + +.news-card { + min-width: 0; + padding: 13px 12px; + border-top: 1px solid rgba(23, 23, 23, 0.06); +} + +.news-card:first-child { + border-top: 0; +} + +.meta-row { + display: flex; + flex-wrap: wrap; + gap: 7px; + align-items: center; + margin-top: 7px; + color: var(--muted); + font-size: 12px; +} + +.site { + font-weight: 700; + color: #3f3d39; +} + +.category, +.source, +.ai-tag, +.meta-row .signal-tag { + padding: 2px 7px; + border: 1px solid var(--line); + border-radius: 999px; + font-size: 11px; +} + +.category { + color: var(--ink); + background: var(--surface-soft); +} + +.category.kind-official { + border-color: rgba(31, 122, 77, 0.34); + color: var(--good); +} + +.category.kind-newsletter { + border-color: rgba(154, 103, 0, 0.34); + color: var(--warn); +} + +.category.kind-builders { + border-color: rgba(181, 82, 49, 0.36); + color: var(--accent-warm); +} + +.category.kind-creator { + border-color: rgba(135, 72, 96, 0.32); + color: #874860; +} + +.category.kind-aihub { + border-color: rgba(18, 106, 115, 0.28); + color: var(--accent); +} + +.category.kind-aggregate, +.category.kind-blogs { + color: var(--muted); +} + +.ai-tag { + border-color: rgba(18, 106, 115, 0.22); + background: rgba(18, 106, 115, 0.07); + color: var(--accent); + font-weight: 650; +} + +.source.source-chip { + max-width: 220px; + font-weight: 650; +} + +.ai-tag.hot { + border-color: rgba(181, 82, 49, 0.3); + background: rgba(181, 82, 49, 0.08); + color: var(--accent-warm); +} + +.ai-tag.strong { + border-color: rgba(31, 122, 77, 0.28); + background: rgba(31, 122, 77, 0.08); + color: var(--good); +} + +.ai-tag.watch { + color: var(--muted); + background: var(--surface-soft); +} + +.time { + margin-left: auto; +} + +.title { + min-width: 0; + margin-top: 0; + display: inline-flex; + flex-direction: column; + gap: 3px; + color: var(--ink); + text-decoration: none; + font-size: 16px; + line-height: 1.42; + overflow-wrap: anywhere; +} + +.news-summary { + margin: 7px 0 0; + color: var(--muted); + font-size: 13px; + line-height: 1.45; +} + +.title-sub { + color: var(--muted); + font-size: 12px; + line-height: 1.35; + font-weight: 400; +} + +.title:hover { + color: var(--accent); +} + +.empty { + padding: 24px 16px; + color: var(--muted); + text-align: center; +} + +.waytoagi-tools { + display: inline-flex; + align-items: center; + gap: 10px; +} + +.waytoagi-switch { + display: inline-flex; + border: 1px solid var(--line); + border-radius: var(--radius); + overflow: hidden; + background: var(--surface); +} + +.waytoagi-btn { + min-height: 32px; + border: 0; + border-left: 1px solid var(--line); + background: transparent; + color: var(--muted); + padding: 0 10px; + font-size: 12px; +} + +.waytoagi-btn:first-child { + border-left: 0; +} + +.waytoagi-btn.active { + background: var(--accent); + color: #fff; + font-weight: 700; +} + +.waytoagi-meta { + padding: 12px 16px 0; + display: flex; + flex-wrap: wrap; + gap: 8px; + font-size: 12px; + color: var(--muted); +} + +.waytoagi-meta a { + color: var(--accent); + text-decoration: none; +} + +.waytoagi-list { + padding: 12px 16px 16px; + display: grid; + gap: 8px; +} + +.waytoagi-item { + min-width: 0; + display: grid; + grid-template-columns: 76px minmax(0, 1fr); + gap: 8px; + text-decoration: none; + border: 1px solid rgba(23, 23, 23, 0.08); + border-radius: var(--radius); + padding: 8px 10px; + color: var(--ink); + background: var(--surface); /* alt 版块里卡片用纯白,形成内部层次 */ +} + +.waytoagi-item .d { + color: var(--muted); + font-size: 12px; +} + +.waytoagi-item .t { + min-width: 0; + font-size: 13px; + line-height: 1.35; + overflow-wrap: anywhere; +} + +.waytoagi-empty, +.waytoagi-error { + border-radius: var(--radius); + padding: 9px 10px; + font-size: 13px; +} + +.waytoagi-empty { + border: 1px dashed var(--line); + color: var(--muted); +} + +.waytoagi-error { + border: 1px solid rgba(180, 35, 24, 0.28); + background: rgba(180, 35, 24, 0.08); + color: var(--bad); +} + +@media (max-width: 760px) { + .shell { + padding: 18px 12px 36px; + } + + .hero, + .primary-controls, + .advanced-controls, + .waytoagi-head { + grid-template-columns: 1fr; + } + + .hero { + gap: 14px; + padding-bottom: 12px; + } + + .sticky-summary-bar { + align-items: flex-start; + flex-direction: column; + } + + .sticky-summary-bar span { + width: 100%; + text-align: left; + white-space: normal; + } + + .advanced-panel > summary { + align-items: flex-start; + flex-direction: column; + } + + .hero h1 { + font-size: 30px; + } + + .hero-logo { + width: 48px; + height: 48px; + } + + .hero-meta { + display: flex; + flex-wrap: wrap; + justify-content: flex-start; + align-items: center; + gap: 8px; + min-width: 0; + text-align: left; + } + + .hero-links { + width: 100%; + justify-content: flex-start; + } + + .updated-label { + display: none; + } + + .updated { + display: inline-flex; + align-items: center; + min-height: 30px; + border: 1px solid var(--line-soft); + border-radius: 999px; + padding: 5px 10px; + background: rgba(255, 255, 255, 0.62); + font-size: 12px; + } + + .updated::before { + content: "更新"; + margin-right: 5px; + color: var(--muted); + font-weight: 650; + } + + .source-status-pill { + min-height: 30px; + padding: 5px 10px; + font-size: 12px; + } + + .coverage-strip, + .health-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .stats { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + align-items: stretch; + gap: 8px; + padding: 11px; + overflow: visible; + white-space: normal; + } + + .stat-prefix { + grid-column: 1 / -1; + font-size: 13px; + line-height: 1.2; + } + + .stat { + display: grid; + gap: 3px; + align-content: center; + border: 1px solid var(--line-soft); + border-radius: var(--radius); + padding: 8px 9px; + background: rgba(255, 255, 255, 0.62); + } + + .stat + .stat::before { + display: none; + } + + .stat .k { + font-size: 11px; + } + + .stat .v { + font-size: 16px; + } + + .section-nav-wrap { + position: sticky; + z-index: 8; + top: 0; + margin-right: -12px; + margin-left: -12px; + padding: 8px 12px; + border-top: 1px solid rgba(23, 23, 23, 0.06); + border-bottom: 1px solid rgba(23, 23, 23, 0.08); + background: rgba(246, 246, 242, 0.96); + backdrop-filter: blur(10px); + } + + .section-tabs { + padding-bottom: 1px; + } + + .section-tab { + min-height: 38px; + padding: 0 10px; + } + + .section-summary { + font-size: 12px; + } + + .mode-hint, + .advanced-summary, + #resultCount, + #waytoagiUpdatedAt { + white-space: normal; + } + + .time { + margin-left: 0; + } + + .waytoagi-head { + align-items: flex-start; + flex-direction: column; + } + + .bole-picks-head { + align-items: center; + flex-direction: row; + } + + .bole-head-tools { + justify-content: flex-end; + } + + #bolePicksMeta { + display: none; + } + + .list-head { + align-items: flex-start; + flex-direction: column; + } + + .list-head-tools { + width: 100%; + justify-content: space-between; + } + + .list-sort-tools { + overflow-x: auto; + } + + .bole-board { + display: block; + padding: 14px 12px 14px; + } + + .top-stories-grid { + grid-template-columns: 1fr; + padding: 12px; + } + + .top-stories-grid > .top-story-card.lead { + grid-row: auto; + } + + .top-story-card { + min-height: 0; + } + + .top-story-card.lead { + min-height: 0; + padding: 16px; + } + + .top-story-card.lead .top-story-title { + font-size: 21px; + } + + .news-list { + padding: 10px 12px 12px; + } + + .bole-compact-list { + grid-template-columns: 1fr; + } + + .bole-compact-list::before { + left: 18px; + } + + .bole-compact-list .bole-row { + grid-template-columns: 1fr; + gap: 6px; + padding-left: 36px; + } + + .bole-compact-list .bole-row::before { + left: 13px; + } + + .bole-compact-list .bole-row-time { + padding-top: 0; + text-align: left; + } + + .story-row { + grid-template-columns: 1fr; + gap: 6px; + padding-left: 36px; + } + + .story-row::before { + left: 13px; + } + + .story-time { + display: flex; + flex-wrap: wrap; + gap: 5px 8px; + align-items: baseline; + padding-top: 0; + text-align: left; + } + + .story-score { + margin-left: 0; + } + + .story-source-chip { + max-width: 140px; + } + + .source-status-table { + overflow-x: auto; + } + + .source-table { + min-width: 580px; + } + + .bole-lead-card { + min-height: 240px; + padding: 56px 16px 16px; + } + + .bole-lead-title { + max-width: 100%; + font-size: 24px; + } + + .bole-side-list::before { + left: 18px; + } + + .bole-row { + grid-template-columns: 1fr; + gap: 6px; + padding-left: 36px; + } + + .bole-row::before { + left: 13px; + } + + .bole-row-time { + padding-top: 0; + text-align: left; + } +} + +@media (max-width: 460px) { + .hero-headline { + align-items: flex-start; + } + + .health-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 6px; + } + + .stats { + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 8px; + padding: 10px; + } + + .coverage-strip { + grid-template-columns: 1fr; + gap: 6px; + } + + .source-health-summary { + align-items: flex-start; + flex-direction: column; + } + + .section-tab { + gap: 6px; + font-size: 12px; + } + + .section-tab strong { + min-width: 20px; + padding: 3px 5px; + } + + .intel-card { + padding: 12px; + } + + .intel-card-sources > span, + .intel-card-sources > strong { + max-width: 180px; + } + + .stat { + gap: 3px; + padding: 8px 9px; + } + + .stat-prefix { + font-size: 12px; + } + + .stat .k { + font-size: 11px; + } + + .stat .v { + font-size: 16px; + } + + .coverage-card { + padding: 8px 9px; + } + + .coverage-card strong { + font-size: 14px; + } + + .waytoagi-tools { + align-items: flex-start; + flex-direction: column; + } +} + +/* Motion layer */ +.story-row, +.bole-row, +.news-card, +.top-story-card, +.intel-card, +.coverage-card { + will-change: transform; + transition: transform 0.18s ease, box-shadow 0.18s ease, border-color 0.18s ease; +} + +.story-row:hover, +.bole-row:hover, +.news-card:hover, +.top-story-card:hover, +.intel-card:hover { + transform: translateY(-2px); + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.07); +} + +.coverage-card:hover { + transform: translateY(-1px); + box-shadow: 0 3px 8px rgba(0, 0, 0, 0.06); +} + +@media (prefers-reduced-motion: reduce) { + .story-row, + .bole-row, + .news-card, + .top-story-card, + .intel-card, + .coverage-card { + will-change: auto; + transition: none; + transform: none !important; + } + + .story-row:hover, + .bole-row:hover, + .news-card:hover, + .top-story-card:hover, + .intel-card:hover, + .coverage-card:hover { + box-shadow: none; + } +} diff --git a/skills/ai-news-radar/classic/index.html b/skills/ai-news-radar/classic/index.html new file mode 100644 index 0000000..9bbb144 --- /dev/null +++ b/skills/ai-news-radar/classic/index.html @@ -0,0 +1,240 @@ + + + + + + + AI News Radar|24 小时 AI 更新雷达 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

AI News Radar

+
+ 更新时间 + 加载中... +
+ 视角 + + +
+
+
+
+
+
+ 源状态加载中 + +
+ +
+ +
+
+
正在整理栏目...
+
+
+ + + +
+ +
AI强相关
+
+ +
+ AI News Radar + 正在整理 24 小时信号... +
+ +
+ + 高级筛选 + 加载中... + +
+
+ + + + + +
+ AI 相关度 +
+ + +
+
+ +
+ +
源状态加载中...
+
+ 查看源状态详情 +
+
+
+
+
+
+
+ +
+
+
+

TODAY'S SIGNALS

+

今日重点信号

+
+
+ + 按评分排序 +
+
+
+
+ +
+
+

社区更新 · WaytoAGI

+
+
+ + +
+ 加载中... +
+
+
+
+
+ +
+
+

全量 AI 情报源

+
+
+ + + + +
+ 0 条 +
+
+
+
+ +
+ + + + + + + + + diff --git a/skills/ai-news-radar/docs/GPT_HANDOFF.md b/skills/ai-news-radar/docs/GPT_HANDOFF.md new file mode 100644 index 0000000..664a377 --- /dev/null +++ b/skills/ai-news-radar/docs/GPT_HANDOFF.md @@ -0,0 +1,132 @@ +> Upstream reference from LearnPrompt/ai-news-radar@689395109cc962a27c369bdd6fa50d1e090eb319. Relative Markdown links target that immutable upstream snapshot. This reference is not a claim that upstream deployment workflows, development tests or private integrations are installed. + +# GPT Handoff: AI News Radar V2 + +Use this document to hand the project to a fresh GPT/Codex/Claude session for +verification. + +## Local Project + +- Local path: `/Users/carl2077/workspace/ai-news-radar` +- Public site: `https://learnprompt.github.io/ai-news-radar/` +- Local preview used during development: `http://127.0.0.1:8091/` +- Local preview directory: `/tmp/ai-news-radar-preview` + +The working repo may use skip-worktree for large `data/*.json` files. For +browser validation, prefer the preview URL above or rebuild a preview directory +from Git-tracked data. If a checked-out copy already has `data/*.json`, this is +enough: + +```bash +cd /Users/carl2077/workspace/ai-news-radar +python -m http.server 8080 +``` + +## What This Project Is + +AI News Radar is a static 24h AI/tech news radar: + +- ordinary readers open the hosted page and read 24h AI updates +- maintainers can fork it and add private OPML/RSS via GitHub Secrets +- Codex / Claude Code can use `skills/ai-news-radar/SKILL.md` to maintain source + coverage, evaluate new feeds, and keep the product simple + +## Implemented V2 Work + +Product/UI: + +- Added first-viewport coverage radar: + - source health + - AI signal density + - official/newsletter coverage + - Builders/X coverage through Follow Builders + - aggregator breadth + - private extension readiness through OPML/Secrets +- Added source-type tags on news cards, such as official, newsletter, + Builders/X, and aggregator. +- Kept advanced filters inside the advanced panel so ordinary readers are not + forced to choose between many source controls. +- Added SVG favicon from the existing logo. + +Sources and coverage: + +- Built-in official AI sources include OpenAI News, OpenAI Codex Changelog, + OpenAI Skills commits filtered for Codex/pet-related updates, Anthropic, + Google DeepMind, Google AI, Hugging Face, and GitHub AI/Changelog. +- AI Breakfast is read through its public archive path because Beehiiv feed + access can be blocked in CLI/GitHub Actions environments. +- Follow Builders is consumed as public generated JSON feed files. The project + does not copy its X API token flow. +- X API, email inboxes, WeChat, cookies, and login-bound bridges are treated as + advanced/private integrations, not public defaults. + +Skill/docs: + +- Added `skills/ai-news-radar/SKILL.md` for Codex/Claude workflows. +- Added `skills/ai-news-radar/references/source-intake.md`. +- Added `skills/ai-news-radar/references/v2-method.md`. +- Added `docs/SOURCE_COVERAGE.md`. +- Added `docs/V2_PRODUCT_BRIEF.md`. +- Updated `README.md` so readers, fork users, and agent users each have a clear + entry point. + +## Validation Already Run + +```bash +node --check assets/app.js +/tmp/ai-news-radar-venv/bin/python /Users/carl2077/.codex/skills/.system/skill-creator/scripts/quick_validate.py skills/ai-news-radar +/tmp/ai-news-radar-venv/bin/pytest -q +git diff --check +``` + +Last known result: + +- Skill validator: `Skill is valid!` +- Tests: `28 passed` +- GitHub Pages deployment: success + +## Verification Checklist For A Fresh GPT + +Please verify: + +1. Reader path: Can a normal user understand that they only need to open the + public page? +2. Fork path: Can a GitHub user understand how to fork, enable Pages/Actions, + and optionally add OPML through `FOLLOW_OPML_B64`? +3. Agent path: Can Codex/Claude find the Skill and know which files to read + first? +4. Coverage honesty: Does the repo clearly distinguish public default sources + from advanced/private integrations? +5. UI: Does the first viewport show source coverage without overwhelming new + users? +6. Safety: Are private OPML files, tokens, cookies, inboxes, and API keys kept + out of the repository? +7. Maintenance: Are validation commands and source-intake rules clear enough for + a future agent to add or reject new sources? + +## Suggested Prompt For New GPT + +```text +你现在接手本地项目: +/Users/carl2077/workspace/ai-news-radar + +请使用项目内 Skill: +skills/ai-news-radar/SKILL.md + +请先阅读: +README.md +docs/GPT_HANDOFF.md +docs/SOURCE_COVERAGE.md +docs/V2_PRODUCT_BRIEF.md +skills/ai-news-radar/references/source-intake.md +skills/ai-news-radar/references/v2-method.md + +任务: +1. 判断这个 AI 新闻聚合项目是否已经达到 v2 soft launch / 可公开发布状态。 +2. 分别从普通读者、fork 用户、Codex/Claude Skill 用户三个角度验收 README 和项目结构。 +3. 检查是否有隐私/密钥/OPML 泄漏风险。 +4. 检查信息源覆盖是否诚实:哪些是公共默认源,哪些只是高级/私有路径。 +5. 如果发现问题,请按严重程度列出具体文件和建议修复方式。 + +不要直接重构。先做验收报告。 +``` diff --git a/skills/ai-news-radar/docs/ROADMAP.md b/skills/ai-news-radar/docs/ROADMAP.md new file mode 100644 index 0000000..c3a0544 --- /dev/null +++ b/skills/ai-news-radar/docs/ROADMAP.md @@ -0,0 +1,113 @@ +> Upstream reference from LearnPrompt/ai-news-radar@689395109cc962a27c369bdd6fa50d1e090eb319. Relative Markdown links target that immutable upstream snapshot. This reference is not a claim that upstream deployment workflows, development tests or private integrations are installed. + +# AI News Radar Roadmap + +## Parked — 三口味 persona 网页 UI(2026-07-15 归档) + +v0.8–v0.9 期间网页端曾上线「今日 TOP3 · 三口味锐评」置顶板块与精选卡片的单条锐评行,因样式不满意在 v0.9 发布前暂时下线,待重新设计后回归。 + +- 开关:`assets/app.js` 的 `PERSONA_UI_ENABLED`(现为 `false`,置回 `true` 即恢复板块与锐评行,渲染代码完整保留)。 +- 不受影响:数据管线(`scripts/persona_score.py` 每轮照常生成 `data/daily-brief.json` 的 persona 字段与 `data/top3-personas.json`)、Skill 端日报的三口味点评。 +- 回归前要解决的:三列并排面板与卡片视觉融合度、锐评行与推荐理由的层级关系、口味名称/分数的展示样式。 + +## v0.3.0 — Source Overlap Check + +Goal: before adding a new public default source, evaluate whether its recent items are mostly duplicates of the existing source set. + +Status: implemented as a maintainer-facing intake tool. + +### What ships + +- `scripts/evaluate_source_overlap.py` + - Fetches a candidate RSS/Atom source. + - Compares recent candidate items against `data/archive.json` or another baseline JSON. + - Reports hard duplicates, possible duplicates, unique items, top overlapping sources, and a recommendation. +- `tests/test_source_overlap.py` + - Covers URL exact matches, title similarity, duplicate-rate statistics, threshold recommendations, and the small-sample guard. + +### Default decision thresholds + +- `< 35%` duplicate rate: `accept_default` +- `35%–65%` duplicate rate: `watchlist` +- `>= 65%` duplicate rate: `skip_duplicate` +- `< 5` recent candidate items: always `watchlist`, because the sample is too small for automatic rejection. + +### Example + +```bash +python scripts/evaluate_source_overlap.py \ + --source-url https://aihot.virxact.com/feed.xml \ + --source-name "AI HOT" \ + --site-id aihot_candidate \ + --baseline data/archive.json \ + --lookback-days 7 \ + --output /tmp/aihot-overlap.json +``` + +The tool is advisory only. It does not change `update_news.py`, does not remove any items, and does not publish the report to GitHub Pages by default. + +## v0.4.0 — Explainable AI Relevance Scoring + +Goal: move beyond a black-box boolean topic filter and make every AI relevance decision inspectable, testable, and tunable. + +Status: implemented as the default topic-filtering layer. + +### What ships + +- `scripts/ai_relevance.py` + - Scores each normalized record with `score_ai_relevance(record)`. + - Emits `is_ai_related`, `score`, `label`, `reason`, `signals`, and `noise`. + - Keeps `is_ai_related_record(record)` as a backward-compatible boolean wrapper. +- `scripts/update_news.py` + - Uses the new scorer before writing the 24h Signal payload. + - Adds AI relevance fields to kept records so downstream UI and audits can explain why an item passed. + - Publishes the filter metadata as `topic_filter=ai_relevance_scoring_v0_4` and `ai_relevance_threshold=0.65`. +- `scripts/audit_ai_relevance.py` + - Generates a Markdown audit report from `latest-24h.json` and `latest-24h-all.json`. + - Summarizes raw keep rate, label distribution, source keep rate, top kept samples, high-score dropped samples, and review-band candidates. +- `tests/test_ai_relevance.py` + - Covers strong AI signals, broad AI terms with tech context, trusted AI-source priors, noise suppression, structured output fields, and boolean compatibility. + +### Default decision thresholds + +- `score >= 0.65`: keep in the AI Signal view. +- `0.45 <= score < 0.65`: review band for future manual or LLM second-pass review. +- `< 0.45`: keep only in all-mode/archive data. + +### Audit example + +```bash +python scripts/update_news.py \ + --output-dir /tmp/ai-news-radar-v0.4-preview \ + --window-hours 24 \ + --rss-opml feeds/follow.opml + +python scripts/audit_ai_relevance.py \ + --data-dir /tmp/ai-news-radar-v0.4-preview \ + --output reports/ai-relevance-audit/v0.4.0-YYYY-MM-DD.md +``` + +### Non-goals for v0.4.0 + +- No LLM classifier in the default GitHub Actions path. +- No full-body semantic reading; the default scorer remains title/source/url based. +- No automatic source deletion based on keep rate. +- No public page layout redesign. + +## v0.5.0 — Story Merge / Event Cluster + +Goal: move beyond per-item filtering and represent the same event as one story with multiple source references. + +### Planned direction + +- Keep the current filter-first behavior as the safe default. +- Add a story clustering layer after source normalization and before page payload generation. +- Preserve one primary title plus secondary source references, instead of randomly choosing one duplicated item. +- Show repeated coverage as a trust signal: "多个来源报道了这件事". + +### Non-goals for v0.5.0 + +- No LLM semantic clustering in the first pass. +- No cross-language deep semantic matching unless the rule-based event merge proves insufficient. +- No automatic deletion of sources based only on overlap score. +- No change to the public page layout unless the story data model is stable. diff --git a/skills/ai-news-radar/docs/SOURCE_COVERAGE.md b/skills/ai-news-radar/docs/SOURCE_COVERAGE.md new file mode 100644 index 0000000..7878fe2 --- /dev/null +++ b/skills/ai-news-radar/docs/SOURCE_COVERAGE.md @@ -0,0 +1,278 @@ +> Upstream reference from LearnPrompt/ai-news-radar@689395109cc962a27c369bdd6fa50d1e090eb319. Relative Markdown links target that immutable upstream snapshot. This reference is not a claim that upstream deployment workflows, development tests or private integrations are installed. + +# Source Coverage Plan + +This project should help ordinary AI enthusiasts scan high-signal updates +without forcing them to follow noisy timelines or manage many source choices. + +## Product Model + +Use a two-layer model: + +1. **Signal layer**: the default web UI. It should show a high-priority curated + subset first, with the complete AI-related pool available as an explicit + advanced choice. It should also show AI/tech updates, + WaytoAGI changes, search, site filtering, and a simple AI-focused / all toggle. +2. **Advanced layer**: maintainer and power-user workflows. It includes OPML, + source health data, GitHub Actions secrets, and custom fetchers. + +Do not expose every source-management decision in the first screen. Too many +choices make the tool harder for new users to understand. +The first screen may show coverage and health as read-only status signals: +source health, AI signal density, official/newsletter coverage, builders/X, +aggregator breadth, and private extension readiness. + +## V2 Coverage Claim + +The project can be packaged as a Skill because it covers the common public paths +for AI news collection: + +- official RSS/Atom/JSON and changelog pages +- OPML collections for personal source lists +- public GitHub-generated feeds such as curated X/blog/newsletter projects +- public newsletter archives and static pages +- optional secret-backed adapters for sources that need user-owned credentials + +It does not promise reliable default coverage for private inboxes, cookies, +WeChat accounts, or raw social timelines. Those belong in the advanced layer or +private forks because they need credentials, bridges, or ongoing maintenance. + +## Supported Source Types + +| Source type | Current support | Recommended path | Notes | +| --- | --- | --- | --- | +| Official RSS / Atom | Supported through OPML | Add to `feeds/follow.opml` locally, or `FOLLOW_OPML_B64` in GitHub Actions | Best default for personal customization. | +| Official AI vendor updates | Built in for selected high-signal sources | Keep OpenAI, Anthropic, Google DeepMind/AI, Hugging Face, and GitHub AI/Changelog as first-class sources | These should not depend only on aggregator coverage. | +| Curated AI media RSS | Built in for selected high-signal public feeds | Keep source-specific caps and AI/research filters so media breadth does not drown the default view | Useful for product, industry, model, and research coverage. | +| OPML collections | Supported | Export from RSS reader, copy from `feeds/follow.example.opml`, keep private file out of git | Good for cross-device and multi-agent workflows. | +| Public JSON APIs | Supported by custom Python fetchers | Add a `fetch_*` function in `scripts/update_news.py` and register it in the task list | Use only stable APIs with timestamps. | +| Public GitHub-generated feeds | Supported by custom Python fetchers | Prefer raw `feed*.json` / RSS / Atom files generated by another repo's Actions | Good for curated projects like Follow Builders. | +| Public static pages | Supported by custom Python fetchers | Parse with `requests` + BeautifulSoup and normalize titles/URLs/times | Avoid fragile selectors when possible. | +| GitHub releases/blogs | Usually supported through Atom/RSS | Prefer GitHub Atom feeds or official blog RSS | Useful for model/platform/tool release tracking. | +| Newsletters | Partially supported | Prefer public archive RSS or stable archive pages | Do not scrape private inboxes. | +| X / Twitter | Supported only through curated central feeds or opt-in API adapters | Prefer public generated feeds that already use official X API; keep direct X API optional and secret-backed | Following a person often imports noise; public bridge routes can be unstable. | +| WeChat public accounts | Not recommended as a default | Use stable third-party RSS only if the maintainer accepts breakage risk | Login/copyright/bridge stability can be poor. | +| Telegram / Bilibili / Zhihu / podcasts | Skipped by default when feeds are unreliable | Add only as opt-in OPML entries | These can be noisy or bridge-dependent. | + +## Source Selection Rules + +Add a source only when it passes most of these checks: + +- Publishes AI, model, developer tool, or tech industry updates with low noise. +- Has a stable URL, feed, API, or page structure. +- Provides usable timestamps or enough ordering information. +- Does not require private cookies, login sessions, browser automation, or secrets. +- Can be fetched politely by GitHub Actions without heavy rate limits. +- Adds coverage not already represented by stronger sources. + +## Built-In Official Nodes + +The public site should directly track these high-signal official sources: + +- OpenAI News RSS +- Anthropic News page +- Google DeepMind RSS +- Google AI Blog RSS +- Hugging Face Blog RSS +- GitHub AI & ML RSS +- GitHub Changelog RSS + +Aggregator sites may already surface some of these updates, but they are not +guaranteed to be complete or timely. Keep these official sources as a stable +baseline, then let the aggregator layer add breadth. + +## Built-In Curated Feeds + +- **Follow Builders**: reads public `feed-x.json`, `feed-blogs.json`, and + `feed-podcasts.json` generated by `zarazhangrui/follow-builders`. That project + uses centralized GitHub Actions plus official X API credentials. This project + consumes only its public generated JSON files, so public visitors do not need + X API credentials. +- **Curated AI media RSS**: reads a small set of public RSS/Atom feeds that add + coverage without requiring login: The Decoder AI News, TechCrunch AI, The + Verge RSS with strict AI-title filtering, MarkTechPost Research with research + filtering, VentureBeat AI, Artificial Intelligence News, and Claude Code + GitHub releases. These feeds are capped per source and pass through the same + AI relevance scoring as the rest of the radar. Research-heavy feeds are + intentionally filtered and downweighted so they fill the research lane without + dominating the default hot view. +- **AI Breakfast**: reads the public Beehiiv archive through Jina Reader because + the original Beehiiv feed can be blocked from GitHub Actions. +- **AI HOT**: reads the public `https://aihot.virxact.com/api/public/items` + API in selected mode and keeps only items whose AI HOT card score is at least + 60. The parser preserves AI HOT's Chinese title, valid English original title, + editorial summary, category, score, and canonical source URL. The RSS feed is + intentionally not used for the default fetch path because it does not expose + the source score field needed for this quality gate. +- **Hacker News Algolia**: reads the public + `https://hn.algolia.com/api/v1/search_by_date` endpoint for the last 24 hours + of HN stories matching focused AI/tooling keywords such as OpenAI, Anthropic, + Claude Code, Codex, MCP, Cursor, Gemini, DeepSeek, Qwen, LLM, GPT, Sora, and + Copilot. This is not a private HN API and does not require a key. It keeps + only titles with multiple AI keyword signals and enough discussion + (`num_comments >= 2` or `points >= 10`), so it remains a discussion/heat + reference rather than a broad HN firehose. +- **WaytoAGI**: reads the public Feishu wiki update log into + `data/waytoagi-7d.json`; the latest update day is also promoted into the + community signal lane so it can appear under the Community tab without + occupying a standalone homepage block. + +## Disabled Default Sources + +- **X API direct recent search**: supported as an advanced, secret-backed adapter + through `X_API_ENABLED=1` and `X_BEARER_TOKEN`, but disabled by default because + current official X API docs describe paid read credits rather than a free daily + read quota. Use `X_API_MAX_RESULTS`, `X_API_DAILY_POST_LIMIT`, and + `X_API_RUN_UTC_HOUR` to cap usage. +- **SocialData.tools X search**: supported as an advanced, secret-backed adapter + through `SOCIALDATA_ENABLED=1` and `SOCIALDATA_API_KEY`, but disabled by + default. It reads public X/Twitter search results from the third-party + SocialData API, not from the official X API. Use `SOCIALDATA_QUERY`, + `SOCIALDATA_MAX_RESULTS`, `SOCIALDATA_DAILY_TWEET_LIMIT`, and + `SOCIALDATA_RUN_INTERVAL_HOURS` to keep cost and noise bounded. The default + SocialData interval is 12 hours. The previous `SOCIALDATA_RUN_UTC_HOUR` + setting still controls the first run window when no paid-source state exists + yet. SocialData search normally returns about 20 + tweets per page; the fetcher follows `next_cursor` with the `cursor` + parameter until the configured effective cap is reached or the API stops + returning a cursor. +- **TikHub Douyin/Xiaohongshu search**: supported as an advanced, + secret-backed adapter through `TIKHUB_ENABLED=1` and `TIKHUB_API_KEY`, but + disabled by default. It reads public Douyin and Xiaohongshu keyword search + results through TikHub's paid API, not official RSS. Use `TIKHUB_QUERY`, + `TIKHUB_PLATFORMS`, `TIKHUB_MAX_RESULTS`, `TIKHUB_DAILY_ITEM_LIMIT`, and + `TIKHUB_RUN_INTERVAL_HOURS` to keep cost and noise bounded. The default + TikHub interval for Douyin/Xiaohongshu is 24 hours. The previous + `TIKHUB_RUN_UTC_HOUR` setting still controls the first run window when no + paid-source state exists yet. Prefer focused AI + keywords over general hot lists so entertainment trends do not flood the + Signal view. The default query puts focused AI terms such as OpenAI, Claude, + large models, Agent, and AI tools ahead of broad `AI`/`人工智能` fallbacks, and + per-platform caps are spread across keywords so one broad term cannot consume + the whole paid-source budget. TikHub requests use the most-liked/popularity + sort and a one-week publish bucket, then the radar enforces the current-week + cutoff in code. The creator lane uses a separate seven-day pool ranked by + 85% engagement heat plus a 15-point bonus for posts published in the last + 24 hours; the rest of the site remains a 24-hour radar. Xiaohongshu uses the + recommended App V2 search endpoint + first and only falls back to Web V3 when App V2 cannot fill the current + keyword budget. It deduplicates by note id, ignores sentinel API timestamps + such as zero, infers missing note times from the timestamp prefix in the + Xiaohongshu note id, and drops results whose publish time is missing or older + than the current-week window; Douyin stays on TikHub's current Douyin Search + API rather than deprecated App V3 search paths. + + The official TikHub Python SDK is generated from OpenAPI V5.3.2, so SDK + resources mirror OpenAPI tags. The SDK documents Douyin coverage as + `douyin_web`, `douyin_app_v3`, `douyin_search`, `douyin_billboard`, + `douyin_creator`, and `douyin_xingtu` with 400+ endpoints. The current + OpenAPI also includes `douyin_creator_v2`, `douyin_index`, and + `douyin_xingtu_v2`. For AI News Radar, keep the default TikHub read on + `douyin_search.fetch_general_search_v2`; App V3 search endpoints are + deprecated, while billboard, creator, xingtu, and index endpoints are better + future candidates for separate advanced trend/creator lanes. + + The SDK documents Xiaohongshu coverage as `xiaohongshu_web` and + `xiaohongshu_app` plus v2/v3 variants with 80+ endpoints. Current OpenAPI + priority is `xiaohongshu_app_v2` first, then `xiaohongshu_app`, then + `xiaohongshu_web_v2`, then `xiaohongshu_web`; however, the old + `xiaohongshu_app` and `xiaohongshu_web` tags are marked deprecated in + OpenAPI. The radar therefore scans `xiaohongshu_app_v2.search_notes` and + `xiaohongshu_web_v3.fetch_search_notes`, records the `search_surface` in + public raw output, and treats Web V3 failures as non-fatal when App V2 + succeeds. +- **AgentMail digest**: supported as an advanced metadata-only source through + `EMAIL_DIGEST_ENABLED=1`, but disabled by default. For the current QQ Agent + Mail path, set `AGENTMAIL_PROVIDER=agently_cli` after `agently-cli auth login`; + the fetcher defaults to `agently-cli message +list`. In a privately authorized run, `AGENTMAIL_RESOLVE_PUBLIC_URLS=1` may read allowed senders’ messages in memory to extract newsletter archive URLs; bodies are never written to output. The + legacy API path remains available with `AGENTMAIL_PROVIDER=api`, + `AGENTMAIL_API_KEY`, and `AGENTMAIL_INBOX_ID`. It deliberately lists messages + only and does not publish body text, raw `.eml`, full email addresses, or + secrets. Use `AGENTMAIL_ALLOWED_SENDER_DOMAINS` to scope a shared inbox. Only + set `EMAIL_DIGEST_INCLUDE_IN_RADAR=1` when the maintainer explicitly wants + subject/snippet metadata to appear as the standalone `agentmail` source in + Radar data. + +See `docs/research/advanced-source-free-tier-budget-2026-05-10.md` for the X API +and AgentMail budget notes. + +## Example OPML Seeds + +`feeds/follow.example.opml` contains a public, low-risk demo set that is expected +to pass through the real project fetch path on GitHub Actions: + +- **Official examples**: OpenAI News, Hugging Face Blog, Google DeepMind Blog, + Google AI Blog, and Microsoft AI Blog. +- **AI media / builder feeds**: Wired AI, InfoQ CN, NVIDIA Generative AI Blog, + 宝玉, and Simon Willison. + +In GitHub Actions, `feeds/follow.example.opml` is also used as the public demo +fallback when no private `FOLLOW_OPML_B64` secret is configured. This keeps the +hosted page visibly proving that RSS/OPML import works without requiring any +private subscriptions. Maintainers can override it by setting `FOLLOW_OPML_B64`. +Substack newsletters are intentionally excluded from the public demo OPML because +GitHub Actions runners can receive `403 Forbidden` even when the same feeds work +locally. QbitAI remains on the watchlist because the direct feed probed via +`urllib` but returned `403 Forbidden` through the project fetch path. Broad +sources such as Hacker News frontpage, general hot lists, X bridges, and WeChat +bridges remain outside the example file unless the maintainer explicitly accepts +the extra filtering and maintenance risk. + +Recent candidates skipped from the built-in default set: + +- **OpenRouter Announcements**: the public page advertises an RSS alternate, but + the observed `/blog/feed.xml` target returned a Not Found page during intake. +- **LMSYS Blog**: probed feed endpoints redirected or returned 404. +- **Hugging Face Daily Papers**: probed RSS-style endpoints returned 401/404; + keep it out of the default set until a stable public feed is available. +- **Berkeley RDI Blog**: `/feed.xml` returned only a stale Jekyll placeholder + item from 2021, so it is not useful as a default source yet. + +## Personal Source Workflow + +For a private custom setup: + +1. Copy `feeds/follow.example.opml` to `feeds/follow.opml`. +2. Add official RSS/Atom feeds to `feeds/follow.opml`. +3. Run: + + ```bash + python scripts/update_news.py --output-dir data --window-hours 24 --rss-opml feeds/follow.opml + ``` + +4. Check `data/source-status.json` for `failed_feeds`, `zero_item_feeds`, + `skipped_feeds`, and `replaced_feeds`. +5. Keep `feeds/follow.opml` private. For GitHub Actions, store its base64 + content in the `FOLLOW_OPML_B64` secret. + +## Adding A Built-In Source + +Use this only for sources that should benefit every public visitor: + +1. Add a `fetch_(session, now)` function in `scripts/update_news.py`. +2. Return `RawItem` objects with `site_id`, `site_name`, `source`, `title`, `url`, + `published_at`, and `meta`. +3. Register the fetcher in the built-in task list. +4. Normalize URLs and dates using existing helpers. +5. Update this document if the source changes coverage. +6. Run the fastest relevant checks: + + ```bash + python -m py_compile scripts/update_news.py + pytest -q + ``` + +## Deployment + +The public deployment should remain GitHub Pages + GitHub Actions: + +- GitHub Actions updates `data/*.json`. +- GitHub Pages serves `index.html` and `assets/*`. +- Private OPML input belongs in `FOLLOW_OPML_B64`, not in the repository. + +This keeps the public version easy to fork while still letting each maintainer +bring their own private source list. + +## Official service status + +The collector reads OpenAI’s public status API and writes `data/service-status.json` separately from news. Only investigating, identified and monitoring incidents appear in the shared mobile/classic banner; resolved incidents, failed reads and snapshots older than two hours stay hidden. A hidden banner is not an assertion that every service is healthy. The normal update workflow publishes the generated file. diff --git a/skills/ai-news-radar/docs/V2_PRODUCT_BRIEF.md b/skills/ai-news-radar/docs/V2_PRODUCT_BRIEF.md new file mode 100644 index 0000000..e71e692 --- /dev/null +++ b/skills/ai-news-radar/docs/V2_PRODUCT_BRIEF.md @@ -0,0 +1,61 @@ +> Upstream reference from LearnPrompt/ai-news-radar@689395109cc962a27c369bdd6fa50d1e090eb319. Relative Markdown links target that immutable upstream snapshot. This reference is not a claim that upstream deployment workflows, development tests or private integrations are installed. + +# AI News Radar V2 Product Brief + +Generated from an Office Hours style product diagnostic plus a Superpowers style +implementation loop. + +## Problem Statement + +Ordinary AI enthusiasts want a high-signal AI update page they can open without +building a personal RSS/X/email pipeline. Maintainers and agent users need a +clear path to add their own sources without breaking the public default. + +## Demand Evidence + +- The user asked for broad distribution, not just a personal dashboard. +- Too many source choices were called out as a problem for newcomers. +- X and email were discussed as valuable but unreliable as defaults. +- GitHub-generated public feeds such as Follow Builders were preferred because + they centralize unstable API work and expose stable public outputs. + +## Status Quo + +People currently mix manual site visits, noisy X timelines, newsletter inboxes, +RSS readers, and aggregator sites. Each path covers part of the signal, but none +is both low-noise and easy to fork. + +## Narrowest Useful Wedge + +Keep the default page as a simple 24h signal board, but make the source model +visible: source health, AI signal density, official/newsletter coverage, +builders/X coverage, aggregator breadth, and private extension readiness. + +## Approaches Considered + +### A: Add More Sources + +Fast to make the feed look richer, but risks noise and does not explain the +coverage model. + +### B: Surface Coverage As Product Signal + +Adds first-viewport trust without adding controls. It helps users understand why +the project is more than another aggregator. + +### C: Build Full Self-Hosted X/Email Adapters + +Powerful for private forks, but too credential-heavy and fragile for the public +default. + +## Recommended Approach + +Use Approach B now. Keep Approach C as advanced/private integration guidance. + +## Success Criteria + +- First viewport answers: what is covered, whether sources are healthy, and how + private extensions fit. +- No extra default choices are required from ordinary readers. +- X/email remain optional and secret-backed, not public defaults. +- Future agents can route a new source into public default vs advanced/private. diff --git a/skills/ai-news-radar/entry.json b/skills/ai-news-radar/entry.json deleted file mode 100644 index 59cba44..0000000 --- a/skills/ai-news-radar/entry.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "id": "ai-news-radar", - "name": "AI News Radar", - "category": "productivity", - "icon": "", - "tags": [ - "ai-news", - "rss", - "learnprompt" - ], - "i18n": { - "zh-CN": { - "name": "AI 资讯雷达", - "shortDesc": "24 小时 AI 资讯雷达:从多信源筛选要闻、合并成故事线,并用三种口味锐评每日头条。需自行配置 Python 运行环境与信源;邮件接入须另行授权。" - }, - "en-US": { - "name": "AI News Radar", - "shortDesc": "24/7 AI news radar that curates multiple sources into storylines and delivers daily headlines with three flavors of commentary. Requires a separately configured Python environment and sources; mail access requires separate authorization." - } - }, - "maintainer": { - "name": "LearnPrompt", - "verified": false, - "account": "LearnPrompt", - "url": "https://github.com/LearnPrompt/ai-news-radar" - }, - "stewardship": "community", - "license": "MIT", - "redistribution": "allowed", - "source": { - "kind": "git", - "repoUrl": "https://github.com/LearnPrompt/ai-news-radar.git", - "repoBranch": "master", - "path": "skills/ai-news-radar", - "ref": "689395109cc962a27c369bdd6fa50d1e090eb319" - } -} diff --git a/skills/ai-news-radar/feeds/follow.example.opml b/skills/ai-news-radar/feeds/follow.example.opml new file mode 100644 index 0000000..ba2a207 --- /dev/null +++ b/skills/ai-news-radar/feeds/follow.example.opml @@ -0,0 +1,82 @@ + + + + AI News Radar RSS Example + + + + + + + + + + + + + + + + + + diff --git a/skills/ai-news-radar/index.html b/skills/ai-news-radar/index.html new file mode 100644 index 0000000..e9f6234 --- /dev/null +++ b/skills/ai-news-radar/index.html @@ -0,0 +1,213 @@ + + + + + + AI News Radar|24 小时 AI 更新雷达 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

AI News Radar

+
+ 更新时间 + 加载中... +
+ 视角 + + +
+
+
+
+
+ + +
+
+ +
+
+ + + +
+
+ + +
+ +
精选加载中
+ +
+ +
+ + 高级筛选 + 只看某个来源,或检查各信源采集是否正常 + +
+
+ +
+ +
源状态加载中...
+
+ 查看源状态详情 +
+
+
+
+
+ +
+
+

当前热点

+ 按热度排序 +
+
+
+ + + +
+
+

社区更新 · WaytoAGI

+
+
+ + +
+ 加载中... +
+
+
+
+
+ +
+
+

精选

+
+ + 0 条 +
+
+
+
+ +
+ + + + + + + + + diff --git a/skills/ai-news-radar/personas/README.md b/skills/ai-news-radar/personas/README.md new file mode 100644 index 0000000..536dfa6 --- /dev/null +++ b/skills/ai-news-radar/personas/README.md @@ -0,0 +1,57 @@ +# Personas 口味目录 + +这里存放 persona 评分器的"口味"定义。`scripts/persona_score.py` 会读取本目录下所有 `*.md` 文件(本 README 除外),用它们作为 LLM 的 system prompt 给每日简报打分和点评。 + +## 内置口味 + +| id | 名称 | 视角 | +|----|------|------| +| `pragmatic` | 实用派(默认) | 只关心对开发者/从业者今天有什么用 | +| `cynic` | 毒舌评论员 | 拆穿营销话术和炒作,讥讽但基于事实 | +| `paper-police` | 较真党 | 只认论文/代码/benchmark 实证,对"即将推出"零容忍 | + +## 文件格式 + +每个 persona 是一个 Markdown 文件,由 YAML frontmatter 和正文 prompt 两部分组成: + +```markdown +--- +id: my-persona +name: 中文名 +name_en: English Name +--- + +正文即 system prompt…… +``` + +frontmatter 字段: + +- `id`(必填):只允许小写字母和连字符(`[a-z-]`),需与文件名一致。 +- `name`(必填):中文显示名。 +- `name_en`(必填):英文显示名。 +- `default: true`(可选):默认口味标记,全目录只允许一个(当前是 `pragmatic`)。 + +注意:解析器是手写的简易 frontmatter 解析(逐行 `key: value`),不要在 frontmatter 里用嵌套结构、多行值或列表。 + +## 正文 prompt 必须包含 + +1. **口味自述**:一段话讲清这个口味的立场和关注点,人格要鲜明。 +2. **评分标准**:0-100 分的分段说明,写明各分段的侧重点。 +3. **输出要求**:要求模型返回 `{"score": <0-100 整数>, "review": "<一句中文点评>"}`,点评不超过 40 字,说人话,不复读标题。 +4. **示例点评**:至少 3 条"输入 → 输出"示例,帮模型对齐语气和分数尺度。 + +## 如何贡献第 4 个口味 + +1. 复制任意内置口味文件作为模板,起一个符合 `[a-z-]` 的文件名(如 `personas/vc-radar.md`)。 +2. 填好 frontmatter(不要写 `default: true`,默认位已被 pragmatic 占用)。 +3. 按上面四要素写正文,中文文案避免翻译腔。 +4. 本地验证: + + ```bash + python scripts/persona_score.py --list-personas + ``` + + 确认新口味出现在列表里。 +5. 跑 `python -m pytest -q tests/test_persona_score.py` 确认解析无误。 + +新口味会自动参与 TOP3 多口味点评(`data/top3-personas.json`);每日逐条评分仍只用默认口味。 diff --git a/skills/ai-news-radar/personas/cynic.md b/skills/ai-news-radar/personas/cynic.md new file mode 100644 index 0000000..6260e5e --- /dev/null +++ b/skills/ai-news-radar/personas/cynic.md @@ -0,0 +1,32 @@ +--- +id: cynic +name: 毒舌评论员 +name_en: Cynic +--- + +你是一名毒舌的科技评论员,代号"毒舌评论员"。 + +## 口味自述 + +你见过太多发布会和"革命性突破",营销话术在你面前一层层剥落。你专门盯 PR 稿里的水分:夸大的对比基线、精心挑选的 demo、避而不谈的成本和限制。你讥讽,但每一句挖苦都踩在事实上;真材实料你也认,只是嘴上不饶人。 + +## 评分标准(0-100) + +- 85-100:经得起拆。有硬数据、可复现、连竞品都得承认的进展。 +- 65-84:七分真三分吹。东西是真的,宣传口径注了水,扣掉水分还剩点干货。 +- 40-64:半真半假。demo 好看但条件苛刻,或者对比对象故意挑弱的。 +- 15-39:营销为主。改个名就叫新品,或蹭热点的跟风官宣。 +- 0-14:纯炒作。无产品、无数据、无时间表,只有形容词。 + +## 输出要求 + +返回 JSON:`{"score": <0-100 整数>, "review": "<一句中文点评>"}`。 + +- 点评不超过 40 字,讥讽要落在具体事实上,不许人身攻击。 +- 禁止复读标题,禁止无凭据的阴阳怪气。 + +## 示例点评 + +- 输入:某公司称新模型"全面超越 GPT" → `{"score": 30, "review": "对比表只挑了三个自家擅长的榜,剩下的呢?"}` +- 输入:开源模型附完整训练代码和数据配方 → `{"score": 88, "review": "少见的全都敢晒出来,这次没法挑刺。"}` +- 输入:某创业公司宣布"即将颠覆搜索" → `{"score": 12, "review": "颠覆搜索的公司排到门口了,先发个能用的再说。"}` diff --git a/skills/ai-news-radar/personas/paper-police.md b/skills/ai-news-radar/personas/paper-police.md new file mode 100644 index 0000000..3cb528b --- /dev/null +++ b/skills/ai-news-radar/personas/paper-police.md @@ -0,0 +1,32 @@ +--- +id: paper-police +name: 较真党 +name_en: Stickler +--- + +你是一名严苛的学术审查员,代号"较真党"。 + +## 口味自述 + +你只认三样东西:论文、代码、benchmark。有 arXiv 链接吗?代码开源了吗?评测能复现吗?三个都没有,在你这里就等于什么都没发生。"即将推出""内部消息""知情人士透露"这类措辞会直接触发你的零分警报。你不是不近人情,你只是要求证据。 + +## 评分标准(0-100) + +- 85-100:铁证如山。论文+开源代码+公开 benchmark 三件套齐全,结果可复现。 +- 65-84:证据充分。有论文或代码之一,评测方法公开,缺一角但主体可查。 +- 40-64:有迹可循。技术报告或博客给了细节和数字,暂无独立验证。 +- 15-39:只有说法。官方博客宣称性能,无论文无代码无第三方评测。 +- 0-14:查无实据。"即将推出"、传闻、内部消息、匿名爆料,一律不认。 + +## 输出要求 + +返回 JSON:`{"score": <0-100 整数>, "review": "<一句中文点评>"}`。 + +- 点评不超过 40 字,指出证据在哪或缺什么证据。 +- 禁止复读标题,禁止用"看起来不错"这类无判断的话。 + +## 示例点评 + +- 输入:新模型发布,附论文和 GitHub 仓库 → `{"score": 92, "review": "论文代码都在,跑一遍就知真假,这才叫发布。"}` +- 输入:CEO 访谈称下一代模型"聪明十倍" → `{"score": 8, "review": "十倍从哪测的?没有评测报告就是十倍形容词。"}` +- 输入:技术博客公布评测数字但未开源 → `{"score": 45, "review": "数字给了但没法复现,等第三方跑分再定论。"}` diff --git a/skills/ai-news-radar/personas/pragmatic.md b/skills/ai-news-radar/personas/pragmatic.md new file mode 100644 index 0000000..0957f6f --- /dev/null +++ b/skills/ai-news-radar/personas/pragmatic.md @@ -0,0 +1,33 @@ +--- +id: pragmatic +name: 实用派 +name_en: Pragmatic +default: true +--- + +你是一名务实的 AI 从业者点评员,代号"实用派"。 + +## 口味自述 + +你只关心一件事:这条新闻对开发者和从业者今天有什么用。能立刻上手的工具、能直接抄的方案、影响选型的价格和接口变化,才值得高分。愿景发布会、融资八卦、没有产品的宣言,一律低分。你不激动也不悲观,像一个每天要交付代码的工程师在扫早报。 + +## 评分标准(0-100) + +- 85-100:今天就能用。新模型/新 API 已开放、开源仓库可 clone、价格降了、限制放开了。 +- 65-84:短期内影响工作。重要工具的路线图、benchmark 换榜首、主流框架大版本。 +- 40-64:值得知道但不用行动。行业动向、大厂人事、中期研究进展。 +- 15-39:与动手无关。融资、估值、宏观评论、口水战。 +- 0-14:纯噪音。旧闻回锅、软文、无信息量的官宣。 + +## 输出要求 + +返回 JSON:`{"score": <0-100 整数>, "review": "<一句中文点评>"}`。 + +- 点评不超过 40 字,说人话,直接讲"对你有什么用"或"为什么不用管"。 +- 禁止复读标题,禁止"值得关注""令人期待"这类空话。 + +## 示例点评 + +- 输入:某模型 API 降价 50% → `{"score": 90, "review": "直接省一半账单,跑批量任务的今天就能换。"}` +- 输入:某大厂宣布五年 AGI 愿景 → `{"score": 20, "review": "愿景不写代码,等有产品再看。"}` +- 输入:主流 Agent 框架发布 2.0,破坏性更新 → `{"score": 78, "review": "老项目升级前先锁版本,迁移指南得读。"}` diff --git a/skills/ai-news-radar/references/source-intake.md b/skills/ai-news-radar/references/source-intake.md new file mode 100644 index 0000000..ca3b728 --- /dev/null +++ b/skills/ai-news-radar/references/source-intake.md @@ -0,0 +1,172 @@ +# Source Intake Reference + +Use this when evaluating a new information source for AI News Radar. + +## V2 Intake Questions + +Before implementation, answer these from the URL, repo, or user's message: + +- Who benefits: every public visitor, the maintainer, or one private fork? +- What signal does it add that stronger existing sources do not already cover? +- Does it publish stable timestamps and canonical URLs? +- Can GitHub Actions fetch it without login, cookies, or browser automation? +- Does it need secrets? If yes, can it skip cleanly when secrets are missing? +- Will it flood the Signal view with off-topic items? + +Only ask the user when the answer changes default vs advanced routing. + +## Decision Order + +1. Prefer official RSS/Atom/JSON feeds. +2. Prefer public GitHub-generated feeds over rebuilding another project's crawler. +3. Use OPML for private or user-specific feeds. +4. Before making a source public-default, run the Source Overlap Check against the recent archive. +5. Use a built-in fetcher only when the source improves the public default. +6. Avoid login, cookies, browser automation, private inboxes, and committed secrets. + +## Source Classes + +| Source class | Preferred integration | Default suitability | +| --- | --- | --- | +| Official RSS/Atom | OPML or built-in official source | High | +| GitHub generated JSON/RSS | Built-in fetcher reading raw GitHub URLs | High if curated and timestamped | +| GitHub releases/commits | Atom feed | Medium to high | +| Public changelog page | Focused `requests` + BeautifulSoup fetcher | Medium | +| Aggregator site | Existing custom fetcher pattern | Medium | +| Newsletter archive | RSS if available; stable archive page otherwise | Medium | +| X/Twitter public timeline | Curated central feed or optional X API adapter | Low as default | +| Email inbox | Do not default; require explicit user-owned bridge/API | Low | +| WeChat/private social | Optional only, bridge-dependent | Low | + +## GitHub Project Intake + +When a user gives a GitHub repo: + +1. Read `README*`, `SKILL.md`, `config/*`, and `.github/workflows/*`. +2. Look for generated outputs: `feed*.json`, `latest*.json`, `rss.xml`, + `atom.xml`, `state*.json`, or a `gh-pages` branch. +3. Inspect output schema: + - title/text field + - canonical URL + - timestamp (`createdAt`, `publishedAt`, `generatedAt`, `pubDate`) + - source/person/feed name + - stable IDs for dedupe +4. Inspect workflow secrets and dependencies: + - If the repo uses API keys centrally but publishes public feed files, consume + the feed files. + - If every user must provide keys, treat it as an optional advanced source. +5. Test raw URLs from GitHub Actions-friendly locations: + - `https://raw.githubusercontent.com////` + - public GitHub Pages URL if provided +6. Add a fetcher only after a source-only probe succeeds locally. + +Treat public generated feed files as the durable path. If the repo has a stable +GitHub Action that commits `feed*.json` using its own API credentials, consume +those public outputs. Do not clone its token flow into this repo unless the user +explicitly asks for a self-hosted variant. + +## X/Twitter Rules + +Do not depend on public RSSHub/XCancel/Nitter routes as a default source unless +the user explicitly accepts instability. They can work briefly and then time out. + +Stable patterns: + +- Read a curated central feed that already uses official X API, like + Follow Builders. +- Add a self-hosted optional X adapter using `X_BEARER_TOKEN`; skip cleanly when + the token is missing. + +For optional X API adapters: + +- Store tokens only in GitHub Secrets or environment variables. +- Never print or commit tokens. +- Exclude retweets/replies by default. +- Cap per-account items. +- Record rate-limit or permission failures in `source-status.json`. +- Skip cleanly when `X_BEARER_TOKEN` is missing; the public site must still run. + +## Newsletter Rules + +Prefer public archive feeds: + +- Substack RSS when available. +- Beehiiv/public archive pages when RSS is blocked. +- Jina Reader only when direct fetch is blocked and the archive is public. + +Avoid private inbox ingestion as a default feature. Email requires OAuth, IMAP, +App Passwords, forwarding, or third-party bridges and raises privacy concerns. +If email support is requested, document it as an advanced private bridge and keep +the public default independent from mailbox access. + +## Built-In Fetcher Pattern + +Add focused code to `scripts/update_news.py`: + +```python +def fetch_example(session: requests.Session, now: datetime) -> list[RawItem]: + resp = session.get("https://example.com/feed.json", timeout=20) + resp.raise_for_status() + data = resp.json() + out: list[RawItem] = [] + for item in data.get("items", []): + published = parse_date_any(item.get("publishedAt"), now) + if not published: + continue + out.append( + RawItem( + site_id="example", + site_name="Example", + source=item.get("source") or "Example", + title=maybe_fix_mojibake(item["title"]), + url=item["url"], + published_at=published, + meta={}, + ) + ) + if not out: + raise ValueError("No Example items parsed") + return out +``` + +Then register it in `collect_all`, update docs, and add tests for parser behavior. + +## Source Overlap Check + +Before promoting a candidate RSS/Atom source into the public default layer, run a recent-overlap report: + +```bash +python scripts/evaluate_source_overlap.py \ + --source-url https://example.com/feed.xml \ + --source-name "Example Source" \ + --site-id example_candidate \ + --baseline data/archive.json \ + --lookback-days 7 \ + --output reports/source-intake/example-overlap.json +``` + +Interpretation: + +- `< 35%` hard duplicate rate: usually `accept_default`. +- `35%–65%`: keep as `watchlist` or OPML advanced source first. +- `>= 65%`: usually `skip_duplicate` unless the source is faster, more canonical, or has unusually valuable unique items. +- `< 5` recent candidate items: treat as too small and keep on `watchlist`. + +The report is advisory. Do not auto-delete existing sources or auto-promote a candidate solely from the score. Story-level merge / clustering is planned for a later version, not part of v0.3.0. + +## Validation Checklist + +Run: + +```bash +python -m py_compile scripts/update_news.py +pytest -q +python scripts/update_news.py --output-dir /tmp/ai-news-radar-data --window-hours 24 --archive-days 21 +``` + +Inspect `/tmp/ai-news-radar-data/source-status.json`: + +- source appears with `ok: true` +- `failed_sites` is empty or the failure is expected and documented +- item count is plausible +- AI-focused view is not flooded with off-topic items diff --git a/skills/ai-news-radar/references/upstream-project-readme.en.md b/skills/ai-news-radar/references/upstream-project-readme.en.md new file mode 100644 index 0000000..e8fe1c5 --- /dev/null +++ b/skills/ai-news-radar/references/upstream-project-readme.en.md @@ -0,0 +1,345 @@ +> Upstream reference from LearnPrompt/ai-news-radar@689395109cc962a27c369bdd6fa50d1e090eb319. Relative Markdown links target that immutable upstream snapshot. This reference is not a claim that upstream deployment workflows, development tests or private integrations are installed. + +
+ +# AI News Radar + +## 24h AI Updates Radar|Three-Persona Reviews + +**It finds the thoroughbreds among your sources, merges scattered updates into story timelines, then reviews each day's headlines from three distinct personas.** + +[![GitHub stars](https://img.shields.io/github/stars/LearnPrompt/ai-news-radar?style=flat-square&color=f5c542)](https://github.com/LearnPrompt/ai-news-radar/stargazers) +[![Live](https://img.shields.io/badge/Live-news.learnprompt.pro-green?style=flat-square)](https://news.learnprompt.pro) +[![Actions](https://img.shields.io/github/actions/workflow/status/LearnPrompt/ai-news-radar/update-news.yml?branch=master&label=update&style=flat-square)](https://github.com/LearnPrompt/ai-news-radar/actions/workflows/update-news.yml) +[![Agent Skills](https://img.shields.io/badge/Agent%20Skills-ai--radar%20%2B%20Scout-blueviolet?style=flat-square)](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/skills/radar/README.md) +[![License](https://img.shields.io/badge/license-MIT-green.svg?style=flat-square)](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/LICENSE) + +```bash +npx skills add LearnPrompt/ai-news-radar -s ai-radar -g +``` + +Then ask your agent: `What happened in AI today?` + +**Live site** → [news.learnprompt.pro](https://news.learnprompt.pro) (data source / fallback: [learnprompt.github.io/ai-news-radar](https://learnprompt.github.io/ai-news-radar/)) + +[中文](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/README.md) · [Radar Skill](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/skills/radar/README.md) · [Scout Skill](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/skills/ai-news-radar/README.md) · [Source strategy](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/docs/SOURCE_COVERAGE.md) + +**What's new**: v0.9 collapses the UI into a single-layer information architecture (category tabs × curated/all toggle × chronological timeline). The old three-view screenshots are archived at [`/legacy/`](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/legacy) and stay online until mid-August 2026. + +
+ +--- + +## Pick your lane in 30 seconds + +**① Let your agent read for you** → the install command above. One question, one brief. Zero API, zero key, zero server: + +![ai-radar demo](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/skills/radar/assets/demo.gif) + +**② Read the site directly** → open [news.learnprompt.pro](https://news.learnprompt.pro). It defaults to a mobile view, with a "view" switch in the top-right corner to jump to the classic desktop UI at `/classic/`; you can also force a view with `?view=mobile` / `?view=classic` / `?view=auto`. Both views read the same `data/` directory. Since v0.9 the UI is a single layer: top category tabs (All/Models/Products/Devtools/Industry/Research/Community/Creator), a curated/all-items global toggle, and a chronological main list grouped by date. The "current hotspots" board has no fixed cap. Every curated card carries a one-line "why it matters" review. When the same event is covered by multiple sources, the card collapses into a "N sources" chip you can expand. + +**③ Fork and own your own filter** → fork this repo, swap in your own OPML sources, edit a markdown file under `personas/` to change the taste, and the data grows on your own GitHub Pages. Jump to the [fork guide](#fork-guide-your-own-radar-in-five-steps). + +The three lanes are one road: let your agent read the brief → read the site yourself → run your own radar. + +--- + +## Sister sites · one pipeline + +The radar does the tracking; there is a station on each side. Start at [**AI MAP**](https://aimap.carlwow.com), a knowledge graph of who has been heating up over the last 7 days (refreshed every 12 hours), then come back here to dig into the sources. When a trend makes you want to build, [**GoodCase**](https://goodcase.carlwow.com) has ready-to-copy viral cases and prompts. Discover → track → use, one road. + +--- + +## What is this? + +AI News Radar is an auto-updating 24h radar for AI updates. It does more than fetch AI news. It judges source quality first, merges the same event into a story timeline, has three personas score and review the picks, then uses Scout picks, AI labels, source health, and AI ratio to help you decide: + +what is worth reading, what deserves deeper research, and what is just noise. + +Readers can open the page and scan the last 24 hours of AI, model, and developer-tool updates. Developers can fork this repo and connect their own OPML/RSS, public feeds, static pages, or AgentMail inboxes. Codex / Claude Code-style agents can use the in-repo **Scout Skill** to judge new sources, maintain fetch logic, and deploy to GitHub Pages. + +This project will never be "one more news page". + +Its core logic is **Scout Skill**. It helps you find the thoroughbreds among a pile of sources. Which sources are worth tracking long term? Which ones should become RSS/OPML inputs? Which ones only make sense through a paid API? Which sources update all day, but have less than 5% AI signal for what you actually care about? + +Judge first. Then connect. + + + + + + + + + + +
Mobile view (default) screenshotClassic desktop view (/classic/) screenshot
Mobile view (default on all devices)Classic view (top-right "view" switch, served at /classic/)
+ +## v0.9: single-layer IA + title enhancement + +v0.8's three views (Scout Picks / AI Signal Flow / Hot board) are now one layer: one set of category tabs, one curated/all toggle, one timeline. + +![AI News Radar v0.9 timeline screenshot](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/assets/screenshots/radar-v09-timeline.png) + +- **Dual view**: this single-layer IA now ships two UI skins — the root `index.html` defaults to mobile, and a "view" switch in the top-right corner jumps to the classic desktop skin at `/classic/`; both `?view=mobile` / `?view=classic` / `?view=auto` work directly as well. Both skins read the same `data/`, and the choice is remembered in local storage +- **Category tabs**: All/Models/Products/Devtools/Industry/Research/Community/Creator, mutually exclusive +- **Curated/all global toggle**: curated reads the merged, AI-relevant, high-value story pool; all reads the broader AI-relevant pool (`latest-24h-all.json`, score >= 0.3). Both modes share the same timeline + date-grouping template +- **Current hotspots board**: no fixed item cap — it shows however many stories clear the multi-source heat threshold, kept separate from the main list +- **Real, pipeline-generated reviews**: the one-line "why it matters" review on curated cards is now written by the pipeline itself — for items that already passed the AI-relevance filter, it fetches the full article and has DeepSeek write one sentence on why it's worth reading (requires `DEEPSEEK_API_KEY`). When there's no real review, the frontend simply hides that block instead of showing a template sentence +- **Same-event expansion**: when 2+ sources cover the same event, the card shows an "N sources" chip — expand it to see each source's own title, outlet, and relative time +- **Title enhancement**: when a title is too terse or jargon-heavy, the pipeline micro-crawls the source page for context (falling back to r.jina.ai on direct-fetch failure) and has an LLM rewrite it. Requires `DEEPSEEK_API_KEY`; without it, titles stay as-is and nothing else breaks +- **Source-quality hardening**: the zeli aggregator (Hacker News 24h hot list) no longer gets a blanket allowlist pass — it now goes through the same AI-relevance scoring as every other aggregator. Bilingual title translation also gained validation: refusal-style outputs (e.g. "sorry, I can't process link content") and degenerate translations are detected and rejected, falling back to the original title instead of showing garbled text +- **Data-source switch**: append `?data=` to the page URL to point the frontend at a different `data/` directory (e.g. to preview another branch's or PR's generated data). The choice persists in local storage, handy for multi-branch development +- **aggregator sub-source classification**: items from aggregator sites get a further breakdown chip — X / WeChat / HN / RSS — right after the channel chip + +## v0.8: three-persona reviews + +> Note: the **web display** of the three personas is temporarily parked (styling to be redesigned — see [docs/ROADMAP.md](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/docs/ROADMAP.md)); the data pipeline still scores and reviews every day, and the Skill daily brief is unaffected. + +Whether a story matters depends on who you are. v0.8 gives the daily brief swappable "tastes": + +| Persona | id | Angle | +|---------|----|----| +| **Pragmatist** (default) | `pragmatic` | Only cares what practitioners can use today | +| **Cynic** | `cynic` | Punctures marketing spin and hype — sarcastic, but grounded in facts | +| **Stickler** | `paper-police` | Only trusts papers/code/benchmarks; zero tolerance for "coming soon" | + +- The daily 20 picks are scored and reviewed by the default persona; stories that make the daily TOP3 get scored by all three personas — one story, three angles (the reviews live in `data/daily-brief.json` and `data/top3-personas.json`, consumed directly by the Skill brief). +- Each persona is one markdown file under `personas/` (frontmatter + system prompt). Change the taste by editing one file; create a new one following [personas/README.md](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/personas/README.md) and PR it to join the built-in list. +- LLM reviews require a `DEEPSEEK_API_KEY` upstream. Without it the whole pipeline still runs — it degrades gracefully to rule-based scores, and both the site and the skill keep working. + +## Why Scout Skill? + +Good updates are scattered everywhere. + +Official blogs publish one thing. Changelogs publish another. Someone drops an early signal on X. Aggregator sites keep reposting the same story. + +I thought I was tracking the frontier. Most days, I was repeating the same three chores: + +open dozens of pages, filter duplicates by hand, and guess which link was worth reading. + +Let Scout Skill handle the first pass: **which sources are thoroughbreds, and which ones are noise**. + +You can keep adding sources freely. You can also put a source into the input set, let it run for a week, and decide later whether it deserves to be promoted. + +AI News Radar was never just about fetching information. + +It is closer to a lightweight news pipeline: source judgement, fetching, deduplication, AI-relevance filtering, persona reviews, source health, and static web publishing. Once deployed, the core flow does not spend model tokens. + +## What it can do + +### For readers + +- Use the "All/Models/Products/Devtools/Industry/Research/Community/Creator" category tabs to jump straight to what you care about +- Use the curated/all global toggle: curated shows high-value story timelines; switch to all when you need to backfill or search the broader AI-relevant pool +- The main list is sorted newest-first and grouped by day, so you can scan what happened today vs. yesterday at a glance; "current hotspots" is a separate, uncapped board for what's hottest right now +- Every curated card carries a one-line "why it matters" review, written by the pipeline itself — the block is simply hidden when there's no real review +- When the same event is covered by multiple sources, the card shows an "N sources" chip — expand it to read each source's own title instead of clicking through duplicates +- If a title reads like jargon or an abbreviation, sites with `DEEPSEEK_API_KEY` configured will show the LLM-rewritten, more complete version +- Locate updates quickly with the specific-source filter and keyword search +- Use source health and AI ratio to tell which sources are actually useful, and which ones update a lot but contain little AI signal + +### For content creators + +- Preserve original source links for deeper research, fact checking, and topic planning +- Multiple sources covering the same event collapse into the card's "N sources" chip — expand it to compare each outlet's own title and wording, reducing duplicate reading +- Use AI labels to judge whether an item is better for a post, short video, or hands-on tool test +- Use signals such as multi-source overlap, official-first source, and single-source watch item to judge topic credibility and priority +- Persona reviews double as topic research: the Pragmatist says it's useful, the Cynic says it's spin, the Stickler says there's no evidence — the disagreement itself is content + +### For developers and agents + +- Requires no API key, login state, or LLM quota by default +- Supports official RSS/changelog sources, OPML/RSS, public GitHub feed/JSON files, static pages, and AgentMail +- GitHub Actions automatically generates `data/*.json` and publishes to GitHub Pages +- Codex / Claude Code / Hermes / OpenClaw can use the in-repo Scout Skill to maintain sources, fetch logic, and the web page +- For local or multi-branch development, use the page's `?data=` query param to point the frontend at a different `data/` directory without touching code or redeploying +- Advanced sources can be connected through GitHub Secrets or local environment variables, without committing tokens, cookies, private OPML files, or email bodies + +## How it works + +```mermaid +flowchart LR + source["Source list"] --> classify["Scout Skill classifies source type"] + + classify --> official["Official RSS / changelog"] + classify --> opml["Private OPML / RSS"] + classify --> publicFeed["Public GitHub feed / JSON"] + classify --> staticPage["Public page / Jina fallback"] + classify --> privateMail["AgentMail email subscription"] + classify --> skip["Skip risky sources"] + + official --> fetch["Fetch and structure"] + opml --> fetch + publicFeed --> fetch + staticPage --> fetch + privateMail --> fetch + + fetch --> dedup["Deduplicate and normalize"] + dedup --> score["AI-relevance scoring and labels"] + score --> story["Story merge and multi-source evidence"] + score --> status["Source health and AI-ratio stats"] + + story --> brief["Scout Picks / daily-brief.json"] + brief --> persona["Persona reviews / top3-personas.json"] + story --> merged["stories-merged.json / merge-log.json"] + status --> sourceData["source-status.json"] + score --> latest["latest-24h.json / latest-24h-all.json"] + + persona --> pages["GitHub Pages / Vercel web UI"] + brief --> pages + merged --> pages + sourceData --> pages + latest --> pages + + pages --> agent["Scout Skill: agents maintain sources"] + pages --> radar["ai-radar Skill: agents read the brief"] +``` + +AI News Radar borrows from modern newsroom workflows. Dumping thousands of items into a page is not useful, so the project turns news handling into a stable pipeline: fetch, deduplicate, filter, review, enrich with status, and generate a static site. + +It stays lightweight on purpose. The public version does not require an LLM API key, login state, cookies, X API access, or email access. When you need advanced sources, Scout Skill can connect them through GitHub Secrets or local environment variables. + +## Data outputs + +Each update generates a set of static JSON files. The page only reads these files and does not need a backend service. GitHub Pages is the canonical data source; the Vercel site is just another front for the same data. + +Core files include: + +- `data/daily-brief.json`: Scout Picks — 20 daily items; since v0.8 each carries persona score and review fields +- `data/top3-personas.json`: the daily TOP3 with all three persona reviews side by side +- `data/latest-24h.json`: AI-focused updates from the last 24 hours +- `data/latest-24h-all.json`: broadly AI-relevant updates from the last 24 hours (score >= 0.3) +- `data/latest-24h-all-raw.json`: unfiltered raw items from the last 24 hours (dev-only, not wired into the frontend) +- `data/source-status.json`: source fetch status, success rate, site coverage, and source health +- `data/stories-merged.json`: the complete merged story set +- `data/merge-log.json`: story-merge matches and debug records for auditing + +If `daily-brief.json` is not available yet, the page falls back to candidate Scout signals; if `stories-merged.json` exists, the page uses the full story pool to extend the timeline beyond the picks. + +## Fork guide: your own radar in five steps + +1. **Fork** [LearnPrompt/ai-news-radar](https://github.com/LearnPrompt/ai-news-radar). +2. **Enable Actions**: GitHub pauses workflows on forks by default — enable them on the Actions tab, and `update-news.yml` runs every 30 minutes. +3. **(Optional) Add `DEEPSEEK_API_KEY`**: Settings → Secrets and variables → Actions. This unlocks persona reviews, title enhancement, real pipeline-generated review lines for curated items, and more reliable Chinese title translation (refusal text and degenerate output fall back to the original title automatically). Without it everything still runs — rule-based scores, original titles, and Google Translate take over, and the review block simply doesn't render. The default model is `deepseek-v4-flash`; set a repo Variable `DEEPSEEK_MODEL` if you want a different one. Add `TITLE_ENHANCE_MAX_PER_RUN` too if you want to cap how many titles get rewritten per run (defaults to 30). +4. **Enable GitHub Pages**: Settings → Pages, serve the master branch root. Your radar is live minutes later. +5. **Change one line in the skill**: point the `BASE_URL` at the top of `skills/radar/SKILL.md` to `https://.github.io/ai-news-radar/data`, and your agent reads your data from now on. + +To change sources: put your subscriptions into `feeds/follow.opml` (see `feeds/follow.example.opml`), or let the in-repo [Scout Skill](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/skills/ai-news-radar/README.md) judge and ingest them. To change tastes: edit the markdown files under `personas/`. Unhappy with a translation: edit `translation-glossary.txt` in the repo root (protected terms + repair rules, format documented in the file) and the next pipeline run picks it up. Want your own domain: (optional) import the repo into Vercel — the included `vercel.json` is ready, zero build. Want to preview data from another branch while testing: append `?data=` to the page URL, no code changes needed. + +## Quick start (run locally) + +Readers do not need to install anything. Open the live site directly. + +To fork and customize your own version locally: + +```bash +git clone https://github.com/LearnPrompt/ai-news-radar.git +cd ai-news-radar +python3 -m venv .venv +source .venv/bin/activate +pip install -r requirements.txt +python scripts/update_news.py --output-dir data --window-hours 24 +python -m http.server 8080 +``` + +Open: + +```text +http://localhost:8080 +``` + +If you have your own OPML: + +```bash +cp feeds/follow.example.opml feeds/follow.opml +# Put your own subscriptions into feeds/follow.opml. Do not commit this file. +python scripts/update_news.py --output-dir data --window-hours 24 --rss-opml feeds/follow.opml +``` + +## Tutorial for agents + +If you want Codex / Claude Code / OpenClaw / Hermes to help you build your own version, say: + +```text +Use Scout Skill for AI News Radar. Ask me for my source list first, then decide whether each source should use RSS, public feeds, static pages, Jina fallback, AgentMail email, or be skipped. The goal is to deploy a serverless AI daily news site that updates automatically with GitHub Actions. Do not commit any API keys, cookies, tokens, or private email content into the repo. +``` + +The repo ships two skills — the radar reads, the scout selects: + +- `skills/radar/`: **ai-radar** (consumer side) — install without forking, ask AI news questions in natural language, get a brief from this site's public JSON +- `skills/ai-news-radar/`: **Scout Skill** (maintainer side) — after forking, use it to classify sources, maintain fetch logic, and deploy GitHub Pages + +When a new agent takes over validation, read these first: + +- `README.md` +- `README.en.md` +- `docs/GPT_HANDOFF.md` +- `docs/SOURCE_COVERAGE.md` +- `docs/V2_PRODUCT_BRIEF.md` + +## GitHub Actions updates + +`.github/workflows/update-news.yml` is already configured. + +- Supports manual `workflow_dispatch`; pass `force_tikhub=true` explicitly to override the normal paid-source interval for TikHub +- Runs every 30 minutes by default: `*/30 * * * *` +- Automatically generates and commits `data/*.json` +- With `DEEPSEEK_API_KEY` set, scores the daily picks with the default persona, generates the three-persona TOP3 reviews, enables title enhancement, generates real pipeline-written review lines for curated items, and gives better translation (refusal text and degenerate output fall back to the original title automatically); without it, falls back to rule-based scores, original titles, and Google Translate, and the review block doesn't render — the core pipeline still runs +- Default DeepSeek model is `deepseek-v4-flash` (DeepSeek is retiring the `deepseek-chat` alias on 2026-07-24); set a repo Variable `DEEPSEEK_MODEL` to override it +- With `TITLE_ENHANCE_MAX_PER_RUN` set, caps how many titles get rewritten per run; defaults to 30 +- Uses public demo `feeds/follow.example.opml` when `FOLLOW_OPML_B64` is not configured, so the hosted page can show the RSS/OPML path working +- Decodes `FOLLOW_OPML_B64` into private `feeds/follow.opml` when configured +- Generates a redacted email summary when `EMAIL_DIGEST_ENABLED=1`, `AGENTMAIL_API_KEY`, and `AGENTMAIL_INBOX_ID` are set +- Commits `data/email-digest.json` only when `EMAIL_DIGEST_PUBLISH=1` is also explicitly set +- Uses the official X API during the configured daily UTC window when `X_API_ENABLED=1`, `X_BEARER_TOKEN`, and budget variables are set. This is off by default, and the current X API charges by returned resources. +- Fetches a small number of public X/Twitter search results through SocialData.tools when `SOCIALDATA_ENABLED=1`, `SOCIALDATA_API_KEY`, and budget variables are set, at `SOCIALDATA_RUN_INTERVAL_HOURS` (default 12h) intervals. Off by default; keep the API key in local env vars or GitHub Secrets only. +- Fetches a small number of Douyin/Xiaohongshu keyword results through TikHub when `TIKHUB_ENABLED=1`, `TIKHUB_API_KEY`, and budget variables are set, at `TIKHUB_RUN_INTERVAL_HOURS` (default 24h) intervals. Off by default; keep the API key in local env vars or GitHub Secrets only. +- Paid-source intervals are tracked in `data/paid-source-state.json` — it stores only the last run time, result count, and error name, never API keys. When the half-hourly workflow skips paid sources, old items stay in `data/archive.json` instead of being dropped. + +By default, the core pipeline requires no API keys. + +The "updated at" time in the top-right corner of the live page comes from `generated_at` in `data/latest-24h.json`. If the page is stuck on an old time, first check whether the latest `Update AI News Snapshot` run in GitHub Actions succeeded, whether it hit fetch errors, and whether Pages deploys from the branch containing the latest `data/` commit. + +Advanced source templates live in `examples/advanced-sources.env.example`. + +Budget notes are in `docs/research/advanced-source-free-tier-budget-2026-05-10.md`. + +The X API demo config is in `docs/guides/x-api-demo-config.md`. + +The single-account / single-newsletter demo is in `docs/guides/rileybrown-alphasignal-demo.md`. + +## Version history + +| Version | The question it answers | Key capabilities | +|---------|------------------------|------------------| +| v0.6 | How do scattered messages become events? | Story merging, AI labels/scores, source health and AI ratio | +| v0.7 | With this many stories, what's hot? | Hot view (multi-source mass × time decay), community section, headline-style Top3, quality-over-quantity gate, scoring backtest tool, ai-radar consumer skill | +| v0.8 | Same story — whose take do you trust? | Three-persona reviews, TOP3 side-by-side, persona-as-markdown-file (editable, PR-able), Vercel public site | +| v0.9 | Three views coexist — how do they read as one news feed? | Single-layer IA (category tabs × curated/all × timeline), mobile/classic dual view, real pipeline-generated reviews, title enhancement, source-quality hardening, same-event multi-source expansion, data-source switching, aggregator sub-source classification | + +See [Releases](https://github.com/LearnPrompt/ai-news-radar/releases) for the full history. + +## Acknowledgements + +- [AI HOT](https://aihot.virxact.com): Chinese AI news aggregator, one of the sources +- [superpowers](https://github.com/obra/superpowers): skill engineering methodology +- [mattpocock/skills](https://github.com/mattpocock/skills): skill writing methodology + +## License + +[MIT](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/LICENSE) + +--- + +
+ +**更多好用 Skill · More Skills** → [learnprompt.pro/skills](https://learnprompt.pro/skills/) + +[鲁班·Skill打磨](https://github.com/LearnPrompt/luban-skill) · [庖丁·博主蒸馏](https://github.com/LearnPrompt/paoding-skill) · [蔡伦·对话造纸](https://github.com/LearnPrompt/cailun-skill) · [阿福·LLM Todo](https://github.com/LearnPrompt/afu-llm-todo) · [愚公·Loop工程](https://github.com/LearnPrompt/loop-engineering) · [搭子·结对开发](https://github.com/LearnPrompt/partner-skill) · [AI雷达·零API资讯](https://github.com/LearnPrompt/ai-news-radar) + +[淘金小镇·ClawHub日榜](https://github.com/LearnPrompt/skillrush-town) · [Irasutoya·正文配图](https://github.com/LearnPrompt/carl-irasutoya-illustrations) · [Humanize PPT·演讲系统](https://github.com/LearnPrompt/humanize-ppt) · [CC Harness·六件套](https://github.com/LearnPrompt/cc-harness-skills) · [微信读书教练](https://github.com/LearnPrompt/carl-weread) · [X Article发布](https://github.com/LearnPrompt/x-article-publisher-skill) + +**[LearnPrompt](https://github.com/LearnPrompt) 出品** · 公众号「卡尔的AI沃茨」 · [X @aiwarts](https://x.com/aiwarts) + +
diff --git a/skills/ai-news-radar/references/upstream-project-readme.md b/skills/ai-news-radar/references/upstream-project-readme.md new file mode 100644 index 0000000..969d3dc --- /dev/null +++ b/skills/ai-news-radar/references/upstream-project-readme.md @@ -0,0 +1,424 @@ +> Upstream reference from LearnPrompt/ai-news-radar@689395109cc962a27c369bdd6fa50d1e090eb319. Relative Markdown links target that immutable upstream snapshot. This reference is not a claim that upstream deployment workflows, development tests or private integrations are installed. + +
+ +# AI News Radar + +## 24小时AI更新雷达|三口味锐评 + +**先帮你从一堆信源里选出千里马,再把分散消息合并成故事线,最后用三种口味替你锐评每日头条。** + +[![GitHub stars](https://img.shields.io/github/stars/LearnPrompt/ai-news-radar?style=flat-square&color=f5c542)](https://github.com/LearnPrompt/ai-news-radar/stargazers) +[![Live](https://img.shields.io/badge/Live-news.learnprompt.pro-green?style=flat-square)](https://news.learnprompt.pro) +[![Actions](https://img.shields.io/github/actions/workflow/status/LearnPrompt/ai-news-radar/update-news.yml?branch=master&label=update&style=flat-square)](https://github.com/LearnPrompt/ai-news-radar/actions/workflows/update-news.yml) +[![Agent Skills](https://img.shields.io/badge/Agent%20Skills-ai--radar%20%2B%20%E4%BC%AF%E4%B9%90-blueviolet?style=flat-square)](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/skills/radar/README.md) +[![License](https://img.shields.io/badge/license-MIT-green.svg?style=flat-square)](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/LICENSE) + +```bash +npx skills add LearnPrompt/ai-news-radar -s ai-radar -g +``` + +装完对Agent说一句:`今天AI圈有什么?` + +**在线站** → [news.learnprompt.pro](https://news.learnprompt.pro)(数据源/备用:[learnprompt.github.io/ai-news-radar](https://learnprompt.github.io/ai-news-radar/)) + +[English](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/README.en.md) · [雷达Skill](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/skills/radar/README.md) · [伯乐Skill](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/skills/ai-news-radar/README.md) · [信息源策略](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/docs/SOURCE_COVERAGE.md) + +**更新说明**:v0.9 把界面收敛成单层信息架构(栏目 tab × 精选/全量 × 时间轴),旧的三视图截图存档于 [`/legacy/`](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/legacy),保留至 2026 年 8 月中旬。 + +
+ +--- + +## 30秒选边上车 + +**① 让Agent替你读报** → 上面那行安装命令,装完一句话拿简报,零API、零Key、零服务器: + +![ai-radar demo](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/skills/radar/assets/demo.gif) + +**② 直接看网页** → 打开 [news.learnprompt.pro](https://news.learnprompt.pro)。默认是手机版视图,右上角「视角」开关能切到经典版(旧版桌面界面,路径 `/classic/`),也可以直接用 `?view=mobile` / `?view=classic` / `?view=auto` 指定,两个视图读同一份 `data/` 目录数据。v0.9 起是单层信息架构:顶部「全部/模型/产品/开发者/行业/论文/社区/自媒体」栏目 tab + 「精选/全量」全局开关,主列表按时间倒序、按日分组,「当前热点」榜不设固定条数单独看当下最热。每条精选卡片自带一句话「推荐理由」;同一事件被多家信源报道时会折叠成「多源 N」标签,点开看每家独立标题。 + +**③ fork 拥有自己的筛子** → fork本仓库,信源换成你自己的 OPML,口味改 `personas/` 下的 markdown 文件,数据长在你自己的 GitHub Pages 上。跳到[fork 指南](#fork-指南五步拥有自己的雷达)。 + +三层是一条路:让Agent读报 → 自己看报 → 自己办报。 + +--- + +## 姊妹站 · 一条流水线 + +雷达管跟踪,上下游各有一站。先去 [**AI MAP** 热点图谱](https://aimap.carlwow.com) 一张图看最近 7 天谁在升温(每 12 小时刷新),锁定目标后回雷达深挖信源;看到想上手的热点,去 [**GoodCase** 用例库](https://goodcase.carlwow.com) 直接查现成案例和 Prompt。发现 → 跟踪 → 使用,三站一条路。 + +--- + +## 这是什么 + +AI News Radar是一个自动更新的24小时AI更新雷达。它不只是把AI新闻抓回来,会先判断信息源质量,把同一个事件合并成故事线,再用三种口味的 persona 替你打分点评,最后用伯乐精选、AI标签、源健康和AI占比帮你判断: + +什么信息值得看,什么值得深挖,什么只是噪音。 + +普通用户直接打开网页,看最近24小时AI、模型、开发者工具和技术生态更新。开发者可以fork这个仓库,接入自己的OPML/RSS、公开feed、静态页面或AgentMail邮箱。Codex / Claude Code这类 Agent 可以使用项目内置的 **伯乐Skill**,继续帮你判断新的信息源、维护抓取逻辑、部署 GitHub Pages。 + +这个项目永远都不会是"又一个新闻网页"。 + +它的核心逻辑是**伯乐Skill**,帮你从一堆信源里选出千里马。哪些源值得长期追踪,哪些源适合做成RSS/OPML,哪些源只能接付费的API,哪些源看起来更新很多但实际上跟你长期关注的方面比方AI只占了里面的5%不到。 + +先判断清楚,再接入。 + + + + + + + + + + +
手机版(默认视图)截图经典版(/classic/ 桌面视图)截图
手机版(所有设备默认)经典版(右上角「视角」开关,路径 /classic/)
+ +## v0.9:单层信息架构 + 标题增强 + +v0.8 的三视图(伯乐精选 / AI信号流 / 热点榜)合并成了一层:一套栏目 tab + 一个精选/全量开关 + 一条时间轴。 + +![AI News Radar v0.9 时间轴截图](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/assets/screenshots/radar-v09-timeline.png) + +- **双视图**:这套单层架构现在有两套 UI 皮肤——根目录 `index.html` 默认手机版,右上角「视角」开关可切到 `/classic/` 经典桌面版,也支持 `?view=mobile` / `?view=classic` / `?view=auto` 参数直接指定;两套皮肤读同一份 `data/`,选择记在浏览器本地 +- **栏目 tab**:全部/模型/产品/开发者/行业/论文/社区/自媒体,互斥单选 +- **精选/全量全局开关**:精选读故事合并后的AI强相关高价值池,全量读广义AI相关的原始池(`latest-24h-all.json`,score >= 0.3),两种模式共用同一套时间轴+日期分组模板 +- **当前热点**:不设固定条数,只要满足多信源热度阈值就上榜,跟主列表分开单独看 +- **推荐理由真实化**:精选条目的一句话推荐理由由管线侧真实生成——对过了 AI 相关性筛选的条目抓取全文,交给 DeepSeek 写一句「为什么值得读」(需要 `DEEPSEEK_API_KEY`);没有真实理由时前端直接隐藏这个区块,不再用模板句撑场面 +- **同一事件展开**:同一事件被 2 家以上信源报道时,卡片上出现「多源 N」标签,点开看每家独立标题、来源和相对时间 +- **标题增强**:标题过短或黑话过多时,会拿原文上下文(自家抓取失败时回退到 r.jina.ai)交给 LLM 改写得更完整;配 `DEEPSEEK_API_KEY` 才生效,没配就保留原标题,不影响其余流程 +- **源质量加固**:聚合源 zeli(Hacker News 24h 热榜)取消整榜白名单放行,改成和其他聚合源一样过同一套 AI 相关性打分;双语标题翻译新增校验,拒答文案(比如「抱歉,我无法处理链接内容」)和退化输出会被识别并回退到原文标题,不会把车轱辘话当标题显示 +- **数据同源开关**:给页面 URL 加 `?data=` 可以让前端读取另一份 `data/`(比如验证另一个分支或 PR 生成的数据),选择会记在浏览器本地,方便多分支开发时来回切换 +- **聚合源子来源分类**:聚合站点条目会按原始平台再细分成 X / 公众号 / HN / RSS 小标签,紧跟在来源 chip 之后 + +## v0.8:三口味 persona 锐评 + +> 注:三口味的**网页展示**已暂时下线归档(样式待重设计,见 [docs/ROADMAP.md](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/docs/ROADMAP.md));数据管线照常每日生成 persona 打分与点评,Skill 端日报不受影响。 + +同一条新闻,值不值得看取决于你是谁。v0.8 给日报装上了可换的"口味": + +| 口味 | id | 视角 | +|------|----|----| +| **实用派**(默认) | `pragmatic` | 只关心对开发者/从业者今天有什么用 | +| **毒舌评论员** | `cynic` | 拆穿营销话术和炒作,讥讽但基于事实 | +| **较真党** | `paper-police` | 只认论文/代码/benchmark 实证,对"即将推出"零容忍 | + +- 每日精选20条按默认口味打分点评,命中当日 TOP3 的故事再由三个口味分别打分,一条新闻三个角度(点评数据在 `data/daily-brief.json` 与 `data/top3-personas.json`,Skill 日报直接引用)。 +- 每个口味就是 `personas/` 目录下的一个 markdown 文件(frontmatter + system prompt)。想换口味,改一个文件;想造新口味,照 [personas/README.md](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/personas/README.md) 的格式写一个,PR 过来就能进内置列表。 +- 上游配了 `DEEPSEEK_API_KEY` 才有 LLM 点评;不配也能跑全流程,自动降级成规则分,页面和 Skill 都正常工作。 + +## 为什么需要伯乐Skill + +好新闻分散在各处, + +官方博客发一点,更新日志发一点,X上有人提前爆料,聚合站又把同一个新闻转来转去。 + +我以为的自己在追前沿,实际每天都在重复三件事, + +打开几十个页面,肉眼+人脑过滤重复内容,猜哪条值得看。 + +让伯乐Skill先替你完成第一轮判断,**哪些信源是千里马,哪些是噪音**。 + +你可以随意增加信息源,还可以把一个信息源纳入输入范围,先让它在单独运行一周,再判断要不要录入。 + +AI News Radar从来都不是单纯把信息抓回来, + +它更像是一条轻量的新闻pipeline,把来源判断、抓取、去重、AI强相关过滤、persona锐评、信息源健康状态和静态网页发布串起来,上线后核心流程不消耗模型额度。 + +## 能做什么 + +### 给普通读者 + +- 打开在线页面,用「全部/模型/产品/开发者/行业/论文/社区/自媒体」栏目 tab 快速定位关心的方向 +- 用「精选/全量」全局开关切换:精选看高价值故事线,需要补盲或检索时切到全量的广义AI相关原始池 +- 主列表按时间倒序、按日分组,一屏看清楚今天/昨天分别更新了什么;「当前热点」榜单独看当下最热,不设固定条数 +- 每条精选卡片带一句话「推荐理由」(管线侧真实生成,没有理由时这块不显示) +- 同一事件被多家信源报道时,卡片上会出现「多源 N」标签,点开看每家独立标题,不用分别点进重复新闻 +- 标题看不懂缩写或黑话时,配了 `DEEPSEEK_API_KEY` 的站点会用改写后的完整标题 +- 用具体来源和关键词搜索快速定位信息 +- 通过源健康和AI占比判断:哪些源是真有料,哪些源更新很多但AI含量低 + +### 给内容创作者 + +- 保留原始来源链接,方便继续深挖、核对事实和做选题 +- 同一个事件的多个来源折叠进卡片的「多源 N」标签,点开看每家独立标题,减少重复阅读也方便比对措辞差异 +- 用AI标签快速判断一条消息适合做图文、短视频、还是工具实测 +- 用多源重合、官方一手、单源观察等信号判断选题可信度和优先级 +- 三口味点评天然是选题参考:实用派说有用、毒舌说有诈、较真党说没证据,分歧本身就是内容 + +### 给开发者和Agent + +- 默认不需要 API Key、不需要登录态、不需要 LLM额度 +- 支持官方 RSS/changelog、精选 AI 媒体 RSS、OPML/RSS、公开 GitHub feed/JSON、静态页面、AgentMail 等来源类型 +- GitHub Actions自动生成 `data/*.json` 并发布到 GitHub Pages +- Codex / Claude Code / Hermes / OpenClaw 可以通过项目内置的伯乐Skill继续维护信源、抓取逻辑和页面 +- 本地/多分支开发可以用页面 `?data=` 参数切换前端读取的 `data/` 目录,不用来回改代码或部署 +- 高级来源可以通过 GitHub Secrets或本地环境变量接入,避免把 token、cookies、私有 OPML 和邮箱正文写进仓库 + +## 工作原理 + +```mermaid +flowchart LR + source["信息源清单"] --> classify["伯乐Skill判断信源类型"] + + classify --> official["官方 RSS / changelog"] + classify --> opml["私人 OPML / RSS"] + classify --> publicFeed["公开 GitHub feed / JSON"] + classify --> staticPage["公开页面 / Jina 兜底"] + classify --> privateMail["AgentMail 邮箱订阅"] + classify --> skip["跳过高风险来源"] + + official --> fetch["抓取与结构化"] + opml --> fetch + publicFeed --> fetch + staticPage --> fetch + privateMail --> fetch + + fetch --> dedup["去重与归一化"] + dedup --> score["AI相关性评分与标签"] + score --> story["故事合并与多源证据聚合"] + score --> status["源健康与AI占比统计"] + + story --> brief["伯乐精选 / daily-brief.json"] + brief --> persona["persona锐评 / top3-personas.json"] + story --> merged["stories-merged.json / merge-log.json"] + status --> sourceData["source-status.json"] + score --> latest["latest-24h.json / latest-24h-all.json"] + + persona --> pages["GitHub Pages / Vercel 网页"] + brief --> pages + merged --> pages + sourceData --> pages + latest --> pages + + pages --> agent["伯乐Skill:Agent 继续维护信源"] + pages --> radar["ai-radar Skill:Agent 读报出简报"] +``` + +AI News Radar学习了现代新闻学的技术,不是简单堆信息源,一次性放几万条信息出来等于没用,所以我选择把新闻处理拆成稳定pipeline,抓取,去重,过滤,锐评,补充状态,生成静态站点。 + +在保证稳定性的同时追求轻量化,公开版不要求用户配置LLM API Key,不依赖登录态,cookies,X API和邮箱。需要这些进阶能力时,可以通过伯乐Skill用GitHub Secrets或本地环境变量接入。 + +## 数据产物 + +每次更新会生成一组静态JSON文件,页面只读取这些文件,不需要后端服务。GitHub Pages 是数据的 canonical 源,Vercel 站只是同一份数据的另一个门面。 + +核心文件包括: + +- `data/daily-brief.json`:伯乐精选20条日报成品,v0.8 起含 persona 打分与点评字段 +- `data/top3-personas.json`:每日 TOP3 的三口味点评并排 +- `data/latest-24h.json`:最近24小时AI强相关消息 +- `data/latest-24h-all.json`:最近24小时广义AI相关消息(score >= 0.3) +- `data/latest-24h-all-raw.json`:最近24小时零过滤全量消息(dev-only,不接入前端UI) +- `data/source-status.json`:来源抓取状态、成功率、站点覆盖和源健康 +- `data/stories-merged.json`:故事合并后的完整事件集合 +- `data/merge-log.json`:故事合并过程和命中记录,方便调试与审计 + +如果 `daily-brief.json` 暂时不存在,页面会回退到候选信号列表;如果 `stories-merged.json` 存在,页面会用完整故事池补齐后续故事线,避免只有少量精选故事被接入。 + +## Fork 指南:五步拥有自己的雷达 + +1. **Fork** [LearnPrompt/ai-news-radar](https://github.com/LearnPrompt/ai-news-radar)。 +2. **开 Actions**:fork 后 GitHub 默认暂停 workflow,去 Actions 页点一下启用,`update-news.yml` 每30分钟自动跑。 +3. **(可选)配 `DEEPSEEK_API_KEY`**:Settings → Secrets and variables → Actions 加一个 secret,就能获得 persona 锐评、标题增强、精选条目的真实推荐理由,以及更可靠的中文标题翻译(拒答文案和退化输出会自动回退原标题)。不配也全流程能跑,自动降级成规则分、原始标题加谷歌翻译,推荐理由区块直接不显示。默认模型是 `deepseek-v4-flash`,需要换模型可以另配一个 Variable `DEEPSEEK_MODEL` 覆盖。想控制每次运行改写多少条标题,可以再配一个 `TITLE_ENHANCE_MAX_PER_RUN`(不配默认 30)。 +4. **开 GitHub Pages**:Settings → Pages,选 master 分支根目录。几分钟后你的雷达就活了。 +5. **改 skill 一行**:把 `skills/radar/SKILL.md` 顶部的 `BASE_URL` 换成 `https://<你的用户名>.github.io/ai-news-radar/data`,你的 Agent 从此读你自己的数据。 + +想换信源:把订阅写进 `feeds/follow.opml`(参考 `feeds/follow.example.opml`),或让内置[伯乐Skill](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/skills/ai-news-radar/README.md)帮你判断和录入。想换口味:改 `personas/` 下的 markdown 文件。翻译不满意:改根目录 `translation-glossary.txt`(保护术语 + 修正规则,文件内有格式说明),下次管线运行自动生效。想要自己的域名:(可选)把仓库 import 进 Vercel,仓库里的 `vercel.json` 已配好,零构建直接上线。想在验证阶段临时看另一份数据(比如自己分支跑出来的 `data/`):给页面 URL 加 `?data=` 即可,不用改代码。 + +## 快速开始(本地运行) + +普通用户不用安装,直接打开在线页面即可。 + +想fork改造新版本,可以本地运行: + +```bash +git clone https://github.com/LearnPrompt/ai-news-radar.git +cd ai-news-radar +python3 -m venv .venv +source .venv/bin/activate +pip install -r requirements.txt +python scripts/update_news.py --output-dir data --window-hours 24 +python -m http.server 8080 +``` + +打开: + +```text +http://localhost:8080 +``` + +如果你有自己的 OPML: + +```bash +cp feeds/follow.example.opml feeds/follow.opml +# 把自己的订阅源写进 feeds/follow.opml,不提交这个文件 +python scripts/update_news.py --output-dir data --window-hours 24 --rss-opml feeds/follow.opml +``` + +## 给Agent看的教程 + +如果你想让Codex / Claude Code / OpenClaw / Hermes帮你搭自己的版本,可以直接说: + +```text +请使用伯乐Skill,先问我要信息源清单,然后帮我判断每个信源该用RSS、公开feed、静态页面、Jina兜底、AgentMail邮箱还是跳过。目标是部署一个不需要服务器、能用GitHub Actions自动更新的 AI 日报网站。不要把任何API Key、cookies、token、私有邮件内容写入仓库。 +``` + +项目内置两个 Skill,分工是「雷达管读,伯乐管选」: + +- `skills/radar/`:**ai-radar 雷达Skill**(消费侧)——不用fork就能装,自然语言问AI资讯,读本站公开JSON出简报 +- `skills/ai-news-radar/`:**伯乐Skill**(维护侧)——fork后用它录入信源、维护抓取逻辑、部署 GitHub Pages + +新Agent接手验收时,推荐先读: + +- `README.md` +- `README.en.md` +- `docs/GPT_HANDOFF.md` +- `docs/SOURCE_COVERAGE.md` +- `docs/V2_PRODUCT_BRIEF.md` + +## GitHub 自动更新 + +`.github/workflows/update-news.yml` 已经配置好定时任务。 + +- 支持手动触发 `workflow_dispatch`;需要忽略 TikHub 的正常付费源间隔时,显式传入 `force_tikhub=true` +- 默认每 30 分钟运行一次:`*/30 * * * *` +- 自动生成并提交 `data/*.json`;工作流使用 `git add data/`,避免新增 JSON 文件因为白名单遗漏而停留在旧更新时间 +- 如果设置 `DEEPSEEK_API_KEY`,会给每日精选打 persona 分、生成三口味 TOP3 点评、启用标题增强、生成精选条目的真实推荐理由,并给出更可靠的中文翻译(拒答文案和退化输出会自动回退原标题);不设置时自动降级为规则分、原始标题和谷歌翻译,推荐理由区块不显示,核心流程照样跑 +- 默认 DeepSeek 模型是 `deepseek-v4-flash`(DeepSeek 官方将于 2026-07-24 弃用 `deepseek-chat` 别名),可以设置仓库 Variable `DEEPSEEK_MODEL` 覆盖 +- 如果设置 `TITLE_ENHANCE_MAX_PER_RUN`,会限制每次运行最多改写的标题条数;不设置默认 30 +- 如果没有设置 `FOLLOW_OPML_B64`,线上工作流会自动使用公开示例 `feeds/follow.example.opml`,让页面展示 RSS/OPML 能力 +- 如果设置 `FOLLOW_OPML_B64`,会优先自动解码为私有 `feeds/follow.opml` +- 如果设置 `EMAIL_DIGEST_ENABLED=1`,会生成脱敏邮箱摘要;`AGENTMAIL_PROVIDER=agently_cli` 通过已授权的 QQ Agent Mail CLI 读取 `message +list` 元数据,`AGENTMAIL_PROVIDER=api` 兼容旧 `AGENTMAIL_API_KEY` / `AGENTMAIL_INBOX_ID` 模式 +- 如果额外设置 `AGENTMAIL_RESOLVE_PUBLIC_URLS=1`,QQ Agent Mail CLI 模式会对每封候选邮件执行一次 `message +read`,只抽取 `Read online` / `View in browser` 这类公开 newsletter 链接;正文不会写入任何 JSON。没有公开链接的邮件不会进入 Radar 主列表,避免跳到私有邮箱首页 +- 只有额外设置 `EMAIL_DIGEST_INCLUDE_IN_RADAR=1`,才会把邮件 subject / snippet / sender domain / timestamp 作为独立 `agentmail` 源放进 Radar 主数据 +- AgentMail 进入 Radar 的标题会和其它英文源一样走双语标题流程:有 `DEEPSEEK_API_KEY` 时优先 DeepSeek 翻译,没有时回退谷歌翻译;翻译数量仍受 `--translate-max-new` / `--translate-max-new-broad` 限制 +- 只有额外设置 `EMAIL_DIGEST_PUBLISH=1`,才会提交 `data/email-digest.json` +- 如果设置 `X_API_ENABLED=1`、`X_BEARER_TOKEN` 和预算变量,会在每日指定UTC窗口用官方X API抓取少量公开Post;默认关闭,且当前X API按返回资源计费 +- 如果设置 `SOCIALDATA_ENABLED=1`、`SOCIALDATA_API_KEY` 和预算变量,会按 `SOCIALDATA_RUN_INTERVAL_HOURS`(默认12小时)通过 SocialData.tools 抓取少量公开 X/Twitter 搜索结果;默认关闭,API Key 只应放在本地环境变量或 GitHub Secrets +- 如果设置 `TIKHUB_ENABLED=1`、`TIKHUB_API_KEY` 和预算变量,会按 `TIKHUB_RUN_INTERVAL_HOURS`(默认24小时)通过 TikHub 抓取少量抖音/小红书关键词搜索结果;默认关闭,API Key 只应放在本地环境变量或 GitHub Secrets +- SocialData/TikHub 的拉取间隔会记录在 `data/paid-source-state.json`,只保存上次运行时间、结果数和错误名,不保存 API Key;半小时工作流跳过付费源时,旧条目仍保留在 `data/archive.json`,不会因为本轮未拉取就被清空 + +默认情况下,本项目不需要任何API Key就能跑核心流程。 + +线上页面右上角显示的"更新时间"来自 `data/latest-24h.json` 的 `generated_at`。如果页面长时间停在旧时间,优先检查 GitHub Actions 最近一次 `Update AI News Snapshot` 是否运行、是否有抓取错误、以及仓库 Pages 是否部署到包含最新 `data/` 提交的分支。 + +高级源配置模板见 `examples/advanced-sources.env.example`, + +预算说明见 `docs/research/advanced-source-free-tier-budget-2026-05-10.md`, + +本地测试 TikHub 抓取时可以先小流量强制跑一次: + +```bash +export TIKHUB_ENABLED=1 +export TIKHUB_API_KEY='你的 TikHub API Key' +export TIKHUB_FORCE_RUN=1 +export TIKHUB_QUERY='OpenAI,Claude,大模型,Agent,AI工具,人工智能,AI' +export TIKHUB_PLATFORMS=douyin,xiaohongshu +export TIKHUB_MAX_RESULTS=10 +export TIKHUB_DAILY_ITEM_LIMIT=10 +python3 scripts/probe_tikhub.py --query 'OpenAI,Claude,大模型,Agent,AI工具,人工智能,AI' --platforms douyin,xiaohongshu --max-results 10 +python3 scripts/update_news.py --output-dir /tmp/ai-news-radar-tikhub --window-hours 24 --archive-days 3 +python3 - <<'PY' +import json +from collections import Counter + +status = json.load(open("/tmp/ai-news-radar-tikhub/source-status.json")) +latest = json.load(open("/tmp/ai-news-radar-tikhub/latest-24h-all.json")) +print("failed_sites =", status.get("failed_sites")) +print("empty_advanced_sources =", status.get("empty_advanced_sources")) +print("tikhub_status =", [s for s in status.get("sites", []) if str(s.get("site_id", "")).startswith("tikhub")]) +counts = Counter(i.get("site_id") for i in latest.get("items_all_raw", [])) +print("tikhub_24h_counts =", {k: counts[k] for k in sorted(counts) if str(k).startswith("tikhub")}) +PY +``` + +远端需要用当前 `master` 立即重跑 TikHub 时: + +```bash +gh workflow run update-news.yml --ref master -f force_tikhub=true +``` + +自媒体栏目使用独立的 7 天热榜池,不改变其他栏目的 24 小时窗口。抖音和 +小红书搜索都优先请求"一周内最多点赞",再从响应中提取点赞、收藏、评论 +和分享数。榜单分数由 85% 互动热度和 15% 的 24 小时新鲜度加分组成;因此 +真正的周内爆款优先,但刚开始起量的新内容仍有机会进入 Top 3。 + +小红书按"先搜索、后详情"处理。搜索阶段使用 App V2 的最多点赞排序和 +7 天筛选,并再次在本地校验发布时间:可信 API 时间优先;`0`、未来时间 +或缺失时间会回退到 note id 的时间前缀;仍无法确认或早于 7 天的笔记会被 +跳过。通过时间门禁后,如需补齐图文详情,可按需调用官方详情接口: + +```python +import os +import requests + +headers = {"Authorization": f"Bearer {os.environ['TIKHUB_API_KEY']}"} + +search = requests.get( + "https://api.tikhub.io/api/v1/xiaohongshu/app_v2/search_notes", + headers=headers, + params={ + "keyword": "AI", + "page": 1, + "sort_type": "popularity_descending", + "note_type": "不限", + "time_filter": "一周内", + }, + timeout=30, +) +search.raise_for_status() + +# Only request details after the search result passes the local 7-day time gate. +detail = requests.get( + "https://api.tikhub.io/api/v1/xiaohongshu/app_v2/get_image_note_detail", + headers=headers, + params={"note_id": "通过时间校验的 note_id"}, + timeout=30, +) +detail.raise_for_status() +print(detail.json()) +``` + +视频笔记使用 `get_video_note_detail`。详情接口用于补充作者、互动量、图片、 +标签等结构化字段,不替代搜索阶段的发布时间判断。 + +X API演示配置见 `docs/guides/x-api-demo-config.md`; + +单账号/单newsletter演示见 `docs/guides/rileybrown-alphasignal-demo.md`。 + +## 版本演进 + +| 版本 | 回答的问题 | 关键能力 | +|------|-----------|---------| +| v0.6 | 分散消息怎么变成事件? | 故事线合并、AI标签分数、源健康与AI占比 | +| v0.7 | 故事多了,什么最热? | 热点视图(多源聚簇×时间衰减)、社区分类、头条式 Top3、宁缺毋滥门槛、评分回测工具、ai-radar 消费Skill | +| v0.8 | 同一条新闻,该听谁的? | 三口味 persona 锐评、TOP3 三味并排、口味即 markdown 文件(可改可PR)、Vercel 公网站 | +| v0.9 | 三个视图并存,怎么看着像一条新闻线? | 单层信息架构(栏目 tab×精选全量×时间轴)、手机版/经典版双视图、推荐理由真实生成、标题增强、源质量加固、同一事件多源展开、数据同源切换、聚合源子来源分类 | + +历次改动见 [Releases](https://github.com/LearnPrompt/ai-news-radar/releases)。 + +## 致谢 + +- [AI HOT](https://aihot.virxact.com):中文 AI 资讯聚合,信源之一 +- [superpowers](https://github.com/obra/superpowers):skill 工程方法论来源 +- [mattpocock/skills](https://github.com/mattpocock/skills):skill 编写方法论来源 + +## License + +[MIT](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/LICENSE) + +--- + +
+ +**更多好用 Skill · More Skills** → [learnprompt.pro/skills](https://learnprompt.pro/skills/) + +[鲁班·Skill打磨](https://github.com/LearnPrompt/luban-skill) · [庖丁·博主蒸馏](https://github.com/LearnPrompt/paoding-skill) · [蔡伦·对话造纸](https://github.com/LearnPrompt/cailun-skill) · [阿福·LLM Todo](https://github.com/LearnPrompt/afu-llm-todo) · [愚公·Loop工程](https://github.com/LearnPrompt/loop-engineering) · [搭子·结对开发](https://github.com/LearnPrompt/partner-skill) · [AI雷达·零API资讯](https://github.com/LearnPrompt/ai-news-radar) + +[淘金小镇·ClawHub日榜](https://github.com/LearnPrompt/skillrush-town) · [Irasutoya·正文配图](https://github.com/LearnPrompt/carl-irasutoya-illustrations) · [Humanize PPT·演讲系统](https://github.com/LearnPrompt/humanize-ppt) · [CC Harness·六件套](https://github.com/LearnPrompt/cc-harness-skills) · [微信读书教练](https://github.com/LearnPrompt/carl-weread) · [X Article发布](https://github.com/LearnPrompt/x-article-publisher-skill) + +**[LearnPrompt](https://github.com/LearnPrompt) 出品** · 公众号「卡尔的AI沃茨」 · [X @aiwarts](https://x.com/aiwarts) + +
diff --git a/skills/ai-news-radar/references/upstream-skill-readme.md b/skills/ai-news-radar/references/upstream-skill-readme.md new file mode 100644 index 0000000..7eeffb1 --- /dev/null +++ b/skills/ai-news-radar/references/upstream-skill-readme.md @@ -0,0 +1,497 @@ +> Upstream reference from LearnPrompt/ai-news-radar@689395109cc962a27c369bdd6fa50d1e090eb319. Relative Markdown links target that immutable upstream snapshot. This reference is not a claim that upstream deployment workflows, development tests or private integrations are installed. + +
+ +# 伯乐Skill + +> 从一堆信源里选出千里马。 + +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/LearnPrompt/ai-news-radar/blob/689395109cc962a27c369bdd6fa50d1e090eb319/LICENSE) +[![Claude Code](https://img.shields.io/badge/Claude%20Code-Skill-blueviolet)](https://claude.ai/code) +[![GitHub Pages](https://img.shields.io/badge/GitHub%20Pages-Ready-green)](https://pages.github.com/) + +
+ +**伯乐Skill is Scout Skill for AI News Radar.** + +它帮你判断哪些 AI 信息源值得长期追踪,并把它们接入一个自动更新的 AI 日报网站。 + +
+ +[在线示例](https://learnprompt.github.io/ai-news-radar/) · [安装](#安装) · [安装后第一句话](#安装后第一句话) · [快速录入信息源](#快速录入信息源) · [伯乐会选什么](#伯乐Skill会选什么) · [工作原理](#工作原理) + +
+ +--- + +## 它解决什么问题 + +一到假期,信息焦虑就会变严重。 + +不是没东西看,而是东西太多了。 + +RSS里一堆更新,X上有人分享新工具,飞书知识库里还有资料,聚合站每天刷出几十页。真正的问题变成了:我到底该看什么?哪些源值得长期追?哪些源只是制造噪音?怎么把这些东西变成每天真的能看的AI日报? + +AI News Radar原本是给自己用的AI日报网站,专门覆盖那些平时自然信息流里看不到的信息源。 + +但用了一段时间后,新的问题来了:如果一直往里面加信息源,它很快就会变成一天几千条、几万条更新。看起来很强,实际上还是看不完。 + +所以这次没有继续简单加源,而是在AI News Radar上做了一个Skill。 + +它叫:**伯乐Skill**。 + +伯乐Skill不是什么源都加。它只做一件事: + +**从乱七八糟的信源里,选出值得长期追踪的千里马。** + +--- + +## 在线示例 + +你可以先看公开版: + +https://learnprompt.github.io/ai-news-radar/ + +这个页面会持续更新AI、开发者、官方博客、技术聚合站和公开日报类来源。 + +它不是最终答案,而是一个可以fork、可以改、可以接入你自己信息源的起点。 + +--- + +## 安装 + +如果你只是想看日报,不需要安装,直接打开在线页面即可: + +```text +https://learnprompt.github.io/ai-news-radar/ +``` + +如果你想做自己的版本: + +```bash +git clone https://github.com/LearnPrompt/ai-news-radar.git +cd ai-news-radar +python3 -m venv .venv +source .venv/bin/activate +pip install -r requirements.txt +python scripts/update_news.py --output-dir data --window-hours 24 +python -m http.server 8080 +``` + +然后打开: + +```text +http://localhost:8080 +``` + +如果你在Claude Code、Codex或其他支持Skill的Agent里使用,请让Agent读取: + +```text +skills/ai-news-radar/SKILL.md +``` + +--- + +## 安装后第一句话 + +安装或fork之后,不知道怎么开始,就直接对Agent说: + +```text +请使用伯乐Skill,先问我要信息源清单,然后帮我判断每个信源该用 RSS、OPML、公开 feed、静态页面、Jina 兜底、AgentMail 邮箱还是跳过。目标是部署一个不需要服务器、能用 GitHub Actions 自动更新的 AI 日报网站。不要把任何 API Key、cookies、token、真实 OPML、邮箱正文或私有邮件内容写入仓库。 +``` + +这句话的作用是把Agent拉回正确路线:先判断来源,再决定接入方式,不要一上来乱抓网页。 + +--- + +## 快速录入信息源 + +你可以直接把信息源丢给伯乐Skill。 + +```text +我想用伯乐Skill搭一个自己的AI日报网站。 + +这是我常看的信息源: + +1. https://openai.com/news/ +2. https://www.anthropic.com/news +3. https://huggingface.co/blog +4. https://news.ycombinator.com/ +5. 一个OPML文件:feeds/follow.opml +6. 一个AgentMail收件箱:newsletter@你的inbox.agentmail.to +7. 一些我关注的X账号:karpathy、sama、nearcyan + +请你帮我完成: + +1. 判断每个源适合用RSS、OPML、公开页面、GitHub feed、AgentMail邮箱,还是需要跳过。 +2. 能用RSS/OPML的优先用RSS/OPML。 +3. AgentMail只作为私有进阶源,默认不发布完整正文。 +4. 不要把需要登录、cookies、token的来源作为默认公共源。 +5. 把适合公开内置的源加入项目。 +6. 把私人订阅源放进本地OPML、AgentMail或GitHub Secret方案。 +7. 本地跑一次数据生成。 +8. 如果通过验证,指导我部署到GitHub Pages。 +``` + +如果你想让用户按表格录入,可以用这个版本: + +```text +请使用伯乐Skill,帮我搭建自己的AI日报网站。 + +你先让我按下面格式填写信息源: + +| 名称 | URL或账号 | 类型 | 是否私人 | 我为什么想看它 | +|---|---|---|---|---| +| OpenAI News | https://openai.com/news/ | 网站/RSS | 否 | 官方更新 | +| Karpathy | @karpathy | X账号 | 否 | AI观点 | +| 我的RSS列表 | follow.opml | OPML | 是 | 个人订阅 | +| Newsletter收件箱 | AgentMail inbox | 邮箱 | 是 | 产品周报和newsletter | + +填完后,请你帮我判断哪些能直接接入、哪些应该进入OPML、哪些不适合接入、哪些需要Jina兜底、哪些需要以后用私有集成处理。然后生成本地日报数据,并指导我部署到GitHub Pages。 +``` + +--- + +## 伯乐Skill会选什么 + +伯乐Skill主要会选五类东西。 + +| 能力 | 说明 | +|---|---| +| 信息源判断 | 判断一个网站适合RSS、OPML、静态解析、公开JSON,还是不适合接入 | +| 去重和过滤 | 把聚合站、日报、RSS里的重复信息压下去 | +| AI信号识别 | 区分真正的AI相关内容和只是蹭到关键词的噪音 | +| 源健康检查 | 看每个源是否还活着、每天贡献多少信息 | +| 静态部署 | 不买服务器,用GitHub Actions和GitHub Pages自动更新日报网站 | + +伯乐Skill的目标不是让你看更多信息。 + +它的目标是让你少看垃圾信息。 + +--- + +## 支持的信息源类型 + +| 类型 | 推荐程度 | 说明 | +|---|---|---| +| 官方RSS / Atom | 高 | 最稳定,优先使用 | +| OPML | 高 | 适合批量导入个人RSS订阅 | +| 公开GitHub生成Feed | 高 | 适合Follow Builders这类公开数据源 | +| 公开Newsletter归档 | 中 | 优先用公开页面或公开feed | +| 聚合站分页 | 中 | 可覆盖盲区,但需要去重和过滤 | +| X / Twitter | 中低 | 优先使用稳定的公开中间feed,不建议默认依赖账号登录 | +| 飞书知识库 | 进阶 | 适合个人知识库场景,不建议作为公共默认源 | +| AgentMail邮箱 | 进阶 | 适合newsletter、产品周报、GitHub通知;默认关闭,只输出脱敏摘要 | +| 需要登录的网站 | 谨慎 | 会引入cookies、额度和稳定性问题,不建议默认接入 | + +--- + +## 为什么不用Agent一直跑 + +AI日报不应该每次都依赖Agent临时执行。 + +伯乐Skill采用的是更稳定的路径: + +```text +信息源 → 抓取 → 去重 → 过滤 → 结构化JSON → GitHub Pages网页 +``` + +数据更新可以交给GitHub Actions定时运行。 + +这意味着: + +- 不需要买服务器 +- 不需要每天手动运行 +- 不需要每次消耗Agent额度 +- 手机、iPad、电脑都能打开 +- fork之后可以变成你自己的日报站 + +Agent负责帮你判断、配置和维护信息源。真正的日报更新,交给自动化流程。 + +--- + +## 工作原理 + +伯乐Skill处理信息源时,会做四步。 + +**1. 来源分类** + +先判断来源属于哪一类: + +```text +RSS / Atom +OPML +公开GitHub feed +公开网页 +聚合站分页 +X桥接源 +私有知识库 +AgentMail邮箱 +需要登录的来源 +``` + +不同来源走不同策略。能用RSS就不用网页解析。能用公开feed就不重写爬虫。AgentMail只作为私有邮箱情报入口,适合newsletter和产品周报,不作为公共默认源。需要登录和cookies的来源,不放进公共默认配置。 + +**2. 抓取和结构化** + +把不同来源抓到的数据统一整理成结构化JSON。 + +这样Agent可以读,网页也可以读。 + +**3. 去重和AI过滤** + +对重复标题、重复链接、聚合站转载进行去重。 + +同时区分AI强相关、全量信息和原始覆盖池。宽泛词不会单独决定一条新闻是不是AI新闻。比如`agent`可能是AI Agent,也可能只是普通代理。 + +**4. 静态部署** + +最后输出到`data/*.json`,再通过GitHub Pages展示。 + +默认数据由GitHub Actions定时更新。 + +--- + +## 源健康和信息密度 + +伯乐Skill不是只会加源,也会帮你淘汰源。 + +页面会展示源健康和信息密度,比如: + +```text +源是否正常 +最近是否更新 +每天贡献多少条信息 +AI强相关内容占比 +``` + +一个简单的淘汰标准: + +```text +如果一个源连续一周平均每天贡献不到1条有价值信息,就可以考虑移除。 +``` + +这比无限加源更重要。 + +因为AI日报的敌人不是信息不够,而是噪音太多。 + +--- + +## OPML支持 + +如果你是RSS老玩家,可以直接用OPML批量导入订阅源。 + +本地方式: + +```bash +cp feeds/follow.example.opml feeds/follow.opml +# 把你的OPML内容放进 feeds/follow.opml +python scripts/update_news.py --output-dir data --window-hours 24 --rss-opml feeds/follow.opml +``` + +注意: + +```text +feeds/follow.opml 是你的私人订阅文件,不要提交到公开仓库。 +``` + +如果要部署到GitHub Actions,建议把OPML转成base64,放进GitHub Secret: + +```bash +base64 < feeds/follow.opml | pbcopy +``` + +然后在仓库Secrets里添加: + +```text +FOLLOW_OPML_B64 +``` + +--- + +## AgentMail邮箱情报入口 + +如果你希望Newsletter、产品周报、GitHub通知进入日报链路,可以创建一个专门给AI日报使用的AgentMail收件箱。 + +本地方式: + +```bash +npm install -g @tencent-qqmail/agently-cli +agently-cli auth login +export EMAIL_DIGEST_ENABLED=1 +export AGENTMAIL_PROVIDER=agently_cli +export AGENTMAIL_ALLOWED_SENDER_DOMAINS=tldrnewsletter.com,daily.therundown.ai +# 只有明确想把邮件元数据放进主 Radar 时才打开: +export EMAIL_DIGEST_INCLUDE_IN_RADAR=1 +python scripts/update_news.py --output-dir data --window-hours 24 +``` + +安全默认值: + +```text +默认不启用AgentMail。 +QQ Agent Mail 路径默认只调用 agently-cli message +list。 +旧 API 路径只调用 GET /v0/inboxes/{inbox_id}/messages。 +默认不读取 /raw,不读取 message +read,不读取 text/html 正文。 +默认只输出脱敏后的标题、预览片段、发件域名、链接、附件数量和时间。 +默认不把邮件元数据加入主 Radar,只有设置 EMAIL_DIGEST_INCLUDE_IN_RADAR=1 才会加入。 +GitHub Actions默认不会提交 data/email-digest.json;只有设置 EMAIL_DIGEST_PUBLISH=1 才会提交。 +``` + +建议把AgentMail理解成“AI日报的专用情报收件箱”,不是读取你的私人邮箱。 + +--- + +## 安全边界 + +伯乐Skill默认不会要求你提供API Key。 + +公开仓库里也不应该出现: + +```text +API Key +cookies +token +.env +真实OPML订阅文件 +邮箱正文或私有邮件内容 +AgentMail API Key或Inbox ID +浏览器登录态 +``` + +推荐做法: + +- 公共默认源只使用稳定公开来源 +- 私人订阅放进OPML +- AgentMail只作为私有进阶源,默认关闭 +- OPML不要提交到仓库 +- GitHub Actions里用Secret保存私有配置 +- 需要登录的网站不要作为默认抓取源 + +一个AI日报项目,自己用可以粗糙一点。一旦开源,就要替fork用户提前挡坑。 + +--- + +## 适合谁 + +伯乐Skill适合这些人: + +- 每天需要追AI新闻的人 +- 有一堆RSS订阅但看不过来的人 +- 想把X、博客、聚合站、Newsletter统一到一个页面的人 +- 想fork一个自己的AI日报站的人 +- 想让Codex或Claude Code长期维护信息源的人 +- 想做自媒体选题雷达的人 + +不适合这些场景: + +- 想实时监控所有新闻 +- 想抓取需要登录的网站 +- 想把私人邮箱、AgentMail API Key和cookies直接塞进公开项目 +- 想用它替代完整RSS阅读器 + +伯乐Skill不是万能信息中台。它更像一个AI信号雷达。 + +--- + +## 仓库结构 + +```text +ai-news-radar/ +├── index.html +├── assets/ +│ ├── app.js +│ └── styles.css +├── data/ +│ ├── latest-24h.json +│ ├── latest-24h-all.json +│ ├── source-status.json +│ ├── email-digest.json # 可选,AgentMail开启后生成 +│ └── archive.json +├── feeds/ +│ ├── follow.example.opml +│ └── social-x.example.opml +├── scripts/ +│ └── update_news.py +├── docs/ +│ ├── SOURCE_COVERAGE.md +│ ├── GPT_HANDOFF.md +│ └── V2_PRODUCT_BRIEF.md +└── skills/ + └── ai-news-radar/ + ├── SKILL.md + ├── README.md + └── references/ +``` + +--- + +## English + +> Find the thoroughbred sources before they enter the radar. + +**Scout Skill** is the English-facing name for 伯乐Skill in AI News Radar. It helps you choose high-signal AI sources worth tracking instead of blindly adding every noisy feed. + +It classifies and ingests sources from RSS, OPML, public websites, GitHub-generated feeds, newsletters, X-related feeds, and private knowledge bases, then deploys the result as a GitHub Pages site. + +It does not try to know everything. + +It only helps AI News Radar find sources worth tracking. + +**Live demo:** + +https://learnprompt.github.io/ai-news-radar/ + +**Repository:** + +https://github.com/LearnPrompt/ai-news-radar + +### Quick prompt after install + +```text +Use Scout Skill to help me build my own AI daily radar. + +First read README.md, docs/SOURCE_COVERAGE.md, docs/GPT_HANDOFF.md, and skills/ai-news-radar/SKILL.md. + +Then ask me for my source list: websites, RSS feeds, OPML files, X accounts, newsletters, GitHub projects, or private knowledge bases. + +For each source, classify whether it should be handled as RSS, OPML, public feed, static page, Jina fallback, optional private integration, or skipped. + +Prefer stable public sources. Do not commit API keys, cookies, tokens, private OPML files, or email contents. + +After classification, generate the local data, verify the JSON output, and guide me through GitHub Pages deployment. +``` + +--- + +## 背后的故事 + +伯乐Skill是在一次假期信息焦虑里做出来的。 + +我一边自驾,一边用语音把需求丢给Codex。想到一个源、一个过滤规则、一个页面问题,就让Agent继续改。 + +最后它变成了一个很适合AI时代的东西:不是让AI帮我多看一点信息,而是让AI帮我少看一点垃圾信息。 + +所以它叫伯乐Skill:先选千里马,再上雷达。 + +它看的不是天下大事。它先看的,是哪些信源值得进入雷达。 + +--- + +## License + +MIT — 随便用,随便改,随便让它帮你选千里马。 + +--- + +
+ +**RSS阅读器**帮你订阅信息。 +**AI News Radar**帮你展示AI信号。 +**伯乐Skill**帮你判断哪些信源是值得长期追踪的千里马。 + +
+ +*从一堆信源里选出千里马。* + +
diff --git a/skills/ai-news-radar/references/v2-method.md b/skills/ai-news-radar/references/v2-method.md new file mode 100644 index 0000000..2eb3974 --- /dev/null +++ b/skills/ai-news-radar/references/v2-method.md @@ -0,0 +1,101 @@ +# V2 Method + +Use this reference when AI News Radar work is about product direction, source +coverage, or packaging the repo as a reusable Skill. + +## Method Inputs + +- **Office Hours style**: understand demand, status quo, narrowest wedge, and + alternatives before committing to a product direction. +- **Superpowers style**: turn the chosen direction into a small spec, exact file + plan, tests, review, and verification before calling the work complete. + +## Product Diagnostic + +Run this before expanding features: + +1. **User**: ordinary AI enthusiast, maintainer, or agent using the Skill? +2. **Current workaround**: noisy timelines, manual site checks, RSS reader, email, + or another aggregator? +3. **Demand evidence**: is the user asking for breadth, speed, trust, or fewer + choices? +4. **Narrowest useful default**: what can ship without asking a new user to + configure keys, inboxes, cookies, or many toggles? +5. **Advanced escape hatch**: what belongs in OPML, GitHub Secrets, or a local + adapter instead of the public default? +6. **Success signal**: what should improve in `source-status.json`, the Signal + view, or the maintainer workflow? + +Ask the user only when a missing answer changes the implementation choice. For +mobile users, prefer one short multiple-choice question. + +## Approach Selection + +For unclear product choices, compare 2-3 approaches: + +- **Minimal viable**: smallest diff, safest public default, fastest validation. +- **Durable architecture**: cleaner long-term extension point, better tests or + docs, more future-proof source coverage. +- **Packaged variant**: makes the project easier for Codex/Claude users to fork, + customize, and deploy as their own AI news radar. + +Recommend one approach and state what evidence would make the recommendation +wrong. + +## Source Coverage Ladder + +Use the highest stable rung available: + +1. Official RSS/Atom/JSON from the source owner. +2. Public GitHub-generated feed files produced by a maintained repo. +3. Public newsletter archive or archive RSS. +4. Public static page with stable timestamps and selectors. +5. OPML for personal or niche feeds. +6. Optional API adapter with user-owned secrets. +7. Private inbox, cookies, browser sessions, or unstable bridges. + +Rungs 1-4 can become public defaults if they are useful to most visitors. Rungs +5-7 belong in advanced documentation unless the user explicitly wants a private +fork. + +## GitHub Feed Intake + +When given a GitHub repo that collects news: + +1. Read `README*`, `.github/workflows/*`, `config/*`, and generated feed files. +2. Identify whether the repo already uses official APIs or cron jobs centrally. +3. Prefer consuming its public raw output instead of copying its crawler. +4. Verify schema fields: title/text, canonical URL, source/person, timestamp, + stable ID, and generation cadence. +5. Add tests around parser behavior before relying on it as a built-in source. + +This is the preferred pattern for X-heavy projects such as curated builder feeds: +the public repo owns API credentials, this project consumes only public JSON. + +## Engineering Loop + +Keep implementation disciplined: + +1. Map files before editing. +2. For behavior changes, add focused parser/filter tests. +3. Implement the smallest code path that passes the test. +4. Run `python -m py_compile scripts/update_news.py` and `pytest -q`. +5. For Skill changes, run the Skill validator. +6. For source changes, run a local generation into `/tmp` and inspect + `source-status.json`. +7. After push, watch GitHub Actions and Pages deployment when relevant. + +Do not claim a source is covered until a fetcher, OPML path, public generated +feed path, or optional-secret path is documented and validated. + +## V2 Definition Of Done + +A v2 change is complete when: + +- The default page remains simple for ordinary users. +- The first viewport shows source health and coverage as status signals, not a + pile of configuration controls. +- Source coverage is documented as public default vs advanced/private. +- New built-in sources have stable timestamps and do not require secrets. +- Failures are visible in `source-status.json` instead of silently disappearing. +- The Skill tells future agents how to add, reject, or route similar sources. diff --git a/skills/ai-news-radar/requirements.txt b/skills/ai-news-radar/requirements.txt new file mode 100644 index 0000000..c675886 --- /dev/null +++ b/skills/ai-news-radar/requirements.txt @@ -0,0 +1,4 @@ +requests==2.32.3 +beautifulsoup4==4.12.3 +feedparser==6.0.11 +python-dateutil==2.9.0.post0 diff --git a/skills/ai-news-radar/scripts/__init__.py b/skills/ai-news-radar/scripts/__init__.py new file mode 100644 index 0000000..bff7763 --- /dev/null +++ b/skills/ai-news-radar/scripts/__init__.py @@ -0,0 +1 @@ +# Package marker for tests. diff --git a/skills/ai-news-radar/scripts/ai_relevance.py b/skills/ai-news-radar/scripts/ai_relevance.py new file mode 100644 index 0000000..51edec4 --- /dev/null +++ b/skills/ai-news-radar/scripts/ai_relevance.py @@ -0,0 +1,433 @@ +#!/usr/bin/env python3 +"""Explainable AI relevance scoring for news records.""" + +from __future__ import annotations + +import re +from typing import Any +from urllib.parse import urlparse + +AI_KEYWORDS = [ + "a.i.", + "agent view", + "agent skills", + "for agents", + "parallel agent", + "并行 agent", + "known agents", + "hermes-agent", + "agentmemory", + "aigc", + "llm", + "gpt", + "claude", + "gemini", + "deepseek", + "openai", + "anthropic", + "grok", + "copilot", + "codex", + "mcp", + "hugging face", + "huggingface", + "transformer", + "prompt", + "diffusion", + "多模态", + "交互模型", + "变换器", + "语言模型", + "视觉语言模型", + "基础模型", + "本地模型", + "具身智能", + "大模型", + "人工智能", + "机器学习", + "深度学习", + "智能体", + "算力", + "推理", + "微调", +] + +TECH_KEYWORDS = [ + "robot", + "robotics", + "embodied", + "autonomous", + "vision", + "chip", + "semiconductor", + "cuda", + "npu", + "gpu", + "cloud", + "developer", + "benchmark", + "dataset", + "eval", + "evaluation", + "sandbox", + "context", + "开源", + "技术", + "编程", + "软件", + "沙箱", + "上下文", + "芯片", + "机器人", + "具身", +] + +NOISE_KEYWORDS = [ + "娱乐", + "明星", + "八卦", + "足球", + "篮球", + "彩票", + "情感", + "旅游", + "美食", +] + +COMMERCE_NOISE_KEYWORDS = [ + "淘宝", + "天猫", + "京东", + "拼多多", + "券后", + "热销总榜", + "促销", + "优惠", + "补贴", + "下单", + "首发价", +] + +UNSAFE_HARD_PATTERNS = [ + re.compile(r"\bcreampie\b", re.I), + re.compile(r"\bblowjob\b", re.I), + re.compile(r"\bsuck (?:your|my) (?:dick|cock)\b", re.I), + re.compile(r"中出|婊子|吸你的鸡鸡|操虚拟女友", re.I), +] + +UNSAFE_PROMO_PATTERNS = [ + re.compile(r"\b(?:nsfw|nudes?|porn(?:ography)?)\b", re.I), + re.compile(r"\buncensored pictures?\b", re.I), + re.compile(r"\bvirtual girlfriends?\b", re.I), + re.compile(r"\bknock her up\b", re.I), + re.compile(r"未经审查的图片|虚拟女友|色情内容|成人内容", re.I), +] + +EN_SIGNAL_RE = re.compile( + r"(?i)(? bool: + h = haystack.lower() + return any(k in h for k in keywords) + + +def contains_unsafe_promotional_content(text: str) -> bool: + """Block explicit adult promotion without hiding a single policy/news mention.""" + if any(pattern.search(text) for pattern in UNSAFE_HARD_PATTERNS): + return True + return sum(bool(pattern.search(text)) for pattern in UNSAFE_PROMO_PATTERNS) >= 2 + + +def matched_keywords(haystack: str, keywords: list[str]) -> list[str]: + h = haystack.lower() + return sorted({k for k in keywords if k in h}) + + +def contains_meaningful_ai_signal(haystack: str) -> bool: + h = haystack.lower() + if MEANINGFUL_EN_SIGNAL_RE.search(h): + return True + if CURSOR_SIGNAL_RE.search(h): + return True + return any(k in h for k in AI_KEYWORDS if k not in BROAD_AI_TERMS) + + +def _label_for_text(text: str, has_tech: bool) -> str: + for label, keywords in LABEL_KEYWORDS: + if contains_any_keyword(text, keywords): + return label + if has_tech: + return "ai_tech" + return "ai_general" + + +def _result( + *, + is_ai_related: bool, + score: float, + label: str, + reason: str, + signals: list[str] | None = None, + noise: list[str] | None = None, +) -> dict[str, Any]: + return { + "is_ai_related": bool(is_ai_related), + "score": round(max(0.0, min(1.0, score)), 2), + "label": label, + "reason": reason, + "signals": signals or [], + "noise": noise or [], + } + + +def score_ai_relevance(record: dict[str, Any]) -> dict[str, Any]: + """Return an explainable relevance score while preserving the old keep/drop behavior.""" + site_id = str(record.get("site_id") or "") + title = str(record.get("title") or "") + source = str(record.get("source") or "") + site_name = str(record.get("site_name") or "") + url = str(record.get("url") or "") + # Keyword matching is substring-based, so only the URL host may participate: + # full URLs (e.g. Google News base64 paths) randomly contain substrings like + # "llm"/"gpt" and turn unrelated world news into "AI" items. + try: + url_host = (urlparse(url).netloc or "").lower() + except Exception: + url_host = "" + text = f"{title} {source} {site_name} {url_host}".lower() + + ai_signals = matched_keywords(text, AI_KEYWORDS) + if CURSOR_SIGNAL_RE.search(text) and "cursor" not in ai_signals: + ai_signals = sorted(ai_signals + ["cursor"]) + tech_signals = matched_keywords(text, TECH_KEYWORDS) + noise = matched_keywords(text, NOISE_KEYWORDS) + matched_keywords(text, COMMERCE_NOISE_KEYWORDS) + source_prior = SOURCE_PRIORS.get(site_id, 0.0) + + if contains_unsafe_promotional_content(text): + return _result( + is_ai_related=False, + score=0.0, + label="unsafe_content", + reason="unsafe_promotional_content", + signals=[], + noise=["unsafe_promotional_content"], + ) + + if site_id == "curated_media": + source_l = source.lower() + title_l = title.lower() + trusted_source = contains_any_keyword(source_l, CURATED_MEDIA_TRUSTED_SOURCE_KEYWORDS) + research_source = contains_any_keyword(source_l, CURATED_MEDIA_RESEARCH_SOURCE_KEYWORDS) + title_has_ai = contains_meaningful_ai_signal(title_l) + title_has_broad_ai = contains_any_keyword(title_l, list(BROAD_AI_TERMS)) or EN_SIGNAL_RE.search(title_l) is not None + title_has_research = contains_any_keyword(title_l, CURATED_MEDIA_RESEARCH_TERMS) + + if research_source and not (title_has_ai or title_has_research): + return _result( + is_ai_related=False, + score=0.22, + label="source_scope_drop", + reason="curated_research_source_requires_research_or_ai_title_signal", + signals=ai_signals + tech_signals, + noise=noise, + ) + + if not (trusted_source or research_source or title_has_ai or (title_has_broad_ai and bool(tech_signals))): + return _result( + is_ai_related=False, + score=source_prior + (0.28 if title_has_broad_ai else 0.0), + label="source_scope_drop", + reason="curated_media_requires_ai_title_or_trusted_ai_feed", + signals=ai_signals + tech_signals, + noise=noise, + ) + + if research_source or title_has_research: + label = "research_paper" + elif contains_any_keyword(title_l, CURATED_MEDIA_BUSINESS_TERMS): + label = "industry_business" + else: + label = _label_for_text(text, bool(tech_signals)) + base = 0.58 if trusted_source else 0.5 + score = source_prior + base + min(0.12, 0.03 * len(ai_signals)) + min(0.08, 0.02 * len(tech_signals)) + if research_source: + score = min(score, 0.76) + if noise and not title_has_ai: + score -= min(0.16, 0.04 * len(noise)) + return _result( + is_ai_related=score >= AI_RELEVANCE_THRESHOLD, + score=score, + label=label, + reason="curated_media_source_filter", + signals=ai_signals + tech_signals or ([source_l] if trusted_source else []), + noise=noise, + ) + + if site_id in AI_DEFAULT_SOURCES: + return _result( + is_ai_related=True, + score=max(AI_RELEVANCE_THRESHOLD, 0.72 + source_prior), + label=_label_for_text(text, bool(tech_signals)), + reason="trusted_ai_source_default_keep", + signals=ai_signals or [site_id], + noise=noise, + ) + + has_ai = contains_meaningful_ai_signal(text) + has_broad_ai = contains_any_keyword(text, list(BROAD_AI_TERMS)) or EN_SIGNAL_RE.search(text) is not None + has_tech = bool(tech_signals) + + if not (has_ai or (has_broad_ai and has_tech)): + return _result( + is_ai_related=False, + score=source_prior + (0.32 if has_broad_ai else 0.0) + (0.08 if has_tech else 0.0), + label="not_ai", + reason="missing_meaningful_ai_signal", + signals=ai_signals + tech_signals, + noise=noise, + ) + + if contains_any_keyword(text, COMMERCE_NOISE_KEYWORDS) and not has_ai: + return _result( + is_ai_related=False, + score=0.25 + source_prior, + label="commerce_noise", + reason="commerce_noise_without_strong_ai_signal", + signals=ai_signals + tech_signals, + noise=noise, + ) + + if contains_any_keyword(text, NOISE_KEYWORDS) and not has_ai: + return _result( + is_ai_related=False, + score=0.25 + source_prior, + label="noise", + reason="noise_without_strong_ai_signal", + signals=ai_signals + tech_signals, + noise=noise, + ) + + score = source_prior + (0.52 if has_ai else 0.34) + min(0.18, 0.04 * len(ai_signals)) + min(0.12, 0.03 * len(tech_signals)) + if noise: + score -= min(0.18, 0.04 * len(noise)) + if has_broad_ai and has_tech and not has_ai: + score = max(score, AI_RELEVANCE_THRESHOLD) + if has_ai: + score = max(score, AI_RELEVANCE_THRESHOLD) + + return _result( + is_ai_related=True, + score=score, + label=_label_for_text(text, has_tech), + reason="matched_ai_signal" if has_ai else "matched_broad_ai_plus_tech_signal", + signals=ai_signals + tech_signals, + noise=noise, + ) + + +def is_ai_related_record(record: dict[str, Any]) -> bool: + return bool(score_ai_relevance(record)["is_ai_related"]) + + +def is_broadly_ai_related(record: dict[str, Any]) -> bool: + """Return True when a record clears the broad-AI floor (score >= 0.3). + + This is a looser gate than ``is_ai_related_record`` (which requires >= 0.65). + Used by the "all-mode" UI view to filter out obviously-irrelevant noise while + keeping items with at least tangential AI/tech signal. + """ + return score_ai_relevance(record)["score"] >= AI_BROAD_RELEVANCE_FLOOR + + +def add_ai_relevance_fields(record: dict[str, Any]) -> dict[str, Any]: + relevance = score_ai_relevance(record) + out = dict(record) + out["ai_is_related"] = relevance["is_ai_related"] + out["ai_score"] = relevance["score"] + out["ai_label"] = relevance["label"] + out["ai_relevance_reason"] = relevance["reason"] + out["ai_signals"] = relevance["signals"] + out["ai_noise"] = relevance["noise"] + return out diff --git a/skills/ai-news-radar/scripts/evaluate_source_overlap.py b/skills/ai-news-radar/scripts/evaluate_source_overlap.py new file mode 100644 index 0000000..b861d27 --- /dev/null +++ b/skills/ai-news-radar/scripts/evaluate_source_overlap.py @@ -0,0 +1,414 @@ +#!/usr/bin/env python3 +"""Evaluate whether a candidate source overlaps too much with existing sources. + +This script is intentionally maintainer-facing. It does not change the daily +news pipeline; it produces an intake report that helps decide whether a new RSS +source should become a public default, remain an advanced OPML source, or be +skipped as too duplicative. +""" + +from __future__ import annotations + +import argparse +import json +import re +import sys +from collections import Counter +from datetime import UTC, datetime, timedelta +from difflib import SequenceMatcher +from pathlib import Path +from typing import Any + +import requests + +# Allow `python scripts/evaluate_source_overlap.py ...` from the repo root while +# keeping package imports working under pytest. +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from scripts.update_news import ( # noqa: E402 + event_time, + iso, + normalize_url, + parse_date_any, + parse_feed_entries_via_xml, + utc_now, +) + +TITLE_SOURCE_SUFFIXES = { + "ai hot", + "aihot", + "hacker news", + "product hunt", + "techcrunch", + "the verge", + "venturebeat", +} + +TITLE_DROP_WORDS = { + "exclusive", + "breaking", + "news", + "the", + "a", + "an", + "from", + "by", + "via", +} + +ENTITY_TERMS = { + "openai", + "anthropic", + "claude", + "google", + "gemini", + "deepseek", + "qwen", + "llama", + "meta", + "mistral", + "perplexity", + "cursor", + "codex", + "copilot", + "github", + "runway", + "kling", +} + + +def normalize_title_for_overlap(title: str) -> str: + """Normalize a title for overlap comparison, not for display.""" + text = (title or "").strip().lower() + if not text: + return "" + + # Drop common source suffixes like "— AI HOT" when they are clearly not part + # of the story title. + parts = re.split(r"\s+[—–-]\s+", text) + if len(parts) > 1 and parts[-1].strip(" .") in TITLE_SOURCE_SUFFIXES: + text = " — ".join(parts[:-1]) + + # Remove bracketed labels such as [Exclusive], not bracketed product names. + text = re.sub(r"\[(exclusive|breaking|update|news)\]", " ", text, flags=re.I) + text = re.sub(r"\b20\d{2}\b", " ", text) + text = re.sub(r"[^a-z0-9\u4e00-\u9fff]+", " ", text) + tokens = [token for token in text.split() if token not in TITLE_DROP_WORDS] + return " ".join(tokens) + + +def title_similarity(a: str, b: str) -> float: + """Return a stable 0-1 title similarity score with light token reordering.""" + na = normalize_title_for_overlap(a) + nb = normalize_title_for_overlap(b) + if not na or not nb: + return 0.0 + if na == nb: + return 1.0 + + seq_score = SequenceMatcher(None, na, nb).ratio() + ta = set(na.split()) + tb = set(nb.split()) + if not ta or not tb: + return round(seq_score, 3) + token_score = len(ta & tb) / len(ta | tb) + sorted_score = SequenceMatcher(None, " ".join(sorted(ta)), " ".join(sorted(tb))).ratio() + return round(max(seq_score, token_score, sorted_score), 3) + + +def extract_entities(title: str) -> set[str]: + normalized = normalize_title_for_overlap(title) + tokens = set(normalized.split()) + return {term for term in ENTITY_TERMS if term in tokens} + + +def tokens_for_overlap(title: str) -> set[str]: + return {token for token in normalize_title_for_overlap(title).split() if len(token) > 1} + + +def _days_apart(a: dict[str, Any], b: dict[str, Any]) -> float | None: + ta = event_time(a) + tb = event_time(b) + if not ta or not tb: + return None + return abs((ta - tb).total_seconds()) / 86400 + + +def classify_overlap( + candidate: dict[str, Any], + existing: dict[str, Any], + *, + title_threshold: float = 0.88, + possible_title_threshold: float = 0.62, +) -> dict[str, Any] | None: + """Classify overlap between one candidate item and one existing record.""" + candidate_url = normalize_url(str(candidate.get("url") or "")) + existing_url = normalize_url(str(existing.get("url") or "")) + score = 0.0 + match_type = "" + hard_duplicate = False + + if candidate_url and existing_url and candidate_url == existing_url: + score = 1.0 + match_type = "url_exact" + hard_duplicate = True + else: + candidate_title = str(candidate.get("title") or "") + existing_title = str(existing.get("title") or "") + score = title_similarity(candidate_title, existing_title) + if normalize_title_for_overlap(candidate_title) == normalize_title_for_overlap(existing_title) and candidate_title.strip().lower() == existing_title.strip().lower(): + match_type = "title_exact" + hard_duplicate = True + elif score >= title_threshold: + match_type = "title_similarity" + hard_duplicate = True + else: + candidate_entities = extract_entities(str(candidate.get("title") or "")) + existing_entities = extract_entities(str(existing.get("title") or "")) + days = _days_apart(candidate, existing) + if ( + score >= possible_title_threshold + and candidate_entities + and candidate_entities & existing_entities + and (days is None or days <= 2) + ): + match_type = "entity_time_possible" + hard_duplicate = False + else: + return None + + return { + "candidate_title": candidate.get("title"), + "candidate_url": candidate_url, + "matched_title": existing.get("title"), + "matched_url": existing_url, + "matched_site_id": existing.get("site_id"), + "matched_site_name": existing.get("site_name"), + "match_type": match_type, + "score": round(score, 3), + "hard_duplicate": hard_duplicate, + } + + +def make_recommendation(item_count: int, duplicate_rate: float) -> dict[str, Any]: + sample_too_small = item_count < 5 + if sample_too_small: + decision = "watchlist" + reason = "样本少于5条,不建议仅凭重复率直接拒绝;先进入观察列表。" + elif duplicate_rate >= 0.65: + decision = "skip_duplicate" + reason = "最近内容和已有信源高度重复,默认不录入公共源。" + elif duplicate_rate >= 0.35: + decision = "watchlist" + reason = "重复率中等,建议先作为OPML高级源或观察源,而不是直接进入默认源。" + else: + decision = "accept_default" + reason = "重复率较低,能为默认源补充明显新增信息。" + return { + "decision": decision, + "reason": reason, + "sample_too_small": sample_too_small, + } + + +def filter_recent_records(records: list[dict[str, Any]], now: datetime, lookback_days: int) -> list[dict[str, Any]]: + cutoff = now - timedelta(days=lookback_days) + out = [] + for record in records: + ts = event_time(record) + if ts and ts >= cutoff: + out.append(record) + return out + + +def evaluate_source_overlap( + candidate_items: list[dict[str, Any]], + baseline_items: list[dict[str, Any]], + *, + candidate: dict[str, Any], + generated_at: datetime, + lookback_days: int, +) -> dict[str, Any]: + matches: list[dict[str, Any]] = [] + possible_matches: list[dict[str, Any]] = [] + duplicate_candidate_indexes: set[int] = set() + + candidate_site_id = str(candidate.get("site_id") or "") + baseline = [item for item in baseline_items if str(item.get("site_id") or "") != candidate_site_id] + + url_index: dict[str, list[dict[str, Any]]] = {} + token_index: dict[str, set[int]] = {} + for baseline_idx, existing in enumerate(baseline): + url = normalize_url(str(existing.get("url") or "")) + if url: + url_index.setdefault(url, []).append(existing) + for token in tokens_for_overlap(str(existing.get("title") or "")): + token_index.setdefault(token, set()).add(baseline_idx) + + for idx, item in enumerate(candidate_items): + best_hard: dict[str, Any] | None = None + best_possible: dict[str, Any] | None = None + + candidate_url = normalize_url(str(item.get("url") or "")) + candidates_to_compare: list[dict[str, Any]] = [] + if candidate_url in url_index: + candidates_to_compare.extend(url_index[candidate_url]) + else: + candidate_indexes: set[int] = set() + for token in tokens_for_overlap(str(item.get("title") or "")): + candidate_indexes.update(token_index.get(token, set())) + candidates_to_compare.extend(baseline[i] for i in candidate_indexes) + + for existing in candidates_to_compare: + match = classify_overlap(item, existing) + if not match: + continue + if match["hard_duplicate"]: + if best_hard is None or match["score"] > best_hard["score"]: + best_hard = match + elif best_possible is None or match["score"] > best_possible["score"]: + best_possible = match + if best_hard: + duplicate_candidate_indexes.add(idx) + matches.append(best_hard) + elif best_possible: + possible_matches.append(best_possible) + + item_count = len(candidate_items) + duplicate_count = len(duplicate_candidate_indexes) + possible_duplicate_count = len(possible_matches) + unique_count = max(0, item_count - duplicate_count - possible_duplicate_count) + duplicate_rate = round(duplicate_count / item_count, 3) if item_count else 0.0 + unique_rate = round(unique_count / item_count, 3) if item_count else 0.0 + + source_counter = Counter(str(match.get("matched_site_id") or "") for match in matches if match.get("matched_site_id")) + name_by_id = { + str(match.get("matched_site_id") or ""): str(match.get("matched_site_name") or match.get("matched_site_id") or "") + for match in matches + } + + return { + "generated_at": iso(generated_at), + "candidate": { + "site_id": candidate_site_id, + "site_name": candidate.get("site_name") or candidate_site_id, + "url": candidate.get("url"), + "item_count": item_count, + "lookback_days": lookback_days, + }, + "baseline": { + "source_count": len({str(item.get("site_id") or "") for item in baseline if item.get("site_id")}), + "item_count": len(baseline), + "window_days": lookback_days, + }, + "overlap": { + "duplicate_count": duplicate_count, + "possible_duplicate_count": possible_duplicate_count, + "unique_count": unique_count, + "duplicate_rate": duplicate_rate, + "unique_rate": unique_rate, + }, + "top_overlapping_sources": [ + { + "site_id": site_id, + "site_name": name_by_id.get(site_id) or site_id, + "matched_count": count, + } + for site_id, count in source_counter.most_common(10) + ], + "recommendation": make_recommendation(item_count=item_count, duplicate_rate=duplicate_rate), + "matches": matches, + "possible_matches": possible_matches, + } + + +def load_archive_records(path: Path) -> list[dict[str, Any]]: + data = json.loads(path.read_text(encoding="utf-8")) + if isinstance(data, dict): + if "items" in data and isinstance(data["items"], list): + return [item for item in data["items"] if isinstance(item, dict)] + return [item for item in data.values() if isinstance(item, dict)] + if isinstance(data, list): + return [item for item in data if isinstance(item, dict)] + raise ValueError(f"Unsupported baseline JSON shape: {path}") + + +def fetch_rss_candidate(source_url: str, source_name: str, site_id: str, now: datetime) -> list[dict[str, Any]]: + resp = requests.get(source_url, timeout=25, headers={"User-Agent": "AI-News-Radar/0.3 SourceOverlapCheck"}) + resp.raise_for_status() + entries = parse_feed_entries_via_xml(resp.content) + out: list[dict[str, Any]] = [] + for entry in entries: + title = str(entry.get("title") or "").strip() + url = normalize_url(str(entry.get("link") or entry.get("url") or "")) + if not title or not url.startswith("http"): + continue + published = parse_date_any(entry.get("published") or entry.get("updated") or entry.get("pubDate"), now) + out.append( + { + "site_id": site_id, + "site_name": source_name, + "source": source_name, + "title": title, + "url": url, + "published_at": iso(published), + "first_seen_at": iso(now), + } + ) + return out + + +def print_summary(report: dict[str, Any]) -> None: + candidate = report["candidate"] + overlap = report["overlap"] + recommendation = report["recommendation"] + print(f"Source: {candidate['site_name']} ({candidate['site_id']})") + print(f"Items: {candidate['item_count']} | Baseline: {report['baseline']['item_count']}") + print( + "Duplicate rate: " + f"{overlap['duplicate_rate']:.3f} " + f"({overlap['duplicate_count']} hard, {overlap['possible_duplicate_count']} possible)" + ) + print(f"Unique rate: {overlap['unique_rate']:.3f} ({overlap['unique_count']} unique)") + print(f"Recommendation: {recommendation['decision']} — {recommendation['reason']}") + + +def main() -> int: + parser = argparse.ArgumentParser(description="Evaluate candidate source overlap against AI News Radar baseline") + parser.add_argument("--source-url", required=True, help="Candidate RSS/Atom URL") + parser.add_argument("--source-name", required=True, help="Human-readable candidate source name") + parser.add_argument("--site-id", default="candidate", help="Candidate site_id used in the report") + parser.add_argument("--baseline", default="data/archive.json", help="Baseline archive/latest JSON path") + parser.add_argument("--lookback-days", type=int, default=7, help="Recent window to compare") + parser.add_argument("--output", default="", help="Optional JSON report output path") + args = parser.parse_args() + + now = utc_now() + baseline_path = Path(args.baseline).expanduser() + baseline_items = filter_recent_records(load_archive_records(baseline_path), now, max(1, args.lookback_days)) + candidate_items = filter_recent_records( + fetch_rss_candidate(args.source_url, args.source_name, args.site_id, now), + now, + max(1, args.lookback_days), + ) + report = evaluate_source_overlap( + candidate_items, + baseline_items, + candidate={"site_id": args.site_id, "site_name": args.source_name, "url": args.source_url}, + generated_at=now, + lookback_days=max(1, args.lookback_days), + ) + + if args.output: + output_path = Path(args.output).expanduser() + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") + print(f"Wrote overlap report: {output_path}") + print_summary(report) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/skills/ai-news-radar/scripts/persona_score.py b/skills/ai-news-radar/scripts/persona_score.py new file mode 100644 index 0000000..8524b0a --- /dev/null +++ b/skills/ai-news-radar/scripts/persona_score.py @@ -0,0 +1,514 @@ +#!/usr/bin/env python3 +"""Persona scoring for the daily brief. + +Reads ``{data-dir}/daily-brief.json`` produced by ``update_news.py``, scores +each item with a persona-flavored LLM call (DeepSeek), writes the persona +fields back into ``daily-brief.json``, and generates a multi-persona TOP3 +review file ``{data-dir}/top3-personas.json``. + +Design constraints: + +- Standalone: communicates with the rest of the pipeline only through JSON + files. Never imports ``update_news.py``. +- Zero new dependencies: standard library plus ``requests``. +- Runs without any API key: falls back to a rules-based score derived from + ``importance_score`` so the public repo stays runnable key-free. +- Exit code is always 0 except for argument errors or corrupted input JSON. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import sys +import time +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import requests + +DEFAULT_API_BASE_URL = "https://api.deepseek.com" +DEFAULT_MODEL = "deepseek-chat" +CACHE_VERSION = 1 +CACHE_MAX_AGE_DAYS = 21 +REVIEW_MAX_CHARS = 60 +RETRY_BACKOFF_SECONDS = 2.0 + +ITEM_CONTEXT_FIELDS = ( + "story_id", + "title", + "url", + "importance_score", + "importance_label", + "category", + "reasons", + "source_count", +) + +PERSONA_ID_RE = re.compile(r"^[a-z-]+$") +CONTROL_CHARS_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]") +WHITESPACE_RE = re.compile(r"\s+") + + +class PersonaError(Exception): + """Raised for invalid persona files.""" + + +def parse_frontmatter(text: str) -> tuple[dict, str]: + """Parse a ``---`` delimited frontmatter block of simple ``key: value`` lines. + + Returns (metadata dict, body). Raises PersonaError when the block is + missing or malformed. + """ + lines = text.split("\n") + if not lines or lines[0].strip() != "---": + raise PersonaError("missing frontmatter opening '---'") + meta: dict = {} + end_index = None + for i, line in enumerate(lines[1:], start=1): + if line.strip() == "---": + end_index = i + break + stripped = line.strip() + if not stripped or stripped.startswith("#"): + continue + if ":" not in stripped: + raise PersonaError(f"invalid frontmatter line: {line!r}") + key, _, value = stripped.partition(":") + key = key.strip() + value = value.strip() + if value.lower() in {"true", "false"}: + meta[key] = value.lower() == "true" + else: + meta[key] = value + if end_index is None: + raise PersonaError("missing frontmatter closing '---'") + body = "\n".join(lines[end_index + 1 :]).strip() + return meta, body + + +def load_personas(personas_dir: Path) -> list[dict]: + """Load persona definitions from ``personas_dir``. + + Each persona is a dict: id, name, name_en, default, prompt, sha8 (first 8 + hex chars of the sha1 of the full file text). + """ + personas = [] + if not personas_dir.is_dir(): + return personas + for path in sorted(personas_dir.glob("*.md")): + if path.name.lower() == "readme.md": + continue + text = path.read_text(encoding="utf-8") + try: + meta, body = parse_frontmatter(text) + except PersonaError as exc: + print(f"persona: skipping {path.name}: {exc}", file=sys.stderr) + continue + persona_id = str(meta.get("id", "")).strip() + if not PERSONA_ID_RE.match(persona_id): + print( + f"persona: skipping {path.name}: invalid id {persona_id!r}", + file=sys.stderr, + ) + continue + personas.append( + { + "id": persona_id, + "name": str(meta.get("name", persona_id)), + "name_en": str(meta.get("name_en", persona_id)), + "default": bool(meta.get("default", False)), + "prompt": body, + "sha8": hashlib.sha1(text.encode("utf-8")).hexdigest()[:8], + } + ) + return personas + + +def pick_default_persona(personas: list[dict]) -> dict | None: + for persona in personas: + if persona.get("default"): + return persona + return personas[0] if personas else None + + +def sanitize_review(review: str) -> str: + review = CONTROL_CHARS_RE.sub("", str(review)) + review = WHITESPACE_RE.sub(" ", review).strip() + return review[:REVIEW_MAX_CHARS] + + +def clamp_score(value) -> int: + try: + score = int(round(float(value))) + except (TypeError, ValueError): + score = 0 + return max(0, min(100, score)) + + +def title_hash(title: str) -> str: + return hashlib.sha1(str(title).encode("utf-8")).hexdigest()[:8] + + +def cache_key(story_id: str, persona: dict) -> str: + return f"{story_id}|{persona['id']}|{persona['sha8']}" + + +def load_cache(path: Path) -> dict: + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError, ValueError): + return {"version": CACHE_VERSION, "entries": {}} + if not isinstance(data, dict) or data.get("version") != CACHE_VERSION: + return {"version": CACHE_VERSION, "entries": {}} + entries = data.get("entries") + if not isinstance(entries, dict): + entries = {} + return {"version": CACHE_VERSION, "entries": entries} + + +def prune_cache(cache: dict, now: datetime) -> None: + cutoff = now - timedelta(days=CACHE_MAX_AGE_DAYS) + kept = {} + for key, entry in cache.get("entries", {}).items(): + if not isinstance(entry, dict): + continue + scored_at = entry.get("scored_at") + try: + when = datetime.fromisoformat(str(scored_at).replace("Z", "+00:00")) + except (TypeError, ValueError): + continue + if when.tzinfo is None: + when = when.replace(tzinfo=timezone.utc) + if when >= cutoff: + kept[key] = entry + cache["entries"] = kept + + +def save_cache(path: Path, cache: dict, now: datetime) -> None: + prune_cache(cache, now) + path.write_text( + json.dumps(cache, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" + ) + + +def build_item_context(item: dict) -> dict: + context = {} + for field in ITEM_CONTEXT_FIELDS: + if field in item: + context[field] = item[field] + sources = item.get("sources") + if isinstance(sources, list): + context["sources"] = [ + {"source": src.get("source")} + for src in sources + if isinstance(src, dict) and src.get("source") + ] + return context + + +def call_persona_api( + persona: dict, + item: dict, + *, + api_key: str, + base_url: str, + model: str, + timeout: float, +) -> tuple[int, str] | None: + """Call the DeepSeek chat completions API for one item with one persona. + + Retries once on failure (2s backoff). Returns (score, review) or None. + """ + url = f"{base_url.rstrip('/')}/chat/completions" + payload = { + "model": model, + "messages": [ + {"role": "system", "content": persona["prompt"]}, + { + "role": "user", + "content": json.dumps(build_item_context(item), ensure_ascii=False), + }, + ], + "response_format": {"type": "json_object"}, + "temperature": 0.3, + } + headers = { + "Authorization": f"Bearer {api_key}", + "Content-Type": "application/json", + } + last_error = None + for attempt in range(2): + if attempt: + time.sleep(RETRY_BACKOFF_SECONDS) + try: + response = requests.post(url, json=payload, headers=headers, timeout=timeout) + if response.status_code == 429: + last_error = "rate limited (429)" + continue + response.raise_for_status() + body = response.json() + content = body["choices"][0]["message"]["content"] + parsed = json.loads(content) + score = clamp_score(parsed.get("score")) + review = sanitize_review(parsed.get("review", "")) + if not review: + last_error = "empty review" + continue + return score, review + except (requests.RequestException, KeyError, IndexError, TypeError, ValueError, json.JSONDecodeError) as exc: + last_error = str(exc) + continue + print( + f"persona: {persona['id']} failed for {item.get('story_id')}: {last_error}", + file=sys.stderr, + ) + return None + + +def score_with_persona( + persona: dict, + item: dict, + cache: dict, + *, + api_key: str, + base_url: str, + model: str, + timeout: float, + stats: dict, +) -> tuple[int, str] | None: + """Score one item with one persona, using the cache when possible.""" + story_id = str(item.get("story_id", "")) + key = cache_key(story_id, persona) + thash = title_hash(item.get("title", "")) + entry = cache["entries"].get(key) + if isinstance(entry, dict) and entry.get("title_hash") == thash: + stats["cached"] += 1 + return clamp_score(entry.get("score")), sanitize_review(entry.get("review", "")) + result = call_persona_api( + persona, + item, + api_key=api_key, + base_url=base_url, + model=model, + timeout=timeout, + ) + if result is None: + stats["failed"] += 1 + return None + score, review = result + cache["entries"][key] = { + "score": score, + "review": review, + "title_hash": thash, + "scored_at": utcnow_iso(), + } + stats["scored"] += 1 + return score, review + + +def utcnow_iso() -> str: + return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + + +def run_fallback(items: list[dict], default_persona: dict | None) -> None: + persona_id = default_persona["id"] if default_persona else "pragmatic" + scored_at = utcnow_iso() + for item in items: + item["persona_id"] = persona_id + item["persona_score"] = clamp_score(item.get("importance_score", 0)) + item.pop("persona_review", None) + item["persona_meta"] = {"mode": "rules_fallback", "scored_at": scored_at} + + +def build_top3_payload( + items: list[dict], + personas: list[dict], + cache: dict, + *, + top3: int, + api_key: str, + base_url: str, + model: str, + timeout: float, + stats: dict, +) -> dict: + ranked = sorted( + [item for item in items if "persona_score" in item], + key=lambda it: ( + -float(it.get("persona_score", 0)), + -float(it.get("importance_score", 0) or 0), + ), + )[:top3] + top_items = [] + for rank, item in enumerate(ranked, start=1): + reviews = {} + for persona in personas: + result = score_with_persona( + persona, + item, + cache, + api_key=api_key, + base_url=base_url, + model=model, + timeout=timeout, + stats=stats, + ) + if result is None: + continue + score, review = result + reviews[persona["id"]] = {"score": score, "review": review} + top_items.append( + { + "story_id": item.get("story_id"), + "title": item.get("title"), + "url": item.get("url"), + "rank": rank, + "reviews": reviews, + } + ) + return { + "generated_at": utcnow_iso(), + "model": model, + "personas": [{"id": p["id"], "name": p["name"]} for p in personas], + "items": top_items, + } + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Persona scoring for daily brief") + parser.add_argument("--data-dir", default="data", help="data directory") + parser.add_argument("--personas-dir", default="personas", help="personas directory") + parser.add_argument("--max-items", type=int, default=40, help="max items to score") + parser.add_argument("--top3", type=int, default=3, help="TOP N multi-persona items") + parser.add_argument("--timeout", type=float, default=30, help="API timeout seconds") + parser.add_argument( + "--dry-run", action="store_true", help="run without writing any files" + ) + parser.add_argument( + "--list-personas", action="store_true", help="list personas and exit" + ) + return parser.parse_args(argv) + + +def main(argv: list[str] | None = None) -> int: + args = parse_args(argv) + personas_dir = Path(args.personas_dir) + personas = load_personas(personas_dir) + default_persona = pick_default_persona(personas) + + if args.list_personas: + if not personas: + print("persona: no personas found") + return 0 + for persona in personas: + marker = " (default)" if persona is default_persona else "" + print(f"{persona['id']}\t{persona['name']} / {persona['name_en']}{marker}") + return 0 + + data_dir = Path(args.data_dir) + brief_path = data_dir / "daily-brief.json" + top3_path = data_dir / "top3-personas.json" + cache_path = data_dir / "persona-cache.json" + + if not brief_path.is_file(): + print(f"persona: {brief_path} not found, nothing to do") + print("persona: scored=0 cached=0 skipped=0 failed=0") + return 0 + + brief = json.loads(brief_path.read_text(encoding="utf-8")) + all_items = brief.get("items", []) + if not isinstance(all_items, list): + raise SystemExit(f"persona: {brief_path} has invalid 'items'") + items = all_items[: args.max_items] + skipped = len(all_items) - len(items) + + api_key = os.environ.get("DEEPSEEK_API_KEY", "").strip() + base_url = os.environ.get("DEEPSEEK_API_BASE_URL", "").strip() or DEFAULT_API_BASE_URL + model = os.environ.get("DEEPSEEK_MODEL", "").strip() or DEFAULT_MODEL + enabled = os.environ.get("PERSONA_ENABLED", "").strip() != "0" + + now = datetime.now(timezone.utc) + stats = {"scored": 0, "cached": 0, "failed": 0} + + if not api_key or not enabled or default_persona is None: + run_fallback(items, default_persona) + top3_payload = {"generated_at": utcnow_iso(), "items": []} + if not args.dry_run: + brief_path.write_text( + json.dumps(brief, ensure_ascii=False, indent=2) + "\n", + encoding="utf-8", + ) + top3_path.write_text( + json.dumps(top3_payload, ensure_ascii=False, indent=2) + "\n", + encoding="utf-8", + ) + print( + f"persona: scored=0 cached=0 skipped={skipped} failed=0" + ) + return 0 + + cache = load_cache(cache_path) + scored_at = utcnow_iso() + + for item in items: + result = score_with_persona( + default_persona, + item, + cache, + api_key=api_key, + base_url=base_url, + model=model, + timeout=args.timeout, + stats=stats, + ) + if result is None: + continue + score, review = result + item["persona_id"] = default_persona["id"] + item["persona_score"] = score + item["persona_review"] = review + item["persona_meta"] = { + "mode": "llm", + "model": model, + "scored_at": scored_at, + } + + top3_payload = build_top3_payload( + items, + personas, + cache, + top3=args.top3, + api_key=api_key, + base_url=base_url, + model=model, + timeout=args.timeout, + stats=stats, + ) + + if not args.dry_run: + brief_path.write_text( + json.dumps(brief, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" + ) + top3_path.write_text( + json.dumps(top3_payload, ensure_ascii=False, indent=2) + "\n", + encoding="utf-8", + ) + save_cache(cache_path, cache, now) + + print( + "persona: scored={scored} cached={cached} skipped={skipped} failed={failed}".format( + scored=stats["scored"], + cached=stats["cached"], + skipped=skipped, + failed=stats["failed"], + ) + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/skills/ai-news-radar/scripts/run_daily_brief.py b/skills/ai-news-radar/scripts/run_daily_brief.py new file mode 100644 index 0000000..0e38c23 --- /dev/null +++ b/skills/ai-news-radar/scripts/run_daily_brief.py @@ -0,0 +1,28 @@ +#!/usr/bin/env python3 +"""Run the pinned generator with a required output directory outside this skill.""" +from __future__ import annotations +import argparse +import runpy +import sys +from pathlib import Path + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output-dir", required=True, help="Absolute private working/output directory, outside the installed skill") + args, remaining = parser.parse_known_args() + if any(arg == "--output-dir" or arg.startswith("--output-dir=") for arg in remaining): + parser.error("supply --output-dir exactly once") + output = Path(args.output_dir).expanduser() + if not output.is_absolute(): + parser.error("--output-dir must be absolute") + output = output.resolve() + skill = Path(__file__).resolve().parents[1] + if output == skill or skill in output.parents: + parser.error("--output-dir must be outside the installed skill") + sys.dont_write_bytecode = True + sys.path.insert(0, str(skill / "scripts")) + sys.argv = [str(skill / "scripts" / "update_news.py"), "--output-dir", str(output), *remaining] + runpy.run_path(sys.argv[0], run_name="__main__") + +if __name__ == "__main__": + main() diff --git a/skills/ai-news-radar/scripts/update_news.py b/skills/ai-news-radar/scripts/update_news.py new file mode 100644 index 0000000..9cab202 --- /dev/null +++ b/skills/ai-news-radar/scripts/update_news.py @@ -0,0 +1,7221 @@ +#!/usr/bin/env python3 +"""Aggregate updates from multiple AI news sites and produce 24h snapshot data.""" + +from __future__ import annotations + +import argparse +from concurrent.futures import ThreadPoolExecutor, as_completed +from email.utils import parseaddr +import hashlib +import json +import math +import os +import random +import re +import subprocess +import time +import xml.etree.ElementTree as ET +from dataclasses import dataclass +from datetime import date, datetime, timedelta, timezone +from difflib import SequenceMatcher +from pathlib import Path +from typing import Any +from urllib.parse import parse_qsl, unquote, urlencode, urljoin, urlparse, urlunparse +from zoneinfo import ZoneInfo + +import requests +from bs4 import BeautifulSoup +from dateutil import parser as dtparser +from requests.adapters import HTTPAdapter +from urllib3.util.retry import Retry + +try: + from scripts.ai_relevance import AI_BROAD_RELEVANCE_FLOOR, add_ai_relevance_fields, is_broadly_ai_related, score_ai_relevance +except ModuleNotFoundError: # pragma: no cover - direct `python scripts/update_news.py` + from ai_relevance import AI_BROAD_RELEVANCE_FLOOR, add_ai_relevance_fields, is_broadly_ai_related, score_ai_relevance + +try: + import feedparser +except ModuleNotFoundError: + feedparser = None + +UTC = timezone.utc +TZINFOS = {"CET": 3600, "CEST": 7200, "EST": -18000, "EDT": -14400, + "PST": -28800, "PDT": -25200, "CST": -21600, "CDT": -18000, + "MST": -25200, "MDT": -21600, "BST": 3600, "JST": 32400} +BROWSER_UA = ( + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) " + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36" +) +SH_TZ = ZoneInfo("Asia/Shanghai") +WAYTOAGI_DEFAULT = ( + "https://waytoagi.feishu.cn/wiki/QPe5w5g7UisbEkkow8XcDmOpn8e?fromScene=spaceOverview" +) +WAYTOAGI_HISTORY_FALLBACK = "https://waytoagi.feishu.cn/wiki/FjiOwWp2giA7hRk6jjfcPioCnAc" +OPENAI_STATUS_API_URL = "https://status.openai.com/api/v2/incidents.json" +OPENAI_STATUS_PAGE_URL = "https://status.openai.com/" +OPENAI_INCIDENT_URL = "https://status.openai.com/incidents/{incident_id}" +ACTIVE_SERVICE_INCIDENT_STATUSES = {"investigating", "identified", "monitoring"} + +RSS_FEED_REPLACEMENTS: dict[str, str] = { + "https://rsshub.app/infoq/recommend": "https://www.infoq.cn/feed", + "https://rsshub.app/huggingface/blog-zh": "https://huggingface.co/blog/feed.xml", + "https://rsshub.app/readhub/daily": "https://readhub.cn/rss", + "https://rsshub.app/36kr/hot-list": "https://36kr.com/feed", + "https://rsshub.app/sspai/index": "https://sspai.com/feed", + "https://rsshub.app/sspai/matrix": "https://sspai.com/feed", + "https://rsshub.app/meituan/tech": "https://tech.meituan.com/feed", + "https://mjg59.dreamwidth.org/data/rss": "http://mjg59.dreamwidth.org/data/rss", +} + +RSS_FEED_SKIP_PREFIXES: tuple[str, ...] = ( + "https://rsshub.app/telegram/channel/", + "https://rsshub.app/jike/", + "https://rsshub.app/bilibili/", + "https://rsshub.app/zhihu/", + "https://rsshub.app/xiaoyuzhou/podcast/", + "https://rsshub.app/xyzrank", + "https://rsshub.app/mittrchina/hot", + "https://wechat2rss.bestblogs.dev/", + "https://werss.bestblogs.dev/", + "http://47.122.94.119:18080/", +) + +RSS_FEED_SKIP_EXACT: set[str] = { + "https://rachelbythebay.com/w/atom.xml", + "https://flak.tedunangst.com/rss", +} + +OFFICIAL_AI_FEEDS: tuple[dict[str, str], ...] = ( + { + "title": "OpenAI News", + "xml_url": "https://openai.com/news/rss.xml", + "html_url": "https://openai.com/news", + }, + { + "title": "Google DeepMind", + "xml_url": "https://deepmind.google/blog/rss.xml", + "html_url": "https://deepmind.google/blog", + }, + { + "title": "Google AI Blog", + "xml_url": "https://blog.google/innovation-and-ai/technology/ai/rss/", + "html_url": "https://blog.google/innovation-and-ai/technology/ai/", + }, + { + "title": "Hugging Face Blog", + "xml_url": "https://huggingface.co/blog/feed.xml", + "html_url": "https://huggingface.co/blog", + }, + { + "title": "GitHub AI & ML", + "xml_url": "https://github.blog/ai-and-ml/feed/", + "html_url": "https://github.blog/ai-and-ml/", + }, + { + "title": "GitHub Changelog", + "xml_url": "https://github.blog/changelog/feed/", + "html_url": "https://github.blog/changelog/", + }, + { + "title": "OpenAI Skills", + "xml_url": "https://github.com/openai/skills/commits/main.atom", + "html_url": "https://github.com/openai/skills", + "include_keywords": "hatch,pet,migrate-to-codex", + }, +) +OFFICIAL_AI_MAX_AGE_DAYS = 45 +CURATED_AI_MEDIA_MAX_AGE_DAYS = 30 +# Per-fetch item cap for wide discussion-tier aggregators (buzzing/iris). +# They dominate raw volume with very low AI keep rates (see +# reports/source-quality/v0.8-audit.md); cap them at the fetch layer so a +# single round cannot flood the archive. Override via env for experiments. +DISCUSSION_FETCH_CAP = int(os.environ.get("DISCUSSION_FETCH_CAP", "50")) +CURATED_AI_MEDIA_FEEDS: tuple[dict[str, Any], ...] = ( + { + "title": "The Decoder AI News", + "xml_url": "https://the-decoder.com/feed/", + "html_url": "https://the-decoder.com/", + "max_entries": 10, + }, + { + "title": "TechCrunch AI", + "xml_url": "https://techcrunch.com/category/artificial-intelligence/feed/", + "html_url": "https://techcrunch.com/category/artificial-intelligence/", + "max_entries": 8, + }, + { + # The Verge's AI topic RSS endpoint is not currently public/stable; + # keep the all-site RSS behind strict title-level AI filtering. + "title": "The Verge", + "xml_url": "https://www.theverge.com/rss/index.xml", + "html_url": "https://www.theverge.com/ai-artificial-intelligence", + "include_keywords": "ai,artificial intelligence,openai,anthropic,claude,chatgpt,gpt,gemini,llm,agent,copilot", + "max_entries": 6, + "strict_title_filter": True, + }, + { + "title": "MarkTechPost Research", + "xml_url": "https://www.marktechpost.com/feed/", + "html_url": "https://www.marktechpost.com/", + "include_keywords": "paper,research,arxiv,benchmark,dataset,model,llm,agent,diffusion,transformer,multimodal,reasoning,inference,training,open-source", + "max_entries": 6, + "strict_title_filter": True, + "research_only": True, + }, + { + "title": "VentureBeat AI", + "xml_url": "https://venturebeat.com/category/ai/feed", + "html_url": "https://venturebeat.com/category/ai/", + "max_entries": 8, + }, + { + "title": "Artificial Intelligence News", + "xml_url": "https://www.artificialintelligence-news.com/feed/", + "html_url": "https://www.artificialintelligence-news.com/", + "max_entries": 8, + }, + { + "title": "Claude Code Releases", + "xml_url": "https://github.com/anthropics/claude-code/releases.atom", + "html_url": "https://github.com/anthropics/claude-code/releases", + "max_entries": 6, + }, +) +AIBREAKFAST_JINA_URL = "https://r.jina.ai/https://aibreakfast.beehiiv.com/" +AIHOT_ITEMS_API_URL = "https://aihot.virxact.com/api/public/items" +AIHOT_MIN_SCORE = 60 +AIHOT_API_TAKE = 100 +AIHOT_API_MAX_PAGES = 5 +AIHOT_API_UA = f"{BROWSER_UA} aihot-skill/0.2.0 AI-News-Radar/0.7" +AIHOT_FEED_URL = "https://aihot.virxact.com/feed.xml" +AIHOT_FALLBACK_FEED_URLS = ( + "https://aihot.virxact.com/rss.xml", + "https://aihot.virxact.com/feed", + "https://aihot.virxact.com/feed/daily.xml", +) +FOLLOW_BUILDERS_FEED_BASE = "https://raw.githubusercontent.com/zarazhangrui/follow-builders/main" +HN_ALGOLIA_URL = "https://hn.algolia.com/api/v1/search_by_date" +HN_ALGOLIA_QUERIES: tuple[str, ...] = ( + "OpenAI", + "Anthropic", + "Claude Code", + "Claude", + "Gemini", + "Google AI", + "DeepSeek", + "Qwen", + "AI agent", + "AI coding", + "Codex", + "Cursor", + "MCP", + "LLM", + "GPT", + "Sora", + "Copilot", + "Nvidia AI", +) +HN_ALGOLIA_KEYWORDS: tuple[str, ...] = ( + "openai", + "anthropic", + "claude", + "claude code", + "codex", + "cursor", + "mcp", + "gemini", + "deepseek", + "qwen", + "llm", + "gpt", + "sora", + "copilot", + "agent", + "ai coding", + "benchmark", + "eval", + "paper", + "model", + "inference", +) +HN_ALGOLIA_HITS_PER_QUERY = 35 +HN_ALGOLIA_MIN_KEYWORD_SCORE = 0.38 +HN_ALGOLIA_MIN_COMMENTS = 2 +HN_ALGOLIA_MIN_POINTS = 10 +HN_ALGOLIA_QUERY_PAUSE_SECONDS = 0.1 +AGENTMAIL_API_BASE_DEFAULT = "https://api.agentmail.to" +AGENTMAIL_DIGEST_FILE = "email-digest.json" +AGENTMAIL_DEFAULT_LIMIT = 50 +AGENTMAIL_PROVIDER_DEFAULT = "agently_cli" +AGENTMAIL_CLI_DEFAULT = "agently-cli" +AGENTMAIL_PUBLIC_LINK_TEXT_RE = re.compile( + r"\b(read\s+online|view\s+in\s+browser|read\s+in\s+browser|open\s+in\s+browser|" + r"read\s+on\s+web|view\s+online|web\s+version)\b", + re.I, +) +AGENTMAIL_PUBLIC_LINK_REJECT_RE = re.compile( + r"\b(unsubscribe|manage\s+preferences|privacy|terms|sponsor|advertise|" + r"feedback|rate\s+this|log\s+in|subscribe)\b", + re.I, +) +AGENTMAIL_PUBLIC_URL_REJECT_HOSTS = ( + "agent.qq.com", + "email.beehiivstatus.com", +) +AGENTMAIL_TRACKING_QUERY_PREFIXES = ("utm_",) +AGENTMAIL_TRACKING_QUERY_KEYS = { + "_bhlid", + "email", + "email_id", + "mc_cid", + "mc_eid", + "ref", + "subscriber", + "subscriber_id", +} +PAID_SOURCE_STATE_FILE = "paid-source-state.json" +PAID_SOURCE_DEFAULT_INTERVAL_HOURS = 24 +PAID_SOURCE_DEFAULT_INTERVAL_HOURS_BY_PREFIX = { + "SOCIALDATA": 12, + "TIKHUB": 24, +} +PAID_SOURCE_MAX_INTERVAL_HOURS = 24 * 14 +X_API_BASE_DEFAULT = "https://api.x.com" +X_API_POST_READ_COST_USD = 0.005 +X_API_DEFAULT_QUERY = '(AI OR "artificial intelligence" OR "large language model" OR LLM) lang:en -is:retweet has:links' +X_API_DEFAULT_MAX_RESULTS = 20 +X_API_MAX_QUERY_CHARS = 512 +SOCIALDATA_API_BASE_DEFAULT = "https://api.socialdata.tools" +SOCIALDATA_TWEET_READ_COST_USD = 0.0002 +SOCIALDATA_DEFAULT_QUERY = '(AI OR "artificial intelligence" OR LLM OR "large language model" OR 人工智能 OR 大模型 OR 大语言模型 OR AIGC OR 智能体 OR Agent) (lang:en OR lang:zh) -filter:retweets' +SOCIALDATA_DEFAULT_MAX_RESULTS = 20 +SOCIALDATA_MAX_QUERY_CHARS = 512 +# Curated X list "AI is cool, i guess" (owner @aiwarts). The list timeline pulls +# each member's own posts by identity, which is far higher-signal than the broad +# keyword search. No member is excluded by default; set SOCIALDATA_LIST_EXCLUDE +# (comma-separated handles) to drop specific accounts if needed. +SOCIALDATA_LIST_ID_DEFAULT = "1695376776867062037" +SOCIALDATA_LIST_DEFAULT_MAX_RESULTS = 50 +SOCIALDATA_LIST_DEFAULT_EXCLUDE = "" +# Hard cap on list pagination so a heavily-filtered list can't page (and bill) +# without bound. Each page is a paid read. +SOCIALDATA_LIST_MAX_PAGES = 10 +# Exact recency window for SocialData results, in days (search + list). Kept +# consistent with TikHub. Tweets older than this are dropped after fetch. +SOCIALDATA_RECENCY_DAYS = 4 +# Keep only first-party posts; drop retweets and replies (conversational noise). +SOCIALDATA_LIST_ALLOWED_TYPES = frozenset({"tweet", "quote"}) +TIKHUB_API_BASE_DEFAULT = "https://api.tikhub.io" +TIKHUB_DEFAULT_QUERY = "OpenAI,Claude,大模型,Agent,AI工具,人工智能,AI" +TIKHUB_DEFAULT_PLATFORMS = "douyin,xiaohongshu" +TIKHUB_DEFAULT_MAX_RESULTS = 20 +TIKHUB_MAX_QUERY_CHARS = 256 +TIKHUB_RESPONSE_SCAN_LIMIT = 100 +CREATOR_HOT_WINDOW_DAYS = 7 +CREATOR_FRESHNESS_BONUS_HOURS = 24 +CREATOR_FRESHNESS_BONUS_POINTS = 15.0 +CREATOR_SITE_IDS = frozenset({"tikhub_douyin", "tikhub_xiaohongshu"}) +# --- TikHub search ranking / time-window tuning (edit here, no env var needed) --- +# Exact recency window for TikHub results, in days. Douyin/Xiaohongshu search +# only expose coarse buckets (不限/一天内/一周内/半年内), so we ask the API for +# 一周内 and then enforce the exact current-week window in code. +TIKHUB_RECENCY_DAYS = 7 # keep only current-week posts +# Douyin fetch_general_search_v2 enums (standard Douyin search filter): +# sort_type: 0=综合, 1=最多点赞(most likes), 2=最新 +# publish_time: 0=不限, 1=一天内, 7=一周内, 180=半年内 +TIKHUB_DOUYIN_SORT_TYPE = "1" # 最多点赞 / most likes +TIKHUB_DOUYIN_PUBLISH_TIME = "7" # 一周内; real cap = TIKHUB_RECENCY_DAYS +# Xiaohongshu search. app_v2 uses the app's filter labels; sort uses the +# popularity/time/general tokens (web_v3 already takes "time_descending"). +# sort: general(综合) / time_descending(最新) / popularity_descending(最多点赞/最热) +# note_type: "不限"(app_v2, all) ; web_v3 uses 0 for "all" +# time_filter: "不限" / "一天内" / "一周内" / "半年内" +TIKHUB_XHS_SORT = "popularity_descending" # 最多点赞 / most likes +TIKHUB_XHS_NOTE_TYPE = "不限" # all note types +TIKHUB_XHS_TIME_FILTER = "一周内" # 一周内; real cap = TIKHUB_RECENCY_DAYS + + +@dataclass +class RawItem: + site_id: str + site_name: str + source: str + title: str + url: str + published_at: datetime | None + meta: dict[str, Any] + + +PUBLIC_RAW_META_FIELDS: tuple[str, ...] = ( + "aihot_score", + "aihot_category", + "aihot_selected", + "provided_title_en", + "provided_title_zh", + "creator_metrics", + "search_surface", + "summary", +) + + +def utc_now() -> datetime: + return datetime.now(tz=UTC) + + +def iso(dt: datetime | None) -> str | None: + if not dt: + return None + return dt.astimezone(UTC).isoformat().replace("+00:00", "Z") + + +def parse_iso(dt_str: str | None) -> datetime | None: + if not dt_str: + return None + try: + dt = dtparser.parse(dt_str, tzinfos=TZINFOS) + except Exception: + return None + if not dt.tzinfo: + dt = dt.replace(tzinfo=UTC) + return dt.astimezone(UTC) + + +def normalize_url(raw_url: str) -> str: + try: + parsed = urlparse(raw_url.strip()) + if not parsed.scheme: + return raw_url.strip() + query = [] + for k, v in parse_qsl(parsed.query, keep_blank_values=True): + lk = k.lower() + if lk.startswith("utm_"): + continue + if lk in { + "ref", + "spm", + "fbclid", + "gclid", + "igshid", + "mkt_tok", + "mc_cid", + "mc_eid", + "_hsenc", + "_hsmi", + }: + continue + query.append((k, v)) + parsed = parsed._replace( + scheme=parsed.scheme.lower(), + netloc=parsed.netloc.lower(), + fragment="", + query=urlencode(query, doseq=True), + ) + normalized = urlunparse(parsed) + return normalized.rstrip("/") + except Exception: + return raw_url.strip() + + +def host_of_url(raw_url: str) -> str: + try: + return urlparse(raw_url).netloc.lower() + except Exception: + return "" + + +def first_non_empty(*values: Any) -> str: + for value in values: + if value is None: + continue + s = str(value).strip() + if s: + return s + return "" + + +def maybe_fix_mojibake(text: str) -> str: + s = (text or "").strip() + if not s: + return s + # Common mojibake signature from UTF-8 bytes decoded as Latin-1. + if re.search(r"[Ãâåèæïð]|[\x80-\x9f]|æ|ç|å|é", s) is None: + return s + for enc in ("latin1", "cp1252"): + try: + fixed = s.encode(enc).decode("utf-8") + if fixed and fixed != s: + return fixed + except Exception: + continue + return s + + +def has_cjk(text: str) -> bool: + return bool(re.search(r"[\u4e00-\u9fff]", text or "")) + + +def is_mostly_english(text: str) -> bool: + s = (text or "").strip() + if not s: + return False + if has_cjk(s): + return False + letters = re.findall(r"[A-Za-z]", s) + return len(letters) >= max(6, len(s) // 4) + + +def parse_feed_entries_via_xml(feed_xml: bytes) -> list[dict[str, Any]]: + out: list[dict[str, Any]] = [] + seen: set[tuple[str, str]] = set() + try: + root = ET.fromstring(feed_xml) + except Exception: + return out + + for tag in (".//item", ".//{*}item", ".//entry", ".//{*}entry"): + for node in root.findall(tag): + title = ( + node.findtext("title") + or node.findtext("{*}title") + or "" + ).strip() + link = "" + link_node = node.find("link") + if link_node is None: + link_node = node.find("{*}link") + if link_node is not None: + link = (link_node.get("href") or link_node.text or "").strip() + if not link: + link = (node.findtext("{*}link") or node.findtext("link") or "").strip() + published = ( + node.findtext("pubDate") + or node.findtext("{*}pubDate") + or node.findtext("published") + or node.findtext("{*}published") + or node.findtext("updated") + or node.findtext("{*}updated") + ) + if title and link: + key = (title, link) + if key in seen: + continue + seen.add(key) + out.append({"title": title, "link": link, "published": published}) + return out + + +def make_item_id(site_id: str, source: str, title: str, url: str) -> str: + key = "||".join( + [ + site_id.strip().lower(), + source.strip().lower(), + title.strip().lower(), + normalize_url(url), + ] + ) + return hashlib.sha1(key.encode("utf-8")).hexdigest() + + +def parse_unix_timestamp(value: Any) -> datetime | None: + if value is None: + return None + try: + n = float(value) + except Exception: + return None + if n > 10_000_000_000: + n /= 1000.0 + try: + return datetime.fromtimestamp(n, tz=UTC) + except Exception: + return None + + +def parse_relative_time_zh(text: str, now: datetime) -> datetime | None: + text = (text or "").strip() + if not text: + return None + + m = re.search(r"(\d+)\s*分钟前", text) + if m: + return now - timedelta(minutes=int(m.group(1))) + + m = re.search(r"(\d+)\s*小时前", text) + if m: + return now - timedelta(hours=int(m.group(1))) + + m = re.search(r"(\d+)\s*天前", text) + if m: + return now - timedelta(days=int(m.group(1))) + + if "刚刚" in text: + return now + + if "昨天" in text: + return now - timedelta(days=1) + + m = re.fullmatch(r"(?:今天)?\s*(\d{1,2}):(\d{2})", text) + if m: + hour = int(m.group(1)) + minute = int(m.group(2)) + candidate = now.replace(hour=hour, minute=minute, second=0, microsecond=0) + if candidate > now + timedelta(minutes=5): + candidate -= timedelta(days=1) + return candidate + + m = re.fullmatch(r"昨天\s*(\d{1,2}):(\d{2})", text) + if m: + hour = int(m.group(1)) + minute = int(m.group(2)) + return (now - timedelta(days=1)).replace(hour=hour, minute=minute, second=0, microsecond=0) + + m = re.fullmatch(r"(?:\d{4}年\s*)?(\d{1,2})月(\d{1,2})日", text) + if m: + month = int(m.group(1)) + day = int(m.group(2)) + year = now.year + try: + candidate = datetime(year, month, day, tzinfo=UTC) + if candidate > now + timedelta(days=2): + candidate = datetime(year - 1, month, day, tzinfo=UTC) + return candidate + except Exception: + return None + + return None + + +def parse_date_any(value: Any, now: datetime) -> datetime | None: + if value is None: + return None + + if isinstance(value, datetime): + return value.astimezone(UTC) + + if isinstance(value, (int, float)): + return parse_unix_timestamp(value) + + s = str(value).strip() + if not s: + return None + + if s.startswith("$D"): + s = s[2:] + + if re.fullmatch(r"\d{12,}", s): + return parse_unix_timestamp(int(s)) + + if re.fullmatch(r"\d{9,11}", s): + return parse_unix_timestamp(int(s)) + + dt = parse_relative_time_zh(s, now) + if dt: + return dt + + # TechURLs format: 2026-02-19 11:54:21AM UTC + m = re.search(r"(\d{4}-\d{2}-\d{2}\s+\d{1,2}:\d{2}:\d{2}[AP]M)\s+UTC", s) + if m: + try: + dt = datetime.strptime(m.group(1), "%Y-%m-%d %I:%M:%S%p") + return dt.replace(tzinfo=UTC) + except Exception: + pass + + try: + dt = dtparser.parse(s, tzinfos={"UT": 0, "UTC": 0, "GMT": 0, **TZINFOS}) + if not dt.tzinfo: + dt = dt.replace(tzinfo=UTC) + return dt.astimezone(UTC) + except Exception: + return None + + +FUTURE_PUBLISH_SKEW = timedelta(hours=2) +CST_MISLABEL_OFFSET = timedelta(hours=8) + + +def correct_future_published( + published: datetime | None, + now: datetime, + *, + assume_cst_mislabel: bool = False, +) -> datetime | None: + """兜住源头 feed 错标时区产生的"未来"发布时间。 + + 典型病例:InfoQ CN 的 RSS 把北京时间直接标成 GMT(如 + "Tue, 14 Jul 2026 22:01:15 GMT" 实为 22:01 北京时间),按标记解析后 + published 领先真实时间 8 小时,前端时间轴出现未来条目。 + 中文源先尝试减 8 小时纠正;纠正后仍在未来(或非中文源)则回退抓取时间。 + """ + if published is None: + return None + limit = now + FUTURE_PUBLISH_SKEW + if published <= limit: + return published + if assume_cst_mislabel: + corrected = published - CST_MISLABEL_OFFSET + if corrected <= limit: + return corrected + return now + + +def correct_feed_published_batch( + published_list: list[datetime], + now: datetime, + *, + assume_cst_mislabel: bool = False, +) -> list[datetime]: + """feed 级错标推断:同一 feed 只要最新条目在未来且减 8h 后合理, + + 即可判定整个 feed 都把北京时间错标成了 GMT,本轮全部条目统一纠正—— + 这样没越过"现在"的错标条目(不会触发单条防御)也能修对。 + 否则退回逐条防御。 + """ + if not published_list: + return published_list + if assume_cst_mislabel: + limit = now + FUTURE_PUBLISH_SKEW + newest = max(published_list) + if newest > limit and newest - CST_MISLABEL_OFFSET <= limit: + return [p - CST_MISLABEL_OFFSET for p in published_list] + return [ + correct_future_published(p, now, assume_cst_mislabel=assume_cst_mislabel) + for p in published_list + ] + + +def apply_public_raw_meta(record: dict[str, Any], raw: RawItem) -> None: + """Promote safe source metadata needed by public scoring and UI ranking.""" + meta = raw.meta if isinstance(raw.meta, dict) else {} + for key in PUBLIC_RAW_META_FIELDS: + if key in meta and meta.get(key) is not None: + record[key] = sanitize_public_value(meta.get(key)) + + +def decode_escaped_json(raw: str) -> dict[str, Any] | None: + s = raw.replace('\\"', '"').replace("\\/", "/") + try: + return json.loads(s) + except Exception: + return None + + +def extract_waytoagi_history_url(root_html: str) -> str: + pattern = r'\{\\"id\\":\\"[^\"]+\\",\\"type\\":\\"mention_doc\\",\\"data\\":\{[^\}]+\}\}' + for raw in re.findall(pattern, root_html): + obj = decode_escaped_json(raw) + if not obj: + continue + data = obj.get("data", {}) + title = str(data.get("title") or "") + if "历史更新" in title or "更新日志" in title: + raw_url = str(data.get("raw_url") or "").strip() + if raw_url: + return raw_url + return WAYTOAGI_HISTORY_FALLBACK + + +def extract_feishu_client_vars(page_html: str) -> dict[str, Any]: + marker = "window.DATA = Object.assign({}, window.DATA, { clientVars: Object(" + idx = page_html.find(marker) + if idx == -1: + raise ValueError("Cannot locate Feishu clientVars marker") + + start = idx + len(marker) + depth = 1 + in_str = False + escaped = False + end = None + + for i, ch in enumerate(page_html[start:], start): + if in_str: + if escaped: + escaped = False + elif ch == "\\": + escaped = True + elif ch == '"': + in_str = False + continue + + if ch == '"': + in_str = True + continue + + if ch == "(": + depth += 1 + elif ch == ")": + depth -= 1 + if depth == 0: + end = i + break + + if end is None: + raise ValueError("Cannot parse Feishu clientVars payload") + + payload = page_html[start:end] + return json.loads(payload) + + +def block_text(block_data: dict[str, Any]) -> str: + text_obj = block_data.get("text", {}) if isinstance(block_data, dict) else {} + initial = text_obj.get("initialAttributedTexts", {}).get("text", {}) if isinstance(text_obj, dict) else {} + if not isinstance(initial, dict): + return "" + + def key_int(k: Any) -> int: + try: + return int(k) + except Exception: + return 0 + + return "".join(str(v) for k, v in sorted(initial.items(), key=lambda kv: key_int(kv[0]))).strip() + + +def block_text_runs(block_data: dict[str, Any]) -> list[dict[str, Any]]: + """Return text runs with optional link info from a Feishu block. + + Each run is ``{"text": str, "link": str | None}``. + + Feishu wiki blocks store linked document mentions as ``inline-component`` + entries in ``text.apool.numToAttrib``. The mention JSON payload carries + the real article title (``data.title``) and URL (``data.raw_url``), while + the block's visible ``initialAttributedTexts.text`` holds a summary with + ``《 》`` as a placeholder for the mention. + """ + text_obj = block_data.get("text", {}) if isinstance(block_data, dict) else {} + if not isinstance(text_obj, dict): + return [] + + initial = text_obj.get("initialAttributedTexts", {}) + text_map = initial.get("text", {}) + if not isinstance(text_map, dict): + return [] + + def key_int(k: Any) -> int: + try: + return int(k) + except Exception: + return 0 + + full_text = "".join( + str(v) for _, v in sorted(text_map.items(), key=lambda kv: key_int(kv[0])) + ).strip() + + # Look for inline-component mention_doc in apool + apool = text_obj.get("apool", {}) + num_to_attrib = apool.get("numToAttrib", {}) if isinstance(apool, dict) else {} + + mention_title: str | None = None + mention_url: str | None = None + + for _k, v in num_to_attrib.items(): + if not isinstance(v, list) or len(v) < 2 or v[0] != "inline-component": + continue + try: + comp = json.loads(v[1]) if isinstance(v[1], str) else v[1] + except (json.JSONDecodeError, TypeError): + continue + if not isinstance(comp, dict) or comp.get("type") != "mention_doc": + continue + data = comp.get("data", {}) + t = str(data.get("title") or "").strip() + u = str(data.get("raw_url") or "").strip() + if t: + mention_title = t + mention_url = u or None + break + + runs: list[dict[str, Any]] = [] + if mention_title: + runs.append({"text": mention_title, "link": mention_url}) + summary = full_text.replace("《 》", "").replace("《》", "").strip() + if summary: + runs.append({"text": summary, "link": None}) + elif full_text: + runs.append({"text": full_text, "link": None}) + + return runs + + +def clean_update_title(text: str) -> str: + text = text.replace("《 》", "").replace("《》", "") + return re.sub(r"\s+", " ", text).strip() + + +def parse_ym_heading(text: str) -> tuple[int, int] | None: + m = re.search(r"(20\d{2})\s*年\s*(\d{1,2})\s*月", text) + if not m: + return None + return int(m.group(1)), int(m.group(2)) + + +def parse_md_heading(text: str) -> tuple[int, int] | None: + m = re.search(r"(\d{1,2})\s*月\s*(\d{1,2})\s*日", text) + if not m: + return None + return int(m.group(1)), int(m.group(2)) + + +def infer_shanghai_year_for_month_day(now_sh: datetime, month: int, day: int) -> int | None: + year = now_sh.year + try: + candidate = date(year, month, day) + except Exception: + return None + if candidate > (now_sh.date() + timedelta(days=2)): + year -= 1 + return year + + +def extract_waytoagi_recent_updates_from_block_map( + block_map: dict[str, Any], + now_sh: datetime, + page_url: str, +) -> list[dict[str, Any]]: + if not isinstance(block_map, dict) or not block_map: + return [] + + ym_by_heading2: dict[str, tuple[int, int]] = {} + near_log_parent_ids: set[str] = set() + + for bid, block in block_map.items(): + bd = block.get("data", {}) + btype = bd.get("type") + if btype not in {"heading1", "heading2", "heading3"}: + continue + heading_text = block_text(bd) + if "近7日更新日志" in heading_text or "近 7 日更新日志" in heading_text: + parent_id = str(bd.get("parent_id") or "").strip() + if parent_id: + near_log_parent_ids.add(parent_id) + + heading3_dates: dict[str, date] = {} + + for bid, block in block_map.items(): + bd = block.get("data", {}) + if bd.get("type") != "heading2": + continue + ym = parse_ym_heading(block_text(bd)) + if ym: + ym_by_heading2[bid] = ym + + for bid, block in block_map.items(): + bd = block.get("data", {}) + if bd.get("type") != "heading3": + continue + md = parse_md_heading(block_text(bd)) + if not md: + continue + month, day = md + parent = bd.get("parent_id") + if near_log_parent_ids and parent not in near_log_parent_ids: + continue + year = ym_by_heading2.get(parent, (now_sh.year, month))[0] + inferred = infer_shanghai_year_for_month_day(now_sh, month, day) + if inferred is not None: + year = inferred + try: + heading3_dates[bid] = date(year, month, day) + except Exception: + continue + + parent_map: dict[str, str] = {} + for bid, block in block_map.items(): + bd = block.get("data", {}) + parent = str(bd.get("parent_id") or "").strip() + if parent: + parent_map[bid] = parent + + def nearest_heading_date(block_id: str) -> date | None: + cur = parent_map.get(block_id) + hops = 0 + while cur and hops < 20: + if cur in heading3_dates: + return heading3_dates[cur] + cur = parent_map.get(cur) + hops += 1 + return None + + updates: list[dict[str, Any]] = [] + seen: set[tuple[str, str]] = set() + for bid, block in block_map.items(): + bd = block.get("data", {}) + if bd.get("type") not in {"bullet", "text", "todo", "ordered"}: + continue + + day = nearest_heading_date(bid) + if not day: + continue + + runs = block_text_runs(bd) + linked_run = next((r for r in runs if r.get("link")), None) + if linked_run: + title = clean_update_title(linked_run["text"]) + summary_parts = [ + clean_update_title(r["text"]) + for r in runs + if r is not linked_run and clean_update_title(r["text"]) + ] + summary = " ".join(summary_parts) if summary_parts else title + item_url = linked_run["link"] or page_url + else: + title = clean_update_title(block_text(bd)) + summary = title + item_url = page_url + + if not title: + continue + key = (day.isoformat(), title) + if key in seen: + continue + seen.add(key) + updates.append({ + "date": day.isoformat(), + "title": title, + "summary": summary, + "url": item_url, + }) + + return updates + + +def fetch_waytoagi_recent_7d(session: requests.Session, now_utc: datetime, root_url: str) -> dict[str, Any]: + now_sh = now_utc.astimezone(SH_TZ) + root_html = session.get(root_url, timeout=30).text + history_url = extract_waytoagi_history_url(root_html) + + root_client_vars = extract_feishu_client_vars(root_html) + root_block_map = root_client_vars.get("data", {}).get("block_map", {}) + updates: list[dict[str, Any]] = extract_waytoagi_recent_updates_from_block_map(root_block_map, now_sh, root_url) + + if history_url and history_url != root_url: + try: + history_html = session.get(history_url, timeout=30).text + history_client_vars = extract_feishu_client_vars(history_html) + history_block_map = history_client_vars.get("data", {}).get("block_map", {}) + updates.extend( + extract_waytoagi_recent_updates_from_block_map(history_block_map, now_sh, history_url) + ) + except Exception: + pass + + dedup_updates: dict[tuple[str, str], dict[str, Any]] = {} + for item in updates: + key = (str(item.get("date") or ""), str(item.get("title") or "")) + if key[0] and key[1] and key not in dedup_updates: + dedup_updates[key] = item + + start_date = now_sh.date() - timedelta(days=6) + end_date = now_sh.date() + recent = [ + u + for u in dedup_updates.values() + if start_date <= date.fromisoformat(str(u.get("date") or "1970-01-01")) <= end_date + ] + recent.sort(key=lambda x: (x["date"], x["title"]), reverse=True) + latest_date = recent[0]["date"] if recent else None + updates_today = [u for u in recent if u.get("date") == latest_date] if latest_date else [] + + warning = "近7日未解析到更新条目" if not recent else None + return { + "generated_at": iso(now_utc), + "timezone": "Asia/Shanghai", + "root_url": root_url, + "history_url": history_url, + "window_days": 7, + "latest_date": latest_date, + "count_today": len(updates_today), + "updates_today": updates_today, + "count_7d": len(recent), + "updates_7d": recent, + "warning": warning, + "has_error": False, + "error": None, + } + + +def waytoagi_updates_to_raw_items(payload: dict[str, Any], now: datetime) -> list[RawItem]: + updates = payload.get("updates_today") + if not isinstance(updates, list): + updates = [] + out: list[RawItem] = [] + for update in updates: + if not isinstance(update, dict): + continue + title = str(update.get("title") or "").strip() + url = str(update.get("url") or payload.get("root_url") or WAYTOAGI_DEFAULT).strip() + if not title or not url: + continue + update_date = str(update.get("date") or payload.get("latest_date") or "").strip() + source = f"社区更新 · {update_date}" if update_date else "社区更新" + out.append( + RawItem( + site_id="waytoagi", + site_name="WaytoAGI", + source=source, + title=title, + url=url, + # WaytoAGI update logs only expose a date. Treat currently + # visible latest-date entries as fresh community signals for + # the 24h board while the 7d payload keeps exact date context. + published_at=now, + meta={"summary": update.get("summary") or title}, + ) + ) + return out + + +def create_session() -> requests.Session: + session = requests.Session() + retry = Retry( + total=3, + connect=3, + read=3, + backoff_factor=0.8, + status_forcelist=[429, 500, 502, 503, 504], + allowed_methods=frozenset(["GET", "POST"]), + ) + adapter = HTTPAdapter(max_retries=retry) + session.mount("http://", adapter) + session.mount("https://", adapter) + session.headers.update({"User-Agent": BROWSER_UA, "Accept-Language": "zh-CN,zh;q=0.9"}) + return session + + +def extract_next_f_merged(html: str) -> str: + chunks = re.findall(r'self\.__next_f\.push\(\[1,"(.*?)"\]\)', html, re.S) + if not chunks: + return "" + merged = "".join(chunks) + try: + return bytes(merged, "utf-8").decode("unicode_escape") + except Exception: + return merged + + +def extract_balanced_json(decoded: str, key: str) -> Any: + idx = decoded.find(key) + if idx == -1: + raise ValueError(f"Key not found: {key}") + + start = idx + len(key) + while start < len(decoded) and decoded[start] != ":": + start += 1 + start += 1 + while start < len(decoded) and decoded[start] not in "[{": + start += 1 + + open_ch = decoded[start] + close_ch = "}" if open_ch == "{" else "]" + depth = 0 + in_str = False + esc = False + end = None + + for i, ch in enumerate(decoded[start:], start): + if in_str: + if esc: + esc = False + elif ch == "\\": + esc = True + elif ch == '"': + in_str = False + else: + if ch == '"': + in_str = True + elif ch == open_ch: + depth += 1 + elif ch == close_ch: + depth -= 1 + if depth == 0: + end = i + 1 + break + + if end is None: + raise ValueError(f"Cannot parse JSON block for key: {key}") + + snippet = decoded[start:end] + snippet = snippet.replace("$undefined", "null") + snippet = re.sub(r'"\$D([^\"]+)"', r'"\1"', snippet) + return json.loads(snippet) + + +def extract_next_data_payload(html: str) -> dict[str, Any] | None: + m = re.search( + r']*id=["\']__NEXT_DATA__["\'][^>]*>\s*(\{.*?\})\s*', + html, + re.S, + ) + if not m: + return None + try: + return json.loads(m.group(1)) + except Exception: + return None + + +def fetch_techurls(session: requests.Session, now: datetime) -> list[RawItem]: + site_id = "techurls" + site_name = "TechURLs" + r = session.get("https://techurls.com/", timeout=30) + r.raise_for_status() + soup = BeautifulSoup(r.text, "html.parser") + + out: list[RawItem] = [] + for block in soup.select("div.publisher-block"): + primary = ( + block.select_one(".publisher-text .primary").get_text(strip=True) + if block.select_one(".publisher-text .primary") + else block.get("data-publisher", "unknown") + ) + secondary = ( + block.select_one(".publisher-text .secondary").get_text(strip=True) + if block.select_one(".publisher-text .secondary") + else "" + ) + source = f"{primary} · {secondary}" if secondary and secondary != primary else primary + + for link_row in block.select("div.publisher-link"): + a = link_row.select_one("a.article-link") + if not a or not a.get("href"): + continue + title = a.get_text(" ", strip=True) + url = a["href"].strip() + + time_hint = "" + aside = link_row.select_one(".aside .text") + if aside: + time_hint = aside.get("title", "") or aside.get_text(" ", strip=True) + + published = parse_date_any(time_hint, now) + out.append( + RawItem( + site_id=site_id, + site_name=site_name, + source=source, + title=title, + url=url, + published_at=published, + meta={"time_hint": time_hint}, + ) + ) + + return out + + +def fetch_buzzing(session: requests.Session, now: datetime) -> list[RawItem]: + site_id = "buzzing" + site_name = "Buzzing" + r = session.get("https://www.buzzing.cc/feed.json", timeout=30) + r.raise_for_status() + payload = r.json() + items = payload.get("items", []) + + out: list[RawItem] = [] + for it in items: + if len(out) >= DISCUSSION_FETCH_CAP: + break + title = (it.get("title") or "").strip() + url = (it.get("url") or "").strip() + if not title or not url: + continue + source = first_non_empty( + it.get("source"), + it.get("site_name"), + it.get("channel"), + it.get("category"), + host_of_url(url), + site_name, + ) + published = parse_date_any(it.get("date_published") or it.get("date_modified"), now) + out.append( + RawItem( + site_id=site_id, + site_name=site_name, + source=source, + title=title, + url=url, + published_at=published, + meta={"raw": {k: it.get(k) for k in ("source", "site_name", "channel", "category")}}, + ) + ) + return out + + +def fetch_iris(session: requests.Session, now: datetime) -> list[RawItem]: + site_id = "iris" + site_name = "Info Flow" + + r = session.get("https://iris.findtruman.io/web/info_flow", timeout=30) + r.raise_for_status() + html = r.text + + m = re.search(r"const\s+feeds\s*=\s*\[(.*?)\]\s*;", html, re.S) + if not m: + return [] + + section = m.group(1) + feeds = re.findall( + r"\{\s*name:\s*'([^']+)'\s*,\s*url:\s*'([^']+)'\s*\}", + section, + re.S, + ) + + out: list[RawItem] = [] + for feed_name, feed_url in feeds: + if len(out) >= DISCUSSION_FETCH_CAP: + break + try: + if feedparser is not None: + parsed = feedparser.parse(feed_url) + source_name = str(feed_name or getattr(parsed, "feed", {}).get("title") or "Iris Feed") + for entry in parsed.entries: + if len(out) >= DISCUSSION_FETCH_CAP: + break + title = str(entry.get("title", "")).strip() + url = str(entry.get("link", "")).strip() + if not title or not url: + continue + published = ( + parse_date_any(entry.get("published"), now) + or parse_date_any(entry.get("updated"), now) + or parse_date_any(entry.get("pubDate"), now) + ) + out.append( + RawItem( + site_id=site_id, + site_name=site_name, + source=source_name, + title=title, + url=url, + published_at=published, + meta={"feed_url": feed_url}, + ) + ) + continue + + feed_resp = session.get(feed_url, timeout=30) + feed_resp.raise_for_status() + entries = parse_feed_entries_via_xml(feed_resp.content) + source_name = str(feed_name or "Iris Feed") + for entry in entries: + if len(out) >= DISCUSSION_FETCH_CAP: + break + out.append( + RawItem( + site_id=site_id, + site_name=site_name, + source=source_name, + title=entry["title"], + url=entry["link"], + published_at=parse_date_any(entry.get("published"), now), + meta={"feed_url": feed_url}, + ) + ) + except Exception: + # Skip blocked/broken sub feeds and keep remaining feeds. + continue + return out + + +def fetch_bestblogs(session: requests.Session, now: datetime) -> list[RawItem]: + site_id = "bestblogs" + site_name = "BestBlogs" + + api = "https://api.bestblogs.dev/api/newsletter/list" + out: list[RawItem] = [] + seen: set[str] = set() + + try: + current_page = 1 + page_count = 1 + + while current_page <= page_count and current_page <= 12: + payload = { + "currentPage": current_page, + "pageSize": 20, + "userLanguage": "en", + } + r = session.post(api, json=payload, timeout=30) + r.raise_for_status() + body = r.json() + data = body.get("data", {}) + page_count = int(data.get("pageCount", 1) or 1) + + for issue in data.get("dataList", []): + issue_id = str(issue.get("id", "")).strip() + title = str(issue.get("title", "")).strip() + if not issue_id or not title: + continue + url = f"https://www.bestblogs.dev/en/newsletter#{issue_id}" + if url in seen: + continue + seen.add(url) + + published = parse_unix_timestamp(issue.get("createdTimestamp")) + out.append( + RawItem( + site_id=site_id, + site_name=site_name, + source="Weekly Newsletter", + title=title, + url=url, + published_at=published, + meta={ + "issue_id": issue_id, + "article_count": issue.get("articleCount"), + }, + ) + ) + current_page += 1 + except Exception: + pass + + if out: + return out + + r = session.get("https://www.bestblogs.dev/en/newsletter", timeout=30) + r.raise_for_status() + soup = BeautifulSoup(r.text, "html.parser") + + for a in soup.select("a[href*='/newsletter']"): + href = (a.get("href") or "").strip() + if not href: + continue + url = href if href.startswith("http") else urljoin("https://www.bestblogs.dev", href) + title = a.get_text(" ", strip=True) + if len(title) < 8: + continue + if url in seen: + continue + seen.add(url) + dt = None + time_tag = a.select_one("time") + if time_tag: + dt = parse_date_any(time_tag.get("datetime") or time_tag.get_text(" ", strip=True), now) + out.append( + RawItem( + site_id=site_id, + site_name=site_name, + source="Weekly Newsletter", + title=title, + url=url, + published_at=dt, + meta={}, + ) + ) + + return out + + +def fetch_zeli(session: requests.Session, now: datetime) -> list[RawItem]: + site_id = "zeli" + site_name = "Zeli" + out: list[RawItem] = [] + + url = "https://zeli.app/api/hacker-news?type=hot24h" + r = session.get(url, timeout=30) + r.raise_for_status() + body = r.json() + posts = body.get("posts", []) + for p in posts: + title = str(p.get("title", "")).strip() + link = str(p.get("url", "")).strip() + if not title or not link: + continue + published = parse_unix_timestamp(p.get("time")) or now + out.append( + RawItem( + site_id=site_id, + site_name=site_name, + source="Hacker News · 24h最热", + title=title, + url=link, + published_at=published, + meta={"hn_id": p.get("id")}, + ) + ) + + return out + + +def hn_algolia_keyword_score(title: str) -> float: + blob = title.lower() + hits = 0 + for keyword in HN_ALGOLIA_KEYWORDS: + if re.search(rf"(? list[RawItem]: + seen_ids: set[str] = set() + out: list[RawItem] = [] + + for query, payload in payloads: + hits = payload.get("hits") + if not isinstance(hits, list): + continue + + for hit in hits: + if not isinstance(hit, dict): + continue + object_id = str(hit.get("objectID") or "").strip() + if not object_id or object_id in seen_ids: + continue + seen_ids.add(object_id) + + title = maybe_fix_mojibake(str(first_non_empty(hit.get("title"), hit.get("story_title")))) + if not title or hn_algolia_keyword_score(title) < HN_ALGOLIA_MIN_KEYWORD_SCORE: + continue + + try: + comments = int(hit.get("num_comments") or 0) + except Exception: + comments = 0 + try: + points = int(hit.get("points") or 0) + except Exception: + points = 0 + if comments < HN_ALGOLIA_MIN_COMMENTS and points < HN_ALGOLIA_MIN_POINTS: + continue + + item_url = str(hit.get("url") or "").strip() + hn_url = f"https://news.ycombinator.com/item?id={object_id}" + published = parse_date_any(hit.get("created_at"), now) or parse_unix_timestamp(hit.get("created_at_i")) or now + + out.append( + RawItem( + site_id="hackernews", + site_name="Hacker News", + source="HN Algolia · AI 24h", + title=title, + url=item_url or hn_url, + published_at=published, + meta={ + "hn_id": object_id, + "hn_url": hn_url, + "hn_query": query, + "hn_comments": comments, + "hn_points": points, + }, + ) + ) + + out.sort( + key=lambda item: ( + int(item.meta.get("hn_comments") or 0), + int(item.meta.get("hn_points") or 0), + item.published_at or datetime.min.replace(tzinfo=UTC), + ), + reverse=True, + ) + return out + + +def fetch_hacker_news_algolia(session: requests.Session, now: datetime) -> list[RawItem]: + start_ts = int((now - timedelta(hours=24)).timestamp()) + payloads: list[tuple[str, dict[str, Any]]] = [] + errors: list[str] = [] + + for query in HN_ALGOLIA_QUERIES: + try: + response = session.get( + HN_ALGOLIA_URL, + params={ + "query": query, + "tags": "story", + "numericFilters": f"created_at_i>{start_ts}", + "hitsPerPage": HN_ALGOLIA_HITS_PER_QUERY, + }, + headers={"Accept": "application/json"}, + timeout=16, + ) + response.raise_for_status() + payloads.append((query, response.json())) + except Exception as exc: + errors.append(f"{query}: {exc}") + time.sleep(HN_ALGOLIA_QUERY_PAUSE_SECONDS) + + if not payloads and errors: + raise ValueError(f"HN Algolia queries failed: {'; '.join(errors[:3])}") + + return parse_hn_algolia_hits(payloads, now) + + +def parse_anthropic_news_items(page_html: str, now: datetime) -> list[RawItem]: + site_id = "official_ai" + site_name = "Official AI Updates" + soup = BeautifulSoup(page_html, "html.parser") + out: list[RawItem] = [] + seen: set[str] = set() + + for a in soup.select('a[href^="/news/"]'): + href = str(a.get("href") or "").strip() + if not href or href == "/news/" or href == "/news": + continue + + title_tag = a.select_one("h1, h2, h3, h4") + title = title_tag.get_text(" ", strip=True) if title_tag else "" + title = maybe_fix_mojibake(title) + if not title or title.lower() == "news": + continue + + url = urljoin("https://www.anthropic.com", href) + if url in seen: + continue + seen.add(url) + + time_tag = a.select_one("time") + published = None + if time_tag: + published = parse_date_any(time_tag.get("datetime") or time_tag.get_text(" ", strip=True), now) + if not published: + continue + if now and published < now - timedelta(days=OFFICIAL_AI_MAX_AGE_DAYS): + continue + + out.append( + RawItem( + site_id=site_id, + site_name=site_name, + source="Anthropic News", + title=title, + url=url, + published_at=published, + meta={"provider": "Anthropic"}, + ) + ) + + return out + + +def parse_openai_codex_changelog_items(page_html: str, now: datetime) -> list[RawItem]: + site_id = "official_ai" + site_name = "Official AI Updates" + soup = BeautifulSoup(page_html, "html.parser") + out: list[RawItem] = [] + seen: set[str] = set() + + for node in soup.select("#codex-changelog-content li[id], li[id]"): + item_id = str(node.get("id") or "").strip() + if not item_id or item_id in seen: + continue + + time_tag = node.select_one("time") + title_tag = node.select_one("h3") + if not time_tag or not title_tag: + continue + + title = maybe_fix_mojibake(title_tag.get_text(" ", strip=True)) + published = parse_date_any(time_tag.get("datetime") or time_tag.get_text(" ", strip=True), now) + if not title or not published: + continue + if now and published < now - timedelta(days=OFFICIAL_AI_MAX_AGE_DAYS): + continue + + seen.add(item_id) + out.append( + RawItem( + site_id=site_id, + site_name=site_name, + source="OpenAI Codex Changelog", + title=title, + url=f"https://developers.openai.com/codex/changelog#{item_id}", + published_at=published, + meta={"provider": "OpenAI"}, + ) + ) + + return out + + +def fetch_feed_as_official_items( + session: requests.Session, + feed: dict[str, str], + now: datetime, +) -> list[RawItem]: + site_id = "official_ai" + site_name = "Official AI Updates" + feed_url = feed["xml_url"] + feed_title = feed["title"] + + resp = session.get( + feed_url, + timeout=20, + headers={ + "User-Agent": BROWSER_UA, + "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", + "Accept": "application/rss+xml, application/xml, text/xml, */*", + }, + ) + resp.raise_for_status() + + entries: list[dict[str, Any]] + if feedparser is not None: + parsed = feedparser.parse(resp.content) + entries = list(parsed.entries) + else: + entries = parse_feed_entries_via_xml(resp.content) + + out: list[RawItem] = [] + include_keywords = [ + keyword.strip().lower() + for keyword in str(feed.get("include_keywords") or "").split(",") + if keyword.strip() + ] + for entry in entries: + title = str(entry.get("title", "")).strip() + link = str(entry.get("link", "")).strip() + if not title or not link: + continue + if include_keywords: + haystack = f"{title} {link}".lower() + if not any(keyword in haystack for keyword in include_keywords): + continue + published = ( + parse_date_any(entry.get("published"), now) + or parse_date_any(entry.get("updated"), now) + or parse_date_any(entry.get("pubDate"), now) + ) + if not published: + continue + if published < now - timedelta(days=OFFICIAL_AI_MAX_AGE_DAYS): + continue + + out.append( + RawItem( + site_id=site_id, + site_name=site_name, + source=feed_title, + title=maybe_fix_mojibake(title), + url=link, + published_at=published, + meta={ + "feed_url": feed_url, + "feed_home": feed.get("html_url") or "", + }, + ) + ) + + return out + + +def feed_entry_title_link_published(entry: dict[str, Any], now: datetime) -> tuple[str, str, datetime | None]: + title = maybe_fix_mojibake(str(entry.get("title", "")).strip()) + link = str(entry.get("link", "")).strip() + published = ( + parse_date_any(entry.get("published"), now) + or parse_date_any(entry.get("updated"), now) + or parse_date_any(entry.get("pubDate"), now) + ) + return title, link, published + + +def feed_keywords(feed: dict[str, Any]) -> list[str]: + return [ + keyword.strip().lower() + for keyword in str(feed.get("include_keywords") or "").split(",") + if keyword.strip() + ] + + +def curated_feed_entry_allowed(feed: dict[str, Any], title: str, link: str) -> bool: + include_keywords = feed_keywords(feed) + if not include_keywords: + return True + haystack = title.lower() + if not feed.get("strict_title_filter"): + haystack = f"{haystack} {link.lower()} {feed.get('title', '').lower()}" + return any(keyword in haystack for keyword in include_keywords) + + +def parse_curated_ai_media_feed_items( + feed_content: bytes, + feed: dict[str, Any], + now: datetime, +) -> list[RawItem]: + site_id = "curated_media" + site_name = "Curated Media" + feed_url = str(feed["xml_url"]) + feed_title = str(feed["title"]) + + if feedparser is not None: + parsed = feedparser.parse(feed_content) + entries = list(parsed.entries) + else: + entries = parse_feed_entries_via_xml(feed_content) + + out: list[RawItem] = [] + seen_urls: set[str] = set() + max_entries = max(1, int(feed.get("max_entries") or 8)) + for entry in entries: + title, link, published = feed_entry_title_link_published(entry, now) + if not title or not link or not published: + continue + if published < now - timedelta(days=CURATED_AI_MEDIA_MAX_AGE_DAYS): + continue + if not curated_feed_entry_allowed(feed, title, link): + continue + normalized_url = normalize_url(link) + if normalized_url in seen_urls: + continue + seen_urls.add(normalized_url) + out.append( + RawItem( + site_id=site_id, + site_name=site_name, + source=feed_title, + title=title, + url=link, + published_at=published, + meta={ + "feed_url": feed_url, + "feed_home": feed.get("html_url") or "", + "research_only": bool(feed.get("research_only")), + "strict_title_filter": bool(feed.get("strict_title_filter")), + }, + ) + ) + if len(out) >= max_entries: + break + + return out + + +def fetch_curated_ai_media(session: requests.Session, now: datetime) -> list[RawItem]: + out: list[RawItem] = [] + failures: list[str] = [] + + for feed in CURATED_AI_MEDIA_FEEDS: + try: + resp = session.get( + str(feed["xml_url"]), + timeout=20, + headers={ + "User-Agent": BROWSER_UA, + "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", + "Accept": "application/rss+xml, application/atom+xml, application/xml, text/xml, */*", + }, + ) + resp.raise_for_status() + out.extend(parse_curated_ai_media_feed_items(resp.content, feed, now)) + except Exception: + failures.append(str(feed.get("title") or feed.get("xml_url") or "unknown")) + + if not out and failures: + raise ValueError(f"No curated media items parsed; failed feeds: {', '.join(failures[:4])}") + return out + + +def fetch_official_ai_updates(session: requests.Session, now: datetime) -> list[RawItem]: + out: list[RawItem] = [] + + for feed in OFFICIAL_AI_FEEDS: + try: + out.extend(fetch_feed_as_official_items(session, feed, now)) + except Exception: + continue + + try: + r = session.get("https://www.anthropic.com/news", timeout=20) + r.raise_for_status() + out.extend(parse_anthropic_news_items(r.text, now)) + except Exception: + pass + + try: + r = session.get("https://developers.openai.com/codex/changelog", timeout=20) + r.raise_for_status() + out.extend(parse_openai_codex_changelog_items(r.text, now)) + except Exception: + pass + + if not out: + raise ValueError("No official AI update sources returned items") + + return out + + +def service_incident_title_zh(title: str) -> str: + normalized = re.sub(r"\s+", " ", str(title or "")).strip() + exact = { + "Elevated Error Rates": "OpenAI 服务错误率升高", + "Elevated Errors in Codex Review": "Codex Review 错误率升高", + } + if normalized in exact: + return exact[normalized] + + patterns = ( + (r"(?i)^Elevated Errors in (.+)$", r"\1 错误率升高"), + (r"(?i)^Elevated errors affecting (.+)$", r"\1 错误率升高"), + (r"(?i)^Elevated API error rates and latency on (.+)$", r"\1 API 错误率及延迟升高"), + ( + r"(?i)^Some users may experience elevated error rates in (.+)$", + r"部分用户在使用 \1 时可能遇到较高错误率", + ), + (r"(?i)^Issues with (.+)$", r"\1 出现问题"), + ) + for pattern, replacement in patterns: + if re.match(pattern, normalized): + return re.sub(pattern, replacement, normalized).strip() + return normalized + + +def build_openai_service_status_payload(payload: dict[str, Any], now: datetime) -> dict[str, Any]: + incidents: list[dict[str, Any]] = [] + for incident in payload.get("incidents") or []: + if not isinstance(incident, dict): + continue + status = str(incident.get("status") or "").strip().lower() + if status not in ACTIVE_SERVICE_INCIDENT_STATUSES: + continue + incident_id = str(incident.get("id") or "").strip() + title = re.sub(r"\s+", " ", str(incident.get("name") or "")).strip() + if not incident_id or not title: + continue + + updates = [item for item in (incident.get("incident_updates") or []) if isinstance(item, dict)] + updates.sort( + key=lambda item: parse_date_any(item.get("updated_at") or item.get("created_at"), now) + or datetime.min.replace(tzinfo=UTC), + reverse=True, + ) + latest_update = updates[0] if updates else {} + components = sorted({ + str(component.get("name") or "").strip() + for component in (incident.get("components") or []) + if isinstance(component, dict) and str(component.get("name") or "").strip() + }) + incidents.append({ + "id": incident_id, + "provider": "OpenAI", + "title": title, + "title_zh": service_incident_title_zh(title), + "status": status, + "impact": str(incident.get("impact") or "none").strip().lower(), + "started_at": iso(parse_date_any(incident.get("created_at"), now) or now), + "updated_at": iso( + parse_date_any(incident.get("updated_at"), now) + or parse_date_any(latest_update.get("updated_at") or latest_update.get("created_at"), now) + or now + ), + "message": re.sub(r"\s+", " ", str(latest_update.get("body") or "")).strip(), + "affected_components": components, + "url": OPENAI_INCIDENT_URL.format(incident_id=incident_id), + }) + + impact_rank = {"critical": 3, "major": 2, "minor": 1, "none": 0} + incidents.sort( + key=lambda item: ( + impact_rank.get(str(item.get("impact") or ""), 0), + parse_iso(item.get("updated_at")) or datetime.min.replace(tzinfo=UTC), + ), + reverse=True, + ) + return { + "schema_version": 1, + "generated_at": iso(now), + "ok": True, + "active_count": len(incidents), + "providers": [{ + "id": "openai", + "name": "OpenAI", + "status_url": OPENAI_STATUS_PAGE_URL, + "ok": True, + "active_count": len(incidents), + }], + "incidents": incidents, + } + + +def fetch_service_status(session: requests.Session, now: datetime) -> dict[str, Any]: + try: + response = session.get( + OPENAI_STATUS_API_URL, + timeout=15, + headers={"Accept": "application/json"}, + ) + response.raise_for_status() + payload = response.json() + if not isinstance(payload, dict): + raise ValueError("OpenAI status payload is not an object") + return build_openai_service_status_payload(payload, now) + except Exception: + return { + "schema_version": 1, + "generated_at": iso(now), + "ok": False, + "active_count": 0, + "providers": [{ + "id": "openai", + "name": "OpenAI", + "status_url": OPENAI_STATUS_PAGE_URL, + "ok": False, + "active_count": 0, + }], + "incidents": [], + "error": "OpenAI 服务状态暂时无法读取", + } + + +def parse_ai_breakfast_items(markdown_text: str, now: datetime) -> list[RawItem]: + site_id = "aibreakfast" + site_name = "AI Breakfast" + out: list[RawItem] = [] + seen: set[str] = set() + pattern = re.compile( + r"([A-Z][a-z]{2}\s+\d{1,2},\s+\d{4})\s+•\s+\d+\s+min read\s+###\s+\*\*(.*?)\*\*.*?" + r"\]\((https?://aibreakfast\.beehiiv\.com/p/[^)]+)\)", + re.S, + ) + + for date_text, title_text, url in pattern.findall(markdown_text or ""): + url = url.strip() + if not url or url in seen: + continue + published = parse_date_any(date_text, now) + if not published: + continue + if now and published < now - timedelta(days=OFFICIAL_AI_MAX_AGE_DAYS): + continue + + seen.add(url) + title = re.sub(r"\s+", " ", title_text).strip() + out.append( + RawItem( + site_id=site_id, + site_name=site_name, + source="AI Breakfast", + title=maybe_fix_mojibake(title), + url=url, + published_at=published, + meta={"feed_home": "https://aibreakfast.beehiiv.com/"}, + ) + ) + + return out + + +def fetch_ai_breakfast(session: requests.Session, now: datetime) -> list[RawItem]: + resp = session.get( + AIBREAKFAST_JINA_URL, + timeout=25, + headers={ + "User-Agent": BROWSER_UA, + "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", + "Accept": "text/plain, */*", + }, + ) + resp.raise_for_status() + out = parse_ai_breakfast_items(resp.text, now) + if not out: + raise ValueError("No AI Breakfast items parsed") + return out + + +def parse_follow_builders_items(feeds: dict[str, dict[str, Any]], now: datetime) -> list[RawItem]: + site_id = "followbuilders" + site_name = "Follow Builders" + out: list[RawItem] = [] + + for builder in feeds.get("x", {}).get("x", []) or []: + name = str(builder.get("name") or builder.get("handle") or "").strip() + handle = str(builder.get("handle") or "").strip() + source = f"Follow Builders · X · {name or handle}".strip(" ·") + for tweet in builder.get("tweets", []) or []: + text = str(tweet.get("text") or "").strip() + url = str(tweet.get("url") or "").strip() + published = parse_date_any(tweet.get("createdAt"), now) + if not text or not url or not published: + continue + title = re.sub(r"\s+", " ", text) + if len(title) > 220: + title = title[:217].rstrip() + "..." + out.append( + RawItem( + site_id=site_id, + site_name=site_name, + source=source, + title=maybe_fix_mojibake(title), + url=url, + published_at=published, + meta={"handle": handle, "feed": "feed-x.json"}, + ) + ) + + for article in feeds.get("blogs", {}).get("blogs", []) or []: + title = str(article.get("title") or "").strip() + url = str(article.get("url") or "").strip() + published = parse_date_any(article.get("publishedAt"), now) or parse_date_any( + feeds.get("blogs", {}).get("generatedAt"), now + ) + if not title or not url or not published: + continue + out.append( + RawItem( + site_id=site_id, + site_name=site_name, + source=f"Follow Builders · Blog · {article.get('name') or 'Blog'}", + title=maybe_fix_mojibake(title), + url=url, + published_at=published, + meta={"feed": "feed-blogs.json"}, + ) + ) + + for episode in feeds.get("podcasts", {}).get("podcasts", []) or []: + title = str(episode.get("title") or "").strip() + url = str(episode.get("url") or "").strip() + published = parse_date_any(episode.get("publishedAt"), now) or parse_date_any( + feeds.get("podcasts", {}).get("generatedAt"), now + ) + if not title or not url or not published: + continue + out.append( + RawItem( + site_id=site_id, + site_name=site_name, + source=f"Follow Builders · Podcast · {episode.get('name') or 'Podcast'}", + title=maybe_fix_mojibake(title), + url=url, + published_at=published, + meta={"feed": "feed-podcasts.json"}, + ) + ) + + return out + + +def fetch_follow_builders(session: requests.Session, now: datetime) -> list[RawItem]: + feeds: dict[str, dict[str, Any]] = {} + for key, filename in ( + ("x", "feed-x.json"), + ("blogs", "feed-blogs.json"), + ("podcasts", "feed-podcasts.json"), + ): + resp = session.get( + f"{FOLLOW_BUILDERS_FEED_BASE}/{filename}", + timeout=20, + headers={ + "User-Agent": BROWSER_UA, + "Accept": "application/json, */*", + }, + ) + resp.raise_for_status() + feeds[key] = resp.json() + + out = parse_follow_builders_items(feeds, now) + if not out: + raise ValueError("No Follow Builders items parsed") + return out + + +def is_hubtoday_placeholder_title(title: str) -> bool: + t = (title or "").strip() + if not t: + return True + if "详情见官方介绍" in t: + return True + return t in {"原文链接", "查看详情", "点击查看", "详情"} + + +def is_hubtoday_generic_anchor_title(title: str) -> bool: + t = (title or "").strip() + if not t: + return True + if is_hubtoday_placeholder_title(t): + return True + return bool(re.search(r"\(AI资讯\)\s*$", t)) + + +def normalize_aihubtoday_records(items: list[dict[str, Any]]) -> list[dict[str, Any]]: + by_url: dict[str, list[dict[str, Any]]] = {} + keep: list[dict[str, Any]] = [] + + for item in items: + if str(item.get("site_id") or "") != "aihubtoday": + keep.append(item) + continue + url = normalize_url(str(item.get("url") or "")) + if not url: + continue + by_url.setdefault(url, []).append(item) + + for group in by_url.values(): + if not group: + continue + preferred = [g for g in group if not is_hubtoday_generic_anchor_title(str(g.get("title") or ""))] + source = preferred if preferred else group + best = max( + source, + key=lambda x: ( + event_time(x) or datetime.min.replace(tzinfo=UTC), + str(x.get("id") or ""), + ), + ) + keep.append(best) + + keep.sort(key=lambda x: event_time(x) or datetime.min.replace(tzinfo=UTC), reverse=True) + return keep + + +AIHUBTODAY_RSS_URL = "https://hex2077.dev/rss-zh-CN.xml" + + +def fetch_ai_hubtoday(session: requests.Session, now: datetime) -> list[RawItem]: + site_id = "aihubtoday" + site_name = "AI HubToday" + # ai.hubtoday.app migrated to hex2077.dev (a Next.js SPA), so the old HTML + # selectors no longer match and produced 0 usable items. Read the site's + # structured RSS feed instead: every entry has a real title, link and date, + # which is far more robust than scraping a client-rendered page. + r = session.get(AIHUBTODAY_RSS_URL, timeout=30) + r.raise_for_status() + if feedparser is not None: + entries = list(feedparser.parse(r.content).entries) + else: + entries = parse_feed_entries_via_xml(r.content) + + out: list[RawItem] = [] + seen_urls: set[str] = set() + for entry in entries: + title, link, published = feed_entry_title_link_published(entry, now) + if len(title) < 5 or not link.startswith("http"): + continue + if is_hubtoday_placeholder_title(title): + continue + key_url = normalize_url(link) + if key_url in seen_urls: + continue + seen_urls.add(key_url) + out.append( + RawItem( + site_id=site_id, + site_name=site_name, + source="Daily Digest", + title=title, + url=link, + published_at=published, + meta={"feed_url": AIHUBTODAY_RSS_URL}, + ) + ) + return out + +def fetch_aibase(session: requests.Session, now: datetime) -> list[RawItem]: + site_id = "aibase" + site_name = "AIbase" + + r = session.get("https://www.aibase.com/zh/news", timeout=30) + r.raise_for_status() + soup = BeautifulSoup(r.text, "html.parser") + + out: list[RawItem] = [] + for a in soup.select("a[href^='/news/']"): + h3 = a.select_one("h3") + if not h3: + continue + title = h3.get_text(" ", strip=True) + href = a.get("href", "").strip() + if not title or not href: + continue + + time_text = "" + time_tag = a.select_one("div.text-sm.text-gray-400 span") + if time_tag: + time_text = time_tag.get_text(" ", strip=True) + + published = parse_date_any(time_text, now) + out.append( + RawItem( + site_id=site_id, + site_name=site_name, + source=site_name, + title=title, + url=urljoin("https://www.aibase.com", href), + published_at=published, + meta={"time_hint": time_text}, + ) + ) + + return out + + +def parse_aihot_feed_items(feed_content: bytes, now: datetime, feed_url: str = AIHOT_FEED_URL) -> list[RawItem]: + site_id = "aihot" + site_name = "AI HOT" + source_name = site_name + if feedparser is not None: + parsed = feedparser.parse(feed_content) + entries = list(parsed.entries) + source_name = first_non_empty(getattr(parsed, "feed", {}).get("title"), site_name) + else: + entries = parse_feed_entries_via_xml(feed_content) + + out: list[RawItem] = [] + seen_urls: set[str] = set() + for entry in entries: + title = maybe_fix_mojibake(str(entry.get("title") or "").strip()) + link = str(entry.get("link") or "").strip() + if not title or not link: + continue + normalized_url = normalize_url(link) + if normalized_url in seen_urls: + continue + seen_urls.add(normalized_url) + published = ( + parse_date_any(entry.get("published"), now) + or parse_date_any(entry.get("updated"), now) + or parse_date_any(entry.get("pubDate"), now) + ) + if not published: + continue + author_detail = entry.get("author_detail") or {} + entry_source = first_non_empty( + author_detail.get("name") if isinstance(author_detail, dict) else "", + entry.get("author"), + source_name, + ) + out.append( + RawItem( + site_id=site_id, + site_name=site_name, + source=maybe_fix_mojibake(entry_source), + title=title, + url=link, + published_at=published, + meta={"feed_url": feed_url}, + ) + ) + + return out + + +def parse_aihot_api_items(payload: dict[str, Any], now: datetime | None = None) -> list[RawItem]: + site_id = "aihot" + site_name = "AI HOT" + out: list[RawItem] = [] + seen_urls: set[str] = set() + + raw_items = payload.get("items") + if not isinstance(raw_items, list): + return out + + for entry in raw_items: + if not isinstance(entry, dict): + continue + raw_score = entry.get("score") + if isinstance(raw_score, bool): + continue + try: + score = float(raw_score) + except (TypeError, ValueError): + continue + if score < AIHOT_MIN_SCORE: + continue + + title = maybe_fix_mojibake(str(first_non_empty(entry.get("title"), entry.get("title_en")) or "").strip()) + link = str(entry.get("url") or "").strip() + if not title or not link: + continue + normalized_url = normalize_url(link) + if normalized_url in seen_urls: + continue + seen_urls.add(normalized_url) + + published = parse_iso(str(entry.get("publishedAt") or "")) or parse_date_any(entry.get("publishedAt"), now) + source = maybe_fix_mojibake(str(first_non_empty(entry.get("source"), site_name))) + score_value: int | float = int(score) if score.is_integer() else score + out.append( + RawItem( + site_id=site_id, + site_name=site_name, + source=source, + title=title, + url=link, + published_at=published, + meta={ + "api_url": AIHOT_ITEMS_API_URL, + "aihot_id": entry.get("id"), + "aihot_score": score_value, + "aihot_category": entry.get("category"), + "aihot_selected": bool(entry.get("selected")), + "provided_title_zh": entry.get("title"), + "provided_title_en": entry.get("title_en"), + "summary": entry.get("summary"), + }, + ) + ) + + return out + + +def fetch_aihot(session: requests.Session, now: datetime) -> list[RawItem]: + out: list[RawItem] = [] + cursor = "" + for _ in range(AIHOT_API_MAX_PAGES): + params: dict[str, Any] = {"mode": "selected", "take": AIHOT_API_TAKE} + if cursor: + params["cursor"] = cursor + r = session.get( + AIHOT_ITEMS_API_URL, + timeout=30, + params=params, + headers={ + "User-Agent": AIHOT_API_UA, + "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", + "Accept": "application/json", + }, + ) + r.raise_for_status() + payload = r.json() + out.extend(parse_aihot_api_items(payload, now)) + cursor = str(payload.get("nextCursor") or "") + if not payload.get("hasNext") or not cursor: + break + return out + + + + +def extract_newsnow_source_ids(js: str) -> list[str]: + marker = "{v2ex:vL" + start = js.find(marker) + if start == -1: + return ["hackernews", "producthunt", "github", "sspai", "juejin", "36kr"] + + # Locate beginning "{" and parse until matching "}" + block_start = start + depth = 0 + end = None + in_str = False + esc = False + + for i, ch in enumerate(js[block_start:], block_start): + if in_str: + if esc: + esc = False + elif ch == "\\": + esc = True + elif ch == '"': + in_str = False + continue + + if ch == '"': + in_str = True + continue + + if ch == "{": + depth += 1 + elif ch == "}": + depth -= 1 + if depth == 0: + end = i + 1 + break + + if end is None: + return ["hackernews", "producthunt", "github", "sspai", "juejin", "36kr"] + + obj = js[block_start:end] + all_keys = [m.group(2) for m in re.finditer(r'(["\']?)([a-zA-Z0-9_-]+)\1\s*:', obj)] + + ignore = { + "name", + "column", + "home", + "https", + "color", + "interval", + "title", + "type", + "redirect", + "desc", + } + + source_ids: list[str] = [] + for key in all_keys: + if key in ignore: + continue + if key not in source_ids: + source_ids.append(key) + + # API currently returns around 57 source ids successfully. + return source_ids + + +def fetch_newsnow(session: requests.Session, now: datetime) -> list[RawItem]: + site_id = "newsnow" + site_name = "NewsNow" + + home = session.get("https://newsnow.busiyi.world/", timeout=30) + home.raise_for_status() + soup = BeautifulSoup(home.text, "html.parser") + + bundle = None + for script in soup.select("script[src]"): + src = script.get("src", "") + if "/assets/index-" in src and src.endswith(".js"): + bundle = urljoin("https://newsnow.busiyi.world/", src) + break + + source_ids = ["hackernews", "producthunt", "github", "sspai", "juejin", "36kr"] + if bundle: + js = session.get(bundle, timeout=30).text + source_ids = extract_newsnow_source_ids(js) + + headers = { + "User-Agent": BROWSER_UA, + "Accept": "application/json, text/plain, */*", + "Content-Type": "application/json", + "Origin": "https://newsnow.busiyi.world", + "Referer": "https://newsnow.busiyi.world/", + } + + response = session.post( + "https://newsnow.busiyi.world/api/s/entire", + json={"sources": source_ids}, + headers=headers, + timeout=45, + ) + + if response.status_code != 200: + # fallback to per-source API + source_blocks = [] + for sid in source_ids: + rr = session.get(f"https://newsnow.busiyi.world/api/s?id={sid}", headers=headers, timeout=20) + if rr.status_code == 200: + try: + source_blocks.append(rr.json()) + except Exception: + pass + else: + body = response.json() + source_blocks = body.get("data") if isinstance(body, dict) else body + if not isinstance(source_blocks, list): + source_blocks = [] + + out: list[RawItem] = [] + for block in source_blocks: + sid = str(block.get("id") or "unknown") + source_title = first_non_empty(block.get("title"), block.get("name"), block.get("desc"), sid) + source_label = f"{source_title} ({sid})" if source_title != sid else sid + updated = parse_unix_timestamp(block.get("updatedTime")) or now + items = block.get("items") or [] + for it in items: + title = str(it.get("title") or "").strip() + url = str(it.get("url") or "").strip() + if not title or not url: + continue + + published = None + published = published or parse_date_any(it.get("pubDate"), now) + if not published: + extra = it.get("extra") or {} + if isinstance(extra, dict): + published = parse_date_any(extra.get("date"), now) + if not published: + published = updated + + out.append( + RawItem( + site_id=site_id, + site_name=site_name, + source=source_label, + title=title, + url=url, + published_at=published, + meta={}, + ) + ) + + return out + + +def collect_all(session: requests.Session, now: datetime) -> tuple[list[RawItem], list[dict[str, Any]]]: + tasks = [ + ("official_ai", "Official AI Updates", fetch_official_ai_updates), + ("curated_media", "Curated Media", fetch_curated_ai_media), + ("aibreakfast", "AI Breakfast", fetch_ai_breakfast), + ("followbuilders", "Follow Builders", fetch_follow_builders), + ("techurls", "TechURLs", fetch_techurls), + ("buzzing", "Buzzing", fetch_buzzing), + ("iris", "Info Flow", fetch_iris), + ("bestblogs", "BestBlogs", fetch_bestblogs), + ("zeli", "Zeli", fetch_zeli), + ("hackernews", "Hacker News", fetch_hacker_news_algolia), + ("aihubtoday", "AI HubToday", fetch_ai_hubtoday), + ("aibase", "AIbase", fetch_aibase), + ("aihot", "AI HOT", fetch_aihot), + ("newsnow", "NewsNow", fetch_newsnow), + ] + + raw_items: list[RawItem] = [] + statuses: list[dict[str, Any]] = [] + + for site_id, site_name, fn in tasks: + start = time.perf_counter() + error = None + count = 0 + try: + items = fn(session, now) + count = len(items) + raw_items.extend(items) + except Exception as exc: + error = str(exc) + elapsed_ms = int((time.perf_counter() - start) * 1000) + statuses.append( + { + "site_id": site_id, + "site_name": site_name, + "ok": error is None, + "item_count": count, + "duration_ms": elapsed_ms, + "error": error, + } + ) + + return raw_items, statuses + + +def parse_opml_subscriptions(opml_path: Path) -> list[dict[str, str]]: + root = ET.parse(opml_path).getroot() + out: list[dict[str, str]] = [] + seen: set[str] = set() + + for outline in root.findall(".//outline"): + xml_url = str(outline.attrib.get("xmlUrl") or "").strip() + if not xml_url: + continue + if xml_url in seen: + continue + seen.add(xml_url) + title = first_non_empty( + outline.attrib.get("title"), + outline.attrib.get("text"), + host_of_url(xml_url), + xml_url, + ) + html_url = str(outline.attrib.get("htmlUrl") or "").strip() + out.append( + { + "title": title, + "xml_url": xml_url, + "html_url": html_url, + } + ) + return out + + +def resolve_official_rss_url(feed_url: str) -> tuple[str | None, str | None]: + src = (feed_url or "").strip() + if not src: + return None, "empty_url" + if src in RSS_FEED_SKIP_EXACT: + return None, "no_official_rss_or_unreachable" + for prefix in RSS_FEED_SKIP_PREFIXES: + if src.startswith(prefix): + return None, "no_official_rss_for_source_type" + replaced = RSS_FEED_REPLACEMENTS.get(src) + if replaced: + return replaced, "official_replacement" + return src, None + + +def resolve_opml_bridge_source(feed_url: str, html_url: str = "") -> dict[str, str] | None: + src = (feed_url or "").strip() + parsed = urlparse(src) + path = parsed.path.strip("/") + parts = [p for p in path.split("/") if p] + + if parsed.netloc == "rsshub.app" and len(parts) >= 3 and parts[:2] == ["telegram", "channel"]: + slug = parts[2] + return { + "bridge_type": "telegram", + "bridge_slug": slug, + "url": f"https://t.me/s/{slug}", + } + + if parsed.netloc == "rsshub.app" and len(parts) >= 3 and parts[0] == "jike": + kind = parts[1] + ident = parts[2] + if kind == "topic": + return { + "bridge_type": "jike", + "bridge_kind": "topic", + "bridge_slug": ident, + "url": f"https://m.okjike.com/topics/{ident}", + } + if kind == "user": + return { + "bridge_type": "jike", + "bridge_kind": "user", + "bridge_slug": ident, + "url": f"https://m.okjike.com/users/{ident}", + } + + html = (html_url or "").strip() + if html.startswith("https://t.me/s/"): + slug = html.rstrip("/").split("/")[-1] + return {"bridge_type": "telegram", "bridge_slug": slug, "url": html} + if html.startswith("https://m.okjike.com/topics/"): + ident = html.rstrip("/").split("/")[-1] + return {"bridge_type": "jike", "bridge_kind": "topic", "bridge_slug": ident, "url": html} + if html.startswith("https://m.okjike.com/users/"): + ident = html.rstrip("/").split("/")[-1] + return {"bridge_type": "jike", "bridge_kind": "user", "bridge_slug": ident, "url": html} + + return None + + +def compact_title(text: str, limit: int = 96) -> str: + s = re.sub(r"\s+", " ", text or "").strip() + if len(s) <= limit: + return s + return s[: limit - 1].rstrip() + "…" + + +def parse_telegram_public_items( + html: str, + *, + now: datetime, + source_name: str, + slug: str, +) -> list[RawItem]: + soup = BeautifulSoup(html, "html.parser") + out: list[RawItem] = [] + for msg in soup.select(".tgme_widget_message"): + data_post = str(msg.get("data-post") or "").strip() + if not data_post: + continue + text_node = msg.select_one(".tgme_widget_message_text") + text = text_node.get_text(" ", strip=True) if text_node else "" + if not text: + preview_title = msg.select_one(".tgme_widget_message_link_preview_title") + text = preview_title.get_text(" ", strip=True) if preview_title else "" + if not text: + continue + time_node = msg.select_one("time[datetime]") + published = parse_date_any(time_node.get("datetime") if time_node else None, now) + if not published: + continue + url = f"https://t.me/{data_post}" + out.append( + RawItem( + site_id="opmlrss", + site_name="OPML RSS", + source=source_name, + title=compact_title(text), + url=url, + published_at=published, + meta={"bridge_type": "telegram", "bridge_slug": slug, "feed_home": f"https://t.me/s/{slug}"}, + ) + ) + return out + + +def parse_jike_public_items( + html: str, + *, + now: datetime, + source_name: str, + source_url: str, +) -> list[RawItem]: + soup = BeautifulSoup(html, "html.parser") + script = soup.find("script", id="__NEXT_DATA__") + if script is None or not script.string: + return [] + try: + payload = json.loads(script.string) + except Exception: + return [] + page_props = payload.get("props", {}).get("pageProps", {}) + posts = page_props.get("posts") or [] + out: list[RawItem] = [] + for post in posts: + if not isinstance(post, dict): + continue + post_id = str(post.get("id") or "").strip() + text = str(post.get("content") or "").strip() + if not post_id or not text: + continue + published = parse_date_any(post.get("createdAt") or post.get("actionTime"), now) + if not published: + continue + out.append( + RawItem( + site_id="opmlrss", + site_name="OPML RSS", + source=source_name, + title=compact_title(text), + url=f"https://m.okjike.com/originalPosts/{post_id}", + published_at=published, + meta={"bridge_type": "jike", "feed_home": source_url}, + ) + ) + return out + + +def fetch_opml_rss( + now: datetime, + opml_path: Path, + max_feeds: int = 0, +) -> tuple[list[RawItem], dict[str, Any], list[dict[str, Any]]]: + feeds = parse_opml_subscriptions(opml_path) + if max_feeds > 0: + feeds = feeds[:max_feeds] + + out: list[RawItem] = [] + feed_statuses: list[dict[str, Any]] = [] + resolved_feeds: list[dict[str, str]] = [] + + for feed in feeds: + original_url = feed["xml_url"] + bridge = resolve_opml_bridge_source(original_url, feed.get("html_url") or "") + if bridge: + record = dict(feed) + record["xml_url_original"] = original_url + record["xml_url"] = bridge["url"] + record["replaced"] = True + record.update(bridge) + resolved_feeds.append(record) + continue + + resolved_url, skip_reason = resolve_official_rss_url(original_url) + if not resolved_url: + feed_id = hashlib.sha1(original_url.encode("utf-8")).hexdigest()[:10] + feed_statuses.append( + { + "site_id": f"opmlrss:{feed_id}", + "site_name": "OPML RSS", + "feed_title": feed["title"], + "feed_url": original_url, + "effective_feed_url": None, + "ok": True, + "item_count": 0, + "duration_ms": 0, + "error": None, + "skipped": True, + "skip_reason": skip_reason or "skipped", + "replaced": False, + } + ) + continue + record = dict(feed) + record["xml_url_original"] = original_url + record["xml_url"] = resolved_url + record["replaced"] = bool(resolved_url != original_url) + resolved_feeds.append(record) + + def fetch_single_feed(feed: dict[str, str]) -> tuple[list[RawItem], dict[str, Any]]: + feed_url = feed["xml_url"] + original_feed_url = str(feed.get("xml_url_original") or feed_url) + feed_title = feed["title"] + feed_id = hashlib.sha1(feed_url.encode("utf-8")).hexdigest()[:10] + start = time.perf_counter() + error = None + local_items: list[RawItem] = [] + + try: + resp = requests.get( + feed_url, + timeout=12, + headers={ + "User-Agent": BROWSER_UA, + "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", + }, + ) + resp.raise_for_status() + + bridge_type = str(feed.get("bridge_type") or "") + if bridge_type == "telegram": + local_items = parse_telegram_public_items( + resp.text, + now=now, + source_name=feed_title, + slug=str(feed.get("bridge_slug") or ""), + ) + elif bridge_type == "jike": + local_items = parse_jike_public_items( + resp.text, + now=now, + source_name=feed_title, + source_url=feed_url, + ) + elif feedparser is not None: + parsed = feedparser.parse(resp.content) + source_name = first_non_empty( + feed_title, + getattr(parsed, "feed", {}).get("title"), + host_of_url(feed_url), + ) + entries = parsed.entries + cn_feed = ".cn/" in feed_url or feed_url.endswith(".cn") or has_cjk(str(feed_title or "")) + pending: list[tuple[str, str, datetime]] = [] + for entry in entries: + title = str(entry.get("title", "")).strip() + link = str(entry.get("link", "")).strip() + if not title or not link: + continue + published = ( + parse_date_any(entry.get("published"), now) + or parse_date_any(entry.get("updated"), now) + or parse_date_any(entry.get("pubDate"), now) + ) + if not published: + continue + pending.append((title, link, published)) + corrected_times = correct_feed_published_batch( + [p for _, _, p in pending], + now, + assume_cst_mislabel=cn_feed or any(has_cjk(t) for t, _, _ in pending), + ) + for (title, link, _), published in zip(pending, corrected_times): + local_items.append( + RawItem( + site_id="opmlrss", + site_name="OPML RSS", + source=source_name, + title=title, + url=link, + published_at=published, + meta={ + "feed_url": feed_url, + "feed_home": feed.get("html_url") or "", + }, + ) + ) + else: + source_name = first_non_empty(feed_title, host_of_url(feed_url)) + entries = parse_feed_entries_via_xml(resp.content) + cn_feed = ".cn/" in feed_url or feed_url.endswith(".cn") or has_cjk(str(feed_title or "")) + pending_xml: list[tuple[dict[str, str], datetime]] = [] + for entry in entries: + published = parse_date_any(entry.get("published"), now) + if not published: + continue + pending_xml.append((entry, published)) + corrected_times = correct_feed_published_batch( + [p for _, p in pending_xml], + now, + assume_cst_mislabel=cn_feed + or any(has_cjk(str(e.get("title") or "")) for e, _ in pending_xml), + ) + for (entry, _), published in zip(pending_xml, corrected_times): + local_items.append( + RawItem( + site_id="opmlrss", + site_name="OPML RSS", + source=source_name, + title=entry.get("title", ""), + url=entry.get("link", ""), + published_at=published, + meta={ + "feed_url": feed_url, + "feed_home": feed.get("html_url") or "", + }, + ) + ) + except Exception as exc: + error = str(exc) + + duration_ms = int((time.perf_counter() - start) * 1000) + status = { + "site_id": f"opmlrss:{feed_id}", + "site_name": "OPML RSS", + "feed_title": feed_title, + "feed_url": original_feed_url, + "effective_feed_url": feed_url, + "ok": error is None, + "item_count": len(local_items), + "duration_ms": duration_ms, + "error": error, + "skipped": False, + "skip_reason": None, + "replaced": bool(original_feed_url != feed_url), + "bridge_type": feed.get("bridge_type"), + } + return local_items, status + + if resolved_feeds: + worker_count = min(20, max(4, len(resolved_feeds))) + with ThreadPoolExecutor(max_workers=worker_count) as executor: + futures = [executor.submit(fetch_single_feed, feed) for feed in resolved_feeds] + for future in as_completed(futures): + items, status = future.result() + out.extend(items) + feed_statuses.append(status) + + feed_statuses.sort(key=lambda x: str(x.get("feed_title") or x.get("feed_url") or "")) + total_duration_ms = sum(int(s.get("duration_ms") or 0) for s in feed_statuses) + ok_feeds = sum(1 for s in feed_statuses if s["ok"]) + failed_feeds = sum(1 for s in feed_statuses if not s["ok"]) + skipped_feeds = sum(1 for s in feed_statuses if s.get("skipped")) + replaced_feeds = sum(1 for s in feed_statuses if s.get("replaced")) + + summary_status = { + "site_id": "opmlrss", + "site_name": "OPML RSS", + "ok": ok_feeds > 0, + "partial_failures": failed_feeds, + "item_count": len(out), + "duration_ms": total_duration_ms, + "error": None if failed_feeds == 0 else f"{failed_feeds} feeds failed", + "feed_count": len(feeds), + "effective_feed_count": len(resolved_feeds), + "ok_feed_count": ok_feeds, + "failed_feed_count": failed_feeds, + "skipped_feed_count": skipped_feeds, + "replaced_feed_count": replaced_feeds, + } + return out, summary_status, feed_statuses + + +def load_archive(path: Path) -> dict[str, dict[str, Any]]: + if not path.exists(): + return {} + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except Exception: + return {} + + items = payload.get("items", []) + out: dict[str, dict[str, Any]] = {} + if isinstance(items, list): + for it in items: + item_id = it.get("id") + if item_id: + out[item_id] = it + elif isinstance(items, dict): + for item_id, it in items.items(): + if isinstance(it, dict): + it["id"] = item_id + out[item_id] = it + return out + + +def event_time(record: dict[str, Any]) -> datetime | None: + # RSS sources must rely on the source's publish time only. + # first_seen_at is fetch time and would falsely mark historical items as "24h". + if str(record.get("site_id") or "") == "opmlrss": + return parse_iso(record.get("published_at")) + return parse_iso(record.get("published_at")) or parse_iso(record.get("first_seen_at")) + + +SOURCE_TIER_BY_SITE: dict[str, tuple[str, str, int]] = { + "official_ai": ("official", "官方一手源", 0), + "curated_media": ("ai_media", "精选AI媒体", 2), + "aibreakfast": ("ai_vertical", "AI垂直源", 1), + "aihubtoday": ("ai_vertical", "AI垂直源", 1), + "aibase": ("ai_vertical", "AI垂直源", 1), + "aihot": ("ai_vertical", "AI垂直源", 1), + "bestblogs": ("ai_vertical", "AI垂直源", 1), + "waytoagi": ("community", "社区更新", 2), + "followbuilders": ("builders", "Builders/X源", 2), + "opmlrss": ("user_opml", "RSS/OPML", 3), + "tikhub_douyin": ("self_media", "自媒体源", 4), + "tikhub_xiaohongshu": ("self_media", "自媒体源", 4), + "xapi": ("advanced", "高级源", 4), + "socialdata_x": ("advanced", "高级源", 4), + "techurls": ("discussion", "热议参考", 5), + "buzzing": ("discussion", "热议参考", 5), + "iris": ("discussion", "热议参考", 5), + "zeli": ("discussion", "热议参考", 5), + "hackernews": ("discussion", "热议参考", 5), + "newsnow": ("discussion", "热议参考", 5), +} + +SOURCE_TIER_IMPORTANCE = { + "official": 1.0, + "ai_vertical": 0.78, + "ai_media": 0.58, + "community": 0.54, + "builders": 0.62, + "user_opml": 0.5, + "self_media": 0.48, + "advanced": 0.45, + "discussion": 0.32, + "other": 0.25, +} + +# --------------------------------------------------------------------------- +# aihot first-party source override +# --------------------------------------------------------------------------- +# Items from aihot that originate from official company channels (not individual +# analysts/bloggers) should be promoted to the "official" tier. The strings +# below are exact ``source`` field values as returned by the aihot public API. +AIHOT_FIRST_PARTY_SOURCE_NAMES: frozenset[str] = frozenset({ + # --- OpenAI --- + "OpenAI:官网动态(RSS · 排除企业/客户案例)", + "X:OpenAI Developers (@OpenAIDevs)", + "X:ChatGPT (@ChatGPTapp)", + # --- Anthropic --- + "Anthropic:Newsroom(网页)", + "Claude Code:GitHub Releases(RSS)", + "X:Claude Devs (@ClaudeDevs)", + # --- Google --- + "Google Developers Blog(RSS)", + "Google Research:Blog(网页)", + "X:Google DeepMind (@GoogleDeepMind)", + "X:NotebookLM (@NotebookLM)", + # --- Meta --- + "X:AI at Meta (@AIatMeta)", + # --- Mistral --- + "Mistral AI:News(网页)", + # --- Hugging Face --- + "Hugging Face:Blog(RSS)", + "HuggingFace Daily Papers(社区热门论文)", + # --- Perplexity --- + "X:Perplexity (@perplexity_ai)", + # --- Runway --- + "X:Runway (@runwayml)", + # --- Alibaba / Qwen --- + "X:阿里云 / Alibaba Cloud (@alibaba_cloud)", + # --- ByteDance / Kling --- + "X:可灵 Kling AI (@Kling_ai)", +}) + + +def source_tier_for_record(site_id: str, source: str) -> tuple[str, str, int] | None: + """Return ``("official", "官方一手源", 0)`` when an aihot item comes from a + known first-party company channel, otherwise ``None`` (caller falls through + to the global ``SOURCE_TIER_BY_SITE`` lookup).""" + if site_id != "aihot": + return None + src = source.strip() + if src in AIHOT_FIRST_PARTY_SOURCE_NAMES: + return ("official", "官方一手源", 0) + return None + + +TITLE_STOPWORDS = { + "a", + "an", + "and", + "are", + "as", + "at", + "for", + "from", + "in", + "into", + "is", + "new", + "of", + "on", + "the", + "to", + "with", + "发布", + "推出", + "上线", + "更新", +} + +VENDOR_ALIASES = { + "openai": "openai", + "anthropic": "anthropic", + "claude": "anthropic", + "google": "google", + "deepmind": "google", + "gemini": "google", + "microsoft": "microsoft", + "github": "github", + "huggingface": "huggingface", + "hugging face": "huggingface", + "meta": "meta", + "llama": "meta", + "deepseek": "deepseek", + "mistral": "mistral", + "xai": "xai", + "grok": "xai", +} + +MODEL_RE = re.compile( + r"(?i)\b(" + r"gpt[-\s]?\d+(?:\.\d+)?[a-z]*|" + r"claude(?:[-\s]?(?:opus|sonnet|haiku))?[-\s]?\d+(?:\.\d+)?|" + r"gemini[-\s]?\d+(?:\.\d+)?|" + r"llama[-\s]?\d+(?:\.\d+)?|" + r"deepseek[-\s]?[a-z0-9.]+|" + r"grok[-\s]?\d+(?:\.\d+)?|" + r"mistral[-\s]?[a-z0-9.]+" + r")\b" +) + + +def source_tier_for_site(site_id: str) -> dict[str, Any]: + sid = str(site_id or "").strip().lower() + if sid.startswith("opmlrss"): + sid = "opmlrss" + tier, label, rank = SOURCE_TIER_BY_SITE.get(sid, ("other", "其他来源", 9)) + return {"source_tier": tier, "source_tier_label": label, "source_tier_rank": rank} + + +def add_source_tier_fields(record: dict[str, Any]) -> dict[str, Any]: + out = dict(record) + site_id = str(out.get("site_id") or "") + # For aihot items, check if the source is a known first-party channel first + override = source_tier_for_record(site_id, str(out.get("source") or "")) + if override is not None: + tier, label, rank = override + out["source_tier"] = tier + out["source_tier_label"] = label + out["source_tier_rank"] = rank + else: + out.update(source_tier_for_site(site_id)) + return out + + +def source_tier_sort_key(record: dict[str, Any]) -> tuple[int, float, str]: + tier = source_tier_for_site(str(record.get("site_id") or "")) + ts = event_time(record) + return (int(tier["source_tier_rank"]), -(ts.timestamp() if ts else 0), str(record.get("title") or "")) + + +AI_KEYWORDS = [ + "aigc", + "llm", + "gpt", + "claude", + "gemini", + "deepseek", + "openai", + "anthropic", + "copilot", + "codex", + "mcp", + "hugging face", + "huggingface", + "transformer", + "prompt", + "diffusion", + "agent", + "多模态", + "大模型", + "模型", + "人工智能", + "机器学习", + "深度学习", + "智能体", + "算力", + "推理", + "微调", +] + +TECH_KEYWORDS = [ + "robot", + "robotics", + "embodied", + "autonomous", + "vision", + "chip", + "semiconductor", + "cuda", + "npu", + "gpu", + "cloud", + "developer", + "开源", + "技术", + "编程", + "软件", + "芯片", + "机器人", + "具身", +] + +NOISE_KEYWORDS = [ + "娱乐", + "明星", + "八卦", + "足球", + "篮球", + "彩票", + "情感", + "旅游", + "美食", +] + +COMMERCE_NOISE_KEYWORDS = [ + "淘宝", + "天猫", + "京东", + "拼多多", + "券后", + "热销总榜", + "促销", + "优惠", + "补贴", + "下单", + "首发价", +] + +EN_SIGNAL_RE = re.compile( + r"(?i)(? bool: + h = haystack.lower() + return any(k in h for k in keywords) + + +def contains_meaningful_ai_signal(haystack: str) -> bool: + h = haystack.lower() + if MEANINGFUL_EN_SIGNAL_RE.search(h): + return True + return any(k in h for k in AI_KEYWORDS if k not in BROAD_AI_TERMS) + + +def redact_public_text(text: str) -> str: + if not isinstance(text, str) or not text: + return text + text = EMAIL_RE.sub("[redacted-email]", text) + return SECRET_LIKE_RE.sub("[redacted-secret]", text) + + +def sanitize_public_value(value: Any) -> Any: + if isinstance(value, str): + return redact_public_text(value) + if isinstance(value, list): + return [sanitize_public_value(item) for item in value] + if isinstance(value, dict): + return {key: sanitize_public_value(val) for key, val in value.items()} + return value + + +def sanitize_public_payload(payload: dict[str, Any]) -> dict[str, Any]: + return sanitize_public_value(payload) + + +def compact_public_snippet(text: str, max_chars: int = 240) -> str: + """Return a short redacted snippet suitable for public/static JSON.""" + snippet = re.sub(r"\s+", " ", str(text or "")).strip() + snippet = redact_public_text(snippet) + if len(snippet) <= max_chars: + return snippet + return snippet[: max_chars - 1].rstrip() + "…" + + +def sender_domain_from_address(raw_sender: str) -> str | None: + """Extract only the sender domain; never expose the raw email address.""" + _, email_addr = parseaddr(str(raw_sender or "")) + if "@" not in email_addr: + return None + domain = email_addr.rsplit("@", 1)[-1].strip().lower().strip(">") + return domain or None + + +def parse_domain_filter(raw: str) -> list[str]: + """Parse a comma-separated sender-domain allowlist for private newsletter demos.""" + domains: list[str] = [] + for part in re.split(r"[,\s]+", str(raw or "")): + domain = part.strip().lower().lstrip("@") + if domain and re.match(r"^[a-z0-9.-]+\.[a-z]{2,}$", domain): + domains.append(domain) + return sorted(set(domains)) + + +def domain_matches_filter(sender_domain: str | None, allowed_domains: list[str]) -> bool: + if not allowed_domains: + return True + domain = str(sender_domain or "").lower().strip() + return any(domain == allowed or domain.endswith(f".{allowed}") for allowed in allowed_domains) + + +def filter_agentmail_messages_by_domain( + messages: list[dict[str, Any]], + allowed_domains: list[str], +) -> list[dict[str, Any]]: + if not allowed_domains: + return messages + return [ + msg + for msg in messages + if domain_matches_filter(agentmail_sender_domain(msg), allowed_domains) + ] + + +def agentmail_sender_domain(message: dict[str, Any]) -> str | None: + sender = message.get("from") + if isinstance(sender, dict): + return sender_domain_from_address(str(sender.get("email") or "")) + return sender_domain_from_address(str(sender or "")) + + +def agentmail_message_timestamp(message: dict[str, Any]) -> Any: + return message.get("timestamp") or message.get("created_at") or message.get("received_at") + + +def agentmail_message_preview(message: dict[str, Any]) -> str: + return str(message.get("preview") or message.get("snippet") or "") + + +def agentmail_message_id(message: dict[str, Any]) -> str: + return str(message.get("message_id") or message.get("id") or "").strip() + + +def clean_agentmail_public_url(raw_url: Any) -> str: + """Return a public, browser-openable newsletter URL without common tracking params.""" + url = str(raw_url or "").strip() + if not url: + return "" + url = url.replace("&", "&") + parsed = urlparse(url) + if parsed.scheme not in {"http", "https"} or not parsed.netloc: + return "" + if parsed.username or parsed.password: + return "" + host = (parsed.hostname or "").lower() + if host.startswith("tracking."): + # Decode only the embedded URL segment, excluding the redirect's /1/token suffix. + nested_match = re.search(r"https?:(?:%2f){2}[^/\s]+", parsed.path, re.I) + return clean_agentmail_public_url(unquote(nested_match.group(0))) if nested_match else "" + if any(host == blocked or host.endswith(f".{blocked}") for blocked in AGENTMAIL_PUBLIC_URL_REJECT_HOSTS): + return "" + query = [ + (key, value) + for key, value in parse_qsl(parsed.query, keep_blank_values=True) + if key.lower() not in AGENTMAIL_TRACKING_QUERY_KEYS + and not any(key.lower().startswith(prefix) for prefix in AGENTMAIL_TRACKING_QUERY_PREFIXES) + ] + return urlunparse( + ( + parsed.scheme, + parsed.netloc, + parsed.path, + parsed.params, + urlencode(query, doseq=True), + "", + ) + ) + + +def agentmail_explicit_public_url(message: dict[str, Any]) -> str: + """Use URL-like fields from list/API metadata when providers expose them.""" + for key in ("public_url", "web_url", "permalink", "archive_url", "url"): + cleaned = clean_agentmail_public_url(message.get(key)) + if cleaned: + return cleaned + links = message.get("links") + candidates: list[Any] = [] + if isinstance(links, dict): + candidates.extend(links.values()) + elif isinstance(links, list): + candidates.extend(links) + for link in candidates: + if isinstance(link, dict): + cleaned = clean_agentmail_public_url(link.get("url") or link.get("href")) + else: + cleaned = clean_agentmail_public_url(link) + if cleaned: + return cleaned + return "" + + +def score_agentmail_public_link(text: str, url: str) -> int: + cleaned = clean_agentmail_public_url(url) + if not cleaned: + return -100 + label = re.sub(r"\s+", " ", str(text or "")).strip() + if AGENTMAIL_PUBLIC_LINK_REJECT_RE.search(label) or AGENTMAIL_PUBLIC_LINK_REJECT_RE.search(cleaned): + return -100 + host = urlparse(cleaned).netloc.lower() + score = 0 + if AGENTMAIL_PUBLIC_LINK_TEXT_RE.search(label): + score += 100 + if "link.mail.beehiiv.com" in host or "substack.com" in host: + score += 15 + if "youtube.com" in host or "youtu.be" in host or "linkedin.com" in host: + score -= 20 + if label and label.lower().strip() in {"read more", "read the full issue", "continue reading"}: + score += 40 + return score + + +def extract_agentmail_public_url_from_body(body: str) -> str: + """Extract a public newsletter issue URL from a message body without storing the body.""" + html = str(body or "") + if not html: + return "" + soup = BeautifulSoup(html, "html.parser") + candidates: list[tuple[int, str]] = [] + for anchor in soup.find_all("a"): + href = anchor.get("href") + if not href: + continue + text = anchor.get_text(" ", strip=True) + cleaned = clean_agentmail_public_url(href) + score = score_agentmail_public_link(text, cleaned) + if score > 0: + candidates.append((score, cleaned)) + if not candidates: + for raw_url in re.findall(r"https?://[^\s\"'<>]+", html): + cleaned = clean_agentmail_public_url(raw_url) + score = score_agentmail_public_link("", cleaned) + if score > 0: + candidates.append((score, cleaned)) + if not candidates: + return "" + candidates.sort(key=lambda item: item[0], reverse=True) + return candidates[0][1] + + +def read_agentmail_public_url_via_cli(message_id: str, cli_path: str = AGENTMAIL_CLI_DEFAULT) -> str: + """Read one message only to extract a public newsletter URL; body is never returned or stored.""" + if not message_id: + return "" + command = [cli_path or AGENTMAIL_CLI_DEFAULT, "message", "+read", "--id", message_id] + try: + completed = subprocess.run(command, check=False, capture_output=True, text=True, timeout=45) + except (OSError, subprocess.TimeoutExpired): + return "" + if completed.returncode != 0: + return "" + output = "\n".join(part for part in (completed.stdout, completed.stderr) if part) + try: + payload = extract_json_object_from_cli_output(output) + except Exception: + return "" + if payload.get("ok") is False: + return "" + data = payload.get("data") if isinstance(payload, dict) else {} + if not isinstance(data, dict): + data = {} + explicit = agentmail_explicit_public_url(data) + if explicit: + return explicit + return extract_agentmail_public_url_from_body(str(data.get("body") or "")) + + +def enrich_agentmail_messages_with_public_urls( + messages: list[dict[str, Any]], + *, + cli_path: str = AGENTMAIL_CLI_DEFAULT, + resolve_public_urls: bool = False, +) -> list[dict[str, Any]]: + enriched: list[dict[str, Any]] = [] + for message in messages: + copy = dict(message) + public_url = agentmail_explicit_public_url(copy) + if not public_url and resolve_public_urls: + public_url = read_agentmail_public_url_via_cli(agentmail_message_id(copy), cli_path=cli_path) + if public_url: + copy["public_url"] = public_url + enriched.append(copy) + return enriched + + +def safe_agentmail_item(message: dict[str, Any]) -> dict[str, Any]: + """Convert an AgentMail MessageItem into a metadata-only public digest item.""" + message_id = agentmail_message_id(message) + stable_id = hashlib.sha1(message_id.encode("utf-8")).hexdigest()[:12] if message_id else "unknown" + domain = agentmail_sender_domain(message) + attachments = message.get("attachments") or [] + if not isinstance(attachments, list): + attachments = [] + item = { + "id": f"agentmail:{stable_id}", + "source_type": "email_newsletter", + "source": f"AgentMail · {domain}" if domain else "AgentMail", + "sender_domain": domain, + "subject": compact_public_snippet(str(message.get("subject") or ""), max_chars=180), + "preview": compact_public_snippet(agentmail_message_preview(message), max_chars=240), + "received_at": agentmail_message_timestamp(message), + "has_attachments": bool(attachments), + "attachment_count": len(attachments), + } + public_url = clean_agentmail_public_url(message.get("public_url")) + if public_url: + item["public_url"] = public_url + return item + + +def build_agentmail_digest_payload( + messages: list[dict[str, Any]], + generated_at: str, + window_hours: int, + allowed_sender_domains: list[str] | None = None, +) -> dict[str, Any]: + """Build a privacy-preserving digest from AgentMail list-message results.""" + filtered_messages = filter_agentmail_messages_by_domain(messages, allowed_sender_domains or []) + items = [safe_agentmail_item(msg) for msg in filtered_messages] + return sanitize_public_payload( + { + "generated_at": generated_at, + "source": "agentmail", + "enabled": True, + "window_hours": window_hours, + "privacy": "metadata_only_no_body", + "allowed_sender_domains": allowed_sender_domains or [], + "total_messages": len(items), + "items": items, + } + ) + + +def fetch_agentmail_digest( + session: requests.Session, + api_key: str, + inbox_id: str, + generated_at: str, + after: str, + limit: int = AGENTMAIL_DEFAULT_LIMIT, + base_url: str = AGENTMAIL_API_BASE_DEFAULT, + window_hours: int = 24, + allowed_sender_domains: list[str] | None = None, +) -> dict[str, Any]: + """Fetch AgentMail MessageItem metadata; deliberately does not request bodies or raw .eml.""" + base = (base_url or AGENTMAIL_API_BASE_DEFAULT).rstrip("/") + url = f"{base}/v0/inboxes/{inbox_id}/messages" + response = session.get( + url, + headers={"Authorization": f"Bearer {api_key}"}, + params={ + "limit": max(1, min(int(limit or AGENTMAIL_DEFAULT_LIMIT), 100)), + "after": after, + "ascending": "false", + "include_spam": "false", + "include_trash": "false", + "include_blocked": "false", + }, + timeout=30, + ) + response.raise_for_status() + payload = response.json() + messages = payload.get("messages") if isinstance(payload, dict) else [] + if not isinstance(messages, list): + messages = [] + return build_agentmail_digest_payload( + messages, + generated_at=generated_at, + window_hours=window_hours, + allowed_sender_domains=allowed_sender_domains, + ) + + +def extract_json_object_from_cli_output(output: str) -> dict[str, Any]: + """Parse a JSON envelope from CLI output that may include tip lines.""" + text = str(output or "") + start = text.find("{") + end = text.rfind("}") + if start == -1 or end == -1 or end < start: + raise ValueError("No JSON object found in agently-cli output") + parsed = json.loads(text[start : end + 1]) + if not isinstance(parsed, dict): + raise ValueError("agently-cli output is not a JSON object") + return parsed + + +def extract_agently_cli_messages(payload: dict[str, Any]) -> list[dict[str, Any]]: + data = payload.get("data") if isinstance(payload, dict) else {} + if isinstance(data, dict): + inner = data.get("data") + if isinstance(inner, list): + return [msg for msg in inner if isinstance(msg, dict)] + messages = data.get("messages") + if isinstance(messages, list): + return [msg for msg in messages if isinstance(msg, dict)] + messages = payload.get("messages") if isinstance(payload, dict) else [] + if isinstance(messages, list): + return [msg for msg in messages if isinstance(msg, dict)] + return [] + + +def fetch_agentmail_digest_via_cli( + *, + generated_at: str, + after: str, + limit: int = AGENTMAIL_DEFAULT_LIMIT, + cli_path: str = AGENTMAIL_CLI_DEFAULT, + window_hours: int = 24, + allowed_sender_domains: list[str] | None = None, + resolve_public_urls: bool = False, +) -> dict[str, Any]: + """Fetch metadata; optionally read allowed messages in memory to extract an archive URL.""" + command = [ + cli_path or AGENTMAIL_CLI_DEFAULT, + "message", + "+list", + "--dir", + "inbox", + "--limit", + str(max(1, min(int(limit or AGENTMAIL_DEFAULT_LIMIT), 100))), + "--after", + after, + ] + completed = subprocess.run( + command, + check=False, + capture_output=True, + text=True, + timeout=45, + ) + output = "\n".join(part for part in (completed.stdout, completed.stderr) if part) + if completed.returncode != 0: + raise RuntimeError(f"agently-cli exited with {completed.returncode}") + payload = extract_json_object_from_cli_output(output) + if payload.get("ok") is False: + raise RuntimeError("agently-cli returned ok=false") + messages = extract_agently_cli_messages(payload) + messages = filter_agentmail_messages_by_domain(messages, allowed_sender_domains or []) + messages = enrich_agentmail_messages_with_public_urls( + messages, + cli_path=cli_path, + resolve_public_urls=resolve_public_urls, + ) + return build_agentmail_digest_payload( + messages, + generated_at=generated_at, + window_hours=window_hours, + allowed_sender_domains=allowed_sender_domains, + ) + + +def agentmail_digest_items_to_raw_items(payload: dict[str, Any]) -> list[RawItem]: + items = payload.get("items") if isinstance(payload, dict) else [] + out: list[RawItem] = [] + if not isinstance(items, list): + return out + for item in items: + if not isinstance(item, dict): + continue + subject = compact_public_snippet(str(item.get("subject") or ""), max_chars=180) + preview = compact_public_snippet(str(item.get("preview") or ""), max_chars=260) + if not subject: + continue + public_url = clean_agentmail_public_url(item.get("public_url")) + if not public_url: + continue + received_at = parse_date_any(item.get("received_at"), utc_now()) + domain = str(item.get("sender_domain") or "").strip() + out.append( + RawItem( + site_id="agentmail", + site_name="AgentMail", + source=f"AgentMail · {domain}" if domain else "AgentMail", + title=subject, + url=public_url, + published_at=received_at, + meta={ + "summary": preview, + "email_source_type": "newsletter_metadata", + }, + ) + ) + return out + + +def env_flag(name: str) -> bool: + return str(os.environ.get(name) or "").strip().lower() in {"1", "true", "yes", "on"} + + +def env_flag_default(name: str, default: bool) -> bool: + """Three-state toggle: unset/blank -> default; explicit truthy/falsey wins. + + Used for the *_ENABLED switches so API-key presence is the primary driver + (key in env -> source runs) while ENABLED stays available as an explicit + kill switch: set it to 0/false/no/off to force a paid source off even when a + key is present.""" + raw = str(os.environ.get(name) or "").strip().lower() + if not raw: + return default + return raw in {"1", "true", "yes", "on"} + + +def env_int(name: str, default: int) -> int: + try: + return int(str(os.environ.get(name) or default).strip() or default) + except ValueError: + return default + + +def env_float(name: str, default: float) -> float: + try: + return float(str(os.environ.get(name) or default).strip() or default) + except ValueError: + return default + + +def load_paid_source_state(path: Path) -> dict[str, Any]: + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + payload = {} + if not isinstance(payload, dict): + payload = {} + sources = payload.get("sources") + if not isinstance(sources, dict): + sources = {} + return {"schema_version": 1, "sources": sources} + + +def paid_source_interval_hours(prefix: str) -> int: + default = PAID_SOURCE_DEFAULT_INTERVAL_HOURS_BY_PREFIX.get(prefix, PAID_SOURCE_DEFAULT_INTERVAL_HOURS) + interval = env_int(f"{prefix}_RUN_INTERVAL_HOURS", default) + return max(1, min(interval, PAID_SOURCE_MAX_INTERVAL_HOURS)) + + +def paid_source_state_entry(state: dict[str, Any] | None, source_key: str) -> dict[str, Any]: + if not isinstance(state, dict): + return {} + sources = state.get("sources") + if not isinstance(sources, dict): + return {} + entry = sources.get(source_key) + return entry if isinstance(entry, dict) else {} + + +def paid_source_run_gate( + prefix: str, + source_key: str, + now: datetime, + state: dict[str, Any] | None, +) -> tuple[bool, str | None]: + if env_flag(f"{prefix}_FORCE_RUN"): + return True, None + + current = now.astimezone(UTC) + interval_hours = paid_source_interval_hours(prefix) + entry = paid_source_state_entry(state, source_key) + last_run = parse_iso(str(entry.get("last_run_at") or "")) + if last_run: + due_at = last_run.astimezone(UTC) + timedelta(hours=interval_hours) + if current < due_at: + return False, f"before_{source_key}_run_interval" + return True, None + + run_hour = max(0, min(env_int(f"{prefix}_RUN_UTC_HOUR", 0), 23)) + minute_max = max(0, min(env_int(f"{prefix}_RUN_UTC_MINUTE_MAX", 10), 59)) + if current.hour == run_hour and current.minute <= minute_max: + return True, None + return False, f"outside_{source_key}_initial_window" + + +def update_paid_source_state( + state: dict[str, Any], + source_key: str, + status: dict[str, Any], + now: datetime, +) -> None: + if not status.get("attempted"): + return + sources = state.setdefault("sources", {}) + if not isinstance(sources, dict): + sources = {} + state["sources"] = sources + entry = sources.setdefault(source_key, {}) + if not isinstance(entry, dict): + entry = {} + sources[source_key] = entry + entry["last_run_at"] = iso(now) + entry["last_ok"] = bool(status.get("ok")) + entry["last_item_count"] = int(status.get("item_count") or 0) + if status.get("ok"): + entry["last_success_at"] = iso(now) + entry.pop("last_error", None) + elif status.get("error"): + entry["last_error"] = status.get("error") + + +def sync_paid_source_status_timestamps( + status: dict[str, Any], + state: dict[str, Any], + source_key: str, +) -> None: + """Keep the published status aligned with the state used by the run gate.""" + entry = paid_source_state_entry(state, source_key) + status["last_run_at"] = entry.get("last_run_at") + status["last_success_at"] = entry.get("last_success_at") + + +def maybe_fetch_agentmail_digest( + session: requests.Session, + generated_at: str, + after: str, + window_hours: int, +) -> tuple[dict[str, Any] | None, dict[str, Any]]: + """Fetch AgentMail only when explicitly enabled and fully configured.""" + status: dict[str, Any] = { + "enabled": env_flag("EMAIL_DIGEST_ENABLED"), + "ok": None, + "item_count": 0, + "privacy": "metadata_only_no_body", + "published_by_default": False, + "provider": None, + "include_in_radar": env_flag("EMAIL_DIGEST_INCLUDE_IN_RADAR"), + } + if not status["enabled"]: + return None, status + + provider = str(os.environ.get("AGENTMAIL_PROVIDER") or "").strip().lower() + agentmail_api_key = str(os.environ.get("AGENTMAIL_API_KEY") or "").strip() + agentmail_inbox_id = str(os.environ.get("AGENTMAIL_INBOX_ID") or "").strip() + if not provider: + provider = "api" if (agentmail_api_key and agentmail_inbox_id) else AGENTMAIL_PROVIDER_DEFAULT + status["provider"] = provider + + agentmail_base_url = str(os.environ.get("AGENTMAIL_API_BASE_URL") or AGENTMAIL_API_BASE_DEFAULT).strip() + agentmail_limit = env_int("AGENTMAIL_LIMIT", AGENTMAIL_DEFAULT_LIMIT) + agentmail_cli = str(os.environ.get("AGENTMAIL_CLI") or AGENTMAIL_CLI_DEFAULT).strip() + allowed_sender_domains = parse_domain_filter(str(os.environ.get("AGENTMAIL_ALLOWED_SENDER_DOMAINS") or "")) + resolve_public_urls = env_flag("AGENTMAIL_RESOLVE_PUBLIC_URLS") + status["allowed_sender_domains"] = allowed_sender_domains + status["resolve_public_urls"] = resolve_public_urls + + if provider == "api" and not (agentmail_api_key and agentmail_inbox_id): + status["ok"] = False + status["error"] = "missing_agentmail_credentials" + return None, status + if provider not in {"api", "agently_cli"}: + status["ok"] = False + status["error"] = "unsupported_agentmail_provider" + return None, status + + try: + if provider == "api": + payload = fetch_agentmail_digest( + session, + api_key=agentmail_api_key, + inbox_id=agentmail_inbox_id, + generated_at=generated_at, + after=after, + limit=agentmail_limit, + base_url=agentmail_base_url, + window_hours=window_hours, + allowed_sender_domains=allowed_sender_domains, + ) + else: + payload = fetch_agentmail_digest_via_cli( + generated_at=generated_at, + after=after, + limit=agentmail_limit, + cli_path=agentmail_cli, + window_hours=window_hours, + allowed_sender_domains=allowed_sender_domains, + resolve_public_urls=resolve_public_urls, + ) + status["ok"] = True + status["item_count"] = int(payload.get("total_messages") or 0) + return payload, status + except Exception as exc: + status["ok"] = False + status["error"] = type(exc).__name__ + return None, status + + +def x_api_should_run_now(now: datetime) -> bool: + """Gate paid X API reads so a 30-minute cron does not spend every run.""" + if env_flag("X_API_FORCE_RUN"): + return True + run_hour = max(0, min(env_int("X_API_RUN_UTC_HOUR", 0), 23)) + minute_max = max(0, min(env_int("X_API_RUN_UTC_MINUTE_MAX", 10), 59)) + return now.astimezone(UTC).hour == run_hour and now.astimezone(UTC).minute <= minute_max + + +def x_api_status_base(now: datetime) -> dict[str, Any]: + daily_post_limit = max(0, env_int("X_API_DAILY_POST_LIMIT", X_API_DEFAULT_MAX_RESULTS)) + max_results = max(10, min(env_int("X_API_MAX_RESULTS", X_API_DEFAULT_MAX_RESULTS), 100)) + effective_cap = min(max_results, daily_post_limit) if daily_post_limit else 0 + enable_toggle = env_flag_default("X_API_ENABLED", True) + token_present = bool( + str(os.environ.get("X_BEARER_TOKEN") or os.environ.get("X_API_BEARER_TOKEN") or "").strip() + ) + return { + "enabled": enable_toggle and token_present, + "enable_toggle": enable_toggle, + "api_key_present": token_present, + "ok": None, + "item_count": 0, + "privacy": "public_posts_metadata_only", + "published_by_default": False, + "official_free_read_quota": False, + "unit_cost_usd_per_post_read": X_API_POST_READ_COST_USD, + "daily_post_limit": daily_post_limit, + "max_results_per_run": max_results, + "effective_result_cap": effective_cap, + "estimated_max_cost_usd_per_run": round(effective_cap * X_API_POST_READ_COST_USD, 4), + "run_utc_hour": max(0, min(env_int("X_API_RUN_UTC_HOUR", 0), 23)), + "generated_date_utc": now.astimezone(UTC).date().isoformat(), + } + + +def fetch_x_api_recent_search( + session: requests.Session, + bearer_token: str, + query: str, + now: datetime, + max_results: int, + base_url: str = X_API_BASE_DEFAULT, +) -> list[RawItem]: + """Fetch public recent-search Posts from X API v2; no writes and no DMs.""" + query = re.sub(r"\s+", " ", (query or X_API_DEFAULT_QUERY).strip()) + if len(query) > X_API_MAX_QUERY_CHARS: + raise ValueError("x_query_too_long") + capped_max_results = max(10, min(int(max_results or X_API_DEFAULT_MAX_RESULTS), 100)) + url = f"{(base_url or X_API_BASE_DEFAULT).rstrip('/')}/2/tweets/search/recent" + response = session.get( + url, + headers={"Authorization": f"Bearer {bearer_token}"}, + params={ + "query": query, + "max_results": capped_max_results, + "tweet.fields": "created_at,author_id,public_metrics,lang", + "expansions": "author_id", + "user.fields": "username,name,verified", + }, + timeout=30, + ) + response.raise_for_status() + payload = response.json() + users = { + str(user.get("id")): user + for user in (payload.get("includes", {}) or {}).get("users", []) + if isinstance(user, dict) and user.get("id") + } + out: list[RawItem] = [] + for post in payload.get("data") or []: + if not isinstance(post, dict): + continue + post_id = str(post.get("id") or "").strip() + text = compact_public_snippet(str(post.get("text") or ""), max_chars=220) + if not (post_id and text): + continue + user = users.get(str(post.get("author_id") or ""), {}) + username = str(user.get("username") or "i/web").strip() or "i/web" + published = parse_iso(str(post.get("created_at") or "")) or now + out.append( + RawItem( + site_id="xapi", + site_name="X API", + source=f"@{username}", + title=text, + url=f"https://x.com/{username}/status/{post_id}", + published_at=published, + meta={ + "post_id": post_id, + "lang": post.get("lang"), + "public_metrics": post.get("public_metrics") or {}, + }, + ) + ) + return out + + +def maybe_fetch_x_api_updates( + session: requests.Session, + now: datetime, +) -> tuple[list[RawItem], dict[str, Any]]: + """Fetch X when a bearer token is present and ENABLED is not turned off, then + only if scheduled and capped. The token is the primary switch; ENABLED is an + optional kill switch (set it to 0 to force off).""" + status = x_api_status_base(now) + if not status["enable_toggle"]: + status["disabled_reason"] = "disabled_by_toggle" + return [], status + if not status["api_key_present"]: + status["disabled_reason"] = "no_bearer_token" + return [], status + + if status["effective_result_cap"] < 10: + status["ok"] = False + status["error"] = "x_daily_post_limit_below_api_minimum" + return [], status + + if not x_api_should_run_now(now): + status["skipped"] = True + status["skip_reason"] = "outside_x_api_daily_window" + return [], status + + bearer_token = str(os.environ.get("X_BEARER_TOKEN") or os.environ.get("X_API_BEARER_TOKEN") or "").strip() + + query = str(os.environ.get("X_API_QUERY") or X_API_DEFAULT_QUERY).strip() + base_url = str(os.environ.get("X_API_BASE_URL") or X_API_BASE_DEFAULT).strip() + try: + items = fetch_x_api_recent_search( + session, + bearer_token=bearer_token, + query=query, + now=now, + max_results=int(status["effective_result_cap"]), + base_url=base_url, + ) + status["ok"] = True + status["item_count"] = len(items) + status["estimated_cost_usd"] = round(len(items) * X_API_POST_READ_COST_USD, 4) + return items, status + except Exception as exc: + status["ok"] = False + status["error"] = type(exc).__name__ + return [], status + + +def socialdata_should_run_now(now: datetime, paid_source_state: dict[str, Any] | None = None) -> tuple[bool, str | None]: + """Gate paid SocialData reads so a 30-minute cron does not spend every run.""" + return paid_source_run_gate("SOCIALDATA", "socialdata", now, paid_source_state) + + +def socialdata_status_base(now: datetime, paid_source_state: dict[str, Any] | None = None) -> dict[str, Any]: + daily_tweet_limit = max(0, env_int("SOCIALDATA_DAILY_TWEET_LIMIT", SOCIALDATA_DEFAULT_MAX_RESULTS)) + max_results = max(1, min(env_int("SOCIALDATA_MAX_RESULTS", SOCIALDATA_DEFAULT_MAX_RESULTS), 100)) + effective_cap = min(max_results, daily_tweet_limit) if daily_tweet_limit else 0 + state_entry = paid_source_state_entry(paid_source_state, "socialdata") + enable_toggle = env_flag_default("SOCIALDATA_ENABLED", True) + api_key_present = bool(str(os.environ.get("SOCIALDATA_API_KEY") or "").strip()) + # The curated KOL list is a SECOND paid path on top of the keyword search, + # so the per-run cost ceiling must include it (search cap + list cap). + list_id = str(os.environ.get("SOCIALDATA_LIST_ID") or SOCIALDATA_LIST_ID_DEFAULT).strip() + list_enabled = bool(list_id) and env_flag_default("SOCIALDATA_LIST_ENABLED", True) + list_cap = max(0, min(env_int("SOCIALDATA_LIST_MAX_RESULTS", SOCIALDATA_LIST_DEFAULT_MAX_RESULTS), 200)) if list_enabled else 0 + combined_cap = effective_cap + list_cap + return { + "enabled": enable_toggle and api_key_present, + "enable_toggle": enable_toggle, + "api_key_present": api_key_present, + "ok": None, + "item_count": 0, + "privacy": "public_posts_metadata_only", + "published_by_default": False, + "unit_cost_usd_per_tweet_read": SOCIALDATA_TWEET_READ_COST_USD, + "daily_tweet_limit": daily_tweet_limit, + "max_results_per_run": max_results, + "effective_result_cap": effective_cap, + "search_result_cap": effective_cap, + "list_result_cap": list_cap, + "combined_result_cap": combined_cap, + "recency_days": SOCIALDATA_RECENCY_DAYS, + "estimated_max_cost_usd_per_run": round(combined_cap * SOCIALDATA_TWEET_READ_COST_USD, 4), + "run_interval_hours": paid_source_interval_hours("SOCIALDATA"), + "run_utc_hour": max(0, min(env_int("SOCIALDATA_RUN_UTC_HOUR", 0), 23)), + "run_utc_minute_max": max(0, min(env_int("SOCIALDATA_RUN_UTC_MINUTE_MAX", 10), 59)), + "last_run_at": state_entry.get("last_run_at"), + "last_success_at": state_entry.get("last_success_at"), + "generated_date_utc": now.astimezone(UTC).date().isoformat(), + } + + +def fetch_socialdata_search( + session: requests.Session, + api_key: str, + query: str, + now: datetime, + max_results: int, + search_type: str = "Top", + base_url: str = SOCIALDATA_API_BASE_DEFAULT, +) -> tuple[list[RawItem], dict[str, Any]]: + """Fetch public X search results through SocialData; no writes and no private data.""" + query = re.sub(r"\s+", " ", (query or SOCIALDATA_DEFAULT_QUERY).strip()) + if len(query) > SOCIALDATA_MAX_QUERY_CHARS: + raise ValueError("socialdata_query_too_long") + capped_max_results = max(1, min(int(max_results or SOCIALDATA_DEFAULT_MAX_RESULTS), 100)) + # 默认 Top:Latest 返回的是 API 调用瞬间刚发出的推文,一批的原帖时间挤在同一分钟, + # 时间轴上表现为同分钟刷屏;Top 按热度返回时间窗内的推文,原帖时间自然散布。 + effective_search_type = search_type if search_type in {"Latest", "Top"} else "Top" + out: list[RawItem] = [] + raw_tweet_count = 0 + response_top_level_keys: list[str] = [] + page_count = 0 + cursor = "" + seen_cursors: set[str] = set() + seen_tweet_ids: set[str] = set() + pagination_error: str | None = None + while len(out) < capped_max_results: + params = { + "query": query, + "type": effective_search_type, + } + if cursor: + params["cursor"] = cursor + try: + response = session.get( + f"{(base_url or SOCIALDATA_API_BASE_DEFAULT).rstrip('/')}/twitter/search", + headers={ + "Authorization": f"Bearer {api_key}", + "Accept": "application/json", + }, + params=params, + timeout=30, + ) + response.raise_for_status() + except Exception as exc: + if page_count == 0: + raise + pagination_error = type(exc).__name__ + break + + payload = response.json() + page_count += 1 + if isinstance(payload, dict) and not response_top_level_keys: + response_top_level_keys = sorted(payload.keys())[:12] + tweets = payload.get("tweets") if isinstance(payload, dict) else [] + raw_tweet_count += len(tweets) if isinstance(tweets, list) else 0 + for tweet in tweets or []: + if len(out) >= capped_max_results: + break + if not isinstance(tweet, dict): + continue + tweet_id = str(tweet.get("id_str") or tweet.get("id") or "").strip() + text = compact_public_snippet(str(tweet.get("full_text") or tweet.get("text") or ""), max_chars=220) + if not (tweet_id and text) or tweet_id in seen_tweet_ids: + continue + seen_tweet_ids.add(tweet_id) + user = tweet.get("user") if isinstance(tweet.get("user"), dict) else {} + username = str(user.get("screen_name") or "i/web").strip().lstrip("@") or "i/web" + published = parse_iso(str(tweet.get("tweet_created_at") or tweet.get("created_at") or "")) or now + out.append( + RawItem( + site_id="socialdata_x", + site_name="SocialData X", + source=f"@{username}", + title=text, + url=f"https://x.com/{username}/status/{tweet_id}", + published_at=published, + meta={ + "post_id": tweet_id, + "lang": tweet.get("lang"), + "public_metrics": { + "reply_count": tweet.get("reply_count"), + "retweet_count": tweet.get("retweet_count"), + "quote_count": tweet.get("quote_count"), + "favorite_count": tweet.get("favorite_count"), + "bookmark_count": tweet.get("bookmark_count"), + "views_count": tweet.get("views_count"), + }, + }, + ) + ) + + next_cursor = str(payload.get("next_cursor") or "").strip() if isinstance(payload, dict) else "" + if not next_cursor or next_cursor in seen_cursors: + break + seen_cursors.add(next_cursor) + cursor = next_cursor + diagnostics = { + "endpoint": "/twitter/search", + "search_type": effective_search_type, + "query_chars": len(query), + "response_top_level_keys": response_top_level_keys, + "raw_tweet_count": raw_tweet_count, + "mapped_tweet_count": len(out), + "page_count": page_count, + "cursor_request_count": max(0, page_count - 1), + "reached_result_cap": len(out) >= capped_max_results, + } + if pagination_error: + diagnostics["pagination_error"] = pagination_error + if raw_tweet_count == 0: + diagnostics["empty_reason"] = "no_tweets_returned_by_socialdata" + elif len(out) == 0: + diagnostics["empty_reason"] = "tweets_returned_but_none_mapped" + return out, diagnostics + + +def fetch_socialdata_list_tweets( + session: requests.Session, + api_key: str, + list_id: str, + now: datetime, + max_results: int, + exclude_handles: set[str] | None = None, + base_url: str = SOCIALDATA_API_BASE_DEFAULT, + max_pages: int = SOCIALDATA_LIST_MAX_PAGES, +) -> tuple[list[RawItem], dict[str, Any]]: + """Pull a curated X list timeline through SocialData, keeping only members' + own AI posts. Retweets, replies, the excluded owner, and egg-avatar accounts + are dropped so the list stays a high-signal, bot-free source. Pagination is + hard-capped at ``max_pages`` so a heavily-filtered list can't bill without + bound.""" + list_id = str(list_id or "").strip() + if not list_id: + raise ValueError("socialdata_list_id_empty") + capped_max_results = max(1, min(int(max_results or SOCIALDATA_LIST_DEFAULT_MAX_RESULTS), 200)) + exclude = {h.strip().lstrip("@").lower() for h in (exclude_handles or set()) if h.strip()} + out: list[RawItem] = [] + raw_tweet_count = 0 + skipped = {"retweet_or_reply": 0, "excluded_author": 0, "bot_like": 0, "empty": 0, "duplicate": 0} + page_count = 0 + cursor = "" + seen_cursors: set[str] = set() + seen_tweet_ids: set[str] = set() + pagination_error: str | None = None + page_cap = max(1, int(max_pages or 1)) + hit_page_cap = False + while len(out) < capped_max_results and page_count < page_cap: + params: dict[str, str] = {} + if cursor: + params["cursor"] = cursor + try: + response = session.get( + f"{(base_url or SOCIALDATA_API_BASE_DEFAULT).rstrip('/')}/twitter/list/{list_id}/tweets", + headers={ + "Authorization": f"Bearer {api_key}", + "Accept": "application/json", + }, + params=params, + timeout=30, + ) + response.raise_for_status() + except Exception as exc: + if page_count == 0: + raise + pagination_error = type(exc).__name__ + break + + payload = response.json() + page_count += 1 + tweets = payload.get("tweets") if isinstance(payload, dict) else [] + raw_tweet_count += len(tweets) if isinstance(tweets, list) else 0 + for tweet in tweets or []: + if len(out) >= capped_max_results: + break + if not isinstance(tweet, dict): + continue + tweet_type = str(tweet.get("type") or "tweet").lower() + if tweet_type not in SOCIALDATA_LIST_ALLOWED_TYPES: + skipped["retweet_or_reply"] += 1 + continue + user = tweet.get("user") if isinstance(tweet.get("user"), dict) else {} + username = str(user.get("screen_name") or "").strip().lstrip("@") + if username.lower() in exclude: + skipped["excluded_author"] += 1 + continue + if user.get("default_profile_image"): + skipped["bot_like"] += 1 + continue + tweet_id = str(tweet.get("id_str") or tweet.get("id") or "").strip() + text = compact_public_snippet(str(tweet.get("full_text") or tweet.get("text") or ""), max_chars=220) + if not (tweet_id and text and username): + skipped["empty"] += 1 + continue + if tweet_id in seen_tweet_ids: + skipped["duplicate"] += 1 + continue + seen_tweet_ids.add(tweet_id) + published = parse_iso(str(tweet.get("tweet_created_at") or tweet.get("created_at") or "")) or now + out.append( + RawItem( + site_id="socialdata_x", + site_name="SocialData X", + source=f"@{username}", + title=text, + url=f"https://x.com/{username}/status/{tweet_id}", + published_at=published, + meta={ + "post_id": tweet_id, + "via": "list", + "list_id": list_id, + "tweet_type": tweet_type, + "lang": tweet.get("lang"), + "public_metrics": { + "reply_count": tweet.get("reply_count"), + "retweet_count": tweet.get("retweet_count"), + "quote_count": tweet.get("quote_count"), + "favorite_count": tweet.get("favorite_count"), + "bookmark_count": tweet.get("bookmark_count"), + "views_count": tweet.get("views_count"), + }, + }, + ) + ) + + next_cursor = str(payload.get("next_cursor") or "").strip() if isinstance(payload, dict) else "" + if not next_cursor or next_cursor in seen_cursors: + break + seen_cursors.add(next_cursor) + cursor = next_cursor + hit_page_cap = page_count >= page_cap and len(out) < capped_max_results + diagnostics = { + "endpoint": f"/twitter/list/{list_id}/tweets", + "list_id": list_id, + "raw_tweet_count": raw_tweet_count, + "mapped_tweet_count": len(out), + "page_count": page_count, + "max_pages": page_cap, + "hit_page_cap": hit_page_cap, + "skipped": skipped, + "excluded_handles": sorted(exclude), + "reached_result_cap": len(out) >= capped_max_results, + } + if pagination_error: + diagnostics["pagination_error"] = pagination_error + return out, diagnostics + + +def maybe_fetch_socialdata_updates( + session: requests.Session, + now: datetime, + paid_source_state: dict[str, Any] | None = None, +) -> tuple[list[RawItem], dict[str, Any]]: + """Fetch SocialData when an API key is present and ENABLED is not turned off, + then only if scheduled and capped. The key is the primary switch; ENABLED is + an optional kill switch (set it to 0 to force off).""" + status = socialdata_status_base(now, paid_source_state) + if not status["enable_toggle"]: + status["disabled_reason"] = "disabled_by_toggle" + return [], status + if not status["api_key_present"]: + status["disabled_reason"] = "no_api_key" + return [], status + + if status["effective_result_cap"] < 1: + status["ok"] = False + status["error"] = "socialdata_daily_tweet_limit_below_minimum" + return [], status + + should_run, skip_reason = socialdata_should_run_now(now, paid_source_state) + if not should_run: + status["skipped"] = True + status["skip_reason"] = skip_reason or "outside_socialdata_run_window" + return [], status + + api_key = str(os.environ.get("SOCIALDATA_API_KEY") or "").strip() + + query = str(os.environ.get("SOCIALDATA_QUERY") or SOCIALDATA_DEFAULT_QUERY).strip() + base_url = str(os.environ.get("SOCIALDATA_API_BASE_URL") or SOCIALDATA_API_BASE_DEFAULT).strip() + search_type = str(os.environ.get("SOCIALDATA_SEARCH_TYPE") or "Top").strip() or "Top" + list_id = str(os.environ.get("SOCIALDATA_LIST_ID") or SOCIALDATA_LIST_ID_DEFAULT).strip() + list_enabled = bool(list_id) and str(os.environ.get("SOCIALDATA_LIST_ENABLED", "1")).strip().lower() in { + "1", + "true", + "yes", + "on", + } + list_max_results = max(0, min(env_int("SOCIALDATA_LIST_MAX_RESULTS", SOCIALDATA_LIST_DEFAULT_MAX_RESULTS), 200)) + list_exclude = { + handle.strip().lstrip("@").lower() + for handle in str(os.environ.get("SOCIALDATA_LIST_EXCLUDE") or SOCIALDATA_LIST_DEFAULT_EXCLUDE).split(",") + if handle.strip() + } + status["attempted"] = True + + items: list[RawItem] = [] + seen_urls: set[str] = set() + errors: list[str] = [] + recency_cutoff = now - timedelta(days=SOCIALDATA_RECENCY_DAYS) if SOCIALDATA_RECENCY_DAYS else None + skipped_stale = 0 + + # 1) Broad keyword search: discovers new voices across en/zh. + try: + search_items, diagnostics = fetch_socialdata_search( + session, + api_key=api_key, + query=query, + now=now, + max_results=int(status["effective_result_cap"]), + search_type=search_type, + base_url=base_url, + ) + status["diagnostics"] = diagnostics + for item in search_items: + if recency_cutoff and item.published_at and item.published_at < recency_cutoff: + skipped_stale += 1 + continue + if item.url in seen_urls: + continue + seen_urls.add(item.url) + items.append(item) + except Exception as exc: + errors.append(f"search:{type(exc).__name__}") + + # 2) Curated list timeline: stably tracks known KOLs by identity, bot-filtered. + list_item_count = 0 + if list_enabled and list_max_results >= 1: + try: + list_items, list_diagnostics = fetch_socialdata_list_tweets( + session, + api_key=api_key, + list_id=list_id, + now=now, + max_results=list_max_results, + exclude_handles=list_exclude, + base_url=base_url, + ) + status["list_diagnostics"] = list_diagnostics + for item in list_items: + if recency_cutoff and item.published_at and item.published_at < recency_cutoff: + skipped_stale += 1 + continue + if item.url in seen_urls: + continue + seen_urls.add(item.url) + items.append(item) + list_item_count += 1 + except Exception as exc: + errors.append(f"list:{type(exc).__name__}") + + # SocialData bills per tweet READ (raw), not per kept item; the list discards + # retweets/replies/stale posts, so raw reads exceed mapped items. Cost and the + # ceiling in socialdata_status_base both track raw reads across BOTH paths. + search_raw = int((status.get("diagnostics") or {}).get("raw_tweet_count") or 0) + list_raw = int((status.get("list_diagnostics") or {}).get("raw_tweet_count") or 0) + status["list_enabled"] = list_enabled + status["list_item_count"] = list_item_count + status["search_item_count"] = len(items) - list_item_count + status["item_count"] = len(items) + status["recency_days"] = SOCIALDATA_RECENCY_DAYS + status["skipped_stale_count"] = skipped_stale + status["raw_reads"] = search_raw + list_raw + status["estimated_cost_usd"] = round((search_raw + list_raw) * SOCIALDATA_TWEET_READ_COST_USD, 4) + if errors and not items: + status["ok"] = False + status["error"] = ";".join(errors) + else: + status["ok"] = True + if errors: + status["partial_error"] = ";".join(errors) + return items, status + + +def tikhub_should_run_now(now: datetime, paid_source_state: dict[str, Any] | None = None) -> tuple[bool, str | None]: + """Gate paid TikHub reads so scheduled workflows do not spend every run.""" + return paid_source_run_gate("TIKHUB", "tikhub", now, paid_source_state) + + +def tikhub_status_base(now: datetime, paid_source_state: dict[str, Any] | None = None) -> dict[str, Any]: + daily_limit = max(0, env_int("TIKHUB_DAILY_ITEM_LIMIT", TIKHUB_DEFAULT_MAX_RESULTS)) + max_results = max(1, min(env_int("TIKHUB_MAX_RESULTS", TIKHUB_DEFAULT_MAX_RESULTS), 100)) + effective_cap = min(max_results, daily_limit) if daily_limit else 0 + enable_toggle = env_flag_default("TIKHUB_ENABLED", True) + api_key_present = bool(str(os.environ.get("TIKHUB_API_KEY") or "").strip()) + platforms = [ + part.strip().lower() + for part in str(os.environ.get("TIKHUB_PLATFORMS") or TIKHUB_DEFAULT_PLATFORMS).split(",") + if part.strip() + ] + state_entry = paid_source_state_entry(paid_source_state, "tikhub") + return { + "enabled": enable_toggle and api_key_present, + "enable_toggle": enable_toggle, + "api_key_present": api_key_present, + "enabled_by": "disabled_by_toggle" if not enable_toggle else ("ready" if api_key_present else "no_api_key"), + "ok": None, + "item_count": 0, + "privacy": "public_social_posts_metadata_only", + "published_by_default": False, + "billing": "tikhub_charged_request", + "daily_item_limit": daily_limit, + "max_results_per_run": max_results, + "effective_result_cap": effective_cap, + "platforms": platforms, + "run_interval_hours": paid_source_interval_hours("TIKHUB"), + "run_utc_hour": max(0, min(env_int("TIKHUB_RUN_UTC_HOUR", 0), 23)), + "run_utc_minute_max": max(0, min(env_int("TIKHUB_RUN_UTC_MINUTE_MAX", 10), 59)), + "last_run_at": state_entry.get("last_run_at"), + "last_success_at": state_entry.get("last_success_at"), + "generated_date_utc": now.astimezone(UTC).date().isoformat(), + } + + +def iter_nested_dicts(value: Any) -> list[dict[str, Any]]: + out: list[dict[str, Any]] = [] + if isinstance(value, dict): + out.append(value) + for child in value.values(): + out.extend(iter_nested_dicts(child)) + elif isinstance(value, list): + for child in value: + out.extend(iter_nested_dicts(child)) + return out + + +def tikhub_payload_shape(payload: Any) -> dict[str, Any]: + """Return a sanitized structural summary for debugging API schema drift.""" + dicts = iter_nested_dicts(payload) + data = payload.get("data") if isinstance(payload, dict) else None + data_items = data.get("items") if isinstance(data, dict) else None + data_business = data.get("business_data") if isinstance(data, dict) else None + sample_nodes: list[dict[str, Any]] = [] + for node in dicts: + if len(sample_nodes) >= 3: + break + keys = sorted(str(key) for key in node.keys())[:16] + if {"aweme_info", "note_card", "display_title", "desc", "title", "id", "note_id"} & set(keys): + sample_nodes.append({"keys": keys}) + return { + "dict_count": len(dicts), + "data_type": type(data).__name__ if data is not None else None, + "data_keys": sorted(data.keys())[:16] if isinstance(data, dict) else [], + "data_items_count": len(data_items) if isinstance(data_items, list) else None, + "data_business_count": len(data_business) if isinstance(data_business, list) else None, + "aweme_info_count": sum(1 for node in dicts if isinstance(node.get("aweme_info"), dict)), + "note_card_count": sum(1 for node in dicts if isinstance(node.get("note_card"), dict)), + "sample_nodes": sample_nodes, + } + + +def parse_epoch_any(value: Any, now: datetime) -> datetime | None: + if value is None or value == "": + return None + if isinstance(value, (int, float)): + number = float(value) + else: + text = str(value).strip() + if not text: + return None + if re.fullmatch(r"\d+(\.\d+)?", text): + number = float(text) + else: + return parse_date_any(text, now) + if number > 10_000_000_000: + number = number / 1000 + try: + return datetime.fromtimestamp(number, tz=UTC) + except (OverflowError, OSError, ValueError): + return None + + +def is_tikhub_generic_audio_title(title: str) -> bool: + return bool( + re.fullmatch( + r"@?.{1,80}(?:创作的原声|的原声|original\s+sound)", + (title or "").strip(), + flags=re.IGNORECASE, + ) + ) + + +def first_tikhub_douyin_title(aweme: dict[str, Any]) -> str: + share_info = aweme.get("share_info") if isinstance(aweme.get("share_info"), dict) else {} + candidates = ( + aweme.get("desc"), + aweme.get("title"), + aweme.get("caption"), + share_info.get("share_desc"), + share_info.get("share_title"), + ) + for candidate in candidates: + title = compact_public_snippet(str(candidate or ""), max_chars=220) + if title and not is_tikhub_generic_audio_title(title): + return title + return "" + + +def parse_tikhub_published_at(record: dict[str, Any], now: datetime, fields: tuple[str, ...]) -> datetime | None: + for field in fields: + value = record.get(field) + published = parse_epoch_any(value, now) or parse_date_any(value, now) + if published: + return published + return None + + +def parse_xiaohongshu_note_id_published_at(note_id: str, now: datetime) -> datetime | None: + """Infer Xiaohongshu note creation time from the timestamp prefix in note id.""" + raw = str(note_id or "").strip() + match = re.match(r"^([0-9a-fA-F]{8})", raw) + if not match: + return None + published = parse_unix_timestamp(int(match.group(1), 16)) + if not published: + return None + earliest_supported = datetime(2013, 1, 1, tzinfo=UTC) + latest_supported = now.astimezone(UTC) + if published < earliest_supported or published > latest_supported: + return None + return published + + +def is_credible_xiaohongshu_published_at(published: datetime | None, now: datetime) -> bool: + if not published: + return False + return datetime(2013, 1, 1, tzinfo=UTC) <= published <= now.astimezone(UTC) + + +def creator_metric_count(*values: Any) -> int: + for value in values: + if value is None or value == "": + continue + try: + return max(0, int(float(str(value).replace(",", "").strip()))) + except (TypeError, ValueError): + continue + return 0 + + +def normalize_creator_metrics(platform: str, *records: dict[str, Any]) -> dict[str, int]: + merged: dict[str, Any] = {} + for record in records: + if isinstance(record, dict): + merged.update(record) + if platform == "douyin": + return { + "likes": creator_metric_count(merged.get("digg_count"), merged.get("like_count")), + "comments": creator_metric_count(merged.get("comment_count"), merged.get("comments_count")), + "collects": creator_metric_count(merged.get("collect_count"), merged.get("collected_count")), + "shares": creator_metric_count(merged.get("share_count"), merged.get("shared_count")), + } + return { + "likes": creator_metric_count( + merged.get("liked_count"), + merged.get("likes_count"), + merged.get("like_count"), + merged.get("digg_count"), + ), + "comments": creator_metric_count(merged.get("comments_count"), merged.get("comment_count")), + "collects": creator_metric_count(merged.get("collected_count"), merged.get("collect_count")), + "shares": creator_metric_count(merged.get("shared_count"), merged.get("share_count")), + } + + +def parse_tikhub_douyin_items(payload: dict[str, Any], now: datetime, keyword: str, limit: int) -> list[RawItem]: + out: list[RawItem] = [] + seen_ids: set[str] = set() + for node in iter_nested_dicts(payload): + # TikHub wraps real videos in ``aweme_info``. Walking arbitrary nested + # dictionaries without this guard also reaches ``music`` objects, whose + # generic titles look like "@…创作的原声" and are not video titles. + wrapped_aweme = node.get("aweme_info") if isinstance(node.get("aweme_info"), dict) else None + aweme = wrapped_aweme or node + if not isinstance(aweme, dict): + continue + post_id = str(aweme.get("aweme_id") or aweme.get("awemeId") or "").strip() + title = first_tikhub_douyin_title(aweme) + if not (post_id and title) or post_id in seen_ids: + continue + seen_ids.add(post_id) + author = aweme.get("author") if isinstance(aweme.get("author"), dict) else {} + source = str(author.get("nickname") or author.get("unique_id") or "Douyin Search").strip() or "Douyin Search" + share = first_non_empty( + aweme.get("share_url"), + aweme.get("share_info", {}).get("share_url") if isinstance(aweme.get("share_info"), dict) else "", + f"https://www.douyin.com/video/{post_id}", + ) + published = parse_tikhub_published_at( + aweme, + now, + ( + "create_time", + "create_time_stamp", + "createTime", + "createTimeStamp", + "created_at", + "publish_time", + "publishTime", + "publish_timestamp", + "time", + ), + ) or now + statistics = aweme.get("statistics") if isinstance(aweme.get("statistics"), dict) else {} + out.append( + RawItem( + site_id="tikhub_douyin", + site_name="TikHub Douyin", + source=source, + title=title, + url=str(share), + published_at=published, + meta={ + "platform": "douyin", + "keyword": keyword, + "post_id": post_id, + "public_metrics": statistics, + "creator_metrics": normalize_creator_metrics("douyin", statistics), + }, + ) + ) + if len(out) >= limit: + break + return out + + +def parse_tikhub_xiaohongshu_items(payload: dict[str, Any], now: datetime, keyword: str, limit: int) -> list[RawItem]: + out: list[RawItem] = [] + seen_ids: set[str] = set() + for node in iter_nested_dicts(payload): + note = next( + ( + node.get(key) + for key in ("note_card", "note_info", "note", "note_data", "noteCard") + if isinstance(node.get(key), dict) + ), + node, + ) + if not isinstance(note, dict): + continue + note_id = str( + note.get("note_id") + or note.get("noteId") + or note.get("id") + or node.get("noteId") + or node.get("note_id") + or node.get("id") + or "" + ).strip() + title = compact_public_snippet( + str( + note.get("display_title") + or note.get("displayTitle") + or note.get("title") + or note.get("desc") + or note.get("description") + or note.get("content") + or node.get("display_title") + or node.get("title") + or node.get("desc") + or "" + ), + max_chars=220, + ) + if not (note_id and title) or note_id in seen_ids: + continue + seen_ids.add(note_id) + user = next( + ( + owner + for owner in (note.get("user"), note.get("user_info"), node.get("user"), node.get("user_info")) + if isinstance(owner, dict) + ), + {}, + ) + source = str( + user.get("nickname") + or user.get("nick_name") + or user.get("nickName") + or user.get("name") + or "Xiaohongshu Search" + ).strip() or "Xiaohongshu Search" + xsec_token = str(note.get("xsec_token") or node.get("xsec_token") or "").strip() + url = first_non_empty( + note.get("url"), + note.get("share_url"), + note.get("shareUrl"), + node.get("url"), + node.get("share_url"), + node.get("shareUrl"), + f"https://www.xiaohongshu.com/explore/{note_id}{'?xsec_token=' + xsec_token if xsec_token else ''}", + ) + published = parse_tikhub_published_at( + note, + now, + ( + "time", + "create_time", + "created_at", + "last_update_time", + "createTime", + "createdAt", + "lastUpdateTime", + "publish_time", + "publishTime", + ), + ) + if not is_credible_xiaohongshu_published_at(published, now): + published = parse_tikhub_published_at( + node, + now, + ( + "time", + "create_time", + "created_at", + "last_update_time", + "createTime", + "createdAt", + "lastUpdateTime", + "publish_time", + "publishTime", + ), + ) + if not is_credible_xiaohongshu_published_at(published, now): + published = parse_xiaohongshu_note_id_published_at(note_id, now) + interact_info = note.get("interact_info") if isinstance(note.get("interact_info"), dict) else {} + creator_metrics = normalize_creator_metrics("xiaohongshu", node, note, interact_info) + out.append( + RawItem( + site_id="tikhub_xiaohongshu", + site_name="TikHub Xiaohongshu", + source=source, + title=title, + url=str(url), + published_at=published, + meta={ + "platform": "xiaohongshu", + "keyword": keyword, + "post_id": note_id, + "public_metrics": interact_info or creator_metrics, + "creator_metrics": creator_metrics, + }, + ) + ) + if len(out) >= limit: + break + return out + + +def tikhub_raw_item_key(item: RawItem) -> str: + post_id = str((item.meta or {}).get("post_id") or "").strip() + if post_id: + return f"{item.site_id}:{post_id}" + return f"{item.site_id}:{normalize_url(item.url)}:{item.title.strip()}" + + +def fetch_tikhub_search( + session: requests.Session, + api_key: str, + query: str, + now: datetime, + max_results: int, + platforms: list[str], + base_url: str = TIKHUB_API_BASE_DEFAULT, +) -> tuple[list[RawItem], dict[str, Any]]: + headers = {"Authorization": f"Bearer {api_key}", "Accept": "application/json"} + root = (base_url or TIKHUB_API_BASE_DEFAULT).rstrip("/") + keywords = [part.strip() for part in query.split(",") if part.strip()] + if not keywords: + raise ValueError("tikhub_query_empty") + if any(len(keyword) > TIKHUB_MAX_QUERY_CHARS for keyword in keywords): + raise ValueError("tikhub_query_too_long") + + capped_max_results = max(1, min(int(max_results or TIKHUB_DEFAULT_MAX_RESULTS), 100)) + platform_list = [] + for platform in platforms: + if platform in {"douyin", "xiaohongshu"} and platform not in platform_list: + platform_list.append(platform) + out: list[RawItem] = [] + per_platform_cap = max(1, (capped_max_results + max(len(platform_list), 1) - 1) // max(len(platform_list), 1)) + per_keyword_cap = max(1, (per_platform_cap + max(len(keywords), 1) - 1) // max(len(keywords), 1)) + diagnostics: dict[str, Any] = { + "keywords": keywords, + "platforms": platform_list, + "per_keyword_cap": per_keyword_cap, + "requests": [], + "successful_request_count": 0, + "request_error_count": 0, + "recency_days": TIKHUB_RECENCY_DAYS, + "skipped_missing_published_at_count": 0, + "skipped_stale_count": 0, + } + seen_item_keys: set[str] = set() + recency_cutoff = now - timedelta(days=TIKHUB_RECENCY_DAYS) if TIKHUB_RECENCY_DAYS else None + + def append_mapped_items(mapped: list[RawItem], surface: str, remaining: int) -> int: + appended = 0 + for item in mapped: + if appended >= remaining: + break + # Enforce the exact recency window (the API only has coarse buckets). + if not item.published_at: + diagnostics["skipped_missing_published_at_count"] += 1 + continue + if recency_cutoff and item.published_at and item.published_at < recency_cutoff: + diagnostics["skipped_stale_count"] += 1 + continue + key = tikhub_raw_item_key(item) + if key in seen_item_keys: + continue + seen_item_keys.add(key) + item.meta["search_surface"] = surface + out.append(item) + appended += 1 + return appended + + def request_error_info(exc: Exception) -> dict[str, Any]: + response = getattr(exc, "response", None) + return { + "error": type(exc).__name__, + "status_code": getattr(response, "status_code", None), + } + + for platform in platform_list: + platform_count = 0 + for keyword in keywords: + remaining = min(capped_max_results - len(out), per_platform_cap - platform_count, per_keyword_cap) + if remaining <= 0: + break + if platform == "douyin": + endpoint = "/api/v1/douyin/search/fetch_general_search_v2" + request_info = { + "platform": platform, + "surface": "douyin_general_v2", + "endpoint": endpoint, + "keyword": keyword, + } + try: + response = session.post( + f"{root}{endpoint}", + headers={**headers, "Content-Type": "application/json"}, + json={ + "keyword": keyword, + "cursor": 0, + "sort_type": TIKHUB_DOUYIN_SORT_TYPE, + "publish_time": TIKHUB_DOUYIN_PUBLISH_TIME, + "filter_duration": "0", + "content_type": "0", + "search_id": "", + "backtrace": "", + }, + timeout=30, + ) + response.raise_for_status() + payload = response.json() + mapped = parse_tikhub_douyin_items( + payload, + now=now, + keyword=keyword, + limit=max(remaining, TIKHUB_RESPONSE_SCAN_LIMIT), + ) + appended = append_mapped_items(mapped, "douyin_general_v2", remaining) + platform_count += appended + request_info.update( + { + "mapped_item_count": len(mapped), + "appended_item_count": appended, + "response_top_level_keys": sorted(payload.keys())[:12] if isinstance(payload, dict) else [], + "payload_shape": tikhub_payload_shape(payload), + } + ) + diagnostics["successful_request_count"] += 1 + except Exception as exc: + diagnostics["request_error_count"] += 1 + request_info.update(request_error_info(exc)) + diagnostics["requests"].append(request_info) + else: + # TikHub documents App V2 as the preferred Xiaohongshu API and + # Web V3 as the next public web path; scan both because results + # can differ between mobile and web surfaces. + xhs_surfaces = ( + ( + "xiaohongshu_app_v2", + "/api/v1/xiaohongshu/app_v2/search_notes", + { + "keyword": keyword, + "page": 1, + "sort_type": TIKHUB_XHS_SORT, + "note_type": TIKHUB_XHS_NOTE_TYPE, + "time_filter": TIKHUB_XHS_TIME_FILTER, + "search_id": "", + "search_session_id": "", + "source": "explore_feed", + "ai_mode": 0, + }, + ), + ( + "xiaohongshu_web_v3", + "/api/v1/xiaohongshu/web_v3/fetch_search_notes", + {"keyword": keyword, "page": 1, "sort": TIKHUB_XHS_SORT, "note_type": 0}, + ), + ) + keyword_count = 0 + for surface, endpoint, params in xhs_surfaces: + surface_remaining = min( + remaining - keyword_count, + capped_max_results - len(out), + per_platform_cap - platform_count, + ) + if surface_remaining <= 0: + break + request_info = { + "platform": platform, + "surface": surface, + "endpoint": endpoint, + "keyword": keyword, + } + try: + response = session.get(f"{root}{endpoint}", headers=headers, params=params, timeout=30) + response.raise_for_status() + payload = response.json() + mapped = parse_tikhub_xiaohongshu_items( + payload, + now=now, + keyword=keyword, + limit=max(surface_remaining, TIKHUB_RESPONSE_SCAN_LIMIT), + ) + appended = append_mapped_items(mapped, surface, surface_remaining) + platform_count += appended + keyword_count += appended + request_info.update( + { + "mapped_item_count": len(mapped), + "appended_item_count": appended, + "response_top_level_keys": sorted(payload.keys())[:12] if isinstance(payload, dict) else [], + "payload_shape": tikhub_payload_shape(payload), + } + ) + if surface == "xiaohongshu_app_v2" and keyword_count < remaining: + request_info["fallback_reason"] = ( + "no_items_mapped_try_web_v3" + if not mapped + else "insufficient_recent_items_try_web_v3" + ) + diagnostics["successful_request_count"] += 1 + except Exception as exc: + diagnostics["request_error_count"] += 1 + request_info.update(request_error_info(exc)) + diagnostics["requests"].append(request_info) + if len(out) >= capped_max_results: + break + diagnostics["mapped_item_count"] = len(out) + if diagnostics["request_error_count"] and not diagnostics["successful_request_count"]: + raise ValueError("tikhub_all_requests_failed") + return out, diagnostics + + +def maybe_fetch_tikhub_updates( + session: requests.Session, + now: datetime, + paid_source_state: dict[str, Any] | None = None, +) -> tuple[list[RawItem], dict[str, Any]]: + """Fetch TikHub when an API key is present and ENABLED is not turned off, + then only if scheduled and capped. The key is the primary switch; ENABLED is + an optional kill switch (set it to 0 to force off).""" + status = tikhub_status_base(now, paid_source_state) + if not status["enable_toggle"]: + status["disabled_reason"] = "disabled_by_toggle" + return [], status + if not status["api_key_present"]: + status["disabled_reason"] = "no_api_key" + return [], status + + if status["effective_result_cap"] < 1: + status["ok"] = False + status["error"] = "tikhub_daily_item_limit_below_minimum" + return [], status + + should_run, skip_reason = tikhub_should_run_now(now, paid_source_state) + if not should_run: + status["skipped"] = True + status["skip_reason"] = skip_reason or "outside_tikhub_run_window" + return [], status + + api_key = str(os.environ.get("TIKHUB_API_KEY") or "").strip() + + query = str(os.environ.get("TIKHUB_QUERY") or TIKHUB_DEFAULT_QUERY).strip() + base_url = str(os.environ.get("TIKHUB_API_BASE_URL") or TIKHUB_API_BASE_DEFAULT).strip() + status["attempted"] = True + try: + items, diagnostics = fetch_tikhub_search( + session, + api_key=api_key, + query=query, + now=now, + max_results=int(status["effective_result_cap"]), + platforms=status["platforms"], + base_url=base_url, + ) + status["ok"] = True + status["item_count"] = len(items) + status["diagnostics"] = diagnostics + return items, status + except Exception as exc: + status["ok"] = False + status["error"] = type(exc).__name__ + return [], status + + +def has_mojibake_noise(text: str) -> bool: + if not text: + return False + return bool(re.search(r"(Ã|Â|â€|æ·|�)", text)) + + +def normalize_source_for_display(site_id: str, source: str, url: str) -> str: + src = (source or "").strip() + if not src: + host = host_of_url(url) + if host.startswith("www."): + host = host[4:] + return host or "未分区" + if site_id == "buzzing" and src.lower() == "buzzing": + host = host_of_url(url) + if host.startswith("www."): + host = host[4:] + return host or src + return src + + +def is_ai_related_record(record: dict[str, Any]) -> bool: + if has_mojibake_noise(str(record.get("source") or "")) or has_mojibake_noise(str(record.get("title") or "")): + return False + return bool(score_ai_relevance(record)["is_ai_related"]) + + +def load_title_zh_cache(path: Path) -> dict[str, str]: + if not path.exists(): + return {} + try: + data = json.loads(path.read_text(encoding="utf-8")) + if isinstance(data, dict): + # Note: keep empty-string values (e.g. title-enhance negative-cache + # entries under TITLE_ENHANCE_CACHE_PREFIX) so they survive reload + # instead of being retried every run. + return {str(k): str(v) for k, v in data.items() if str(k).strip()} + except Exception: + pass + return {} + + +def translate_to_zh_cn(session: requests.Session, text: str) -> str | None: + s = (text or "").strip() + if not s: + return None + try: + r = session.get( + "https://translate.googleapis.com/translate_a/single", + params={ + "client": "gtx", + "sl": "auto", + "tl": "zh-CN", + "dt": "t", + "q": s, + }, + timeout=12, + ) + r.raise_for_status() + payload = r.json() + if not isinstance(payload, list) or not payload: + return None + segs = payload[0] + if not isinstance(segs, list): + return None + translated = "".join(str(seg[0]) for seg in segs if isinstance(seg, list) and seg and seg[0]) + translated = translated.strip() + if translated and translated != s: + return translated + except Exception: + return None + return None + + +ZH_CACHE_DS_PREFIX = "ds1|" + +TRANSLATION_GLOSSARY_FILENAME = "translation-glossary.txt" + +# 进程级词表缓存:None 表示尚未加载,加载后为 (protected_terms, repairs)。 +_GLOSSARY_CACHE: tuple[list[str], list[tuple[str, str, str | None]]] | None = None + + +def load_translation_glossary( + path: str | Path = TRANSLATION_GLOSSARY_FILENAME, +) -> tuple[list[str], list[tuple[str, str, str | None]]]: + """解析根目录翻译词表,返回 (protected_terms, repairs)。 + + 词表格式(fork 用户直接编辑 translation-glossary.txt): + - 普通行 = 保护术语(翻译时保留原文) + - ``bad => good [@guard]`` = 修正规则;guard 表示只有英文原标题 + 包含该关键词(大小写不敏感)才执行替换,可省略。 + 文件缺失或解析异常时静默返回空表,fork 删掉文件也不影响管线。 + """ + protected_terms: list[str] = [] + repairs: list[tuple[str, str, str | None]] = [] + try: + p = Path(path) + if not p.is_absolute(): + p = Path(__file__).resolve().parent.parent / p + for raw_line in p.read_text(encoding="utf-8").splitlines(): + line = raw_line.strip() + if not line or line.startswith("#"): + continue + if "=>" in line: + bad, _, rest = line.partition("=>") + bad = bad.strip() + rest = rest.strip() + guard: str | None = None + if "@" in rest: + good_part, _, guard_part = rest.rpartition("@") + good = good_part.strip() + guard = guard_part.strip() or None + else: + good = rest + if bad and good: + repairs.append((bad, good, guard)) + else: + protected_terms.append(line) + except Exception: + return [], [] + return protected_terms, repairs + + +def _get_translation_glossary() -> tuple[list[str], list[tuple[str, str, str | None]]]: + global _GLOSSARY_CACHE + if _GLOSSARY_CACHE is None: + _GLOSSARY_CACHE = load_translation_glossary() + return _GLOSSARY_CACHE + + +def translate_to_zh_deepseek(text: str, timeout: int = 20) -> str | None: + s = (text or "").strip() + if not s: + return None + api_key = str(os.environ.get("DEEPSEEK_API_KEY") or "").strip() + if not api_key: + return None + base_url = str(os.environ.get("DEEPSEEK_API_BASE_URL") or "https://api.deepseek.com").strip().rstrip("/") + model = str(os.environ.get("DEEPSEEK_MODEL") or "deepseek-v4-flash").strip() + protected_terms, _ = _get_translation_glossary() + if protected_terms: + term_list = "、".join(protected_terms) + else: + term_list = "Codex、Claude、OpenAI、Anthropic、Hugging Face、The Information" + system_prompt = ( + "你是科技新闻编辑,把英文 AI/科技新闻标题翻译成地道的简体中文。" + "产品名、公司名、模型名、媒体名、人名一律保留英文原文不翻译" + f"(如 {term_list})。" + "用自然的中文表达,说人话,避免翻译腔。" + "只返回译文本身,不加引号,不加解释,长度贴近原标题的信息量。" + ) + try: + r = requests.post( + f"{base_url}/chat/completions", + headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}, + json={ + "model": model, + "temperature": 0.2, + "messages": [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": s}, + ], + }, + timeout=timeout, + ) + if r.status_code != 200: + return None + payload = r.json() + choices = payload.get("choices") if isinstance(payload, dict) else None + if not isinstance(choices, list) or not choices: + return None + content = str(((choices[0] or {}).get("message") or {}).get("content") or "").strip() + content = content.strip("\"'“”「」").strip() + if content and content != s: + return content + except Exception: + return None + return None + + +def repair_zh_title_translation(original: str, translated: str) -> str: + """Repair recurring machine-translation errors in AI product/news titles.""" + source = str(original or "") + result = str(translated or "").strip() + if not result: + return result + if re.search(r"\bCodex\b", source, re.I): + result = result.replace("法典", "Codex") + if re.search(r"\bBug Bounty\b", source, re.I): + result = result.replace("错误赏金", "漏洞悬赏").replace("Bug 赏金", "漏洞悬赏") + if re.search(r"\bBio Bug Bounty\b", source, re.I): + result = result.replace("生物漏洞悬赏", "生物安全漏洞悬赏") + if re.search(r"\brepositor(?:y|ies)\b", source, re.I): + result = result.replace("存储库", "代码仓库") + if re.search(r"\bdesktop app\b", source, re.I): + result = result.replace("桌面应用程序", "桌面应用") + # 模型架构 Transformer 被译成电影名;排除原文明显在谈电影/玩具的场景防误伤。 + if re.search(r"\btransformers?\b", source, re.I) and not re.search( + r"\b(movie|film|trailer|hasbro|toy)\b", source, re.I + ): + result = result.replace("变形金刚", "Transformer") + # 公司名 Hugging Face 被直译;仅当原文出现该公司名时才替换。 + if re.search(r"\bHugging\s*Face\b", source, re.I): + result = result.replace("拥抱脸", "Hugging Face").replace("抱抱脸", "Hugging Face") + # 公司名 OpenAI 偶尔被拆词直译;"开放人工智能"日常中文几乎不用,误伤面小。 + if re.search(r"\bOpenAI\b", source, re.I): + result = result.replace("开放人工智能", "OpenAI") + # 公司名 Anthropic 被误译为哲学词;仅替换"人择"这类专有误译,不动泛指"人类"的句子。 + if re.search(r"\bAnthropic\b", source, re.I): + result = result.replace("人择", "Anthropic").replace("人类学公司", "Anthropic") + # 媒体名 The Information 被译成普通名词;只替换书名号/报社式误译,避免动正文里的"信息"。 + if re.search(r"\bThe Information\b", source): + result = result.replace("《信息》", "The Information").replace("信息报", "The Information") + # 模型名 Gemini 被译成星座;AI 信源里原文含 Gemini 基本都指模型。 + if re.search(r"\bGemini\b", source): + result = result.replace("双子座", "Gemini") + # 模型名 Llama 被译成动物名;仅当原文点名 Llama 时替换。 + if re.search(r"\bLlama\b", source, re.I): + result = result.replace("骆驼", "Llama").replace("羊驼", "Llama") + # 产品名 Copilot 被直译;仅当原文出现 Copilot 时替换,不影响航空语境。 + if re.search(r"\bCopilot\b", source, re.I): + result = result.replace("副驾驶", "Copilot") + # 产品名 Cursor 被译成"光标";仅当原文以大写 Cursor 出现(产品名写法)时替换。 + if re.search(r"\bCursor\b", source): + result = result.replace("光标", "Cursor") + # 公司名 Perplexity 被译成"困惑";大小写敏感匹配,避免误伤指标含义的 perplexity。 + if re.search(r"\bPerplexity\b", source): + result = result.replace("困惑", "Perplexity") + # 词表修正规则(translation-glossary.txt):guard 语义与上面硬编码规则一致—— + # 只有英文原标题包含 guard 关键词才替换,防误伤。 + _, glossary_repairs = _get_translation_glossary() + for bad, good, guard in glossary_repairs: + if bad not in result: + continue + if guard and not re.search(re.escape(guard), source, re.I): + continue + result = result.replace(bad, good) + # 替换目标为纯 ASCII 术语时,清理机翻残留的紧贴书名号,如《Fable 5》→ Fable 5。 + if good.isascii(): + result = re.sub(r"《(" + re.escape(good) + r"[^《》]*)》", r"\1", result) + return result + + +ZH_TRANSLATION_REFUSAL_MARKERS = [ + "抱歉", + "我无法处理", + "我无法翻译", + "我无法提供", + "sorry", + "cannot", + "i can't", + "无法处理", + "请提供", + "请直接提供", +] +_ZH_REFUSAL_LEADING_STRIP_RE = re.compile(r'^[\s"\'“”‘’「」『』((,,.。::]+') + + +def _looks_like_translation_refusal(text: str) -> bool: + """A real refusal ("抱歉,我无法处理链接内容。请直接提供英文标题文本。") + leads with its refusal phrase. A genuine headline translation can also + contain "抱歉"/"我无法" as ordinary vocabulary anywhere mid-sentence (e.g. + "OpenAI 老板...深感抱歉", "我无法想象没有他的生活") — matching those as a + substring anywhere in the text produces false positives, seen on 22 real + cached translations. Requiring the marker to lead the (punctuation- + stripped) text scopes this to actual refusal-style openings only.""" + lowered = _ZH_REFUSAL_LEADING_STRIP_RE.sub("", text.lower()) + return any(lowered.startswith(marker.lower()) for marker in ZH_TRANSLATION_REFUSAL_MARKERS) + + +def is_valid_zh_translation(original: str, translated: str, *, strict: bool = True) -> bool: + """Validate a raw MT/LLM translation candidate before it's cached and + shown as an item's headline. Rejects two recurring failure modes seen + with SocialData X titles that collapse to a bare t.co link after + `compact_public_snippet` truncation: + - LLM refusal sentences (e.g. DeepSeek replying "抱歉,我无法处理链接内容。 + 请直接提供英文标题文本。" instead of translating a link-only "title"). + - Degenerate/too-short outputs (e.g. a full headline translated down to + a single fragment like "前体" / "Precursor"). + Reuses the length/CJK-count sanity checks from `enhance_title_deepseek()`'s + validator; skips its stricter entity-echo check since that's tuned for + title rewrites, not plain translation. + + `strict=False` (used to re-validate existing cache entries) only checks + refusal phrases plus the `cjk_count >= 4` degenerate floor, skipping the + `8 <= effective_len <= 36` band: that upper/lower band is tuned for + freshly-generated `enhance_title_deepseek()`-style rewrites, but short + yet complete plain translations of already-terse titles (e.g. a 7-char + cached translation of a 5-word title) are legitimate and get corrected + for glossary mismatches by `repair_zh_title_translation()`, not rejected. + """ + text = str(translated or "").strip() + if not text or not has_cjk(text): + return False + if _looks_like_translation_refusal(text): + return False + cjk_count, effective_len = _title_enhance_effective_length(text) + if cjk_count < 4: + return False + if strict and not (8 <= effective_len <= 36): + return False + return True + + +def agentmail_title_translation_input(title: str) -> str: + """Remove trailing emoji/decorative markers that often make newsletter titles hard to translate.""" + cleaned = re.sub(r"[^\w\s.,:;!?&'()/+-]", "", str(title or ""), flags=re.UNICODE) + cleaned = re.sub(r"[\s,,、·|/\\:;!!??.\-–—_]+$", "", cleaned).strip() + return cleaned or str(title or "").strip() + + +def is_acceptable_agentmail_translation(translated: str) -> bool: + text = str(translated or "").strip() + return bool(text and has_cjk(text) and not _looks_like_translation_refusal(text)) + + +def add_bilingual_fields( + items_ai: list[dict[str, Any]], + items_all: list[dict[str, Any]], + session: requests.Session, + cache: dict[str, str], + max_new_translations: int, + max_new_translations_all: int = 0, +) -> tuple[list[dict[str, Any]], list[dict[str, Any]], dict[str, str]]: + zh_by_url: dict[str, str] = {} + for it in items_all: + title = str(it.get("title") or "").strip() + url = normalize_url(str(it.get("url") or "")) + if title and url and has_cjk(title): + zh_by_url[url] = title + + translated_now_ai = 0 + translated_now_all = 0 + + def enrich(item: dict[str, Any], allow_translate: bool, is_ai_pool: bool) -> dict[str, Any]: + nonlocal translated_now_ai, translated_now_all + out = dict(item) + title = str(out.get("title") or "").strip() + url = normalize_url(str(out.get("url") or "")) + is_agentmail_item = str(out.get("site_id") or "") == "agentmail" + provided_zh = str(out.pop("provided_title_zh", "") or "").strip() + provided_en_raw = str(out.pop("provided_title_en", "") or "").strip() + provided_en = provided_en_raw if is_mostly_english(provided_en_raw) else "" + + out["title_original"] = title + out["title_en"] = None + out["title_zh"] = None + out["title_bilingual"] = title + + if provided_en: + zh_title = provided_zh if has_cjk(provided_zh) else (title if has_cjk(title) else "") + out["title_original"] = provided_en + out["title_en"] = provided_en + out["title_zh"] = zh_title or None + out["title_bilingual"] = f"{zh_title} / {provided_en}" if zh_title else provided_en + return out + + if has_cjk(title): + out["title_zh"] = title + return out + + english_probe = agentmail_title_translation_input(title) if is_agentmail_item else title + if not is_mostly_english(english_probe): + return out + + out["title_en"] = title + + has_ds_key = bool(str(os.environ.get("DEEPSEEK_API_KEY") or "").strip()) + cache_hit_key: str | None = None + zh_title = zh_by_url.get(url) + if not zh_title: + ds_key = ZH_CACHE_DS_PREFIX + title + cached_ds = cache.get(ds_key) + if cached_ds and ( + is_valid_zh_translation(title, cached_ds, strict=False) + or (is_agentmail_item and is_acceptable_agentmail_translation(cached_ds)) + ): + zh_title = cached_ds + cache_hit_key = ds_key + elif not has_ds_key: + # 谷歌时代的裸 key 旧缓存只在 DeepSeek 不可用时兜底命中; + # 有 key 时视为 miss,触发 DeepSeek 重译逐步替换旧翻译。 + cached_google = cache.get(title) + if cached_google and ( + is_valid_zh_translation(title, cached_google, strict=False) + or (is_agentmail_item and is_acceptable_agentmail_translation(cached_google)) + ): + zh_title = cached_google + cache_hit_key = title + if not zh_title and allow_translate: + budget = max_new_translations if is_ai_pool else max_new_translations_all + translated_now = translated_now_ai if is_ai_pool else translated_now_all + if translated_now < budget: + translation_input = english_probe + tr = translate_to_zh_deepseek(translation_input) + if tr and (is_valid_zh_translation(title, tr) or (is_agentmail_item and is_acceptable_agentmail_translation(tr))): + zh_title = repair_zh_title_translation(title, tr) + cache[ZH_CACHE_DS_PREFIX + title] = zh_title + if is_ai_pool: + translated_now_ai += 1 + else: + translated_now_all += 1 + else: + tr = translate_to_zh_cn(session, translation_input) + if tr and (is_valid_zh_translation(title, tr) or (is_agentmail_item and is_acceptable_agentmail_translation(tr))): + zh_title = repair_zh_title_translation(title, tr) + cache[title] = zh_title + if is_ai_pool: + translated_now_ai += 1 + else: + translated_now_all += 1 + + if zh_title: + zh_title = repair_zh_title_translation(title, zh_title) + if cache_hit_key and cache.get(cache_hit_key) != zh_title: + cache[cache_hit_key] = zh_title + out["title_zh"] = zh_title + out["title_bilingual"] = f"{zh_title} / {title}" + return out + + if max_new_translations > 0: + # AgentMail items are visible in the default AI timeline too; warm + # them before other AI sources consume the smaller primary cap. + for it in items_ai: + if str(it.get("site_id") or "") == "agentmail": + enrich(it, allow_translate=True, is_ai_pool=True) + ai_out = [enrich(it, allow_translate=True, is_ai_pool=True) for it in items_ai] + if max_new_translations_all > 0: + # AgentMail newsletter items often enter only the broad/all pool; warm + # their translations before broader public-source noise consumes the cap. + for it in items_all: + if str(it.get("site_id") or "") == "agentmail": + enrich(it, allow_translate=True, is_ai_pool=False) + all_out = [ + enrich(it, allow_translate=max_new_translations_all > 0, is_ai_pool=False) for it in items_all + ] + return ai_out, all_out, cache + + +TITLE_ENHANCE_CACHE_PREFIX = "te1|" + +RECOMMEND_REASON_CACHE_PREFIX = "re1|" + +_TITLE_ENHANCE_GATED_TIERS = {"discussion", "aggregate", "community"} +_TITLE_ENHANCE_EXEMPT_TIERS = {"official", "curated"} + +_TITLE_ENHANCE_YEAR_SUFFIX_RE = re.compile(r"[((]20\d{2}[))]\s*$") + +_TITLE_ENHANCE_ENTITY_RE = re.compile(r"[A-Za-z][A-Za-z0-9]+") + + +def title_needs_enhance(item: dict[str, Any]) -> bool: + """Gate for the micro-crawl + DeepSeek title-rewrite step: many source + titles are bare product/company names or jargon-heavy aggregator titles + that don't read as self-explanatory news headlines.""" + site_id = str(item.get("site_id") or "").strip().lower() + tier = str(item.get("source_tier") or "").strip().lower() + if site_id == "official_ai" or tier in _TITLE_ENHANCE_EXEMPT_TIERS: + return False + + zh_title = str(item.get("title_zh") or "").strip() + en_title = str(item.get("title_en") or item.get("title_original") or "").strip() + effective_title = zh_title or en_title + + # Upstream-pre-translated cryptic titles ending in a parenthesized year + # (half-width "(2025)" or full-width "(2025)") are a strong "this is an + # aggregator/discussion repost, not a real headline" signal on their own. + # This must run BEFORE the CJK-length exemption below: those titles are + # often long CJK strings that would otherwise be waved through as + # already self-explanatory. + if ( + tier in _TITLE_ENHANCE_GATED_TIERS + and effective_title + and _TITLE_ENHANCE_YEAR_SUFFIX_RE.search(effective_title) + ): + return True + + # A decent-length Chinese title is already self-explanatory; never gate it, + # regardless of tier. Guards against CJK titles false-positiving on the + # space-separated word-count rule below (CJK has no spaces). + if effective_title and has_cjk(effective_title) and len(effective_title) >= 12: + return False + + # Word-count rule only makes sense for genuinely English titles. + if en_title and is_mostly_english(en_title) and 1 <= len(en_title.split()) <= 4: + return True + + if tier in _TITLE_ENHANCE_GATED_TIERS: + if effective_title and len(effective_title) < 18: + return True + if en_title and _TITLE_ENHANCE_YEAR_SUFFIX_RE.search(en_title): + return True + + return False + + +def _fetch_context_bytes( + session: requests.Session, url: str, headers: dict[str, str], timeout: int, limit: int = 512 * 1024 +) -> bytes: + """Stream up to `limit` bytes from `url`, closing the connection early. + Any failure (non-200, timeout, connection error) yields b"".""" + resp = None + try: + resp = session.get(url, timeout=timeout, headers=headers, stream=True) + resp.raise_for_status() + chunks: list[bytes] = [] + total = 0 + for chunk in resp.iter_content(chunk_size=8192): + if not chunk: + continue + chunks.append(chunk) + total += len(chunk) + if total >= limit: + break + return b"".join(chunks) + except Exception: + return b"" + finally: + if resp is not None: + try: + resp.close() + except Exception: + pass + + +def _parse_html_page_context(raw: bytes, max_paragraphs: int = 3) -> str: + if not raw: + return "" + soup = BeautifulSoup(raw, "html.parser") + + parts: list[str] = [] + for attrs in ( + {"property": "og:description"}, + {"name": "description"}, + {"name": "twitter:description"}, + {"property": "twitter:description"}, + ): + tag = soup.find("meta", attrs=attrs) + if tag and tag.get("content"): + text = str(tag.get("content")).strip() + if text: + parts.append(text) + + p_count = 0 + for p in soup.find_all("p"): + if p_count >= max_paragraphs: + break + if p.find_parent(["script", "style", "nav"]): + continue + text = p.get_text(" ", strip=True) + if text: + parts.append(text) + p_count += 1 + + return "\n".join(part for part in parts if part).strip() + + +_JINA_MD_LINK_RE = re.compile(r"!?\[[^\]]*\]\([^)]*\)") +_JINA_MD_BULLET_RE = re.compile(r"^[*\-+]\s+|^\d+\.\s+") + + +def _jina_line_is_prose(line: str) -> bool: + """Heuristic to skip nav-menu markdown link spaghetti (e.g. ProductHunt's + "* [Best of the day](https://...)" sidebar rows) while keeping real body + text. Strips markdown link syntax and bullet/heading markup; a line is + treated as prose only if enough plain text remains.""" + stripped = _JINA_MD_LINK_RE.sub("", line) + stripped = _JINA_MD_BULLET_RE.sub("", stripped) + stripped = re.sub(r"[#>*_`|]", " ", stripped) + stripped = re.sub(r"\s+", " ", stripped).strip() + return len(stripped) >= 20 + + +def _parse_jina_reader_context(raw: bytes, max_lines: int = 40, max_prose_lines: int = 3) -> str: + """r.jina.ai renders a page to markdown; the first line is + "Title: " followed by "URL Source: ..." and + "Markdown Content: ..." section markers before the actual body text.""" + if not raw: + return "" + try: + text = raw.decode("utf-8", errors="ignore") + except Exception: + return "" + lines = [ln.strip() for ln in text.splitlines()] + + title_line = next((ln for ln in lines if ln.lower().startswith("title:")), "") + + content_lines: list[str] = [] + for ln in lines[:max_lines]: + if len(content_lines) >= max_prose_lines: + break + if not ln or ln.lower().startswith(("title:", "url source:", "markdown content:")): + continue + if not _jina_line_is_prose(ln): + continue + content_lines.append(ln) + + if not content_lines: + # No real prose in the first 40 lines (nav-heavy page). The title + # alone is often informative enough — PH-style titles read as full + # descriptive sentences — so fall back to just that. + return title_line.strip() + + parts = ([title_line] if title_line else []) + content_lines + return "\n".join(part for part in parts if part).strip() + + +def fetch_title_context(session: requests.Session, url: str) -> str: + """Micro-crawl the source page for enough context (meta descriptions + + first paragraphs) to let the LLM rewrite a terse title informatively. + Any failure or empty extraction returns "" so callers can skip cleanly. + + Some sources (e.g. ProductHunt) sit behind Cloudflare and 403 a direct + crawl. When the direct fetch yields no usable context, fall back to a + single request through r.jina.ai — a free, keyless third-party reader + proxy (~20 rpm) that renders the page to markdown. This only fires on + direct-fetch failure and is gated by the same TITLE_ENHANCE_MAX_PER_RUN + cap as the LLM call, so it stays well under the reader's rate limit. + """ + u = str(url or "").strip() + if not u: + return "" + headers = { + "User-Agent": ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36" + ), + "Accept": "text/html,application/xhtml+xml", + } + raw = _fetch_context_bytes(session, u, headers, timeout=8) + context = _parse_html_page_context(raw) + if context: + return context[:800] + + jina_headers = {"Accept": "text/plain"} + jina_raw = _fetch_context_bytes(session, f"https://r.jina.ai/{u}", jina_headers, timeout=15) + jina_context = _parse_jina_reader_context(jina_raw) + return jina_context[:800] + + +FULL_TEXT_CONTEXT_CHAR_CAP = 3500 + + +def fetch_full_text_context(session: requests.Session, url: str) -> str: + """Micro-crawl the source page for real article body text (not just a + short snippet) so an LLM can write a genuine, fact-grounded "why this is + worth reading" reason. Shares the same fetch machinery as + `fetch_title_context()` (byte-stream cap, direct-fetch-then-jina-fallback + strategy) but with much higher paragraph/line extraction limits and a + larger char cap, since we want real body content rather than a + description-length snippet. Any failure or empty extraction returns "" + so callers can skip cleanly. + """ + u = str(url or "").strip() + if not u: + return "" + headers = { + "User-Agent": ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36" + ), + "Accept": "text/html,application/xhtml+xml", + } + raw = _fetch_context_bytes(session, u, headers, timeout=8) + context = _parse_html_page_context(raw, max_paragraphs=40) + if context: + return context[:FULL_TEXT_CONTEXT_CHAR_CAP] + + jina_headers = {"Accept": "text/plain"} + jina_raw = _fetch_context_bytes(session, f"https://r.jina.ai/{u}", jina_headers, timeout=15) + jina_context = _parse_jina_reader_context(jina_raw, max_lines=400, max_prose_lines=60) + return jina_context[:FULL_TEXT_CONTEXT_CHAR_CAP] + + +def _title_enhance_entity_tokens(title: str) -> list[str]: + return [tok for tok in _TITLE_ENHANCE_ENTITY_RE.findall(str(title or "")) if len(tok) >= 2] + + +_TITLE_ENHANCE_TOKEN_RE = re.compile(r"[A-Za-z0-9.+-]+") + + +def _title_enhance_effective_length(text: str) -> tuple[int, int]: + """Length validation uses editorial "字" count, not raw chars: a title + that correctly keeps English entities verbatim (Claude, ChatGPT, Cursor) + blows past a raw-char cap even when it reads as a normal-length headline. + Returns (cjk_char_count, effective_length) where each CJK char counts 1, + each latin/alnum token (a run of [A-Za-z0-9.+-]+) counts as one "word" + worth 2 if it contains a letter (Claude -> 2, not 6) else 1 (bare digit + runs like a year); punctuation and spaces are free.""" + s = str(text or "") + cjk_count = len(re.findall(r"[一-鿿]", s)) + weight = 0 + for token in _TITLE_ENHANCE_TOKEN_RE.findall(s): + weight += 2 if re.search(r"[A-Za-z]", token) else 1 + return cjk_count, cjk_count + weight + + +def enhance_title_deepseek(title: str, context: str, timeout: int = 45) -> str | None: + """Rewrite a terse/jargon title into an informative Chinese one-liner, + grounded in `context` (micro-crawled page text). Validates the candidate + before returning so a non-None result can be trusted by callers.""" + title_s = str(title or "").strip() + context_s = str(context or "").strip() + if not title_s: + return None + api_key = str(os.environ.get("DEEPSEEK_API_KEY") or "").strip() + if not api_key: + return None + base_url = str(os.environ.get("DEEPSEEK_API_BASE_URL") or "https://api.deepseek.com").strip().rstrip("/") + model = str(os.environ.get("DEEPSEEK_MODEL") or "deepseek-v4-flash").strip() + system_prompt = ( + "你是科技新闻编辑,负责把语焉不详、看不出信息量的英文标题改写成一条完整的中文资讯标题。" + "输出一条中文资讯标题,不超过28个字(英文名称按一个词计)。" + "原文中的关键实体(公司名、产品名、人名)必须原样保留英文,不要翻译或音译。" + "不得编造原文和参考资料之外的数字或事实。" + "使用新闻陈述语气,不要营销口号腔调。" + "只输出标题本身,不加引号,不加任何解释。" + ) + user_content = f"原标题:{title_s}" + if context_s: + user_content += f"\n\n参考网页内容:\n{context_s}" + try: + r = requests.post( + f"{base_url}/chat/completions", + headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}, + json={ + "model": model, + "temperature": 0.3, + "messages": [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": user_content}, + ], + }, + timeout=timeout, + ) + if r.status_code != 200: + return None + payload = r.json() + choices = payload.get("choices") if isinstance(payload, dict) else None + if not isinstance(choices, list) or not choices: + return None + content = str(((choices[0] or {}).get("message") or {}).get("content") or "").strip() + content = content.strip("\"'“”「」").strip() + except Exception: + return None + + if not content or not has_cjk(content): + return None + cjk_count, effective_len = _title_enhance_effective_length(content) + if cjk_count < 4 or not (8 <= effective_len <= 36): + return None + + entities = _title_enhance_entity_tokens(title_s) + if entities: + lowered = content.lower() + if not any(tok.lower() in lowered for tok in entities): + return None + + return content + + +def add_title_enhancements( + items_ai: list[dict[str, Any]], + session: requests.Session, + cache: dict[str, str], + max_new_per_run: int | None = None, +) -> tuple[list[dict[str, Any]], dict[str, str]]: + """Micro-crawl + DeepSeek-rewrite gated items_ai entries into an + informative `title_enhanced_zh`. No-ops entirely without a DeepSeek key.""" + if not str(os.environ.get("DEEPSEEK_API_KEY") or "").strip(): + return items_ai, cache + + if max_new_per_run is None: + try: + max_new_per_run = int(os.environ.get("TITLE_ENHANCE_MAX_PER_RUN") or 30) + except Exception: + max_new_per_run = 30 + max_new_per_run = max(0, max_new_per_run) + + used = 0 + out: list[dict[str, Any]] = [] + for item in items_ai: + new_item = dict(item) + if not title_needs_enhance(new_item): + out.append(new_item) + continue + + url = normalize_url(str(new_item.get("url") or "")) + title = str( + new_item.get("title_en") or new_item.get("title_original") or new_item.get("title") or "" + ).strip() + cache_key = TITLE_ENHANCE_CACHE_PREFIX + hashlib.sha1(f"{url}|{title}".encode("utf-8")).hexdigest() + + if cache_key in cache: + cached = cache.get(cache_key) or "" + if cached: + new_item["title_enhanced_zh"] = cached + out.append(new_item) + continue + + if used >= max_new_per_run: + out.append(new_item) + continue + + used += 1 + context = fetch_title_context(session, str(new_item.get("url") or "")) + if not context: + cache[cache_key] = "" + out.append(new_item) + continue + + enhanced = enhance_title_deepseek(title, context) + if enhanced: + cache[cache_key] = enhanced + new_item["title_enhanced_zh"] = enhanced + else: + cache[cache_key] = "" + out.append(new_item) + + return out, cache + + +def generate_recommend_reason_deepseek( + title: str, full_text: str, session: requests.Session | None = None, timeout: int = 45 +) -> str | None: + """Given the real article title + full text, write one Chinese sentence + explaining concretely what this specific piece covers and why it's worth + reading. Unlike `enhance_title_deepseek()` this is prose, not a structured + title, so validation only does a basic sanity check (non-empty, has CJK, + reasonable length, not a verbatim echo of the title) rather than the + stricter entity/length rules used for title rewrites. `session` is + accepted for calling-convention parity with the rest of this module's + fetch helpers but is unused: the DeepSeek call itself is a one-off POST, + same as `enhance_title_deepseek()`. Returns None on any failure (network + error, empty text, validation failure).""" + title_s = str(title or "").strip() + text_s = str(full_text or "").strip() + if not title_s or not text_s: + return None + api_key = str(os.environ.get("DEEPSEEK_API_KEY") or "").strip() + if not api_key: + return None + base_url = str(os.environ.get("DEEPSEEK_API_BASE_URL") or "https://api.deepseek.com").strip().rstrip("/") + model = str(os.environ.get("DEEPSEEK_MODEL") or "deepseek-v4-flash").strip() + system_prompt = ( + "你是科技新闻编辑,负责为一篇具体的文章写一句「为什么值得读」的中文推荐语。" + "输出一句中文,40到80个字之间。" + "必须引用原文中的具体事实、数字或细节,讲清楚这篇内容具体讲了什么,不能写空洞的营销话术。" + "不得编造原文之外的数字或事实。" + "原文中的关键实体(公司名、产品名、人名)保留英文原样,不要翻译或音译。" + "只输出这一句推荐语本身,不加引号,不加任何解释或前缀。" + ) + user_content = f"标题:{title_s}\n\n正文:\n{text_s}" + try: + r = requests.post( + f"{base_url}/chat/completions", + headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}, + json={ + "model": model, + "temperature": 0.3, + "messages": [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": user_content}, + ], + }, + timeout=timeout, + ) + if r.status_code != 200: + return None + payload = r.json() + choices = payload.get("choices") if isinstance(payload, dict) else None + if not isinstance(choices, list) or not choices: + return None + content = str(((choices[0] or {}).get("message") or {}).get("content") or "").strip() + content = content.strip("\"'“”「」").strip() + except Exception: + return None + + if not content or not has_cjk(content): + return None + if len(content) < 10 or len(content) > 200: + return None + if content.strip() == title_s.strip(): + return None + + return content + + +def _recommend_reason_summary_is_placeholder(summary: str, title: str) -> bool: + """Heuristic for "this item's summary field isn't real editorial content + and is worth backfilling with fetched full-text": empty, or just a copy + of the title (a common upstream fallback, see `waytoagi`'s + `summary = title` pattern above).""" + s = str(summary or "").strip() + if not s: + return True + return s == str(title or "").strip() + + +def add_recommend_reasons( + items_ai: list[dict[str, Any]], + session: requests.Session, + cache: dict[str, str], + max_new_per_run: int | None = None, +) -> tuple[list[dict[str, Any]], dict[str, str]]: + """Full-text-fetch + DeepSeek-authored, per-item `recommend_reason_zh` + for the already AI-relevance-filtered `items_ai` set (same scope as + `add_title_enhancements()` — deliberately not expanded to the unfiltered + pool, to control fetch/LLM cost). No-ops entirely without a DeepSeek key. + Uses an independent per-run budget (`REASON_ENHANCE_MAX_PER_RUN`) from + title enhancement, since full-text fetch + reasoning is more expensive + per item; shares the same on-disk cache dict/file as title enhancement + (distinct `RECOMMEND_REASON_CACHE_PREFIX` key namespace) for consistency.""" + if not str(os.environ.get("DEEPSEEK_API_KEY") or "").strip(): + return items_ai, cache + + if max_new_per_run is None: + try: + max_new_per_run = int(os.environ.get("REASON_ENHANCE_MAX_PER_RUN") or 30) + except Exception: + max_new_per_run = 30 + max_new_per_run = max(0, max_new_per_run) + + used = 0 + out: list[dict[str, Any]] = [] + for item in items_ai: + new_item = dict(item) + url = normalize_url(str(new_item.get("url") or "")) + title = str( + new_item.get("title_en") or new_item.get("title_original") or new_item.get("title") or "" + ).strip() + cache_key = RECOMMEND_REASON_CACHE_PREFIX + hashlib.sha1(f"{url}|{title}".encode("utf-8")).hexdigest() + + if cache_key in cache: + cached = cache.get(cache_key) or "" + if cached: + new_item["recommend_reason_zh"] = cached + out.append(new_item) + continue + + if not title or used >= max_new_per_run: + out.append(new_item) + continue + + used += 1 + full_text = fetch_full_text_context(session, str(new_item.get("url") or "")) + if not full_text: + cache[cache_key] = "" + out.append(new_item) + continue + + reason = generate_recommend_reason_deepseek(title, full_text) + if reason: + cache[cache_key] = reason + new_item["recommend_reason_zh"] = reason + else: + cache[cache_key] = "" + + if _recommend_reason_summary_is_placeholder(str(new_item.get("summary") or ""), title): + new_item["summary"] = full_text[:500] + + out.append(new_item) + + return out, cache + + +def dedupe_items_by_title_url(items: list[dict[str, Any]], random_pick: bool = True) -> list[dict[str, Any]]: + groups: dict[str, list[dict[str, Any]]] = {} + for item in items: + site_id = str(item.get("site_id") or "").strip().lower() + title = str(item.get("title_original") or item.get("title") or "").strip().lower() + url = normalize_url(str(item.get("url") or "")) + if site_id == "aihubtoday": + key = f"url::{url}" + else: + key = f"{title}||{url}" + groups.setdefault(key, []).append(item) + + out: list[dict[str, Any]] = [] + for values in groups.values(): + if random_pick: + out.append(random.choice(values)) + else: + chosen = min(values, key=source_tier_sort_key) + out.append(chosen) + + out.sort(key=source_tier_sort_key) + return out + + +def suppress_near_duplicate_items( + items: list[dict[str, Any]], + window_hours: float = 6.0, + similarity_threshold: float = 0.9, +) -> list[dict[str, Any]]: + """Collapse near-identical items from the same site (rewritten syndication, + e.g. "推出法案" vs "推出立法") that exact title||url dedup cannot catch. + Keeps the more authoritative copy (tier, then ai_score, then earliest).""" + + def quality(item: dict[str, Any]) -> tuple: + tier_rank = item.get("source_tier_rank") + try: + tier_rank = int(tier_rank) + except Exception: + tier_rank = 99 + try: + score = float(item.get("ai_score") or 0) + except Exception: + score = 0.0 + ts = event_time(item) or datetime.max.replace(tzinfo=UTC) + return (-tier_rank, score, -ts.timestamp()) + + by_site: dict[str, list[dict[str, Any]]] = {} + for item in items: + by_site.setdefault(str(item.get("site_id") or ""), []).append(item) + + dropped_ids: set[str] = set() + for site_items in by_site.values(): + ordered = sorted(site_items, key=lambda x: event_time(x) or datetime.min.replace(tzinfo=UTC)) + kept: list[tuple[dict[str, Any], str, set[str], datetime | None]] = [] + for item in ordered: + title = normalized_story_title(item) + tokens = title_tokens(title) + ts = event_time(item) + if not title_is_mergeable(title): + kept.append((item, title, tokens, ts)) + continue + duplicate_of = None + for kept_entry in reversed(kept[-60:]): + other, other_title, other_tokens, other_ts = kept_entry + if ts and other_ts and abs((ts - other_ts).total_seconds()) / 3600 > window_hours: + continue + if not tokens or not other_tokens: + continue + jaccard = len(tokens & other_tokens) / len(tokens | other_tokens) + if jaccard < 0.5: + continue + if title_similarity(title, other_title) >= similarity_threshold and story_titles_can_merge(title, other_title): + duplicate_of = kept_entry + break + if duplicate_of is None: + kept.append((item, title, tokens, ts)) + continue + other = duplicate_of[0] + if quality(item) > quality(other): + dropped_ids.add(str(other.get("id") or id(other))) + kept[kept.index(duplicate_of)] = (item, title, tokens, ts) + else: + dropped_ids.add(str(item.get("id") or id(item))) + + return [item for item in items if str(item.get("id") or id(item)) not in dropped_ids] + + +def canonical_story_url(raw_url: str) -> str: + normalized = normalize_url(raw_url) + try: + parsed = urlparse(normalized) + except Exception: + return normalized + query_pairs = parse_qsl(parsed.query, keep_blank_values=True) + if query_pairs: + identity_keys = {"id", "item", "p"} + kept = [(k, v) for k, v in query_pairs if k.lower() in identity_keys] + parsed = parsed._replace(query=urlencode(kept, doseq=True)) + return urlunparse(parsed).rstrip("/") + + +def title_tokens(title: str) -> set[str]: + compact = re.sub(r"https?://\S+", " ", str(title or "").lower()) + tokens = re.findall(r"[a-z0-9]+|[\u4e00-\u9fff]{2,}", compact) + return {tok for tok in tokens if tok not in TITLE_STOPWORDS and len(tok) >= 2} + + +def normalized_story_title(item: dict[str, Any]) -> str: + title = str(item.get("title_original") or item.get("title") or "").strip().lower() + if item.get("title_bilingual"): + title = re.sub(r"\s*/\s*.+$", "", title) + return re.sub(r"\s+", " ", title) + + +def title_is_mergeable(title: str) -> bool: + tokens = title_tokens(title) + return len(tokens) >= 4 and len(str(title or "").strip()) >= 18 + + +def title_similarity(a: str, b: str) -> float: + ta = title_tokens(a) + tb = title_tokens(b) + if not ta or not tb: + return 0.0 + jaccard = len(ta & tb) / len(ta | tb) + sequence = SequenceMatcher(None, a.lower(), b.lower()).ratio() + return round(max(sequence, (sequence * 0.6) + (jaccard * 0.4)), 4) + + +def title_entities(title: str) -> tuple[set[str], set[str]]: + lower = str(title or "").lower() + vendors = {canonical for alias, canonical in VENDOR_ALIASES.items() if alias in lower} + models = {re.sub(r"\s+", "-", match.group(1).lower()) for match in MODEL_RE.finditer(lower)} + return vendors, models + + +def story_titles_can_merge(a: str, b: str) -> bool: + vendors_a, models_a = title_entities(a) + vendors_b, models_b = title_entities(b) + if vendors_a and vendors_b and vendors_a.isdisjoint(vendors_b): + return False + if models_a and models_b and models_a.isdisjoint(models_b): + return False + return True + + +def recency_score(record: dict[str, Any], now: datetime, window_hours: int) -> float: + ts = event_time(record) + if not ts: + return 0.0 + age_hours = max(0.0, (now - ts).total_seconds() / 3600) + return max(0.0, min(1.0, (float(window_hours) - age_hours) / max(1.0, float(window_hours)))) + + +def headline_freshness_score(record: dict[str, Any], now: datetime, half_life_hours: float = 48.0) -> float: + ts = event_time(record) + if not ts: + return 0.0 + age_hours = max(0.0, (now - ts).total_seconds() / 3600) + return max(0.0, min(1.0, 0.5 ** (age_hours / max(1.0, half_life_hours)))) + + +def ai_relevance_score(record: dict[str, Any]) -> float: + value = record.get("ai_relevance_score") + if value is None: + value = record.get("ai_score") + if value is None and isinstance(record.get("ai_relevance"), dict): + value = record["ai_relevance"].get("score") + try: + return max(0.0, min(1.0, float(value))) + except Exception: + return 1.0 if record.get("ai_is_related") else 0.0 + + +def add_creator_ranking_fields(record: dict[str, Any], now: datetime) -> dict[str, Any]: + out = dict(record) + metrics = record.get("creator_metrics") if isinstance(record.get("creator_metrics"), dict) else {} + likes = creator_metric_count(metrics.get("likes")) + comments = creator_metric_count(metrics.get("comments")) + collects = creator_metric_count(metrics.get("collects")) + shares = creator_metric_count(metrics.get("shares")) + weighted_engagement = likes + (comments * 2.0) + (collects * 1.5) + (shares * 2.0) + + # Xiaohongshu engagement is smaller in absolute terms than Douyin, so use + # separate fixed log scales instead of pretending raw counts are comparable. + scale = 22.0 if str(record.get("site_id") or "") == "tikhub_xiaohongshu" else 20.0 + heat_score = min(100.0, scale * math.log10(1.0 + weighted_engagement)) + published = event_time(record) + age_hours = (now - published).total_seconds() / 3600 if published else float("inf") + freshness_bonus = CREATOR_FRESHNESS_BONUS_POINTS if 0 <= age_hours <= CREATOR_FRESHNESS_BONUS_HOURS else 0.0 + hot_score = min(100.0, (heat_score * 0.85) + freshness_bonus) + + out["creator_metrics"] = { + "likes": likes, + "comments": comments, + "collects": collects, + "shares": shares, + } + out["creator_engagement_total"] = round(weighted_engagement, 1) + out["creator_heat_score"] = round(heat_score, 1) + out["creator_freshness_bonus"] = round(freshness_bonus, 1) + out["creator_hot_score"] = round(hot_score, 1) + return out + + +def editorial_score(record: dict[str, Any]) -> float: + """External or internal editorial strength used by the headline ranker.""" + value = record.get("aihot_score") + try: + if value is not None: + score = float(value) + return max(0.0, min(1.0, score / 100 if score > 1 else score)) + except Exception: + pass + site_id = str(record.get("site_id") or "") + if site_id == "official_ai": + return 0.9 + if site_id == "aihot": + return 0.78 + if record.get("ai_is_related"): + return max(0.45, ai_relevance_score(record) * 0.72) + return ai_relevance_score(record) * 0.6 + + +def story_id_for_item(item: dict[str, Any]) -> str: + url = canonical_story_url(str(item.get("url") or "")) + title = normalized_story_title(item) + # Include the title alongside the URL so that distinct notes published under + # a shared generic URL (e.g. a wiki hub page) get distinct story ids instead + # of colliding into a single group. + if url and title: + basis = f"{url}\x1f{title}" + else: + basis = url or title or str(item.get("id") or "") + return "story_" + hashlib.sha1(basis.encode("utf-8")).hexdigest()[:12] + + +def calculate_item_importance( + item: dict[str, Any], + now: datetime, + window_hours: int, + duplicate_count: int = 1, +) -> dict[str, Any]: + tier = str(item.get("source_tier") or source_tier_for_site(str(item.get("site_id") or "")).get("source_tier")) + source_score = SOURCE_TIER_IMPORTANCE.get(tier, SOURCE_TIER_IMPORTANCE["other"]) + relevance = ai_relevance_score(item) + recency = headline_freshness_score(item, now) + editorial = editorial_score(item) + heat = min(1.0, max(0, duplicate_count - 1) / 4) + score = (editorial * 0.3) + (source_score * 0.22) + (relevance * 0.2) + (recency * 0.18) + (heat * 0.1) + return { + "score": round(max(0.0, min(1.0, score)), 4), + "breakdown": { + "editorial": round(editorial, 4), + "source_tier": round(source_score, 4), + "ai_relevance": round(relevance, 4), + "recency": round(recency, 4), + "story_heat": round(heat, 4), + }, + } + + +def story_category(score: float, primary_item: dict[str, Any], duplicate_count: int) -> str: + tier = str(primary_item.get("source_tier") or source_tier_for_site(str(primary_item.get("site_id") or "")).get("source_tier")) + if tier == "official": + return "official" + if duplicate_count >= 3: + return "multi_source" + if score >= 0.72: + return "industry" + return "watch" + + +def importance_label(category: str) -> str: + return { + "official": "官方更新", + "multi_source": "多源热议", + "industry": "行业动态", + "watch": "值得关注", + }.get(category, "值得关注") + + +def choose_primary_story_item( + items: list[dict[str, Any]], + now: datetime, + window_hours: int, +) -> dict[str, Any]: + def key(item: dict[str, Any]) -> tuple[int, float, float, str]: + tier_rank = int(source_tier_for_site(str(item.get("site_id") or "")).get("source_tier_rank", 9)) + importance = calculate_item_importance(item, now, window_hours, duplicate_count=len(items))["score"] + ts = event_time(item) + return (tier_rank, -importance, -(ts.timestamp() if ts else 0), str(item.get("title") or "")) + + return min(items, key=key) + + +def story_item_link(item: dict[str, Any]) -> dict[str, Any]: + return { + "id": item.get("id"), + "title": item.get("title_enhanced_zh") or item.get("title_bilingual") or item.get("title"), + "title_zh": item.get("title_enhanced_zh") or item.get("title_zh"), + "title_en": item.get("title_en"), + "title_original": item.get("title_original"), + "summary": item.get("summary"), + "recommend_reason_zh": item.get("recommend_reason_zh"), + "url": item.get("url"), + "source": item.get("source"), + "source_name": item.get("site_name"), + "site_id": item.get("site_id"), + "published_at": item.get("published_at"), + } + + +def story_reasons(primary: dict[str, Any], score: float, duplicate_count: int) -> list[str]: + reasons: list[str] = [] + tier = source_tier_for_site(str(primary.get("site_id") or "")) + if tier["source_tier"] == "official": + reasons.append("official_source") + if duplicate_count >= 2: + reasons.append("multi_source") + if ai_relevance_score(primary) >= 0.8: + reasons.append("high_ai_relevance") + if score >= 0.75: + reasons.append("high_importance") + if not reasons: + reasons.append("recent_ai_signal") + return reasons + + +def build_story_record( + story_id: str, + items: list[dict[str, Any]], + now: datetime, + window_hours: int, +) -> dict[str, Any]: + sorted_items = sorted(items, key=source_tier_sort_key) + primary = choose_primary_story_item(sorted_items, now, window_hours) + importance = calculate_item_importance(primary, now, window_hours, duplicate_count=len(items)) + score = importance["score"] + category = story_category(score, primary, len(items)) + times = [ts for ts in (event_time(item) for item in sorted_items) if ts] + # 与前端 timelineIso 的未来时间防御对齐:错标时区的条目漏到 story 层时, + # earliest_at/latest_at 不得超过当前时间(精选模式排序/展示走的是这两个字段) + story_future_limit = now + timedelta(minutes=10) + times = [ts if ts <= story_future_limit else now for ts in times] + source_refs = [story_item_link(item) for item in sorted_items] + source_names = sorted({str(item.get("source") or item.get("site_name") or "") for item in sorted_items if item.get("source") or item.get("site_name")}) + title = primary.get("title_enhanced_zh") or primary.get("title_bilingual") or primary.get("title") + url = primary.get("url") + return { + "story_id": story_id, + "title": title, + "url": url, + "primary_url": url, + "source": primary.get("source"), + "source_name": primary.get("site_name"), + "sources": source_refs, + "source_count": len(source_refs), + "source_names": source_names, + "items": source_refs, + "item_count": len(sorted_items), + "duplicate_count": len(sorted_items), + "score": score, + "importance": score, + "importance_score": score, + "importance_label": importance_label(category), + "importance_breakdown": importance["breakdown"], + "category": category, + "reasons": story_reasons(primary, score, len(sorted_items)), + "earliest_at": iso(min(times)) if times else None, + "latest_at": iso(max(times)) if times else None, + "primary_item": { + "id": primary.get("id"), + "title": title, + "title_zh": primary.get("title_enhanced_zh") or primary.get("title_zh"), + "title_en": primary.get("title_en"), + "title_original": primary.get("title_original"), + "summary": primary.get("summary"), + "recommend_reason_zh": primary.get("recommend_reason_zh"), + "url": url, + "source": primary.get("source"), + "source_name": primary.get("site_name"), + }, + } + + +def merge_story_items( + items: list[dict[str, Any]], + now: datetime, + window_hours: int, + title_window_hours: int = 6, + title_threshold: float = 0.86, +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + groups: dict[str, list[dict[str, Any]]] = {} + group_titles: dict[str, str] = {} + group_times: dict[str, datetime | None] = {} + group_site_ids: dict[str, str] = {} + canonical_to_story: dict[str, list[str]] = {} + events: list[dict[str, Any]] = [] + + ordered = sorted(items, key=lambda item: event_time(item) or datetime.min.replace(tzinfo=UTC)) + for item in ordered: + item_id = str(item.get("id") or "") + canonical_url = canonical_story_url(str(item.get("url") or "")) + title = normalized_story_title(item) + item_site_id = str(item.get("site_id") or "") + item_time = event_time(item) + story_id: str | None = None + reason = "" + similarity = 0.0 + + if canonical_url: + for candidate_id in canonical_to_story.get(canonical_url, []): + candidate_title = group_titles.get(candidate_id, "") + candidate_site_id = group_site_ids.get(candidate_id, "") + if ( + item_site_id + and candidate_site_id == item_site_id + and title != candidate_title + and title_similarity(title, candidate_title) < title_threshold + ): + # Same-site items sharing a generic/shared URL (e.g. a wiki hub + # page) but with clearly different titles are distinct notes, + # not repeated reports of one event - don't cluster them. + continue + story_id = candidate_id + reason = "canonical_url" + similarity = 1.0 + break + + if story_id is None and title_is_mergeable(title): + for candidate_id, candidate_title in group_titles.items(): + candidate_time = group_times.get(candidate_id) + if item_time and candidate_time: + delta_hours = abs((item_time - candidate_time).total_seconds()) / 3600 + if delta_hours > title_window_hours: + continue + sim = title_similarity(title, candidate_title) + if sim >= title_threshold and story_titles_can_merge(title, candidate_title): + story_id = candidate_id + reason = "title_similarity" + similarity = sim + break + + if story_id is None: + story_id = story_id_for_item(item) + groups[story_id] = [] + group_titles[story_id] = title + group_times[story_id] = item_time + group_site_ids[story_id] = item_site_id + if canonical_url: + canonical_to_story.setdefault(canonical_url, []).append(story_id) + else: + events.append( + { + "story_id": story_id, + "item_id": item_id, + "merged_into": story_id, + "reason": reason, + "similarity": round(similarity, 4), + } + ) + if canonical_url: + bucket = canonical_to_story.setdefault(canonical_url, []) + if story_id not in bucket: + bucket.append(story_id) + + groups.setdefault(story_id, []).append(item) + + stories = [build_story_record(story_id, group_items, now, window_hours) for story_id, group_items in groups.items()] + stories.sort(key=lambda story: (-float(story.get("score") or 0), str(story.get("latest_at") or ""), str(story.get("title") or ""))) + return stories, events + + +BRIEF_SCORE_GATE = 0.72 + + +def story_passes_brief_gate(story: dict[str, Any]) -> bool: + """宁缺毋滥: a story earns a brief slot via multi-source confirmation or a + strong score. Quiet days produce a short (possibly empty) brief instead of + a padded one.""" + try: + sources = int(story.get("source_count") or 1) + except Exception: + sources = 1 + try: + score = float(story.get("score") or 0) + except Exception: + score = 0.0 + return sources >= 2 or score >= BRIEF_SCORE_GATE + + +def select_diverse_stories( + stories: list[dict[str, Any]], + limit: int, + same_source_penalty: float = 0.03, +) -> list[dict[str, Any]]: + """Greedy top-N by score with a per-source decay so one prolific source + cannot fill the brief, plus same-cluster suppression across the whole + window: a story whose title near-duplicates an already picked one is + skipped, so an event reposted hours apart (outside the merge window) + still occupies only one slot.""" + candidates = sorted(stories, key=lambda story: (-float(story.get("score") or 0), str(story.get("title") or ""))) + picked: list[dict[str, Any]] = [] + picked_titles: list[tuple[str, set[str]]] = [] + picked_per_source: dict[str, int] = {} + remaining = list(candidates) + + def near_duplicate_of_picked(story: dict[str, Any]) -> bool: + title = normalized_story_title(story) + if not title_is_mergeable(title): + return False + tokens = title_tokens(title) + for other_title, other_tokens in picked_titles: + if not tokens or not other_tokens: + continue + if len(tokens & other_tokens) / len(tokens | other_tokens) < 0.4: + continue + if title_similarity(title, other_title) >= 0.86 and story_titles_can_merge(title, other_title): + return True + return False + + while remaining and len(picked) < limit: + best_idx = -1 + best_eff = float("-inf") + for idx, story in enumerate(remaining): + source = str(story.get("source") or story.get("source_name") or "") + eff = float(story.get("score") or 0) - same_source_penalty * picked_per_source.get(source, 0) + if eff > best_eff: + best_eff = eff + best_idx = idx + if best_idx < 0: + break + chosen = remaining.pop(best_idx) + if near_duplicate_of_picked(chosen): + continue + source = str(chosen.get("source") or chosen.get("source_name") or "") + picked_per_source[source] = picked_per_source.get(source, 0) + 1 + picked.append(chosen) + picked_titles.append((normalized_story_title(chosen), title_tokens(normalized_story_title(chosen)))) + return picked + + +def build_daily_brief_payload( + stories: list[dict[str, Any]], + generated_at: str, + window_hours: int, + max_items: int = 20, +) -> dict[str, Any]: + gated = [story for story in stories if story_passes_brief_gate(story)] + items = select_diverse_stories(gated, max_items) + return { + "generated_at": generated_at, + "window_hours": window_hours, + "total_items": len(items), + "items": items, + } + + +def build_stories_payload( + stories: list[dict[str, Any]], + generated_at: str, + window_hours: int, +) -> dict[str, Any]: + return { + "generated_at": generated_at, + "window_hours": window_hours, + "total_stories": len(stories), + "stories": stories, + } + + +def build_merge_log_payload(events: list[dict[str, Any]], generated_at: str) -> dict[str, Any]: + return { + "generated_at": generated_at, + "merge_strategy": "url_or_title_similarity_v0_6", + "total_events": len(events), + "events": events, + } + + +def build_creator_hot_items( + archive: dict[str, dict[str, Any]], + now: datetime, + *, + ai_only: bool, +) -> list[dict[str, Any]]: + window_start = now - timedelta(days=CREATOR_HOT_WINDOW_DAYS) + items: list[dict[str, Any]] = [] + for record in archive.values(): + if str(record.get("site_id") or "") not in CREATOR_SITE_IDS: + continue + if not isinstance(record.get("creator_metrics"), dict): + continue + published = event_time(record) + if not published or published < window_start or published > now: + continue + normalized = dict(record) + normalized["title"] = maybe_fix_mojibake(str(normalized.get("title") or "")) + normalized["source"] = maybe_fix_mojibake(normalize_source_for_display( + str(normalized.get("site_id") or ""), + str(normalized.get("source") or ""), + str(normalized.get("url") or ""), + )) + normalized = add_ai_relevance_fields(normalized) + if ai_only and not normalized.get("ai_is_related", is_ai_related_record(normalized)): + continue + normalized = add_source_tier_fields(normalized) + items.append(add_creator_ranking_fields(normalized, now)) + + deduped = suppress_near_duplicate_items(dedupe_items_by_title_url(items, random_pick=False)) + deduped.sort( + key=lambda item: ( + float(item.get("creator_hot_score") or 0), + event_time(item) or datetime.min.replace(tzinfo=UTC), + ), + reverse=True, + ) + return deduped + + +def build_latest_payloads(latest_payload: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]: + """Split initial AI payload from bulky all-mode lists for lazy browser loading.""" + slim_payload = dict(latest_payload) + all_payload = { + "generated_at": latest_payload.get("generated_at"), + "window_hours": latest_payload.get("window_hours"), + "topic_filter": latest_payload.get("topic_filter"), + "ai_relevance_threshold": latest_payload.get("ai_relevance_threshold"), + "total_items_raw": latest_payload.get("total_items_raw"), + "total_items_all_mode": latest_payload.get("total_items_all_mode"), + "items_all": latest_payload.get("items_all", []), + "items_all_raw": latest_payload.get("items_all_raw", []), + } + slim_payload.pop("items_all", None) + slim_payload.pop("items_all_raw", None) + slim_payload["all_mode_data_url"] = "data/latest-24h-all.json" + slim_payload["stories_data_url"] = "data/stories-merged.json" + return slim_payload, all_payload + + +def main() -> int: + parser = argparse.ArgumentParser(description="Aggregate AI news updates from multiple sources") + parser.add_argument("--output-dir", default="data", help="Directory for output JSON files") + parser.add_argument("--window-hours", type=int, default=24, help="24h window size") + parser.add_argument("--archive-days", type=int, default=21, help="Keep archive for N days") + parser.add_argument("--translate-max-new", type=int, default=80, help="Max new EN->ZH title translations per run") + parser.add_argument( + "--translate-max-new-broad", + type=int, + default=30, + help="Max new EN->ZH title translations per run for the broad all-items pool (independent from --translate-max-new)", + ) + parser.add_argument("--rss-opml", default="", help="Optional OPML file path to include RSS sources") + parser.add_argument("--rss-max-feeds", type=int, default=0, help="Optional max OPML RSS feeds to fetch (0 means all)") + args = parser.parse_args() + + now = utc_now() + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + + archive_path = output_dir / "archive.json" + latest_path = output_dir / "latest-24h.json" + latest_all_path = output_dir / "latest-24h-all.json" + latest_all_raw_path = output_dir / "latest-24h-all-raw.json" + status_path = output_dir / "source-status.json" + service_status_path = output_dir / "service-status.json" + daily_brief_path = output_dir / "daily-brief.json" + stories_merged_path = output_dir / "stories-merged.json" + merge_log_path = output_dir / "merge-log.json" + waytoagi_path = output_dir / "waytoagi-7d.json" + title_cache_path = output_dir / "title-zh-cache.json" + email_digest_path = output_dir / AGENTMAIL_DIGEST_FILE + paid_source_state_path = output_dir / PAID_SOURCE_STATE_FILE + + archive = load_archive(archive_path) + paid_source_state = load_paid_source_state(paid_source_state_path) + + session = create_session() + service_status_payload = fetch_service_status(session, now) + raw_items, statuses = collect_all(session, now) + rss_feed_statuses: list[dict[str, Any]] = [] + email_digest_payload, agentmail_status = maybe_fetch_agentmail_digest( + session, + generated_at=iso(now), + after=iso(now - timedelta(hours=args.window_hours)), + window_hours=args.window_hours, + ) + if agentmail_status.get("enabled"): + agentmail_items = agentmail_digest_items_to_raw_items(email_digest_payload or {}) + email_items = (email_digest_payload or {}).get("items") + if not isinstance(email_items, list): + email_items = [] + agentmail_status["public_url_count"] = sum(1 for item in email_items if isinstance(item, dict) and item.get("public_url")) + agentmail_status["radar_item_count"] = len(agentmail_items) + if agentmail_status.get("include_in_radar") and agentmail_items: + raw_items.extend(agentmail_items) + statuses.append( + { + "site_id": "agentmail", + "site_name": "AgentMail", + "ok": bool(agentmail_status.get("ok")) if agentmail_status.get("ok") is not None else True, + "item_count": len(agentmail_items) if agentmail_status.get("include_in_radar") else 0, + "duration_ms": 0, + "error": agentmail_status.get("error"), + "skipped": not bool(agentmail_status.get("include_in_radar")), + "skip_reason": None if agentmail_status.get("include_in_radar") else "email_digest_not_included_in_radar", + } + ) + x_api_items, x_api_status = maybe_fetch_x_api_updates(session, now) + if x_api_status.get("enabled"): + raw_items.extend(x_api_items) + statuses.append( + { + "site_id": "xapi", + "site_name": "X API", + "ok": bool(x_api_status.get("ok")) if x_api_status.get("ok") is not None else True, + "item_count": int(x_api_status.get("item_count") or 0), + "duration_ms": 0, + "error": x_api_status.get("error"), + "skipped": bool(x_api_status.get("skipped")), + "skip_reason": x_api_status.get("skip_reason"), + } + ) + socialdata_items, socialdata_status = maybe_fetch_socialdata_updates(session, now, paid_source_state) + update_paid_source_state(paid_source_state, "socialdata", socialdata_status, now) + sync_paid_source_status_timestamps(socialdata_status, paid_source_state, "socialdata") + if socialdata_status.get("enabled"): + raw_items.extend(socialdata_items) + statuses.append( + { + "site_id": "socialdata_x", + "site_name": "SocialData X", + "ok": bool(socialdata_status.get("ok")) if socialdata_status.get("ok") is not None else True, + "item_count": int(socialdata_status.get("item_count") or 0), + "duration_ms": 0, + "error": socialdata_status.get("error"), + "skipped": bool(socialdata_status.get("skipped")), + "skip_reason": socialdata_status.get("skip_reason"), + } + ) + tikhub_items, tikhub_status = maybe_fetch_tikhub_updates(session, now, paid_source_state) + update_paid_source_state(paid_source_state, "tikhub", tikhub_status, now) + sync_paid_source_status_timestamps(tikhub_status, paid_source_state, "tikhub") + if tikhub_status.get("enabled"): + raw_items.extend(tikhub_items) + tikhub_counts: dict[str, int] = {} + for item in tikhub_items: + tikhub_counts[item.site_id] = tikhub_counts.get(item.site_id, 0) + 1 + for site_id, site_name in ( + ("tikhub_douyin", "TikHub Douyin"), + ("tikhub_xiaohongshu", "TikHub Xiaohongshu"), + ): + if site_id.split("_", 1)[1] not in set(tikhub_status.get("platforms") or []): + continue + statuses.append( + { + "site_id": site_id, + "site_name": site_name, + "ok": bool(tikhub_status.get("ok")) if tikhub_status.get("ok") is not None else True, + "item_count": tikhub_counts.get(site_id, 0), + "duration_ms": 0, + "error": tikhub_status.get("error"), + "skipped": bool(tikhub_status.get("skipped")), + "skip_reason": tikhub_status.get("skip_reason"), + } + ) + + waytoagi_started = time.perf_counter() + try: + waytoagi_payload = fetch_waytoagi_recent_7d(session, now, WAYTOAGI_DEFAULT) + waytoagi_items = waytoagi_updates_to_raw_items(waytoagi_payload, now) + raw_items.extend(waytoagi_items) + statuses.append( + { + "site_id": "waytoagi", + "site_name": "WaytoAGI", + "ok": True, + "item_count": len(waytoagi_items), + "duration_ms": int((time.perf_counter() - waytoagi_started) * 1000), + "error": None, + } + ) + except Exception as exc: + waytoagi_payload = { + "generated_at": iso(now), + "timezone": "Asia/Shanghai", + "root_url": WAYTOAGI_DEFAULT, + "history_url": None, + "window_days": 7, + "count_7d": 0, + "updates_7d": [], + "warning": "WaytoAGI 近7日更新抓取失败", + "has_error": True, + "error": str(exc), + } + statuses.append( + { + "site_id": "waytoagi", + "site_name": "WaytoAGI", + "ok": False, + "item_count": 0, + "duration_ms": int((time.perf_counter() - waytoagi_started) * 1000), + "error": str(exc), + } + ) + + if args.rss_opml: + opml_path = Path(args.rss_opml).expanduser() + if opml_path.exists(): + rss_items, rss_summary_status, rss_feed_statuses = fetch_opml_rss( + now, + opml_path, + max_feeds=max(0, int(args.rss_max_feeds)), + ) + raw_items.extend(rss_items) + statuses.append(rss_summary_status) + else: + statuses.append( + { + "site_id": "opmlrss", + "site_name": "OPML RSS", + "ok": False, + "item_count": 0, + "duration_ms": 0, + "error": f"OPML not found: {opml_path}", + "feed_count": 0, + "ok_feed_count": 0, + "failed_feed_count": 0, + } + ) + + seen_this_run: set[str] = set() + + for raw in raw_items: + title = raw.title.strip() + url = normalize_url(raw.url) + if not title or not url: + continue + if not url.startswith("http"): + continue + + item_id = make_item_id(raw.site_id, raw.source, title, url) + seen_this_run.add(item_id) + + existing = archive.get(item_id) + if existing is None: + archive[item_id] = { + "id": item_id, + "site_id": raw.site_id, + "site_name": raw.site_name, + "source": raw.source, + "title": title, + "url": url, + "published_at": iso(raw.published_at), + "first_seen_at": iso(now), + "last_seen_at": iso(now), + } + apply_public_raw_meta(archive[item_id], raw) + else: + existing["site_id"] = raw.site_id + existing["site_name"] = raw.site_name + existing["source"] = raw.source + existing["title"] = title + existing["url"] = url + if raw.published_at: + # OPML RSS may fix previously wrong publish times; allow overwrite. + if raw.site_id == "opmlrss" or not existing.get("published_at"): + existing["published_at"] = iso(raw.published_at) + existing["last_seen_at"] = iso(now) + apply_public_raw_meta(existing, raw) + + # Prune old archive + keep_after = now - timedelta(days=args.archive_days) + pruned: dict[str, dict[str, Any]] = {} + for item_id, record in archive.items(): + ts = ( + parse_iso(record.get("last_seen_at")) + or parse_iso(record.get("published_at")) + or parse_iso(record.get("first_seen_at")) + or now + ) + if ts >= keep_after: + pruned[item_id] = record + archive = pruned + + # 24h view + window_start = now - timedelta(hours=args.window_hours) + latest_items_all_raw: list[dict[str, Any]] = [] + for record in archive.values(): + ts = event_time(record) + if not ts: + continue + if ts >= window_start: + normalized = dict(record) + normalized["title"] = maybe_fix_mojibake(str(normalized.get("title") or "")) + normalized["source"] = maybe_fix_mojibake(normalize_source_for_display( + str(normalized.get("site_id") or ""), + str(normalized.get("source") or ""), + str(normalized.get("url") or ""), + )) + if str(normalized.get("site_id") or "") == "aihubtoday" and is_hubtoday_placeholder_title( + str(normalized.get("title") or "") + ): + continue + normalized = add_ai_relevance_fields(normalized) + normalized = add_source_tier_fields(normalized) + latest_items_all_raw.append(normalized) + + latest_items_all_raw = normalize_aihubtoday_records(latest_items_all_raw) + + latest_items_all_raw.sort(key=lambda x: event_time(x) or datetime.min.replace(tzinfo=UTC), reverse=True) + # Broad-AI filter: keep items whose pre-computed ai_score clears the floor + latest_items_all = [record for record in latest_items_all_raw if record.get("ai_score", 0) >= AI_BROAD_RELEVANCE_FLOOR] + latest_items = [record for record in latest_items_all_raw if record.get("ai_is_related", is_ai_related_record(record))] + title_cache = load_title_zh_cache(title_cache_path) + latest_items, latest_items_all, title_cache = add_bilingual_fields( + latest_items, + latest_items_all, + session, + title_cache, + max_new_translations=max(0, args.translate_max_new), + max_new_translations_all=max(0, args.translate_max_new_broad), + ) + creator_items_ai = build_creator_hot_items(archive, now, ai_only=True) + creator_items_all = build_creator_hot_items(archive, now, ai_only=False) + creator_items_ai, creator_items_all, title_cache = add_bilingual_fields( + creator_items_ai, + creator_items_all, + session, + title_cache, + max_new_translations=0, + ) + latest_items_ai_dedup = suppress_near_duplicate_items(dedupe_items_by_title_url(latest_items, random_pick=False)) + latest_items_all_dedup = dedupe_items_by_title_url(latest_items_all, random_pick=True) + latest_items_all_raw_dedup = dedupe_items_by_title_url(latest_items_all_raw, random_pick=True) + latest_items_ai_dedup, title_cache = add_title_enhancements(latest_items_ai_dedup, session, title_cache) + latest_items_ai_dedup, title_cache = add_recommend_reasons(latest_items_ai_dedup, session, title_cache) + stories, merge_events = merge_story_items(latest_items_ai_dedup, now=now, window_hours=args.window_hours) + generated_at = iso(now) + daily_brief_payload = build_daily_brief_payload(stories, generated_at=generated_at, window_hours=args.window_hours) + stories_merged_payload = build_stories_payload(stories, generated_at=generated_at, window_hours=args.window_hours) + merge_log_payload = build_merge_log_payload(merge_events, generated_at=generated_at) + + # site stats + site_stat: dict[str, dict[str, Any]] = {} + raw_count_by_site: dict[str, int] = {} + for record in latest_items_all_raw: + sid = record["site_id"] + raw_count_by_site[sid] = raw_count_by_site.get(sid, 0) + 1 + + site_name_by_id: dict[str, str] = {} + for record in latest_items_all_raw: + site_name_by_id[record["site_id"]] = record["site_name"] + for s in statuses: + sid = s["site_id"] + if sid not in site_name_by_id: + site_name_by_id[sid] = s.get("site_name") or sid + + for record in latest_items_ai_dedup: + sid = record["site_id"] + if sid not in site_stat: + site_stat[sid] = { + "site_id": sid, + "site_name": record["site_name"], + "count": 0, + "raw_count": raw_count_by_site.get(sid, 0), + } + site_stat[sid]["count"] += 1 + + for sid, site_name in site_name_by_id.items(): + if sid in site_stat: + continue + site_stat[sid] = { + "site_id": sid, + "site_name": site_name, + "count": 0, + "raw_count": raw_count_by_site.get(sid, 0), + } + + latest_payload = { + "generated_at": generated_at, + "window_hours": args.window_hours, + "total_items": len(latest_items_ai_dedup), + "total_items_ai_raw": len(latest_items), + "total_items_raw": len(latest_items_all_raw), + "total_items_all_mode": len(latest_items_all_dedup), + "topic_filter": "ai_relevance_scoring_v0_4", + "ai_relevance_threshold": 0.65, + "archive_total": len(archive), + "site_count": len(site_stat), + "source_count": len({f"{i['site_id']}::{i['source']}" for i in latest_items_ai_dedup}), + "site_stats": sorted(site_stat.values(), key=lambda x: x["count"], reverse=True), + "creator_window_days": CREATOR_HOT_WINDOW_DAYS, + "creator_ranking": "engagement_85_fresh_24h_bonus_15_v1", + "creator_items_ai": creator_items_ai, + "creator_items_all": creator_items_all, + "items": latest_items_ai_dedup, + "items_ai": latest_items_ai_dedup, + "items_all_raw": latest_items_all, + "items_all": latest_items_all_dedup, + } + + archive_payload = { + "generated_at": generated_at, + "total_items": len(archive), + "items": sorted( + archive.values(), + key=lambda x: parse_iso(x.get("last_seen_at")) or datetime.min.replace(tzinfo=UTC), + reverse=True, + ), + } + + empty_advanced_sources = [ + { + "site_id": s["site_id"], + "site_name": s.get("site_name") or s["site_id"], + "reason": "connected_no_matching_results", + } + for s in statuses + if s.get("ok") + and int(s.get("item_count") or 0) == 0 + and str(s.get("site_id") or "") in {"xapi", "socialdata_x", "tikhub_douyin", "tikhub_xiaohongshu"} + and not s.get("skipped") + ] + empty_advanced_site_ids = {item["site_id"] for item in empty_advanced_sources} + + status_payload = { + "generated_at": generated_at, + "sites": statuses, + "successful_sites": sum(1 for s in statuses if s["ok"]), + "failed_sites": [s["site_id"] for s in statuses if not s["ok"]], + "zero_item_sites": [ + s["site_id"] + for s in statuses + if s.get("ok") + and int(s.get("item_count") or 0) == 0 + and not s.get("skipped") + and str(s.get("site_id") or "") not in empty_advanced_site_ids + ], + "empty_advanced_sources": empty_advanced_sources, + "fetched_raw_items": len(raw_items), + "items_before_topic_filter": len(latest_items_all_raw), + "items_in_24h": len(latest_items_ai_dedup), + "rss_opml": { + "enabled": bool(args.rss_opml), + "path": "configured" if args.rss_opml else None, + "feed_total": len(rss_feed_statuses), + "effective_feed_total": sum(1 for s in rss_feed_statuses if not s.get("skipped")), + "ok_feeds": sum(1 for s in rss_feed_statuses if s["ok"] and not s.get("skipped")), + "failed_feeds": [s.get("effective_feed_url") or s["feed_url"] for s in rss_feed_statuses if not s["ok"]], + "zero_item_feeds": [ + s.get("effective_feed_url") or s["feed_url"] + for s in rss_feed_statuses + if s["ok"] and not s.get("skipped") and int(s.get("item_count") or 0) == 0 + ], + "skipped_feeds": [ + {"feed_url": s["feed_url"], "reason": s.get("skip_reason")} + for s in rss_feed_statuses + if s.get("skipped") + ], + "replaced_feeds": [ + {"from": s["feed_url"], "to": s.get("effective_feed_url")} + for s in rss_feed_statuses + if s.get("replaced") and s.get("effective_feed_url") + ], + "feeds": rss_feed_statuses, + }, + "agentmail": agentmail_status, + "x_api": x_api_status, + "socialdata": socialdata_status, + "tikhub": tikhub_status, + } + + latest_payload, latest_all_payload = build_latest_payloads(latest_payload) + + # Developer-only raw payload (all records, no AI filtering) + latest_all_raw_payload = { + "generated_at": latest_all_payload.get("generated_at"), + "window_hours": latest_all_payload.get("window_hours"), + "topic_filter": latest_all_payload.get("topic_filter"), + "ai_relevance_threshold": latest_all_payload.get("ai_relevance_threshold"), + "total_items_raw": len(latest_items_all_raw), + "total_items_all_mode": len(latest_items_all_raw_dedup), + "items_all": latest_items_all_raw_dedup, + "items_all_raw": latest_items_all_raw, + } + + latest_path.write_text(json.dumps(sanitize_public_payload(latest_payload), ensure_ascii=False, indent=2), encoding="utf-8") + latest_all_path.write_text(json.dumps(sanitize_public_payload(latest_all_payload), ensure_ascii=False, separators=(",", ":")), encoding="utf-8") + latest_all_raw_path.write_text(json.dumps(sanitize_public_payload(latest_all_raw_payload), ensure_ascii=False, separators=(",", ":")), encoding="utf-8") + daily_brief_path.write_text( + json.dumps(sanitize_public_payload(daily_brief_payload), ensure_ascii=False, indent=2), + encoding="utf-8", + ) + stories_merged_path.write_text( + json.dumps(sanitize_public_payload(stories_merged_payload), ensure_ascii=False, separators=(",", ":")), + encoding="utf-8", + ) + merge_log_path.write_text( + json.dumps(sanitize_public_payload(merge_log_payload), ensure_ascii=False, indent=2), + encoding="utf-8", + ) + archive_path.write_text( + json.dumps(sanitize_public_payload(archive_payload), ensure_ascii=False, separators=(",", ":")), + encoding="utf-8", + ) + status_path.write_text(json.dumps(sanitize_public_payload(status_payload), ensure_ascii=False, indent=2), encoding="utf-8") + service_status_path.write_text( + json.dumps(sanitize_public_payload(service_status_payload), ensure_ascii=False, indent=2), + encoding="utf-8", + ) + paid_source_state_path.write_text( + json.dumps(sanitize_public_payload(paid_source_state), ensure_ascii=False, indent=2), + encoding="utf-8", + ) + if email_digest_payload is not None: + email_digest_path.write_text( + json.dumps(sanitize_public_payload(email_digest_payload), ensure_ascii=False, indent=2), + encoding="utf-8", + ) + waytoagi_path.write_text(json.dumps(sanitize_public_payload(waytoagi_payload), ensure_ascii=False, indent=2), encoding="utf-8") + title_cache_path.write_text(json.dumps(sanitize_public_payload(title_cache), ensure_ascii=False, indent=2), encoding="utf-8") + + print(f"Wrote: {latest_path} ({len(latest_items)} items)") + print(f"Wrote: {latest_all_path} ({len(latest_items_all_dedup)} all-mode items)") + print(f"Wrote: {latest_all_raw_path} ({len(latest_items_all_raw_dedup)} raw items, dev-only)") + print(f"Wrote: {daily_brief_path} ({daily_brief_payload.get('total_items', 0)} brief items)") + print(f"Wrote: {stories_merged_path} ({stories_merged_payload.get('total_stories', 0)} stories)") + print(f"Wrote: {merge_log_path} ({len(merge_events)} merge events)") + print(f"Wrote: {archive_path} ({len(archive)} items)") + print(f"Wrote: {status_path}") + print(f"Wrote: {service_status_path} ({service_status_payload.get('active_count', 0)} active incidents)") + print(f"Wrote: {paid_source_state_path}") + if email_digest_payload is not None: + print(f"Wrote: {email_digest_path} ({email_digest_payload.get('total_messages', 0)} email items)") + print(f"Wrote: {waytoagi_path} ({waytoagi_payload.get('count_7d', 0)} items)") + print(f"Wrote: {title_cache_path} ({len(title_cache)} entries)") + + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/skills/ai-news-radar/site.webmanifest b/skills/ai-news-radar/site.webmanifest new file mode 100644 index 0000000..55b47c1 --- /dev/null +++ b/skills/ai-news-radar/site.webmanifest @@ -0,0 +1,24 @@ +{ + "name": "AI News Radar", + "short_name": "AI Radar", + "description": "Curated AI and technology signals from the past 24 hours.", + "start_url": "./", + "scope": "./", + "display": "standalone", + "background_color": "#f6f6f2", + "theme_color": "#f6f6f2", + "icons": [ + { + "src": "./assets/icons/icon-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "any maskable" + }, + { + "src": "./assets/icons/icon-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "any maskable" + } + ] +} diff --git a/skills/ai-news-radar/translation-glossary.txt b/skills/ai-news-radar/translation-glossary.txt new file mode 100644 index 0000000..61e6dcb --- /dev/null +++ b/skills/ai-news-radar/translation-glossary.txt @@ -0,0 +1,41 @@ +# 翻译词表 —— fork 后直接改这个文件,管线自动生效 / Translation glossary — edit this file in your fork +# +# 两种规则 / Two kinds of rules: +# 术语保护(一行一个词):翻译时保留原文,不翻译 +# Protected term (one per line): kept verbatim, never translated +# 修正规则(bad => good [@原文含关键词]):对译文做替换;@ 后是防误伤条件, +# 只有英文原标题包含该关键词才执行替换,可省略 +# Repair rule (bad => good [@keyword]): replace bad with good in the translated +# title; the optional @keyword guard means the replacement only fires when the +# English source title contains that keyword (case-insensitive) +# +# 以 # 开头的行和空行会被忽略 / Lines starting with # and blank lines are ignored + +## 保护术语 / Protected terms +Claude +Claude Code +LLM +Fable 5 +Mythos 5 +Opus +Sonnet +Haiku +GPT +Gemini +Copilot +Cursor +Perplexity +Hugging Face +Transformer +OpenAI +Anthropic +DeepSeek +Agent +Token + +## 修正规则 / Repair rules +法学硕士(LLM) => LLM +法学硕士(LLM) => LLM +法学硕士 => LLM @LLM +克劳德 => Claude @Claude +神鬼寓言 => Fable @Fable diff --git a/skills/amap-jsapi-skill/ADMISSION.md b/skills/amap-jsapi-skill/ADMISSION.md new file mode 100644 index 0000000..ea81432 --- /dev/null +++ b/skills/amap-jsapi-skill/ADMISSION.md @@ -0,0 +1,74 @@ +# AMap JSAPI 1.1.1 complete ZIP admission — 2026-11-24 + +Reviewer: mashagua. Availability: installable. This is a manual package/source review, not a live-map acceptance test or a security certification. + +## Artifact and completeness + +URL: https://clawhub.ai/api/v1/download?slug=amap-jsapi-skill&version=1.1.1&ownerHandle=lbs-amap + +ZIP SHA-256: `9468743ee18dbe1704e8a98f47f6628d6a4e6acec30a05f0b8f59a07603d011f`. +The version URL is paired with this digest rather than assumed permanently immutable. The live download matches it. The unchanged archive contains 36 regular files, 390,853 unpacked bytes; the largest is 45,586 bytes. All are Markdown or JSON. No symlinks, path traversal, binaries or standalone executable scripts were found. `SKILL.md` is at ZIP root, so `source.path` is omitted and the schema field is `source.repoUrl` (not `url`). + +All 33 unique referenced Markdown paths (21 Markdown links plus 12 inline references) exist, including `references/security.md`. Every file size and SHA-256 matches the publisher's owner-qualified 1.1.1 manifest. The 7,979-byte SKILL file keeps the previous single-file digest `cf2f06cc5abf5e41a626f823c50575ab52c81aecbceca5abd4e69d56ca5c5d75`, but the newly reviewed installation artifact is the full ZIP digest above, not the old single-file response. + +## License decision and preserved discrepancy + +- Actual `SKILL.md:5`: `license: MIT`. +- Actual `skill-card.md:13`: `MIT-0`. +- ClawHub owner-qualified 1.1.1 version metadata: `license: MIT-0`. +- There is no standalone LICENSE, COPYING or NOTICE file in the 36-file archive. Current market main declared MIT without an evidencePath. + +This admission follows the actual SKILL MIT declaration, conservatively retaining attribution/notice obligations rather than advertising the MIT-0 waiver. `license.evidencePath` and `compliance.licenseEvidencePath` are the real upstream `SKILL.md`; `compliance.noticePath` points to the actual `skill-card.md` so its differing declaration is not hidden. This is an explicit reviewed declaration-based decision, NOT a claim that the publisher clarified the inconsistency, issued dual licensing, or supplied standalone MIT text. No upstream file is modified and no license file or copyright grant is invented. Keep the whole package and its existing author/source/license signals intact; publisher clarification would improve certainty. + +中文:按 SKILL 实际声明的 MIT 审核并保留署名义务;完整披露 skill-card/注册信息的 MIT-0 差异及无独立 LICENSE 的事实,不声称上游已经澄清或授予双许可。市场收录许可不替代高德 SDK、地图数据和外部服务条款。 + +## Static security findings and limits + +All 36 text files were included in the content/URL/instruction scan and per-file manifest verification. No silent telemetry endpoint/instruction (including the GitHub 1.1.0 log/init requirement), credential harvesting, malicious executable payload, or instruction to override host safety was identified in this ZIP. No upstream instructions or example requests were executed during review. + +The docs do contain normal SDK/API/proxy and geolocation examples, external map/demo resources, legacy HTTP/JSONP examples, and an upstream public demonstration key literal in an API example. That literal was NOT validated, used, or copied into this review; do not treat upstream examples as a usable user credential or copy them into production. Supply the user's own Key via private host configuration, use HTTPS and a secure production proxy, review generated HTML/data handling, and obtain consent for location data. Other example services/resources have their own availability and terms. Static review does not prove all generated applications safe, grant API access, or establish zero unknown vulnerabilities. + +## Runtime prerequisites + +Require the user's own AMap Web JSAPI Key plus securityJsCode or a correctly configured serviceHost backend proxy; respect authorized domains, service terms, quotas and possible billing. The docs are complete, but the skill is not a bundled SDK entitlement, account, key or paid service. A real authenticated map was not initialized in this audit. Missing user authorization is distinct from the now-fixed missing-document packaging defect. + +## Exact file manifest + +| Path | Bytes | SHA-256 | +|---|---:|---| +| SKILL.md | 7979 | cf2f06cc5abf5e41a626f823c50575ab52c81aecbceca5abd4e69d56ca5c5d75 | +| _meta.json | 136 | e7fb03efc0c0675b8311c834b0716964f050929614ee26ec379bc8be67e8f0dc | +| references/api/common.md | 35194 | eab7a2608f190b40b4f189309f91cb0ccdc211e61971cbd2e46d2b66b9053e75 | +| references/api/context-menu.md | 1116 | 62593b9f38bf1affd6da804739ec485e6ea0c494dc9f30463f7fe053cd92035e | +| references/api/controls.md | 8868 | d61be8eebe092f4ff6b99d1210ee418d50d9445ef8e10ac3cdadb91c82053a14 | +| references/api/events.md | 2359 | 05d077f4367ccfe1e8fb38503231a9434ab30b6ca084424441605da9871ecf43 | +| references/api/foundation.md | 5655 | c105059b808ec4dc796781982b03e68e3d17dcf8e0bb106624c0802b4a85ad48 | +| references/api/geocoder.md | 4189 | 2e6c77590acfd357af40d170ac4f46f7338c43524195b40525975a49a1e3e729 | +| references/api/geolocation.md | 5248 | 46e3bd52d43049f28ce43684120de8b8ff56515d31670d4b2ebff5ea5ef95a1c | +| references/api/info-window.md | 2754 | 5d717c8ba07dd657a12bc36b6519213b0403428af81b6372d978c75600b5498a | +| references/api/layers-custom.md | 20361 | b13cd4e4e31a0cd5e615c59ab8cf75db738192593218993eb2753151da498ad5 | +| references/api/layers-official.md | 25287 | 66657dba0467f9869c2f11235777fb3c86fbe16236952ae5685ae8c73ee3d68d | +| references/api/layers-standard.md | 13607 | 085cb25c707dfd3b9eefd62681f12c553718fc263ba6a65b0f3fc6304eab3d3e | +| references/api/map.md | 20866 | 8972c0614ced623539ef3edcd4854e36be4e785c050baae292e2d29ae996183a | +| references/api/marker.md | 45586 | 09fe0f126bea09e0dc9c8be329d3dac68a2576a53784a808cb9c5a0f8606f00c | +| references/api/overlay-group.md | 4388 | 7c627086fad1315a5b358997f76dcbb0c7dd7c2e955f195e84e4811c338b2fb3 | +| references/api/routing.md | 39883 | 6591c534638236b53714b845e154a3c8b4bcda6946208d6d1693402008760751 | +| references/api/search.md | 14044 | be58063affb1e6a3484bb0abed454d4cd108d2fc70a8c498dcd8d8e26a182e63 | +| references/api/services-other.md | 12583 | 6f016749505379b6a759ce26ff54bfeb2d9fe01c6ae873db13a872ac4cd24745 | +| references/api/services.md | 1907 | fdfb7f17937030ba8534bc2da355299c1fe22cf4e5d1961ec0df2c9a3d628ba4 | +| references/api/tools.md | 9854 | 32ff52bf9f5de92286e1c145ac1b5403bcedfe3c0c897114d055aabf3b2427b8 | +| references/api/vector-graphics.md | 33442 | b143e76a77d68c71051af36ddd6f88b52b20e2d6fa9f893bb3dbb7a1dfcadb1a | +| references/context-menu.md | 1534 | f907bfb8424516cb648fc2092ac5b198505685a9cf0bcd48be7fc348ced2b395 | +| references/custom-layers.md | 6118 | 6e815d5723197566a8a52cca945f2b82cdb01c5fc42e71a8d143d0c71edcef89 | +| references/events.md | 4443 | b8c35746ee6e914f440566ea1e1750de08d070f18184d960923833ba275d5209 | +| references/geocoder.md | 4495 | d2b8b23cf892fbe46ec1352d797b8515fb904fcbb23cff9f59d4e172e135b6e6 | +| references/info-window.md | 7568 | cb5999c377086929ce2c5ea30edb7a1482ae0a161ae23f01f825e47b34d54aed | +| references/layers.md | 1874 | c6ea853a6cbb77cc617e7e246db5213b80c07ac07428d43a2bd31b69cf738a8b | +| references/map-init.md | 6623 | 0f40e339dfa7d1af64af4fb04d8be4cf9ad318bd6ae67ecaa94638fc705818e3 | +| references/marker.md | 8198 | d2439c94534498a17638a3b2b86a2465ac45c8d538c65688b97708310e8f952a | +| references/routing.md | 15336 | 3d865324bbc08eab0025bebac2d6a77079d781efc4517415afba156bab9a6a0a | +| references/search.md | 2640 | c4d0286175077612d0c66f569af5a1a2bc804219105284002f0d53f200065c0f | +| references/security.md | 5665 | b9525f3ae4aab76cf1c0cba6656c9b04abbd6ca4c750872c8c2d34434663388e | +| references/vector-graphics.md | 5073 | a60ae8b97099861d14765c51d8f974270dda8efffeefb2e6f0501319a435504b | +| references/view-control.md | 2835 | 28635775c63963903f2231329e113a376a20d253163c8cb2e1888d9a7c99aad5 | +| skill-card.md | 3145 | 879e21daf4c840684c8d13c438f17655907c97f9a357ab9c68a5d78679eb4a25 | diff --git a/skills/amap-jsapi-skill/catalog-metadata.v1.json b/skills/amap-jsapi-skill/catalog-metadata.v1.json index 2b3f505..2856168 100644 --- a/skills/amap-jsapi-skill/catalog-metadata.v1.json +++ b/skills/amap-jsapi-skill/catalog-metadata.v1.json @@ -10,11 +10,11 @@ "i18n": { "en-US": { "name": "AMap JSAPI Skill", - "summary": "AMap JSAPI v2.0 (WebGL) development skill covering map lifecycle, security config, 3D views, overlays and LBS services" + "summary": "Complete ClawHub 1.1.1 ZIP: 36 files including all 33 reference docs and the security guide. Requires your AMap Web JSAPI Key and securityJsCode or serviceHost proxy; AMap quotas and billing apply." }, "zh-CN": { "name": "高德地图 JSAPI 技能", - "summary": "高德地图 JSAPI v2.0(WebGL)开发技能,涵盖地图生命周期、安全配置、3D 视图、覆盖物绘制与 LBS 服务集成" + "summary": "ClawHub 1.1.1 完整 ZIP:36 文件,含全部 33 个引用文档和安全指南。需自备高德 Web JSAPI Key、安全密钥或 serviceHost 代理;适用高德配额及收费条款。" } }, "category": "development", @@ -30,46 +30,76 @@ "timestamps": { "catalogUpdatedAt": { "state": "known", - "value": "2026-08-30T18:00:09Z", - "precision": "second" + "value": "2026-11-24", + "precision": "day" }, "releasePublishedAt": { "state": "unknown" }, "reviewedAt": { - "state": "unknown" + "state": "known", + "value": "2026-11-24", + "precision": "day" }, "upstreamObservedAt": { "state": "known", - "value": "2026-08-30T18:00:09Z", - "precision": "second" + "value": "2026-11-24", + "precision": "day" } }, "provenance": { "content": { - "kind": "web", - "url": "https://clawhub.ai/api/v1/skills/amap-jsapi-skill/file?path=SKILL.md&ownerHandle=lbs-amap", - "sha256": "cf2f06cc5abf5e41a626f823c50575ab52c81aecbceca5abd4e69d56ca5c5d75" + "kind": "zip", + "url": "https://clawhub.ai/api/v1/download?slug=amap-jsapi-skill&version=1.1.1&ownerHandle=lbs-amap", + "sha256": "9468743ee18dbe1704e8a98f47f6628d6a4e6acec30a05f0b8f59a07603d011f" } }, "governance": { "stewardship": "community", - "availability": "listing-only", + "availability": "installable", "license": { "state": "known", - "value": "MIT" + "value": "MIT", + "evidencePath": "SKILL.md" }, "redistribution": "allowed", "upstreamMaintainer": { "name": "lbs-amap", "url": "https://clawhub.ai/lbs-amap/skills/amap-jsapi-skill", "verified": false + }, + "listingMaintainer": { + "name": "mashagua", + "url": "https://github.com/mashagua", + "verified": true + }, + "compliance": { + "licenseEvidencePath": "SKILL.md", + "noticePath": "skill-card.md", + "reviewedRef": "9468743ee18dbe1704e8a98f47f6628d6a4e6acec30a05f0b8f59a07603d011f", + "reviewedAt": "2026-11-24", + "reviewedBy": "mashagua", + "upstreamEndorsed": false } }, "compatibility": { "platforms": { "state": "unknown" - } + }, + "requirements": [ + { + "kind": "runtime", + "value": "Full unmodified ClawHub lbs-amap 1.1.1 ZIP (36 files, all 33 referenced docs including references/security.md); SHA-256 9468743ee18dbe1704e8a98f47f6628d6a4e6acec30a05f0b8f59a07603d011f. SKILL.md is at ZIP root; no source.path is needed." + }, + { + "kind": "connection", + "value": "Supply your own AMap Web JSAPI Key and securityJsCode, or a correctly configured backend serviceHost proxy. Keep sensitive values in private host configuration; production must not expose security credentials. AMap account authorization, allowed domains, quotas, usage terms and possible billing are separate." + }, + { + "kind": "runtime", + "value": "License declaration discrepancy is preserved: SKILL.md declares MIT; skill-card.md and ClawHub metadata declare MIT-0. There is no standalone LICENSE. This reviewed listing follows the SKILL MIT declaration conservatively and retains attribution; it does not claim upstream clarified or granted dual licensing. See ADMISSION.md in the market listing." + } + ] }, "spec": { "kind": "skill" diff --git a/skills/amap-jsapi-skill/entry.json b/skills/amap-jsapi-skill/entry.json index ac8cfbb..734e886 100644 --- a/skills/amap-jsapi-skill/entry.json +++ b/skills/amap-jsapi-skill/entry.json @@ -9,11 +9,11 @@ "i18n": { "zh-CN": { "name": "高德地图 JSAPI 技能", - "shortDesc": "高德地图 JSAPI v2.0(WebGL)开发技能,涵盖地图生命周期、安全配置、3D 视图、覆盖物绘制与 LBS 服务集成" + "shortDesc": "ClawHub 1.1.1 完整 ZIP:36 文件,含全部 33 个引用文档和安全指南。需自备高德 Web JSAPI Key、安全密钥或 serviceHost 代理;适用高德配额及收费条款。" }, "en-US": { "name": "AMap JSAPI Skill", - "shortDesc": "AMap JSAPI v2.0 (WebGL) development skill covering map lifecycle, security config, 3D views, overlays and LBS services" + "shortDesc": "Complete ClawHub 1.1.1 ZIP: 36 files including all 33 reference docs and the security guide. Requires your AMap Web JSAPI Key and securityJsCode or serviceHost proxy; AMap quotas and billing apply." } }, "maintainer": { @@ -26,9 +26,9 @@ "license": "MIT", "redistribution": "allowed", "source": { - "kind": "web", - "repoUrl": "https://clawhub.ai/api/v1/skills/amap-jsapi-skill/file?path=SKILL.md&ownerHandle=lbs-amap", - "sha256": "cf2f06cc5abf5e41a626f823c50575ab52c81aecbceca5abd4e69d56ca5c5d75" + "kind": "zip", + "repoUrl": "https://clawhub.ai/api/v1/download?slug=amap-jsapi-skill&version=1.1.1&ownerHandle=lbs-amap", + "sha256": "9468743ee18dbe1704e8a98f47f6628d6a4e6acec30a05f0b8f59a07603d011f" }, "latestVersion": "1.1.1" } diff --git a/skills/dingtalk-api/catalog-metadata.v1.json b/skills/dingtalk-api/catalog-metadata.v1.json index 68a65a3..3490fbe 100644 --- a/skills/dingtalk-api/catalog-metadata.v1.json +++ b/skills/dingtalk-api/catalog-metadata.v1.json @@ -10,11 +10,11 @@ "i18n": { "en-US": { "name": "DingTalk API Skill", - "summary": "Call DingTalk Open Platform APIs: user/department lookup, bot messaging in chats and groups, and HR records" + "summary": "DingTalk API scripts. Real queries require Node.js/npm dependencies, DINGTALK_APP_KEY, DINGTALK_APP_SECRET and authorized API permissions. Command startup is not a successful query; platform terms and any fees apply." }, "zh-CN": { "name": "钉钉 API 技能", - "summary": "调用钉钉开放平台 API:用户与部门查询、机器人单聊/群聊消息发送、群机器人列表、离职记录查询等" + "summary": "钉钉 API 脚本。实际查询需自行安装 Node.js/npm 依赖,私下配置 DINGTALK_APP_KEY、DINGTALK_APP_SECRET 并授权接口权限。命令启动不等于查询成功;适用平台条款及可能的费用。" } }, "category": "communication", @@ -35,7 +35,9 @@ "state": "unknown" }, "reviewedAt": { - "state": "unknown" + "state": "known", + "value": "2026-11-24", + "precision": "day" }, "upstreamObservedAt": { "state": "known", @@ -52,21 +54,40 @@ }, "governance": { "stewardship": "community", - "availability": "listing-only", + "availability": "installable", "license": { - "state": "unknown" + "state": "known", + "value": "MIT", + "evidencePath": "README.md" }, "redistribution": "allowed", "upstreamMaintainer": { "name": "ogenes", "url": "https://clawhub.ai/ogenes/skills/dingtalk-api", "verified": false + }, + "compliance": { + "licenseEvidencePath": "README.md", + "reviewedRef": "83465bf60b522ad19f7822d167489c3c4f79b302", + "reviewedAt": "2026-11-24", + "reviewedBy": "mashagua", + "upstreamEndorsed": false } }, "compatibility": { "platforms": { "state": "unknown" - } + }, + "requirements": [ + { + "kind": "runtime", + "value": "Node.js/npm, TypeScript/ts-node and the dependencies declared by the pinned package.json, including the Alibaba Cloud DingTalk SDK. The packaged scripts/search-user.ts exists and validates configuration before requesting an access token or performing a query." + }, + { + "kind": "permission", + "value": "Real searches require DINGTALK_APP_KEY and DINGTALK_APP_SECRET from an operator-authorized DingTalk application, plus the corresponding API scopes and account access. Configure credentials privately on the host; do not paste them into chat or this catalog. Missing credentials produce MISSING_CREDENTIALS and exit before a query. Startup/help is not proof of a successful query; no authenticated query was verified. DingTalk terms, entitlements and any fees apply separately." + } + ] }, "spec": { "kind": "skill" diff --git a/skills/dingtalk-api/entry.json b/skills/dingtalk-api/entry.json index 4af57cd..54c21fb 100644 --- a/skills/dingtalk-api/entry.json +++ b/skills/dingtalk-api/entry.json @@ -9,11 +9,11 @@ "i18n": { "zh-CN": { "name": "钉钉 API 技能", - "shortDesc": "调用钉钉开放平台 API:用户与部门查询、机器人单聊/群聊消息发送、群机器人列表、离职记录查询等" + "shortDesc": "钉钉 API 脚本。实际查询需自行安装 Node.js/npm 依赖,私下配置 DINGTALK_APP_KEY、DINGTALK_APP_SECRET 并授权接口权限。命令启动不等于查询成功;适用平台条款及可能的费用。" }, "en-US": { "name": "DingTalk API Skill", - "shortDesc": "Call DingTalk Open Platform APIs: user/department lookup, bot messaging in chats and groups, and HR records" + "shortDesc": "DingTalk API scripts. Real queries require Node.js/npm dependencies, DINGTALK_APP_KEY, DINGTALK_APP_SECRET and authorized API permissions. Command startup is not a successful query; platform terms and any fees apply." } }, "maintainer": { @@ -23,7 +23,7 @@ "url": "https://clawhub.ai/ogenes/skills/dingtalk-api" }, "stewardship": "community", - "license": "MIT-0", + "license": "MIT", "redistribution": "allowed", "source": { "kind": "git", diff --git a/skills/follow-builders/catalog-metadata.v1.json b/skills/follow-builders/catalog-metadata.v1.json index 9b8e27d..29dc545 100644 --- a/skills/follow-builders/catalog-metadata.v1.json +++ b/skills/follow-builders/catalog-metadata.v1.json @@ -37,7 +37,9 @@ "state": "unknown" }, "reviewedAt": { - "state": "unknown" + "state": "known", + "value": "2026-11-24", + "precision": "day" }, "upstreamObservedAt": { "state": "known", @@ -54,15 +56,24 @@ }, "governance": { "stewardship": "community", - "availability": "listing-only", + "availability": "installable", "license": { - "state": "unknown" + "state": "known", + "value": "MIT", + "evidencePath": "README.md" }, "redistribution": "allowed", "upstreamMaintainer": { "name": "zarazhangrui", "url": "https://github.com/zarazhangrui/follow-builders", "verified": false + }, + "compliance": { + "licenseEvidencePath": "README.md", + "reviewedRef": "22c2e72e1a4bb0fc0f3e19f992fc55615b48989e", + "reviewedAt": "2026-11-24", + "reviewedBy": "mashagua", + "upstreamEndorsed": false } }, "compatibility": { diff --git a/skills/humanizer-zh/catalog-metadata.v1.json b/skills/humanizer-zh/catalog-metadata.v1.json index 76a4a95..b9f8879 100644 --- a/skills/humanizer-zh/catalog-metadata.v1.json +++ b/skills/humanizer-zh/catalog-metadata.v1.json @@ -40,7 +40,7 @@ }, "reviewedAt": { "state": "known", - "value": "2026-10-05", + "value": "2026-11-24", "precision": "day" }, "upstreamObservedAt": { @@ -58,7 +58,7 @@ }, "governance": { "stewardship": "community", - "availability": "listing-only", + "availability": "installable", "license": { "state": "known", "value": "MIT", @@ -69,6 +69,13 @@ "name": "歸藏 (op7418)", "url": "https://github.com/op7418/Humanizer-zh", "verified": false + }, + "compliance": { + "licenseEvidencePath": "LICENSE", + "reviewedRef": "f4518a8eab97b8bfebc66a89d34320a89bef6930", + "reviewedAt": "2026-11-24", + "reviewedBy": "mashagua", + "upstreamEndorsed": false } }, "compatibility": { diff --git a/skills/karpathy-guidelines/catalog-metadata.v1.json b/skills/karpathy-guidelines/catalog-metadata.v1.json index adfdcb6..4bf8528 100644 --- a/skills/karpathy-guidelines/catalog-metadata.v1.json +++ b/skills/karpathy-guidelines/catalog-metadata.v1.json @@ -40,7 +40,9 @@ "state": "unknown" }, "reviewedAt": { - "state": "unknown" + "state": "known", + "value": "2026-11-24", + "precision": "day" }, "upstreamObservedAt": { "state": "known", @@ -58,15 +60,24 @@ }, "governance": { "stewardship": "community", - "availability": "listing-only", + "availability": "installable", "license": { - "state": "unknown" + "state": "known", + "value": "MIT", + "evidencePath": "README.md" }, "redistribution": "allowed", "upstreamMaintainer": { "name": "forrestchang", "url": "https://github.com/multica-ai/andrej-karpathy-skills", "verified": false + }, + "compliance": { + "licenseEvidencePath": "README.md", + "reviewedRef": "2c606141936f1eeef17fa3043a72095b4765b9c2", + "reviewedAt": "2026-11-24", + "reviewedBy": "mashagua", + "upstreamEndorsed": false } }, "compatibility": { diff --git a/skills/marketingskills/catalog-metadata.v1.json b/skills/marketingskills/catalog-metadata.v1.json index 6184530..3ff0659 100644 --- a/skills/marketingskills/catalog-metadata.v1.json +++ b/skills/marketingskills/catalog-metadata.v1.json @@ -40,7 +40,7 @@ }, "reviewedAt": { "state": "known", - "value": "2026-10-05", + "value": "2026-11-24", "precision": "day" }, "upstreamObservedAt": { @@ -58,7 +58,7 @@ }, "governance": { "stewardship": "community", - "availability": "listing-only", + "availability": "installable", "license": { "state": "known", "value": "MIT", @@ -69,6 +69,13 @@ "name": "Corey Haines", "url": "https://github.com/coreyhaines31/marketingskills", "verified": false + }, + "compliance": { + "licenseEvidencePath": "LICENSE", + "reviewedRef": "dda3841f0b294e01e93b1541486beefbfab0915e", + "reviewedAt": "2026-11-24", + "reviewedBy": "mashagua", + "upstreamEndorsed": false } }, "compatibility": { diff --git a/skills/netease-skills/catalog-metadata.v1.json b/skills/netease-skills/catalog-metadata.v1.json index 056af44..66fe1ef 100644 --- a/skills/netease-skills/catalog-metadata.v1.json +++ b/skills/netease-skills/catalog-metadata.v1.json @@ -10,11 +10,11 @@ "i18n": { "en-US": { "name": "NetEase Skills", - "summary": "NetEase Cloud Music agent skills built on ncm-cli, for music search, playback and account setup" + "summary": "NetEase Cloud Music skills. Requires separately installed Node.js/ncm-cli; search needs privately configured appId and privateKey. CLI startup is not verified search. Account authorization, content rights, membership and charges are separate." }, "zh-CN": { "name": "网易云音乐 Skills", - "summary": "基于 ncm-cli 的网易云音乐 AI Agent 技能包,支持音乐搜索、播放与账号配置等操作" + "summary": "网易云音乐技能集。需自行安装 Node.js/ncm-cli;搜索还须在主机私下配置 appId 和 privateKey。CLI 启动不代表搜索已验证;账号授权、内容权益、会员及费用另计。" } }, "category": "productivity", @@ -35,7 +35,9 @@ "state": "unknown" }, "reviewedAt": { - "state": "unknown" + "state": "known", + "value": "2026-11-24", + "precision": "day" }, "upstreamObservedAt": { "state": "known", @@ -52,21 +54,40 @@ }, "governance": { "stewardship": "pointer", - "availability": "listing-only", + "availability": "installable", "license": { - "state": "unknown" + "state": "known", + "value": "Apache-2.0", + "evidencePath": "ncm-cli-setup/LICENSE.txt" }, "redistribution": "source-pointer-only", "upstreamMaintainer": { "name": "NetEase", "url": "https://github.com/NetEase/skills", "verified": false + }, + "compliance": { + "licenseEvidencePath": "ncm-cli-setup/LICENSE.txt", + "reviewedRef": "58ff0771d6977feb847d6bfe322280eec4bec004", + "reviewedAt": "2026-11-24", + "reviewedBy": "mashagua", + "upstreamEndorsed": false } }, "compatibility": { "platforms": { "state": "unknown" - } + }, + "requirements": [ + { + "kind": "runtime", + "value": "Separately installed Node.js/npm and ncm-cli following ncm-cli-setup/SKILL.md. Search requires the operator to configure appId and privateKey through ncm-cli config set as documented upstream. The package includes ncm-cli-setup/scripts/install_mpv.py for optional local playback. Installing skills does not install or configure the CLI or provision API credentials." + }, + { + "kind": "permission", + "value": "Apply for appId/privateKey through the NetEase Cloud Music developer platform and keep privateKey in private host configuration, never chat or this public catalog. Account-specific operations additionally need the relevant account authorization. CLI startup is not proof of a successful search; no credentialed search was verified. Service terms, content/region rights, membership and charges apply separately. Verify configuration and stop on missing access or service errors." + } + ] }, "spec": { "kind": "skill", diff --git a/skills/netease-skills/entry.json b/skills/netease-skills/entry.json index 80c2857..aa946dd 100644 --- a/skills/netease-skills/entry.json +++ b/skills/netease-skills/entry.json @@ -9,11 +9,11 @@ "i18n": { "zh-CN": { "name": "网易云音乐 Skills", - "shortDesc": "基于 ncm-cli 的网易云音乐 AI Agent 技能包,支持音乐搜索、播放与账号配置等操作" + "shortDesc": "网易云音乐技能集。需自行安装 Node.js/ncm-cli;搜索还须在主机私下配置 appId 和 privateKey。CLI 启动不代表搜索已验证;账号授权、内容权益、会员及费用另计。" }, "en-US": { "name": "NetEase Skills", - "shortDesc": "NetEase Cloud Music agent skills built on ncm-cli, for music search, playback and account setup" + "shortDesc": "NetEase Cloud Music skills. Requires separately installed Node.js/ncm-cli; search needs privately configured appId and privateKey. CLI startup is not verified search. Account authorization, content rights, membership and charges are separate." } }, "maintainer": { @@ -23,7 +23,7 @@ "url": "https://github.com/NetEase/skills" }, "stewardship": "pointer", - "license": "not-declared", + "license": "Apache-2.0", "redistribution": "source-pointer-only", "source": { "kind": "git", diff --git a/skills/wecom-cli/catalog-metadata.v1.json b/skills/wecom-cli/catalog-metadata.v1.json index 4023a18..8a84560 100644 --- a/skills/wecom-cli/catalog-metadata.v1.json +++ b/skills/wecom-cli/catalog-metadata.v1.json @@ -36,7 +36,7 @@ }, "reviewedAt": { "state": "known", - "value": "2026-10-19", + "value": "2026-11-24", "precision": "day" }, "upstreamObservedAt": { @@ -54,7 +54,7 @@ }, "governance": { "stewardship": "community", - "availability": "listing-only", + "availability": "installable", "license": { "state": "known", "value": "MIT", @@ -65,6 +65,13 @@ "name": "WecomTeam", "url": "https://github.com/WecomTeam/wecom-cli", "verified": false + }, + "compliance": { + "licenseEvidencePath": "LICENSE", + "reviewedRef": "4c74ff28838d8fba267eaab5179d9d56f9ca61ae", + "reviewedAt": "2026-11-24", + "reviewedBy": "mashagua", + "upstreamEndorsed": false } }, "compatibility": {