@useanvil/claude-code 0.0.0-stage → 0.8.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/CHANGELOG.md +1992 -0
- package/LICENSE +111 -0
- package/README.md +214 -2
- package/TELEMETRY.md +60 -0
- package/dist/claude-conditions.js +12 -0
- package/dist/claude-helpers.js +12 -0
- package/dist/claude-hook-core.js +87 -0
- package/dist/claude-hook.js +38 -0
- package/dist/claude-meter.js +35 -0
- package/dist/claude-powershell.cjs +37 -0
- package/dist/claude-sync.js +28 -0
- package/dist/cli/claude-main.js +23561 -0
- package/dist/cli.js +18 -0
- package/docs/coding-agents/YOUR-RULES.md +701 -0
- package/package.json +34 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
Business Source License 1.1
|
|
2
|
+
|
|
3
|
+
License text copyright (c) 2020 MariaDB Corporation Ab, All Rights Reserved.
|
|
4
|
+
"Business Source License" is a trademark of MariaDB Corporation Ab.
|
|
5
|
+
|
|
6
|
+
-----------------------------------------------------------------------------
|
|
7
|
+
|
|
8
|
+
Parameters
|
|
9
|
+
|
|
10
|
+
Licensor: Anvil (henry@anvilcontrol.ai)
|
|
11
|
+
|
|
12
|
+
Licensed Work: Anvil — @useanvil/sdk, the `anvil` CLI, and the
|
|
13
|
+
accompanying control-plane and ghost-intake sources
|
|
14
|
+
distributed in this repository and in the published
|
|
15
|
+
npm package.
|
|
16
|
+
The Licensed Work is (c) 2026 Anvil.
|
|
17
|
+
|
|
18
|
+
Additional Use Grant: You may make production use of the Licensed Work for
|
|
19
|
+
your own internal business operations, including
|
|
20
|
+
running the Licensed Work (and any modified version of
|
|
21
|
+
it) on your own infrastructure to guard, observe, and
|
|
22
|
+
audit your own systems' actions, with no limit on the
|
|
23
|
+
number of users, workloads, hosts, or transactions.
|
|
24
|
+
|
|
25
|
+
This grant does not extend to offering the Licensed
|
|
26
|
+
Work to third parties as a hosted, managed, or embedded
|
|
27
|
+
service that provides those third parties with the
|
|
28
|
+
Licensed Work's execution-control, policy-enforcement,
|
|
29
|
+
idempotency, or decision-audit functionality, where that
|
|
30
|
+
service competes with a product or service offered by
|
|
31
|
+
the Licensor.
|
|
32
|
+
|
|
33
|
+
Change Date: 2030-07-29
|
|
34
|
+
|
|
35
|
+
Change License: Mozilla Public License, Version 2.0
|
|
36
|
+
|
|
37
|
+
For information about alternative licensing arrangements for the Licensed Work,
|
|
38
|
+
please contact henry@anvilcontrol.ai.
|
|
39
|
+
|
|
40
|
+
-----------------------------------------------------------------------------
|
|
41
|
+
|
|
42
|
+
Notice
|
|
43
|
+
|
|
44
|
+
Business Source License 1.1
|
|
45
|
+
|
|
46
|
+
Terms
|
|
47
|
+
|
|
48
|
+
The Licensor hereby grants you the right to copy, modify, create derivative
|
|
49
|
+
works, redistribute, and make non-production use of the Licensed Work. The
|
|
50
|
+
Licensor may make an Additional Use Grant, above, permitting limited
|
|
51
|
+
production use.
|
|
52
|
+
|
|
53
|
+
Effective on the Change Date, or the fourth anniversary of the first publicly
|
|
54
|
+
available distribution of a specific version of the Licensed Work under this
|
|
55
|
+
License, whichever comes first, the Licensor hereby grants you rights under
|
|
56
|
+
the terms of the Change License, and the rights granted in the paragraph
|
|
57
|
+
above terminate.
|
|
58
|
+
|
|
59
|
+
If your use of the Licensed Work does not comply with the requirements
|
|
60
|
+
currently in effect as described in this License, you must purchase a
|
|
61
|
+
commercial license from the Licensor, its affiliated entities, or authorized
|
|
62
|
+
resellers, or you must refrain from using the Licensed Work.
|
|
63
|
+
|
|
64
|
+
All copies of the original and modified Licensed Work, and derivative works
|
|
65
|
+
of the Licensed Work, are subject to this License. This License applies
|
|
66
|
+
separately for each version of the Licensed Work and the Change Date may vary
|
|
67
|
+
for each version of the Licensed Work released by Licensor.
|
|
68
|
+
|
|
69
|
+
You must conspicuously display this License on each original or modified copy
|
|
70
|
+
of the Licensed Work. If you receive the Licensed Work in original or
|
|
71
|
+
modified form from a third party, the terms and conditions set forth in this
|
|
72
|
+
License apply to your use of that work.
|
|
73
|
+
|
|
74
|
+
Any use of the Licensed Work in violation of this License will automatically
|
|
75
|
+
terminate your rights under this License for the current and all other
|
|
76
|
+
versions of the Licensed Work.
|
|
77
|
+
|
|
78
|
+
This License does not grant you any right in any trademark or logo of
|
|
79
|
+
Licensor or its affiliates (provided that you may use a trademark or logo of
|
|
80
|
+
Licensor as expressly required by this License).
|
|
81
|
+
|
|
82
|
+
TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
|
|
83
|
+
AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
|
|
84
|
+
EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
|
|
85
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
|
|
86
|
+
TITLE.
|
|
87
|
+
|
|
88
|
+
MariaDB hereby grants you permission to use this License's text to license
|
|
89
|
+
your works, and to refer to it using the trademark "Business Source License",
|
|
90
|
+
as long as you comply with the Covenants of Licensor below.
|
|
91
|
+
|
|
92
|
+
Covenants of Licensor
|
|
93
|
+
|
|
94
|
+
In consideration of the right to use this License's text and the "Business
|
|
95
|
+
Source License" name and trademark, Licensor covenants to MariaDB, and to all
|
|
96
|
+
other recipients of the licensed work to be provided by Licensor:
|
|
97
|
+
|
|
98
|
+
1. To specify as the Change License the GPL Version 2.0 or any later version,
|
|
99
|
+
or a license that is compatible with GPL Version 2.0 or a later version,
|
|
100
|
+
where "compatible" means that software provided under the Change License can
|
|
101
|
+
be included in a program with software provided under GPL Version 2.0 or a
|
|
102
|
+
later version. Licensor may specify additional Change Licenses without
|
|
103
|
+
limitation.
|
|
104
|
+
|
|
105
|
+
2. To either: (a) specify an additional grant of rights to use that does not
|
|
106
|
+
impose any additional restriction on the right granted in this License, as
|
|
107
|
+
the Additional Use Grant; or (b) insert the text "None".
|
|
108
|
+
|
|
109
|
+
3. To specify a Change Date.
|
|
110
|
+
|
|
111
|
+
4. Not to modify this License in any other way.
|
package/README.md
CHANGED
|
@@ -1,3 +1,215 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Anvil for Claude Code
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Stop Claude Code before it does something you can't undo.**
|
|
4
|
+
|
|
5
|
+
Anvil checks every action Claude Code takes before it happens: each command it runs, each file it changes, each app it
|
|
6
|
+
touches. What can't be undone is blocked. What's dangerous waits for your OK. Everything else runs, and you see what
|
|
7
|
+
Anvil would have stopped.
|
|
8
|
+
|
|
9
|
+
No setup and no account. It runs on your machine, and it never stores or sends your prompts or Claude's replies.
|
|
10
|
+
|
|
11
|
+
<br>
|
|
12
|
+
|
|
13
|
+
## Get started
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm i -g @useanvil/claude-code && anvil-claude
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
That installs it and opens Home. Choose **Turn it on**, press Enter, then start a new Claude Code session, in the
|
|
20
|
+
terminal or the desktop app: Home starts either one for you. Come back to Home any time with `anvil-claude`.
|
|
21
|
+
|
|
22
|
+
Want to see it first? `anvil-claude try` shows what Anvil does if Claude tries to wipe your home folder, drop your
|
|
23
|
+
database, email your customers or push to main. Nothing runs.
|
|
24
|
+
|
|
25
|
+
<br>
|
|
26
|
+
|
|
27
|
+
## What it does
|
|
28
|
+
|
|
29
|
+
| | |
|
|
30
|
+
|---|---|
|
|
31
|
+
| ✕ **Blocks** | What can't be undone: wiping your home folder or the project, force-pushing main. Always on. |
|
|
32
|
+
| ■ **Holds** | The dangerous, until you say OK: cloud and database destroys, plus anything you choose. |
|
|
33
|
+
| ○ **Watches** | Everything else risky. It runs, and you see what Anvil would have stopped. |
|
|
34
|
+
|
|
35
|
+
<br>
|
|
36
|
+
|
|
37
|
+
## What you'll see
|
|
38
|
+
|
|
39
|
+
Anvil's lines in Claude Code lead with what happened, between two 🔹.
|
|
40
|
+
|
|
41
|
+
```
|
|
42
|
+
🔹 Anvil is on 🔹 blocking unsafe actions automatically · holding cluster, cloud and database destroys for your OK
|
|
43
|
+
› To add your own rules, run in a terminal: anvil-claude rules edit
|
|
44
|
+
🔹 Blocked by Anvil 🔹 force-pushes main · can't be overridden
|
|
45
|
+
🔹 Held by Anvil for your OK 🔹 deletes a real folder
|
|
46
|
+
› To allow it once, run this in a terminal (not in this chat):
|
|
47
|
+
anvil-claude allow k3mpq7rx
|
|
48
|
+
› Then tell Claude to go on.
|
|
49
|
+
🔹 Anvil would've held this for review 🔹 pushes to main (a deploy) · it ran
|
|
50
|
+
› To hold these for your OK, run in a terminal:
|
|
51
|
+
anvil-claude enforce push-main
|
|
52
|
+
🔹 Today's budget is spent 🔹 $50.12 of $50 · resets at midnight
|
|
53
|
+
› To keep going, run this in a terminal (not in this chat):
|
|
54
|
+
anvil-claude allow 7k2m9xqa
|
|
55
|
+
› Then send your message again.
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Every step Anvil asks of you says where it runs: an `anvil-claude` command goes in a terminal (in the desktop app, the
|
|
59
|
+
Terminal panel or any terminal), never in the chat, where Claude can't run it.
|
|
60
|
+
|
|
61
|
+
- **Terminal and desktop app:** both read the same Claude Code settings, so both are checked from the next session on.
|
|
62
|
+
- **Status bar:** in a terminal, Claude Code's bottom line keeps it in view, with what Claude spent today:
|
|
63
|
+
`🔹 Anvil on 🔹 14 checked · 2 stopped · $3.10 today`. On a Claude plan it shows your week instead: `… · 41% of week`.
|
|
64
|
+
If you have a status line of your own, `on` keeps it and adds nothing there.
|
|
65
|
+
- **Your own status line, and a plan budget:** Claude Code sends your plan's limits only to the status line it runs,
|
|
66
|
+
so a budget like `80% of my weekly limit` can't be measured until yours passes the same input to Anvil. `on`,
|
|
67
|
+
`anvil-claude rules add` and `anvil-claude report` print the exact command for your settings, with yours in it:
|
|
68
|
+
`input=$(cat); printf '%s' "$input" | node "$HOME/.anvil/claude/bin/claude-sync.js" --statusline >/dev/null 2>&1;
|
|
69
|
+
printf '%s' "$input" | { your-command; }`. Dollar and token budgets don't need it.
|
|
70
|
+
- **Notifications:** on a Mac, a held action Claude Code can't ask you about (the desktop app, a background run) sends one.
|
|
71
|
+
|
|
72
|
+
<br>
|
|
73
|
+
|
|
74
|
+
## Make it yours
|
|
75
|
+
|
|
76
|
+
**How it starts:** the blocks and a few holds (cloud and database destroys, printed cloud keys) are on from the first
|
|
77
|
+
action. Every other risky action is only watched: it runs, and you see what Anvil would have stopped.
|
|
78
|
+
|
|
79
|
+
**Hold what you care about.** When a watched line keeps showing up, hold that kind: the line gives the command, and
|
|
80
|
+
Home offers the one it saw most as a single Enter. Or hold every rule at once with `anvil-claude enforce all`.
|
|
81
|
+
|
|
82
|
+
**Set a budget.** `anvil-claude rules add "budget: $50 a day"`. Past it, Claude Code stops before its next message or
|
|
83
|
+
action, and `anvil-claude allow <code>`, run in a terminal, lets that task go on (for that task, one more budget's
|
|
84
|
+
worth and an hour at most).
|
|
85
|
+
Also a week or a task, new tokens (`5M new tokens a day`), or a share of your plan (`80% of my weekly limit`). Anvil
|
|
86
|
+
checks it when you send a message, without reading the message. It can run over by about two replies per thread
|
|
87
|
+
(the reply that crosses it, the one in flight, and the one that reads the stop): usually cents, at worst a cold 1M
|
|
88
|
+
context reply, about $15–30.
|
|
89
|
+
|
|
90
|
+
**Every screen says what a limit does now.** `rules add`, `anvil-claude rules`, the rules screen, Home, `on` and
|
|
91
|
+
`report` show each budget, cap and model rule as it stands: one Anvil can't measure or hear here says why, with the
|
|
92
|
+
fix, never that it stops anything.
|
|
93
|
+
|
|
94
|
+
| Command | What it does |
|
|
95
|
+
|---|---|
|
|
96
|
+
| `anvil-claude` | Home: where it stands, what to do next |
|
|
97
|
+
| `anvil-claude try` | see it work; nothing runs |
|
|
98
|
+
| `anvil-claude report` | what it stopped this week, and what Claude spent |
|
|
99
|
+
| `anvil-claude rules` | every rule, and what it does now |
|
|
100
|
+
| `anvil-claude enforce push-main` | hold one kind of action for your OK |
|
|
101
|
+
| `anvil-claude enforce all` | hold every rule |
|
|
102
|
+
| `anvil-claude rules add "Ask before it deploys."` | add a rule in plain words |
|
|
103
|
+
| `anvil-claude rules add "budget: $50 a day"` | stop Claude Code past what it may spend |
|
|
104
|
+
| `anvil-claude rules add "model: opus for deploys"` | hold deploys made on another model |
|
|
105
|
+
| `anvil-claude rules edit` | every rule on one screen: type one in plain English to add it |
|
|
106
|
+
| `anvil-claude off` | take it out; your settings go back as they were |
|
|
107
|
+
|
|
108
|
+
Run these in your own terminal. Claude can't run them from inside Claude Code, so it can't switch Anvil off.
|
|
109
|
+
|
|
110
|
+
Your rules live in `~/.anvil/rules.md` (every project) or `.anvil/rules.md` (one project), one per line, like
|
|
111
|
+
`hold: deploys`. `anvil-claude help rules` prints the rest (`docs/coding-agents/YOUR-RULES.md`, in this package).
|
|
112
|
+
|
|
113
|
+
**Helper agents.** `model: haiku for exploring` (or `sonnet for helper agents`) runs the agents Claude launches on
|
|
114
|
+
the model you name, whatever Claude asks for. `cap: at most 5 helper agents at once` holds the next launch until one
|
|
115
|
+
finishes, and `cap: 20 helper agents an hour` works too. A fork keeps the session's model.
|
|
116
|
+
|
|
117
|
+
**The main chat's model.** No tool can switch it, so Anvil holds instead: `model: opus for deploys` holds a deploy made
|
|
118
|
+
on another model (`/model opus`, then ask Claude again, runs it), and `model: never haiku` refuses a switch to Haiku
|
|
119
|
+
and every message in a session on it (one the desktop app's picker or `claude --model haiku` started there), in the
|
|
120
|
+
terminal and the desktop app.
|
|
121
|
+
|
|
122
|
+
<br>
|
|
123
|
+
|
|
124
|
+
## What a rule can cover
|
|
125
|
+
|
|
126
|
+
A rule is about a **kind of action** Claude takes, and it can name one app, one file or folder, or one target of the
|
|
127
|
+
kind. Type it in plain words, or paste the command: Anvil reads a command the way it does when Claude runs it, so
|
|
128
|
+
`docker push` holds what Anvil calls a publish.
|
|
129
|
+
|
|
130
|
+
| You can | For example |
|
|
131
|
+
|---|---|
|
|
132
|
+
| Hold a kind of action for your OK, or block it | `hold pushes to main` · `never force-push` · `ask before it deploys` · `docker push` |
|
|
133
|
+
| Narrow it to one app | `hold Stripe changes` · `never send email through Gmail` · `hold Slack posts` |
|
|
134
|
+
| Narrow it to a file or folder | `don't touch migrations/` · `ask before editing package-lock.json` · `hold changes to infra/` |
|
|
135
|
+
| Narrow it to one target | `hold deploys to production` · `hold pushes to main in billing-api` · `hold deletes outside the project` |
|
|
136
|
+
| Hold only some of them | `hold Stripe refunds over $500` · `never email anyone outside the company` · `hold Slack posts in #general` · `hold deploys on Fridays` |
|
|
137
|
+
| Cap how often, or how much | `at most 3 deploys a day` · `at most 5 Stripe refunds a day` · `at most $2,000 of Stripe refunds a day` · `5 helper agents at once` |
|
|
138
|
+
| Set a budget | `$50 a day` · `80% of my weekly limit` |
|
|
139
|
+
| Tie an action to a model | `model: opus for deploys` · `model: haiku for exploring` |
|
|
140
|
+
|
|
141
|
+
The kinds: pushes to main, force-pushes, deletes, throwing away uncommitted work, database destroys, deploys,
|
|
142
|
+
publishing, printing secrets, running as root, killing processes, writes to other services, paid compute, tunnels,
|
|
143
|
+
copying a database here, crypto transactions, background jobs, helper agents, `.env` files, and app changes.
|
|
144
|
+
|
|
145
|
+
**A narrowed rule only adds a stop, and holds what it can't read.** The box shows what still runs before you add one.
|
|
146
|
+
|
|
147
|
+
**Every rule you type gets one of three answers, said first:** ✓ ready; ▲ a catch, where it works with one difference
|
|
148
|
+
said plainly (an app not connected here, a category that covers every app of it Anvil knows, a deploy that doesn't say where it
|
|
149
|
+
goes held too); or ? can't yet, with the closest rule Anvil can do, one key away (`rules add` prints it as a command).
|
|
150
|
+
A catch stays on the rule's row: `hold Shopify refunds` says "not connected yet" until you connect Shopify.
|
|
151
|
+
|
|
152
|
+
- **One app** covers its MCP tools, its API reached from a command (`curl -X POST https://api.stripe.com/…`) and its
|
|
153
|
+
CLI. Reads run. Anvil knows an app by your own MCP servers and connectors too, by name only.
|
|
154
|
+
- **A file or folder** covers Claude's file tools and every shell write Anvil can read (`>`, `tee`, `sed -i`, `cp`,
|
|
155
|
+
`mv`, `rm`). Reads run. A script that builds its paths as it runs isn't seen. Claude Code's own `Edit(…)` rule is the
|
|
156
|
+
other way to do it, without the one-time OK.
|
|
157
|
+
- **A target** is read from the command itself: `vercel --prod`, `fly -a`, `railway -e`, `kubectl --context`, `modal -e`,
|
|
158
|
+
terraform's workspace; a push's repository from the checkout it runs in. A deploy whose command doesn't say where it
|
|
159
|
+
goes is held, and so is a tool whose default may be production.
|
|
160
|
+
- **A condition** is read from the call itself: a money app's amount, who an email or an invite reaches (with
|
|
161
|
+
`define: my company = acme.com` for "outside the company"), one part of an app (a Slack channel, a GitHub
|
|
162
|
+
repository, a Linear team, a Jira project), or the time on this Mac's clock. What it can't read, it holds, saying why
|
|
163
|
+
(a full refund names no amount; a channel id Anvil hasn't seen yet). `anvil-claude help rules` lists each.
|
|
164
|
+
|
|
165
|
+
**What a rule can't cover yet.** The box says which one, and what to type instead:
|
|
166
|
+
|
|
167
|
+
- **Conditions Anvil can't read** (`deploys unless tests pass`, `during the launch`, `on December 3rd`, refunds
|
|
168
|
+
`over 10%`, who a Slack message or a text reaches). The box offers the rule without them, which holds every one.
|
|
169
|
+
- **Other environments and regions** (`deploys to staging`, `to eu-west`). Hold production instead: staging and
|
|
170
|
+
previews run.
|
|
171
|
+
- **Advice for Claude** (`write tests first`). That belongs in CLAUDE.md.
|
|
172
|
+
- **Everyday commands** (`npm install`, `git commit`). They run as always.
|
|
173
|
+
|
|
174
|
+
Always on can't be turned down. Anvil checks what Claude does, not the commands you run yourself.
|
|
175
|
+
|
|
176
|
+
<br>
|
|
177
|
+
|
|
178
|
+
## Privacy
|
|
179
|
+
|
|
180
|
+
- **Only actions.** Anvil judges what Claude does, never what you or Claude say, and it never stores or sends your
|
|
181
|
+
prompts or Claude's replies. From Claude Code's session files it picks out four things only: Claude Code's version,
|
|
182
|
+
whether you said Yes to a held action, each reply's model, token counts and cost, and when a helper agent last
|
|
183
|
+
worked, never its text. From a helper launch, only its type and model.
|
|
184
|
+
- **On your machine.** What it records stays in `~/.anvil`. What Claude spent is kept for 40 days.
|
|
185
|
+
- **Usage counts.** Anvil sends anonymous usage counts, listed in `TELEMETRY.md`. `DO_NOT_TRACK=1` turns them off.
|
|
186
|
+
|
|
187
|
+
<br>
|
|
188
|
+
|
|
189
|
+
## Good to know
|
|
190
|
+
|
|
191
|
+
**Runs on** macOS and Linux · Node 20+ · Claude Code 2.1.295 or later. Not on Windows yet: it is built and in testing.
|
|
192
|
+
|
|
193
|
+
**What each limit needs:**
|
|
194
|
+
|
|
195
|
+
| Limit | Needs |
|
|
196
|
+
|---|---|
|
|
197
|
+
| rules, caps, a helper's model | Claude Code 2.1.295 or later |
|
|
198
|
+
| `model: opus for deploys` | Claude Code 2.1.304 or later (it records each request's model) |
|
|
199
|
+
| refusing the next message, a task budget, helpers at once, `model: never …` | Claude Code 2.1.318 or later, on every Claude Code `on` finds |
|
|
200
|
+
| a plan budget (`80% of my weekly limit`) | a status line reading in the terminal (above) |
|
|
201
|
+
|
|
202
|
+
An older Claude Code anywhere on the machine keeps `on` from adding the events those listen to (one that can't read them
|
|
203
|
+
could cost the hooks that guard); the screens name it, by version and path. The desktop app reads the same settings,
|
|
204
|
+
so everything works there, but it has no status line: a plan budget uses the latest terminal reading. The Claude Code
|
|
205
|
+
plugin, instead of `anvil-claude on`, checks actions only: no message refusal, task budgets, helper count or `/model`
|
|
206
|
+
refusal.
|
|
207
|
+
|
|
208
|
+
- **Update it:** `npm i -g @useanvil/claude-code`, then run `anvil-claude` once: it puts the new hook in place.
|
|
209
|
+
- **Remove it:** `anvil-claude off --purge`, then `npm uninstall -g @useanvil/claude-code`. Your rules files stay.
|
|
210
|
+
- **Beside the SDK:** this package's command is `anvil-claude`, and `@useanvil/sdk` keeps its own `anvil`, so the
|
|
211
|
+
two install side by side and neither touches the other's. The SDK's `anvil-claude …` is the same Anvil for Claude
|
|
212
|
+
Code, with the same files in `~/.anvil/claude`: use either.
|
|
213
|
+
|
|
214
|
+
Questions, or something broken? henry@anvilcontrol.ai · Security: [anvilcontrol.ai/security](https://anvilcontrol.ai/security) ·
|
|
215
|
+
What's new: `CHANGELOG.md`
|
package/TELEMETRY.md
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# Telemetry
|
|
2
|
+
|
|
3
|
+
What the Anvil CLI (`@useanvil/sdk`) tells Anvil about how it is used, field by field. A test
|
|
4
|
+
(`tests/coding-agents/telemetry.test.ts`) holds this page to the code: an event or field that is not
|
|
5
|
+
listed here cannot be sent.
|
|
6
|
+
|
|
7
|
+
## Turn it off
|
|
8
|
+
|
|
9
|
+
- `DO_NOT_TRACK=1` or `ANVIL_FUNNEL_DISABLED=1` turns all of it off.
|
|
10
|
+
- The Claude Code events below are never sent in CI (`CI`, `GITHUB_ACTIONS`, `GITLAB_CI`, `BUILDKITE`,
|
|
11
|
+
`CIRCLECI`, `TF_BUILD`, `JENKINS_URL`, `TEAMCITY_VERSION`).
|
|
12
|
+
|
|
13
|
+
## Where it goes
|
|
14
|
+
|
|
15
|
+
One `POST` per event to `https://app.anvilcontrol.ai/api/funnel` (`ANVIL_HOSTED_DASHBOARD_URL` moves it),
|
|
16
|
+
with the body `{ "fid", "event", "props" }`:
|
|
17
|
+
|
|
18
|
+
- `fid` is a random id made on this machine, not derived from anything about you or your machine.
|
|
19
|
+
The Claude Code events below use their own (`c_` and 32 hex characters, in `~/.anvil/claude/telemetry-id`),
|
|
20
|
+
shared with nothing else. The other CLI events use `~/.anvil/anon-id.json` (`a_` and 32 hex characters):
|
|
21
|
+
`anvil protect` also puts that one in the address of the onboarding page it opens, and once you sign up
|
|
22
|
+
there the page can link it to your workspace. With tracking off, no id is made and none is passed.
|
|
23
|
+
- The server keeps the event name, the time, the `fid` and the fields below. It drops any event it does
|
|
24
|
+
not know and keeps at most 8 fields.
|
|
25
|
+
|
|
26
|
+
## Never sent
|
|
27
|
+
|
|
28
|
+
Commands, file paths, folder or project names, rule text, your machine's name, emails, workspace ids,
|
|
29
|
+
API keys, and anything from your Claude Code transcripts.
|
|
30
|
+
|
|
31
|
+
## Anvil for Claude Code
|
|
32
|
+
|
|
33
|
+
The first command that would send one of these prints a notice once per machine, before anything is
|
|
34
|
+
sent: `anvil claude on` on stdout, `anvil replay` on stderr. It counts only when that output is a terminal a
|
|
35
|
+
person can read: piped to a file, or run by an agent, nothing is shown and nothing is sent. Until it has been
|
|
36
|
+
shown, the hook's background sync never sends either.
|
|
37
|
+
|
|
38
|
+
| Event | When | Fields |
|
|
39
|
+
| --- | --- | --- |
|
|
40
|
+
| `claude_on` | `anvil claude on` | `mode` (`ghost` or `some-enforced`), `scope` (`user` or `project`), `linked` (signed in, `true`/`false`), `plugin` (the Claude Code plugin is enabled, `true`/`false`) |
|
|
41
|
+
| `replay_run` | `anvil replay` | `window` (`30d` or `all`), `sessions`, `actions`, `would_stop`, `active_days`: each a bucket, `0`, `1-9`, `10-99`, `100-999`, `1k-9k` or `10k+` |
|
|
42
|
+
| `decisions_daily` | once for each past day the hook ran, at most the last 7, never a day before the notice: sent by `anvil claude on` or `anvil claude sync`, or by the background sync when signed in | `day` (the UTC date), `calls` (tool calls checked, a bucket), and counts: `held`, `blocked`, `would` (would have stopped, in ghost), `approved` (allowed once), `errors` (calls Anvil could not check) |
|
|
43
|
+
|
|
44
|
+
## Other CLI events
|
|
45
|
+
|
|
46
|
+
| Event | When | Fields |
|
|
47
|
+
| --- | --- | --- |
|
|
48
|
+
| `install` | the first `anvil protect` on a machine | none |
|
|
49
|
+
| `command_run` | each `anvil protect` | none |
|
|
50
|
+
| `protect_no_match` | `anvil protect` found nothing to wrap | `cause`, `scope`, `language` |
|
|
51
|
+
| `signed_in` | `anvil login` | none |
|
|
52
|
+
|
|
53
|
+
## Not telemetry: your dashboard
|
|
54
|
+
|
|
55
|
+
Signed in (`anvil login`), the Claude Code hook's stops go to **your own workspace**, so your dashboard
|
|
56
|
+
can show them. That is your data, not usage counts, and the hook never sends it itself: a background
|
|
57
|
+
process does, within seconds. Each stop carries the kind of action (`claude.bash.git.push_main`), the
|
|
58
|
+
verdict and mode, the name of the Anvil rule (your own rules are sent as `your-rule`), a reason made only
|
|
59
|
+
of Anvil's fixed labels, the time, how long the check took, and a key made of your machine label, the
|
|
60
|
+
first 8 characters of the Claude Code session id, and a hash. Never the command, a path or a project name.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
var le=[{app:"stripe",name:"Stripe",minor:!0,obj:null,servers:["stripe"],clis:["stripe"],hosts:["api.stripe.com"],at:{create_refund:["amount"],"/v1/refunds":["amount"],"/v1/charges":["amount"],"/v1/charges/*/capture":["amount"],"/v1/payment_intents":["amount"],"/v1/payment_intents/*":["amount"],"/v1/payment_intents/*/capture":["amount_to_capture"],"/v1/payment_intents/*/increment_authorization":["amount"],"/v1/payouts":["amount"],"/v1/transfers":["amount"],"/v1/transfers/*/reversals":["amount"],"/v1/topups":["amount"],"refunds create":["amount"],"charges create":["amount"],"charges capture":["amount"],"payment_intents create":["amount"],"payment_intents update":["amount"],"payment_intents capture":["amount_to_capture"],"payment_intents increment_authorization":["amount"],"payouts create":["amount"],"transfers create":["amount"],"topups create":["amount"]},digits:{isk:2,ugx:2},nameless:["create_refund","/v1/refunds","refunds create"],unread:{invoice:"Stripe adds it up from items added one call at a time, and can bill it on its own"}},{app:"paypal",name:"PayPal",minor:!1,json:!0,obj:["value","currency_code","currency"],servers:["paypal"],clis:[],hosts:["paypal.com"],at:{create_refund:["amount"],record_payment_for_invoice:["amount"],record_refund_for_invoice:["amount"],pay_order:[],"/v2/payments/captures/*/refund":["amount"],"/v2/payments/authorizations/*/capture":["amount"],"/v2/checkout/orders":["purchase_units.*.amount"],"/v2/checkout/orders/*/capture":[],"/v1/payments/payouts":["items.*.amount"],"/v2/invoicing/invoices/*/payments":["amount"],"/v2/invoicing/invoices/*/refunds":["amount"]},invoices:{create_invoice:["items.*.unit_amount \xD7 quantity","$currency_code","!items.*.tax","!items.*.discount","!shipping_cost","!allow_tip"],update_invoicing:["invoice_update.items.*.unit_amount \xD7 quantity","$invoice_update.currency_code","!invoice_update.items.*.tax","!invoice_update.items.*.discount","!invoice_update.shipping_cost","!invoice_update.allow_tip","!recurring_series_update"],"/v2/invoicing/invoices":["items.*.unit_amount \xD7 quantity","$detail.currency_code","!items.*.tax","!items.*.discount","!amount","!configuration.template_id","!configuration.allow_tip"],"/v2/invoicing/invoices/*":["items.*.unit_amount \xD7 quantity","$detail.currency_code","!items.*.tax","!items.*.discount","!amount","!configuration.template_id","!configuration.allow_tip"]}},{app:"square",name:"Square",minor:!0,json:!0,obj:["amount","currency"],servers:["square","squareup"],clis:[],hosts:["squareup.com","squareupsandbox.com"],at:{"make_api_request payments create":["request.amount_money","request.tip_money"],"make_api_request refunds payment":["request.amount_money"],"/v2/payments":["amount_money","tip_money"],"/v2/refunds":["amount_money"]},unread:{invoice:"it bills an order made by a call of its own"}},{app:"shopify",name:"Shopify",minor:!1,json:!0,obj:null,servers:["shopify"],clis:[],hosts:["myshopify.com"],changes:["refund"],at:{"/admin/api/*/graphql.json refundCreate":["input.transactions.*.amount","~input.shipping.amount"],"/admin/api/*/orders/*/refunds.json":["refund.transactions.*.amount","~refund.shipping.amount"]},nameless:["/admin/api/*/graphql.json refundCreate","/admin/api/*/orders/*/refunds.json"]}];var ce=/^[0-9a-f]{8}(?:_[0-9a-f]{4}){3}_[0-9a-f]{12}$/,Qe=/(?:^|_)(?:zapier|composio|pipedream|n8n|make|rube|activepieces|klavis|toolhouse|arcade|ifttt|integrately|gumloop|viasocket|metamcp|1mcp|smithery|mcp_?(?:hub|gateway|proxy|router|docker))(?:_|$)/,et=/(?:^|[^a-z])(?:api|request|requests|execute|exec|run|call|invoke|http|graphql|rpc|raw|batch|bulk|action|actions|command|operation|perform|proxy|custom|query|sql|services|hooks?|webhooks?|triggers?)(?:[^a-z]|$)/,ue=e=>e.normalize("NFKC").replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase(),de=(e,t)=>e.split("+").every(n=>n[0]==="="?t.split(/[^a-z0-9]+/).includes(n.slice(1)):t.includes(n));function tt(e,t){let n=`_${t}_`.replace(/_mcp(?=[a-z])|(?<=[a-z])mcp_/g,"_"),o=t.replace(/_/g,"");return e.servers.some(r=>{let s=r.replace(/_/g,"");return`_${t}_`.includes(`_${r}_`)||n.includes(`_${r}_`)||(s.length>4?o.includes(s):s.length>3&&(o.startsWith(s)||o.endsWith(s)))})}function nt(e,t,n){let o=t.normalize("NFKC").toLowerCase().replace(/\.+$/,""),r=/^[a-z0-9.-]+$/.test(o);if(!o.includes("."))return r?(e.clis??[]).includes(o)?"this":"other":"?";let s=o.split("."),a=u=>o===u||o.endsWith(`.${u}`)||u.includes("*")&&u.split(".").every((d,i,l)=>l.length===s.length&&(d==="*"||d===s[i])),c=!1;return e.hosts.some(u=>{let d=u.indexOf("/");return d<0?a(u):(c||=a(u.slice(0,d))&&/^(?:\/batch\/?|\u0000)$/.test(n),a(u.slice(0,d))&&n.includes(u.slice(d)))})?"this":r&&!c?"other":"?"}function rt(e){if(!e||!/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return null;try{return new URL(e).hostname.replace(/^\[|\]$/g,"")}catch{return"\0"}}function N(e,t,n,o){let r=ue(n);return e.toolWords.length===0||e.toolWords.some(s=>de(s,r))?{hit:"match",part:t,why:e.said}:o===3||/\u0000|%00/.test(r)||et.test(r)||!/[a-z]{3}/.test(r.replace(/[a-z]*\d[a-z0-9]*/g,""))||o===1&&!/[a-z0-9][^a-z0-9]+[a-z0-9]/.test(r)?{hit:"unknown",part:t,why:`Anvil can't tell whether this is one of ${e.said}, so it holds it`}:null}function ot(e,t,n){let o=l=>({hit:"unknown",part:t,why:`Anvil can't tell ${l}, so it holds it (your rule: ${e.said})`});if(t.action==="claude.mcp.side_effect"){let l=t.host;if(!l)return o("which app this tool belongs to");let f=`mcp.${l}.`,m=ue(n.tool?.startsWith("mcp__")?n.tool.split("__").slice(2).join("__"):t.target?.startsWith(f)?t.target.slice(f.length):"");if(tt(e,l))return N(e,t,m,1);let p=(e.anywhere??[]).some(g=>de(g,m))?{hit:"match",part:t,why:e.said}:null;if(!ce.test(l)&&!Qe.test(l))return p;let h=e.toolPrefixes.find(g=>m.startsWith(g));return h?N(e,t,m.slice(h.length),1):e.servers.some(g=>g.length>2&&`_${m}_`.includes(`_${g}_`))?N(e,t,m,1):p||(e.others??[]).includes(l)?p:o(`which app ${ce.test(l)?`the connector ${l.slice(0,8)}\u2026`:l} acts on`)}let r=t.target??"",s=/^[\w-]+(?:\.[\w-]+)+(?::\d+)?\//.test(r)?`https://${r}`:r,a=/^[a-z][a-z0-9+.-]*:\/\//i.test(s),c="";try{a&&(c=decodeURIComponent(new URL(s).pathname).replace(/\/{2,}/g,"/"))}catch{c="\0"}if(!t.host&&!t.service)return o("where this writes");let u=[t.host,t.service,...Array.isArray(t.attributes.hosts)?t.attributes.hosts:[],rt(s)].filter(l=>typeof l=="string"&&l!==""),d=u.map(l=>nt(e,l,c)),i=[r,...u].some(l=>/^smtps?[:.]/i.test(l));if(d.includes("this")||i&&e.hosts.includes("smtp:")){let l=u.find((m,p)=>d[p]==="this"&&!m.includes(".")),f=r.includes("/")?3:2;return l?N(e,t,`cli:${l.toLowerCase()} ${r}`,f):i?N(e,t,"send mail",2):a?N(e,t,c,3):N(e,t,r,f)}return d.includes("?")?o(`where this writes (${u[0].replace(/[\u0000-\u001f]/g,"")})`):n.tool?.startsWith("mcp__")?o("what else this tool's command writes"):null}function B(e,t,n){let o=null;for(let r of t){let s=ot(e,r,n);if(s?.hit==="match")return s;o??=s}return o??(n.parts.length>15&&t[0]?{hit:"unknown",part:t[0],why:`Anvil can't read everything this line does, so it holds it (your rule: ${e.said})`}:null)}var st={over:"over",at_least:"at least",under:"under",at_most:"at most"};var k="Anvil can't read how much this moves",he="Anvil can't read this invoice's total (only drafting or replacing one says it)",it="Anvil can't add up this total (a tax, a discount, shipping, a tip, a template or a series changes it)",fe="Anvil can't tell which currency this moves (it names two)",at="Anvil can't tell how many requests this makes (curl expands {\u2026} and [\u2026] in a URL)",ye="claude.mcp.side_effect",lt=/\$\(|\$'|\$"|`|<<|(?:^|[\s;&|])(?:eval|xargs|source|exec)(?=\s|$)|\b(?:ba|z|k|da)?sh\s+-\w*c\b/,ct=/^(?:[A-Za-z_]\w*=.*|env|sudo|time|nohup|command|builtin|nice)$/,ut="012346#aBfgGiIjJklLMnNOpqRsSvVZ",dt=/^(?:silent|show-error|fail(?:-with-body|-early)?|location(?:-trusted)?|insecure|compressed|include|show-headers|verbose|http1\.[01]|http2(?:-prior-knowledge)?|http3(?:-only)?|globoff|progress-bar|raw|path-as-is|ssl-reqd|tlsv1(?:\.[0-3])?|ipv[46]|tcp-nodelay|remote-name(?:-all)?|remote-header-name|create-dirs|digest|basic|ntlm|negotiate|anyauth|crlf|append|junk-session-cookies|list-only|disable|netrc(?:-optional)?|proxytunnel|parallel|retry-all-errors|retry-connrefused|no-[a-z0-9-]+|get|head)$/,ft=/^(?:data(?:-raw|-binary|-ascii|-urlencode)?|form(?:-string)?|json)$/,pt=/^(?:live|confirm|help|version|dark_style|show_headers|dry_run|reverse_transfer|refund_application_fee|capture|final_capture)$/;function T(e){let t=(e.host??"").toLowerCase(),n=`_${t}_`.replace(/_mcp(?=[a-z])|(?<=[a-z])mcp_/g,"_"),o=le.filter(r=>e.action===ye?r.servers.some(s=>`_${t}_`.includes(`_${s}_`)||n.includes(`_${s}_`)):r.clis.includes(t)||r.hosts.some(s=>t===s||t.endsWith(`.${s}`)));return o.length===1?o[0]:null}function gt(e){let t=[[]],n="",o=!1,r=!1,s=!1,a=!1,c=!1,u=!1,d=()=>{c&&u?u=!1:c&&t[t.length-1].push({w:n,d:o,x:r,g:s}),n="",o=r=s=a=c=!1};for(let i=0;i<e.length;i++){let l=e[i];if(l==="'"){let f=e.indexOf("'",i+1);if(f<0)return null;n+=e.slice(i+1,f),i=f,a=!0}else if(l==='"'){let f=i+1;for(;f<e.length&&e[f]!=='"';f++){if(e[f]==="\\"&&e[f+1]===`
|
|
2
|
+
`){f++;continue}e[f]==="\\"&&/["\\$`]/.test(e[f+1]??"")?f++:e[f]==="$"&&(o=!0),n+=e[f]}if(f>=e.length)return null;i=f,a=!0}else if(l==="\\"){if(i++,e[i]!==`
|
|
3
|
+
`)n+=e[i]??"",a=!0;else if(!c)continue}else if(l==="#"&&!c){if(i=e.indexOf(`
|
|
4
|
+
`,i)-1,i<0)break;continue}else{if(/[(){}]/.test(l))return null;if(l==="<"||l===">"||l==="&"&&e[i+1]===">"){if((a||!/^\d+$/.test(n))&&d(),n="",o=r=s=a=c=!1,u)return null;l==="&"&&i++,(e[i]===">"?/[>|&]/:/[&>]/).test(e[i+1]??"")&&i++,u=!0;continue}else if(/[;|&\n]/.test(l)){if(d(),u)return null;t[t.length-1].length>0&&t.push([]);continue}else if(l===" "||l===" "){d();continue}else{if(/\s/.test(l))return null;l==="$"&&(o=r=!0),/[*?[]/.test(l)&&(s=!0),n+=l}}c=!0}return d(),u?null:t}function we(e,t){let n=t.replace(/\/{2,}/g,"/").replace(/(.)\/$/,"$1").split("/");return Object.keys(e).filter(o=>{let r=o.split(" ")[0].split("/");return o[0]==="/"&&r.length===n.length&&r.every((s,a)=>s==="*"?n[a]!=="":s===n[a])})}var Z=e=>e.filter(t=>t[0]!=="!"&&t[0]!=="$").map(t=>t.replace(/^~/,"").split(" ")[0]);function L(e,t){return[...new Set(e.map(n=>n.split(".").pop()))].reduce((n,o)=>n+(t.match(new RegExp(`(?:(?<![a-z0-9_]|[a-z0-9]-)|(?<=(?:^|\\s)-[a-z]+))${o.replace(/_/g,"[-_]")}(?![a-z0-9_]|-[a-z0-9])`,"gi"))?.length??0),0)}function J(e,t,n,o,r){let s=[],a=[],c=0;for(let d of t){let i=/^[!~$]/.test(d)?d[0]:"",[l="",f]=d.slice(i.length).split(" \xD7 "),m=[{v:n,up:null,curs:[]}];for(let p of l.split(".")){let h=[];for(let{v:g,curs:y}of m)if(g!=null){if(p==="*"?!Array.isArray(g):typeof g!="object"||Array.isArray(g))return k;if(p==="*")h.push(...g.map(b=>({v:b,up:null,curs:y})));else if(Object.hasOwn(g,p)){let b=g;h.push({v:b[p],up:b,curs:b.currency===void 0?y:[...y,b.currency]})}}m=h.filter(g=>g.v!==void 0&&g.v!==null)}if(i==="!"&&m.some(p=>p.v!==!1))return it;if(i==="~"&&(c+=m.length),i==="$")for(let{v:p}of m){if(typeof p!="string")return k;a.push(p.toLowerCase())}if(!i)for(let{v:p,up:h,curs:g}of m){let y=f===void 0?void 0:h?.[f];if(f!==void 0&&y==null)return k;if(e.obj){if(typeof p!="object"||Array.isArray(p))return k;{let b=p,w=[...new Set(e.obj.slice(1).map($=>b[$]).filter($=>$!==void 0))];s.push({v:b[e.obj[0]],cur:w.length>1?"?":w[0],q:y})}}else{let b=[...new Set(g)];s.push({v:p,cur:b.length>1?"?":b[0],drop:r,q:y})}}}if(a.length>0){if(new Set(a).size>1)return fe;for(let[d,i]of s.entries())if(i.cur===void 0)s[d]={...i,cur:a[0]};else if(typeof i.cur!="string"||i.cur.toLowerCase()!==a[0])return fe}let u=Z(t);return Math.max(L(u,o),L(u,JSON.stringify(n)))>s.length+c?k:s}var K=/[\s,]+|#[^\n\r]*|("(?:[^"\\\n\r]|\\.)*")|(\.\.\.|[!$&():=@[\]{|}])|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|([_A-Za-z]\w*)/y;function mt(e,t,n,o){let r=o,s=r?.variables??{},a=r?.query;if(!r||typeof r!="object"||Array.isArray(r)||typeof a!="string"||a.includes('"""')||typeof s!="object"||Array.isArray(s))return k;let c=[];for(K.lastIndex=0;K.lastIndex<a.length;){let h=K.exec(a);if(!h)return k;let g=h[1]??h[2]??h[3]??h[4];g!==void 0&&c.push(g)}let u=0,d=()=>c[u],i=h=>{let g=c[u++];if(g===void 0||h!==void 0&&g!==h)throw new Error;return g},l=()=>{let h=i();if(!/^[_A-Za-z]/.test(h))throw new Error;return h},f=()=>{let h=i();if(h==="$"){let g=l();if(!Object.hasOwn(s,g))throw new Error;return s[g]}if(h==="["){let g=[];for(;d()!=="]";)g.push(f());return i(),g}if(h==="{"){let g={};for(;d()!=="}";){let y=l();i(":"),g[y]=f()}return i(),g}if(h[0]==='"')return JSON.parse(h);if(/^-?\d/.test(h))return h;if(/^[_A-Za-z]/.test(h))return h==="true"?!0:h==="false"?!1:h==="null"?null:h;throw new Error},m=()=>{let h={};if(d()!=="(")return h;for(i();d()!==")";){let g=l();i(":"),h[g]=f()}return i(),h},p=()=>{for(let h=1;h>0;){let g=i();h+=g==="{"?1:g==="}"?-1:0}};try{let h="query";if(d()!=="{"&&(h=i(),d()!=="("&&d()!=="{"&&l(),d()==="(")){for(i();i()!==")";)if(c[u-1]==="=")throw new Error}i("{");let g=[];if(h==="query")p();else{if(h!=="mutation")throw new Error;for(;d()!=="}";){let y=l();d()===":"&&(i(),y=l());let b=m();for(;d()==="@";){if(i(),l()!=="idempotent")throw new Error;m()}d()==="{"&&(i(),p());let w=n.find($=>$.endsWith(` ${y}`));g.push(w?J(e,t[w],b,JSON.stringify(b),e.nameless?.includes(w)):k)}if(i(),g.length===0)throw new Error}if(u<c.length)throw new Error;return h==="query"?"read":g}catch{return k}}var W=(e,t,n)=>{e.set(t,[...e.get(t)??[],n])};function be(e,t,n,o){let r=Z(e);if([...t.keys()].some(d=>!e.includes(d)&&L(r,d)>0))return k;let s=t.get("currency")??[],a=d=>d.some(i=>i.d)||new Set(d.map(i=>i.w)).size>1?"?":d[0]?.w,c=[],u=0;for(let d of e){let i=t.get(d)??[];if(u+=i.length,i.length===0)continue;let l=a(i);if(l==="?")return k;c.push({v:l,cur:s.length>0?a(s):void 0,drop:o})}return L(Z(e),n)>u?k:c}function Y(e,t,n){let o=t.w.indexOf("=");if(o<=0||t.w.slice(0,o).includes("$"))return!1;let r=t.w.slice(0,o),s=t.w.slice(o+1);try{r=decodeURIComponent(r.replace(/\+/g," ")),n&&(s=decodeURIComponent(s.replace(/\+/g," ")))}catch{return!1}return W(e,r,{w:s,d:t.d&&s.includes("$"),x:!1}),!0}function ht(e,t,n,o,r){let s=[],a=new Map;for(let l=0;l<n.length;l++){let{w:f,d:m}=n[l];if(f.startsWith("--")){let p=f.indexOf("="),h=(p<0?f.slice(2):f.slice(2,p)).replace(/-/g,"_");if(p<0&&pt.test(h))continue;let g=p>=0?{w:f.slice(p+1),d:m,x:!1}:n[++l];if(!g||p<0&&/^-./.test(g.w))return k;if(h==="data"){if(!Y(a,g,!1))return k}else W(a,h,g)}else if(/^-./.test(f)){let p=1;for(;p<f.length&&"chs".includes(f[p]);)p++;if(p===f.length)continue;let h=p+1<f.length?{w:f.slice(p+1),d:m,x:!1}:n[++l];if(!h||p+1===f.length&&/^-./.test(h.w)||f[p]==="d"&&!Y(a,h,!1))return k}else s.push(n[l])}let[c="",u=""]=s.map(l=>l.w);if(c==="get"||u==="list"||u==="retrieve")return"read";let d=`${c} ${u}`,i=Object.hasOwn(t,d)?d:/^(?:post|delete)$/.test(c)&&u[0]==="/"?we(t,u.split("?")[0]).find(l=>!l.includes(" ")):void 0;if(!i)return r;if(i!==d){if(s[1].d)return k;for(let[l,f]of new URLSearchParams(u.includes("?")?u.slice(u.indexOf("?")+1):""))W(a,l,{w:f,d:!1,x:!1})}return be(t[i],a,o,!!e.nameless?.includes(i))}function yt(e){try{return/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?new URL(e):/^[\w-]+(?:\.[\w-]+)+(?::\d+)?(?:\/|$)/.test(e)?new URL(`https://${e}`):null}catch{return null}}var wt=(e,t)=>{let n=yt(t);return n&&e.hosts.some(o=>n.hostname===o||n.hostname.endsWith(`.${o}`))?n:null};function bt(e,t,n,o,r){let s=null,a="",c="",u=!1,d=!1,i=[];for(let y=0;y<n.length;y++){let{w:b,d:w}=n[y];if(b.startsWith("--")){let $=b.slice(2);if(/^(?:next|config|variable|expand-.*|upload-file)$|=/.test($))return k;if(/^(?:no-)?(?:get|head)$/.test($)&&(u=$[0]!=="n"),/^(?:no-)?globoff$/.test($)&&(d=$[0]!=="n"),dt.test($))continue;let _=n[++y];if(!_)return k;ft.test($)?i.push({v:_,how:$}):$==="request"&&(c=_.w.toUpperCase())}else if(/^-./.test(b))for(let $=1;$<b.length;$++){let _=b[$];if(_==="K"||_===":"||_==="T")return k;if((_==="G"||_==="I")&&(u=!0),_==="g"&&(d=!0),ut.includes(_))continue;let A=$+1<b.length?{w:b.slice($+1),d:w,x:!1}:n[++y];if(!A)return k;_==="d"||_==="F"?i.push({v:A,how:_==="d"?"data":"form"}):_==="X"&&(c=A.w.toUpperCase());break}else{let $=wt(e,b);if(!$)continue;if(w||s)return k;s=$,a=b}}if(!s)return null;if(/^(?:GET|HEAD|OPTIONS)$/.test(c||(u||i.length===0?"GET":"POST")))return"read";if(!d&&/[{}[\]]/.test(a))return at;if(e.json&&u&&i.length>0)return k;let l;try{l=decodeURIComponent(s.pathname)}catch{return k}let f=we(t,l),m=f.find(y=>!y.includes(" "));if(!m&&f.length===0)return r;let p=new Map;for(let[y,b]of s.searchParams)W(p,y,{w:b,d:!1,x:!1});let h;for(let{v:y,how:b}of i){let w=y.w.trim();if(w[0]==="{"||w[0]==="["){if(y.d||h!==void 0)return k;try{h=JSON.parse(w)}catch{return k}}else for(let $ of w.split("&"))if(!Y(p,{w:$,d:y.d,x:!1},!/urlencode|form/.test(b)))return k}if((h!==void 0||e.json)&&p.size>0)return k;if(!m){let y=h===void 0||p.size>0?k:mt(e,t,f,h);return typeof y=="string"?y:{many:y}}let g=!!e.nameless?.includes(m);return h!==void 0?J(e,t[m],h,o,g):be(t[m],p,o,g)}function $t(e,t,n,o){let r=n.input?.command,s=typeof r=="string"&&!lt.test(r)?gt(r):null;if(!s)return k;let a=[],c=new RegExp([...e.servers,...e.clis].join("|"),"i");for(let u of s){let d=u.map(p=>p.w).join(" "),i=0;for(;i<u.length&&ct.test(u[i].w);)i++;let l=(u[i]?.w??"").replace(/^.*\//,""),f=u.slice(i+1),m=e.clis.includes(l)?ht(e,t,f,d,o):l==="curl"?bt(e,t,f,d,o):null;if(m===null){if(!/^(?:cd|pushd)$/.test(l)&&u.some(p=>c.test(p.w)))return k;continue}if(f.some(p=>p.x||p.g&&!p.w.includes("://")))return"Anvil can't read a word the shell expands (an unquoted $ or *)";m!=="read"&&a.push(...typeof m=="object"&&!Array.isArray(m)?m.many:[m])}return a.length<n.parts.filter(u=>T(u)===e).length?k:a}var V="this call doesn't say how much it moves",pe=e=>typeof e=="number"?Number.isFinite(e)&&e>=0?String(e):"":typeof e=="string"?e.trim():"",ge=/^(\d+)(?:\.(\d+))?$/;function $e(e,t,n){if(e.length===0)return V;let o=0n,r=0;for(let{v:s,cur:a,drop:c,q:u}of e){let d=c&&(a===void 0||typeof a=="string"&&a.toLowerCase()===n.currency)?void 0:a,i=d===void 0?n.bare?n.currency:null:typeof d=="string"&&/^[a-z]{3}$/i.test(d)?d.toLowerCase():"?";if(i===null)return"Anvil can't tell which currency this moves";if(i!==n.currency)return i==="?"?k:`it's in ${i.toUpperCase()}, not ${n.currency.toUpperCase()}`;let l=(t.minor?/^(\d+)()$/:ge).exec(pe(s)),f=u===void 0?null:ge.exec(pe(u));if(!l||u!==void 0&&!f)return k;let m=(t.minor?t.digits?.[i]??n.digits:(l[2]??"").length)+(f?.[2]??"").length,p=Math.max(r,m);o=o*10n**BigInt(p-r)+BigInt(l[1]+(l[2]??""))*BigInt(f?f[1]+(f[2]??""):1)*10n**BigInt(p-m),r=p}return[o,r]}function me(e,t,n){let o=e.toString().padStart(t+1,"0");return`${n}${o.slice(0,o.length-t).replace(/\B(?=(\d{3})+(?!\d))/g,",")}${t>0?`.${o.slice(-t)}`:""}`}function ke(e,t,n){let o=T(t),r=e.invoice?o?.invoices:o?.at,s=n.tool?.startsWith("mcp__")?n.tool.split("__").slice(2).join("__"):"",a=n.input,c=!a||Object.hasOwn(r??{},s)?s:`${s} ${String(a.service).toLowerCase()} ${String(a.method)}`,u=e.invoice?he:k;return!o||!r||!e.apps.includes(o.app)?k:t.action!==ye?$t(o,r,n,u):a&&Object.hasOwn(r,c)?[J(o,r[c],a,JSON.stringify(a),o.nameless?.includes(c))]:u}function kt(e,t,n){let o=ke(e,t,n);if(typeof o=="string")return o;if(o.length===0)return V;let r=0n;for(let s of o){let a=typeof s=="string"?s:$e(s,T(t),e);if(typeof a=="string")return a;let[c,u]=a,d=10n**BigInt(Math.abs(u-e.digits));r+=u<=e.digits?c*d:(c+d-1n)/d}return r<=BigInt(Number.MAX_SAFE_INTEGER)?Number(r):"Anvil can't count an amount that large"}function vt(e,t){let n=e.money;if(!n||!/^[a-z]{3}$/.test(n.currency)||!Number.isInteger(n.digits)||n.digits<0||n.digits>4||!Array.isArray(n.apps))return"Anvil can't use this cap's currency";let o=t?.parts.filter(s=>e.kinds.includes(s.action)&&(!e.match||B(e.match,[s],t)!==null))??[];if(o.length===0)return"Anvil can't tell how much this moves";let r=0;for(let s of o){let a=kt(n,s,t);if(typeof a=="string")return a;r+=a}return Number.isSafeInteger(r)?r:"Anvil can't count an amount that large"}function ve(e,t,n){let o=T(t),r=ke(e,t,n),s=c=>e.invoice&&c===V?he:c;if(typeof r=="string")return{hit:"unknown",why:s(r)};let a=null;for(let c of r){let u=typeof c=="string"?c:$e(c,o,e);if(typeof u=="string"){a??=u;continue}let[d,i]=u,l=Math.max(i,e.digits),f=d*10n**BigInt(l-i),m=BigInt(e.value)*10n**BigInt(l-e.digits),[p,h]=[f,l];for(;h>e.digits&&p%10n===0n;)[p,h]=[p/10n,h-1];if(e.op==="over"?f>m:e.op==="at_least"?f>=m:e.op==="under"?f<m:f<=m)return{hit:"match",detail:`${me(p,h,e.sign)} is ${st[e.op]} ${me(BigInt(e.value),e.digits,e.sign).replace(/\.0+$/,"")}`}}return a===null?null:{hit:"unknown",why:s(a)}}import{existsSync as U,readdirSync as on,statSync as He}from"fs";import{dirname as se,isAbsolute as sn,join as C,posix as an,resolve as I}from"path";import{posix as Sn}from"path";var _t=null;function z(){return _t??process.platform==="win32"}function _e(e){if(!z())return e;let t=/^\/([a-z])(\/.*)?$/s.exec(e);if(t)return`${t[1].toUpperCase()}:${(t[2]??"/").replace(/\//g,"\\")}`;let n=/^\/unc\/(.+)$/s.exec(e);return n?`\\\\${n[1].replace(/\//g,"\\")}`:null}function D(e){return z()?_e(e)??e:e}import{createHash as Pr}from"crypto";import{appendFileSync as Or,closeSync as en,constants as qe,fstatSync as tn,mkdirSync as Mr,openSync as nn,readdirSync as Ir,readFileSync as Lr,readSync as rn,renameSync as Wr,statSync as Tr,unlinkSync as zr,writeFileSync as Dr}from"fs";import{homedir as qr}from"os";import{dirname as Ur,join as Gr}from"path";import{domainToASCII as Ct}from"url";var xt="to cc bcc torecipients ccrecipients bccrecipients toaddresses ccaddresses bccaddresses toaddress ccaddress bccaddress rcptto recipient recipients attendee attendees optionalattendees requiredattendees guests invitees recipientemail extrarecipients toemail toemails ccemails bccemails",At="klaviyo himalaya convertkit api.kit.com activecampaign api-us1.com activehosted constantcontact constant_contact api.cc.email beehiiv helpscout help_scout freshdesk substack",ee=e=>e.toLowerCase().replace(/[^a-z0-9]/g,""),Rt=null,te={has:e=>(Rt??=new Set(xt.split(" "))).has(e)},je=/^(?:from|sender|replyto|returnpath|envelopefrom|mailfrom|bounce)|^(?:useremail|usergoogleemail|account|accountemail|organizer|owner|user|mailbox|asm)$/,ne=/(?:contact|member|participant|attendee|guest|invitee|person|people|subscriber|customer|recipient|audience|segment|list|group)(?:id|ids|s)?$|userids$|identifiers$|campaignids?$/,Pe=/^(?:draft|(?:draft|message|msg|email|thread|conversation|originalmessage|replytomessage|parentmessage)ids?|inreplyto|references)$/,Nt=/^(?:instructions?|prompt|task)$/,Ee=/ids?$/,Oe=/^(?:subject|body|text|html|content|contents|textbody|htmlbody|htmlcontent|textcontent|textpart|htmlpart|message|comment|description|summary|title|location|notes?|signature|snippet|preheader|plaintext|markdown|name|displayname)$|body$|html$/,St=/^(?:email|emailaddress|address|mail|addr)$/,jt=null,Pt={exec:e=>(jt??=new RegExp(`(?:^|[^a-z0-9])(${At.replace(/\./g,"\\.").replace(/ /g,"|")})`)).exec(e)},re=/send.{0,20}draft|draft.{0,20}send|(?<!no-?)reply|\/messages\/[^/?\s]+\/[^?\s]{0,200}send/,Me=/\$batch|(?:^|[^a-z])(?:batch|jmap)(?:[^a-z]|$)|multi_?execute|(?:^|[^a-z])execute(?:[^a-z]|$)|graphql|(?:^|[^a-z])(?:api_?)?request(?:[^a-z]|$)/,Et=/^(?:all|everyone|everybody|team|staff|group|list|lists|members|announce(?:ments)?|all-?hands|employees|company)$|^(?:all|team|list|everyone)[._-]|[._-](?:all|team|list|group|members|announce|everyone|staff)$|[%!]/,Ot=/(?:^|\.)(?:googlegroups\.com|groups\.io)$|^(?:lists?|groups?)\./;function oe(e){let t=Ct(e.normalize("NFKC").toLowerCase().replace(/\.$/,""));return/^[a-z0-9_-]+(?:\.[a-z0-9_-]+)+$/.test(t)?t:""}function Mt(e){let t=e.trim().replace(/^mailto:/i,""),n=/<([^<>]*)>$/.exec(t);n&&(t=n[1].trim());let o=t.length;for(;o>0&&`"'`.includes(t[o-1]);)o--;t=t.slice(0,o).replace(/^["']+/,"");let r=/^([^\s@<>(),;:"[\]]+)@([^\s@<>(),;:"[\]]+)$/u.exec(t),s=r?oe(r[2]):"";if(!s)return null;let a=r[1].normalize("NFKC").toLowerCase().replace(/(?<=.)\+.*$/,"");return(s==="gmail.com"||s==="googlemail.com")&&(a=a.replace(/\./g,""),s="gmail.com"),{shown:t,local:a,domain:s,alien:/[^\x00-\x7f]/.test(t)||/(?:^|\.)xn--/.test(s),group:Et.test(a)||Ot.test(s)}}function H(e){let t=[],n=!/[<"]/.test(e),o="",r=!1,s=!1;for(let a=0;a<e.length;a++){let c=e[a];if(r&&c==="\\"){o+=c+(e[++a]??"");continue}c==='"'?r=!r:c==="<"?s=!0:c===">"&&(s=!1),!r&&!s&&(c===","||c===";"||n&&/\s/.test(c))?(t.push(o),o=""):o+=c}return t.push(o),r||s?[null]:t.filter(a=>a.trim()).map(a=>(a.replace(/"(?:[^"\\]|\\.)*"/g,"").match(/@/g)??[]).length===1?Mt(a):null)}var v="Anvil can't read who this goes to",j="Anvil can't read who this goes to: it is built when the line runs",Ce="Anvil can't read who this goes to: its body can't be read",O="Anvil can't read who this goes to: a reply, or a draft sent by its id, goes to whoever the thread or the draft names",Ie="Anvil can't read who this goes to: it runs a batch, or any request";function S(e,t){for(let n of H(e))n?(t.list.push(n),t.known=!0):t.why??=`${v} ("${e.trim().slice(0,40)}")`}function Le(e,t){let n=e.includes(`
|
|
5
|
+
`)?e:Buffer.from(e,"base64").toString("utf8"),o=/\r?\n\r?\n/.exec(n),r=o?n.slice(0,o.index+o[0].length):n;(!/^[\w-]+:/.test(r)||/\r(?!\n)/.test(r)||n.includes(`\r
|
|
6
|
+
`)&&/(?<!\r)\n/.test(r))&&(t.why??=`${v}: its message can't be read`);for(let s of r.replace(/\r?\n[ \t]+/g," ").split(/\r?\n/)){let a=/^(?:resent-)?(?:to|cc|bcc)\s*:/i.exec(s);a&&S(s.slice(a[0].length),t)}}function xe(e){let t=0;for(let n=0;n<e.length;n++){if(e[n]!=='"')continue;for(n++;n<e.length&&e[n]!=='"';n++)e[n]==="\\"&&n++;let o=n+1;for(;/\s/.test(e[o]??"");)o++;e[o]===":"&&t++}return t}function We(e,t){let n;try{n=/^\s*[[{]/.test(e)?JSON.parse(e):void 0}catch{n=void 0}return n!==void 0&&xe(e)!==xe(JSON.stringify(n))&&(t.why??=`${v}: it names a field twice`),n}function R(e,t,n=!1,o=0,r=!1,s=!1){if(o>12)t.why??=v;else if(typeof e=="string"){if(n)S(e,t);else if(!r&&!/[\s@]/.test(e)&&/[/_.]/.test(e)&&re.test(e.toLowerCase()))t.why??=O;else if(!r){let a=We(e,t),c=a===void 0?H(e):[];if(a!==void 0)R(a,t,!1,o+1,!1,s);else if(c.length>0&&c.every(u=>u!==null))for(let u of c)t.list.push(u);else/[^\s@]@[^\s@.]+\.[^\s@]/.test(e)&&(t.why??=`${v} ("${e.trim().slice(0,40)}")`)}}else if(Array.isArray(e))for(let a of e)R(a,t,n,o+1,r,s);else if(e&&typeof e=="object"){let a=!1;for(let[c,u]of Object.entries(e)){let d=ee(c);u==null||u===""||Array.isArray(u)&&u.length===0||(n?St.test(d)&&(a=!0,R(u,t,!0,o+1)):te.has(d)?R(u,t,!0,o+1):d==="raw"&&typeof u=="string"?Le(u,t):(Pe.test(d)||d==="id"&&o===0)&&(typeof u!="object"||Array.isArray(u))?(!s||d.startsWith("draft"))&&(t.why??=O):ne.test(d)?t.why??=`${v}: it names a list ("${c}")`:Nt.test(d)?t.why??=`${v}: another tool picks who it reaches`:d==="calendarid"&&typeof u=="string"&&!/calendar\.google\.com$/i.test(u)?R(u,t,!1,o+1,r,s):!je.test(d)&&!Ee.test(d)&&R(u,t,!1,o+1,r||Oe.test(d),s))}n&&!a&&(t.why??=v)}else n&&e!==null&&e!==void 0&&(t.why??=v)}var X=(e,t)=>e[t]==="`"||e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="(";function It(e){let t=[],n=[],o=!1,r=[],s=[],a="",c=!1,u=!1,d=0,i=[],l=()=>{u&&(d?d===2&&!/^(?:\d+|-)$/.test(a)&&n.push({f:a,dyn:c}):(r.push(a),s.push(c)),d=0),a="",c=u=!1},f=()=>{l(),r.length>0&&t.push({w:r,dyn:s}),r=[],s=[]};for(let m=0;m<e.length;m++){let p=e[m],h=e[m+1];if(p==="\\")h!==void 0&&h!==`
|
|
7
|
+
`&&(a+=h,u=!0),m++;else if(p==="'"||p==="$"&&h==="'"){let g=p==="$"?m+2:m+1,y=e.indexOf("'",g);a+=e.slice(g,y<0?void 0:y),c||=p==="$"||y<0,u=!0,m=y<0?e.length:y}else if(p==='"'){let g=m+1;for(;g<e.length&&e[g]!=='"';g++){let y=e[g+1];e[g]==="\\"&&y!==void 0&&'"\\$`\n'.includes(y)?a+=e[++g]===`
|
|
8
|
+
`?"":y:(o||=X(e,g),c||=e[g]==="$"||e[g]==="`",a+=e[g])}c||=g>=e.length,u=!0,m=g}else if(p==="$"||p==="`")o||=X(e,m),a+=p,c=u=!0;else if(p==="#"&&!u){let g=e.indexOf(`
|
|
9
|
+
`,m);m=(g<0?e.length:g)-1}else if(p==="<"&&h==="<"&&e[m+2]!=="<"){l();let g=/^<<(-?)[ \t]*((?:[^\s;&|<>()'"\\]|'[^']*'|"[^"]*"|\\.)+)/.exec(e.slice(m));g&&i.push([g[2].replace(/'([^']*)'|"([^"]*)"|\\(.)/g,"$1$2$3"),g[1]==="-",/['"\\]/.test(g[2])]),m+=(g?.[0].length??2)-1}else if(p==="<"||p===">"||p==="&"&&h===">"){/^\d+$/.test(a)&&!c&&(u=!1),l();let g=p;for(;/[<>&|]/.test(e[m+1]??"");)g+=e[++m];d=g.includes(">")?2:1}else if(/[;&|()\n]/.test(p)){if(f(),p===`
|
|
10
|
+
`)for(let[g,y,b]of i.splice(0)){let w=m+1;for(;;){let $=e.indexOf(`
|
|
11
|
+
`,w),_=e.slice(w,$<0?void 0:$);if(w=$<0?e.length:$+1,$<0||(y?_.replace(/^\t+/,""):_)===g)break;for(let A=0;!b&&A<_.length;A++)_[A]==="\\"?A++:o||=X(_,A)}m=w-1}}else/\s/.test(p)?l():(a+=p,u=!0)}return f(),{list:t,sub:o,writes:n}}function Lt(e){let t=0;for(;t<e.w.length&&(/^[A-Za-z_]\w*\+?=/.test(e.w[t])||/^(?:env|sudo|doas|nohup|exec|command|time|nice|stdbuf)$/.test(e.w[t])||t>0&&e.w[t].startsWith("-"));)t++;let n=e.w[t];return n!==void 0&&!e.dyn[t]?{name:(/^(?:\/(?:usr\/(?:local\/)?|opt\/(?:homebrew|local)\/)?s?bin\/)?[^/]+$/.test(n)?n.slice(n.lastIndexOf("/")+1):n).toLowerCase(),at:t+1}:null}var Q=["srAaSqTOuC","cb","tfHE"],Ae=["sifmQd","cb","HeF"],Wt={mail:Q,mailx:Q,"s-nail":Q,sendmail:["fFOpRVNLBXh","","tC"],msmtp:["afCX","","t"],mutt:Ae,neomutt:Ae},Re=/^\s*(?:to|cc|bcc)\s*:/i,F="Anvil can't read who this goes to: it may read them from the message or its settings";function Tt(e,t,n,o,r){let s=Wt[e];if(!s){let i=!1;for(let l=o;l<t.length;l++){let f=/^(?:--(to|cc|bcc|recipients?|attendees?)|-(t))(?:=([^]*))?$/.exec(t[l]);if(!f||f[2]&&e!=="swaks")continue;let m=f[3]??t[++l];i=!0,m===void 0||n[l]?r.why??=j:S(m,r)}i||(r.why??=v);return}let[a,c,u]=s,d=!1;for(let i=o;i<t.length;i++){let l=t[i];if(d||!l.startsWith("-")||l==="-")n[i]?r.why??=j:S(l,r);else if(l==="--")d=!0;else if(l.startsWith("--")){let f=/^--([\w-]+)(=?)/.exec(l),m=f?.[1]??"";if(/^(?:append|subject|return-address|from|attach|content-type|encoding|account|host|port|user)$/.test(m)){let p=f?.[2]?l.slice(l.indexOf("=")+1):t[++i];p!==void 0&&Re.test(p)&&(n[i]?r.why??=j:S(p.slice(p.indexOf(":")+1),r))}else/^(?:norc|nosum|ignore|quit|debug|verbose|auth|tls|read-envelope-from|skip-empty-attachments)$/.test(m)||(r.why??=F)}else if(e==="sendmail"&&/^-b[^m]/.test(l))r.why??=F;else if(/mutt/.test(e)&&l.startsWith("-a"))for(;i+1<t.length&&t[i+1]!=="--";)i++;else for(let f=1;f<l.length;f++){let m=l[f];if(u.includes(m)&&(r.why??=F),!a.includes(m)&&!c.includes(m))continue;let p=f+1<l.length?l.slice(f+1):t[++i];/^\s*(?:sendmail|mta)\s*=/i.test(p??"")&&(r.why??=F),n[i]&&"aTC".includes(m)&&a.includes(m)&&(r.why??=j);let h=p!==void 0&&Re.test(p);if(!c.includes(m)&&!h)break;p===void 0||n[i]?r.why??=j:S(h?p.slice(p.indexOf(":")+1):p,r);break}}}function Ne(e){try{return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`http://${e}`)}catch{return null}}var zt="AbcCdDeEFHKmoPQrtTuUwxXyYz",Dt=/^(?:data(?:-ascii|-binary|-raw|-urlencode)?|json|form(?:-string)?|url|header)$/,Se=/^(?:config|upload-file|url-query|variable|request-target|mail-rcpt|expand-[\w.-]+)$/,Ft=/^(?:request|user|user-agent|referer|cookie|cookie-jar|output|output-dir|dump-header|max-time|connect-timeout|retry|retry-delay|retry-max-time|max-redirs|write-out|oauth2-bearer|cacert|capath|cert|key|cert-type|key-type|pass|proto|proto-default|proto-redir|limit-rate|max-filesize|aws-sigv4|mail-from|mail-auth|noproxy|keepalive-time|expect100-timeout|tls-max|ciphers|interface|stderr|trace|trace-ascii|libcurl|etag-save|etag-compare|hsts|alt-svc|range|continue-at|time-cond|speed-limit|speed-time|netrc-file)$/,qt=/^(?:silent|show-error|fail|fail-with-body|fail-early|location|location-trusted|verbose|include|insecure|compressed|http1\.0|http1\.1|http2|http2-prior-knowledge|http3|globoff|get|head|progress-bar|progress-meter|ipv4|ipv6|tlsv1\.2|tlsv1\.3|ssl-reqd|retry-all-errors|retry-connrefused|path-as-is|disable|tcp-nodelay|buffer|keepalive|clobber|remote-name|remote-name-all|create-dirs|netrc|netrc-optional|junk-session-cookies|raw|tr-encoding|trace-time|styled-output|parallel|parallel-immediate|anyauth|basic|digest|ntlm|negotiate|post301|post302|post303|ca-native|form-escape|remove-on-error)$/,Ht=/^(?:[oDc]|output|output-dir|dump-header|cookie-jar|stderr|trace|trace-ascii|libcurl|etag-save|hsts|alt-svc)$/,q="Anvil can't read who this goes to: curl takes part of it from elsewhere";function E(e,t,n){(t||/(?:^|\/)(?:\.?(?:curlrc|mailrc|nailrc|muttrc|msmtprc)|mail\.rc|s-nail\.rc|curl|mailx?|s-nail|sendmail|msmtp|(?:neo)?mutt|swaks)$|\/\.?(?:curl|mutt|msmtp|s-nail)\//.test(e))&&(n.why??=`${v}: this line writes a file a send may read or run (${e.slice(0,60)})`)}function Ut(e,t,n,o,r,s){let a=0,c=0,u=[],d=[],i=!1,l=!1,f=e.some((p,h)=>h>=n&&(/^-[^-]*O/.test(p)||p.startsWith("--remote-name"))),m=p=>{if(!r(p))return;let h=Ne(p);if(h?.hostname.toLowerCase().replace(/\.$/,"")!==o)s.why??=`${v}: a URL Anvil reads two ways`;else{c++;let g=h.pathname.toLowerCase();try{g=decodeURIComponent(g)}catch{s.why??=v}re.test(g)?s.why??=O:Me.test(g)&&(s.why??=Ie);for(let[y,b]of h.searchParams)u.push([y,b,!1,!1])}};for(let p=n;p<=e.length;p++){let h=e[p];if(h===void 0||h==="--next"||h==="-:"){if(c>0){a++;for(let w of d)Gt(w,i&&!l,u,s);Bt(u,s)}[c,u,d,i,l]=[0,[],[],!1,!1];continue}let g="",y;if(h.startsWith("--")){let w=/^--([\w.-]+)(=?)/.exec(h);if(g=w?.[1]??"",qt.test(g.replace(/^no-/,"")))continue;if(g==="remote-header-name"||!Dt.test(g)&&!Se.test(g)&&!Ft.test(g)){s.why??=g==="remote-header-name"?q:`${v}: curl takes an option Anvil doesn't know (--${g.slice(0,40)})`;continue}y=w?.[2]?h.slice(h.indexOf("=")+1):e[++p]}else if(h.startsWith("-")&&h.length>1){for(let w=1;w<h.length&&!g;w++)h[w]==="J"&&(s.why??=q),zt.includes(h[w])&&(g=h[w],y=h.slice(w+1)||e[++p]);if(!g)continue}else{if(f){let w=Ne(h)?.pathname.split("/").pop()??"";E(w,!1,s);try{E(decodeURIComponent(w),!1,s)}catch{s.why??=v}}m(h);continue}if(y===void 0){s.why??=v;break}let b=t[p]??!1;if(/^[KT]$/.test(g)||Se.test(g))s.why??=q;else if(g==="url")m(y);else if(g==="H"||g==="header"){let w=/^\s*content-type\s*:/i.exec(y);y.startsWith("@")?s.why??=q:w?/json/i.test(y.slice(w[0].length))&&!b?i=!0:l=!0:b&&!/^\s*[\w-]+\s*:/.test(y)&&(l=!0)}else if(Ht.test(g))E(y,b,s);else if(g==="F"||g.startsWith("form")||g==="data-urlencode"){let w=y.indexOf("="),$=y.indexOf("@"),_=g==="data-urlencode"?$>=0&&(w<0||$<w):g!=="form-string"&&/^[@<]/.test(y.slice(w+1));u.push([w>0?y.slice(0,w):"",y.slice(w+1),b,_])}else(g==="d"||g.startsWith("data")||g==="json")&&(b||g!=="data-raw"&&y.startsWith("@")?s.why??=`${v}: its body is ${b?"built when the line runs":"read from a file"}`:(i||=g==="json",d.push(y)))}return a}function Gt(e,t,n,o){let r=We(e,o);if(r!==void 0?R(r,o):t&&(o.why??=Ce),!t){r===void 0&&/^[\w-]+\s*:/.test(e)&&Le(e,o);for(let s of e.split("&")){let a=s.indexOf("=");try{let c=decodeURIComponent(s.slice(0,Math.max(a,0)).replace(/\+/g," "));/^[\w.[\]-]*$/.test(c)&&(r===void 0||c.split(/[.[\]]+/).map(ee).some(u=>te.has(u)||ne.test(u)))&&n.push([c,decodeURIComponent(s.slice(a+1).replace(/\+/g," ")),!1,!1])}catch{o.why??=Ce}}}}function Bt(e,t){for(let[n,o,r,s]of e){let a=n.split(/[.[\]]+/).map(ee).filter(Boolean),c=a[a.length-1]??"";if(a.some(u=>te.has(u)))s||r?t.why??=`${v}: it is ${s?"read from a file":"built when the line runs"}`:S(o,t);else if(a.some(u=>ne.test(u)))t.why??=`${v}: it names a list ("${n}")`;else if(a.some(u=>Pe.test(u)))t.why??=O;else{if(a.some(u=>je.test(u))||Ee.test(c)||a.some(u=>Oe.test(u)))continue;r?t.why??=j:s||R(o,t)}}}var Kt=/^(?:echo|printf|cat|jq|grep|egrep|fgrep|head|tail|wc|cut|tr|date|sleep|true|false|:|cd|pwd|ls|test|\[|export|unset|column|fold|rev|nl|paste|basename|dirname|realpath|mkdir|touch|tee|curl)$/;function Zt(e,t,n,o){let r=t.includes("."),s=new RegExp(`(?<![\\w.-])${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w-]|\\.\\w)`),a=l=>s.test(l.replace(/['"\\]/g,"").toLowerCase()),{list:c,sub:u,writes:d}=It(e);u&&(o.why??=`${v}: this line runs a command inside another ($(\u2026) or \`\u2026\`), which Anvil doesn't read`);for(let l of d)E(l.f,l.dyn,o);let i=0;for(let l of c){let f=Lt(l);if(((f?.name==="export"?l.w:l.w.slice(0,f?f.at-1:void 0)).some(m=>/^(?:\w*PATH|path|\w*HOME|\w*RC|LD_\w*|DYLD_\w*|(?:BASH_)?ENV)\+?=/.test(m))||f?.name==="printf"&&l.w.slice(f.at).some(m=>/^-\w*v/.test(m)))&&(o.why??=`${v}: this line sets where a program or its settings come from`),f?.name==="tee")for(let m=f.at;m<l.w.length;m++)l.w[m].startsWith("-")||E(l.w[m],l.dyn[m],o);!f&&l.w.every(m=>/^[A-Za-z_]\w*\+?=/.test(m))||(f&&r&&f.name==="curl"?i+=Ut(l.w,l.dyn,f.at,t,a,o):f&&!r&&f.name===t?(i++,Tt(f.name,l.w,l.dyn,f.at,o)):(!f||!Kt.test(f.name))&&(o.why??=`${v}: this line also runs ${f?f.name:"a command built when it runs"}, which Anvil doesn't read`))}(i===0||i<n)&&(o.why??=`${v}: Anvil reads a plain curl request or mail program, not this`)}function Te(e,t){let n={list:[],why:null},o=(e.host??"").toLowerCase(),r=e.action==="claude.mcp.side_effect",s=`${o} ${r?t.tool??"":/^[a-z][a-z0-9+.-]*:\/\//i.test(e.target??"")?e.target:""}`.toLowerCase(),a=Pt.exec(s)?.[1];return a?n.why=`Anvil can't read who ${a} sends reach: they go to a list or a ticket`:re.test(s)?n.why=O:Me.test(s)?n.why=Ie:r&&t.input?R(t.input,n,!1,0,!1,/forward/.test((t.tool??"").split("__").pop().toLowerCase())):!r&&t.command&&o?Zt(t.command,o,t.parts.filter(c=>c.action===e.action&&(c.host??"").toLowerCase()===o).length,n):n.why=v,n.known||(n.why??=v),n}function Yt(e){let t=a=>Array.isArray(a)&&a.every(c=>typeof c=="string")?a:null,n=t(e.domains??[]),o=t(e.addresses??[]);if(!n||!o)return"a recipient condition's domains and addresses must be lists";if(e.outside!==void 0&&e.outside!==!0)return"a recipient condition's outside must be true";let r=n.map(oe),s=o.map(a=>{let[c,u]=H(a);return c&&!u?`${c.local}@${c.domain}`:""});return r.includes("")||s.includes("")?"a recipient condition names an address or a domain Anvil can't read":r.length+s.length===0?"a recipient condition needs an address or a domain":{type:"recipient",said:String(e.said),...e.outside===!0?{outside:!0}:{},domains:r,addresses:s}}var ze=new WeakMap;function De(e,t,n){let o=ze.get(e);if(o===void 0&&ze.set(e,o=Yt(e)),typeof o=="string")return{hit:"unknown",why:`Anvil can't use this rule's recipients (${o})`};let r;try{r=Te(t,n)}catch{return{hit:"unknown",why:"Anvil can't read who this goes to"}}let s=r.why;for(let a of r.list){let c=o.addresses.includes(`${a.local}@${a.domain}`)||o.domains.some(u=>a.domain===u||a.domain.endsWith(`.${u}`));if(o.outside?!c:c)return{hit:"match",detail:o.outside?`${a.shown} is outside ${[...o.domains,...o.addresses.length>0?["the addresses your rule names"]:[]].join(" and ")}`:`it goes to ${a.shown}`};a.group?s??=`${a.shown} may reach ${o.outside?"people outside":"anyone"} (a list or a relay)`:a.alien&&!o.outside&&(s??=`${a.shown} is in letters from another alphabet`)}return s===null?null:{hit:"unknown",why:s}}var Jt="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");function Vt(e,t){if(e&&/^:?[+-]?\d/.test(e))return!0;let n=e?/^:?(?:<[^>]*>|[a-z]{3,})([+-]?)(\d{1,2})(?::(\d\d))?(<|[a-z]{3})?/i.exec(e):null;if(!n)return!1;let o=(n[1]==="-"?1:-1)*(Number(n[2])*60+Number(n[3]??0)),r=-t.getTimezoneOffset();return r!==o&&!(n[4]!==void 0&&r===o+60)}function Fe(e,t,n){let o=new Date(n.now??NaN),r=o.getDay(),s=o.getHours(),a=s*60+o.getMinutes();if(!((n.now??0)>0&&r>=0))return{hit:"unknown",why:"Anvil can't tell when this call was made"};let c=process.env.TZ,u=`:${String(a%60).padStart(2,"0")}`;if(c!==void 0||o.getTimezoneOffset()===0){let d="";try{let i=Intl.DateTimeFormat().resolvedOptions().timeZone;i&&!Vt(c,o)&&(d=o.toLocaleTimeString("en-GB",{timeZone:i,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}))}catch{}if(d!==`${String(s).padStart(2,"0")}${u}`)return{hit:"unknown",why:`Anvil can't read your Mac's time zone${c===void 0?"":` (TZ is "${c}")`}`}}return e.at.some(d=>d.days.includes(r)&&a>=d.from&&a<d.to)?{hit:"match",detail:`it's ${Jt[r]} ${s%12||12}${u}${s<12?"am":"pm"}`}:null}import{existsSync as Qn,readdirSync as er,realpathSync as tr}from"fs";import{basename as rr,dirname as or,join as sr}from"path";function M(e,t=8*1024*1024){let n;try{n=nn(e,qe.O_RDONLY|qe.O_NONBLOCK)}catch(o){if(o.code==="ENOENT"||o.code==="ENOTDIR")return null;throw o}try{let o=tn(n);if(!o.isFile())throw new Error(`${e} is not a regular file`);if(o.size>t)throw new Error(`${e} is over ${t} bytes`);let r=Buffer.alloc(o.size),s=0;for(;s<o.size;){let a=rn(n,r,s,o.size-s,s);if(a===0)break;s+=a}return r.subarray(0,s)}finally{en(n)}}var Kr=256*1024,Zr=1024*1024;function Ge(e,t){try{let n=typeof e.repo_dir=="string"?D(e.repo_dir):e.repo_dir,o=t===null?null:D(t),r=e.repo_via,s=typeof e.repo_remote=="string"&&e.repo_remote?e.repo_remote:r==="gh"&&process.env.GH_REPO||null;if(typeof n!="string"||!sn(n)||!U(n)||r!=="git"&&r!=="gh"||/[$`]/.test(s??""))return null;if(r==="gh"&&s!==null)return Ue([s],n);let a=ln(n,o);if(a===null)return null;let c=new Map;for(let i of a)i.section==="remote"&&i.sub!==null&&(i.key==="url"||(r==="git"?i.key==="pushurl":i.key==="gh-resolved"&&i.value!=="base"))&&c.set(i.sub,[...c.get(i.sub)??[],i.value]);if(s!==null&&!c.has(s)&&!/^[./]|[/:]/.test(s))return null;let u=s!==null?c.get(s)??[s]:[...c.values()].flat();if(s===null)for(let i of a)(i.section==="branch"&&/^(push)?remote$/.test(i.key)||i.section==="remote"&&i.sub===null&&i.key==="pushdefault")&&i.value!=="."&&!c.has(i.value)&&u.push(i.value);let d=new Set(u);for(let i of u)for(let l of a)l.section==="url"&&l.sub!==null&&/^(push)?insteadof$/.test(l.key)&&l.value&&i.startsWith(l.value)&&d.add(l.sub+i.slice(l.value.length));return d.size>0?Ue([...d],n):null}catch{return null}}function Ue(e,t){let n=[];for(let o of e){let r=decodeURIComponent(o.trim()),s=process.platform==="win32"&&/^[A-Za-z]:[\\/]/.test(r)?null:/^[a-z][a-z0-9+.-]*:\/\/[^/]*(\/.*)?$|^(?:[^@/:\s]+@)?[^/:\s]+:(?!\/\/)(.*)$/i.exec(r),c=(s?an.resolve("/",s[1]??s[2]??""):/^[\w.-]+(\/[\w.-]+){1,2}$/.test(r)&&!r.startsWith(".")?r:I(t,r)).replace(/[?#].*$/,"").split(/[\\/]/).filter(f=>f&&f!=="."),u=c.findIndex((f,m)=>m>=2&&/^pulls?$/.test(f));u>=2&&(c=c.slice(0,u));let[d,i]=c.slice(-2).map(f=>f.replace(/\.git$/i,"").toLowerCase()),l=i??d;if(!l||l==="..")return null;n.push(i!==void 0&&d!==".."?`${d}/${i}`:l)}return n}function ln(e,t){let n=process.env;if(n.GIT_CONFIG_COUNT||n.GIT_CONFIG_PARAMETERS||n.GIT_DIR||n.GIT_COMMON_DIR)return null;let o=cn(e);if(o===null)return null;let r=process.platform==="win32"?[C(n.ProgramFiles||"C:\\Program Files","Git","etc","gitconfig"),C(n.ProgramData||"C:\\ProgramData","Git","config")]:["/etc","/opt/homebrew/etc","/usr/local/etc","/Library/Developer/CommandLineTools/usr/share/git-core"].map(d=>`${d}/gitconfig`),s=n.GIT_CONFIG_NOSYSTEM?[]:n.GIT_CONFIG_SYSTEM?[n.GIT_CONFIG_SYSTEM]:r;n.GIT_CONFIG_GLOBAL?s.push(n.GIT_CONFIG_GLOBAL):t&&s.push(C(n.XDG_CONFIG_HOME||C(t,".config"),"git","config"),C(t,".gitconfig")),s.push(C(o.common,"config"),C(o.gitDir,"config.worktree"));let a=[],c=24,u=(d,i)=>{let l=--c<0||i>5?void 0:M(d,1048576);if(l===void 0)return!1;for(let f of un(l?.toString("utf8")??""))if(a.push(f),f.key==="path"&&/^include(if)?$/.test(f.section)){let m=f.value.startsWith("~/")?t&&C(t,f.value.slice(2)):!/^[~%]/.test(f.value)&&I(se(d),f.value);if(!m||!u(m,i+1))return!1}return!0};return s.every(d=>u(d,0))?a:null}function cn(e){let t=n=>/^(ref: refs\/|[0-9a-f]{40})/.test(M(C(n,"HEAD"),4096)?.toString("utf8")??"");for(let n=I(e),o=0;o<64;o++,n=se(n)){let r=C(n,".git"),s=["objects","refs"].every(a=>U(C(n,a)))&&t(n)?n:null;if(U(r)){let a=He(r);if(a.isDirectory())t(r)&&(s=r);else if(s=a.isFile()?/^gitdir:\s*(.+)$/m.exec(M(r,65536)?.toString("utf8")??"")?.[1]?.trim():null,!s)return null}if(s){let a=I(n,s),c=M(C(a,"commondir"),65536),u=c===null?a:I(a,c.toString("utf8").trim());for(let d of["remotes","branches"]){let i=C(u,d);if(U(i)&&(!He(i).isDirectory()||on(i).length>0))return null}return{gitDir:a,common:u}}if(se(n)===n)return null}return null}function un(e){let t=[],n="",o=null;for(let r of e.replace(/\\\r?\n/g,"").split(/\r?\n/)){r=r.trim();let s=/^\[\s*([\w.-]+)(?:\s+"((?:[^"\\]|\\.)*)")?\s*\]/.exec(r);if(s){let[c,...u]=s[1].toLowerCase().split(".");n=c,o=s[2]?.replace(/\\(.)/g,"$1")??(u.length>0?u.join("."):null),r=r.slice(s[0].length).trim()}let a=/^([a-z][\w-]*)\s*(?:=(.*))?$/i.exec(r);a&&t.push({section:n,sub:o,key:a[1].toLowerCase(),value:a[2]===void 0?"true":a[2].replace(/"((?:[^"\\]|\\.)*)"|\\(.)|[#;].*$/g,(c,u,d)=>u??d??"").trim()})}return t}var dn={slack:"channel",github:"repo",linear:"team",jira:"project"};var fn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function x(e,t,n=!1){let o=e==="jira"&&typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?String(t):t;if(typeof o!="string")return null;let r=o.normalize("NFKC").trim().replace(/^(["'])(.*)\1$/,"$2");if(!r||r.length>300||/[$`\u0000-\u001f]/.test(r)||/[^\u0000-\u007f]/.test(r)&&new RegExp("\\p{Script=Latin}","u").test(r)&&new RegExp("(?!\\p{Script=Latin})\\p{L}","u").test(r))return null;if(e==="slack"){if(r=/^<#([A-Z0-9]+)(?:\|[^>]*)?>$/.exec(r)?.[1]??/\/archives\/([A-Z0-9]{6,})(?:[/?#]|$)/.exec(r)?.[1]??r,r.startsWith("@")||/^[DUW][A-Z0-9]{6,}$/.test(r))return"dm";if(/^[A-Z0-9]+$/.test(r))return/^[CG][A-Z0-9]{6,}$/.test(r)?`id:${r}`:null;let c=r.replace(/^#/,"").toLowerCase();return/^[a-z0-9][a-z0-9._-]{0,79}$/.test(c)||/^[\p{L}\p{N}][\p{L}\p{N}._-]{0,79}$/u.test(c)?`name:${c}`:null}if(e==="github"){let c=/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/\s]+)\/([^/\s?#]+)/i.exec(r)??/^https?:\/\/(?:api|uploads)\.github\.com\/repos\/([^/\s]+)\/([^/\s?#]+)/i.exec(r)??/^([\w.-]+)\/([\w.-]+)$/.exec(r),u=i=>/^[\w.-]+$/.test(i)&&!/^\.+$/.test(i),d=i=>i.toLowerCase().replace(/\.git$/,"");return c?u(c[1])&&u(c[2])?`repo:${d(c[1])}/${d(c[2])}`:null:u(r)?`repo:?/${d(r)}`:null}let s=e==="linear"?"[A-Za-z][A-Za-z0-9]{0,6}":"[A-Z][A-Z0-9_]{1,9}",a=new RegExp(`^(${s})-\\d+$`).exec(r)??new RegExp(`(?:/issue/|/browse/)(${s})-\\d+`).exec(r);return a?`key:${a[1].toLowerCase()}`:n?null:(e==="linear"?fn.test(r):/^\d+$/.test(r))?`id:${r.toLowerCase()}`:new RegExp(`^${e==="linear"?"[A-Z0-9]{1,7}":"[A-Z][A-Z0-9_]{1,9}"}$`).test(r)?`key:${r.toLowerCase()}`:`name:${r.toLowerCase().replace(/\s+/g," ")}`}function P(e,t){if(!t||e!=="linear"&&e!=="jira"||!t.startsWith("name:"))return[t??"?"];let n=t.slice(5);return(e==="linear"?/^[a-z][a-z0-9]{0,6}$/:/^[a-z][a-z0-9_]{1,9}$/).test(n)?[`key:${n}`,t]:[t]}var ae={slack:/^(?:(?:to|target|dest|destination|source|from|in)_?)?(?:channel|conversation)s?(?:_?(?:ids?|names?|url|link))?$|^(?:target|chat_?id|permalink|message_?(?:url|link))$/i,github:/^(?:(?:parent|item|base|head|target|source)_?)?(?:repo|repository)(?:_?name)?s?$|^(?:repo_?full_?name|full_?name|name_?with_?owner|html_?url|pull_?request_?url|issue_?url)$/i,linear:/^(?:new_?)?team(?:_?(?:id|key|name))?s?$/i,jira:/^projects?(?:_?(?:key|id|id_?or_?key))?s?$/i},Ke={linear:/^(?:id|ids|issues?|issue_?ids?|identifiers?|issue_?identifiers?|parent_?id|url)$/i,jira:/^(?:key|keys|issues?|issue_?keys?|issue_?ids?|issue_?id_?or_?key|parent|parent_?key|url)$/i},pn=/^(?:user|users|user_?ids?|recipient|recipients)$/i,gn=/^(?:arguments|args|params|parameters|input|data|payload|body|request|message|fields|issue|issues|items|options|update)$/i,ie=/^channels?$|^channel_ids?$/,mn=/^(?:text|body|title|description|content|comment|summary|markdown|blocks|attachments)$/i;function hn(e,t){let n=0,o=(r,s)=>++n>2e3||s>6?!1:typeof r=="string"?P(e.app,x(e.app,r)).some(a=>Ve(e,a)):Array.isArray(r)?r.slice(0,200).some(a=>o(a,s+1)):!!(r&&typeof r=="object")&&Object.entries(r).some(([a,c])=>!mn.test(a)&&!ae[e.app].test(a)&&!Ke[e.app]?.test(a)&&o(c,s+1));return o(t,0)}function Ze(e,t,n=!1){if(!t)return null;let o=[],r=0,s=(a,c,u)=>{for(let[d,i]of Object.entries(a)){if(++r>2e3)return void o.push("?");let l=u?"":"~",f=Array.isArray(i)?i:[i];f.length>200&&o.push("?");let m=f.slice(0,200).flatMap(p=>p&&typeof p=="object"&&!Array.isArray(p)?["key","id","name"].map(h=>p[h]).filter(h=>h!==void 0):e==="slack"&&typeof p=="string"?p.split(","):[p]);if(ae[e].test(d)||Ke[e]?.test(d)){let p=!ae[e].test(d),h=e==="github"?/^(.*?)(_?)(?:repo|repository)(?:_?name)?$/i.exec(d):null,g=h?a[`${h[1]}${h[2]}owner`]:void 0;for(let y of m.length>0?m:[void 0])for(let b of P(e,x(e,typeof g=="string"&&typeof y=="string"&&!y.includes("/")?`${g.trim()}/${y.trim()}`:y,p)))o.push(b==="?"?"?":`${l}${b}`)}else if(e==="slack"&&pn.test(d))for(let p of m)o.push(x("slack",p)==="dm"?`${l}dm`:"?");else if(c<6&&i&&typeof i=="object")for(let p of f.slice(0,200))p&&typeof p=="object"&&!Array.isArray(p)&&s(p,c+1,n||u&&c<2&&gn.test(d))}};return s(t,0,!0),o.length>0?o.every(a=>a.startsWith("~"))?[...o,"?"]:o:null}function yn(e){let t=[],n="",o=null;for(let r=0;r<e.length;r++){let s=e[r];if(s==="\\"&&o!=="'"){n+=s+(e[++r]??"");continue}if(o)o=s===o?null:o;else if(s==="'"||s==='"')o=s;else if(s===";"||s==="&"||s==="|"||s===`
|
|
12
|
+
`){n.trim()&&t.push(n),n="";continue}n+=s}return n.trim()&&t.push(n),t}function Ye(e){let t=[],n="",o=null,r=!1;for(let s=0;s<e.length;s++){let a=e[s];o==="'"?a==="'"?o=null:n+=a:o==='"'?a==='"'?o=null:n+=a==="\\"&&s+1<e.length?e[++s]:a:a==="'"||a==='"'?(o=a,r=!0):a==="\\"?(n+=e[++s]??"",r=!0):/\s/.test(a)?((n||r)&&t.push(n),n="",r=!1):(n+=a,r=!0)}return o?null:((n||r)&&t.push(n),t)}var Be=e=>{try{return new URL(/^https?:\/\//i.test(e)?e:`/${e.replace(/^\/+/,"")}`,"https://x").pathname}catch{return"\0"}};function wn(e){let t=Ye(e),n=t?t.findIndex(d=>/(?:^|\/)gh$/.test(d)):-1;if(!t||n<0)return["?"];let o=t.slice(0,n).flatMap(d=>d.startsWith("GH_REPO=")?[d.slice(8)]:[]).pop(),r=t.slice(n+1),s;for(let d=0;d<r.length;d++){let i=r[d];i==="-R"||i==="--repo"?s=r[++d]??"":i.startsWith("--repo=")?s=i.slice(7):/^-R[^-]/.test(i)?s=i.slice(2):/^-[A-Za-z]+R/.test(i)&&(s="?")}let a=r[0]==="repo"&&r[1]!=="rename"&&r[2]!==void 0&&!r[2].startsWith("-")?r[2]:void 0,c=s??o??a,u=r.filter(d=>/^https?:\/\/(?:www\.)?github\.com\/[^/]+\/[^/]+\/(?:pull|issues)\/\d+/i.test(d)).map(d=>`~${x("github",d)??"?"}`);return[c===void 0?"none":x("github",c)??"?",...u]}var bn=(e,t)=>Ge(e.attributes,t.home)?.map(n=>x("github",n)??"?")??["?"];function $n(e,t){let n=Ye(t),o=n?n.findIndex(i=>/(?:^|\/)(?:curl|wget)$/.test(i)):-1;if(!n||o<0)return["?"];let r=[],s=[],a=n.slice(o+1);for(let i=0;i<a.length;i++){let l=a[i],f=/^(--data(?:-ascii|-binary|-raw|-urlencode)?|--json|--form(?:-string)?|--post-data|--body-data)(?:=([\s\S]*))?$/.exec(l);f?r.push(f[2]??a[++i]??""):l==="-d"||l==="-F"?r.push(a[++i]??""):/^-[dF]./.test(l)?r.push(l.slice(2)):/^https?:\/\//i.test(l)&&s.push(l)}let c=[],u=i=>{for(let l of[i].flat().flatMap(f=>typeof f=="string"?f.split(","):[f]))c.push(...P(e,x(e,l)))},d=i=>{let l=i&&typeof i=="object"&&!Array.isArray(i)?i:null;if(!l)return void c.push("?");if(e==="slack"){let f=Object.keys(l).filter(m=>ie.test(m));f.length===0&&c.push("?");for(let m of f)u(l[m])}else if(e==="jira"){let f=(l.fields&&typeof l.fields=="object"?l.fields:l).project,m=f&&typeof f=="object"?f:null;c.push(...m?[m.key,m.id].filter(p=>p!==void 0).flatMap(p=>P(e,x(e,p))):["?"])}else{let f=Ze("linear",l.variables??{},!0)??[],p=[...(typeof l.query=="string"?l.query:"").matchAll(/\b(teamId|teamKey|team|id|issueId|identifier)\s*:\s*"([^"\\]{1,100})"/g)].flatMap(h=>P(e,x(e,h[2],!/^team/.test(h[1])))).map(h=>`~${h}`);c.push(...f,...p,...f.length===0?["?"]:[])}};for(let i of s)try{for(let[l,f]of new URL(i).searchParams)e==="slack"&&ie.test(l)&&u(f)}catch{c.push("?")}for(let i of r){if(/^@|^[\w-]*@/.test(i)){c.push("?");continue}let l;try{l=JSON.parse(i)}catch{l=void 0}if(l!==void 0)d(l);else if(e==="slack"&&/^[\w-]+=/.test(i)){let f=i.split("&").map(m=>[m.slice(0,m.indexOf("=")<0?m.length:m.indexOf("=")),m.slice(m.indexOf("=")+1)]);for(let[m,p]of f){if(!ie.test(m))continue;let h=p;try{h=decodeURIComponent(p.replace(/\+/g," "))}catch{c.push("?");continue}u(h)}}else c.push("?")}return c.length>0?c:["?"]}var Je=e=>/^[a-z][a-z-]*\s+[a-z][a-z-]*$/.test(e)||!/[/:]/.test(e)&&e!=="graphql"&&e.length>0;function kn(e,t,n){let o=t.target??"";if(e==="slack"&&/hooks\.slack\.com/i.test(`${t.host??""} ${o}`))return["?"];let r=e==="github"&&Je(o);if(e==="github"&&!r){let i=Be(o),l=/^\/repos\/([^/]+)\/([^/]+)/.exec(i)??(/^https?:\/\/(?:www\.)?github\.com\//i.test(o)?/^\/([^/]+)\/([^/]+)/.exec(i):null);return[l?x("github",`${l[1]}/${l[2]}`)??"?":"?"]}let s=e==="jira"?/\/rest\/api\/(?:2|3|latest)\/(issue|project)\/([^/]+)/.exec(Be(o)):null;if(s)return P("jira",x("jira",s[2],s[1]==="issue"));let a=n.command??(typeof n.input?.command=="string"?n.input.command:"");if(a.length>65536)return["?"];let c=yn(a),u=c.filter(i=>r?/(?:^|[\s/])gh\s/.test(i)&&(/\s/.test(o)?i.includes(o.split(/\s+/)[1]):i.includes(o)):o.length>0&&i.includes(o)),d=i=>r?wn(i).flatMap(l=>l==="none"?bn(t,n):[l]):$n(e,i);return u.length>0?u.flatMap(d):[...c.flatMap(d).filter(i=>i!=="?"&&!i.startsWith("~")).map(i=>`~${i}`),"?"]}function vn(e,t){return t==="dm"?e.app==="slack":e.app==="slack"?t.startsWith("name:"):e.app==="github"?t.startsWith("repo:")&&!(t.startsWith("repo:?/")&&e.is.some(n=>n.endsWith(`/${t.slice(7)}`))):e.as!==void 0&&t.startsWith(`${e.as}:`)}function Ve(e,t){return e.is.includes(t)?!0:e.app!=="github"||!t.startsWith("repo:")?!1:e.is.includes(`repo:${t.startsWith("repo:?/")?t.slice(7):t.slice(t.indexOf("/")+1)}`)}var G=e=>e.startsWith("key:")?e.slice(4).toUpperCase():e.replace(/^(?:name|id|repo):(?:\?\/)?/,"");function Xe(e,t,n){let o=dn[e.app],r=e.said.replace(/^in /,""),s=t.action==="claude.mcp.side_effect"?Ze(e.app,n.input):kn(e.app,t,n),a=`Anvil can't tell which ${o} this acts in${e.app==="github"&&t.action!=="claude.mcp.side_effect"&&Je(t.target??"")?" (gh says it with --repo)":""}`;if(!s||s.length===0)return{hit:"unknown",why:a};let c=s.map(i=>i.replace(/^~/,"")).find(i=>Ve(e,i));if(c)return{hit:"match",detail:c.startsWith("id:")?`${G(c)} is ${r}`:e.app==="github"?G(c):r};let u=s.find(i=>i==="?"||i.startsWith("~")||!(e.not??[]).includes(i)&&!vn(e,i));if(u===void 0)return t.action==="claude.mcp.side_effect"&&hn(e,n.input)?{hit:"unknown",why:`Anvil can't tell whether this acts in ${r}: the call names it in a field Anvil doesn't read`}:null;let d=u.replace(/^~/,"");return{hit:"unknown",why:d==="?"?a:`Anvil can't tell whether ${d.startsWith("id:")?`${o} ${G(d)}`:G(d)} is ${r}`}}function ao(e,t,n){switch(e.type){case"amount":return ve(e,t,n);case"recipient":return De(e,t,n);case"part":return Xe(e,t,n);case"when":return Fe(e,t,n)}}async function lo(){}export{vt as capMoved,ao as matchCondition,lo as preloadConditions};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{createHash as Pe}from"crypto";import{readdirSync as M,readFileSync as Me,rmdirSync as Le,rmSync as Ie,statSync as Te,unlinkSync as ae}from"fs";import{basename as B,dirname as L,join as h,resolve as De}from"path";import{existsSync as It,readdirSync as Tt,statSync as Dt}from"fs";import{dirname as Ft,isAbsolute as zt,join as qt,posix as Ht,resolve as Ut}from"path";import{posix as X}from"path";var we=null;function j(){return we??process.platform==="win32"}var V=/^([A-Za-z]):(.*)$/s,be=/^\/(?:cygdrive\/)?([A-Za-z])(\/.*)?$/s;function D(e,t){let n=X.normalize(`/${t}`);return n==="/"?e:`${e}${n.replace(/\/$/,"")}`}function C(e,t){return e.split("/").map(n=>{if(n===""||n==="."||n===".."||/[\u0000\u0001]/.test(n))return n;let r=n.indexOf(":"),o=r>=0?n.slice(0,r):n,i=t?o:o.replace(/[. ]+$/,"");return i===""?".":i}).join("/")}function W(e){if(!j())return e;let t=e.replace(/^(?:Microsoft\.PowerShell\.Core\\)?FileSystem::/i,""),n=!1,r=/^[\\/]{2}([?.])[\\/](.*)$/s.exec(t);if(r){let s=r[2];if(r[1]===".")return`/dev/${s.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;if(/^unc[\\/]/i.test(s))t=`\\\\${s.slice(4)}`;else if(V.test(s))t=s;else return`/dev/${s.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;n=!0}t=t.replace(/\\/g,"/");let o=/^\/\/([^/]+)(?:\/([^/]+))?(\/.*)?$/s.exec(t);if(o){let s=`/unc/${C(o[1],n).toLowerCase()}${o[2]?`/${C(o[2],n).toLowerCase()}`:""}`;return D(s,C(o[3]??"",n).toLowerCase())}let i=V.exec(t);if(i){let s=i[2];return s===""?`/${i[1].toLowerCase()}`:s.startsWith("/")?D(`/${i[1].toLowerCase()}`,C(s,n).toLowerCase()):null}let l=be.exec(t);if(l)return D(`/${l[1].toLowerCase()}`,C(l[2]??"",n).toLowerCase());let c=C(t,n).toLowerCase();if(c.startsWith("/")){let s=X.normalize(c);return s.length>1&&s.endsWith("/")?s.slice(0,-1):s}return c}function $e(e){return W(e)??e}function F(e){return!j()||typeof e!="string"||e===""?e:$e(e)}import{createHash as wt}from"crypto";import{appendFileSync as ke,closeSync as ee,constants as Q,fstatSync as te,mkdirSync as ve,openSync as ne,readdirSync as $t,readFileSync as kt,readSync as re,renameSync as vt,statSync as xe,unlinkSync as xt,writeFileSync as _t}from"fs";import{homedir as At}from"os";import{dirname as St,join as Nt}from"path";var _e=3500;function A(e,t=8*1024*1024){try{let n=xe(e);return n.isFile()&&n.size<=t}catch(n){return n.code==="ENOENT"?null:!1}}function R(e,t=8*1024*1024){let n;try{n=ne(e,Q.O_RDONLY|Q.O_NONBLOCK)}catch(r){if(r.code==="ENOENT"||r.code==="ENOTDIR")return null;throw r}try{let r=te(n);if(!r.isFile())throw new Error(`${e} is not a regular file`);if(r.size>t)throw new Error(`${e} is over ${t} bytes`);let o=Buffer.alloc(r.size),i=0;for(;i<r.size;){let l=re(n,o,i,r.size-i,i);if(l===0)break;i+=l}return o.subarray(0,i)}finally{ee(n)}}function y(e,t){let n=t.endsWith(`
|
|
2
|
+
`)?t:`${t}
|
|
3
|
+
`;if(Buffer.byteLength(n)>_e)throw new Error(`refusing to append a ${Buffer.byteLength(n)}-byte line`);if(A(e,Number.MAX_SAFE_INTEGER)===!1)throw new Error(`refusing to append to ${e}: not a regular file`);ke(e,n,{mode:384})}function S(e){ve(e,{recursive:!0,mode:448})}function P(e,t){if(A(e,Number.MAX_SAFE_INTEGER)!==!0)return"";let n;try{n=ne(e,"r")}catch{return""}try{let r=te(n).size,o=Math.max(0,r-t),i=r-o;if(i<=0)return"";let l=Buffer.alloc(i);re(n,l,0,i,o);let c=l.toString("utf8");if(o>0){let s=c.indexOf(`
|
|
4
|
+
`);c=s<0?"":c.slice(s+1)}return c}finally{ee(n)}}var Ot=256*1024,jt=1024*1024;import{domainToASCII as Xt}from"url";var sn="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");import{existsSync as _n,readdirSync as Cn,realpathSync as An}from"fs";import{basename as Sn,dirname as Nn,join as En}from"path";function oe(e,t){return e.origin!=="project"||!!(t&&e.project_dir&&Re(t,e.project_dir))}function Re(e,t){let n=F(e),r=F(t),o=r.endsWith("/")?r.slice(0,-1):r;return n===o||n.startsWith(o+"/")}var k={on:"\u25CF",watching:"\u25CB",held:"\u25A0",ok:"\u2713",blocked:"\u2715",problem:"\u25B2",next:"\u203A"};function Se(e){if(!e){let s=a=>a;return{on:!1,bold:s,dim:s,blue:s,grey:s,amber:s,mark:s,field:s}}let t=e==="truecolor",n=s=>a=>`\x1B[${s}m${a}\x1B[0m`,r=n(t?"38;2;76;139;255":"38;5;69"),o=n(t?"38;2;130;134;150":"90"),i=n(t?"38;2;245;165;36":"38;5;214"),l=n(t?"38;2;34;197;94":"32"),c={[k.on]:r,[k.blocked]:r,[k.held]:r,[k.next]:r,[k.watching]:o,[k.problem]:i,[k.ok]:l};return{on:!0,bold:n("1"),dim:n("2"),blue:r,grey:o,amber:i,mark:s=>(c[s]??(a=>a))(s),field:s=>`\x1B[${t?"48;2;24;2;166;38;2;255;255;255":"48;5;19;97"}m${Ee(s)}\x1B[0m`}}var Qn=Se(!1),Ne=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function Ee(e){return e.replace(Ne,"")}var se=[{id:"protect",name:"Protect what can't come back",verdict:"block",short:"wiping your home folder or the project, and force-pushing main",context:"blocks deleting the user's home folder, the disk, a system folder, the project or its .git, force-pushing main or deleting it on the remote, and killing every process",slugs:{protected:"deleting your home folder, the disk, a system folder, the project or its .git; force-pushing main or deleting it on the remote; killing every process"}},{id:"keep-anvil-on",name:"Keep Anvil on",verdict:"hold",short:"changes to Anvil",context:"holds any change to Anvil or to Claude Code's permissions, hooks and settings",slugs:{"agent-controls":"any change to Anvil, or to Claude Code's permissions, hooks and settings"}},{id:"stop-loops",name:"Stop runaway loops",verdict:"hold",short:"delete bursts and repeats",context:"holds more than 20 recursive deletes in a minute and the same app change twice in 10 minutes",slugs:{"delete-burst":"more than 20 recursive deletes in a minute",repeat:"the same app (MCP) change twice in 10 minutes"}},{id:"stop-helper-bursts",name:"Stop runaway helpers",verdict:"hold",short:"helper bursts",context:"holds more than 20 helper agent launches in 10 minutes in one session",slugs:{"helper-burst":"more than 20 helper launches in 10 minutes"}},{id:"keep-keys-in",name:"Keep keys in",verdict:"hold",short:"use of your account keys",context:"holds reading or writing the user's account key files (such as ~/.ssh/id_* and ~/.aws/credentials) and committing or sending a secrets file",slugs:{credentials:"reading or writing your account key files (~/.ssh/id_*, ~/.aws/credentials, ~/.npmrc \u2026)","secrets-expose":"committing or sending a secrets file"}},{id:"hold-unchecked",name:"Hold what it can't check",verdict:"hold",short:"actions it can't check",context:"holds a call it could not read in full or check in time",slugs:{"could-not-check":"a command too long or nested too deep to read, or one its classifier failed on","too-long-to-check":"a call it could not check in time (1 second a pass, 3 in all)"}}],Oe="home and project wipes and force-pushes to main",ir=`always blocking ${Oe}`,ar=new Map(se.map(e=>[e.id,e]));var je=new Set(se.flatMap(e=>Object.keys(e.slugs)));var z="anvil-claude";function N(e){let t=e.trim();return t===z||t.endsWith(` ${z}`)||t.endsWith(`/${z}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(t)||/(^|\s)claude$/.test(t)?t:`${t} claude`}var ie="\u{1F539}",x=e=>`${ie} ${e} ${ie}`;var q=(e,t)=>`they run \`${N(e)} allow\` in a terminal (not in this chat: Claude can't run it), which lists what's waiting for their OK, then ${t}`;var le="claude.agent.helper",We=6e4,Fe=30*6e4,ze=30*6e4,ce=6e4,qe="workflow-subagent",He=4*1024*1024,ue=[2,1,318],Ue="/.anvil/claude/bin/claude-hook.js",Be=process.platform==="darwin"?"/Library/Application Support/ClaudeCode/managed-settings.json":process.platform==="win32"?`${process.env.ProgramFiles||"C:\\Program Files"}\\ClaudeCode\\managed-settings.json`:"/etc/claude-code/managed-settings.json",de=40,m=e=>typeof e=="string"&&e.length>0?e:null,G=e=>e?/^[A-Za-z0-9_-]{1,80}$/.test(e)?e:Pe("sha256").update(e).digest("hex").slice(0,24):"none",Ge=/^[A-Za-z0-9_-]{1,64}$/,Ke=e=>e[0].toUpperCase()+e.slice(1),K=e=>{let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`},_=e=>h(e.dir,"helpers"),J=(e,t)=>h(_(e),"live",`${G(t)}.log`);function Je(e,t){let n=null,r=null;for(let o of e)for(let i of o.helpers?.models??[])i.types===null?n=i:i.types.includes(t)&&(r=i);return r??(t==="fork"?null:n)}function Ye(e){let t=null;for(let n of e)for(let r of n.helpers?.at_once??[])(!t||r.limit<t.limit)&&(t=r);return t}function Ze(e,t){let n=m(e.env.CLAUDE_CONFIG_DIR),r=h(n?De(n):h(e.home,".claude"),"settings.json"),o=m(e.env.CLAUDE_PROJECT_DIR)??m(t.cwd);return o?[r,h(o,".claude","settings.local.json"),h(o,".claude","settings.json")]:[r]}function Or(e){let t=Ze(e.deps,e.payload),n=e.modes?.kill_switch===!0,r=e.payload.tool_input&&typeof e.payload.tool_input=="object"&&!Array.isArray(e.payload.tool_input)?e.payload.tool_input:{},o=typeof r.subagent_type=="string"&&r.subagent_type.trim()?r.subagent_type.trim():"general-purpose",i=m(e.payload.session_id),l=e.table.policies.filter(p=>p.helpers&&oe(p,e.projectDir)),c=[],s=(p,d)=>{tt(e.paths,i,p)&&c.push(d)},a=n?null:Je(l,o);a&&r.model===a.model&&(a=null);let g=n?null:Ye(l),f=a||g?Qe(t,o,e.managed??Be):null;if(f==="deny"&&(a=null),o==="fork"&&!n){let p=l.flatMap(d=>d.helpers?.models??[]).find(d=>d.types===null);p&&s(`fork-${p.id}`,`${x("Anvil")} a fork helper keeps this session's model \xB7 ${p.text} can't switch it`)}let u=m(e.payload.tool_use_id)??`${e.now}-${process.pid}`,w=J(e.paths,i),b=!1,v=null,$=0;if(g&&f!=="deny"){let p=Ve(e,t);if(p)s(`count-${g.id}`,`${x("Anvil")} can't count helper agents here (${p}) \xB7 ${g.text} isn't enforced`);else{try{let d=st(w,u,g.limit,e.now);b=d===null,d!==null&&($=d)}catch(d){$=-1,v={action:le,decision:{verdict:"hold",policy:"caps",origin:null,ruleId:g.id,blockedBy:"cap_unreadable",source:g.source},mode:"enforce",floor:null,why:`couldn't count helper agents for ${g.text} (${d?.code??(d instanceof Error?d.message.slice(0,60):"unreadable")})`,target:o}}$>0&&(v={action:le,decision:{verdict:"hold",policy:"caps",origin:null,ruleId:g.id,blockedBy:"cap_reached",source:g.source},mode:"enforce",floor:null,why:`${$} helper ${$===1?"agent":"agents"} running or starting (cap: ${g.text})`,target:o})}}let I=()=>{if(b){b=!1;try{y(w,JSON.stringify({t:e.now,op:"x",k:u}))}catch{}}},me=()=>{if(!b)return;let p=m(e.payload.transcript_path),d=m(e.payload.tool_use_id);try{y(w,JSON.stringify({t:e.now,op:"q",k:u,...p&&d&&p.length<1024&&d.length<256?{tr:p,c:d}:{}}))}catch{}};return{stop:v,agent:p=>$<0?`${x("Held by Anvil")} ${v.why}. Nothing ran. Tell the user${p?`: to let it start once, ${q(e.cli,"tell you to launch it again")}`:"; once it is fixed, launch it again"}. Do not try another way.`:`${x("Held by Anvil")} ${$} helper ${$===1?"agent is":"agents are"} running or starting in this session, and the user's cap is ${g?.text??"reached"}. Nothing ran. Wait for one of them to finish, then launch this one again; don't retry it before then.${p?` To let it start now, ${q(e.cli,"tell you to launch it")}.`:""}`,release:I,ran:()=>{if(a)try{it(e.paths,{t:e.now,session:i?G(i):null,type:o,from:typeof r.model=="string"?r.model.slice(0,40):null,to:a.model,rule:a.id,project:e.projectDir?B(e.projectDir):null})}catch{}},finish:p=>{let d={};try{d=p.stdout?JSON.parse(p.stdout):{}}catch{return I(),p}let Y=d.hookSpecificOutput&&typeof d.hookSpecificOutput=="object"?d.hookSpecificOutput:null,E=Y?.permissionDecision;E==="deny"?I():(E==="ask"||f==="ask")&&me();let O=c.join(`
|
|
5
|
+
`);if(!a&&!O)return p;if(a&&E!=="deny"){let T={...r,model:a.model},Z=`switched this helper to ${Ke(a.model)} \xB7 ${a.text}`;E==="ask"?d.hookSpecificOutput={...Y,updatedInput:T}:f==="ask"?d.hookSpecificOutput={hookEventName:"PreToolUse",permissionDecision:"ask",permissionDecisionReason:`${x("Anvil")} ${Z}; your own rule asks before helper agents`,updatedInput:T}:d.hookSpecificOutput={hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`${x("Anvil")} ${Z}`,updatedInput:T}}return O&&(d.systemMessage=typeof d.systemMessage=="string"?`${d.systemMessage}
|
|
6
|
+
${O}`:O),{stdout:`${JSON.stringify(d)}
|
|
7
|
+
`,exitCode:0}}}}function Ve(e,t){if(!Xe(t))return e.deps.plugin===!0?`the plugin isn't told when helpers start and stop; ${N(e.cli)} on is`:`its helper start and stop entries aren't set up: run ${N(e.cli)} on, which names any Claude Code that keeps them out`;let n=et(m(e.payload.transcript_path));if(!n)return"this session's Claude Code version can't be read";for(let r=0;r<3;r++)if(n[r]!==ue[r])return n[r]>ue[r]?null:`Claude Code ${n.join(".")} doesn't report helpers starting and stopping; 2.1.318 does`;return null}function fe(e){try{if(A(e,4*1024*1024)!==!0)return null;let t=JSON.parse(Me(e,"utf8").replace(/^/,""));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Xe(e){return e.some(t=>{let n=fe(t)?.hooks;return["SubagentStart","SubagentStop"].every(r=>JSON.stringify(n?.[r]??null).includes(Ue))})}function Qe(e,t,n){let r=null;for(let o of[n,...e]){let i=fe(o)?.permissions;for(let l of["deny","ask"]){let s=(Array.isArray(i?.[l])?i[l]:[]).some(a=>{let g=typeof a=="string"?/^\s*(?:Agent|Task)\s*(?:\(\s*([^)]*?)\s*\))?\s*$/.exec(a):null;return g!==null&&(g[1]===void 0||g[1]===""||g[1]==="*"||g[1]===t)});if(s&&l==="deny")return"deny";s&&(r="ask")}}return r}function et(e){if(!e)return null;try{let t=null;for(let n of P(e,256*1024).matchAll(/"version":"(\d+)\.(\d+)\.(\d+)"/g)){let r=[Number(n[1]),Number(n[2]),Number(n[3])];(!t||r[0]>t[0]||r[0]===t[0]&&(r[1]>t[1]||r[1]===t[1]&&r[2]>t[2]))&&(t=r)}return t}catch{return null}}function tt(e,t,n){try{let r=h(e.state,`helpers-said-${G(t)}`);return P(r,64*1024).split(`
|
|
8
|
+
`).includes(n)?!1:(S(e.state),y(r,n),!0)}catch{return!0}}function H(e){let t=R(e,He);if(!t)return[];let n=[];for(let r of t.toString("utf8").split(`
|
|
9
|
+
`))if(r)try{let o=JSON.parse(r);typeof o.t=="number"&&typeof o.op=="string"&&n.push(o)}catch{}return n}var U=e=>{try{return Te(e).mtimeMs}catch{return 0}};function nt(e){let t=U(e);if(t>0)return t;let n=0;try{let r=h(L(e),"workflows");for(let o of M(r).slice(0,512))n=Math.max(n,U(h(r,o,B(e))))}catch{}return n}function pe(e,t,n=e.length,r=nt){return ge(e,t,n,r).count}function ge(e,t,n,r){let o=new Map,i=new Map,l=new Set,c=f=>f.q?Fe:We;for(let f=0;f<Math.min(n,e.length);f++){let u=e[f];if(u.op==="z")o.clear(),i.clear();else if(u.op==="r"&&u.k)o.set(u.k,{t:u.t,q:null});else if(u.op==="q"&&u.k){let w=o.get(u.k);w&&(w.q=u)}else if(u.op==="x"&&u.k)o.delete(u.k);else if((u.op==="s"||u.op==="e")&&u.a){if(u.op==="s"&&!i.has(u.a)&&!l.has(u.a)){if(!u.w){for(let[b,v]of o)u.t-v.t>=c(v)&&o.delete(b);let w=[...o].find(([,b])=>!b.q)?.[0]??o.keys().next().value;w!==void 0&&o.delete(w)}i.set(u.a,u)}u.op==="e"&&(i.delete(u.a),l.add(u.a))}}let s=f=>f>t+ce?0:f,a=0,g=[];for(let f of o.values())f.t>t+ce||t-f.t>=c(f)||(a++,f.q&&g.push(f.q));for(let f of i.values())t-Math.max(s(f.t),f.f?s(r(f.f)):0)<ze&&a++;return{count:a,asked:g}}function rt(e,t,n){let r=0;for(let o of ge(t,n,t.length,()=>0).asked)r>=4||!o.tr||!o.c||n-o.t<1e3||(r++,ot(o.tr,o.c)&&y(e,JSON.stringify({t:n,op:"x",k:o.k})))}function ot(e,t){try{let n=P(e,1048576),r=`"tool_use_id":"${t}"`;for(let o=n.indexOf(r);o>=0;o=n.indexOf(r,o+r.length)){let i=n.indexOf(`
|
|
10
|
+
`,o);try{let l=JSON.parse(n.slice(n.lastIndexOf(`
|
|
11
|
+
`,o)+1,i<0?void 0:i)),s=(Array.isArray(l.message?.content)?l.message.content:[]).find(a=>a.type==="tool_result"&&a.tool_use_id===t);if(s)return s.is_error===!0}catch{}}return!1}catch{return!1}}function st(e,t,n,r,o){try{rt(e,H(e),r)}catch{}let i=()=>{S(L(e)),y(e,JSON.stringify({t:r,op:"r",k:t}))};try{i()}catch(a){if(a.code!=="ENOENT")throw a;i()}o?.();let l=H(e),c=l.findIndex(a=>a.op==="r"&&a.k===t&&a.t===r);if(c<0)throw new Error("its place wasn't read back");let s=pe(l,r,c+1);return s<=n?null:(y(e,JSON.stringify({t:r,op:"x",k:t})),s-1)}function jr(e,t,n){return pe(H(J(e,t)),n)}function Pr(e,t,n){try{let r=m(e.hook_event_name),o=m(e.session_id);if(!o)return;if(!R(t.compiled,16*1024*1024)?.includes('"at_once"'))return void Ie(h(_(t),"live"),{recursive:!0,force:!0});let i=J(t,o),l=A(i,Number.MAX_SAFE_INTEGER)===!0;if(r==="SessionStart"){l&&m(e.source)==="resume"&&y(i,JSON.stringify({t:n,op:"z"}));return}let c=m(e.agent_id);if(!c||!Ge.test(c)||r!=="SubagentStart"&&r!=="SubagentStop")return;if(l||he(t,n),S(L(i)),r==="SubagentStop")return y(i,JSON.stringify({t:n,op:"e",a:c}));let s=m(e.transcript_path),a=s&&s.startsWith("/")&&s.endsWith(".jsonl")?h(L(s),B(s,".jsonl"),"subagents",`agent-${c}.jsonl`):null;y(i,JSON.stringify({t:n,op:"s",a:c,...a&&a.length<1024?{f:a}:{},...m(e.agent_type)===qe?{w:1}:{}}))}catch{}}function it(e,t){let n=_(e),r=h(n,`${K(t.t)}.log`);S(n),A(r)===null&&he(e,t.t),y(r,JSON.stringify(t))}function Mr(e,t,n){let r={},o=0,i=new Date(Math.max(t,n-(de+1)*864e5));for(i.setHours(0,0,0,0);i.getTime()<=n;i.setDate(i.getDate()+1)){let l="";try{l=R(h(_(e),`${K(i.getTime())}.log`),16*1024*1024)?.toString("utf8")??""}catch{l=""}for(let c of l.split(`
|
|
12
|
+
`))if(c)try{let s=JSON.parse(c);if(typeof s.t!="number"||s.t<t||s.t>n||typeof s.to!="string")continue;r[s.to]=(r[s.to]??0)+1,o++}catch{}}return{total:o,byModel:r}}function he(e,t){try{let n=K(t-de*864e5);for(let r of M(_(e)))/^\d{4}-\d{2}-\d{2}\.log$/.test(r)&&r.slice(0,10)<n&&ae(h(_(e),r))}catch{}try{let n=h(_(e),"live");for(let r of M(n))r.endsWith(".log")&&t-U(h(n,r))>2*864e5&&ae(h(n,r));M(n).length===0&&Le(n)}catch{}}export{Fe as ASK_MS,le as HELPER_ACTION,We as RESERVE_MS,ze as STALE_MS,st as admit,Ye as atOnceFor,_ as helpersDir,Or as launchStep,J as ledgerFile,pe as liveAt,Je as modelRuleFor,Pr as onEvent,Qe as ownAgentRule,H as readLedger,ot as refusedIn,jr as runningNow,Ze as settingsFiles,Xe as subagentEntries,Mr as switchesIn,nt as transcriptChanged};
|