pocketshell 0.5.0__tar.gz → 0.5.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. {pocketshell-0.5.0 → pocketshell-0.5.2}/PKG-INFO +2 -1
  2. {pocketshell-0.5.0 → pocketshell-0.5.2}/pyproject.toml +96 -3
  3. pocketshell-0.5.2/src/pocketshell/aplexer.py +215 -0
  4. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/sessions.py +286 -14
  5. pocketshell-0.5.2/tests/test_aplexer_contract.py +647 -0
  6. pocketshell-0.5.2/tests/test_aplexer_resolution.py +391 -0
  7. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_profiles.py +46 -5
  8. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_sessions_attach.py +12 -6
  9. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_sessions_create_routing.py +45 -1
  10. pocketshell-0.5.2/tests/test_sessions_kill.py +360 -0
  11. {pocketshell-0.5.0 → pocketshell-0.5.2}/uv.lock +24 -1
  12. pocketshell-0.5.0/src/pocketshell/aplexer.py +0 -108
  13. {pocketshell-0.5.0 → pocketshell-0.5.2}/.gitignore +0 -0
  14. {pocketshell-0.5.0 → pocketshell-0.5.2}/README.md +0 -0
  15. {pocketshell-0.5.0 → pocketshell-0.5.2}/scheduler/README.md +0 -0
  16. {pocketshell-0.5.0 → pocketshell-0.5.2}/scheduler/pocketshell-usage-capture.service +0 -0
  17. {pocketshell-0.5.0 → pocketshell-0.5.2}/scheduler/pocketshell-usage-capture.timer +0 -0
  18. {pocketshell-0.5.0 → pocketshell-0.5.2}/scripts/sync-readme-exit-codes.py +0 -0
  19. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/__init__.py +0 -0
  20. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/__main__.py +0 -0
  21. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/agent_card_push.py +0 -0
  22. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/agent_log.py +0 -0
  23. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/agents.py +0 -0
  24. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/agents_kind.py +0 -0
  25. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/cards.py +0 -0
  26. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/cgroup_agents.py +0 -0
  27. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/cli.py +0 -0
  28. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/config.py +0 -0
  29. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/daemon.py +0 -0
  30. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/engines.py +0 -0
  31. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/env.py +0 -0
  32. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/github.py +0 -0
  33. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/hooks.py +0 -0
  34. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/jobs.py +0 -0
  35. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/logs.py +0 -0
  36. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/profiles.py +0 -0
  37. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/prune_attachments.py +0 -0
  38. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/push.py +0 -0
  39. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/qr_share.py +0 -0
  40. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/repos.py +0 -0
  41. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/resume.py +0 -0
  42. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/send.py +0 -0
  43. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/serve.py +0 -0
  44. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/session_enum.py +0 -0
  45. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/tree.py +0 -0
  46. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/usage.py +0 -0
  47. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/usage_capture.py +0 -0
  48. {pocketshell-0.5.0 → pocketshell-0.5.2}/src/pocketshell/usage_reset.py +0 -0
  49. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/__init__.py +0 -0
  50. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/conftest.py +0 -0
  51. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/data/quse-0.0.11-usage.json +0 -0
  52. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/data/quse-0.0.13-usage.json +0 -0
  53. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/data/quse-0.0.15-usage.json +0 -0
  54. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/data/quse-0.0.15-usage.ndjson +0 -0
  55. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/data/quse-0.0.15-usage.provenance.txt +0 -0
  56. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/data/quse-0.0.9-usage.json +0 -0
  57. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/data/sshd_anchor/Dockerfile.from-unanchored-base +0 -0
  58. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/fixtures/aplexer/snapshot-reported-state.json +0 -0
  59. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/fixtures/aplexer/snapshot.json +0 -0
  60. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_agent_card_push.py +0 -0
  61. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_agent_log.py +0 -0
  62. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_agents.py +0 -0
  63. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_agents_kind.py +0 -0
  64. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_agents_kind_target.py +0 -0
  65. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_agents_source_target.py +0 -0
  66. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_cards.py +0 -0
  67. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_cards_push_notify.py +0 -0
  68. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_cgroup_agents.py +0 -0
  69. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_cli.py +0 -0
  70. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_daemon.py +0 -0
  71. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_daemon_fallback.py +0 -0
  72. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_engines.py +0 -0
  73. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_env.py +0 -0
  74. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_github.py +0 -0
  75. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_hooks.py +0 -0
  76. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_jobs.py +0 -0
  77. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_logs.py +0 -0
  78. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_prune_attachments.py +0 -0
  79. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_push.py +0 -0
  80. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_qr_share.py +0 -0
  81. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_repos.py +0 -0
  82. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_resume.py +0 -0
  83. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_send.py +0 -0
  84. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_serve.py +0 -0
  85. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_session_enum.py +0 -0
  86. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_session_enum_schema2.py +0 -0
  87. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_sessions.py +0 -0
  88. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_ssh_fixture_penalties.py +0 -0
  89. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_tree.py +0 -0
  90. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_usage.py +0 -0
  91. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_usage_capture.py +0 -0
  92. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_usage_reset.py +0 -0
  93. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_watch_ci.py +0 -0
  94. {pocketshell-0.5.0 → pocketshell-0.5.2}/tests/test_watch_ci_cancelled.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pocketshell
