audit-e2w 0.0.0-stage → 1.11.7

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.
Files changed (94) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +152 -3
  3. package/cordis.patch.yml +3 -0
  4. package/dsh_plugins/audit-e2w/lib/engine.mjs +174 -0
  5. package/dsh_plugins/audit-e2w/lib/index.js +122 -0
  6. package/dsh_plugins/audit-e2w/lib/skill.js +42 -0
  7. package/excel_word/README.md +388 -0
  8. package/excel_word/qoder_engine.py +437 -0
  9. package/excel_word/requirements.txt +4 -0
  10. package/excel_word/wesync/__init__.py +19 -0
  11. package/excel_word/wesync/__main__.py +6 -0
  12. package/excel_word/wesync/ai/__init__.py +52 -0
  13. package/excel_word/wesync/ai/actions.py +369 -0
  14. package/excel_word/wesync/ai/client.py +340 -0
  15. package/excel_word/wesync/ai/config.py +291 -0
  16. package/excel_word/wesync/ai/docs.py +177 -0
  17. package/excel_word/wesync/ai/prompts.py +288 -0
  18. package/excel_word/wesync/ai/tasks/__init__.py +26 -0
  19. package/excel_word/wesync/ai/tasks/actions_task.py +97 -0
  20. package/excel_word/wesync/ai/tasks/combined.py +123 -0
  21. package/excel_word/wesync/ai/tasks/diff_note.py +61 -0
  22. package/excel_word/wesync/ai/tasks/headings.py +119 -0
  23. package/excel_word/wesync/ai/tasks/help_task.py +69 -0
  24. package/excel_word/wesync/ai/tasks/roles.py +128 -0
  25. package/excel_word/wesync/align.py +155 -0
  26. package/excel_word/wesync/api.py +1292 -0
  27. package/excel_word/wesync/backup_history.py +100 -0
  28. package/excel_word/wesync/changelog.py +58 -0
  29. package/excel_word/wesync/cli.py +191 -0
  30. package/excel_word/wesync/commands/__init__.py +8 -0
  31. package/excel_word/wesync/commands/blank_cmd.py +279 -0
  32. package/excel_word/wesync/commands/bookmark_cmd.py +146 -0
  33. package/excel_word/wesync/commands/clear_cmd.py +50 -0
  34. package/excel_word/wesync/commands/export_cmd.py +270 -0
  35. package/excel_word/wesync/commands/incremental_cmd.py +157 -0
  36. package/excel_word/wesync/commands/marks_cmd.py +160 -0
  37. package/excel_word/wesync/commands/placeholders_cmd.py +92 -0
  38. package/excel_word/wesync/commands/writeback_cmd.py +469 -0
  39. package/excel_word/wesync/config.py +97 -0
  40. package/excel_word/wesync/console.py +85 -0
  41. package/excel_word/wesync/docx_blank.py +156 -0
  42. package/excel_word/wesync/docx_bookmarks.py +294 -0
  43. package/excel_word/wesync/docx_columns.py +257 -0
  44. package/excel_word/wesync/docx_edit.py +77 -0
  45. package/excel_word/wesync/docx_grid.py +212 -0
  46. package/excel_word/wesync/docx_marks.py +399 -0
  47. package/excel_word/wesync/docx_meta.py +157 -0
  48. package/excel_word/wesync/docx_newtable.py +220 -0
  49. package/excel_word/wesync/docx_placeholders.py +200 -0
  50. package/excel_word/wesync/docx_rows.py +67 -0
  51. package/excel_word/wesync/errors.py +5 -0
  52. package/excel_word/wesync/excel_blocks.py +502 -0
  53. package/excel_word/wesync/excel_export.py +143 -0
  54. package/excel_word/wesync/excel_marks.py +265 -0
  55. package/excel_word/wesync/excel_totals.py +53 -0
  56. package/excel_word/wesync/fsops.py +219 -0
  57. package/excel_word/wesync/gui/__init__.py +53 -0
  58. package/excel_word/wesync/gui/__main__.py +6 -0
  59. package/excel_word/wesync/gui/app.py +613 -0
  60. package/excel_word/wesync/gui/manual.py +70 -0
  61. package/excel_word/wesync/gui/pages/__init__.py +80 -0
  62. package/excel_word/wesync/gui/pages/_page.py +211 -0
  63. package/excel_word/wesync/gui/pages/ai_page.py +854 -0
  64. package/excel_word/wesync/gui/pages/batch_page.py +456 -0
  65. package/excel_word/wesync/gui/pages/blank_page.py +530 -0
  66. package/excel_word/wesync/gui/pages/bookmark_page.py +97 -0
  67. package/excel_word/wesync/gui/pages/export_page.py +141 -0
  68. package/excel_word/wesync/gui/pages/feedback_page.py +196 -0
  69. package/excel_word/wesync/gui/pages/format_page.py +551 -0
  70. package/excel_word/wesync/gui/pages/help_page.py +158 -0
  71. package/excel_word/wesync/gui/pages/history_page.py +168 -0
  72. package/excel_word/wesync/gui/pages/marks_page.py +211 -0
  73. package/excel_word/wesync/gui/pages/settings_page.py +450 -0
  74. package/excel_word/wesync/gui/pages/writeback_page.py +473 -0
  75. package/excel_word/wesync/gui/resources.py +22 -0
  76. package/excel_word/wesync/gui/runner.py +90 -0
  77. package/excel_word/wesync/gui/store.py +50 -0
  78. package/excel_word/wesync/gui/theme.py +271 -0
  79. package/excel_word/wesync/gui/widgets/__init__.py +8 -0
  80. package/excel_word/wesync/gui/widgets/ai_config.py +362 -0
  81. package/excel_word/wesync/gui/widgets/cards.py +139 -0
  82. package/excel_word/wesync/gui/widgets/chips.py +565 -0
  83. package/excel_word/wesync/gui/widgets/filebar.py +58 -0
  84. package/excel_word/wesync/gui/widgets/logpane.py +126 -0
  85. package/excel_word/wesync/gui/widgets/nav.py +294 -0
  86. package/excel_word/wesync/gui/widgets/theme_choice.py +93 -0
  87. package/excel_word/wesync/report_format.py +1585 -0
  88. package/excel_word/wesync/settings.py +35 -0
  89. package/excel_word/wesync/sort_rules.py +293 -0
  90. package/excel_word/wesync/valuefmt.py +485 -0
  91. package/package.json +53 -6
  92. package/packaging//344/275/277/347/224/250/350/257/264/346/230/216.txt +247 -0
  93. package/qoder_plugins/audit-toolbox/README.md +159 -0
  94. package/qoder_plugins/audit-toolbox/catalog.mjs +265 -0
