@alexgreensh/token-optimizer 0.0.0-stage → 5.13.50

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 (161) hide show
  1. package/.claude-plugin/marketplace.json +76 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/LICENSE +130 -0
  4. package/LICENSE-SMALL-BUSINESS.md +62 -0
  5. package/PRIVACY.md +200 -0
  6. package/README.md +13 -2
  7. package/hooks/codex-hooks.json +4 -0
  8. package/hooks/hooks.json +182 -0
  9. package/hooks/module_runner.py +149 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +776 -0
  13. package/hooks/sessionstart_runner.py +629 -0
  14. package/hooks/stop_runner.py +408 -0
  15. package/hooks/userpromptsubmit_runner.py +722 -0
  16. package/hooks/windows-launcher.py +163 -0
  17. package/install-cloud.sh +23 -0
  18. package/package.json +29 -4
  19. package/skills/fleet-auditor/SKILL.md +150 -0
  20. package/skills/fleet-auditor/references/fleet-systems.md +167 -0
  21. package/skills/fleet-auditor/references/report-template.md +50 -0
  22. package/skills/fleet-auditor/references/waste-patterns.md +126 -0
  23. package/skills/fleet-auditor/scripts/fleet.py +3612 -0
  24. package/skills/fleet-auditor/scripts/shared.py +277 -0
  25. package/skills/resume-checkpoint/SKILL.md +52 -0
  26. package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
  27. package/skills/token-coach/SKILL.md +129 -0
  28. package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
  29. package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
  30. package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
  31. package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
  32. package/skills/token-coach/references/agentic-systems.md +147 -0
  33. package/skills/token-coach/references/coach-patterns.md +120 -0
  34. package/skills/token-coach/references/coaching-scripts.md +146 -0
  35. package/skills/token-coach/references/deterministic-stages.md +102 -0
  36. package/skills/token-coach/references/keepwarm-consent.md +48 -0
  37. package/skills/token-coach/references/quick-reference.md +155 -0
  38. package/skills/token-dashboard/SKILL.md +72 -0
  39. package/skills/token-optimizer/SKILL.md +150 -0
  40. package/skills/token-optimizer/assets/dashboard.html +7251 -0
  41. package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
  42. package/skills/token-optimizer/examples/hooks-starter.json +179 -0
  43. package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
  44. package/skills/token-optimizer/pricing/prices.json +695 -0
  45. package/skills/token-optimizer/references/agent-prompts.md +687 -0
  46. package/skills/token-optimizer/references/cli-reference.md +92 -0
  47. package/skills/token-optimizer/references/codex-workflow.md +188 -0
  48. package/skills/token-optimizer/references/cursor-workflow.md +74 -0
  49. package/skills/token-optimizer/references/error-recovery.md +37 -0
  50. package/skills/token-optimizer/references/implementation-playbook.md +416 -0
  51. package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
  52. package/skills/token-optimizer/references/opencode-workflow.md +72 -0
  53. package/skills/token-optimizer/references/optimization-checklist.md +714 -0
  54. package/skills/token-optimizer/references/phase0-setup.md +142 -0
  55. package/skills/token-optimizer/references/presentation-workflow.md +72 -0
  56. package/skills/token-optimizer/references/session-continuity.md +19 -0
  57. package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
  58. package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
  59. package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
  60. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
  61. package/skills/token-optimizer/scripts/antigravity_install.py +376 -0
  62. package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
  63. package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
  64. package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
  65. package/skills/token-optimizer/scripts/archive_result.py +1725 -0
  66. package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
  67. package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
  68. package/skills/token-optimizer/scripts/bash_hook.py +61 -0
  69. package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
  70. package/skills/token-optimizer/scripts/benchmark.py +1765 -0
  71. package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
  72. package/skills/token-optimizer/scripts/cloud_kit.py +991 -0
  73. package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
  74. package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
  75. package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
  76. package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
  77. package/skills/token-optimizer/scripts/codex_install.py +810 -0
  78. package/skills/token-optimizer/scripts/codex_io.py +119 -0
  79. package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
  80. package/skills/token-optimizer/scripts/codex_models.py +34 -0
  81. package/skills/token-optimizer/scripts/codex_session.py +1186 -0
  82. package/skills/token-optimizer/scripts/codex_state.py +707 -0
  83. package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
  84. package/skills/token-optimizer/scripts/command_filters.py +386 -0
  85. package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
  86. package/skills/token-optimizer/scripts/compression_log.py +230 -0
  87. package/skills/token-optimizer/scripts/context_intel.py +331 -0
  88. package/skills/token-optimizer/scripts/context_pressure.py +115 -0
  89. package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
  90. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
  91. package/skills/token-optimizer/scripts/copilot_install.py +277 -0
  92. package/skills/token-optimizer/scripts/copilot_session.py +496 -0
  93. package/skills/token-optimizer/scripts/copilot_state.py +569 -0
  94. package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
  95. package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
  96. package/skills/token-optimizer/scripts/cowork_install.py +380 -0
  97. package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
  98. package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
  99. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
  100. package/skills/token-optimizer/scripts/cursor_install.py +423 -0
  101. package/skills/token-optimizer/scripts/cursor_session.py +303 -0
  102. package/skills/token-optimizer/scripts/cursor_state.py +348 -0
  103. package/skills/token-optimizer/scripts/delta_diff.py +110 -0
  104. package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
  105. package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
  106. package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
  107. package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
  108. package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
  109. package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
  110. package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
  111. package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
  112. package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
  113. package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
  114. package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
  115. package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
  116. package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
  117. package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
  118. package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
  119. package/skills/token-optimizer/scripts/devin_compress.py +790 -0
  120. package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
  121. package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
  122. package/skills/token-optimizer/scripts/devin_install.py +1086 -0
  123. package/skills/token-optimizer/scripts/devin_source.py +119 -0
  124. package/skills/token-optimizer/scripts/devin_state.py +330 -0
  125. package/skills/token-optimizer/scripts/devin_verify.py +67 -0
  126. package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
  127. package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
  128. package/skills/token-optimizer/scripts/grok_install.py +397 -0
  129. package/skills/token-optimizer/scripts/grok_session.py +317 -0
  130. package/skills/token-optimizer/scripts/grok_state.py +299 -0
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
  132. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
  133. package/skills/token-optimizer/scripts/hermes_install.py +668 -0
  134. package/skills/token-optimizer/scripts/hermes_session.py +691 -0
  135. package/skills/token-optimizer/scripts/hermes_state.py +448 -0
  136. package/skills/token-optimizer/scripts/hook_io.py +120 -0
  137. package/skills/token-optimizer/scripts/hook_runtime.py +713 -0
  138. package/skills/token-optimizer/scripts/injection.py +156 -0
  139. package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
  140. package/skills/token-optimizer/scripts/measure.py +58739 -0
  141. package/skills/token-optimizer/scripts/outline.py +53 -0
  142. package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
  143. package/skills/token-optimizer/scripts/plugin_env.py +562 -0
  144. package/skills/token-optimizer/scripts/py_trust.py +80 -0
  145. package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
  146. package/skills/token-optimizer/scripts/read_cache.py +2489 -0
  147. package/skills/token-optimizer/scripts/recovery_output.py +110 -0
  148. package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
  149. package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
  150. package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
  151. package/skills/token-optimizer/scripts/runtime_env.py +1893 -0
  152. package/skills/token-optimizer/scripts/session_store.py +979 -0
  153. package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
  154. package/skills/token-optimizer/scripts/statusline.js +660 -0
  155. package/skills/token-optimizer/scripts/structure_map.py +2880 -0
  156. package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
  157. package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
  158. package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
  159. package/skills/token-optimizer/scripts/token_estimate.py +80 -0
  160. package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
  161. package/skills/token-optimizer/scripts/utf8_io.py +219 -0
