tokenusage-cli 0.1.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 (125) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +22 -0
  3. package/README.md +94 -0
  4. package/THIRD_PARTY_NOTICES.md +140 -0
  5. package/bin/tokenusage.js +69 -0
  6. package/package.json +59 -0
  7. package/src/cli.js +134 -0
  8. package/src/commands/device-login.js +205 -0
  9. package/src/commands/diagnostics.js +38 -0
  10. package/src/commands/doctor.js +110 -0
  11. package/src/commands/init.js +2436 -0
  12. package/src/commands/sessions.js +29 -0
  13. package/src/commands/status.js +1747 -0
  14. package/src/commands/sync.js +7934 -0
  15. package/src/commands/uninstall.js +312 -0
  16. package/src/lib/account-usage-dedup.js +267 -0
  17. package/src/lib/antigravity-paths.js +48 -0
  18. package/src/lib/ark-agent-plan-limits.js +438 -0
  19. package/src/lib/ark-coding-plan-limits.js +537 -0
  20. package/src/lib/async-queue-reader.js +138 -0
  21. package/src/lib/atomic-json.js +27 -0
  22. package/src/lib/bearer-token.js +11 -0
  23. package/src/lib/categorizer-utils.js +232 -0
  24. package/src/lib/claude-categorizer.js +1343 -0
  25. package/src/lib/claude-config.js +279 -0
  26. package/src/lib/claude-user-identity.js +56 -0
  27. package/src/lib/cli-ui.js +179 -0
  28. package/src/lib/cloud-account.js +541 -0
  29. package/src/lib/cloud-device-token.js +141 -0
  30. package/src/lib/cloud-sync-prefs.js +14 -0
  31. package/src/lib/cloud-usage-reset.js +115 -0
  32. package/src/lib/codex-config.js +595 -0
  33. package/src/lib/codex-context-breakdown.js +806 -0
  34. package/src/lib/codex-model-attribution.js +128 -0
  35. package/src/lib/codex-rollout-parser.js +1471 -0
  36. package/src/lib/codex-service-tier.js +49 -0
  37. package/src/lib/codex-token-refresh.js +140 -0
  38. package/src/lib/codex-token-usage.js +195 -0
  39. package/src/lib/codex-usage-record.js +195 -0
  40. package/src/lib/command-runner.js +313 -0
  41. package/src/lib/commandcode-limits.js +317 -0
  42. package/src/lib/context-health.js +124 -0
  43. package/src/lib/cursor-config.js +605 -0
  44. package/src/lib/cursor-store.js +1918 -0
  45. package/src/lib/debug-flags.js +7 -0
  46. package/src/lib/devin-limits.js +249 -0
  47. package/src/lib/devin-usage.js +212 -0
  48. package/src/lib/diagnostics.js +383 -0
  49. package/src/lib/doctor.js +385 -0
  50. package/src/lib/dumate.js +95 -0
  51. package/src/lib/fs.js +455 -0
  52. package/src/lib/function-url.js +14 -0
  53. package/src/lib/gemini-config.js +291 -0
  54. package/src/lib/git-outcomes.js +243 -0
  55. package/src/lib/grok-context-breakdown.js +890 -0
  56. package/src/lib/grok-hook.js +360 -0
  57. package/src/lib/grok-limits.js +865 -0
  58. package/src/lib/grok-usage.js +98 -0
  59. package/src/lib/heatmap-compact.js +114 -0
  60. package/src/lib/ingest-sanitize.js +41 -0
  61. package/src/lib/init-flow.js +42 -0
  62. package/src/lib/install-resolver.js +170 -0
  63. package/src/lib/jsonl-lines.js +134 -0
  64. package/src/lib/kimi-model-repair.js +173 -0
  65. package/src/lib/kimi-profile.js +61 -0
  66. package/src/lib/kimi-session.js +216 -0
  67. package/src/lib/local-api.js +3588 -0
  68. package/src/lib/machine-id.js +238 -0
  69. package/src/lib/multi-install-parser.js +113 -0
  70. package/src/lib/notify-command.js +38 -0
  71. package/src/lib/omp-hook.js +589 -0
  72. package/src/lib/openclaw-cli.js +104 -0
  73. package/src/lib/openclaw-hook.js +375 -0
  74. package/src/lib/openclaw-session-plugin.js +560 -0
  75. package/src/lib/opencode-config.js +121 -0
  76. package/src/lib/opencode-go-limits.js +807 -0
  77. package/src/lib/outcomes-engine.js +253 -0
  78. package/src/lib/passive-mode.js +219 -0
  79. package/src/lib/pet-packages.js +722 -0
  80. package/src/lib/pricing/curated-overrides.json +822 -0
  81. package/src/lib/pricing/index.js +379 -0
  82. package/src/lib/pricing/litellm-fetcher.js +172 -0
  83. package/src/lib/pricing/matcher.js +456 -0
  84. package/src/lib/pricing/seed-snapshot.json +1 -0
  85. package/src/lib/progress.js +76 -0
  86. package/src/lib/project-usage-purge.js +117 -0
  87. package/src/lib/prompt.js +24 -0
  88. package/src/lib/provider-status.js +104 -0
  89. package/src/lib/proxy-env.js +489 -0
  90. package/src/lib/proxy-settings.js +163 -0
  91. package/src/lib/qoder-cn-cli-limits.js +119 -0
  92. package/src/lib/qoder-limits.js +880 -0
  93. package/src/lib/quiet-warnings.js +26 -0
  94. package/src/lib/rollout.js +25966 -0
  95. package/src/lib/runtime-config.js +259 -0
  96. package/src/lib/scan-roots.js +277 -0
  97. package/src/lib/sentry.js +231 -0
  98. package/src/lib/session-analytics.js +2972 -0
  99. package/src/lib/session-performance.js +237 -0
  100. package/src/lib/session-upload.js +379 -0
  101. package/src/lib/skill-usage.js +267 -0
  102. package/src/lib/skills-manager.js +1591 -0
  103. package/src/lib/source-metadata.js +48 -0
  104. package/src/lib/sqlite-reader.js +215 -0
  105. package/src/lib/star-cta.js +73 -0
  106. package/src/lib/subscription-manager.js +293 -0
  107. package/src/lib/subscriptions.js +508 -0
  108. package/src/lib/telemetry.js +193 -0
  109. package/src/lib/tracker-paths.js +16 -0
  110. package/src/lib/trae-cn-config.js +548 -0
  111. package/src/lib/trae-db.js +127 -0
  112. package/src/lib/trae-snapshot.js +230 -0
  113. package/src/lib/trae-sqlite.js +143 -0
  114. package/src/lib/trae-usage.js +121 -0
  115. package/src/lib/upload-queue.js +134 -0
  116. package/src/lib/upload-throttle.js +171 -0
  117. package/src/lib/usage-limits.js +4552 -0
  118. package/src/lib/wrapped-aggregator.js +236 -0
  119. package/src/lib/wsl-probe.js +281 -0
  120. package/src/lib/zcode-limits.js +1172 -0
  121. package/src/lib/zcode-reset-credits.js +66 -0
  122. package/test/cli-smoke.test.js +53 -0
  123. package/test/ingest-sanitize.test.js +162 -0
  124. package/test/quiet-warnings.test.js +53 -0
  125. package/test/session-upload.test.js +427 -0
