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.
- package/lib/index.js +30 -1
- package/lib/modules/standby.js +61 -0
- package/lib/modules/state.js +22 -3
- package/package.json +1 -1
- package/python/biocore_memory/core/config.py +7 -3
- package/python/biocore_memory/engine.py +91 -6
- package/python/biocore_memory/recall/embedding.py +0 -51
- package/python/biocore_memory/recall/feedback.py +34 -7
- package/python/biocore_memory/recall/fusion.py +5 -1
- package/python/biocore_memory/scoring.py +203 -0
- package/python/biocore_memory/space.py +355 -0
- package/python/biocore_memory/store/dedupe.py +1 -0
- package/python/biocore_memory/store/tiering.py +14 -3
- package/python/biocore_model/affective_labor.py +14 -1
- package/python/biocore_model/appraisal.py +172 -3
- package/python/biocore_model/bio_tick.py +43 -13
- package/python/biocore_model/emotion_geometry.py +9 -0
- package/python/biocore_model/envy.py +21 -0
- package/python/biocore_model/feedback_memory.py +53 -0
- package/python/biocore_model/needs_events.py +32 -11
- package/python/biocore_model/regulation_strategies.py +5 -0
- package/python/biocore_model/repair_after_boundary.py +1 -0
- package/python/biocore_model/self_esteem.py +14 -2
- package/python/biocore_model/self_intent.py +6 -4
- package/python/biocore_model/tests/test_autonomy_self.py +153 -153
- package/python/biocore_model/tests/test_cache_series.py +137 -0
- package/python/biocore_model/tests/test_core_state.py +240 -240
- package/python/biocore_model/tests/test_extensions.py +167 -167
- package/python/biocore_model/tests/test_field_arbiter.py +444 -0
- package/python/biocore_model/tests/test_governance.py +181 -181
- package/python/biocore_model/tests/test_lifecycle.py +153 -0
- package/python/biocore_model/tests/test_memory_inject.py +211 -211
- package/python/biocore_model/tests/test_retrieval_plus.py +143 -0
- package/python/biocore_model/tests/test_signals.py +106 -106
- package/python/biocore_model/tests/test_standby.py +199 -0
- package/python/biocore_runtime/__init__.py +3 -0
- package/python/biocore_runtime/arbiter.py +307 -0
- package/python/biocore_runtime/batch_b.py +724 -0
- package/python/biocore_runtime/batch_c.py +186 -0
- package/python/biocore_runtime/batch_d.py +659 -0
- package/python/biocore_runtime/batch_e.py +328 -0
- package/python/biocore_runtime/batch_registry.py +446 -0
- package/python/biocore_runtime/cache_stats.py +161 -0
- package/python/biocore_runtime/core_state.py +106 -3
- package/python/biocore_runtime/dimensions.py +419 -0
- package/python/biocore_runtime/expression.py +261 -0
- package/python/biocore_runtime/field.py +440 -0
- package/python/biocore_runtime/lifecycle.py +233 -0
- package/python/biocore_runtime/perception.py +1045 -0
- package/python/biocore_runtime/pipeline.py +4458 -2974
- package/python/biocore_runtime/priority.py +210 -0
- package/python/biocore_runtime/retrieval_plus.py +352 -0
- package/python/biocore_runtime/standby.py +581 -472
- package/python/biocore_runtime/timescales.py +263 -0
- package/python/data/signals.json +3266 -206
- package/ui/panel-layout.js +32 -29
- package/ui/panel.css +563 -974
- package/ui/panel.html +427 -401
- 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
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
"
|
|
53
|
-
"
|
|
54
|
-
"
|
|
55
|
-
"
|
|
56
|
-
"
|
|
57
|
-
"
|
|
58
|
-
"
|
|
59
|
-
"
|
|
60
|
-
"
|
|
61
|
-
"
|
|
62
|
-
"
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
if
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
if isinstance(value,
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
out["
|
|
107
|
-
|
|
108
|
-
out["
|
|
109
|
-
|
|
110
|
-
out["
|
|
111
|
-
out.get("
|
|
112
|
-
out["
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
return
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
def
|
|
132
|
-
return
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
def
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
return
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
if
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
if
|
|
214
|
-
parts.append(
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
return ""
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
"
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
return "", "
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
"
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
last_sent
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
if
|
|
405
|
-
|
|
406
|
-
result
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
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())
|