3
- Version: 0.5.0
3
+ Version: 0.5.2
4
4
  Summary: Unified server-side Python utility for the PocketShell Android client.
5
5
  Project-URL: Homepage, https://github.com/alexeygrigorev/pocketshell
6
6
  Project-URL: Issues, https://github.com/alexeygrigorev/pocketshell/issues
@@ -18,6 +18,7 @@ Classifier: Programming Language :: Python :: 3.13
18
18
  Classifier: Topic :: Software Development
19
19
  Classifier: Topic :: System :: Monitoring
20
20
  Requires-Python: >=3.11
21
+ Requires-Dist: aplexer==0.1.3; sys_platform == 'linux'
21
22
  Requires-Dist: click>=8.2.0
22
23
  Requires-Dist: google-auth>=2.0.0
23
24
  Requires-Dist: pyyaml>=6.0
@@ -14,7 +14,7 @@ name = "pocketshell"
14
14
  # scripts/check-pypi-version.sh enforces the stamped value matches the tag;
15
15
  # scripts/check-version-coupling.sh enforces the derivation itself is
16
16
  # single-sourced. See tools/pocketshell/README.md ("Version coupling").
17
- version = "0.5.0"
17
+ version = "0.5.2"
18
18
  description = "Unified server-side Python utility for the PocketShell Android client."
19
19
  readme = "README.md"
20
20
  requires-python = ">=3.11"
@@ -82,6 +82,92 @@ dependencies = [
82
82
  # per-session-server migration so every caller resolves sessions the same
83
83
  # way.
84
84
  "tmuxctl>=0.3.5",
85
+ # aplexer ships WITH the pocketshell CLI (issue #2543). `pocketshell
86
+ # sessions create --backend aplexer` needs BOTH the `a` CLI and its
87
+ # `aplexer` worker binary (aplexer/src/lib.rs::worker_executable resolves
88
+ # the worker as a sibling of current_exe); the published wheel bundles
89
+ # both native binaries and exposes them as the `a` / `aplexer`
90
+ # console-scripts, so `uv tool install pocketshell` delivers a complete,
91
+ # working aplexer with no separate build/copy/PATH step. That closes the
92
+ # reported failure where a hand-installed `~/bin/a` was invisible to the
93
+ # app's NON-INTERACTIVE SSH PATH and half-installed (no sibling worker).
94
+ #
95
+ # Pinned exactly, like `quse`: pocketshell speaks a specific `a --json`
96
+ # contract (`start`/`snapshot`/`list`/`launch-spec`/`engines`/`profiles`),
97
+ # and `pocketshell/aplexer.py` resolves the BUNDLED copy INSTEAD of PATH,
98
+ # so the pinned wheel is the ONLY aplexer this CLI can run. Bumping the
99
+ # pin is a deliberate, reviewed change.
100
+ #
101
+ # 0.1.3 is required for a USER-VISIBLE session-tree defect, not for
102
+ # version hygiene (aplexer#2 / aplexer#3). Through 0.1.2, aplexer's
103
+ # `list_records` treated a session directory containing no `session.json`
104
+ # as a CORRUPT REGISTRY and failed the entire scan:
105
+ #
106
+ # a: load session registry entry <dir>: read <dir>/session.json:
107
+ # No such file or directory (os error 2) exit=1
108
+ #
109
+ # But `start_session` creates that directory 26-43 ms BEFORE it writes the
110
+ # record, on every single `a start`. The window is therefore on the normal
111
+ # create path, and every reader that does not hold the registry lock can
112
+ # land in it — which is every reader PocketShell has. `a watch` died on it
113
+ # (1 run in 60 on an idle box) and `a list` was bricked outright for the
114
+ # duration.
115
+ #
116
+ # That reaches the phone directly. `session_enum.py::_probe_aplexer` and
117
+ # `sessions.py::_aplexer_snapshot` both probe `a --json snapshot` and fall
118
+ # back to `a --json list`; the fallback cannot help, because the failure
119
+ # is in the shared registry scan underneath both. `aplexer.run_json`
120
+ # collapses any failure to None, so while a session was being created the
121
+ # session tree silently lost EVERY aplexer row. Worse, a record-less
122
+ # directory that outlives the window (a killed/crashed `a start`) bricks
123
+ # 0.1.2's registry permanently — including `a start` itself, which runs
124
+ # the same scan under the lock, so `sessions create --backend aplexer`
125
+ # stops working until someone manually `rmdir`s it.
126
+ # tests/test_aplexer_contract.py drives the bundled binary through both
127
+ # production probes with exactly that on-disk shape; verified red on
128
+ # published 0.1.2, green on 0.1.3.
129
+ #
130
+ # 0.1.2 (not 0.1.1) was the previous floor, and the version string alone
131
+ # could not tell you why: aplexer HEAD sat 143 commits past the v0.1.1 tag
132
+ # while STILL self-reporting `a --version` as 0.1.1, so the published
133
+ # 0.1.1 wheel and the build every PocketShell host actually ran were
134
+ # indistinguishable by version. Pinning 0.1.1 under the hard cut would
135
+ # have silently DOWNGRADED every host to a build missing two fixes the
136
+ # real create-agent path needs:
137
+ # * aplexer ee4b957 — profile `executable` override (argv[0]) for Codex
138
+ # variants. Without it, `[profiles.zcodex] engine="codex",
139
+ # executable="zcodex"` resolves argv[0] to `codex`, and `pocketshell
140
+ # sessions create --backend aplexer --engine codex --profile zcodex`
141
+ # dies with "a: command is not executable or was not found in PATH:
142
+ # codex".
143
+ # * aplexer d13ecb2 — preserve the provider environment for plain
144
+ # `shell` launches (0.1.1 stripped 71 provider vars from every shell
145
+ # session).
146
+ # tests/test_aplexer_contract.py pins ALL of these behaviours against the
147
+ # BUNDLED binary, because `a --version` demonstrably cannot: a future pin
148
+ # that regresses to a build without them fails that test loudly instead
149
+ # of shipping a silent downgrade. Re-run it whenever this pin moves.
150
+ #
151
+ # There is no separate release-time guard for the aplexer version itself
152
+ # (scripts/check-pypi-version.sh only couples pocketshell's OWN version to
153
+ # the release tag and says nothing about quse or tmuxctl either), so the
154
+ # exact pin + the committed uv.lock + that contract test are the
155
+ # enforcement.
156
+ #
157
+ # The `sys_platform == 'linux'` marker is load-bearing: aplexer publishes
158
+ # manylinux wheels only (x86_64 + aarch64) and NO sdist, so an unmarked
159
+ # hard dependency would make `pip install pocketshell` unresolvable on
160
+ # macOS/Windows. PocketShell hosts are Linux; a non-Linux host simply gets
161
+ # no bundled aplexer at all, so `sessions create --backend aplexer` there
162
+ # fails loud (there is no PATH fallback — D22) while tmux, the default
163
+ # backend, keeps working.
164
+ #
165
+ # Install-surface note (unchanged in 0.1.3): as of 0.1.2 the wheels moved
166
+ # from manylinux_2_17 to manylinux_2_28, raising the minimum glibc from
167
+ # 2.17 to 2.28. Linux hosts older than that (CentOS 7, Ubuntu 18.04) can
168
+ # no longer install pocketshell at all now that aplexer is a hard
169
+ # dependency. Flagged, not solved here — see docs/aplexer-integration.md.
170
+ "aplexer==0.1.3; sys_platform == 'linux'",
85
171
  ]