@@ -0,0 +1,115 @@
1
+ const fs = require("node:fs");
2
+ const fsp = require("node:fs/promises");
3
+ const path = require("node:path");
4
+ const crypto = require("node:crypto");
5
+ const { openLock, writeFileAtomic } = require("./fs");
6
+ const { functionUrlFor, fetchFunctionResponse } = require("./function-url");
7
+
8
+ const MARKER = "cloud-usage-reset.json";
9
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
10
+ const failure = (code, status = 409) => Object.assign(new Error(code), { code, status });
11
+ const sameBase = (a, b) => String(a).replace(/\/$/, "") === String(b).replace(/\/$/, "");
12
+
13
+ function readCloudUsageReset(trackerDir) {
14
+ let raw;
15
+ try { raw = fs.readFileSync(path.join(trackerDir, MARKER), "utf8"); }
16
+ catch (error) { if (error.code === "ENOENT") return null; throw error; }
17
+ let value;
18
+ try { value = JSON.parse(raw); } catch { throw failure("cloud_usage_reset_invalid_state"); }
19
+ if (value?.version !== 1 || !UUID.test(value.operationId) || !UUID.test(value.deviceId) ||
20
+ !UUID.test(value.ownerId) || !/^https?:\/\//.test(value.baseUrl || "") ||
21
+ !["prepared", "uploading"].includes(value.phase)) throw failure("cloud_usage_reset_invalid_state");
22
+ return value;
23
+ }
24
+
25
+ function cloudUsageResetBlocksUpload(trackerDir, { ownerId, baseUrl, deviceId } = {}) {
26
+ try {
27
+ const marker = readCloudUsageReset(trackerDir);
28
+ return Boolean(marker && (marker.phase === "prepared" || marker.ownerId !== ownerId ||
29
+ !sameBase(marker.baseUrl, baseUrl) || (deviceId && marker.deviceId !== deviceId)));
30
+ }
31
+ catch { return true; }
32
+ }
33
+
34
+ async function writeMarker(trackerDir, marker) {
35
+ await writeFileAtomic(path.join(trackerDir, MARKER), JSON.stringify(marker) + "\n", { mode: 0o600 });
36
+ }
37
+
38
+ async function requestReset({ baseUrl, anonKey, authorization, body, fetchImpl = fetchFunctionResponse }) {
39
+ const response = await fetchImpl(functionUrlFor(baseUrl, "token-usage-device-usage-reset"), {
40
+ method: "POST",
41
+ headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: `Bearer ${authorization}`,
42
+ ...(anonKey ? { apikey: anonKey } : {}) },
43
+ signal: AbortSignal.timeout(60_000),
44
+ body: JSON.stringify(body),
45
+ });
46
+ const data = await response.json().catch(() => ({}));
47
+ if (!response.ok || data.ok !== true) throw failure(data.code || "cloud_usage_reset_failed", response.status || 502);
48
+ if (data.operation_id !== body.operation_id) throw failure("cloud_usage_reset_invalid_response", 502);
49
+ return data;
50
+ }
51
+
52
+ // Called only after the local bridge has bound the JWT to its current device.
53
+ // The marker precedes the remote mutation: an interrupted request must retry the
54
+ // same operation, never clear already-replayed history a second time.
55
+ async function resetCloudDeviceUsage({ trackerDir, ownerId, deviceId, baseUrl, anonKey, accessToken,
56
+ isCurrent = () => true, fetchImpl }) {
57
+ if (!UUID.test(ownerId) || !UUID.test(deviceId) || !accessToken) throw failure("auth_required", 401);
58
+ const lock = await openLock(path.join(trackerDir, "sync.lock"), { quietIfLocked: true });
59
+ if (!lock) throw failure("cloud_usage_reset_sync_busy");
60
+ try {
61
+ if (!isCurrent()) throw failure("auth_session_changed");
62
+ let marker = readCloudUsageReset(trackerDir);
63
+ const newOperation = !marker;
64
+ if (marker && (marker.ownerId !== ownerId || marker.deviceId !== deviceId || !sameBase(marker.baseUrl, baseUrl))) {
65
+ throw failure("cloud_usage_reset_owner_changed");
66
+ }
67
+ if (marker?.phase === "uploading") return { ok: true, operation_id: marker.operationId, status: "uploading" };
68
+ if (!marker) {
69
+ marker = { version: 1, operationId: crypto.randomUUID(), ownerId, deviceId, baseUrl, phase: "prepared" };
70
+ await writeMarker(trackerDir, marker);
71
+ }
72
+ if (!isCurrent()) throw failure("auth_session_changed");
73
+ const result = await requestReset({ baseUrl, anonKey, authorization: accessToken, fetchImpl,
74
+ body: { action: "reset", device_id: deviceId, operation_id: marker.operationId } }).catch(async error => {
75
+ // A definitive first-request rejection did not erase anything. Unknown
76
+ // outcomes and retries retain their operation so they cannot erase twice.
77
+ if (newOperation && [400, 401, 403, 404, 409, 422].includes(error.status)) {
78
+ await fsp.unlink(path.join(trackerDir, MARKER));
79
+ }
80
+ throw error;
81
+ });
82
+ if (result.device_id !== deviceId || !["reset", "complete"].includes(result.status)) {
83
+ throw failure("cloud_usage_reset_invalid_response", 502);
84
+ }
85
+ if (!isCurrent()) throw failure("auth_session_changed");
86
+ await writeFileAtomic(path.join(trackerDir, "queue.state.json"),
87
+ JSON.stringify({ offset: 0, updatedAt: new Date().toISOString() }) + "\n", { mode: 0o600 });
88
+ await fsp.unlink(path.join(trackerDir, "upload.throttle.json")).catch(error => { if (error.code !== "ENOENT") throw error; });
89
+ marker.phase = "uploading";
90
+ await writeMarker(trackerDir, marker);
91
+ return { ...result, status: "uploading" };
92
+ } finally { await lock.release(); }
93
+ }
94
+
95
+ // sync owns sync.lock here. Only its fully acknowledged queue can finish the
96
+ // operation; a partial batch/checkpoint or another account leaves it pending.
97
+ async function finishCloudDeviceUsageReset({ trackerDir, ownerId, deviceId, baseUrl, anonKey, deviceToken, fetchImpl }) {
98
+ const marker = readCloudUsageReset(trackerDir);
99
+ if (!marker || marker.phase !== "uploading" || marker.ownerId !== ownerId || (deviceId && marker.deviceId !== deviceId) || !sameBase(marker.baseUrl, baseUrl)) return false;
100
+ if (!deviceToken) return false;
101
+ const queuePath = path.join(trackerDir, "queue.jsonl");
102
+ const size = await fsp.stat(queuePath).then(stat => stat.size).catch(error => { if (error.code === "ENOENT") return 0; throw error; });
103
+ let offset;
104
+ try { offset = JSON.parse(await fsp.readFile(path.join(trackerDir, "queue.state.json"), "utf8")).offset; }
105
+ catch { throw failure("cloud_usage_reset_invalid_offset"); }
106
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > size) throw failure("cloud_usage_reset_invalid_offset");
107
+ if (offset !== size) return false;
108
+ const result = await requestReset({ baseUrl, anonKey, authorization: deviceToken, fetchImpl,
109
+ body: { action: "refresh", operation_id: marker.operationId } });
110
+ if (result.status !== "complete" || result.device_id !== marker.deviceId) throw failure("cloud_usage_reset_invalid_response", 502);
111
+ await fsp.unlink(path.join(trackerDir, MARKER));
112
+ return true;
113
+ }
114
+
115
+ module.exports = { readCloudUsageReset, cloudUsageResetBlocksUpload, resetCloudDeviceUsage, finishCloudDeviceUsageReset };
@@ -0,0 +1,595 @@
1
+ const fs = require("node:fs/promises");
2
+ const path = require("node:path");
3
+
4
+ const { ensureDir, readJson, writeJson } = require("./fs");
5
+
6
+ // Build the notify command Codex/Every Code exec on turn end. `/usr/bin/env` is
7
+ // not executable on native Windows, so the wrapper never launches notify.cjs
8
+ // (issue #361). On Windows, invoke the running Node executable directly.
9
+ function buildCodexNotifyCmd(
10
+ notifyPath,
11
+ { platform = process.platform, execPath = process.execPath } = {},
12
+ ) {
13
+ return platform === "win32"
14
+ ? [execPath, notifyPath]
15
+ : ["/usr/bin/env", "node", notifyPath];
16
+ }
17
+
18
+ function buildEveryCodeNotifyCmd(notifyPath, options) {
19
+ return [...buildCodexNotifyCmd(notifyPath, options), "--source=every-code"];
20
+ }
21
+
22
+ function buildAcodeNotifyCmd(notifyPath, options) {
23
+ return [...buildCodexNotifyCmd(notifyPath, options), "--source=acode"];
24
+ }
25
+
26
+ // Is this notify command one we wrote? Strict array equality is not a safe
27
+ // test, because the command is not a stable constant across invocations:
28
+ // - argv[0] on Windows is an absolute `process.execPath` (#361). The desktop
29
+ // app runs the bundled EmbeddedServer\node.exe, `tokenusage` in a
30
+ // terminal runs the system / nvm Node, and an nvm version switch moves it
31
+ // again. All three write a different argv[0] on the same machine.
32
+ // - the notify.cjs path itself varies with binDir (npm global vs embedded).
33
+ // Under strict equality our own command reads as a stranger's: `status` reports
34
+ // the integration as not configured (pushing the user to re-run setup), and
35
+ // `uninstall` skips it as `current-not-managed`, leaving a dead notify entry
36
+ // that points at a deleted app directory and fails on every Codex turn.
37
+ // Match on the notify.cjs tail instead — the path must live under
38
+ // ~/.tokenusage/, and the args after it must match so the Codex command is
39
+ // never confused with the Every Code one (`--source=every-code`).
40
+ function isManagedNotifyCmd(cmd, expectedNotify) {
41
+ if (!Array.isArray(cmd)) return false;
42
+ if (arraysEqual(cmd, expectedNotify)) return true;
43
+
44
+ const notifyIndexOf = (parts) =>
45
+ parts.findIndex(
46
+ (part) =>
47
+ typeof part === "string" && part.replace(/\\/g, "/").endsWith("notify.cjs"),
48
+ );
49
+
50
+ const index = notifyIndexOf(cmd);
51
+ if (index === -1) return false;
52
+ if (!cmd[index].replace(/\\/g, "/").includes("/.tokenusage/")) return false;
53
+
54
+ if (!Array.isArray(expectedNotify)) return true;
55
+ const expectedIndex = notifyIndexOf(expectedNotify);
56
+ if (expectedIndex === -1) return true;
57
+ return arraysEqual(cmd.slice(index + 1), expectedNotify.slice(expectedIndex + 1));
58
+ }
59
+
60
+ async function upsertNotify({
61
+ configPath,
62
+ notifyCmd,
63
+ notifyOriginalPath,
64
+ configLabel,
65
+ captureOriginal = true,
66
+ replaceOriginal = false,
67
+ }) {
68
+ const originalText = await fs.readFile(configPath, "utf8").catch(() => null);
69
+ if (originalText == null) {
70
+ const label =
71
+ typeof configLabel === "string" && configLabel.length > 0 ? configLabel : "Config";
72
+ throw new Error(`${label} not found: ${configPath}`);
73
+ }
74
+
75
+ const existingNotify = extractNotify(originalText);
76
+ const already = arraysEqual(existingNotify, notifyCmd);
77
+
78
+ if (!already) {
79
+ // Persist original notify once (for uninstall + chaining). When a caller
80
+ // asks to replace the stored original and the config has no notify, record
81
+ // that absence so uninstall does not resurrect a stale backup.
82
+ // A command of ours that merely went stale (different argv[0] / binDir —
83
+ // see isManagedNotifyCmd) is NOT the user's original: recording it would
84
+ // make uninstall "restore" our own dead command forever. Treat it as an
85
+ // absence instead. Reachable when the backup file is gone but the config
86
+ // entry is not, e.g. after the user deletes ~/.tokenusage.
87
+ const hasForeignNotify =
88
+ Array.isArray(existingNotify) && !isManagedNotifyCmd(existingNotify, notifyCmd);
89
+ if (captureOriginal && (hasForeignNotify || replaceOriginal)) {
90
+ await ensureDir(path.dirname(notifyOriginalPath));
91
+ const existing = await readJson(notifyOriginalPath);
92
+ if (replaceOriginal || !existing) {
93
+ await writeJson(notifyOriginalPath, {
94
+ notify: hasForeignNotify ? existingNotify : null,
95
+ capturedAt: new Date().toISOString(),
96
+ });
97
+ }
98
+ }
99
+
100
+ const updated = setNotify(originalText, notifyCmd);
101
+ const backupPath = `${configPath}.bak.${new Date().toISOString().replace(/[:.]/g, "-")}`;
102
+ await fs.copyFile(configPath, backupPath);
103
+ await fs.writeFile(configPath, updated, "utf8");
104
+ return { changed: true, backupPath };
105
+ }
106
+
107
+ return { changed: false, backupPath: null };
108
+ }
109
+
110
+ async function restoreNotify({ configPath, notifyOriginalPath, expectedNotify }) {
111
+ const text = await fs.readFile(configPath, "utf8").catch(() => null);
112
+ if (text == null) return { restored: false, skippedReason: "config-missing" };
113
+
114
+ const original = await readJson(notifyOriginalPath);
115
+ const originalNotify = Array.isArray(original?.notify) ? original.notify : null;
116
+ const currentNotify = extractNotify(text);
117
+
118
+ if (!originalNotify && expectedNotify && currentNotify == null) {
119
+ return { restored: false, skippedReason: "no-backup-not-installed" };
120
+ }
121
+
122
+ if (expectedNotify && !isManagedNotifyCmd(currentNotify, expectedNotify)) {
123
+ return { restored: false, skippedReason: "current-not-managed" };
124
+ }
125
+
126
+ const updated = originalNotify ? setNotify(text, originalNotify) : removeNotify(text);
127
+ if (updated === text) return { restored: false, skippedReason: "no-change" };
128
+
129
+ const backupPath = `${configPath}.bak.${new Date().toISOString().replace(/[:.]/g, "-")}`;
130
+ await fs.copyFile(configPath, backupPath).catch(() => {});
131
+ await fs.writeFile(configPath, updated, "utf8");
132
+ return { restored: true, skippedReason: null };
133
+ }
134
+
135
+ async function loadNotifyOriginal(notifyOriginalPath) {
136
+ const original = await readJson(notifyOriginalPath);
137
+ return Array.isArray(original?.notify) ? original.notify : null;
138
+ }
139
+
140
+ async function readNotify(configPath) {
141
+ const text = await fs.readFile(configPath, "utf8").catch(() => null);
142
+ if (text == null) return null;
143
+ return extractNotify(text);
144
+ }
145
+
146
+ async function upsertCodexNotify({
147
+ codexConfigPath,
148
+ notifyCmd,
149
+ notifyOriginalPath,
150
+ captureOriginal = true,
151
+ replaceOriginal = false,
152
+ }) {
153
+ return upsertNotify({
154
+ configPath: codexConfigPath,
155
+ notifyCmd,
156
+ notifyOriginalPath,
157
+ configLabel: "Codex config",
158
+ captureOriginal,
159
+ replaceOriginal,
160
+ });
161
+ }
162
+
163
+ async function restoreCodexNotify({ codexConfigPath, notifyOriginalPath, notifyCmd }) {
164
+ return restoreNotify({
165
+ configPath: codexConfigPath,
166
+ notifyOriginalPath,
167
+ expectedNotify: notifyCmd,
168
+ });
169
+ }
170
+
171
+ async function loadCodexNotifyOriginal(notifyOriginalPath) {
172
+ return loadNotifyOriginal(notifyOriginalPath);
173
+ }
174
+
175
+ async function readCodexNotify(codexConfigPath) {
176
+ return readNotify(codexConfigPath);
177
+ }
178
+
179
+ async function upsertAcodeNotify({
180
+ acodeConfigPath,
181
+ notifyCmd,
182
+ notifyOriginalPath,
183
+ captureOriginal = true,
184
+ replaceOriginal = false,
185
+ }) {
186
+ return upsertNotify({
187
+ configPath: acodeConfigPath,
188
+ notifyCmd,
189
+ notifyOriginalPath,
190
+ configLabel: "AStudio config",
191
+ captureOriginal,
192
+ replaceOriginal,
193
+ });
194
+ }
195
+
196
+ async function restoreAcodeNotify({ acodeConfigPath, notifyOriginalPath, notifyCmd }) {
197
+ return restoreNotify({
198
+ configPath: acodeConfigPath,
199
+ notifyOriginalPath,
200
+ expectedNotify: notifyCmd,
201
+ });
202
+ }
203
+
204
+ async function loadAcodeNotifyOriginal(notifyOriginalPath) {
205
+ return loadNotifyOriginal(notifyOriginalPath);
206
+ }
207
+
208
+ async function readAcodeNotify(acodeConfigPath) {
209
+ return readNotify(acodeConfigPath);
210
+ }
211
+
212
+ async function upsertEveryCodeNotify({
213
+ codeConfigPath,
214
+ notifyCmd,
215
+ notifyOriginalPath,
216
+ captureOriginal = true,
217
+ replaceOriginal = false,
218
+ }) {
219
+ return upsertNotify({
220
+ configPath: codeConfigPath,
221
+ notifyCmd,
222
+ notifyOriginalPath,
223
+ configLabel: "Every Code config",
224
+ captureOriginal,
225
+ replaceOriginal,
226
+ });
227
+ }
228
+
229
+ async function restoreEveryCodeNotify({ codeConfigPath, notifyOriginalPath, notifyCmd }) {
230
+ return restoreNotify({
231
+ configPath: codeConfigPath,
232
+ notifyOriginalPath,
233
+ expectedNotify: notifyCmd,
234
+ });
235
+ }
236
+
237
+ async function loadEveryCodeNotifyOriginal(notifyOriginalPath) {
238
+ return loadNotifyOriginal(notifyOriginalPath);
239
+ }
240
+
241
+ async function readEveryCodeNotify(codeConfigPath) {
242
+ return readNotify(codeConfigPath);
243
+ }
244
+
245
+ function extractNotify(text) {
246
+ // Heuristic parse: find a line that starts with "notify =".
247
+ // Supports single-line arrays:
248
+ // - notify = ["a", "b"]
249
+ // And multi-line arrays:
250
+ // - notify = [
251
+ // "a",
252
+ // "b"
253
+ // ]
254
+ const lines = text.split(/\r?\n/);
255
+ for (let i = 0; i < lines.length; i++) {
256
+ const line = lines[i];
257
+ if (isTomlTableHeader(line)) break;
258
+ const m = line.match(/^\s*notify\s*=\s*(.*)\s*$/);
259
+ if (!m) continue;
260
+
261
+ const rhs = (m[1] || "").trim();
262
+ const literal = readTomlArrayLiteral(lines, i, rhs);
263
+ if (!literal) return null;
264
+
265
+ const parsed = parseTomlStringArray(literal);
266
+ return parsed;
267
+ }
268
+ return null;
269
+ }
270
+
271
+ function setNotify(text, notifyCmd) {
272
+ const lines = text.split(/\r?\n/);
273
+ const notifyLine = `notify = ${formatTomlStringArray(notifyCmd)}`;
274
+
275
+ const out = [];
276
+ let replaced = false;
277
+ for (let i = 0; i < lines.length; i++) {
278
+ const line = lines[i];
279
+ if (isTomlTableHeader(line)) {
280
+ if (!replaced) {
281
+ out.push(notifyLine);
282
+ replaced = true;
283
+ }
284
+ out.push(...lines.slice(i));
285
+ break;
286
+ }
287
+ const m = line.match(/^\s*notify\s*=\s*(.*)\s*$/);
288
+ if (m) {
289
+ if (!replaced) {
290
+ out.push(notifyLine);
291
+ replaced = true;
292
+ }
293
+
294
+ const rhs = (m[1] || "").trim();
295
+ i = findNotifyBlockEnd(lines, i, rhs);
296
+ continue;
297
+ }
298
+ out.push(line);
299
+ }
300
+
301
+ if (!replaced) {
302
+ // Insert at top-level, before the first table header.
303
+ const firstTableIdx = out.findIndex((l) => /^\s*\[/.test(l));
304
+ const headerIdx = firstTableIdx === -1 ? out.length : firstTableIdx;
305
+ out.splice(headerIdx, 0, notifyLine);
306
+ }
307
+
308
+ return out.join("\n").replace(/\n+$/, "\n");
309
+ }
310
+
311
+ function removeNotify(text) {
312
+ const lines = text.split(/\r?\n/);
313
+ const out = [];
314
+ for (let i = 0; i < lines.length; i++) {
315
+ const line = lines[i];
316
+ if (isTomlTableHeader(line)) {
317
+ out.push(...lines.slice(i));
318
+ break;
319
+ }
320
+ const m = line.match(/^\s*notify\s*=\s*(.*)\s*$/);
321
+ if (m) {
322
+ const rhs = (m[1] || "").trim();
323
+ i = findNotifyBlockEnd(lines, i, rhs);
324
+ continue;
325
+ }
326
+ out.push(line);
327
+ }
328
+ return out.join("\n").replace(/\n+$/, "\n");
329
+ }
330
+
331
+ function parseTomlStringArray(rhs) {
332
+ // Minimal parser for TOML basic/literal string arrays.
333
+ if (!rhs.startsWith("[") || !rhs.endsWith("]")) return null;
334
+
335
+ const parts = [];
336
+ let i = 1;
337
+ let expectValue = true;
338
+
339
+ function skipSpaceAndComments() {
340
+ while (i < rhs.length) {
341
+ const ch = rhs[i];
342
+ if (/\s/.test(ch)) {
343
+ i += 1;
344
+ continue;
345
+ }
346
+ if (ch === "#") {
347
+ while (i < rhs.length && rhs[i] !== "\n") i += 1;
348
+ continue;
349
+ }
350
+ break;
351
+ }
352
+ }
353
+
354
+ function parseString() {
355
+ const quote = rhs[i];
356
+ if (quote !== '"' && quote !== "'") return null;
357
+ i += 1;
358
+ let value = "";
359
+ while (i < rhs.length) {
360
+ const ch = rhs[i];
361
+ if (ch === quote) {
362
+ i += 1;
363
+ return value;
364
+ }
365
+ if (ch === "\n" || ch === "\r") return null;
366
+ if (quote === '"' && ch === "\\") {
367
+ if (i + 1 >= rhs.length) return null;
368
+ const next = rhs[i + 1];
369
+ if (next === "b") value += "\b";
370
+ else if (next === "t") value += "\t";
371
+ else if (next === "n") value += "\n";
372
+ else if (next === "f") value += "\f";
373
+ else if (next === "r") value += "\r";
374
+ else if (next === '"' || next === "\\" || next === "/") value += next;
375
+ else return null;
376
+ i += 2;
377
+ continue;
378
+ }
379
+ value += ch;
380
+ i += 1;
381
+ }
382
+ return null;
383
+ }
384
+
385
+ while (i < rhs.length) {
386
+ skipSpaceAndComments();
387
+ if (rhs[i] === "]") {
388
+ i += 1;
389
+ skipSpaceAndComments();
390
+ return i === rhs.length ? parts : null;
391
+ }
392
+ if (!expectValue) {
393
+ if (rhs[i] !== ",") return null;
394
+ i += 1;
395
+ expectValue = true;
396
+ continue;
397
+ }
398
+
399
+ const value = parseString();
400
+ if (value == null) return null;
401
+ parts.push(value);
402
+ expectValue = false;
403
+ }
404
+
405
+ return null;
406
+ }
407
+
408
+ function formatTomlStringArray(arr) {
409
+ return `[${arr.map((s) => JSON.stringify(String(s))).join(", ")}]`;
410
+ }
411
+
412
+ function readTomlArrayLiteral(lines, startIndex, rhs) {
413
+ const first = rhs.trim();
414
+ if (!first.startsWith("[")) return null;
415
+
416
+ let inString = false;
417
+ let quote = null;
418
+ let depth = 0;
419
+ let sawOpen = false;
420
+ let invalid = false;
421
+
422
+ function scanChunk(chunk) {
423
+ for (let i = 0; i < chunk.length; i++) {
424
+ const ch = chunk[i];
425
+ if (!inString) {
426
+ if (ch === '"' || ch === "'") {
427
+ inString = true;
428
+ quote = ch;
429
+ continue;
430
+ }
431
+ if (ch === "[") {
432
+ depth += 1;
433
+ sawOpen = true;
434
+ continue;
435
+ }
436
+ if (ch === "]") {
437
+ depth -= 1;
438
+ if (sawOpen && depth === 0) {
439
+ if (!isTomlArrayTrailer(chunk.slice(i + 1))) invalid = true;
440
+ return i;
441
+ }
442
+ }
443
+ continue;
444
+ }
445
+ if (ch === quote) {
446
+ inString = false;
447
+ quote = null;
448
+ continue;
449
+ }
450
+ if (quote === '"' && ch === "\\") {
451
+ if (i + 1 >= chunk.length) {
452
+ invalid = true;
453
+ return -1;
454
+ }
455
+ i += 1;
456
+ }
457
+ }
458
+ return -1;
459
+ }
460
+
461
+ const parts = [first];
462
+ let endPos = scanChunk(first);
463
+ if (invalid) return null;
464
+ if (endPos !== -1) return first.slice(0, endPos + 1).trim();
465
+
466
+ for (let j = startIndex + 1; j < lines.length; j++) {
467
+ const line = lines[j];
468
+ endPos = scanChunk(line);
469
+ if (invalid) return null;
470
+ if (endPos !== -1) {
471
+ parts.push(line.slice(0, endPos + 1));
472
+ return parts.join("\n").trim();
473
+ }
474
+ parts.push(line);
475
+ }
476
+
477
+ return null;
478
+ }
479
+
480
+ function findTomlArrayBlockEnd(lines, startIndex, rhs) {
481
+ const first = rhs.trim();
482
+ if (!first.startsWith("[")) return startIndex;
483
+
484
+ let inString = false;
485
+ let quote = null;
486
+ let depth = 0;
487
+ let sawOpen = false;
488
+ let invalid = false;
489
+
490
+ function scanChunk(chunk) {
491
+ for (let i = 0; i < chunk.length; i++) {
492
+ const ch = chunk[i];
493
+ if (!inString) {
494
+ if (ch === '"' || ch === "'") {
495
+ inString = true;
496
+ quote = ch;
497
+ continue;
498
+ }
499
+ if (ch === "[") {
500
+ depth += 1;
501
+ sawOpen = true;
502
+ continue;
503
+ }
504
+ if (ch === "]") {
505
+ depth -= 1;
506
+ if (sawOpen && depth === 0) {
507
+ if (!isTomlArrayTrailer(chunk.slice(i + 1))) invalid = true;
508
+ return true;
509
+ }
510
+ }
511
+ continue;
512
+ }
513
+ if (ch === quote) {
514
+ inString = false;
515
+ quote = null;
516
+ continue;
517
+ }
518
+ if (quote === '"' && ch === "\\") {
519
+ if (i + 1 >= chunk.length) {
520
+ invalid = true;
521
+ return false;
522
+ }
523
+ i += 1;
524
+ }
525
+ }
526
+ return false;
527
+ }
528
+
529
+ if (scanChunk(first)) return startIndex;
530
+ if (invalid) return startIndex;
531
+ for (let j = startIndex + 1; j < lines.length; j++) {
532
+ if (scanChunk(lines[j])) return j;
533
+ if (invalid) return startIndex;
534
+ }
535
+ return startIndex;
536
+ }
537
+
538
+ function findNotifyBlockEnd(lines, startIndex, rhs) {
539
+ const endIndex = findTomlArrayBlockEnd(lines, startIndex, rhs);
540
+ const literal = readTomlArrayLiteral(lines, startIndex, rhs);
541
+ if (
542
+ endIndex !== startIndex ||
543
+ !rhs.trim().startsWith("[") ||
544
+ (literal && parseTomlStringArray(literal))
545
+ ) {
546
+ return endIndex;
547
+ }
548
+
549
+ for (let j = startIndex + 1; j < lines.length; j++) {
550
+ if (isTopLevelTomlBoundary(lines[j])) return j - 1;
551
+ }
552
+ return lines.length - 1;
553
+ }
554
+
555
+ function isTomlTableHeader(line) {
556
+ return /^\s*\[\[?[^\]]+\]\]?\s*(?:#.*)?$/.test(line);
557
+ }
558
+
559
+ function isTopLevelTomlBoundary(line) {
560
+ return /^\s*(?:\[\[?[^\]]+\]\]?|(?:[A-Za-z0-9_-]+|"[^"]+"|'[^']+')(?:\s*\.\s*(?:[A-Za-z0-9_-]+|"[^"]+"|'[^']+'))*\s*=)/.test(line);
561
+ }
562
+
563
+ function isTomlArrayTrailer(text) {
564
+ return /^\s*(?:#.*)?$/.test(text);
565
+ }
566
+
567
+ function arraysEqual(a, b) {
568
+ if (!Array.isArray(a) || !Array.isArray(b)) return false;
569
+ if (a.length !== b.length) return false;
570
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
571
+ return true;
572
+ }
573
+
574
+ module.exports = {
575
+ buildCodexNotifyCmd,
576
+ buildAcodeNotifyCmd,
577
+ buildEveryCodeNotifyCmd,
578
+ isManagedNotifyCmd,
579
+ upsertNotify,
580
+ restoreNotify,
581
+ loadNotifyOriginal,
582
+ readNotify,
583
+ upsertCodexNotify,
584
+ restoreCodexNotify,
585
+ loadCodexNotifyOriginal,
586
+ readCodexNotify,
587
+ upsertAcodeNotify,
588
+ restoreAcodeNotify,
589
+ loadAcodeNotifyOriginal,
590
+ readAcodeNotify,
591
+ upsertEveryCodeNotify,
592
+ restoreEveryCodeNotify,
593
+ loadEveryCodeNotifyOriginal,
594
+ readEveryCodeNotify,
595
+ };