ctxline 0.1.1__py3-none-any.whl

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.
ctxline/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.1"
ctxline/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from ctxline.cli import main
4
+
5
+ sys.exit(main())
ctxline/cli.py ADDED
@@ -0,0 +1,77 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import shlex
6
+ import shutil
7
+ import sys
8
+ import time
9
+ from pathlib import Path
10
+
11
+ from ctxline import __version__, settings
12
+ from ctxline.limits import current_limits
13
+ from ctxline.line import git_branch, render, section
14
+
15
+ USAGE = """usage: ctxline [install | uninstall | --version]
16
+
17
+ (piped JSON) print the status line for a Claude Code session
18
+ install make ctxline your Claude Code status line
19
+ uninstall remove it and restore the status line you had before
20
+ """
21
+
22
+ EPHEMERAL_MARKERS = ("/cache/uv/", "/.cache/uv/", "/archive-v")
23
+
24
+
25
+ def own_command() -> str:
26
+ on_path = shutil.which("ctxline")
27
+ executable = Path(on_path) if on_path else Path(sys.argv[0]).absolute()
28
+ return shlex.quote(str(executable))
29
+
30
+
31
+ def print_line() -> int:
32
+ try:
33
+ payload = json.load(sys.stdin)
34
+ except ValueError:
35
+ payload = {}
36
+ if not isinstance(payload, dict):
37
+ payload = {}
38
+ directory = section(payload, "workspace").get("current_dir") or payload.get("cwd")
39
+ color = not os.environ.get("NO_COLOR")
40
+ now = time.time()
41
+ print(render(payload, now, git_branch(directory), color, current_limits(payload, now)))
42
+ return 0
43
+
44
+
45
+ def run_install() -> int:
46
+ command = own_command()
47
+ if any(marker in command for marker in EPHEMERAL_MARKERS):
48
+ print("Install it for good first: uv tool install ctxline, then run ctxline install.", file=sys.stderr)
49
+ return 1
50
+ note = settings.install(command)
51
+ print(f"ctxline is now your status line ({settings.settings_path()}).")
52
+ if note:
53
+ print(note)
54
+ return 0
55
+
56
+
57
+ def main(argv: list[str] | None = None) -> int:
58
+ args = sys.argv[1:] if argv is None else argv
59
+ if not args:
60
+ if sys.stdin.isatty():
61
+ print(USAGE, end="")
62
+ return 0
63
+ try:
64
+ return print_line()
65
+ except Exception:
66
+ print("")
67
+ return 0
68
+ if args[0] == "install":
69
+ return run_install()
70
+ if args[0] == "uninstall":
71
+ print(settings.uninstall())
72
+ return 0
73
+ if args[0] in ("--version", "-V"):
74
+ print(__version__)
75
+ return 0
76
+ print(USAGE, end="", file=sys.stderr)
77
+ return 2
ctxline/limits.py ADDED
@@ -0,0 +1,26 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ from ctxline.line import has_limits, section
7
+ from ctxline.settings import claude_home, write_json
8
+
9
+
10
+ def memory_path() -> Path:
11
+ return claude_home() / "cache" / "ctxline-limits.json"
12
+
13
+
14
+ def current_limits(payload: dict, now: float) -> dict:
15
+ live = section(payload, "rate_limits")
16
+ if has_limits(live):
17
+ try:
18
+ write_json(memory_path(), live)
19
+ except OSError:
20
+ pass
21
+ return live
22
+ try:
23
+ remembered = json.loads(memory_path().read_text())
24
+ except (OSError, ValueError):
25
+ return live
26
+ return remembered if isinstance(remembered, dict) else live
ctxline/line.py ADDED
@@ -0,0 +1,153 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from pathlib import Path
5
+
6
+ SEPARATOR = " · "
7
+ RESET = "\033[0m"
8
+ DIM = "\033[2m"
9
+ CYAN = "\033[36m"
10
+ GREEN = "\033[32m"
11
+ YELLOW = "\033[33m"
12
+ RED = "\033[31m"
13
+
14
+ LIMIT_LABELS = (("five_hour", "5h"), ("seven_day", "wk"))
15
+
16
+
17
+ def round_half_up(value: float) -> int:
18
+ return math.floor(value + 0.5)
19
+
20
+
21
+ def paint(code: str, text: str, color: bool) -> str:
22
+ return f"{code}{text}{RESET}" if color else text
23
+
24
+
25
+ def tone_for(remaining_pct: float) -> str:
26
+ if remaining_pct <= 10:
27
+ return RED
28
+ if remaining_pct <= 25:
29
+ return YELLOW
30
+ return GREEN
31
+
32
+
33
+ def time_until(seconds: float) -> str:
34
+ if seconds <= 60:
35
+ return "now"
36
+ minutes = int(seconds // 60)
37
+ if minutes >= 24 * 60:
38
+ return f"{minutes // (24 * 60)}d"
39
+ if minutes >= 60:
40
+ return f"{minutes // 60}h"
41
+ return f"{minutes}m"
42
+
43
+
44
+ def token_amount(tokens: int) -> str:
45
+ if tokens < 1_000_000:
46
+ return f"{round_half_up(tokens / 1000)}k"
47
+ return f"{round_half_up(tokens / 10_000) / 100:.2f}M"
48
+
49
+
50
+ def is_number(value: object) -> bool:
51
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
52
+
53
+
54
+ def section(payload: dict, key: str) -> dict:
55
+ value = payload.get(key)
56
+ return value if isinstance(value, dict) else {}
57
+
58
+
59
+ def git_branch(directory: str | None) -> str | None:
60
+ if not directory:
61
+ return None
62
+ for folder in (Path(directory), *Path(directory).parents):
63
+ dot_git = folder / ".git"
64
+ try:
65
+ if dot_git.is_file():
66
+ pointer = dot_git.read_text().strip()
67
+ if not pointer.startswith("gitdir:"):
68
+ return None
69
+ dot_git = (folder / pointer.removeprefix("gitdir:").strip()).resolve()
70
+ if not dot_git.is_dir():
71
+ continue
72
+ head = (dot_git / "HEAD").read_text().strip()
73
+ except OSError:
74
+ return None
75
+ if head.startswith("ref: refs/heads/"):
76
+ return head.removeprefix("ref: refs/heads/")
77
+ return head[:7] or None
78
+ return None
79
+
80
+
81
+ def session_fields(payload: dict, branch: str | None, color: bool) -> list[str]:
82
+ fields = []
83
+ model = section(payload, "model").get("display_name")
84
+ if model:
85
+ fields.append(paint(CYAN, model, color))
86
+ directory = section(payload, "workspace").get("current_dir") or payload.get("cwd")
87
+ if directory:
88
+ place = Path(directory).name or directory
89
+ fields.append(paint(DIM, f"{place} ⑂ {branch}" if branch else place, color))
90
+ return fields
91
+
92
+
93
+ def context_field(payload: dict, color: bool) -> str | None:
94
+ window = section(payload, "context_window")
95
+ tokens = sum(
96
+ window.get(key) for key in ("total_input_tokens", "total_output_tokens") if is_number(window.get(key))
97
+ )
98
+ used = window.get("used_percentage")
99
+ size = window.get("context_window_size")
100
+ if not is_number(used):
101
+ if not tokens or not is_number(size) or size <= 0:
102
+ return None
103
+ used = tokens / size * 100
104
+ text = f"ctx {token_amount(tokens)} ({round_half_up(used)}%)" if tokens else f"ctx {round_half_up(used)}%"
105
+ return paint(tone_for(100 - used), text, color)
106
+
107
+
108
+ def is_live(window: dict, now: float) -> bool:
109
+ resets_at = window.get("resets_at")
110
+ return is_number(window.get("used_percentage")) and (not is_number(resets_at) or resets_at > now)
111
+
112
+
113
+ def has_limits(limits: dict) -> bool:
114
+ return any(is_number(section(limits, key).get("used_percentage")) for key, _ in LIMIT_LABELS)
115
+
116
+
117
+ def limit_fields(limits: dict, now: float, color: bool) -> list[str]:
118
+ if not has_limits(limits):
119
+ return []
120
+ fields = []
121
+ for key, label in LIMIT_LABELS:
122
+ window = section(limits, key)
123
+ if not is_live(window, now):
124
+ fields.append(paint(GREEN, f"{label} 0%", color))
125
+ continue
126
+ used = window["used_percentage"]
127
+ text = paint(tone_for(100 - used), f"{label} {round_half_up(used)}%", color)
128
+ resets_at = window.get("resets_at")
129
+ if is_number(resets_at):
130
+ text += paint(DIM, f"({time_until(resets_at - now)})", color)
131
+ fields.append(text)
132
+ return fields
133
+
134
+
135
+ def cost_field(payload: dict, color: bool) -> str | None:
136
+ cost = section(payload, "cost").get("total_cost_usd")
137
+ if not is_number(cost):
138
+ return None
139
+ return paint(DIM, f"${round_half_up(cost * 100) / 100:,.2f}", color)
140
+
141
+
142
+ def render(
143
+ payload: dict,
144
+ now: float,
145
+ branch: str | None = None,
146
+ color: bool = True,
147
+ limits: dict | None = None,
148
+ ) -> str:
149
+ fields = session_fields(payload, branch, color)
150
+ fields.append(context_field(payload, color))
151
+ fields.extend(limit_fields(section(payload, "rate_limits") if limits is None else limits, now, color))
152
+ fields.append(cost_field(payload, color))
153
+ return SEPARATOR.join(field for field in fields if field)
ctxline/settings.py ADDED
@@ -0,0 +1,69 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+
7
+ REFRESH_SECONDS = 60
8
+
9
+
10
+ def claude_home() -> Path:
11
+ return Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude")
12
+
13
+
14
+ def settings_path() -> Path:
15
+ return claude_home() / "settings.json"
16
+
17
+
18
+ def previous_path() -> Path:
19
+ return claude_home() / "ctxline-previous.json"
20
+
21
+
22
+ def read_json(path: Path) -> dict:
23
+ if not path.is_file():
24
+ return {}
25
+ return json.loads(path.read_text() or "{}")
26
+
27
+
28
+ def write_json(path: Path, data: dict) -> None:
29
+ path.parent.mkdir(parents=True, exist_ok=True)
30
+ staging = path.with_name(f"{path.name}.{os.getpid()}.tmp")
31
+ staging.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n")
32
+ staging.replace(path)
33
+
34
+
35
+ def is_ours(status_line: object) -> bool:
36
+ return isinstance(status_line, dict) and "ctxline" in str(status_line.get("command", ""))
37
+
38
+
39
+ def install(command: str) -> str:
40
+ settings = read_json(settings_path())
41
+ current = settings.get("statusLine")
42
+ if current and not is_ours(current):
43
+ write_json(previous_path(), {"statusLine": current})
44
+ settings["statusLine"] = {
45
+ "type": "command",
46
+ "command": command,
47
+ "padding": 0,
48
+ "refreshInterval": REFRESH_SECONDS,
49
+ }
50
+ write_json(settings_path(), settings)
51
+ if current and not is_ours(current):
52
+ return f"Saved your old status line to {previous_path()}. `ctxline uninstall` puts it back."
53
+ return ""
54
+
55
+
56
+ def uninstall() -> str:
57
+ settings = read_json(settings_path())
58
+ if not is_ours(settings.get("statusLine")):
59
+ return "ctxline isn't your status line, so nothing changed."
60
+ previous = read_json(previous_path()).get("statusLine")
61
+ if previous:
62
+ settings["statusLine"] = previous
63
+ message = "Put your previous status line back."
64
+ else:
65
+ settings.pop("statusLine")
66
+ message = "Removed the ctxline status line."
67
+ write_json(settings_path(), settings)
68
+ previous_path().unlink(missing_ok=True)
69
+ return message
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.5
2
+ Name: ctxline
3
+ Version: 0.1.1
4
+ Summary: A Claude Code status line for context and usage limits
5
+ Project-URL: Repository, https://github.com/ericwafula/ctxline
6
+ Author: Eric Wafula
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.9
10
+ Description-Content-Type: text/markdown
11
+
12
+ # ctxline
13
+
14
+ A status line for Claude Code that shows how much context you've used and how close you are to your usage limits.
15
+
16
+ ```
17
+ Opus 5.5 · stovetime ⑂ main · ctx 186k (19%) · 5h 8%(3h) · wk 28%(2d) · $8.30
18
+ ```
19
+
20
+ | Field | Meaning |
21
+ |---|---|
22
+ | `Opus 5.5` | The model |
23
+ | `stovetime ⑂ main` | Folder and git branch |
24
+ | `ctx 186k (19%)` | Tokens in the context window, and the share of the window they fill |
25
+ | `5h 8%(3h)` | Share of your 5-hour limit used, and time until it resets |
26
+ | `wk 28%(2d)` | Same for the weekly limit |
27
+ | `$8.30` | What the session would cost at API prices |
28
+
29
+ Each field turns yellow when a quarter or less is left, and red at a tenth. Fields with no data yet are left out. The limits only appear on Pro, Max and Ultra plans, after the first reply in a session.
30
+
31
+ It uses no tokens. Claude Code runs it on your machine and sends it the session details as JSON. Nothing it prints goes to the model.
32
+
33
+ ## Install
34
+
35
+ With uv:
36
+
37
+ ```bash
38
+ uv tool install ctxline
39
+ ctxline install
40
+ ```
41
+
42
+ With pipx:
43
+
44
+ ```bash
45
+ pipx install ctxline
46
+ ctxline install
47
+ ```
48
+
49
+ With Homebrew:
50
+
51
+ ```bash
52
+ brew install ericwafula/tools/ctxline
53
+ ctxline install
54
+ ```
55
+
56
+ With Node 18 or newer:
57
+
58
+ ```bash
59
+ npm install -g github:ericwafula/ctxline
60
+ ctxline install
61
+ ```
62
+
63
+ `ctxline install` adds a `statusLine` entry to `~/.claude/settings.json`, using the full path to the command so it works from the desktop app too. If you already had a status line, it's saved to `~/.claude/ctxline-previous.json`.
64
+
65
+ The Node version records the path of the Node it was installed with. If you remove that Node version (with nvm, say), run `ctxline install` again.
66
+
67
+ ## Remove
68
+
69
+ ```bash
70
+ ctxline uninstall
71
+ ```
72
+
73
+ This puts back the status line you had before, or removes the entry if there wasn't one. Then uninstall the package with `uv tool uninstall ctxline`, `pipx uninstall ctxline`, `brew uninstall ctxline` or `npm uninstall -g ctxline`.
74
+
75
+ ## Try it without Claude Code
76
+
77
+ ```bash
78
+ echo '{"model":{"display_name":"Opus"},"context_window":{"total_input_tokens":42000,"context_window_size":200000}}' | ctxline
79
+ ```
80
+
81
+ Set `NO_COLOR=1` for plain text. `CLAUDE_CONFIG_DIR` changes where settings are written.
82
+
83
+ ## Development
84
+
85
+ The Python version lives in `src/ctxline`, the Node version in `lib` and `bin`. Both are tested against the same cases in `tests/fixtures/cases.json`, so they print identical lines.
86
+
87
+ ```bash
88
+ python3 -m unittest discover -s tests
89
+ ```
90
+
91
+ ```bash
92
+ npm test
93
+ ```
@@ -0,0 +1,11 @@
1
+ ctxline/__init__.py,sha256=rnObPjuBcEStqSO0S6gsdS_ot8ITOQjVj_-P1LUUYpg,22
2
+ ctxline/__main__.py,sha256=QZLLJZXafmQinnVVkRpWvRiMJFkTSiCNBX0Fzb0ZKFI,59
3
+ ctxline/cli.py,sha256=BkCSOx2XgY9iHTcrzPEEUQTxD_-NxV6v67OrLHrAysI,2213
4
+ ctxline/limits.py,sha256=5bL8HYskvWO7FPXkfgFY1SJAug4o_1o0pQuEd_o0VOA,689
5
+ ctxline/line.py,sha256=Nh9tnFUvrR6ssziaVm_QEFY1c7taZZUbQQFcq2LDW1I,4885
6
+ ctxline/settings.py,sha256=jUl7AnSmffD8aZIpiDqu5v5E7IpM3FZ9EmUjHiMP73I,2046
7
+ ctxline-0.1.1.dist-info/METADATA,sha256=26P3g_AMFpvCCQWl8B0YijOPJcycxiR7biUKRuiNWuE,2740
8
+ ctxline-0.1.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ ctxline-0.1.1.dist-info/entry_points.txt,sha256=udUBkJtbLH2k0SGjwv3N819aaH8D5V0JArI9XC01dfo,45
10
+ ctxline-0.1.1.dist-info/licenses/LICENSE,sha256=lbhZqN9uLMpIXQX5_Bqhh8Kqbd7fpspg-Ny4H0mEGXE,1068
11
+ ctxline-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ctxline = ctxline.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Eric Wafula
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.