tokenusage-cli 0.1.0 → 0.2.0

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 (131) hide show
  1. package/CHANGELOG.md +39 -19
  2. package/LICENSE +22 -22
  3. package/README.md +94 -94
  4. package/THIRD_PARTY_NOTICES.md +140 -140
  5. package/bin/tokenusage.js +69 -69
  6. package/package.json +59 -59
  7. package/src/cli.js +146 -134
  8. package/src/commands/device-login.js +205 -205
  9. package/src/commands/diagnostics.js +38 -38
  10. package/src/commands/doctor.js +110 -110
  11. package/src/commands/init.js +2484 -2436
  12. package/src/commands/pause.js +77 -0
  13. package/src/commands/sessions.js +29 -29
  14. package/src/commands/status.js +1758 -1747
  15. package/src/commands/sync.js +8048 -7934
  16. package/src/commands/uninstall.js +322 -312
  17. package/src/lib/account-usage-dedup.js +267 -267
  18. package/src/lib/antigravity-paths.js +48 -48
  19. package/src/lib/ark-agent-plan-limits.js +438 -438
  20. package/src/lib/ark-coding-plan-limits.js +537 -537
  21. package/src/lib/async-queue-reader.js +138 -138
  22. package/src/lib/atomic-json.js +27 -27
  23. package/src/lib/bearer-token.js +11 -11
  24. package/src/lib/categorizer-utils.js +232 -232
  25. package/src/lib/claude-categorizer.js +1343 -1343
  26. package/src/lib/claude-config.js +279 -279
  27. package/src/lib/claude-user-identity.js +56 -56
  28. package/src/lib/cli-ui.js +179 -179
  29. package/src/lib/cloud-account.js +541 -541
  30. package/src/lib/cloud-device-token.js +141 -141
  31. package/src/lib/cloud-sync-prefs.js +14 -14
  32. package/src/lib/cloud-usage-reset.js +115 -115
  33. package/src/lib/codex-config.js +595 -595
  34. package/src/lib/codex-context-breakdown.js +806 -806
  35. package/src/lib/codex-model-attribution.js +128 -128
  36. package/src/lib/codex-rollout-parser.js +1471 -1471
  37. package/src/lib/codex-service-tier.js +49 -49
  38. package/src/lib/codex-token-refresh.js +140 -140
  39. package/src/lib/codex-token-usage.js +195 -195
  40. package/src/lib/codex-usage-record.js +195 -195
  41. package/src/lib/collection-pause.js +77 -0
  42. package/src/lib/command-runner.js +313 -313
  43. package/src/lib/commandcode-limits.js +317 -317
  44. package/src/lib/context-health.js +124 -124
  45. package/src/lib/cursor-config.js +605 -605
  46. package/src/lib/cursor-store.js +1918 -1918
  47. package/src/lib/debug-flags.js +7 -7
  48. package/src/lib/devin-limits.js +249 -249
  49. package/src/lib/devin-usage.js +212 -212
  50. package/src/lib/diagnostics.js +383 -383
  51. package/src/lib/doctor.js +385 -385
  52. package/src/lib/dumate.js +95 -95
  53. package/src/lib/fs.js +455 -455
  54. package/src/lib/function-url.js +14 -14
  55. package/src/lib/gemini-config.js +291 -291
  56. package/src/lib/git-outcomes.js +243 -243
  57. package/src/lib/grok-context-breakdown.js +890 -890
  58. package/src/lib/grok-hook.js +360 -360
  59. package/src/lib/grok-limits.js +865 -865
  60. package/src/lib/grok-usage.js +98 -98
  61. package/src/lib/heatmap-compact.js +114 -114
  62. package/src/lib/ingest-sanitize.js +41 -41
  63. package/src/lib/init-flow.js +42 -42
  64. package/src/lib/install-resolver.js +170 -170
  65. package/src/lib/jsonl-lines.js +134 -134
  66. package/src/lib/kimi-model-repair.js +173 -173
  67. package/src/lib/kimi-profile.js +61 -61
  68. package/src/lib/kimi-session.js +216 -216
  69. package/src/lib/local-api.js +3588 -3588
  70. package/src/lib/machine-id.js +238 -238
  71. package/src/lib/multi-install-parser.js +113 -113
  72. package/src/lib/notify-command.js +38 -38
  73. package/src/lib/omp-hook.js +589 -589
  74. package/src/lib/openclaw-cli.js +104 -104
  75. package/src/lib/openclaw-hook.js +375 -375
  76. package/src/lib/openclaw-session-plugin.js +560 -560
  77. package/src/lib/opencode-config.js +121 -121
  78. package/src/lib/opencode-go-limits.js +807 -807
  79. package/src/lib/outcomes-engine.js +253 -253
  80. package/src/lib/passive-mode.js +219 -219
  81. package/src/lib/pet-packages.js +722 -722
  82. package/src/lib/pricing/curated-overrides.json +822 -822
  83. package/src/lib/pricing/index.js +379 -379
  84. package/src/lib/pricing/litellm-fetcher.js +172 -172
  85. package/src/lib/pricing/matcher.js +456 -456
  86. package/src/lib/pricing/seed-snapshot.json +1 -1
  87. package/src/lib/progress.js +76 -76
  88. package/src/lib/project-usage-purge.js +117 -117
  89. package/src/lib/prompt.js +24 -24
  90. package/src/lib/provider-status.js +104 -104
  91. package/src/lib/proxy-env.js +489 -489
  92. package/src/lib/proxy-settings.js +163 -163
  93. package/src/lib/qoder-cn-cli-limits.js +119 -119
  94. package/src/lib/qoder-limits.js +880 -880
  95. package/src/lib/quiet-warnings.js +26 -26
  96. package/src/lib/rollout.js +26005 -25966
  97. package/src/lib/runtime-config.js +9 -4
  98. package/src/lib/scan-roots.js +277 -277
  99. package/src/lib/scheduled-task.js +145 -0
  100. package/src/lib/sentry.js +231 -231
  101. package/src/lib/session-analytics.js +2972 -2972
  102. package/src/lib/session-performance.js +237 -237
  103. package/src/lib/session-upload.js +379 -379
  104. package/src/lib/skill-usage.js +267 -267
  105. package/src/lib/skills-manager.js +1591 -1591
  106. package/src/lib/source-metadata.js +48 -48
  107. package/src/lib/sqlite-reader.js +215 -215
  108. package/src/lib/star-cta.js +73 -73
  109. package/src/lib/subscription-manager.js +293 -293
  110. package/src/lib/subscriptions.js +508 -508
  111. package/src/lib/sync-report.js +138 -0
  112. package/src/lib/telemetry.js +193 -193
  113. package/src/lib/tracker-paths.js +16 -16
  114. package/src/lib/trae-cn-config.js +548 -548
  115. package/src/lib/trae-db.js +127 -127
  116. package/src/lib/trae-snapshot.js +230 -230
  117. package/src/lib/trae-sqlite.js +143 -143
  118. package/src/lib/trae-usage.js +121 -121
  119. package/src/lib/upload-queue.js +134 -134
  120. package/src/lib/upload-throttle.js +171 -171
  121. package/src/lib/usage-limits.js +4552 -4552
  122. package/src/lib/wrapped-aggregator.js +236 -236
  123. package/src/lib/wsl-probe.js +281 -281
  124. package/src/lib/zcode-limits.js +1172 -1172
  125. package/src/lib/zcode-reset-credits.js +66 -66
  126. package/test/audit-fixes.test.js +200 -0
  127. package/test/cli-smoke.test.js +53 -53
  128. package/test/collection-controls.test.js +181 -0
  129. package/test/ingest-sanitize.test.js +162 -162
  130. package/test/quiet-warnings.test.js +53 -53
  131. package/test/session-upload.test.js +427 -427
