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.
- package/README.md +2 -2
- package/lib/py/bridge.py +15 -7
- package/lib/py-bridge.js +4 -3
- package/package.json +3 -2
- package/python/biocore_memory/__init__.py +21 -0
- package/python/biocore_memory/adapters/__init__.py +2 -0
- package/python/biocore_memory/adapters/astrbot.py +24 -0
- package/python/biocore_memory/adapters/dsh_cli.py +335 -0
- package/python/biocore_memory/co_recall.py +324 -0
- package/python/biocore_memory/consolidate/__init__.py +11 -0
- package/python/biocore_memory/consolidate/gated.py +104 -0
- package/python/biocore_memory/consolidate/neighbors.py +68 -0
- package/python/biocore_memory/consolidate/reflection.py +45 -0
- package/python/biocore_memory/consolidate/tree.py +95 -0
- package/python/biocore_memory/consolidate/writeback.py +181 -0
- package/python/biocore_memory/core/__init__.py +4 -0
- package/python/biocore_memory/core/config.py +127 -0
- package/python/biocore_memory/core/permissions.py +69 -0
- package/python/biocore_memory/core/types.py +116 -0
- package/python/biocore_memory/core/util.py +26 -0
- package/python/biocore_memory/embedding_local.py +447 -0
- package/python/biocore_memory/embedding_mode.py +156 -0
- package/python/biocore_memory/engine.py +2476 -0
- package/python/biocore_memory/engine_helpers.py +266 -0
- package/python/biocore_memory/event/__init__.py +3 -0
- package/python/biocore_memory/event/_types.py +16 -0
- package/python/biocore_memory/event/consistency.py +117 -0
- package/python/biocore_memory/event/extract.py +48 -0
- package/python/biocore_memory/event/media.py +111 -0
- package/python/biocore_memory/event/notes.py +85 -0
- package/python/biocore_memory/event/notes_link.py +87 -0
- package/python/biocore_memory/event/vector.py +69 -0
- package/python/biocore_memory/evict/__init__.py +3 -0
- package/python/biocore_memory/evict/adaptive.py +73 -0
- package/python/biocore_memory/evict/consequence.py +58 -0
- package/python/biocore_memory/evict/heat.py +54 -0
- package/python/biocore_memory/evict/inhibition.py +105 -0
- package/python/biocore_memory/evict/policy.py +188 -0
- package/python/biocore_memory/evict/score.py +23 -0
- package/python/biocore_memory/identity/__init__.py +6 -0
- package/python/biocore_memory/identity/api.py +99 -0
- package/python/biocore_memory/identity/history.py +9 -0
- package/python/biocore_memory/identity/ledger.py +191 -0
- package/python/biocore_memory/identity/narrative.py +358 -0
- package/python/biocore_memory/identity/snapshot.py +13 -0
- package/python/biocore_memory/identity/writeback.py +61 -0
- package/python/biocore_memory/index/__init__.py +3 -0
- package/python/biocore_memory/index/cue_index.py +80 -0
- package/python/biocore_memory/index/entities.py +85 -0
- package/python/biocore_memory/index/entity_boost.py +104 -0
- package/python/biocore_memory/index/graph.py +172 -0
- package/python/biocore_memory/recall/__init__.py +5 -0
- package/python/biocore_memory/recall/api.py +65 -0
- package/python/biocore_memory/recall/bm25.py +118 -0
- package/python/biocore_memory/recall/channels.py +98 -0
- package/python/biocore_memory/recall/complexity.py +62 -0
- package/python/biocore_memory/recall/constraints.py +75 -0
- package/python/biocore_memory/recall/embedding.py +745 -0
- package/python/biocore_memory/recall/expand.py +26 -0
- package/python/biocore_memory/recall/filters.py +40 -0
- package/python/biocore_memory/recall/fusion.py +18 -0
- package/python/biocore_memory/recall/mmr.py +70 -0
- package/python/biocore_memory/recall/ppr.py +85 -0
- package/python/biocore_memory/recall/retrieval_practice.py +102 -0
- package/python/biocore_memory/relay/__init__.py +2 -0
- package/python/biocore_memory/relay/card.py +51 -0
- package/python/biocore_memory/slots/__init__.py +18 -0
- package/python/biocore_memory/slots/admission.py +64 -0
- package/python/biocore_memory/slots/boundary.py +128 -0
- package/python/biocore_memory/slots/evict_bridge.py +106 -0
- package/python/biocore_memory/slots/registry.py +135 -0
- package/python/biocore_memory/slots/switch.py +42 -0
- package/python/biocore_memory/store/__init__.py +4 -0
- package/python/biocore_memory/store/audit.py +74 -0
- package/python/biocore_memory/store/compress.py +81 -0
- package/python/biocore_memory/store/dedupe.py +178 -0
- package/python/biocore_memory/store/json_store.py +154 -0
- package/python/biocore_memory/store/media.py +145 -0
- package/python/biocore_memory/store/provenance.py +73 -0
- package/python/biocore_memory/store/rate_limit.py +93 -0
- package/python/biocore_memory/store/security.py +107 -0
- package/python/biocore_memory/store/source_consistency.py +123 -0
- package/python/biocore_memory/store/tiering.py +61 -0
- package/python/biocore_memory/store/tiering_exec.py +50 -0
- package/python/biocore_memory/store/tombstone.py +23 -0
- package/python/biocore_memory/store/versions.py +69 -0
- package/python/biocore_memory/thread/__init__.py +2 -0
- package/python/biocore_memory/thread/card.py +58 -0
- package/python/biocore_model/__init__.py +37 -0
- package/python/biocore_model/affective_labor.py +162 -0
- package/python/biocore_model/appraisal.py +257 -0
- package/python/biocore_model/appraisal_action.py +78 -0
- package/python/biocore_model/archive_queue.py +60 -0
- package/python/biocore_model/attachment_behavior.py +130 -0
- package/python/biocore_model/attachment_regulation.py +75 -0
- package/python/biocore_model/attachment_state.py +41 -0
- package/python/biocore_model/attribution.py +73 -0
- package/python/biocore_model/attributor.py +162 -0
- package/python/biocore_model/autonomic.py +91 -0
- package/python/biocore_model/autonomy_affect.py +51 -0
- package/python/biocore_model/autonomy_check.py +67 -0
- package/python/biocore_model/autonomy_loop.py +122 -0
- package/python/biocore_model/autonomy_mode.py +114 -0
- package/python/biocore_model/autonomy_model.py +733 -0
- package/python/biocore_model/autonomy_params.py +131 -0
- package/python/biocore_model/autonomy_reason.py +73 -0
- package/python/biocore_model/autonomy_tick.py +227 -0
- package/python/biocore_model/bio_appraisal.py +49 -0
- package/python/biocore_model/bio_autonomy_state.py +171 -0
- package/python/biocore_model/bio_config.py +221 -0
- package/python/biocore_model/bio_const.py +128 -0
- package/python/biocore_model/bio_daily.py +267 -0
- package/python/biocore_model/bio_emotion.py +538 -0
- package/python/biocore_model/bio_emotion2.py +214 -0
- package/python/biocore_model/bio_goal.py +220 -0
- package/python/biocore_model/bio_identity.py +82 -0
- package/python/biocore_model/bio_noise.py +119 -0
- package/python/biocore_model/bio_physiology2.py +114 -0
- package/python/biocore_model/bio_snapshot.py +324 -0
- package/python/biocore_model/bio_state.py +272 -0
- package/python/biocore_model/bio_tick.py +310 -0
- package/python/biocore_model/bio_util.py +82 -0
- package/python/biocore_model/blocks.py +264 -0
- package/python/biocore_model/boundary.py +251 -0
- package/python/biocore_model/boundary_gate.py +188 -0
- package/python/biocore_model/commitment_extractor.py +517 -0
- package/python/biocore_model/compassion_fatigue.py +84 -0
- package/python/biocore_model/connection_bids.py +120 -0
- package/python/biocore_model/core_bridge.py +177 -0
- package/python/biocore_model/core_client.py +127 -0
- package/python/biocore_model/core_commands.py +112 -0
- package/python/biocore_model/core_mode.py +104 -0
- package/python/biocore_model/core_mode_ui.mjs +104 -0
- package/python/biocore_model/criticality.py +81 -0
- package/python/biocore_model/defense_mechanisms.py +272 -0
- package/python/biocore_model/delta_budget.py +99 -0
- package/python/biocore_model/diag_trace.py +274 -0
- package/python/biocore_model/dissonance.py +134 -0
- package/python/biocore_model/emotion_geometry.py +108 -0
- package/python/biocore_model/emotion_probe.py +209 -0
- package/python/biocore_model/entity_graph.py +931 -0
- package/python/biocore_model/entity_resolve.py +260 -0
- package/python/biocore_model/envy.py +193 -0
- package/python/biocore_model/exit_or_silence.py +230 -0
- package/python/biocore_model/expr_guard.py +24 -0
- package/python/biocore_model/expr_intent.py +77 -0
- package/python/biocore_model/expr_state.py +204 -0
- package/python/biocore_model/expr_template.py +105 -0
- package/python/biocore_model/expr_tone.py +81 -0
- package/python/biocore_model/extreme_scenarios.py +205 -0
- package/python/biocore_model/feedback_flow.py +227 -0
- package/python/biocore_model/feedback_guard.py +129 -0
- package/python/biocore_model/feedback_llm.py +163 -0
- package/python/biocore_model/feedback_memory.py +96 -0
- package/python/biocore_model/feedback_user.py +93 -0
- package/python/biocore_model/frustration_curve.py +110 -0
- package/python/biocore_model/granularity.py +283 -0
- package/python/biocore_model/graph_extract.py +248 -0
- package/python/biocore_model/graph_recall.py +221 -0
- package/python/biocore_model/intent_render.py +91 -0
- package/python/biocore_model/intero_core.py +235 -0
- package/python/biocore_model/intero_style.py +116 -0
- package/python/biocore_model/layered_memory.py +297 -0
- package/python/biocore_model/learning_probe.py +120 -0
- package/python/biocore_model/memory_dual.py +224 -0
- package/python/biocore_model/memory_forgetting.py +125 -0
- package/python/biocore_model/memory_store.py +1399 -0
- package/python/biocore_model/metacog.py +153 -0
- package/python/biocore_model/migrate.py +733 -0
- package/python/biocore_model/migrate_store.py +337 -0
- package/python/biocore_model/mind_wander.py +111 -0
- package/python/biocore_model/mood.py +48 -0
- package/python/biocore_model/narrative.py +172 -0
- package/python/biocore_model/needs_esteem.py +116 -0
- package/python/biocore_model/needs_events.py +137 -0
- package/python/biocore_model/needs_sleep.py +72 -0
- package/python/biocore_model/noise_bank.py +95 -0
- package/python/biocore_model/persona_flow.mjs +25 -0
- package/python/biocore_model/pipeline.py +240 -0
- package/python/biocore_model/pipeline_api.py +200 -0
- package/python/biocore_model/plugin_config.py +83 -0
- package/python/biocore_model/plugin_routes.py +1435 -0
- package/python/biocore_model/policy_learning.py +132 -0
- package/python/biocore_model/possible_selves.py +110 -0
- package/python/biocore_model/predictor.py +178 -0
- package/python/biocore_model/preset.py +205 -0
- package/python/biocore_model/proactive_context.py +153 -0
- package/python/biocore_model/prompt_rules.py +90 -0
- package/python/biocore_model/prospective.py +183 -0
- package/python/biocore_model/provider_fallback.py +97 -0
- package/python/biocore_model/reconstruction.py +132 -0
- package/python/biocore_model/regulation_loop.py +179 -0
- package/python/biocore_model/regulation_strategies.py +294 -0
- package/python/biocore_model/relation_stage.py +130 -0
- package/python/biocore_model/relationship_stage.py +95 -0
- package/python/biocore_model/render.py +901 -0
- package/python/biocore_model/render_guard.mjs +34 -0
- package/python/biocore_model/repair_after_boundary.py +350 -0
- package/python/biocore_model/reply_limit.py +183 -0
- package/python/biocore_model/reply_split.py +203 -0
- package/python/biocore_model/rollback.py +143 -0
- package/python/biocore_model/runtime.py +479 -0
- package/python/biocore_model/sanitize.py +200 -0
- package/python/biocore_model/scheduler.py +123 -0
- package/python/biocore_model/schema.py +120 -0
- package/python/biocore_model/secrecy.py +145 -0
- package/python/biocore_model/self_esteem.py +50 -0
- package/python/biocore_model/self_intent.py +437 -0
- package/python/biocore_model/self_interest.py +263 -0
- package/python/biocore_model/self_verification.py +178 -0
- package/python/biocore_model/services.py +78 -0
- package/python/biocore_model/situation.py +254 -0
- package/python/biocore_model/sleep_circadian.py +116 -0
- package/python/biocore_model/social_pain.py +69 -0
- package/python/biocore_model/social_repair.py +111 -0
- package/python/biocore_model/social_theory.py +131 -0
- package/python/biocore_model/source_monitoring.py +292 -0
- package/python/biocore_model/stages.py +487 -0
- package/python/biocore_model/state_tag.py +231 -0
- package/python/biocore_model/switch_groups.mjs +201 -0
- package/python/biocore_model/tabs_state.mjs +37 -0
- package/python/biocore_model/template_expr.py +252 -0
- package/python/biocore_model/tools/caps_check.mjs +23 -0
- package/python/biocore_model/tools/init_symbols_check.mjs +11 -0
- package/python/biocore_model/tools/missing_ids.mjs +16 -0
- package/python/biocore_model/tools/scope_check.mjs +19 -0
- package/python/biocore_model/topic_control.py +268 -0
- package/python/biocore_model/turn_memory.py +152 -0
- package/python/biocore_model/ui_compat.mjs +48 -0
- package/python/biocore_model/ui_settings.py +266 -0
- package/python/biocore_model/ui_settings.py.bak_authority +108 -0
- package/python/biocore_model/value_order.py +186 -0
- package/python/biocore_model/view_mode.mjs +8 -0
- package/python/biocore_model/voice_bank.py +177 -0
- package/python/biocore_model/waiting_sense.py +229 -0
- package/python/biocore_model/x_directives.py +142 -0
- package/python/biocore_runtime/__init__.py +7 -0
- package/python/biocore_runtime/pipeline.py +1915 -0
- package/python/dsh_adapter/README.md +96 -0
- package/python/dsh_adapter/adapter.py +1077 -0
- package/python/dsh_adapter/cli.py +107 -0
- package/python/dsh_adapter/data/demo_state.json +164 -0
- package/python/dsh_adapter/data/verify_state.json +164 -0
- package/python/dsh_adapter/tests/__init__.py +1 -0
- package/python/dsh_adapter/tests/test_adapter.py +494 -0
- package/ui/panel-layout.js +3 -3
- package/ui/panel.css +53 -6
- package/ui/panel.html +33 -32
- package/ui/panel.js +9 -1
- package/lib/py/__pycache__/bridge.cpython-310.pyc +0 -0
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Williams 2007 four needs + Leary 1995 state self-esteem (GAP-C)."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
from . import needs_sleep as _bio
|
|
7
|
+
except Exception: # pragma: no cover
|
|
8
|
+
from biocore_model import needs_sleep as _bio
|
|
9
|
+
|
|
10
|
+
NEED_KEYS = ("belonging", "self_esteem", "control", "meaningful_existence")
|
|
11
|
+
BASE_NEED = 0.6
|
|
12
|
+
BASE_ESTEEM = 0.55
|
|
13
|
+
REGRESS_RATE = 0.05
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def clamp(value, low=0.0, high=1.0):
|
|
17
|
+
return max(low, min(high, float(value)))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def defaults():
|
|
21
|
+
"""Deprecated wrapper: delegates to the biological layer (BIO-5)."""
|
|
22
|
+
_bio.defaults(0.0)
|
|
23
|
+
return {key: BASE_NEED for key in NEED_KEYS}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def silence_effects(hours, phases_stalled=False):
|
|
27
|
+
try:
|
|
28
|
+
h = max(0.0, float(hours))
|
|
29
|
+
except Exception:
|
|
30
|
+
h = 0.0
|
|
31
|
+
belonging = max(-0.4, -0.02 * h)
|
|
32
|
+
control = max(-0.3, -0.03 * h) if phases_stalled else 0.0
|
|
33
|
+
meaning = -0.02 * h if h > 48.0 else 0.0
|
|
34
|
+
return {"belonging": belonging, "self_esteem": 0.0,
|
|
35
|
+
"control": control, "meaningful_existence": meaning}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def apply_silence(needs, hours, stalled=False):
|
|
39
|
+
"""Deprecated wrapper: delegates to needs_sleep.need_step."""
|
|
40
|
+
data = _bio.need_step(dict(needs or defaults()), {"silence_hours": float(hours), "stalled": bool(stalled)}, dt=0.0, now=0.0)
|
|
41
|
+
return {key: data[key] for key in NEED_KEYS}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def on_ignored(needs, rejected=False):
|
|
45
|
+
data = _bio.need_step(dict(needs or defaults()), {"ignored": True}, dt=0.0, now=0.0)
|
|
46
|
+
if rejected:
|
|
47
|
+
data["belonging"] = round(clamp(float(data.get("belonging", BASE_NEED)) - 0.02), 4)
|
|
48
|
+
else:
|
|
49
|
+
# BIO-5 delegation keeps the historical mild-ignore value (-0.02 net).
|
|
50
|
+
data["self_esteem"] = round(clamp(float(data.get("self_esteem", BASE_NEED)) + 0.03), 4)
|
|
51
|
+
return {key: data[key] for key in NEED_KEYS}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def on_responded(needs):
|
|
55
|
+
data = _bio.need_step(dict(needs or defaults()), {"responded": True}, dt=0.0, now=0.0)
|
|
56
|
+
return {key: data[key] for key in NEED_KEYS}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def on_praised(needs):
|
|
60
|
+
data = _bio.need_step(dict(needs or defaults()), {"praised": True}, dt=0.0, now=0.0)
|
|
61
|
+
return {key: data[key] for key in NEED_KEYS}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def dominant(needs):
|
|
65
|
+
data = needs or defaults()
|
|
66
|
+
key = min(NEED_KEYS, key=lambda name: float(data.get(name, BASE_NEED)))
|
|
67
|
+
return key if float(data.get(key, BASE_NEED)) < BASE_NEED else ""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
BEHAVIOUR = {
|
|
71
|
+
"belonging": {"drive_delta": 0.03, "arousal_delta": 0.0, "blame_mult": 1.0,
|
|
72
|
+
"confidence_delta": 0.0, "tone": "靠近、亲昵"},
|
|
73
|
+
"self_esteem": {"drive_delta": 0.0, "arousal_delta": 0.0, "blame_mult": 1.3,
|
|
74
|
+
"confidence_delta": -0.05, "tone": "犹豫、少说话"},
|
|
75
|
+
"control": {"drive_delta": 0.0, "arousal_delta": 0.05, "blame_mult": 1.0,
|
|
76
|
+
"confidence_delta": 0.0, "tone": "追问式短句"},
|
|
77
|
+
"meaningful_existence": {"drive_delta": -0.05, "arousal_delta": 0.0, "blame_mult": 1.0,
|
|
78
|
+
"confidence_delta": -0.02, "tone": "更少更淡"},
|
|
79
|
+
"": {"drive_delta": 0.0, "arousal_delta": 0.0, "blame_mult": 1.0,
|
|
80
|
+
"confidence_delta": 0.0, "tone": ""},
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def behaviour(needs):
|
|
85
|
+
key = dominant(needs)
|
|
86
|
+
data = dict(BEHAVIOUR.get(key, BEHAVIOUR[""]))
|
|
87
|
+
data["dominant"] = key
|
|
88
|
+
return data
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def self_esteem_update(current, responded=False, praised=False, ignored=False, rejected=False):
|
|
92
|
+
try:
|
|
93
|
+
value = float(current if current is not None else BASE_ESTEEM)
|
|
94
|
+
except Exception:
|
|
95
|
+
value = BASE_ESTEEM
|
|
96
|
+
if responded or praised:
|
|
97
|
+
value += 0.06
|
|
98
|
+
if ignored or rejected:
|
|
99
|
+
value -= 0.05
|
|
100
|
+
value += (BASE_ESTEEM - value) * REGRESS_RATE
|
|
101
|
+
return round(clamp(value), 4)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def confidence_from_esteem(esteem, base=1.0):
|
|
105
|
+
try:
|
|
106
|
+
value = clamp(esteem)
|
|
107
|
+
except Exception:
|
|
108
|
+
value = BASE_ESTEEM
|
|
109
|
+
return round(clamp(base - 0.5 * (BASE_ESTEEM - value)), 4)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def view(needs, esteem):
|
|
113
|
+
data = dict(needs or defaults())
|
|
114
|
+
dominant_key = dominant(data)
|
|
115
|
+
return {key: round(float(data.get(key, BASE_NEED)), 3) for key in NEED_KEYS} | {
|
|
116
|
+
"dominant": dominant_key, "self_esteem": round(float(esteem or BASE_ESTEEM), 3)}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""P1-3 need-event hooks: events move needs, needs bias behaviour.
|
|
3
|
+
|
|
4
|
+
Until now the four needs (belonging / self_esteem / control /
|
|
5
|
+
meaningful_existence) only drifted back to baseline with time. This module adds
|
|
6
|
+
a deterministic event hook: structured events (judged by the model's dims, not
|
|
7
|
+
by a word table) add bounded per-event deltas, and the resulting deficits bias
|
|
8
|
+
the next expression (approach / assert / clarify / share).
|
|
9
|
+
|
|
10
|
+
Pure functions only: dicts in, dicts out; no IO, no clock, no main import, no
|
|
11
|
+
prompt text.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
NEED_KEYS = ("belonging", "self_esteem", "control", "meaningful_existence")
|
|
16
|
+
DEFAULT_NEEDS = {key: 0.6 for key in NEED_KEYS}
|
|
17
|
+
BASELINE = 0.6
|
|
18
|
+
MAX_EVENTS = 6
|
|
19
|
+
CAPS = {"belonging": 0.05, "self_esteem": 0.05, "control": 0.05,
|
|
20
|
+
"meaningful_existence": 0.04}
|
|
21
|
+
|
|
22
|
+
EVENT_EFFECTS = {
|
|
23
|
+
"praised": {"self_esteem": 0.05, "belonging": 0.02},
|
|
24
|
+
"rejected": {"belonging": -0.05, "self_esteem": -0.04},
|
|
25
|
+
"ignored": {"belonging": -0.04, "control": -0.02,
|
|
26
|
+
"meaningful_existence": -0.03},
|
|
27
|
+
"connected": {"belonging": 0.04, "meaningful_existence": 0.02},
|
|
28
|
+
"achieved": {"self_esteem": 0.04, "control": 0.04,
|
|
29
|
+
"meaningful_existence": 0.02},
|
|
30
|
+
"dismissed": {"self_esteem": -0.04, "control": -0.04},
|
|
31
|
+
"criticized": {"self_esteem": -0.05, "belonging": -0.02},
|
|
32
|
+
"abandoned": {"belonging": -0.05, "meaningful_existence": -0.03},
|
|
33
|
+
}
|
|
34
|
+
EVENT_KINDS = tuple(EVENT_EFFECTS)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _num(value, default=0.0):
|
|
38
|
+
try:
|
|
39
|
+
number = float(value)
|
|
40
|
+
except Exception:
|
|
41
|
+
return float(default)
|
|
42
|
+
if number != number:
|
|
43
|
+
return float(default)
|
|
44
|
+
return number
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _clamp(value, low, high):
|
|
48
|
+
return max(low, min(high, _num(value, 0.0)))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def needs_state(needs):
|
|
52
|
+
"""Clamped need dict; missing needs use the 0.6 baseline."""
|
|
53
|
+
data = needs if isinstance(needs, dict) else {}
|
|
54
|
+
return {key: round(_clamp(data.get(key, BASELINE), 0.0, 1.0), 4)
|
|
55
|
+
for key in NEED_KEYS}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def events_from_dims(dims):
|
|
59
|
+
"""Structured need events judged from the probe's numeric dims."""
|
|
60
|
+
data = dims if isinstance(dims, dict) else {}
|
|
61
|
+
|
|
62
|
+
def _d(key):
|
|
63
|
+
return _clamp(data.get(key, 0.0), 0.0, 1.0)
|
|
64
|
+
|
|
65
|
+
events = []
|
|
66
|
+
goal, blame, hit = _d("goal"), _d("blame"), _d("hit")
|
|
67
|
+
involve, control = _d("involve"), _d("control")
|
|
68
|
+
if goal >= 0.4:
|
|
69
|
+
events.append({"kind": "achieved", "strength": round(goal, 3)})
|
|
70
|
+
if hit >= 0.6:
|
|
71
|
+
events.append({"kind": "rejected", "strength": round(hit, 3)})
|
|
72
|
+
elif blame >= 0.5:
|
|
73
|
+
events.append({"kind": "criticized", "strength": round(blame, 3)})
|
|
74
|
+
if involve >= 0.6:
|
|
75
|
+
events.append({"kind": "connected", "strength": round(involve, 3)})
|
|
76
|
+
if control >= 0.6:
|
|
77
|
+
events.append({"kind": "achieved", "strength": round(control, 3)})
|
|
78
|
+
return events[:MAX_EVENTS]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def apply(needs, events, scale=1.0):
|
|
82
|
+
"""Apply structured events to the needs; returns (needs, report)."""
|
|
83
|
+
current = needs_state(needs)
|
|
84
|
+
factor = _clamp(scale, 0.0, 4.0)
|
|
85
|
+
deltas = {key: 0.0 for key in NEED_KEYS}
|
|
86
|
+
applied = []
|
|
87
|
+
for event in (events or [])[:MAX_EVENTS]:
|
|
88
|
+
if not isinstance(event, dict):
|
|
89
|
+
continue
|
|
90
|
+
kind = str(event.get("kind") or "").strip().lower()
|
|
91
|
+
effects = EVENT_EFFECTS.get(kind)
|
|
92
|
+
if not effects:
|
|
93
|
+
continue
|
|
94
|
+
strength = _clamp(event.get("strength", 1.0), 0.0, 1.0)
|
|
95
|
+
if strength <= 0:
|
|
96
|
+
continue
|
|
97
|
+
for key, value in effects.items():
|
|
98
|
+
if key not in deltas:
|
|
99
|
+
continue
|
|
100
|
+
cap = CAPS[key]
|
|
101
|
+
deltas[key] = max(-cap, min(cap,
|
|
102
|
+
deltas[key] + value * strength * factor))
|
|
103
|
+
applied.append({"kind": kind, "strength": round(strength, 3)})
|
|
104
|
+
after = {}
|
|
105
|
+
for key in NEED_KEYS:
|
|
106
|
+
after[key] = round(_clamp(current[key] + deltas[key], 0.0, 1.0), 4)
|
|
107
|
+
return after, {"deltas": {k: round(v, 4) for k, v in deltas.items()},
|
|
108
|
+
"events": applied, "scale": round(factor, 3)}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def behavior_bias(needs, baseline=BASELINE):
|
|
112
|
+
"""Need deficits -> 0..1 behavioural biases (expression/inclination)."""
|
|
113
|
+
state = needs_state(needs)
|
|
114
|
+
base = _clamp(baseline, 0.0, 1.0)
|
|
115
|
+
|
|
116
|
+
def deficit(key):
|
|
117
|
+
return max(0.0, base - state[key])
|
|
118
|
+
|
|
119
|
+
def surplus(key):
|
|
120
|
+
return max(0.0, state[key] - base)
|
|
121
|
+
|
|
122
|
+
return {
|
|
123
|
+
"seek_contact": round(_clamp(3.0 * deficit("belonging"), 0.0, 1.0), 3),
|
|
124
|
+
"self_assert": round(_clamp(2.0 * surplus("self_esteem")
|
|
125
|
+
+ 1.5 * deficit("control"), 0.0, 1.0), 3),
|
|
126
|
+
"ask_clarify": round(_clamp(2.0 * deficit("control")
|
|
127
|
+
+ 1.0 * deficit("meaningful_existence"),
|
|
128
|
+
0.0, 1.0), 3),
|
|
129
|
+
"share_meaning": round(_clamp(2.5 * surplus("meaningful_existence"),
|
|
130
|
+
0.0, 1.0), 3),
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def summary(needs):
|
|
135
|
+
"""Bounded row for logs/panel."""
|
|
136
|
+
state = needs_state(needs)
|
|
137
|
+
return {"needs": state, "behavior": behavior_bias(state)}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""BIO-5: four needs (Williams 2007) + sleep debt (Borbély 1982). Pure functions."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
NEED_KEYS = ("belonging", "self_esteem", "control", "meaningful_existence")
|
|
6
|
+
BASE_NEED = 0.6
|
|
7
|
+
DEBT_BASE_HOURS = 0.0
|
|
8
|
+
DEBT_CAP = 24.0
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def clamp(value, low=0.0, high=1.0):
|
|
12
|
+
return max(low, min(high, float(value)))
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def defaults(now=0.0):
|
|
16
|
+
return {key: BASE_NEED for key in NEED_KEYS} | {"last_tick_ts": float(now)}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def need_step(needs, events=None, dt=1.0, now=0.0):
|
|
20
|
+
"""Apply event/silence deltas once per tick (idempotent by now)."""
|
|
21
|
+
data = dict(needs or defaults(now))
|
|
22
|
+
last = float(data.get("last_tick_ts", 0.0) or 0.0)
|
|
23
|
+
if last > 0 and float(now) <= last:
|
|
24
|
+
return data
|
|
25
|
+
events = events if isinstance(events, dict) else {}
|
|
26
|
+
dt = max(0.0, min(6.0, float(dt or 0.0)))
|
|
27
|
+
silence_hours = float(events.get("silence_hours", dt) or 0.0)
|
|
28
|
+
data["belonging"] = round(clamp(float(data.get("belonging", BASE_NEED)) - 0.02 * min(silence_hours, 20.0)), 4)
|
|
29
|
+
data["control"] = round(clamp(float(data.get("control", BASE_NEED)) - (0.03 * min(silence_hours, 10.0) if events.get("stalled") else 0.0)), 4)
|
|
30
|
+
if silence_hours > 48.0:
|
|
31
|
+
data["meaningful_existence"] = round(clamp(float(data.get("meaningful_existence", BASE_NEED)) - 0.02 * min(silence_hours - 48.0, 20.0)), 4)
|
|
32
|
+
if events.get("responded"):
|
|
33
|
+
for key in NEED_KEYS:
|
|
34
|
+
data[key] = round(clamp(float(data.get(key, BASE_NEED)) + 0.03), 4)
|
|
35
|
+
if events.get("praised"):
|
|
36
|
+
data["self_esteem"] = round(clamp(float(data.get("self_esteem", BASE_NEED)) + 0.04), 4)
|
|
37
|
+
if events.get("ignored"):
|
|
38
|
+
data["self_esteem"] = round(clamp(float(data.get("self_esteem", BASE_NEED)) - 0.05), 4)
|
|
39
|
+
data["last_tick_ts"] = float(now)
|
|
40
|
+
return data
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def sleep_debt_step(debt, slept_hours=0.0, dt=1.0, now=0.0, state=None):
|
|
44
|
+
"""Lack of sleep accumulates debt; sleeping repays it. Idempotent by now."""
|
|
45
|
+
state = dict(state or {})
|
|
46
|
+
if float(state.get("last_debt_ts", 0.0) or 0.0) >= float(now) and now:
|
|
47
|
+
return {"debt": round(float(debt or 0.0), 3), "last_debt_ts": float(now)}
|
|
48
|
+
value = max(0.0, float(debt or 0.0))
|
|
49
|
+
slept = max(0.0, float(slept_hours or 0.0))
|
|
50
|
+
dt = max(0.0, min(24.0, float(dt or 0.0)))
|
|
51
|
+
if slept > 0:
|
|
52
|
+
value = max(0.0, value - slept * 0.75)
|
|
53
|
+
else:
|
|
54
|
+
value = value + dt * 0.5
|
|
55
|
+
return {"debt": round(min(DEBT_CAP, value), 3), "last_debt_ts": float(now)}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def energy_penalty(debt):
|
|
59
|
+
return round(clamp(float(debt or 0.0) / DEBT_CAP), 3)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def irritability(debt):
|
|
63
|
+
return round(min(1.0, float(debt or 0.0) / 12.0), 3)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def view(needs, debt=0.0):
|
|
67
|
+
data = dict(needs or defaults())
|
|
68
|
+
values = {key: round(clamp(float(data.get(key, BASE_NEED))), 3) for key in NEED_KEYS}
|
|
69
|
+
dominant = min(NEED_KEYS, key=lambda key: values[key]) if min(values.values()) < BASE_NEED else ""
|
|
70
|
+
return {"needs": values, "dominant": dominant,
|
|
71
|
+
"sleep_debt": round(float(debt or 0.0), 3),
|
|
72
|
+
"energy_penalty": energy_penalty(debt), "irritability": irritability(debt)}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""HUMAN-2 noise bank: common + channel-specific + reproducible event bursts.
|
|
3
|
+
|
|
4
|
+
Every draw is a pure hash of (seed, tick, salt), so replaying the same seed and
|
|
5
|
+
tick reproduces the exact noise without storing RNG state. Bursts are rare
|
|
6
|
+
deterministic events (avalanche-like sensory spikes) layered on top.
|
|
7
|
+
|
|
8
|
+
Literature
|
|
9
|
+
Fields 2007 (neural noise shapes behaviour), Faisal 2008 (noise in the
|
|
10
|
+
nervous system), Wiesenfeld & Moss 1995 (stochastic resonance), Beggs & Plenz
|
|
11
|
+
2003 (neuronal avalanches), Carver & Scheier 1998 (control loop needs a
|
|
12
|
+
stable signal), Seth 2013 (prediction error is noisy).
|
|
13
|
+
|
|
14
|
+
Constraints: pure functions, stdlib only, no IO, no main import, time is the
|
|
15
|
+
injected tick/now; the same inputs are byte-reproducible.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import hashlib
|
|
20
|
+
import math
|
|
21
|
+
|
|
22
|
+
COMMON_SIGMA = 0.12
|
|
23
|
+
CHANNEL_SIGMA = 0.08
|
|
24
|
+
BURST_P = 0.02
|
|
25
|
+
BURST_GAIN = 6.0
|
|
26
|
+
CLAMP = 3.0
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _unit(seed, tick, salt=""):
|
|
30
|
+
"""Deterministic uniform [0, 1) from seed/tick/salt (stdlib only)."""
|
|
31
|
+
key = ("%s|%s|%s" % (seed, tick, salt)).encode("utf-8")
|
|
32
|
+
digest = hashlib.sha256(key).digest()
|
|
33
|
+
value = int.from_bytes(digest[:8], "big")
|
|
34
|
+
return value / float(1 << 64)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _gauss(seed, tick, salt=""):
|
|
38
|
+
"""Box-Muller pair from two independent deterministic uniforms."""
|
|
39
|
+
u1 = max(1e-9, _unit(seed, tick, salt + ":a"))
|
|
40
|
+
u2 = _unit(seed, tick, salt + ":b")
|
|
41
|
+
return math.sqrt(-2.0 * math.log(u1)) * math.cos(2.0 * math.pi * u2)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _clamp(value, lo=-CLAMP, hi=CLAMP):
|
|
45
|
+
try:
|
|
46
|
+
return max(lo, min(hi, float(value)))
|
|
47
|
+
except Exception:
|
|
48
|
+
return 0.0
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def common(seed, tick, sigma=COMMON_SIGMA):
|
|
52
|
+
"""Shared sensory noise for one tick (same for every channel)."""
|
|
53
|
+
return round(_clamp(_gauss(seed, tick, "common") * max(0.0, _num(sigma, COMMON_SIGMA))), 4)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def channel(seed, tick, name, sigma=CHANNEL_SIGMA):
|
|
57
|
+
"""Channel-specific noise (independent across channels)."""
|
|
58
|
+
return round(_clamp(_gauss(seed, tick, "ch:" + str(name))
|
|
59
|
+
* max(0.0, _num(sigma, CHANNEL_SIGMA))), 4)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def burst(seed, tick, p=BURST_P, gain=BURST_GAIN):
|
|
63
|
+
"""Rare deterministic spike: {hit, value, magnitude}."""
|
|
64
|
+
chance = _clamp(p, 0.0, 1.0)
|
|
65
|
+
hit = _unit(seed, tick, "burst") < chance
|
|
66
|
+
if not hit:
|
|
67
|
+
return {"hit": False, "value": 0.0, "magnitude": 0.0}
|
|
68
|
+
magnitude = _clamp(_unit(seed, tick, "burst:mag") * max(0.0, _num(gain, BURST_GAIN)))
|
|
69
|
+
sign = 1.0 if _unit(seed, tick, "burst:sign") >= 0.5 else -1.0
|
|
70
|
+
return {"hit": True, "value": round(sign * magnitude, 4),
|
|
71
|
+
"magnitude": round(magnitude, 4)}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def value(seed, tick, name="", p=BURST_P, sigma=COMMON_SIGMA, channel_sigma=CHANNEL_SIGMA):
|
|
75
|
+
"""Combined noise = common + channel + burst, clamped to +/-3."""
|
|
76
|
+
spike = burst(seed, tick, p=p)
|
|
77
|
+
total = (common(seed, tick, sigma=sigma)
|
|
78
|
+
+ (channel(seed, tick, name, sigma=channel_sigma) if name else 0.0)
|
|
79
|
+
+ spike["value"])
|
|
80
|
+
return {"value": round(_clamp(total), 4), "burst": bool(spike["hit"]),
|
|
81
|
+
"common": common(seed, tick, sigma=sigma),
|
|
82
|
+
"channel": (channel(seed, tick, name, sigma=channel_sigma) if name else 0.0)}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _num(value, default=0.0):
|
|
86
|
+
try:
|
|
87
|
+
return float(value)
|
|
88
|
+
except Exception:
|
|
89
|
+
return float(default)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def sample_window(seed, start_tick, count=10, name=""):
|
|
93
|
+
"""Vector of values for ticks start_tick..start_tick+count-1 (tests/debug)."""
|
|
94
|
+
return [value(seed, int(start_tick) + index, name=name)
|
|
95
|
+
for index in range(max(0, int(count)))]
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** Persona selection + compile flow (pure state machine, testable). */
|
|
2
|
+
export function buildOptions(personas) {
|
|
3
|
+
const list = Array.isArray(personas) ? personas.filter((p) => p && p.id) : []
|
|
4
|
+
return list.map((p) => ({ id: String(p.id), label: p.name && String(p.name) !== String(p.id) ? p.name + '(' + p.id + ')' : String(p.name || p.id) }))
|
|
5
|
+
}
|
|
6
|
+
export function initialTarget(personas, personaId) {
|
|
7
|
+
const list = Array.isArray(personas) ? personas.filter((p) => p && p.id) : []
|
|
8
|
+
if (personaId && list.some((p) => String(p.id) === String(personaId))) return String(personaId)
|
|
9
|
+
const fallback = list.find((p) => String(p.id) === 'default') || list[0]
|
|
10
|
+
return fallback ? String(fallback.id) : ''
|
|
11
|
+
}
|
|
12
|
+
export function compileStep(state, event) {
|
|
13
|
+
const current = ['idle', 'confirm', 'running', 'done'].includes(state) ? state : 'idle'
|
|
14
|
+
if (event === 'click' && current === 'idle') return 'confirm'
|
|
15
|
+
if (event === 'confirm' && current === 'confirm') return 'running'
|
|
16
|
+
if (event === 'result' && current === 'running') return 'done'
|
|
17
|
+
return current
|
|
18
|
+
}
|
|
19
|
+
export function createSaveOnce(post, state = { saved: 0 }) {
|
|
20
|
+
return async function save(payload) {
|
|
21
|
+
if (state.saved > 0 && state.last === JSON.stringify(payload)) return null
|
|
22
|
+
state.saved += 1; state.last = JSON.stringify(payload)
|
|
23
|
+
return post(payload)
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""PIPE-1: one main line pipeline with pluggable / disable-able / isolated / observable stages.
|
|
3
|
+
|
|
4
|
+
Contract (task-107):
|
|
5
|
+
- ctx is a plain dict with the fixed fields in CTX_FIELDS; stages may add
|
|
6
|
+
private keys but must not remove the contract keys.
|
|
7
|
+
- one stage is {name, required, enabled(ctx), timeout_ms, on_error, run(ctx)}.
|
|
8
|
+
- run(ctx, start=None) walks the stages in order; disabled stages are recorded
|
|
9
|
+
as skipped, exceptions as failed (or timeout), and the configured on_error
|
|
10
|
+
policy decides whether to continue (skip), call the stage fallback and
|
|
11
|
+
continue (fallback), or abort (abort).
|
|
12
|
+
- a failed required stage always raises PipelineAbort.
|
|
13
|
+
- every stage appends {name, ms, status, note} to ctx["trace"]["stages"] and to
|
|
14
|
+
a ring buffer that keeps the last 50 records.
|
|
15
|
+
- no main import and no file I/O: configuration (enabled flags, clock) is
|
|
16
|
+
injected through the constructor, which keeps the executor deterministic and
|
|
17
|
+
unit-testable.
|
|
18
|
+
|
|
19
|
+
Limits: timeout_ms is enforced cooperatively (elapsed time is measured around
|
|
20
|
+
run, so a stage cannot be preempted mid-call); start records the stages before
|
|
21
|
+
it as skipped(before_start) without running them.
|
|
22
|
+
"""
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import time
|
|
26
|
+
from collections import deque
|
|
27
|
+
|
|
28
|
+
REQUIRED_STAGES = ("perceive", "express", "think", "present")
|
|
29
|
+
TRACE_RING_MAX = 50
|
|
30
|
+
ON_ERROR_MODES = ("skip", "fallback", "abort")
|
|
31
|
+
CTX_FIELDS = (
|
|
32
|
+
"event", "user", "umo", "core", "state", "memory", "decision", "intent",
|
|
33
|
+
"tone", "prompt", "llm_raw", "parsed", "deltas", "reply", "meta", "trace",
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def make_ctx(**overrides):
|
|
38
|
+
"""Fresh ctx carrying every contract field (trace starts empty)."""
|
|
39
|
+
ctx = {field: None for field in CTX_FIELDS}
|
|
40
|
+
ctx["meta"] = {}
|
|
41
|
+
ctx["trace"] = {"stages": [], "ring": []}
|
|
42
|
+
ctx.update(overrides or {})
|
|
43
|
+
return ctx
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class PipelineAbort(Exception):
|
|
47
|
+
"""Raised when a required stage fails (or a stage uses on_error='abort')."""
|
|
48
|
+
|
|
49
|
+
def __init__(self, stage_name, note="", trace=None):
|
|
50
|
+
self.stage_name = str(stage_name)
|
|
51
|
+
self.note = str(note or "")
|
|
52
|
+
self.trace = trace if isinstance(trace, dict) else {"stages": [], "ring": []}
|
|
53
|
+
super().__init__(self.stage_name + ": " + (self.note or "aborted"))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class Stage:
|
|
57
|
+
def __init__(self, name, run, required=False, enabled=None, timeout_ms=2000,
|
|
58
|
+
on_error="skip", fallback=None):
|
|
59
|
+
self.name = str(name or "").strip()
|
|
60
|
+
if not self.name:
|
|
61
|
+
raise ValueError("stage name required")
|
|
62
|
+
if not callable(run):
|
|
63
|
+
raise TypeError("stage run must be callable")
|
|
64
|
+
if fallback is not None and not callable(fallback):
|
|
65
|
+
raise TypeError("stage fallback must be callable or None")
|
|
66
|
+
self.run = run
|
|
67
|
+
self.fallback = fallback
|
|
68
|
+
self.required = bool(required) or self.name in REQUIRED_STAGES
|
|
69
|
+
self._enabled = enabled
|
|
70
|
+
self.timeout_ms = int(timeout_ms or 0)
|
|
71
|
+
if self.timeout_ms < 0:
|
|
72
|
+
raise ValueError("timeout_ms must be >= 0")
|
|
73
|
+
self.on_error = on_error if on_error in ON_ERROR_MODES else "skip"
|
|
74
|
+
self.last_status = "idle"
|
|
75
|
+
self.last_ms = 0.0
|
|
76
|
+
self.last_note = ""
|
|
77
|
+
|
|
78
|
+
def enabled(self, ctx):
|
|
79
|
+
if self._enabled is None:
|
|
80
|
+
return True
|
|
81
|
+
try:
|
|
82
|
+
return bool(self._enabled(ctx))
|
|
83
|
+
except Exception:
|
|
84
|
+
return False
|
|
85
|
+
|
|
86
|
+
def describe(self, ctx=None):
|
|
87
|
+
return {"name": self.name, "required": self.required,
|
|
88
|
+
"enabled": self.enabled({} if ctx is None else ctx),
|
|
89
|
+
"last_status": self.last_status,
|
|
90
|
+
"last_ms": round(self.last_ms, 3)}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class Pipeline:
|
|
94
|
+
def __init__(self, stages=None, trace_ring_max=TRACE_RING_MAX, clock=None):
|
|
95
|
+
self._clock = clock if callable(clock) else time.perf_counter
|
|
96
|
+
self.stages = []
|
|
97
|
+
self._ring = deque(maxlen=max(1, int(trace_ring_max)))
|
|
98
|
+
self.last_trace = {"stages": [], "ring": []}
|
|
99
|
+
for stage in (stages or []):
|
|
100
|
+
self.register(stage)
|
|
101
|
+
|
|
102
|
+
def _find(self, name):
|
|
103
|
+
for index, stage in enumerate(self.stages):
|
|
104
|
+
if stage.name == name:
|
|
105
|
+
return index, stage
|
|
106
|
+
return -1, None
|
|
107
|
+
|
|
108
|
+
def register(self, stage, index=None):
|
|
109
|
+
"""Append (or insert) one Stage; duplicate names are rejected."""
|
|
110
|
+
if isinstance(stage, dict):
|
|
111
|
+
stage = Stage(**stage)
|
|
112
|
+
if not isinstance(stage, Stage):
|
|
113
|
+
raise TypeError("register expects a Stage or a dict")
|
|
114
|
+
if self._find(stage.name)[1] is not None:
|
|
115
|
+
raise ValueError("duplicate stage: " + stage.name)
|
|
116
|
+
if index is None:
|
|
117
|
+
self.stages.append(stage)
|
|
118
|
+
else:
|
|
119
|
+
self.stages.insert(max(0, min(len(self.stages), int(index))), stage)
|
|
120
|
+
return stage
|
|
121
|
+
|
|
122
|
+
def names(self):
|
|
123
|
+
return [stage.name for stage in self.stages]
|
|
124
|
+
|
|
125
|
+
def set_enabled(self, name, enabled):
|
|
126
|
+
"""Toggle one stage at runtime; required stages refuse to be disabled."""
|
|
127
|
+
_, stage = self._find(name)
|
|
128
|
+
if stage is None:
|
|
129
|
+
raise KeyError(name)
|
|
130
|
+
if stage.name in REQUIRED_STAGES and not enabled:
|
|
131
|
+
raise ValueError("required stage cannot be disabled: " + stage.name)
|
|
132
|
+
value = bool(enabled)
|
|
133
|
+
stage._enabled = lambda ctx, _value=value: _value
|
|
134
|
+
return True
|
|
135
|
+
|
|
136
|
+
def enable(self, name):
|
|
137
|
+
return self.set_enabled(name, True)
|
|
138
|
+
|
|
139
|
+
def disable(self, name):
|
|
140
|
+
return self.set_enabled(name, False)
|
|
141
|
+
|
|
142
|
+
def get_status(self):
|
|
143
|
+
"""Per-stage observability: name/required/enabled/last_status/last_ms."""
|
|
144
|
+
rows = [stage.describe() for stage in self.stages]
|
|
145
|
+
return {"stages": rows, "last_trace": self.last_trace}
|
|
146
|
+
|
|
147
|
+
def _start_index(self, start):
|
|
148
|
+
if start is None:
|
|
149
|
+
return 0
|
|
150
|
+
if isinstance(start, int):
|
|
151
|
+
if start < 0 or start > len(self.stages):
|
|
152
|
+
raise IndexError("start index out of range: %d" % start)
|
|
153
|
+
return start
|
|
154
|
+
index, stage = self._find(str(start))
|
|
155
|
+
if stage is None:
|
|
156
|
+
raise KeyError(start)
|
|
157
|
+
return index
|
|
158
|
+
|
|
159
|
+
def _record(self, ctx, trace, record):
|
|
160
|
+
trace["stages"].append(record)
|
|
161
|
+
self._ring.append(dict(record))
|
|
162
|
+
ctx["trace"] = trace
|
|
163
|
+
return record
|
|
164
|
+
|
|
165
|
+
def _skip(self, ctx, trace, stage, note):
|
|
166
|
+
stage.last_status = "skipped"
|
|
167
|
+
stage.last_ms = 0.0
|
|
168
|
+
stage.last_note = note
|
|
169
|
+
return self._record(ctx, trace, {"name": stage.name, "ms": 0.0,
|
|
170
|
+
"status": "skipped", "note": note})
|
|
171
|
+
|
|
172
|
+
def _run_stage(self, stage, ctx):
|
|
173
|
+
started = self._clock()
|
|
174
|
+
status, note = "ok", ""
|
|
175
|
+
try:
|
|
176
|
+
result = stage.run(ctx)
|
|
177
|
+
if isinstance(result, dict):
|
|
178
|
+
ctx.update(result)
|
|
179
|
+
except TimeoutError as exc:
|
|
180
|
+
status, note = "timeout", "timeout: " + str(exc)[:100]
|
|
181
|
+
except Exception as exc:
|
|
182
|
+
status, note = "failed", type(exc).__name__ + ": " + str(exc)[:120]
|
|
183
|
+
elapsed_ms = max(0.0, (self._clock() - started) * 1000.0)
|
|
184
|
+
if status == "ok" and stage.timeout_ms and elapsed_ms > stage.timeout_ms:
|
|
185
|
+
status = "timeout"
|
|
186
|
+
note = "exceeded %dms (%.1fms)" % (stage.timeout_ms, elapsed_ms)
|
|
187
|
+
if status != "ok" and stage.on_error == "fallback" and stage.fallback is not None:
|
|
188
|
+
try:
|
|
189
|
+
patch = stage.fallback(ctx)
|
|
190
|
+
if isinstance(patch, dict):
|
|
191
|
+
ctx.update(patch)
|
|
192
|
+
note = (note + " | fallback:ok").strip(" |")
|
|
193
|
+
except Exception as exc:
|
|
194
|
+
note = (note + " | fallback:" + type(exc).__name__).strip(" |")
|
|
195
|
+
stage.last_ms = elapsed_ms
|
|
196
|
+
stage.last_note = note
|
|
197
|
+
return status, note
|
|
198
|
+
|
|
199
|
+
def run(self, ctx=None, start=None):
|
|
200
|
+
"""Run every stage in order; start may be a stage name or an index.
|
|
201
|
+
|
|
202
|
+
Stages before start are recorded as skipped(before_start) but not run.
|
|
203
|
+
Raises PipelineAbort when a required stage fails or on_error='abort'.
|
|
204
|
+
"""
|
|
205
|
+
base = make_ctx()
|
|
206
|
+
base.update(dict(ctx or {}))
|
|
207
|
+
ctx = base
|
|
208
|
+
trace = {"stages": [], "ring": []}
|
|
209
|
+
ctx["trace"] = trace
|
|
210
|
+
start_index = self._start_index(start)
|
|
211
|
+
for position, stage in enumerate(self.stages):
|
|
212
|
+
if position < start_index:
|
|
213
|
+
self._skip(ctx, trace, stage, "before_start")
|
|
214
|
+
continue
|
|
215
|
+
if not stage.enabled(ctx):
|
|
216
|
+
self._skip(ctx, trace, stage, "disabled")
|
|
217
|
+
continue
|
|
218
|
+
status, note = self._run_stage(stage, ctx)
|
|
219
|
+
stage.last_status = status
|
|
220
|
+
self._record(ctx, trace, {"name": stage.name, "ms": round(stage.last_ms, 3),
|
|
221
|
+
"status": status, "note": note})
|
|
222
|
+
if status != "ok" and (stage.required or stage.on_error == "abort"):
|
|
223
|
+
trace["ring"] = [dict(item) for item in self._ring]
|
|
224
|
+
ctx["trace"] = trace
|
|
225
|
+
self.last_trace = trace
|
|
226
|
+
raise PipelineAbort(stage.name, note or status, trace)
|
|
227
|
+
trace["ring"] = [dict(item) for item in self._ring]
|
|
228
|
+
ctx["trace"] = trace
|
|
229
|
+
self.last_trace = trace
|
|
230
|
+
return ctx
|
|
231
|
+
|
|
232
|
+
def _push(self, record):
|
|
233
|
+
self._ring.append(dict(record))
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def default_stages():
|
|
237
|
+
return [Stage("perceive", lambda ctx: {"meta": {"ok": True}}, required=True),
|
|
238
|
+
Stage("think", lambda ctx: {"decision": "reply"}, required=True),
|
|
239
|
+
Stage("express", lambda ctx: {"tone": {"text": "自然"}}, required=True),
|
|
240
|
+
Stage("present", lambda ctx: {"reply": "你好。"}, required=True)]
|