86
172
 
87
173
  [project.scripts]
@@ -137,8 +223,15 @@ required-version = "==0.10.11"
137
223
  # a rolling global `exclude-newer` policy that predates deliberately pinned
138
224
  # releases (quse 0.0.15 and tmuxctl 0.3.5); this exact value is also the
139
225
  # `uv.lock` options cutoff and must be used when checking this lock. Moved
140
- # past quse 0.0.15's 2026-08-28T12:09:07Z PyPI upload for issue #2293.
141
- exclude-newer = "2026-08-28T22:00:00Z"
226
+ # past quse 0.0.15's 2026-08-28T12:09:07Z PyPI upload for issue #2293, then
227
+ # past aplexer 0.1.2's 2026-09-05T22:38:08Z PyPI upload (its `aplexer-client`
228
+ # runtime dep landed at 22:38:04Z) for issue #2543. A package uploaded after
229
+ # the cutoff is simply invisible to `uv lock`, which reads like a broken index
230
+ # rather than a stale cutoff, so this value moves in lock-step with every new
231
+ # pin — and the `uv.lock` options cutoff must be moved to match. Now past
232
+ # aplexer 0.1.3's 2026-09-06T00:32:09Z PyPI upload (its `aplexer-client`
233
+ # runtime dep landed at 00:32:04Z) for the session-tree regression fix above.
234
+ exclude-newer = "2026-09-06T01:00:00Z"
142
235
 
143
236
  [tool.pytest.ini_options]
144
237
  testpaths = ["tests"]
