dsh-biocore 0.3.3 → 0.5.0

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 (59) hide show
  1. package/lib/index.js +30 -1
  2. package/lib/modules/standby.js +61 -0
  3. package/lib/modules/state.js +22 -3
  4. package/package.json +1 -1
  5. package/python/biocore_memory/core/config.py +7 -3
  6. package/python/biocore_memory/engine.py +91 -6
  7. package/python/biocore_memory/recall/embedding.py +0 -51
  8. package/python/biocore_memory/recall/feedback.py +34 -7
  9. package/python/biocore_memory/recall/fusion.py +5 -1
  10. package/python/biocore_memory/scoring.py +203 -0
  11. package/python/biocore_memory/space.py +355 -0
  12. package/python/biocore_memory/store/dedupe.py +1 -0
  13. package/python/biocore_memory/store/tiering.py +14 -3
  14. package/python/biocore_model/affective_labor.py +14 -1
  15. package/python/biocore_model/appraisal.py +172 -3
  16. package/python/biocore_model/bio_tick.py +43 -13
  17. package/python/biocore_model/emotion_geometry.py +9 -0
  18. package/python/biocore_model/envy.py +21 -0
  19. package/python/biocore_model/feedback_memory.py +53 -0
  20. package/python/biocore_model/needs_events.py +32 -11
  21. package/python/biocore_model/regulation_strategies.py +5 -0
  22. package/python/biocore_model/repair_after_boundary.py +1 -0
  23. package/python/biocore_model/self_esteem.py +14 -2
  24. package/python/biocore_model/self_intent.py +6 -4
  25. package/python/biocore_model/tests/test_autonomy_self.py +153 -153
  26. package/python/biocore_model/tests/test_cache_series.py +137 -0
  27. package/python/biocore_model/tests/test_core_state.py +240 -240
  28. package/python/biocore_model/tests/test_extensions.py +167 -167
  29. package/python/biocore_model/tests/test_field_arbiter.py +444 -0
  30. package/python/biocore_model/tests/test_governance.py +181 -181
  31. package/python/biocore_model/tests/test_lifecycle.py +153 -0
  32. package/python/biocore_model/tests/test_memory_inject.py +211 -211
  33. package/python/biocore_model/tests/test_retrieval_plus.py +143 -0
  34. package/python/biocore_model/tests/test_signals.py +106 -106
  35. package/python/biocore_model/tests/test_standby.py +199 -0
  36. package/python/biocore_runtime/__init__.py +3 -0
  37. package/python/biocore_runtime/arbiter.py +307 -0
  38. package/python/biocore_runtime/batch_b.py +724 -0
  39. package/python/biocore_runtime/batch_c.py +186 -0
  40. package/python/biocore_runtime/batch_d.py +659 -0
  41. package/python/biocore_runtime/batch_e.py +328 -0
  42. package/python/biocore_runtime/batch_registry.py +446 -0
  43. package/python/biocore_runtime/cache_stats.py +161 -0
  44. package/python/biocore_runtime/core_state.py +106 -3
  45. package/python/biocore_runtime/dimensions.py +419 -0
  46. package/python/biocore_runtime/expression.py +261 -0
  47. package/python/biocore_runtime/field.py +440 -0
  48. package/python/biocore_runtime/lifecycle.py +233 -0
  49. package/python/biocore_runtime/perception.py +1045 -0
  50. package/python/biocore_runtime/pipeline.py +4458 -2974
  51. package/python/biocore_runtime/priority.py +210 -0
  52. package/python/biocore_runtime/retrieval_plus.py +352 -0
  53. package/python/biocore_runtime/standby.py +581 -472
  54. package/python/biocore_runtime/timescales.py +263 -0
  55. package/python/data/signals.json +3266 -206
  56. package/ui/panel-layout.js +32 -29
  57. package/ui/panel.css +563 -974
  58. package/ui/panel.html +427 -401
  59. package/ui/panel.js +543 -450
