Repository navigation
Expand file tree
/
Copy pathsession_inventory.py
More file actions
executable file
·6378 lines (5833 loc) · 239 KB
/
Copy pathsession_inventory.py
File metadata and controls
executable file
·6378 lines (5833 loc) · 239 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
#!/usr/bin/env python3
"""Exact, read-only shpool/Claude/Codex session inventory.
The collector takes one shpool JSON snapshot and one Claude agents JSON
snapshot, then joins provider identities to a bounded native process table.
Linux Codex identities come from an open root rollout owned by the native
Codex CLI or App Server process; Darwin uses that exact process's
``CODEX_THREAD_ID``. It
never selects a conversation by cwd or recency.
"""
from __future__ import annotations
import argparse
import contextlib
import datetime as dt
import hashlib
import fcntl
import json
import os
from pathlib import Path
import re
import shutil # noqa: F401 # re-exported facade symbol
import signal
import stat as statmod
import subprocess
import sys
import tempfile
import time
from typing import Any, Callable, Iterable, Iterator, Mapping, Sequence
_SESSION_KIT_LIB_DIR = os.fspath(Path(__file__).resolve().parent)
if _SESSION_KIT_LIB_DIR not in sys.path:
sys.path.insert(0, _SESSION_KIT_LIB_DIR)
from sessionkit_inventory import collector as _collector # noqa: E402
from sessionkit_inventory import accounts as _accounts # noqa: E402
from sessionkit_inventory import attention as _attention # noqa: E402
from sessionkit_inventory import colors as _colors # noqa: E402
from sessionkit_inventory import common as _common # noqa: E402
from sessionkit_inventory import labels as _labels # noqa: E402
from sessionkit_inventory import idle_state as _idle_state # noqa: E402
from sessionkit_inventory import lifecycle as _lifecycle # noqa: E402
from sessionkit_inventory import model as _model # noqa: E402
from sessionkit_inventory import migration as _migration # noqa: E402
from sessionkit_inventory import names as _names # noqa: E402
from sessionkit_inventory import names_push as _names_push # noqa: E402
from sessionkit_inventory import closed_sessions as _closed_sessions # noqa: E402
from sessionkit_inventory import origins as _origins # noqa: E402
from sessionkit_inventory import transcripts as _transcripts # noqa: E402
from sessionkit_inventory import processes as _processes # noqa: E402
from sessionkit_inventory import recovery as _recovery # noqa: E402
from sessionkit_inventory import recovery_list as _recovery_list # noqa: E402
from sessionkit_inventory import printed_selectors as _printed # noqa: E402
from sessionkit_inventory import render as _render # noqa: E402
from sessionkit_inventory import providers as _providers # noqa: E402
from sessionkit_inventory import providers_claude as _providers_claude # noqa: E402
from sessionkit_inventory import providers_codex as _providers_codex # noqa: E402
from sessionkit_inventory import state_io as _state_io # noqa: E402
from sessionkit_inventory import subagent_sweep as _subagent_sweep # noqa: E402
from sessionkit_inventory import self_name as _self_name # noqa: E402
from sessionkit_inventory import session_model as _session_model_reader # noqa: E402
from sessionkit_inventory import snapshot as _snapshot # noqa: E402
from sessionkit_inventory import terminal as _terminal # noqa: E402
from sessionkit_inventory import validation as _validation # noqa: E402
from sessionkit_inventory.collector import ( # noqa: E402, F401
AVAILABILITY_ORDER,
PROVIDER_ORDER,
)
from sessionkit_inventory.terminal import ( # noqa: E402, F401
TERMINAL_NUMBER_QUARANTINE_SECONDS,
)
from sessionkit_inventory.colors import ( # noqa: E402, F401
CLAUDE_SESSION_COLORS,
CODEX_SESSION_COLORS,
COLOR_RESERVATION_MAX_AGE_SECONDS,
LAUNCH_COLOR_MAX_AGE_SECONDS,
SESSION_COLORS,
first_free_color,
)
from sessionkit_inventory.self_name import ( # noqa: E402, F401
MAX_AUTO_TITLE_TRANSCRIPT_BYTES,
RESUME_CONTINUATION_TEXT,
_TITLE_TRAILING_STOPWORDS,
)
from sessionkit_inventory.names_push import ( # noqa: E402, F401
MAX_CLAUDE_SESSION_RECORDS,
MAX_CODEX_LIVE_RENAME_FRAME,
MAX_CODEX_LIVE_RENAME_SOCKETS,
)
from sessionkit_inventory.render import ( # noqa: E402, F401
DEFAULT_STALL_SECONDS,
_color_enabled,
_display_title,
_display_width,
_format_age,
lookup,
stall_threshold_seconds,
)
from sessionkit_inventory.validation import ( # noqa: E402, F401
_missing_shell_generation_is_quarantinable,
_missing_shell_generation_is_quarantined,
)
from sessionkit_inventory.recovery import ( # noqa: E402, F401
_generation_key,
_pending_conflict_fields,
_pending_evidence,
_pending_preferred_entry,
)
from sessionkit_inventory.model import ( # noqa: E402, F401
_agent_identity,
_base_agent,
_empty_recovery,
_shell_title,
recovery_spec,
)
from sessionkit_inventory.providers import _arg_value, _parse_shpool_payload # noqa: E402, F401
from sessionkit_inventory.providers_claude import ( # noqa: E402, F401
MAX_CLAUDE_TITLE_SCAN_BYTES,
_is_native_claude,
)
from sessionkit_inventory.providers_codex import ( # noqa: E402, F401
ROLLOUT_LIFECYCLE_SEARCH_BYTES,
ROLLOUT_TAIL_BYTES,
_codex_state_databases,
_codex_turn_state,
_is_native_codex,
)
from sessionkit_inventory.common import ( # noqa: E402, F401
GENERATED_OPERATIONAL_ID_RE,
LEGACY_OPERATIONAL_ID_RE,
MAX_OPERATIONAL_ID_BYTES,
PROVIDERS,
UUID_RE,
CollectionError,
_load_json_file,
_positive_float,
_positive_int,
_utc_now,
_valid_aliases,
_valid_automatic_title_failures,
_valid_automatic_titles,
automatic_naming_enabled,
clean_text,
default_runner,
display_shpool_id,
natural_name_key,
normalize_automatic_title,
shpool_id_mutation_policy,
valid_uuid,
)
from sessionkit_inventory.state_io import ( # noqa: E402, F401
StateLock,
_atomic_json_bytes,
_launch_fields,
_read_bounded_owner_file,
_read_private_launch_file,
_state_paths,
_terminal_generation_key,
atomic_write_json,
)
from sessionkit_inventory.processes import ( # noqa: E402, F401
DARWIN_PLATFORM,
_children_index,
_DarwinBsdInfo,
_DarwinTimeval,
_darwin_bsd_info,
_darwin_generation,
_darwin_procargs2,
_decode_c_string,
_is_shpool_daemon,
_parse_darwin_procargs2,
_proc_environ,
_proc_stat,
_process_age,
_process_ancestor_chain,
descendants,
)
SCHEMA_VERSION = 1
MAX_PRIVATE_JSON_BYTES = 1024 * 1024
MAX_CODEX_SESSION_INDEX_BYTES = 4 * 1024 * 1024
DEFAULT_MAX_PROC_NODES = 16384
ABSENT_ALIAS_CONFIG_BACKUP = b"session-kit-alias-config-absent-v1\n"
# `lifecycle reopen` answers with the reopened provider's own outcome so the
# managed shell can make the same clean-close / crash-menu decision it makes
# for a first exit. 0 is a clean provider exit and this status is a crashed
# one; every other status is a refusal to reopen anything at all, which is
# why the reopened provider's own code is not passed through directly.
LIFECYCLE_REOPENED_PROVIDER_CRASHED = 76
Runner = Callable[[Sequence[str], float], str]
def _runtime_platform() -> str:
"""Return the real platform, with a test-only override for Linux fixtures."""
return _processes._runtime_platform(
environ=os.environ,
platform_name=sys.platform,
)
def _require_supported_platform() -> str:
return _processes._require_supported_platform(
runtime_platform=_runtime_platform,
)
def _home() -> Path:
return _common._home(environ=os.environ, home_factory=Path.home)
def _xdg_path(env_name: str, fallback: Path) -> Path:
return _common._xdg_path(env_name, fallback, environ=os.environ)
def config_path() -> Path:
return _common.config_path(
environ=os.environ,
home=_home,
xdg_path=_xdg_path,
)
def default_state_dir() -> Path:
return _common.default_state_dir(
environ=os.environ,
home=_home,
xdg_path=_xdg_path,
)
def _scoped_config_path(environ: Mapping[str, str] | None) -> Path | None:
"""Resolve the naming document inside the caller's own environment.
An explicit environment IS the caller's sandbox — the automatic namers
run inside one, and resolving the real home from in there would read (and
write) name ownership outside the sandbox that asked for the work.
"""
if environ is None:
return config_path()
env = dict(environ)
if not (
env.get("SESSION_KIT_CONFIG") or env.get("XDG_CONFIG_HOME") or env.get("HOME")
):
return None
return _common.config_path(
environ=env,
home=lambda: _common._home(environ=env, home_factory=Path.home),
xdg_path=lambda name, fallback: _common._xdg_path(name, fallback, environ=env),
)
def _scoped_state_config(environ: Mapping[str, str] | None) -> dict[str, Any] | None:
"""The state root the caller's own environment locks its naming writes in."""
if environ is None:
return load_config()
env = dict(environ)
if not (
env.get("SESSION_KIT_STATE_DIR") or env.get("XDG_STATE_HOME") or env.get("HOME")
):
return None
return {
"schema_version": SCHEMA_VERSION,
"state_dir": _common.default_state_dir(
environ=env,
home=lambda: _common._home(environ=env, home_factory=Path.home),
xdg_path=lambda name, fallback: _common._xdg_path(
name, fallback, environ=env
),
),
}
def record_pushed_title(
provider: str,
uuid: str,
title: str,
*,
previous_native_title: str | None = None,
previous_native_name_since: Any = None,
previous_native_name_source: str = "",
environ: Mapping[str, str] | None = None,
) -> None:
"""Remember what the kit just wrote into a provider's own store.
Fail-open: naming is advisory, and a thread with no record simply falls
back to its retained automatic title as the last kit-authored value.
"""
path = _scoped_config_path(environ)
config = _scoped_state_config(environ)
if path is None or config is None:
return
try:
_names.record_pushed_title(
config,
provider,
uuid,
title,
previous_native_title=previous_native_title,
previous_native_name_since=previous_native_name_since,
previous_native_name_source=previous_native_name_source,
atomic_write_json=atomic_write_json,
config_path=lambda: path,
private_alias_document=_private_alias_document,
private_alias_parent=_private_alias_parent,
)
except (CollectionError, OSError):
return
def adopt_native_rename(
provider: str,
uuid: str,
native_title: str,
*,
native_name_source: str = "",
native_name_since: Any = None,
environ: Mapping[str, str] | None = None,
) -> str:
"""Take a provider-native rename as the permanent human-owned name."""
path = _scoped_config_path(environ)
config = _scoped_state_config(environ)
if path is None or config is None:
return ""
try:
return _names.adopt_native_rename(
config,
provider,
uuid,
native_title,
native_name_source=native_name_source,
native_name_since=native_name_since,
atomic_write_json=atomic_write_json,
config_path=lambda: path,
private_alias_document=_private_alias_document,
private_alias_parent=_private_alias_parent,
)
except (CollectionError, OSError):
return ""
def name_owner(
provider: str, uuid: str, *, environ: Mapping[str, str] | None = None
) -> str:
"""Say who owns a session's name: human, automatic, or nobody ("").
Fails open: a document that cannot be read owns nothing, because a
naming pass that cannot prove a name is taken is exactly the pass that
should keep looking rather than refuse to work at all.
"""
exact = _common.valid_uuid(uuid)
if provider not in PROVIDERS or not exact:
return ""
path = _scoped_config_path(environ)
if path is None:
return ""
try:
document = _private_alias_document(path, allow_missing=True)
except (CollectionError, OSError):
return ""
return _names._name_owner(document, f"{provider}:{exact}")
def human_named_keys(environ: Mapping[str, str] | None = None) -> frozenset[str]:
"""Every session a person renamed, as provider:uuid keys."""
path = _scoped_config_path(environ)
if path is None:
return frozenset()
try:
document = _private_alias_document(path, allow_missing=True)
except (CollectionError, OSError):
return frozenset()
keys = {
key
for key, record in _common._valid_name_ownership(
document.get("name_ownership")
).items()
if record["owner"] == "human"
}
# Documents written before the ownership record still hold the evidence.
keys.update(
key
for key in _names._valid_aliases(document.get("aliases"))
if _names._name_owner(document, key) == "human"
)
return frozenset(keys)
def claim_automatic_name(
provider: str, uuid: str, *, environ: Mapping[str, str] | None = None
) -> str:
"""Take the one-shot automatic claim on a session's name.
Returns "" when the claim landed, or the reason it did not. Naming is
advisory work that must never break a session, so every failure is
reported rather than raised.
"""
exact = _common.valid_uuid(uuid)
if provider not in PROVIDERS or not exact:
return "invalid automatic name claim request"
path = _scoped_config_path(environ)
config = _scoped_state_config(environ)
if path is None or config is None:
return "caller environment has no home; automatic name not claimed"
try:
return _names.claim_automatic_name(
config,
provider,
exact,
atomic_write_json=atomic_write_json,
config_path=lambda: path,
private_alias_document=_private_alias_document,
private_alias_parent=_private_alias_parent,
)
except (CollectionError, OSError) as exc:
return f"automatic name not claimed: {exc}"
def release_automatic_name_claim(
provider: str, uuid: str, *, environ: Mapping[str, str] | None = None
) -> bool:
"""Release an untouched claim after its first durable write failed."""
exact = _common.valid_uuid(uuid)
if provider not in PROVIDERS or not exact:
return False
path = _scoped_config_path(environ)
config = _scoped_state_config(environ)
if path is None or config is None:
return False
try:
return _names.release_automatic_name_claim(
config,
provider,
exact,
atomic_write_json=atomic_write_json,
config_path=lambda: path,
private_alias_document=_private_alias_document,
private_alias_parent=_private_alias_parent,
)
except (CollectionError, OSError):
return False
def default_journal_dir() -> Path:
return _common.default_journal_dir(
environ=os.environ,
home=_home,
xdg_path=_xdg_path,
)
def default_journal_recovery_dir() -> Path:
return _common.default_journal_recovery_dir(
environ=os.environ,
home=_home,
xdg_path=_xdg_path,
)
def default_start_dir() -> Path:
return _common.default_start_dir(
environ=os.environ,
home=_home,
xdg_path=_xdg_path,
)
def load_config() -> dict[str, Any]:
"""Load and validate configuration, with safe defaults."""
config = _common.load_config(
config_path=config_path,
load_json_file=_load_json_file,
default_state_dir=default_state_dir,
positive_float=_positive_float,
positive_int=_positive_int,
valid_aliases=_valid_aliases,
valid_automatic_titles=_valid_automatic_titles,
valid_automatic_title_failures=_valid_automatic_title_failures,
schema_version=SCHEMA_VERSION,
default_max_proc_nodes=DEFAULT_MAX_PROC_NODES,
)
# Session colors ride the same document; the pinned kernel contract
# predates them, so they are validated here at the facade layer.
path = config_path()
raw: Any = {}
if path.is_file():
try:
raw = _load_json_file(path)
except (OSError, ValueError):
raw = {}
config["colors"] = _valid_colors(
raw.get("colors") if isinstance(raw, Mapping) else None
)
# So does the record of what the kit last pushed into each provider's own
# store — the collector needs it to tell a native /rename from its own echo.
config["pushed_titles"] = _common._valid_pushed_titles(
raw.get("pushed_titles") if isinstance(raw, Mapping) else None
)
config["pending_native_titles"] = _common._valid_pending_native_titles(
raw.get("pending_native_titles") if isinstance(raw, Mapping) else None
)
config["name_ownership"] = _common._valid_name_ownership(
raw.get("name_ownership") if isinstance(raw, Mapping) else None
)
return config
def _command_from_env(env_name: str, default: str) -> list[str]:
return _common._command_from_env(env_name, default, environ=os.environ)
def _command_json(
*,
fixture_env: str,
command_env: str,
default_command: Sequence[str],
runner: Runner,
timeout: float,
) -> Any:
return _common._command_json(
fixture_env=fixture_env,
command_env=command_env,
default_command=default_command,
runner=runner,
timeout=timeout,
environ=os.environ,
load_json_file=_load_json_file,
command_from_env=_command_from_env,
)
def _parse_claude_payload(payload: Any) -> list[dict[str, Any]]:
"""Read the poll rows, corrected by whatever the Notification hook recorded.
The hook records are read once per snapshot, for exactly the sessions the
poll returned: a session Claude does not list is not a session the picker
can act on, so a record without a live row is nobody's evidence.
"""
source = _attention.attention_source(os.environ)
records: dict[str, dict[str, Any]] = {}
if source != "poll" and isinstance(payload, list):
state_dir = _attention.default_state_dir(os.environ, Path.home())
records = _attention.read_all(
state_dir,
[item.get("sessionId") for item in payload if isinstance(item, Mapping)],
)
return _providers_claude._parse_claude_payload(
payload,
palette=CLAUDE_SESSION_COLORS,
attention_records=records,
attention_source=source,
)
def read_claude_transcript_signals(
uuid: str, home: Path | None = None
) -> dict[str, str]:
"""Return Claude's persisted per-conversation title and color evidence."""
return _providers_claude.read_claude_transcript_signals(
uuid,
home,
environ=os.environ,
home_factory=Path.home,
palette=CLAUDE_SESSION_COLORS,
)
def read_claude_ai_title(uuid: str, home: Path | None = None) -> str:
"""Compatibility wrapper: the auto-title half of the transcript signals."""
return _providers_claude.read_claude_ai_title(
uuid,
home,
transcript_signals=read_claude_transcript_signals,
)
def _enrich_claude_payload(payload: Any) -> Any:
"""Attach per-session nameSource and ai-title evidence for the collector."""
return _providers_claude._enrich_claude_payload(
payload,
environ=os.environ,
home_factory=Path.home,
palette=CLAUDE_SESSION_COLORS,
transcript_signals=read_claude_transcript_signals,
)
def scan_process_table(proc_root: Path, max_nodes: int) -> dict[int, dict[str, Any]]:
"""Read one bounded process-table view from proc_root."""
def inventory_environ(path: Path) -> dict[str, str]:
values = _proc_environ(path)
return {
key: values[key]
for key in (
"SHPOOL_SESSION_NAME",
"SESSION_KIT_REQUESTED_MODEL",
"SESSION_KIT_LAUNCH_IDEMPOTENCY_KEY",
"CLAUDE_CONFIG_DIR",
"CODEX_HOME",
"SESSION_KIT_ACCOUNT_ALIAS",
"SESSION_KIT_ACCOUNT_CAPABLE",
)
if key in values
}
table = _processes.scan_process_table(
proc_root,
max_nodes,
proc_stat=_proc_stat,
proc_environ=inventory_environ,
)
for pid, row in table.items():
try:
values = inventory_environ(proc_root / str(pid) / "environ")
except OSError:
continue
row["requested_model"] = values.get("SESSION_KIT_REQUESTED_MODEL", "")
row["launch_idempotency_key"] = values.get(
"SESSION_KIT_LAUNCH_IDEMPOTENCY_KEY", ""
)
return table
def scan_darwin_process_table(
max_nodes: int,
*,
pids: Sequence[int] | None = None,
bsd_reader: Callable[[int], _DarwinBsdInfo] | None = None,
args_reader: Callable[[int], bytes] | None = None,
) -> dict[int, dict[str, Any]]:
"""Read one bounded Darwin process view using libproc and KERN_PROCARGS2."""
return _processes.scan_darwin_process_table(
max_nodes,
pids=pids,
bsd_reader=bsd_reader,
args_reader=args_reader,
darwin_libraries=_darwin_libraries,
darwin_bsd_info=_darwin_bsd_info,
darwin_procargs2=_darwin_procargs2,
darwin_generation=_darwin_generation,
parse_darwin_procargs2=_parse_darwin_procargs2,
decode_c_string=_decode_c_string,
)
def _darwin_libraries() -> tuple[Any, Any]:
return _processes._darwin_libraries(runtime_platform=_runtime_platform)
def platform_process_table(
proc_root: Path, max_nodes: int
) -> dict[int, dict[str, Any]]:
return _processes.platform_process_table(
proc_root,
max_nodes,
require_supported_platform=_require_supported_platform,
darwin_process_table=scan_darwin_process_table,
linux_process_table=scan_process_table,
)
def shpool_roots(
session_names: Iterable[str], process_table: Mapping[int, Mapping[str, Any]]
) -> tuple[dict[str, int], dict[str, list[str]]]:
"""Map a shpool name only through a unique daemon direct child."""
return _processes.shpool_roots(
session_names,
process_table,
is_shpool_daemon=_is_shpool_daemon,
)
def daemon_generation(
process_table: Mapping[int, Mapping[str, Any]],
) -> dict[str, int] | None:
return _processes.daemon_generation(
process_table,
is_shpool_daemon=_is_shpool_daemon,
)
def _payload_daemon_identity(
process_table: Mapping[int, Mapping[str, Any]],
) -> dict[str, int] | None:
"""Exact holder generation for binding one shpool list payload."""
# Linux exposes the authoritative listener inode and each candidate's fd
# tree. Darwin's bounded native scanner has no equivalent socket-owner
# primitive here, so its safe ordinary case is one definite daemon with
# the same generation on all three observations; multiple or unreadable-
# argv candidates still refuse in _kit_daemons.
require_holder = _require_supported_platform().startswith("linux")
return _processes.daemon_generation(
process_table,
is_shpool_daemon=_is_shpool_daemon,
require_socket_holder=require_holder,
)
def claude_subagents(
root_uuid: str, process_table: Mapping[int, Mapping[str, Any]]
) -> list[dict[str, Any]]:
return _providers_claude.claude_subagents(
root_uuid,
process_table,
arg_value=_arg_value,
)
def _is_codex_app_server(process: Mapping[str, Any]) -> bool:
"""Recognize the native Codex process that owns remote TUI threads."""
return _providers_codex._is_codex_app_server(
process,
is_native_codex=_is_native_codex,
)
def codex_refresh_target(
process_table: Mapping[int, Mapping[str, Any]],
shell_pid: int,
shell_generation: int,
provider_pid: int,
provider_generation: int,
) -> tuple[int, int]:
"""Prove the exact Codex process a title refresh may restart."""
return _providers_codex.codex_refresh_target(
process_table,
shell_pid,
shell_generation,
provider_pid,
provider_generation,
is_native_codex=_is_native_codex,
is_codex_app_server=_is_codex_app_server,
children_index=_children_index,
descendants=descendants,
arg_value=_arg_value,
max_proc_nodes=DEFAULT_MAX_PROC_NODES,
)
def _native_claude_uuid(process: Mapping[str, Any]) -> str | None:
return _providers_claude._native_claude_uuid(
process,
is_native_claude=_is_native_claude,
arg_value=_arg_value,
)
def _rollout_turn_state(descriptor: int) -> str:
"""Compatibility facade for the provider-specific structured parser."""
return _providers_codex.rollout_turn_state(descriptor)
def _rollout_meta_fd(descriptor: int) -> dict[str, Any] | None:
"""Parse bounded rollout metadata from an already-open descriptor."""
return _providers_codex._rollout_meta_fd(
descriptor,
rollout_turn_state=_rollout_turn_state,
)
def _expected_proc_identity(
proc_root: Path, pid: int, expected_process: Mapping[str, Any]
) -> tuple[int, int, int] | None:
return _processes._expected_proc_identity(
proc_root,
pid,
expected_process,
proc_stat=_proc_stat,
)
def codex_open_rollouts(
pid: int,
proc_root: Path,
codex_home: Path,
expected_process: Mapping[str, Any],
) -> list[dict[str, Any]]:
"""Read metadata through stable, native Codex-owned proc descriptors."""
return _providers_codex.codex_open_rollouts(
pid,
proc_root,
codex_home,
expected_process,
expected_proc_identity=_expected_proc_identity,
rollout_meta_fd=_rollout_meta_fd,
)
def codex_rollout_by_uuid(
codex_home: Path,
uuid: str,
*,
max_files: int = 10_000,
) -> list[dict[str, Any]]:
"""Read one exact Darwin Codex rollout selected only by its process UUID."""
return _providers_codex.codex_rollout_by_uuid(
codex_home,
uuid,
max_files=max_files,
rollout_meta_fd=_rollout_meta_fd,
)
def codex_rollout_state_by_path(codex_home: Path, rollout_path: object) -> str:
"""Read one child thread's state from an owner-controlled Codex rollout."""
return _providers_codex.codex_rollout_state_by_path(
codex_home,
rollout_path,
rollout_turn_state=_rollout_turn_state,
)
def index_codex_processes(
process_table: Mapping[int, Mapping[str, Any]], proc_root: Path, codex_home: Path
) -> dict[int, list[dict[str, Any]]]:
return _providers_codex.index_codex_processes(
process_table,
proc_root,
codex_home,
runtime_platform=_runtime_platform,
darwin_platform=DARWIN_PLATFORM,
is_native_codex=_is_native_codex,
rollout_by_uuid=codex_rollout_by_uuid,
open_rollouts=codex_open_rollouts,
)
def _root_codex_uuid(
process: Mapping[str, Any], metadata: Sequence[Mapping[str, Any]]
) -> list[str]:
"""Return exact root threads owned by one native Codex process."""
return _providers_codex._root_codex_uuid(
process,
metadata,
is_codex_app_server=_is_codex_app_server,
)
def _codex_home(
environ: Mapping[str, str] | None = None, *, default_home: Path | None = None
) -> Path:
"""Resolve one Codex home consistently for reads and writes."""
return _providers_codex._codex_home(
environ,
default_home=default_home,
process_environ=os.environ,
home=_home,
)
def _codex_paths() -> tuple[Path, Path]:
return _providers_codex._codex_paths(
environ=os.environ,
codex_home=_codex_home,
codex_state_databases=_codex_state_databases,
)
def read_codex_session_index(
path: Path, warning_sink: list[str] | None = None
) -> dict[str, str]:
"""Read exact UUID-bound Codex names from the append-only local index."""
return _providers_codex.read_codex_session_index(
path,
warning_sink,
read_bounded_owner_file=_read_bounded_owner_file,
max_bytes=MAX_CODEX_SESSION_INDEX_BYTES,
)
def read_codex_db(
db_path: Path,
session_index_names: Mapping[str, str] | None = None,
) -> tuple[dict[str, dict[str, Any]], dict[str, list[dict[str, Any]]]]:
"""Read titles and spawn edges from Codex state without creating journal files."""
return _providers_codex.read_codex_db(
db_path,
session_index_names,
session_index_reader=read_codex_session_index,
rollout_state_by_path=codex_rollout_state_by_path,
)
def _provider_title(
provider: str,
uuid: str | None,
native_title: str,
aliases: Mapping[str, str],
cwd: str = "",
started_at_unix_ms: int | None = None,
automatic_titles: Mapping[str, str] | None = None,
*,
provider_title_is_explicit: bool = True,
native_name_source: str = "",
native_name_since: Any = None,
pushed_titles: Mapping[str, str] | None = None,
pending_native_titles: Mapping[str, Mapping[str, Any]] | None = None,
name_ownership: Mapping[str, Mapping[str, str]] | None = None,
) -> str:
return _model._provider_title(
provider,
uuid,
native_title,
aliases,
cwd,
started_at_unix_ms,
automatic_titles,
provider_title_is_explicit=provider_title_is_explicit,
native_name_source=native_name_source,
native_name_since=native_name_since,
provider_title_info=_provider_title_info,
pushed_titles=pushed_titles,
pending_native_titles=pending_native_titles,
name_ownership=name_ownership,
)
def _provider_title_info(
provider: str,
uuid: str | None,
native_title: str,
aliases: Mapping[str, str],
cwd: str = "",
started_at_unix_ms: int | None = None,
automatic_titles: Mapping[str, str] | None = None,
*,
provider_title_is_explicit: bool = True,
native_name_source: str = "",
native_name_since: Any = None,
pushed_titles: Mapping[str, str] | None = None,
pending_native_titles: Mapping[str, Mapping[str, Any]] | None = None,
name_ownership: Mapping[str, Mapping[str, str]] | None = None,
) -> tuple[str, str]:
return _model._provider_title_info(
provider,
uuid,
native_title,
aliases,
cwd,
started_at_unix_ms,
automatic_titles,
provider_title_is_explicit=provider_title_is_explicit,
native_name_source=native_name_source,
native_name_since=native_name_since,
context_title=_context_title,
pushed_titles=pushed_titles,
pending_native_titles=pending_native_titles,
name_ownership=name_ownership,
)
def _context_title(provider: str, cwd: str, started_at_unix_ms: int | None) -> str:
"""Return a deterministic project hint without exposing a full path."""
return _model._context_title(
provider,
cwd,
started_at_unix_ms,
home=_home,
)
def _regular_file_mtime_ms(path: Path) -> int | None:
"""Return an exact regular file's mtime without following a symlink."""
return _collector.regular_file_mtime_ms(path)
def recent_output_times(
shpool_ids: Iterable[str],
*,
journal_dir: Path | None = None,
recovery_dir: Path | None = None,
) -> dict[str, int]:
"""Map operational shpool IDs to their exact active journal mtime."""
return _collector.recent_output_times(
shpool_ids,
journal_dir=journal_dir,
recovery_dir=recovery_dir,
journal_dir_factory=default_journal_dir,
journal_recovery_dir_factory=default_journal_recovery_dir,
regular_file_mtime_ms=_regular_file_mtime_ms,
)
def apply_retained_setup_attributions(
inventory: dict[str, Any],
*,
start_dir: Path | None = None,
boot_id: str | None = None,
) -> dict[str, Any]:
"""Add display-only provider hints from exact retained startup proofs."""
return _collector.apply_retained_setup_attributions(
inventory,
start_dir=start_dir,
boot_id=boot_id,
start_dir_factory=default_start_dir,
boot_id_reader=_boot_id,
launch_fields=_launch_fields,
read_private_launch_file=_read_private_launch_file,