@@ -0,0 +1,215 @@
1
+ """Host-local client for the ``a`` binary (aplexer Phase A).
2
+
3
+ PocketShell and aplexer share a machine: the helper invokes ``a --json …``
4
+ and overlays presentation/tmux concerns. Probe failures are silent and
5
+ return ``None`` so every call site can fall back to the native path.
6
+
7
+ Kill switches (any one is enough to skip):
8
+
9
+ - ``POCKETSHELL_APLEXER=0`` — master
10
+ - ``POCKETSHELL_APLEXER_PROFILES=0``
11
+ - ``POCKETSHELL_APLEXER_ENGINES=0``
12
+ - ``POCKETSHELL_APLEXER_LAUNCH=0``
13
+ - ``POCKETSHELL_APLEXER_SESSIONS=0``
14
+
15
+ Binary resolution (issue #2543)
16
+ -------------------------------
17
+
18
+ aplexer ships WITH this CLI: PyPI ``aplexer`` is a pinned, Linux-marked hard
19
+ dependency (``pyproject.toml``), so ``uv tool install pocketshell`` drops the
20
+ ``a`` and ``aplexer`` console-scripts into the SAME ``bin`` directory as the
21
+ interpreter running pocketshell. There is no separate aplexer install step and
22
+ no PATH surgery. Resolution order, highest first:
23
+
24
+ 1. ``APLEXER_BIN`` — the one explicit override (a debug/test knob, not an
25
+ install path).
26
+ 2. The **bundled** copy next to ``sys.executable`` — the pinned wheel, the
27
+ same anchor ``usage.py::_resolve_quse_binary`` uses for the pinned ``quse``.
28
+
29
+ There is no third step: the ``PATH`` lookup is HARD-CUT (D22 — no fallback
30
+ branch; the superseded code is deleted, not conditioned). This mirrors
31
+ ``quse`` exactly. A host-level or locally-built ``a`` on ``PATH`` must NOT
32
+ shadow the pinned copy, and an absent bundled copy is a packaging-integrity
33
+ error that fails loud — not a "please install aplexer" nag. aplexer is a
34
+ dependency of this CLI; it is never installed separately.
35
+
36
+ The original bug this fixes: ``which_a`` used to be a bare
37
+ ``shutil.which("a", path=env["PATH"])``, and the app drives the host CLI over
38
+ a NON-INTERACTIVE SSH command whose PATH is
39
+ ``~/.local/bin:/usr/local/sbin:…`` — a correctly installed ``a`` outside those
40
+ dirs (e.g. ``~/bin/a``) was invisible, and the error said "not installed".
41
+
42
+ ``a`` needs a sibling ``aplexer`` worker binary (``aplexer/src/lib.rs``
43
+ ``worker_executable`` resolves it next to ``current_exe``, else bare
44
+ ``aplexer`` on PATH). The pinned wheel always ships both into the same dir, so
45
+ :class:`AplexerResolution` reports the worker it found next to ``a``.
46
+ """
47
+
48
+ from __future__ import annotations
49
+
50
+ import json
51
+ import os
52
+ import signal
53
+ import subprocess
54
+ import sys
55
+ from dataclasses import dataclass, field
56
+ from pathlib import Path
57
+ from typing import Any, Mapping, Optional
58
+
59
+ JSON_TIMEOUT_S = 2.0
60
+ LAUNCH_TIMEOUT_S = 5.0
61
+ BIN_ENV = "APLEXER_BIN"
62
+ # Snapshot Popen so helper tests that patch ``subprocess.Popen`` (to block
63
+ # the source-recorder child) cannot swallow ``a`` probes.
64
+ _Popen = subprocess.Popen
65
+ _TimeoutExpired = subprocess.TimeoutExpired
66
+ MASTER_KILL = "POCKETSHELL_APLEXER"
67
+ FEATURE_KILLS = {
68
+ "profiles": "POCKETSHELL_APLEXER_PROFILES",
69
+ "engines": "POCKETSHELL_APLEXER_ENGINES",
70
+ "launch": "POCKETSHELL_APLEXER_LAUNCH",
71
+ "sessions": "POCKETSHELL_APLEXER_SESSIONS",
72
+ }
73
+
74
+
75
+ def env_map(env: Optional[Mapping[str, str]] = None) -> dict[str, str]:
76
+ merged = dict(os.environ)
77
+ if env:
78
+ merged.update({str(k): str(v) for k, v in env.items()})
79
+ return merged
80
+
81
+
82
+ def enabled(feature: str, env: Optional[Mapping[str, str]] = None) -> bool:
83
+ source = env_map(env)
84
+ if source.get(MASTER_KILL) == "0":
85
+ return False
86
+ kill = FEATURE_KILLS.get(feature)
87
+ if kill and source.get(kill) == "0":
88
+ return False
89
+ return True
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class AplexerResolution:
94
+ """Outcome of resolving the ``a`` CLI, including what was tried.
95
+
96
+ ``tried`` is human-readable and exists so a failure can NAME the candidate
97
+ paths instead of claiming aplexer "is not installed" (issue #2543).
98
+ """
99
+
100
+ path: Optional[str] = None
101
+ source: Optional[str] = None
102
+ worker: Optional[str] = None
103
+ tried: tuple[str, ...] = field(default_factory=tuple)
104
+
105
+
106
+ def _bundled_bin_dirs() -> list[Path]:
107
+ """Directories that can hold the pinned aplexer console-scripts.
108
+
109
+ Console-scripts live next to the UNRESOLVED ``sys.executable``: in a venv
110
+ (or a ``uv tool`` install) ``bin/python`` is a symlink to the underlying
111
+ interpreter, so ``Path(sys.executable).resolve()`` points at the shared
112
+ interpreter dir where ``a`` is NOT installed. Check the interpreter's own
113
+ ``bin`` dir first and only fall through to the resolved dir for layouts
114
+ where the two coincide. Both candidates are anchored to ``sys.executable``
115
+ — this is NOT a PATH search. Same trap, same handling, as
116
+ ``usage.py::_resolve_quse_binary``.
117
+ """
118
+ exe_dir = Path(sys.executable).parent
119
+ dirs = [exe_dir]
120
+ resolved_dir = Path(sys.executable).resolve().parent
121
+ if resolved_dir != exe_dir:
122
+ dirs.append(resolved_dir)
123
+ return dirs
124
+
125
+
126
+ def _sibling_worker(cli_path: str) -> Optional[str]:
127
+ """The ``aplexer`` worker binary shipped next to ``cli_path``, if any."""
128
+ worker = Path(cli_path).parent / "aplexer"
129
+ return str(worker) if worker.exists() else None
130
+
131
+
132
+ def resolve_a(env: Optional[Mapping[str, str]] = None) -> AplexerResolution:
133
+ """Resolve the ``a`` CLI: ``APLEXER_BIN``, else the BUNDLED copy. No PATH.
134
+
135
+ See the module docstring: ``PATH`` is deliberately not consulted at all,
136
+ so a separately-installed ``a`` can never be load-bearing. Never raises —
137
+ an unresolvable ``a`` comes back as a report whose ``path`` is ``None``
138
+ and whose ``tried`` lists every candidate, for the caller's error message.
139
+ """
140
+ source = env_map(env)
141
+ tried: list[str] = []
142
+
143
+ explicit = source.get(BIN_ENV)
144
+ if explicit:
145
+ return AplexerResolution(
146
+ path=explicit,
147
+ source=BIN_ENV,
148
+ worker=_sibling_worker(explicit),
149
+ tried=(f"{BIN_ENV}={explicit}",),
150
+ )
151
+ tried.append(f"{BIN_ENV} (unset)")
152
+
153
+ for bin_dir in _bundled_bin_dirs():
154
+ candidate = bin_dir / "a"
155
+ if candidate.exists():
156
+ return AplexerResolution(
157
+ path=str(candidate),
158
+ source="bundled",
159
+ worker=_sibling_worker(str(candidate)),
160
+ tried=tuple([*tried, f"{candidate} (bundled, found)"]),
161
+ )
162
+ tried.append(f"{candidate} (bundled, missing)")
163
+
164
+ # No PATH lookup by design (D22 hard cut, issue #2543): resolution ends
165
+ # here. An `a` that exists only on PATH is a SEPARATE install, which is the
166
+ # mode this change removes — it must not be picked up silently.
167
+ return AplexerResolution(tried=tuple(tried))
168
+
169
+
170
+ def which_a(env: Optional[Mapping[str, str]] = None) -> Optional[str]:
171
+ """Path to the ``a`` CLI, or ``None``. Thin wrapper over :func:`resolve_a`."""
172
+ return resolve_a(env).path
173
+
174
+
175
+ def run_json(
176
+ args: list[str],
177
+ *,
178
+ env: Optional[Mapping[str, str]] = None,
179
+ timeout: Optional[float] = None,
180
+ feature: Optional[str] = None,
181
+ ) -> Any | None:
182
+ """Run ``a --json <args>`` and parse stdout. None on skip or any failure."""
183
+ if timeout is None:
184
+ timeout = JSON_TIMEOUT_S
185
+ if feature and not enabled(feature, env):
186
+ return None
187
+ cli = which_a(env)
188
+ if cli is None:
189
+ return None
190
+ try:
191
+ proc = _Popen(
192
+ [cli, "--json", *args],
193
+ stdout=subprocess.PIPE,
194
+ stderr=subprocess.PIPE,
195
+ text=True,
196
+ env=env_map(env),
197
+ start_new_session=True,
198
+ )
199
+ try:
200
+ stdout, _stderr = proc.communicate(timeout=timeout)
201
+ except _TimeoutExpired:
202
+ try:
203
+ os.killpg(proc.pid, signal.SIGKILL)
204
+ except OSError:
205
+ proc.kill()
206
+ proc.communicate()
207
+ return None
208
+ except OSError:
209
+ return None
210
+ if proc.returncode != 0:
211
+ return None
212
+ try:
213
+ return json.loads(stdout)
214
+ except json.JSONDecodeError:
215
+ return None
@@ -810,12 +810,24 @@ def _create_on_aplexer(
810
810
  ``session_enum.aplexer_display_name``) so it round-trips with what
