forked from razzant/ouroboros
-
Notifications
You must be signed in to change notification settings - Fork 278
Expand file tree
/
Copy pathserver.py
More file actions
2388 lines (2147 loc) · 103 KB
/
Copy pathserver.py
File metadata and controls
2388 lines (2147 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
76
77
78
79
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
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
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
205
206
207
208
209
210
211
212
213
214
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
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
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
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
405
406
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Self-editable Starlette/uvicorn entry point for UI and supervisor runtime."""
import asyncio
import base64
import json
import logging
import socket
import os
import pathlib
import sys
import threading
import time
import uuid
from ouroboros.utils import utc_now_iso
from typing import Any, Dict, Optional
from starlette.applications import Starlette
from starlette.routing import Route, Mount
import uvicorn
from ouroboros.server_control import (
execute_panic_stop as _execute_panic_stop_impl,
restart_current_process as _restart_current_process_impl,
)
from ouroboros.server_auth import (
NetworkAuthGate,
get_network_auth_startup_warning,
validate_network_auth_configuration,
)
from ouroboros.server_entrypoint import find_free_port, parse_server_args, write_port_file
from ouroboros.server_web import NoCacheStaticFiles, make_index_page, resolve_web_dir
from ouroboros.usage_accounting import ensure_legacy_imported
from ouroboros.gateway import collect_routes
from ouroboros.gateway import settings as _gateway_settings
from ouroboros.gateway.ws import (
broadcast_ws,
broadcast_ws_sync,
close_all_ws,
has_ws_clients as _has_ws_clients,
set_event_loop as _set_ws_event_loop,
)
REPO_DIR = pathlib.Path(os.environ.get("OUROBOROS_REPO_DIR", pathlib.Path(__file__).parent))
DATA_DIR = pathlib.Path(os.environ.get("OUROBOROS_DATA_DIR",
pathlib.Path.home() / "Ouroboros" / "data"))
DEFAULT_HOST = os.environ.get("OUROBOROS_SERVER_HOST", "127.0.0.1")
DEFAULT_PORT = int(os.environ.get("OUROBOROS_SERVER_PORT", "8765"))
PORT_FILE = DATA_DIR / "state" / "server_port"
sys.path.insert(0, str(REPO_DIR))
if not os.environ.get("OUROBOROS_AGENT_PYTHON"):
_agent_python = sys.executable
if isinstance(_agent_python, str) and _agent_python:
os.environ["OUROBOROS_AGENT_PYTHON"] = _agent_python
_LOG_FORMAT = "%(asctime)s [%(levelname)s] %(name)s: %(message)s"
_pytest_default_real_data_dir = (
"pytest" in sys.modules
and not os.environ.get("OUROBOROS_DATA_DIR")
and DATA_DIR == pathlib.Path.home() / "Ouroboros" / "data"
)
if _pytest_default_real_data_dir:
logging.basicConfig(level=logging.INFO, format=_LOG_FORMAT, handlers=[logging.StreamHandler()])
else:
_log_dir = DATA_DIR / "logs"
_log_dir.mkdir(parents=True, exist_ok=True)
from logging.handlers import RotatingFileHandler
_file_handler = RotatingFileHandler(
_log_dir / "server.log", maxBytes=2 * 1024 * 1024, backupCount=3, encoding="utf-8",
)
_file_handler.setFormatter(logging.Formatter(_LOG_FORMAT))
logging.basicConfig(level=logging.INFO, format=_LOG_FORMAT, handlers=[_file_handler, logging.StreamHandler()])
from ouroboros.observability import SecretRedactingLogFilter as _SecretRedactingLogFilter
for _handler in logging.getLogger().handlers:
_handler.addFilter(_SecretRedactingLogFilter())
# httpx logs each request URL at INFO; polling transports put credentials in
# the URL path, so even redacted lines are noise at this level.
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
log = logging.getLogger("server")
RESTART_EXIT_CODE = 42
PANIC_EXIT_CODE = 99
_restart_requested = threading.Event()
_LAUNCHER_MANAGED = str(os.environ.get("OUROBOROS_MANAGED_BY_LAUNCHER", "") or "").strip() == "1"
# Captured in main() for Settings LAN-reachability metadata.
_BIND_HOST = DEFAULT_HOST
def _has_active_evolution_transaction() -> bool:
try:
path = DATA_DIR / "state" / "evolution_campaign.json"
if not path.is_file():
return False
raw = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(raw, dict):
return False
if raw.get("status") not in {"active", "paused"}:
return False
tx = raw.get("active_transaction")
return isinstance(tx, dict) and not str(tx.get("commit_sha") or "").strip()
except Exception:
return False
def _installed_skill_names():
"""Names of skills currently installed ON DISK (disk-derived, not in-memory).
Passed to the process-custody reaper so it can tell which skill-companion
orphans are safe to reap (owner uninstalled). Disk-derived so it is correct
independent of in-memory extension-reload timing; returns None on any failure
so the reaper fails toward KEEP (never mass-kills live skills' companions).
"""
try:
from ouroboros.config import get_skills_repo_path
from ouroboros.skill_loader import discover_skills
names = {s.name for s in discover_skills(DATA_DIR, repo_path=get_skills_repo_path())}
# Coalesce an EMPTY result to None ("unknown"), NOT "everything
# uninstalled": discover_skills returns [] without raising when the skills
# dir is momentarily unavailable; treating that as an empty install set
# would let an enforced reap mass-kill live companions. None ⇒ keep-all.
return names or None
except Exception:
log.debug("Could not compute installed skill names for custody reaper", exc_info=True)
return None
def _restart_current_process(host: str, port: int) -> None:
_restart_current_process_impl(host, port, repo_dir=REPO_DIR, log=log)
from ouroboros.config import (
load_settings, save_settings, apply_settings_to_env as _apply_settings_to_env,
)
from ouroboros.server_runtime import (
apply_runtime_provider_defaults,
has_startup_ready_provider,
needs_local_model_autostart,
setup_remote_if_configured,
ws_heartbeat_loop,
)
_supervisor_ready = threading.Event()
_supervisor_error: Optional[str] = None
_event_loop: Optional[asyncio.AbstractEventLoop] = None
_supervisor_thread: Optional[threading.Thread] = None
_consciousness: Any = None
def _describe_bg_consciousness_state(requested_enabled: bool) -> dict:
snapshot = _consciousness.status_snapshot() if _consciousness else {}
running = bool(snapshot.get("running"))
paused = bool(snapshot.get("paused"))
next_wakeup_sec = int(snapshot.get("next_wakeup_sec") or 0)
idle_reason = str(snapshot.get("last_idle_reason") or "")
detail = "Background consciousness is off."
status = "disabled"
if requested_enabled and running and paused:
status = "paused"
detail = "Paused while another foreground task is active."
elif requested_enabled and running and idle_reason == "thinking":
status = "running"
detail = "Background consciousness is thinking now."
elif requested_enabled and running and idle_reason == "budget_blocked":
status = "budget_blocked"
detail = "Background consciousness hit its budget allocation and is waiting."
elif requested_enabled and running:
status = "running"
detail = (
"Background consciousness is idle between wakeups."
+ (f" Next wakeup in {next_wakeup_sec}s." if next_wakeup_sec > 0 else "")
)
elif requested_enabled:
status = "stopped"
detail = "Enabled in state, but the background thread is not running."
if idle_reason == "error_backoff" and snapshot.get("last_error"):
status = "error_backoff"
detail = f"Waiting to retry after an internal error: {snapshot['last_error']}"
return {
"enabled": requested_enabled,
"status": status,
"detail": detail,
**snapshot,
}
def _start_supervisor_if_needed(settings: dict) -> bool:
"""Start the supervisor once when runtime providers become available."""
global _supervisor_thread, _supervisor_error
if not has_startup_ready_provider(settings):
return False
if _supervisor_thread and _supervisor_thread.is_alive():
return False
_supervisor_error = None
_supervisor_thread = threading.Thread(
target=_run_supervisor,
args=(settings,),
daemon=True,
name="supervisor-main",
)
_supervisor_thread.start()
return True
def _task_belongs_to_chat(ctx: Any, task_id: str, task_obj: Dict[str, Any], chat_id: int) -> bool:
try:
if int(task_obj.get("chat_id") or 0) == int(chat_id or 0):
return True
except (TypeError, ValueError):
pass
try:
from ouroboros.projects_registry import project_chat_for_task
return int(project_chat_for_task(ctx.DRIVE_ROOT, task_id) or 0) == int(chat_id or 0)
except Exception:
return False
def _active_direct_root(ctx: Any) -> Dict[str, Any]:
"""Snapshot the one in-process direct root without creating queue state."""
try:
agent = ctx.get_chat_agent()
lock = getattr(agent, "_owner_message_admission_lock", None)
if lock is None:
return {}
with lock:
task_id = str(getattr(agent, "_current_task_id", "") or "").strip()
if (
not getattr(agent, "_busy", False)
or not getattr(agent, "_accepting_owner_messages", False)
or not task_id
):
return {}
metadata = getattr(agent, "_current_task_metadata", {})
metadata = metadata if isinstance(metadata, dict) else {}
return {
"task_id": task_id,
"status": "running",
"title": _clip_marked(metadata.get("title"), 120),
"objective": _clip_marked(getattr(agent, "_current_task_text", ""), 600),
"project_id": str(metadata.get("project_id") or ""),
"chat_id": int(getattr(agent, "_current_chat_id", 0) or 0),
"started_at": float(getattr(agent, "_task_started_ts", 0.0) or 0.0),
"steerable": True,
"direct_chat": True,
}
except Exception:
return {}
def _addressable_root_tasks(ctx: Any, chat_id: Optional[int] = None) -> list:
"""Compact RUNNING+PENDING owner-root manifest, without choosing a target."""
out: list = []
seen: set[str] = set()
def _add(task_id: Any, task_obj: Any, status: str, started_at: Any = None) -> None:
tid = str(task_id or "").strip()
if not tid or tid in seen or not isinstance(task_obj, dict):
return
if task_obj.get("_is_direct_chat") or str(task_obj.get("delegation_role") or "") == "subagent":
return
if chat_id is not None and not _task_belongs_to_chat(ctx, tid, task_obj, int(chat_id or 0)):
return
objective = str(
task_obj.get("objective") or task_obj.get("description") or task_obj.get("text") or ""
).strip()
out.append({
"task_id": tid,
"status": status,
"title": _clip_marked(task_obj.get("title"), 120),
"objective": _clip_marked(objective, 600),
"project_id": str(task_obj.get("project_id") or ""),
"started_at": started_at,
"steerable": True,
})
seen.add(tid)
for tid, running in list(getattr(ctx, "RUNNING", {}).items()):
if not isinstance(running, dict):
continue
task_obj = running.get("task") if isinstance(running.get("task"), dict) else running
_add(tid, task_obj, "running", running.get("started_at"))
for pending in list(getattr(ctx, "PENDING", []) or []):
if isinstance(pending, dict):
_add(pending.get("id"), pending, "pending", pending.get("queued_at"))
direct = _active_direct_root(ctx)
if direct and str(direct.get("task_id") or "") not in seen:
if chat_id is None or int(direct.get("chat_id") or 0) == int(chat_id or 0):
out.append(direct)
return out
def _stage_mailbox_attachments(
ctx: Any,
task_id: str,
task_metadata: Any,
image_data: Any = None,
) -> str:
"""Stage one routed turn's files into the existing task artifact store."""
metadata = task_metadata if isinstance(task_metadata, dict) else {}
uploads = list(metadata.get("chat_attachment_uploads") or [])
temp_source: Optional[pathlib.Path] = None
if image_data and not uploads:
# Non-Web transports may carry an inline image rather than an uploaded
# path. Materialise it only long enough for the canonical staging helper
# to copy it into the addressed task's artifact store.
try:
raw = base64.b64decode(str(image_data[0] or ""), validate=True)
if raw and len(raw) <= 50 * 1024 * 1024:
mime = str(image_data[1] or "image/jpeg").lower()
suffix = ".png" if "png" in mime else ".webp" if "webp" in mime else ".jpg"
temp_source = pathlib.Path(ctx.DRIVE_ROOT) / "uploads" / f"routed-{uuid.uuid4().hex}{suffix}"
temp_source.parent.mkdir(parents=True, exist_ok=True)
with temp_source.open("xb") as handle:
handle.write(raw)
handle.flush()
os.fsync(handle.fileno())
uploads.append({"path": str(temp_source), "label": "owner image"})
except Exception:
log.warning("Unable to stage routed inline image for task %s", task_id, exc_info=True)
try:
if not uploads:
return ""
from ouroboros.artifacts import stage_task_attachments
from ouroboros.gateway.tasks import _render_attachment_lines
manifest = stage_task_attachments(ctx.DRIVE_ROOT, task_id, uploads)
rendered = _render_attachment_lines(manifest)
return f"\n\n[ATTACHMENTS]\n{rendered}\n[END_ATTACHMENTS]" if rendered else ""
finally:
if temp_source is not None:
try:
temp_source.unlink(missing_ok=True)
except OSError:
log.debug("Unable to remove routed attachment staging source", exc_info=True)
def _route_project_chat_to_running_task(
ctx: Any,
chat_id: int,
message: str,
client_message_id: str = "",
*,
task_metadata: Any = None,
image_data: Any = None,
) -> str:
"""Deliver a Project follow-up to the sole RUNNING/PENDING root mailbox.
Multi-project (v6.32.0): a focused project room with exactly ONE active pooled
task IS that task's context, so a follow-up is delivered to it as a TRANSPORT
invariant (the loop drains the mailbox every round) — there is no routing CHOICE
to make. But when the room has ZERO or MORE THAN ONE steerable task, picking a
target is a JUDGMENT, and code must never make it mechanically (BIBLE P5 LLM-first,
v6.34.0 WS1): this returns "" so the message flows to the decision turn, where the
agent sees `current_chat.running_tasks` and chooses `steer_task` / `promote_chat_to_task`.
Returns the delivered task id, or "" (no delivery — fall through to the decision lane).
A chat is a project thread by REGISTRY membership, not a bare numeric range —
large external-transport (Telegram-style) chat ids must not be misclassified and
have their owner messages swallowed.
"""
try:
if not _project_id_for_registered_chat(ctx, chat_id):
return ""
except Exception:
return ""
try:
steerable = _addressable_root_tasks(ctx, chat_id)
# Exactly one candidate => unambiguous transport. Zero or many => a routing
# decision the AGENT must make (P5/WS1), so do not deliver here.
if len(steerable) != 1:
return ""
candidate = steerable[0]
tid = str(candidate["task_id"])
direct_agent = None
direct_lock = None
if candidate.get("direct_chat"):
direct_agent = ctx.get_chat_agent()
direct_lock = getattr(direct_agent, "_owner_message_admission_lock", None)
if direct_lock is None:
return ""
task_obj: Dict[str, Any] = {}
running = getattr(ctx, "RUNNING", {}).get(tid)
if isinstance(running, dict):
task_obj = running.get("task") if isinstance(running.get("task"), dict) else running
if not task_obj:
task_obj = next(
(row for row in list(getattr(ctx, "PENDING", []) or []) if str(row.get("id") or "") == tid),
{},
)
from ouroboros.owner_mailbox import write_owner_message
from supervisor.queue import (
ACCEPTANCE_FENCES,
_queue_lock,
_task_drive_for_task,
persist_queue_snapshot,
)
# Active drive (child drive for forked/workspace tasks) — mirror
# forward_to_worker / steer_task so the mailbox lands where the task
# actually drains it, not the canonical root. A stable msg_id derived from
# client_message_id makes this 1:1 delivery idempotent — a WebSocket retry of
# the same message can't double-deliver (drain_owner_entries dedups by msg_id),
# matching steer_task's contract.
direct_lock_held = False
queue_lock_held = False
fence_generation_changed = False
active_fence = None
if direct_lock is not None:
direct_lock.acquire()
direct_lock_held = True
if not (
getattr(direct_agent, "_busy", False)
and getattr(direct_agent, "_accepting_owner_messages", False)
and str(getattr(direct_agent, "_current_task_id", "") or "") == tid
):
direct_lock.release()
direct_lock_held = False
return ""
task_drive = pathlib.Path(ctx.DRIVE_ROOT) if direct_lock_held else _task_drive_for_task(task_obj, tid)
msg_id = f"{client_message_id}:{tid}" if client_message_id else None
try:
attachment_note = _stage_mailbox_attachments(ctx, tid, task_metadata, image_data)
if not direct_lock_held:
_queue_lock.acquire()
queue_lock_held = True
live_meta = getattr(ctx, "RUNNING", {}).get(tid)
still_pending = any(
isinstance(row, dict) and str(row.get("id") or "") == tid
for row in list(getattr(ctx, "PENDING", []) or [])
)
if live_meta is None and not still_pending:
return ""
fence_root = str(task_obj.get("root_task_id") or tid)
active_fence = ACCEPTANCE_FENCES.get(fence_root)
if isinstance(active_fence, dict) and str(active_fence.get("status") or "") == "sealed":
return ""
write_owner_message(task_drive, f"{message}{attachment_note}", tid, msg_id=msg_id)
if direct_lock_held:
direct_agent._owner_message_generation = int(
getattr(direct_agent, "_owner_message_generation", 0) or 0
) + 1
else:
if isinstance(active_fence, dict) and str(active_fence.get("status") or "") == "active":
active_fence["owner_message_generation"] = int(
active_fence.get("owner_message_generation") or 0
) + 1
fence_generation_changed = True
finally:
if queue_lock_held:
_queue_lock.release()
if direct_lock_held:
direct_lock.release()
if fence_generation_changed:
persist_queue_snapshot(reason="acceptance_fence_owner_message")
return tid
except Exception:
log.debug("Mailbox follow-up routing failed; falling back to direct lane", exc_info=True)
return ""
def _clip_marked(value: str, limit: int) -> str:
"""Clip a routing/recognition string but NEVER silently: an explicit omission
marker keeps a decision-context field honest (no silent ``[:N]`` truncation of a
cognitive/routing artifact — DEVELOPMENT.md). The marker + the full task_id keep
enough signal for the agent to disambiguate the steer target."""
s = str(value or "").strip()
if len(s) <= limit:
return s
return s[:limit] + f" …[+{len(s) - limit} chars omitted]"
def _chat_running_tasks(ctx: Any, chat_id: int) -> list:
"""Structural snapshot of the owner's RUNNING root tasks in THIS chat (id +
objective + recency). The decision turn reads this from runtime context to
pick a steer_task target by its own judgment — code only exposes the state,
it never auto-chooses (BIBLE P5). Direct in-process turns and subagents are
not pooled RUNNING tasks and are excluded."""
return [row for row in _addressable_root_tasks(ctx, chat_id) if row.get("status") == "running"]
def _main_routing_manifest(ctx: Any) -> Dict[str, Any]:
"""Bounded canonical facts for one Main-chat LLM routing decision."""
from ouroboros.projects_registry import list_projects
from ouroboros.task_results import list_task_results
from ouroboros.utils import iter_jsonl_objects
projects = [{
"project_id": str(row.get("id") or ""),
"name": _clip_marked(row.get("name"), 120),
"chat_id": int(row.get("chat_id") or 0),
"lifecycle": str(row.get("lifecycle") or "active"),
} for row in list_projects(ctx.DRIVE_ROOT)]
roots = _addressable_root_tasks(ctx, None)
all_results = list_task_results(ctx.DRIVE_ROOT)
all_results.sort(key=lambda row: str(row.get("ts") or row.get("updated_at") or ""), reverse=True)
finals: list = []
for row in all_results[:16]:
bundle = row.get("artifact_bundle") if isinstance(row.get("artifact_bundle"), dict) else {}
artifacts = bundle.get("artifacts") if isinstance(bundle.get("artifacts"), list) else []
finals.append({
"task_id": str(row.get("task_id") or row.get("id") or ""),
"status": str(row.get("status") or ""),
"title": _clip_marked(row.get("title"), 120),
"objective": _clip_marked(row.get("objective") or row.get("description"), 300),
"project_id": str(row.get("project_id") or ""),
"artifact_status": str(row.get("artifact_status") or ""),
"artifact_refs": [
str(item.get("path") or item.get("name") or "")
for item in artifacts[:8] if isinstance(item, dict)
],
})
dialogue_rows: list = []
chat_paths = sorted(
(pathlib.Path(ctx.DRIVE_ROOT) / "archive").glob("chat_*.jsonl"),
key=lambda path: path.name,
)[-2:] + [pathlib.Path(ctx.DRIVE_ROOT) / "logs" / "chat.jsonl"]
for path in chat_paths:
for row in iter_jsonl_objects(path):
text = str(row.get("text") or "").strip()
if text:
dialogue_rows.append({
"ts": str(row.get("ts") or ""),
"direction": str(row.get("direction") or ""),
"chat_id": int(row.get("chat_id") or 1),
"text": _clip_marked(text, 500),
"task_id": str(row.get("task_id") or ""),
"client_message_id": str(row.get("client_message_id") or ""),
})
dialogue = dialogue_rows[-20:]
return {
"projects": projects[:40],
"root_tasks": roots[:40],
"final_results": finals,
"recent_canonical_dialogue": dialogue,
"omissions": {
"projects": max(0, len(projects) - 40),
"root_tasks": max(0, len(roots) - 40),
"final_results": max(0, len(all_results) - 16),
"dialogue_rows": max(0, len(dialogue_rows) - 20),
},
}
def _decision_turn_metadata(ctx: Any, chat_id: int, client_message_id: str, task_metadata: Any) -> Any:
"""Enrich a chat turn's metadata with the structural facts the decision turn
needs: the RUNNING tasks in THIS chat (so it can steer_task the right one
instead of spawning a duplicate) and the originating message id (for idempotent
steer delivery). P5-clean: surfaces state only; the agent picks the target by
judgment among answer / steer_task / promote_chat_to_task / route_to_project."""
addressable_here = _addressable_root_tasks(ctx, chat_id)
running_here = [row for row in addressable_here if row.get("status") == "running"]
project_id = _project_id_for_registered_chat(ctx, chat_id)
is_main_lane = not bool(project_id)
try:
# Every non-Project owner transport is the Main lane. External transports
# commonly use a real provider chat id rather than Web's numeric ``1``;
# keying this decision to ``chat_id == 1`` made their canonical router see
# neither Projects nor globally addressable roots.
main_manifest = _main_routing_manifest(ctx) if is_main_lane else {}
if main_manifest and not (
main_manifest.get("projects") or main_manifest.get("root_tasks")
):
main_manifest = {}
except Exception:
log.warning("Unable to build Main routing manifest", exc_info=True)
main_manifest = {"error": "routing_manifest_unavailable"} if is_main_lane else {}
if not addressable_here and not client_message_id and not main_manifest:
return task_metadata
md = dict(task_metadata) if isinstance(task_metadata, dict) else {}
if addressable_here:
md["current_chat"] = {
"chat_id": int(chat_id or 0),
"running_tasks": running_here,
"addressable_root_tasks": addressable_here,
}
if main_manifest:
md["main_routing_manifest"] = main_manifest
if client_message_id:
md["client_message_id"] = client_message_id
option_roots = (
list(main_manifest.get("root_tasks") or [])
if is_main_lane and isinstance(main_manifest, dict)
else addressable_here
)
manual_options = [
{
"action": "steer_task",
"task_id": row["task_id"],
"status": row["status"],
"title": row.get("title") or row.get("objective"),
"project_id": str(row.get("project_id") or ""),
}
for row in option_roots
if isinstance(row, dict) and row.get("task_id")
]
if is_main_lane and isinstance(main_manifest, dict):
manual_options.extend({
"action": "new_task_in_project",
"project_id": str(row.get("project_id") or ""),
"project_name": str(row.get("name") or row.get("project_id") or "Project"),
"label": f"New task in {str(row.get('name') or 'Project')}",
} for row in list(main_manifest.get("projects") or []) if isinstance(row, dict))
elif project_id:
manual_options.append({
"action": "new_task_in_project",
"project_id": project_id,
"label": "New task in Project",
})
md["routing_contract"] = {
"llm_first": True,
"source_lane": "main" if is_main_lane else "project",
"valid_actions": [
"answer_inline", "steer_task", "promote_chat_to_task", "route_to_project",
"needs_manual_target",
],
"on_uncertain_or_invalid_target": "needs_manual_target",
"manual_target_tool": {"name": "route_to_project", "project_id": ""},
"manual_options": manual_options,
}
return md
def _supervisor_loop_stalled(last_tick: float, now: float, deadline_sec: int) -> bool:
"""True when the supervisor loop has not published a liveness tick within the
deadline (WS3). deadline_sec<=0 disables the watchdog."""
return deadline_sec > 0 and (now - last_tick) > deadline_sec
def _chat_turn_wedged(busy: bool, last_activity_ts, now: float, deadline_sec: int) -> bool:
"""True when an IN-PROCESS direct-chat turn is busy but its liveness tick has been
silent past the deadline (WS3). ``last_activity_ts is None`` => the turn has not
started its liveness loop yet (not wedged). deadline_sec<=0 disables the check."""
if not busy or last_activity_ts is None or deadline_sec <= 0:
return False
return (now - last_activity_ts) > deadline_sec
def _alert_chat_turn_wedge(task_id, gap: float) -> None:
"""WS3: a direct-chat turn is heartbeat-silent. New messages still get answered
(WS10 ephemeral decision turns), but a hung IN-PROCESS turn cannot be killed and
still holds the chat-agent lock, so admission cannot be freed in-process (full
kill-ability via out-of-process direct chat was deferred per owner). Surface it +
recommend /restart, which is the safe full recovery."""
from supervisor.state import append_jsonl, load_state
try:
append_jsonl(DATA_DIR / "logs" / "supervisor.jsonl", {
"ts": utc_now_iso(), "type": "chat_turn_wedge",
"task_id": str(task_id or ""), "silent_sec": round(gap, 1),
})
except Exception:
log.debug("chat-turn wedge log failed", exc_info=True)
try:
owner_chat = int((load_state() or {}).get("owner_chat_id") or 0)
if owner_chat:
from supervisor.message_bus import send_with_budget
send_with_budget(
owner_chat,
f"⚠️ A chat turn looks wedged (~{int(gap)}s with no heartbeat). New messages "
"still get answered, but the stuck turn can't be cleared in-process — /restart "
"to fully recover it.",
is_progress=True,
task_id=str(task_id or ""),
progress_meta={
"task_incident": "chat_turn_wedge",
"toast_once": f"{task_id or 'direct-chat'}:chat_turn_wedge",
},
)
except Exception:
log.debug("chat-turn wedge owner alert failed", exc_info=True)
def _start_supervisor_liveness_watchdog(liveness: list, stop_event=None) -> None:
"""Dedicated daemon thread (NOT inside the supervisor loop, so it fires even when
that loop stalls). It ALERTS the owner on two silent-wedge classes — a supervisor
loop stall (new-message intake starvation) and a heartbeat-silent in-process
direct-chat turn — converting a multi-hour silent wedge into an immediate signal.
It deliberately does NOT kill a hung thread or free the chat-agent lock: the wedged
turn holds that lock for its whole duration, so in-process admission-freeing is
unsafe (out-of-process direct chat for full kill-ability was deferred per owner);
WS10 ephemeral decision turns keep the chat responsive meanwhile. ``stop_event`` is
a PER-GENERATION token: when the supervisor loop that owns ``liveness`` exits (incl.
the crash-storm death path, which never sets the global restart flag), it is set so
this watchdog stops watching a now-stale liveness list (no false post-revival alert)."""
from ouroboros.config import get_supervisor_liveness_deadline_sec
deadline = get_supervisor_liveness_deadline_sec()
if deadline <= 0:
return
def _watch() -> None:
from supervisor.state import append_jsonl, load_state
interval = min(15, max(1, deadline // 3))
loop_alerted = False
wedged_task = None
while not _restart_requested.is_set() and not (stop_event is not None and stop_event.is_set()):
time.sleep(interval)
now = time.time()
# (1) Supervisor loop stall — new-message intake starvation.
if _supervisor_loop_stalled(liveness[0], now, deadline):
if not loop_alerted:
gap = now - liveness[0]
log.error(
"Supervisor loop STALLED ~%.0fs — new-message intake starved (WS10 "
"ephemeral chat still answers); investigate a blocking step.", gap,
)
try:
append_jsonl(DATA_DIR / "logs" / "supervisor.jsonl", {
"ts": utc_now_iso(), "type": "supervisor_loop_stall", "stalled_sec": round(gap, 1),
})
except Exception:
log.debug("loop-stall log failed", exc_info=True)
try:
owner_chat = int((load_state() or {}).get("owner_chat_id") or 0)
if owner_chat:
from supervisor.message_bus import send_with_budget
send_with_budget(
owner_chat,
f"⚠️ My supervisor loop stalled for ~{int(gap)}s — new messages may be "
"delayed. I recover on the next tick or a restart; investigating.",
is_progress=True,
progress_meta={
"task_incident": "supervisor_loop_stall",
"toast_once": f"supervisor-loop-stall:{int(liveness[0])}",
},
)
except Exception:
log.debug("loop-stall owner alert failed", exc_info=True)
loop_alerted = True
else:
loop_alerted = False
# (2) In-process direct-chat turn wedge — a heartbeat-silent busy turn.
try:
from supervisor.workers import chat_turn_liveness
busy, turn_task, turn_ts = chat_turn_liveness()
except Exception:
busy, turn_task, turn_ts = (False, None, None)
if _chat_turn_wedged(busy, turn_ts, now, deadline):
if wedged_task != turn_task: # alert once per wedged turn
_alert_chat_turn_wedge(turn_task, now - (turn_ts or now))
wedged_task = turn_task
elif not busy:
wedged_task = None
threading.Thread(target=_watch, name="supervisor-liveness-watchdog", daemon=True).start()
def _periodic_supervisor_maintenance(last_custody_reap: list, last_review_reconcile: list) -> None:
"""Throttled periodic upkeep extracted from the supervisor loop: custody reap
of orphaned task-scoped processes (every 600s) + review-job zombie reconcile
(every 300s). Each cadence gates itself via its own last-run marker."""
if time.time() - last_custody_reap[0] > 600:
last_custody_reap[0] = time.time()
try:
from ouroboros.process_custody import reap_orphaned_processes
from supervisor.queue import RUNNING as _running_tasks
reap_orphaned_processes(
DATA_DIR, running_task_ids=set(_running_tasks.keys()),
live_owner_skills=_installed_skill_names(),
)
except Exception:
log.debug("Periodic custody reap failed", exc_info=True)
if time.time() - last_review_reconcile[0] > 300:
last_review_reconcile[0] = time.time()
_periodic_zombie_reconcile()
def _scoped_task_metadata(project_id: str, task_metadata: Any) -> Any:
"""Bind a chat frame's task_metadata to the thread's project via chat_id (the
SSOT). A registered project chat scopes to its OWN project, overriding any
client-supplied project_id; a non-project chat DROPS an untrusted client
project_id (work is scoped to a project only via the promote_chat_to_task tool,
never a raw ws frame). Prevents a stale/malformed frame (chat_id A + project_id
B) from rendering in A while loading/writing project B's memory."""
if project_id:
return {**(task_metadata or {}), "project_id": project_id}
if task_metadata and task_metadata.get("project_id"):
return {k: v for k, v in task_metadata.items() if k != "project_id"}
return task_metadata
def _owner_binding_chat_id(ctx: Any, chat_id: int, is_external_transport: bool) -> int:
"""The owner's canonical chat for owner-targeted notices (restart, supervisor
death, consciousness). External transports bind to their own chat; a WEB owner
always binds to MAIN (1), never a project panel — so if the first post-reset
web message lands in a project room, owner notices still reach main."""
if not is_external_transport and _project_id_for_registered_chat(ctx, chat_id):
return 1
try:
return int(chat_id or 0)
except (TypeError, ValueError):
return 0
def _project_id_for_registered_chat(ctx: Any, chat_id: int) -> str:
"""Return the registered project id for a project chat_id, else ``""``.
NOT an isolation gate (full project awareness, v6.32.0): the one mind notices
EVERY human message via inject_observation, project rooms included. This just
classifies a chat as a project thread so the message is scoped to that project
(task_metadata.project_id) and routed to its panel. This active-only lookup is
paired with ``_reserved_project_for_chat`` for deleting/tombstoned IDs, so a
reserved chat cannot be resurrected through ordinary routing.
"""
try:
from ouroboros.projects_registry import list_projects
cid = int(chat_id or 0)
for project in list_projects(ctx.DRIVE_ROOT):
try:
if int(project.get("chat_id") or 0) == cid:
return str(project.get("id") or "").strip()
except (TypeError, ValueError):
continue
except Exception:
log.debug("Project chat_id lookup failed", exc_info=True)
return ""
def _reserved_project_for_chat(ctx: Any, chat_id: int) -> Dict[str, Any]:
try:
from ouroboros.projects_registry import list_reserved_projects
cid = int(chat_id or 0)
for project in list_reserved_projects(ctx.DRIVE_ROOT):
try:
if int(project.get("chat_id") or 0) == cid:
return dict(project)
except (TypeError, ValueError):
continue
except Exception:
log.debug("Reserved Project chat lookup failed", exc_info=True)
return {}
def _record_routing_receipt(
bridge: Any,
ctx: Any,
*,
chat_id: int,
client_message_id: str,
action: str,
target: str = "",
status: str,
persist: bool = True,
options: Optional[list] = None,
) -> None:
"""Emit a typed bubble-free ack and optionally persist its presentation state."""
if persist:
try:
from ouroboros.project_dialogue import append_chat_annotation
append_chat_annotation(
ctx.DRIVE_ROOT,
client_message_id,
action=action,
target=target,
status=status,
)
except Exception:
log.debug("Routing annotation append failed", exc_info=True)
try:
ack = getattr(bridge, "send_routing_ack", None)
if callable(ack):
ack_kwargs = {
"client_message_id": client_message_id,
"action": action,
"target": target,
"status": status,
}
if options is not None:
ack_kwargs["options"] = options
ack(
chat_id,
**ack_kwargs,
)
else:
broadcast = getattr(bridge, "broadcast", None)
if callable(broadcast):
payload = {
"type": "message_annotation",
"annotation_type": "routing_ack",
"chat_id": int(chat_id or 0),
"client_message_id": str(client_message_id or ""),
"action": action,
"target": target,
"status": status,
"suppress_bubble": True,
}
if options is not None:
payload["options"] = options
broadcast(payload)
except Exception:
log.debug("Routing receipt broadcast failed", exc_info=True)
def _route_owner_message(bridge: Any, ctx: Any, incoming: Dict[str, Any]) -> None:
"""Route one non-command owner message through the canonical decision lane."""
chat_id = int(incoming["chat_id"])
text = str(incoming.get("text") or "")
image_caption = str(incoming.get("image_caption") or "")
client_message_id = str(incoming.get("client_message_id") or "")
image_data = incoming.get("image_data")
task_constraint = incoming.get("task_constraint")
task_metadata = incoming.get("task_metadata")
reserved_project = _reserved_project_for_chat(ctx, chat_id)
project_id = (
str(reserved_project.get("id") or "")
if str((reserved_project or {}).get("lifecycle") or "active") == "active"
else ""
)
if reserved_project and not project_id:
_record_routing_receipt(
bridge,
ctx,
chat_id=chat_id,
client_message_id=client_message_id,
action="project_route",
target=str(reserved_project.get("id") or ""),
status="project_unavailable",
)
return
ctx.consciousness.inject_observation(f"Message from my human: {incoming.get('log_text') or ''}")
task_metadata = _scoped_task_metadata(project_id, task_metadata)
# The turn's origin identity rides UNCONDITIONALLY (not only when the
# decision lane runs): a bare direct turn with no projects/roots yet — the
# first-ever project creation — must still carry it so promote/route/bind
# receive the ref by value.
origin_ref = incoming.get("origin_message_ref")
if isinstance(origin_ref, dict) and origin_ref:
task_metadata = {
**(task_metadata or {}),
"origin_message_ref": origin_ref,
"origin_message_text": str(incoming.get("log_text") or ""),
}
else:
# A suppressed (never-logged) message has a DESIGNED absence of origin;
# downstream binders must not classify it as a producer bug.
task_metadata = {**(task_metadata or {}), "origin_suppressed": True}
if project_id:
routed_to_task = _route_project_chat_to_running_task(
ctx,
chat_id,
text or image_caption,
client_message_id,
task_metadata=task_metadata,
image_data=image_data,
)
if routed_to_task:
_record_routing_receipt(
bridge,
ctx,
chat_id=chat_id,
client_message_id=client_message_id,
action="mailbox_delivery",
target=routed_to_task,
status="delivered",
)
return
global_roots = _addressable_root_tasks(ctx, None)
try:
from ouroboros.projects_registry import list_projects
has_projects = bool(list_projects(ctx.DRIVE_ROOT))
except Exception:
log.warning("Unable to inspect Projects for owner routing", exc_info=True)
has_projects = True
needs_decision_lane = bool(project_id) or has_projects or bool(global_roots)
if needs_decision_lane:
task_metadata = _decision_turn_metadata(ctx, chat_id, client_message_id, task_metadata)
agent = ctx.get_chat_agent()
def _run_direct() -> None:
try:
ctx.handle_chat_direct(
chat_id,
text or image_caption,
image_data,
task_constraint=task_constraint,
task_metadata=task_metadata,
)
finally:
ctx.consciousness.resume()
if needs_decision_lane or agent._busy:
threading.Thread(
target=ctx.handle_chat_ephemeral,