@mainwave/cli 0.7.1 → 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 +141 -42
- package/dist/adapters/claude-code.js +33 -7
- package/dist/adapters/claude-desktop.js +0 -1
- package/dist/adapters/codex-cli.js +1 -2
- package/dist/adapters/copilot-chat.js +0 -1
- package/dist/adapters/copilot-cli.js +0 -1
- package/dist/adapters/cursor-enterprise.js +0 -1
- package/dist/adapters/cursor.js +15 -4
- package/dist/adapters/index.js +0 -1
- package/dist/adapters/types.js +0 -1
- package/dist/api/index.js +0 -1
- package/dist/api/types.gen.js +0 -1
- package/dist/cli.js +0 -1
- package/dist/core/apply.js +151 -42
- package/dist/core/auth-commands.js +0 -1
- package/dist/core/behaviour-hooks.js +0 -1
- package/dist/core/browser.js +0 -1
- package/dist/core/codecs/cursor-hooks-json.js +0 -1
- package/dist/core/codecs/env-file.js +0 -1
- package/dist/core/codecs/json-env.js +0 -1
- package/dist/core/codecs/json-flat.js +0 -1
- package/dist/core/codecs/json-managed.js +0 -1
- package/dist/core/codecs/toml-otel.js +0 -1
- package/dist/core/codecs/types.js +0 -1
- package/dist/core/detect.js +0 -1
- package/dist/core/device-login.js +0 -1
- package/dist/core/doctor.js +45 -9
- package/dist/core/edit.js +9 -5
- package/dist/core/effective-settings.js +71 -20
- package/dist/core/entry-script.js +90 -0
- package/dist/core/env-command.js +0 -1
- package/dist/core/errors.js +0 -1
- package/dist/core/flags.js +0 -1
- package/dist/core/format.js +0 -1
- package/dist/core/git-bash.js +40 -0
- package/dist/core/git.js +0 -1
- package/dist/core/headers.js +0 -1
- package/dist/core/install-hooks.js +127 -44
- package/dist/core/interview.js +53 -4
- package/dist/core/keys.js +0 -1
- package/dist/core/layer-policy.js +2 -1
- package/dist/core/markers.js +826 -133
- package/dist/core/pinned-use-case.js +0 -1
- package/dist/core/platform.js +0 -1
- package/dist/core/post-setup.js +0 -1
- package/dist/core/prompts.js +0 -1
- package/dist/core/settings.js +32 -8
- package/dist/core/skills.js +5 -2
- package/dist/core/status.js +7 -5
- package/dist/core/store.js +0 -1
- package/dist/core/tty.js +0 -1
- package/dist/core/ucid.js +0 -1
- package/dist/core/ui.js +0 -1
- package/dist/core/use-case.js +0 -1
- package/dist/core/validate.js +0 -1
- package/dist/core/verify.js +0 -1
- package/dist/core/version.js +0 -1
- package/dist/core/wizard.js +49 -8
- package/dist/main.js +16 -10
- package/hooks/cursor-otlp.mjs +13 -15
- package/hooks/github-pr-marker.mjs +55 -31
- package/hooks/glab-mr-marker.mjs +795 -0
- package/hooks/jira-ticket-marker.mjs +35 -23
- package/hooks/linear-ticket-marker.mjs +35 -21
- package/hooks/mainwave-hook-node.mjs +42 -0
- package/hooks/mainwave-hook.mjs +301 -0
- package/hooks/managed-entry.mjs +42 -0
- package/hooks/marker-core.mjs +389 -62
- 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 +6 -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-instrument-node/SKILL.md +420 -0
- package/skills/mainwave-instrument-node/reference/api.md +96 -0
- package/skills/mainwave-instrument-node/reference/frameworks.md +82 -0
- package/skills/mainwave-instrument-node/reference/troubleshooting.md +152 -0
- package/skills/mainwave-setup/SKILL.md +47 -12
- package/dist/adapters/claude-code.js.map +0 -1
- package/dist/adapters/claude-desktop.js.map +0 -1
- package/dist/adapters/codex-cli.js.map +0 -1
- package/dist/adapters/copilot-chat.js.map +0 -1
- package/dist/adapters/copilot-cli.js.map +0 -1
- package/dist/adapters/cursor-enterprise.js.map +0 -1
- package/dist/adapters/cursor.js.map +0 -1
- package/dist/adapters/index.js.map +0 -1
- package/dist/adapters/types.js.map +0 -1
- package/dist/api/index.js.map +0 -1
- package/dist/api/types.gen.js.map +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/core/apply.js.map +0 -1
- package/dist/core/auth-commands.js.map +0 -1
- package/dist/core/behaviour-hooks.js.map +0 -1
- package/dist/core/browser.js.map +0 -1
- package/dist/core/codecs/cursor-hooks-json.js.map +0 -1
- package/dist/core/codecs/env-file.js.map +0 -1
- package/dist/core/codecs/json-env.js.map +0 -1
- package/dist/core/codecs/json-flat.js.map +0 -1
- package/dist/core/codecs/json-managed.js.map +0 -1
- package/dist/core/codecs/toml-otel.js.map +0 -1
- package/dist/core/codecs/types.js.map +0 -1
- package/dist/core/detect.js.map +0 -1
- package/dist/core/device-login.js.map +0 -1
- package/dist/core/doctor.js.map +0 -1
- package/dist/core/edit.js.map +0 -1
- package/dist/core/effective-settings.js.map +0 -1
- package/dist/core/env-command.js.map +0 -1
- package/dist/core/errors.js.map +0 -1
- package/dist/core/flags.js.map +0 -1
- package/dist/core/format.js.map +0 -1
- package/dist/core/git.js.map +0 -1
- package/dist/core/headers.js.map +0 -1
- package/dist/core/install-hooks.js.map +0 -1
- package/dist/core/interview.js.map +0 -1
- package/dist/core/keys.js.map +0 -1
- package/dist/core/layer-policy.js.map +0 -1
- package/dist/core/markers.js.map +0 -1
- package/dist/core/pinned-use-case.js.map +0 -1
- package/dist/core/platform.js.map +0 -1
- package/dist/core/post-setup.js.map +0 -1
- package/dist/core/prompts.js.map +0 -1
- package/dist/core/settings.js.map +0 -1
- package/dist/core/skills.js.map +0 -1
- package/dist/core/status.js.map +0 -1
- package/dist/core/store.js.map +0 -1
- package/dist/core/tty.js.map +0 -1
- package/dist/core/ucid.js.map +0 -1
- package/dist/core/ui.js.map +0 -1
- package/dist/core/use-case.js.map +0 -1
- package/dist/core/validate.js.map +0 -1
- package/dist/core/verify.js.map +0 -1
- package/dist/core/version.js.map +0 -1
- package/dist/core/wizard.js.map +0 -1
- package/dist/main.js.map +0 -1
package/hooks/matchers.json
CHANGED
|
@@ -1,17 +1,93 @@
|
|
|
1
1
|
[
|
|
2
2
|
{
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"event": "UserPromptSubmit",
|
|
4
|
+
"features": ["plan-snapshot"],
|
|
5
|
+
"optOut": "markers",
|
|
6
|
+
"hosts": ["claude-code"],
|
|
7
|
+
"dataClasses": [
|
|
8
|
+
"Claude account email, account id and organization id",
|
|
9
|
+
"plan tier names and roles",
|
|
10
|
+
"subscription start, trial end and length, first-use date",
|
|
11
|
+
"usage against rate limits",
|
|
12
|
+
"extra-usage on/off, amount, limit, currency and why it is off",
|
|
13
|
+
"session id, prompt id, turn trace and span ids"
|
|
14
|
+
],
|
|
15
|
+
"why": "UserPromptSubmit fires on every submitted prompt, including one whose turn is later interrupted (Stop fires only on completed turns). It also fires on turns no person started (scheduled tasks and loops, background-subagent reports, cross-session messages), and Claude Code doesn't yet say which, so a snapshot marks when one was received, not developer activity. SessionEnd is deliberately not used: an exit-time snapshot would move the developer's last-seen to quit time with no work then, and a figure refreshed by /usage just before quitting reaches Mainwave at the next prompt, because Claude Code's cache persists on disk. It takes no matcher. Claude Code only: the feature reads Claude Code's own account record (.claude.json), which no other host has. The group is async, so the prompt never waits on the collector; the feature bounds its own send."
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
"event": "PostToolUse",
|
|
19
|
+
"route": "gh",
|
|
20
|
+
"matcher": "Bash",
|
|
21
|
+
"if": "Bash(gh *)",
|
|
22
|
+
"features": ["github-pr-marker"],
|
|
23
|
+
"optOut": "markers",
|
|
24
|
+
"hosts": ["claude-code"],
|
|
25
|
+
"dataClasses": [
|
|
26
|
+
"pull request url, number and title",
|
|
27
|
+
"changed-file, added-line and removed-line counts"
|
|
28
|
+
],
|
|
29
|
+
"why": "Built-in tool, exact name, narrowed by the handler's `if` to Bash commands that start with `gh` (compound commands and VAR= prefixes included), so Claude Code starts nothing for any other command. The feature still returns immediately unless the command was 'gh pr create'. A pattern naming more than the command (`Bash(gh pr create *)`) is deliberately not used: Claude Code runs such a hook on every command it can't parse, which is any command with $(), backticks or $VAR. A wrapper or a path (`env gh`, `/usr/local/bin/gh`) doesn't match `gh *`; that miss is accepted."
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
"event": "PostToolUse",
|
|
33
|
+
"route": "glab",
|
|
34
|
+
"matcher": "Bash",
|
|
35
|
+
"if": "Bash(glab *)",
|
|
36
|
+
"features": ["glab-mr-marker"],
|
|
37
|
+
"optOut": "markers",
|
|
38
|
+
"hosts": ["claude-code"],
|
|
39
|
+
"dataClasses": [
|
|
40
|
+
"merge request url, iid and title",
|
|
41
|
+
"instance-namespaced project id",
|
|
42
|
+
"changed-file count"
|
|
43
|
+
],
|
|
44
|
+
"why": "Built-in tool, exact name, narrowed by the handler's `if` to Bash commands that start with `glab`. The feature still returns immediately unless the command was 'glab mr create' or a POST of 'glab api' to a project's merge_requests endpoint. The feature's own detector also accepts env, sudo and exec wrappers and a path-qualified glab, which `glab *` doesn't match; that miss is accepted rather than widening the `if`."
|
|
6
45
|
},
|
|
7
46
|
{
|
|
8
|
-
"
|
|
47
|
+
"event": "PostToolUse",
|
|
48
|
+
"route": "bash",
|
|
9
49
|
"matcher": "Bash",
|
|
10
|
-
"
|
|
50
|
+
"features": ["github-pr-marker", "glab-mr-marker"],
|
|
51
|
+
"optOut": "markers",
|
|
52
|
+
"hosts": ["codex"],
|
|
53
|
+
"dataClasses": [
|
|
54
|
+
"pull request url, number and title",
|
|
55
|
+
"changed-file, added-line and removed-line counts",
|
|
56
|
+
"merge request url, iid and title",
|
|
57
|
+
"instance-namespaced project id",
|
|
58
|
+
"changed-file count"
|
|
59
|
+
],
|
|
60
|
+
"why": "Codex has no `if` filter, so one Bash group serves both pull-request markers: the shell entry reads the hook input and starts Node only when it contains `pr`…`create`, `mr`…`create`, `mr`…`new` or `merge_requests` — a superset of what the two features' own detectors accept."
|
|
11
61
|
},
|
|
12
62
|
{
|
|
13
|
-
"
|
|
63
|
+
"event": "PostToolUse",
|
|
64
|
+
"route": "linear",
|
|
65
|
+
"matcher": "^mcp__.*[Ll]inear.*_(save|create|update)_issue$",
|
|
66
|
+
"features": ["linear-ticket-marker"],
|
|
67
|
+
"optOut": "markers",
|
|
68
|
+
"hosts": ["claude-code", "codex"],
|
|
69
|
+
"dataClasses": ["issue key, url, team id and create/update"],
|
|
70
|
+
"why": "The server PREFIX and the separator both vary. Prefix: this workspace connects Linear as mcp__linear-server__save_issue, the older integration as mcp__linear__save_issue, and Codex exposes it as mcp__codex_apps__linear_save_issue — a SINGLE underscore before save_issue. So the separator is `.*_` (one-or-more via the greedy `.*`, which absorbs the extra underscore in the __ forms) rather than a literal `__`. create_issue / update_issue are covered defensively in case an integration splits the save; detectOp reads the op off the tool name and falls back to the input's id. Anchored (`$`) because linear-server really does expose create_issue_label — the trailing `_issue$` excludes it."
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
"event": "PostToolUse",
|
|
74
|
+
"route": "jira",
|
|
14
75
|
"matcher": "^mcp__.*[Aa]tlassian.*__(createJiraIssue|editJiraIssue)$",
|
|
76
|
+
"features": ["jira-ticket-marker"],
|
|
77
|
+
"optOut": "markers",
|
|
78
|
+
"hosts": ["claude-code", "codex"],
|
|
79
|
+
"dataClasses": ["issue key, url, site id and create/update"],
|
|
15
80
|
"why": "The Atlassian MCP keeps its tool names stable but the server prefix varies (mcp__atlassian__, mcp__claude_ai_Atlassian_Rovo__). detectOp already matches on the tool-name suffix, so widening the prefix is all that is needed. Anchored to exclude the other *JiraIssue tools (transition, addComment, ...)."
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
"event": "StopFailure",
|
|
84
|
+
"features": ["stop-failure"],
|
|
85
|
+
"optOut": "markers",
|
|
86
|
+
"hosts": ["claude-code"],
|
|
87
|
+
"dataClasses": [
|
|
88
|
+
"the error type when a turn ends on an API error",
|
|
89
|
+
"session id, prompt id, Claude account id and email"
|
|
90
|
+
],
|
|
91
|
+
"why": "StopFailure fires instead of Stop when a turn ends on an API error. Rate-limit and billing errors are the developer's own limit hits, joined to the plan snapshot. No matcher: every error type is rare enough, and the feature sends only the type enum, never the error details or the rendered message. Notification is deliberately not used: Claude Code's usage-limit auto-resume notices (`quota_auto_resume_*`) can fire while the developer is idle, which would move the use case's last-seen with no work then, the same reason SessionEnd is not used."
|
|
16
92
|
}
|
|
17
93
|
]
|
|
@@ -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
|
+
}
|