@@ -1,472 +1,581 @@
1
- # -*- coding: utf-8 -*-
2
- """Standby initiative mode: when idle, let a small model write one line.
3
-
4
- Config (dict or BIOCORE_STANDBY_* env; every key optional):
5
- standby_enabled False
6
- standby_model_base_url ""
7
- standby_model ""
8
- standby_model_key ""
9
- standby_every_minutes 30
10
- standby_active_hours "09:00-23:00"
11
- standby_max_per_day 6
12
- standby_channel "outbox"
13
- standby_timeout 20
14
- standby_store "" (memory store root; defaults to plugin data/memory)
15
- standby_session_id "standby"
16
-
17
- tick(now) reads the same session state as turn_start, asks the existing
18
- pipeline.proactive_tick for the decision, then (only if should_send) builds a
19
- full-persona prompt and calls an OpenAI-compatible /v1/chat/completions.
20
- A successful line is sanitized and appended to
21
- <store>/proactive/outbox.jsonl; cooldown/daily bookkeeping goes to
22
- <store>/proactive/state.json. Any model failure writes no outbox.
23
-
24
- CLI: python biocore_runtime/standby.py tick
25
- python biocore_runtime/standby.py sleep-loop [--once]
26
- """
27
- from __future__ import annotations
28
-
29
- import json
30
- import math
31
- import os
32
- import sys
33
- import time
34
- import urllib.error
35
- import urllib.request
36
- from pathlib import Path
37
-
38
- _PLUGIN_ROOT = str(Path(__file__).resolve().parents[1])
39
- if _PLUGIN_ROOT not in sys.path:
40
- sys.path.insert(0, _PLUGIN_ROOT)
41
-
42
- from biocore_runtime import pipeline as _pipeline # noqa: E402
43
-
44
- try:
45
- from biocore_model import sanitize as _sanitize
46
- except Exception: # pragma: no cover
47
- _sanitize = None
48
-
49
- DEFAULTS = {
50
- "standby_enabled": False,
51
- "standby_model_base_url": "",
52
- "standby_model": "",
53
- "standby_model_key": "",
54
- "standby_every_minutes": 30,
55
- "standby_active_hours": "09:00-23:00",
56
- "standby_max_per_day": 6,
57
- "standby_channel": "outbox",
58
- "standby_timeout": 20.0,
59
- "standby_store": "",
60
- "standby_session_id": "standby",
61
- "standby_min_trust": 0.6,
62
- "standby_require_open_loop": True,
63
- }
64
-
65
-
66
- def _num(value, default=0.0):
67
- try:
68
- number = float(value)
69
- except Exception:
70
- return float(default)
71
- return number if math.isfinite(number) else float(default)
72
-
73
-
74
- def _as_bool(value, default=False):
75
- if isinstance(value, bool):
76
- return value
77
- if isinstance(value, (int, float)):
78
- return bool(value)
79
- if isinstance(value, str):
80
- lowered = value.strip().lower()
81
- if lowered in ("1", "true", "yes", "on"):
82
- return True
83
- if lowered in ("0", "false", "no", "off", ""):
84
- return False
85
- return bool(default)
86
-
87
-
88
- def normalize_config(config=None):
89
- data = config if isinstance(config, dict) else {}
90
- out = dict(DEFAULTS)
91
- for key in DEFAULTS:
92
- env_key = "BIOCORE_" + key.upper()
93
- if key in data:
94
- out[key] = data[key]
95
- elif os.environ.get(env_key) is not None:
96
- out[key] = os.environ.get(env_key)
97
- out["standby_enabled"] = _as_bool(out["standby_enabled"], False)
98
- for key in ("standby_model_base_url", "standby_model",
99
- "standby_model_key", "standby_channel", "standby_store",
100
- "standby_session_id"):
101
- out[key] = str(out.get(key) or "").strip()
102
- out["standby_every_minutes"] = max(
103
- 1, min(24 * 60, int(_num(out.get("standby_every_minutes"), 30))))
104
- out["standby_max_per_day"] = max(
105
- 1, min(100, int(_num(out.get("standby_max_per_day"), 6))))
106
- out["standby_timeout"] = max(
107
- 0.2, min(120.0, _num(out.get("standby_timeout"), 20.0)))
108
- out["standby_min_trust"] = max(
109
- 0.0, min(1.0, _num(out.get("standby_min_trust"), 0.6)))
110
- out["standby_require_open_loop"] = _as_bool(
111
- out.get("standby_require_open_loop"), True)
112
- out["standby_session_id"] = out["standby_session_id"] or "standby"
113
- return out
114
-
115
-
116
- def _store_root(store):
117
- raw = str(store or "").strip()
118
- if raw:
119
- return Path(raw)
120
- return Path(_pipeline._default_store())
121
-
122
-
123
- def _proactive_dir(store):
124
- return _store_root(store) / "proactive"
125
-
126
-
127
- def _outbox_path(store):
128
- return _proactive_dir(store) / "outbox.jsonl"
129
-
130
-
131
- def _bookkeeping_path(store):
132
- return _proactive_dir(store) / "state.json"
133
-
134
-
135
- def _load_json(path, fallback):
136
- try:
137
- if path is None or not Path(path).exists():
138
- return fallback
139
- data = json.loads(Path(path).read_text(encoding="utf-8"))
140
- return data if isinstance(data, dict) else fallback
141
- except Exception:
142
- return fallback
143
-
144
-
145
- def _write_json(path, data):
146
- path = Path(path)
147
- path.parent.mkdir(parents=True, exist_ok=True)
148
- tmp = path.with_name(path.name + ".tmp")
149
- tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2),
150
- encoding="utf-8")
151
- os.replace(tmp, path)
152
-
153
-
154
- def _in_active_hours(now, spec):
155
- text = str(spec or "").strip()
156
- if not text:
157
- return True
158
- try:
159
- start_text, end_text = text.split("-", 1)
160
- start_h, start_m = [int(part) for part in start_text.split(":")]
161
- end_h, end_m = [int(part) for part in end_text.split(":")]
162
- except Exception:
163
- return True
164
- local = time.localtime(now)
165
- minutes = local.tm_hour * 60 + local.tm_min
166
- start = start_h * 60 + start_m
167
- end = end_h * 60 + end_m
168
- if start == end:
169
- return True
170
- if start < end:
171
- return start <= minutes < end
172
- return minutes >= start or minutes < end
173
-
174
-
175
- def _day_key(now):
176
- return time.strftime("%Y-%m-%d", time.localtime(now))
177
-
178
-
179
- def _sent_today(state, now):
180
- sent = state.get("sent") if isinstance(state.get("sent"), list) else []
181
- today = _day_key(now)
182
- values = []
183
- for item in sent:
184
- stamp = _num(item, 0.0)
185
- if stamp > 0 and time.strftime("%Y-%m-%d", time.localtime(stamp)) == today:
186
- values.append(stamp)
187
- return values
188
-
189
-
190
- def load_state(store):
191
- return _load_json(_bookkeeping_path(store), {})
192
-
193
-
194
- def load_session_state(store, session_id):
195
- state = _pipeline._load_session_state(_store_root(store), session_id)
196
- if not isinstance(state, dict):
197
- state = {}
198
- return _pipeline.apply_intero_to_state(state)
199
-
200
-
201
- def build_prompt(state, memories, persona_text="", channel="outbox"):
202
- """Full persona (never truncated) + thinking rule + state + recent memories."""
203
- parts = []
204
- if persona_text:
205
- parts.append(str(persona_text))
206
- parts.append(_pipeline.THINKING_STYLE_TEXT)
207
- try:
208
- state_line = _pipeline._state_block(state, 200)
209
- except Exception:
210
- state_line = "此刻:心情平稳。"
211
- parts.append(state_line)
212
- recent = [str(item).strip() for item in (memories or []) if str(item).strip()]
213
- if recent:
214
- parts.append("最近记得:" + ";".join(recent[:3]))
215
- prompt = "\n\n".join(parts)
216
- return prompt
217
-
218
-
219
- def _recent_memories(store, session_id, limit=3):
220
- try:
221
- doc = _pipeline.load_memory(_store_root(store), session_id)
222
- entries = [entry for entry in (doc.get("entries") or [])
223
- if isinstance(entry, dict) and not entry.get("deleted")
224
- and not entry.get("archived")]
225
- entries.sort(key=lambda entry: _num(entry.get("ts"), 0.0), reverse=True)
226
- return [str(entry.get("text") or "")[:120] for entry in entries[:limit]]
227
- except Exception:
228
- return []
229
-
230
-
231
- def _persona_text(store):
232
- try:
233
- profile = _pipeline.load_persona_profile({"store": str(_store_root(store))})
234
- return str((profile or {}).get("persona_text") or "")
235
- except Exception:
236
- return ""
237
-
238
-
239
- def _chat_url(base_url):
240
- base = str(base_url or "").strip().rstrip("/")
241
- if not base:
242
- return ""
243
- if base.endswith("/v1"):
244
- return base + "/chat/completions"
245
- return base + "/v1/chat/completions"
246
-
247
-
248
- def _urllib_transport(url, payload, timeout, headers):
249
- request = urllib.request.Request(
250
- url, data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
251
- headers=headers, method="POST")
252
- with urllib.request.urlopen(request, timeout=timeout) as response:
253
- status = int(getattr(response, "status", 200) or 200)
254
- body = response.read()
255
- return status, body
256
-
257
-
258
- def _extract_text(response_body):
259
- try:
260
- if isinstance(response_body, bytes):
261
- response_body = response_body.decode("utf-8", "replace")
262
- data = json.loads(response_body)
263
- choices = data.get("choices") if isinstance(data, dict) else None
264
- if not isinstance(choices, list) or not choices:
265
- return ""
266
- message = choices[0].get("message") if isinstance(choices[0], dict) else {}
267
- return str((message or {}).get("content") or "").strip()
268
- except Exception:
269
- return ""
270
-
271
-
272
- def generate(prompt, config, transport=None):
273
- """Call the OpenAI-compatible chat endpoint; return (text, reason)."""
274
- cfg = normalize_config(config)
275
- base = cfg["standby_model_base_url"]
276
- model = cfg["standby_model"]
277
- if not base or not model:
278
- return "", "missing_config"
279
- url = _chat_url(base)
280
- if not url:
281
- return "", "missing_config"
282
- payload = {
283
- "model": model,
284
- "messages": [
285
- {"role": "system", "content": prompt},
286
- {"role": "user", "content": "现在没有人说话。你想主动发一句,只回一句话,不超过60字。"},
287
- ],
288
- "temperature": 0.8,
289
- "max_tokens": 120,
290
- }
291
- headers = {"Content-Type": "application/json"}
292
- if cfg["standby_model_key"]:
293
- headers["Authorization"] = "Bearer " + cfg["standby_model_key"]
294
- call = transport or _urllib_transport
295
- try:
296
- status, body = call(url, payload, cfg["standby_timeout"], headers)
297
- except (TimeoutError, OSError) as error:
298
- return "", "timeout" if isinstance(error, TimeoutError) else "model_error"
299
- except Exception:
300
- return "", "model_error"
301
- try:
302
- status = int(status)
303
- except Exception:
304
- status = 0
305
- if status < 200 or status >= 300:
306
- return "", "http_%s" % status
307
- text = _extract_text(body)
308
- if not text:
309
- return "", "empty_reply"
310
- text = text.replace("\n", " ").strip()
311
- if len(text) > 60:
312
- text = text[:59].rstrip() + "…"
313
- if _sanitize is not None:
314
- try:
315
- text = _sanitize.clean(text)
316
- except Exception:
317
- pass
318
- if not str(text).strip():
319
- return "", "empty_reply"
320
- return str(text).strip(), "ok"
321
-
322
-
323
- def _bookkeep(store, now, state, sent=False, reason="", text=""):
324
- path = _bookkeeping_path(store)
325
- sent_list = [stamp for stamp in (state.get("sent") or [])
326
- if _num(stamp, 0.0) > 0 and now - _num(stamp, 0.0) < 7 * 86400]
327
- if sent:
328
- sent_list.append(now)
329
- data = {
330
- "last_attempt_ts": now,
331
- "last_sent_ts": now if sent else _num(state.get("last_sent_ts"), 0.0),
332
- "sent": sent_list[-50:],
333
- "last_reason": reason,
334
- "last_text": text[:80],
335
- "ts": now,
336
- }
337
- try:
338
- _write_json(path, data)
339
- except Exception:
340
- pass
341
- return data
342
-
343
-
344
- def tick(now=None, config=None, transport=None, proactive=None):
345
- """One standby tick. Returns {ok, sent, reason, text?, channel, outbox?}."""
346
- cfg = normalize_config(config)
347
- store = cfg["standby_store"] or _pipeline._default_store()
348
- session_id = cfg["standby_session_id"]
349
- now_value = _num(now, time.time())
350
- if now_value > 1e12:
351
- now_value = now_value / 1000.0
352
- result = {"ok": True, "sent": False, "reason": "",
353
- "channel": cfg["standby_channel"]}
354
- if not cfg["standby_enabled"]:
355
- result["reason"] = "disabled"
356
- return result
357
- if not _in_active_hours(now_value, cfg["standby_active_hours"]):
358
- result["reason"] = "outside_active_hours"
359
- return result
360
- state = load_state(store)
361
- if len(_sent_today(state, now_value)) >= cfg["standby_max_per_day"]:
362
- result["reason"] = "daily_cap"
363
- return result
364
- last_attempt = _num(state.get("last_attempt_ts"), 0.0)
365
- last_sent = _num(state.get("last_sent_ts"), 0.0)
366
- cooldown_until = max(last_attempt, last_sent) + cfg["standby_every_minutes"] * 60.0
367
- if cooldown_until > now_value:
368
- result["reason"] = "cooldown"
369
- return result
370
- session_state = load_session_state(store, session_id)
371
- last_human = _num(session_state.get("last_human_ts"),
372
- now_value - max(cfg["standby_every_minutes"], 180) * 60.0)
373
- switches = {
374
- "proactiveEnabled": True,
375
- "proactiveSend": True,
376
- "proactiveMinGapMinutes": cfg["standby_every_minutes"],
377
- "proactivePerHour": 6,
378
- "proactiveMinTrust": cfg["standby_min_trust"],
379
- "proactiveMaxChars": 60,
380
- "proactiveRequireOpenLoop": cfg["standby_require_open_loop"],
381
- }
382
- decision = proactive
383
- if decision is None:
384
- decision = _pipeline.proactive_tick
385
- try:
386
- decision_result = decision(
387
- session_id=session_id, last_human_ts=last_human,
388
- switches=switches, store=store, now=now_value * 1000.0,
389
- state_file=str(_pipeline.state_path(store, session_id)))
390
- except Exception:
391
- result["reason"] = "decision_error"
392
- return result
393
- if not isinstance(decision_result, dict):
394
- result["reason"] = "decision_error"
395
- return result
396
- if not decision_result.get("should_send"):
397
- result["reason"] = str(decision_result.get("reason") or "should_not_send")
398
- return result
399
- memories = _recent_memories(store, session_id)
400
- persona = _persona_text(store)
401
- prompt = build_prompt(session_state, memories, persona,
402
- cfg["standby_channel"])
403
- text, reason = generate(prompt, cfg, transport=transport)
404
- if reason != "ok" or not text:
405
- _bookkeep(store, now_value, state, sent=False, reason=reason)
406
- result["reason"] = reason
407
- return result
408
- outbox = _outbox_path(store)
409
- try:
410
- outbox.parent.mkdir(parents=True, exist_ok=True)
411
- row = {
412
- "ts": round(now_value, 3),
413
- "text": text,
414
- "reason": "ok",
415
- "state_snapshot": session_state,
416
- "channel": cfg["standby_channel"],
417
- "model": cfg["standby_model"],
418
- }
419
- with outbox.open("a", encoding="utf-8") as handle:
420
- handle.write(json.dumps(row, ensure_ascii=False) + "\n")
421
- except Exception:
422
- _bookkeep(store, now_value, state, sent=False, reason="outbox_write_failed")
423
- result["reason"] = "outbox_write_failed"
424
- return result
425
- data = _bookkeep(store, now_value, state, sent=True, reason="ok", text=text)
426
- result.update({"sent": True, "reason": "ok", "text": text,
427
- "outbox": str(outbox), "sent_today": len(_sent_today(data, now_value))})
428
- return result
429
-
430
-
431
- def sleep_loop(config=None, once=False):
432
- cfg = normalize_config(config)
433
- interval = max(60, int(cfg["standby_every_minutes"] * 60))
434
- while True:
435
- try:
436
- result = tick(config=cfg)
437
- print(json.dumps(result, ensure_ascii=False))
438
- except Exception as error:
439
- print(json.dumps({"ok": False, "reason": "tick_error",
440
- "detail": str(error)[:200]}, ensure_ascii=False))
441
- if once:
442
- return 0
443
- try:
444
- time.sleep(interval)
445
- except KeyboardInterrupt:
446
- return 0
447
-
448
-
449
- def main(argv=None):
450
- args = list(argv if argv is not None else sys.argv[1:])
451
- action = args[0] if args else "tick"
452
- config = {}
453
- index = 1
454
- while index < len(args):
455
- if args[index] == "--once":
456
- config["once"] = True
457
- index += 1
458
- else:
459
- break
460
- if action == "tick":
461
- result = tick(config=config)
462
- print(json.dumps(result, ensure_ascii=False))
463
- return 0 if result.get("ok") else 1
464
- if action == "sleep-loop":
465
- return sleep_loop(config=config, once=bool(config.get("once")))
466
- print(json.dumps({"ok": False, "reason": "unknown_action",
467
- "action": action}, ensure_ascii=False))
468
- return 1
469
-
470
-
471
- if __name__ == "__main__":
472
- raise SystemExit(main())
1
+ # -*- coding: utf-8 -*-
2
+ """Standby initiative mode: when idle, let a small model write one line.
3
+
4
+ Config (dict or BIOCORE_STANDBY_* env; every key optional):
5
+ standby_enabled False
6
+ standby_model_base_url ""
7
+ standby_model ""
8
+ standby_model_key ""
9
+ standby_every_minutes 30
10
+ standby_active_hours "09:00-23:00"
11
+ standby_max_per_day 6
12
+ standby_channel "outbox"
13
+ standby_timeout 20
14
+ standby_store "" (memory store root; defaults to plugin data/memory)
15
+ standby_session_id "standby"
16
+
17
+ tick(now) reads the same session state as turn_start, asks the existing
18
+ pipeline.proactive_tick for the decision, then (only if should_send) builds a
19
+ full-persona prompt and calls an OpenAI-compatible /v1/chat/completions.
20
+ A successful line is sanitized and appended to
21
+ <store>/proactive/outbox.jsonl; cooldown/daily bookkeeping goes to
22
+ <store>/proactive/state.json. Any model failure writes no outbox.
23
+
24
+ CLI: python biocore_runtime/standby.py tick
25
+ python biocore_runtime/standby.py sleep-loop [--once]
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import json
30
+ import math
31
+ import os
32
+ import sys
33
+ import time
34
+ import urllib.error
35
+ import urllib.request
36
+ from pathlib import Path
37
+
38
+ _PLUGIN_ROOT = str(Path(__file__).resolve().parents[1])
39
+ if _PLUGIN_ROOT not in sys.path:
40
+ sys.path.insert(0, _PLUGIN_ROOT)
41
+
42
+ from biocore_runtime import pipeline as _pipeline # noqa: E402
43
+
44
+ try:
45
+ from biocore_model import sanitize as _sanitize
46
+ except Exception: # pragma: no cover
47
+ _sanitize = None
48
+
49
+ # [engineering] every cadence/limit below is a product decision (see
50
+ # PAPER-MAP.md); there is no user study behind 30min / 3 per day / 120min.
51
+ DEFAULTS = {
52
+ "standby_enabled": False,
53
+ "standby_model_base_url": "",
54
+ "standby_model": "",
55
+ "standby_model_key": "",
56
+ "standby_every_minutes": 30,
57
+ "standby_active_hours": "09:00-23:00",
58
+ "standby_max_per_day": 3,
59
+ "standby_cooldown_minutes": 120,
60
+ "standby_max_no_reply": 2,
61
+ "standby_channel": "outbox",
62
+ "standby_timeout": 20.0,
63
+ "standby_store": "",
64
+ "standby_session_id": "standby",
65
+ "standby_min_trust": 0.0,
66
+ "standby_require_open_loop": False,
67
+ }
68
+
69
+
70
+ def _num(value, default=0.0):
71
+ try:
72
+ number = float(value)
73
+ except Exception:
74
+ return float(default)
75
+ return number if math.isfinite(number) else float(default)
76
+
77
+
78
+ def _as_bool(value, default=False):
79
+ if isinstance(value, bool):
80
+ return value
81
+ if isinstance(value, (int, float)):
82
+ return bool(value)
83
+ if isinstance(value, str):
84
+ lowered = value.strip().lower()
85
+ if lowered in ("1", "true", "yes", "on"):
86
+ return True
87
+ if lowered in ("0", "false", "no", "off", ""):
88
+ return False
89
+ return bool(default)
90
+
91
+
92
+ def normalize_config(config=None):
93
+ data = config if isinstance(config, dict) else {}
94
+ out = dict(DEFAULTS)
95
+ for key in DEFAULTS:
96
+ env_key = "BIOCORE_" + key.upper()
97
+ if key in data:
98
+ out[key] = data[key]
99
+ elif os.environ.get(env_key) is not None:
100
+ out[key] = os.environ.get(env_key)
101
+ out["standby_enabled"] = _as_bool(out["standby_enabled"], False)
102
+ for key in ("standby_model_base_url", "standby_model",
103
+ "standby_model_key", "standby_channel", "standby_store",
104
+ "standby_session_id"):
105
+ out[key] = str(out.get(key) or "").strip()
106
+ out["standby_every_minutes"] = max(
107
+ 1, min(24 * 60, int(_num(out.get("standby_every_minutes"), 30))))
108
+ out["standby_max_per_day"] = max(
109
+ 1, min(100, int(_num(out.get("standby_max_per_day"), 3))))
110
+ out["standby_cooldown_minutes"] = max(
111
+ 1, min(24 * 60, int(_num(out.get("standby_cooldown_minutes"), 120))))
112
+ out["standby_max_no_reply"] = max(
113
+ 1, min(10, int(_num(out.get("standby_max_no_reply"), 2))))
114
+ out["standby_timeout"] = max(
115
+ 0.2, min(120.0, _num(out.get("standby_timeout"), 20.0)))
116
+ out["standby_min_trust"] = max(
117
+ 0.0, min(1.0, _num(out.get("standby_min_trust"), 0.0)))
118
+ out["standby_require_open_loop"] = _as_bool(
119
+ out.get("standby_require_open_loop"), False)
120
+ out["standby_session_id"] = out["standby_session_id"] or "standby"
121
+ return out
122
+
123
+
124
+ def _store_root(store):
125
+ raw = str(store or "").strip()
126
+ if raw:
127
+ return Path(raw)
128
+ return Path(_pipeline._default_store())
129
+
130
+
131
+ def _proactive_dir(store):
132
+ return _store_root(store) / "proactive"
133
+
134
+
135
+ def _outbox_path(store):
136
+ return _proactive_dir(store) / "outbox.jsonl"
137
+
138
+
139
+ def _bookkeeping_path(store):
140
+ return _proactive_dir(store) / "state.json"
141
+
142
+
143
+ def _load_json(path, fallback):
144
+ try:
145
+ if path is None or not Path(path).exists():
146
+ return fallback
147
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
148
+ return data if isinstance(data, dict) else fallback
149
+ except Exception:
150
+ return fallback
151
+
152
+
153
+ def _write_json(path, data):
154
+ path = Path(path)
155
+ path.parent.mkdir(parents=True, exist_ok=True)
156
+ tmp = path.with_name(path.name + ".tmp")
157
+ tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2),
158
+ encoding="utf-8")
159
+ os.replace(tmp, path)
160
+
161
+
162
+ def _in_active_hours(now, spec):
163
+ text = str(spec or "").strip()
164
+ if not text:
165
+ return True
166
+ try:
167
+ start_text, end_text = text.split("-", 1)
168
+ start_h, start_m = [int(part) for part in start_text.split(":")]
169
+ end_h, end_m = [int(part) for part in end_text.split(":")]
170
+ except Exception:
171
+ return True
172
+ local = time.localtime(now)
173
+ minutes = local.tm_hour * 60 + local.tm_min
174
+ start = start_h * 60 + start_m
175
+ end = end_h * 60 + end_m
176
+ if start == end:
177
+ return True
178
+ if start < end:
179
+ return start <= minutes < end
180
+ return minutes >= start or minutes < end
181
+
182
+
183
+ def _day_key(now):
184
+ return time.strftime("%Y-%m-%d", time.localtime(now))
185
+
186
+
187
+ def _sent_today(state, now):
188
+ sent = state.get("sent") if isinstance(state.get("sent"), list) else []
189
+ today = _day_key(now)
190
+ values = []
191
+ for item in sent:
192
+ stamp = _num(item, 0.0)
193
+ if stamp > 0 and time.strftime("%Y-%m-%d", time.localtime(stamp)) == today:
194
+ values.append(stamp)
195
+ return values
196
+
197
+
198
+ def load_state(store):
199
+ return _load_json(_bookkeeping_path(store), {})
200
+
201
+
202
+ def load_session_state(store, session_id):
203
+ state = _pipeline._load_session_state(_store_root(store), session_id)
204
+ if not isinstance(state, dict):
205
+ state = {}
206
+ return _pipeline.apply_intero_to_state(state)
207
+
208
+
209
+ def build_prompt(state, memories, persona_text="", channel="outbox",
210
+ digest=""):
211
+ """Full persona (never truncated) + thinking rule + state + memories + digest."""
212
+ parts = []
213
+ if persona_text:
214
+ parts.append(str(persona_text))
215
+ parts.append(_pipeline.THINKING_STYLE_TEXT)
216
+ try:
217
+ state_line = _pipeline._state_block(state, 200)
218
+ except Exception:
219
+ state_line = "此刻:心情平稳。"
220
+ parts.append(state_line)
221
+ recent = [str(item).strip() for item in (memories or []) if str(item).strip()]
222
+ if recent:
223
+ parts.append("最近记得:" + ";".join(recent[:3]))
224
+ if digest:
225
+ parts.append("上次对话:" + str(digest)[:60])
226
+ prompt = "\n\n".join(parts)
227
+ return prompt
228
+
229
+
230
+ def _recent_memories(store, session_id, limit=3):
231
+ try:
232
+ doc = _pipeline.load_memory(_store_root(store), session_id)
233
+ entries = [entry for entry in (doc.get("entries") or [])
234
+ if isinstance(entry, dict) and not entry.get("deleted")
235
+ and not entry.get("archived")]
236
+ entries.sort(key=lambda entry: _num(entry.get("ts"), 0.0), reverse=True)
237
+ return [str(entry.get("text") or "")[:120] for entry in entries[:limit]]
238
+ except Exception:
239
+ return []
240
+
241
+
242
+ def _persona_text(store):
243
+ try:
244
+ profile = _pipeline.load_persona_profile({"store": str(_store_root(store))})
245
+ return str((profile or {}).get("persona_text") or "")
246
+ except Exception:
247
+ return ""
248
+
249
+
250
+ def _chat_url(base_url):
251
+ base = str(base_url or "").strip().rstrip("/")
252
+ if not base:
253
+ return ""
254
+ if base.endswith("/v1"):
255
+ return base + "/chat/completions"
256
+ return base + "/v1/chat/completions"
257
+
258
+
259
+ def _urllib_transport(url, payload, timeout, headers):
260
+ request = urllib.request.Request(
261
+ url, data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
262
+ headers=headers, method="POST")
263
+ with urllib.request.urlopen(request, timeout=timeout) as response:
264
+ status = int(getattr(response, "status", 200) or 200)
265
+ body = response.read()
266
+ return status, body
267
+
268
+
269
+ def _extract_text(response_body):
270
+ try:
271
+ if isinstance(response_body, bytes):
272
+ response_body = response_body.decode("utf-8", "replace")
273
+ data = json.loads(response_body)
274
+ choices = data.get("choices") if isinstance(data, dict) else None
275
+ if not isinstance(choices, list) or not choices:
276
+ return ""
277
+ message = choices[0].get("message") if isinstance(choices[0], dict) else {}
278
+ return str((message or {}).get("content") or "").strip()
279
+ except Exception:
280
+ return ""
281
+
282
+
283
+ def generate(prompt, config, transport=None):
284
+ """Call the OpenAI-compatible chat endpoint; return (text, reason)."""
285
+ cfg = normalize_config(config)
286
+ base = cfg["standby_model_base_url"]
287
+ model = cfg["standby_model"]
288
+ if not base or not model:
289
+ return "", "missing_config"
290
+ url = _chat_url(base)
291
+ if not url:
292
+ return "", "missing_config"
293
+ payload = {
294
+ "model": model,
295
+ "messages": [
296
+ {"role": "system", "content": prompt},
297
+ {"role": "user", "content": "现在没有人说话。你想主动发一句,只回一句话,不超过60字。"},
298
+ ],
299
+ "temperature": 0.8,
300
+ "max_tokens": 120,
301
+ }
302
+ headers = {"Content-Type": "application/json"}
303
+ if cfg["standby_model_key"]:
304
+ headers["Authorization"] = "Bearer " + cfg["standby_model_key"]
305
+ call = transport or _urllib_transport
306
+ try:
307
+ status, body = call(url, payload, cfg["standby_timeout"], headers)
308
+ except (TimeoutError, OSError) as error:
309
+ return "", "timeout" if isinstance(error, TimeoutError) else "model_error"
310
+ except Exception:
311
+ return "", "model_error"
312
+ try:
313
+ status = int(status)
314
+ except Exception:
315
+ status = 0
316
+ if status < 200 or status >= 300:
317
+ return "", "http_%s" % status
318
+ text = _extract_text(body)
319
+ if not text:
320
+ return "", "empty_reply"
321
+ text = text.replace("\n", " ").strip()
322
+ if len(text) > 60:
323
+ text = text[:59].rstrip() + "…"
324
+ if _sanitize is not None:
325
+ try:
326
+ text = _sanitize.clean(text)
327
+ except Exception:
328
+ pass
329
+ if not str(text).strip():
330
+ return "", "empty_reply"
331
+ return str(text).strip(), "ok"
332
+
333
+
334
+ def _bookkeep(store, now, state, sent=False, reason="", text=""):
335
+ path = _bookkeeping_path(store)
336
+ sent_list = [stamp for stamp in (state.get("sent") or [])
337
+ if _num(stamp, 0.0) > 0 and now - _num(stamp, 0.0) < 7 * 86400]
338
+ if sent:
339
+ sent_list.append(now)
340
+ data = {
341
+ "last_attempt_ts": now,
342
+ "last_sent_ts": now if sent else _num(state.get("last_sent_ts"), 0.0),
343
+ "sent": sent_list[-50:],
344
+ "last_reason": reason,
345
+ "last_text": text[:80],
346
+ "ts": now,
347
+ }
348
+ try:
349
+ _write_json(path, data)
350
+ except Exception:
351
+ pass
352
+ return data
353
+
354
+
355
+ def _settle_reply_bookkeeping(store, state, session_state, now, cfg):
356
+ """Count unanswered sends; two in a row block standby."""
357
+ awaiting = bool(state.get("awaiting_reply"))
358
+ streak = int(_num(state.get("no_reply_streak"), 0))
359
+ if not awaiting:
360
+ return streak, state
361
+ last_sent = _num(state.get("last_sent_ts"), 0.0)
362
+ last_human = _num((session_state or {}).get("last_human_ts"), 0.0)
363
+ if last_human > last_sent:
364
+ streak = 0
365
+ elif now - last_sent > cfg["standby_cooldown_minutes"] * 60.0:
366
+ streak += 1
367
+ else:
368
+ return streak, state
369
+ state = dict(state)
370
+ state["awaiting_reply"] = False
371
+ state["no_reply_streak"] = streak
372
+ try:
373
+ _write_json(_bookkeeping_path(store), state)
374
+ except Exception:
375
+ pass
376
+ return streak, state
377
+
378
+
379
+ def _last_digest(session_state):
380
+ for key in ("last_user_text", "last_digest", "last_line"):
381
+ value = str((session_state or {}).get(key) or "").strip()
382
+ if value:
383
+ return value[:60]
384
+ return ""
385
+
386
+
387
+ def _template_line(state):
388
+ intero = (state or {}).get("intero") if isinstance((state or {}).get("intero"), dict) else {}
389
+ if _num(intero.get("tension"), 0.5) >= 0.65:
390
+ return "在忙吗?刚刚想起你,不用急着回。"
391
+ return "刚刚想起你,今天还好吗?"
392
+
393
+
394
+ def tick(now=None, config=None, transport=None, proactive=None):
395
+ """One standby tick. Returns {ok, sent, reason, text?, channel, outbox?}."""
396
+ cfg = normalize_config(config)
397
+ store = cfg["standby_store"] or _pipeline._default_store()
398
+ session_id = cfg["standby_session_id"]
399
+ now_value = _num(now, time.time())
400
+ if now_value > 1e12:
401
+ now_value = now_value / 1000.0
402
+ result = {"ok": True, "sent": False, "reason": "",
403
+ "channel": cfg["standby_channel"]}
404
+ if not cfg["standby_enabled"]:
405
+ result["reason"] = "disabled"
406
+ return result
407
+ if not _in_active_hours(now_value, cfg["standby_active_hours"]):
408
+ result["reason"] = "outside_active_hours"
409
+ return result
410
+ state = load_state(store)
411
+ session_state = load_session_state(store, session_id)
412
+ streak, state = _settle_reply_bookkeeping(store, state, session_state,
413
+ now_value, cfg)
414
+ result["no_reply_streak"] = streak
415
+ if streak >= cfg["standby_max_no_reply"]:
416
+ result["reason"] = "no_reply_streak"
417
+ return result
418
+ if len(_sent_today(state, now_value)) >= cfg["standby_max_per_day"]:
419
+ result["reason"] = "daily_cap"
420
+ return result
421
+ last_attempt = _num(state.get("last_attempt_ts"), 0.0)
422
+ last_sent = _num(state.get("last_sent_ts"), 0.0)
423
+ cooldown_until = max(last_attempt, last_sent) + cfg["standby_cooldown_minutes"] * 60.0
424
+ if cooldown_until > now_value:
425
+ result["reason"] = "cooldown"
426
+ return result
427
+ last_human = _num(session_state.get("last_human_ts"),
428
+ now_value - max(cfg["standby_every_minutes"], 180) * 60.0)
429
+ switches = {
430
+ "proactiveEnabled": True,
431
+ "proactiveSend": True,
432
+ "proactiveMinGapMinutes": cfg["standby_every_minutes"],
433
+ "proactivePerHour": 6,
434
+ "proactiveMinTrust": cfg["standby_min_trust"],
435
+ "proactiveMaxChars": 60,
436
+ "proactiveRequireOpenLoop": cfg["standby_require_open_loop"],
437
+ }
438
+ decision = proactive
439
+ if decision is None:
440
+ decision = _pipeline.proactive_tick
441
+ try:
442
+ decision_result = decision(
443
+ session_id=session_id, last_human_ts=last_human,
444
+ switches=switches, store=store, now=now_value * 1000.0,
445
+ state_file=str(_pipeline.state_path(store, session_id)))
446
+ except Exception:
447
+ result["reason"] = "decision_error"
448
+ return result
449
+ if not isinstance(decision_result, dict):
450
+ result["reason"] = "decision_error"
451
+ return result
452
+ if not decision_result.get("should_send"):
453
+ result["reason"] = str(decision_result.get("reason") or "should_not_send")
454
+ return result
455
+ memories = _recent_memories(store, session_id)
456
+ persona = _persona_text(store)
457
+ prompt = build_prompt(session_state, memories, persona,
458
+ cfg["standby_channel"],
459
+ digest=_last_digest(session_state))
460
+ text, reason = generate(prompt, cfg, transport=transport)
461
+ fallback = False
462
+ if reason != "ok" or not text:
463
+ text = _template_line(session_state)
464
+ reason = "template_fallback"
465
+ fallback = True
466
+ outbox = _outbox_path(store)
467
+ try:
468
+ outbox.parent.mkdir(parents=True, exist_ok=True)
469
+ row = {
470
+ "ts": round(now_value, 3),
471
+ "text": text,
472
+ "reason": reason,
473
+ "state_snapshot": session_state,
474
+ "channel": cfg["standby_channel"],
475
+ "model": cfg["standby_model"],
476
+ "fallback": fallback,
477
+ "prompt": prompt,
478
+ }
479
+ with outbox.open("a", encoding="utf-8") as handle:
480
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
481
+ except Exception:
482
+ _bookkeep(store, now_value, state, sent=False, reason="outbox_write_failed")
483
+ result["reason"] = "outbox_write_failed"
484
+ return result
485
+ state = dict(state)
486
+ state["awaiting_reply"] = True
487
+ state["no_reply_streak"] = 0
488
+ data = _bookkeep(store, now_value, state, sent=True, reason=reason, text=text)
489
+ data["awaiting_reply"] = True
490
+ data["no_reply_streak"] = 0
491
+ try:
492
+ _write_json(_bookkeeping_path(store), data)
493
+ except Exception:
494
+ pass
495
+ result.update({"sent": True, "reason": reason, "text": text,
496
+ "fallback": fallback, "prompt": prompt,
497
+ "outbox": str(outbox),
498
+ "sent_today": len(_sent_today(data, now_value))})
499
+ return result
500
+
501
+
502
+ def _results_path(store):
503
+ return _proactive_dir(store) / "results.jsonl"
504
+
505
+
506
+ def _count_lines(path):
507
+ try:
508
+ if path is None or not Path(path).exists():
509
+ return 0
510
+ return sum(1 for line in Path(path).read_text(encoding="utf-8").splitlines()
511
+ if line.strip())
512
+ except Exception:
513
+ return 0
514
+
515
+
516
+ def summary(store, now=None, enabled=False):
517
+ """Numbers for /state; never generates or sends."""
518
+ stamp = _num(now, time.time())
519
+ state = load_state(store)
520
+ sent_today = len(_sent_today(state, stamp))
521
+ pending = max(0, _count_lines(_outbox_path(store))
522
+ - _count_lines(_results_path(store)))
523
+ cfg = normalize_config({})
524
+ last_attempt = _num(state.get("last_attempt_ts"), 0.0)
525
+ next_at = (last_attempt + cfg["standby_every_minutes"] * 60.0
526
+ if last_attempt > 0 else 0.0)
527
+ return {
528
+ "enabled": bool(enabled),
529
+ "next_at": round(next_at, 3),
530
+ "pending": pending,
531
+ "sent_today": sent_today,
532
+ "last_reason": str(state.get("last_reason") or ""),
533
+ "no_reply_streak": int(_num(state.get("no_reply_streak"), 0)),
534
+ "awaiting_reply": bool(state.get("awaiting_reply")),
535
+ "cooldown_minutes": cfg["standby_cooldown_minutes"],
536
+ "max_per_day": cfg["standby_max_per_day"],
537
+ }
538
+
539
+
540
+ def sleep_loop(config=None, once=False):
541
+ cfg = normalize_config(config)
542
+ interval = max(60, int(cfg["standby_every_minutes"] * 60))
543
+ while True:
544
+ try:
545
+ result = tick(config=cfg)
546
+ print(json.dumps(result, ensure_ascii=False))
547
+ except Exception as error:
548
+ print(json.dumps({"ok": False, "reason": "tick_error",
549
+ "detail": str(error)[:200]}, ensure_ascii=False))
550
+ if once:
551
+ return 0
552
+ try:
553
+ time.sleep(interval)
554
+ except KeyboardInterrupt:
555
+ return 0
556
+
557
+
558
+ def main(argv=None):
559
+ args = list(argv if argv is not None else sys.argv[1:])
560
+ action = args[0] if args else "tick"
561
+ config = {}
562
+ index = 1
563
+ while index < len(args):
564
+ if args[index] == "--once":
565
+ config["once"] = True
566
+ index += 1
567
+ else:
568
+ break
569
+ if action == "tick":
570
+ result = tick(config=config)
571
+ print(json.dumps(result, ensure_ascii=False))
572
+ return 0 if result.get("ok") else 1
573
+ if action == "sleep-loop":
574
+ return sleep_loop(config=config, once=bool(config.get("once")))
575
+ print(json.dumps({"ok": False, "reason": "unknown_action",
576
+ "action": action}, ensure_ascii=False))
577
+ return 1
578
+
579
+
580
+ if __name__ == "__main__":
581
+ raise SystemExit(main())