sessioncost 1.2.0__tar.gz → 1.2.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 (86) hide show
  1. {sessioncost-1.2.0/sessioncost.egg-info → sessioncost-1.2.2}/PKG-INFO +1 -1
  2. {sessioncost-1.2.0 → sessioncost-1.2.2}/pyproject.toml +1 -1
  3. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/__init__.py +1 -1
  4. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/analyse_lists.py +5 -1
  5. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/cli.py +17 -17
  6. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/editor.py +49 -1
  7. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixer.py +60 -34
  8. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixer_plan.py +19 -1
  9. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixer_store.py +21 -0
  10. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixes/unused_builtins.py +2 -1
  11. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/guard.py +19 -15
  12. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/guard_auto.py +1 -1
  13. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/guard_checks.py +0 -50
  14. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/guard_decide.py +1 -5
  15. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/guard_report.py +1 -1
  16. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/guard_store.py +6 -5
  17. sessioncost-1.2.2/sessioncost/guard_waste.py +81 -0
  18. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/locate.py +16 -0
  19. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/prices.py +22 -3
  20. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/readers/antigravity.py +28 -11
  21. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/update.py +5 -0
  22. {sessioncost-1.2.0 → sessioncost-1.2.2/sessioncost.egg-info}/PKG-INFO +1 -1
  23. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost.egg-info/SOURCES.txt +1 -0
  24. {sessioncost-1.2.0 → sessioncost-1.2.2}/LICENSE +0 -0
  25. {sessioncost-1.2.0 → sessioncost-1.2.2}/MANIFEST.in +0 -0
  26. {sessioncost-1.2.0 → sessioncost-1.2.2}/README.md +0 -0
  27. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/__main__.py +0 -0
  28. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/analyse.py +0 -0
  29. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/analyse_calls.py +0 -0
  30. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/cli_setup.py +0 -0
  31. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixes/__init__.py +0 -0
  32. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixes/big_results.py +0 -0
  33. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixes/cache_break.py +0 -0
  34. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixes/common.py +0 -0
  35. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixes/confirm_turns.py +0 -0
  36. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixes/error_loop.py +0 -0
  37. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixes/helper_polling.py +0 -0
  38. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixes/helper_rereads.py +0 -0
  39. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixes/images.py +0 -0
  40. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixes/long_chat.py +0 -0
  41. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixes/long_output.py +0 -0
  42. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixes/model_choice.py +0 -0
  43. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixes/overlap.py +0 -0
  44. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixes/repeated_reads.py +0 -0
  45. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixes/repeated_writes.py +0 -0
  46. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixes/reruns.py +0 -0
  47. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixes/stale_context.py +0 -0
  48. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixes/startup_bloat.py +0 -0
  49. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/fixes/unused_tools.py +0 -0
  50. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/guard_agents.py +0 -0
  51. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/guard_inventory.py +0 -0
  52. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/guard_setup.py +0 -0
  53. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/model.py +0 -0
  54. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/names.py +0 -0
  55. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/practices.py +0 -0
  56. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/prices.json +0 -0
  57. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/prices_cmd.py +0 -0
  58. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/readers/__init__.py +0 -0
  59. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/readers/_pb.py +0 -0
  60. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/readers/_util.py +0 -0
  61. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/readers/claude.py +0 -0
  62. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/readers/claude_text.py +0 -0
  63. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/readers/codex.py +0 -0
  64. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/readers/copilot.py +0 -0
  65. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/readers/cursor.py +0 -0
  66. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/readers/cursor_steps.py +0 -0
  67. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/readers/cursor_usage.py +0 -0
  68. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/readers/vscode_chat.py +0 -0
  69. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/report.py +0 -0
  70. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/report_board.html +0 -0
  71. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/risk_bypass.py +0 -0
  72. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/risk_patterns.py +0 -0
  73. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/risk_shell.py +0 -0
  74. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/risks.py +0 -0
  75. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/rules.py +0 -0
  76. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/sarif.py +0 -0
  77. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/serve.py +0 -0
  78. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/skill/SKILL.md +0 -0
  79. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/skill/liveguard.md +0 -0
  80. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/status.py +0 -0
  81. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/textflags.py +0 -0
  82. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost/zfile.py +0 -0
  83. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost.egg-info/dependency_links.txt +0 -0
  84. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost.egg-info/entry_points.txt +0 -0
  85. {sessioncost-1.2.0 → sessioncost-1.2.2}/sessioncost.egg-info/top_level.txt +0 -0
  86. {sessioncost-1.2.0 → sessioncost-1.2.2}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sessioncost
3
- Version: 1.2.0
3
+ Version: 1.2.2
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.0"
7
+ version = "1.2.2"
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.0"
2
+ __version__ = "1.2.2"
@@ -113,10 +113,14 @@ LINK_RE = re.compile(r"\[([^\]]+)\]\(([^)\s]+)\)")
113
113
  PATH_RE = re.compile(r"(?<![\w:/\\])(?:[A-Za-z]:[\\/]+|~[\\/]+|[\\/]+)(?:[^\s\\/\"'`()\[\]]+[\\/]+)+([^\s\\/\"'`()\[\]]*)")
114
114
 
115
115
 
116
+ PASTED_RE = re.compile(r"</?pasted_content\b[^>]*>\s*")
117
+
118
+
116
119
  def plain(text: str) -> str:
117
120
  """What a person reads: markdown links become their text, file paths become their last name
118
121
  ("[$architect](C:/Users/me/SKILL.md)" -> "$architect"). Also keeps folder names out of shared screenshots."""
119
- text = LINK_RE.sub(lambda m: m.group(1), text or "")
122
+ text = PASTED_RE.sub("", text or "") # Claude Code wraps a pasted text in <pasted_content id="…"> tags
123
+ text = LINK_RE.sub(lambda m: m.group(1), text)
120
124
  text = re.sub(r"@\[([^\]]+)\]", lambda m: "@" + re.split(r"[\\/]", m.group(1).rstrip("\\/"))[-1], text)
121
125
  return PATH_RE.sub(lambda m: m.group(1) or "folder", text).strip()
122
126
 
@@ -11,13 +11,12 @@ from pathlib import Path
11
11
  from . import __version__, locate, prices as pricemod, readers, report, zfile
12
12
  from .analyse import analyse
13
13
  from .readers import cursor
14
- from .readers.antigravity import antigravity_homes
15
14
  from .cli_setup import SKILL_HOMES, agent_installed, claude_plugin_installed, cmd_setup
16
15
  from .names import GUARD_CMD
17
16
  from .cli_setup import LIVE_SKILL, SKILL, plugin_installed, setup # noqa: F401 (cli.<name> for other modules and tests)
18
17
 
19
18
 
20
- REPORTS = Path.home() / ".sessioncost" / "reports"
19
+ REPORTS = Path(os.environ.get("SESSIONCOST_DIR") or Path.home() / ".sessioncost") / "reports"
21
20
  DOWNLOADS = Path.home() / "Downloads" # where a browser saves Cursor's usage export (tests point it elsewhere)
22
21
  DOWNLOADS_DAYS = 60 # an export older than this cannot hold a recent chat
23
22
 
@@ -170,18 +169,23 @@ def downloaded_usage(s, folder: Path | None = None) -> tuple[Path, int] | None:
170
169
  return None
171
170
 
172
171
 
172
+ def note(args, text: str) -> None:
173
+ """A note for the person: on stdout, unless stdout is JSON for a program (--json): then on stderr."""
174
+ print(text, file=sys.stderr if getattr(args, "json", False) else sys.stdout)
175
+
176
+
173
177
  def build(path, args) -> tuple[dict, Path | None]:
174
178
  s = readers.read(path)
175
179
  if s.agent == "cursor" and not args.cursor_usage and (found := downloaded_usage(s)):
176
- print(f"sessioncost: used Cursor's usage export from Downloads: {found[0].name} ({found[1]} requests matched "
177
- "this chat)")
180
+ note(args, f"sessioncost: used Cursor's usage export from Downloads: {found[0].name} ({found[1]} requests "
181
+ "matched this chat)")
178
182
  if args.cursor_usage:
179
183
  if s.agent != "cursor":
180
- print("sessioncost: --cursor-usage is for Cursor chats; ignored")
184
+ note(args, "sessioncost: --cursor-usage is for Cursor chats; ignored")
181
185
  else:
182
186
  used = cursor.apply_usage_csv(s, cursor.read_usage_csv(args.cursor_usage))
183
- print(f"sessioncost: {used} requests from the usage export matched this chat" if used else
184
- "sessioncost: no row of the usage export falls inside this chat's turns (check the export's dates)")
187
+ note(args, f"sessioncost: {used} requests from the usage export matched this chat" if used else
188
+ "sessioncost: no row of the usage export falls inside this chat's turns (check the export's dates)")
185
189
  a = analyse(s, pricemod.load(args.prices), subscription=args.subscription)
186
190
  from . import fixer, guard
187
191
  a["guard_all"] = guard_totals(s.cwd)
@@ -217,7 +221,7 @@ def cmd_list(args) -> int:
217
221
  loose: list = []
218
222
  found = locate.sessions(args.project, unlinked=loose)
219
223
  if not found and not loose:
220
- print(f"No Claude Code, Codex, Copilot CLI, Antigravity or Cursor sessions found for {args.project or Path.cwd()}" + zfile.codex_note("\n"))
224
+ print(locate.none_found(args.project))
221
225
  return 1
222
226
  P = pricemod.load(args.prices)
223
227
 
@@ -400,7 +404,7 @@ def main(argv: list[str] | None = None) -> int:
400
404
  description="See where every token of your agent session went, turn by turn, and what to fix. "
401
405
  "Local: reads log files on this computer and sends nothing anywhere.")
402
406
  ap.add_argument("target", nargs="?", default="last",
403
- help="'last' (newest Claude Code, Codex, Copilot CLI, Antigravity or Cursor session of this project, the default), 'fix' (this project's token waste and the change for each, applied on your yes with a backup; `sessioncost fix --undo` puts it back; `sessioncost fix auto on|off`: the list after each answer, in the chat), 'list', 'serve' (a live report page on this computer only, with a Refresh button; Ctrl+C stops it), 'setup' (add /sessioncost to your agents),'clean' (delete all saved reports but the latest), 'update' (update every copy of SessionCost on this computer), 'version' (this copy's version; --all lists every copy on this computer), 'prices' (the prices used, where each came from and its date; `sessioncost prices set|import|team|update`),'auto' (`sessioncost auto on|off`: rebuild each chat's report after each answer, on by default), 'guard' (the live guard: `sessioncost guard on|off|auto on|off`; `sessioncost guard` alone shows its state), or a session file (.jsonl, or an Antigravity .db)")
407
+ help="'last' (newest Claude Code, Codex, Copilot CLI, Antigravity or Cursor session of this project, the default), 'fix' (this project's token waste and the change for each, applied on your yes with a backup; `sessioncost fix --undo` puts it back; `sessioncost fix auto on|off`: the list after each answer, in the chat), 'list', 'serve' (a live report page on this computer only, with a Refresh button; Ctrl+C stops it), 'setup' (add /sessioncost to your agents), 'clean' (delete all saved reports but the latest), 'update' (update every copy of SessionCost on this computer), 'version' (this copy's version; --all lists every copy on this computer), 'prices' (the prices used, where each came from and its date; `sessioncost prices set|import|team|update`), 'auto' (`sessioncost auto on|off`: rebuild each chat's report after each answer, on by default), 'guard' (the live guard: `sessioncost guard on|off|auto on|off`; `sessioncost guard` alone shows its state), or a session file (.jsonl, or an Antigravity .db)")
404
408
  ap.add_argument("--project", help="project folder (default: the current folder)")
405
409
  ap.add_argument("--no-open", action="store_true", help="write the report but do not open it")
406
410
  ap.add_argument("--brief", action="store_true", help="print only the report's path, not the summary (for agents: "
@@ -474,16 +478,12 @@ def find_session(args, chat: str | None = None) -> Path | None:
474
478
  loose: list = []
475
479
  found = locate.sessions(args.project, unlinked=loose)
476
480
  if not found and loose:
477
- print(f"sessioncost: no session is recorded for {args.project or Path.cwd()}. Showing the newest session "
478
- "whose folder the agent did not record; it may belong to another project. "
479
- "`sessioncost list` shows the others.")
481
+ note(args, f"sessioncost: no session is recorded for {args.project or Path.cwd()}. Showing the newest "
482
+ "session whose folder the agent did not record; it may belong to another project. "
483
+ "`sessioncost list` shows the others.")
480
484
  found = loose
481
485
  if not found:
482
- from .readers.copilot import copilot_home
483
- print(f"No Claude Code, Codex, Copilot CLI, Antigravity or Cursor sessions found for {args.project or Path.cwd()} "
484
- f"(looked in {locate.claude_home() / 'projects'}, {locate.codex_home() / 'sessions'} and "
485
- f"{locate.codex_home() / 'archived_sessions'}, {copilot_home() / 'session-state'}, "
486
- f"{', '.join(str(h / 'conversations') for h in antigravity_homes())}, and Cursor's chats)")
486
+ note(args, locate.none_found(args.project))
487
487
  return None
488
488
  return found[0][1]
489
489
  path = Path(target).expanduser()
@@ -13,6 +13,7 @@ rest; it holds no logic of its own. Read on this computer only; nothing is sent
13
13
  "last_stop": {"ts", "decision", "what", "why"} or null, "last_tip"}
14
14
  handover the handover file to continue from, or null
15
15
  watch files whose change means this answer is out of date (the chat's log, its guard log, the switches)
16
+ watch_dirs folders where a new chat of this folder appears (any agent): a new entry there means "ask again"
16
17
  error only when this chat could not be read: why, in plain words
17
18
  """
18
19
  from __future__ import annotations
@@ -71,6 +72,48 @@ def _chat(project: str) -> tuple[dict | None, str]:
71
72
  "last_tip": str(last or "").replace("💡 SessionCost: ", "").strip()}, ""
72
73
 
73
74
 
75
+ def _nearest(p: Path) -> Path | None:
76
+ """p, or its closest folder that exists (a folder made later still shows up as a new entry there)."""
77
+ for q in [p, *p.parents]:
78
+ if q.is_dir():
79
+ return q
80
+ return None
81
+
82
+
83
+ def watch_dirs(project: str) -> list[str]:
84
+ """The folders where a new chat of this project appears, any agent: a new entry there means a new chat may have
85
+ started. Cursor keeps every chat in one database, which changes all the time; the bar checks it on its timer."""
86
+ from datetime import datetime
87
+
88
+ from . import locate
89
+ from .readers.antigravity import antigravity_homes
90
+ from .readers.copilot import copilot_home
91
+ from .readers.vscode_chat import folder_of, vscode_homes
92
+ want = [locate.project_dir(project) or locate.claude_home() / "projects",
93
+ locate.codex_home() / "sessions" / datetime.now().strftime("%Y/%m/%d"),
94
+ copilot_home() / "session-state"]
95
+ want += [base / "conversations" for base in antigravity_homes()]
96
+ for home in vscode_homes():
97
+ ws = home / "workspaceStorage"
98
+ for d in sorted(ws.glob("*/chatSessions")) if ws.is_dir() else []:
99
+ folder = folder_of(d / "x") # the window's folder, from workspace.json beside chatSessions
100
+ if folder and locate._same_dir(folder, project):
101
+ want.append(d)
102
+ out = []
103
+ for p in want:
104
+ q = _nearest(p)
105
+ if q is not None and q != q.parent and str(q) not in out and q != Path.home():
106
+ out.append(str(q))
107
+ return out
108
+
109
+
110
+ def _cursor_db() -> list[str]:
111
+ """Cursor's chat database, when there is one: a new Cursor chat changes it (checked on the bar's timer)."""
112
+ from .readers.cursor import state_db
113
+ p = state_db()
114
+ return [str(p)] if p.is_file() else []
115
+
116
+
74
117
  def answer(project: str) -> dict:
75
118
  from .fixer_store import auto_on, find_handover, project_path
76
119
  from .guard_store import _read, guard_on, home, log_path
@@ -81,7 +124,12 @@ def answer(project: str) -> dict:
81
124
  out = {"schema": SCHEMA, "version": __version__, "project": project,
82
125
  "guard": {"on": guard_on(cfg), "strict": bool(guard_on(cfg) and cfg.get("strict")), "dir": str(home())},
83
126
  "tips": {"on": auto_on()}, "chat": chat, "handover": str(h) if h else None,
84
- "watch": [str(home() / "config.json")] + ([chat["log"], str(log_path(chat["id"]))] if chat else [])}
127
+ # Cursor's database changes whenever Cursor is used: watched only when this folder's chat is Cursor's (its
128
+ # numbers live there) or there is none yet; otherwise the bar's minute timer finds a new Cursor chat
129
+ "watch": list(dict.fromkeys([str(home() / "config.json")]
130
+ + ([chat["log"], str(log_path(chat["id"]))] if chat else [])
131
+ + (_cursor_db() if not chat or chat["agent"] == "cursor" else []))),
132
+ "watch_dirs": watch_dirs(project)}
85
133
  if error:
86
134
  out["error"] = error
87
135
  return out
@@ -23,14 +23,18 @@ from pathlib import Path
23
23
 
24
24
  from . import practices
25
25
  from .fixer_plan import Plan, plan
26
- from .fixer_store import (ASKED_FIX, BIG_TIP_TOKENS, CHAT_KEEP_S, HANDOVER_ASK, HEAD, KEEP_SEEN, MIN_TIP_TOKENS,
26
+ from .fixer_store import (ASKED_FIX, BIG_TIP_TOKENS, CHAT_KEEP_S, HANDOVER_END, HANDOVER_NAME, HEAD, KEEP_SEEN, MIN_TIP_TOKENS,
27
27
  NOTE_MAX_AGE_S, OFFER_QUIET_S, RULE_OF, SAY_FIX, SAY_HANDOVER, SETTINGS, _load, _norm, _now, _save, _sha, _size, _tok, _ts, _usd,
28
- auto_on, backups_dir, base, chat_file, find_handover, fixes_file, handover_file, known,
29
- live_file, offered_file, project_key, project_path, start_folder)
28
+ asks_handover, auto_on, backups_dir, base, chat_file, find_handover, fixes_file, handover_file, known,
29
+ live_file, newest_lines, offered_file, project_key, project_path, start_folder)
30
30
  # Names other modules and tests use as fixer.<name>; they live in fixer_store.py and fixer_plan.py.
31
31
  from .fixer_plan import for_report, render # noqa: F401
32
32
  from .fixer_store import LONG_CHAT, auto_text, budget_text, budget_usd, learn, learned, long_chat, set_auto, set_budget, set_long_chat # noqa: F401
33
33
 
34
+ # a user may keep their own notes in the handover file: the newest handover goes first, nothing is lost (owner, 2026-11-17)
35
+ ON_TOP = ("keep everything already in the file below it, and end the new handover with this line, as written, so a "
36
+ f"new chat reads only the newest one: {HANDOVER_END}")
37
+
34
38
 
35
39
  def apply(p: Plan) -> tuple[int, str]:
36
40
  """Back up, then write every change of the plan. (exit code, what happened)."""
@@ -98,7 +102,8 @@ def apply(p: Plan) -> tuple[int, str]:
98
102
  + "\n".join(" " + x for x in i.steps.splitlines()))
99
103
  if any(i.kind == "handover" for i in p.items):
100
104
  h = handover_file(p.project)
101
- out.append(f"Handover: write it now in {h.as_posix()} (replace what is there): the goal, what is done, files "
105
+ out.append(f"Handover: write it now at the top of {h.as_posix()} under a heading with today's date (a new "
106
+ f"file if there is none; {ON_TOP}): the goal, what is done, files "
102
107
  "changed, tests run, what is next. Show it in your reply, then tell the user to start a new chat "
103
108
  "and say \"continue from handover\" there.")
104
109
  out.append("In the same handover, add a short section \"Other token waste in this chat\": what cost tokens in "
@@ -249,10 +254,17 @@ def mark_shown(p: Plan) -> None:
249
254
  if not p.chat or not p.items:
250
255
  return
251
256
  st = _load(chat_file(p.chat), {})
252
- st["shown"] = sorted(set(st.get("shown", [])) | {i.id for i in p.items})
257
+ _seen(st, [i.id for i in p.items], p.context)
253
258
  _save(chat_file(p.chat), st)
254
259
 
255
260
 
261
+ def _seen(st: dict, ids: list[str], context) -> None:
262
+ """These items were shown in this chat; the long-chat tip also keeps the size it was shown at (see _quiet)."""
263
+ st["shown"] = sorted(set(st.get("shown", [])) | set(ids))
264
+ if "long-chat" in ids and context:
265
+ st["long_at"] = int(context)
266
+
267
+
256
268
  def _q(s: str) -> str:
257
269
  return f'"{s}"' if re.search(r"\s", s) else s
258
270
 
@@ -275,7 +287,9 @@ def _quiet(note: dict, chat: str, cwd: str, st: dict) -> list[dict]:
275
287
  out = []
276
288
  for i in note.get("items", []):
277
289
  iid, tok, kind = str(i.get("id")), int(i.get("tokens") or 0), i.get("kind")
278
- if iid in shown or (iid == "long-chat" and not same):
290
+ # a long chat: said again each time it doubled since it was last said (owner, 2026-11-15)
291
+ doubled = iid == "long-chat" and int(note.get("context") or 0) >= 2 * int(st.get("long_at") or long_chat())
292
+ if (iid in shown and not doubled) or (iid == "long-chat" and not same):
279
293
  continue # once a chat; a long chat only in that chat
280
294
  if iid != "long-chat" and time.time() - float(offered.get(iid) or 0) < OFFER_QUIET_S:
281
295
  continue # offered in this project this week and not fixed: that was a no
@@ -306,13 +320,12 @@ def _one_line(items: list[dict], same: bool) -> str:
306
320
  # its own words, never "Shall I ...?": the agent may have asked its own question higher up the reply, and a bare
307
321
  # "yes" would answer either (owner, 2026-11-11). The command is named too, for those who prefer to type it.
308
322
  typed = "(or type /sessioncost fix)"
309
- line = f"💡 SessionCost: {'. Also '.join(parts)}." if parts else ""
323
+ line = f'💡 SessionCost: {". Also ".join(parts)}. Say "{SAY_FIX}" {typed} to fix these.' if parts else ""
310
324
  if not long:
311
- return f'{line} Say "{SAY_FIX}" {typed} to fix these.' if line else ""
312
- line = (line + " " if line else "💡 SessionCost: ") + long.get("line", "")
313
- if parts:
314
- return f'{line} Say "{SAY_FIX}" {typed} to fix these and write a handover, so you can start a fresh chat.'
315
- return f'{line} Say "{SAY_HANDOVER}" {typed} so you can start a fresh chat.'
325
+ return line
326
+ # the agent writes the handover in the same reply, unasked (owner, 2026-11-17): the line says where it is
327
+ return ((line + " " if line else "💡 SessionCost: ") + long.get("line", "")
328
+ + f' A handover is in {HANDOVER_NAME}: start a fresh chat and say "continue from handover".')
316
329
 
317
330
 
318
331
  def _same_agent(hook_agent: str, note_agent: str) -> bool:
@@ -338,9 +351,12 @@ def tip(chat: str, cwd: str, prompt: str = "", start: bool = False, turn: str |
338
351
  "(keep only the ids they chose) and show the lines it prints. Otherwise ignore this.")
339
352
  st["pending"] = ""
340
353
  h = find_handover(cwd) if cwd else None
341
- if h and prompt and HANDOVER_ASK.search(prompt):
342
- out.append(f"The user wants to continue from the handover of an earlier chat: read "
343
- f"{h.as_posix()} first, then carry on from its \"what is next\".")
354
+ if h and prompt and asks_handover(prompt):
355
+ n = newest_lines(h) # the newest handover only: older ones below it would cost tokens for nothing
356
+ what = (f"read only lines 1-{n} of {h.as_posix()} (the newest handover; do not read the older notes below "
357
+ "it unless the user asks)" if n else f"read {h.as_posix()} first")
358
+ out.append(f"The user wants to continue from the handover of an earlier chat: {what}, then carry on from its "
359
+ "\"what is next\".")
344
360
  elif h and start and time.time() - h.stat().st_mtime < CHAT_KEEP_S:
345
361
  out.append(f"A handover from an earlier chat in this project is at {h.as_posix()}. Read it "
346
362
  "only if the user asks to continue from it.")
@@ -353,34 +369,44 @@ def tip(chat: str, cwd: str, prompt: str = "", start: bool = False, turn: str |
353
369
  items = _quiet(note, chat, cwd, st)
354
370
  if items and ASKED_FIX.search(prompt or ""):
355
371
  # the user asked for the list or the report themselves: it shows the same, so no second list now
356
- st["shown"] = sorted(set(st.get("shown", [])) | {i["id"] for i in items})
372
+ _seen(st, [i["id"] for i in items], note.get("context"))
357
373
  items, dirty = [], True
358
374
  if items:
359
- ids = ",".join(i["id"] for i in items)
360
375
  where = _q(Path(cwd).as_posix())
361
376
  of = f"{_q(str(note['chat']))} " if note.get("chat") else "" # the chat the list came from
362
- cmd = f"{run_cmd()} fix -y {of}--only {ids} --project {where}"
363
- look = f"{run_cmd()} fix --preview {of}--only {ids} --project {where}"
377
+ long = any(i["id"] == "long-chat" for i in items)
378
+ ids = ",".join(i["id"] for i in items if i["id"] != "long-chat")
379
+ cmd = f"{run_cmd()} fix -y {of}--only {ids} --project {where}" if ids else ""
364
380
  # chat-start text stays in the agent's context for the whole chat (Copilot, Cursor): said once, or the
365
381
  # agent ends every reply with it, even after the fix ran (owner, 2026-11-12)
366
382
  when = ("put this one line only at the end of your first reply in this chat and never repeat it in a "
367
383
  "later reply (also not after the fix ran or the user said no); in that first reply put it "
368
384
  if start else "end your reply with this one line, ")
369
- out.append(
370
- "SessionCost (fix auto is on) found token waste. Answer the user's message as usual first; when "
371
- f"all your work for it is done, {when}as written, as a quote block "
372
- "(begin it with \"> \"), as the very last thing in the reply, so the user sees it where the chat "
373
- f"stops:\n{_one_line(items, note.get('chat') == chat)}\n"
374
- "Put nothing after that line. Do not end that reply with a question of your own: the user answers this one first. "
375
- f"If the user asks what these are, run `{look}` and show what it prints. Only if the user says "
376
- f"\"{SAY_FIX}\" or \"{SAY_HANDOVER}\" (or \"fix these\", \"fix all\", \"fix the first one\": all, "
377
- f"or some), run `{cmd}` "
378
- "(keep only the ids they chose) and show the lines it prints. A bare \"yes\" answers your own "
379
- "question, not this line: do not run it then. If "
380
- "it asks you to write a handover, do it. If running it is blocked or refused (auto mode, for "
381
- "example), do not try another way: tell the user to type /sessioncost fix and answer yes there. "
382
- "If they say no, or say nothing about it, drop it. Never run it without their yes.")
383
- st["shown"] = sorted(set(st.get("shown", [])) | {i["id"] for i in items})
385
+ say = [f"SessionCost (fix auto is on) found token waste. Answer the user's message as usual first; when "
386
+ f"all your work for it is done, {when}as written, as a quote block "
387
+ "(begin it with \"> \"), as the very last thing in the reply, so the user sees it where the chat "
388
+ f"stops:\n{_one_line(items, note.get('chat') == chat)}\n"
389
+ "Put nothing after that line."]
390
+ if long: # a long chat: the handover is written at once, no yes needed (owner, 2026-11-17)
391
+ say.append(f"This chat is long, so write a handover now, without waiting for the user's yes: "
392
+ "after your work for the user's message and before that last line, run "
393
+ f"`{run_cmd()} fix -y {of}--only long-chat --project {where}` and do what it prints. "
394
+ "If running it is blocked or refused, write the handover yourself at the top of "
395
+ f"{handover_file(cwd).as_posix()} ({ON_TOP}): the goal, what is done, files "
396
+ "changed, tests run, what is next.")
397
+ if cmd:
398
+ look = f"{run_cmd()} fix --preview {of}--only {ids} --project {where}"
399
+ say.append(
400
+ "Do not end that reply with a question of your own: the user answers this one first. "
401
+ f"If the user asks what these are, run `{look}` and show what it prints. Only if the user says "
402
+ f"\"{SAY_FIX}\" (or \"fix these\", \"fix all\", \"fix the first one\": all, or some), run "
403
+ f"`{cmd}` (keep only the ids they chose) and show the lines it prints. A bare \"yes\" answers "
404
+ "your own question, not this line: do not run it then. If running it is blocked or refused "
405
+ "(auto mode, for example), do not try another way: tell the user to type /sessioncost fix and "
406
+ "answer yes there. If they say no, or say nothing about it, drop it. Never run it without "
407
+ "their yes.")
408
+ out.append(" ".join(say))
409
+ _seen(st, [i["id"] for i in items], note.get("context"))
384
410
  st["last_tip"] = {"at": time.time(), "line": _one_line(items, note.get("chat") == chat)} # status.py
385
411
  st["lists"] = int(st.get("lists") or 0) + 1
386
412
  st["pending"] = cmd if turn is not None else ""
@@ -150,7 +150,23 @@ def _settings(text: str | None, updates: dict) -> tuple[str | None, str]:
150
150
  new[k], changed = have + add, True
151
151
  elif new.get(k) != v:
152
152
  new[k], changed = v, True
153
- return (json.dumps(new, indent=2) + "\n" if changed else text), ""
153
+ if not changed:
154
+ return text, ""
155
+ nl = "\r\n" if text and "\r\n" in text else "\n" # the file's own line endings and its own letters
156
+ return json.dumps(new, indent=2, ensure_ascii=False).replace("\n", nl) + nl, ""
157
+
158
+
159
+ def _narrow_builtin(it, targets: list[str], per: dict, was: int) -> None:
160
+ """The built-in tools item after a recent chat of this project used some of them: its title, reason and saving
161
+ name only the tools still switched off (the setting change already holds only those)."""
162
+ s = "s" if len(targets) > 1 else ""
163
+ names = " and ".join(targets)
164
+ it.title = f"Switch off Claude Code's own {names} tool{s} (not used in this project's recent chats)"
165
+ it.why = (f"Claude Code's own {names} tool{s} went out with every call and no recent chat of this project used "
166
+ f"{'them' if s else 'it'}; the other built-in tools are kept, because a recent chat used them.")
167
+ whole = it.tokens
168
+ it.tokens = sum(int(per.get(t) or 0) for t in targets) if per else round(whole * len(targets) / max(1, was))
169
+ it.usd = it.usd * it.tokens / whole if whole else 0.0 # the same share of the money
154
170
 
155
171
 
156
172
  def split_servers(project: Path, targets: list[str]) -> tuple[list[str], list[str]]:
@@ -246,6 +262,8 @@ def plan(a: dict, project, only: set[str] | None = None, home: Path | None = Non
246
262
  rule, updates, rest = RULE_OF.get(fid), {}, []
247
263
  if fid == "unused-builtin" and agent == "claude-code":
248
264
  updates = dict(BUILTIN_SETTING[t] for t in targets if t in BUILTIN_SETTING)
265
+ if len(targets) < len(f.get("targets") or []): # a recent chat used one: name and count only the rest
266
+ _narrow_builtin(it, targets, f.get("per_target") or {}, len(f.get("targets") or []))
249
267
  elif fid == "unused-tools" and agent == "claude-code":
250
268
  idle, rest = split_servers(project, targets)
251
269
  if idle:
@@ -45,6 +45,13 @@ ASKED_FIX = re.compile(r"^\s*[/$](?:sessioncost:)?sessioncost\b|\bsessioncost fi
45
45
  SAY_FIX = "fix it" # what the user says to the live tip: its own words, not a bare "yes" (owner, 2026-11-11)
46
46
  SAY_HANDOVER = "write a handover" # ... to the long-chat tip
47
47
  HANDOVER_ASK = re.compile(r"\b(?:continue|carry on|resume|pick up)\b.{0,40}\bhand-?over\b", re.I | re.S)
48
+ # words just before the ask that make it a mention, not a request: 'instead of saying continue from handover'
49
+ _MENTION = re.compile(r"(?:\bsay(?:s|ing)?|\bsaid|\btypes?|\btyping|\bwords?|[\"'“‘`])\s*$", re.I)
50
+
51
+
52
+ def asks_handover(prompt: str) -> bool:
53
+ """The user asks to continue from the handover (and does not only talk about those words)."""
54
+ return any(not _MENTION.search(prompt[:m.start()]) for m in HANDOVER_ASK.finditer(prompt or ""))
48
55
 
49
56
 
50
57
  # ---- where things are kept ----
@@ -86,6 +93,20 @@ def backups_dir(project) -> Path:
86
93
 
87
94
 
88
95
  HANDOVER_NAME = "NEXT-SESSION.md" # in the project, where the user can find it (owner, 2026-11-12)
96
+ # the last line of each handover: "continue from handover" reads up to the first one only (owner, 2026-11-18)
97
+ HANDOVER_END = "<!-- End of the newest handover. Older notes below: do not read further unless asked. -->"
98
+
99
+
100
+ def newest_lines(f: Path) -> int:
101
+ """How many lines the newest handover takes (up to and with the first end line); 0 when the file has none."""
102
+ try:
103
+ with f.open(encoding="utf-8", errors="replace") as fh:
104
+ for n, line in enumerate(fh, 1):
105
+ if line.strip() == HANDOVER_END:
106
+ return n
107
+ except OSError:
108
+ pass
109
+ return 0
89
110
 
90
111
 
91
112
  def handover_file(project) -> Path:
@@ -44,4 +44,5 @@ def unused_builtins(s: Session, P) -> Fix | None:
44
44
  f"{'them' if len(idle) > 1 else 'it'} in other chats either."),
45
45
  saving_usd=usd, saving_tokens=tokens * len(s.calls), where="every call",
46
46
  items=[f"{t.what}: ~{tok(t.chars):,} tokens on every call ({BUILTIN_SWITCHES[t.what][0]}, or "
47
- f"{BUILTIN_SWITCHES[t.what][1]})" for t in idle], targets=[t.what for t in idle])
47
+ f"{BUILTIN_SWITCHES[t.what][1]})" for t in idle], targets=[t.what for t in idle],
48
+ per_target={t.what: tok(t.chars) * len(s.calls) for t in idle})
@@ -49,9 +49,10 @@ from .guard_decide import (WHY, _fail_key, _full, _git, _raw_never, _step_fp, de
49
49
  step_of, tier)
50
50
  from .guard_inventory import _remove_how, _take_inventory, mcp_servers, mcp_tools
51
51
  from .guard_setup import SETTINGS, _hooks_file, _launch, _path_arg, command, refresh, setup
52
- from .guard_store import _default_home as home
52
+ from .guard_store import (STATE_WAIT, _default_home as home, _locked, _read, _write, append_log, guard_on, log_path,
53
+ state_path, verify_log, verify_status)
54
+ from .guard_waste import stop as stop_waste
53
55
  from .names import GUARD_CMD
54
- from .guard_store import _locked, _read, _write, append_log, guard_on, log_path, state_path, verify_log, verify_status
55
56
 
56
57
  # Names other modules, tests and tools use as guard.<name>; they live in the guard_* modules above.
57
58
  __all__ = ["WHY", "_copilot_in", "_full", "_git", "_hooks_file", "_launch", "_locked", "_path_arg", "_read",
@@ -78,12 +79,13 @@ STALE_S = 2 * 24 * 3600 # a chat's state left behind (its end hook can be ca
78
79
 
79
80
  def _clear_stale() -> None:
80
81
  now = time.time()
81
- for p in home().glob("*.state.json"):
82
- try:
83
- if now - p.stat().st_mtime > STALE_S:
84
- p.unlink()
85
- except OSError:
86
- pass
82
+ for pat in ("*.state.json", "*.waste.json", "*.state.json.lock"): # a lock: once its chat's state is gone
83
+ for p in home().glob(pat):
84
+ try:
85
+ if now - p.stat().st_mtime > STALE_S and not (pat.endswith(".lock") and p.with_suffix("").exists()):
86
+ p.unlink()
87
+ except OSError:
88
+ pass
87
89
 
88
90
 
89
91
  def on_session_start(inp: dict) -> dict | None:
@@ -356,6 +358,8 @@ def _run(event: str, inp: dict, agent: str) -> dict | None:
356
358
  return out
357
359
  if event == "post" and inp.get("_failed"): # a result that says it failed (agents without a failure hook)
358
360
  return (on_post(inp), on_fail(inp))[0]
361
+ if event == "pre": # the guard first; else a whole read of a big file (guard_waste)
362
+ return on_pre(inp) or stop_waste(inp)
359
363
  return EVENTS[event](inp) if event in EVENTS else None
360
364
 
361
365
 
@@ -418,7 +422,10 @@ def hook(event: str, raw: str, agent: str = "claude") -> tuple[int, str]:
418
422
  raw_cmd = str(inp.get("toolArgs") or "")
419
423
  inp = _copilot_in(event, inp)
420
424
  inp.setdefault("command", raw_cmd)
421
- out = _run(event, inp, agent)
425
+ # an agent running steps at once runs their hooks at once: each reads the chat's state and writes it back,
426
+ # so they take turns, or one overwrites what another saved (an injected page's "untrusted" mark, an ask)
427
+ with _locked(state_path(str(inp.get("session_id") or "")), STATE_WAIT):
428
+ out = _run(event, inp, agent)
422
429
  try: # fix auto's to-do list: never in the way of the guard's own answer
423
430
  tip = _fix_tip(raw_event if agent == "antigravity" else event, inp, raw_in, agent)
424
431
  except Exception as e:
@@ -457,17 +464,14 @@ def main(argv: list[str] | None = None) -> int:
457
464
  # Agents send UTF-8 JSON; Windows Python would read the pipe as cp1252 and garble any non-English text
458
465
  raw = sys.stdin.buffer.read().decode("utf-8-sig", errors="replace") if sys.stdin else ""
459
466
  code, out = hook(argv[1], raw, agent)
460
- if out:
461
- sys.stdout.write(out)
467
+ sys.stdout.write(out)
462
468
  return code
463
469
  if argv[:1] == ["setup"] and len(argv) > 1:
464
470
  print(setup(argv[1]))
465
471
  return 0
466
472
  if argv[:1] == ["allow"]:
467
- if argv[1:2] in ([], ["--list"]):
468
- print(command("allow-list-rules", os.getcwd()))
469
- elif argv[1:2] == ["--clear"]:
470
- print(command("allow-clear", os.getcwd()))
473
+ if argv[1:2] in ([], ["--list"], ["--clear"]):
474
+ print(command("allow-clear" if argv[1:2] == ["--clear"] else "allow-list-rules", os.getcwd()))
471
475
  elif len(argv) >= 3:
472
476
  print(command("allow", os.getcwd(), rule=(argv[1], " ".join(argv[2:]))))
473
477
  else:
@@ -82,7 +82,7 @@ def _auto_report(inp: dict, st: dict) -> str:
82
82
  if st.get("report_told") or not reports:
83
83
  return ""
84
84
  st["report_told"] = True
85
- where = Path.home() / ".sessioncost" / "reports" / (f"{Path(target).stem}.html" if target != "last" else "")
85
+ where = Path(os.environ.get("SESSIONCOST_DIR") or Path.home() / ".sessioncost") / "reports" / (f"{Path(target).stem}.html" if target != "last" else "")
86
86
  return f"SessionCost report (updated after each answer): {where}"
87
87
 
88
88
 
@@ -17,8 +17,6 @@ _LOCK_NAMES = {
17
17
  "cargo.lock", "poetry.lock", "composer.lock", "gemfile.lock",
18
18
  }
19
19
  _BUILD_SUFFIXES = (".min.js", ".min.css", ".bundle.js", ".chunk.js", ".map")
20
- BIG_READ_LINES = 2_000
21
- BIG_READ_BYTES = 80_000
22
20
 
23
21
  _RANGED_CMD = re.compile(
24
22
  r"\b(?:head|tail)\b|"
@@ -140,53 +138,6 @@ def _cmd_search_paths(cmd: str) -> list[str]:
140
138
  return paths
141
139
 
142
140
 
143
- def _file_is_big(raw: str, cwd: str) -> bool:
144
- raw = (raw or "").strip()
145
- if not raw:
146
- return False
147
- t = raw.replace("\\", "/").lower()
148
- base = t.rsplit("/", 1)[-1]
149
- is_lock_or_build = base in _LOCK_NAMES or base.endswith(_BUILD_SUFFIXES) or "/dist/" in f"/{t.lstrip('/')}"
150
- p = Path(os.path.expanduser(raw))
151
- p = p if p.is_absolute() or not cwd else Path(cwd) / p
152
- try:
153
- st = p.stat() if p.is_file() else None
154
- except OSError:
155
- st = None
156
- if is_lock_or_build:
157
- if st is None or st.st_size >= 12_000:
158
- return True
159
- try:
160
- with p.open(encoding="utf-8", errors="replace") as fh:
161
- if sum(1 for _ in fh) >= 200:
162
- return True
163
- except OSError:
164
- return True
165
- elif st is not None:
166
- if st.st_size > BIG_READ_BYTES:
167
- return True
168
- if st.st_size >= BIG_READ_LINES:
169
- try:
170
- with p.open(encoding="utf-8", errors="replace") as fh:
171
- if sum(1 for _ in fh) > BIG_READ_LINES:
172
- return True
173
- except OSError:
174
- pass
175
- return False
176
-
177
-
178
- def _big_read(a, cwd: str) -> bool:
179
- """True when a Read step or shell command reads a whole lockfile, build bundle or >2,000-line file without range limits."""
180
- if a.kind == "read":
181
- if getattr(a, "ranged", False) or not (a.target or "").strip():
182
- return False
183
- return any(_file_is_big(raw, cwd) for raw in (a.target or "").splitlines())
184
- if a.kind == "command":
185
- _, unlimited = _cmd_read_paths(a.target or "")
186
- return any(_file_is_big(p, cwd) for p in unlimited)
187
- return False
188
-
189
-
190
141
  def _agent_roots() -> list[str]:
191
142
  home = Path.home()
192
143
  roots = [str(home / d) for d in (".claude", ".codex", ".cursor", ".gemini", ".copilot", ".agents", ".sessioncost")]
@@ -400,7 +351,6 @@ WHY = {"pipe_to_shell": "runs a script straight from the internet", "encoded_com
400
351
  "after_untrusted": "a risky step right after untrusted content", "guardrails": "changes the agent's own rules, settings or memory",
401
352
  "git_push": "pushes with git", "deletes": "deletes files", "installs": "installs or fetches packages",
402
353
  "outside_project": "changes or reads a file outside the project", "network": "uses the network",
403
- "big_read": "reads a whole lockfile, build bundle or large file (>2,000 lines) without a line range (search first with Grep, or pass offset and limit)",
404
354
  "inline_script": "runs code written into the command", "injected": "its result showed signs of a prompt injection",
405
355
  "mcp_action": "an MCP tool that changes or sends something",
406
356
  "poisoned_tool": "a tool of an MCP server whose descriptions showed signs of a prompt injection",
@@ -6,7 +6,7 @@ import json
6
6
  import os
7
7
  import re
8
8
 
9
- from .guard_checks import (INSTEAD, SCRIPT, SCRIPT_MAX, WHY, _big_read, _git, _new_packages,
9
+ from .guard_checks import (INSTEAD, SCRIPT, SCRIPT_MAX, WHY, _git, _new_packages,
10
10
  _outside_read_step, _push_dest, _raw_never, _run_scripts, _secret_commit, _step_fp)
11
11
  from .guard_store import _read, home
12
12
  from .names import GUARD_CMD
@@ -77,8 +77,6 @@ def learn_key(mark: str, a) -> str:
77
77
  if mark == "guardrails" and auto_memory(a):
78
78
  m = AUTO_MEMORY.search(t)
79
79
  return f"guardrails:memory:{(m.group(1) or 'codex').lower()}"
80
- if mark == "big_read":
81
- return f"big_read:{os.path.normcase(t)}"
82
80
  if mark in ("outside_project", "guardrails"):
83
81
  target_dir = getattr(a, "outside_target", "") or t
84
82
  return f"{mark}:{os.path.normcase(os.path.dirname(target_dir) if mark == 'outside_project' else t)}"
@@ -212,8 +210,6 @@ def decide(st: dict, a, cwd: str) -> tuple[str, list[str], str]:
212
210
  if not risks._allowed(a, "outside_project", rules, cwd):
213
211
  a.outside_target = out_p
214
212
  marks.append("outside_project")
215
- if _big_read(a, cwd) and not risks._allowed(a, "big_read", rules, cwd):
216
- marks.append("big_read")
217
213
  a.risks = list(marks)
218
214
  if "git_push" in marks:
219
215
  _push_dest(a, cwd)
@@ -176,7 +176,7 @@ def write(as_json: bool = False, out: Path | None = None, folder: Path | None =
176
176
  r = collect(folder)
177
177
  if as_json:
178
178
  return json.dumps(r, indent=1)
179
- out = out or Path.home() / ".sessioncost" / "reports" / "guard.html"
179
+ out = out or Path(os.environ.get("SESSIONCOST_DIR") or Path.home() / ".sessioncost") / "reports" / "guard.html"
180
180
  out.parent.mkdir(parents=True, exist_ok=True)
181
181
  # errors="replace": logs written before 1.1 may hold a broken character (a lone surrogate); show "?", don't crash
182
182
  out.write_text(render(r, folder), encoding="utf-8", errors="replace")
@@ -108,20 +108,21 @@ def _prev_hash(p: Path) -> tuple[str, bool]:
108
108
 
109
109
 
110
110
  LOCK_WAIT = 2.0 # seconds one hook waits for another hook of the same chat
111
+ STATE_WAIT = 5.0 # ... for the chat's state: hooks time out at 10 s
111
112
 
112
113
 
113
114
  @contextlib.contextmanager
114
- def _locked(p: Path):
115
- """Hold <log>.lock while one entry is read and written, so two hooks of one chat at once cannot fork the chain;
116
- other chats have their own lock. Yields False when the lock could not be had in time. The system lets go of the
117
- lock when a process dies holding it."""
115
+ def _locked(p: Path, wait: float | None = None):
116
+ """Hold <p>.lock while it is read and written, so two hooks of one chat at once cannot fork the log's chain or
117
+ overwrite each other's state; other chats have their own lock. Yields False when the lock could not be had in
118
+ time (`wait` seconds, default LOCK_WAIT). The system lets go of the lock when a process dies holding it."""
118
119
  try:
119
120
  p.parent.mkdir(parents=True, exist_ok=True)
120
121
  fd = os.open(str(p) + ".lock", os.O_RDWR | os.O_CREAT, 0o600)
121
122
  except OSError:
122
123
  yield False
123
124
  return
124
- got, end = False, time.monotonic() + LOCK_WAIT
125
+ got, end = False, time.monotonic() + (LOCK_WAIT if wait is None else wait)
125
126
  try:
126
127
  while True:
127
128
  try:
@@ -0,0 +1,81 @@
1
+ """Stop token waste before it happens: an agent about to read a whole big file (Read tool, or cat / type /
2
+ Get-Content without head or tail) is turned back once, with a smaller way to get what it needs. Reading the same
3
+ file again goes through, so an agent that really needs all of it is never stuck.
4
+
5
+ Runs when the guard is on (for every chat, or this chat by /liveguard) or token tips are on. It is a token tip, not
6
+ a guard block: nothing is asked of the user and the guard's counts are not touched.
7
+ Left out: command output and web pages (their size is known only after they ran: the report covers them), and
8
+ Cursor's file-read hook (it says nothing about a line range, and it also runs for files the user attaches)."""
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ from pathlib import Path
13
+
14
+ from .guard_checks import _BUILD_SUFFIXES, _LOCK_NAMES, _cmd_read_paths
15
+ from .guard_store import _read, _safe_id, _write, fix_auto_on, guard_on, home, state_path
16
+
17
+ BIG_BYTES = 40_000 # about 10k tokens: the size the big-results check calls huge (fixes/big_results.py)
18
+ LOCK_BYTES = 12_000 # about 3k tokens: a lockfile or build bundle (fixes/big_results.py LOCKFILE_TOKENS)
19
+
20
+
21
+ def waste_path(sid: str) -> Path:
22
+ return home() / f"{_safe_id(sid)}.waste.json"
23
+
24
+
25
+ def _on(sid: str) -> bool:
26
+ cfg = _read(home() / "config.json", {})
27
+ return guard_on(cfg) or fix_auto_on(cfg) or state_path(sid).exists()
28
+
29
+
30
+ def _big(raw: str, cwd: str) -> tuple[str, int] | None:
31
+ """(full path, size in bytes) of a file too big to read whole, else None (a missing file is not big)."""
32
+ raw = (raw or "").strip()
33
+ if not raw:
34
+ return None
35
+ p = Path(os.path.expanduser(raw))
36
+ p = p if p.is_absolute() or not cwd else Path(cwd) / p
37
+ try:
38
+ size = p.stat().st_size if p.is_file() else None
39
+ except OSError:
40
+ size = None
41
+ if size is None:
42
+ return None
43
+ t = str(p).replace("\\", "/").lower()
44
+ lock = t.rsplit("/", 1)[-1] in _LOCK_NAMES or t.endswith(_BUILD_SUFFIXES) or "/dist/" in t
45
+ return (str(p), size) if size >= (LOCK_BYTES if lock else BIG_BYTES) else None
46
+
47
+
48
+ def _whole_reads(a, cwd: str) -> list[tuple[str, int]]:
49
+ if a.kind == "read" and not getattr(a, "ranged", False):
50
+ found = [_big(raw, cwd) for raw in (a.target or "").splitlines()]
51
+ elif a.kind == "command":
52
+ found = [_big(raw, cwd) for raw in _cmd_read_paths(a.target or "")[1]]
53
+ else:
54
+ return []
55
+ return [f for f in found if f]
56
+
57
+
58
+ def stop(inp: dict) -> dict | None:
59
+ """The pre-step answer that turns back a whole read of a big file the first time in this chat, else None."""
60
+ from .guard_decide import step_of
61
+ sid, cwd = str(inp.get("session_id") or ""), str(inp.get("cwd") or "")
62
+ if inp.get("_agent") == "cursor" and inp.get("tool_name") == "Read":
63
+ return None
64
+ a = step_of(str(inp.get("tool_name") or ""), inp.get("tool_input") or {}, str(inp.get("tool_use_id") or ""))
65
+ if a.kind not in ("read", "command") or not _on(sid):
66
+ return None
67
+ big = _whole_reads(a, cwd)
68
+ if big: # the project expects this read: `big_read <file>` in .sessioncost-allow
69
+ from . import risks
70
+ big = [] if risks._allowed(a, "big_read", risks.read_allow(cwd), cwd) else big
71
+ seen = _read(waste_path(sid), {}).get("files") or []
72
+ new = [(p, n) for p, n in big if os.path.normcase(p) not in seen]
73
+ if not new:
74
+ return None
75
+ _write(waste_path(sid), {"files": (seen + [os.path.normcase(p) for p, _ in new])[-200:]})
76
+ names = ", ".join(f"`{os.path.basename(p)}` (~{max(1, round(n / 4 / 1000))}k tokens)" for p, n in new)
77
+ reason = (f"SessionCost token tip: this reads all of {names}, and every later message sends it again. "
78
+ "Search it first, or read only the lines you need (a line range, or head / tail). "
79
+ "If you really need the whole file, read it again: it will go through.")
80
+ return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny",
81
+ "permissionDecisionReason": reason}}
@@ -380,6 +380,22 @@ def cursor_sessions(project: str | Path | None = None, db: Path | None = None, h
380
380
  return out
381
381
 
382
382
 
383
+ def none_found(project: str | Path | None = None) -> str:
384
+ """What `last` and `list` say when no chat of the folder is found: where they looked, and the next step."""
385
+ from . import zfile
386
+ from .readers.antigravity import antigravity_homes
387
+ from .readers.copilot import copilot_home
388
+ from .readers.vscode_chat import vscode_homes
389
+ where = [claude_home() / "projects", codex_home() / "sessions", codex_home() / "archived_sessions",
390
+ copilot_home() / "session-state", *(h / "conversations" for h in antigravity_homes()),
391
+ *(h / "workspaceStorage" for h in vscode_homes())]
392
+ folder = project or Path.cwd()
393
+ return (f"No chat found for {folder}: no Claude Code, Codex, Copilot CLI, VS Code Copilot Chat, Antigravity or "
394
+ f"Cursor chat names this folder (looked in {', '.join(map(str, where))}, and Cursor's chats).\n"
395
+ "Run SessionCost in the folder you opened your agent in, or name it: "
396
+ "sessioncost --project <that folder>" + zfile.codex_note("\n"))
397
+
398
+
383
399
  def sessions(project: str | Path | None = None, home: Path | None = None, codex: Path | None = None,
384
400
  antigravity: Path | None = None, cursor: Path | None = None, cursor_dir: Path | None = None,
385
401
  unlinked: list | None = None, copilot: Path | None = None,
@@ -66,8 +66,9 @@ def stale_note(prices: dict) -> str:
66
66
  if days is not None and days > STALE_DAYS:
67
67
  notes.append(f"The price list is {days} days old (checked {checked_day(prices['as_of'])}): run "
68
68
  "`sessioncost prices update`, or set your own with `sessioncost prices set`.")
69
- if prices.get("team_problem"):
70
- notes.append(prices["team_problem"])
69
+ for k in ("team_problem", "own_problem"):
70
+ if prices.get(k):
71
+ notes.append(prices[k])
71
72
  return " ".join(notes)
72
73
 
73
74
 
@@ -186,9 +187,25 @@ def load(extra_file: str | None = None, user_file=AUTO) -> dict:
186
187
  except (OSError, ValueError) as e:
187
188
  prices["team_problem"] = f"Your team's price file could not be read ({e}), so list prices were used."
188
189
  mine = own_file() if personal else user_file
190
+ problems = []
189
191
  for f, label in ((mine, "your own"), (Path(extra_file).expanduser() if extra_file else None, "--prices")):
190
192
  if f and Path(f).is_file():
191
- data = json.loads(Path(f).read_text(encoding="utf-8"))
193
+ try:
194
+ data = json.loads(Path(f).read_text(encoding="utf-8-sig"))
195
+ if not isinstance(data, dict) or not isinstance(data.get("models", {}), dict):
196
+ raise ValueError('it needs {"models": {"<model>": {"input": .., "output": ..}}}')
197
+ except (OSError, ValueError) as e:
198
+ if label == "--prices": # a file named on the command line: say so and stop
199
+ raise ValueError(f"the price file {f} could not be read ({e})") from None
200
+ problems.append(f"Your own price file {f} could not be read ({e}), so list prices were used: fix "
201
+ "it, or delete it and set your prices again with `sessioncost prices set`.")
202
+ continue
203
+ bad = [m for m, r in (data.get("models") or {}).items() if not isinstance(r, dict)]
204
+ if bad:
205
+ data = {**data, "models": {m: r for m, r in data["models"].items() if m not in bad}}
206
+ problems.append(f"In the price file {f}, {', '.join(bad)} {'is' if len(bad) == 1 else 'are'} not "
207
+ "a list of prices, so list prices were used for "
208
+ f"{'it' if len(bad) == 1 else 'them'}.")
192
209
  prices = _merge(prices, data)
193
210
  for m, r in (data.get("models") or {}).items():
194
211
  set_on = r.get("set_on") if isinstance(r, dict) else None
@@ -196,6 +213,8 @@ def load(extra_file: str | None = None, user_file=AUTO) -> dict:
196
213
  own.append(Path(f).name)
197
214
  if own:
198
215
  prices["own"] = own
216
+ if problems:
217
+ prices["own_problem"] = " ".join(problems)
199
218
  prices["from"] = src
200
219
  return prices
201
220
 
@@ -97,27 +97,44 @@ def _pieces(b: bytes, out: dict, depth: int = 0) -> None:
97
97
  _pieces(v, out, depth + 1)
98
98
 
99
99
 
100
- def _lines(b: bytes) -> set[str]:
101
- return {re.sub(r"^\d+: ", "", x).strip() for x in b.decode("utf-8", "replace").splitlines() if x.strip()}
100
+ _NUM = re.compile(r"^\d+: ")
102
101
 
103
102
 
104
- def _inside(small: bytes, big: bytes) -> bool:
105
- """A copy of the same text inside a bigger piece: the model sees a file with "12: " before every line, and the
106
- step also keeps the bare file. Every line of the small piece is in the big one."""
107
- if small in big:
108
- return True
109
- s = _lines(small)
110
- return bool(s) and len(s & _lines(big)) >= 0.9 * len(s)
103
+ def _lines(b: bytes) -> set[str]:
104
+ return {_NUM.sub("", x).strip() for x in b.decode("utf-8", "replace").splitlines() if x.strip()}
111
105
 
112
106
 
113
107
  def _content(rest: bytes, raw: str) -> tuple[int, str]:
114
108
  """(characters, fingerprint) of what a tool step returned, without the call's own arguments or the step's ids
115
- and times, so the same file read twice gets the same fingerprint."""
109
+ and times, so the same file read twice gets the same fingerprint.
110
+
111
+ A piece that is a copy of a bigger one counts once: it sits inside it, or 90% of its lines are lines of it (the
112
+ model sees a file with "12: " before every line, and the step also keeps the bare file). A step can hold
113
+ thousands of pieces, so each is split into lines once, an index finds the bigger pieces sharing its lines, and
114
+ one search over all bigger pieces (joined with a byte no text holds) replaces one search per piece."""
116
115
  found: dict[bytes, bytes] = {}
117
116
  _pieces(rest, found)
118
117
  found.pop(hashlib.sha1(raw.encode("utf-8", "replace")).digest(), None)
119
118
  big = sorted(found.items(), key=lambda kv: -len(kv[1]))
120
- keep = [(k, v) for i, (k, v) in enumerate(big) if not any(_inside(v, w) for _, w in big[:i])]
119
+ keep: list[tuple[bytes, bytes]] = []
120
+ joined, index = bytearray(), {} # every bigger piece so far; line -> the pieces that hold it
121
+ for i, (k, v) in enumerate(big):
122
+ s = _lines(v)
123
+ if b"\x00" in v:
124
+ copy = any(v in w for _, w in big[:i])
125
+ else:
126
+ copy = v in joined
127
+ if not copy and s:
128
+ shared: dict[int, int] = {}
129
+ for ln in s:
130
+ for j in index.get(ln, ()):
131
+ shared[j] = shared.get(j, 0) + 1
132
+ copy = any(n >= 0.9 * len(s) for n in shared.values())
133
+ if not copy:
134
+ keep.append((k, v))
135
+ joined += b"\x00" + v
136
+ for ln in s:
137
+ index.setdefault(ln, []).append(i)
121
138
  return sum(len(v) for _, v in keep), hashlib.sha1(b"".join(sorted(k for k, _ in keep))).hexdigest()[:16]
122
139
 
123
140
 
@@ -24,6 +24,7 @@ from pathlib import Path
24
24
 
25
25
  PUBLIC_ZIP = "https://github.com/kish21/sessioncost/archive/refs/heads/main.zip" # what the installers use
26
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
27
28
  WINDOWS = sys.platform == "win32"
28
29
 
29
30
 
@@ -55,6 +56,8 @@ def plan(home: Path | None = None, exe: str | None = None, here: Path | None = N
55
56
  if not in_plugin:
56
57
  if NPX_HOME in Path(exe).as_posix().lower(): # npx's own environment: npx installs the new one
57
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"))
58
61
  elif "/uv/tools/sessioncost/" in Path(exe).as_posix().lower() and which("uv"):
59
62
  steps.append(Step("Update SessionCost (installed with the install line)",
60
63
  [which("uv"), "pip", "install", "--quiet", "--python", exe, "--reinstall-package",
@@ -162,6 +165,8 @@ def kind(here: Path) -> str:
162
165
  for folder, name in ((".claude", "Claude Code plugin"), (".codex", "Codex plugin"), (".cursor", "Cursor plugin")):
163
166
  if f"/{folder}/plugins/" in p:
164
167
  return name
168
+ if EDITOR_HOME in p:
169
+ return "editor extension"
165
170
  return "npx" if NPX_HOME in p else "Python package"
166
171
 
167
172
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sessioncost
3
- Version: 1.2.0
3
+ Version: 1.2.2
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
@@ -22,6 +22,7 @@ sessioncost/guard_inventory.py
22
22
  sessioncost/guard_report.py
23
23
  sessioncost/guard_setup.py
24
24
  sessioncost/guard_store.py
25
+ sessioncost/guard_waste.py
25
26
  sessioncost/locate.py
26
27
  sessioncost/model.py
27
28
  sessioncost/names.py
File without changes
File without changes
File without changes
File without changes