@@ -0,0 +1,303 @@
1
+ #!/usr/bin/env python3
2
+ """Manage Token Optimizer's Codex CLI status line config.
3
+
4
+ Codex v0.131+ ships a native ``[tui].status_line`` mechanism (blended token
5
+ count, permissions, context). Token Optimizer does NOT add a separate status
6
+ bar; it configures that same native mechanism with a token-aware item set
7
+ (context-remaining / context-used / used-tokens alongside model and git info).
8
+
9
+ Because it writes the user's native config, it must never silently clobber a
10
+ hand-tuned ``[tui]`` block: an existing ``status_line``/``terminal_title`` is
11
+ preserved and the install errors unless ``--force`` is given, which comments the
12
+ originals out rather than deleting them.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import json
19
+ import re
20
+ import sys
21
+ from pathlib import Path
22
+
23
+ import codex_io
24
+ from runtime_env import codex_home
25
+
26
+ MANAGED_BEGIN = "# BEGIN token-optimizer status line"
27
+ MANAGED_END = "# END token-optimizer status line"
28
+ STATUS_ITEMS = [
29
+ "model-with-reasoning",
30
+ "fast-mode",
31
+ "context-remaining",
32
+ "context-used",
33
+ "used-tokens",
34
+ "git-branch",
35
+ "current-dir",
36
+ ]
37
+ TERMINAL_TITLE_ITEMS = [
38
+ "thread-title",
39
+ "context-remaining",
40
+ "git-branch",
41
+ ]
42
+ TUI_HEADER_RE = re.compile(r"(?m)^[ \t]*\[tui\][ \t]*(?:#.*)?$")
43
+ TABLE_HEADER_RE = re.compile(r"(?m)^[ \t]*\[[^\]\n]+\][ \t]*(?:#.*)?$")
44
+ STATUS_LINE_RE = re.compile(r"(?m)^[ \t]*status_line[ \t]*=")
45
+ TERMINAL_TITLE_RE = re.compile(r"(?m)^[ \t]*terminal_title[ \t]*=")
46
+ SETTING_LINE_RE = re.compile(r"(?m)^([ \t]*)(status_line|terminal_title)([ \t]*=.*)$")
47
+ # Lines Token Optimizer commented out on a --force install. The install writes
48
+ # ``<indent># replaced by Token Optimizer: <original line>``; uninstall restores
49
+ # the original by stripping that prefix. Scoped to status_line/terminal_title
50
+ # only so the compact-prompt uninstaller's commented lines are untouched.
51
+ _TO_COMMENT_PREFIX_RE = re.compile(
52
+ r"(?m)^([ \t]*)# replaced by Token Optimizer: ([ \t]*(?:status_line|terminal_title)[ \t]*=.*)$"
53
+ )
54
+ # Consume the single blank-line separator install inserts before the block so
55
+ # uninstall is byte-faithful (mirrors codex_compact_prompt._MANAGED_BLOCK_RE).
56
+ _MANAGED_BLOCK_RE = re.compile(
57
+ rf"(?ms)\n?^{re.escape(MANAGED_BEGIN)}.*?^{re.escape(MANAGED_END)}\n?"
58
+ )
59
+
60
+
61
+ def _config_path() -> Path:
62
+ return codex_home() / "config.toml"
63
+
64
+
65
+ def _managed_block() -> str:
66
+ status = json.dumps(STATUS_ITEMS)
67
+ title = json.dumps(TERMINAL_TITLE_ITEMS)
68
+ return "\n".join(
69
+ [
70
+ MANAGED_BEGIN,
71
+ f"status_line = {status}",
72
+ f"terminal_title = {title}",
73
+ MANAGED_END,
74
+ "",
75
+ ]
76
+ )
77
+
78
+
79
+ def _tui_span(text: str) -> tuple[int, int, int] | None:
80
+ match = TUI_HEADER_RE.search(text)
81
+ if not match:
82
+ return None
83
+ next_match = TABLE_HEADER_RE.search(text, match.end())
84
+ end = next_match.start() if next_match else len(text)
85
+ return match.start(), match.end(), end
86
+
87
+
88
+ def _comment_out_existing_settings(tui_body: str) -> str:
89
+ return SETTING_LINE_RE.sub(r"\1# replaced by Token Optimizer: \2\3", tui_body)
90
+
91
+
92
+ def _replace_or_append_config(config_text: str, *, force: bool) -> tuple[str, str]:
93
+ block = _managed_block()
94
+ managed_re = re.compile(rf"(?ms)^{re.escape(MANAGED_BEGIN)}.*?^{re.escape(MANAGED_END)}\n?")
95
+ if managed_re.search(config_text):
96
+ return managed_re.sub(block, config_text), "updated"
97
+
98
+ span = _tui_span(config_text)
99
+ if span is None:
100
+ suffix = "" if not config_text or config_text.endswith("\n") else "\n"
101
+ return config_text + suffix + "\n[tui]\n" + block, "installed"
102
+
103
+ _, header_end, table_end = span
104
+ tui_body = config_text[header_end:table_end]
105
+ has_status = STATUS_LINE_RE.search(tui_body)
106
+ has_title = TERMINAL_TITLE_RE.search(tui_body)
107
+ if (has_status or has_title) and not force:
108
+ raise ValueError(
109
+ "config.toml already defines a native [tui] status_line/terminal_title "
110
+ "(Codex v0.131+). Leaving it untouched; rerun with --force to replace it "
111
+ "with Token Optimizer's token-aware items (the originals are commented, not deleted)."
112
+ )
113
+ if has_status or has_title:
114
+ tui_body = _comment_out_existing_settings(tui_body)
115
+
116
+ updated_table = config_text[:header_end] + "\n" + block + tui_body
117
+ return updated_table + config_text[table_end:], "installed"
118
+
119
+
120
+ def plan_install(force: bool = False) -> dict[str, str | bool | list[str]]:
121
+ """Validate a Codex CLI status-line install without writing files."""
122
+ config_path = _config_path()
123
+ codex_io.validate_codex_path(config_path, codex_home())
124
+ try:
125
+ config_text = config_path.read_text(encoding="utf-8")
126
+ except (OSError, UnicodeDecodeError):
127
+ config_text = ""
128
+ _, action = _replace_or_append_config(config_text, force=force)
129
+ return {
130
+ "action": action,
131
+ "config_path": str(config_path),
132
+ "would_create_config": not config_path.exists(),
133
+ "status_line": STATUS_ITEMS,
134
+ "terminal_title": TERMINAL_TITLE_ITEMS,
135
+ }
136
+
137
+
138
+ def install(force: bool = False) -> str:
139
+ home = codex_home()
140
+ config_path = codex_io.ensure_codex_child(home, "config.toml")
141
+ try:
142
+ config_text, crlf = codex_io.read_config_text(config_path)
143
+ except (OSError, UnicodeDecodeError):
144
+ config_text, crlf = "", False
145
+ updated, action = _replace_or_append_config(config_text, force=force)
146
+ codex_io.atomic_write(config_path, updated, crlf=crlf)
147
+ return action
148
+
149
+
150
+ def _strip_managed_block(config_text: str) -> tuple[str, bool]:
151
+ """Remove the Token Optimizer status-line managed block; return (text, removed?)."""
152
+ new, n = _MANAGED_BLOCK_RE.subn("", config_text)
153
+ return new, n > 0
154
+
155
+
156
+ def _restore_commented_settings(config_text: str) -> tuple[str, int]:
157
+ """Uncomment status_line/terminal_title lines Token Optimizer commented out."""
158
+ new, n = _TO_COMMENT_PREFIX_RE.subn(r"\1\2", config_text)
159
+ return new, n
160
+
161
+
162
+ def _drop_empty_tui_header(config_text: str) -> str:
163
+ """Remove a ``[tui]`` header left empty after stripping the managed block.
164
+
165
+ When Token Optimizer installed into a config that had no ``[tui]`` table,
166
+ it appended ``[tui]`` + the managed block. After stripping the block, the
167
+ bare ``[tui]`` header is TO's own residue — remove it only when the table
168
+ body is empty (no key=value lines, no other content). A user-populated
169
+ ``[tui]`` table is never touched.
170
+ """
171
+ span = _tui_span(config_text)
172
+ if span is None:
173
+ return config_text
174
+ start, header_end, table_end = span
175
+ body = config_text[header_end:table_end]
176
+ # Body is significant if it contains any non-whitespace line, including
177
+ # comments — user comments are user content and must not be orphaned by
178
+ # dropping the [tui] header above them (contradicts the docstring promise
179
+ # that "a user-populated [tui] table is never touched").
180
+ significant = any(
181
+ ln.strip()
182
+ for ln in body.splitlines()
183
+ )
184
+ if significant:
185
+ return config_text
186
+ # Drop the empty [tui] header and its trailing blank lines.
187
+ before = config_text[:start]
188
+ after = config_text[table_end:]
189
+ # Collapse multiple blank lines left behind to a single separator. When the
190
+ # [tui] header was at EOF (after is blank), still preserve the trailing
191
+ # newline of the preceding content so the round-trip is byte-faithful.
192
+ sep = "\n\n" if before.strip() and after.strip() else ("\n" if before.strip() else "")
193
+ return before.rstrip("\n") + sep + after.lstrip("\n")
194
+
195
+
196
+ def plan_uninstall() -> dict[str, str | bool | list[str]]:
197
+ """Validate a status-line uninstall without writing files."""
198
+ config_path = _config_path()
199
+ codex_io.validate_codex_path(config_path, codex_home())
200
+ try:
201
+ config_text = config_path.read_text(encoding="utf-8")
202
+ except (OSError, UnicodeDecodeError):
203
+ config_text = ""
204
+ stripped, block_removed = _strip_managed_block(config_text)
205
+ stripped, restored = _restore_commented_settings(stripped)
206
+ return {
207
+ "action": "removed" if (block_removed or restored) else "noop",
208
+ "config_path": str(config_path),
209
+ "would_remove_config_block": block_removed,
210
+ "would_restore_commented": restored,
211
+ "would_drop_empty_tui_header": _drop_empty_tui_header(stripped) != stripped,
212
+ }
213
+
214
+
215
+ def uninstall() -> str:
216
+ """Remove Token Optimizer's ``[tui]`` status-line block from config.toml.
217
+
218
+ Reverses ``install``: strips the ``# BEGIN/END token-optimizer status
219
+ line`` managed block, uncomments any ``status_line``/``terminal_title``
220
+ settings Token Optimizer commented out on a ``--force`` install, and
221
+ removes a ``[tui]`` header that Token Optimizer added if the table is
222
+ left empty. User-authored ``[tui]`` content is never touched. Idempotent.
223
+ """
224
+ home = codex_home()
225
+ config_path = codex_io.ensure_codex_child(home, "config.toml")
226
+ try:
227
+ config_text, crlf = codex_io.read_config_text(config_path)
228
+ except (OSError, UnicodeDecodeError):
229
+ return "noop"
230
+ updated, block_removed = _strip_managed_block(config_text)
231
+ updated, _ = _restore_commented_settings(updated)
232
+ updated = _drop_empty_tui_header(updated)
233
+ if updated != config_text:
234
+ codex_io.atomic_write(config_path, updated, crlf=crlf)
235
+ return "removed"
236
+ return "noop"
237
+
238
+
239
+ def status() -> str:
240
+ config_path = _config_path()
241
+ if not config_path.exists():
242
+ return f"not configured: {config_path} not found"
243
+ try:
244
+ text = config_path.read_text(encoding="utf-8")
245
+ except (OSError, UnicodeDecodeError):
246
+ return f"not configured: {config_path} unreadable"
247
+ if MANAGED_BEGIN in text and MANAGED_END in text:
248
+ return "configured: Token Optimizer status line"
249
+ span = _tui_span(text)
250
+ if span is None:
251
+ return "not configured"
252
+ _, header_end, table_end = span
253
+ tui_body = text[header_end:table_end]
254
+ if STATUS_LINE_RE.search(tui_body) or TERMINAL_TITLE_RE.search(tui_body):
255
+ return "configured: custom Codex TUI status line"
256
+ return "not configured"
257
+
258
+
259
+ # NOTE (D4): a per-session ``resumable-<sid>.json`` flag is written by the
260
+ # SessionStart hook (measure._write_resumable_flag) and rendered as a
261
+ # ``⤸resumable`` token by the Claude statusline (statusline.js reads the flag).
262
+ # Codex has NO equivalent surface: its native ``[tui].status_line`` is a static
263
+ # list of built-in item names (STATUS_ITEMS) and cannot invoke a Python function
264
+ # per render, and the only per-turn Codex hook (UserPromptSubmit) is a BILLED
265
+ # ``additionalContext`` channel the UI-only signal must never touch. A
266
+ # ``resumable_signal`` accessor previously lived here but nothing could invoke
267
+ # it, so it was dead code; it has been removed rather than left as a false
268
+ # promise that Codex surfaces the signal. If Codex ever gains a command-driven
269
+ # status item, re-add an accessor and wire it into that item.
270
+
271
+
272
+ def build_parser() -> argparse.ArgumentParser:
273
+ parser = argparse.ArgumentParser(description="Manage Token Optimizer's Codex CLI status line.")
274
+ parser.add_argument("--install", action="store_true", help="Write Token Optimizer [tui] status_line settings")
275
+ parser.add_argument("--force", action="store_true", help="Replace existing [tui] status_line/terminal_title settings")
276
+ parser.add_argument("--status", action="store_true", help="Show current status-line config")
277
+ return parser
278
+
279
+
280
+ def main(argv: list[str] | None = None) -> int:
281
+ try:
282
+ from utf8_io import enforce_utf8_io
283
+ enforce_utf8_io()
284
+ except Exception:
285
+ pass
286
+ args = build_parser().parse_args(argv)
287
+ if args.status:
288
+ print(status())
289
+ return 0
290
+ if args.install:
291
+ try:
292
+ action = install(force=args.force)
293
+ except ValueError as exc:
294
+ print(f"[Token Optimizer] {exc}", file=sys.stderr)
295
+ return 1
296
+ print(f"[Token Optimizer] Codex status line {action}: {_config_path()}")
297
+ return 0
298
+ print(_managed_block())
299
+ return 0
300
+
301
+
302
+ if __name__ == "__main__":
303
+ raise SystemExit(main())
@@ -0,0 +1,386 @@
1
+ #!/usr/bin/env python3
2
+ """User-editable TOML command-filter schema + loader.
3
+
4
+ Lets a user opt NEW read-only commands into existing compression handlers
5
+ and exclude commands from compression, without weakening safety. The loader
6
+ is pure stdlib (tomllib with a no-tomllib fallback), performs no file writes,
7
+ and gates every ``add`` entry through ``_is_safe_add`` before it reaches the
8
+ effective allowlist.
9
+
10
+ File location: ``<runtime-home>/token-optimizer/command-filters.toml``
11
+ (sibling of the existing ``config.json``), overridable via
12
+ ``TOKEN_OPTIMIZER_COMMAND_FILTERS``.
13
+
14
+ Schema (illustrative)::
15
+
16
+ # Add read-only commands to an existing handler.
17
+ # pattern_name = { command = "...", handler = "git_status|pytest|lint|..." }
18
+ [filters.add]
19
+ my-tests = { command = "cargo test", handler = "pytest" }
20
+ my-lint = { command = "ruff check", handler = "lint" }
21
+
22
+ # Exclude commands from compression (glob patterns supported).
23
+ [filters.exclude]
24
+ commands = ["git status", "ls -la"]
25
+
26
+ Rules:
27
+ * ``add`` entries are appended only if they pass ``_is_safe_add``
28
+ (read-only, not a shell interpreter, not sudo/su, no write subcommand).
29
+ * ``exclude`` entries remove commands from the effective set.
30
+ * Categorical exclusions (dangerous chars, git write subcmds, interpreters)
31
+ are enforced downstream in bash_hook/bash_compress, never overridden
32
+ here.
33
+ * A missing file is a no-op (empty config). Malformed TOML is fail-open
34
+ (empty config + one-time stderr warning).
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ import fnmatch
40
+ import os
41
+ import sys
42
+ from dataclasses import dataclass, field
43
+ from pathlib import Path
44
+ from typing import List, Optional, Tuple
45
+
46
+ try:
47
+ import tomllib
48
+ except ImportError:
49
+ tomllib = None # type: ignore[assignment]
50
+
51
+ # ---------------------------------------------------------------------------
52
+ # Constants
53
+ # ---------------------------------------------------------------------------
54
+
55
+ ENV_FILTERS_PATH = "TOKEN_OPTIMIZER_COMMAND_FILTERS"
56
+ DEFAULT_FILTERS_FILENAME = "command-filters.toml"
57
+
58
+ # Valid handler names (the keys of bash_compress._PATTERN_HANDLERS). Listed
59
+ # here so the loader can reject unknown handlers without importing
60
+ # bash_compress (which would create a circular dependency on the hot path).
61
+ VALID_HANDLERS = frozenset({
62
+ "git_status", "git_log", "git_diff", "pytest", "jest", "npm_install",
63
+ "ls", "lint", "logs", "tree", "progress", "list", "build", "sqlite3",
64
+ "disk_stats", "docker_output", "json", "csv", "stack_trace", "k8s",
65
+ "cloud_cli", "search_results", "git_log_basic", "find", "find_raw",
66
+ })
67
+
68
+ # Commands that are NEVER safe to add (shell interpreters, privilege
69
+ # escalation, destructive utilities). Mirrors bash_hook's safety gates.
70
+ _UNSAFE_INTERPRETERS = frozenset({
71
+ "bash", "sh", "zsh", "dash", "ksh", "fish", "csh", "tcsh",
72
+ "python", "python3", "python2", "ruby", "perl", "node", "deno", "bun",
73
+ "lua", "tcl", "awk", "sed", "eval", "exec", "source", ".",
74
+ })
75
+ _UNSAFE_PREFIXES = frozenset({"sudo", "su", "doas", "pkexec", "gksudo"})
76
+ _UNSAFE_WRITE_SUBCMDS = frozenset({
77
+ "rm", "mv", "cp", "chmod", "chown", "chgrp", "mkdir", "rmdir", "ln",
78
+ "dd", "mkfs", "fdisk", "mount", "umount", "kill", "killall", "pkill",
79
+ "shutdown", "reboot", "halt", "poweroff",
80
+ })
81
+ _DANGEROUS_CHARS = frozenset(";|&`$(){}><\n\r\x00")
82
+
83
+ _warned_paths: set = set()
84
+
85
+
86
+ # ---------------------------------------------------------------------------
87
+ # Dataclasses
88
+ # ---------------------------------------------------------------------------
89
+
90
+ @dataclass(frozen=True)
91
+ class AddEntry:
92
+ """A user-declared add rule: map a command to an existing handler."""
93
+ name: str
94
+ command: str
95
+ handler: str
96
+
97
+
98
+ @dataclass(frozen=True)
99
+ class CommandFilterConfig:
100
+ """Normalized filter config loaded from TOML."""
101
+ adds: Tuple[AddEntry, ...] = ()
102
+ excludes: Tuple[str, ...] = ()
103
+
104
+ def is_excluded(self, command_str: str) -> bool:
105
+ """Return True if ``command_str`` matches any exclude glob/pattern."""
106
+ for pattern in self.excludes:
107
+ if fnmatch.fnmatch(command_str, pattern):
108
+ return True
109
+ return False
110
+
111
+ def find_add(self, command_str: str) -> Optional[AddEntry]:
112
+ """Return the first add entry whose command matches ``command_str``,
113
+ or None."""
114
+ for entry in self.adds:
115
+ if entry.command == command_str:
116
+ return entry
117
+ # Also support glob matching on the add command.
118
+ if fnmatch.fnmatch(command_str, entry.command):
119
+ return entry
120
+ return None
121
+
122
+
123
+ @dataclass(frozen=True)
124
+ class EffectiveFilters:
125
+ """The merged result of builtin + user filters, ready for bash_hook /
126
+ bash_compress to consult on the hot path."""
127
+ user_adds: Tuple[AddEntry, ...] = field(default_factory=tuple)
128
+ user_excludes: Tuple[str, ...] = field(default_factory=tuple)
129
+
130
+ def is_user_excluded(self, command_str: str) -> bool:
131
+ for pattern in self.user_excludes:
132
+ if fnmatch.fnmatch(command_str, pattern):
133
+ return True
134
+ return False
135
+
136
+ def find_user_add(self, command_str: str) -> Optional[AddEntry]:
137
+ for entry in self.user_adds:
138
+ if entry.command == command_str:
139
+ return entry
140
+ if fnmatch.fnmatch(command_str, entry.command):
141
+ return entry
142
+ return None
143
+
144
+
145
+ # ---------------------------------------------------------------------------
146
+ # Safety gate
147
+ # ---------------------------------------------------------------------------
148
+
149
+ def _is_all_wildcard(token: str) -> bool:
150
+ """True when ``token`` is a non-empty run of only ``*`` (e.g. ``*``/``**``).
151
+ Such a pattern matches every command via fnmatch and is far too broad to
152
+ opt into a compression handler."""
153
+ return bool(token) and set(token) <= {"*"}
154
+
155
+
156
+ def _effective_cmd0(tokens: List[str]) -> Optional[str]:
157
+ """Return the basename of the REAL command being run.
158
+
159
+ Normalizes away the path (so ``/bin/bash``, ``./python``, ``/usr/bin/sudo``
160
+ are recognized as ``bash``/``python``/``sudo``) and resolves a leading
161
+ ``env`` invocation by skipping ``VAR=val`` assignments and env's own options
162
+ (``-i``, and the operand-taking ``-u``/``-C``/``-S``) to reach the command
163
+ env would exec. Returns None when no command token remains.
164
+ """
165
+ if not tokens:
166
+ return None
167
+ i = 0
168
+ if os.path.basename(tokens[0]) == "env":
169
+ i = 1
170
+ while i < len(tokens):
171
+ tok = tokens[i]
172
+ if "=" in tok and not tok.startswith("-"):
173
+ i += 1 # VAR=val assignment
174
+ continue
175
+ if tok in ("-i", "--ignore-environment", "-", "-v", "--debug"):
176
+ i += 1
177
+ continue
178
+ if tok in ("-u", "--unset", "-C", "--chdir", "-S", "--split-string"):
179
+ i += 2 # option consumes its operand
180
+ continue
181
+ break # first non-option, non-assignment token = the command
182
+ if i >= len(tokens):
183
+ return None
184
+ return os.path.basename(tokens[i])
185
+
186
+
187
+ def _is_safe_add(command: str, handler: str) -> bool:
188
+ """Gate a user ``add`` entry before it reaches the effective allowlist.
189
+
190
+ Rejects:
191
+ * Empty command or handler.
192
+ * Unknown handler (not in VALID_HANDLERS).
193
+ * Commands containing dangerous shell metacharacters.
194
+ * Bare/overly-broad wildcard patterns (just ``*`` or ``**``).
195
+ * Shell interpreters (bash, python, node, etc.) as argv[0] -- recognized
196
+ even when given by absolute/relative path or via ``env``.
197
+ * Privilege escalation prefixes (sudo, su, doas, pkexec) -- likewise
198
+ path- and ``env``-normalized.
199
+ * Destructive write subcommands (rm, mv, chmod, etc.) as argv[0].
200
+ Returns True only for read-only commands mapped to a known handler.
201
+
202
+ Defense-in-depth: dangerous shell metacharacters are already blocked
203
+ upstream (bash_hook main, before the whitelist), so there is no injection
204
+ here; this gate exists to deliver exactly what its docstring claims.
205
+ """
206
+ if not command or not command.strip():
207
+ return False
208
+ if handler not in VALID_HANDLERS:
209
+ return False
210
+ for ch in command:
211
+ if ch in _DANGEROUS_CHARS:
212
+ return False
213
+ stripped = command.strip()
214
+ if _is_all_wildcard(stripped):
215
+ return False
216
+ tokens = stripped.split()
217
+ if not tokens:
218
+ return False
219
+ cmd0 = _effective_cmd0(tokens)
220
+ if cmd0 is None:
221
+ return False
222
+ if _is_all_wildcard(cmd0):
223
+ return False
224
+ if cmd0 in _UNSAFE_INTERPRETERS:
225
+ return False
226
+ if cmd0 in _UNSAFE_PREFIXES:
227
+ return False
228
+ if cmd0 in _UNSAFE_WRITE_SUBCMDS:
229
+ return False
230
+ return True
231
+
232
+
233
+ # ---------------------------------------------------------------------------
234
+ # Loader
235
+ # ---------------------------------------------------------------------------
236
+
237
+ def _filters_path() -> Optional[Path]:
238
+ """Resolve the TOML file path from env override or the default runtime
239
+ home. Returns None when no path is resolvable."""
240
+ env_path = os.environ.get(ENV_FILTERS_PATH)
241
+ if env_path:
242
+ return Path(env_path)
243
+ # Default: <runtime-home>/token-optimizer/command-filters.toml
244
+ # The runtime home is the same dir as config.json. We resolve it via
245
+ # the same plugin_env helper used by the config loader, but avoid
246
+ # importing plugin_env on the hot path when the file doesn't exist.
247
+ try:
248
+ from plugin_env import resolve_plugin_data_dir, _USER_CONFIG_DIR
249
+ candidates = [_USER_CONFIG_DIR / DEFAULT_FILTERS_FILENAME]
250
+ pdd = resolve_plugin_data_dir()
251
+ if pdd is not None:
252
+ candidates.append(pdd / "config" / DEFAULT_FILTERS_FILENAME)
253
+ for c in candidates:
254
+ if c.exists():
255
+ return c
256
+ except Exception:
257
+ pass
258
+ return None
259
+
260
+
261
+ def _warn_once(path: Path, message: str) -> None:
262
+ """One-time stderr warning per path (avoids spamming every hook call)."""
263
+ key = str(path)
264
+ if key in _warned_paths:
265
+ return
266
+ _warned_paths.add(key)
267
+ print(f"[Command Filters] {message}: {path}", file=sys.stderr)
268
+
269
+
270
+ def load_filters() -> CommandFilterConfig:
271
+ """Load and validate the TOML command-filter file.
272
+
273
+ Returns a normalized ``CommandFilterConfig``. A missing file is a no-op
274
+ (empty config). Malformed TOML is fail-open (empty config + one-time
275
+ warning). Malformed entries are skipped with a one-time warning. Never
276
+ raises. Performs no file writes.
277
+ """
278
+ path = _filters_path()
279
+ if path is None or not path.exists():
280
+ return CommandFilterConfig()
281
+ if tomllib is None:
282
+ _warn_once(path, "tomllib not available; ignoring")
283
+ return CommandFilterConfig()
284
+ try:
285
+ with open(path, "rb") as handle:
286
+ data = tomllib.load(handle)
287
+ except (OSError, tomllib.TOMLDecodeError) as exc:
288
+ _warn_once(path, f"malformed TOML ({exc}); ignoring")
289
+ return CommandFilterConfig()
290
+ return _parse_filters(data, path)
291
+
292
+
293
+ def _parse_filters(data: dict, path: Path) -> CommandFilterConfig:
294
+ """Parse the raw TOML dict into a normalized CommandFilterConfig.
295
+
296
+ Validates structure; skips malformed entries with a one-time warning.
297
+ """
298
+ filters = data.get("filters")
299
+ if not isinstance(filters, dict):
300
+ return CommandFilterConfig()
301
+ adds: List[AddEntry] = []
302
+ excludes: List[str] = []
303
+ # [filters.add] — mapping of pattern_name = { command, handler }
304
+ add_section = filters.get("add")
305
+ if isinstance(add_section, dict):
306
+ for name, spec in add_section.items():
307
+ if not isinstance(spec, dict):
308
+ _warn_once(path, f"add entry '{name}' is not a table; skipping")
309
+ continue
310
+ command = spec.get("command")
311
+ handler = spec.get("handler")
312
+ if not isinstance(command, str) or not isinstance(handler, str):
313
+ _warn_once(path, f"add entry '{name}' missing command/handler; skipping")
314
+ continue
315
+ if not _is_safe_add(command, handler):
316
+ _warn_once(path, f"add entry '{name}' failed safety gate; skipping")
317
+ continue
318
+ adds.append(AddEntry(name=name, command=command.strip(), handler=handler))
319
+ # [filters.exclude] — table with a `commands` array
320
+ exclude_section = filters.get("exclude")
321
+ if isinstance(exclude_section, dict):
322
+ commands = exclude_section.get("commands")
323
+ if isinstance(commands, list):
324
+ for item in commands:
325
+ if isinstance(item, str) and item.strip():
326
+ excludes.append(item.strip())
327
+ else:
328
+ _warn_once(path, "exclude entry is not a string; skipping")
329
+ return CommandFilterConfig(adds=tuple(adds), excludes=tuple(excludes))
330
+
331
+
332
+ # ---------------------------------------------------------------------------
333
+ # Merge
334
+ # ---------------------------------------------------------------------------
335
+
336
+ def merge_filters(user: CommandFilterConfig) -> EffectiveFilters:
337
+ """Compute the effective filter set from user config.
338
+
339
+ The builtin allowlist/dispatch is not passed in (it lives in bash_hook /
340
+ bash_compress and is consulted first on the hot path). This function
341
+ simply wraps the user config into an ``EffectiveFilters`` object ready
342
+ for downstream consultation. User ``add`` entries have already passed
343
+ ``_is_safe_add`` in the loader; user ``exclude`` entries are glob
344
+ patterns checked against the command string.
345
+ """
346
+ return EffectiveFilters(
347
+ user_adds=user.adds,
348
+ user_excludes=user.excludes,
349
+ )
350
+
351
+
352
+ # ---------------------------------------------------------------------------
353
+ # Cached accessor for the hot path
354
+ # ---------------------------------------------------------------------------
355
+
356
+ _cached: Optional[EffectiveFilters] = None
357
+
358
+
359
+ def get_effective_filters() -> EffectiveFilters:
360
+ """Return the merged effective filters, loading once and caching for the
361
+ process lifetime. The hot path (bash_hook / bash_compress) calls this
362
+ instead of load_filters + merge_filters directly."""
363
+ global _cached
364
+ if _cached is not None:
365
+ return _cached
366
+ _cached = merge_filters(load_filters())
367
+ return _cached
368
+
369
+
370
+ def reset_cache() -> None:
371
+ """Reset the process-level cache (for tests)."""
372
+ global _cached
373
+ _cached = None
374
+
375
+
376
+ __all__ = [
377
+ "AddEntry",
378
+ "CommandFilterConfig",
379
+ "ENV_FILTERS_PATH",
380
+ "EffectiveFilters",
381
+ "VALID_HANDLERS",
382
+ "get_effective_filters",
383
+ "load_filters",
384
+ "merge_filters",
385
+ "reset_cache",
386
+ ]