sessioncost 1.2.6__tar.gz → 1.2.7__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 (98) hide show
  1. {sessioncost-1.2.6/sessioncost.egg-info → sessioncost-1.2.7}/PKG-INFO +1 -1
  2. {sessioncost-1.2.6 → sessioncost-1.2.7}/pyproject.toml +1 -1
  3. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/__init__.py +1 -1
  4. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/update.py +252 -227
  5. {sessioncost-1.2.6 → sessioncost-1.2.7/sessioncost.egg-info}/PKG-INFO +1 -1
  6. {sessioncost-1.2.6 → sessioncost-1.2.7}/LICENSE +0 -0
  7. {sessioncost-1.2.6 → sessioncost-1.2.7}/MANIFEST.in +0 -0
  8. {sessioncost-1.2.6 → sessioncost-1.2.7}/README.md +0 -0
  9. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/__main__.py +0 -0
  10. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/analyse.py +0 -0
  11. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/analyse_calls.py +0 -0
  12. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/analyse_lists.py +0 -0
  13. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/cli.py +0 -0
  14. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/cli_setup.py +0 -0
  15. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/current_chat.py +0 -0
  16. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/editor.py +0 -0
  17. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixer.py +0 -0
  18. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixer_plan.py +0 -0
  19. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixer_store.py +0 -0
  20. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixes/__init__.py +0 -0
  21. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixes/big_results.py +0 -0
  22. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixes/cache_break.py +0 -0
  23. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixes/common.py +0 -0
  24. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixes/confirm_turns.py +0 -0
  25. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixes/error_loop.py +0 -0
  26. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixes/helper_polling.py +0 -0
  27. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixes/helper_rereads.py +0 -0
  28. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixes/images.py +0 -0
  29. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixes/long_chat.py +0 -0
  30. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixes/long_output.py +0 -0
  31. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixes/model_choice.py +0 -0
  32. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixes/overlap.py +0 -0
  33. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixes/repeated_reads.py +0 -0
  34. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixes/repeated_writes.py +0 -0
  35. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixes/reruns.py +0 -0
  36. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixes/stale_context.py +0 -0
  37. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixes/startup_bloat.py +0 -0
  38. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixes/unused_builtins.py +0 -0
  39. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fixes/unused_tools.py +0 -0
  40. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/fresh_chat.py +0 -0
  41. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/guard.py +0 -0
  42. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/guard_agents.py +0 -0
  43. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/guard_auto.py +0 -0
  44. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/guard_checks.py +0 -0
  45. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/guard_decide.py +0 -0
  46. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/guard_fresh.py +0 -0
  47. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/guard_inventory.py +0 -0
  48. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/guard_owasp.py +0 -0
  49. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/guard_post.py +0 -0
  50. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/guard_quiet.py +0 -0
  51. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/guard_report.py +0 -0
  52. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/guard_scan.py +0 -0
  53. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/guard_setup.py +0 -0
  54. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/guard_store.py +0 -0
  55. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/guard_waste.py +0 -0
  56. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/help_menu.py +0 -0
  57. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/hook.py +0 -0
  58. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/locate.py +0 -0
  59. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/model.py +0 -0
  60. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/names.py +0 -0
  61. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/opener.py +0 -0
  62. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/practices.py +0 -0
  63. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/prices.json +0 -0
  64. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/prices.py +0 -0
  65. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/prices_cmd.py +0 -0
  66. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/readers/__init__.py +0 -0
  67. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/readers/_pb.py +0 -0
  68. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/readers/_util.py +0 -0
  69. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/readers/antigravity.py +0 -0
  70. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/readers/claude.py +0 -0
  71. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/readers/claude_text.py +0 -0
  72. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/readers/codex.py +0 -0
  73. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/readers/copilot.py +0 -0
  74. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/readers/cursor.py +0 -0
  75. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/readers/cursor_steps.py +0 -0
  76. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/readers/cursor_usage.py +0 -0
  77. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/readers/vscode_chat.py +0 -0
  78. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/report.py +0 -0
  79. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/report_board.html +0 -0
  80. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/risk_bypass.py +0 -0
  81. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/risk_patterns.py +0 -0
  82. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/risk_shell.py +0 -0
  83. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/risks.py +0 -0
  84. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/rules.py +0 -0
  85. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/sarif.py +0 -0
  86. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/serve.py +0 -0
  87. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/skill/SKILL.md +0 -0
  88. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/skill/liveguard.md +0 -0
  89. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/status.py +0 -0
  90. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/textflags.py +0 -0
  91. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/uninstall.py +0 -0
  92. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/unsafe_code.py +0 -0
  93. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost/zfile.py +0 -0
  94. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost.egg-info/SOURCES.txt +0 -0
  95. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost.egg-info/dependency_links.txt +0 -0
  96. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost.egg-info/entry_points.txt +0 -0
  97. {sessioncost-1.2.6 → sessioncost-1.2.7}/sessioncost.egg-info/top_level.txt +0 -0
  98. {sessioncost-1.2.6 → sessioncost-1.2.7}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sessioncost
