@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,660 @@
1
+ #!/usr/bin/env node
2
+ // Token Optimizer - Claude Code Status Line (two-row layout)
3
+ //
4
+ // Row 1: model | effort | project | context bar used% | ContextQ:grade(score)
5
+ // Row 2: Eff:grade(score) | warnings | Compacts:N(loss) | duration | Agents
6
+ //
7
+ // Install: python3 measure.py setup-quality-bar
8
+ // The quality score is updated by a UserPromptSubmit hook every ~2 minutes.
9
+ // Reads from the most recent per-session quality-cache-*.json for accuracy.
10
+ // Effort level comes from the stdin payload (data.effort.level) when Claude
11
+ // Code provides it, falling back to settings.json effortLevel on older versions.
12
+
13
+ const fs = require('fs');
14
+ const path = require('path');
15
+ const os = require('os');
16
+ const { execFileSync } = require('child_process');
17
+
18
+ // --- Self-disabling guard ---
19
+ // Claude Code has NO plugin uninstall/teardown hook, so a `/plugin uninstall`
20
+ // (or a manual `rm -rf` of the plugin tree) can leave this statusLine command
21
+ // pointing at a script whose plugin tree has been removed. A missing command
22
+ // makes the status line go silently blank with no error surfaced to the user
23
+ // (visible only under `claude --debug`). Rather than emit a broken-command
24
+ // state, we self-disable: if our own plugin tree is gone (this script's
25
+ // directory no longer holds the sibling files a real install always ships),
26
+ // exit 0 with no output. A blank status line is exactly what a missing command
27
+ // already produces, so this changes nothing while installed and removes the
28
+ // dangling-reference state after removal. The guard runs BEFORE reading stdin
29
+ // so a deleted tree never pays the parse cost.
30
+ //
31
+ // We do NOT change the command string shape for existing installs (per the
32
+ // locked design decision): the command stays `node '<path>/statusline.js'`.
33
+ // When the script file itself is deleted, node fails to load it before this
34
+ // guard runs, and the host already renders that as a blank line, so the guard
35
+ // targets the partial-removal case (script present, tree gutted).
36
+ function _pluginTreeGone() {
37
+ // __dirname is this script's directory: <tree>/skills/token-optimizer/scripts
38
+ // (plugin cache) or <repo>/skills/token-optimizer/scripts (dev/script install).
39
+ // measure.py is the canonical sibling every real install ships alongside
40
+ // statusline.js. If it is gone while statusline.js remains, the plugin tree
41
+ // is being or has been removed, and a working status line would be a lie.
42
+ try {
43
+ if (!fs.existsSync(path.join(__dirname, 'measure.py'))) return true;
44
+ } catch (e) { return true; }
45
+ return false;
46
+ }
47
+
48
+ // --- Clone-path uninstall guard ---
49
+ // For plugin-cache installs the statusLine command now points at the marketplace
50
+ // CLONE (<claude>/plugins/marketplaces/<mkt>/skills/token-optimizer/scripts/
51
+ // statusline.js) so it survives version bumps. But a native `/plugin uninstall
52
+ // token-optimizer` removes only the plugin's CACHE tree
53
+ // (<claude>/plugins/cache/<mkt>/token-optimizer/<ver>) and leaves the shared
54
+ // marketplace clone in place. The clone still ships measure.py next to
55
+ // statusline.js, so _pluginTreeGone() stays false and we would render a working
56
+ // "ghost" status line for an uninstalled plugin. Detect that: when we are
57
+ // running FROM a marketplace clone and no token-optimizer cache install remains
58
+ // under the same <plugins> root, the plugin has been uninstalled -> self-disable.
59
+ function _pluginUninstalledFromClone() {
60
+ try {
61
+ const parts = __dirname.split(path.sep);
62
+ const mi = parts.lastIndexOf('marketplaces');
63
+ if (mi <= 0) return false; // not running from a clone
64
+ const marketplace = parts[mi + 1];
65
+ if (!marketplace) return false;
66
+ const pluginsDir = parts.slice(0, mi).join(path.sep); // <claude>/plugins
67
+ const cachePluginDir = path.join(pluginsDir, 'cache', marketplace, 'token-optimizer');
68
+ // A live plugin-cache install has at least one <version> dir here. The dir
69
+ // gone (or emptied) means `/plugin uninstall` removed the cache tree.
70
+ if (!fs.existsSync(cachePluginDir)) return true;
71
+ return fs.readdirSync(cachePluginDir).length === 0;
72
+ } catch (e) {
73
+ // Never blank a healthy line on an unexpected error: a lingering ghost is
74
+ // strictly less harmful than blanking a working status line.
75
+ return false;
76
+ }
77
+ }
78
+
79
+ if (_pluginTreeGone() || _pluginUninstalledFromClone()) {
80
+ process.exit(0);
81
+ }
82
+
83
+ // Claude Code's config dir. Mirrors runtime_env.claude_home(): honor
84
+ // CLAUDE_CONFIG_DIR when it is an ABSOLUTE, EXISTING, NON-SYMLINK directory,
85
+ // else ~/.claude. Hard-coding ~/.claude here split state with the Python hooks
86
+ // for relocated configs (#198): live-fill/rate-limits landed in ~/.claude while
87
+ // the hooks read $CLAUDE_CONFIG_DIR, and the quality cache was read from the
88
+ // wrong side. Any divergence from the Python rules reintroduces that split.
89
+ function _claudeHome() {
90
+ const fallback = path.join(os.homedir(), '.claude');
91
+ const raw = (process.env.CLAUDE_CONFIG_DIR || '').trim();
92
+ if (!raw) return fallback;
93
+ try {
94
+ const win = process.platform === 'win32';
95
+ // Path.expanduser() parity: only a bare ~ or ~/ (also ~\ on Windows).
96
+ const tilde = win ? /^~(?=$|[\\/])/ : /^~(?=$|\/)/;
97
+ let p = tilde.test(raw) ? os.homedir() + raw.slice(1) : raw;
98
+ // pathlib parity: drop empty and '.' segments, keep '..'. A trailing slash
99
+ // would make lstat follow a symlink pathlib rejects, and collapsing '..'
100
+ // lexically lands somewhere else under a symlinked parent.
101
+ const root = path.parse(p).root;
102
+ const segs = p.slice(root.length).split(win ? /[\\/]+/ : /\/+/);
103
+ p = root + segs.filter(s => s && s !== '.').join(path.sep);
104
+ // pathlib on Windows needs a drive or UNC root: a bare \foo is relative
105
+ // there, while Node's isAbsolute() would accept it.
106
+ const absolute = win ? /^([a-zA-Z]:[\\/]|[\\/]{2})/.test(p) : path.isAbsolute(p);
107
+ if (absolute) {
108
+ const st = fs.lstatSync(p); // lstat: a symlink is never isDirectory()
109
+ // realpath, like Python's resolve(), so '..' after a symlinked parent
110
+ // names the same physical dir on both sides. .native on purpose: the JS
111
+ // realpathSync collapses '..' lexically before resolving.
112
+ const real = () => { try { return fs.realpathSync.native(p); } catch (e) { return path.resolve(p); } };
113
+ if (st.isDirectory()) return real();
114
+ // Python's is_symlink() is False for a Windows junction (the usual way to
115
+ // relocate a dir without admin rights), so it accepts one. Node's lstat
116
+ // reports junctions as symlinks and cannot tell them apart, so accept any
117
+ // reparse point that resolves to a directory on Windows. The one residual
118
+ // mismatch is a true directory symlink there, which needs admin rights or
119
+ // Developer Mode and is far rarer than a junction.
120
+ if (win && st.isSymbolicLink() && fs.statSync(p).isDirectory()) return real();
121
+ }
122
+ } catch (e) {}
123
+ return fallback;
124
+ }
125
+ const CLAUDE_HOME = _claudeHome();
126
+
127
+ // Host parse (Claude Code 2.1.296 Dd/FOo): scientific notation and thousand
128
+ // separators first, then a decimal prefix. NaN or <= 0 is invalid and IGNORED
129
+ // (the next source applies). Mirrors measure.py _host_parse_int; shared vectors
130
+ // live in tests/fixtures/compact_window_env_vectors.json.
131
+ const _HOST_SCI = /^[+-]?(\d+(\.\d*)?|\.\d+)[eE][+-]?\d+$/;
132
+ const _HOST_GROUPED = /^[+-]?\d{1,3}([_,\u00A0\u202F ])\d{3}(?:\1\d{3})*$/;
133
+ function _hostParseInt(raw) {
134
+ const text = String(raw).trim();
135
+ if (text.length <= 32) {
136
+ if (_HOST_SCI.test(text)) {
137
+ const n = Number(text);
138
+ return Number.isInteger(n) ? n : NaN;
139
+ }
140
+ if (_HOST_GROUPED.test(text)) return parseInt(text.replace(/[_,\u00A0\u202F ]/g, ''), 10);
141
+ }
142
+ return parseInt(text, 10);
143
+ }
144
+ function _parseCompactWindow(v) {
145
+ if (v === null || v === undefined || typeof v === 'boolean') return null;
146
+ if (typeof v === 'number') return Number.isFinite(v) && v > 0 ? Math.floor(v) : null;
147
+ const n = _hostParseInt(v);
148
+ return Number.isNaN(n) || n <= 0 ? null : n;
149
+ }
150
+ // ---- Effective compact window (JS twin of measure.py effective_compact_window) ----
151
+ // Where THIS session auto-compacts, so the fill bar divides by the window the
152
+ // user will actually hit. Precedence (code.claude.com/docs/en/model-config):
153
+ // env CLAUDE_CODE_AUTO_COMPACT_WINDOW > per-model modelSettings (/autocompact)
154
+ // > top-level autoCompactWindow. Explicit values clamp to 100000..1000000 and
155
+ // cap at the model window; CLAUDE_AUTOCOMPACT_PCT_OVERRIDE (1-99, may be a float) then scales it
156
+ // down (it can never raise it). Returns the window in tokens ONLY when a real
157
+ // user override shrank it below the model window (the tuned ~967K default is
158
+ // not an override of the host's own number); otherwise null.
159
+ // Bedrock inference-profile ids are dot/colon-qualified
160
+ // ("us.anthropic.claude-haiku-4-5", "bedrock:claude-sonnet-4-5"): a leading
161
+ // chain of KNOWN provider/region tokens. Version dots ("gpt-4.1",
162
+ // "claude-3.5-sonnet") are never cut. Mirror of measure.py's
163
+ // _canonical_compact_model_id.
164
+ const _PROVIDER_PREFIX_RE = /^(?:(?:anthropic|openai|google|gemini|vertex|bedrock|openrouter|gateway|litellm|azure|aws|amazon|us|us-gov|eu|ap|apac|au|ca|cn|global|jp|sa|me|af|il)[.:])+/;
165
+ function _canonModelId(model) {
166
+ let m = String(model || '').trim().toLowerCase();
167
+ if (!m) return '';
168
+ m = m.split('/').pop().replace(_PROVIDER_PREFIX_RE, '').replace('[1m]', '').trim().replace(/[-@]\d{8}$/, '');
169
+ if (m && !m.startsWith('claude-')) m = 'claude-' + m;
170
+ return m;
171
+ }
172
+ function _reducedCompactWindow(modelId, modelWindow, settings) {
173
+ try {
174
+ if (!(modelWindow > 0)) return null;
175
+ const envBlock = (settings && typeof settings.env === 'object' && settings.env) || {};
176
+ const envVal = (name) => (process.env[name] !== undefined ? process.env[name] : envBlock[name]);
177
+ const clamp = (n) => Math.max(100000, Math.min(1000000, n));
178
+ let tokens = null;
179
+ let autoForModel = false;
180
+ const fromEnv = _parseCompactWindow(envVal('CLAUDE_CODE_AUTO_COMPACT_WINDOW'));
181
+ if (fromEnv !== null) {
182
+ tokens = clamp(fromEnv);
183
+ } else {
184
+ const ms = settings && settings.modelSettings;
185
+ if (ms && typeof ms === 'object') {
186
+ const raw = String(modelId || '').trim().toLowerCase();
187
+ const canon = _canonModelId(modelId);
188
+ const fam = /^(?:claude[-_])?(fable|mythos|opus|sonnet|haiku)/.exec(canon);
189
+ const family = fam ? fam[1] : '';
190
+ // Two passes: an exact/canonical id outranks a family alias regardless
191
+ // of key order; the first matching key decides (a non-window value is
192
+ // ignored like the host, not skipped to the next key).
193
+ let matched = false;
194
+ for (const kind of ['exact', 'family']) {
195
+ for (const key of Object.keys(ms)) {
196
+ const entry = ms[key];
197
+ if (!entry || typeof entry !== 'object' || !('autoCompactWindow' in entry)) continue;
198
+ const k = String(key).trim().toLowerCase();
199
+ const hit = kind === 'exact'
200
+ ? (k === raw || _canonModelId(k) === canon)
201
+ : (family !== '' && k === family);
202
+ if (!hit) continue;
203
+ matched = true;
204
+ // `/autocompact auto` is per model and means the tuned default: it
205
+ // replaces the top-level value for this model (no fall-through).
206
+ if (entry.autoCompactWindow === 'auto') { autoForModel = true; break; }
207
+ const w = _parseCompactWindow(entry.autoCompactWindow);
208
+ if (w !== null) tokens = clamp(w);
209
+ break;
210
+ }
211
+ if (matched) break;
212
+ }
213
+ }
214
+ if (tokens === null && settings && !autoForModel) {
215
+ const top = _parseCompactWindow(settings.autoCompactWindow);
216
+ if (top !== null) tokens = clamp(top);
217
+ }
218
+ }
219
+ if (tokens !== null && tokens > modelWindow) tokens = modelWindow;
220
+ // The host reads the percentage with parseFloat ("50.5" and "50%" count).
221
+ const pct = parseFloat(String(envVal('CLAUDE_AUTOCOMPACT_PCT_OVERRIDE') ?? '').trim());
222
+ if (Number.isFinite(pct) && pct >= 1 && pct < 100) {
223
+ tokens = Math.floor((tokens === null ? Math.min(modelWindow, 967000) : tokens) * pct / 100);
224
+ }
225
+ return tokens !== null && tokens < modelWindow ? tokens : null;
226
+ } catch (e) {
227
+ return null;
228
+ }
229
+ }
230
+
231
+ let input = '';
232
+ process.stdin.setEncoding('utf8');
233
+ process.stdin.on('data', chunk => input += chunk);
234
+ process.stdin.on('end', () => {
235
+ try {
236
+ const data = JSON.parse(input);
237
+ const model = data.model?.display_name || 'Claude';
238
+ const dir = data.workspace?.current_dir || process.cwd();
239
+ const remaining = data.context_window?.remaining_percentage;
240
+ const usedPct = data.context_window?.used_percentage;
241
+ const sessionId = data.session_id;
242
+ // Account-global usage limits (Pro/Max only, populated after first API
243
+ // response; each window may be independently absent). Handed only to the
244
+ // status line, persisted nowhere else, so we bridge it to a sidecar file
245
+ // for the VS Code companion (rate limits are account-wide, not per-session).
246
+ const rateLimits = data.rate_limits || null;
247
+ // A readable medium grey instead of ANSI faint (\x1b[2m), which renders too
248
+ // low-contrast for secondary info like session time on most terminals.
249
+ const DIM = '\x1b[38;5;245m';
250
+ const RESET = '\x1b[0m';
251
+ const SEP = ` ${DIM}|${RESET} `;
252
+
253
+ let branch = '';
254
+ try {
255
+ const b = execFileSync('git', ['branch', '--show-current'], {
256
+ cwd: dir,
257
+ encoding: 'utf8',
258
+ timeout: 200,
259
+ windowsHide: true,
260
+ stdio: ['ignore', 'pipe', 'ignore'],
261
+ }).trim();
262
+ if (b) branch = `${SEP}${DIM}(${b})${RESET}`;
263
+ } catch (e) {}
264
+ const gradeFor = (s) => s >= 90 ? 'S' : s >= 80 ? 'A' : s >= 70 ? 'B' : s >= 55 ? 'C' : s >= 40 ? 'D' : 'F';
265
+
266
+ // Effort level: prefer the LIVE session value Claude Code now passes in the
267
+ // statusline stdin (data.effort.level — reflects mid-session /effort changes,
268
+ // values low/medium/high/xhigh/max). Fall back to settings.json effortLevel
269
+ // for older Claude Code versions that don't send it (a session-only /effort
270
+ // there won't show, but it's the best available). 'max' is short enough to
271
+ // wear its own name.
272
+ let effort = '';
273
+ try {
274
+ let level = data.effort?.level;
275
+ if (!level) {
276
+ const settingsPath = path.join(CLAUDE_HOME, 'settings.json');
277
+ if (fs.existsSync(settingsPath)) {
278
+ const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
279
+ level = settings.effortLevel;
280
+ }
281
+ }
282
+ if (level) {
283
+ const effortMap = { low: 'lo', medium: 'med', high: 'hi', xhigh: 'xhi' };
284
+ const effortLabel = effortMap[level] || level;
285
+ effort = `${SEP}${DIM}${effortLabel}${RESET}`;
286
+ }
287
+ } catch (e) {}
288
+
289
+ // Cache directory (declared early, used by live-fill write and quality score read)
290
+ const cacheDir = path.join(CLAUDE_HOME, 'token-optimizer');
291
+
292
+ // Context window bar with degradation-aware colors
293
+ // Fill bands: <50% green, 50-70% yellow, 70-80% orange, 80%+ red (blinking)
294
+ let ctx = '';
295
+ const hostUsed = usedPct != null
296
+ ? Math.round(usedPct)
297
+ : (remaining != null ? Math.max(0, Math.min(100, 100 - Math.round(remaining))) : null);
298
+
299
+ // Fill on the window the session will actually compact at. When the user
300
+ // shrank it (env / /autocompact / autoCompactWindow / PCT override), divide
301
+ // the live token count by that window instead of the model window.
302
+ const cw = data.context_window || {};
303
+ const modelWindow = typeof cw.context_window_size === 'number' ? cw.context_window_size : null;
304
+ const cu = cw.current_usage || null;
305
+ const liveTokens = cu
306
+ ? (Number(cu.input_tokens) || 0) + (Number(cu.cache_creation_input_tokens) || 0)
307
+ + (Number(cu.cache_read_input_tokens) || 0)
308
+ : (hostUsed != null && modelWindow ? Math.round(hostUsed / 100 * modelWindow) : null);
309
+ let used = hostUsed;
310
+ try {
311
+ let settingsForWindow = null;
312
+ const sp = path.join(CLAUDE_HOME, 'settings.json');
313
+ if (fs.existsSync(sp)) settingsForWindow = JSON.parse(fs.readFileSync(sp, 'utf8'));
314
+ const reduced = modelWindow
315
+ ? _reducedCompactWindow(data.model && data.model.id, modelWindow, settingsForWindow)
316
+ : null;
317
+ if (reduced && liveTokens !== null && liveTokens >= 0) {
318
+ used = Math.max(0, Math.min(100, Math.round(liveTokens / reduced * 100)));
319
+ }
320
+ } catch (e) {}
321
+
322
+ // Sanitize session_id for safe use in filesystem paths
323
+ const safeSessionId = sessionId ? sessionId.replace(/[^a-zA-Z0-9_-]/g, '') : null;
324
+
325
+ if (used != null) {
326
+ const clamped = Math.max(0, Math.min(100, used));
327
+ const filled = Math.floor(clamped / 10);
328
+ const bar = '█'.repeat(filled) + '░'.repeat(10 - filled);
329
+
330
+ if (clamped < 50) {
331
+ ctx = `${SEP}\x1b[32m${bar} ${clamped}%${RESET}`;
332
+ } else if (clamped < 70) {
333
+ ctx = `${SEP}\x1b[33m${bar} ${clamped}%${RESET}`;
334
+ } else if (clamped < 80) {
335
+ ctx = `${SEP}\x1b[38;5;208m${bar} ${clamped}%${RESET}`;
336
+ } else {
337
+ ctx = `${SEP}\x1b[5;31m${bar} ${clamped}%${RESET}`;
338
+ }
339
+
340
+ // Write live fill data for quality score to use (bridges statusline -> quality cache)
341
+ try {
342
+ // used_percentage stays the HOST's model-window fill (measure.py scales
343
+ // it onto the effective compact window); context_tokens + window carry
344
+ // the numerator so it can recompute exactly.
345
+ const liveFillData = JSON.stringify({
346
+ used_percentage: hostUsed != null ? Math.max(0, Math.min(100, hostUsed)) : clamped,
347
+ context_tokens: liveTokens !== null && liveTokens > 0 ? liveTokens : undefined,
348
+ context_window: modelWindow || undefined,
349
+ timestamp: Date.now(),
350
+ session_id: sessionId || null
351
+ });
352
+ // PID-scoped tmp so two concurrent terminals never write the same
353
+ // temp file (which would corrupt one another's rename).
354
+ const tmpPath = path.join(cacheDir, `.live-fill.${process.pid}.tmp`);
355
+ fs.writeFileSync(tmpPath, liveFillData);
356
+ fs.renameSync(tmpPath, path.join(cacheDir, 'live-fill.json'));
357
+ } catch (e) {}
358
+ }
359
+
360
+ // ---- Write authoritative rate limits to a global sidecar ----
361
+ // Bridges status-line-only data (used %, reset time) to disk so the VS Code
362
+ // companion can show authoritative usage limits with no terminal of its own.
363
+ // Account-global file (not per-session): rate limits are account-wide.
364
+ const pickWindow = (w) => {
365
+ if (!w || typeof w.used_percentage !== 'number' || !isFinite(w.used_percentage)) return null;
366
+ return {
367
+ used_percentage: Math.max(0, Math.min(100, w.used_percentage)),
368
+ resets_at: typeof w.resets_at === 'number'
369
+ ? w.resets_at
370
+ : (typeof w.resets_at === 'string'
371
+ ? (Math.floor(Date.parse(w.resets_at) / 1000) || null)
372
+ : null)
373
+ };
374
+ };
375
+ const fiveHour = rateLimits ? pickWindow(rateLimits.five_hour) : null;
376
+ const sevenDay = rateLimits ? pickWindow(rateLimits.seven_day) : null;
377
+ if (fiveHour || sevenDay) {
378
+ try {
379
+ const payload = JSON.stringify({
380
+ five_hour: fiveHour,
381
+ seven_day: sevenDay,
382
+ timestamp: Date.now(),
383
+ source: 'statusline'
384
+ });
385
+ const rlTmp = path.join(cacheDir, `.rate-limits.${process.pid}.tmp`);
386
+ fs.writeFileSync(rlTmp, payload);
387
+ fs.renameSync(rlTmp, path.join(cacheDir, 'rate-limits.json'));
388
+ } catch (e) {}
389
+ }
390
+
391
+ // ---- Bridge the native prompt_cache object to a per-session sidecar ----
392
+ // Claude Code v2.1.251+ includes prompt_cache (ttl, expires_at, warm, ...)
393
+ // in the status-line input for MAIN conversations. measure.py status-bar
394
+ // reads prompt-cache-<sid>.json and prefers it over the transcript guess
395
+ // for the cache countdown and cache-cold warning. Older Claude Code sends
396
+ // no such field and we simply write nothing.
397
+ if (data.prompt_cache && typeof data.prompt_cache === 'object' && safeSessionId) {
398
+ try {
399
+ const pcTmp = path.join(cacheDir, `.prompt-cache.${process.pid}.tmp`);
400
+ fs.writeFileSync(pcTmp, JSON.stringify({ ...data.prompt_cache, timestamp: Date.now() }));
401
+ fs.renameSync(pcTmp, path.join(cacheDir, `prompt-cache-${safeSessionId}.json`));
402
+ } catch (e) {}
403
+ }
404
+
405
+ // ---- Read quality cache ----
406
+ // The hooks write the quality-cache under _STATE_BASE, which is
407
+ // ${CLAUDE_PLUGIN_DATA}/token-optimizer (<claude home>/plugins/data/{id}/...)
408
+ // when that env is set (the desktop plugin hook context), else <claude home>/
409
+ // token-optimizer. The statusline runs WITHOUT CLAUDE_PLUGIN_DATA, so reading only
410
+ // `cacheDir` (the claude-home fallback) missed the per-session cache the hooks
411
+ // wrote under plugins/data -> ContextQ/Eff showed "--" for every desktop
412
+ // plugin user. Search every candidate dir and take the freshest matching file.
413
+ let q = null;
414
+ try {
415
+ if (safeSessionId) {
416
+ const _candidates = [];
417
+ if (process.env.CLAUDE_PLUGIN_DATA) {
418
+ _candidates.push(path.join(process.env.CLAUDE_PLUGIN_DATA, 'token-optimizer'));
419
+ }
420
+ try {
421
+ const _dataRoot = path.join(CLAUDE_HOME, 'plugins', 'data');
422
+ for (const d of fs.readdirSync(_dataRoot)) {
423
+ if (d.includes('token-optimizer')) {
424
+ _candidates.push(path.join(_dataRoot, d, 'token-optimizer'));
425
+ }
426
+ }
427
+ } catch (e) {}
428
+ _candidates.push(cacheDir); // <claude home>/token-optimizer fallback (non-hook context)
429
+ let _best = null, _bestMtime = -1;
430
+ for (const c of _candidates) {
431
+ try {
432
+ const f = path.join(c, `quality-cache-${safeSessionId}.json`);
433
+ const st = fs.statSync(f);
434
+ if (st.mtimeMs > _bestMtime) { _bestMtime = st.mtimeMs; _best = f; }
435
+ } catch (e) {}
436
+ }
437
+ if (_best) {
438
+ q = JSON.parse(fs.readFileSync(_best, 'utf8'));
439
+ }
440
+ }
441
+ } catch (e) {}
442
+
443
+ const cacheMatchesSession = q && typeof q.session_file === 'string' && safeSessionId && q.session_file.includes(safeSessionId);
444
+
445
+ // ---- ROW 1: Core identity + context health ----
446
+ // Staleness guard: the score is recomputed by hooks (PostToolUse is
447
+ // throttled to ~2min). If the cache is older than 5 min the displayed score
448
+ // may not reflect recent activity, so mark it (~ prefix + dim) rather than
449
+ // showing a frozen score as if it were live.
450
+ let stale = false;
451
+ if (q) {
452
+ // Absent or unparseable timestamp => unknown age => treat as stale, so a
453
+ // cache written by an older plugin version can't show as live.
454
+ const ts = q.timestamp ? new Date(q.timestamp).getTime() : NaN;
455
+ if (isNaN(ts) || (Date.now() - ts) / 1000 > 300) stale = true;
456
+ }
457
+ let qScore = '';
458
+ if (q) {
459
+ const rh = q.resource_health != null ? q.resource_health : q.score;
460
+ if (rh != null) {
461
+ const score = Math.round(rh);
462
+ const grade = q.resource_health_grade || q.grade || gradeFor(score);
463
+ // Keep the score's value-color (green/yellow/orange/red) regardless of
464
+ // staleness; the `~` prefix is the only stale indicator so the number
465
+ // stays readable. (Dimming the whole score made it barely visible.)
466
+ const tag = `ContextQ:${stale ? '~' : ''}${grade}(${score})`;
467
+ if (score >= 85) {
468
+ qScore = `${SEP}\x1b[32m${tag}${RESET}`;
469
+ } else if (score >= 75) {
470
+ qScore = `${SEP}\x1b[33m${tag}${RESET}`;
471
+ } else if (score >= 50) {
472
+ qScore = `${SEP}\x1b[38;5;208m${tag}${RESET}`;
473
+ } else {
474
+ qScore = `${SEP}\x1b[31m${tag}${RESET}`;
475
+ }
476
+ }
477
+ } else {
478
+ qScore = `${SEP}${DIM}ContextQ:--${RESET}`;
479
+ }
480
+
481
+ const dirname = path.basename(dir);
482
+ // Row 1 as BARE segments (no baked-in SEP) so a narrow terminal can reflow them
483
+ // across physical rows instead of the host clipping the overflow. The effort/
484
+ // branch/ctx/qScore builders each prepend SEP, so strip that leading separator;
485
+ // packRows re-inserts it between whatever segments land on the same row.
486
+ const _stripLeadSep = s => (s && s.startsWith(SEP) ? s.slice(SEP.length) : s);
487
+ const row1Segs = [
488
+ `${DIM}${model}${RESET}`,
489
+ _stripLeadSep(effort),
490
+ `${DIM}${dirname}${RESET}`,
491
+ _stripLeadSep(branch),
492
+ _stripLeadSep(ctx),
493
+ _stripLeadSep(qScore),
494
+ ].filter(Boolean);
495
+
496
+ // ---- ROW 2: Session details ----
497
+ const row2Parts = [];
498
+
499
+ // U3: near-zero-cost "resumable checkpoint" existence signal.
500
+ // When the SessionStart pointer fired (a relevance-cleared checkpoint
501
+ // exists for this session), compact_restore wrote a per-session flag file
502
+ // beside the quality cache. Show a compact ⤸resumable token in the
503
+ // statusline UI ONLY -- this is never injected as additionalContext, so it
504
+ // costs zero billed tokens (R2). Stale flags (>30 min) are ignored so the
505
+ // signal does not outlive the resumable window.
506
+ try {
507
+ if (safeSessionId) {
508
+ const flagPath = path.join(cacheDir, `resumable-${safeSessionId}.json`);
509
+ if (fs.existsSync(flagPath)) {
510
+ const flag = JSON.parse(fs.readFileSync(flagPath, 'utf8'));
511
+ const ts = typeof flag.ts === 'number' ? flag.ts : NaN;
512
+ if (isFinite(ts) && (Date.now() - ts) < (30 * 60 * 1000)) {
513
+ row2Parts.push(`\x1b[36m⤸resumable${RESET}`);
514
+ }
515
+ }
516
+ }
517
+ } catch (e) {}
518
+
519
+ // SessionEfficiency
520
+ if (q) {
521
+ const se = q.session_efficiency;
522
+ if (se != null) {
523
+ const seScore = Math.round(se);
524
+ const seGrade = q.session_efficiency_grade || gradeFor(seScore);
525
+ row2Parts.push(`${DIM}Eff:${seGrade}(${seScore})${RESET}`);
526
+ }
527
+ } else {
528
+ row2Parts.push(`${DIM}Eff:--${RESET}`);
529
+ }
530
+
531
+ // Biggest drag: the actual signal pulling the score down — context fill,
532
+ // compactions, or the dominant waste cause — computed upstream by weighted
533
+ // deficit, not guessed from waste keys here.
534
+ if (q && q.top_drag && q.top_drag.label) {
535
+ row2Parts.push(`${DIM}Drag:${q.top_drag.label}${RESET}`);
536
+ }
537
+
538
+ // Fill warning
539
+ if (q) {
540
+ const fw = q.fill_warning;
541
+ if (fw && fw.level) {
542
+ if (fw.level === 'CRITICAL') {
543
+ row2Parts.push(`\x1b[5;31mFill:${Math.round(fw.fill_pct)}%!${RESET}`);
544
+ } else if (fw.level === 'WARNING') {
545
+ row2Parts.push(`\x1b[33mFill:${Math.round(fw.fill_pct)}%${RESET}`);
546
+ }
547
+ }
548
+
549
+ // Tool call fatigue warning
550
+ const tcw = q.tool_call_warning;
551
+ if (tcw && tcw.level === 'CRITICAL') {
552
+ row2Parts.push(`\x1b[31mTools:${q.tool_calls}!${RESET}`);
553
+ } else if (tcw && tcw.level === 'WARNING') {
554
+ row2Parts.push(`\x1b[33mTools:${q.tool_calls}${RESET}`);
555
+ }
556
+ }
557
+
558
+ // Compaction count
559
+ if (q) {
560
+ const c = q.compactions;
561
+ if (c != null) {
562
+ if (c > 0) {
563
+ const lossPct = q.breakdown?.compaction_depth?.cumulative_loss_pct;
564
+ const loss = lossPct ? `~${Math.round(lossPct)}%` : (c >= 3 ? '~95%' : c >= 2 ? '~88%' : '~65%');
565
+ const color = c <= 2 ? '\x1b[33m' : '\x1b[31m';
566
+ row2Parts.push(`${color}Compacts:${c}(${loss} lost)${RESET}`);
567
+ } else {
568
+ row2Parts.push(`\x1b[32mCompacts:0${RESET}`);
569
+ }
570
+ }
571
+ }
572
+
573
+ // Session duration - ALWAYS shown when cache matches session
574
+ if (cacheMatchesSession && q.session_start_ts > 0) {
575
+ const elapsed = Math.floor((Date.now() / 1000) - q.session_start_ts);
576
+ if (elapsed > 0 && elapsed < 604800) {
577
+ const h = Math.floor(elapsed / 3600);
578
+ const m = Math.floor((elapsed % 3600) / 60);
579
+ const dur = h > 0 ? `${h}h${m}m` : `${m}m`;
580
+ row2Parts.push(`${DIM}${dur}${RESET}`);
581
+ }
582
+ }
583
+
584
+ // Active agents
585
+ const stripAnsi = s => String(s).replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '').replace(/[\x00-\x1f]/g, '');
586
+ if (cacheMatchesSession && q.active_agents && q.active_agents.length > 0) {
587
+ const running = q.active_agents.filter(a => a.status === 'running');
588
+ if (running.length > 0) {
589
+ const agentParts = running.slice(0, 3).map(a => {
590
+ const m = stripAnsi(a.model || '?');
591
+ const desc = stripAnsi(a.description || '');
592
+ let elapsed = '';
593
+ if (a.start_time) {
594
+ try {
595
+ const secs = Math.floor((Date.now() - new Date(a.start_time).getTime()) / 1000);
596
+ elapsed = secs >= 60 ? `${Math.floor(secs / 60)}m${secs % 60}s` : `${secs}s`;
597
+ } catch (e) {}
598
+ }
599
+ return `\x1b[33m${m}\x1b[0m:${desc}${elapsed ? '(' + elapsed + ')' : ''}`;
600
+ });
601
+ row2Parts.push(`Agents: ${agentParts.join(' ')}`);
602
+ }
603
+ }
604
+
605
+ // Usage limits row fragment (5h primary, 7d compact). Colored by pressure.
606
+ const fmtReset = (epochSec) => {
607
+ if (typeof epochSec !== 'number' || epochSec <= 0) return '';
608
+ try {
609
+ const d = new Date(epochSec * 1000);
610
+ let h = d.getHours();
611
+ const m = d.getMinutes();
612
+ const ap = h >= 12 ? 'p' : 'a';
613
+ h = h % 12; if (h === 0) h = 12;
614
+ return ` ↺${h}:${String(m).padStart(2, '0')}${ap}`;
615
+ } catch (e) { return ''; }
616
+ };
617
+ const limitColor = (pct) =>
618
+ pct >= 90 ? '\x1b[5;31m' : pct >= 75 ? '\x1b[38;5;208m' : pct >= 50 ? '\x1b[33m' : '\x1b[32m';
619
+ if (fiveHour) {
620
+ const p = Math.ceil(fiveHour.used_percentage);
621
+ row2Parts.push(`${limitColor(p)}5h:${p}%${fmtReset(fiveHour.resets_at)}${RESET}`);
622
+ }
623
+ if (sevenDay) {
624
+ const p = Math.ceil(sevenDay.used_percentage);
625
+ row2Parts.push(`${DIM}7d:${p}%${RESET}`);
626
+ }
627
+
628
+ // Responsive layout: when Claude Code exports COLUMNS (v2.1.153+), greedily pack
629
+ // each row's segments into physical rows no wider than the terminal, so narrow
630
+ // windows drop segments to the next line instead of the host clipping them.
631
+ // COLUMNS unset (older Claude Code) -> the exact prior two-row output, byte-for-byte.
632
+ const vlen = s => stripAnsi(s).length; // visible width; SEP (" | ") is 3 cols
633
+ const packRows = (segs, width) => {
634
+ const rows = [];
635
+ let cur = '';
636
+ for (const seg of segs) {
637
+ if (cur === '') { cur = seg; continue; }
638
+ if (vlen(cur) + 3 + vlen(seg) <= width) cur += SEP + seg;
639
+ else { rows.push(cur); cur = seg; } // a lone over-wide segment still clips (unsplittable)
640
+ }
641
+ if (cur !== '') rows.push(cur);
642
+ return rows;
643
+ };
644
+ const _cols = parseInt(process.env.COLUMNS, 10);
645
+ const _width = Number.isFinite(_cols) && _cols > 4 ? _cols : null;
646
+ // TOKEN_OPTIMIZER_STATUS_BAR_SIZE=slim: one line with the most important
647
+ // fields (row 1), never wrapped, whatever COLUMNS says.
648
+ const _slim = (process.env.TOKEN_OPTIMIZER_STATUS_BAR_SIZE || '').trim().toLowerCase() === 'slim';
649
+ if (_slim) {
650
+ process.stdout.write(row1Segs.join(SEP));
651
+ } else if (_width) {
652
+ const rows = [...packRows(row1Segs, _width), ...packRows(row2Parts, _width)];
653
+ process.stdout.write(rows.join('\n'));
654
+ } else {
655
+ process.stdout.write(`${row1Segs.join(SEP)}\n${row2Parts.join(SEP)}`);
656
+ }
657
+ } catch (e) {
658
+ // Silent fail - never break the status line
659
+ }
660
+ });