Repository navigation
Expand file tree
/
Copy pathsession_kit_common
More file actions
executable file
·1726 lines (1638 loc) · 65.6 KB
/
Copy pathsession_kit_common
File metadata and controls
executable file
·1726 lines (1638 loc) · 65.6 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 bash
# Shared helpers for session-kit commands. Source this file; do not execute it.
SESSION_KIT_BIN_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
SESSION_KIT_RELEASE_DIR=$(cd -- "$SESSION_KIT_BIN_DIR/.." && pwd -P)
# A release directory is installed read-only, so Python's bytecode cache can
# never be written there: every import attempts to create __pycache__ and is
# denied. Nothing is lost by not asking, since nothing was ever cached, and it
# saves a failed syscall per module per command. This only disables writing, so
# a .pyc precompiled by a future install step is still read.
export PYTHONDONTWRITEBYTECODE=1
SK_STATE_DIR=${SESSION_KIT_STATE_DIR:-${XDG_STATE_HOME:-"$HOME/.local/state"}/session-kit}
SK_JOURNAL_DIR=${SESSION_KIT_JOURNAL_DIR:-${XDG_STATE_HOME:-"$HOME/.local/state"}/shpool-journal}
SK_ARCHIVE_DIR=${SESSION_KIT_ARCHIVE_DIR:-${XDG_STATE_HOME:-"$HOME/.local/state"}/shpool-archive}
SK_RECOVERY_DIR=${SESSION_KIT_JOURNAL_RECOVERY_DIR:-${XDG_STATE_HOME:-"$HOME/.local/state"}/shpool-journal-recovery}
SK_START_DIR=${SESSION_KIT_START_DIR:-${XDG_STATE_HOME:-"$HOME/.local/state"}/shpool-start}
SK_INTEGRATION_MARKER=${SESSION_KIT_INTEGRATION_MARKER:-"$SK_STATE_DIR/integration-ready-v1"}
SK_PROJECTS_FILE=${SESSION_KIT_PROJECTS_FILE:-${XDG_CONFIG_HOME:-"$HOME/.config"}/session-kit/projects.tsv}
SK_CONFIG_FILE=${SESSION_KIT_CONFIG:-${XDG_CONFIG_HOME:-"$HOME/.config"}/session-kit/inventory.json}
SK_SHPOOL=${SESSION_KIT_SHPOOL_CMD:-}
SK_INVENTORY_CORE=${SESSION_KIT_INVENTORY_CORE:-"$SESSION_KIT_RELEASE_DIR/lib/session_inventory.py"}
SK_PROJECTS_CORE=${SESSION_KIT_PROJECTS_CORE:-"$SESSION_KIT_RELEASE_DIR/lib/sessionkit_projects/cli.py"}
SK_ACTION_LOG="$SK_STATE_DIR/action-events.jsonl"
# Internal dynamic-scope proof set only after one exact shell death. Never
# inherit a caller-supplied value that could weaken restore duplicate checks.
SK_RESTORE_IGNORE_STALE_ID=
if [[ -z $SK_SHPOOL ]]; then
SK_SHPOOL=$(command -v shpool 2>/dev/null || true)
fi
if [[ -z $SK_SHPOOL ]]; then
for sk_candidate in "$HOME/.cargo/bin/shpool" /opt/homebrew/bin/shpool /usr/local/bin/shpool; do
if [[ -x $sk_candidate ]]; then
SK_SHPOOL=$sk_candidate
break
fi
done
fi
unset sk_candidate
sk_die() {
printf 'session-kit: %s\n' "$*" >&2
return 1
}
sk_require_shpool() {
[[ -n $SK_SHPOOL && -x $SK_SHPOOL ]] || sk_die "shpool executable unavailable"
}
# Reads a test-only hook variable. Returns 0 and sets SK_TEST_HOOK to its value
# only when the isolated test harness armed it; otherwise returns 1 and leaves
# SK_TEST_HOOK empty.
#
# Every one of these variables replaces evidence the kit would otherwise gather
# from the machine -- the platform, whether a provider process really started.
# Setting an environment variable is not a privilege, so honouring one outside
# the harness would let any process that can reach this shell's environment
# feed session-kit a fabricated answer. The single SESSION_KIT_TESTING gate
# lives here so no caller can forget it, and an ungated attempt is reported
# once rather than silently swallowed.
sk_test_hook() {
local name=$1
SK_TEST_HOOK=${!name:-}
[[ -n $SK_TEST_HOOK ]] || return 1
if [[ ${SESSION_KIT_TESTING:-0} != 1 ]]; then
SK_TEST_HOOK=
if [[ ${SK_TEST_HOOK_NOTED:-} != *"|$name|"* ]]; then
SK_TEST_HOOK_NOTED="${SK_TEST_HOOK_NOTED:-|}$name|"
printf 'session-kit: ignoring %s: reserved for isolated tests\n' "$name" >&2
fi
return 1
fi
return 0
}
sk_platform() {
if sk_test_hook SESSION_KIT_TEST_PLATFORM; then
printf '%s\n' "$SK_TEST_HOOK"
else
command uname -s 2>/dev/null
fi
}
sk_boot_id() {
if [[ -n ${SESSION_KIT_BOOT_ID_FILE:-} ]]; then
command cat -- "$SESSION_KIT_BOOT_ID_FILE"
elif [[ $(sk_platform) == Darwin ]]; then
python3 "$SK_INVENTORY_CORE" platform boot-id
else
command cat -- /proc/sys/kernel/random/boot_id
fi
}
sk_now_unix_ms() {
if [[ $(sk_platform) == Darwin ]]; then
python3 -c 'import time; print(time.time_ns() // 1_000_000)'
else
date +%s%3N
fi
}
# Linux keeps its established flock command. Darwin uses the native flock(2)
# binding through Python, holding the lock on the inherited Bash descriptor so
# a killed command releases it with the descriptor instead of leaving stale
# lock state behind.
#
# The wait is bounded on both. An unbounded acquire meant one holder wedged
# inside the daemon stopped every attach, create and close on the machine for
# as long as it stayed wedged, with no message and no way out but finding the
# process by hand. The bound is generous — an honest create holds this lock
# through an attach and its generation proof — so reaching it means the holder
# is stuck, not merely slow.
SK_LOCK_WAIT_SECONDS=${SESSION_KIT_LOCK_WAIT_SECONDS:-120}
[[ $SK_LOCK_WAIT_SECONDS =~ ^[0-9]+$ && $SK_LOCK_WAIT_SECONDS -ge 1 ]] ||
SK_LOCK_WAIT_SECONDS=120
sk_lock_acquire() {
local fd=$1 path=$2 seconds=${3:-$SK_LOCK_WAIT_SECONDS}
[[ $seconds =~ ^[0-9]+$ && $seconds -ge 1 ]] || seconds=$SK_LOCK_WAIT_SECONDS
if [[ $(sk_platform) != Darwin ]]; then
command -v flock >/dev/null 2>&1 || {
sk_die "flock is required"
return 1
}
flock -x -w "$seconds" "$fd" && return 0
sk_die "another session-kit action has held $(basename -- "$path") for ${seconds}s; nothing changed"
return 1
fi
python3 - "$fd" "$seconds" <<'PY' && return 0
import fcntl
import sys
import time
descriptor, seconds = int(sys.argv[1]), float(sys.argv[2])
deadline = time.monotonic() + seconds
while True:
try:
fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
break
except BlockingIOError:
if time.monotonic() >= deadline:
raise SystemExit(1)
time.sleep(0.1)
PY
sk_die "another session-kit action has held $(basename -- "$path") for ${seconds}s; nothing changed"
return 1
}
sk_lock_release() {
local fd=$1
eval "exec ${fd}>&-"
}
sk_timeout() {
local seconds=$1
shift
# Keep the caller's stdin attached to the child. The former here-doc
# replaced pipeline input with Python source, so the hidden Claude color
# bootstrap never received its /color command.
# This is Python source, so shell expansion is deliberately disabled.
# shellcheck disable=SC2016
python3 -c '
import ctypes
import os
import signal
import subprocess
import sys
import time
seconds = float(sys.argv[1])
if not 0 < seconds <= 3600 or len(sys.argv) < 3:
raise SystemExit(2)
# Opt-in: the child must not outlive this wrapper under ANY death, and one
# Ctrl-C must take it with us. Only callers that start a REAL provider ask for
# this; the picker refresh deliberately does not (see _forward).
tied = os.environ.get("SK_TIMEOUT_TIE_CHILD") == "1"
def _tie_to_parent():
# PR_SET_PDEATHSIG(1): the kernel signals this child the moment its parent
# dies, including a SIGKILL nothing can trap. Without it a wrapper killed
# hard leaves a detached provider running forever -- a four-day-old
# throwaway pair was found alive on the operator box, holding ~250 MB and
# an account profile, with nothing on the machine able to reap it.
try:
ctypes.CDLL("libc.so.6", use_errno=True).prctl(1, int(signal.SIGTERM))
except OSError:
pass
process = subprocess.Popen(
sys.argv[2:],
start_new_session=True,
preexec_fn=_tie_to_parent if tied else None,
)
def _descendants(root):
# `script` puts the provider in its OWN session, so the provider is NOT in
# the group this wrapper started: one killpg reached `script` and left the
# real provider running. Walk the tree instead, deepest last, so a signal
# goes to every process this wrapper is responsible for.
children = {}
for entry in os.listdir("/proc"):
if not entry.isdigit():
continue
try:
with open(f"/proc/{entry}/stat", "rb") as handle:
fields = handle.read().rpartition(b")")[2].split()
parent = int(fields[1])
except (OSError, IndexError, ValueError):
continue
children.setdefault(parent, []).append(int(entry))
found, queue = [], [root]
while queue:
current = queue.pop()
for child in children.get(current, ()):
if child not in found:
found.append(child)
queue.append(child)
return found
def _signal_everything(number, targets):
try:
os.killpg(process.pid, number)
except (ProcessLookupError, PermissionError):
pass
for pid in targets:
try:
os.kill(pid, number)
os.killpg(pid, number)
except (ProcessLookupError, PermissionError):
pass
def _forward(number, _frame):
# The child owns its own process group and session, so nothing that signals
# this wrapper reaches the real work: a terminated collector left a full
# status collection running detached, ~150 MB, until it finished by itself.
# SIGINT is handled ONLY when the caller tied the child to us: bash sets it
# to ignore for background jobs, and taking it over unasked would make one
# Ctrl-C fail the live refresh the picker depends on -- but for a real
# provider, a Ctrl-C the child never receives is exactly how an orphan is
# made.
# Collected BEFORE anything is signalled. `script` dies first and the
# provider is reparented to init within milliseconds, so a tree walked
# after the first signal no longer contains the process that matters --
# which is how the provider survived a wrapper that thought it had killed
# everything.
targets = _descendants(process.pid)
_signal_everything(signal.SIGTERM, targets)
if tied:
# One SIGTERM and an immediate exit is not cleanup: a provider that
# ignores TERM simply outlives the Ctrl-C that was meant to stop it,
# and the caller is already dying, so nothing later gets to try again.
# Same escalation the timeout path uses, with time to flush first --
# a provider SIGKILLed mid-write is what leaves a torn record behind.
time.sleep(1.5)
_signal_everything(signal.SIGKILL, targets)
raise SystemExit(128 + number)
_handled = [signal.SIGTERM, signal.SIGHUP]
if tied:
_handled.append(signal.SIGINT)
for _number in _handled:
if signal.getsignal(_number) is not signal.SIG_IGN:
signal.signal(_number, _forward)
try:
status = process.wait(timeout=seconds)
except subprocess.TimeoutExpired:
# The tree is collected first, for the same reason the signal path does
# it: `script` gives the provider its own session, so signalling only the
# child process group reaches the wrapper around the provider and not the
# provider itself, and once the wrapper dies the provider is no longer
# anywhere a later walk would find it.
_timed_out = _descendants(process.pid)
_signal_everything(signal.SIGTERM, _timed_out)
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
pass
_signal_everything(signal.SIGKILL, _timed_out)
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
pass
raise SystemExit(124)
raise SystemExit(status if status >= 0 else 128 - status)
' "$seconds" "$@"
}
sk_integration_marker_ok() {
local release_id=$1
local marker_value=
local marker_stat=
local marker_size=
if [[ -f $SK_INTEGRATION_MARKER && ! -L $SK_INTEGRATION_MARKER ]]; then
IFS= read -r marker_value < "$SK_INTEGRATION_MARKER" || true
if [[ $(sk_platform) == Darwin ]]; then
marker_stat=$(stat -f '%Lp:%u' "$SK_INTEGRATION_MARKER" 2>/dev/null || true)
marker_size=$(stat -f '%z' "$SK_INTEGRATION_MARKER" 2>/dev/null || true)
else
marker_stat=$(stat -c '%a:%u' "$SK_INTEGRATION_MARKER" 2>/dev/null || true)
marker_size=$(stat -c '%s' "$SK_INTEGRATION_MARKER" 2>/dev/null || true)
fi
fi
local marker_expected="session-kit-integration-v1 $release_id"
[[ $release_id =~ ^[0-9a-f]{40}$ &&
$marker_value == "$marker_expected" &&
$marker_size == $((${#marker_expected} + 1)) &&
$marker_stat == "600:$(id -u)" ]]
}
# A marker that is missing or names a stale release while the managed login
# block still exists is an inconsistent state by definition: enabling login
# writes both and disabling removes both. Healing rewrites only that state and
# can never override a deliberate disable, whose bashrc block is gone too.
sk_integration_self_heal() {
[[ ${SESSION_KIT_NO_SELF_HEAL:-0} != 1 &&
! -e $SK_STATE_DIR/self-heal-off ]] || return 1
local release_id=$1
local bashrc=${SESSION_KIT_BASHRC:-"$HOME/.bashrc"}
[[ $release_id =~ ^[0-9a-f]{40}$ ]] || return 1
[[ -f $bashrc && ! -L $bashrc ]] || return 1
command grep -qF '# >>> session-kit managed integration >>>' "$bashrc" \
2>/dev/null || return 1
[[ ! -L $SK_INTEGRATION_MARKER ]] || return 1
umask 077
mkdir -p "$SK_STATE_DIR" || return 1
printf 'session-kit-integration-v1 %s\n' "$release_id" \
> "$SK_INTEGRATION_MARKER" || return 1
chmod 600 "$SK_INTEGRATION_MARKER" || return 1
sk_log_action marker_self_heal repaired || true
return 0
}
sk_require_integration() {
local release_id=${SESSION_KIT_RELEASE_ID:-${SESSION_KIT_RELEASE_DIR##*/}}
sk_integration_marker_ok "$release_id" && return 0
if sk_integration_self_heal "$release_id" &&
sk_integration_marker_ok "$release_id"; then
return 0
fi
sk_die "new-session launch is disabled until shell integration is validated for this release"
}
sk_prepare_state() {
umask 077
mkdir -p "$SK_STATE_DIR" "$SK_JOURNAL_DIR" "$SK_ARCHIVE_DIR"
chmod 700 "$SK_STATE_DIR" "$SK_JOURNAL_DIR" "$SK_ARCHIVE_DIR" 2>/dev/null || true
}
# Keep a small local record of picker actions without recording anything that
# identifies a conversation or its contents. The only variable fields are two
# source-controlled enums. Every append also removes entries older than seven
# days and caps the file at 1,000 records / 256 KiB.
sk_log_action() {
local action=$1 outcome=$2
[[ $action =~ ^[a-z][a-z_]{0,31}$ &&
$outcome =~ ^[a-z][a-z_]{0,31}$ ]] || return 1
python3 - "$SK_ACTION_LOG" "$action" "$outcome" <<'PY' 2>/dev/null
import fcntl
import json
import os
from pathlib import Path
import re
import stat
import sys
import tempfile
import time
path = Path(sys.argv[1])
action, outcome = sys.argv[2:4]
now_ms = time.time_ns() // 1_000_000
cutoff_ms = now_ms - 7 * 24 * 60 * 60 * 1000
max_records = 1_000
max_bytes = 256 * 1024
enum_pattern = re.compile(r"[a-z][a-z_]{0,31}")
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
os.chmod(path.parent, 0o700)
lock_path = path.with_suffix(path.suffix + ".lock")
lock_fd = os.open(
lock_path,
os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0),
0o600,
)
try:
os.fchmod(lock_fd, 0o600)
fcntl.flock(lock_fd, fcntl.LOCK_EX)
records = []
try:
metadata = path.lstat()
if (
not stat.S_ISREG(metadata.st_mode)
or metadata.st_uid != os.geteuid()
or metadata.st_nlink != 1
or stat.S_IMODE(metadata.st_mode) != 0o600
or metadata.st_size > max_bytes
):
raise OSError("unsafe action log")
payload = path.read_bytes()
except FileNotFoundError:
payload = b""
for raw_line in payload.splitlines():
try:
item = json.loads(raw_line)
except (UnicodeDecodeError, ValueError):
continue
if (
isinstance(item, dict)
and set(item) in (
{"action", "at_unix_ms", "outcome", "schema_version"},
# A record may name the session it is about. An audit line
# that cannot say WHICH session it describes is why a night of
# launches that started nothing took hours to explain.
{"action", "at_unix_ms", "outcome", "schema_version", "session"},
)
and (
"session" not in item
or (
isinstance(item.get("session"), str)
and re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,63}", item["session"])
)
)
and item.get("schema_version") == 1
and isinstance(item.get("at_unix_ms"), int)
and not isinstance(item["at_unix_ms"], bool)
and cutoff_ms <= item["at_unix_ms"] <= now_ms
and isinstance(item.get("action"), str)
and enum_pattern.fullmatch(item["action"])
and isinstance(item.get("outcome"), str)
and enum_pattern.fullmatch(item["outcome"])
):
records.append(item)
records.append(
{
"action": action,
"at_unix_ms": now_ms,
"outcome": outcome,
"schema_version": 1,
}
)
encoded = [
json.dumps(item, sort_keys=True, separators=(",", ":")).encode() + b"\n"
for item in records[-max_records:]
]
kept = []
total = 0
for line in reversed(encoded):
if total + len(line) > max_bytes:
break
kept.append(line)
total += len(line)
output = b"".join(reversed(kept))
descriptor, temporary = tempfile.mkstemp(
prefix=".action-events.", dir=path.parent
)
try:
os.fchmod(descriptor, 0o600)
with os.fdopen(descriptor, "wb") as handle:
descriptor = -1
handle.write(output)
handle.flush()
os.fsync(handle.fileno())
os.replace(temporary, path)
finally:
if descriptor >= 0:
os.close(descriptor)
try:
os.unlink(temporary)
except FileNotFoundError:
pass
finally:
os.close(lock_fd)
PY
}
sk_snapshot_file() {
local destination=$1
"$SESSION_KIT_BIN_DIR/shpool_status" --json > "$destination"
}
sk_strict_snapshot_file() {
local destination=$1
"$SESSION_KIT_BIN_DIR/shpool_status" --strict-json > "$destination"
}
sk_guard_snapshot_file() {
local destination=$1
"$SESSION_KIT_BIN_DIR/shpool_status" --guard-json > "$destination"
}
sk_lookup_file() {
local inventory=$1 selector=$2
python3 - "$inventory" "$selector" <<'PY'
import json, re, sys
path, selector = sys.argv[1:3]
with open(path, encoding="utf-8") as handle:
data = json.load(handle)
rows = data.get("sessions", [])
matches = []
if selector.isdigit():
wanted = int(selector)
has_terminal_numbers = any(
isinstance(row, dict) and row.get("terminal_number") is not None
for row in rows
)
selector_field = "terminal_number" if has_terminal_numbers else "row"
matches = [row for row in rows if row.get(selector_field) == wanted]
else:
matches = [row for row in rows if row.get("shpool_id") == selector]
if len(matches) != 1:
raise SystemExit(2)
row = matches[0]
identity = row.get("identity") or {}
daemon = data.get("daemon_generation") or {}
conversation_provider = row.get("provider") or "unknown"
conversation_uuid = identity.get("uuid") or ""
if conversation_provider not in {"claude", "codex"} or not conversation_uuid:
exited_identity = row.get("exited_identity") or {}
recovery = row.get("recovery") or {}
exited_provider = row.get("exited_provider")
exited_uuid = exited_identity.get("uuid")
if (
row.get("provider") == "shell"
and row.get("agent_status") == "provider exited"
and exited_provider in {"claude", "codex"}
and row.get("display_provider") == exited_provider
and exited_identity.get("confidence") == "historical-exact"
and isinstance(exited_uuid, str)
and recovery.get("available") is True
and recovery.get("provider") == exited_provider
and recovery.get("uuid") == exited_uuid
):
conversation_provider = exited_provider
conversation_uuid = exited_uuid
else:
conversation_provider = ""
conversation_uuid = ""
raw_id = row.get("shpool_id_raw")
if not isinstance(raw_id, str) or raw_id != row.get("shpool_id"):
raise SystemExit(2)
values = [
raw_id,
str(row.get("started_at_unix_ms") or ""),
row.get("shpool_status") or "",
row.get("availability") or "",
row.get("provider") or "unknown",
identity.get("uuid") or "",
row.get("title") or "",
row.get("cwd") or "",
str(identity.get("pid") or ""),
str(identity.get("process_start_ticks") or ""),
str((row.get("shpool_shell") or {}).get("pid") or ""),
str((row.get("shpool_shell") or {}).get("process_start_ticks") or ""),
str(daemon.get("pid") or ""),
str(daemon.get("process_start_ticks") or ""),
"true" if row.get("mutation_allowed") is True else "false",
row.get("mutation_rejection_reason") or "",
conversation_provider,
conversation_uuid,
str(row.get("terminal_number") or ""),
row.get("account_alias") or "",
"true" if row.get("account_switch_capable") is True else "false",
row.get("model") or "",
]
for value in values:
value = re.sub(r"[\t\r\n]+", " ", str(value))
print(value)
PY
}
sk_resolve() {
local inventory=$1 selector=$2
local -a fields=()
while IFS= read -r field; do fields+=("$field"); done < <(sk_lookup_file "$inventory" "$selector") || return 2
[[ ${#fields[@]} -eq 22 ]] || return 2
SK_ID=${fields[0]}
SK_STARTED=${fields[1]}
SK_STATUS=${fields[2]}
SK_AVAILABILITY=${fields[3]}
SK_PROVIDER=${fields[4]}
SK_UUID=${fields[5]}
SK_TITLE=${fields[6]}
SK_CWD=${fields[7]}
SK_PROVIDER_PID=${fields[8]}
SK_PROVIDER_START=${fields[9]}
SK_SHELL_PID=${fields[10]}
SK_SHELL_START=${fields[11]}
SK_DAEMON_PID=${fields[12]}
SK_DAEMON_START=${fields[13]}
SK_MUTATION_ALLOWED=${fields[14]}
SK_MUTATION_REASON=${fields[15]}
SK_CONVERSATION_PROVIDER=${fields[16]}
SK_CONVERSATION_UUID=${fields[17]}
SK_NUMBER=${fields[18]}
SK_ACCOUNT_ALIAS=${fields[19]}
SK_ACCOUNT_CAPABLE=${fields[20]}
SK_MODEL=${fields[21]}
}
sk_require_mutation_target() {
[[ ${SK_MUTATION_ALLOWED:-false} == true ]] || {
sk_die "session ID is display-only and cannot be mutated (${SK_MUTATION_REASON:-unsafe-id})"
return 1
}
}
# Report the exact daemon generation holding the Unix listener used by this
# kit's shpool client. This does not issue a client request of its own, so it
# can bracket the one raw request whose author a caller needs to prove.
sk_observe_shpool_holder() {
python3 "$SK_INVENTORY_CORE" platform shpool-holder-generation 2>/dev/null
}
# True only when the current socket author is the daemon generation carried by
# a guard-live snapshot. PID alone is never enough because it can be reused.
sk_shpool_holder_is() {
local expected_pid=$1 expected_start=$2 observed
observed=$(sk_observe_shpool_holder) || return 1
[[ $observed == "$expected_pid"$'\t'"$expected_start" ]]
}
# Prove the close itself, independently of a client's exit status or a raw
# list losing a name. The exact old shell generation must be gone while the
# bound daemon generation remains unchanged throughout the observation.
sk_exact_shell_gone() {
local daemon_pid=$1 daemon_start=$2 shell_pid=$3 shell_start=$4
python3 "$SK_INVENTORY_CORE" platform exact-shell-gone \
"$daemon_pid" "$daemon_start" "$shell_pid" "$shell_start"
}
# End one exact PID/start-tick generation. Production delivery is pinned by a
# pidfd and re-reads the identity after the fd is open, immediately before
# TERM and (only after a delivered TERM) bounded KILL.
sk_terminate_exact_process() {
local pid=$1 start_ticks=$2 outcome status=0
outcome=$(python3 "$SK_INVENTORY_CORE" platform terminate-exact-process \
"$pid" "$start_ticks" 2>&1) || status=$?
if (( status != 0 )); then
[[ -n $outcome ]] || outcome="exact process terminator unavailable"
printf '%s\n' "$outcome" >&2
return "$status"
fi
printf '%s\n' "$outcome"
}
# The shell is the destructive act. A name is never used to choose what dies;
# the daemon proof remains a postcondition so a stale snapshot cannot turn a
# successful signal into a false close claim.
sk_terminate_exact_shell() {
local daemon_pid=$1 daemon_start=$2 shell_pid=$3 shell_start=$4 outcome
outcome=$(sk_terminate_exact_process "$shell_pid" "$shell_start" 2>&1) || {
# The picker proof can outlive the shell by a few milliseconds. Already
# gone is the desired close state, but only while the exact bound daemon
# generation still brackets that proof.
if sk_exact_shell_gone "$daemon_pid" "$daemon_start" \
"$shell_pid" "$shell_start" >/dev/null 2>&1; then
return 0
fi
printf '%s\n' "$outcome" >&2
return 1
}
sk_exact_shell_gone "$daemon_pid" "$daemon_start" \
"$shell_pid" "$shell_start"
}
# Read one manager entry only while the Unix listener is still owned by the
# exact daemon generation from the guard snapshot. Prints `present` or `gone`;
# a reused name, malformed payload, wrong lifecycle state, or changed author
# refuses.
sk_bound_manager_entry_state() {
local id=$1 started=$2 daemon_pid=$3 daemon_start=$4 payload answer status=0
sk_shpool_holder_is "$daemon_pid" "$daemon_start" || return 1
payload=$(sk_timeout 5 "$SK_SHPOOL" list --json 2>/dev/null) || return 1
sk_shpool_holder_is "$daemon_pid" "$daemon_start" || return 1
answer=$(SK_MANAGER_LIST_JSON=$payload python3 - "$id" "$started" <<'PY'
import json
import os
import sys
session_id, started_text = sys.argv[1:3]
try:
started = int(started_text)
payload = json.loads(os.environ["SK_MANAGER_LIST_JSON"])
except (KeyError, ValueError, json.JSONDecodeError):
raise SystemExit(2)
rows = payload.get("sessions") if isinstance(payload, dict) else payload
if not isinstance(rows, list) or not all(isinstance(row, dict) for row in rows):
raise SystemExit(2)
matches = [row for row in rows if row.get("name") == session_id]
if not matches:
print("gone")
raise SystemExit(0)
if len(matches) != 1:
raise SystemExit(2)
row = matches[0]
if (
row.get("started_at_unix_ms") != started
or str(row.get("status", "")).casefold() not in {"disconnected", "attached"}
):
raise SystemExit(2)
print("present")
PY
) || status=$?
(( status == 0 )) || return 1
printf '%s\n' "$answer"
}
# Stock shpool 0.11 aborts `kill` bookkeeping when the child PID is already
# gone. Reattaching is its supported stale-entry recovery path: select_shell
# replaces the exited generation, and /bin/true exits under the attach handler
# so that handler removes the table entry normally. The reusable name is used
# only after the old instance timestamp, disconnected state, dead shell, and
# exact daemon author have all been proved under the kit's creation lock.
sk_finalize_dead_shpool_entry() {
local id=$1 daemon_pid=$2 daemon_start=$3 started=$4 state attach_status=0
state=$(sk_bound_manager_entry_state \
"$id" "$started" "$daemon_pid" "$daemon_start") || {
printf 'session-kit: ERROR: cannot prove manager entry %s is the exact dead instance; it was not removed\n' \
"$id" >&2
return 1
}
[[ $state == present ]] || return 0
sk_shpool_holder_is "$daemon_pid" "$daemon_start" || {
printf 'session-kit: ERROR: manager changed before dead entry %s could be finalized; it was not removed\n' \
"$id" >&2
return 1
}
sk_timeout 10 "$SK_SHPOOL" attach --cmd /bin/true --dir / "$id" \
</dev/null >/dev/null 2>&1 || attach_status=$?
sk_shpool_holder_is "$daemon_pid" "$daemon_start" || {
printf 'session-kit: ERROR: manager changed while finalizing dead entry %s; removal is unproved\n' \
"$id" >&2
return 1
}
# The attach client in stock 0.11 can report 1 even after the shell's exit
# landed. The table postcondition, not that unreliable status, is truth.
local attempt
for attempt in 1 2 3 4 5; do
state=$(sk_bound_manager_entry_state \
"$id" "$started" "$daemon_pid" "$daemon_start") || break
[[ $state == gone ]] && return 0
sleep 0.1
done
printf 'session-kit: ERROR: manager entry %s remains after dead-shell finalization (attach status %s)\n' \
"$id" "$attach_status" >&2
return 1
}
sk_cleanup_dead_shpool_entry() {
local id=$1 daemon_pid=$2 daemon_start=$3 shell_pid=$4 shell_start=$5
local started=${6:-}
if ! sk_exact_shell_gone "$daemon_pid" "$daemon_start" \
"$shell_pid" "$shell_start" >/dev/null 2>&1; then
printf 'session-kit: ERROR: manager entry %s was not finalized because exact shell death is unproved\n' \
"$id" >&2
return 1
fi
if [[ ! $started =~ ^[0-9]+$ || $started -le 0 ]]; then
printf 'session-kit: ERROR: manager entry %s was not finalized because its exact start time is unavailable\n' \
"$id" >&2
return 1
fi
sk_finalize_dead_shpool_entry "$id" "$daemon_pid" "$daemon_start" "$started"
}
# True only when the running process is the exact one recorded earlier. The
# start ticks make a recycled PID impossible to mistake for the original.
sk_proc_is_exact() {
local pid=$1 start_ticks=$2 stat tail
local -a fields=()
[[ $pid =~ ^[0-9]+$ && $start_ticks =~ ^[0-9]+$ ]] || return 1
(( pid > 0 && start_ticks > 0 )) || return 1
if [[ $(sk_platform) == Darwin ]]; then
local current
current=$(python3 "$SK_INVENTORY_CORE" platform process-info "$pid" 2>/dev/null) || return 1
[[ ${current#*$'\t'} == "$start_ticks" ]]
return
fi
[[ -r /proc/$pid/stat ]] || return 1
stat=$(<"/proc/$pid/stat") || return 1
tail=${stat##*) }
read -r -a fields <<<"$tail"
[[ ${#fields[@]} -ge 20 ]] || return 1
[[ ${fields[19]} == "$start_ticks" ]]
}
# True when a provider process of the expected kind is running underneath the
# exact proven shell of this session.
#
# This exists because a brand-new Codex session cannot be identified from the
# inventory. Codex identity is derived from an open rollout file, and Codex does
# not write one until the human sends a first message -- so a new Codex session
# reports provider "unknown" until it is used. `sp new codex` used to wait for
# that identity, time out, and abandon a perfectly good session without ever
# attaching the human to it. Claude was unaffected because `claude agents
# --json` lists a new session immediately.
#
# The process tree is the correct evidence for "did the provider start": it is
# exactly what the launch record asked the shell to do.
sk_provider_process_present() {
local shell_pid=$1 shell_start=$2 provider=$3
if sk_test_hook SESSION_KIT_PROVIDER_PRESENCE_OVERRIDE; then
# Test and diagnostic hook only; unset in normal operation. Checked before
# anything reads /proc, because a fixture's shell PIDs are synthetic. This
# answer is the whole proof that a launch succeeded, so outside the harness
# sk_test_hook refuses it and the real process tree decides.
[[ $SK_TEST_HOOK == present ]]
return
fi
sk_proc_is_exact "$shell_pid" "$shell_start" || return 1
if [[ $(sk_platform) == Darwin ]]; then
python3 "$SK_INVENTORY_CORE" platform provider-present \
"$shell_pid" "$shell_start" "$provider" >/dev/null
return
fi
python3 - "$shell_pid" "$provider" <<'PY'
import os
import re
import sys
wanted_pid, provider = int(sys.argv[1]), sys.argv[2]
patterns = {
"codex": re.compile(r"(^|/)codex($|\s|\0)"),
"claude": re.compile(r"(^|/)claude($|\s|\0)"),
}
pattern = patterns.get(provider)
if pattern is None:
raise SystemExit(1)
parents: dict[int, int] = {}
commands: dict[int, str] = {}
for entry in os.listdir("/proc"):
if not entry.isdigit():
continue
pid = int(entry)
try:
with open(f"/proc/{pid}/stat", encoding="utf-8", errors="replace") as handle:
tail = handle.read().rsplit(") ", 1)[-1].split()
parents[pid] = int(tail[1])
with open(f"/proc/{pid}/cmdline", "rb") as handle:
commands[pid] = handle.read(4096).decode("utf-8", "replace")
except (OSError, IndexError, ValueError):
continue
for pid, command in commands.items():
if not pattern.search(command):
continue
# Bounded walk to the session shell; a provider is a close descendant.
walker, depth = pid, 0
while walker > 1 and depth < 8:
if walker == wanted_pid:
raise SystemExit(0)
walker = parents.get(walker, 0)
depth += 1
raise SystemExit(1)
PY
}
# A delegated session was given its own copy of the code; closing it gives the
# copy back. Only a copy the kit cut for that session is a candidate, and the
# core refuses one with uncommitted or unmerged work, one somebody is still
# working in, and anything outside the kit's own worktree root -- it says which
# and keeps the directory. The close already happened, so nothing here can fail
# it: the worst case is a line saying the copy was kept.
sk_release_worktree() {
local id=$1 verdict= status=0
[[ -n $id ]] || return 0
verdict=$(python3 "$SK_INVENTORY_CORE" worktree release --shpool-id "$id" \
2>/dev/null) || status=$?
if (( status != 0 )); then
# The copy is still on disk -- nothing removes one except this verb -- so
# the only cost is a directory. Saying nothing is the part that is not
# free: the close would print exactly what it prints when there was no
# copy at all, and the operator would read "handled".
printf 'session-kit: could not check the working copy for session %s, so it was left where it is. Run sp worktree list to see it.\n' \
"$id"
return 0
fi
[[ -n $verdict ]] || return 0
printf '%s' "$verdict"
return 0
}
# Ending the session's own shell can leave a provider wedged on a terminal
# write alive and holding the old pty. Only processes
# whose PID *and* start ticks still match the recorded generation are signalled.
sk_reap_session_leftovers() {
local pid start_ticks
local -a pairs=("$@")
local index
for (( index = 0; index + 1 < ${#pairs[@]}; index += 2 )); do
pid=${pairs[index]}
start_ticks=${pairs[index + 1]}
[[ $pid =~ ^[0-9]+$ && $start_ticks =~ ^[0-9]+$ ]] || continue
(( pid > 0 && start_ticks > 0 )) || continue
sk_terminate_exact_process "$pid" "$start_ticks" >/dev/null 2>&1 || true
done
return 0
}
sk_snapshot_matches_exact() {
local inventory=$1 expected_id=$2 expected_started=$3 expected_provider=$4
local expected_uuid=$5 expected_shell_pid=$6 expected_shell_start=$7
local expected_provider_pid=$8 expected_provider_start=$9
local expected_daemon_pid=${10} expected_daemon_start=${11}
local expected_conversation_provider=${12:-}
local expected_conversation_uuid=${13:-}
local result=0
if ! sk_resolve "$inventory" "$expected_id"; then
result=1
elif [[ $SK_ID != "$expected_id" || $SK_STARTED != "$expected_started" ]]; then
result=1
elif [[ $SK_PROVIDER != "$expected_provider" || $SK_UUID != "$expected_uuid" ]]; then
result=1
elif [[ $SK_SHELL_PID != "$expected_shell_pid" || $SK_SHELL_START != "$expected_shell_start" ]]; then
result=1
elif [[ $SK_PROVIDER_PID != "$expected_provider_pid" || $SK_PROVIDER_START != "$expected_provider_start" ]]; then
result=1
elif [[ $SK_DAEMON_PID != "$expected_daemon_pid" || $SK_DAEMON_START != "$expected_daemon_start" ]]; then
result=1
elif [[ $SK_MUTATION_ALLOWED != true ]]; then
result=1
elif [[ -n $expected_conversation_provider ]] &&
[[ $SK_CONVERSATION_PROVIDER != "$expected_conversation_provider" ||
$SK_CONVERSATION_UUID != "$expected_conversation_uuid" ]]; then
result=1
fi
return "$result"
}
sk_revalidate() {
local fresh result=0
fresh=$(mktemp "$SK_STATE_DIR/revalidate.json.XXXXXX") || return 1
if ! sk_guard_snapshot_file "$fresh" || ! sk_snapshot_matches_exact "$fresh" "$@"; then
result=1
fi
command rm -- "$fresh"
return "$result"
}
sk_load_picker_proof() {
local proof=$1 output
output=$(python3 - "$proof" "$(id -u)" <<'PY'
import json
import os
import re
import stat
import sys
path, expected_uid_raw = sys.argv[1:3]
expected_uid = int(expected_uid_raw)
expected_keys = {
"schema_version",
"proof_type",
"shpool_id",
"started_at_unix_ms",
"provider",
"uuid",
"provider_pid",
"provider_process_start_ticks",
"shell_pid",
"shell_process_start_ticks",
"daemon_pid",
"daemon_process_start_ticks",
}
id_pattern = re.compile(
r"(?:main(?:[1-9][0-9]*)?|s[0-9]{8}-[0-9]{6}-[1-9][0-9]*(?:-[1-9][0-9]*)?)"
)
uuid_pattern = re.compile(
r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
)
def reject_duplicates(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError("duplicate key")
result[key] = value
return result
flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)
try:
descriptor = os.open(path, flags)
except OSError:
raise SystemExit(2)
try:
before = os.fstat(descriptor)
if (
not stat.S_ISREG(before.st_mode)
or before.st_uid != expected_uid
or stat.S_IMODE(before.st_mode) != 0o600
or before.st_nlink != 1
or before.st_size <= 0