3
- Version: 1.2.6
3
+ Version: 1.2.7
4
4
  Summary: See how many tokens each turn of your coding-agent chat sends, why, and what to cut. Cost goes down with it.
5
5
  Author: kish21
6
6
  License-Expression: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "sessioncost"
7
- version = "1.2.6"
7
+ version = "1.2.7"
8
8
  description = "See how many tokens each turn of your coding-agent chat sends, why, and what to cut. Cost goes down with it."
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -1,2 +1,2 @@
1
1
  """SessionCost: see where every token of your agent session went, turn by turn, and what to fix."""
2
- __version__ = "1.2.6"
2
+ __version__ = "1.2.7"
@@ -1,227 +1,252 @@
1
- """`sessioncost update`: bring every copy of SessionCost on this computer up to date, the right way for each.
2
-
3
- SessionCost can be installed several ways, and each updates differently (checked 2026-10-16):
4
- - the install line (uv tool): update the package inside its own environment from the public repo (not a
5
- reinstall, which would have to replace the Python that is running);
6
- - pip: pip install -U sessioncost;
7
- - the Claude Code plugin: claude plugin marketplace update, then claude plugin update (Claude Code does
8
- not update plugins from our marketplace by itself unless you turn that on);
9
- - the Codex plugin: codex plugin marketplace upgrade;
10
- - the Cursor plugin: no command: Cursor's marketplace has a Refresh button.
11
- Then `setup` runs again, so the /sessioncost skill in each agent names the new version.
12
-
13
- Nothing is read or sent from your sessions; the commands only fetch SessionCost itself.
14
- """
15
- from __future__ import annotations
16
-
17
- import json
18
- import re
19
- import shutil
20
- import subprocess
21
- import sys
22
- from dataclasses import dataclass
23
- from pathlib import Path
24
-
25
- PUBLIC_ZIP = "https://github.com/kish21/sessioncost/archive/refs/heads/main.zip" # what the installers use
26
- NPX_HOME = "/.sessioncost/npm/" # where `npx sessioncost` keeps its own Python environment (npm/bin/sessioncost.js)
27
- EDITOR_HOME = "/.sessioncost/editor/" # the editor extension's own copy: made by uv (no pip), updated by the extension
28
- WINDOWS = sys.platform == "win32"
29
-
30
-
31
- @dataclass
32
- class Step:
33
- what: str # plain words
34
- argv: list[str] | None = None # the command; None = something the user does by hand (shown, not run)
35
- manual_after: bool = False # Windows cannot replace a running .exe: shown for the user to run afterwards
36
-
37
-
38
- def _plugin_keys(home: Path) -> list[str]:
39
- try:
40
- plugins = json.loads((home / ".claude" / "plugins" / "installed_plugins.json").read_text(encoding="utf-8"))
41
- except (OSError, ValueError):
42
- return []
43
- return [k for k in (plugins.get("plugins") or {}) if k.startswith("sessioncost@")]
44
-
45
-
46
- def plan(home: Path | None = None, exe: str | None = None, here: Path | None = None, which=shutil.which,
47
- windows: bool = WINDOWS, launcher: str | None = None) -> list[Step]:
48
- """The steps for this computer. `exe` is the Python running SessionCost, `here` this package's folder,
49
- `launcher` the program the user started (sys.argv[0])."""
50
- home = home or Path.home()
51
- exe = exe or sys.executable
52
- here_s = (here or Path(__file__).resolve().parent).as_posix().lower()
53
- started = Path(launcher if launcher is not None else sys.argv[0]).name.lower()
54
- steps: list[Step] = []
55
- in_plugin = "/plugins/cache/" in here_s # this run is a plugin's own bundled copy
56
- if not in_plugin:
57
- if NPX_HOME in Path(exe).as_posix().lower(): # npx's own environment: npx installs the new one
58
- steps.append(Step("Update SessionCost (run with npx): run `npx sessioncost@latest` once"))
59
- elif EDITOR_HOME in Path(exe).as_posix().lower(): # the extension installs the matching one when it updates
60
- steps.append(Step("SessionCost in your editor updates by itself when the SessionCost extension updates"))
61
- elif "/uv/tools/sessioncost/" in Path(exe).as_posix().lower() and which("uv"):
62
- steps.append(Step("Update SessionCost (installed with the install line)",
63
- [which("uv"), "pip", "install", "--quiet", "--python", exe, "--reinstall-package",
64
- "sessioncost", PUBLIC_ZIP]))
65
- else:
66
- steps.append(Step("Update SessionCost (installed with pip)",
67
- [exe, "-m", "pip", "install", "--quiet", "-U", "sessioncost"],
68
- manual_after=windows and started == "sessioncost.exe")) # pip would replace it
69
- for key in _plugin_keys(home):
70
- market = key.split("@", 1)[1]
71
- claude = which("claude") # the full path: on Windows it is a .cmd launcher
72
- if claude:
73
- steps.append(Step("Claude Code plugin: fetch the newest version",
74
- [claude, "plugin", "marketplace", "update", market]))
75
- steps.append(Step("Claude Code plugin: install it", [claude, "plugin", "update", key]))
76
- else:
77
- steps.append(Step("Claude Code plugin: in Claude Code, type /plugin, open Installed, choose sessioncost, "
78
- "then Update now"))
79
- steps.append(Step("Claude Code plugin: to get every new version by itself, type /plugin, open Marketplaces, "
80
- f"choose {market}, then Enable auto-update"))
81
- codex_cache = home / ".codex" / "plugins" / "cache"
82
- if codex_cache.is_dir() and any(codex_cache.glob("*/sessioncost")):
83
- codex = which("codex")
84
- steps.append(Step("Codex plugin: fetch the newest version", [codex, "plugin", "marketplace", "upgrade"])
85
- if codex else Step("Codex plugin: run `codex plugin marketplace upgrade`"))
86
- cursor_plugins = home / ".cursor" / "plugins"
87
- if cursor_plugins.is_dir() and any(cursor_plugins.glob("**/sessioncost")):
88
- steps.append(Step("Cursor plugin: in Cursor, open Customize, find the marketplace with SessionCost, then Refresh"))
89
- if not in_plugin:
90
- steps.append(Step("Refresh /sessioncost in each agent", [exe, "-m", "sessioncost", "setup"]))
91
- return steps
92
-
93
-
94
- SKILL_VERSION = re.compile(r"\(SessionCost ([^\s)]+)\)") # the skill's description names its version
95
- PROBE = ("import os, sys, sessioncost as s; print(sys.executable); print(s.__version__); "
96
- "print(os.path.dirname(s.__file__))") # the version it reports itself, as `sessioncost --version` does
97
-
98
-
99
- def _json_version(f: Path) -> str | None:
100
- try:
101
- return json.loads(f.read_text(encoding="utf-8")).get("version")
102
- except (OSError, ValueError, AttributeError):
103
- return None
104
-
105
-
106
- def _probe(argv: list[str]) -> list[str] | None:
107
- """Another program's output lines, or None when it fails or takes too long (Store Python starts in ~2 s). Run from
108
- the temp folder: a project folder holding sessioncost itself would be found first."""
109
- import tempfile
110
- try:
111
- r = subprocess.run(argv, capture_output=True, text=True, timeout=15, cwd=tempfile.gettempdir())
112
- except (OSError, subprocess.SubprocessError):
113
- return None
114
- return [x.strip() for x in r.stdout.splitlines() if x.strip()] if r.returncode == 0 else None
115
-
116
-
117
- def copies(home: Path | None = None, exe: str | None = None, here: Path | None = None, which=shutil.which,
118
- probe=_probe) -> list[tuple[str, str, str]]:
119
- """Every copy of SessionCost found on this computer: (what, version, where). The first is the one running."""
120
- from . import __version__
121
- from .cli import SKILL_HOMES
122
- home = home or Path.home()
123
- exe = exe or sys.executable
124
- here = here or Path(__file__).resolve().parent
125
- found = [("This copy (running now)", __version__, str(here))]
126
- same = lambda a, b: Path(a).resolve() == Path(b).resolve()
127
- python = which("python") # the terminal's own Python, when it is not this one
128
- if python and (out := probe([python, "-c", PROBE])) and len(out) == 3 and not same(out[2], here):
129
- found.append(("Terminal (python)", out[1], out[0]))
130
- cmd = which("sessioncost") # a sessioncost command on the PATH from another Python
131
- if cmd and not same(Path(cmd).parent, Path(exe).parent) and not same(Path(cmd).parent, Path(exe).parent / "Scripts"):
132
- if (out := probe([cmd, "--version"])) and out[0].startswith("sessioncost "):
133
- # inside `npx sessioncost`, npm puts its own launcher first on the PATH: not a copy you can type later
134
- npx = "_npx" in Path(cmd).parts
135
- found.append(("npx launcher (temporary)" if npx else "Terminal (sessioncost)", out[0].split()[-1], cmd))
136
- for key in _plugin_keys(home):
137
- try:
138
- entries = json.loads((home / ".claude" / "plugins" / "installed_plugins.json")
139
- .read_text(encoding="utf-8"))["plugins"][key]
140
- except (OSError, ValueError, KeyError):
141
- entries = []
142
- for e in entries or [{}]:
143
- found.append(("Claude Code plugin", e.get("version") or "?", e.get("installPath") or key))
144
- for d in sorted((home / ".codex" / "plugins" / "cache").glob("*/sessioncost/*")):
145
- if d.is_dir():
146
- found.append(("Codex plugin", _json_version(d / ".codex-plugin" / "plugin.json") or d.name, str(d)))
147
- cursor = home / ".cursor" / "plugins"
148
- for f in sorted(cursor.glob("**/sessioncost/**/.cursor-plugin/plugin.json")) if cursor.is_dir() else []:
149
- if (v := _json_version(f)) and not any(c[0] == "Cursor plugin" and c[1] == v for c in found):
150
- found.append(("Cursor plugin", v, str(f.parent.parent)))
151
- for agent, folder, sub, _ in SKILL_HOMES: # the /sessioncost skill `setup` wrote into each agent
152
- f = home / folder / sub / "sessioncost" / "SKILL.md"
153
- try:
154
- m = SKILL_VERSION.search(f.read_text(encoding="utf-8", errors="replace"))
155
- except OSError:
156
- continue
157
- found.append((f"{agent} /sessioncost", m.group(1) if m else "?", str(f)))
158
- # a plugin's folder holding the running copy is that copy, not another one
159
- return found[:1] + [c for c in found[1:] if not (same(c[2], here) or same(c[2], here.parent))]
160
-
161
-
162
- def kind(here: Path) -> str:
163
- """What the running copy is, in the user's words."""
164
- p = here.as_posix().lower()
165
- for folder, name in ((".claude", "Claude Code plugin"), (".codex", "Codex plugin"), (".cursor", "Cursor plugin")):
166
- if f"/{folder}/plugins/" in p:
167
- return name
168
- if EDITOR_HOME in p:
169
- return "editor extension"
170
- return "npx" if NPX_HOME in p else "Python package"
171
-
172
-
173
- def show_versions(every: bool = False) -> int:
174
- """This copy only, by default: in a chat, the other agents' copies are noise (owner 2026-10-31). --all lists
175
- every copy."""
176
- here = Path(__file__).resolve().parent
177
- found = copies(here=here)
178
- if not every:
179
- others = found[1:]
180
- print(f"SessionCost {found[0][1]} ({kind(here)}): {found[0][2]}")
181
- if others:
182
- differ = sum(v != found[0][1] for _, v, _ in others)
183
- print(f"{len(others)} other {'copy' if len(others) == 1 else 'copies'} on this computer"
184
- f"{f', {differ} on another version' if differ else ''}. All of them: sessioncost version --all")
185
- return 0
186
- print("SessionCost on this computer:")
187
- width = max(len(w) for w, _, _ in found)
188
- for what, v, where in found:
189
- print(f" {what:{width}} {v:14} {where}")
190
- other = [w for w, v, _ in found[1:] if v != found[0][1]]
191
- if other:
192
- print(f"\nNot the same version as this copy: {', '.join(other)}. `sessioncost update` updates them "
193
- "(a plugin can also be updated in its agent).")
194
- return 0
195
-
196
-
197
- def run(dry_run: bool = False) -> int:
198
- try:
199
- sys.stdout.reconfigure(line_buffering=True) # our step names before each command's own output
200
- except (AttributeError, ValueError):
201
- pass
202
- steps = plan()
203
- failed, later = 0, [] # later: commands the user runs once this SessionCost has closed
204
- for n, st in enumerate(steps, 1):
205
- print(f"{n}. {st.what}")
206
- if st.argv is None or dry_run:
207
- if st.argv:
208
- print(" " + " ".join(st.argv))
209
- continue
210
- if st.manual_after:
211
- later.append(st.argv)
212
- continue
213
- try:
214
- ok = subprocess.run(st.argv).returncode == 0
215
- except OSError as e:
216
- ok = False
217
- print(f" could not run it: {e}")
218
- if not ok:
219
- failed += 1
220
- print(" that step did not work; the rest still ran")
221
- if dry_run:
222
- print("\n(dry run: nothing was changed)")
223
- return 0
224
- for argv in later:
225
- print("\nSessionCost cannot replace itself while it runs. Close it, then run:\n " + " ".join(argv))
226
- print("\nRestart your agent so it picks up the new version.")
227
- return 1 if failed else 0
1
+ """`sessioncost update`: bring every copy of SessionCost on this computer up to date, the right way for each.
2
+
3
+ SessionCost can be installed several ways, and each updates differently (checked 2026-10-16):
4
+ - the install line (uv tool): update the package inside its own environment from the public repo (not a
5
+ reinstall, which would have to replace the Python that is running);
6
+ - pip: pip install -U sessioncost;
7
+ - the Claude Code plugin: claude plugin marketplace update, then claude plugin update (Claude Code does
8
+ not update plugins from our marketplace by itself unless you turn that on);
9
+ - the Codex plugin: codex plugin marketplace upgrade;
10
+ - the Cursor plugin: no command: Cursor's marketplace has a Refresh button.
11
+ Then `setup` runs again, so the /sessioncost skill in each agent names the new version.
12
+
13
+ Nothing is read or sent from your sessions; the commands only fetch SessionCost itself.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import re
19
+ import shutil
20
+ import subprocess
21
+ import sys
22
+ from dataclasses import dataclass
23
+ from pathlib import Path
24
+
25
+ PUBLIC_ZIP = "https://github.com/kish21/sessioncost/archive/refs/heads/main.zip" # what the installers use
26
+ NPX_HOME = "/.sessioncost/npm/" # where `npx sessioncost` keeps its own Python environment (npm/bin/sessioncost.js)
27
+ EDITOR_HOME = "/.sessioncost/editor/" # the editor extension's own copy: made by uv (no pip), updated by the extension
28
+ WINDOWS = sys.platform == "win32"
29
+
30
+
31
+ @dataclass
32
+ class Step:
33
+ what: str # plain words
34
+ argv: list[str] | None = None # the command; None = something the user does by hand (shown, not run)
35
+ manual_after: bool = False # Windows cannot replace a running .exe: shown for the user to run afterwards
36
+ retry: list[str] | None = None # run instead when the first try fails on a known, harmless setting (Codex)
37
+
38
+
39
+ # The Codex app writes service_tier = "default" into ~/.codex/config.toml, which Codex's own command line refuses
40
+ # ("unknown variant `default`, expected `fast` or `flex`": owner's PC 2026-11-22). The upgrade runs no model, so the
41
+ # setting does not matter there: override it for that one command, the user's file stays as it is.
42
+ CODEX_TIER_ERROR = "service_tier"
43
+ CODEX_TIER_FIX = ["-c", "service_tier=flex"]
44
+
45
+
46
+ def _plugin_keys(home: Path) -> list[str]:
47
+ try:
48
+ plugins = json.loads((home / ".claude" / "plugins" / "installed_plugins.json").read_text(encoding="utf-8"))
49
+ except (OSError, ValueError):
50
+ return []
51
+ return [k for k in (plugins.get("plugins") or {}) if k.startswith("sessioncost@")]
52
+
53
+
54
+ def plan(home: Path | None = None, exe: str | None = None, here: Path | None = None, which=shutil.which,
55
+ windows: bool = WINDOWS, launcher: str | None = None) -> list[Step]:
56
+ """The steps for this computer. `exe` is the Python running SessionCost, `here` this package's folder,
57
+ `launcher` the program the user started (sys.argv[0])."""
58
+ home = home or Path.home()
59
+ exe = exe or sys.executable
60
+ here_s = (here or Path(__file__).resolve().parent).as_posix().lower()
61
+ started = Path(launcher if launcher is not None else sys.argv[0]).name.lower()
62
+ steps: list[Step] = []
63
+ in_plugin = "/plugins/cache/" in here_s # this run is a plugin's own bundled copy
64
+ if not in_plugin:
65
+ if NPX_HOME in Path(exe).as_posix().lower(): # npx's own environment: npx installs the new one
66
+ steps.append(Step("Update SessionCost (run with npx): run `npx sessioncost@latest` once"))
67
+ elif EDITOR_HOME in Path(exe).as_posix().lower(): # the extension installs the matching one when it updates
68
+ steps.append(Step("SessionCost in your editor updates by itself when the SessionCost extension updates"))
69
+ elif "/uv/tools/sessioncost/" in Path(exe).as_posix().lower() and which("uv"):
70
+ steps.append(Step("Update SessionCost (installed with the install line)",
71
+ [which("uv"), "pip", "install", "--quiet", "--python", exe, "--reinstall-package",
72
+ "sessioncost", PUBLIC_ZIP]))
73
+ else:
74
+ steps.append(Step("Update SessionCost (installed with pip)",
75
+ [exe, "-m", "pip", "install", "--quiet", "-U", "sessioncost"],
76
+ manual_after=windows and started == "sessioncost.exe")) # pip would replace it
77
+ for key in _plugin_keys(home):
78
+ market = key.split("@", 1)[1]
79
+ claude = which("claude") # the full path: on Windows it is a .cmd launcher
80
+ if claude:
81
+ steps.append(Step("Claude Code plugin: fetch the newest version",
82
+ [claude, "plugin", "marketplace", "update", market]))
83
+ steps.append(Step("Claude Code plugin: install it", [claude, "plugin", "update", key]))
84
+ else:
85
+ steps.append(Step("Claude Code plugin: in Claude Code, type /plugin, open Installed, choose sessioncost, "
86
+ "then Update now"))
87
+ steps.append(Step("Claude Code plugin: to get every new version by itself, type /plugin, open Marketplaces, "
88
+ f"choose {market}, then Enable auto-update"))
89
+ codex_cache = home / ".codex" / "plugins" / "cache"
90
+ if codex_cache.is_dir() and any(codex_cache.glob("*/sessioncost")):
91
+ codex = which("codex")
92
+ steps.append(Step("Codex plugin: fetch the newest version", [codex, "plugin", "marketplace", "upgrade"],
93
+ retry=[codex, *CODEX_TIER_FIX, "plugin", "marketplace", "upgrade"])
94
+ if codex else Step("Codex plugin: run `codex plugin marketplace upgrade`"))
95
+ cursor_plugins = home / ".cursor" / "plugins"
96
+ if cursor_plugins.is_dir() and any(cursor_plugins.glob("**/sessioncost")):
97
+ steps.append(Step("Cursor plugin: in Cursor, open Customize, find the marketplace with SessionCost, then Refresh"))
98
+ if not in_plugin:
99
+ steps.append(Step("Refresh /sessioncost in each agent", [exe, "-m", "sessioncost", "setup"]))
100
+ return steps
101
+
102
+
103
+ SKILL_VERSION = re.compile(r"\(SessionCost ([^\s)]+)\)") # the skill's description names its version
104
+ PROBE = ("import os, sys, sessioncost as s; print(sys.executable); print(s.__version__); "
105
+ "print(os.path.dirname(s.__file__))") # the version it reports itself, as `sessioncost --version` does
106
+
107
+
108
+ def _json_version(f: Path) -> str | None:
109
+ try:
110
+ return json.loads(f.read_text(encoding="utf-8")).get("version")
111
+ except (OSError, ValueError, AttributeError):
112
+ return None
113
+
114
+
115
+ def _probe(argv: list[str]) -> list[str] | None:
116
+ """Another program's output lines, or None when it fails or takes too long (Store Python starts in ~2 s). Run from
117
+ the temp folder: a project folder holding sessioncost itself would be found first."""
118
+ import tempfile
119
+ try:
120
+ r = subprocess.run(argv, capture_output=True, text=True, timeout=15, cwd=tempfile.gettempdir())
121
+ except (OSError, subprocess.SubprocessError):
122
+ return None
123
+ return [x.strip() for x in r.stdout.splitlines() if x.strip()] if r.returncode == 0 else None
124
+
125
+
126
+ def copies(home: Path | None = None, exe: str | None = None, here: Path | None = None, which=shutil.which,
127
+ probe=_probe) -> list[tuple[str, str, str]]:
128
+ """Every copy of SessionCost found on this computer: (what, version, where). The first is the one running."""
129
+ from . import __version__
130
+ from .cli import SKILL_HOMES
131
+ home = home or Path.home()
132
+ exe = exe or sys.executable
133
+ here = here or Path(__file__).resolve().parent
134
+ found = [("This copy (running now)", __version__, str(here))]
135
+ same = lambda a, b: Path(a).resolve() == Path(b).resolve()
136
+ python = which("python") # the terminal's own Python, when it is not this one
137
+ if python and (out := probe([python, "-c", PROBE])) and len(out) == 3 and not same(out[2], here):
138
+ found.append(("Terminal (python)", out[1], out[0]))
139
+ cmd = which("sessioncost") # a sessioncost command on the PATH from another Python
140
+ if cmd and not same(Path(cmd).parent, Path(exe).parent) and not same(Path(cmd).parent, Path(exe).parent / "Scripts"):
141
+ if (out := probe([cmd, "--version"])) and out[0].startswith("sessioncost "):
142
+ # inside `npx sessioncost`, npm puts its own launcher first on the PATH: not a copy you can type later
143
+ npx = "_npx" in Path(cmd).parts
144
+ found.append(("npx launcher (temporary)" if npx else "Terminal (sessioncost)", out[0].split()[-1], cmd))
145
+ for key in _plugin_keys(home):
146
+ try:
147
+ entries = json.loads((home / ".claude" / "plugins" / "installed_plugins.json")
148
+ .read_text(encoding="utf-8"))["plugins"][key]
149
+ except (OSError, ValueError, KeyError):
150
+ entries = []
151
+ for e in entries or [{}]:
152
+ found.append(("Claude Code plugin", e.get("version") or "?", e.get("installPath") or key))
153
+ for d in sorted((home / ".codex" / "plugins" / "cache").glob("*/sessioncost/*")):
154
+ if d.is_dir():
155
+ found.append(("Codex plugin", _json_version(d / ".codex-plugin" / "plugin.json") or d.name, str(d)))
156
+ cursor = home / ".cursor" / "plugins"
157
+ for f in sorted(cursor.glob("**/sessioncost/**/.cursor-plugin/plugin.json")) if cursor.is_dir() else []:
158
+ if (v := _json_version(f)) and not any(c[0] == "Cursor plugin" and c[1] == v for c in found):
159
+ found.append(("Cursor plugin", v, str(f.parent.parent)))
160
+ for agent, folder, sub, _ in SKILL_HOMES: # the /sessioncost skill `setup` wrote into each agent
161
+ f = home / folder / sub / "sessioncost" / "SKILL.md"
162
+ try:
163
+ m = SKILL_VERSION.search(f.read_text(encoding="utf-8", errors="replace"))
164
+ except OSError:
165
+ continue
166
+ found.append((f"{agent} /sessioncost", m.group(1) if m else "?", str(f)))
167
+ # a plugin's folder holding the running copy is that copy, not another one
168
+ return found[:1] + [c for c in found[1:] if not (same(c[2], here) or same(c[2], here.parent))]
169
+
170
+
171
+ def kind(here: Path) -> str:
172
+ """What the running copy is, in the user's words."""
173
+ p = here.as_posix().lower()
174
+ for folder, name in ((".claude", "Claude Code plugin"), (".codex", "Codex plugin"), (".cursor", "Cursor plugin")):
175
+ if f"/{folder}/plugins/" in p:
176
+ return name
177
+ if EDITOR_HOME in p:
178
+ return "editor extension"
179
+ return "npx" if NPX_HOME in p else "Python package"
180
+
181
+
182
+ def show_versions(every: bool = False) -> int:
183
+ """This copy only, by default: in a chat, the other agents' copies are noise (owner 2026-10-31). --all lists
184
+ every copy."""
185
+ here = Path(__file__).resolve().parent
186
+ found = copies(here=here)
187
+ if not every:
188
+ others = found[1:]
189
+ print(f"SessionCost {found[0][1]} ({kind(here)}): {found[0][2]}")
190
+ if others:
191
+ differ = sum(v != found[0][1] for _, v, _ in others)
192
+ print(f"{len(others)} other {'copy' if len(others) == 1 else 'copies'} on this computer"
193
+ f"{f', {differ} on another version' if differ else ''}. All of them: sessioncost version --all")
194
+ return 0
195
+ print("SessionCost on this computer:")
196
+ width = max(len(w) for w, _, _ in found)
197
+ for what, v, where in found:
198
+ print(f" {what:{width}} {v:14} {where}")
199
+ other = [w for w, v, _ in found[1:] if v != found[0][1]]
200
+ if other:
201
+ print(f"\nNot the same version as this copy: {', '.join(other)}. `sessioncost update` updates them "
202
+ "(a plugin can also be updated in its agent).")
203
+ return 0
204
+
205
+
206
+ def _run_step(st: Step) -> bool:
207
+ """Runs a step, its output shown. A step with a retry runs quietly first: when it fails on the known setting, the
208
+ retry runs (shown) and the first error is never printed; any other failure prints the first try's output."""
209
+ if not st.retry:
210
+ return subprocess.run(st.argv).returncode == 0
211
+ first = subprocess.run(st.argv, capture_output=True, text=True, encoding="utf-8", errors="replace")
212
+ said = (first.stdout or "") + (first.stderr or "")
213
+ if first.returncode == 0:
214
+ print(said, end="")
215
+ return True
216
+ if CODEX_TIER_ERROR in said:
217
+ return subprocess.run(st.retry).returncode == 0
218
+ print(said, end="")
219
+ return False
220
+
221
+
222
+ def run(dry_run: bool = False) -> int:
223
+ try:
224
+ sys.stdout.reconfigure(line_buffering=True) # our step names before each command's own output
225
+ except (AttributeError, ValueError):
226
+ pass
227
+ steps = plan()
228
+ failed, later = 0, [] # later: commands the user runs once this SessionCost has closed
229
+ for n, st in enumerate(steps, 1):
230
+ print(f"{n}. {st.what}")
231
+ if st.argv is None or dry_run:
232
+ if st.argv:
233
+ print(" " + " ".join(st.argv))
234
+ continue
235
+ if st.manual_after:
236
+ later.append(st.argv)
237
+ continue
238
+ try:
239
+ ok = _run_step(st)
240
+ except OSError as e:
241
+ ok = False
242
+ print(f" could not run it: {e}")
243
+ if not ok:
244
+ failed += 1
245
+ print(" that step did not work; the rest still ran")
246
+ if dry_run:
247
+ print("\n(dry run: nothing was changed)")
248
+ return 0
249
+ for argv in later:
250
+ print("\nSessionCost cannot replace itself while it runs. Close it, then run:\n " + " ".join(argv))
251
+ print("\nRestart your agent so it picks up the new version.")
252
+ return 1 if failed else 0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sessioncost
3
- Version: 1.2.6
3
+ Version: 1.2.7
4
4
  Summary: See how many tokens each turn of your coding-agent chat sends, why, and what to cut. Cost goes down with it.
5
5
  Author: kish21
6
6
  License-Expression: MIT
File without changes
File without changes
File without changes
File without changes