@mnemom/mnemom 0.17.33 → 0.17.34-next.2

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 (236) hide show
  1. package/dist/base-url-proxy.mjs +18 -4
  2. package/dist/commands/agent-config.js +5 -1
  3. package/dist/commands/agent-doctor.d.ts +9 -0
  4. package/dist/commands/agent-doctor.js +4 -0
  5. package/dist/commands/agent-session.d.ts +1 -2
  6. package/dist/commands/agent-session.js +1 -2
  7. package/dist/commands/agent-setup.d.ts +6 -0
  8. package/dist/commands/agent-setup.js +12 -1
  9. package/dist/commands/agent-share-render.d.ts +1 -1
  10. package/dist/commands/agent-share-render.js +1 -1
  11. package/dist/commands/agent.d.ts +26 -0
  12. package/dist/commands/agent.js +228 -53
  13. package/dist/commands/durable-doctor.d.ts +50 -0
  14. package/dist/commands/durable-doctor.js +186 -0
  15. package/dist/commands/durable-lock.d.ts +254 -0
  16. package/dist/commands/durable-lock.js +595 -0
  17. package/dist/commands/durable-sessions.d.ts +87 -0
  18. package/dist/commands/durable-sessions.js +303 -0
  19. package/dist/commands/durable-verbs.d.ts +116 -0
  20. package/dist/commands/durable-verbs.js +393 -0
  21. package/dist/commands/protection.js +1 -1
  22. package/dist/commands/scan.d.ts +97 -0
  23. package/dist/commands/scan.js +238 -0
  24. package/dist/durable/flock.d.ts +26 -0
  25. package/dist/durable/flock.js +80 -0
  26. package/dist/durable/launch-spec.d.ts +7 -1
  27. package/dist/durable/launch-spec.js +10 -3
  28. package/dist/durable/seat-proxy-entry.d.ts +11 -0
  29. package/dist/durable/seat-proxy-entry.js +25 -0
  30. package/dist/durable/seat-proxy.d.ts +107 -0
  31. package/dist/durable/seat-proxy.js +599 -0
  32. package/dist/durable/seat-socket.d.ts +46 -0
  33. package/dist/durable/seat-socket.js +179 -0
  34. package/dist/durable/seat-spec-validator.d.ts +28 -0
  35. package/dist/durable/seat-spec-validator.js +59 -0
  36. package/dist/durable/test-mode.mjs +81 -0
  37. package/dist/durable/turn-chain.d.ts +55 -0
  38. package/dist/durable/turn-chain.js +178 -0
  39. package/dist/host/auto-continue.d.ts +67 -0
  40. package/dist/host/auto-continue.js +118 -0
  41. package/dist/host/bootid.d.ts +13 -0
  42. package/dist/host/bootid.js +41 -0
  43. package/dist/host/client.d.ts +123 -0
  44. package/dist/host/client.js +171 -0
  45. package/dist/host/commands.d.ts +2 -0
  46. package/dist/host/commands.js +122 -0
  47. package/dist/host/control.d.ts +33 -0
  48. package/dist/host/control.js +144 -0
  49. package/dist/host/daemon.d.ts +217 -0
  50. package/dist/host/daemon.js +606 -0
  51. package/dist/host/gate.d.ts +46 -0
  52. package/dist/host/gate.js +82 -0
  53. package/dist/host/grant.d.ts +24 -0
  54. package/dist/host/grant.js +24 -0
  55. package/dist/host/instance.d.ts +35 -0
  56. package/dist/host/instance.js +62 -0
  57. package/dist/host/integrity.d.ts +35 -0
  58. package/dist/host/integrity.js +115 -0
  59. package/dist/host/launchd.d.ts +16 -0
  60. package/dist/host/launchd.js +45 -0
  61. package/dist/host/lock.d.ts +20 -0
  62. package/dist/host/lock.js +63 -0
  63. package/dist/host/owner.d.ts +55 -0
  64. package/dist/host/owner.js +121 -0
  65. package/dist/host/plist.d.ts +16 -0
  66. package/dist/host/plist.js +85 -0
  67. package/dist/host/procs.d.ts +27 -0
  68. package/dist/host/procs.js +105 -0
  69. package/dist/host/run.d.ts +66 -0
  70. package/dist/host/run.js +314 -0
  71. package/dist/host/runtime.d.ts +8 -0
  72. package/dist/host/runtime.js +22 -0
  73. package/dist/host/s1-names.d.ts +22 -0
  74. package/dist/host/s1-names.js +21 -0
  75. package/dist/host/seat-credential.d.ts +27 -0
  76. package/dist/host/seat-credential.js +41 -0
  77. package/dist/host/seat-launch-main.d.ts +1 -0
  78. package/dist/host/seat-launch-main.js +59 -0
  79. package/dist/host/seat-launch.d.ts +116 -0
  80. package/dist/host/seat-launch.js +302 -0
  81. package/dist/host/seat.d.ts +48 -0
  82. package/dist/host/seat.js +149 -0
  83. package/dist/host/state.d.ts +33 -0
  84. package/dist/host/state.js +117 -0
  85. package/dist/host/status.d.ts +101 -0
  86. package/dist/host/status.js +307 -0
  87. package/dist/host/tmux.d.ts +56 -0
  88. package/dist/host/tmux.js +182 -0
  89. package/dist/host/transcript.d.ts +30 -0
  90. package/dist/host/transcript.js +130 -0
  91. package/dist/host/verbs.d.ts +50 -0
  92. package/dist/host/verbs.js +271 -0
  93. package/dist/index.d.ts +8 -6
  94. package/dist/index.js +232 -35
  95. package/dist/lib/agent.d.ts +8 -26
  96. package/dist/lib/agent.js +11 -26
  97. package/dist/lib/api.d.ts +13 -0
  98. package/dist/lib/api.js +8 -0
  99. package/dist/lib/claude-plugin.d.ts +11 -2
  100. package/dist/lib/claude-plugin.js +10 -1
  101. package/dist/lib/durable/api.d.ts +136 -0
  102. package/dist/lib/durable/api.js +220 -0
  103. package/dist/lib/durable/codes.d.ts +8 -0
  104. package/dist/lib/durable/codes.js +2 -0
  105. package/dist/lib/durable/first-turn.d.ts +50 -0
  106. package/dist/lib/durable/first-turn.js +102 -0
  107. package/dist/lib/durable/gate.d.ts +48 -0
  108. package/dist/lib/durable/gate.js +122 -0
  109. package/dist/lib/durable/handover.d.ts +101 -0
  110. package/dist/lib/durable/handover.js +175 -0
  111. package/dist/lib/durable/launch.d.ts +182 -0
  112. package/dist/lib/durable/launch.js +443 -0
  113. package/dist/lib/durable/launching.d.ts +15 -0
  114. package/dist/lib/durable/launching.js +70 -0
  115. package/dist/lib/durable/live.d.ts +194 -0
  116. package/dist/lib/durable/live.js +635 -0
  117. package/dist/lib/durable/refusal.d.ts +57 -0
  118. package/dist/lib/durable/refusal.js +78 -0
  119. package/dist/lib/durable/view.d.ts +83 -0
  120. package/dist/lib/durable/view.js +244 -0
  121. package/dist/lib/experimental.d.ts +0 -9
  122. package/dist/lib/experimental.js +18 -17
  123. package/dist/lib/launcher-config.d.ts +7 -0
  124. package/dist/lib/launcher-config.js +21 -0
  125. package/dist/lib/scan/caps.d.ts +35 -0
  126. package/dist/lib/scan/caps.js +67 -0
  127. package/dist/lib/scan/credential.d.ts +37 -0
  128. package/dist/lib/scan/credential.js +104 -0
  129. package/dist/lib/scan/failure.d.ts +10 -0
  130. package/dist/lib/scan/failure.js +43 -0
  131. package/dist/lib/scan/pr-source.d.ts +57 -0
  132. package/dist/lib/scan/pr-source.js +130 -0
  133. package/dist/lib/scan/record.d.ts +49 -0
  134. package/dist/lib/scan/record.js +85 -0
  135. package/dist/lib/scan/report-email.d.ts +92 -0
  136. package/dist/lib/scan/report-email.js +144 -0
  137. package/dist/lib/scan/report.d.ts +13 -0
  138. package/dist/lib/scan/report.js +30 -0
  139. package/dist/lib/scan/scan.d.ts +64 -0
  140. package/dist/lib/scan/scan.js +182 -0
  141. package/dist/lib/scan/share.d.ts +38 -0
  142. package/dist/lib/scan/share.js +47 -0
  143. package/dist/lib/scan/spend/ai-tool-detect.d.ts +6 -0
  144. package/dist/lib/scan/spend/ai-tool-detect.js +18 -0
  145. package/dist/lib/scan/spend/anthropic-usage.d.ts +57 -0
  146. package/dist/lib/scan/spend/anthropic-usage.js +244 -0
  147. package/dist/lib/scan/spend/cost-corpus.v1.d.ts +56 -0
  148. package/dist/lib/scan/spend/cost-corpus.v1.js +64 -0
  149. package/dist/lib/scan/spend/prices.d.ts +33 -0
  150. package/dist/lib/scan/spend/prices.js +57 -0
  151. package/dist/lib/scan/spend/spend-estimate.d.ts +30 -0
  152. package/dist/lib/scan/spend/spend-estimate.js +70 -0
  153. package/dist/lib/scan/spend/spend-tiers.d.ts +25 -0
  154. package/dist/lib/scan/spend/spend-tiers.js +42 -0
  155. package/dist/lib/scan/spend/token-rate.d.ts +30 -0
  156. package/dist/lib/scan/spend/token-rate.js +54 -0
  157. package/dist/lib/session-key.d.ts +41 -0
  158. package/dist/lib/session-key.js +124 -0
  159. package/dist/lib/subscription-login.d.ts +15 -0
  160. package/dist/lib/subscription-login.js +28 -1
  161. package/dist/rc-key-401.mjs +75 -0
  162. package/dist/rc-proxy.mjs +221 -25
  163. package/dist/vendor/durable-contract/index.js +240 -18
  164. package/dist/vendor/shared/durable-contract/admission.d.ts +240 -0
  165. package/dist/vendor/shared/durable-contract/admission.js +533 -0
  166. package/dist/vendor/shared/durable-contract/arm.d.ts +51 -0
  167. package/dist/vendor/shared/durable-contract/arm.js +133 -0
  168. package/dist/vendor/shared/durable-contract/canonical.d.ts +29 -0
  169. package/dist/vendor/shared/durable-contract/canonical.js +98 -0
  170. package/dist/vendor/shared/durable-contract/cell-id.d.ts +22 -0
  171. package/dist/vendor/shared/durable-contract/cell-id.js +38 -0
  172. package/dist/vendor/shared/durable-contract/cli-output.d.ts +342 -0
  173. package/dist/vendor/shared/durable-contract/cli-output.js +201 -0
  174. package/dist/vendor/shared/durable-contract/cli-surface.d.ts +119 -0
  175. package/dist/vendor/shared/durable-contract/cli-surface.js +270 -0
  176. package/dist/vendor/shared/durable-contract/codes.d.ts +537 -0
  177. package/dist/vendor/shared/durable-contract/codes.js +475 -0
  178. package/dist/vendor/shared/durable-contract/constants.d.ts +153 -0
  179. package/dist/vendor/shared/durable-contract/constants.js +179 -0
  180. package/dist/vendor/shared/durable-contract/doors.d.ts +119 -0
  181. package/dist/vendor/shared/durable-contract/doors.js +249 -0
  182. package/dist/vendor/shared/durable-contract/envelope.d.ts +103 -0
  183. package/dist/vendor/shared/durable-contract/envelope.js +317 -0
  184. package/dist/vendor/shared/durable-contract/events.d.ts +147 -0
  185. package/dist/vendor/shared/durable-contract/events.js +630 -0
  186. package/dist/vendor/shared/durable-contract/executor-state.d.ts +41 -0
  187. package/dist/vendor/shared/durable-contract/executor-state.js +32 -0
  188. package/dist/vendor/shared/durable-contract/fixlines.d.ts +318 -0
  189. package/dist/vendor/shared/durable-contract/fixlines.js +483 -0
  190. package/dist/vendor/shared/durable-contract/freeze-record.d.ts +787 -0
  191. package/dist/vendor/shared/durable-contract/freeze-record.js +361 -0
  192. package/dist/vendor/shared/durable-contract/index.d.ts +36 -0
  193. package/dist/vendor/shared/durable-contract/index.js +37 -0
  194. package/dist/vendor/shared/durable-contract/journal-approvals.d.ts +29 -0
  195. package/dist/vendor/shared/durable-contract/journal-approvals.js +60 -0
  196. package/dist/vendor/shared/durable-contract/keys.d.ts +24 -0
  197. package/dist/vendor/shared/durable-contract/keys.js +66 -0
  198. package/dist/vendor/shared/durable-contract/lock.d.ts +128 -0
  199. package/dist/vendor/shared/durable-contract/lock.js +151 -0
  200. package/dist/vendor/shared/durable-contract/names.d.ts +25 -0
  201. package/dist/vendor/shared/durable-contract/names.js +78 -0
  202. package/dist/vendor/shared/durable-contract/owner-verbs.d.ts +175 -0
  203. package/dist/vendor/shared/durable-contract/owner-verbs.js +403 -0
  204. package/dist/vendor/shared/durable-contract/paths.d.ts +23 -0
  205. package/dist/vendor/shared/durable-contract/paths.js +35 -0
  206. package/dist/vendor/shared/durable-contract/pure-fn.d.ts +48 -0
  207. package/dist/vendor/shared/durable-contract/pure-fn.js +89 -0
  208. package/dist/vendor/shared/durable-contract/routes.d.ts +205 -0
  209. package/dist/vendor/shared/durable-contract/routes.js +315 -0
  210. package/dist/vendor/shared/durable-contract/schema.d.ts +126 -0
  211. package/dist/vendor/shared/durable-contract/schema.js +441 -0
  212. package/dist/vendor/shared/durable-contract/seal.d.ts +54 -0
  213. package/dist/vendor/shared/durable-contract/seal.js +99 -0
  214. package/dist/vendor/shared/durable-contract/secret-scope.d.ts +28 -0
  215. package/dist/vendor/shared/durable-contract/secret-scope.js +76 -0
  216. package/dist/vendor/shared/durable-contract/session-id.d.ts +21 -0
  217. package/dist/vendor/shared/durable-contract/session-id.js +58 -0
  218. package/dist/vendor/shared/durable-contract/spec.d.ts +162 -0
  219. package/dist/vendor/shared/durable-contract/spec.js +286 -0
  220. package/dist/vendor/shared/durable-contract/states.d.ts +96 -0
  221. package/dist/vendor/shared/durable-contract/states.js +218 -0
  222. package/dist/vendor/shared/durable-contract/telemetry.d.ts +94 -0
  223. package/dist/vendor/shared/durable-contract/telemetry.js +180 -0
  224. package/dist/vendor/shared/durable-contract/test-mode.d.ts +62 -0
  225. package/dist/vendor/shared/durable-contract/test-mode.js +140 -0
  226. package/dist/vendor/shared/durable-contract/turn.d.ts +57 -0
  227. package/dist/vendor/shared/durable-contract/turn.js +81 -0
  228. package/dist/vendor/shared/durable-contract/vectors.d.ts +191 -0
  229. package/dist/vendor/shared/durable-contract/vectors.js +208 -0
  230. package/package.json +4 -3
  231. package/plugins/integrity-manifest.json +35 -0
  232. package/plugins/mnemom/hooks/hooks.json +15 -1
  233. package/plugins/mnemom/hooks/register.tsx +60 -2
  234. package/plugins/mnemom/hooks/seat-hello.mjs +116 -0
  235. package/dist/commands/agent-implicit-notice.d.ts +0 -31
  236. package/dist/commands/agent-implicit-notice.js +0 -73