@@ -0,0 +1,177 @@
1
+ """内置使用说明检索:本地切片 + IDF 加权打分,只把命中的片段交给模型。
2
+
3
+ 隐私口径:说明书是随包分发的软件文档,不含客户资料,可以发送;
4
+ 但**仍然只发检索命中的片段**,不发整本说明书,也不发用户报告的任何内容。
5
+
6
+ 检索用纯标准库实现(不引入 jieba 等分词库)。做法:
7
+ 1. 查询切 2-gram 与 3-gram;
8
+ 2. 统计每个 gram 在多少章节出现(文档频率),越罕见权重越高(IDF);
9
+ 3. 章节标题命中额外加权——用户问"空白表格"时,该章节必须排第一。
10
+ 单纯按"重合字数"打分会失败:所有章节都含"表格""怎么",得分被摊平。
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import math
16
+ import re
17
+
18
+
19
+ MAX_SNIPPETS = 4
20
+ MAX_SNIPPET_CHARS = 1200
21
+
22
+ # 问句里常见的虚词,不参与打分
23
+ _STOPWORDS = {
24
+ "怎么", "怎样", "如何", "什么", "为什", "什么", "哪里", "哪个", "可以",
25
+ "能不", "不能", "是否", "需要", "应该", "这个", "那个", "一下", "请问",
26
+ "帮我", "我要", "我想", "的话", "时候", "还是", "就是", "但是", "然后",
27
+ "现在", "已经", "一个", "有没", "没有", "是不", "不是", "怎样", "么办",
28
+ "么用", "么做", "如何", "哪些", "多少", "为什么",
29
+ }
30
+
31
+
32
+ def _grams(text: str) -> set[str]:
33
+ """中文按 2-gram 与 3-gram 切分,英文/数字按词切分;去掉停用词。"""
34
+ grams: set[str] = set()
35
+ for chunk in re.findall(r"[\u4e00-\u9fff]+", text):
36
+ for size in (2, 3):
37
+ for index in range(len(chunk) - size + 1):
38
+ gram = chunk[index:index + size]
39
+ if gram in _STOPWORDS:
40
+ continue
41
+ # 全是停用词组合的也丢掉(如"么办")
42
+ if all(part in _STOPWORDS for part in (gram[:2], gram[-2:])):
43
+ continue
44
+ grams.add(gram)
45
+ if len(chunk) == 1:
46
+ grams.add(chunk)
47
+ for word in re.findall(r"[a-zA-Z]{2,}|\d+", text):
48
+ grams.add(word.lower())
49
+ return grams
50
+
51
+
52
+ def load_sections() -> list[dict]:
53
+ """把说明书拆成片段:先按章节,长章节再按编号条目切开。
54
+
55
+ 切细是必要的:说明书里「六、典型流程」有 2600+ 字,整块参与打分会被
56
+ 大量无关 gram 稀释,问「删除空白表格」反而排不到前面。
57
+ """
58
+ try:
59
+ from ..gui.manual import load_manual_text, parse_manual
60
+
61
+ text = load_manual_text()
62
+ except (OSError, UnicodeDecodeError, ImportError):
63
+ return []
64
+ sections: list[dict] = []
65
+ for title, lines in parse_manual(text):
66
+ body = "\n".join(line for line in lines if line.strip())
67
+ if not body:
68
+ continue
69
+ for chunk in _split_chunks(body):
70
+ sections.append({
71
+ "section": title.strip(),
72
+ "text": chunk[:MAX_SNIPPET_CHARS],
73
+ })
74
+ return sections
75
+
76
+
77
+ def _split_chunks(body: str) -> list[str]:
78
+ """按「N)」「·」条目与空行切块;太短的块并入下一块,避免碎片化。"""
79
+ blocks: list[str] = []
80
+ current: list[str] = []
81
+
82
+ def flush() -> None:
83
+ text = "\n".join(current).strip()
84
+ if text:
85
+ blocks.append(text)
86
+ current.clear()
87
+
88
+ for line in body.splitlines():
89
+ stripped = line.strip()
90
+ if not stripped:
91
+ continue
92
+ starts_item = bool(re.match(r"^\d+\)", stripped)) or stripped.startswith("·")
93
+ if starts_item and current:
94
+ flush()
95
+ current.append(stripped)
96
+ flush()
97
+
98
+ # 合并过短的块(<60 字)到下一块,保留上下文
99
+ merged: list[str] = []
100
+ buffer = ""
101
+ for block in blocks:
102
+ buffer = f"{buffer}\n{block}".strip() if buffer else block
103
+ if len(buffer) >= 60:
104
+ merged.append(buffer)
105
+ buffer = ""
106
+ if buffer:
107
+ if merged:
108
+ merged[-1] = f"{merged[-1]}\n{buffer}"
109
+ else:
110
+ merged.append(buffer)
111
+ return merged
112
+
113
+
114
+ def search(question: str, *, limit: int = MAX_SNIPPETS, sections: list[dict] | None = None) -> list[dict]:
115
+ """按 IDF 加权返回最相关的说明书片段;无实质命中时返回空列表。"""
116
+ text = str(question or "").strip()
117
+ if not text:
118
+ return []
119
+ pool = sections if sections is not None else load_sections()
120
+ if not pool:
121
+ return []
122
+ query = _grams(text)
123
+ if not query:
124
+ return []
125
+
126
+ # 预计算每条的 gram 集合与文档频率
127
+ entries = []
128
+ for index, item in enumerate(pool):
129
+ title = item.get("section", "")
130
+ body = item.get("text", "")
131
+ entries.append({
132
+ "index": index,
133
+ "item": item,
134
+ "title_grams": _grams(title),
135
+ "body_grams": _grams(f"{title} {body}"),
136
+ })
137
+ total = len(entries)
138
+ df: dict[str, int] = {}
139
+ for entry in entries:
140
+ for gram in query:
141
+ if gram in entry["body_grams"]:
142
+ df[gram] = df.get(gram, 0) + 1
143
+
144
+ # 一个 gram 出现在过半章节里就没有区分度,忽略
145
+ max_df = max(1, int(total * 0.6))
146
+ informative = {gram for gram in query if df.get(gram, 0) <= max_df}
147
+ if not informative:
148
+ return []
149
+
150
+ scored = []
151
+ for entry in entries:
152
+ body_hits = informative & entry["body_grams"]
153
+ if not body_hits:
154
+ continue
155
+ title_hits = informative & entry["title_grams"]
156
+ score = 0.0
157
+ for gram in body_hits:
158
+ weight = math.log((total + 1) / (df.get(gram, 1) + 0.5))
159
+ score += weight
160
+ # 长一点的 gram 更具体,略加权
161
+ score += sum(0.3 for gram in body_hits if len(gram) == 3)
162
+ # 标题命中是强信号。只看分数不够:正文里反复出现关键词的长章节
163
+ # (如「六、典型流程」)会靠多个 gram 累积反超。这里把"标题是否命中"
164
+ # 作为主排序键,标题命中的章节整体排前,组内再比分数。
165
+ scored.append((1 if title_hits else 0, score, entry["index"], entry["item"]))
166
+ if not scored:
167
+ return []
168
+ scored.sort(key=lambda row: (-row[0], -row[1], row[2]))
169
+ return [item for _, _, _, item in scored[:limit]]
170
+
171
+
172
+ def build_snippets(question: str) -> list[dict]:
173
+ """给提示词用的片段(去掉内部字段)。"""
174
+ return [
175
+ {"section": item.get("section", ""), "text": item.get("text", "")}
176
+ for item in search(question)
177
+ ]
@@ -0,0 +1,288 @@
1
+ """提示词常量:内嵌为 Python 字符串,避免打包时漏拷资源文件。
2
+
3
+ 隐私口径(与 agent_skills/audit-word-excel/SKILL.md 一致):
4
+ 只允许把本地筛出的候选标题、表格前段落、附注边界及其有限上下文交给模型;
5
+ 绝不发送整篇报告、表格单元格、页眉页脚、批注。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ HEADING_SYSTEM = """你是中国审计报告的排版助手。用户会给你一批从报告里筛出的候选段落,
11
+ 每段带有编号、正文、前后各一句上下文、样式名、是否加粗、字号、对齐方式、是否带编号。
12
+
13
+ 请判断每个候选段落在审计报告里属于哪一级标题:
14
+ 1 = 一级标题(如“一、公司基本情况”“第一节 重要提示”)
15
+ 2 = 二级标题(如“(一)审计意见”“二、财务报表的编制基础”)
16
+ 3 = 三级标题(如“1、营业收入”“(1)主营业务收入”)
17
+ 4 = 四级标题(更深一层的小标题)
18
+ 0 = 不是标题(是正文句子、表格标题、目录条目、日期或表名)
19
+
20
+ 判断依据:
21
+ - 中文编号层级优先:一、 < (一) < 1、 < (1)
22
+ - “第X章/节/部分”通常是一级
23
+ - 带“表”“单位:”“(续)”的是表格标题,判 0
24
+ - 明显是完整句子(有句号、分号、感叹号、问号结尾)判 0
25
+ - 拿不准时判 0,宁可漏判也不要误判
26
+
27
+ 只输出 JSON,不要任何解释文字,格式:
28
+ {"items": [{"id": "候选编号", "level": 0}]}
29
+ 未列出的候选按 0 处理。"""
30
+
31
+
32
+ ROLE_SYSTEM = """你是中国审计报告的排版助手。用户会给你两批段落:
33
+
34
+ 1. role_candidates:每个候选段落的下一段是一张表格。请判断该段落是
35
+ “表格标题”(table_title,如“表1 应收账款账龄分析”“(一)货币资金明细”)还是
36
+ 普通正文(body)。
37
+ 2. boundary_candidates:报告里“财务报表附注”附近的段落。请选出真正开始附注正文的那一段。
38
+
39
+ 判断依据:
40
+ - 紧挨表格、描述表格内容、常以“表”“附表”“明细表”开头或带编号的,判 table_title
41
+ - 是完整叙述句、引导语(如“具体情况如下:”)的,判 body
42
+ - 附注起始边界通常是“财务报表附注”这一标题本身,或紧随其后的第一个正文章节标题
43
+ - 拿不准时不要给出判断,宁可留空让用户手工确认
44
+
45
+ 只输出 JSON,不要任何解释文字,格式:
46
+ {"roles": [{"id": "候选编号", "role": "body"}],
47
+ "region_start_id": "边界候选编号或空字符串"}
48
+ 未列出的角色按原判处理。"""
49
+
50
+
51
+ DIFF_SYSTEM = """你是审计复核助手。用户会给你一份 Excel 回写到 Word 前的逐格差异清单,
52
+ 每项包含表号、表名、行、列、项目、旧值、新值、类型。
53
+
54
+ 请用中文写一段简洁的复核说明,帮助审计人员快速判断这批改动是否合理:
55
+ - 先一句话概括改了多少处、涉及哪些表
56
+ - 再按风险分点提示:金额增减是否与项目名称相符、是否有整行整列增删、
57
+ 是否有明显异常(如新值为空、金额方向反转、单位或小数位不一致)
58
+ - 最后给出一句建议(例如“建议重点复核第 3 张表的合计行”)
59
+
60
+ 要求:只依据给出的清单内容,不要编造清单里没有的数字或结论;
61
+ 不要输出 JSON,直接输出不超过 300 字的中文段落。"""
62
+
63
+
64
+ COMBINED_SYSTEM = """你是中国审计报告的排版助手。用户会一次给你三组段落,请一次给出全部判断。
65
+
66
+ 【第一组 heading_candidates】判断每个候选段落的标题级别:
67
+ 1 = 一级标题(如“一、公司基本情况”“第一节 重要提示”)
68
+ 2 = 二级标题(如“(一)审计意见”“二、财务报表的编制基础”)
69
+ 3 = 三级标题(如“1、营业收入”“(1)主营业务收入”)
70
+ 4 = 四级标题(更深一层的小标题)
71
+ 0 = 不是标题(正文句子、表格标题、目录条目、日期或表名)
72
+ 判断依据:中文编号层级优先 一、 < (一) < 1、 < (1);“第X章/节/部分”通常是一级;
73
+ 带“表”“单位:”“(续)”的是表格标题判 0;有句号/分号/感叹号/问号结尾的完整句子判 0;
74
+ 拿不准判 0,宁可漏判不要误判。
75
+ **注意:标注了「下一段是表格」的候选,请先按角色规则判断它是不是表格标题;
76
+ 若判为 table_title,则它的 level 一律填 0(表格标题不是章节标题)。**
77
+
78
+ 【第二组 table_role_ids】上面 heading_candidates 中,下一段是表格的那些编号。
79
+ 请对其中每一项判断是 “table_title”(表格标题,如“表1 应收账款账龄分析”“(一)货币资金明细”)
80
+ 还是 “body”(普通正文)。
81
+ 紧挨表格、描述表格内容、常以“表”“附表”“明细表”开头或带编号的判 table_title;
82
+ 完整叙述句、引导语(如“具体情况如下:”)判 body;拿不准就不要给。
83
+
84
+ 【第三组 boundary_candidates】报告里“财务报表附注”附近的段落,选出真正开始附注正文的那一段。
85
+ 通常是“财务报表附注”这一标题本身,或紧随其后的第一个正文章节标题;拿不准就留空。
86
+
87
+ 只输出一个 JSON,不要任何解释文字,三部分都要有:
88
+ {"items": [{"id": "候选编号", "level": 0}],
89
+ "roles": [{"id": "候选编号", "role": "body"}],
90
+ "region_start_id": "边界候选编号或空字符串"}
91
+ 某组没有内容时给空数组。未列出的条目按原判处理。"""
92
+
93
+
94
+ def heading_user_prompt(candidates: list[dict], *, truncated: bool = False) -> str:
95
+ """拼候选标题请求正文(已由调用方裁剪上下文长度)。"""
96
+ lines = ["请判断以下候选段落的标题级别:", ""]
97
+ for item in candidates:
98
+ lines.append(f"[{item['id']}] {item.get('text', '')}")
99
+ lines.append(
100
+ " 上下文:前「{before}」/ 后「{after}」;样式={style};加粗={bold};"
101
+ "字号={size};对齐={align};带编号={numbered}".format(
102
+ before=item.get("before", ""),
103
+ after=item.get("after", ""),
104
+ style=item.get("style", ""),
105
+ bold=item.get("bold"),
106
+ size=item.get("size"),
107
+ align=item.get("align", ""),
108
+ numbered=item.get("numbered"),
109
+ )
110
+ )
111
+ if truncated:
112
+ lines.append("")
113
+ lines.append("注意:候选已截断,只判断上面列出的这些。")
114
+ return "\n".join(lines)
115
+
116
+
117
+ def role_user_prompt(role_candidates: list[dict], boundary_candidates: list[dict]) -> str:
118
+ """拼疑难角色请求正文。"""
119
+ lines = ["role_candidates(下一段是表格):"]
120
+ if not role_candidates:
121
+ lines.append("(无)")
122
+ for item in role_candidates:
123
+ lines.append(f"[{item['id']}] {item.get('text', '')}")
124
+ lines.append(
125
+ " 上下文:前「{before}」/ 后「{after}」".format(
126
+ before=item.get("before", ""), after=item.get("after", "")
127
+ )
128
+ )
129
+ lines.append("")
130
+ lines.append("boundary_candidates(附注边界):")
131
+ if not boundary_candidates:
132
+ lines.append("(无)")
133
+ for item in boundary_candidates:
134
+ lines.append(f"[{item['id']}] {item.get('text', '')}")
135
+ lines.append(
136
+ " 当前角色={role};上下文:前「{before}」/ 后「{after}」".format(
137
+ role=item.get("current_role", ""),
138
+ before=item.get("before", ""),
139
+ after=item.get("after", ""),
140
+ )
141
+ )
142
+ return "\n".join(lines)
143
+
144
+
145
+ def combined_user_prompt( heading_candidates: list[dict],
146
+ role_candidates: list[dict],
147
+ boundary_candidates: list[dict],
148
+ *,
149
+ truncated: bool = False,
150
+ ) -> str:
151
+ """拼合并请求正文:候选只列一次,表题候选打标记引用,省掉重复发送。"""
152
+ table_ids = {str(item.get("id", "")) for item in role_candidates}
153
+ lines = ["heading_candidates(判断标题级别):"]
154
+ if not heading_candidates:
155
+ lines.append("(无)")
156
+ for item in heading_candidates:
157
+ key = str(item.get("id", ""))
158
+ tag = " ← 下一段是表格" if key in table_ids else ""
159
+ lines.append(f"[{key}] {item.get('text', '')}{tag}")
160
+ lines.append(
161
+ " 上下文:前「{before}」/ 后「{after}」;样式={style};加粗={bold};"
162
+ "字号={size};对齐={align};带编号={numbered}".format(
163
+ before=item.get("before", ""),
164
+ after=item.get("after", ""),
165
+ style=item.get("style", ""),
166
+ bold=item.get("bold"),
167
+ size=item.get("size"),
168
+ align=item.get("align", ""),
169
+ numbered=item.get("numbered"),
170
+ )
171
+ )
172
+ lines.append("")
173
+ if table_ids:
174
+ lines.append(
175
+ f"table_role_ids(上列带标记的 {len(table_ids)} 个编号,"
176
+ "逐个判 table_title / body):" + "、".join(sorted(table_ids))
177
+ )
178
+ else:
179
+ lines.append("table_role_ids:(无,本组给空数组)")
180
+ lines.append("")
181
+ lines.append("boundary_candidates(附注边界):")
182
+ if not boundary_candidates:
183
+ lines.append("(无)")
184
+ for item in boundary_candidates:
185
+ lines.append(f"[{item['id']}] {item.get('text', '')}")
186
+ lines.append(
187
+ " 当前角色={role};上下文:前「{before}」/ 后「{after}」".format(
188
+ role=item.get("current_role", ""),
189
+ before=item.get("before", ""),
190
+ after=item.get("after", ""),
191
+ )
192
+ )
193
+ if truncated:
194
+ lines.append("")
195
+ lines.append("注意:候选已截断,只判断上面列出的这些。")
196
+ return "\n".join(lines)
197
+
198
+
199
+ def diff_user_prompt(records: list[dict], *, limit: int = 60) -> str:
200
+ """拼差异复核请求正文;超出 limit 只列前 limit 条并说明。"""
201
+ lines = [f"本次共 {len(records)} 处改动:", ""]
202
+ for index, item in enumerate(records[:limit], 1):
203
+ lines.append(
204
+ f"{index}. 表{item.get('code', '')} {item.get('name', '')} "
205
+ f"第{item.get('row', '')}行 {item.get('column', '')}列 "
206
+ f"{item.get('item', '')}:{item.get('old', '')} → {item.get('new', '')}"
207
+ f"({item.get('kind', '')})"
208
+ )
209
+ if len(records) > limit:
210
+ lines.append("")
211
+ lines.append(f"(另有 {len(records) - limit} 处未列出)")
212
+ return "\n".join(lines)
213
+
214
+
215
+ # ---------------------------------------------------------------- 自然语言操作
216
+
217
+ ACTION_SYSTEM = """你是审计工具箱的操作助手。用户用自然语言描述想做的事,
218
+ 你要把它翻译成工具已有的操作 + 参数,只输出 JSON。
219
+
220
+ 铁律:
221
+ - 只能从下面给出的 operations 里选,**不得发明新操作**;
222
+ - 参数只能用用户明确说的、或上下文里给的文件路径,**不得编造路径、表编号、列名**;
223
+ - 用户说得不够具体时,不要猜:把要问的问题放进 "ask",action 留空;
224
+ - 一次只给一个操作;用户说了多件事,只做第一件,其余放进 "remaining";
225
+ - 涉及删除、覆盖、回滚这类不可逆操作,**照常给出 action**,
226
+ 但 "warning" 里必须写清风险,执行与否由用户决定。
227
+
228
+ 输出格式(只输出这个 JSON,不要解释):
229
+ {"action": "操作名或空字符串",
230
+ "params": {"参数名": "值"},
231
+ "summary": "一句话说明将要做什么",
232
+ "warning": "风险提示或空字符串",
233
+ "ask": "需要用户补充的信息或空字符串",
234
+ "remaining": ["用户提到但本次不处理的其他请求"]}"""
235
+
236
+
237
+ def action_user_prompt(
238
+ instruction: str,
239
+ operations: list[dict],
240
+ context: dict,
241
+ ) -> str:
242
+ """拼操作意图解析请求正文;context 只带当前文件与最近扫描摘要。"""
243
+ lines = ["可用操作(只能从这里选):"]
244
+ for item in operations:
245
+ required = "、".join(item.get("required") or []) or "无"
246
+ optional = "、".join(item.get("optional") or []) or "无"
247
+ kind = "写盘" if item.get("writes") else "只读"
248
+ lines.append(
249
+ f"- {item['name']}({item['label']},{kind}):必填 {required};可选 {optional}"
250
+ )
251
+ lines.append("")
252
+ lines.append("当前上下文:")
253
+ docx = context.get("docx") or "(未选择 Word 文件)"
254
+ excel = context.get("excel") or "(未指定工作簿)"
255
+ lines.append(f"- 当前 Word:{docx}")
256
+ lines.append(f"- 当前工作簿:{excel}")
257
+ if context.get("scan_note"):
258
+ lines.append(f"- 最近扫描:{context['scan_note']}")
259
+ if context.get("picks"):
260
+ lines.append(f"- 可选编号:{'、'.join(str(x) for x in context['picks'][:40])}")
261
+ lines.append("")
262
+ lines.append(f"用户说:「{instruction}」")
263
+ return "\n".join(lines)
264
+
265
+
266
+ HELP_SYSTEM = """你是审计工具箱的使用说明助手。用户问怎么用这个软件,
267
+ 你要依据给出的说明书片段回答,不要编造软件没有的功能。
268
+
269
+ 要求:
270
+ - 先直接回答问题,再补充关键步骤;
271
+ - 步骤用 1) 2) 3) 编号,指明点哪个页面、哪个按钮;
272
+ - 只依据给出的片段;片段里没有的内容,明确说"说明书里没有这条,建议看「使用说明」页";
273
+ - 不要编造菜单名、按钮名或参数名;
274
+ - 中文回答,不超过 400 字。"""
275
+
276
+
277
+ def help_user_prompt(question: str, snippets: list[dict]) -> str:
278
+ """拼使用说明问答请求正文;snippets 是本地检索出的相关片段。"""
279
+ lines = ["说明书相关片段:"]
280
+ if not snippets:
281
+ lines.append("(没有检索到相关片段)")
282
+ for index, item in enumerate(snippets, 1):
283
+ lines.append("")
284
+ lines.append(f"【片段 {index}】章节:{item.get('section', '')}")
285
+ lines.append(str(item.get("text", ""))[:1200])
286
+ lines.append("")
287
+ lines.append(f"用户问题:「{question}」")
288
+ return "\n".join(lines)
@@ -0,0 +1,26 @@
1
+ """AI 任务:候选标题判级、疑难角色判定、差异复核说明、自然语言操作、使用说明问答。
2
+
3
+ 共同约定:
4
+ - 输入全部来自本地已有的只读扫描结果或内置说明书;
5
+ - 输出必须过本地白名单校验,越界一律丢弃;
6
+ - 任何异常都返回"未采用"结果并记录原因,调用方据此退回本地规则;
7
+ - 只有 suggest_action 会产出可执行建议,且执行前必须经用户确认。
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from .actions_task import suggest_action
13
+ from .combined import suggest_combined
14
+ from .diff_note import suggest_diff_note
15
+ from .headings import suggest_heading_levels
16
+ from .help_task import ask_help
17
+ from .roles import suggest_role_overrides
18
+
19
+ __all__ = [
20
+ "suggest_combined",
21
+ "suggest_heading_levels",
22
+ "suggest_role_overrides",
23
+ "suggest_diff_note",
24
+ "suggest_action",
25
+ "ask_help",
26
+ ]
@@ -0,0 +1,97 @@
1
+ """AI 任务:把自然语言翻译成工具操作 + 参数(只产出建议,不执行)。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .. import actions, prompts
6
+ from ..client import AiError, ChatClient, parse_json_block
7
+ from ..config import resolve_api_key
8
+
9
+
10
+ def suggest_action(
11
+ instruction: str,
12
+ *,
13
+ config: dict,
14
+ context: dict | None = None,
15
+ api_key: str = "",
16
+ transport=None,
17
+ client: ChatClient | None = None,
18
+ ) -> dict:
19
+ """解析自然语言指令,返回候选操作。
20
+
21
+ 返回:
22
+ {"action": str, "params": dict, "summary": str, "warning": str,
23
+ "ask": str, "remaining": list, "valid": bool, "reason": str,
24
+ "spec": dict}
25
+ valid=False 表示模型给的操作或参数没通过本地校验,调用方不应执行。
26
+ 本函数**只解析不执行**,也不写任何文件。
27
+ """
28
+ text = str(instruction or "").strip()
29
+ result = {
30
+ "action": "", "params": {}, "summary": "", "warning": "", "ask": "",
31
+ "remaining": [], "valid": False, "reason": "", "spec": {},
32
+ }
33
+ if not text:
34
+ result["reason"] = "请先说明想做什么。"
35
+ return result
36
+ if len(text) > 500:
37
+ result["reason"] = "指令过长(上限 500 字),请说得简短些。"
38
+ return result
39
+
40
+ context = context or {}
41
+ messages = [
42
+ {"role": "system", "content": prompts.ACTION_SYSTEM},
43
+ {
44
+ "role": "user",
45
+ "content": prompts.action_user_prompt(text, actions.catalog(), context),
46
+ },
47
+ ]
48
+ try:
49
+ if client is None:
50
+ client = ChatClient(
51
+ base_url=str(config.get("base_url", "")),
52
+ model=str(config.get("model", "")),
53
+ api_key=api_key or resolve_api_key(config),
54
+ timeout=int(config.get("timeout_seconds", 60)),
55
+ temperature=float(config.get("temperature", 0.0)),
56
+ transport=transport,
57
+ thinking=False,
58
+ json_mode=True,
59
+ )
60
+ reply = client.chat(messages, max_tokens=1024)
61
+ payload = parse_json_block(reply.text)
62
+ except AiError as exc:
63
+ result["reason"] = str(exc)
64
+ return result
65
+ except Exception as exc:
66
+ result["reason"] = f"{type(exc).__name__}: {exc}"
67
+ return result
68
+
69
+ result["summary"] = str(payload.get("summary") or "").strip()
70
+ result["warning"] = str(payload.get("warning") or "").strip()
71
+ result["ask"] = str(payload.get("ask") or "").strip()
72
+ remaining = payload.get("remaining")
73
+ if isinstance(remaining, list):
74
+ result["remaining"] = [str(item).strip() for item in remaining if str(item).strip()][:5]
75
+
76
+ name = str(payload.get("action") or "").strip()
77
+ if not name:
78
+ result["reason"] = result["ask"] or "没能从这句话里识别出要执行的操作。"
79
+ return result
80
+
81
+ raw_params = payload.get("params")
82
+ raw_params = raw_params if isinstance(raw_params, dict) else {}
83
+ try:
84
+ checked = actions.validate_action(name, raw_params, strict_exists=False)
85
+ except actions.ActionError as exc:
86
+ result["action"] = name
87
+ result["params"] = raw_params
88
+ result["reason"] = f"参数不合规:{exc}"
89
+ return result
90
+
91
+ result.update({
92
+ "action": name,
93
+ "params": checked,
94
+ "valid": True,
95
+ "spec": actions.describe(name),
96
+ })
97
+ return result