811
811
  `sessions list --json` shows.
812
812
  """
813
- aplexer_path = _aplexer.which_a()
813
+ resolution = _aplexer.resolve_a()
814
+ aplexer_path = resolution.path
814
815
  if aplexer_path is None:
816
+ # #2543: this used to say "is not installed", which was actively
817
+ # misleading — the real cause was a RESOLUTION failure (a correctly
818
+ # installed `a` outside the app's non-interactive SSH PATH). aplexer
819
+ # now ships WITH this CLI as a pinned dependency, so an unresolvable
820
+ # `a` is a packaging-integrity problem, and the message names every
821
+ # candidate that was checked.
815
822
  raise _CreateError(
816
- "pocketshell: `a` (aplexer) is not installed on this host, but "
817
- "the backend routing selected it. Install aplexer or set "
818
- "[backends] in ~/.config/pocketshell/config.toml back to tmux.",
823
+ _aplexer_unresolved_message(
824
+ resolution,
825
+ action=(
826
+ "the backend routing selected it, so `sessions create` "
827
+ "cannot run (or set [backends] in "
828
+ "~/.config/pocketshell/config.toml back to tmux)"
829
+ ),
830
+ ),
819
831
  exit_code=127,
820
832
  )
821
833
  workspace = cwd or os.getcwd()
@@ -1040,15 +1052,37 @@ TMUX_PROBE_TIMEOUT_S = 2.0
1040
1052
  TMUX_SOCKET_SWEEP_BUDGET_S = 5.0
1041
1053
 
1042
1054
 
1043
- def _resolve_aplexer_binary() -> Optional[str]:
1044
- """Locate the ``a`` (aplexer) CLI, honouring ``APLEXER_BIN``.
1055
+ def _resolve_aplexer() -> "_aplexer.AplexerResolution":
1056
+ """Resolve the ``a`` CLI for attach/kill: ``APLEXER_BIN``, else bundled.
1045
1057
 
1046
- Wrapped rather than calling :func:`pocketshell.aplexer.which_a` inline so
1058
+ Wrapped rather than calling :func:`pocketshell.aplexer.resolve_a` inline so
1047
1059
  the attach-time availability check has its own monkeypatch seam: patching
1048
- ``which_a`` itself would also silence the enumeration probe that produced
1049
- the aplexer rows in the first place.
1060
+ ``resolve_a`` itself would also silence the enumeration probe that produced
1061
+ the aplexer rows in the first place. Returns the full report, because the
1062
+ failure message names every candidate it tried (#2543), and the callers
1063
+ exec/run the RESOLVED path — never a bare ``a`` that execvp would look up
1064
+ on PATH.
1050
1065
  """