@@ -0,0 +1,244 @@
1
+ // MNE-9298 Tier 1: the CTO's own Anthropic Admin key, used LOCALLY, to read measured usage. Port of
2
+ // mnemom-api src/org-scan/usage/usage-client.ts (two read-only GETs: usage_report/messages grouped by
3
+ // context_window, and cost_report) with the server-only parts (egress allowlist, WIF) dropped.
4
+ //
5
+ // The key is held in memory for the length of the two reads. It is never stored, logged, written to disk,
6
+ // echoed, put in argv, a URL or an error message, and is sent only to api.anthropic.com (a constant, not
7
+ // configurable) in the x-api-key header. Every failure surfaces as a fixed sentence: the thrown value, the
8
+ // response body and the key never reach the terminal.
9
+ export const ANTHROPIC_ADMIN_ORIGIN = "https://api.anthropic.com";
10
+ export const ADMIN_KEY_ENV = "ANTHROPIC_ADMIN_KEY";
11
+ const ANTHROPIC_VERSION = "2023-06-01";
12
+ const USAGE_PATH = "/v1/organizations/usage_report/messages";
13
+ const COST_PATH = "/v1/organizations/cost_report";
14
+ export const DEFAULT_MAX_PAGES = 20;
15
+ /** One shared deadline for a request including its retries (not N x timeout). */
16
+ export const DEFAULT_TIMEOUT_MS = 15_000;
17
+ export const DEFAULT_MAX_RETRIES = 2;
18
+ const MAX_RETRY_WAIT_MS = 5_000;
19
+ const ADMIN_KEY_RE = /^sk-ant-admin[A-Za-z0-9_-]{8,}$/;
20
+ /** Shape check only; the key is never echoed, even on a mismatch. */
21
+ export const isAdminKeyShape = (k) => typeof k === "string" && ADMIN_KEY_RE.test(k.trim());
22
+ const FAILURE_TEXT = {
23
+ key_invalid: "The Anthropic admin key is not an Admin API key (it should start with sk-ant-admin).",
24
+ key_refused: "Anthropic refused the admin key (401/403).",
25
+ rate_limited: "Anthropic rate limit reached.",
26
+ timeout: "Anthropic did not answer in time.",
27
+ network: "Anthropic was unreachable.",
28
+ upstream: "Anthropic usage could not be read.",
29
+ malformed: "Anthropic returned usage in a shape this CLI does not recognise.",
30
+ too_large: "Anthropic usage for this period is too large to read completely.",
31
+ };
32
+ /** Fixed sentence for a failure reason. */
33
+ export const usageFailureText = (r) => FAILURE_TEXT[r];
34
+ /** Carries only a reason tag. Its message is the fixed sentence: nothing upstream can reach it. */
35
+ export class AnthropicUsageError extends Error {
36
+ reason;
37
+ constructor(reason) {
38
+ super(FAILURE_TEXT[reason]);
39
+ this.reason = reason;
40
+ this.name = "AnthropicUsageError";
41
+ }
42
+ }
43
+ const bad = () => {
44
+ throw new AnthropicUsageError("malformed");
45
+ };
46
+ const rec = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : bad();
47
+ function reqNum(r, k) {
48
+ const v = r[k];
49
+ return typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : bad();
50
+ }
51
+ /** Optional counter inside an optional object: absent is 0, present-but-wrong is an error. */
52
+ function optNum(o, k) {
53
+ if (o === undefined || o === null)
54
+ return 0;
55
+ if (typeof o !== "object")
56
+ return bad();
57
+ const v = o[k];
58
+ if (v === undefined || v === null)
59
+ return 0;
60
+ return typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : bad();
61
+ }
62
+ export function parseUsageRow(raw) {
63
+ const r = rec(raw);
64
+ const cw = r.context_window;
65
+ if (cw !== null && cw !== undefined && cw !== "0-200k" && cw !== "200k-1M")
66
+ bad();
67
+ return {
68
+ tokens: reqNum(r, "uncached_input_tokens") +
69
+ reqNum(r, "cache_read_input_tokens") +
70
+ reqNum(r, "output_tokens") +
71
+ optNum(r.cache_creation, "ephemeral_1h_input_tokens") +
72
+ optNum(r.cache_creation, "ephemeral_5m_input_tokens"),
73
+ contextWindow: (cw ?? null),
74
+ };
75
+ }
76
+ const CENT = /^-?\d+(\.\d+)?$/;
77
+ export function parseCostRow(raw) {
78
+ const r = rec(raw);
79
+ if (typeof r.amount !== "string" || !CENT.test(r.amount))
80
+ bad();
81
+ if (typeof r.currency !== "string" || r.currency === "")
82
+ bad();
83
+ return { cents: Number(r.amount), currency: r.currency };
84
+ }
85
+ const DAY_MS = 86_400_000;
86
+ /** Buckets are UTC-aligned: floor so a mid-day start reads the whole bucket it falls in. */
87
+ export function alignStartingAt(startingAt) {
88
+ const t = Date.parse(startingAt);
89
+ if (!Number.isFinite(t))
90
+ return startingAt;
91
+ return new Date(Math.floor(t / DAY_MS) * DAY_MS).toISOString().replace(".000Z", "Z");
92
+ }
93
+ const backoff = (attempt) => Math.min(250 * 2 ** (attempt - 1), MAX_RETRY_WAIT_MS);
94
+ function retryWait(res, attempt) {
95
+ const ra = Number(res.headers.get("retry-after"));
96
+ return Number.isFinite(ra) && ra > 0 ? ra * 1000 : backoff(attempt);
97
+ }
98
+ class Reader {
99
+ key;
100
+ fetchImpl;
101
+ sleep;
102
+ maxPages;
103
+ timeoutMs;
104
+ maxRetries;
105
+ constructor(key, deps) {
106
+ this.key = key;
107
+ this.fetchImpl = deps.fetchImpl ?? ((...a) => fetch(...a));
108
+ this.sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
109
+ this.maxPages = deps.maxPages ?? DEFAULT_MAX_PAGES;
110
+ this.timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
111
+ this.maxRetries = deps.maxRetries ?? DEFAULT_MAX_RETRIES;
112
+ }
113
+ async walk(path, base, parse, callMaxPages) {
114
+ const ceiling = typeof callMaxPages === "number" && Number.isFinite(callMaxPages) && callMaxPages >= 1
115
+ ? Math.min(this.maxPages, Math.floor(callMaxPages))
116
+ : this.maxPages;
117
+ const rows = [];
118
+ let page = null;
119
+ let pages = 0;
120
+ for (;;) {
121
+ const params = new URLSearchParams(base);
122
+ if (page)
123
+ params.set("page", page);
124
+ const body = await this.request(`${ANTHROPIC_ADMIN_ORIGIN}${path}?${params.toString()}`);
125
+ pages += 1;
126
+ if (!Array.isArray(body.data))
127
+ bad();
128
+ for (const raw of body.data) {
129
+ const b = rec(raw);
130
+ if (typeof b.starting_at !== "string" || typeof b.ending_at !== "string")
131
+ bad();
132
+ if (!Array.isArray(b.results))
133
+ bad();
134
+ for (const r of b.results)
135
+ rows.push(parse(r));
136
+ }
137
+ const more = body.has_more;
138
+ if (more !== undefined && more !== null && typeof more !== "boolean")
139
+ bad();
140
+ if (more !== true)
141
+ return { rows, truncated: false, pages };
142
+ if (typeof body.next_page !== "string" || body.next_page === "")
143
+ bad();
144
+ if (pages >= ceiling)
145
+ return { rows, truncated: true, pages };
146
+ page = body.next_page;
147
+ }
148
+ }
149
+ async request(url) {
150
+ const deadline = AbortSignal.timeout(this.timeoutMs);
151
+ for (let attempt = 0;;) {
152
+ let res;
153
+ try {
154
+ res = await this.fetchImpl(url, {
155
+ method: "GET",
156
+ headers: {
157
+ "x-api-key": this.key,
158
+ "anthropic-version": ANTHROPIC_VERSION,
159
+ accept: "application/json",
160
+ },
161
+ // A redirect would carry the x-api-key header to wherever it points: refuse to follow one.
162
+ redirect: "error",
163
+ signal: deadline,
164
+ });
165
+ }
166
+ catch {
167
+ // Never surface the thrown value: it can carry the request.
168
+ if (deadline.aborted)
169
+ throw new AnthropicUsageError("timeout");
170
+ if (attempt++ < this.maxRetries) {
171
+ await this.sleep(backoff(attempt));
172
+ continue;
173
+ }
174
+ throw new AnthropicUsageError("network");
175
+ }
176
+ if (res.ok) {
177
+ let json;
178
+ try {
179
+ json = await res.json();
180
+ }
181
+ catch {
182
+ throw new AnthropicUsageError("upstream");
183
+ }
184
+ return rec(json);
185
+ }
186
+ await res.body?.cancel().catch(() => { });
187
+ if (res.status === 401 || res.status === 403)
188
+ throw new AnthropicUsageError("key_refused");
189
+ const retryable = res.status === 429 || res.status >= 500;
190
+ const wait = retryable ? retryWait(res, attempt + 1) : 0;
191
+ if (retryable &&
192
+ !deadline.aborted &&
193
+ wait <= MAX_RETRY_WAIT_MS &&
194
+ attempt++ < this.maxRetries) {
195
+ await this.sleep(wait);
196
+ continue;
197
+ }
198
+ throw new AnthropicUsageError(res.status === 429 ? "rate_limited" : "upstream");
199
+ }
200
+ }
201
+ }
202
+ const validDay = (d) => /^\d{4}-\d{2}-\d{2}$/.test(d) && Number.isFinite(Date.parse(`${d}T00:00:00Z`));
203
+ /**
204
+ * The same two reads mnemom-api made: usage grouped by context_window (the exact >200k share) and cost
205
+ * (total spend). The key is shape-checked before any call so a regular API key never leaves the machine.
206
+ * Throws AnthropicUsageError only. A walk stopped by the page cap is an error, never a short total.
207
+ */
208
+ export async function fetchMeasuredUsage(key, period, deps = {}) {
209
+ const k = key?.trim();
210
+ if (!k || !isAdminKeyShape(k))
211
+ throw new AnthropicUsageError("key_invalid");
212
+ if (!validDay(period.start) || !validDay(period.end))
213
+ throw new AnthropicUsageError("malformed");
214
+ const startingAt = alignStartingAt(`${period.start}T00:00:00Z`);
215
+ const endingAt = new Date(Date.parse(`${period.end}T00:00:00Z`) + DAY_MS).toISOString();
216
+ const reader = new Reader(k, deps);
217
+ const up = new URLSearchParams({
218
+ starting_at: startingAt,
219
+ ending_at: endingAt,
220
+ bucket_width: "1d",
221
+ });
222
+ up.append("group_by[]", "context_window");
223
+ const usage = await reader.walk(USAGE_PATH, up, parseUsageRow);
224
+ if (usage.truncated)
225
+ throw new AnthropicUsageError("too_large");
226
+ const cp = new URLSearchParams({ starting_at: startingAt, ending_at: endingAt });
227
+ const cost = await reader.walk(COST_PATH, cp, parseCostRow);
228
+ if (cost.truncated)
229
+ throw new AnthropicUsageError("too_large");
230
+ let total = 0;
231
+ let over = 0;
232
+ for (const r of usage.rows) {
233
+ total += r.tokens;
234
+ if (r.contextWindow === "200k-1M")
235
+ over += r.tokens;
236
+ }
237
+ let cents = 0;
238
+ for (const r of cost.rows) {
239
+ if (r.currency !== "USD")
240
+ throw new AnthropicUsageError("malformed");
241
+ cents += r.cents;
242
+ }
243
+ return { usd: Math.round(cents) / 100, over200kShare: total > 0 ? over / total : null };
244
+ }
@@ -0,0 +1,56 @@
1
+ declare const _default: {
2
+ readonly schema_version: 1;
3
+ readonly as_of: "2026-10-28T00:00:00Z";
4
+ readonly source: "ADW 'Run cost' PR comments (cost_report.py) on merged fleet PRs (org-wide GitHub search for run-cost comments, plus shipped PRs from the eval sets); cost_usd sums distinct runs and is a floor";
5
+ readonly candidates: 236;
6
+ readonly rows: readonly [{
7
+ readonly repo: "aap";
8
+ readonly pr: 100;
9
+ readonly additions: 117;
10
+ readonly deletions: 68;
11
+ readonly cost_usd: 0.4;
12
+ readonly runs: 1;
13
+ readonly models: readonly ["sonnet"];
14
+ }, {
15
+ readonly repo: "mnemom-api";
16
+ readonly pr: 1816;
17
+ readonly additions: 239;
18
+ readonly deletions: 0;
19
+ readonly cost_usd: 0.55;
20
+ readonly runs: 1;
21
+ readonly models: readonly ["haiku", "sonnet"];
22
+ }, {
23
+ readonly repo: "mnemom-api";
24
+ readonly pr: 3639;
25
+ readonly additions: 2260;
26
+ readonly deletions: 0;
27
+ readonly cost_usd: 5.42;
28
+ readonly runs: 1;
29
+ readonly models: readonly ["sonnet"];
30
+ }, {
31
+ readonly repo: "mnemom-research-grade";
32
+ readonly pr: 112;
33
+ readonly additions: 73;
34
+ readonly deletions: 10;
35
+ readonly cost_usd: 0.35;
36
+ readonly runs: 1;
37
+ readonly models: readonly ["haiku", "sonnet"];
38
+ }, {
39
+ readonly repo: "mnemom-website";
40
+ readonly pr: 1668;
41
+ readonly additions: 78;
42
+ readonly deletions: 119;
43
+ readonly cost_usd: 0.23;
44
+ readonly runs: 1;
45
+ readonly models: readonly ["sonnet"];
46
+ }, {
47
+ readonly repo: "mnemom-website";
48
+ readonly pr: 1669;
49
+ readonly additions: 126;
50
+ readonly deletions: 22;
51
+ readonly cost_usd: 0.28;
52
+ readonly runs: 1;
53
+ readonly models: readonly ["sonnet"];
54
+ }];
55
+ };
56
+ export default _default;
@@ -0,0 +1,64 @@
1
+ // Cost corpus (port of mnemom-api src/org-scan/spend/cost-corpus.v1.json, as_of 2026-10-28T00:00:00Z). A TS module, not a
2
+ // JSON asset, so the build needs no copy-assets entry.
3
+ export default {
4
+ schema_version: 1,
5
+ as_of: "2026-10-28T00:00:00Z",
6
+ source: "ADW 'Run cost' PR comments (cost_report.py) on merged fleet PRs (org-wide GitHub search for run-cost comments, plus shipped PRs from the eval sets); cost_usd sums distinct runs and is a floor",
7
+ candidates: 236,
8
+ rows: [
9
+ {
10
+ repo: "aap",
11
+ pr: 100,
12
+ additions: 117,
13
+ deletions: 68,
14
+ cost_usd: 0.4,
15
+ runs: 1,
16
+ models: ["sonnet"],
17
+ },
18
+ {
19
+ repo: "mnemom-api",
20
+ pr: 1816,
21
+ additions: 239,
22
+ deletions: 0,
23
+ cost_usd: 0.55,
24
+ runs: 1,
25
+ models: ["haiku", "sonnet"],
26
+ },
27
+ {
28
+ repo: "mnemom-api",
29
+ pr: 3639,
30
+ additions: 2260,
31
+ deletions: 0,
32
+ cost_usd: 5.42,
33
+ runs: 1,
34
+ models: ["sonnet"],
35
+ },
36
+ {
37
+ repo: "mnemom-research-grade",
38
+ pr: 112,
39
+ additions: 73,
40
+ deletions: 10,
41
+ cost_usd: 0.35,
42
+ runs: 1,
43
+ models: ["haiku", "sonnet"],
44
+ },
45
+ {
46
+ repo: "mnemom-website",
47
+ pr: 1668,
48
+ additions: 78,
49
+ deletions: 119,
50
+ cost_usd: 0.23,
51
+ runs: 1,
52
+ models: ["sonnet"],
53
+ },
54
+ {
55
+ repo: "mnemom-website",
56
+ pr: 1669,
57
+ additions: 126,
58
+ deletions: 22,
59
+ cost_usd: 0.28,
60
+ runs: 1,
61
+ models: ["sonnet"],
62
+ },
63
+ ],
64
+ };
@@ -0,0 +1,33 @@
1
+ export type AiTool = "claude_code" | "codex" | "copilot" | "gemini";
2
+ export interface TokenPrice {
3
+ /** USD per 1M input tokens. */
4
+ inputPerMTok: number;
5
+ /** USD per 1M output tokens. */
6
+ outputPerMTok: number;
7
+ model: string;
8
+ }
9
+ export interface PriceBand {
10
+ low: TokenPrice;
11
+ high: TokenPrice;
12
+ /** Page the prices were read from. */
13
+ source: string;
14
+ }
15
+ export declare const PRICES_AS_OF = "2026-10-28";
16
+ export declare const TOOL_PRICES: Record<Exclude<AiTool, "copilot">, PriceBand>;
17
+ /**
18
+ * GitHub Copilot bills per premium request, not per token
19
+ * (https://docs.github.com/en/copilot/concepts/billing/copilot-requests),
20
+ * so it has no token price of its own. Its agent routes to the other vendors' models, so its band is
21
+ * the union of the other three: cheapest low to dearest high. An assumption, stated here once.
22
+ */
23
+ export declare function copilotBand(): PriceBand;
24
+ /**
25
+ * Share of billed tokens that are input (the rest output). Agent loops re-read large context and
26
+ * write little, so input dominates. An ASSUMPTION used both to turn our known run cost into
27
+ * tokens-per-line and to price those tokens for each tool; it cancels to first order when the
28
+ * tool's input/output price ratio matches ours, and is the main source of the range's width.
29
+ */
30
+ export declare const INPUT_SHARE = 0.9;
31
+ export declare function bandFor(tool: AiTool): PriceBand;
32
+ /** USD per token at the assumed input/output mix. */
33
+ export declare function blendedUsdPerToken(p: TokenPrice): number;
@@ -0,0 +1,57 @@
1
+ // MNE-9268: public list prices for the AI coding tools the Tier-3 spend estimator can name.
2
+ // Constants, not magic numbers: every row carries its source page and the date it was read.
3
+ // USD per million tokens (input / output), standard (non-batch) list price. A band is the cheapest
4
+ // and the dearest model a tool's coding agent plausibly runs on, so the estimate is a RANGE.
5
+ // Re-read the pages and bump PRICES_AS_OF when they move; a stale price widens nothing silently,
6
+ // it just shifts the range, which is why the date ships with the estimate's method text.
7
+ export const PRICES_AS_OF = "2026-10-28";
8
+ export const TOOL_PRICES = {
9
+ claude_code: {
10
+ source: "https://platform.claude.com/docs/en/about-claude/pricing",
11
+ low: { model: "Claude Sonnet 5.5", inputPerMTok: 2, outputPerMTok: 10 },
12
+ high: { model: "Claude Opus 5", inputPerMTok: 5, outputPerMTok: 25 },
13
+ },
14
+ codex: {
15
+ source: "https://developers.openai.com/api/docs/pricing",
16
+ low: { model: "gpt-5.3-codex (standard)", inputPerMTok: 1.75, outputPerMTok: 14 },
17
+ high: { model: "gpt-5.3-codex (fast)", inputPerMTok: 3.5, outputPerMTok: 28 },
18
+ },
19
+ gemini: {
20
+ source: "https://ai.google.dev/gemini-api/docs/pricing",
21
+ // Gemini 3.8 Flash is $0.75/$3.75 through 2026-12-31 and $1.50/$7.50 from 2027-01-01; the
22
+ // post-promotion price is used so the lower bound does not expire in two months.
23
+ low: { model: "Gemini 3.8 Flash (from 2027-01-01)", inputPerMTok: 1.5, outputPerMTok: 7.5 },
24
+ high: { model: "Gemini 3.1 Pro (prompts up to 200k)", inputPerMTok: 2, outputPerMTok: 12 },
25
+ },
26
+ };
27
+ /**
28
+ * GitHub Copilot bills per premium request, not per token
29
+ * (https://docs.github.com/en/copilot/concepts/billing/copilot-requests),
30
+ * so it has no token price of its own. Its agent routes to the other vendors' models, so its band is
31
+ * the union of the other three: cheapest low to dearest high. An assumption, stated here once.
32
+ */
33
+ export function copilotBand() {
34
+ const bands = Object.values(TOOL_PRICES);
35
+ const blend = (p) => p.inputPerMTok * INPUT_SHARE + p.outputPerMTok * (1 - INPUT_SHARE);
36
+ const low = bands.map((b) => b.low).sort((a, b) => blend(a) - blend(b))[0];
37
+ const high = bands.map((b) => b.high).sort((a, b) => blend(b) - blend(a))[0];
38
+ return {
39
+ low,
40
+ high,
41
+ source: "union of the claude_code, codex and gemini bands (per-request billing)",
42
+ };
43
+ }
44
+ /**
45
+ * Share of billed tokens that are input (the rest output). Agent loops re-read large context and
46
+ * write little, so input dominates. An ASSUMPTION used both to turn our known run cost into
47
+ * tokens-per-line and to price those tokens for each tool; it cancels to first order when the
48
+ * tool's input/output price ratio matches ours, and is the main source of the range's width.
49
+ */
50
+ export const INPUT_SHARE = 0.9;
51
+ export function bandFor(tool) {
52
+ return tool === "copilot" ? copilotBand() : TOOL_PRICES[tool];
53
+ }
54
+ /** USD per token at the assumed input/output mix. */
55
+ export function blendedUsdPerToken(p) {
56
+ return (p.inputPerMTok * INPUT_SHARE + p.outputPerMTok * (1 - INPUT_SHARE)) / 1_000_000;
57
+ }
@@ -0,0 +1,30 @@
1
+ import { type AiTool } from "./prices.js";
2
+ import { type TokenRate } from "./token-rate.js";
3
+ /** AI-assisted PRs needed before a range is worth printing. */
4
+ export declare const MIN_AI_PRS = 10;
5
+ /** Per-PR input. `markText` is commit messages / PR body, read for tool marks and dropped. */
6
+ export interface SpendPrInput {
7
+ additions: number;
8
+ deletions: number;
9
+ markText: string;
10
+ /** Tools already detected inside the PR source (so the body never leaves it). Wins over markText. */
11
+ tools?: AiTool[];
12
+ }
13
+ export type NoSpendReason = "too_few_ai_prs" | "no_rate" | "invalid_input";
14
+ export type SpendEstimate = {
15
+ kind: "range";
16
+ lowUsd: number;
17
+ highUsd: number;
18
+ aiPrs: number;
19
+ scannedPrs: number;
20
+ byTool: Partial<Record<AiTool, number>>;
21
+ /** One line, labelled estimate, passes claim-lint. */
22
+ line: string;
23
+ } | {
24
+ kind: "none";
25
+ reason: NoSpendReason;
26
+ aiPrs: number;
27
+ scannedPrs: number;
28
+ line: string;
29
+ };
30
+ export declare function estimateSpend(prs: unknown, rate?: TokenRate | null): SpendEstimate;
@@ -0,0 +1,70 @@
1
+ // MNE-9268: Tier-3 spend RANGE estimator. Pure and in-memory: takes per-PR counts and mark text, returns
2
+ // one labelled estimate line or an explicit "no estimate". Nothing is stored, fetched or logged.
3
+ //
4
+ // No line is produced when there are too few AI-assisted PRs to price (MIN_AI_PRS). That is a
5
+ // data-sufficiency threshold on the evidence behind the range, nothing to do with how large a
6
+ // reporting cohort is. Default-OFF behind ORG_SCAN_MODE via estimateSpendIfEnabled.
7
+ import { AI_TOOLS, detectAiTools } from "./ai-tool-detect.js";
8
+ import { PRICES_AS_OF, bandFor, blendedUsdPerToken } from "./prices.js";
9
+ import { DERIVED_TOKEN_RATE } from "./token-rate.js";
10
+ /** AI-assisted PRs needed before a range is worth printing. */
11
+ export const MIN_AI_PRS = 10;
12
+ /** Fixed strings only: a failure never carries input or an error message into the output. */
13
+ const NONE_LINES = {
14
+ too_few_ai_prs: "No spend estimate: too few AI-assisted PRs in this scan to price a range.",
15
+ no_rate: "No spend estimate: the cost reference data is not sufficient to price a range.",
16
+ invalid_input: "No spend estimate: the PR counts could not be read.",
17
+ };
18
+ const isCount = (n) => typeof n === "number" && Number.isFinite(n) && n >= 0;
19
+ function none(reason, aiPrs, scannedPrs) {
20
+ return { kind: "none", reason, aiPrs, scannedPrs, line: NONE_LINES[reason] };
21
+ }
22
+ function validPr(p) {
23
+ if (typeof p !== "object" || p === null)
24
+ return false;
25
+ const o = p;
26
+ return (isCount(o.additions) &&
27
+ isCount(o.deletions) &&
28
+ typeof o.markText === "string" &&
29
+ (o.tools === undefined ||
30
+ (Array.isArray(o.tools) && o.tools.every((t) => AI_TOOLS.includes(t)))));
31
+ }
32
+ /** Two significant figures so the range does not claim precision it lacks ($2.4, not $2; 0 stays $0). */
33
+ function usd(n) {
34
+ return `$${n.toLocaleString("en-US", { maximumSignificantDigits: 2 })}`;
35
+ }
36
+ export function estimateSpend(prs, rate = DERIVED_TOKEN_RATE) {
37
+ if (!Array.isArray(prs))
38
+ return none("invalid_input", 0, 0);
39
+ const scanned = prs.length;
40
+ if (!prs.every(validPr))
41
+ return none("invalid_input", 0, scanned);
42
+ let aiPrs = 0;
43
+ let low = 0;
44
+ let high = 0;
45
+ const byTool = {};
46
+ for (const p of prs) {
47
+ const tools = p.tools ?? detectAiTools(p.markText);
48
+ if (tools.length === 0)
49
+ continue;
50
+ aiPrs += 1;
51
+ for (const t of tools)
52
+ byTool[t] = (byTool[t] ?? 0) + 1;
53
+ if (!rate)
54
+ continue;
55
+ const lines = p.additions + p.deletions;
56
+ // A PR carrying several marks is priced once, across the widest band of the tools named.
57
+ const bands = tools.map(bandFor);
58
+ const lo = Math.min(...bands.map((b) => blendedUsdPerToken(b.low)));
59
+ const hi = Math.max(...bands.map((b) => blendedUsdPerToken(b.high)));
60
+ low += lines * rate.low * lo;
61
+ high += lines * rate.high * hi;
62
+ }
63
+ if (aiPrs < MIN_AI_PRS)
64
+ return none("too_few_ai_prs", aiPrs, scanned);
65
+ if (!rate)
66
+ return none("no_rate", aiPrs, scanned);
67
+ const line = `Estimate, AI tool spend: ${usd(low)} to ${usd(high)} across ${aiPrs} AI-assisted PRs ` +
68
+ `(public list prices as of ${PRICES_AS_OF} times a tokens-per-line rate from our own agents' PRs; not billing data).`;
69
+ return { kind: "range", lowUsd: low, highUsd: high, aiPrs, scannedPrs: scanned, byTool, line };
70
+ }
@@ -0,0 +1,25 @@
1
+ import type { SpendEstimate } from "./spend-estimate.js";
2
+ export declare const ORG_SCAN_ENV = "MNEMOM_ORG_SCAN_MODE";
3
+ /** Default OFF: only the exact string "true" turns the tiers on. */
4
+ export declare const isSpendTiersEnabled: (env?: NodeJS.ProcessEnv) => boolean;
5
+ export declare const NOT_ENABLED_MSG = "The spend fallback is not enabled.";
6
+ export declare const SPEND_INVALID_MSG = "Monthly spend must be a dollar amount above zero, like 5000.";
7
+ export declare const SPEND_NO_TERMINAL_MSG = "Pass --monthly-spend <usd> (there is no terminal to ask on).";
8
+ export declare const MAX_MONTHLY_SPEND_USD = 10000000;
9
+ /** Dollars, or null if the text is not a positive, plausible amount. */
10
+ export declare function parseMonthlySpendUsd(raw: string): number | null;
11
+ export type SpendTier = 1 | 2 | 3;
12
+ export interface SpendSelection {
13
+ /** null when the evidence is too thin: print nothing. */
14
+ tier: SpendTier | null;
15
+ line: string | null;
16
+ /** May this line leave the machine in a share payload? Never for a self-reported figure. */
17
+ shareable: boolean;
18
+ }
19
+ export declare function selectSpend(i: {
20
+ measuredUsd?: number;
21
+ /** Fraction of measured tokens from requests over 200k context; shown only with a measured figure. */
22
+ over200kShare?: number | null;
23
+ selfReportedUsd?: number | null;
24
+ estimate: SpendEstimate;
25
+ }): SpendSelection;
@@ -0,0 +1,42 @@
1
+ export const ORG_SCAN_ENV = "MNEMOM_ORG_SCAN_MODE";
2
+ /** Default OFF: only the exact string "true" turns the tiers on. */
3
+ export const isSpendTiersEnabled = (env = process.env) => env[ORG_SCAN_ENV] === "true";
4
+ export const NOT_ENABLED_MSG = "The spend fallback is not enabled.";
5
+ export const SPEND_INVALID_MSG = "Monthly spend must be a dollar amount above zero, like 5000.";
6
+ export const SPEND_NO_TERMINAL_MSG = "Pass --monthly-spend <usd> (there is no terminal to ask on).";
7
+ export const MAX_MONTHLY_SPEND_USD = 10_000_000;
8
+ const SPEND_RE = /^\$?\s*(\d{1,3}(,\d{3})+|\d+)(\.\d{1,2})?$/;
9
+ /** Dollars, or null if the text is not a positive, plausible amount. */
10
+ export function parseMonthlySpendUsd(raw) {
11
+ const t = raw.trim();
12
+ if (!SPEND_RE.test(t))
13
+ return null;
14
+ const n = Number(t.replace(/[$,\s]/g, ""));
15
+ return Number.isFinite(n) && n > 0 && n <= MAX_MONTHLY_SPEND_USD ? n : null;
16
+ }
17
+ const usd = (n) => `$${n.toLocaleString("en-US", { maximumFractionDigits: 2 })}`;
18
+ const isUsd = (n) => typeof n === "number" && Number.isFinite(n) && n > 0;
19
+ const pct = (f) => `${Math.round(f * 100)}%`;
20
+ const isShare = (n) => typeof n === "number" && Number.isFinite(n) && n >= 0 && n <= 1;
21
+ export function selectSpend(i) {
22
+ if (isUsd(i.measuredUsd)) {
23
+ return {
24
+ tier: 1,
25
+ line: `Tier 1, measured: ${usd(i.measuredUsd)} of Anthropic usage over the period${isShare(i.over200kShare)
26
+ ? ` (${pct(i.over200kShare)} of tokens in requests over 200k context)`
27
+ : ""}.`,
28
+ shareable: true,
29
+ };
30
+ }
31
+ if (isUsd(i.selfReportedUsd)) {
32
+ return {
33
+ tier: 2,
34
+ line: `Tier 2, self-reported: about ${usd(i.selfReportedUsd)} a month (given by you; not verified, not sent, not saved).`,
35
+ shareable: false,
36
+ };
37
+ }
38
+ if (i.estimate.kind === "range") {
39
+ return { tier: 3, line: `Tier 3, ${i.estimate.line}`, shareable: true };
40
+ }
41
+ return { tier: null, line: null, shareable: false };
42
+ }
@@ -0,0 +1,30 @@
1
+ /** Rows needed before the rate is trusted at all (data sufficiency, not a group size). */
2
+ export declare const MIN_CORPUS_ROWS = 5;
3
+ export interface CostRowShape {
4
+ repo: string;
5
+ pr: number;
6
+ additions: number;
7
+ deletions: number;
8
+ cost_usd: number;
9
+ runs: number;
10
+ models: string[];
11
+ }
12
+ export interface TokenRate {
13
+ /** Price-equivalent tokens per changed (added + deleted) line: 25th percentile. */
14
+ low: number;
15
+ median: number;
16
+ /** 75th percentile. */
17
+ high: number;
18
+ rows: number;
19
+ }
20
+ /** Linear-interpolated quantile of a sorted array. */
21
+ export declare function quantile(sorted: number[], q: number): number;
22
+ /**
23
+ * Derive the rate from corpus rows: per-row tokens/line, then the 25th, 50th and 75th percentile.
24
+ * Rows that fail validation are dropped (not repaired); fewer than MIN_CORPUS_ROWS valid rows
25
+ * returns null, never a rate built on a handful.
26
+ */
27
+ export declare function deriveTokenRate(rows: unknown): TokenRate | null;
28
+ export declare const CORPUS_AS_OF: string;
29
+ /** The shipped rate: derived once from the committed fixture. */
30
+ export declare const DERIVED_TOKEN_RATE: TokenRate | null;