@alexgreensh/token-optimizer 0.0.0-stage → 5.13.51

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 +448 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +788 -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 +149 -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 +3633 -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 +141 -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 +93 -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 +379 -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 +1011 -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 +288 -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 +426 -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 +400 -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 +716 -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 +59531 -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 +1923 -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,163 @@
1
+ #!/usr/bin/env python3
2
+ """Token Optimizer Windows launcher for Codex hooks.
3
+
4
+ Codex spawns ``command`` hooks through ``%COMSPEC% /C`` on native Windows,
5
+ and cmd.exe parses a /C command line ONCE, before anything on it runs:
6
+ ``%VAR%`` expands to the pre-line value and ``setlocal
7
+ EnableDelayedExpansion`` only takes effect from the NEXT line, so no cmd
8
+ expansion form can carry a resolved marketplace version into the runner
9
+ path on the same line (issue #180). The pre-launcher fix embedded the
10
+ resolver as a base64 ``python -c`` exec-bootstrap,
11
+ which trips generic-loader antivirus signatures (issue #183): the match is
12
+ on the literal encoded-exec string, not on behavior, and a detection on an
13
+ install script surfaces as malware, not a warning.
14
+
15
+ This file is the replacement: a stable, readable .py that codex_install.py
16
+ copies NEXT TO the versioned install dirs (``.../token-optimizer/
17
+ windows-launcher.py``, a path that survives the marketplace swapping
18
+ ``.../token-optimizer/<X.Y.Z>/`` on upgrade) and that baked hook commands
19
+ invoke by quoted path. Paths and arguments live as plainly quoted argv --
20
+ no encoded-exec string appears anywhere, and the cmd.exe single-parse
21
+ problem stays solved because nothing needs expanding.
22
+
23
+ Invocation contract (generated by codex_install._windows_launcher_command):
24
+
25
+ python.exe "<parent>\\windows-launcher.py" --baked-root "<root>"
26
+ [--env KEY=VALUE ...] -- <script> [args...] [MARKER]
27
+
28
+ * ``--baked-root`` is the install dir the command was generated from. It is
29
+ the fail-open fallback only: the launcher rescans its sibling version
30
+ dirs on every run and runs the NEWEST semver install, so hooks keep
31
+ working after a marketplace upgrade prunes the baked one.
32
+ * ``--env KEY=VALUE`` applies per-hook environment (e.g.
33
+ TOKEN_OPTIMIZER_NO_UPDATED_TOOL_OUTPUT=1) before dispatch.
34
+ * Everything after ``--`` is forwarded verbatim: ``sys.argv`` for the
35
+ runner becomes ``[run.py, script, *args]`` and stdin passes through
36
+ untouched. A trailing token equal to the generated-command ownership
37
+ marker (token-optimizer/scripts/windows-launcher) is stripped, matching
38
+ the old bootstrap, which dropped it when it replaced sys.argv.
39
+
40
+ Audit: the file IS the audit -- read it. For hooks.json entries baked by
41
+ the retired base64 launcher, ``codex_install.py --decode-launcher
42
+ "<command>"`` still decodes them.
43
+ """
44
+
45
+ from __future__ import annotations
46
+
47
+ import os
48
+ import re
49
+ import runpy
50
+ import sys
51
+ from pathlib import Path
52
+
53
+ # Trailing ownership marker baked into every generated Windows launcher
54
+ # command (see codex_install._LAUNCHER_MARKER). It identifies the command
55
+ # to install/uninstall/doctor ownership checks and is never forwarded to
56
+ # the runner.
57
+ _LAUNCHER_MARKER = "token-optimizer/scripts/windows-launcher"
58
+
59
+ _SEMVER_DIR_RE = re.compile(r"\d+\.\d+\.\d+")
60
+
61
+ _USAGE = (
62
+ "usage: windows-launcher.py --baked-root DIR [--env KEY=VALUE ...] "
63
+ "-- SCRIPT [ARGS...]"
64
+ )
65
+
66
+
67
+ def _parse(argv: list[str]) -> tuple[str, list[str], str, list[str]]:
68
+ """Split generated launcher argv into (baked_root, env, script, args).
69
+
70
+ Manual parse, not argparse: hook arguments legitimately start with
71
+ ``--`` (e.g. ``--quiet``), which argparse would misread as its own
72
+ options. Everything after the ``--`` separator is positional.
73
+ """
74
+ baked_root = None
75
+ env: list[str] = []
76
+ i = 0
77
+ while i < len(argv):
78
+ token = argv[i]
79
+ if token == "--":
80
+ i += 1
81
+ break
82
+ if token in ("--baked-root", "--env") and i + 1 < len(argv):
83
+ value = argv[i + 1]
84
+ if token == "--baked-root":
85
+ baked_root = value
86
+ else:
87
+ env.append(value)
88
+ i += 2
89
+ continue
90
+ break # unrecognized token: stop option parsing, rest is positional
91
+ rest = argv[i:]
92
+ if rest and rest[-1] == _LAUNCHER_MARKER:
93
+ rest = rest[:-1]
94
+ if not baked_root or not rest:
95
+ raise SystemExit(_USAGE)
96
+ return baked_root, env, rest[0], rest[1:]
97
+
98
+
99
+ def main(argv: list[str] | None = None) -> None:
100
+ baked_root, env_pairs, script, args = _parse(
101
+ sys.argv[1:] if argv is None else argv
102
+ )
103
+ root = Path(baked_root)
104
+ baked = root
105
+ # Resolve the newest semver sibling of the install parent; on any
106
+ # listing failure keep the baked install (fail-open, same contract the
107
+ # retired base64 bootstrap documented).
108
+ #
109
+ # Windows-only launcher, so os.access(run.py, R_OK) is unusable: it maps
110
+ # to the read-only file attribute, not the ACL, and returns True for a
111
+ # run.py an ACL forbids reading -- runpy would then die with
112
+ # PermissionError instead of falling back. And a bare .is_file() on a
113
+ # candidate whose hooks/ dir can't be traversed RAISES PermissionError,
114
+ # which on 3.12 escapes the comprehension and aborts the whole scan
115
+ # (caught below), selecting the wrong runtime. So probe each candidate by
116
+ # actually opening its run.py, newest-first, and take the first that
117
+ # opens with real content: an unreadable, missing, or incomplete
118
+ # candidate is skipped (not fatal), and a genuine ACL denial is honored.
119
+ try:
120
+ candidates = sorted(
121
+ (p for p in root.parent.iterdir()
122
+ if _SEMVER_DIR_RE.fullmatch(p.name)),
123
+ key=lambda p: tuple(map(int, p.name.split("."))),
124
+ reverse=True,
125
+ )
126
+ for candidate in candidates:
127
+ run_py = candidate / "hooks" / "run.py"
128
+ try:
129
+ with open(run_py, "rb") as fh:
130
+ if not fh.read(1):
131
+ continue # zero-byte/truncated: would run nothing rc 0
132
+ except OSError:
133
+ continue # missing, incomplete upgrade, or ACL-denied
134
+ root = candidate
135
+ break
136
+ except OSError:
137
+ pass
138
+ # The baked-install fallback is silent by design; the only observable
139
+ # channel is a TOKEN_OPTIMIZER_DEBUG-gated line appended next to the
140
+ # version dirs. A healthy semver resolve is not a fallback and never
141
+ # logs.
142
+ if root == baked and os.environ.get("TOKEN_OPTIMIZER_DEBUG"):
143
+ try:
144
+ with (root.parent / "token-optimizer-codex-resolver.log").open(
145
+ "a", encoding="utf-8"
146
+ ) as log:
147
+ log.write(str(root) + "\n")
148
+ except OSError:
149
+ pass
150
+ os.environ["TOKEN_OPTIMIZER_RUNTIME"] = "codex"
151
+ os.environ["TOKEN_OPTIMIZER_RUNTIME_ROOT"] = str(root)
152
+ for pair in env_pairs:
153
+ key, sep, value = pair.partition("=")
154
+ if sep and key: # skip malformed pairs rather than breaking the hook
155
+ os.environ[key] = value
156
+ runner = root / "hooks" / "run.py"
157
+ sys.argv = [str(runner), script, *args]
158
+ sys.path.insert(0, str(runner.parent))
159
+ runpy.run_path(str(runner), run_name="__main__")
160
+
161
+
162
+ if __name__ == "__main__":
163
+ main()
@@ -0,0 +1,23 @@
1
+ #!/bin/sh
2
+ # Token Optimizer: install for Claude Code cloud sessions.
3
+ #
4
+ # Run by the cloud environment's setup script after the tarball's sha512 was
5
+ # checked (see `measure.py cloud-setup-script`). Copies this package to
6
+ # ~/.cache/token-optimizer-cloud/<version>, writes the runner, and merges the
7
+ # hook map generated from hooks/hooks.json into ~/.claude/settings.json.
8
+ #
9
+ # Always exits 0 and prints nothing: a failing setup script blocks the cloud
10
+ # session. Details go to ~/.cache/token-optimizer-cloud/install.log.
11
+ S=$(cd "$(dirname "$0")" 2>/dev/null && pwd) || exit 0
12
+ C="${TOKEN_OPTIMIZER_CLOUD_HOME:-${HOME:-/root}/.cache/token-optimizer-cloud}"
13
+ mkdir -p "$C" 2>/dev/null || exit 0
14
+ {
15
+ date -u '+%Y-%m-%dT%H:%M:%SZ install-cloud.sh start'
16
+ if command -v python3 >/dev/null 2>&1; then
17
+ python3 -I -B "$S/skills/token-optimizer/scripts/cloud_kit.py" install --source "$S" --cache "$C" "$@" </dev/null
18
+ echo "exit $?"
19
+ else
20
+ echo "python3 not found; Token Optimizer needs Python 3.9+"
21
+ fi
22
+ } >>"$C/install.log" 2>&1
23
+ exit 0
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@alexgreensh/token-optimizer",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "5.13.51",
4
+ "description": "Token Optimizer for Claude Code cloud sessions: the real plugin, installed by your cloud environment's setup script.",
5
+ "license": "PolyForm-Noncommercial-1.0.0",
6
+ "author": "Alex Greenshpun (https://linkedin.com/in/alexgreensh)",
7
+ "homepage": "https://github.com/alexgreensh/token-optimizer",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/alexgreensh/token-optimizer.git"
11
+ },
12
+ "keywords": [
13
+ "claude-code",
14
+ "token-optimizer",
15
+ "context",
16
+ "tokens"
17
+ ],
18
+ "files": [
19
+ "install-cloud.sh",
20
+ "hooks/",
21
+ "skills/",
22
+ ".claude-plugin/",
23
+ "LICENSE",
24
+ "LICENSE-SMALL-BUSINESS.md",
25
+ "PRIVACY.md"
26
+ ],
27
+ "publishConfig": {
28
+ "access": "public",
29
+ "registry": "https://registry.npmjs.org/"
30
+ }
31
+ }
@@ -0,0 +1,149 @@
1
+ ---
2
+ name: fleet-auditor
3
+ description: "Audits token waste and cost across Claude Code, Codex, OpenClaw, Hermes and OpenCode, with dollar savings. Use when running several agent systems or suspecting idle heartbeats burn tokens."
4
+ ---
5
+
6
+ # Fleet Auditor: Cross-Platform Agent Token Waste Auditor
7
+
8
+ Token Optimizer's own skills (`token-optimizer`, `token-coach`, `token-dashboard`, `fleet-auditor`) are the measurement layer, so leave them out of every removal, archive, trimming, disabling or consolidation suggestion; deleting them to save a few hundred tokens defeats the audit.
9
+
10
+ Detects installed agent systems, collects token usage data, identifies waste patterns, and recommends fixes with dollar savings estimates.
11
+
12
+ Use when running multiple agent systems, spending $2-5/day on agents, suspecting idle heartbeats are burning tokens, or wanting a cross-system cost audit.
13
+
14
+ ---
15
+
16
+ ## Phase 0: Initialize
17
+
18
+ 1. **Resolve runtime and fleet.py path** (works for both skill and plugin installs):
19
+ ```bash
20
+ RUNTIME="${TOKEN_OPTIMIZER_RUNTIME:-}"
21
+ if [ -z "$RUNTIME" ]; then
22
+ if [ -n "$CLAUDE_PLUGIN_ROOT" ] || [ -n "$CLAUDE_PLUGIN_DATA" ]; then RUNTIME="claude"
23
+ elif [ -n "$OPENCODE" ] || [ -n "$OPENCODE_BIN" ] || [ -n "$OPENCODE_CONFIG_DIR" ] || [ -n "$OPENCODE_CONFIG" ]; then RUNTIME="opencode"
24
+ elif [ -n "$CODEX_HOME" ]; then RUNTIME="codex"
25
+ # Another harness's config-dir env: same tier as Python's detect_runtime().
26
+ elif [ -n "$HERMES_HOME" ]; then RUNTIME="hermes"
27
+ elif [ -n "$COPILOT_HOME" ] || [ -n "$TOKEN_OPTIMIZER_COPILOT_HOME" ]; then RUNTIME="copilot"
28
+ elif [ -n "$TOKEN_OPTIMIZER_CURSOR_HOME" ]; then RUNTIME="cursor"
29
+ elif [ -n "$TOKEN_OPTIMIZER_ANTIGRAVITY_HOME" ]; then RUNTIME="antigravity"
30
+ elif [ -n "$GROK_HOME" ] || [ -n "$TOKEN_OPTIMIZER_GROK_HOME" ]; then RUNTIME="grok"
31
+ elif [ -n "$CLAUDECODE" ] || [ -n "$CLAUDE_CODE_ENTRYPOINT" ] || [ -n "$CLAUDE_CODE_SESSION_ID" ]; then RUNTIME="claude"
32
+ elif [ -d "$HOME/.config/opencode" ] && [ ! -d "$HOME/.codex" ]; then RUNTIME="opencode"
33
+ elif [ -d "$HOME/.codex" ]; then RUNTIME="codex"
34
+ else RUNTIME="claude"
35
+ fi
36
+ fi
37
+
38
+ # Resolve fleet.py to the NEWEST installed copy across channels so a stale
39
+ # plugin-cache copy never shadows a fresh install. find -L follows the
40
+ # install.sh symlink under ~/.claude/skills; cd -P resolves it before reading each
41
+ # copy's plugin.json for its version. find (not bare globs) never errors under zsh.
42
+ FLEET_PY=""; _best_ver=""
43
+ while IFS= read -r _cand; do
44
+ [ -f "$_cand" ] || continue
45
+ _root="$(cd -P -- "$(dirname -- "$_cand")/../../.." 2>/dev/null && pwd)"
46
+ _ver="$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$_root/.claude-plugin/plugin.json" 2>/dev/null | head -1)"
47
+ [ -n "$_ver" ] || _ver="0.0.0"
48
+ if [ -z "$_best_ver" ] || [ "$(printf '%s\n%s\n' "$_ver" "$_best_ver" | sort -t. -k1,1n -k2,2n -k3,3n -k4,4n | tail -n1)" = "$_ver" ]; then
49
+ _best_ver="$_ver"; FLEET_PY="$_cand"
50
+ fi
51
+ done <<EOF
52
+ $(find -L "$HOME/.claude/skills" "$HOME/.claude/plugins/cache" "$HOME/.claude/token-optimizer" "$HOME/.codex/skills" "$HOME/.codex/plugins/cache" "$HOME/.config/opencode/plugins/cache" "$HOME/.config/opencode/plugins" -type f -name fleet.py -path '*fleet-auditor*/scripts/fleet.py' 2>/dev/null)
53
+ EOF
54
+ if [ -z "$FLEET_PY" ]; then echo "[Error] fleet.py not found. Is Fleet Auditor installed?"; exit 1; fi
55
+ echo "Using: $FLEET_PY"
56
+ export TOKEN_OPTIMIZER_RUNTIME="$RUNTIME"
57
+ ```
58
+ Use `$FLEET_PY` for all subsequent fleet.py calls.
59
+
60
+ 2. **Detect systems**:
61
+ ```bash
62
+ python3 "$FLEET_PY" detect --json
63
+ ```
64
+ Parse the JSON output. Report what was found.
65
+
66
+ If nothing detected, explain: "No agent systems found. Fleet Auditor supports: Claude Code, Codex, OpenClaw, NanoClaw, Hermes, OpenCode, IronClaw."
67
+
68
+ ---
69
+
70
+ ## Phase 1: Scan
71
+
72
+ Collect token usage data from detected systems:
73
+ ```bash
74
+ python3 "$FLEET_PY" scan --days 30
75
+ ```
76
+
77
+ Report how many runs were collected per system. If this is the first scan, it may take a moment to parse all session files.
78
+
79
+ ---
80
+
81
+ ## Phase 2: Audit
82
+
83
+ Run waste pattern detection:
84
+ ```bash
85
+ python3 "$FLEET_PY" audit --json
86
+ ```
87
+
88
+ Parse the JSON output. Present findings ordered by severity and monthly savings.
89
+
90
+ If no waste found: "Your fleet looks clean. No significant waste patterns detected."
91
+
92
+ Dollar figures need a price for the model. For Codex and other non-Claude systems, and for the OpenClaw security checks, read `references/report-template.md` before presenting.
93
+
94
+ ---
95
+
96
+ ## Phase 3: Present Findings
97
+
98
+ Use the layout in `references/report-template.md`: systems detected, waste patterns with severity, monthly savings and a fix for each, then the total and the next-step options.
99
+
100
+ ---
101
+
102
+ ## Phase 4: Dashboard (optional)
103
+
104
+ If user wants visual analysis:
105
+ ```bash
106
+ python3 "$FLEET_PY" dashboard
107
+ ```
108
+
109
+ This generates `~/.claude/_backups/token-optimizer/fleet-dashboard.html` in Claude Code, or `~/.codex/_backups/token-optimizer/fleet-dashboard.html` when `TOKEN_OPTIMIZER_RUNTIME=codex`.
110
+
111
+ ---
112
+
113
+ ## Phase 5: Deep Dive (optional)
114
+
115
+ For Claude Code specifically, offer `/token-optimizer` for full audit (`CLAUDE.md`, skills, MCP, hooks, etc.).
116
+
117
+ For Codex specifically, offer `token-optimizer` for full audit (`AGENTS.md`, Codex memories, plugin skills, MCP, balanced hooks, compact prompt, status line).
118
+
119
+ For other systems, show the fix snippets from the audit and guide the user through implementing them.
120
+
121
+ ---
122
+
123
+ ## Reference Files
124
+
125
+ | Read | When |
126
+ |------|------|
127
+ | [references/report-template.md](references/report-template.md) | Presenting findings, Codex dollar caveats, OpenClaw checks |
128
+ | [references/waste-patterns.md](references/waste-patterns.md) | Detector thresholds, severity and confidence levels |
129
+ | [references/fleet-systems.md](references/fleet-systems.md) | Per-system data locations and token fields |
130
+
131
+ ---
132
+
133
+ ## Error Handling
134
+
135
+ - **No systems detected**: report cleanly and list the supported systems
136
+ - **Empty scan results**: system detected but no session data in the window; suggest a larger `--days`
137
+ - **Permission errors**: name the files that could not be read and continue with the rest
138
+ - **Corrupted data**: skip bad files and report how many were skipped
139
+ - **fleet.py not found**: check both the skill and plugin install paths
140
+
141
+ ## Core Rules
142
+
143
+ - Quantify everything in dollars and tokens
144
+ - Never read or expose message content (privacy-first)
145
+ - Report confidence levels alongside findings and suppress anything below 0.4
146
+ - Show a fix snippet with every recommendation
147
+ - Frame savings as monthly recurring, not one-time
148
+
149
+ Written for and checked on Claude Opus 5.5 and Sonnet 5.5, and GPT-5.6 on Codex.
@@ -0,0 +1,167 @@
1
+ # Fleet Systems: Data Format Specifications
2
+
3
+ Reference file for Fleet Auditor. Loaded on demand for adapter development.
4
+
5
+ ---
6
+
7
+ ## Contents
8
+
9
+ - [Claude Code](#claude-code)
10
+ - [OpenClaw](#openclaw)
11
+ - [NanoClaw](#nanoclaw)
12
+ - [Hermes](#hermes)
13
+ - [OpenCode](#opencode)
14
+ - [IronClaw](#ironclaw)
15
+
16
+ ---
17
+
18
+ ## Claude Code
19
+
20
+ **Data Location**: `~/.claude/projects/`
21
+ **Format**: JSONL (one JSON object per line)
22
+ **Structure**: Each project gets a directory named with a path-encoded slug (e.g., `-Users-alex-myproject/`). Session files are `{uuid}.jsonl`. Subagent files live in `{uuid}/subagents/{sub-uuid}.jsonl`.
23
+
24
+ ### JSONL Record Types
25
+ - `type: "user"` - User messages with `message.content` (string or array of blocks)
26
+ - `type: "assistant"` - Assistant messages with `message.content` (array of tool_use and text blocks), `message.usage` (token data), `message.model`
27
+ - `type: "result"` - Tool results
28
+
29
+ ### Token Fields (in `message.usage`)
30
+ ```json
31
+ {
32
+ "input_tokens": 12345,
33
+ "output_tokens": 678,
34
+ "cache_read_input_tokens": 9000,
35
+ "cache_creation_input_tokens": 3000
36
+ }
37
+ ```
38
+
39
+ ### Key Extraction Points
40
+ - **Version**: First record with `version` field
41
+ - **Slug**: First record with `slug` field
42
+ - **Timestamp**: `timestamp` field (ISO-8601 with Z suffix)
43
+ - **Model**: `message.model` in assistant records
44
+ - **Tools**: `tool_use` blocks in `message.content` array
45
+
46
+ ---
47
+
48
+ ## OpenClaw
49
+
50
+ **Data Location**: `~/.openclaw/agents/` (also `~/.clawdbot/`, `~/.moltbot/`)
51
+ **Format**: JSON index + JSONL transcripts
52
+
53
+ ### Key Files
54
+ - `sessions.json` - Index of all sessions with metadata
55
+ - `agents/{agent-name}/sessions/{session-id}.jsonl` - Individual session transcripts
56
+ - `cron/` - Heartbeat/cron configuration and logs
57
+ - `config.json` - Global config including model settings, pricing overrides
58
+
59
+ ### Token Fields
60
+ ```json
61
+ {
62
+ "inputTokens": 12345,
63
+ "outputTokens": 678,
64
+ "totalTokens": 13023
65
+ }
66
+ ```
67
+
68
+ Note: OpenClaw does NOT expose cache read/write breakdown. Use `inputTokens` for total input.
69
+
70
+ ---
71
+
72
+ ## NanoClaw
73
+
74
+ **Data Location**: `~/.nanoclaw/` or container volume mounts
75
+ **Format**: SQLite (`messages` table) + Claude Agent SDK response objects
76
+ **Built on**: Anthropic Claude Agent SDK
77
+
78
+ ### Token Fields (from SDK response)
79
+ ```python
80
+ response.usage.input_tokens
81
+ response.usage.output_tokens
82
+ response.usage.cache_creation_input_tokens
83
+ response.usage.cache_read_input_tokens
84
+ ```
85
+
86
+ ### SQLite Schema
87
+ ```sql
88
+ -- messages table stores conversations
89
+ -- Token data in SDK response metadata, not always in DB
90
+ CREATE TABLE messages (
91
+ id TEXT PRIMARY KEY,
92
+ session_id TEXT,
93
+ role TEXT,
94
+ content TEXT,
95
+ created_at TIMESTAMP
96
+ );
97
+ ```
98
+
99
+ ### Container Considerations
100
+ - Data may be inside Docker/container volumes
101
+ - Check for exported/mounted data directories
102
+ - Container isolation means direct DB access may not be possible
103
+
104
+ ---
105
+
106
+ ## Hermes
107
+
108
+ **Data Location**: `~/.hermes/`
109
+ **Format**: SQLite (`state.db`) + JSONL session logs
110
+
111
+ ### Key Files
112
+ - `state.db` - Primary state database
113
+ - `sessions/{date}/{session-id}.jsonl` - Session transcripts
114
+
115
+ ### Token Fields
116
+ ```json
117
+ {
118
+ "tokens": {
119
+ "input": 12345,
120
+ "output": 678
121
+ }
122
+ }
123
+ ```
124
+
125
+ ---
126
+
127
+ ## OpenCode
128
+
129
+ **Data Location**: `~/.local/share/opencode/` or `$OPENCODE_DATA_DIR`
130
+ **Format**: JSON per-message, or SQLite on OpenCode builds that use `storage.db`
131
+
132
+ ### Token Fields
133
+ ```json
134
+ {
135
+ "usage": {
136
+ "input": 12345,
137
+ "output": 678
138
+ },
139
+ "cacheRead": 9000,
140
+ "cacheWrite": 3000
141
+ }
142
+ ```
143
+
144
+ ### File Structure
145
+ - `sessions/{session-id}/` - Per-session directories
146
+ - `sessions/{session-id}/messages.json` - Array of messages
147
+ - `storage.db` - SQLite database, present on builds that replace the JSON files
148
+
149
+ ---
150
+
151
+ ## IronClaw
152
+
153
+ **Data Location**: `~/.ironclaw/`
154
+ **Format**: PostgreSQL or libSQL (requires connection config)
155
+
156
+ ### Token Fields
157
+ ```json
158
+ {
159
+ "max_tokens": 4096,
160
+ "total_tokens_used": 12345
161
+ }
162
+ ```
163
+
164
+ ### Access Pattern
165
+ - Requires database connection string from config
166
+ - Detect only today, no scan
167
+ - Scanning would need exported data files or a direct DB connection
@@ -0,0 +1,50 @@
1
+ # Fleet Auditor Report Template
2
+
3
+ Reference file for Fleet Auditor. Read it when presenting audit findings (Phase 3).
4
+
5
+ Order findings by severity, then by monthly savings. Show confidence beside each finding and
6
+ leave out anything below 0.4.
7
+
8
+ ```
9
+ [Fleet Auditor Results]
10
+
11
+ SYSTEMS DETECTED
12
+ - Claude Code: X runs ($Y.YY)
13
+ - Codex: X runs ($Y.YY)
14
+ - OpenClaw: X runs ($Y.YY)
15
+
16
+ WASTE PATTERNS FOUND
17
+ 1. [SEVERITY] Description
18
+ Est. savings: $X.XX/month
19
+ Fix: recommendation
20
+
21
+ 2. [SEVERITY] Description
22
+ ...
23
+
24
+ TOTAL POTENTIAL SAVINGS: $X.XX/month
25
+
26
+ Ready to act? I can:
27
+ 1. Show detailed fix snippets for each finding
28
+ 2. Generate the fleet dashboard for visual analysis
29
+ 3. Run /token-optimizer for deeper Claude Code optimization
30
+ ```
31
+
32
+ ## Dollars on Codex and other non-Claude systems
33
+
34
+ If a model's price is missing from the local pricing table, report the token waste and say the
35
+ dollar impact depends on current model pricing. Do not invent a cost.
36
+
37
+ ## OpenClaw checks
38
+
39
+ OpenClaw instances that are out of date or exposed can run rogue agents that burn tokens
40
+ unnoticed, so treat these as spend findings as well as security findings:
41
+
42
+ - Compare the detected OpenClaw version with the project's current security advisories. Flag an
43
+ outdated install as high severity and recommend upgrading.
44
+ - Look for installed ClawHub skills that make extra API calls or send data out, since those
45
+ inflate token spend.
46
+ - Flag a gateway with rate limiting disabled: without it, brute-force traffic can spawn unlimited
47
+ agent sessions. The fix is `openclaw config set security.rateLimit.enabled true`.
48
+
49
+ These checks come from public advisories, not from the audit data, so state that when reporting
50
+ them and let the user verify before acting.