1051
- return _aplexer.which_a()
1066
+ return _aplexer.resolve_a()
1067
+
1068
+
1069
+ def _aplexer_unresolved_message(
1070
+ resolution: "_aplexer.AplexerResolution", *, action: str
1071
+ ) -> str:
1072
+ """Explain an unresolvable ``a`` by NAMING the candidates (issue #2543).
1073
+
1074
+ The old wording — "`a` (aplexer) is not installed on this host" — was the
1075
+ inverse of the truth in the reported failure: aplexer WAS installed, just
1076
+ not where a bare PATH lookup could see it. aplexer now ships WITH this CLI
1077
+ as a pinned dependency, so an unresolvable `a` is a packaging-integrity
1078
+ problem with a concrete fix, and the message says which paths were checked.
1079
+ """
1080
+ return (
1081
+ "pocketshell: could not resolve the `a` (aplexer) binary; "
1082
+ f"{action}. aplexer ships with the pocketshell CLI, so reinstalling "
1083
+ "normally fixes this (`uv tool install --force pocketshell`); "
1084
+ "otherwise set APLEXER_BIN. Tried: " + "; ".join(resolution.tried)
1085
+ )
1052
1086
 
1053
1087
 
1054
1088
  def _exec(argv: list[str]) -> None:
@@ -1231,15 +1265,21 @@ def sessions_attach(ctx: click.Context, name: str, hide_status: bool) -> None:
1231
1265
 
1232
1266
  row = matches[0]
1233
1267
  if row.manager == _session_enum.MANAGER_APLEXER:
1234
- if _resolve_aplexer_binary() is None:
1268
+ # Resolve ONCE and exec that exact path (#2543). A bare "a" here would
1269
+ # be an execvp PATH lookup — the separate-install mode this CLI no
1270
+ # longer supports, and a way to run a different copy than the one the
1271
+ # availability check just approved.
1272
+ resolution = _resolve_aplexer()
1273
+ if resolution.path is None:
1235
1274
  click.echo(
1236
- "pocketshell: `a` (aplexer) is not installed on this host; "
1237
- f"cannot attach to {row.name!r}.",
1275
+ _aplexer_unresolved_message(
1276
+ resolution, action=f"cannot attach to {row.name!r}"
1277
+ ),
1238
1278
  err=True,
1239
1279
  )
1240
1280
  ctx.exit(ATTACH_EXIT_NO_BINARY)
1241
1281
  return
1242
- _exec(["a", "attach", str(row.aplexer_id)])
1282
+ _exec([resolution.path, "attach", str(row.aplexer_id)])
1243
1283
  return
1244
1284
 
1245
1285
  if shutil.which("tmux") is None:
@@ -1294,3 +1334,235 @@ def sessions_attach(ctx: click.Context, name: str, hide_status: bool) -> None:
1294
1334
  err=True,
