dsh-biocore 0.1.0 → 0.1.2

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 (250) hide show
  1. package/README.md +2 -2
  2. package/lib/py/bridge.py +15 -7
  3. package/lib/py-bridge.js +4 -3
  4. package/package.json +3 -2
  5. package/python/biocore_memory/__init__.py +21 -0
  6. package/python/biocore_memory/adapters/__init__.py +2 -0
  7. package/python/biocore_memory/adapters/astrbot.py +24 -0
  8. package/python/biocore_memory/adapters/dsh_cli.py +335 -0
  9. package/python/biocore_memory/co_recall.py +324 -0
  10. package/python/biocore_memory/consolidate/__init__.py +11 -0
  11. package/python/biocore_memory/consolidate/gated.py +104 -0
  12. package/python/biocore_memory/consolidate/neighbors.py +68 -0
  13. package/python/biocore_memory/consolidate/reflection.py +45 -0
  14. package/python/biocore_memory/consolidate/tree.py +95 -0
  15. package/python/biocore_memory/consolidate/writeback.py +181 -0
  16. package/python/biocore_memory/core/__init__.py +4 -0
  17. package/python/biocore_memory/core/config.py +127 -0
  18. package/python/biocore_memory/core/permissions.py +69 -0
  19. package/python/biocore_memory/core/types.py +116 -0
  20. package/python/biocore_memory/core/util.py +26 -0
  21. package/python/biocore_memory/embedding_local.py +447 -0
  22. package/python/biocore_memory/embedding_mode.py +156 -0
  23. package/python/biocore_memory/engine.py +2476 -0
  24. package/python/biocore_memory/engine_helpers.py +266 -0
  25. package/python/biocore_memory/event/__init__.py +3 -0
  26. package/python/biocore_memory/event/_types.py +16 -0
  27. package/python/biocore_memory/event/consistency.py +117 -0
  28. package/python/biocore_memory/event/extract.py +48 -0
  29. package/python/biocore_memory/event/media.py +111 -0
  30. package/python/biocore_memory/event/notes.py +85 -0
  31. package/python/biocore_memory/event/notes_link.py +87 -0
  32. package/python/biocore_memory/event/vector.py +69 -0
  33. package/python/biocore_memory/evict/__init__.py +3 -0
  34. package/python/biocore_memory/evict/adaptive.py +73 -0
  35. package/python/biocore_memory/evict/consequence.py +58 -0
  36. package/python/biocore_memory/evict/heat.py +54 -0
  37. package/python/biocore_memory/evict/inhibition.py +105 -0
  38. package/python/biocore_memory/evict/policy.py +188 -0
  39. package/python/biocore_memory/evict/score.py +23 -0
  40. package/python/biocore_memory/identity/__init__.py +6 -0
  41. package/python/biocore_memory/identity/api.py +99 -0
  42. package/python/biocore_memory/identity/history.py +9 -0
  43. package/python/biocore_memory/identity/ledger.py +191 -0
  44. package/python/biocore_memory/identity/narrative.py +358 -0
  45. package/python/biocore_memory/identity/snapshot.py +13 -0
  46. package/python/biocore_memory/identity/writeback.py +61 -0
  47. package/python/biocore_memory/index/__init__.py +3 -0
  48. package/python/biocore_memory/index/cue_index.py +80 -0
  49. package/python/biocore_memory/index/entities.py +85 -0
  50. package/python/biocore_memory/index/entity_boost.py +104 -0
  51. package/python/biocore_memory/index/graph.py +172 -0
  52. package/python/biocore_memory/recall/__init__.py +5 -0
  53. package/python/biocore_memory/recall/api.py +65 -0
  54. package/python/biocore_memory/recall/bm25.py +118 -0
  55. package/python/biocore_memory/recall/channels.py +98 -0
  56. package/python/biocore_memory/recall/complexity.py +62 -0
  57. package/python/biocore_memory/recall/constraints.py +75 -0
  58. package/python/biocore_memory/recall/embedding.py +745 -0
  59. package/python/biocore_memory/recall/expand.py +26 -0
  60. package/python/biocore_memory/recall/filters.py +40 -0
  61. package/python/biocore_memory/recall/fusion.py +18 -0
  62. package/python/biocore_memory/recall/mmr.py +70 -0
  63. package/python/biocore_memory/recall/ppr.py +85 -0
  64. package/python/biocore_memory/recall/retrieval_practice.py +102 -0
  65. package/python/biocore_memory/relay/__init__.py +2 -0
  66. package/python/biocore_memory/relay/card.py +51 -0
  67. package/python/biocore_memory/slots/__init__.py +18 -0
  68. package/python/biocore_memory/slots/admission.py +64 -0
  69. package/python/biocore_memory/slots/boundary.py +128 -0
  70. package/python/biocore_memory/slots/evict_bridge.py +106 -0
  71. package/python/biocore_memory/slots/registry.py +135 -0
  72. package/python/biocore_memory/slots/switch.py +42 -0
  73. package/python/biocore_memory/store/__init__.py +4 -0
  74. package/python/biocore_memory/store/audit.py +74 -0
  75. package/python/biocore_memory/store/compress.py +81 -0
  76. package/python/biocore_memory/store/dedupe.py +178 -0
  77. package/python/biocore_memory/store/json_store.py +154 -0
  78. package/python/biocore_memory/store/media.py +145 -0
  79. package/python/biocore_memory/store/provenance.py +73 -0
  80. package/python/biocore_memory/store/rate_limit.py +93 -0
  81. package/python/biocore_memory/store/security.py +107 -0
  82. package/python/biocore_memory/store/source_consistency.py +123 -0
  83. package/python/biocore_memory/store/tiering.py +61 -0
  84. package/python/biocore_memory/store/tiering_exec.py +50 -0
  85. package/python/biocore_memory/store/tombstone.py +23 -0
  86. package/python/biocore_memory/store/versions.py +69 -0
  87. package/python/biocore_memory/thread/__init__.py +2 -0
  88. package/python/biocore_memory/thread/card.py +58 -0
  89. package/python/biocore_model/__init__.py +37 -0
  90. package/python/biocore_model/affective_labor.py +162 -0
  91. package/python/biocore_model/appraisal.py +257 -0
  92. package/python/biocore_model/appraisal_action.py +78 -0
  93. package/python/biocore_model/archive_queue.py +60 -0
  94. package/python/biocore_model/attachment_behavior.py +130 -0
  95. package/python/biocore_model/attachment_regulation.py +75 -0
  96. package/python/biocore_model/attachment_state.py +41 -0
  97. package/python/biocore_model/attribution.py +73 -0
  98. package/python/biocore_model/attributor.py +162 -0
  99. package/python/biocore_model/autonomic.py +91 -0
  100. package/python/biocore_model/autonomy_affect.py +51 -0
  101. package/python/biocore_model/autonomy_check.py +67 -0
  102. package/python/biocore_model/autonomy_loop.py +122 -0
  103. package/python/biocore_model/autonomy_mode.py +114 -0
  104. package/python/biocore_model/autonomy_model.py +733 -0
  105. package/python/biocore_model/autonomy_params.py +131 -0
  106. package/python/biocore_model/autonomy_reason.py +73 -0
  107. package/python/biocore_model/autonomy_tick.py +227 -0
  108. package/python/biocore_model/bio_appraisal.py +49 -0
  109. package/python/biocore_model/bio_autonomy_state.py +171 -0
  110. package/python/biocore_model/bio_config.py +221 -0
  111. package/python/biocore_model/bio_const.py +128 -0
  112. package/python/biocore_model/bio_daily.py +267 -0
  113. package/python/biocore_model/bio_emotion.py +538 -0
  114. package/python/biocore_model/bio_emotion2.py +214 -0
  115. package/python/biocore_model/bio_goal.py +220 -0
  116. package/python/biocore_model/bio_identity.py +82 -0
  117. package/python/biocore_model/bio_noise.py +119 -0
  118. package/python/biocore_model/bio_physiology2.py +114 -0
  119. package/python/biocore_model/bio_snapshot.py +324 -0
  120. package/python/biocore_model/bio_state.py +272 -0
  121. package/python/biocore_model/bio_tick.py +310 -0
  122. package/python/biocore_model/bio_util.py +82 -0
  123. package/python/biocore_model/blocks.py +264 -0
  124. package/python/biocore_model/boundary.py +251 -0
  125. package/python/biocore_model/boundary_gate.py +188 -0
  126. package/python/biocore_model/commitment_extractor.py +517 -0
  127. package/python/biocore_model/compassion_fatigue.py +84 -0
  128. package/python/biocore_model/connection_bids.py +120 -0
  129. package/python/biocore_model/core_bridge.py +177 -0
  130. package/python/biocore_model/core_client.py +127 -0
  131. package/python/biocore_model/core_commands.py +112 -0
  132. package/python/biocore_model/core_mode.py +104 -0
  133. package/python/biocore_model/core_mode_ui.mjs +104 -0
  134. package/python/biocore_model/criticality.py +81 -0
  135. package/python/biocore_model/defense_mechanisms.py +272 -0
  136. package/python/biocore_model/delta_budget.py +99 -0
  137. package/python/biocore_model/diag_trace.py +274 -0
  138. package/python/biocore_model/dissonance.py +134 -0
  139. package/python/biocore_model/emotion_geometry.py +108 -0
  140. package/python/biocore_model/emotion_probe.py +209 -0
  141. package/python/biocore_model/entity_graph.py +931 -0
  142. package/python/biocore_model/entity_resolve.py +260 -0
  143. package/python/biocore_model/envy.py +193 -0
  144. package/python/biocore_model/exit_or_silence.py +230 -0
  145. package/python/biocore_model/expr_guard.py +24 -0
  146. package/python/biocore_model/expr_intent.py +77 -0
  147. package/python/biocore_model/expr_state.py +204 -0
  148. package/python/biocore_model/expr_template.py +105 -0
  149. package/python/biocore_model/expr_tone.py +81 -0
  150. package/python/biocore_model/extreme_scenarios.py +205 -0
  151. package/python/biocore_model/feedback_flow.py +227 -0
  152. package/python/biocore_model/feedback_guard.py +129 -0
  153. package/python/biocore_model/feedback_llm.py +163 -0
  154. package/python/biocore_model/feedback_memory.py +96 -0
  155. package/python/biocore_model/feedback_user.py +93 -0
  156. package/python/biocore_model/frustration_curve.py +110 -0
  157. package/python/biocore_model/granularity.py +283 -0
  158. package/python/biocore_model/graph_extract.py +248 -0
  159. package/python/biocore_model/graph_recall.py +221 -0
  160. package/python/biocore_model/intent_render.py +91 -0
  161. package/python/biocore_model/intero_core.py +235 -0
  162. package/python/biocore_model/intero_style.py +116 -0
  163. package/python/biocore_model/layered_memory.py +297 -0
  164. package/python/biocore_model/learning_probe.py +120 -0
  165. package/python/biocore_model/memory_dual.py +224 -0
  166. package/python/biocore_model/memory_forgetting.py +125 -0
  167. package/python/biocore_model/memory_store.py +1399 -0
  168. package/python/biocore_model/metacog.py +153 -0
  169. package/python/biocore_model/migrate.py +733 -0
  170. package/python/biocore_model/migrate_store.py +337 -0
  171. package/python/biocore_model/mind_wander.py +111 -0
  172. package/python/biocore_model/mood.py +48 -0
  173. package/python/biocore_model/narrative.py +172 -0
  174. package/python/biocore_model/needs_esteem.py +116 -0
  175. package/python/biocore_model/needs_events.py +137 -0
  176. package/python/biocore_model/needs_sleep.py +72 -0
  177. package/python/biocore_model/noise_bank.py +95 -0
  178. package/python/biocore_model/persona_flow.mjs +25 -0
  179. package/python/biocore_model/pipeline.py +240 -0
  180. package/python/biocore_model/pipeline_api.py +200 -0
  181. package/python/biocore_model/plugin_config.py +83 -0
  182. package/python/biocore_model/plugin_routes.py +1435 -0
  183. package/python/biocore_model/policy_learning.py +132 -0
  184. package/python/biocore_model/possible_selves.py +110 -0
  185. package/python/biocore_model/predictor.py +178 -0
  186. package/python/biocore_model/preset.py +205 -0
  187. package/python/biocore_model/proactive_context.py +153 -0
  188. package/python/biocore_model/prompt_rules.py +90 -0
  189. package/python/biocore_model/prospective.py +183 -0
  190. package/python/biocore_model/provider_fallback.py +97 -0
  191. package/python/biocore_model/reconstruction.py +132 -0
  192. package/python/biocore_model/regulation_loop.py +179 -0
  193. package/python/biocore_model/regulation_strategies.py +294 -0
  194. package/python/biocore_model/relation_stage.py +130 -0
  195. package/python/biocore_model/relationship_stage.py +95 -0
  196. package/python/biocore_model/render.py +901 -0
  197. package/python/biocore_model/render_guard.mjs +34 -0
  198. package/python/biocore_model/repair_after_boundary.py +350 -0
  199. package/python/biocore_model/reply_limit.py +183 -0
  200. package/python/biocore_model/reply_split.py +203 -0
  201. package/python/biocore_model/rollback.py +143 -0
  202. package/python/biocore_model/runtime.py +479 -0
  203. package/python/biocore_model/sanitize.py +200 -0
  204. package/python/biocore_model/scheduler.py +123 -0
  205. package/python/biocore_model/schema.py +120 -0
  206. package/python/biocore_model/secrecy.py +145 -0
  207. package/python/biocore_model/self_esteem.py +50 -0
  208. package/python/biocore_model/self_intent.py +437 -0
  209. package/python/biocore_model/self_interest.py +263 -0
  210. package/python/biocore_model/self_verification.py +178 -0
  211. package/python/biocore_model/services.py +78 -0
  212. package/python/biocore_model/situation.py +254 -0
  213. package/python/biocore_model/sleep_circadian.py +116 -0
  214. package/python/biocore_model/social_pain.py +69 -0
  215. package/python/biocore_model/social_repair.py +111 -0
  216. package/python/biocore_model/social_theory.py +131 -0
  217. package/python/biocore_model/source_monitoring.py +292 -0
  218. package/python/biocore_model/stages.py +487 -0
  219. package/python/biocore_model/state_tag.py +231 -0
  220. package/python/biocore_model/switch_groups.mjs +201 -0
  221. package/python/biocore_model/tabs_state.mjs +37 -0
  222. package/python/biocore_model/template_expr.py +252 -0
  223. package/python/biocore_model/tools/caps_check.mjs +23 -0
  224. package/python/biocore_model/tools/init_symbols_check.mjs +11 -0
  225. package/python/biocore_model/tools/missing_ids.mjs +16 -0
  226. package/python/biocore_model/tools/scope_check.mjs +19 -0
  227. package/python/biocore_model/topic_control.py +268 -0
  228. package/python/biocore_model/turn_memory.py +152 -0
  229. package/python/biocore_model/ui_compat.mjs +48 -0
  230. package/python/biocore_model/ui_settings.py +266 -0
  231. package/python/biocore_model/ui_settings.py.bak_authority +108 -0
  232. package/python/biocore_model/value_order.py +186 -0
  233. package/python/biocore_model/view_mode.mjs +8 -0
  234. package/python/biocore_model/voice_bank.py +177 -0
  235. package/python/biocore_model/waiting_sense.py +229 -0
  236. package/python/biocore_model/x_directives.py +142 -0
  237. package/python/biocore_runtime/__init__.py +7 -0
  238. package/python/biocore_runtime/pipeline.py +1915 -0
  239. package/python/dsh_adapter/README.md +96 -0
  240. package/python/dsh_adapter/adapter.py +1077 -0
  241. package/python/dsh_adapter/cli.py +107 -0
  242. package/python/dsh_adapter/data/demo_state.json +164 -0
  243. package/python/dsh_adapter/data/verify_state.json +164 -0
  244. package/python/dsh_adapter/tests/__init__.py +1 -0
  245. package/python/dsh_adapter/tests/test_adapter.py +494 -0
  246. package/ui/panel-layout.js +3 -3
  247. package/ui/panel.css +53 -6
  248. package/ui/panel.html +33 -32
  249. package/ui/panel.js +9 -1
  250. package/lib/py/__pycache__/bridge.cpython-310.pyc +0 -0
