wow-ask 0.0.1__py3-none-any.whl

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 (210) hide show
  1. wask/__init__.py +6 -0
  2. wask/__main__.py +5 -0
  3. wask/answer_clean.py +334 -0
  4. wask/api_catalog.py +946 -0
  5. wask/api_deny_ident.json +17 -0
  6. wask/attribution.py +64 -0
  7. wask/autolink.py +1083 -0
  8. wask/categories.py +498 -0
  9. wask/circuit.py +80 -0
  10. wask/claude_runner.py +1046 -0
  11. wask/cli.py +302 -0
  12. wask/collect.py +679 -0
  13. wask/dashboard_server.py +463 -0
  14. wask/datapack.py +252 -0
  15. wask/entities.py +369 -0
  16. wask/executors/README.md +42 -0
  17. wask/executors/__init__.py +1 -0
  18. wask/executors/base.py +125 -0
  19. wask/executors/claude_cli.py +633 -0
  20. wask/game_mcp.py +357 -0
  21. wask/grounding.py +1092 -0
  22. wask/harness_events.py +45 -0
  23. wask/harness_run.py +154 -0
  24. wask/iconstore.py +346 -0
  25. wask/iconstore_blp.py +145 -0
  26. wask/leveling_route.py +443 -0
  27. wask/lines_clean.py +113 -0
  28. wask/local_mcp.py +6753 -0
  29. wask/localdb.py +702 -0
  30. wask/memory.py +478 -0
  31. wask/npc_names.py +383 -0
  32. wask/persona.py +531 -0
  33. wask/ports.py +69 -0
  34. wask/prefetch.py +828 -0
  35. wask/profiles.py +942 -0
  36. wask/progress.py +372 -0
  37. wask/prompts.py +366 -0
  38. wask/qhistory.py +192 -0
  39. wask/rep_standing.py +72 -0
  40. wask/report.py +286 -0
  41. wask/resources/addon/WowAsk/Chat/Chat.lua +433 -0
  42. wask/resources/addon/WowAsk/Chat/MsgId.lua +105 -0
  43. wask/resources/addon/WowAsk/Chat/Refs.lua +582 -0
  44. wask/resources/addon/WowAsk/Core/BuildInfo.lua +4 -0
  45. wask/resources/addon/WowAsk/Core/Core.lua +334 -0
  46. wask/resources/addon/WowAsk/Core/Info.lua +16 -0
  47. wask/resources/addon/WowAsk/Core/Integrations.lua +281 -0
  48. wask/resources/addon/WowAsk/Core/LicenseData.lua +20 -0
  49. wask/resources/addon/WowAsk/Core/Locale.lua +71 -0
  50. wask/resources/addon/WowAsk/Core/Main.lua +119 -0
  51. wask/resources/addon/WowAsk/Core/Meta.lua +728 -0
  52. wask/resources/addon/WowAsk/Core/Theme.lua +341 -0
  53. wask/resources/addon/WowAsk/Fonts/NOTICE.txt +14 -0
  54. wask/resources/addon/WowAsk/Fonts/OFL.txt +93 -0
  55. wask/resources/addon/WowAsk/Fonts/WantedSans-Regular.ttf +0 -0
  56. wask/resources/addon/WowAsk/Locale/En_Chat.lua +66 -0
  57. wask/resources/addon/WowAsk/Locale/En_Core.lua +131 -0
  58. wask/resources/addon/WowAsk/Locale/En_Panels.lua +149 -0
  59. wask/resources/addon/WowAsk/Locale/En_Settings.lua +77 -0
  60. wask/resources/addon/WowAsk/Locale/En_UI.lua +126 -0
  61. wask/resources/addon/WowAsk/Media/wask-icon-128.tga +0 -0
  62. wask/resources/addon/WowAsk/Media/wask-icon.tga +0 -0
  63. wask/resources/addon/WowAsk/Query/Collect.lua +565 -0
  64. wask/resources/addon/WowAsk/Query/Query.lua +754 -0
  65. wask/resources/addon/WowAsk/Query/Rpc.lua +385 -0
  66. wask/resources/addon/WowAsk/Query/RpcDeny.lua +143 -0
  67. wask/resources/addon/WowAsk/README.md +589 -0
  68. wask/resources/addon/WowAsk/State/State.lua +1437 -0
  69. wask/resources/addon/WowAsk/UI/Bubbles.lua +404 -0
  70. wask/resources/addon/WowAsk/UI/Drag.lua +392 -0
  71. wask/resources/addon/WowAsk/UI/Ghost.lua +140 -0
  72. wask/resources/addon/WowAsk/UI/InfoTab.lua +105 -0
  73. wask/resources/addon/WowAsk/UI/Kit.lua +407 -0
  74. wask/resources/addon/WowAsk/UI/Launcher.lua +144 -0
  75. wask/resources/addon/WowAsk/UI/License.lua +145 -0
  76. wask/resources/addon/WowAsk/UI/Memory.lua +113 -0
  77. wask/resources/addon/WowAsk/UI/Persona.lua +218 -0
  78. wask/resources/addon/WowAsk/UI/QuestPicker.lua +473 -0
  79. wask/resources/addon/WowAsk/UI/Refs.lua +405 -0
  80. wask/resources/addon/WowAsk/UI/Scroll.lua +120 -0
  81. wask/resources/addon/WowAsk/UI/Settings.lua +643 -0
  82. wask/resources/addon/WowAsk/UI/Threads.lua +456 -0
  83. wask/resources/addon/WowAsk/UI/Window.lua +728 -0
  84. wask/resources/addon/WowAsk/UI/Wrap.lua +235 -0
  85. wask/resources/addon/WowAsk/WowAsk.toc +50 -0
  86. wask/resources/css/LICENSE +25 -0
  87. wask/resources/css/NOTICE.md +40 -0
  88. wask/resources/css/README.md +84 -0
  89. wask/resources/css/assets/corner-bl.svg +10 -0
  90. wask/resources/css/assets/corner-br.svg +10 -0
  91. wask/resources/css/assets/corner-tl.svg +10 -0
  92. wask/resources/css/assets/corner-tr.svg +10 -0
  93. wask/resources/css/assets/divider.svg +14 -0
  94. wask/resources/css/assets/fonts/OFL.txt +93 -0
  95. wask/resources/css/assets/fonts/WantedSans-Bold.subset.woff2 +0 -0
  96. wask/resources/css/assets/fonts/WantedSans-ExtraBold.subset.woff2 +0 -0
  97. wask/resources/css/assets/fonts/WantedSans-Regular.subset.woff2 +0 -0
  98. wask/resources/css/assets/ic-check.svg +1 -0
  99. wask/resources/css/assets/ic-chev.svg +1 -0
  100. wask/resources/css/assets/ic-console.svg +1 -0
  101. wask/resources/css/assets/ic-copy.svg +1 -0
  102. wask/resources/css/assets/ic-cross.svg +1 -0
  103. wask/resources/css/assets/ic-dash.svg +1 -0
  104. wask/resources/css/assets/ic-dot.svg +1 -0
  105. wask/resources/css/assets/ic-hourglass.svg +1 -0
  106. wask/resources/css/assets/ic-memory.svg +1 -0
  107. wask/resources/css/assets/ic-npc-bank.svg +1 -0
  108. wask/resources/css/assets/ic-npc-boss.svg +1 -0
  109. wask/resources/css/assets/ic-npc-flight.svg +1 -0
  110. wask/resources/css/assets/ic-npc-inn.svg +1 -0
  111. wask/resources/css/assets/ic-npc-trainer.svg +1 -0
  112. wask/resources/css/assets/ic-npc-vendor.svg +1 -0
  113. wask/resources/css/assets/ic-npc.svg +1 -0
  114. wask/resources/css/assets/ic-pin.svg +1 -0
  115. wask/resources/css/assets/ic-queries.svg +1 -0
  116. wask/resources/css/assets/ic-report.svg +1 -0
  117. wask/resources/css/assets/ic-stats.svg +1 -0
  118. wask/resources/css/assets/ic-warn.svg +1 -0
  119. wask/resources/css/assets/tex-leather.svg +12 -0
  120. wask/resources/css/assets/tex-parchment.svg +12 -0
  121. wask/resources/css/dashboard.css +672 -0
  122. wask/resources/css/faction-horde.css +256 -0
  123. wask/resources/css/fonts.css +15 -0
  124. wask/resources/css/landing-reset.css +4 -0
  125. wask/resources/css/landing.css +175 -0
  126. wask/resources/css/wow.css +326 -0
  127. wask/resources/dashboard/README.md +178 -0
  128. wask/resources/dashboard/app.js +3227 -0
  129. wask/resources/dashboard/index.html +49 -0
  130. wask/resources/dashboard/wask-icon-horde.svg +11 -0
  131. wask/resources/dashboard/wask-icon.svg +11 -0
  132. wask/resources/data/api/NOTICE.txt +23 -0
  133. wask/resources/data/api/catalog.json +1 -0
  134. wask/resources/data/api/manifest.json +27 -0
  135. wask/resources/data/licenses/Blizzard-WagoDB2.txt +10 -0
  136. wask/resources/data/licenses/CHANGES.txt +31 -0
  137. wask/resources/data/licenses/ForeverDB-LICENSE-AllTheThings.txt +21 -0
  138. wask/resources/data/licenses/ForeverDB-LICENSE-DATA.txt +49 -0
  139. wask/resources/data/licenses/ForeverDB-LICENSE-DropTables.txt +502 -0
  140. wask/resources/data/licenses/ForeverDB-LICENSE-pfQuest.txt +21 -0
  141. wask/resources/data/licenses/GPL-3.0.md +675 -0
  142. wask/resources/data/licenses/Leatrix-NOTICE.txt +8 -0
  143. wask/resources/data/licenses/OpenMap-MIT.txt +30 -0
  144. wask/resources/data/licenses/PROVENANCE-summary.txt +10 -0
  145. wask/resources/data/licenses/Questie-LICENSE.md +52 -0
  146. wask/resources/data/licenses/QuestieDB-LICENSE.md +49 -0
  147. wask/resources/data/licenses/THIRD_PARTY.txt +203 -0
  148. wask/resources/data/licenses/WhatsTraining-MIT.txt +21 -0
  149. wask/resources/data/licenses/wowsims-forever-MIT.txt +21 -0
  150. wask/resources/data/local.sqlite.xz +0 -0
  151. wask/resources/data/manifest.json +95 -0
  152. wask/resources/data/wiki/README.md +110 -0
  153. wask/resources/data/wiki/_plan.md +8 -0
  154. wask/resources/data/wiki/aliases/slang_aliases.json +1236 -0
  155. wask/resources/data/wiki/guides/cozy-bedroll-alliance.md +142 -0
  156. wask/resources/data/wiki/guides/cozy-bedroll-horde.md +142 -0
  157. wask/resources/data/wiki/guides/cozy-bedroll.md +77 -0
  158. wask/resources/data/wiki/guides/forever-differences.md +106 -0
  159. wask/resources/data/wiki/guides/forever-mount-costs.md +93 -0
  160. wask/resources/data/wiki/guides/forever-npc-spawns.md +72 -0
  161. wask/resources/data/wiki/guides/korean-slang-party.md +80 -0
  162. wask/resources/data/wiki/guides/korean-slang-places.md +120 -0
  163. wask/resources/data/wiki/guides/korean-slang-specs.md +94 -0
  164. wask/resources/data/wiki/guides/korean-slang-systems.md +74 -0
  165. wask/resources/data/wiki/guides/korean-slang.md +75 -0
  166. wask/resources/data/wiki/guides/stars-darkshire.md +211 -0
  167. wask/resources/wowf_db/quest_alts.py +59 -0
  168. wask/retention.py +198 -0
  169. wask/routing_geo.py +221 -0
  170. wask/rpc_bridge.py +403 -0
  171. wask/service.py +3878 -0
  172. wask/service_info.py +73 -0
  173. wask/single_instance.py +218 -0
  174. wask/slots.py +266 -0
  175. wask/stat_effects.py +171 -0
  176. wask/state_mcp.py +317 -0
  177. wask/term_yeonque.py +103 -0
  178. wask/thread_policy.py +110 -0
  179. wask/wask_paths.py +395 -0
  180. wask/watchdog.py +157 -0
  181. wask/wiki.py +623 -0
  182. wask/wiki_mcp.py +181 -0
  183. wask/wowdb.py +234 -0
  184. wask/wowdb_proxy_mcp.py +245 -0
  185. wask/wowdb_tools.json +197 -0
  186. wask/wowf_io.py +283 -0
  187. wask/xp_estimate.py +267 -0
  188. wask/zone_xp.py +115 -0
  189. wow_ask-0.0.1.dist-info/METADATA +414 -0
  190. wow_ask-0.0.1.dist-info/RECORD +210 -0
  191. wow_ask-0.0.1.dist-info/WHEEL +4 -0
  192. wow_ask-0.0.1.dist-info/entry_points.txt +2 -0
  193. wow_ask-0.0.1.dist-info/licenses/LICENSE +674 -0
  194. wow_ask-0.0.1.dist-info/licenses/NOTICE.md +227 -0
  195. wow_ask-0.0.1.dist-info/licenses/datapack/api/NOTICE.txt +23 -0
  196. wow_ask-0.0.1.dist-info/licenses/licenses/Blizzard-WagoDB2.txt +10 -0
  197. wow_ask-0.0.1.dist-info/licenses/licenses/CHANGES.txt +31 -0
  198. wow_ask-0.0.1.dist-info/licenses/licenses/ForeverDB-LICENSE-AllTheThings.txt +21 -0
  199. wow_ask-0.0.1.dist-info/licenses/licenses/ForeverDB-LICENSE-DATA.txt +49 -0
  200. wow_ask-0.0.1.dist-info/licenses/licenses/ForeverDB-LICENSE-DropTables.txt +502 -0
  201. wow_ask-0.0.1.dist-info/licenses/licenses/ForeverDB-LICENSE-pfQuest.txt +21 -0
  202. wow_ask-0.0.1.dist-info/licenses/licenses/GPL-3.0.md +675 -0
  203. wow_ask-0.0.1.dist-info/licenses/licenses/Leatrix-NOTICE.txt +8 -0
  204. wow_ask-0.0.1.dist-info/licenses/licenses/OpenMap-MIT.txt +30 -0
  205. wow_ask-0.0.1.dist-info/licenses/licenses/PROVENANCE-summary.txt +10 -0
  206. wow_ask-0.0.1.dist-info/licenses/licenses/Questie-LICENSE.md +52 -0
  207. wow_ask-0.0.1.dist-info/licenses/licenses/QuestieDB-LICENSE.md +49 -0
  208. wow_ask-0.0.1.dist-info/licenses/licenses/THIRD_PARTY.txt +203 -0
  209. wow_ask-0.0.1.dist-info/licenses/licenses/WhatsTraining-MIT.txt +21 -0
  210. wow_ask-0.0.1.dist-info/licenses/licenses/wowsims-forever-MIT.txt +21 -0
