@mainwave/cli 0.8.0 → 0.9.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.
- package/README.md +137 -41
- package/dist/adapters/claude-code.js +23 -4
- package/dist/adapters/codex-cli.js +1 -1
- package/dist/adapters/cursor.js +2 -2
- package/dist/core/apply.js +151 -41
- package/dist/core/doctor.js +26 -8
- package/dist/core/effective-settings.js +10 -0
- package/dist/core/entry-script.js +90 -0
- package/dist/core/git-bash.js +40 -0
- package/dist/core/install-hooks.js +126 -43
- package/dist/core/interview.js +53 -3
- package/dist/core/markers.js +678 -140
- package/dist/core/settings.js +16 -5
- package/dist/core/status.js +2 -1
- package/dist/core/wizard.js +46 -1
- package/dist/main.js +16 -9
- package/hooks/cursor-otlp.mjs +1 -1
- package/hooks/github-pr-marker.mjs +35 -22
- package/hooks/glab-mr-marker.mjs +795 -0
- package/hooks/jira-ticket-marker.mjs +27 -15
- package/hooks/linear-ticket-marker.mjs +27 -15
- package/hooks/mainwave-hook-node.mjs +42 -0
- package/hooks/mainwave-hook.mjs +301 -0
- package/hooks/marker-core.mjs +273 -40
- package/hooks/matchers.json +82 -6
- package/hooks/plan-snapshot.mjs +529 -0
- package/hooks/stop-failure.mjs +43 -0
- package/hooks/vocabulary.d.mts +48 -0
- package/hooks/vocabulary.mjs +181 -0
- package/package.json +5 -5
- package/skills/mainwave-instrument/SKILL.md +21 -7
- package/skills/mainwave-instrument/reference/api.md +29 -10
- package/skills/mainwave-instrument/reference/frameworks.md +3 -3
- package/skills/mainwave-instrument/reference/troubleshooting.md +12 -5
- package/skills/mainwave-setup/SKILL.md +47 -12
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The plan-snapshot feature of the Mainwave hook dispatcher (mainwave-hook.mjs),
|
|
3
|
+
// which runs it on Claude Code's UserPromptSubmit event: a snapshot of the
|
|
4
|
+
// signed-in Claude account's plan, its usage against its rate limits, and its
|
|
5
|
+
// extra-usage spend.
|
|
6
|
+
//
|
|
7
|
+
// Claude Code's own OpenTelemetry export carries none of these, but Claude
|
|
8
|
+
// Code keeps them in its local account record, `.claude.json`. This feature
|
|
9
|
+
// runs on every submitted prompt, reads only the fields
|
|
10
|
+
// listed below from that record, and emits one OTLP span
|
|
11
|
+
// (`mainwave.subscription.snapshot`) to the collector the session already
|
|
12
|
+
// exports to — every time it runs. UserPromptSubmit fires even on a turn that
|
|
13
|
+
// is later interrupted, which the end-of-turn event does not. It also fires on
|
|
14
|
+
// turns no person started (a scheduled task or loop, a background subagent
|
|
15
|
+
// reporting back, a message from another session), and Claude Code doesn't yet
|
|
16
|
+
// say which, so a snapshot marks when one was received, not that someone was
|
|
17
|
+
// at the keyboard.
|
|
18
|
+
//
|
|
19
|
+
// Claude Code refreshes these figures on its own schedule (the usage figures
|
|
20
|
+
// when the developer opens its usage view, the profile on sign-in), not per
|
|
21
|
+
// prompt, so each group carries the time Claude Code fetched it: the profile
|
|
22
|
+
// fields `profile_observed_at`, the usage figures `observed_at`. A field
|
|
23
|
+
// missing from the record is left out of the span — never sent as zero.
|
|
24
|
+
//
|
|
25
|
+
// What leaves the machine:
|
|
26
|
+
// - the hook event that ran, the session id, the prompt id when Claude Code passes one, and the turn's
|
|
27
|
+
// trace id and span id from the TRACEPARENT Claude Code gives hooks;
|
|
28
|
+
// - the account id, organization id and email (the same identity Claude
|
|
29
|
+
// Code's own spans carry);
|
|
30
|
+
// - from the account profile, exactly as Claude Code stores them: organization
|
|
31
|
+
// type, seat tier, rate-limit tier, billing type, organization role,
|
|
32
|
+
// workspace role, when the subscription was created, the trial's end and
|
|
33
|
+
// length, the date of the account's first Claude Code token, and when
|
|
34
|
+
// Claude Code fetched the profile;
|
|
35
|
+
// - from the usage cache, only when it names the same account: the 5-hour and
|
|
36
|
+
// 7-day utilization and their reset times; per rate limit, its group,
|
|
37
|
+
// percent used, severity, whether it is the active one and its reset time,
|
|
38
|
+
// and for a scoped limit (one per model) the scope's model id, model name or
|
|
39
|
+
// surface;
|
|
40
|
+
// whether extra usage is on, the amount spent and its monthly limit in the
|
|
41
|
+
// currency's minor unit, the currency and its decimal places, whether the
|
|
42
|
+
// spend limit is reached, whether and why extra usage is disabled; and when
|
|
43
|
+
// Claude Code fetched those figures.
|
|
44
|
+
// Nothing else in the file is read into the span, and the prompt is never
|
|
45
|
+
// read at all.
|
|
46
|
+
//
|
|
47
|
+
// The record's layout is Claude Code's own and undocumented, so every field is
|
|
48
|
+
// checked before use and anything unexpected is left out. Fails open: any
|
|
49
|
+
// error ends the run with nothing on stdout (Claude Code feeds a
|
|
50
|
+
// UserPromptSubmit hook's stdout to the model). The hook group is `async`, so
|
|
51
|
+
// Claude Code starts it and carries on without waiting: the span is POSTed
|
|
52
|
+
// inline, under a hard timeout of its own (Claude Code doesn't enforce
|
|
53
|
+
// `timeout` on an async hook), and a prompt never waits on the collector.
|
|
54
|
+
// Under `claude -p` Claude Code kills an async hook still running at teardown,
|
|
55
|
+
// so a send that hasn't finished when such a run ends is lost.
|
|
56
|
+
|
|
57
|
+
import { createHash } from 'node:crypto'
|
|
58
|
+
import { readFileSync, writeFileSync } from 'node:fs'
|
|
59
|
+
|
|
60
|
+
import {
|
|
61
|
+
boolAttr,
|
|
62
|
+
buildMarkerPayload,
|
|
63
|
+
doubleAttr,
|
|
64
|
+
emitMarker,
|
|
65
|
+
hookFlag,
|
|
66
|
+
intAttr,
|
|
67
|
+
isOkStatus,
|
|
68
|
+
loadOtelConfig,
|
|
69
|
+
ensureLogDir,
|
|
70
|
+
markerHostSource,
|
|
71
|
+
markerLog,
|
|
72
|
+
markerLogPath,
|
|
73
|
+
markerManagedDir,
|
|
74
|
+
markerOauthAccountPath,
|
|
75
|
+
markerProjectDir,
|
|
76
|
+
markerSessionEnv,
|
|
77
|
+
markerTool,
|
|
78
|
+
oauthAccountFromRecord,
|
|
79
|
+
onceReaders,
|
|
80
|
+
parseTraceparent,
|
|
81
|
+
stringAttr,
|
|
82
|
+
trimmedOrUndefined,
|
|
83
|
+
} from './marker-core.mjs'
|
|
84
|
+
import {
|
|
85
|
+
ATTR_EXTRA_USAGE_CACHED_DISABLED_REASON,
|
|
86
|
+
ATTR_EXTRA_USAGE_CURRENCY,
|
|
87
|
+
ATTR_EXTRA_USAGE_DISABLED_REASON,
|
|
88
|
+
ATTR_EXTRA_USAGE_ENABLED,
|
|
89
|
+
ATTR_EXTRA_USAGE_EXPONENT,
|
|
90
|
+
ATTR_EXTRA_USAGE_LIMIT_MINOR,
|
|
91
|
+
ATTR_EXTRA_USAGE_SPEND_LIMIT_REACHED,
|
|
92
|
+
ATTR_EXTRA_USAGE_USED_MINOR,
|
|
93
|
+
ATTR_EXTRA_USAGE_USER_DISABLED,
|
|
94
|
+
ATTR_ORGANIZATION_ID,
|
|
95
|
+
ATTR_PROMPT_ID,
|
|
96
|
+
ATTR_SUBSCRIPTION_BILLING_TYPE,
|
|
97
|
+
ATTR_SUBSCRIPTION_CREATED_AT,
|
|
98
|
+
ATTR_SUBSCRIPTION_FIRST_TOKEN_DATE,
|
|
99
|
+
ATTR_SUBSCRIPTION_OBSERVED_AT,
|
|
100
|
+
ATTR_SUBSCRIPTION_ORGANIZATION_ROLE,
|
|
101
|
+
ATTR_SUBSCRIPTION_ORGANIZATION_TYPE,
|
|
102
|
+
ATTR_SUBSCRIPTION_PROFILE_OBSERVED_AT,
|
|
103
|
+
ATTR_SUBSCRIPTION_PROVIDER,
|
|
104
|
+
ATTR_SUBSCRIPTION_RATE_LIMIT_TIER,
|
|
105
|
+
ATTR_SUBSCRIPTION_SEAT_TIER,
|
|
106
|
+
ATTR_SUBSCRIPTION_TRIAL_DURATION_DAYS,
|
|
107
|
+
ATTR_SUBSCRIPTION_TRIAL_ENDS_AT,
|
|
108
|
+
ATTR_SUBSCRIPTION_TRIGGER,
|
|
109
|
+
ATTR_SUBSCRIPTION_WORKSPACE_ROLE,
|
|
110
|
+
ATTR_USAGE_FIVE_HOUR_RESETS_AT,
|
|
111
|
+
ATTR_USAGE_FIVE_HOUR_UTILIZATION,
|
|
112
|
+
ATTR_USAGE_SEVEN_DAY_RESETS_AT,
|
|
113
|
+
ATTR_USAGE_SEVEN_DAY_UTILIZATION,
|
|
114
|
+
SUBSCRIPTION_SNAPSHOT,
|
|
115
|
+
VENDOR_ANTHROPIC,
|
|
116
|
+
SUBSCRIPTION_LIMIT_FIELDS,
|
|
117
|
+
SUBSCRIPTION_LIMIT_SCOPED_FIELDS,
|
|
118
|
+
subscriptionLimitKey,
|
|
119
|
+
} from './vocabulary.mjs'
|
|
120
|
+
|
|
121
|
+
const LOG_NAME = 'plan-snapshot.log'
|
|
122
|
+
/** The feature's log: skips and failures — what someone diagnoses. A 2xx
|
|
123
|
+
* post, the common case on every prompt, is not logged (§ `emitMarker`'s
|
|
124
|
+
* `logOk`); it stamps the success sidecar instead (§ `stampSuccess`). */
|
|
125
|
+
const snapshotLog = (argv) => markerLog(argv, LOG_NAME)
|
|
126
|
+
|
|
127
|
+
/** The sidecar a 2xx post rewrites: `<log>.ok`, one timestamp line, never
|
|
128
|
+
* appended to, so it stays one line however many prompts run. Its mtime is
|
|
129
|
+
* the last successful send — what `doctor` reports as activity. */
|
|
130
|
+
export const successMarkerPath = (argv) => `${markerLogPath(argv, LOG_NAME)}.ok`
|
|
131
|
+
|
|
132
|
+
/** Rewrite the success sidecar when `status` is a 2xx; anything else — no
|
|
133
|
+
* response, a non-2xx — never counts as activity. Best-effort, like the log. */
|
|
134
|
+
export const stampSuccess = (status, argv = process.argv, now = new Date()) => {
|
|
135
|
+
if (!isOkStatus(status)) return false
|
|
136
|
+
try {
|
|
137
|
+
const path = successMarkerPath(argv)
|
|
138
|
+
ensureLogDir(path)
|
|
139
|
+
writeFileSync(path, `${now.toISOString()}\n`, { mode: 0o600 })
|
|
140
|
+
return true
|
|
141
|
+
} catch {
|
|
142
|
+
return false
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Non-coding source/service, as for the ticket and PR markers: the span is
|
|
147
|
+
// about the Anthropic account, not a stretch of coding work.
|
|
148
|
+
const SNAPSHOT_SOURCE = 'hook.anthropic'
|
|
149
|
+
const SNAPSHOT_SERVICE = 'mainwave.plan-hook'
|
|
150
|
+
|
|
151
|
+
/** How long the POST may wait on the collector, and the most a
|
|
152
|
+
* `--send-timeout-ms` flag may set. Claude Code doesn't enforce a `timeout`
|
|
153
|
+
* on an async hook, so this bound — and § `EXIT_GRACE_MS` after it — is the
|
|
154
|
+
* feature's own; the dispatcher's cap for it is their sum. */
|
|
155
|
+
export const SEND_TIMEOUT_MS = 4000
|
|
156
|
+
|
|
157
|
+
/** How long after the send timeout a watchdog exits the process, should
|
|
158
|
+
* anything (a DNS lookup the abort can't cancel) still hold it open. */
|
|
159
|
+
export const EXIT_GRACE_MS = 250
|
|
160
|
+
|
|
161
|
+
/** At most this many rate-limit entries become keys (the record held 3). */
|
|
162
|
+
export const MAX_LIMITS = 16
|
|
163
|
+
|
|
164
|
+
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
|
|
165
|
+
|
|
166
|
+
/** A non-empty string exactly as stored, else undefined. Strings from the
|
|
167
|
+
* record are never trimmed, mapped or re-cased: readers interpret them. */
|
|
168
|
+
const rawString = (v) => (typeof v === 'string' && v !== '' ? v : undefined)
|
|
169
|
+
|
|
170
|
+
/** A non-negative safe integer, else undefined. */
|
|
171
|
+
const count = (v) => (Number.isSafeInteger(v) && v >= 0 ? v : undefined)
|
|
172
|
+
|
|
173
|
+
/** A finite number, else undefined (a percent may be fractional). */
|
|
174
|
+
const finite = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined)
|
|
175
|
+
|
|
176
|
+
const bool = (v) => (typeof v === 'boolean' ? v : undefined)
|
|
177
|
+
|
|
178
|
+
/** Epoch milliseconds as an ISO-8601 UTC timestamp, else undefined. */
|
|
179
|
+
const isoFromMs = (v) => {
|
|
180
|
+
if (typeof v !== 'number' || !Number.isFinite(v) || v <= 0) return undefined
|
|
181
|
+
const d = new Date(v)
|
|
182
|
+
return Number.isNaN(d.getTime()) ? undefined : d.toISOString()
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** `[key, value]` pairs → typed attributes, skipping undefined values. */
|
|
186
|
+
const typed = (make, pairs) => pairs.filter(([, v]) => v !== undefined).map(([k, v]) => make(k, v))
|
|
187
|
+
|
|
188
|
+
/** A rate limit's `kind` or scope as a key segment: lower-cased, every run
|
|
189
|
+
* of characters outside `[a-z0-9_]` collapsed to `_`, trimmed of `_`, at most
|
|
190
|
+
* 64 characters; undefined when nothing is left. A segment that would be cut
|
|
191
|
+
* keeps a 55-character prefix (trailing `_` trimmed), `_`, and the first 8 hex
|
|
192
|
+
* of the sha256 of the raw value, so distinct long ids stay distinct. */
|
|
193
|
+
export const limitKeySegment = (v) => {
|
|
194
|
+
if (typeof v !== 'string') return undefined
|
|
195
|
+
const seg = v
|
|
196
|
+
.toLowerCase()
|
|
197
|
+
.replace(/[^a-z0-9_]+/g, '_')
|
|
198
|
+
.replace(/^_+|_+$/g, '')
|
|
199
|
+
if (seg === '') return undefined
|
|
200
|
+
if (seg.length <= 64) return seg
|
|
201
|
+
const hash = createHash('sha256').update(v).digest('hex').slice(0, 8)
|
|
202
|
+
return `${seg.slice(0, 55).replace(/_+$/, '')}_${hash}`
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** The label a limit's `scope` is known by: `scope.model.id`, else
|
|
206
|
+
* `scope.model.display_name`, else `scope.surface` — the first non-empty
|
|
207
|
+
* string, raw. Undefined for no scope (`null` on the unscoped kinds). */
|
|
208
|
+
export const limitScopeLabel = (scope) => {
|
|
209
|
+
if (!isPlainObject(scope)) return undefined
|
|
210
|
+
const model = isPlainObject(scope.model) ? scope.model : {}
|
|
211
|
+
return rawString(model.id) ?? rawString(model.display_name) ?? rawString(scope.surface)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** How each declared limit field is typed and read. Keyed by field name so the
|
|
215
|
+
* emitted keys come from vocabulary's declared field lists, which the registry
|
|
216
|
+
* conformance test checks. */
|
|
217
|
+
const LIMIT_FIELDS = {
|
|
218
|
+
group: [stringAttr, (l) => rawString(l.group)],
|
|
219
|
+
percent: [doubleAttr, (l) => finite(l.percent)],
|
|
220
|
+
severity: [stringAttr, (l) => rawString(l.severity)],
|
|
221
|
+
is_active: [boolAttr, (l) => bool(l.is_active)],
|
|
222
|
+
resets_at: [stringAttr, (l) => rawString(l.resets_at)],
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** One limit entry's typed attributes under `kind` (and `scope`, when scoped),
|
|
226
|
+
* with the raw scope label when scoped. */
|
|
227
|
+
const limitEntryAttributes = (kind, scope, l, scopeLabel) =>
|
|
228
|
+
(scope === undefined ? SUBSCRIPTION_LIMIT_FIELDS : SUBSCRIPTION_LIMIT_SCOPED_FIELDS).flatMap(
|
|
229
|
+
(field) => {
|
|
230
|
+
const [make, read] =
|
|
231
|
+
field === 'scope_label' ? [stringAttr, () => scopeLabel] : LIMIT_FIELDS[field]
|
|
232
|
+
return typed(make, [[subscriptionLimitKey(kind, field, scope), read(l)]])
|
|
233
|
+
},
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* The typed attributes for `utilization.limits[]`, one key group per entry:
|
|
238
|
+
* `mainwave.subscription.limit.<kind>.<field>` for an unscoped entry, and
|
|
239
|
+
* `mainwave.subscription.limit.<kind>.<scope>.<field>` plus `….scope_label`
|
|
240
|
+
* (the raw label, which sanitizing would otherwise lose) for a scoped one —
|
|
241
|
+
* `weekly_scoped` comes once per model (§ `limitKeySegment`,
|
|
242
|
+
* § `limitScopeLabel`). An entry that isn't an object or has no usable kind is
|
|
243
|
+
* skipped; a scope with no usable label keys as unscoped. When entries still
|
|
244
|
+
* land on the same key group, exact duplicates are sent once; entries that
|
|
245
|
+
* differ there are all dropped, since the keys couldn't say which one they
|
|
246
|
+
* came from. At most § `MAX_LIMITS` entries are read.
|
|
247
|
+
*/
|
|
248
|
+
export const limitAttributes = (limits) => {
|
|
249
|
+
if (!Array.isArray(limits)) return []
|
|
250
|
+
const groups = new Map()
|
|
251
|
+
for (const l of limits.slice(0, MAX_LIMITS)) {
|
|
252
|
+
if (!isPlainObject(l)) continue
|
|
253
|
+
const kind = limitKeySegment(l.kind)
|
|
254
|
+
if (kind === undefined) continue
|
|
255
|
+
const label = limitScopeLabel(l.scope)
|
|
256
|
+
const scope = limitKeySegment(label)
|
|
257
|
+
const base = scope === undefined ? kind : `${kind}.${scope}`
|
|
258
|
+
const attrs = limitEntryAttributes(kind, scope, l, scope === undefined ? undefined : label)
|
|
259
|
+
groups.set(base, [...(groups.get(base) ?? []), attrs])
|
|
260
|
+
}
|
|
261
|
+
return [...groups.values()].flatMap((variants) => {
|
|
262
|
+
const first = JSON.stringify(variants[0])
|
|
263
|
+
return variants.every((v) => JSON.stringify(v) === first) ? variants[0] : []
|
|
264
|
+
})
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* The snapshot in one parsed `.claude.json` document, or `undefined` when it
|
|
269
|
+
* has no usable `oauthAccount.accountUuid` (no account, nothing to attribute).
|
|
270
|
+
*
|
|
271
|
+
* Returns `{ accountUuid, email, attributes }`, where `attributes` is the
|
|
272
|
+
* OTLP key/value list for the span, in a fixed order, each key present only
|
|
273
|
+
* when its source value is usable:
|
|
274
|
+
*
|
|
275
|
+
* - plan / profile: provider (`anthropic`), organization id, organization
|
|
276
|
+
* type, seat tier, rate-limit tier, billing type, organization role,
|
|
277
|
+
* workspace role, subscription created-at, trial ends-at and duration
|
|
278
|
+
* (days), `profile_observed_at` (`profileFetchedAt`) — from `oauthAccount`;
|
|
279
|
+
* first-token date — the record's top-level `claudeCodeFirstTokenDate`;
|
|
280
|
+
* - `extra_usage.enabled`: the usage cache's `is_enabled`, else the account's
|
|
281
|
+
* `hasExtraUsageEnabled`;
|
|
282
|
+
* - everything else — 5-hour / 7-day utilization and resets, per-kind rate
|
|
283
|
+
* limits, the extra-usage figures and flags, the top-level
|
|
284
|
+
* `cachedExtraUsageDisabledReason`, and `observed_at` (`fetchedAtMs`) —
|
|
285
|
+
* only when `cachedUsageUtilization` names the same `accountUuid`: another
|
|
286
|
+
* account's figures are never sent. An absent cache sends none of them.
|
|
287
|
+
*/
|
|
288
|
+
export const snapshotFromRecord = (doc) => {
|
|
289
|
+
if (!isPlainObject(doc) || !isPlainObject(doc.oauthAccount)) return undefined
|
|
290
|
+
const account = doc.oauthAccount
|
|
291
|
+
// Identity is normalized as every marker normalizes it (ASCII-trimmed).
|
|
292
|
+
const { accountUuid, email } = oauthAccountFromRecord(doc)
|
|
293
|
+
if (accountUuid === undefined) return undefined
|
|
294
|
+
|
|
295
|
+
const cache = doc.cachedUsageUtilization
|
|
296
|
+
const usage =
|
|
297
|
+
isPlainObject(cache) &&
|
|
298
|
+
trimmedOrUndefined(cache.accountUuid) === accountUuid &&
|
|
299
|
+
isPlainObject(cache.utilization)
|
|
300
|
+
? cache.utilization
|
|
301
|
+
: undefined
|
|
302
|
+
const extra = isPlainObject(usage?.extra_usage) ? usage.extra_usage : undefined
|
|
303
|
+
const window = (name) => (isPlainObject(usage?.[name]) ? usage[name] : {})
|
|
304
|
+
|
|
305
|
+
const enabled = bool(extra?.is_enabled) ?? bool(account.hasExtraUsageEnabled)
|
|
306
|
+
|
|
307
|
+
const attributes = [
|
|
308
|
+
...typed(stringAttr, [
|
|
309
|
+
[ATTR_SUBSCRIPTION_PROVIDER, VENDOR_ANTHROPIC],
|
|
310
|
+
[ATTR_ORGANIZATION_ID, trimmedOrUndefined(account.organizationUuid)],
|
|
311
|
+
[ATTR_SUBSCRIPTION_ORGANIZATION_TYPE, rawString(account.organizationType)],
|
|
312
|
+
[ATTR_SUBSCRIPTION_SEAT_TIER, rawString(account.seatTier)],
|
|
313
|
+
[ATTR_SUBSCRIPTION_RATE_LIMIT_TIER, rawString(account.userRateLimitTier)],
|
|
314
|
+
[ATTR_SUBSCRIPTION_BILLING_TYPE, rawString(account.billingType)],
|
|
315
|
+
[ATTR_SUBSCRIPTION_ORGANIZATION_ROLE, rawString(account.organizationRole)],
|
|
316
|
+
[ATTR_SUBSCRIPTION_WORKSPACE_ROLE, rawString(account.workspaceRole)],
|
|
317
|
+
[ATTR_SUBSCRIPTION_CREATED_AT, rawString(account.subscriptionCreatedAt)],
|
|
318
|
+
[ATTR_SUBSCRIPTION_TRIAL_ENDS_AT, rawString(account.claudeCodeTrialEndsAt)],
|
|
319
|
+
]),
|
|
320
|
+
...typed(intAttr, [
|
|
321
|
+
[ATTR_SUBSCRIPTION_TRIAL_DURATION_DAYS, count(account.claudeCodeTrialDurationDays)],
|
|
322
|
+
]),
|
|
323
|
+
...typed(stringAttr, [
|
|
324
|
+
[ATTR_SUBSCRIPTION_FIRST_TOKEN_DATE, rawString(doc.claudeCodeFirstTokenDate)],
|
|
325
|
+
[ATTR_SUBSCRIPTION_PROFILE_OBSERVED_AT, isoFromMs(account.profileFetchedAt)],
|
|
326
|
+
]),
|
|
327
|
+
...typed(boolAttr, [[ATTR_EXTRA_USAGE_ENABLED, enabled]]),
|
|
328
|
+
]
|
|
329
|
+
if (usage === undefined) return { accountUuid, email, attributes }
|
|
330
|
+
|
|
331
|
+
attributes.push(
|
|
332
|
+
...typed(doubleAttr, [
|
|
333
|
+
[ATTR_USAGE_FIVE_HOUR_UTILIZATION, finite(window('five_hour').utilization)],
|
|
334
|
+
]),
|
|
335
|
+
...typed(stringAttr, [
|
|
336
|
+
[ATTR_USAGE_FIVE_HOUR_RESETS_AT, rawString(window('five_hour').resets_at)],
|
|
337
|
+
]),
|
|
338
|
+
...typed(doubleAttr, [
|
|
339
|
+
[ATTR_USAGE_SEVEN_DAY_UTILIZATION, finite(window('seven_day').utilization)],
|
|
340
|
+
]),
|
|
341
|
+
...typed(stringAttr, [
|
|
342
|
+
[ATTR_USAGE_SEVEN_DAY_RESETS_AT, rawString(window('seven_day').resets_at)],
|
|
343
|
+
]),
|
|
344
|
+
...limitAttributes(usage.limits),
|
|
345
|
+
...typed(intAttr, [
|
|
346
|
+
[ATTR_EXTRA_USAGE_USED_MINOR, count(extra?.used_credits)],
|
|
347
|
+
[ATTR_EXTRA_USAGE_LIMIT_MINOR, count(extra?.monthly_limit)],
|
|
348
|
+
]),
|
|
349
|
+
...typed(stringAttr, [[ATTR_EXTRA_USAGE_CURRENCY, rawString(extra?.currency)]]),
|
|
350
|
+
...typed(intAttr, [[ATTR_EXTRA_USAGE_EXPONENT, count(extra?.decimal_places)]]),
|
|
351
|
+
...typed(boolAttr, [[ATTR_EXTRA_USAGE_SPEND_LIMIT_REACHED, bool(extra?.spend_limit_reached)]]),
|
|
352
|
+
...typed(stringAttr, [[ATTR_EXTRA_USAGE_DISABLED_REASON, rawString(extra?.disabled_reason)]]),
|
|
353
|
+
...typed(boolAttr, [[ATTR_EXTRA_USAGE_USER_DISABLED, bool(extra?.user_disabled)]]),
|
|
354
|
+
...typed(stringAttr, [
|
|
355
|
+
[ATTR_EXTRA_USAGE_CACHED_DISABLED_REASON, rawString(doc.cachedExtraUsageDisabledReason)],
|
|
356
|
+
[ATTR_SUBSCRIPTION_OBSERVED_AT, isoFromMs(cache.fetchedAtMs)],
|
|
357
|
+
]),
|
|
358
|
+
)
|
|
359
|
+
return { accountUuid, email, attributes }
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** The snapshot in `.claude.json`'s text, or `undefined` for unparseable JSON
|
|
363
|
+
* or a record § `snapshotFromRecord` rejects. */
|
|
364
|
+
export const snapshotFromText = (text) => {
|
|
365
|
+
let doc
|
|
366
|
+
try {
|
|
367
|
+
doc = JSON.parse(text)
|
|
368
|
+
} catch {
|
|
369
|
+
return undefined
|
|
370
|
+
}
|
|
371
|
+
return snapshotFromRecord(doc)
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** An opaque id from the hook input (Claude Code's session and prompt ids are
|
|
375
|
+
* UUIDs): letters, digits and `_ . : -`, at most 256 characters, else
|
|
376
|
+
* undefined. Those keys are ids-only, so anything else is dropped. */
|
|
377
|
+
const OPAQUE_ID_RE = /^[A-Za-z0-9_.:-]{1,256}$/
|
|
378
|
+
export const opaqueId = (v) => (typeof v === 'string' && OPAQUE_ID_RE.test(v) ? v : undefined)
|
|
379
|
+
|
|
380
|
+
/** A hook event name — a short `[A-Za-z_]` token — else undefined. */
|
|
381
|
+
const TOKEN_RE = /^[A-Za-z_]{1,64}$/
|
|
382
|
+
const token = (v) => (typeof v === 'string' && TOKEN_RE.test(v) ? v : undefined)
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* What this invocation adds about where it ran, from the hook input and env:
|
|
386
|
+
* `{ attributes, sessionId, caller }`.
|
|
387
|
+
*
|
|
388
|
+
* - `trigger`: the input's `hook_event_name` (`UserPromptSubmit`).
|
|
389
|
+
* - `prompt.id`: the input's `prompt_id`, present on UserPromptSubmit.
|
|
390
|
+
* - `sessionId`: the input's `session_id`, stamped as `session.id`.
|
|
391
|
+
* - `caller`: `{ traceId, spanId }` from `TRACEPARENT` (W3C, version `00`,
|
|
392
|
+
* § `parseTraceparent`), stamped as `mainwave.caller.trace_id` /
|
|
393
|
+
* `span_id`. Referenced, not joined: the span keeps its own trace, as every
|
|
394
|
+
* marker does, because a marker row's run is keyed on its trace id.
|
|
395
|
+
*/
|
|
396
|
+
export const invocationContext = (payload, env = process.env) => {
|
|
397
|
+
const trigger = token(payload?.hook_event_name)
|
|
398
|
+
const attributes = typed(stringAttr, [
|
|
399
|
+
[ATTR_SUBSCRIPTION_TRIGGER, trigger],
|
|
400
|
+
[ATTR_PROMPT_ID, opaqueId(payload?.prompt_id)],
|
|
401
|
+
])
|
|
402
|
+
return {
|
|
403
|
+
attributes,
|
|
404
|
+
sessionId: opaqueId(payload?.session_id),
|
|
405
|
+
caller: parseTraceparent(env.TRACEPARENT),
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** The OTLP/JSON payload for one snapshot span. */
|
|
410
|
+
export const buildSnapshotPayload = ({
|
|
411
|
+
snapshot,
|
|
412
|
+
context = { attributes: [] },
|
|
413
|
+
resourceAttrs,
|
|
414
|
+
hostSource,
|
|
415
|
+
nowNs,
|
|
416
|
+
}) =>
|
|
417
|
+
buildMarkerPayload({
|
|
418
|
+
spanName: SUBSCRIPTION_SNAPSHOT,
|
|
419
|
+
// The OTLP scope name predates the feature's file name; readers don't key
|
|
420
|
+
// on it, and it stays as it was.
|
|
421
|
+
scopeName: 'mainwave.claude-plan-snapshot',
|
|
422
|
+
attributes: {},
|
|
423
|
+
typedAttributes: [...context.attributes, ...snapshot.attributes],
|
|
424
|
+
sessionId: context.sessionId,
|
|
425
|
+
userEmail: snapshot.email,
|
|
426
|
+
userAccountUuid: snapshot.accountUuid,
|
|
427
|
+
resourceAttrs,
|
|
428
|
+
source: SNAPSHOT_SOURCE,
|
|
429
|
+
service: SNAPSHOT_SERVICE,
|
|
430
|
+
hostSource,
|
|
431
|
+
callContext: { caller: context.caller },
|
|
432
|
+
nowNs,
|
|
433
|
+
})
|
|
434
|
+
|
|
435
|
+
/** `--send-timeout-ms <n>` (tests pass a short one), clamped to
|
|
436
|
+
* 1..§ `SEND_TIMEOUT_MS`; else § `SEND_TIMEOUT_MS`. */
|
|
437
|
+
export const sendTimeoutMs = (argv) => {
|
|
438
|
+
const n = Number(hookFlag(argv, '--send-timeout-ms'))
|
|
439
|
+
return Number.isSafeInteger(n) && n >= 1 ? Math.min(n, SEND_TIMEOUT_MS) : SEND_TIMEOUT_MS
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** POST the span under § `sendTimeoutMs`, stamping the success sidecar on a
|
|
443
|
+
* 2xx. A watchdog exits the process § `EXIT_GRACE_MS` after the timeout,
|
|
444
|
+
* should anything keep it alive past the abort. Never throws. `emit` is the
|
|
445
|
+
* dispatcher's allowlisted post. */
|
|
446
|
+
export const send = async (
|
|
447
|
+
{ endpoint, bearer, body },
|
|
448
|
+
argv = process.argv,
|
|
449
|
+
{ log = snapshotLog(argv), emit = emitMarker } = {},
|
|
450
|
+
) => {
|
|
451
|
+
const timeoutMs = sendTimeoutMs(argv)
|
|
452
|
+
setTimeout(() => process.exit(0), timeoutMs + EXIT_GRACE_MS).unref()
|
|
453
|
+
const status = await emit({
|
|
454
|
+
endpoint,
|
|
455
|
+
bearer,
|
|
456
|
+
body,
|
|
457
|
+
label: 'plan snapshot',
|
|
458
|
+
log,
|
|
459
|
+
timeoutMs,
|
|
460
|
+
logOk: false,
|
|
461
|
+
})
|
|
462
|
+
stampSuccess(status, argv)
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* The feature: one snapshot span for this prompt, or nothing (logged) when
|
|
467
|
+
* the session isn't signed in with a Claude account, no collector is
|
|
468
|
+
* configured, or the account record has no usable account. `ctx.argv` carries
|
|
469
|
+
* the hook command's flags and `--tool <host>`; `ctx.emit` posts.
|
|
470
|
+
*/
|
|
471
|
+
export const handle = async (payload, { argv = process.argv, emit = emitMarker } = {}) => {
|
|
472
|
+
if (!isPlainObject(payload)) return
|
|
473
|
+
const tool = markerTool(argv)
|
|
474
|
+
// Claude Code's account record only; another host has none.
|
|
475
|
+
if (tool !== 'claude-code') return
|
|
476
|
+
const log = snapshotLog(argv)
|
|
477
|
+
|
|
478
|
+
const projectDir = markerProjectDir(payload)
|
|
479
|
+
const managedDir = markerManagedDir(argv)
|
|
480
|
+
const env = markerSessionEnv(tool, payload)
|
|
481
|
+
// The sign-in gate and the OTLP lookup read the same settings files; read
|
|
482
|
+
// each once.
|
|
483
|
+
const readers = onceReaders()
|
|
484
|
+
// Only a session signed in with a Claude account: under an API key or a
|
|
485
|
+
// cloud provider the cached account isn't the one this session runs as.
|
|
486
|
+
const accountPath = markerOauthAccountPath(tool, {
|
|
487
|
+
cwd: projectDir,
|
|
488
|
+
env,
|
|
489
|
+
managedDir,
|
|
490
|
+
...readers,
|
|
491
|
+
})
|
|
492
|
+
if (accountPath === undefined) {
|
|
493
|
+
log('skip: session is not signed in with a Claude account')
|
|
494
|
+
return
|
|
495
|
+
}
|
|
496
|
+
const { endpoint, bearer, resourceAttrs } = loadOtelConfig(
|
|
497
|
+
projectDir,
|
|
498
|
+
env,
|
|
499
|
+
tool,
|
|
500
|
+
managedDir,
|
|
501
|
+
readers,
|
|
502
|
+
)
|
|
503
|
+
if (!endpoint || !bearer) {
|
|
504
|
+
log('skip: collector endpoint/bearer not found in settings or env')
|
|
505
|
+
return
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
let text
|
|
509
|
+
try {
|
|
510
|
+
text = readFileSync(accountPath, 'utf8')
|
|
511
|
+
} catch {
|
|
512
|
+
log('skip: no Claude account record')
|
|
513
|
+
return
|
|
514
|
+
}
|
|
515
|
+
const snapshot = snapshotFromText(text)
|
|
516
|
+
if (snapshot === undefined) {
|
|
517
|
+
log('skip: Claude account record has no usable account')
|
|
518
|
+
return
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
const body = buildSnapshotPayload({
|
|
522
|
+
snapshot,
|
|
523
|
+
context: invocationContext(payload),
|
|
524
|
+
resourceAttrs,
|
|
525
|
+
hostSource: markerHostSource(tool),
|
|
526
|
+
nowNs: BigInt(Date.now()) * 1_000_000n,
|
|
527
|
+
})
|
|
528
|
+
await send({ endpoint, bearer, body }, argv, { log, emit })
|
|
529
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The stop-failure feature of the Mainwave hook dispatcher (mainwave-hook.mjs),
|
|
3
|
+
// which runs it on Claude Code's StopFailure event: Claude Code fires that
|
|
4
|
+
// instead of Stop when a turn ends on an API error — a rate limit, a billing
|
|
5
|
+
// error, an overloaded API, a sign-in that stopped working.
|
|
6
|
+
//
|
|
7
|
+
// It sends one span (`mainwave.claude_code.stop_failure`, source
|
|
8
|
+
// `hook.anthropic`) carrying the error TYPE only — Claude Code's own enum
|
|
9
|
+
// (`rate_limit`, `billing_error`, `overloaded`, ...) — with the session id, the
|
|
10
|
+
// prompt id, the Claude account identity and the turn's trace context, so it
|
|
11
|
+
// joins the plan snapshot on the same keys. Never the error details, the
|
|
12
|
+
// rendered error message, or anything else from the hook input.
|
|
13
|
+
//
|
|
14
|
+
// Fails open: anything unexpected sends nothing.
|
|
15
|
+
|
|
16
|
+
import { emitMarker, sendClaudeEvent, stringAttr } from './marker-core.mjs'
|
|
17
|
+
import { ATTR_PROMPT_ID, ATTR_STOP_FAILURE_ERROR, CLAUDE_CODE_STOP_FAILURE } from './vocabulary.mjs'
|
|
18
|
+
|
|
19
|
+
/** An error type as Claude Code names them: a lower-case `[a-z_]` token, at
|
|
20
|
+
* most 64 characters. An open set — a new type is sent as is — but never
|
|
21
|
+
* free text. */
|
|
22
|
+
const ERROR_TYPE_RE = /^[a-z_]{1,64}$/
|
|
23
|
+
export const errorType = (v) => (typeof v === 'string' && ERROR_TYPE_RE.test(v) ? v : undefined)
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The feature: one span naming the error type, or nothing when the input
|
|
27
|
+
* names none. `ctx.argv` carries the hook command's flags and
|
|
28
|
+
* `--tool <host>`; `ctx.emit` posts.
|
|
29
|
+
*/
|
|
30
|
+
export const handle = async (payload, { argv = process.argv, emit = emitMarker } = {}) => {
|
|
31
|
+
const error = errorType(payload?.error)
|
|
32
|
+
if (error === undefined) return
|
|
33
|
+
await sendClaudeEvent({
|
|
34
|
+
payload,
|
|
35
|
+
argv,
|
|
36
|
+
emit,
|
|
37
|
+
spanName: CLAUDE_CODE_STOP_FAILURE,
|
|
38
|
+
scopeName: 'mainwave.stop-failure',
|
|
39
|
+
attributes: [stringAttr(ATTR_STOP_FAILURE_ERROR, error)],
|
|
40
|
+
promptIdKey: ATTR_PROMPT_ID,
|
|
41
|
+
label: `stop failure ${error}`,
|
|
42
|
+
})
|
|
43
|
+
}
|
package/hooks/vocabulary.d.mts
CHANGED
|
@@ -31,13 +31,61 @@ export const ATTR_VCS_REPOSITORY_URL_FULL: string
|
|
|
31
31
|
export const ATTR_VCS_CHANGE_ID: string
|
|
32
32
|
export const ATTR_VCS_CHANGE_TITLE: string
|
|
33
33
|
export const ATTR_VCS_PROVIDER_NAME: string
|
|
34
|
+
export const ATTR_VCS_REPOSITORY_ID: string
|
|
34
35
|
export const ATTR_VCS_CHANGE_FILES_CHANGED: string
|
|
35
36
|
export const ATTR_VCS_CHANGE_LINES_ADDED: string
|
|
36
37
|
export const ATTR_VCS_CHANGE_LINES_REMOVED: string
|
|
37
38
|
export const VCS_PROVIDER_GITHUB: string
|
|
39
|
+
export const VCS_PROVIDER_GITLAB: string
|
|
38
40
|
export const VCS_MARKER_KEYS: readonly string[]
|
|
39
41
|
|
|
40
42
|
export const ATTR_CODE_FILE_PATH: string
|
|
41
43
|
export const CODE_KEYS: readonly string[]
|
|
42
44
|
|
|
43
45
|
export const CLI_EVENT_NAMES: readonly string[]
|
|
46
|
+
|
|
47
|
+
export const SUBSCRIPTION_SNAPSHOT: string
|
|
48
|
+
export const VENDOR_ANTHROPIC: string
|
|
49
|
+
export const ATTR_SUBSCRIPTION_TRIGGER: string
|
|
50
|
+
export const ATTR_PROMPT_ID: string
|
|
51
|
+
export const ATTR_SUBSCRIPTION_PROVIDER: string
|
|
52
|
+
export const ATTR_SUBSCRIPTION_ORGANIZATION_TYPE: string
|
|
53
|
+
export const ATTR_SUBSCRIPTION_SEAT_TIER: string
|
|
54
|
+
export const ATTR_SUBSCRIPTION_RATE_LIMIT_TIER: string
|
|
55
|
+
export const ATTR_SUBSCRIPTION_BILLING_TYPE: string
|
|
56
|
+
export const ATTR_SUBSCRIPTION_ORGANIZATION_ROLE: string
|
|
57
|
+
export const ATTR_SUBSCRIPTION_WORKSPACE_ROLE: string
|
|
58
|
+
export const ATTR_SUBSCRIPTION_CREATED_AT: string
|
|
59
|
+
export const ATTR_SUBSCRIPTION_TRIAL_ENDS_AT: string
|
|
60
|
+
export const ATTR_SUBSCRIPTION_TRIAL_DURATION_DAYS: string
|
|
61
|
+
export const ATTR_SUBSCRIPTION_PROFILE_OBSERVED_AT: string
|
|
62
|
+
export const ATTR_SUBSCRIPTION_FIRST_TOKEN_DATE: string
|
|
63
|
+
export const ATTR_USAGE_FIVE_HOUR_UTILIZATION: string
|
|
64
|
+
export const ATTR_USAGE_FIVE_HOUR_RESETS_AT: string
|
|
65
|
+
export const ATTR_USAGE_SEVEN_DAY_UTILIZATION: string
|
|
66
|
+
export const ATTR_USAGE_SEVEN_DAY_RESETS_AT: string
|
|
67
|
+
export const ATTR_EXTRA_USAGE_ENABLED: string
|
|
68
|
+
export const ATTR_EXTRA_USAGE_USED_MINOR: string
|
|
69
|
+
export const ATTR_EXTRA_USAGE_LIMIT_MINOR: string
|
|
70
|
+
export const ATTR_EXTRA_USAGE_CURRENCY: string
|
|
71
|
+
export const ATTR_EXTRA_USAGE_EXPONENT: string
|
|
72
|
+
export const ATTR_EXTRA_USAGE_SPEND_LIMIT_REACHED: string
|
|
73
|
+
export const ATTR_EXTRA_USAGE_DISABLED_REASON: string
|
|
74
|
+
export const ATTR_EXTRA_USAGE_USER_DISABLED: string
|
|
75
|
+
export const ATTR_EXTRA_USAGE_CACHED_DISABLED_REASON: string
|
|
76
|
+
export const ATTR_SUBSCRIPTION_OBSERVED_AT: string
|
|
77
|
+
export const SUBSCRIPTION_LIMIT_PREFIX: string
|
|
78
|
+
export const ATTR_ORGANIZATION_ID: string
|
|
79
|
+
export const SUBSCRIPTION_LIMIT_FIELDS: readonly string[]
|
|
80
|
+
export const SUBSCRIPTION_LIMIT_SCOPED_FIELDS: readonly string[]
|
|
81
|
+
export const subscriptionLimitKey: (kind: string, field: string, scope?: string) => string
|
|
82
|
+
export const SUBSCRIPTION_SNAPSHOT_KEYS: readonly string[]
|
|
83
|
+
|
|
84
|
+
export const CLAUDE_CODE_STOP_FAILURE: string
|
|
85
|
+
export const ATTR_STOP_FAILURE_ERROR: string
|
|
86
|
+
export const STOP_FAILURE_KEYS: readonly string[]
|
|
87
|
+
export const COMMON_SPAN_KEYS: readonly string[]
|
|
88
|
+
export const FEATURE_EMITS: Readonly<
|
|
89
|
+
Record<string, { spans: readonly string[]; keys: readonly string[]; prefixes: readonly string[] }>
|
|
90
|
+
>
|
|
91
|
+
export const ANTHROPIC_HOOK_SPANS: readonly string[]
|