@@ -1,195 +1,195 @@
1
- "use strict";
2
-
3
- // Codex rollouts written since CLI 0.151 carry a top-level
4
- // {"type":"token_usage_record","payload":{usage,turn_token_usage,thread_token_usage,...}}
5
- // next to the event_msg token_count that has always carried usage (issue
6
- // #652). While both are written they describe the same model response, so
7
- // token_count stays the only source of normal usage and a record is counted
8
- // in exactly one case:
9
- //
10
- // Compaction. Codex bills the compaction model call in a record that is
11
- // immediately followed by a top-level `compacted` line, and the next
12
- // token_count repeats the previous cumulative total (its last_token_usage is
13
- // the post-compaction context size, not a response). The cumulative delta is
14
- // zero, so without the record the call is lost. Inside a file that has
15
- // already shown a token_count, such a record is held as `compaction` and
16
- // counted when the next token_count arrives with a total identical to the
17
- // previous one. If that total advanced, the token_count already covers the
18
- // call and the record is dropped. Each compaction is counted once per
19
- // payload.response_id: a fork replays its parent's records and a copied
20
- // rollout repeats them, both with the same id. A record without one is never
21
- // counted.
22
- //
23
- // A file whose records are never matched by a token_count is not counted from
24
- // its records. It is flagged `recordOnly` instead, and sync surfaces a
25
- // warning. The proof is the same ordering Codex keeps for every response: its
26
- // token_count is written after its record and before the next record or the
27
- // turn end. So a record followed by another record or a turn end with no
28
- // token_count in between flags the file; a sync that stops between a record
29
- // and its token_count does not.
30
- //
31
- // payload.usage is the per-response delta; turn_token_usage and
32
- // thread_token_usage are cumulative and are never read. All state below is
33
- // persisted in the sync cursor and the session parser resume state, so the
34
- // record, the `compacted` line and the token_count may land in different
35
- // reads.
36
-
37
- const { canonicalUsage, sameUsage } = require("./codex-token-usage");
38
-
39
- function extractTokenUsageRecord(obj) {
40
- if (obj?.type !== "token_usage_record") return null;
41
- const usage = obj.payload?.usage;
42
- if (!usage || typeof usage !== "object" || Array.isArray(usage)) return null;
43
- const timestamp = typeof obj.timestamp === "string" ? obj.timestamp : null;
44
- if (!timestamp) return null;
45
- // canonicalUsage folds cache_write_input_tokens into
46
- // cache_creation_input_tokens exactly as the token_count path does.
47
- const canonical = canonicalUsage(usage);
48
- if (!canonical) return null;
49
- const responseId = typeof obj.payload.response_id === "string" && obj.payload.response_id
50
- ? obj.payload.response_id
51
- : null;
52
- return { usage: canonical, timestamp, responseId };
53
- }
54
-
55
- // Compaction calls already counted by sync, by response_id, kept in core
56
- // cursor state as cursors.codexCompactionResponseIds (oldest first). The id
57
- // is unique per API response and survives fork replays and file copies, so
58
- // it is the only dedup key a compaction needs. Compactions are rare (19 on
59
- // the maintainer's corpus), so the cap is far above any real history.
60
- const MAX_COMPACTION_RESPONSE_IDS = 20000;
61
-
62
- function createCompactionResponseIds(cursors) {
63
- const stored = Array.isArray(cursors.codexCompactionResponseIds)
64
- ? cursors.codexCompactionResponseIds
65
- : [];
66
- const ids = new Set(stored);
67
- const added = [];
68
- return {
69
- has: (id) => ids.has(id),
70
- add(id) {
71
- if (ids.has(id)) return;
72
- ids.add(id);
73
- added.push(id);
74
- },
75
- persist() {
76
- if (added.length === 0) return;
77
- cursors.codexCompactionResponseIds = [...stored, ...added].slice(-MAX_COMPACTION_RESPONSE_IDS);
78
- },
79
- };
80
- }
81
-
82
- function isCodexTurnEndEvent(obj) {
83
- if (obj?.type !== "event_msg") return false;
84
- const type = obj.payload?.type;
85
- return type === "task_complete" || type === "turn_aborted";
86
- }
87
-
88
- function isPlainObject(value) {
89
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
90
- }
91
-
92
- function createUsageRecordState(snapshot) {
93
- const compaction = snapshot?.compaction;
94
- return {
95
- sawTokenCount: Boolean(snapshot?.sawTokenCount),
96
- unmatchedRecord: Boolean(snapshot?.unmatchedRecord),
97
- recordOnly: Boolean(snapshot?.recordOnly),
98
- compaction: isPlainObject(compaction) && isPlainObject(compaction.candidate)
99
- ? { candidate: compaction.candidate, compacted: Boolean(compaction.compacted) }
100
- : null,
101
- };
102
- }
103
-
104
- // Called for every token_count carrying an info object.
105
- function noteTokenCount(state) {
106
- state.sawTokenCount = true;
107
- state.unmatchedRecord = false;
108
- state.recordOnly = false;
109
- }
110
-
111
- // Called for every record. `candidate` is what the caller would count if the
112
- // record turns out to be a compaction call (null when it cannot be counted).
113
- function noteUsageRecord(state, candidate) {
114
- if (state.sawTokenCount) {
115
- state.compaction = candidate ? { candidate, compacted: false } : null;
116
- return;
117
- }
118
- if (state.unmatchedRecord) state.recordOnly = true;
119
- state.unmatchedRecord = true;
120
- }
121
-
122
- // Turn end: a record still waiting for its token_count will not get one.
123
- function noteTurnEnd(state) {
124
- if (state.sawTokenCount) return;
125
- if (state.unmatchedRecord) state.recordOnly = true;
126
- state.unmatchedRecord = false;
127
- }
128
-
129
- // True while the line right after a record decides whether it was a
130
- // compaction call.
131
- function awaitsCompactedLine(state) {
132
- return Boolean(state?.compaction && !state.compaction.compacted);
133
- }
134
-
135
- // Called for each complete line after a record, other than a record. Only a
136
- // `compacted` line directly after the record keeps it as a candidate.
137
- function noteLineAfterUsageRecord(state, isCompactedLine) {
138
- if (!awaitsCompactedLine(state)) return;
139
- if (isCompactedLine) state.compaction.compacted = true;
140
- else state.compaction = null;
141
- }
142
-
143
- // Called for every token_count carrying an info object, with the cumulative
144
- // total that was active before it. Returns the compaction candidate to count,
145
- // or null.
146
- function takeCompactionOnTokenCount(state, previousTotal, totalUsage) {
147
- const compaction = state.compaction;
148
- state.compaction = null;
149
- if (!compaction?.compacted) return null;
150
- if (!canonicalUsage(previousTotal) || !sameUsage(previousTotal, totalUsage)) return null;
151
- return compaction.candidate;
152
- }
153
-
154
- function isRecordOnly(state) {
155
- return Boolean(state?.recordOnly && !state.sawTokenCount);
156
- }
157
-
158
- function snapshotUsageRecordState(state) {
159
- if (!state || (!state.sawTokenCount && !state.unmatchedRecord && !state.recordOnly)) return null;
160
- const out = { sawTokenCount: state.sawTokenCount };
161
- if (state.unmatchedRecord) out.unmatchedRecord = true;
162
- if (state.recordOnly) out.recordOnly = true;
163
- if (state.compaction) out.compaction = state.compaction;
164
- return out;
165
- }
166
-
167
- // Sync keeps the flagged rollouts in core cursor state:
168
- // cursors.codexUsageRecordOnlyFiles = { [rolloutPath]: true }.
169
- function countRecordOnlyFiles(cursors) {
170
- const flagged = cursors?.codexUsageRecordOnlyFiles;
171
- return isPlainObject(flagged) ? Object.keys(flagged).length : 0;
172
- }
173
-
174
- function formatRecordOnlyWarning(count) {
175
- if (!count) return null;
176
- return `${count} Codex session(s) report usage only via token_usage_record; not counted yet (see #652)`;
177
- }
178
-
179
- module.exports = {
180
- MAX_COMPACTION_RESPONSE_IDS,
181
- createCompactionResponseIds,
182
- countRecordOnlyFiles,
183
- formatRecordOnlyWarning,
184
- awaitsCompactedLine,
185
- createUsageRecordState,
186
- extractTokenUsageRecord,
187
- isCodexTurnEndEvent,
188
- isRecordOnly,
189
- noteLineAfterUsageRecord,
190
- noteTokenCount,
191
- noteTurnEnd,
192
- noteUsageRecord,
193
- snapshotUsageRecordState,
194
- takeCompactionOnTokenCount,
195
- };
1
+ "use strict";
2
+
3
+ // Codex rollouts written since CLI 0.151 carry a top-level
4
+ // {"type":"token_usage_record","payload":{usage,turn_token_usage,thread_token_usage,...}}
5
+ // next to the event_msg token_count that has always carried usage (issue
6
+ // #652). While both are written they describe the same model response, so
7
+ // token_count stays the only source of normal usage and a record is counted
8
+ // in exactly one case:
9
+ //
10
+ // Compaction. Codex bills the compaction model call in a record that is
11
+ // immediately followed by a top-level `compacted` line, and the next
12
+ // token_count repeats the previous cumulative total (its last_token_usage is
13
+ // the post-compaction context size, not a response). The cumulative delta is
14
+ // zero, so without the record the call is lost. Inside a file that has
15
+ // already shown a token_count, such a record is held as `compaction` and
16
+ // counted when the next token_count arrives with a total identical to the
17
+ // previous one. If that total advanced, the token_count already covers the
18
+ // call and the record is dropped. Each compaction is counted once per
19
+ // payload.response_id: a fork replays its parent's records and a copied
20
+ // rollout repeats them, both with the same id. A record without one is never
21
+ // counted.
22
+ //
23
+ // A file whose records are never matched by a token_count is not counted from
24
+ // its records. It is flagged `recordOnly` instead, and sync surfaces a
25
+ // warning. The proof is the same ordering Codex keeps for every response: its
26
+ // token_count is written after its record and before the next record or the
27
+ // turn end. So a record followed by another record or a turn end with no
28
+ // token_count in between flags the file; a sync that stops between a record
29
+ // and its token_count does not.
30
+ //
31
+ // payload.usage is the per-response delta; turn_token_usage and
32
+ // thread_token_usage are cumulative and are never read. All state below is
33
+ // persisted in the sync cursor and the session parser resume state, so the
34
+ // record, the `compacted` line and the token_count may land in different
35
+ // reads.
36
+
37
+ const { canonicalUsage, sameUsage } = require("./codex-token-usage");
38
+
39
+ function extractTokenUsageRecord(obj) {
40
+ if (obj?.type !== "token_usage_record") return null;
41
+ const usage = obj.payload?.usage;
42
+ if (!usage || typeof usage !== "object" || Array.isArray(usage)) return null;
43
+ const timestamp = typeof obj.timestamp === "string" ? obj.timestamp : null;
44
+ if (!timestamp) return null;
45
+ // canonicalUsage folds cache_write_input_tokens into
46
+ // cache_creation_input_tokens exactly as the token_count path does.
47
+ const canonical = canonicalUsage(usage);
48
+ if (!canonical) return null;
49
+ const responseId = typeof obj.payload.response_id === "string" && obj.payload.response_id
50
+ ? obj.payload.response_id
51
+ : null;
52
+ return { usage: canonical, timestamp, responseId };
53
+ }
54
+
55
+ // Compaction calls already counted by sync, by response_id, kept in core
56
+ // cursor state as cursors.codexCompactionResponseIds (oldest first). The id
57
+ // is unique per API response and survives fork replays and file copies, so
58
+ // it is the only dedup key a compaction needs. Compactions are rare (19 on
59
+ // the maintainer's corpus), so the cap is far above any real history.
60
+ const MAX_COMPACTION_RESPONSE_IDS = 20000;
61
+
62
+ function createCompactionResponseIds(cursors) {
63
+ const stored = Array.isArray(cursors.codexCompactionResponseIds)
64
+ ? cursors.codexCompactionResponseIds
65
+ : [];
66
+ const ids = new Set(stored);
67
+ const added = [];
68
+ return {
69
+ has: (id) => ids.has(id),
70
+ add(id) {
71
+ if (ids.has(id)) return;
72
+ ids.add(id);
73
+ added.push(id);
74
+ },
75
+ persist() {
76
+ if (added.length === 0) return;
77
+ cursors.codexCompactionResponseIds = [...stored, ...added].slice(-MAX_COMPACTION_RESPONSE_IDS);
78
+ },
79
+ };
80
+ }
81
+
82
+ function isCodexTurnEndEvent(obj) {
83
+ if (obj?.type !== "event_msg") return false;
84
+ const type = obj.payload?.type;
85
+ return type === "task_complete" || type === "turn_aborted";
86
+ }
87
+
88
+ function isPlainObject(value) {
89
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
90
+ }
91
+
92
+ function createUsageRecordState(snapshot) {
93
+ const compaction = snapshot?.compaction;
94
+ return {
95
+ sawTokenCount: Boolean(snapshot?.sawTokenCount),
96
+ unmatchedRecord: Boolean(snapshot?.unmatchedRecord),
97
+ recordOnly: Boolean(snapshot?.recordOnly),
98
+ compaction: isPlainObject(compaction) && isPlainObject(compaction.candidate)
99
+ ? { candidate: compaction.candidate, compacted: Boolean(compaction.compacted) }
100
+ : null,
101
+ };
102
+ }
103
+
104
+ // Called for every token_count carrying an info object.
105
+ function noteTokenCount(state) {
106
+ state.sawTokenCount = true;
107
+ state.unmatchedRecord = false;
108
+ state.recordOnly = false;
109
+ }
110
+
111
+ // Called for every record. `candidate` is what the caller would count if the
112
+ // record turns out to be a compaction call (null when it cannot be counted).
113
+ function noteUsageRecord(state, candidate) {
114
+ if (state.sawTokenCount) {
115
+ state.compaction = candidate ? { candidate, compacted: false } : null;
116
+ return;
117
+ }
118
+ if (state.unmatchedRecord) state.recordOnly = true;
119
+ state.unmatchedRecord = true;
120
+ }
121
+
122
+ // Turn end: a record still waiting for its token_count will not get one.
123
+ function noteTurnEnd(state) {
124
+ if (state.sawTokenCount) return;
125
+ if (state.unmatchedRecord) state.recordOnly = true;
126
+ state.unmatchedRecord = false;
127
+ }
128
+
129
+ // True while the line right after a record decides whether it was a
130
+ // compaction call.
131
+ function awaitsCompactedLine(state) {
132
+ return Boolean(state?.compaction && !state.compaction.compacted);
133
+ }
134
+
135
+ // Called for each complete line after a record, other than a record. Only a
136
+ // `compacted` line directly after the record keeps it as a candidate.
137
+ function noteLineAfterUsageRecord(state, isCompactedLine) {
138
+ if (!awaitsCompactedLine(state)) return;
139
+ if (isCompactedLine) state.compaction.compacted = true;
140
+ else state.compaction = null;
141
+ }
142
+
143
+ // Called for every token_count carrying an info object, with the cumulative
144
+ // total that was active before it. Returns the compaction candidate to count,
145
+ // or null.
146
+ function takeCompactionOnTokenCount(state, previousTotal, totalUsage) {
147
+ const compaction = state.compaction;
148
+ state.compaction = null;
149
+ if (!compaction?.compacted) return null;
150
+ if (!canonicalUsage(previousTotal) || !sameUsage(previousTotal, totalUsage)) return null;
151
+ return compaction.candidate;
152
+ }
153
+
154
+ function isRecordOnly(state) {
155
+ return Boolean(state?.recordOnly && !state.sawTokenCount);
156
+ }
157
+
158
+ function snapshotUsageRecordState(state) {
159
+ if (!state || (!state.sawTokenCount && !state.unmatchedRecord && !state.recordOnly)) return null;
160
+ const out = { sawTokenCount: state.sawTokenCount };
161
+ if (state.unmatchedRecord) out.unmatchedRecord = true;
162
+ if (state.recordOnly) out.recordOnly = true;
163
+ if (state.compaction) out.compaction = state.compaction;
164
+ return out;
165
+ }
166
+
167
+ // Sync keeps the flagged rollouts in core cursor state:
168
+ // cursors.codexUsageRecordOnlyFiles = { [rolloutPath]: true }.
169
+ function countRecordOnlyFiles(cursors) {
170
+ const flagged = cursors?.codexUsageRecordOnlyFiles;
171
+ return isPlainObject(flagged) ? Object.keys(flagged).length : 0;
172
+ }
173
+
174
+ function formatRecordOnlyWarning(count) {
175
+ if (!count) return null;
176
+ return `${count} Codex session(s) report usage only via token_usage_record; not counted yet (see #652)`;
177
+ }
178
+
179
+ module.exports = {
180
+ MAX_COMPACTION_RESPONSE_IDS,
181
+ createCompactionResponseIds,
182
+ countRecordOnlyFiles,
183
+ formatRecordOnlyWarning,
184
+ awaitsCompactedLine,
185
+ createUsageRecordState,
186
+ extractTokenUsageRecord,
187
+ isCodexTurnEndEvent,
188
+ isRecordOnly,
189
+ noteLineAfterUsageRecord,
190
+ noteTokenCount,
191
+ noteTurnEnd,
192
+ noteUsageRecord,
193
+ snapshotUsageRecordState,
194
+ takeCompactionOnTokenCount,
195
+ };
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+
3
+ // Collection pause flag + run-report preference (0.2.0, docs/cli-contract.md
4
+ // §2.11). The pause flag is a tiny JSON marker in ~/.tokenusage so the check
5
+ // stays cross-platform: cron/launchd/scheduled-task runs all execute `sync`,
6
+ // and sync itself consults the flag — no platform automation changes needed
7
+ // to stop collecting. The run-report preference lives in config.json
8
+ // (`runReport: false` disables §2.11 reporting); absent means enabled
9
+ // (default on), so pre-0.2.0 configs report without any migration.
10
+
11
+ const fs = require("node:fs");
12
+ const path = require("node:path");
13
+
14
+ const PAUSE_FILE = "pause.flag.json";
15
+ const RUN_REPORT_KEY = "runReport";
16
+
17
+ function pauseFilePath(trackerDir) {
18
+ return path.join(trackerDir, PAUSE_FILE);
19
+ }
20
+
21
+ // Missing or unreadable marker → not paused: a corrupt flag must never
22
+ // silently stop collection.
23
+ function isCollectionPaused(trackerDir) {
24
+ try {
25
+ const parsed = JSON.parse(fs.readFileSync(pauseFilePath(trackerDir), "utf8"));
26
+ return parsed?.paused === true;
27
+ } catch {
28
+ return false;
29
+ }
30
+ }
31
+
32
+ function readCollectionPause(trackerDir) {
33
+ if (!isCollectionPaused(trackerDir)) return null;
34
+ try {
35
+ const parsed = JSON.parse(fs.readFileSync(pauseFilePath(trackerDir), "utf8"));
36
+ return { paused: true, at: typeof parsed.at === "string" ? parsed.at : null };
37
+ } catch {
38
+ return { paused: true, at: null };
39
+ }
40
+ }
41
+
42
+ function setCollectionPaused(trackerDir, paused, { at = new Date().toISOString() } = {}) {
43
+ fs.mkdirSync(trackerDir, { recursive: true });
44
+ const file = pauseFilePath(trackerDir);
45
+
46
+ if (!paused) {
47
+ try {
48
+ fs.unlinkSync(file);
49
+ } catch (error) {
50
+ if (error?.code !== "ENOENT") throw error;
51
+ }
52
+ return;
53
+ }
54
+
55
+ const tmp = `${file}.${process.pid}.tmp`;
56
+ fs.writeFileSync(tmp, `${JSON.stringify({ paused: true, at })}\n`, { mode: 0o600 });
57
+ fs.renameSync(tmp, file);
58
+ }
59
+
60
+ function isRunReportEnabled(trackerDir) {
61
+ try {
62
+ const config = JSON.parse(fs.readFileSync(path.join(trackerDir, "config.json"), "utf8"));
63
+ return config?.runReport !== false;
64
+ } catch {
65
+ return true;
66
+ }
67
+ }
68
+
69
+ module.exports = {
70
+ PAUSE_FILE,
71
+ RUN_REPORT_KEY,
72
+ pauseFilePath,
73
+ isCollectionPaused,
74
+ readCollectionPause,
75
+ setCollectionPaused,
76
+ isRunReportEnabled,
77
+ };