1295
1335
  )
1296
1336
  _exec(["tmux", "-S", socket_path, "attach-session", "-t", target])
1337
+
1338
+
1339
+ # ---------------------------------------------------------------------------
1340
+ # `sessions kill` — same name resolution as attach, then kill that one session
1341
+ # ---------------------------------------------------------------------------
1342
+ #
1343
+ # Desktop kills with `tmux -S <socket> kill-session -t '=NAME'`. The `=` is
1344
+ # tmux's exact-match form: without it, `-t api` will happily destroy
1345
+ # `api-staging` once `api` itself is gone. `tmux kill-server` is never used
1346
+ # — that would wipe every session on the socket, including ones the user did
1347
+ # not name.
1348
+ #
1349
+ # Exit codes match attach so a client can branch the same way:
1350
+ # 3 no session by that name
1351
+ # 4 ambiguous — several sessions match
1352
+ # 5 matched a tmux session but its server socket could not be located
1353
+ # 127 the `tmux` / `a` binary needed to kill is not installed
1354
+
1355
+ KILL_SCHEMA_VERSION = CREATE_SCHEMA_VERSION
1356
+
1357
+
1358
+ def _emit_kill_failure(
1359
+ ctx: click.Context, message: str, *, exit_code: int, as_json: bool
1360
+ ) -> None:
1361
+ """Report a failed kill: JSON error envelope on stdout, else stderr."""
1362
+ if as_json:
1363
+ click.echo(
1364
+ json.dumps({"schema": KILL_SCHEMA_VERSION, "error": message}, indent=2)
1365
+ )
1366
+ else:
1367
+ click.echo(message, err=True)
1368
+ ctx.exit(exit_code if exit_code else 1)
1369
+
1370
+
1371
+ def _run_session_kill(argv: list[str]) -> subprocess.CompletedProcess[str]:
1372
+ """Run one kill argv (tmux kill-session or ``a kill``). Never kill-server."""
1373
+ return subprocess.run(
1374
+ argv,
1375
+ check=False,
1376
+ capture_output=True,
1377
+ text=True,
1378
+ timeout=_TMUX_TIMEOUT_S,
1379
+ )
1380
+
1381
+
1382
+ @sessions_group.command(
1383
+ "kill",
1384
+ context_settings={"help_option_names": ["-h", "--help"]},
1385
+ )
1386
+ @click.argument("name")
1387
+ @click.option(
1388
+ "--json",
1389
+ "as_json",
1390
+ is_flag=True,
1391
+ default=False,
1392
+ help=(
1393
+ "Emit the schema-2 kill envelope "
1394
+ '{"schema","name","manager","id","killed"} on stdout.'
1395
+ ),
1396
+ )
1397
+ @click.pass_context
1398
+ def sessions_kill(ctx: click.Context, name: str, as_json: bool) -> None:
1399
+ """Kill a live session by exact name.
1400
+
1401
+ NAME is a tmux session name, an aplexer display name
1402
+ (`<workspace>:<tag>`), or an aplexer id prefix of at least 8 characters.
1403
+ Resolution uses the same enumeration and matching rules as
1404
+ `sessions attach`, so any name that listing shows can be killed — and a
1405
+ prefix cannot silently destroy a neighbour.
1406
+
1407
+ tmux sessions are killed with `tmux -S <socket> kill-session -t '=NAME'`
1408
+ on the socket `_find_tmux_socket` located. aplexer sessions are killed
1409
+ with `a kill <id>`. This never runs `tmux kill-server`.
1410
+
1411
+ Exit 3 = no such session, 4 = ambiguous, 5 = tmux session found but its
1412
+ socket could not be located, 127 = the kill binary is missing.
1413
+ """
1414
+ rows, _errors = _attach_live_rows()
1415
+ matches = _match_attach_target(rows, name)
1416
+ if not matches:
1417
+ _emit_kill_failure(
1418
+ ctx,
1419
+ f"no session named {name!r}",
1420
+ exit_code=ATTACH_EXIT_NOT_FOUND,
1421
+ as_json=as_json,
1422
+ )
1423
+ return
1424
+ if len(matches) > 1:
1425
+ if as_json:
1426
+ _emit_kill_failure(
1427
+ ctx,
1428
+ f"ambiguous session name {name!r}",
1429
+ exit_code=ATTACH_EXIT_AMBIGUOUS,
1430
+ as_json=True,
1431
+ )
1432
+ return
1433
+ click.echo(f"ambiguous session name {name!r}; candidates:", err=True)
1434
+ for row in matches:
1435
+ click.echo(_describe_candidate(row), err=True)
1436
+ ctx.exit(ATTACH_EXIT_AMBIGUOUS)
1437
+ return
1438
+
1439
+ row = matches[0]
1440
+ if row.manager == _session_enum.MANAGER_APLEXER:
1441
+ resolution = _resolve_aplexer()
1442
+ if resolution.path is None:
1443
+ _emit_kill_failure(
1444
+ ctx,
1445
+ _aplexer_unresolved_message(
1446
+ resolution, action=f"cannot kill {row.name!r}"
1447
+ ),
1448
+ exit_code=ATTACH_EXIT_NO_BINARY,
1449
+ as_json=as_json,
1450
+ )
1451
+ return
1452
+ aplexer_id = row.aplexer_id
1453
+ if not aplexer_id:
1454
+ _emit_kill_failure(
1455
+ ctx,
1456
+ f"pocketshell: aplexer session {row.name!r} has no id; cannot kill it.",
1457
+ exit_code=ATTACH_EXIT_NOT_FOUND,
1458
+ as_json=as_json,
1459
+ )
1460
+ return
1461
+ # The resolved path, not a bare "a" on PATH (#2543).
1462
+ argv = [resolution.path, "kill", str(aplexer_id)]
1463
+ try:
1464
+ completed = _run_session_kill(argv)
1465
+ except subprocess.TimeoutExpired:
1466
+ _emit_kill_failure(
1467
+ ctx,
1468
+ f"pocketshell: `a kill {aplexer_id}` timed out.",
1469
+ exit_code=1,
1470
+ as_json=as_json,
1471
+ )
1472
+ return
1473
+ except OSError as exc:
1474
+ _emit_kill_failure(
1475
+ ctx,
1476
+ f"pocketshell: `{resolution.path} kill` could not run; "
1477
+ f"cannot kill {row.name!r}: {exc}",
1478
+ exit_code=ATTACH_EXIT_NO_BINARY,
1479
+ as_json=as_json,
1480
+ )
1481
+ return
1482
+ if completed.returncode != 0:
1483
+ detail = str(completed.stderr or "").strip() or f"exit {completed.returncode}"
1484
+ _emit_kill_failure(
1485
+ ctx,
1486
+ f"pocketshell: could not kill {row.name!r}: {detail}",
1487
+ exit_code=completed.returncode,
1488
+ as_json=as_json,
1489
+ )
1490
+ return
1491
+ if as_json:
1492
+ click.echo(
1493
+ json.dumps(
1494
+ {
1495
+ "schema": KILL_SCHEMA_VERSION,
1496
+ "name": row.name,
1497
+ "manager": row.manager,
1498
+ "id": aplexer_id,
1499
+ "killed": True,
1500
+ },
1501
+ indent=2,
1502
+ )
1503
+ )
1504
+ return
1505
+
1506
+ if shutil.which("tmux") is None:
1507
+ _emit_kill_failure(
1508
+ ctx,
1509
+ "pocketshell: `tmux` is not installed on this host; "
1510
+ f"cannot kill {row.name!r}.",
1511
+ exit_code=ATTACH_EXIT_NO_BINARY,
1512
+ as_json=as_json,
1513
+ )
1514
+ return
1515
+ socket_path = _find_tmux_socket(row.name)
1516
+ if socket_path is None:
1517
+ _emit_kill_failure(
1518
+ ctx,
1519
+ f"pocketshell: found tmux session {row.name!r} in the listing but "
1520
+ "no tmux server socket serves it; it may have just exited.",
1521
+ exit_code=ATTACH_EXIT_NO_SOCKET,
1522
+ as_json=as_json,
1523
+ )
1524
+ return
1525
+ # Exact `=` match on the listing's socket. A bare `-t NAME` fails open
1526
+ # (kills a prefix neighbour and reports success); `=` fails closed.
1527
+ argv = ["tmux", "-S", socket_path, "kill-session", "-t", f"={row.name}"]
1528
+ try:
1529
+ completed = _run_session_kill(argv)
1530
+ except subprocess.TimeoutExpired:
1531
+ _emit_kill_failure(
1532
+ ctx,
1533
+ f"pocketshell: `tmux kill-session` for {row.name!r} timed out.",
1534
+ exit_code=1,
1535
+ as_json=as_json,
1536
+ )
1537
+ return
1538
+ except OSError as exc:
1539
+ _emit_kill_failure(
1540
+ ctx,
1541
+ "pocketshell: `tmux` is not installed on this host; "
1542
+ f"cannot kill {row.name!r}: {exc}",
1543
+ exit_code=ATTACH_EXIT_NO_BINARY,
1544
+ as_json=as_json,
1545
+ )
1546
+ return
1547
+ if completed.returncode != 0:
1548
+ detail = str(completed.stderr or "").strip() or f"exit {completed.returncode}"
1549
+ _emit_kill_failure(
1550
+ ctx,
1551
+ f"pocketshell: could not kill {row.name!r}: {detail}",
1552
+ exit_code=completed.returncode,
1553
+ as_json=as_json,
1554
+ )
1555
+ return
1556
+ if as_json:
1557
+ click.echo(
1558
+ json.dumps(
1559
+ {
1560
+ "schema": KILL_SCHEMA_VERSION,
1561
+ "name": row.name,
1562
+ "manager": row.manager,
1563
+ "id": row.aplexer_id,
1564
+ "killed": True,
1565
+ },
1566
+ indent=2,
1567
+ )
1568
+ )