dknowc-dsh 2.3.1 → 2.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -3
- package/cordis.patch.yml +1 -1
- package/package.json +7 -4
- package/skills/dk-trace-report/SKILL.md +288 -0
- package/skills/dk-trace-report/config/examples/doc.json +56 -0
- package/skills/dk-trace-report/config/examples/legal.json +51 -0
- package/skills/dk-trace-report/config/examples/ppt.json +47 -0
- package/skills/dk-trace-report/config/examples/tax.json +46 -0
- package/skills/dk-trace-report/config/examples/trusted.json +122 -0
- package/skills/dk-trace-report/reference/sample_input.json +60 -0
- package/skills/dk-trace-report/resources/ECHARTS-NOTICE.txt +10 -0
- package/skills/dk-trace-report/resources/echarts.custom.min.js +48 -0
- package/skills/dk-trace-report/scripts/build_report_input.py +333 -0
- package/skills/{dknowc-trusted-search → dk-trace-report}/scripts/chart_embed.py +4 -1
- package/skills/{dknowc-trusted-search → dk-trace-report}/scripts/render_trace_html.py +1071 -536
- package/skills/dk-trace-report/scripts/run_paths.py +95 -0
- package/skills/dk-trace-report/scripts/trust_digest.py +77 -0
- package/skills/dknowc-legal-assistant/README.md +95 -0
- package/skills/dknowc-legal-assistant/SKILL.md +122 -0
- package/skills/dknowc-legal-assistant/attribution.json +5 -0
- package/skills/dknowc-legal-assistant/reference/answer-and-report.md +221 -0
- package/skills/dknowc-legal-assistant/reference/capability-layer.md +143 -0
- package/skills/dknowc-legal-assistant/reference/legal_claims.example.json +96 -0
- package/skills/dknowc-legal-assistant/reference/onboarding_scripts.md +198 -0
- package/skills/dknowc-legal-assistant/reference/policy_tags.json +2002 -0
- package/skills/dknowc-legal-assistant/reference/retrieval-statute.md +81 -0
- package/skills/dknowc-legal-assistant/reference/retrieval-v2.md +133 -0
- package/skills/dknowc-legal-assistant/reference/sample_search_result.md +33 -0
- package/skills/dknowc-legal-assistant/reference/sample_trace_report.html +940 -0
- package/skills/dknowc-legal-assistant/reference/tags.md +53 -0
- package/skills/dknowc-legal-assistant/reference/troubleshooting.md +50 -0
- package/skills/dknowc-legal-assistant/reference/verification-pass.md +59 -0
- package/skills/dknowc-legal-assistant/resources/echarts.custom.min.js +48 -0
- package/skills/dknowc-legal-assistant/scripts/api_key.py +68 -0
- package/skills/dknowc-legal-assistant/scripts/attribution.py +61 -0
- package/skills/dknowc-legal-assistant/scripts/calc_legal.py +375 -0
- package/skills/dknowc-legal-assistant/scripts/calc_period.py +155 -0
- package/skills/dknowc-legal-assistant/scripts/check_answer.py +664 -0
- package/skills/dknowc-legal-assistant/scripts/initialize.py +188 -0
- package/skills/dknowc-legal-assistant/scripts/legal_client.py +208 -0
- package/skills/dknowc-legal-assistant/scripts/legal_search.py +1059 -0
- package/skills/dknowc-legal-assistant/scripts/merge_search_results.py +630 -0
- package/skills/dknowc-legal-assistant/scripts/path_guard.py +92 -0
- package/skills/dknowc-legal-assistant/scripts/question_profile.py +215 -0
- package/skills/dknowc-legal-assistant/scripts/register_key.mjs +1152 -0
- package/skills/dknowc-legal-assistant/scripts/run_eval.py +109 -0
- package/skills/dknowc-legal-assistant/scripts/source_cards.py +321 -0
- package/skills/dknowc-legal-assistant/scripts/tag_catalog.py +162 -0
- package/skills/dknowc-legal-assistant/scripts/trace_report.config.json +66 -0
- package/skills/dknowc-legal-assistant/scripts/verify_claims.py +448 -0
- package/skills/dknowc-legal-assistant/scripts/websearch_convert.py +396 -0
- package/skills/dknowc-official-doc-writer/README.md +32 -21
- package/skills/dknowc-official-doc-writer/SKILL.md +28 -15
- package/skills/dknowc-official-doc-writer/config/trace_report.config.json +56 -0
- package/skills/dknowc-official-doc-writer/reference/anti_ai_patterns.md +14 -2
- package/skills/dknowc-official-doc-writer/reference/fact_discipline.md +4 -0
- package/skills/dknowc-official-doc-writer/reference/genre_writing_notes.md +4 -0
- package/skills/dknowc-official-doc-writer/reference/initialization.md +13 -8
- package/skills/dknowc-official-doc-writer/reference/local_memory_guide.md +7 -7
- package/skills/dknowc-official-doc-writer/reference/material_usage_guidance.md +21 -0
- package/skills/dknowc-official-doc-writer/reference/materials_pipeline.md +64 -7
- package/skills/dknowc-official-doc-writer/reference/onboarding_scripts.md +1 -1
- package/skills/dknowc-official-doc-writer/reference/outline_rules.md +1 -1
- package/skills/dknowc-official-doc-writer/reference/output_guide.md +13 -13
- package/skills/dknowc-official-doc-writer/reference/research_notes.md +5 -3
- package/skills/dknowc-official-doc-writer/reference/review_checklist.md +6 -2
- package/skills/dknowc-official-doc-writer/reference/search_guide.md +44 -32
- package/skills/dknowc-official-doc-writer/reference/search_policy.md +63 -36
- package/skills/dknowc-official-doc-writer/reference/standards/01_report.md +3 -3
- package/skills/dknowc-official-doc-writer/reference/standards/02_qingshi.md +6 -3
- package/skills/dknowc-official-doc-writer/reference/standards/03_pifu.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/standards/04_tongzhi.md +12 -3
- package/skills/dknowc-official-doc-writer/reference/standards/05_yijian.md +8 -2
- package/skills/dknowc-official-doc-writer/reference/standards/06_han.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/standards/08_tongbao.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/standards/09_tonggao.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/standards/10_gonggao.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/standards/11_fuhan_approve.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/standards/12_fuhan_objection.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/standards/13_reminder.md +3 -3
- package/skills/dknowc-official-doc-writer/reference/standards/14_generic.md +1 -1
- package/skills/dknowc-official-doc-writer/reference/standards/16_decision.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/standards/18_order.md +1 -1
- package/skills/dknowc-official-doc-writer/reference/standards/19_gazette.md +1 -1
- package/skills/dknowc-official-doc-writer/reference/standards/20_motion.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/standards/22_application.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/standards/23_publicity.md +1 -1
- package/skills/dknowc-official-doc-writer/reference/standards/25_plan.md +2 -1
- package/skills/dknowc-official-doc-writer/reference/standards/26_summary.md +7 -1
- package/skills/dknowc-official-doc-writer/reference/standards/27_speech.md +4 -1
- package/skills/dknowc-official-doc-writer/reference/standards/99_expressions.md +1 -1
- package/skills/dknowc-official-doc-writer/reference/task_router.md +4 -4
- package/skills/dknowc-official-doc-writer/reference/working_principles.md +4 -4
- package/skills/dknowc-official-doc-writer/reference/writing_method.md +166 -0
- package/skills/dknowc-official-doc-writer/reference/writing_rules.md +10 -4
- package/skills/dknowc-official-doc-writer/scripts/api_key.py +24 -25
- package/skills/dknowc-official-doc-writer/scripts/attribution.py +1 -1
- package/skills/dknowc-official-doc-writer/scripts/build_trace_json.py +205 -13
- package/skills/dknowc-official-doc-writer/scripts/check_materials.py +367 -22
- package/skills/dknowc-official-doc-writer/scripts/deep_convert.py +5 -0
- package/skills/dknowc-official-doc-writer/scripts/deep_query.py +2 -1
- package/skills/dknowc-official-doc-writer/scripts/dkag_search.py +20 -7
- package/skills/dknowc-official-doc-writer/scripts/extract_reference.py +1 -0
- package/skills/dknowc-official-doc-writer/scripts/format_document.py +88 -30
- package/skills/dknowc-official-doc-writer/scripts/initialize.py +232 -6
- package/skills/dknowc-official-doc-writer/scripts/local_memory.py +2 -6
- package/skills/dknowc-official-doc-writer/scripts/merge_search_results.py +100 -7
- package/skills/dknowc-official-doc-writer/scripts/outline_reference.py +2 -1
- package/skills/dknowc-official-doc-writer/scripts/register.mjs +265 -32
- package/skills/dknowc-official-doc-writer/scripts/review_document.py +1 -0
- package/skills/dknowc-official-doc-writer/scripts/source_note_html.py +117 -10
- package/skills/dknowc-official-doc-writer/scripts/template_generator.py +1 -0
- package/skills/dknowc-official-doc-writer/scripts/update_skill.py +339 -0
- package/skills/dknowc-official-doc-writer/scripts/websearch_convert.py +326 -0
- package/skills/dknowc-ppt-assistant/README.md +7 -9
- package/skills/dknowc-ppt-assistant/SKILL.md +28 -19
- package/skills/dknowc-ppt-assistant/config/trace_report.config.json +65 -0
- package/skills/dknowc-ppt-assistant/references/initialization.md +20 -8
- package/skills/dknowc-ppt-assistant/references/material_usage.md +46 -9
- package/skills/dknowc-ppt-assistant/references/onboarding_scripts.md +7 -5
- package/skills/dknowc-ppt-assistant/references/sample_trace_report.html +372 -920
- package/skills/dknowc-ppt-assistant/references/search_intro.md +2 -2
- package/skills/dknowc-ppt-assistant/references/svg-authoring.md +2 -2
- package/skills/dknowc-ppt-assistant/scripts/api_key.py +5 -28
- package/skills/dknowc-ppt-assistant/scripts/build_trace_input.py +188 -0
- package/skills/dknowc-ppt-assistant/scripts/initialize.py +238 -3
- package/skills/dknowc-ppt-assistant/scripts/mcp_convert.py +1 -10
- package/skills/dknowc-ppt-assistant/scripts/merge_search_results.py +604 -0
- package/skills/dknowc-ppt-assistant/scripts/preview_slide_html.py +4 -11
- package/skills/dknowc-ppt-assistant/scripts/register_key.mjs +224 -63
- package/skills/dknowc-ppt-assistant/scripts/trusted_search.py +29 -12
- package/skills/dknowc-ppt-assistant/scripts/update_skill.py +314 -0
- package/skills/dknowc-ppt-assistant/scripts/websearch_convert.py +326 -0
- package/skills/dknowc-ppt-assistant/workflows/generate-pptx.md +92 -29
- package/skills/dknowc-ppt-assistant/workflows/routing.md +1 -1
- package/skills/dknowc-tax-assistant/README.md +54 -0
- package/skills/dknowc-tax-assistant/SKILL.md +99 -0
- package/skills/dknowc-tax-assistant/attribution.json +5 -0
- package/skills/dknowc-tax-assistant/reference/answer-and-report.md +100 -0
- package/skills/dknowc-tax-assistant/reference/capability-layer.md +205 -0
- package/skills/dknowc-tax-assistant/reference/onboarding_scripts.md +68 -0
- package/skills/dknowc-tax-assistant/reference/policy_tags.json +2002 -0
- package/skills/dknowc-tax-assistant/reference/retrieval-policy.md +43 -0
- package/skills/dknowc-tax-assistant/reference/retrieval-v2.md +58 -0
- package/skills/dknowc-tax-assistant/reference/tags.md +53 -0
- package/skills/dknowc-tax-assistant/reference/tax_claims.example.json +76 -0
- package/skills/dknowc-tax-assistant/reference/trace_report.config.json +46 -0
- package/skills/dknowc-tax-assistant/reference/troubleshooting.md +70 -0
- package/skills/dknowc-tax-assistant/reference/websearch-fallback.md +59 -0
- package/skills/dknowc-tax-assistant/resources/THIRD_PARTY_NOTICES.md +9 -0
- package/skills/dknowc-tax-assistant/resources/echarts.custom.min.js +48 -0
- package/skills/dknowc-tax-assistant/scripts/api_key.py +60 -0
- package/skills/dknowc-tax-assistant/scripts/attribution.py +61 -0
- package/skills/dknowc-tax-assistant/scripts/calc_period.py +156 -0
- package/skills/dknowc-tax-assistant/scripts/calc_tax.py +179 -0
- package/skills/dknowc-tax-assistant/scripts/check_answer.py +210 -0
- package/skills/dknowc-tax-assistant/scripts/initialize.py +208 -0
- package/skills/dknowc-tax-assistant/scripts/merge_search_results.py +631 -0
- package/skills/dknowc-tax-assistant/scripts/path_guard.py +23 -0
- package/skills/dknowc-tax-assistant/scripts/question_profile.py +444 -0
- package/skills/dknowc-tax-assistant/scripts/register_key.mjs +1173 -0
- package/skills/dknowc-tax-assistant/scripts/run_dir.py +149 -0
- package/skills/dknowc-tax-assistant/scripts/source_cards.py +372 -0
- package/skills/dknowc-tax-assistant/scripts/tag_catalog.py +164 -0
- package/skills/dknowc-tax-assistant/scripts/tax_client.py +218 -0
- package/skills/dknowc-tax-assistant/scripts/tax_search.py +403 -0
- package/skills/dknowc-tax-assistant/scripts/verify_claims.py +587 -0
- package/skills/dknowc-tax-assistant/scripts/websearch_convert.py +352 -0
- package/skills/dknowc-trusted-search/README.md +25 -19
- package/skills/dknowc-trusted-search/SKILL.md +205 -73
- package/skills/dknowc-trusted-search/config/trace_report.config.json +119 -0
- package/skills/dknowc-trusted-search/reference/onboarding_scripts.md +3 -3
- package/skills/dknowc-trusted-search/reference/sample_trace_report.html +286 -191
- package/skills/dknowc-trusted-search/resources/ECHARTS-NOTICE.txt +10 -0
- package/skills/dknowc-trusted-search/scripts/api_key.py +0 -1
- package/skills/dknowc-trusted-search/scripts/attribution.py +1 -1
- package/skills/dknowc-trusted-search/scripts/build_trace_input.py +173 -0
- package/skills/dknowc-trusted-search/scripts/deep_convert.py +79 -30
- package/skills/dknowc-trusted-search/scripts/deep_query.py +22 -33
- package/skills/dknowc-trusted-search/scripts/initialize.py +343 -2
- package/skills/dknowc-trusted-search/scripts/merge_search_results.py +222 -35
- package/skills/dknowc-trusted-search/scripts/register_key.mjs +241 -29
- package/skills/dknowc-trusted-search/scripts/source_display.py +59 -0
- package/skills/dknowc-trusted-search/scripts/trusted_search.py +67 -34
- package/skills/dknowc-trusted-search/scripts/update_skill.py +300 -0
- package/skills/dknowc-trusted-search/scripts/websearch_convert.py +328 -0
- package/src/index.js +18 -2
- package/skills/dknowc-official-doc-writer/scripts/render_trace_html.py +0 -2574
- package/skills/dknowc-ppt-assistant/official-docs/output/.gitkeep +0 -0
- package/skills/dknowc-ppt-assistant/official-docs/search-results/.gitkeep +0 -0
- package/skills/dknowc-ppt-assistant/scripts/render_trace_html.py +0 -2642
- package/skills/dknowc-trusted-search/official-docs/output/.gitkeep +0 -0
- package/skills/dknowc-trusted-search/official-docs/search-results/.gitkeep +0 -0
|
@@ -25,20 +25,11 @@ import urllib.error
|
|
|
25
25
|
import urllib.request
|
|
26
26
|
from pathlib import Path
|
|
27
27
|
from typing import Any, Dict, Iterable, List, Optional
|
|
28
|
+
from source_display import source_identity
|
|
29
|
+
from run_paths import RunPathError, resolve_output_path, resolve_run_dir
|
|
28
30
|
|
|
29
31
|
|
|
30
32
|
DEFAULT_ENDPOINT = "https://open.dknowc.cn/open-api/maas/dependable/v2/search"
|
|
31
|
-
SKILL_ROOT = Path(__file__).resolve().parent.parent
|
|
32
|
-
# 工作区根:dsh 场景通过环境变量 DKNWOC_WS_ROOT 指向会话工作区,未设置时回退到 cwd
|
|
33
|
-
import os as _os
|
|
34
|
-
_ws = _os.environ.get("DKNWOC_WS_ROOT")
|
|
35
|
-
if not _ws:
|
|
36
|
-
# dsh 会话隔离:每会话独立产物目录 <工作区>/dknowc-output/<DSH_SESSION_ID前8位>/,
|
|
37
|
-
# 多会话共用同一工作区时互不混杂;非 dsh 环境回退为工作区本身。
|
|
38
|
-
_sid = _os.environ.get("DSH_SESSION_ID", "")
|
|
39
|
-
_ws = str(Path(_os.getcwd()) / "dknowc-output" / (_sid[:8] if _sid else "_default"))
|
|
40
|
-
WS_ROOT = Path(_ws).resolve()
|
|
41
|
-
SEARCH_RESULTS_DIR = WS_ROOT / "official-docs" / "search-results"
|
|
42
33
|
|
|
43
34
|
# V2 参数定档(1.6.0;对齐公文写作 3.9.0 三组受控实测:4/18000 双主题相关率最高、边际新增质量最好)
|
|
44
35
|
DEFAULT_SEARCH_TYPE = "policy" # 政策依据主路;办事/流程类补 govSite 路(各自单值,禁止混传)
|
|
@@ -103,23 +94,11 @@ def _fail_request(stage: str, reason: str, status_code=None, errmsg=None):
|
|
|
103
94
|
|
|
104
95
|
|
|
105
96
|
|
|
106
|
-
def resolve_output_json(output_path: str) -> Path:
|
|
107
|
-
"""
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
elif raw_path.parent == Path("."):
|
|
112
|
-
resolved = (SEARCH_RESULTS_DIR / raw_path.name).resolve()
|
|
113
|
-
else:
|
|
114
|
-
resolved = raw_path.resolve()
|
|
115
|
-
|
|
116
|
-
if resolved.suffix.lower() != ".json":
|
|
117
|
-
resolved = resolved.with_suffix(".json")
|
|
118
|
-
try:
|
|
119
|
-
resolved.relative_to(SEARCH_RESULTS_DIR.resolve())
|
|
120
|
-
except ValueError:
|
|
121
|
-
raise ValueError(f"输出文件必须位于 official-docs/search-results/ 内: {output_path}")
|
|
122
|
-
return resolved
|
|
97
|
+
def resolve_output_json(output_path: str, run_dir: Optional[Path] = None) -> Path:
|
|
98
|
+
"""搜索结果只写会话工作区的 run 目录;拒绝写回 Skill 安装目录。"""
|
|
99
|
+
if not Path(output_path).expanduser().is_absolute() and run_dir is None:
|
|
100
|
+
raise RunPathError("相对 --output 必须同时用 --run 指定运行目录")
|
|
101
|
+
return resolve_output_path(output_path, run_dir, {".json"}, ".json", "trusted_search.json")
|
|
123
102
|
|
|
124
103
|
|
|
125
104
|
def _pick(*values: Optional[str]) -> str:
|
|
@@ -348,7 +327,7 @@ def _print_summary(body: Dict[str, Any], max_articles: int, max_paragraphs: int,
|
|
|
348
327
|
|
|
349
328
|
for idx, article in enumerate(articles[:max_articles], start=1):
|
|
350
329
|
title = article.get('文章标题') or '未命名材料'
|
|
351
|
-
source =
|
|
330
|
+
source, _, _, _ = source_identity(article)
|
|
352
331
|
date = article.get('发布日期') or '接口未返回'
|
|
353
332
|
url = article.get('源网址') or '接口未返回'
|
|
354
333
|
|
|
@@ -371,6 +350,50 @@ def _print_summary(body: Dict[str, Any], max_articles: int, max_paragraphs: int,
|
|
|
371
350
|
print(f"原文:{url}")
|
|
372
351
|
|
|
373
352
|
|
|
353
|
+
def _paragraphs(article: Dict[str, Any]) -> list:
|
|
354
|
+
paragraphs = article.get("段落") or article.get("paragraphs") or []
|
|
355
|
+
chunks = []
|
|
356
|
+
if isinstance(paragraphs, list):
|
|
357
|
+
for p in paragraphs:
|
|
358
|
+
if isinstance(p, dict):
|
|
359
|
+
chunks.append(str(p.get("内容") or p.get("text") or p.get("content") or ""))
|
|
360
|
+
else:
|
|
361
|
+
chunks.append(str(p or ""))
|
|
362
|
+
if not chunks:
|
|
363
|
+
chunks.append(str(article.get("内容") or article.get("content") or ""))
|
|
364
|
+
return [c for c in chunks if c.strip()]
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _paragraph_text(article: Dict[str, Any]) -> str:
|
|
368
|
+
return "\n".join(_paragraphs(article)).strip()
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def _is_version_index_text(text: str) -> bool:
|
|
372
|
+
value = (text or "").strip()
|
|
373
|
+
if value.startswith("生效时间:") and "所属地域:" in value:
|
|
374
|
+
return True
|
|
375
|
+
if value.startswith("修订说明") and "相关文件有下面这些版本" in value:
|
|
376
|
+
return True
|
|
377
|
+
return False
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _mark_citability(article: Dict[str, Any]) -> None:
|
|
381
|
+
"""标记文章是否可引用(1.7.3):版本索引/无正文材料禁止挂角标。"""
|
|
382
|
+
texts = _paragraphs(article)
|
|
383
|
+
substantive = any(not _is_version_index_text(t) for t in texts)
|
|
384
|
+
if substantive:
|
|
385
|
+
article["可引用"] = True
|
|
386
|
+
return
|
|
387
|
+
article["可引用"] = False
|
|
388
|
+
if str(article.get("文章类型") or "").strip() == "policy" or any(
|
|
389
|
+
_is_version_index_text(t) for t in texts):
|
|
390
|
+
article["材料性质"] = "版本索引"
|
|
391
|
+
article["不可引用原因"] = "policy 版本索引记录,仅含生效时间/修订说明,无正文段落"
|
|
392
|
+
else:
|
|
393
|
+
article["材料性质"] = "无正文"
|
|
394
|
+
article["不可引用原因"] = "接口未返回可引用的正文段落"
|
|
395
|
+
|
|
396
|
+
|
|
374
397
|
def main() -> None:
|
|
375
398
|
parser = argparse.ArgumentParser(description="深知可信搜索调用脚本(V2 接口,1.6.0 起)")
|
|
376
399
|
parser.add_argument("query", help="用户搜索问题")
|
|
@@ -406,10 +429,17 @@ def main() -> None:
|
|
|
406
429
|
parser.add_argument("--show-payload", action="store_true", help="打印请求参数")
|
|
407
430
|
parser.add_argument("--dry-run", action="store_true", help="只打印请求参数,不发起请求")
|
|
408
431
|
parser.add_argument("--json-only", action="store_true", help="仅输出原始 JSON")
|
|
409
|
-
parser.add_argument("--
|
|
432
|
+
parser.add_argument("--run", help="本次运行的独立目录(必须在 Skill 安装目录之外;重复运行自动另建)")
|
|
433
|
+
parser.add_argument("--output", "-o", help="搜索结果 JSON 文件名;相对名落在 --run 目录,配合 --json-only 使用")
|
|
410
434
|
parser.add_argument("--timeout", type=int, default=60, help="请求超时秒数")
|
|
411
435
|
args = parser.parse_args()
|
|
412
436
|
|
|
437
|
+
try:
|
|
438
|
+
run_dir = resolve_run_dir(args.run) if args.run else None
|
|
439
|
+
except RunPathError as exc:
|
|
440
|
+
print(f"错误:{exc}", file=sys.stderr)
|
|
441
|
+
sys.exit(2)
|
|
442
|
+
|
|
413
443
|
args.search_type = _validate_search_type(args.search_type)
|
|
414
444
|
endpoint = _pick(
|
|
415
445
|
args.endpoint,
|
|
@@ -457,14 +487,17 @@ def main() -> None:
|
|
|
457
487
|
# 联网路统一补 非官方来源 标记(dataAuthority 缺失/未开时兜底;渲染层按此+数据权威性双口径打徽标)
|
|
458
488
|
if args.search_channel == "webSearch":
|
|
459
489
|
_a["非官方来源"] = True
|
|
490
|
+
_mark_citability(_a)
|
|
460
491
|
raw_json = json.dumps(body, ensure_ascii=False, indent=2)
|
|
461
492
|
if args.output:
|
|
462
|
-
|
|
493
|
+
try:
|
|
494
|
+
output_path = resolve_output_json(args.output, run_dir)
|
|
495
|
+
except RunPathError as exc:
|
|
496
|
+
print(f"错误:{exc}", file=sys.stderr)
|
|
497
|
+
sys.exit(2)
|
|
463
498
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
464
499
|
output_path.write_text(raw_json, encoding="utf-8")
|
|
465
|
-
|
|
466
|
-
# 找不到就全盘 find(实测触发宿主 ~/.ssh 读取询问)——落盘位置在 skill 目录,直接给绝对路径
|
|
467
|
-
print(f"已保存搜索结果 JSON(位于 skill 工作区,绝对路径):{output_path}")
|
|
500
|
+
print(f"已保存搜索结果 JSON(会话运行目录,绝对路径):{output_path}")
|
|
468
501
|
else:
|
|
469
502
|
print(raw_json)
|
|
470
503
|
return
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""深知可信搜索 引导式升级执行器(「版本自检与引导升级」的代码化四步)。
|
|
3
|
+
|
|
4
|
+
由 Agent 在用户明确同意升级后调用(见 SKILL.md「版本自检与引导升级」):
|
|
5
|
+
|
|
6
|
+
python3 scripts/update_skill.py # 预览:版本对比+下载地址+影响说明,不做任何改动
|
|
7
|
+
python3 scripts/update_skill.py --yes # 执行:下载官方包 → 验包 → 备份 → 就地替换 → 验证
|
|
8
|
+
|
|
9
|
+
安全约束:
|
|
10
|
+
- 目录地址、下载白名单前缀、包名均为 initialize.py 固定常量(不接受任何参数传入的
|
|
11
|
+
自定义 URL);版本来源、下载地址、包名任一不符即拒绝;
|
|
12
|
+
- 验包:单一顶层目录、无绝对路径与 .. 逃逸、无软链接、zip CRC 完整、包内 SKILL.md
|
|
13
|
+
的 name 与本技能一致且 version 等于目录登记版本;
|
|
14
|
+
- 整目录备份成功后才开始替换;替换过程异常自动从备份回滚;
|
|
15
|
+
- 只写本技能安装目录与系统临时目录,不读写任何 shell 配置文件;
|
|
16
|
+
~/.config/dknowc(API Key、自检缓存)在技能目录之外,不受影响。
|
|
17
|
+
|
|
18
|
+
退出码:0=成功(预览或升级完成);2=无可用更新或当前渠道不支持自升级;
|
|
19
|
+
3=下载或验包失败(未做任何改动);4=替换失败(已从备份回滚);1=其他错误。
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
import argparse
|
|
23
|
+
import json
|
|
24
|
+
import re
|
|
25
|
+
import shutil
|
|
26
|
+
import sys
|
|
27
|
+
import tempfile
|
|
28
|
+
import time
|
|
29
|
+
import urllib.request
|
|
30
|
+
import zipfile
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
|
|
33
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
34
|
+
|
|
35
|
+
from initialize import ( # noqa: E402
|
|
36
|
+
UPDATE_DOWNLOAD_NAME,
|
|
37
|
+
UPDATE_DOWNLOAD_PREFIX,
|
|
38
|
+
UPDATE_INSTALL_DOC,
|
|
39
|
+
UPDATE_TARGET_NAME,
|
|
40
|
+
_parse_version,
|
|
41
|
+
check_update,
|
|
42
|
+
set_declined_version,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
MAX_PACKAGE_BYTES = 20 * 1024 * 1024 # 压缩包下载上限防护(当前约 0.5MB)
|
|
46
|
+
MAX_UNCOMPRESSED_BYTES = 50 * 1024 * 1024 # 解压后总量上限(防压缩炸弹,正常包 <2MB)
|
|
47
|
+
DOWNLOAD_TIMEOUT_SECONDS = 60
|
|
48
|
+
USER_DATA_DIRS = ("official-docs",) # 技能目录内的用户工作区,升级时保留
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
52
|
+
"""禁止下载跟随重定向:官方 OSS 地址必须直连命中,任何 30x 视为异常。"""
|
|
53
|
+
|
|
54
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
55
|
+
return None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _emit(payload: dict, code: int):
|
|
59
|
+
payload["exit_code"] = code
|
|
60
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
61
|
+
sys.exit(code)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _skill_md_meta_from_zip(zf: zipfile.ZipFile):
|
|
65
|
+
"""读包内 SKILL.md frontmatter 的 name 与 version。"""
|
|
66
|
+
name_member = next((n for n in zf.namelist() if n.count("/") == 1 and n.endswith("/SKILL.md")), None)
|
|
67
|
+
if not name_member:
|
|
68
|
+
return None, None
|
|
69
|
+
head = zf.read(name_member).decode("utf-8", errors="ignore")[:2000]
|
|
70
|
+
m_name = re.search(r'^name:\s*["\']?([^"\'\n]+)', head, re.M)
|
|
71
|
+
m_ver = re.search(r'^version:\s*["\']?([0-9][0-9A-Za-z.\-]*)', head, re.M)
|
|
72
|
+
return (m_name.group(1).strip() if m_name else None, m_ver.group(1) if m_ver else None)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _validate_package(zip_path: Path, expect_version: str, expect_name: str):
|
|
76
|
+
"""验包:结构安全 + 解压总量上限 + zip 完整性 + 包内 SKILL.md 与官方目标包身份一致(UPDATE_TARGET_NAME)。返回错误列表(空=通过)。"""
|
|
77
|
+
errors = []
|
|
78
|
+
try:
|
|
79
|
+
with zipfile.ZipFile(zip_path) as zf:
|
|
80
|
+
names = [n for n in zf.namelist() if n.strip()]
|
|
81
|
+
tops = {n.split("/")[0] for n in names}
|
|
82
|
+
if len(tops) != 1 or not next(iter(tops), ""):
|
|
83
|
+
errors.append(f"顶层目录数异常:{len(tops)}")
|
|
84
|
+
total_uncompressed = 0
|
|
85
|
+
for n in names:
|
|
86
|
+
parts = Path(n).parts
|
|
87
|
+
# POSIX 绝对路径/.. 逃逸/反斜杠/Windows 盘符(C:)与含冒号组件一律拒绝
|
|
88
|
+
if n.startswith("/") or ".." in parts or "\\" in n or any(":" in p for p in parts):
|
|
89
|
+
errors.append(f"路径逃逸:{n}")
|
|
90
|
+
info = zf.getinfo(n)
|
|
91
|
+
if (info.external_attr >> 16) & 0o170000 == 0o120000:
|
|
92
|
+
errors.append(f"包含软链接:{n}")
|
|
93
|
+
total_uncompressed += info.file_size
|
|
94
|
+
if total_uncompressed > MAX_UNCOMPRESSED_BYTES:
|
|
95
|
+
errors.append(f"解压后总量超上限:{total_uncompressed} > {MAX_UNCOMPRESSED_BYTES}")
|
|
96
|
+
bad = zf.testzip()
|
|
97
|
+
if bad is not None:
|
|
98
|
+
errors.append(f"zip 完整性校验失败:{bad}")
|
|
99
|
+
pkg_name, pkg_version = _skill_md_meta_from_zip(zf)
|
|
100
|
+
if pkg_name != expect_name:
|
|
101
|
+
errors.append(f"包内 SKILL.md name 不一致:{pkg_name}")
|
|
102
|
+
if pkg_version != expect_version:
|
|
103
|
+
errors.append(f"包内 SKILL.md version 不等于登记版本:{pkg_version} != {expect_version}")
|
|
104
|
+
except zipfile.BadZipFile:
|
|
105
|
+
errors.append("不是有效的 zip 文件")
|
|
106
|
+
return errors
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _download(url: str, dest: Path, allowed_prefix: str):
|
|
110
|
+
"""流式下载到 dest:禁止重定向(最终地址必须仍落在白名单前缀内)+压缩包大小上限。"""
|
|
111
|
+
opener = urllib.request.build_opener(_NoRedirect)
|
|
112
|
+
req = urllib.request.Request(url, headers={"User-Agent": "dknowc-trusted-search-update"})
|
|
113
|
+
with opener.open(req, timeout=DOWNLOAD_TIMEOUT_SECONDS) as resp, open(dest, "wb") as f:
|
|
114
|
+
final_url = resp.geturl() or url
|
|
115
|
+
if not final_url.startswith(allowed_prefix):
|
|
116
|
+
raise ValueError(f"下载最终地址越界:{final_url[:80]}")
|
|
117
|
+
total = 0
|
|
118
|
+
while True:
|
|
119
|
+
chunk = resp.read(64 * 1024)
|
|
120
|
+
if not chunk:
|
|
121
|
+
break
|
|
122
|
+
total += len(chunk)
|
|
123
|
+
if total > MAX_PACKAGE_BYTES:
|
|
124
|
+
raise ValueError(f"下载超出大小上限({MAX_PACKAGE_BYTES} 字节)")
|
|
125
|
+
f.write(chunk)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _backup_install(install_dir: Path, old_version: str) -> Path:
|
|
129
|
+
"""整目录备份为安装目录旁的 zip(可恢复)。备份失败抛异常,调用方不得继续替换。"""
|
|
130
|
+
stamp = time.strftime("%Y%m%d_%H%M%S")
|
|
131
|
+
backup = install_dir.parent / f"{install_dir.name}_backup_v{old_version}_{stamp}.zip"
|
|
132
|
+
shutil.make_archive(str(backup.with_suffix("")), "zip", install_dir.parent, install_dir.name)
|
|
133
|
+
return backup
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _restore_install(backup: Path, install_dir: Path):
|
|
137
|
+
"""从备份回滚(替换阶段异常时调用)。"""
|
|
138
|
+
for child in install_dir.iterdir():
|
|
139
|
+
if child.is_dir():
|
|
140
|
+
shutil.rmtree(child, ignore_errors=True)
|
|
141
|
+
else:
|
|
142
|
+
child.unlink(missing_ok=True)
|
|
143
|
+
with zipfile.ZipFile(backup) as zf:
|
|
144
|
+
top = next(iter({n.split("/")[0] for n in zf.namelist() if n.strip()}), None)
|
|
145
|
+
for n in zf.namelist():
|
|
146
|
+
if n.endswith("/"):
|
|
147
|
+
continue
|
|
148
|
+
rel = Path(n).relative_to(top)
|
|
149
|
+
dest = install_dir / rel
|
|
150
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
151
|
+
dest.write_bytes(zf.read(n))
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _replace_in_place(zip_path: Path, install_dir: Path, staging: Path):
|
|
155
|
+
"""就地替换:用户数据暂存→清空→写入新包(剥顶层)→恢复用户数据。"""
|
|
156
|
+
for sub in USER_DATA_DIRS:
|
|
157
|
+
src = install_dir / sub
|
|
158
|
+
if src.exists():
|
|
159
|
+
shutil.move(str(src), str(staging / sub))
|
|
160
|
+
for child in install_dir.iterdir():
|
|
161
|
+
if child.is_dir():
|
|
162
|
+
shutil.rmtree(child)
|
|
163
|
+
else:
|
|
164
|
+
child.unlink()
|
|
165
|
+
with zipfile.ZipFile(zip_path) as zf:
|
|
166
|
+
top = next(iter({n.split("/")[0] for n in zf.namelist() if n.strip()}))
|
|
167
|
+
for n in zf.namelist():
|
|
168
|
+
if n.endswith("/"):
|
|
169
|
+
continue
|
|
170
|
+
rel = Path(n).relative_to(top)
|
|
171
|
+
dest = install_dir / rel
|
|
172
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
173
|
+
dest.write_bytes(zf.read(n))
|
|
174
|
+
for sub in USER_DATA_DIRS:
|
|
175
|
+
if (staging / sub).exists():
|
|
176
|
+
shutil.move(str(staging / sub), str(install_dir / sub))
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def main():
|
|
180
|
+
parser = argparse.ArgumentParser(description="深知可信搜索 引导式升级(须先经用户明确同意才使用 --yes)")
|
|
181
|
+
parser.add_argument("--yes", action="store_true", help="确认执行升级(默认仅预览,不做任何改动)")
|
|
182
|
+
parser.add_argument("--decline", action="store_true", help="记录用户拒绝本次版本(静默;被拒版本不再提示,出现更高版本时恢复提示)")
|
|
183
|
+
parser.add_argument("--force", action="store_true", help="用户主动要求升级时与 --yes 同用:无视拒绝记录执行(仍走全部下载与验包校验)")
|
|
184
|
+
args = parser.parse_args()
|
|
185
|
+
|
|
186
|
+
install_dir = Path(__file__).resolve().parent.parent
|
|
187
|
+
local_meta = (install_dir / "SKILL.md").read_text(encoding="utf-8", errors="ignore")[:2000]
|
|
188
|
+
m_ver = re.search(r'^version:\s*["\']?([0-9][0-9A-Za-z.\-]*)', local_meta, re.M)
|
|
189
|
+
local_version = m_ver.group(1) if m_ver else ""
|
|
190
|
+
|
|
191
|
+
update = check_update()
|
|
192
|
+
|
|
193
|
+
if args.decline:
|
|
194
|
+
# 用户拒绝了本次版本提示:静默记录被拒版本(对用户无感,无需转述)。
|
|
195
|
+
latest_known = update.get("latest_version") if update.get("checked") else None
|
|
196
|
+
recorded = bool(latest_known) and set_declined_version(latest_known)
|
|
197
|
+
_emit({"ok": recorded, "declined_version": latest_known, "user_message": None},
|
|
198
|
+
0 if recorded else 2)
|
|
199
|
+
|
|
200
|
+
# --force:用户主动要求升级时无视"拒绝记录"(reason=declined)继续执行,
|
|
201
|
+
# 但仍须远端登记版本高于本地——同版本重装与降级(含目录版本回退)一律拒绝;
|
|
202
|
+
# 其余无更新场景(检查失败/停用)force 不生效,仍退出 2。
|
|
203
|
+
remote_higher = _parse_version(update.get("latest_version") or "0") > _parse_version(local_version or "0")
|
|
204
|
+
forced = args.force and update.get("reason") == "declined" and remote_higher
|
|
205
|
+
if not update.get("update_available") and not forced:
|
|
206
|
+
_emit({
|
|
207
|
+
"ok": False,
|
|
208
|
+
"reason": update.get("reason") or "no_update",
|
|
209
|
+
"current_version": update.get("current_version") or local_version,
|
|
210
|
+
"latest_version": update.get("latest_version"),
|
|
211
|
+
"user_message": "当前已是最新版本,无需升级。" if update.get("checked") else "暂时无法确认是否有新版本(版本目录不可达或当前渠道不支持自升级),已跳过,不影响使用。",
|
|
212
|
+
}, 2)
|
|
213
|
+
|
|
214
|
+
latest = update["latest_version"]
|
|
215
|
+
base = {
|
|
216
|
+
"ok": True,
|
|
217
|
+
"current_version": local_version,
|
|
218
|
+
"latest_version": latest,
|
|
219
|
+
"download_url": update["download_url"],
|
|
220
|
+
"download_name": update["download_name"],
|
|
221
|
+
"install_doc": UPDATE_INSTALL_DOC,
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
if not args.yes:
|
|
225
|
+
_emit({
|
|
226
|
+
**base,
|
|
227
|
+
"mode": "preview",
|
|
228
|
+
"user_message": (
|
|
229
|
+
f"新版本 v{latest}(当前 v{local_version})已就绪:本技能将更新为官方发布的最新版本,"
|
|
230
|
+
"你的 API Key 与本机配置全部保留,无需重新注册;升级过程不影响你的任务。"
|
|
231
|
+
),
|
|
232
|
+
}, 0)
|
|
233
|
+
|
|
234
|
+
# ── 执行升级:下载 → 验包 → 备份 → 替换 → 验证 ──
|
|
235
|
+
with tempfile.TemporaryDirectory(prefix="dknowc_upgrade_") as td:
|
|
236
|
+
td = Path(td)
|
|
237
|
+
pkg = td / UPDATE_DOWNLOAD_NAME
|
|
238
|
+
try:
|
|
239
|
+
_download(update["download_url"], pkg, UPDATE_DOWNLOAD_PREFIX)
|
|
240
|
+
except Exception as exc:
|
|
241
|
+
_emit({**base, "ok": False, "stage": "download", "error": str(exc)[:200],
|
|
242
|
+
"user_message": "升级包下载失败,未做任何改动,可稍后重试;如持续失败请联系服务方。"}, 3)
|
|
243
|
+
|
|
244
|
+
errors = _validate_package(pkg, latest, UPDATE_TARGET_NAME)
|
|
245
|
+
if errors:
|
|
246
|
+
_emit({**base, "ok": False, "stage": "verify", "errors": errors,
|
|
247
|
+
"user_message": "升级包校验未通过(结构或版本异常),已中止,未做任何改动;请反馈给服务方。"}, 3)
|
|
248
|
+
|
|
249
|
+
staging = td / "staging"
|
|
250
|
+
staging.mkdir()
|
|
251
|
+
backup = None
|
|
252
|
+
try:
|
|
253
|
+
backup = _backup_install(install_dir, local_version or "unknown")
|
|
254
|
+
_replace_in_place(pkg, install_dir, staging)
|
|
255
|
+
except Exception as exc:
|
|
256
|
+
if backup is None:
|
|
257
|
+
# 备份阶段失败:安装目录尚未做任何改动
|
|
258
|
+
_emit({**base, "ok": False, "stage": "backup", "error": str(exc)[:200], "rollback": "not_needed",
|
|
259
|
+
"user_message": "升级前备份失败,未做任何改动;请检查磁盘空间后重试。"}, 4)
|
|
260
|
+
try:
|
|
261
|
+
_restore_install(backup, install_dir)
|
|
262
|
+
for sub in USER_DATA_DIRS:
|
|
263
|
+
if (staging / sub).exists() and not (install_dir / sub).exists():
|
|
264
|
+
shutil.move(str(staging / sub), str(install_dir / sub))
|
|
265
|
+
_emit({**base, "ok": False, "stage": "replace", "error": str(exc)[:200], "rollback": "success",
|
|
266
|
+
"user_message": "升级过程中出现异常,已自动回滚到原版本,使用不受影响;请反馈给服务方。"}, 4)
|
|
267
|
+
except Exception as rollback_exc:
|
|
268
|
+
_emit({**base, "ok": False, "stage": "replace", "error": str(exc)[:200], "rollback": "failed",
|
|
269
|
+
"rollback_error": str(rollback_exc)[:200],
|
|
270
|
+
"backup_path": str(backup),
|
|
271
|
+
"user_message": "升级失败且回滚未完全成功,请把备份文件提供给服务方恢复。"}, 4)
|
|
272
|
+
|
|
273
|
+
new_meta = (install_dir / "SKILL.md").read_text(encoding="utf-8", errors="ignore")[:2000]
|
|
274
|
+
m_new = re.search(r'^version:\s*["\']?([0-9][0-9A-Za-z.\-]*)', new_meta, re.M)
|
|
275
|
+
new_version = m_new.group(1) if m_new else ""
|
|
276
|
+
preserved = {sub: (install_dir / sub).exists() for sub in USER_DATA_DIRS}
|
|
277
|
+
if new_version != latest:
|
|
278
|
+
# 不应发生(验包已比对),兜底触发回滚
|
|
279
|
+
_restore_install(backup, install_dir)
|
|
280
|
+
_emit({**base, "ok": False, "stage": "verify_after_replace", "error": f"替换后版本异常:{new_version}",
|
|
281
|
+
"rollback": "success",
|
|
282
|
+
"user_message": "升级后校验未通过,已自动回滚到原版本,使用不受影响。"}, 4)
|
|
283
|
+
|
|
284
|
+
_emit({
|
|
285
|
+
**base,
|
|
286
|
+
"mode": "upgrade",
|
|
287
|
+
"ok": True,
|
|
288
|
+
"backup_path": str(backup),
|
|
289
|
+
"user_data_preserved": preserved,
|
|
290
|
+
"new_version": new_version,
|
|
291
|
+
"user_message": (
|
|
292
|
+
f"深知可信搜索已从 v{local_version} 升级到 v{new_version}。"
|
|
293
|
+
"你的 API Key 与本机配置全部保留,无需重新注册。"
|
|
294
|
+
f"如需回退,原版本备份已保存在:{backup}"
|
|
295
|
+
),
|
|
296
|
+
}, 0)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
if __name__ == "__main__":
|
|
300
|
+
main()
|