-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclio_bot_mode.py
More file actions
3182 lines (2907 loc) · 125 KB
/
Copy pathclio_bot_mode.py
File metadata and controls
3182 lines (2907 loc) · 125 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
"""Clio-native Bot Mode services.
A Bot is a Clio profile. This module provides the profile metadata, canonical
session identity, local/peer direct-message transport, routines, and bounded
team-room coordinator used by the CLI, API surfaces, and desktop plugin.
The implementation is deliberately local first:
* profile identity remains in ``profile.yaml``;
* Bot/Group conversations remain ordinary rows in that profile's ``state.db``;
* routines remain ordinary profile-scoped Clio cron jobs;
* room coordination state is one small atomic JSON document at the Clio root;
* remote delivery composes over the authenticated ``api_server`` platform.
No user-authored ``SOUL.md`` file is ever changed by Bot Mode.
"""
from __future__ import annotations
import base64
import binascii
import contextlib
import hashlib
import ipaddress
import json
import os
import re
import signal
import subprocess
import sys
import tempfile
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence
BOT_CHAT_TITLE = "Bot Chat"
BOT_CANONICAL_KEY = "bot.chat"
BOT_PROTOCOL_VERSION = 1
BOT_METADATA_VERSION = 1
ROOM_STORE_VERSION = 1
ROOM_MIN_MEMBERS = 2
ROOM_MAX_MEMBERS = 6
ROOM_MAX_ROUNDS = 3
ROOM_MAX_VISIBLE_PER_SEND = 10
ROOM_HISTORY_LIMIT = 24
ROOM_MAX_ATTACHMENTS = 12
ROOM_MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024
ROOM_REMOTE_ATTACHMENT_BYTES = 7 * 1024 * 1024
PEER_MAX_RESPONSE_BYTES = 1024 * 1024
ROOM_SOFT_TIMEOUT_SECONDS = 90.0
ROOM_HARD_TIMEOUT_SECONDS = 300.0
WORKER_ACTIVE_SECONDS = 120.0
BOT_HANDOFF_VERSION = 1
BOT_HANDOFF_POLL_SECONDS = 0.1
BOT_HANDOFF_MAX_TEXT = 100_000
BOT_CHILD_RESULT_VERSION = 1
BOT_CHILD_EVENT_VERSION = 1
BOT_CHILD_RESULT_MAX_TEXT = 200_000
BOT_CHILD_EVENT_MAX_LINE = 4096
BOT_PEER_HANDOFF_VERSION = 1
BOT_PEER_TURN_MAX_ACTIVE = 32
BOT_PEER_TURN_MAX_RECORDS = 128
BOT_PEER_TURN_TTL_SECONDS = 120.0
_PROFILE_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
_SOURCE_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
_HANDLE_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,127}$")
_MENTION_RE = re.compile(r"(?<![\w@])@([a-zA-Z0-9][a-zA-Z0-9_-]{0,127})")
_PASS_RE = re.compile(r"^\s*\(?\s*pass\s*\)?\s*[.!]?\s*$", re.I)
_ROOM_STAGING_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,127}$")
_PEER_TURN_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
_MIME_RE = re.compile(r"^[a-z0-9][a-z0-9!#$&^_.+-]{0,63}/[a-z0-9][a-z0-9!#$&^_.+-]{0,63}$")
_ROOM_ATTACHMENT_MIME_TYPES = frozenset(
{"application/pdf", "image/png", "image/jpeg", "image/webp", "text/plain", "text/markdown"}
)
_ROOM_LOCK = threading.RLock()
_CRON_LOCK = threading.RLock()
_ROOM_HANDOFF_LOCK = threading.RLock()
_ROOM_HANDOFFS: Dict[str, Dict[str, Any]] = {}
_PEER_ROOM_TURN_LOCK = threading.RLock()
_PEER_ROOM_TURNS: Dict[str, Dict[str, Any]] = {}
class BotModeError(RuntimeError):
"""Expected Bot Mode usage or delivery failure."""
@dataclass(frozen=True)
class BotAddress:
"""Stable identity for one Bot on one source."""
profile: str
source: str = "local"
source_label: str = "This device"
@property
def key(self) -> str:
return f"{self.source}:{self.profile}"
@property
def base_handle(self) -> str:
return "clio" if self.profile == "default" else self.profile
def handle(self, duplicated_names: Iterable[str] = ()) -> str:
duplicate_set = {str(item).lower() for item in duplicated_names}
if self.base_handle.lower() not in duplicate_set and self.source == "local":
return self.base_handle
suffix = _slug(self.source_label if self.source_label else self.source)
return f"{self.base_handle}-{suffix}"
@dataclass(frozen=True)
class RoomTurnResult:
room_id: str
epoch: int
rounds: int
state: str
needs_user: bool
messages: List[Dict[str, Any]]
suppressed: int = 0
activity: Optional[List[Dict[str, Any]]] = None
def _slug(value: str) -> str:
slug = re.sub(r"[^a-z0-9_-]+", "-", str(value or "").strip().lower()).strip("-_")
return slug or "source"
def _validate_profile(name: str) -> str:
normalized = str(name or "").strip().lower()
if not _PROFILE_RE.fullmatch(normalized):
raise ValueError(f"Invalid profile name: {name!r}")
return normalized
def _validate_source(name: str) -> str:
normalized = str(name or "local").strip().lower()
if not _SOURCE_RE.fullmatch(normalized):
raise ValueError(f"Invalid Bot source: {name!r}")
return normalized
def _validate_room_staging_id(room_id: str) -> str:
normalized = str(room_id or "").strip().lower()
if not _ROOM_STAGING_RE.fullmatch(normalized):
raise ValueError("Invalid Bot room attachment identifier")
return normalized
def _validate_peer_turn_id(turn_id: Any) -> str:
normalized = str(turn_id or "").strip()
if not _PEER_TURN_RE.fullmatch(normalized):
raise ValueError("Invalid peer Bot room turn identifier")
return normalized
def _validate_room_epoch(epoch: Any) -> int:
if isinstance(epoch, bool):
raise ValueError("Bot room epoch must be a positive integer")
try:
normalized = int(epoch)
except (TypeError, ValueError) as exc:
raise ValueError("Bot room epoch must be a positive integer") from exc
if normalized < 1 or str(normalized) != str(epoch).strip():
raise ValueError("Bot room epoch must be a positive integer")
return normalized
def _validate_attachment_name(name: Any) -> str:
if not isinstance(name, str):
raise ValueError("Attachment name must be a string")
normalized = name.strip()
if (
not normalized
or len(normalized) > 200
or normalized in {".", ".."}
or Path(normalized).name != normalized
or "/" in normalized
or "\\" in normalized
or any(ord(character) < 32 or ord(character) == 127 for character in normalized)
):
raise ValueError("Attachment name must be a plain filename of at most 200 characters")
return normalized
def _validate_attachment_mime(mime_type: Any) -> str:
if not isinstance(mime_type, str):
raise ValueError("Attachment MIME type must be a string")
normalized = mime_type.strip().lower()
if not _MIME_RE.fullmatch(normalized):
raise ValueError("Attachment MIME type is invalid")
if normalized not in _ROOM_ATTACHMENT_MIME_TYPES and not normalized.startswith("image/"):
raise ValueError(f"Unsupported room attachment type: {normalized}")
return normalized
def _profiles_module():
from clio_cli import profiles
return profiles
def clio_root_for_home(home: Path) -> Path:
"""Return the root ``~/.clio`` for a default or named profile home."""
resolved = Path(home).expanduser().resolve()
if resolved.parent.name == "profiles":
return resolved.parent.parent
return resolved
def profile_name_for_home(home: Path) -> str:
resolved = Path(home).expanduser().resolve()
return resolved.name if resolved.parent.name == "profiles" else "default"
def profile_home(profile: str) -> Path:
profile = _validate_profile(profile)
profiles = _profiles_module()
if not profiles.profile_exists(profile):
raise FileNotFoundError(f"Profile '{profile}' does not exist")
return Path(profiles.get_profile_dir(profile))
def _read_yaml_mapping(path: Path) -> Dict[str, Any]:
if not path.is_file():
return {}
try:
import yaml
value = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
return dict(value) if isinstance(value, dict) else {}
except Exception:
return {}
def _atomic_yaml(path: Path, value: Mapping[str, Any]) -> None:
import yaml
path.parent.mkdir(parents=True, exist_ok=True)
payload = yaml.safe_dump(dict(value), sort_keys=False, default_flow_style=False)
fd, raw_tmp = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=str(path.parent))
tmp = Path(raw_tmp)
try:
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.write(payload)
handle.flush()
os.fsync(handle.fileno())
os.chmod(tmp, 0o600)
os.replace(tmp, path)
finally:
tmp.unlink(missing_ok=True)
def read_bot_metadata(profile: str) -> Dict[str, Any]:
"""Read optional Bot metadata, returning safe defaults for legacy profiles."""
profile = _validate_profile(profile)
home = profile_home(profile)
raw = _read_yaml_mapping(home / "profile.yaml")
bot: Dict[str, Any] = dict(raw["bot"]) if isinstance(raw.get("bot"), dict) else {}
groups: List[Any] = list(bot["groups"]) if isinstance(bot.get("groups"), list) else []
return {
"version": int(bot.get("version") or BOT_METADATA_VERSION),
"identity_id": str(bot.get("identity_id") or "").strip(),
"enabled": bot.get("enabled", True) is not False,
"display_name": str(raw.get("display_name") or bot.get("display_name") or profile).strip() or profile,
"title": str(bot.get("title") or "").strip(),
"description": str(bot.get("description") or raw.get("description") or "").strip(),
"hidden": bool(bot.get("hidden", False)),
"avatar": bot.get("avatar") if isinstance(bot.get("avatar"), dict) else {},
"groups": [str(group) for group in groups if str(group).strip()],
"created_at": bot.get("created_at"),
"updated_at": bot.get("updated_at"),
}
def ensure_bot_identity(profile: str) -> str:
"""Return a durable profile-Bot identity that survives profile renames."""
profile = _validate_profile(profile)
path = profile_home(profile) / "profile.yaml"
with _ROOM_LOCK:
raw = _read_yaml_mapping(path)
bot: Dict[str, Any] = dict(raw["bot"]) if isinstance(raw.get("bot"), dict) else {}
identity_id = str(bot.get("identity_id") or "").strip()
if not identity_id:
identity_id = f"bot-{uuid.uuid4().hex}"
bot["identity_id"] = identity_id
bot.setdefault("version", BOT_METADATA_VERSION)
raw["bot"] = bot
_atomic_yaml(path, raw)
return identity_id
def _latest_worker_session(home: Path) -> Optional[Dict[str, Any]]:
"""Return the freshest kanban/tool worker heartbeat for one profile."""
db_path = Path(home) / "state.db"
if not db_path.is_file():
return None
try:
from clio_state import SessionDB
db = SessionDB(db_path=db_path)
try:
for session in db.list_sessions_rich(
limit=50,
order_by_last_active=True,
include_hidden=True,
):
source = str(session.get("source") or "").strip().lower()
if source not in {"kanban", "tool"}:
continue
last_active = float(session.get("last_active") or session.get("started_at") or 0)
return {
"id": session["id"],
"source": source,
"title": session.get("title") or "",
"last_active": last_active,
}
finally:
db.close()
except Exception:
return None
return None
def update_bot_metadata(profile: str, **updates: Any) -> Dict[str, Any]:
"""Atomically update Bot metadata while preserving unrelated profile data."""
profile = _validate_profile(profile)
home = profile_home(profile)
path = home / "profile.yaml"
with _ROOM_LOCK:
raw = _read_yaml_mapping(path)
bot: Dict[str, Any] = dict(raw["bot"]) if isinstance(raw.get("bot"), dict) else {}
now = time.time()
bot.setdefault("version", BOT_METADATA_VERSION)
bot.setdefault("created_at", now)
allowed = {"enabled", "title", "description", "hidden", "avatar", "groups"}
for key, value in updates.items():
if key == "display_name":
display = str(value or "").strip()
raw["display_name"] = display or profile
elif key in allowed:
if key in {"title", "description"}:
bot[key] = str(value or "").strip()
elif key in {"enabled", "hidden"}:
bot[key] = bool(value)
elif key == "avatar":
if not isinstance(value, dict):
raise ValueError("avatar must be an object")
bot[key] = dict(value)
elif key == "groups":
if not isinstance(value, (list, tuple)):
raise ValueError("groups must be a list")
bot[key] = sorted({str(item).strip() for item in value if str(item).strip()})
bot["updated_at"] = now
raw["bot"] = bot
_atomic_yaml(path, raw)
return read_bot_metadata(profile)
def list_bot_roster(*, include_hidden: bool = False, source: str = "local", source_label: str = "This device") -> List[Dict[str, Any]]:
"""List profile-backed Bots with deterministic source-qualified handles."""
source = _validate_source(source)
records: List[Dict[str, Any]] = []
for info in _profiles_module().list_profiles():
meta = read_bot_metadata(info.name)
if not meta["enabled"] or (meta["hidden"] and not include_hidden):
continue
address = BotAddress(info.name, source, source_label)
identity_id = ensure_bot_identity(info.name)
worker_session = _latest_worker_session(profile_home(info.name))
worker_active = bool(
worker_session
and float(worker_session.get("last_active") or 0) >= time.time() - WORKER_ACTIVE_SECONDS
)
records.append(
{
"profile": info.name,
"source": source,
"source_label": source_label,
"key": address.key,
"identity_id": identity_id,
"handle": address.handle(),
"display_name": meta["display_name"],
"title": meta["title"],
"description": meta["description"],
"hidden": meta["hidden"],
"avatar": meta["avatar"],
"groups": meta["groups"],
"model": getattr(info, "model", None),
"provider": getattr(info, "provider", None),
"gateway_running": bool(getattr(info, "gateway_running", False)),
"worker_session": worker_session,
"worker_active": worker_active,
"is_default": bool(getattr(info, "is_default", False)),
}
)
return records
def source_qualified_roster(sources: Mapping[str, Mapping[str, Any]]) -> List[Dict[str, Any]]:
"""Merge cached/live source inventories and disambiguate duplicate handles."""
rows: List[Dict[str, Any]] = []
base_counts: Dict[str, int] = {}
for source, payload in sources.items():
label = str(payload.get("label") or source)
for raw in payload.get("bots") or []:
profile = _validate_profile(str(raw.get("profile") or raw.get("name") or ""))
address = BotAddress(profile, _validate_source(source), label)
row = {**dict(raw), "profile": profile, "source": address.source, "source_label": label, "key": address.key}
row["_base_handle"] = address.base_handle
rows.append(row)
base_counts[address.base_handle] = base_counts.get(address.base_handle, 0) + 1
duplicates = {name for name, count in base_counts.items() if count > 1}
for row in rows:
address = BotAddress(row["profile"], row["source"], row["source_label"])
row["handle"] = address.handle(duplicates)
row.pop("_base_handle", None)
return sorted(rows, key=lambda row: (str(row.get("display_name") or row["profile"]).lower(), row["source"]))
def ensure_canonical_session(
profile: str,
*,
canonical_key: str = BOT_CANONICAL_KEY,
title: str = BOT_CHAT_TITLE,
identity_kind: str = "bot",
hidden: bool = True,
) -> Dict[str, Any]:
"""Atomically get/create one canonical session in a profile's state DB."""
profile = _validate_profile(profile)
home = profile_home(profile)
from clio_state import SessionDB
with _ROOM_LOCK:
db = SessionDB(db_path=home / "state.db")
try:
owner_kind = "profile_bot" if identity_kind == "bot" else "bot_group"
owner_ref = ensure_bot_identity(profile)
db.reconcile_canonical_session_owner(
owner_profile=profile,
canonical_key=str(canonical_key),
identity_kind=identity_kind,
owner_kind=owner_kind,
owner_ref=owner_ref,
)
return db.get_or_create_canonical_session(
owner_profile=profile,
canonical_key=str(canonical_key),
title=title,
source="bot" if identity_kind == "bot" else "bot_group",
identity_kind=identity_kind,
hidden=hidden,
owner_kind=owner_kind,
owner_ref=owner_ref,
adopt_exact_title=(
identity_kind == "bot"
and str(canonical_key) == BOT_CANONICAL_KEY
and title == BOT_CHAT_TITLE
),
)
finally:
db.close()
def ensure_bot_chat(profile: str, *, hidden: bool = True) -> Dict[str, Any]:
return ensure_canonical_session(profile, hidden=hidden)
def ensure_group_session(profile: str, room_id: str, room_name: str) -> Dict[str, Any]:
room_id = _slug(room_id)
return ensure_canonical_session(
profile,
canonical_key=f"group:{room_id}",
title=f"Group: {room_name}"[:100],
identity_kind="group",
hidden=False,
)
def capability_fingerprint(home_or_profile: str | os.PathLike[str] | Path) -> str:
"""Fingerprint only user-controlled Bot capabilities; unchanged state is stable."""
try:
raw = Path(home_or_profile).expanduser()
if raw.is_dir() or "/" in str(home_or_profile):
home = raw.resolve()
profile = profile_name_for_home(home)
else:
profile = _validate_profile(str(home_or_profile))
home = profile_home(profile)
surface: Dict[str, Any] = {"protocol": BOT_PROTOCOL_VERSION, "profile": profile}
profile_yaml = _read_yaml_mapping(home / "profile.yaml")
surface["bot"] = profile_yaml.get("bot") if isinstance(profile_yaml.get("bot"), dict) else {}
config = _read_yaml_mapping(home / "config.yaml")
surface["agent"] = {"bot_mode_protocol": (config.get("agent") or {}).get("bot_mode_protocol", True)} if isinstance(config.get("agent"), dict) else {}
surface["skills_config"] = config.get("skills") if isinstance(config.get("skills"), dict) else {}
surface["tools"] = config.get("tools") if isinstance(config.get("tools"), dict) else {}
surface["mcp_servers"] = config.get("mcp_servers") if isinstance(config.get("mcp_servers"), dict) else {}
surface["peers"] = sorted((_read_yaml_mapping(clio_root_for_home(home) / "config.yaml").get("bot_peers") or {}).keys())
soul = home / "SOUL.md"
surface["soul"] = hashlib.sha256(soul.read_bytes()).hexdigest() if soul.is_file() else ""
skills = home / "skills"
surface["installed_skills"] = sorted(
str(item.parent.relative_to(skills)) for item in skills.glob("**/SKILL.md")
) if skills.is_dir() else []
surface["roster"] = [row["profile"] for row in list_bot_roster(include_hidden=True)]
blob = json.dumps(surface, sort_keys=True, separators=(",", ":"), default=str).encode("utf-8")
return hashlib.sha256(blob).hexdigest()[:16]
except Exception:
return "unavailable"
def protocol_epoch_line(home: Path) -> str:
return f"Clio Bot capability epoch: {capability_fingerprint(home)}"
def stored_prompt_capability_stale(prompt: str, home: Path) -> bool:
match = re.search(r"Clio Bot capability epoch: ([0-9a-f]{16})", prompt or "")
if not match:
return False
current = capability_fingerprint(home)
return current != "unavailable" and match.group(1) != current
def _agent_home(agent: Any) -> Optional[Path]:
db = getattr(agent, "_session_db", None)
path = getattr(db, "db_path", None)
if path:
return Path(path).resolve().parent
try:
from clio_constants import get_clio_home
return Path(get_clio_home()).resolve()
except Exception:
return None
def _agent_is_canonical(agent: Any) -> bool:
# During AIAgent construction no session row has been bound yet. Avoid a
# speculative DB read: it breaks cold-start prompt stability and turns a
# generic MagicMock/session adapter into a false Bot match.
if not bool(getattr(agent, "_session_db_created", False)):
return False
db = getattr(agent, "_session_db", None)
session_id = getattr(agent, "session_id", None)
if not db or not session_id:
return False
try:
row = db.get_session(session_id)
return bool(row and row.get("canonical_key") == BOT_CANONICAL_KEY and row.get("identity_kind") == "bot")
except Exception:
return False
def bot_protocol_section_for_agent(agent: Any) -> str:
"""Return the protocol only for the profile's canonical Bot Chat."""
if not getattr(agent, "_bot_mode_protocol", True) or not _agent_is_canonical(agent):
return ""
home = _agent_home(agent)
if home is None:
return ""
me = profile_name_for_home(home)
handle = "clio" if me == "default" else me
roster = list_bot_roster(include_hidden=True)
teammates = [f"@{row['handle']}" for row in roster if row["profile"] != me]
peer_names = sorted((_read_yaml_mapping(clio_root_for_home(home) / "config.yaml").get("bot_peers") or {}).keys())
peer_text = ""
if peer_names:
peer_text = (
" Registered peer gateways: " + ", ".join(peer_names) + ". Use `clio peer dm <peer>/<profile> --file <path>` for cross-machine delivery."
)
return (
"## Messaging other Clio Bots\n"
"This is your canonical Bot Chat. Other Bots and the user may send attributed messages here. "
f"Your handle is @{handle}. A teammate message begins `Message from Clio Bot <sender> (@<handle>):`; "
"reply to that teammate rather than pretending it came directly from the user. For a local handoff, "
"write the exact message to a file first, then run `clio bot dm <profile> --from <your-profile> --file <path>`; "
"never interpolate teammate text into a shell command. Mention handles are validated against the live roster. "
f"Teammates now: {', '.join(teammates) if teammates else '(none)'}.{peer_text}\n"
+ protocol_epoch_line(home)
)
def maybe_refresh_bot_prompt(agent: Any, stored_prompt: str, system_message: Optional[str]) -> bool:
"""Refresh a stale canonical prompt once per capability change."""
if not _agent_is_canonical(agent):
return False
home = _agent_home(agent)
if home is None:
return False
needs_upgrade = "## Messaging other Clio Bots" not in (stored_prompt or "")
if not needs_upgrade and not stored_prompt_capability_stale(stored_prompt, home):
return False
agent._cached_system_prompt = agent._build_system_prompt(system_message)
try:
agent._session_db.update_system_prompt(agent.session_id, agent._cached_system_prompt)
agent._session_db.set_canonical_capability(
agent.session_id,
fingerprint=capability_fingerprint(home),
epoch=int(time.time()),
)
except Exception:
pass
return True
def _safe_message_text(message: str, *, max_chars: int = 200_000) -> str:
text = str(message or "")
if not text.strip():
raise ValueError("Message must not be empty")
if "\x00" in text:
raise ValueError("Message contains a NUL byte")
if len(text) > max_chars:
raise ValueError(f"Message exceeds {max_chars} characters")
return text
RoomHandoffCallback = Callable[[Mapping[str, Any]], None]
RoomProgressCallback = Callable[[Mapping[str, str], Mapping[str, Any]], None]
def _atomic_handoff_json(path: Path, value: Mapping[str, Any]) -> None:
"""Write one owner-only child/parent handoff frame atomically."""
path.parent.mkdir(parents=True, exist_ok=True)
fd, raw_tmp = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=str(path.parent))
tmp = Path(raw_tmp)
try:
with os.fdopen(fd, "w", encoding="utf-8") as handle:
json.dump(dict(value), handle, ensure_ascii=False, separators=(",", ":"))
handle.flush()
os.fsync(handle.fileno())
os.chmod(tmp, 0o600)
os.replace(tmp, path)
finally:
tmp.unlink(missing_ok=True)
def _read_handoff_json(path: Path) -> Dict[str, Any]:
try:
value = json.loads(path.read_text(encoding="utf-8"))
except (FileNotFoundError, OSError, UnicodeError, json.JSONDecodeError):
return {}
return dict(value) if isinstance(value, dict) else {}
def bot_child_write_result(response: Any) -> bool:
"""Write a token-bound final response for the owning Bot coordinator."""
if os.environ.get("CLIO_BOT_CHILD") != "1":
return False
raw_path = os.environ.get("CLIO_BOT_RESULT_PATH", "").strip()
token = os.environ.get("CLIO_BOT_RESULT_TOKEN", "").strip()
if not raw_path or not token:
return False
text = str(response or "")
if len(text) > BOT_CHILD_RESULT_MAX_TEXT or "\x00" in text:
return False
try:
_atomic_handoff_json(
Path(raw_path),
{
"version": BOT_CHILD_RESULT_VERSION,
"token": token,
"response": text,
},
)
return True
except (OSError, TypeError, ValueError):
return False
def bot_child_emit_tool_event(
event_type: str,
tool_name: Any,
*,
duration: Any = None,
is_error: Any = False,
) -> bool:
"""Append one bounded tool-only event; reasoning and results are excluded."""
if os.environ.get("CLIO_BOT_CHILD") != "1":
return False
raw_path = os.environ.get("CLIO_BOT_EVENT_PATH", "").strip()
token = os.environ.get("CLIO_BOT_EVENT_TOKEN", "").strip()
normalized_type = str(event_type or "").strip().lower()
if not raw_path or not token or normalized_type not in {"tool.started", "tool.completed"}:
return False
name = str(tool_name or "").strip()
if not re.fullmatch(r"[A-Za-z0-9_.:-]{1,128}", name):
return False
event: Dict[str, Any] = {
"version": BOT_CHILD_EVENT_VERSION,
"token": token,
"event": normalized_type,
"name": name,
}
if normalized_type == "tool.completed":
try:
elapsed = max(0.0, min(float(duration or 0.0), 86400.0))
except (TypeError, ValueError):
elapsed = 0.0
event.update(duration=elapsed, is_error=bool(is_error))
payload = (json.dumps(event, ensure_ascii=False, separators=(",", ":")) + "\n").encode("utf-8")
if len(payload) > BOT_CHILD_EVENT_MAX_LINE:
return False
try:
fd = os.open(raw_path, os.O_WRONLY | os.O_APPEND)
try:
os.write(fd, payload)
finally:
os.close(fd)
return True
except OSError:
return False
def _read_bot_child_result(path: Path, token: str, fallback_stdout: str) -> str:
frame = _read_handoff_json(path)
response = frame.get("response")
if (
frame.get("version") == BOT_CHILD_RESULT_VERSION
and frame.get("token") == token
and isinstance(response, str)
and len(response) <= BOT_CHILD_RESULT_MAX_TEXT
and "\x00" not in response
):
return response.strip()
return _bot_turn_output(fallback_stdout)
def _drain_bot_child_events(
path: Path,
token: str,
offset: int,
) -> tuple[List[Dict[str, Any]], int]:
try:
with path.open("rb") as handle:
handle.seek(max(0, int(offset)))
data = handle.read(256 * 1024)
except (FileNotFoundError, OSError, ValueError):
return [], offset
final_newline = data.rfind(b"\n")
if final_newline < 0:
return [], offset
complete = data[: final_newline + 1]
new_offset = offset + final_newline + 1
events: List[Dict[str, Any]] = []
for raw_line in complete.splitlines():
if not raw_line or len(raw_line) > BOT_CHILD_EVENT_MAX_LINE:
continue
try:
frame = json.loads(raw_line.decode("utf-8"))
except (UnicodeError, json.JSONDecodeError):
continue
if not isinstance(frame, dict):
continue
event_type = str(frame.get("event") or "")
name = str(frame.get("name") or "")
if (
frame.get("version") != BOT_CHILD_EVENT_VERSION
or frame.get("token") != token
or event_type not in {"tool.started", "tool.completed"}
or not re.fullmatch(r"[A-Za-z0-9_.:-]{1,128}", name)
):
continue
event: Dict[str, Any] = {"event": event_type, "name": name}
if event_type == "tool.completed":
try:
elapsed = max(0.0, min(float(frame.get("duration") or 0.0), 86400.0))
except (TypeError, ValueError):
elapsed = 0.0
event.update(duration=elapsed, is_error=bool(frame.get("is_error")))
events.append(event)
return events, new_offset
def bot_child_handoff(kind: str, payload: Mapping[str, Any]) -> str:
"""Block a Bot child at a user prompt until its room owner responds.
This is intentionally a tiny, file-based IPC contract. The path and random
token are inherited only by the argv-safe Bot child. Public room state never
contains either value, and a response is accepted only when both the token
and request id still match. Returning from this function resumes the same
process, agent instance, canonical member session, and tool call.
"""
if os.environ.get("CLIO_BOT_CHILD") != "1":
raise BotModeError("Bot handoff is only available to a managed Bot child")
raw_path = os.environ.get("CLIO_BOT_HANDOFF_PATH", "").strip()
token = os.environ.get("CLIO_BOT_HANDOFF_TOKEN", "").strip()
if not raw_path or not token:
raise BotModeError("Bot room handoff channel is unavailable")
kind = str(kind or "").strip().lower()
if kind not in {"clarify", "approval"}:
raise ValueError("Unsupported Bot room handoff kind")
path = Path(raw_path)
request_id = f"handoff-{uuid.uuid4().hex}"
request = {
"request_id": request_id,
"kind": kind,
**dict(payload),
}
_atomic_handoff_json(
path,
{
"version": BOT_HANDOFF_VERSION,
"token": token,
"state": "pending",
"request": request,
},
)
try:
timeout = max(1.0, float(os.environ.get("CLIO_BOT_HANDOFF_TIMEOUT") or "300"))
except (TypeError, ValueError):
timeout = 300.0
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
frame = _read_handoff_json(path)
if frame.get("token") != token:
time.sleep(BOT_HANDOFF_POLL_SECONDS)
continue
if frame.get("state") == "responded" and frame.get("request_id") == request_id:
return str(frame.get("response") or "")
if frame.get("state") == "cancelled" and frame.get("request_id") in {None, request_id}:
return "deny" if kind == "approval" else (
"The room turn was cancelled before the user answered. Stop this workflow."
)
time.sleep(BOT_HANDOFF_POLL_SECONDS)
return "deny" if kind == "approval" else (
"The user did not answer before the room handoff expired. Stop this workflow."
)
def _terminate_bot_process(process: subprocess.Popen[Any]) -> None:
if process.poll() is not None:
return
try:
if os.name == "posix":
os.killpg(process.pid, signal.SIGTERM)
else: # pragma: no cover - Windows CI exercises terminate fallback
process.terminate()
process.wait(timeout=1.0)
except Exception:
try:
if os.name == "posix":
os.killpg(process.pid, signal.SIGKILL)
else: # pragma: no cover
process.kill()
except Exception:
pass
def _bot_turn_output(result_stdout: str) -> str:
output = str(result_stdout or "").strip()
# Quiet mode may append a stable session-id diagnostic. It is metadata,
# not part of the Bot's reply.
lines = output.splitlines()
if lines and re.fullmatch(r"Session(?: ID)?:\s*\S+", lines[-1], re.I):
lines.pop()
return "\n".join(lines).strip()
def run_profile_turn(
profile: str,
session_id: str,
message: str,
*,
timeout: float = 600.0,
handoff_callback: Optional[RoomHandoffCallback] = None,
progress_callback: Optional[Callable[[Mapping[str, Any]], None]] = None,
cancelled: Optional[Callable[[], bool]] = None,
) -> str:
"""Run one finalized CLI turn using argv + 0600 files (never a shell).
Normal direct messages retain the small ``subprocess.run`` path. Room
members opt into a monitored ``Popen`` path so clarify/approval requests can
cross the hidden child-session boundary while the exact turn remains alive.
"""
profile = _validate_profile(profile)
message = _safe_message_text(message)
home = profile_home(profile)
temp_dir = home / "tmp"
temp_dir.mkdir(parents=True, exist_ok=True)
fd, raw_path = tempfile.mkstemp(prefix="bot-dm-", suffix=".txt", dir=str(temp_dir))
path = Path(raw_path)
handoff_path: Optional[Path] = None
result_path: Optional[Path] = None
event_path: Optional[Path] = None
result_token = ""
event_token = ""
event_offset = 0
try:
os.fchmod(fd, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as handle:
handle.write(message)
handle.flush()
os.fsync(handle.fileno())
command = [
sys.executable,
"-m",
"clio_cli.main",
"--profile",
profile,
"chat",
"--resume",
session_id,
"--quiet",
"--query-file",
str(path),
"--source",
"bot",
]
env = os.environ.copy()
env["CLIO_BOT_CHILD"] = "1"
result_fd, raw_result_path = tempfile.mkstemp(
prefix="bot-result-", suffix=".json", dir=str(temp_dir)
)
os.close(result_fd)
result_path = Path(raw_result_path)
os.chmod(result_path, 0o600)
result_token = uuid.uuid4().hex + uuid.uuid4().hex
env.update(
{
"CLIO_BOT_RESULT_PATH": str(result_path),
"CLIO_BOT_RESULT_TOKEN": result_token,
}
)
if progress_callback is not None:
event_fd, raw_event_path = tempfile.mkstemp(
prefix="bot-events-", suffix=".jsonl", dir=str(temp_dir)
)
os.close(event_fd)
event_path = Path(raw_event_path)
os.chmod(event_path, 0o600)
event_token = uuid.uuid4().hex + uuid.uuid4().hex
env.update(
{
"CLIO_BOT_EVENT_PATH": str(event_path),
"CLIO_BOT_EVENT_TOKEN": event_token,
}
)
if handoff_callback is None:
result = subprocess.run(
command,
cwd=str(Path(__file__).resolve().parent),
env=env,
capture_output=True,
text=True,
timeout=max(1.0, timeout),
check=False,
)
if result.returncode != 0:
detail = (result.stderr or result.stdout or "Bot turn failed").strip()
raise BotModeError(detail[-2000:])
assert result_path is not None
return _read_bot_child_result(result_path, result_token, result.stdout)
handoff_fd, raw_handoff_path = tempfile.mkstemp(
prefix="bot-room-handoff-", suffix=".json", dir=str(temp_dir)
)
os.close(handoff_fd)
handoff_path = Path(raw_handoff_path)
os.chmod(handoff_path, 0o600)
handoff_token = uuid.uuid4().hex + uuid.uuid4().hex
env.update(
{
"CLIO_BOT_HANDOFF_PATH": str(handoff_path),
"CLIO_BOT_HANDOFF_TOKEN": handoff_token,
"CLIO_BOT_HANDOFF_TIMEOUT": str(max(1.0, timeout)),
# Dangerous-command guards must use the managed approval
# callback rather than the non-interactive auto-approve path.
"CLIO_INTERACTIVE": "1",
}
)
started = time.monotonic()
seen_requests: set[str] = set()
def drain_progress_events() -> None:
nonlocal event_offset
if event_path is None or progress_callback is None:
return
events, event_offset = _drain_bot_child_events(
event_path,
event_token,
event_offset,
)
for event in events:
try:
progress_callback(event)
except Exception:
pass
with tempfile.TemporaryFile(mode="w+t", encoding="utf-8") as stdout_file, tempfile.TemporaryFile(
mode="w+t", encoding="utf-8"
) as stderr_file: