sessioncost 1.2.1__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.1/sessioncost.egg-info → sessioncost-1.2.2}/PKG-INFO +1 -1
  2. {sessioncost-1.2.1 → sessioncost-1.2.2}/pyproject.toml +1 -1
  3. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/__init__.py +1 -1
  4. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixer.py +47 -30
  5. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixer_store.py +21 -0
  6. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/guard.py +15 -21
  7. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/guard_checks.py +0 -50
  8. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/guard_decide.py +1 -5
  9. sessioncost-1.2.2/sessioncost/guard_waste.py +81 -0
  10. {sessioncost-1.2.1 → sessioncost-1.2.2/sessioncost.egg-info}/PKG-INFO +1 -1
  11. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost.egg-info/SOURCES.txt +1 -0
  12. {sessioncost-1.2.1 → sessioncost-1.2.2}/LICENSE +0 -0
  13. {sessioncost-1.2.1 → sessioncost-1.2.2}/MANIFEST.in +0 -0
  14. {sessioncost-1.2.1 → sessioncost-1.2.2}/README.md +0 -0
  15. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/__main__.py +0 -0
  16. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/analyse.py +0 -0
  17. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/analyse_calls.py +0 -0
  18. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/analyse_lists.py +0 -0
  19. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/cli.py +0 -0
  20. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/cli_setup.py +0 -0
  21. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/editor.py +0 -0
  22. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixer_plan.py +0 -0
  23. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixes/__init__.py +0 -0
  24. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixes/big_results.py +0 -0
  25. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixes/cache_break.py +0 -0
  26. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixes/common.py +0 -0
  27. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixes/confirm_turns.py +0 -0
  28. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixes/error_loop.py +0 -0
  29. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixes/helper_polling.py +0 -0
  30. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixes/helper_rereads.py +0 -0
  31. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixes/images.py +0 -0
  32. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixes/long_chat.py +0 -0
  33. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixes/long_output.py +0 -0
  34. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixes/model_choice.py +0 -0
  35. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixes/overlap.py +0 -0
  36. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixes/repeated_reads.py +0 -0
  37. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixes/repeated_writes.py +0 -0
  38. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixes/reruns.py +0 -0
  39. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixes/stale_context.py +0 -0
  40. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixes/startup_bloat.py +0 -0
  41. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixes/unused_builtins.py +0 -0
  42. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/fixes/unused_tools.py +0 -0
  43. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/guard_agents.py +0 -0
  44. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/guard_auto.py +0 -0
  45. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/guard_inventory.py +0 -0
  46. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/guard_report.py +0 -0
  47. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/guard_setup.py +0 -0
  48. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/guard_store.py +0 -0
  49. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/locate.py +0 -0
  50. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/model.py +0 -0
  51. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/names.py +0 -0
  52. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/practices.py +0 -0
  53. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/prices.json +0 -0
  54. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/prices.py +0 -0
  55. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/prices_cmd.py +0 -0
  56. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/readers/__init__.py +0 -0
  57. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/readers/_pb.py +0 -0
  58. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/readers/_util.py +0 -0
  59. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/readers/antigravity.py +0 -0
  60. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/readers/claude.py +0 -0
  61. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/readers/claude_text.py +0 -0
  62. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/readers/codex.py +0 -0
  63. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/readers/copilot.py +0 -0
  64. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/readers/cursor.py +0 -0
  65. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/readers/cursor_steps.py +0 -0
  66. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/readers/cursor_usage.py +0 -0
  67. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/readers/vscode_chat.py +0 -0
  68. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/report.py +0 -0
  69. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/report_board.html +0 -0
  70. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/risk_bypass.py +0 -0
  71. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/risk_patterns.py +0 -0
  72. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/risk_shell.py +0 -0
  73. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/risks.py +0 -0
  74. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/rules.py +0 -0
  75. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/sarif.py +0 -0
  76. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/serve.py +0 -0
  77. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/skill/SKILL.md +0 -0
  78. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/skill/liveguard.md +0 -0
  79. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/status.py +0 -0
  80. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/textflags.py +0 -0
  81. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/update.py +0 -0
  82. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost/zfile.py +0 -0
  83. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost.egg-info/dependency_links.txt +0 -0
  84. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost.egg-info/entry_points.txt +0 -0
  85. {sessioncost-1.2.1 → sessioncost-1.2.2}/sessioncost.egg-info/top_level.txt +0 -0
  86. {sessioncost-1.2.1 → 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.1
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.1"
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.1"
2
+ __version__ = "1.2.2"
@@ -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 "
@@ -315,13 +320,12 @@ def _one_line(items: list[dict], same: bool) -> str:
315
320
  # its own words, never "Shall I ...?": the agent may have asked its own question higher up the reply, and a bare
316
321
  # "yes" would answer either (owner, 2026-11-11). The command is named too, for those who prefer to type it.
317
322
  typed = "(or type /sessioncost fix)"
318
- 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 ""
319
324
  if not long:
320
- return f'{line} Say "{SAY_FIX}" {typed} to fix these.' if line else ""
321
- line = (line + " " if line else "💡 SessionCost: ") + long.get("line", "")
322
- if parts:
323
- return f'{line} Say "{SAY_FIX}" {typed} to fix these and write a handover, so you can start a fresh chat.'
324
- 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".')
325
329
 
326
330
 
327
331
  def _same_agent(hook_agent: str, note_agent: str) -> bool:
@@ -347,9 +351,12 @@ def tip(chat: str, cwd: str, prompt: str = "", start: bool = False, turn: str |
347
351
  "(keep only the ids they chose) and show the lines it prints. Otherwise ignore this.")
348
352
  st["pending"] = ""
349
353
  h = find_handover(cwd) if cwd else None
350
- if h and prompt and HANDOVER_ASK.search(prompt):
351
- out.append(f"The user wants to continue from the handover of an earlier chat: read "
352
- 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\".")
353
360
  elif h and start and time.time() - h.stat().st_mtime < CHAT_KEEP_S:
354
361
  out.append(f"A handover from an earlier chat in this project is at {h.as_posix()}. Read it "
355
362
  "only if the user asks to continue from it.")
@@ -365,30 +372,40 @@ def tip(chat: str, cwd: str, prompt: str = "", start: bool = False, turn: str |
365
372
  _seen(st, [i["id"] for i in items], note.get("context"))
366
373
  items, dirty = [], True
367
374
  if items:
368
- ids = ",".join(i["id"] for i in items)
369
375
  where = _q(Path(cwd).as_posix())
370
376
  of = f"{_q(str(note['chat']))} " if note.get("chat") else "" # the chat the list came from
371
- cmd = f"{run_cmd()} fix -y {of}--only {ids} --project {where}"
372
- 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 ""
373
380
  # chat-start text stays in the agent's context for the whole chat (Copilot, Cursor): said once, or the
374
381
  # agent ends every reply with it, even after the fix ran (owner, 2026-11-12)
375
382
  when = ("put this one line only at the end of your first reply in this chat and never repeat it in a "
376
383
  "later reply (also not after the fix ran or the user said no); in that first reply put it "
377
384
  if start else "end your reply with this one line, ")
378
- out.append(
379
- "SessionCost (fix auto is on) found token waste. Answer the user's message as usual first; when "
380
- f"all your work for it is done, {when}as written, as a quote block "
381
- "(begin it with \"> \"), as the very last thing in the reply, so the user sees it where the chat "
382
- f"stops:\n{_one_line(items, note.get('chat') == chat)}\n"
383
- "Put nothing after that line. Do not end that reply with a question of your own: the user answers this one first. "
384
- f"If the user asks what these are, run `{look}` and show what it prints. Only if the user says "
385
- f"\"{SAY_FIX}\" or \"{SAY_HANDOVER}\" (or \"fix these\", \"fix all\", \"fix the first one\": all, "
386
- f"or some), run `{cmd}` "
387
- "(keep only the ids they chose) and show the lines it prints. A bare \"yes\" answers your own "
388
- "question, not this line: do not run it then. If "
389
- "it asks you to write a handover, do it. If running it is blocked or refused (auto mode, for "
390
- "example), do not try another way: tell the user to type /sessioncost fix and answer yes there. "
391
- "If they say no, or say nothing about it, drop it. Never run it without their yes.")
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))
392
409
  _seen(st, [i["id"] for i in items], note.get("context"))
393
410
  st["last_tip"] = {"at": time.time(), "line": _one_line(items, note.get("chat") == chat)} # status.py
394
411
  st["lists"] = int(st.get("lists") or 0) + 1
@@ -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:
@@ -49,10 +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 (STATE_WAIT, _locked, _read, _write, append_log, guard_on, log_path, state_path, verify_log,
55
- verify_status)
56
56
 
57
57
  # Names other modules, tests and tools use as guard.<name>; they live in the guard_* modules above.
58
58
  __all__ = ["WHY", "_copilot_in", "_full", "_git", "_hooks_file", "_launch", "_locked", "_path_arg", "_read",
@@ -79,18 +79,13 @@ STALE_S = 2 * 24 * 3600 # a chat's state left behind (its end hook can be ca
79
79
 
80
80
  def _clear_stale() -> None:
81
81
  now = time.time()
82
- for p in home().glob("*.state.json"):
83
- try:
84
- if now - p.stat().st_mtime > STALE_S:
85
- p.unlink()
86
- except OSError:
87
- pass
88
- for p in home().glob("*.state.json.lock"): # a chat's lock, once its state is gone (ended, or stale above)
89
- try:
90
- if not p.with_suffix("").exists() and now - p.stat().st_mtime > STALE_S:
91
- p.unlink()
92
- except OSError:
93
- 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
94
89
 
95
90
 
96
91
  def on_session_start(inp: dict) -> dict | None:
@@ -363,6 +358,8 @@ def _run(event: str, inp: dict, agent: str) -> dict | None:
363
358
  return out
364
359
  if event == "post" and inp.get("_failed"): # a result that says it failed (agents without a failure hook)
365
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)
366
363
  return EVENTS[event](inp) if event in EVENTS else None
367
364
 
368
365
 
@@ -467,17 +464,14 @@ def main(argv: list[str] | None = None) -> int:
467
464
  # Agents send UTF-8 JSON; Windows Python would read the pipe as cp1252 and garble any non-English text
468
465
  raw = sys.stdin.buffer.read().decode("utf-8-sig", errors="replace") if sys.stdin else ""
469
466
  code, out = hook(argv[1], raw, agent)
470
- if out:
471
- sys.stdout.write(out)
467
+ sys.stdout.write(out)
472
468
  return code
473
469
  if argv[:1] == ["setup"] and len(argv) > 1:
474
470
  print(setup(argv[1]))
475
471
  return 0
476
472
  if argv[:1] == ["allow"]:
477
- if argv[1:2] in ([], ["--list"]):
478
- print(command("allow-list-rules", os.getcwd()))
479
- elif argv[1:2] == ["--clear"]:
480
- 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()))
481
475
  elif len(argv) >= 3:
482
476
  print(command("allow", os.getcwd(), rule=(argv[1], " ".join(argv[2:]))))
483
477
  else:
@@ -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)
@@ -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}}
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sessioncost
3
- Version: 1.2.1
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