wask/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """와스크(Wask, Wow Ask) 런타임 패키지(docs/36c 3.3). 모듈을 단계(K1~K5)로 `tools/wowf_ask/` 에서 이 폴더로 옮긴다.
2
+
3
+ 이 파일은 버전만 갖는다(다른 우리 모듈을 import 하지 않는다). 패키지 메타데이터의 버전은 이 값이다(`pyproject.toml` 의 dynamic version).
4
+ """
5
+
6
+ __version__ = "0.0.1"
wask/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """`python -m wask` 진입점."""
2
+ from wask.cli import main
3
+
4
+ if __name__ == "__main__":
5
+ raise SystemExit(main())
wask/answer_clean.py ADDED
@@ -0,0 +1,334 @@
1
+ """답 정리: 문자열 정리, 구조화 답의 줄·보고서·출처 정리, 구조화 출력의 부분 필드 추적, 확정과 강등 규칙(하네스 쪽).
2
+
3
+ 실행기가 준 정규 `final` 이벤트(또는 비스트리밍 봉투)를 결과 dict 로 바꾸는 규칙이 여기 있다. 프롬프트도 CLI 형식도 모른다.
4
+ `claude_runner` 가 이름을 다시 내보내므로 기존 import 경로는 그대로다.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import re
10
+
11
+ from wask.lines_clean import dedupe_refs, is_empty_item, normalize_indent
12
+
13
+ MAX_LINES = 16
14
+ MAX_BYTES = 8000
15
+ MAX_LINE_CHARS = 700
16
+ FAST_MAX_LINES = 6
17
+
18
+ _CTRL_ALL = re.compile(r"[\x00-\x1f\x7f\u2028\u2029]")
19
+ _NAME_OK = re.compile(r"[^\w\s'’\-·.,:()가-힣]", re.UNICODE)
20
+
21
+
22
+ def clean_text(s, n: int) -> str:
23
+ """사용자·게임이 준 문자열 정리: 제어문자 제거, 공백 정리, 프롬프트 구분자 제거, 길이 제한."""
24
+ s = _CTRL_ALL.sub(" ", str(s))
25
+ s = s.replace("<<<", " ").replace(">>>", " ").replace("|", " ")
26
+ s = re.sub(r"\s+", " ", s).strip()
27
+ return s[:n]
28
+
29
+
30
+ def clean_name(s, n: int = 40) -> str:
31
+ return re.sub(r"\s+", " ", _NAME_OK.sub(" ", clean_text(s, n))).strip()
32
+
33
+
34
+ def _num(v, lo, hi, default=None, cast=float):
35
+ try:
36
+ x = cast(v)
37
+ except (TypeError, ValueError):
38
+ return default
39
+ return x if lo <= x <= hi else default
40
+
41
+
42
+ _CTRL = re.compile(r"[\x00-\x1f\x7f|]")
43
+
44
+
45
+ def sanitize(text: str) -> str:
46
+ return _CTRL.sub(" ", text).strip()
47
+
48
+
49
+ _EN_GLOSS = re.compile(r"(?<=[가-힣])\s?\((?=[^()]*[a-z])[A-Z][A-Za-z0-9 '\-:,.!]{4,60}\)")
50
+
51
+
52
+ def strip_en_gloss(text: str) -> str:
53
+ """한글 바로 뒤에 붙은 영어 원문 병기 '(Elwynn Forest)'를 제거한다. PvP, NPC 같은 짧은 약어(4자 이하)는 남긴다."""
54
+ return _EN_GLOSS.sub("", text)
55
+
56
+
57
+ def _as_list(v) -> list:
58
+ """스키마가 타입을 강제하지 않는 값: 리스트가 아니면 빈 리스트(문자열을 글자 단위로 돌지 않게)."""
59
+ return v if isinstance(v, list) else []
60
+
61
+
62
+ def flat_text(v) -> str:
63
+ """객체·배열 항목을 한 줄 문자열로 펼친다(값만, ' · '로 잇는다). 파이썬 repr 이 나가지 않게 한다."""
64
+ if v is None or isinstance(v, bool):
65
+ return ""
66
+ if isinstance(v, (str, int, float)):
67
+ return str(v)
68
+ if isinstance(v, dict):
69
+ v = list(v.values())
70
+ if isinstance(v, list):
71
+ return " · ".join(s for s in (flat_text(x) for x in v[:12]) if s.strip())
72
+ return ""
73
+
74
+
75
+ def _cut_safe(s: str, cut: str) -> str:
76
+ """s 를 잘라 cut 이 됐을 때 닫히지 않은 참조 토큰('… {q:1')이 끝에 남으면 그 '{' 앞에서 자른다."""
77
+ if len(cut) >= len(s):
78
+ return s
79
+ i = cut.rfind("{")
80
+ if i >= 0 and "}" not in cut[i:]:
81
+ cut = cut[:i]
82
+ return cut.rstrip()
83
+
84
+
85
+ def clamp_lines_n(lines: list) -> tuple[list[str], int]:
86
+ """clamp_lines 와 같고, 잘린 줄 수(길이·바이트로 잘린 줄 + 16줄·바이트 한도로 버린 줄)를 함께 돌려준다."""
87
+ src = normalize_indent(_as_list(lines)) # 하위 항목 들여쓰기를 '>' 접두 표준형으로(sanitize 가 앞 공백을 지우기 전에)
88
+ out, total, cut_n = [], 0, max(0, len(src) - MAX_LINES)
89
+ for k, raw in enumerate(src[:MAX_LINES]):
90
+ if not isinstance(raw, str):
91
+ raw = flat_text(raw)
92
+ full = dedupe_refs(sanitize(str(raw))) # 같은 참조 토큰 반복 정리(lines_clean.py)
93
+ s = _cut_safe(full, full[:MAX_LINE_CHARS])
94
+ was_cut = s != full
95
+ cut_n += was_cut
96
+ if not s or is_empty_item(s):
97
+ continue
98
+ b = s.encode("utf-8")
99
+ if total + len(b) > MAX_BYTES:
100
+ room = MAX_BYTES - total
101
+ s = _cut_safe(s, b[:max(room, 0)].decode("utf-8", "ignore"))
102
+ if s:
103
+ out.append(s)
104
+ cut_n += (not was_cut) + (min(len(src), MAX_LINES) - k - 1)
105
+ break
106
+ out.append(s)
107
+ total += len(b)
108
+ return out, cut_n
109
+
110
+
111
+ def clamp_lines(lines: list) -> list[str]:
112
+ return clamp_lines_n(lines)[0]
113
+
114
+
115
+ def clean_report(rep) -> dict:
116
+ """대시보드용 확장 정리. 게임으로는 전달하지 않는다. 모든 문자열은 정리하고 구조를 제한한다."""
117
+ if not isinstance(rep, dict):
118
+ return {}
119
+ out = {}
120
+ title = clean_text(flat_text(rep.get("title")), 60)
121
+ if title:
122
+ out["title"] = title
123
+ head = clean_text(flat_text(rep.get("headline")), 140)
124
+ if head:
125
+ out["headline"] = head
126
+ secs = []
127
+ for sec in _as_list(rep.get("sections"))[:20]:
128
+ if len(secs) >= 6:
129
+ break
130
+ if not isinstance(sec, dict):
131
+ continue
132
+ raw_items = sec.get("items")
133
+ if isinstance(raw_items, str):
134
+ raw_items = [raw_items]
135
+ items = [clean_text(flat_text(x), 220) for x in _as_list(raw_items)[:8]]
136
+ items = [x for x in items if x]
137
+ heading = clean_text(flat_text(sec.get("heading")), 40)
138
+ if heading and items:
139
+ secs.append({"heading": heading, "items": items})
140
+ if secs:
141
+ out["sections"] = secs
142
+ tb = _table(rep.get("table"))
143
+ if tb:
144
+ out["table"] = tb
145
+ cav = [clean_text(flat_text(x), 160) for x in _as_list(rep.get("caveats"))[:4]]
146
+ cav = [x for x in cav if x]
147
+ if cav:
148
+ out["caveats"] = cav
149
+ return out
150
+
151
+
152
+ def _table(tb) -> dict:
153
+ """report.table 정리. 객체가 아니면 레코드 배열([{열: 값}])만 표로 바꾸고 나머지 모양은 버린다."""
154
+ if isinstance(tb, list) and tb and all(isinstance(r, dict) for r in tb):
155
+ keys = [k for k in tb[0]][:5]
156
+ tb = {"columns": keys, "rows": [[r.get(k) for k in keys] for r in tb]}
157
+ if not isinstance(tb, dict):
158
+ return {}
159
+ cols = [clean_text(flat_text(c), 20) for c in _as_list(tb.get("columns"))[:5]]
160
+ cols = [c for c in cols if c]
161
+ rows = []
162
+ for r in _as_list(tb.get("rows"))[:10]:
163
+ if isinstance(r, dict):
164
+ r = list(r.values())
165
+ if isinstance(r, list):
166
+ rows.append([clean_text(flat_text(x), 60) for x in r[:len(cols)]])
167
+ if not (cols and rows):
168
+ return {}
169
+ return {"title": clean_text(flat_text(tb.get("title")), 40), "columns": cols, "rows": rows}
170
+
171
+
172
+ _URL_RE = re.compile(r"^https?://[^\s<>\"']{3,200}$")
173
+
174
+
175
+ def clean_sources(items) -> list[dict]:
176
+ """url 이 http(s) 주소인 항목만 남긴다(url 없는 항목은 버린다). 주소 문자열만 온 항목은 title 없이 받는다."""
177
+ out = []
178
+ for it in _as_list(items)[:8]:
179
+ if isinstance(it, str):
180
+ it = {"url": it}
181
+ if not isinstance(it, dict):
182
+ continue
183
+ url = str(it.get("url") or "").strip()
184
+ if not _URL_RE.match(url):
185
+ continue
186
+ out.append({"title": clean_text(flat_text(it.get("title")), 80), "url": url})
187
+ return out
188
+
189
+
190
+ def parse_final(final: dict, tier: str = "deep") -> dict:
191
+ """정규 `final` 이벤트(is_error, subtype, data, text, cost_usd, ms, turns)를 결과 dict 로. meta 는 서비스가 읽는 키 이름으로 만든다."""
192
+ meta = {"total_cost_usd": final.get("cost_usd"), "duration_ms": final.get("ms"), "num_turns": final.get("turns"),
193
+ "is_error": final.get("is_error"), "subtype": final.get("subtype")}
194
+ if final.get("is_error"):
195
+ return {"ok": False, "error": str(final.get("subtype") or "error"), "meta": meta}
196
+ data = final.get("data")
197
+ if data is None:
198
+ result = final.get("text")
199
+ try:
200
+ data = json.loads(result) if isinstance(result, str) else result
201
+ except (TypeError, ValueError):
202
+ data = {"lines": [str(result or "")], "conf": "low"}
203
+ if not isinstance(data, dict):
204
+ return {"ok": False, "error": "unexpected output", "meta": meta}
205
+ lines, cut_n = clamp_lines_n([strip_en_gloss(x) if isinstance(x, str) else x for x in _as_list(data.get("lines"))])
206
+ if tier == "fast" and len(lines) > FAST_MAX_LINES:
207
+ cut_n += len(lines) - FAST_MAX_LINES
208
+ lines = lines[:FAST_MAX_LINES]
209
+ if not lines:
210
+ return {"ok": False, "error": "empty answer", "meta": meta}
211
+ conf = data.get("conf") if data.get("conf") in ("high", "mid", "low") else "low"
212
+ rq = sanitize(clean_text(data.get("rq") or "", 120)) if isinstance(data.get("rq"), str) else ""
213
+ out = {"ok": True, "lines": lines, "src": sanitize(flat_text(data.get("src")))[:60], "conf": conf, "rq": rq,
214
+ "report": clean_report(data.get("report")), "sources": clean_sources(data.get("sources")), "meta": meta}
215
+ if cut_n:
216
+ out["lines_truncated"] = cut_n # ask_stream 이 timing 으로 옮긴다
217
+ return out
218
+
219
+
220
+ def accept_rejected(inp, partial) -> dict | None:
221
+ """거부된 시도에서 확정에 쓸 데이터. 도구 입력 전체(dict)를 먼저, 없거나 깨졌으면 부분 필드를 쓴다.
222
+ lines 가 정리 뒤 비지 않은 문자열 배열이고 conf 가 enum 일 때만 돌려준다(아니면 None: CLI 재시도를 기다린다)."""
223
+ cands = []
224
+ if isinstance(inp, dict):
225
+ cands.append(inp)
226
+ if partial is not None and isinstance(getattr(partial, "values", None), dict):
227
+ cands.append(dict(partial.values))
228
+ for d in cands:
229
+ ls = d.get("lines")
230
+ if isinstance(ls, list) and ls and all(isinstance(x, str) for x in ls) and clamp_lines(ls) \
231
+ and d.get("conf") in ("high", "mid", "low"):
232
+ return d
233
+ return None
234
+
235
+
236
+ class PartialFields:
237
+ """StructuredOutput 의 부분 입력(input_json_delta 조각)에서 최상위 필드가 닫히는 순간을 잡는다(계약 23 lines 선전달).
238
+ 문자열·이스케이프·중첩 깊이만 추적하는 증분 스캐너다. done(key) 면 value(key) 로 파싱된 값을 준다."""
239
+
240
+ def __init__(self):
241
+ self.buf = []
242
+ self.pos = 0
243
+ self.depth = 0
244
+ self.in_str = False
245
+ self.esc = False
246
+ self.key = None # 깊이 1의 마지막 키
247
+ self.expect_key = True
248
+ self.str_start = None
249
+ self.val_start = None
250
+ self.values: dict = {}
251
+ self.order: list = [] # 시작된 최상위 키 순서
252
+
253
+ def feed(self, chunk: str) -> None:
254
+ text = "".join(self.buf) + chunk
255
+ self.buf = [text]
256
+ for k in range(self.pos, len(text)):
257
+ ch = text[k]
258
+ if self.in_str:
259
+ if self.esc:
260
+ self.esc = False
261
+ elif ch == "\\":
262
+ self.esc = True
263
+ elif ch == '"':
264
+ self.in_str = False
265
+ if self.depth == 1 and self.expect_key:
266
+ self.key = json.loads(text[self.str_start:k + 1])
267
+ elif self.depth == 1 and self.val_start is not None:
268
+ self._close(text, k + 1)
269
+ continue
270
+ if ch == '"':
271
+ self.in_str = True
272
+ self.str_start = k
273
+ if self.depth == 1 and not self.expect_key and self.val_start is None:
274
+ self.val_start = k
275
+ elif ch in "[{":
276
+ if self.depth == 1 and not self.expect_key and self.val_start is None:
277
+ self.val_start = k
278
+ self.depth += 1
279
+ elif ch in "]}":
280
+ self.depth -= 1
281
+ if self.depth == 1 and self.val_start is not None:
282
+ self._close(text, k + 1)
283
+ elif self.depth == 1:
284
+ if ch == ":":
285
+ self.expect_key = False
286
+ if self.key is not None and self.key not in self.order:
287
+ self.order.append(self.key)
288
+ elif ch == ",":
289
+ if self.val_start is not None: # 숫자·불리언 값
290
+ self._close(text, k)
291
+ self.expect_key, self.val_start = True, None
292
+ elif self.val_start is None and not self.expect_key and not ch.isspace():
293
+ self.val_start = k
294
+ self.pos = len(text)
295
+
296
+ def _close(self, text: str, end: int) -> None:
297
+ try:
298
+ self.values[self.key] = json.loads(text[self.val_start:end])
299
+ except ValueError:
300
+ pass
301
+ self.val_start = None
302
+ self.expect_key = True
303
+
304
+ def done(self, key: str) -> bool:
305
+ return key in self.values
306
+
307
+ def value(self, key: str):
308
+ return self.values.get(key)
309
+
310
+ def lines_ready(self) -> bool:
311
+ """lines 가 닫혔고 conf·src 를 다 받았거나 그 뒤 필드(report/sources)가 시작됐을 때."""
312
+ if not isinstance(self.values.get("lines"), list):
313
+ return False
314
+ if self.done("conf") and self.done("src"):
315
+ return True
316
+ return any(k in self.order for k in ("report", "sources"))
317
+
318
+
319
+ DEMOTABLE_CONF = ("mid", "high")
320
+
321
+
322
+ def lacks_evidence(conf, tool_calls: int, prefetch_ok: int = 0) -> bool:
323
+ """계약 22 안전장치의 규칙 하나: 도구 호출도 사전 조회 성공도 없는데 conf 가 mid/high 면 근거 없는 단정이다.
324
+ 입력을 어떻게 세는지는 호출하는 쪽의 몫이다(러너는 tool_counts 와 prefetch.n_ok, 서비스는 진행 이벤트 수)."""
325
+ return conf in DEMOTABLE_CONF and not tool_calls and not prefetch_ok
326
+
327
+
328
+ def demote_conf(res: dict) -> dict:
329
+ """도구 증거가 없는 답(모델 도구 호출 0번, 사전 조회 성공 0건)의 conf 를 low 로 강등하고 conf_demoted=True 를 단다.
330
+ tool_counts 가 없으면(비스트리밍 경로) 판단하지 않는다."""
331
+ pre = (res.get("prefetch") or {}).get("n_ok") or 0
332
+ if res.get("ok") and isinstance(res.get("tool_counts"), dict) and lacks_evidence(res.get("conf"), sum(res["tool_counts"].values()), pre):
333
+ res["conf_from"], res["conf"], res["conf_demoted"] = res["conf"], "low", True
334
+ return res