@@ -0,0 +1,231 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Inline state tag: ask the reply call itself for the state numbers.
3
+
4
+ The reply call is owned by the host, but we control the injected content, so we
5
+ can append ONE instruction that asks for a JSON line after the reply text. When
6
+ the model complies we get the state for free (single call). When it does not,
7
+ callers fall back to the separate probe call.
8
+
9
+ This module is pure: it builds the instruction text and parses the model output.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import re
15
+
16
+ from . import entity_resolve as _er
17
+
18
+ INSTRUCTION = """【回复后附状态】
19
+ 回复正文之后,另起一行,输出这一行(照抄结构,不要解释,不要包在代码块里):
20
+ {"dims":{"goal":0.0,"blame":0.0,"hit":0.0,"involve":0.5},"situation":{"challenge":0.0,"praise":0.0,"hurt":0.0},"why":"不超过20字","c":0.8,"fact":"","entities":[{"name":"小夏","type":"人物"},{"name":"体检","type":"事件"}],"relations":[{"src":"小夏","rel":"have_checkup","dst":"体检","when":"周五"}]}
21
+
22
+ 说明:
23
+ - goal 是目标顺逆(-1 受阻 到 +1 顺利),blame 是责怪对方程度(0 到 1),hit 是被击中程度(0 到 1),involve 是这件事与你的相关程度(0 到 1)
24
+ - situation 三个数表示对方这句话的意图强度:challenge 质疑、praise 夸赞、hurt 受伤
25
+ - why 用你自己的话写一句,不超过 20 字;c 是这句判断的置信度(0 到 1)
26
+ - fact 是对方透露的关于他自己的长期信息(姓名/称呼/家人/住址/工作/长期偏好),不超过 20 字;这句没有就写空字符串 "",不要编造
27
+ - entities 是这句里值得记住的实体,最多 3 个,type 用 人物/地点/事件/话题;别名写进 aliases;没有就给空数组 []
28
+ - relations 是实体间的长期关系,最多 3 条,rel 用英文 snake_case(如 planned/located_at),when 用时间词(今天/昨天/周五/上周);没有就给空数组 []
29
+ - 若这句话对你没有明显影响,输出 {"dims":{"goal":0.0,"blame":0.0,"hit":0.0,"involve":0.2},"why":"没有明显影响","c":0.5}"""
30
+
31
+ DIM_KEYS = {"goal": (-1.0, 1.0), "blame": (0.0, 1.0), "control": (0.0, 1.0),
32
+ "certainty": (0.0, 1.0), "novelty": (0.0, 1.0),
33
+ "involve": (0.0, 1.0), "hit": (0.0, 1.0)}
34
+ SIT_KEYS = ("challenge", "praise", "hurt")
35
+ _CLOSE = re.compile(r'\{\s*"dims".*?\}', re.S)
36
+ _FENCE = re.compile(r'```(?:json)?\s*(\{.*?\})\s*```', re.S)
37
+
38
+
39
+ def instruction() -> str:
40
+ return INSTRUCTION
41
+
42
+
43
+ def _clamp(value, low, high):
44
+ try:
45
+ num = float(value)
46
+ except Exception:
47
+ return None
48
+ if num != num: # NaN
49
+ return None
50
+ return max(low, min(high, num))
51
+
52
+
53
+ def _loads(text):
54
+ try:
55
+ return json.loads(text)
56
+ except Exception:
57
+ return None
58
+
59
+
60
+ def _candidate_blocks(text):
61
+ raw = str(text or "")
62
+ blocks = [m.group(1) for m in _FENCE.finditer(raw)]
63
+ for match in _CLOSE.finditer(raw):
64
+ blocks.append(match.group(0))
65
+ # last resort: outermost braces containing "dims"
66
+ start = raw.find('{"dims"')
67
+ if start >= 0:
68
+ depth = 0
69
+ for idx in range(start, len(raw)):
70
+ if raw[idx] == "{":
71
+ depth += 1
72
+ elif raw[idx] == "}":
73
+ depth -= 1
74
+ if depth == 0:
75
+ blocks.append(raw[start:idx + 1])
76
+ break
77
+ return blocks
78
+
79
+
80
+ MAX_GRAPH_ITEMS = 3
81
+
82
+
83
+ def _bounded_entities(raw) -> list:
84
+ out = []
85
+ if not isinstance(raw, (list, tuple)):
86
+ return out
87
+ for item in raw:
88
+ if len(out) >= MAX_GRAPH_ITEMS:
89
+ break
90
+ if isinstance(item, str):
91
+ name = " ".join(item.split()).strip()[:40]
92
+ if name:
93
+ out.append(name)
94
+ continue
95
+ if isinstance(item, dict):
96
+ name = " ".join(str(item.get("name") or "").split()).strip()[:40]
97
+ if not name:
98
+ continue
99
+ kind = str(item.get("type") or "").strip()[:10]
100
+ # P0-1: the model may declare other names for the same entity.
101
+ aliases = _er.bounded_aliases(item.get("aliases") or item.get("aka"),
102
+ name)
103
+ if aliases:
104
+ row = {"name": name, "aliases": aliases}
105
+ if kind:
106
+ row["type"] = kind
107
+ out.append(row)
108
+ continue
109
+ out.append({"name": name, "type": kind} if kind else name)
110
+ return out
111
+
112
+
113
+ def _bounded_relations(raw) -> list:
114
+ out = []
115
+ if not isinstance(raw, (list, tuple)):
116
+ return out
117
+ for item in raw:
118
+ if len(out) >= MAX_GRAPH_ITEMS:
119
+ break
120
+ if not isinstance(item, dict):
121
+ continue
122
+ src = " ".join(str(item.get("src") or "").split()).strip()[:40]
123
+ rel = " ".join(str(item.get("rel") or "").split()).strip()[:40]
124
+ dst = " ".join(str(item.get("dst") or "").split()).strip()[:40]
125
+ if not src or not rel or not dst:
126
+ continue
127
+ row = {"src": src, "rel": rel, "dst": dst}
128
+ when = " ".join(str(item.get("when") or "").split()).strip()[:20]
129
+ if when:
130
+ row["when"] = when
131
+ out.append(row)
132
+ return out
133
+
134
+
135
+ def parse(text) -> dict:
136
+ """Return {dims, situation, fact, why, confidence, source} or {} when absent."""
137
+ raw = str(text or "")
138
+ if not raw or "dims" not in raw:
139
+ return {}
140
+ for block in reversed(_candidate_blocks(raw)):
141
+ data = _loads(block)
142
+ if not isinstance(data, dict):
143
+ continue
144
+ dims_in = data.get("dims")
145
+ if not isinstance(dims_in, dict):
146
+ continue
147
+ dims = {}
148
+ for key, (low, high) in DIM_KEYS.items():
149
+ if key not in dims_in:
150
+ continue
151
+ value = _clamp(dims_in.get(key), low, high)
152
+ if value is not None:
153
+ dims[key] = value
154
+ situation = {}
155
+ sit_in = data.get("situation")
156
+ if isinstance(sit_in, dict):
157
+ for key in SIT_KEYS:
158
+ value = _clamp(sit_in.get(key), 0.0, 1.0)
159
+ if value is not None:
160
+ situation[key] = value
161
+ why = str(data.get("why") or "").strip()[:40]
162
+ fact = str(data.get("fact") or "").strip()
163
+ if len(fact) > 20:
164
+ fact = fact[:20]
165
+ confidence = _clamp(data.get("c"), 0.0, 1.0)
166
+ if confidence is None:
167
+ confidence = 0.6 if dims else 0.0
168
+ entities = _bounded_entities(data.get("entities"))
169
+ relations = _bounded_relations(data.get("relations"))
170
+ if (not dims and not situation and not fact and not entities
171
+ and not relations):
172
+ continue
173
+ out = {"dims": dims, "situation": situation, "why": why,
174
+ "confidence": confidence, "source": "inline_tag"}
175
+ if fact:
176
+ out["fact"] = fact
177
+ if entities:
178
+ out["entities"] = entities
179
+ if relations:
180
+ out["relations"] = relations
181
+ return out
182
+ return {}
183
+
184
+
185
+ def _balanced_block(raw, start):
186
+ depth = 0
187
+ in_str = False
188
+ escape = False
189
+ for idx in range(start, len(raw)):
190
+ ch = raw[idx]
191
+ if in_str:
192
+ if escape:
193
+ escape = False
194
+ elif ch == "\\":
195
+ escape = True
196
+ elif ch == '"':
197
+ in_str = False
198
+ continue
199
+ if ch == '"':
200
+ in_str = True
201
+ elif ch == "{":
202
+ depth += 1
203
+ elif ch == "}":
204
+ depth -= 1
205
+ if depth == 0:
206
+ return raw[start:idx + 1]
207
+ return ""
208
+
209
+
210
+ def strip(text) -> str:
211
+ """Remove the state tag (balanced braces) from the visible reply text."""
212
+ raw = str(text or "")
213
+ if "dims" not in raw:
214
+ return raw
215
+ out = raw
216
+ while True:
217
+ start = out.find('{"dims"')
218
+ if start < 0:
219
+ break
220
+ block = _balanced_block(out, start)
221
+ if not block:
222
+ break
223
+ out = (out[:start] + out[start + len(block):])
224
+ out = _FENCE.sub("", out)
225
+ # The model sometimes gets cut off mid-tag ("{...\"dims\": {\"goal\"").
226
+ # Balanced blocks are removed above; drop any remaining fragment from the
227
+ # marker so the raw JSON never reaches the visible reply.
228
+ _marker = out.find('{"dims"')
229
+ if _marker >= 0:
230
+ out = out[:_marker]
231
+ return re.sub(r"\n{3,}", "\n\n", out).strip()
@@ -0,0 +1,201 @@
1
+ /** Pure switch grouping for the dashboard (6 aggregate groups over 31 switches).
2
+ * UI-only: no new config keys, no backend semantics. app.js mirrors this table.
3
+ */
4
+ export const SWITCH_GROUPS = {
5
+ memory: {
6
+ label: '记忆', hint: '压缩/总结/洞察/关系印象',
7
+ ids: ['swCompress', 'swHybridRetrieval', 'fn_event_summary_enabled', 'fn_event_ranking_enabled',
8
+ 'fn_insight_enabled', 'swInsightAuto', 'fn_memory_summary_enabled', 'fn_image_caption_enabled',
9
+ 'fn_relationship_impression_enabled', 'fn_repair_hint_enabled', 'fn_diary_enabled',
10
+ 'fn_relationship_narrative_enabled']
11
+ },
12
+ expression: {
13
+ label: '表达', hint: '共情/语用/心智理论/幽默/人格编译',
14
+ ids: ['fn_empathy_hint_enabled', 'fn_pragmatics_hint_enabled',
15
+ 'fn_tom_probe_enabled', 'fn_humor_hint_enabled']
16
+ },
17
+ llm: {
18
+ label: 'LLM 路由', hint: 'LLM 候选开关(人格编译已改为动作按钮)',
19
+ ids: ['swLlmCandidates']
20
+ },
21
+ safety: { label: '安全', hint: '敏感信息掩码与投毒过滤', ids: ['swSafetyEnabled'] },
22
+ visual: {
23
+ label: '视觉', hint: '球体/引力/连线/图层',
24
+ ids: ['swMemoryBallGravity', 'swShowNoise', 'swShowLinks', 'swShowMemoryNodes',
25
+ 'swMemoryBallsImportant', 'swShowEmotionRings', 'swShowEcho', 'swShowDominance', 'swShowSocial']
26
+ },
27
+ system: { label: '系统', hint: '版本/备份为操作按钮,无个体开关', ids: [] }
28
+ }
29
+
30
+ export const GROUP_ORDER = ['memory', 'expression', 'llm', 'safety', 'visual', 'system']
31
+
32
+ export function groupIds() { return GROUP_ORDER.slice() }
33
+ export function switchIds() { return GROUP_ORDER.flatMap((group) => SWITCH_GROUPS[group].ids) }
34
+ export function advancedCount() { return switchIds().length }
35
+ export function classifySwitch(id) {
36
+ for (const group of GROUP_ORDER) {
37
+ if (SWITCH_GROUPS[group].ids.includes(id)) return group
38
+ }
39
+ return ''
40
+ }
41
+ export function hasChildren(group) { return (SWITCH_GROUPS[group] || { ids: [] }).ids.length > 0 }
42
+
43
+ /** 'on' (all true) | 'off' (all false) | 'mixed' (some true); empty groups -> 'off'. */
44
+ export function groupState(group, values = {}) {
45
+ const ids = (SWITCH_GROUPS[group] || { ids: [] }).ids
46
+ if (!ids.length) return 'off'
47
+ const on = ids.filter((id) => values[id] === true).length
48
+ if (on === 0) return 'off'
49
+ if (on === ids.length) return 'on'
50
+ return 'mixed'
51
+ }
52
+
53
+ /** Updates to apply when a group switch is toggled: every child -> value. */
54
+ export function expandGroup(group, value) {
55
+ const ids = (SWITCH_GROUPS[group] || { ids: [] }).ids
56
+ const target = value === true
57
+ const updates = {}
58
+ for (const id of ids) updates[id] = target
59
+ return updates
60
+ }
61
+
62
+ /** Group row text: label + hint + child count. */
63
+ export function groupRowText(group) {
64
+ const meta = SWITCH_GROUPS[group] || { label: group, hint: '', ids: [] }
65
+ return meta.label + (meta.ids.length ? '(' + meta.ids.length + ' 项)' : '') + ' · ' + meta.hint
66
+ }
67
+
68
+ /** Two-tier settings view: simple = groups + core card; advanced = groups + all switches + diagnostics. */
69
+ export const VIEW_MODES = ['simple', 'advanced']
70
+ export const VIEW_STORAGE_KEY = 'biocore_settings_view'
71
+
72
+ export function normalizeViewMode(value) {
73
+ return VIEW_MODES.includes(String(value || '').toLowerCase()) ? String(value).toLowerCase() : 'simple'
74
+ }
75
+
76
+ /** Tabs: every switch belongs to exactly one settings tab; the four core/llm tabs
77
+ * carry status / mode buttons / switches, not group toggles for core status/mode. */
78
+ export const TAB_GROUPS = {
79
+ api: [],
80
+ coreStatus: [],
81
+ safety: ['safety'],
82
+ llm: ['llm'],
83
+ memory: ['memory'],
84
+ expression: ['expression'],
85
+ visual: ['visual'],
86
+ version: [],
87
+ backup: [],
88
+ persona: []
89
+ }
90
+ export const TAB_ORDER = ['api', 'coreStatus', 'safety', 'llm', 'expression', 'memory', 'visual', 'version', 'backup', 'persona']
91
+
92
+ export function tabOfSwitch(id) {
93
+ for (const tab of TAB_ORDER) {
94
+ for (const group of TAB_GROUPS[tab]) {
95
+ if (SWITCH_GROUPS[group].ids.includes(id)) return tab
96
+ }
97
+ }
98
+ return ''
99
+ }
100
+
101
+ /** Required content units per tab (acceptance: the four new tabs are non-empty). */
102
+ export const TAB_CONTENT = {
103
+ api: ['apiGrid'],
104
+ coreStatus: ['statusCard', 'storePath', 'bridgeDiag', 'indexCounts', 'modeButtons', 'inlineConfirm', 'inlineToast', 'riskNote'],
105
+ safety: ['safetySwitch', 'gatingNote'],
106
+ llm: ['llmCandidateSwitch', 'routeSelects', 'budget'],
107
+ memory: ['memorySwitches'],
108
+ expression: ['expressionSwitches'],
109
+ visual: ['visualSwitches'],
110
+ version: ['versionPanel'],
111
+ backup: ['backupPanel'],
112
+ persona: ['personaCompileBtn', 'personaCompileConfirmRow']
113
+ }
114
+ export function tabContentCount(tab) { return (TAB_CONTENT[tab] || []).length }
115
+
116
+ /** Interactive element counts per view mode (pure acceptance helper). */
117
+ export function visibleInteractive(mode) {
118
+ const view = normalizeViewMode(mode)
119
+ const groupSwitches = GROUP_ORDER.length
120
+ const viewButtons = 2
121
+ const modeButtons = 3
122
+ const individual = view === 'advanced' ? advancedCount() : 0
123
+ return { mode: view, groups: groupSwitches, viewButtons, modeButtons, individual, total: groupSwitches + viewButtons + modeButtons + individual }
124
+ }
125
+
126
+ /** Visible element counts for a mode (pure; DOM-free acceptance helper). */
127
+ export function visibleElements(mode) {
128
+ const view = normalizeViewMode(mode)
129
+ const groups = GROUP_ORDER.length
130
+ const switches = advancedCount()
131
+ const coreCard = 1
132
+ const diagnostics = view === 'advanced' ? 1 : 0
133
+ return {
134
+ mode: view,
135
+ groups,
136
+ switches: view === 'advanced' ? switches : 0,
137
+ coreCard,
138
+ diagnostics,
139
+ total: groups + coreCard + (view === 'advanced' ? switches + 1 : 1) // + diagnostics or + view toggle
140
+ }
141
+ }
142
+
143
+ /** Merged visual switches write BOTH legacy local keys (compatibility). */
144
+ export const VISUAL_MERGED_KEYS = {
145
+ swShowMemoryNodes: ['bio_show_memory_nodes', 'bio_show_nodes'],
146
+ swShowLinks: ['bio_show_links', 'bio_show_node_links'],
147
+ swShowEcho: ['bio_show_echo', 'bio_show_ripple']
148
+ }
149
+ export function visualWrites(id, value) {
150
+ const out = {}
151
+ for (const key of VISUAL_MERGED_KEYS[id] || []) out[key] = value === true ? '1' : '0'
152
+ return out
153
+ }
154
+ export function visualReads(id, stored = {}) {
155
+ const keys = VISUAL_MERGED_KEYS[id] || []
156
+ if (!keys.length) return undefined
157
+ return keys.some((key) => (stored[key] === undefined ? true : stored[key] !== '0'))
158
+ }
159
+
160
+ /** Function-domain switches (simple view): each writes back several legacy keys. */
161
+ export const FEATURE_SWITCHES = {
162
+ feat_memory_compress: { label: '记忆压缩', llm: false, ids: ['swCompress'] },
163
+ feat_memory_retrieval: { label: '混合检索', llm: false, ids: ['swHybridRetrieval'] },
164
+ feat_memory_insight: { label: '事件与洞察', llm: false, ids: ['fn_event_summary_enabled','fn_event_ranking_enabled','fn_insight_enabled','swInsightAuto','fn_memory_summary_enabled'] },
165
+ feat_memory_relation: { label: '关系与日记', llm: false, ids: ['fn_relationship_impression_enabled','fn_repair_hint_enabled','fn_diary_enabled','fn_relationship_narrative_enabled'] },
166
+ feat_expression_rules: { label: '情绪表达调节', llm: false, local: true, defaultOn: true, ids: ['fn_empathy_hint_enabled'] },
167
+ feat_visual_nodes: { label: '节点显示', llm: false, ids: ['swShowMemoryNodes'] },
168
+ feat_visual_links: { label: '连线显示', llm: false, ids: ['swShowLinks'] },
169
+ feat_visual_rings: { label: '光环强度', llm: false, ids: ['swShowEcho','swShowDominance','swShowSocial'] },
170
+ feat_safety: { label: '敏感掩码与投毒过滤', llm: false, ids: ['swSafetyEnabled'] },
171
+ feat_llm_image: { label: '图片描述', llm: true, ids: ['fn_image_caption_enabled'] },
172
+ feat_archive_batch: { label: '归档批量', llm: true, local: true, defaultOn: true, ids: [] }
173
+ }
174
+ export const FEATURE_ORDER = ['feat_memory_compress','feat_memory_retrieval','feat_memory_insight','feat_memory_relation','feat_expression_rules','feat_visual_nodes','feat_visual_links','feat_visual_rings','feat_safety','feat_llm_image','feat_archive_batch']
175
+ export const LLM_SIMPLE_CONTROLS = ['feat_llm_image','feat_archive_batch']
176
+
177
+ export function featureIds() { return FEATURE_ORDER.slice() }
178
+ export function featureAbsorbed(id) { return (FEATURE_SWITCHES[id] || { ids: [] }).ids.slice() }
179
+ export function featureAbsorbedAll() { return FEATURE_ORDER.flatMap((id) => featureAbsorbed(id)) }
180
+ export function featureState(id, values = {}) {
181
+ const ids = featureAbsorbed(id)
182
+ if (!ids.length) return 'off'
183
+ const on = ids.filter((key) => values[key] === true).length
184
+ return on === 0 ? 'off' : (on === ids.length ? 'on' : 'mixed')
185
+ }
186
+ export function featureWrites(id, value) {
187
+ const target = value === true
188
+ const updates = {}
189
+ for (const key of featureAbsorbed(id)) updates[key] = target
190
+ return updates
191
+ }
192
+ export function featureLabel(id) {
193
+ const meta = FEATURE_SWITCHES[id] || { label: id, llm: false }
194
+ const tag = meta.llm ? '[LLM] ' : (meta.local ? '[本地] ' : '')
195
+ return tag + meta.label
196
+ }
197
+
198
+ /** Empathy is rendered by the interpretation layer (affect -> text), never an LLM call. */
199
+ export function compatEmpathy(oldValue) {
200
+ return { localOn: oldValue === true, llmContentEnhance: oldValue === true, llmCallsByDefault: 0 }
201
+ }
@@ -0,0 +1,37 @@
1
+ /** Tab persistence helpers (pure; local-storage key contract for the dashboard). */
2
+ export const TAB_STORAGE_KEYS = {
3
+ settings: 'biocore_settings_tab',
4
+ persona: 'biocore_persona_tab',
5
+ session: 'biocore_session_tab',
6
+ intent: 'biocore_intent_tab'
7
+ }
8
+
9
+ export function tabStorageKey(kind) {
10
+ return TAB_STORAGE_KEYS[kind] || ''
11
+ }
12
+
13
+ export function resolveTab(stored, validTabs, fallback) {
14
+ const valid = Array.isArray(validTabs) ? validTabs : []
15
+ return valid.includes(stored) ? stored : fallback
16
+ }
17
+
18
+ export function defaultTab(validTabs, fallback) {
19
+ return resolveTab('', Array.isArray(validTabs) ? validTabs : [], fallback)
20
+ }
21
+
22
+ /** In-memory value wins over storage; storage failure never forces the default. */
23
+ export function resolveActiveTab({ mem = null, stored = '', valid = [], fallback = null } = {}) {
24
+ const list = Array.isArray(valid) ? valid : []
25
+ if (mem && list.includes(mem)) return mem
26
+ if (stored && list.includes(stored)) return stored
27
+ return fallback
28
+ }
29
+
30
+ export function safeRead(storage, key) {
31
+ try { return (storage && storage.getItem && storage.getItem(key)) || '' } catch (e) { return '' }
32
+ }
33
+
34
+ export function safeWrite(storage, key, value) {
35
+ try { if (storage && storage.setItem) { storage.setItem(key, value); return true } } catch (e) { return false }
36
+ return false
37
+ }