@useanvil/claude-code 0.8.1 → 0.9.1
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 +241 -1
- package/dist/claude-conditions.js +6 -6
- package/dist/claude-hook-core.js +84 -82
- package/dist/claude-hook.js +37 -35
- package/dist/claude-meter.js +55 -35
- package/dist/claude-sync.js +26 -24
- package/dist/cli/claude-main.js +7890 -1382
- package/docs/coding-agents/YOUR-RULES.md +293 -49
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,7 +4,247 @@ All notable changes to `@useanvil/sdk` are documented here. The format follows
|
|
|
4
4
|
[Keep a Changelog](https://keepachangelog.com/), and this project adheres to
|
|
5
5
|
[Semantic Versioning](https://semver.org/).
|
|
6
6
|
|
|
7
|
-
## [
|
|
7
|
+
## [0.9.1] — Anvil for Claude Code: a second security review's fixes
|
|
8
|
+
|
|
9
|
+
A second review (2026-11-29) took up what the first left open: commands started through another program, the key that
|
|
10
|
+
signs Anvil's rules, and what passes as you. Each fix below has a test that fails on 0.9.0.
|
|
11
|
+
|
|
12
|
+
- **A command started through another program is judged as that command.** `setsid sh -c 'rm -rf ~'`,
|
|
13
|
+
`screen -dm sh -c '…'`, `launchctl asuser 501 …`, `flock`, `sandbox-exec`, `taskset`, `chrt`, `prlimit`, `unshare`
|
|
14
|
+
and `systemd-inhibit` ran what was under them unread, so a home wipe passed the floor on a fresh install. And
|
|
15
|
+
`launchctl submit -- sh -c 'rm -rf ~'` (or `… anvil-claude allow`) read as only a background job, watched in ghost
|
|
16
|
+
mode. The floor now blocks what it blocks under each of them, and a switch of Anvil's under one is held.
|
|
17
|
+
- **Anvil's seal key is held like its controls.** The key that signs your rules was guarded only as a printed `.key`
|
|
18
|
+
file: on a fresh install `cat`, `cp`, a `tar` of its folder, code that opens it, or the Read tool ran unheld, and with
|
|
19
|
+
it a rule changed out of sight would pass as Anvil's. Every call that reads, copies or packs it is held now; reading
|
|
20
|
+
Anvil's other files still runs.
|
|
21
|
+
- **An app the agent opens can't pass as you.** A program macOS opened (an `.app` the agent built, or one run from a
|
|
22
|
+
temp folder) could run `anvil-claude off` as yours. Everything you type in gives what it runs a controlling terminal,
|
|
23
|
+
stdin piped or not; what macOS opens has none, so it is refused now.
|
|
24
|
+
- **`/v1/modes` has per-key limits.** One key could loop the break-glass pair without end. Turning an action back to
|
|
25
|
+
ghost (or an invalid body) is 30 a minute per key, `anvil protect`'s registrations 600, reads 1,200; enforcing is
|
|
26
|
+
never limited.
|
|
27
|
+
- **The Claude Code plugin's MCP server starts.** Since 0.8.0 the plugin asked npm for an SDK release it doesn't have,
|
|
28
|
+
and its fix lines named a command npm's SDK lacks. It runs `@useanvil/sdk@0.5.6` now and names
|
|
29
|
+
`npx @useanvil/claude-code`.
|
|
30
|
+
|
|
31
|
+
## [0.9.0] — Anvil for Claude Code: folder locks, smart spend, a second opinion, and rules read in your own words
|
|
32
|
+
|
|
33
|
+
A rule on a folder now locks it. `model: smart` runs Sonnet with Opus advising, and `second opinion:` sends Claude to
|
|
34
|
+
the advisor before a risky action. `rules import` enforces 73% of the rules real CLAUDE.md files write (0.8.1: 43%), and
|
|
35
|
+
the rules box reads back what you type before it saves. What missed its bar stays off; it is listed at the end, with
|
|
36
|
+
how to try it.
|
|
37
|
+
|
|
38
|
+
### Anvil for Claude Code: say a second opinion or smart spend in your own words (UI pass)
|
|
39
|
+
|
|
40
|
+
- **Say a second opinion or smart spend in your own words.** `rules add` and the rules box read "get a second opinion
|
|
41
|
+
before deploys" as `second opinion: deploys` and "use Sonnet with Opus advising" as `model: smart`, show the line with
|
|
42
|
+
the words it was read from, and save it on yes. Before, both were misread into a weaker rule (`watch: deploys`, a watch
|
|
43
|
+
on paid compute) or refused. Who approves decides: "ask me before deploys" stays a hold. "Use opus for deploys" is a
|
|
44
|
+
model rule, "never use opus" is `model: never opus`, "keep spending under $50 a day" a budget. A line that mentions
|
|
45
|
+
the advisor or Opus that Anvil can't place is offered the exact line, never saved as a watch; where your Claude Code is
|
|
46
|
+
here it reads such a line first (the form only, never a kind your words don't name). The rules box adds both lines,
|
|
47
|
+
typed exactly too; `rules import` lists such a CLAUDE.md line with the command that adds it.
|
|
48
|
+
- **`anvil claude --help` has rows for locks, smart spend and the advisor**, and the guide's section on them reads
|
|
49
|
+
examples first. Adding a hold on deploys, publishing, database changes or pushes to main suggests a second opinion
|
|
50
|
+
once per kind.
|
|
51
|
+
|
|
52
|
+
### Anvil for Claude Code: a folder rule locks the folder, `model: smart`, and a second opinion before a risky action
|
|
53
|
+
|
|
54
|
+
- **A rule on a folder locks it.** `block: edits to ~/Documents/` is now kept twice: the hook blocks every write it can
|
|
55
|
+
read, and Claude Code's own sandbox makes the operating system refuse a Bash write there it can't (a script that
|
|
56
|
+
builds its path while it runs). Nothing to turn on: Anvil writes the sandbox block only where a rule names a plain
|
|
57
|
+
path (network, localhost, Docker and `gh` as before), merged with the person's own and taken out byte for byte by
|
|
58
|
+
`off`. A lock never ends an approval prompt: the block turns Claude Code's auto-allow off and adds no folder to the
|
|
59
|
+
sandbox's write list (Claude Code takes one as leave to change files there unasked), so every command asks or runs as
|
|
60
|
+
it would without the rule, in every mode; a write outside the project is rerun outside the sandbox, asked as any
|
|
61
|
+
command is. A rerun right after a refusal on a lock is held. Proof names the rule (`locked by your rule`); the
|
|
62
|
+
screens say `locked`, `partly locked` or `held by Anvil, not locked`, with why: on Linux, which of bubblewrap and
|
|
63
|
+
socat is missing (or that Ubuntu's AppArmor stops bubblewrap), and in a project whose own settings turn the sandbox
|
|
64
|
+
off, or set a sandbox Anvil's network settings widen, that it does.
|
|
65
|
+
- **`model: smart`: Sonnet works, Opus advises.** Writes `model` and `advisorModel` into Claude Code's settings for new
|
|
66
|
+
sessions and gives the person's own back when the line goes. `/anvil` and the status line say `advisor: Opus · on`,
|
|
67
|
+
or the one reason it is off. The desktop app starts every session on the model picked in it, before any setting:
|
|
68
|
+
there smart can't make Sonnet work, and the screens say so (the advisor still reaches it). Suggested in one line with
|
|
69
|
+
a `budget:` or `model:` line and the budget's 80% note, never switched on for you.
|
|
70
|
+
- **`second opinion: deploys`** (any kind): the first such action in a task is refused, and Claude told to ask the
|
|
71
|
+
advisor first ("if it advises against it, don't rerun: tell the user"). The rerun runs only once Claude Code's own
|
|
72
|
+
record of the session shows the advisor asked and answering after the refusal; a rerun without it is refused once
|
|
73
|
+
more, then held for your OK. Each thread (a helper agent, the main session) is its own. In the terminal, which writes
|
|
74
|
+
Claude's reply only after Anvil checks the call, and with no advisor, each such action waits for your OK. In ten live
|
|
75
|
+
runs every rerun after the advisor's answer ran; in two told never to ask it, each rerun was held. Proof says
|
|
76
|
+
`advisor asked, then let through` or `rerun without the advisor: held`, and the pause is no stop.
|
|
77
|
+
- **Budgets come before a second opinion spends.** Before Claude is sent to the advisor (the first refusal, a rerun sent
|
|
78
|
+
back, the terminal's hold that asks it), Anvil prices the call: the advisor reads the whole conversation uncached
|
|
79
|
+
(about $0.64 at 150K tokens with Opus advising). A budget already spent, or one that call would pass with what's
|
|
80
|
+
running, holds the action by the budget instead, says the price, and tells Claude not to ask the advisor.
|
|
81
|
+
- **Smart spend says the truth when the advisor never attaches.** No screen says `advisor: Opus · on` before a
|
|
82
|
+
session shows it (`set: seen at your next session`). A session that began after the line was added and came without
|
|
83
|
+
the advisor (Claude Code's rollout, the account's credits, a telemetry setting) shows it, and every screen then says
|
|
84
|
+
lastingly that smart runs Sonnet alone, with how to have your own model back; never switched back for you.
|
|
85
|
+
`DISABLE_TELEMETRY`, `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` (any value), `CLAUDE_CODE_DISABLE_FEATURE_FLAGS` and
|
|
86
|
+
`DISABLE_GROWTHBOOK` are named where they keep it off (measured live). `rules add "model: smart"` says what it
|
|
87
|
+
replaced when yours was stronger, and a project's own `model` is said where it wins.
|
|
88
|
+
- **A model Anvil has no price for never turns a dollar budget off.** It is priced at the newest of its family, else the
|
|
89
|
+
most expensive Anvil knows, and every total, hold, Proof's Spend line and `report` say so ("estimated at Opus 5.5's
|
|
90
|
+
prices"). Where Claude Code's own cost record covers it, Claude Code's figure stands.
|
|
91
|
+
- **The meter counts the advisor**, once per reply, at its own model's rates, so budgets include it: Anvil's estimate
|
|
92
|
+
matched Claude Code's own total to the micro-dollar on a real session ($0.1977597). Proof's Spend line and `report`
|
|
93
|
+
say its share.
|
|
94
|
+
|
|
95
|
+
### Anvil for Claude Code: the model guard reads the model twice, and is heard everywhere it can be
|
|
96
|
+
|
|
97
|
+
- **Two readings of the model.** Every reply Claude Code writes names the model that answered it and the request it
|
|
98
|
+
answers; over 30 days on the build machine it agreed with the request line on 149,743 of 149,743 replies. A call a
|
|
99
|
+
model rule names is now judged on both: in the desktop app and a headless run Anvil waits for the call's own reply
|
|
100
|
+
(half a second at most), and that reply is compared wherever it sits. In the terminal, where the reply comes after the
|
|
101
|
+
check, a request line written right after another with no reply between (a forged line's mark) must name the same
|
|
102
|
+
model unless a change is recorded or heard between (a message of yours, `/model`, a fallback, plan mode); after a
|
|
103
|
+
reply the request alone is read, since the model changes between
|
|
104
|
+
replies in ways Claude Code records nowhere first. Two that differ hold the call and say so. A reply the API
|
|
105
|
+
answered on another model (a fallback, on the call's own reply) is judged by that model; a model id Anvil can't
|
|
106
|
+
read (a cloud's profile, a gateway's alias) by the model the reply names; a request line Claude Code skipped, by
|
|
107
|
+
the reply (when it is the call's own, or a change is recorded since: one forged reply can't set the line aside).
|
|
108
|
+
With no request line
|
|
109
|
+
the reply is read on Claude Code 2.1.304 and later (the record turned off); before it, only in the desktop app and
|
|
110
|
+
headless runs.
|
|
111
|
+
- **A rule that can't hear the model says so everywhere.** Where nothing records the model, the call isn't held, and
|
|
112
|
+
every call the rule names, the rules screen, Home and the status line say Anvil can't hear it, for a week. A model
|
|
113
|
+
this release doesn't know is said on the screens too ("can't tell the model").
|
|
114
|
+
- **Claude's writes to its own session files are held**, from the first call: a redirect, `tee`, `sed -i`, `cp` or `mv`
|
|
115
|
+
onto one, `rm`, a pattern of them, a variable an `ls` or `find` over the projects folder fills, a writer `xargs` or
|
|
116
|
+
`find -exec` hands them, `node -e` or `python -c` naming one, building its path from the home folder or handed it,
|
|
117
|
+
`sh -c` handed one by position,
|
|
118
|
+
an archive unpacked into their folder, and the Write and Edit tools. Memory notes, reading, copying out and month-old
|
|
119
|
+
housekeeping stay open. On 0.8.1 none of 27 such write forms was held as a change to Anvil. Code or a script that
|
|
120
|
+
finds the file itself can still write it.
|
|
121
|
+
- **The plugin refuses a message and a switch on a model your rules say never**, as `anvil-claude on` does: a message
|
|
122
|
+
entry, and a model-switch entry in a file of its own, since Claude Code 2.1.250 and older drop a plugin's whole hooks
|
|
123
|
+
file over an event they don't know. Where `on`'s own entries run too, the plugin steps aside for those events.
|
|
124
|
+
- **An older Claude Code no longer switches the newer entries off for every other one.** Every Claude Code from 2.1.153
|
|
125
|
+
on skips a settings entry for an event it doesn't know, so `on` writes the message, switch and helper entries from
|
|
126
|
+
2.1.153 (was 2.1.318). `on` and Home name each Claude Code too old to hear an event, and Home updates it on a key;
|
|
127
|
+
one updated elsewhere is seen by the next `anvil-claude`, which writes the newer entries.
|
|
128
|
+
- **Two model rules no one model can meet are said when the second is added**, including a project's guard that wins
|
|
129
|
+
only some of your guard's kinds.
|
|
130
|
+
- **`release:verify` checks the model guard's records against a real Claude Code** (one `claude -p` on Haiku, about
|
|
131
|
+
$0.002): it fails the release if request lines or reply models stop being written, or if it can't run, unless
|
|
132
|
+
`--skip-contract` is passed, and then it says "skipped".
|
|
133
|
+
### Anvil for Claude Code: caps count what actually ran
|
|
134
|
+
|
|
135
|
+
- **Every capped action in a command line counts.** `vercel --prod && vercel --prod` is 2 deploys; so is the pair
|
|
136
|
+
joined by `;`, `&` or `||`, inside `bash -c` or `ssh`, or a literal list. A line that would cross a cap partway is
|
|
137
|
+
held whole and says what it adds ("1 used today + 2 in this call"). What can't be counted is held, saying so: a line
|
|
138
|
+
of 16 actions or more, a line that repeats an action a number of times Anvil can't read (`{1..50}`, `$(…)`, `while`,
|
|
139
|
+
`xargs`, `find -exec`, `watch`, a function written `name() { … }` that calls itself; also inside quoted code a shell
|
|
140
|
+
runs, as in `bash -c '…'`), and an MCP tool's shell line of several commands. Other runners (`fd --exec`,
|
|
141
|
+
`pnpm -r exec`) count as written. Paid compute counts each start at the line's largest figures. Replay counts count
|
|
142
|
+
and money caps the same way.
|
|
143
|
+
- **A money cap adds each amount once.** Two Stripe refunds on one line ($500 and $700) counted $2,400; they count
|
|
144
|
+
$1,200.
|
|
145
|
+
- **A call Claude Code itself refused gives its place back:** a No at its prompt (probed live in the terminal and
|
|
146
|
+
headless; the desktop app's refusals carry the same fields in its session files), a deny by a permission rule or
|
|
147
|
+
another hook, or auto mode's refusal. It is read from the fields Claude
|
|
148
|
+
Code writes on a refusal, never from the result's words, which a command can print; only where Claude Code can still
|
|
149
|
+
refuse (not under Bypass); a helper's call in its own file. Each waiting count is read before the next tool call of
|
|
150
|
+
its own session runs (and at other sessions' calls, up to 4 more session files a check for places given back and 4
|
|
151
|
+
for counts), so a call that ran is settled as run before a later call of its session could change its record; the
|
|
152
|
+
place comes back at the refused call's own thread's next call. A place given back is checked again for 6 hours and
|
|
153
|
+
counts again if another result for the call appears. A command whose output printed the refusal's words used to free
|
|
154
|
+
the place of an Anvil hold it was allowed past; it no longer does.
|
|
155
|
+
- **Two limits on one cap line are two caps.** `cap: 2 deploys a day and 1 an hour` counts each, and a hold names the
|
|
156
|
+
one reached. `sync` no longer refuses the line.
|
|
157
|
+
- **Numbers in words.** "at most one hundred deploys a day" read as a cap of 1, and "1,000" as 1; both read as written
|
|
158
|
+
now, and so do "a hundred", "a dozen" and "twenty-five". Money in words is refused, never counted as calls. "never
|
|
159
|
+
more than a hundred Stripe refunds a day" offers the cap, as "…100…" does, where it offered a block on every refund.
|
|
160
|
+
|
|
161
|
+
### Anvil for Claude Code: a clearer held notice on macOS
|
|
162
|
+
|
|
163
|
+
- **The notice for a held call reads in three lines, one job each**: `🔹 Anvil 🔹 needs your OK`, then
|
|
164
|
+
`Held: pushes to main`, then `Allow once: run anvil claude allow in a terminal.`
|
|
165
|
+
|
|
166
|
+
### Anvil for Claude Code: `rules import` turns more of your CLAUDE.md into real rules
|
|
167
|
+
|
|
168
|
+
- **On by default: your Claude Code reads each CLAUDE.md line and writes the rule it asks for**, in the same words
|
|
169
|
+
`rules.md` uses. Anvil then checks each rule against the line's own words before offering it:
|
|
170
|
+
- a kind needs its words in the line;
|
|
171
|
+
- a file or folder must be named in the line, and the rule uses the line's spelling;
|
|
172
|
+
- "ask first", "avoid" and "only after CI passes" give a hold, never a block; "even if asked" stays a block.
|
|
173
|
+
- **What Anvil can't enforce yet is listed as "Not covered yet"**: "only commit when I ask", "don't run the build".
|
|
174
|
+
Plain guidance is no longer listed beside it.
|
|
175
|
+
- **On 200 real CLAUDE.md files** it enforced 73% of the rules written there (0.8.1: 43%). It also got 85% of the files
|
|
176
|
+
that ask for a rule fully right (0.8.1: 52%).
|
|
177
|
+
- It adds a little more noise to files that ask for none: about one over-broad or wrong rule in 160 such files.
|
|
178
|
+
- The measure and its numbers: `docs/coding-agents/IMPORT-MEASURE-POOL5-RESULT.md`.
|
|
179
|
+
- **To read as 0.8.1 did:** `ANVIL_IMPORT_BRIEF=0`. With `--no-model`, or no Claude Code installed, nothing changes:
|
|
180
|
+
Anvil's own matcher reads the lines.
|
|
181
|
+
|
|
182
|
+
### Anvil for Claude Code: the rules box reads back what you type, part by part
|
|
183
|
+
|
|
184
|
+
- **On where Claude Code is installed.** Enter reads what you typed back before anything is saved: "Block deploys.
|
|
185
|
+
Publishes too." is two rules, and a part Anvil can't make a rule of is listed as "Not covered yet" beside your own
|
|
186
|
+
words. Enter again adds the rules (e edits, a adds one). The box reads each part; your Claude Code reads only the
|
|
187
|
+
parts it can't (Haiku, through your own login).
|
|
188
|
+
- **On two fresh sealed sets it read 71 and 68 of 90 right**, against 40 and 32 for 0.8.1's box, and left 8 parts of
|
|
189
|
+
180 unsaid against 31. It misses its round's own bar (79 of 90, none unsaid); it ships for the gain.
|
|
190
|
+
- **To type as 0.8.1 did:** `ANVIL_READBACK=0`. With no Claude Code, or `--no-model`, nothing changes. The rewrite
|
|
191
|
+
step, tab, and round 2's held reading stay off (`ANVIL_REWRITE_STEP=1` tries them).
|
|
192
|
+
|
|
193
|
+
### The policy server's change log is written before it answers
|
|
194
|
+
|
|
195
|
+
- **A save, a version, a delete or an approval decision now answers after its change-log row is written.** Seven
|
|
196
|
+
routes sent the 200 first, so a change log read on the next request (the dashboard's activity feed) could miss the
|
|
197
|
+
row. A log that can't be written still never fails the request; it is logged, as before.
|
|
198
|
+
|
|
199
|
+
### Anvil for Claude Code: the read-back, round 3 (IMPROVEMENTS-TO-90)
|
|
200
|
+
|
|
201
|
+
- **Held, not on yet: the rest of round 3** (the rules box's read-back is on: its own entry above). It missed its
|
|
202
|
+
bars, so it stays off and Anvil imports as above. `ANVIL_REWRITE_STEP=1` turns it on to try it:
|
|
203
|
+
- **`rules import` reads each CLAUDE.md line back, as the rules box does.** What it can't enforce is listed under "Not covered
|
|
204
|
+
yet", where it stays in your CLAUDE.md; a long list shows six and folds the rest (`--show-not-covered` lists all); a
|
|
205
|
+
line naming a file not to be edited gives the rule on that file. On 60 fresh real CLAUDE.md files it showed 95.7%
|
|
206
|
+
of their rule lines and hid none weaker, but 60–76.5% of the rules it offered were right (the bar is 85%).
|
|
207
|
+
- **Its check of a rewrite reads each amount at its currency's own precision**: BHD 1.234 and 1.231 are two amounts,
|
|
208
|
+
yen whole, dollars and euros to the cent as before.
|
|
209
|
+
|
|
210
|
+
### Anvil for Claude Code: reading what you type, round 2 (IMPROVEMENTS-TO-90)
|
|
211
|
+
|
|
212
|
+
- **Held, not on yet: everything round 2 built.** It missed its bars, so it stays off and Anvil reads and imports as
|
|
213
|
+
above. `ANVIL_REWRITE_STEP=1` turns it on to try it:
|
|
214
|
+
- **Words that only look like an action name none in the rules box.** "Publishes to our blog" is no package publish,
|
|
215
|
+
"kill a customer's subscription" no process kill, "database migrations" no database destroy. Held after a review
|
|
216
|
+
found it can lose an action said beside them.
|
|
217
|
+
- **The rules box's rewrite step answers in fields**, each quoting your own words. Anvil composes the rule, and a
|
|
218
|
+
guard checks every field against what you wrote. On two fresh sealed sets it read 81 and 67 of 90 plain-speech rules
|
|
219
|
+
right (the bar is 79 each, and the second had one softer rule).
|
|
220
|
+
- **`rules import` asks Sonnet and reads rules on files a CLAUDE.md line names.** On 40 fresh real CLAUDE.md files
|
|
221
|
+
it found 55–65% of their rules (the bar is 90%).
|
|
222
|
+
|
|
223
|
+
### Anvil for Claude Code: importing your CLAUDE.md (IMPROVEMENTS-TO-90, part A)
|
|
224
|
+
|
|
225
|
+
- **`rules import` ends with one choice: `↵ hold these N now · w watch first · q save nothing`.** Enter writes each
|
|
226
|
+
rule's own `block:` or `hold:` line, in force at once; `w` writes `watch:` lines; `q` saves nothing. Before, a yes
|
|
227
|
+
wrote `watch:` lines only, and nothing was held until `enforce`. With no terminal it saves nothing and says how;
|
|
228
|
+
`--yes` still writes `watch:` lines (a script never holds unasked). Anvil's validator checks the rules before it asks.
|
|
229
|
+
- **Each rule is shown beside its CLAUDE.md line as rules.md makes of it**, as `sync` shows it:
|
|
230
|
+
`→ block: force push · blocks every force-push`, or `▲ hold: deploying to production · holds deploys to production`
|
|
231
|
+
with its catch ("a deploy that doesn't say where it goes waits for your OK too"). A line rules.md can't take as
|
|
232
|
+
written ("Never push to main in the upstream repo.": name the repository) is shown `?` with rules.md's reason and
|
|
233
|
+
takes the closest rule (`block: push-main`), as the rules box offers one: never said to hold as written.
|
|
234
|
+
- **Each rule once.** The same words on two lines are added once, with the stronger verb; a rule on a whole kind covers
|
|
235
|
+
a narrower one of the same verb ("Ask before deploying." beside "Ask before deploying to production."), and the
|
|
236
|
+
skipped line names the one that covers it; a line that gives a block and a hold adds both. One already in rules.md is
|
|
237
|
+
never added again, and one there with a weaker verb is named ("already in ~/.anvil/rules.md as watch: change it there
|
|
238
|
+
to block it").
|
|
239
|
+
- **A count typed on a whole kind offers the cap.** "never more than 100 deploys a day" was read as `block: deploys`,
|
|
240
|
+
every deploy blocked; the rules box now answers as it does for an app's count: a rule doesn't count, a cap does,
|
|
241
|
+
`cap: at most 100 deploys a day`. A line written by hand in rules.md keeps its rule.
|
|
242
|
+
- **Home offers the import:** "Import N rules from your CLAUDE.md", when a CLAUDE.md here has rules Anvil can hold and
|
|
243
|
+
your rules.md has none.
|
|
244
|
+
- **Held, not on yet: your Claude Code rewriting what the rules box can't say, and the box reading CLAUDE.md lines.**
|
|
245
|
+
On fresh sealed sets the rewrite step read 66 and 32 of 90 plain-speech rules right (the bar is 79; none lost, none
|
|
246
|
+
softer), and the box's reading of 40 real CLAUDE.md files found 31.6% of their rules (the bar is 90%). Both stay off;
|
|
247
|
+
`ANVIL_REWRITE_STEP=1` turns them on to try them.
|
|
8
248
|
|
|
9
249
|
## [0.8.1] — Anvil for Claude Code: a security review's fixes
|
|
10
250
|
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
function E(e){return Object.assign(Object.create(null),e)}var
|
|
1
|
+
function E(e){return Object.assign(Object.create(null),e)}var ue=[{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 de=/^[0-9a-f]{8}(?:_[0-9a-f]{4}){3}_[0-9a-f]{12}$/,et=/(?:^|_)(?:zapier|composio|pipedream|n8n|make|rube|activepieces|klavis|toolhouse|arcade|ifttt|integrately|gumloop|viasocket|metamcp|1mcp|smithery|mcp_?(?:hub|gateway|proxy|router|docker))(?:_|$)/,tt=/(?:^|[^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]|$)/,fe=e=>e.normalize("NFKC").replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase(),pe=(e,t)=>e.split("+").every(n=>n[0]==="="?t.split(/[^a-z0-9]+/).includes(n.slice(1)):t.includes(n));function nt(e,t){let n=`_${t}_`.replace(/_mcp(?=[a-z])|(?<=[a-z])mcp_/g,"_"),s=t.replace(/_/g,"");return e.servers.some(r=>{let o=r.replace(/_/g,"");return`_${t}_`.includes(`_${r}_`)||n.includes(`_${r}_`)||(o.length>4?s.includes(o):o.length>3&&(s.startsWith(o)||s.endsWith(o)))})}function rt(e,t,n){let s=t.normalize("NFKC").toLowerCase().replace(/\.+$/,""),r=/^[a-z0-9.-]+$/.test(s);if(!s.includes("."))return r?(e.clis??[]).includes(s)?"this":"other":"?";let o=s.split("."),i=u=>s===u||s.endsWith(`.${u}`)||u.includes("*")&&u.split(".").every((d,a,l)=>l.length===o.length&&(d==="*"||d===o[a])),c=!1;return e.hosts.some(u=>{let d=u.indexOf("/");return d<0?i(u):(c||=i(u.slice(0,d))&&/^(?:\/batch\/?|\u0000)$/.test(n),i(u.slice(0,d))&&n.includes(u.slice(d)))})?"this":r&&!c?"other":"?"}function ot(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,s){let r=fe(n);return e.toolWords.length===0||e.toolWords.some(o=>pe(o,r))?{hit:"match",part:t,why:e.said}:s===3||/\u0000|%00/.test(r)||tt.test(r)||!/[a-z]{3}/.test(r.replace(/[a-z]*\d[a-z0-9]*/g,""))||s===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 st(e,t,n){let s=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 s("which app this tool belongs to");let f=`mcp.${l}.`,m=fe(n.tool?.startsWith("mcp__")?n.tool.split("__").slice(2).join("__"):t.target?.startsWith(f)?t.target.slice(f.length):"");if(nt(e,l))return N(e,t,m,1);let p=(e.anywhere??[]).some(g=>pe(g,m))?{hit:"match",part:t,why:e.said}:null;if(!de.test(l)&&!et.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:s(`which app ${de.test(l)?`the connector ${l.slice(0,8)}\u2026`:l} acts on`)}let r=t.target??"",o=/^[\w-]+(?:\.[\w-]+)+(?::\d+)?\//.test(r)?`https://${r}`:r,i=/^[a-z][a-z0-9+.-]*:\/\//i.test(o),c="";try{i&&(c=decodeURIComponent(new URL(o).pathname).replace(/\/{2,}/g,"/"))}catch{c="\0"}if(!t.host&&!t.service)return s("where this writes");let u=[t.host,t.service,...Array.isArray(t.attributes.hosts)?t.attributes.hosts:[],ot(o)].filter(l=>typeof l=="string"&&l!==""),d=u.map(l=>rt(e,l,c)),a=[r,...u].some(l=>/^smtps?[:.]/i.test(l));if(d.includes("this")||a&&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):a?N(e,t,"send mail",2):i?N(e,t,c,3):N(e,t,r,f)}return d.includes("?")?s(`where this writes (${u[0].replace(/[\u0000-\u001f]/g,"")})`):n.tool?.startsWith("mcp__")?s("what else this tool's command writes"):null}function K(e,t,n){let s=null;for(let r of t){let o=st(e,r,n);if(o?.hit==="match")return o;s??=o}return s??(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 it={over:"over",at_least:"at least",under:"under",at_most:"at most"};var $="Anvil can't read how much this moves",we="Anvil can't read this invoice's total (only drafting or replacing one says it)",at="Anvil can't add up this total (a tax, a discount, shipping, a tip, a template or a series changes it)",ge="Anvil can't tell which currency this moves (it names two)",lt="Anvil can't tell how many requests this makes (curl expands {\u2026} and [\u2026] in a URL)",V="claude.mcp.side_effect",ct=/\$\(|\$'|\$"|`|<<|(?:^|[\s;&|])(?:eval|xargs|source|exec)(?=\s|$)|\b(?:ba|z|k|da)?sh\s+-\w*c\b/,ut=/^(?:[A-Za-z_]\w*=.*|env|sudo|time|nohup|command|builtin|nice)$/,dt="012346#aBfgGiIjJklLMnNOpqRsSvVZ",ft=/^(?: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)$/,pt=/^(?:data(?:-raw|-binary|-ascii|-urlencode)?|form(?:-string)?|json)$/,gt=/^(?:live|confirm|help|version|dark_style|show_headers|dry_run|reverse_transfer|refund_application_fee|capture|final_capture)$/;function O(e){let t=(e.host??"").toLowerCase(),n=`_${t}_`.replace(/_mcp(?=[a-z])|(?<=[a-z])mcp_/g,"_"),s=ue.filter(r=>e.action===V?r.servers.some(o=>`_${t}_`.includes(`_${o}_`)||n.includes(`_${o}_`)):r.clis.includes(t)||r.hosts.some(o=>t===o||t.endsWith(`.${o}`)));return s.length===1?s[0]:null}function mt(e){let t=[[]],n="",s=!1,r=!1,o=!1,i=!1,c=!1,u=!1,d=()=>{c&&u?u=!1:c&&t[t.length-1].push({w:n,d:s,x:r,g:o}),n="",s=r=o=i=c=!1};for(let a=0;a<e.length;a++){let l=e[a];if(l==="'"){let f=e.indexOf("'",a+1);if(f<0)return null;n+=e.slice(a+1,f),a=f,i=!0}else if(l==='"'){let f=a+1;for(;f<e.length&&e[f]!=='"';f++){if(e[f]==="\\"&&e[f+1]===`
|
|
2
2
|
`){f++;continue}e[f]==="\\"&&/["\\$`]/.test(e[f+1]??"")?f++:e[f]==="$"&&(s=!0),n+=e[f]}if(f>=e.length)return null;a=f,i=!0}else if(l==="\\"){if(a++,e[a]!==`
|
|
3
3
|
`)n+=e[a]??"",i=!0;else if(!c)continue}else if(l==="#"&&!c){if(a=e.indexOf(`
|
|
4
|
-
`,a)-1,a<0)break;continue}else{if(/[(){}]/.test(l))return null;if(l==="<"||l===">"||l==="&"&&e[a+1]===">"){if((i||!/^\d+$/.test(n))&&d(),n="",s=r=o=i=c=!1,u)return null;l==="&"&&a++,(e[a]===">"?/[>|&]/:/[&>]/).test(e[a+1]??"")&&a++,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==="$"&&(s=r=!0),/[*?[]/.test(l)&&(o=!0),n+=l}}c=!0}return d(),u?null:t}function be(e,t){let n=t.replace(/\/{2,}/g,"/").replace(/(.)\/$/,"$1").split("/");return Object.keys(e).filter(s=>{let r=s.split(" ")[0].split("/");return s[0]==="/"&&r.length===n.length&&r.every((o,i)=>o==="*"?n[i]!=="":o===n[i])})}var Y=e=>e.filter(t=>t[0]!=="!"&&t[0]!=="$").map(t=>t.replace(/^~/,"").split(" ")[0]);function W(e,t){return[...new Set(e.map(n=>n.split(".").pop()))].reduce((n,s)=>n+(t.match(new RegExp(`(?:(?<![a-z0-9_]|[a-z0-9]-)|(?<=(?:^|\\s)-[a-z]+))${s.replace(/_/g,"[-_]")}(?![a-z0-9_]|-[a-z0-9])`,"gi"))?.length??0),0)}function V(e,t,n,s,r){let o=[],i=[],c=0;for(let d of t){let a=/^[!~$]/.test(d)?d[0]:"",[l="",f]=d.slice(a.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 $;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(a==="!"&&m.some(p=>p.v!==!1))return at;if(a==="~"&&(c+=m.length),a==="$")for(let{v:p}of m){if(typeof p!="string")return $;i.push(p.toLowerCase())}if(!a)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 $;if(e.obj){if(typeof p!="object"||Array.isArray(p))return $;{let b=p,w=[...new Set(e.obj.slice(1).map(k=>b[k]).filter(k=>k!==void 0))];o.push({v:b[e.obj[0]],cur:w.length>1?"?":w[0],q:y})}}else{let b=[...new Set(g)];o.push({v:p,cur:b.length>1?"?":b[0],drop:r,q:y})}}}if(i.length>0){if(new Set(i).size>1)return pe;for(let[d,a]of o.entries())if(a.cur===void 0)o[d]={...a,cur:i[0]};else if(typeof a.cur!="string"||a.cur.toLowerCase()!==i[0])return pe}let u=Y(t);return Math.max(W(u,s),W(u,JSON.stringify(n)))>o.length+c?$:o}var Z=/[\s,]+|#[^\n\r]*|("(?:[^"\\\n\r]|\\.)*")|(\.\.\.|[!$&():=@[\]{|}])|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|([_A-Za-z]\w*)/y;function ht(e,t,n,s){let r=s,o=r?.variables??{},i=r?.query;if(!r||typeof r!="object"||Array.isArray(r)||typeof i!="string"||i.includes('"""')||typeof o!="object"||Array.isArray(o))return $;let c=[];for(Z.lastIndex=0;Z.lastIndex<i.length;){let h=Z.exec(i);if(!h)return $;let g=h[1]??h[2]??h[3]??h[4];g!==void 0&&c.push(g)}let u=0,d=()=>c[u],a=h=>{let g=c[u++];if(g===void 0||h!==void 0&&g!==h)throw new Error;return g},l=()=>{let h=a();if(!/^[_A-Za-z]/.test(h))throw new Error;return h},f=()=>{let h=a();if(h==="$"){let g=l();if(!Object.hasOwn(o,g))throw new Error;return o[g]}if(h==="["){let g=[];for(;d()!=="]";)g.push(f());return a(),g}if(h==="{"){let g={};for(;d()!=="}";){let y=l();a(":"),g[y]=f()}return a(),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(a();d()!==")";){let g=l();a(":"),h[g]=f()}return a(),h},p=()=>{for(let h=1;h>0;){let g=a();h+=g==="{"?1:g==="}"?-1:0}};try{let h="query";if(d()!=="{"&&(h=a(),d()!=="("&&d()!=="{"&&l(),d()==="(")){for(a();a()!==")";)if(c[u-1]==="=")throw new Error}a("{");let g=[];if(h==="query")p();else{if(h!=="mutation")throw new Error;for(;d()!=="}";){let y=l();d()===":"&&(a(),y=l());let b=m();for(;d()==="@";){if(a(),l()!=="idempotent")throw new Error;m()}d()==="{"&&(a(),p());let w=n.find(k=>k.endsWith(` ${y}`));g.push(w?V(e,t[w],b,JSON.stringify(b),e.nameless?.includes(w)):$)}if(a(),g.length===0)throw new Error}if(u<c.length)throw new Error;return h==="query"?"read":g}catch{return $}}var T=(e,t,n)=>{e.set(t,[...e.get(t)??[],n])};function $e(e,t,n,s){let r=Y(e);if([...t.keys()].some(d=>!e.includes(d)&&W(r,d)>0))return $;let o=t.get("currency")??[],i=d=>d.some(a=>a.d)||new Set(d.map(a=>a.w)).size>1?"?":d[0]?.w,c=[],u=0;for(let d of e){let a=t.get(d)??[];if(u+=a.length,a.length===0)continue;let l=i(a);if(l==="?")return $;c.push({v:l,cur:o.length>0?i(o):void 0,drop:s})}return W(Y(e),n)>u?$:c}function J(e,t,n){let s=t.w.indexOf("=");if(s<=0||t.w.slice(0,s).includes("$"))return!1;let r=t.w.slice(0,s),o=t.w.slice(s+1);try{r=decodeURIComponent(r.replace(/\+/g," ")),n&&(o=decodeURIComponent(o.replace(/\+/g," ")))}catch{return!1}return T(e,r,{w:o,d:t.d&&o.includes("$"),x:!1}),!0}function yt(e,t,n,s,r){let o=[],i=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&>.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 $;if(h==="data"){if(!J(i,g,!1))return $}else T(i,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"&&!J(i,h,!1))return $}else o.push(n[l])}let[c="",u=""]=o.map(l=>l.w);if(c==="get"||u==="list"||u==="retrieve")return"read";let d=`${c} ${u}`,a=Object.hasOwn(t,d)?d:/^(?:post|delete)$/.test(c)&&u[0]==="/"?be(t,u.split("?")[0]).find(l=>!l.includes(" ")):void 0;if(!a)return r;if(a!==d){if(o[1].d)return $;for(let[l,f]of new URLSearchParams(u.includes("?")?u.slice(u.indexOf("?")+1):""))T(i,l,{w:f,d:!1,x:!1})}return $e(t[a],i,s,!!e.nameless?.includes(a))}function wt(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 bt=(e,t)=>{let n=wt(t);return n&&e.hosts.some(s=>n.hostname===s||n.hostname.endsWith(`.${s}`))?n:null};function $t(e,t,n,s,r){let o=null,i="",c="",u=!1,d=!1,a=[];for(let y=0;y<n.length;y++){let{w:b,d:w}=n[y];if(b.startsWith("--")){let k=b.slice(2);if(/^(?:next|config|variable|expand-.*|upload-file)$|=/.test(k))return $;if(/^(?:no-)?(?:get|head)$/.test(k)&&(u=k[0]!=="n"),/^(?:no-)?globoff$/.test(k)&&(d=k[0]!=="n"),ft.test(k))continue;let _=n[++y];if(!_)return $;pt.test(k)?a.push({v:_,how:k}):k==="request"&&(c=_.w.toUpperCase())}else if(/^-./.test(b))for(let k=1;k<b.length;k++){let _=b[k];if(_==="K"||_===":"||_==="T")return $;if((_==="G"||_==="I")&&(u=!0),_==="g"&&(d=!0),dt.includes(_))continue;let A=k+1<b.length?{w:b.slice(k+1),d:w,x:!1}:n[++y];if(!A)return $;_==="d"||_==="F"?a.push({v:A,how:_==="d"?"data":"form"}):_==="X"&&(c=A.w.toUpperCase());break}else{let k=bt(e,b);if(!k)continue;if(w||o)return $;o=k,i=b}}if(!o)return null;if(/^(?:GET|HEAD|OPTIONS)$/.test(c||(u||a.length===0?"GET":"POST")))return"read";if(!d&&/[{}[\]]/.test(i))return lt;if(e.json&&u&&a.length>0)return $;let l;try{l=decodeURIComponent(o.pathname)}catch{return $}let f=be(t,l),m=f.find(y=>!y.includes(" "));if(!m&&f.length===0)return r;let p=new Map;for(let[y,b]of o.searchParams)T(p,y,{w:b,d:!1,x:!1});let h;for(let{v:y,how:b}of a){let w=y.w.trim();if(w[0]==="{"||w[0]==="["){if(y.d||h!==void 0)return $;try{h=JSON.parse(w)}catch{return $}}else for(let k of w.split("&"))if(!J(p,{w:k,d:y.d,x:!1},!/urlencode|form/.test(b)))return $}if((h!==void 0||e.json)&&p.size>0)return $;if(!m){let y=h===void 0||p.size>0?$:ht(e,t,f,h);return typeof y=="string"?y:{many:y}}let g=!!e.nameless?.includes(m);return h!==void 0?V(e,t[m],h,s,g):$e(t[m],p,s,g)}function kt(e,t,n,s){let r=n.input?.command,o=typeof r=="string"&&!ct.test(r)?mt(r):null;if(!o)return $;let i=[],c=new RegExp([...e.servers,...e.clis].join("|"),"i");for(let u of o){let d=u.map(p=>p.w).join(" "),a=0;for(;a<u.length&&ut.test(u[a].w);)a++;let l=(u[a]?.w??"").replace(/^.*\//,""),f=u.slice(a+1),m=e.clis.includes(l)?yt(e,t,f,d,s):l==="curl"?$t(e,t,f,d,s):null;if(m===null){if(!/^(?:cd|pushd)$/.test(l)&&u.some(p=>c.test(p.w)))return $;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"&&i.push(...typeof m=="object"&&!Array.isArray(m)?m.many:[m])}return i.length<n.parts.filter(u=>z(u)===e).length?$:i}var X="this call doesn't say how much it moves",ge=e=>typeof e=="number"?Number.isFinite(e)&&e>=0?String(e):"":typeof e=="string"?e.trim():"",me=/^(\d+)(?:\.(\d+))?$/;function ke(e,t,n){if(e.length===0)return X;let s=0n,r=0;for(let{v:o,cur:i,drop:c,q:u}of e){let d=c&&(i===void 0||typeof i=="string"&&i.toLowerCase()===n.currency)?void 0:i,a=d===void 0?n.bare?n.currency:null:typeof d=="string"&&/^[a-z]{3}$/i.test(d)?d.toLowerCase():"?";if(a===null)return"Anvil can't tell which currency this moves";if(a!==n.currency)return a==="?"?$:`it's in ${a.toUpperCase()}, not ${n.currency.toUpperCase()}`;let l=(t.minor?/^(\d+)()$/:me).exec(ge(o)),f=u===void 0?null:me.exec(ge(u));if(!l||u!==void 0&&!f||(l[1]+(l[2]??"")).length>30||f!==null&&(f[1]+(f[2]??"")).length>30)return $;let m=(t.minor?t.digits?.[a]??n.digits:(l[2]??"").length)+(f?.[2]??"").length,p=Math.max(r,m);s=s*10n**BigInt(p-r)+BigInt(l[1]+(l[2]??""))*BigInt(f?f[1]+(f[2]??""):1)*10n**BigInt(p-m),r=p}return[s,r]}function he(e,t,n){let s=e.toString().padStart(t+1,"0"),r=s.slice(0,s.length-t),o="";for(let i=r.length;i>0;i-=3)o=`${r.slice(Math.max(0,i-3),i)}${o?`,${o}`:""}`;return`${n}${o}${t>0?`.${s.slice(-t)}`:""}`}function ve(e,t,n){let s=z(t),r=e.invoice?s?.invoices:s?.at,o=n.tool?.startsWith("mcp__")?n.tool.split("__").slice(2).join("__"):"",i=n.input,c=!i||Object.hasOwn(r??{},o)?o:`${o} ${String(i.service).toLowerCase()} ${String(i.method)}`,u=e.invoice?ye:$;return!s||!r||!e.apps.includes(s.app)?$:t.action!==we?kt(s,r,n,u):i&&Object.hasOwn(r,c)?[V(s,r[c],i,JSON.stringify(i),s.nameless?.includes(c))]:u}function vt(e,t,n){let s=ve(e,t,n);if(typeof s=="string")return s;if(s.length===0)return X;let r=0n;for(let o of s){let i=typeof o=="string"?o:ke(o,z(t),e);if(typeof i=="string")return i;let[c,u]=i,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 _t(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 s=t?.parts.filter(o=>e.kinds.includes(o.action)&&(!e.match||K(e.match,[o],t)!==null))??[];if(s.length===0)return"Anvil can't tell how much this moves";let r=0;for(let o of s){let i=vt(n,o,t);if(typeof i=="string")return i;r+=i}return Number.isSafeInteger(r)?r:"Anvil can't count an amount that large"}function _e(e,t,n){try{return Ct(e,t,n)}catch{return{hit:"unknown",why:"Anvil can't read the amount this moves"}}}function Ct(e,t,n){let s=z(t),r=ve(e,t,n),o=c=>e.invoice&&c===X?ye:c;if(typeof r=="string")return{hit:"unknown",why:o(r)};let i=null;for(let c of r){let u=typeof c=="string"?c:ke(c,s,e);if(typeof u=="string"){i??=u;continue}let[d,a]=u,l=Math.max(a,e.digits),f=d*10n**BigInt(l-a),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:`${he(p,h,e.sign)} is ${it[e.op]} ${he(BigInt(e.value),e.digits,e.sign).replace(/\.0+$/,"")}`}}return i===null?null:{hit:"unknown",why:o(i)}}import{existsSync as G,readdirSync as an,statSync as Ue}from"fs";import{dirname as ie,isAbsolute as ln,join as C,posix as cn,resolve as L}from"path";import{posix as On}from"path";var xt=null;function D(){return xt??process.platform==="win32"}function Ce(e){if(!D())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 F(e){return D()?Ce(e)??e:e}import{createHash as Wr}from"crypto";import{appendFileSync as zr,closeSync as nn,constants as He,fstatSync as rn,mkdirSync as Dr,openSync as on,readdirSync as Fr,readFileSync as qr,readSync as sn,renameSync as Hr,statSync as Ur,unlinkSync as Gr,writeFileSync as Br}from"fs";import{homedir as Zr}from"os";import{dirname as Jr,join as Vr}from"path";import{domainToASCII as At}from"url";var Rt="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",Nt="klaviyo himalaya convertkit api.kit.com activecampaign api-us1.com activehosted constantcontact constant_contact api.cc.email beehiiv helpscout help_scout freshdesk substack",te=e=>e.toLowerCase().replace(/[^a-z0-9]/g,""),St=null,ne={has:e=>(St??=new Set(Rt.split(" "))).has(e)},Pe=/^(?:from|sender|replyto|returnpath|envelopefrom|mailfrom|bounce)|^(?:useremail|usergoogleemail|account|accountemail|organizer|owner|user|mailbox|asm)$/,re=/(?:contact|member|participant|attendee|guest|invitee|person|people|subscriber|customer|recipient|audience|segment|list|group)(?:id|ids|s)?$|userids$|identifiers$|campaignids?$/,Ee=/^(?:draft|(?:draft|message|msg|email|thread|conversation|originalmessage|replytomessage|parentmessage)ids?|inreplyto|references)$/,jt=/^(?:instructions?|prompt|task)$/,Oe=/ids?$/,Me=/^(?: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$/,Pt=/^(?:email|emailaddress|address|mail|addr)$/,Et=null,Ot={exec:e=>(Et??=new RegExp(`(?:^|[^a-z0-9])(${Nt.replace(/\./g,"\\.").replace(/ /g,"|")})`)).exec(e)},oe=/send.{0,20}draft|draft.{0,20}send|(?<!no-?)reply|\/messages\/[^/?\s]+\/[^?\s]{0,200}send/,Ie=/\$batch|(?:^|[^a-z])(?:batch|jmap)(?:[^a-z]|$)|multi_?execute|(?:^|[^a-z])execute(?:[^a-z]|$)|graphql|(?:^|[^a-z])(?:api_?)?request(?:[^a-z]|$)/,Mt=/^(?: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)$|[%!]/,It=/(?:^|\.)(?:googlegroups\.com|groups\.io)$|^(?:lists?|groups?)\./;function se(e){let t=At(e.normalize("NFKC").toLowerCase().replace(/\.$/,""));return/^[a-z0-9_-]+(?:\.[a-z0-9_-]+)+$/.test(t)?t:""}function Lt(e){let t=e.trim().replace(/^mailto:/i,""),n=/<([^<>]*)>$/.exec(t);n&&(t=n[1].trim());let s=t.length;for(;s>0&&`"'`.includes(t[s-1]);)s--;t=t.slice(0,s).replace(/^["']+/,"");let r=/^([^\s@<>(),;:"[\]]+)@([^\s@<>(),;:"[\]]+)$/u.exec(t),o=r?se(r[2]):"";if(!o)return null;let i=r[1].normalize("NFKC").toLowerCase().replace(/(?<=.)\+.*$/,"");return(o==="gmail.com"||o==="googlemail.com")&&(i=i.replace(/\./g,""),o="gmail.com"),{shown:t,local:i,domain:o,alien:/[^\x00-\x7f]/.test(t)||/(?:^|\.)xn--/.test(o),group:Mt.test(i)||It.test(o)}}function U(e){let t=[],n=!/[<"]/.test(e),s="",r=!1,o=!1;for(let i=0;i<e.length;i++){let c=e[i];if(r&&c==="\\"){s+=c+(e[++i]??"");continue}c==='"'?r=!r:c==="<"?o=!0:c===">"&&(o=!1),!r&&!o&&(c===","||c===";"||n&&/\s/.test(c))?(t.push(s),s=""):s+=c}return t.push(s),r||o?[null]:t.filter(i=>i.trim()).map(i=>(i.replace(/"(?:[^"\\]|\\.)*"/g,"").match(/@/g)??[]).length===1?Lt(i):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",xe="Anvil can't read who this goes to: its body can't be read",M="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",Le="Anvil can't read who this goes to: it runs a batch, or any request";function S(e,t){for(let n of U(e))n?(t.list.push(n),t.known=!0):t.why??=`${v} ("${e.trim().slice(0,40)}")`}function We(e,t){let n=e.includes(`
|
|
4
|
+
`,a)-1,a<0)break;continue}else{if(/[(){}]/.test(l))return null;if(l==="<"||l===">"||l==="&"&&e[a+1]===">"){if((i||!/^\d+$/.test(n))&&d(),n="",s=r=o=i=c=!1,u)return null;l==="&"&&a++,(e[a]===">"?/[>|&]/:/[&>]/).test(e[a+1]??"")&&a++,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==="$"&&(s=r=!0),/[*?[]/.test(l)&&(o=!0),n+=l}}c=!0}return d(),u?null:t}function be(e,t){let n=t.replace(/\/{2,}/g,"/").replace(/(.)\/$/,"$1").split("/");return Object.keys(e).filter(s=>{let r=s.split(" ")[0].split("/");return s[0]==="/"&&r.length===n.length&&r.every((o,i)=>o==="*"?n[i]!=="":o===n[i])})}var Y=e=>e.filter(t=>t[0]!=="!"&&t[0]!=="$").map(t=>t.replace(/^~/,"").split(" ")[0]);function T(e,t){return[...new Set(e.map(n=>n.split(".").pop()))].reduce((n,s)=>n+(t.match(new RegExp(`(?:(?<![a-z0-9_]|[a-z0-9]-)|(?<=(?:^|\\s)-[a-z]+))${s.replace(/_/g,"[-_]")}(?![a-z0-9_]|-[a-z0-9])`,"gi"))?.length??0),0)}function X(e,t,n,s,r){let o=[],i=[],c=0;for(let d of t){let a=/^[!~$]/.test(d)?d[0]:"",[l="",f]=d.slice(a.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 $;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(a==="!"&&m.some(p=>p.v!==!1))return at;if(a==="~"&&(c+=m.length),a==="$")for(let{v:p}of m){if(typeof p!="string")return $;i.push(p.toLowerCase())}if(!a)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 $;if(e.obj){if(typeof p!="object"||Array.isArray(p))return $;{let b=p,w=[...new Set(e.obj.slice(1).map(k=>b[k]).filter(k=>k!==void 0))];o.push({v:b[e.obj[0]],cur:w.length>1?"?":w[0],q:y})}}else{let b=[...new Set(g)];o.push({v:p,cur:b.length>1?"?":b[0],drop:r,q:y})}}}if(i.length>0){if(new Set(i).size>1)return ge;for(let[d,a]of o.entries())if(a.cur===void 0)o[d]={...a,cur:i[0]};else if(typeof a.cur!="string"||a.cur.toLowerCase()!==i[0])return ge}let u=Y(t);return Math.max(T(u,s),T(u,JSON.stringify(n)))>o.length+c?$:o}var Z=/[\s,]+|#[^\n\r]*|("(?:[^"\\\n\r]|\\.)*")|(\.\.\.|[!$&():=@[\]{|}])|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|([_A-Za-z]\w*)/y;function ht(e,t,n,s){let r=s,o=r?.variables??{},i=r?.query;if(!r||typeof r!="object"||Array.isArray(r)||typeof i!="string"||i.includes('"""')||typeof o!="object"||Array.isArray(o))return $;let c=[];for(Z.lastIndex=0;Z.lastIndex<i.length;){let h=Z.exec(i);if(!h)return $;let g=h[1]??h[2]??h[3]??h[4];g!==void 0&&c.push(g)}let u=0,d=()=>c[u],a=h=>{let g=c[u++];if(g===void 0||h!==void 0&&g!==h)throw new Error;return g},l=()=>{let h=a();if(!/^[_A-Za-z]/.test(h))throw new Error;return h},f=()=>{let h=a();if(h==="$"){let g=l();if(!Object.hasOwn(o,g))throw new Error;return o[g]}if(h==="["){let g=[];for(;d()!=="]";)g.push(f());return a(),g}if(h==="{"){let g={};for(;d()!=="}";){let y=l();a(":"),g[y]=f()}return a(),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(a();d()!==")";){let g=l();a(":"),h[g]=f()}return a(),h},p=()=>{for(let h=1;h>0;){let g=a();h+=g==="{"?1:g==="}"?-1:0}};try{let h="query";if(d()!=="{"&&(h=a(),d()!=="("&&d()!=="{"&&l(),d()==="(")){for(a();a()!==")";)if(c[u-1]==="=")throw new Error}a("{");let g=[];if(h==="query")p();else{if(h!=="mutation")throw new Error;for(;d()!=="}";){let y=l();d()===":"&&(a(),y=l());let b=m();for(;d()==="@";){if(a(),l()!=="idempotent")throw new Error;m()}d()==="{"&&(a(),p());let w=n.find(k=>k.endsWith(` ${y}`));g.push(w?X(e,t[w],b,JSON.stringify(b),e.nameless?.includes(w)):$)}if(a(),g.length===0)throw new Error}if(u<c.length)throw new Error;return h==="query"?"read":g}catch{return $}}var z=(e,t,n)=>{e.set(t,[...e.get(t)??[],n])};function $e(e,t,n,s){let r=Y(e);if([...t.keys()].some(d=>!e.includes(d)&&T(r,d)>0))return $;let o=t.get("currency")??[],i=d=>d.some(a=>a.d)||new Set(d.map(a=>a.w)).size>1?"?":d[0]?.w,c=[],u=0;for(let d of e){let a=t.get(d)??[];if(u+=a.length,a.length===0)continue;let l=i(a);if(l==="?")return $;c.push({v:l,cur:o.length>0?i(o):void 0,drop:s})}return T(Y(e),n)>u?$:c}function J(e,t,n){let s=t.w.indexOf("=");if(s<=0||t.w.slice(0,s).includes("$"))return!1;let r=t.w.slice(0,s),o=t.w.slice(s+1);try{r=decodeURIComponent(r.replace(/\+/g," ")),n&&(o=decodeURIComponent(o.replace(/\+/g," ")))}catch{return!1}return z(e,r,{w:o,d:t.d&&o.includes("$"),x:!1}),!0}function yt(e,t,n,s,r){let o=[],i=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&>.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 $;if(h==="data"){if(!J(i,g,!1))return $}else z(i,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"&&!J(i,h,!1))return $}else o.push(n[l])}let[c="",u=""]=o.map(l=>l.w);if(c==="get"||u==="list"||u==="retrieve")return"read";let d=`${c} ${u}`,a=Object.hasOwn(t,d)?d:/^(?:post|delete)$/.test(c)&&u[0]==="/"?be(t,u.split("?")[0]).find(l=>!l.includes(" ")):void 0;if(!a)return r;if(a!==d){if(o[1].d)return $;for(let[l,f]of new URLSearchParams(u.includes("?")?u.slice(u.indexOf("?")+1):""))z(i,l,{w:f,d:!1,x:!1})}return $e(t[a],i,s,!!e.nameless?.includes(a))}function wt(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 bt=(e,t)=>{let n=wt(t);return n&&e.hosts.some(s=>n.hostname===s||n.hostname.endsWith(`.${s}`))?n:null};function $t(e,t,n,s,r){let o=null,i="",c="",u=!1,d=!1,a=[];for(let y=0;y<n.length;y++){let{w:b,d:w}=n[y];if(b.startsWith("--")){let k=b.slice(2);if(/^(?:next|config|variable|expand-.*|upload-file)$|=/.test(k))return $;if(/^(?:no-)?(?:get|head)$/.test(k)&&(u=k[0]!=="n"),/^(?:no-)?globoff$/.test(k)&&(d=k[0]!=="n"),ft.test(k))continue;let _=n[++y];if(!_)return $;pt.test(k)?a.push({v:_,how:k}):k==="request"&&(c=_.w.toUpperCase())}else if(/^-./.test(b))for(let k=1;k<b.length;k++){let _=b[k];if(_==="K"||_===":"||_==="T")return $;if((_==="G"||_==="I")&&(u=!0),_==="g"&&(d=!0),dt.includes(_))continue;let A=k+1<b.length?{w:b.slice(k+1),d:w,x:!1}:n[++y];if(!A)return $;_==="d"||_==="F"?a.push({v:A,how:_==="d"?"data":"form"}):_==="X"&&(c=A.w.toUpperCase());break}else{let k=bt(e,b);if(!k)continue;if(w||o)return $;o=k,i=b}}if(!o)return null;if(/^(?:GET|HEAD|OPTIONS)$/.test(c||(u||a.length===0?"GET":"POST")))return"read";if(!d&&/[{}[\]]/.test(i))return lt;if(e.json&&u&&a.length>0)return $;let l;try{l=decodeURIComponent(o.pathname)}catch{return $}let f=be(t,l),m=f.find(y=>!y.includes(" "));if(!m&&f.length===0)return r;let p=new Map;for(let[y,b]of o.searchParams)z(p,y,{w:b,d:!1,x:!1});let h;for(let{v:y,how:b}of a){let w=y.w.trim();if(w[0]==="{"||w[0]==="["){if(y.d||h!==void 0)return $;try{h=JSON.parse(w)}catch{return $}}else for(let k of w.split("&"))if(!J(p,{w:k,d:y.d,x:!1},!/urlencode|form/.test(b)))return $}if((h!==void 0||e.json)&&p.size>0)return $;if(!m){let y=h===void 0||p.size>0?$:ht(e,t,f,h);return typeof y=="string"?y:{many:y}}let g=!!e.nameless?.includes(m);return h!==void 0?X(e,t[m],h,s,g):$e(t[m],p,s,g)}function kt(e,t,n,s){let r=n.input?.command,o=typeof r=="string"&&!ct.test(r)?mt(r):null;if(!o)return $;let i=[],c=new RegExp([...e.servers,...e.clis].join("|"),"i");for(let u of o){let d=u.map(p=>p.w).join(" "),a=0;for(;a<u.length&&ut.test(u[a].w);)a++;let l=(u[a]?.w??"").replace(/^.*\//,""),f=u.slice(a+1),m=e.clis.includes(l)?yt(e,t,f,d,s):l==="curl"?$t(e,t,f,d,s):null;if(m===null){if(!/^(?:cd|pushd)$/.test(l)&&u.some(p=>c.test(p.w)))return $;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"&&i.push(...typeof m=="object"&&!Array.isArray(m)?m.many:[m])}return i.length<n.parts.filter(u=>O(u)===e).length?$:i}var Q="this call doesn't say how much it moves",me=e=>typeof e=="number"?Number.isFinite(e)&&e>=0?String(e):"":typeof e=="string"?e.trim():"",he=/^(\d+)(?:\.(\d+))?$/;function ke(e,t,n){if(e.length===0)return Q;let s=0n,r=0;for(let{v:o,cur:i,drop:c,q:u}of e){let d=c&&(i===void 0||typeof i=="string"&&i.toLowerCase()===n.currency)?void 0:i,a=d===void 0?n.bare?n.currency:null:typeof d=="string"&&/^[a-z]{3}$/i.test(d)?d.toLowerCase():"?";if(a===null)return"Anvil can't tell which currency this moves";if(a!==n.currency)return a==="?"?$:`it's in ${a.toUpperCase()}, not ${n.currency.toUpperCase()}`;let l=(t.minor?/^(\d+)()$/:he).exec(me(o)),f=u===void 0?null:he.exec(me(u));if(!l||u!==void 0&&!f||(l[1]+(l[2]??"")).length>30||f!==null&&(f[1]+(f[2]??"")).length>30)return $;let m=(t.minor?t.digits?.[a]??n.digits:(l[2]??"").length)+(f?.[2]??"").length,p=Math.max(r,m);s=s*10n**BigInt(p-r)+BigInt(l[1]+(l[2]??""))*BigInt(f?f[1]+(f[2]??""):1)*10n**BigInt(p-m),r=p}return[s,r]}function ye(e,t,n){let s=e.toString().padStart(t+1,"0"),r=s.slice(0,s.length-t),o="";for(let i=r.length;i>0;i-=3)o=`${r.slice(Math.max(0,i-3),i)}${o?`,${o}`:""}`;return`${n}${o}${t>0?`.${s.slice(-t)}`:""}`}function ve(e,t,n){let s=O(t),r=e.invoice?s?.invoices:s?.at,o=n.tool?.startsWith("mcp__")?n.tool.split("__").slice(2).join("__"):"",i=n.input,c=!i||Object.hasOwn(r??{},o)?o:`${o} ${String(i.service).toLowerCase()} ${String(i.method)}`,u=e.invoice?we:$;return!s||!r||!e.apps.includes(s.app)?$:t.action!==V?kt(s,r,n,u):i&&Object.hasOwn(r,c)?[X(s,r[c],i,JSON.stringify(i),s.nameless?.includes(c))]:u}function vt(e,t,n){let s=ve(e,t,n);if(typeof s=="string")return s;if(s.length===0)return Q;let r=0n;for(let o of s){let i=typeof o=="string"?o:ke(o,O(t),e);if(typeof i=="string")return i;let[c,u]=i,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 _t(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 s=t?.parts.filter(i=>e.kinds.includes(i.action)&&(!e.match||K(e.match,[i],t)!==null))??[];if(s.length===0)return"Anvil can't tell how much this moves";let r=0,o=new Set;for(let i of s){let c=O(i),u=c?`${c.app}\0${i.action===V}`:null;if(u!==null&&o.has(u))continue;u!==null&&o.add(u);let d=vt(n,i,t);if(typeof d=="string")return d;r+=d}return Number.isSafeInteger(r)?r:"Anvil can't count an amount that large"}function _e(e,t,n){try{return Ct(e,t,n)}catch{return{hit:"unknown",why:"Anvil can't read the amount this moves"}}}function Ct(e,t,n){let s=O(t),r=ve(e,t,n),o=c=>e.invoice&&c===Q?we:c;if(typeof r=="string")return{hit:"unknown",why:o(r)};let i=null;for(let c of r){let u=typeof c=="string"?c:ke(c,s,e);if(typeof u=="string"){i??=u;continue}let[d,a]=u,l=Math.max(a,e.digits),f=d*10n**BigInt(l-a),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:`${ye(p,h,e.sign)} is ${it[e.op]} ${ye(BigInt(e.value),e.digits,e.sign).replace(/\.0+$/,"")}`}}return i===null?null:{hit:"unknown",why:o(i)}}import{existsSync as G,readdirSync as an,statSync as Ue}from"fs";import{dirname as ae,isAbsolute as ln,join as C,posix as cn,resolve as W}from"path";import{posix as On}from"path";var xt=null;function D(){return xt??process.platform==="win32"}function Ce(e){if(!D())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 F(e){return D()?Ce(e)??e:e}import{createHash as Wr}from"crypto";import{appendFileSync as zr,closeSync as nn,constants as He,fstatSync as rn,mkdirSync as Dr,openSync as on,readdirSync as Fr,readFileSync as qr,readSync as sn,renameSync as Hr,statSync as Ur,unlinkSync as Gr,writeFileSync as Br}from"fs";import{homedir as Zr}from"os";import{dirname as Jr,join as Vr}from"path";import{domainToASCII as At}from"url";var Rt="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",Nt="klaviyo himalaya convertkit api.kit.com activecampaign api-us1.com activehosted constantcontact constant_contact api.cc.email beehiiv helpscout help_scout freshdesk substack",ne=e=>e.toLowerCase().replace(/[^a-z0-9]/g,""),St=null,re={has:e=>(St??=new Set(Rt.split(" "))).has(e)},Pe=/^(?:from|sender|replyto|returnpath|envelopefrom|mailfrom|bounce)|^(?:useremail|usergoogleemail|account|accountemail|organizer|owner|user|mailbox|asm)$/,oe=/(?:contact|member|participant|attendee|guest|invitee|person|people|subscriber|customer|recipient|audience|segment|list|group)(?:id|ids|s)?$|userids$|identifiers$|campaignids?$/,Ee=/^(?:draft|(?:draft|message|msg|email|thread|conversation|originalmessage|replytomessage|parentmessage)ids?|inreplyto|references)$/,jt=/^(?:instructions?|prompt|task)$/,Oe=/ids?$/,Me=/^(?: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$/,Pt=/^(?:email|emailaddress|address|mail|addr)$/,Et=null,Ot={exec:e=>(Et??=new RegExp(`(?:^|[^a-z0-9])(${Nt.replace(/\./g,"\\.").replace(/ /g,"|")})`)).exec(e)},se=/send.{0,20}draft|draft.{0,20}send|(?<!no-?)reply|\/messages\/[^/?\s]+\/[^?\s]{0,200}send/,Ie=/\$batch|(?:^|[^a-z])(?:batch|jmap)(?:[^a-z]|$)|multi_?execute|(?:^|[^a-z])execute(?:[^a-z]|$)|graphql|(?:^|[^a-z])(?:api_?)?request(?:[^a-z]|$)/,Mt=/^(?: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)$|[%!]/,It=/(?:^|\.)(?:googlegroups\.com|groups\.io)$|^(?:lists?|groups?)\./;function ie(e){let t=At(e.normalize("NFKC").toLowerCase().replace(/\.$/,""));return/^[a-z0-9_-]+(?:\.[a-z0-9_-]+)+$/.test(t)?t:""}function Lt(e){let t=e.trim().replace(/^mailto:/i,""),n=/<([^<>]*)>$/.exec(t);n&&(t=n[1].trim());let s=t.length;for(;s>0&&`"'`.includes(t[s-1]);)s--;t=t.slice(0,s).replace(/^["']+/,"");let r=/^([^\s@<>(),;:"[\]]+)@([^\s@<>(),;:"[\]]+)$/u.exec(t),o=r?ie(r[2]):"";if(!o)return null;let i=r[1].normalize("NFKC").toLowerCase().replace(/(?<=.)\+.*$/,"");return(o==="gmail.com"||o==="googlemail.com")&&(i=i.replace(/\./g,""),o="gmail.com"),{shown:t,local:i,domain:o,alien:/[^\x00-\x7f]/.test(t)||/(?:^|\.)xn--/.test(o),group:Mt.test(i)||It.test(o)}}function U(e){let t=[],n=!/[<"]/.test(e),s="",r=!1,o=!1;for(let i=0;i<e.length;i++){let c=e[i];if(r&&c==="\\"){s+=c+(e[++i]??"");continue}c==='"'?r=!r:c==="<"?o=!0:c===">"&&(o=!1),!r&&!o&&(c===","||c===";"||n&&/\s/.test(c))?(t.push(s),s=""):s+=c}return t.push(s),r||o?[null]:t.filter(i=>i.trim()).map(i=>(i.replace(/"(?:[^"\\]|\\.)*"/g,"").match(/@/g)??[]).length===1?Lt(i):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",xe="Anvil can't read who this goes to: its body can't be read",I="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",Le="Anvil can't read who this goes to: it runs a batch, or any request";function S(e,t){for(let n of U(e))n?(t.list.push(n),t.known=!0):t.why??=`${v} ("${e.trim().slice(0,40)}")`}function We(e,t){let n=e.includes(`
|
|
5
5
|
`)?e:Buffer.from(e,"base64").toString("utf8"),s=/\r?\n\r?\n/.exec(n),r=s?n.slice(0,s.index+s[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 o of r.replace(/\r?\n[ \t]+/g," ").split(/\r?\n/)){let i=/^(?:resent-)?(?:to|cc|bcc)\s*:/i.exec(o);i&&S(o.slice(i[0].length),t)}}function Ae(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 s=n+1;for(;/\s/.test(e[s]??"");)s++;e[s]===":"&&t++}return t}function Te(e,t){let n;try{n=/^\s*[[{]/.test(e)?JSON.parse(e):void 0}catch{n=void 0}return n!==void 0&&Ae(e)!==Ae(JSON.stringify(n))&&(t.why??=`${v}: it names a field twice`),n}function R(e,t,n=!1,s=0,r=!1,o=!1){if(s>12)t.why??=v;else if(typeof e=="string"){if(n)S(e,t);else if(!r&&!/[\s@]/.test(e)&&/[/_.]/.test(e)&&
|
|
6
|
+
`)&&/(?<!\r)\n/.test(r))&&(t.why??=`${v}: its message can't be read`);for(let o of r.replace(/\r?\n[ \t]+/g," ").split(/\r?\n/)){let i=/^(?:resent-)?(?:to|cc|bcc)\s*:/i.exec(o);i&&S(o.slice(i[0].length),t)}}function Ae(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 s=n+1;for(;/\s/.test(e[s]??"");)s++;e[s]===":"&&t++}return t}function Te(e,t){let n;try{n=/^\s*[[{]/.test(e)?JSON.parse(e):void 0}catch{n=void 0}return n!==void 0&&Ae(e)!==Ae(JSON.stringify(n))&&(t.why??=`${v}: it names a field twice`),n}function R(e,t,n=!1,s=0,r=!1,o=!1){if(s>12)t.why??=v;else if(typeof e=="string"){if(n)S(e,t);else if(!r&&!/[\s@]/.test(e)&&/[/_.]/.test(e)&&se.test(e.toLowerCase()))t.why??=I;else if(!r){let i=Te(e,t),c=i===void 0?U(e):[];if(i!==void 0)R(i,t,!1,s+1,!1,o);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 i of e)R(i,t,n,s+1,r,o);else if(e&&typeof e=="object"){let i=!1;for(let[c,u]of Object.entries(e)){let d=ne(c);u==null||u===""||Array.isArray(u)&&u.length===0||(n?Pt.test(d)&&(i=!0,R(u,t,!0,s+1)):re.has(d)?R(u,t,!0,s+1):d==="raw"&&typeof u=="string"?We(u,t):(Ee.test(d)||d==="id"&&s===0)&&(typeof u!="object"||Array.isArray(u))?(!o||d.startsWith("draft"))&&(t.why??=I):oe.test(d)?t.why??=`${v}: it names a list ("${c}")`:jt.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,s+1,r,o):!Pe.test(d)&&!Oe.test(d)&&R(u,t,!1,s+1,r||Me.test(d),o))}n&&!i&&(t.why??=v)}else n&&e!==null&&e!==void 0&&(t.why??=v)}var ee=(e,t)=>e[t]==="`"||e[t]==="$"&&e[t+1]==="("&&e[t+2]!=="(";function Wt(e){let t=[],n=[],s=!1,r=[],o=[],i="",c=!1,u=!1,d=0,a=[],l=()=>{u&&(d?d===2&&!/^(?:\d+|-)$/.test(i)&&n.push({f:i,dyn:c}):(r.push(i),o.push(c)),d=0),i="",c=u=!1},f=()=>{l(),r.length>0&&t.push({w:r,dyn:o}),r=[],o=[]};for(let m=0;m<e.length;m++){let p=e[m],h=e[m+1];if(p==="\\")h!==void 0&&h!==`
|
|
7
7
|
`&&(i+=h,u=!0),m++;else if(p==="'"||p==="$"&&h==="'"){let g=p==="$"?m+2:m+1,y=e.indexOf("'",g);i+=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)?i+=e[++g]===`
|
|
8
|
-
`?"":y:(s||=
|
|
8
|
+
`?"":y:(s||=ee(e,g),c||=e[g]==="$"||e[g]==="`",i+=e[g])}c||=g>=e.length,u=!0,m=g}else if(p==="$"||p==="`")s||=ee(e,m),i+=p,c=u=!0;else if(p==="#"&&!u){let g=e.indexOf(`
|
|
9
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&&a.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(i)&&!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
10
|
`)for(let[g,y,b]of a.splice(0)){let w=m+1;for(;;){let k=e.indexOf(`
|
|
11
|
-
`,w),_=e.slice(w,k<0?void 0:k);if(w=k<0?e.length:k+1,k<0||(y?_.replace(/^\t+/,""):_)===g)break;for(let A=0;!b&&A<_.length;A++)_[A]==="\\"?A++:s||=Q(_,A)}m=w-1}}else/\s/.test(p)?l():(i+=p,u=!0)}return f(),{list:t,sub:s,writes:n}}function Tt(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 ee=["srAaSqTOuC","cb","tfHE"],Re=["sifmQd","cb","HeF"],zt=E({mail:ee,mailx:ee,"s-nail":ee,sendmail:["fFOpRVNLBXh","","tC"],msmtp:["afCX","","t"],mutt:Re,neomutt:Re}),Ne=/^\s*(?:to|cc|bcc)\s*:/i,q="Anvil can't read who this goes to: it may read them from the message or its settings";function Dt(e,t,n,s,r){let o=zt[e];if(!o){let a=!1;for(let l=s;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];a=!0,m===void 0||n[l]?r.why??=j:S(m,r)}a||(r.why??=v);return}let[i,c,u]=o,d=!1;for(let a=s;a<t.length;a++){let l=t[a];if(d||!l.startsWith("-")||l==="-")n[a]?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[++a];p!==void 0&&Ne.test(p)&&(n[a]?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??=q)}else if(e==="sendmail"&&/^-b[^m]/.test(l))r.why??=q;else if(/mutt/.test(e)&&l.startsWith("-a"))for(;a+1<t.length&&t[a+1]!=="--";)a++;else for(let f=1;f<l.length;f++){let m=l[f];if(u.includes(m)&&(r.why??=q),!i.includes(m)&&!c.includes(m))continue;let p=f+1<l.length?l.slice(f+1):t[++a];/^\s*(?:sendmail|mta)\s*=/i.test(p??"")&&(r.why??=q),n[a]&&"aTC".includes(m)&&i.includes(m)&&(r.why??=j);let h=p!==void 0&&Ne.test(p);if(!c.includes(m)&&!h)break;p===void 0||n[a]?r.why??=j:S(h?p.slice(p.indexOf(":")+1):p,r);break}}}function Se(e){try{return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`http://${e}`)}catch{return null}}var Ft="AbcCdDeEFHKmoPQrtTuUwxXyYz",qt=/^(?:data(?:-ascii|-binary|-raw|-urlencode)?|json|form(?:-string)?|url|header)$/,je=/^(?:config|upload-file|url-query|variable|request-target|mail-rcpt|expand-[\w.-]+)$/,Ht=/^(?: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)$/,Ut=/^(?: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)$/,Gt=/^(?:[oDc]|output|output-dir|dump-header|cookie-jar|stderr|trace|trace-ascii|libcurl|etag-save|hsts|alt-svc)$/,H="Anvil can't read who this goes to: curl takes part of it from elsewhere";function O(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 Bt(e,t,n,s,r,o){let i=0,c=0,u=[],d=[],a=!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=Se(p);if(h?.hostname.toLowerCase().replace(/\.$/,"")!==s)o.why??=`${v}: a URL Anvil reads two ways`;else{c++;let g=h.pathname.toLowerCase();try{g=decodeURIComponent(g)}catch{o.why??=v}oe.test(g)?o.why??=M:Ie.test(g)&&(o.why??=Le);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){i++;for(let w of d)Kt(w,a&&!l,u,o);Zt(u,o)}[c,u,d,a,l]=[0,[],[],!1,!1];continue}let g="",y;if(h.startsWith("--")){let w=/^--([\w.-]+)(=?)/.exec(h);if(g=w?.[1]??"",Ut.test(g.replace(/^no-/,"")))continue;if(g==="remote-header-name"||!qt.test(g)&&!je.test(g)&&!Ht.test(g)){o.why??=g==="remote-header-name"?H:`${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"&&(o.why??=H),Ft.includes(h[w])&&(g=h[w],y=h.slice(w+1)||e[++p]);if(!g)continue}else{if(f){let w=Se(h)?.pathname.split("/").pop()??"";O(w,!1,o);try{O(decodeURIComponent(w),!1,o)}catch{o.why??=v}}m(h);continue}if(y===void 0){o.why??=v;break}let b=t[p]??!1;if(/^[KT]$/.test(g)||je.test(g))o.why??=H;else if(g==="url")m(y);else if(g==="H"||g==="header"){let w=/^\s*content-type\s*:/i.exec(y);y.startsWith("@")?o.why??=H:w?/json/i.test(y.slice(w[0].length))&&!b?a=!0:l=!0:b&&!/^\s*[\w-]+\s*:/.test(y)&&(l=!0)}else if(Gt.test(g))O(y,b,o);else if(g==="F"||g.startsWith("form")||g==="data-urlencode"){let w=y.indexOf("="),k=y.indexOf("@"),_=g==="data-urlencode"?k>=0&&(w<0||k<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("@")?o.why??=`${v}: its body is ${b?"built when the line runs":"read from a file"}`:(a||=g==="json",d.push(y)))}return i}function Kt(e,t,n,s){let r=Te(e,s);if(r!==void 0?R(r,s):t&&(s.why??=xe),!t){r===void 0&&/^[\w-]+\s*:/.test(e)&&We(e,s);for(let o of e.split("&")){let i=o.indexOf("=");try{let c=decodeURIComponent(o.slice(0,Math.max(i,0)).replace(/\+/g," "));/^[\w.[\]-]*$/.test(c)&&(r===void 0||c.split(/[.[\]]+/).map(te).some(u=>ne.has(u)||re.test(u)))&&n.push([c,decodeURIComponent(o.slice(i+1).replace(/\+/g," ")),!1,!1])}catch{s.why??=xe}}}}function Zt(e,t){for(let[n,s,r,o]of e){let i=n.split(/[.[\]]+/).map(te).filter(Boolean),c=i[i.length-1]??"";if(i.some(u=>ne.has(u)))o||r?t.why??=`${v}: it is ${o?"read from a file":"built when the line runs"}`:S(s,t);else if(i.some(u=>re.test(u)))t.why??=`${v}: it names a list ("${n}")`;else if(i.some(u=>Ee.test(u)))t.why??=M;else{if(i.some(u=>Pe.test(u))||Oe.test(c)||i.some(u=>Me.test(u)))continue;r?t.why??=j:o||R(s,t)}}}var Yt=/^(?: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 Jt(e,t,n,s){let r=t.includes("."),o=new RegExp(`(?<![\\w.-])${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w-]|\\.\\w)`),i=l=>o.test(l.replace(/['"\\]/g,"").toLowerCase()),{list:c,sub:u,writes:d}=Wt(e);u&&(s.why??=`${v}: this line runs a command inside another ($(\u2026) or \`\u2026\`), which Anvil doesn't read`);for(let l of d)O(l.f,l.dyn,s);let a=0;for(let l of c){let f=Tt(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)))&&(s.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("-")||O(l.w[m],l.dyn[m],s);!f&&l.w.every(m=>/^[A-Za-z_]\w*\+?=/.test(m))||(f&&r&&f.name==="curl"?a+=Bt(l.w,l.dyn,f.at,t,i,s):f&&!r&&f.name===t?(a++,Dt(f.name,l.w,l.dyn,f.at,s)):(!f||!Yt.test(f.name))&&(s.why??=`${v}: this line also runs ${f?f.name:"a command built when it runs"}, which Anvil doesn't read`))}(a===0||a<n)&&(s.why??=`${v}: Anvil reads a plain curl request or mail program, not this`)}function ze(e,t){let n={list:[],why:null},s=(e.host??"").toLowerCase(),r=e.action==="claude.mcp.side_effect",o=`${s} ${r?t.tool??"":/^[a-z][a-z0-9+.-]*:\/\//i.test(e.target??"")?e.target:""}`.toLowerCase(),i=Ot.exec(o)?.[1];return i?n.why=`Anvil can't read who ${i} sends reach: they go to a list or a ticket`:oe.test(o)?n.why=M:Ie.test(o)?n.why=Le:r&&t.input?R(t.input,n,!1,0,!1,/forward/.test((t.tool??"").split("__").pop().toLowerCase())):!r&&t.command&&s?Jt(t.command,s,t.parts.filter(c=>c.action===e.action&&(c.host??"").toLowerCase()===s).length,n):n.why=v,n.known||(n.why??=v),n}function Vt(e){let t=i=>Array.isArray(i)&&i.every(c=>typeof c=="string")?i:null,n=t(e.domains??[]),s=t(e.addresses??[]);if(!n||!s)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(se),o=s.map(i=>{let[c,u]=U(i);return c&&!u?`${c.local}@${c.domain}`:""});return r.includes("")||o.includes("")?"a recipient condition names an address or a domain Anvil can't read":r.length+o.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:o}}var De=new WeakMap;function Fe(e,t,n){let s=De.get(e);if(s===void 0&&De.set(e,s=Vt(e)),typeof s=="string")return{hit:"unknown",why:`Anvil can't use this rule's recipients (${s})`};let r;try{r=ze(t,n)}catch{return{hit:"unknown",why:"Anvil can't read who this goes to"}}let o=r.why;for(let i of r.list){let c=s.addresses.includes(`${i.local}@${i.domain}`)||s.domains.some(u=>i.domain===u||i.domain.endsWith(`.${u}`));if(s.outside?!c:c)return{hit:"match",detail:s.outside?`${i.shown} is outside ${[...s.domains,...s.addresses.length>0?["the addresses your rule names"]:[]].join(" and ")}`:`it goes to ${i.shown}`};i.group?o??=`${i.shown} may reach ${s.outside?"people outside":"anyone"} (a list or a relay)`:i.alien&&!s.outside&&(o??=`${i.shown} is in letters from another alphabet`)}return o===null?null:{hit:"unknown",why:o}}var Xt="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");function Qt(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 s=(n[1]==="-"?1:-1)*(Number(n[2])*60+Number(n[3]??0)),r=-t.getTimezoneOffset();return r!==s&&!(n[4]!==void 0&&r===s+60)}function qe(e,t,n){let s=new Date(n.now??NaN),r=s.getDay(),o=s.getHours(),i=o*60+s.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(i%60).padStart(2,"0")}`;if(c!==void 0||s.getTimezoneOffset()===0){let d="";try{let a=Intl.DateTimeFormat().resolvedOptions().timeZone;a&&!Qt(c,s)&&(d=s.toLocaleTimeString("en-GB",{timeZone:a,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}))}catch{}if(d!==`${String(o).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)&&i>=d.from&&i<d.to)?{hit:"match",detail:`it's ${Xt[r]} ${o%12||12}${u}${o<12?"am":"pm"}`}:null}import{existsSync as or,readdirSync as sr,realpathSync as ir}from"fs";import{basename as lr,dirname as cr,join as ur}from"path";function I(e,t=8*1024*1024){let n;try{n=on(e,He.O_RDONLY|He.O_NONBLOCK)}catch(s){if(s.code==="ENOENT"||s.code==="ENOTDIR")return null;throw s}try{let s=rn(n);if(!s.isFile())throw new Error(`${e} is not a regular file`);if(s.size>t)throw new Error(`${e} is over ${t} bytes`);let r=Buffer.alloc(s.size),o=0;for(;o<s.size;){let i=sn(n,r,o,s.size-o,o);if(i===0)break;o+=i}return r.subarray(0,o)}finally{nn(n)}}var Qr=256*1024,eo=1024*1024;function Be(e,t){try{let n=typeof e.repo_dir=="string"?F(e.repo_dir):e.repo_dir,s=t===null?null:F(t),r=e.repo_via,o=typeof e.repo_remote=="string"&&e.repo_remote?e.repo_remote:r==="gh"&&process.env.GH_REPO||null;if(typeof n!="string"||!ln(n)||!G(n)||r!=="git"&&r!=="gh"||/[$`]/.test(o??""))return null;if(r==="gh"&&o!==null)return Ge([o],n);let i=un(n,s);if(i===null)return null;let c=new Map;for(let a of i)a.section==="remote"&&a.sub!==null&&(a.key==="url"||(r==="git"?a.key==="pushurl":a.key==="gh-resolved"&&a.value!=="base"))&&c.set(a.sub,[...c.get(a.sub)??[],a.value]);if(o!==null&&!c.has(o)&&!/^[./]|[/:]/.test(o))return null;let u=o!==null?c.get(o)??[o]:[...c.values()].flat();if(o===null)for(let a of i)(a.section==="branch"&&/^(push)?remote$/.test(a.key)||a.section==="remote"&&a.sub===null&&a.key==="pushdefault")&&a.value!=="."&&!c.has(a.value)&&u.push(a.value);let d=new Set(u);for(let a of u)for(let l of i)l.section==="url"&&l.sub!==null&&/^(push)?insteadof$/.test(l.key)&&l.value&&a.startsWith(l.value)&&d.add(l.sub+a.slice(l.value.length));return d.size>0?Ge([...d],n):null}catch{return null}}function Ge(e,t){let n=[];for(let s of e){let r=decodeURIComponent(s.trim()),o=process.platform==="win32"&&/^[A-Za-z]:[\\/]/.test(r)?null:/^[a-z][a-z0-9+.-]*:\/\/[^/]*(\/.*)?$|^(?:[^@/:\s]+@)?[^/:\s]+:(?!\/\/)(.*)$/i.exec(r),c=(o?cn.resolve("/",o[1]??o[2]??""):/^[\w.-]+(\/[\w.-]+){1,2}$/.test(r)&&!r.startsWith(".")?r:L(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,a]=c.slice(-2).map(f=>f.replace(/\.git$/i,"").toLowerCase()),l=a??d;if(!l||l==="..")return null;n.push(a!==void 0&&d!==".."?`${d}/${a}`:l)}return n}function un(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 s=dn(e);if(s===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`),o=n.GIT_CONFIG_NOSYSTEM?[]:n.GIT_CONFIG_SYSTEM?[n.GIT_CONFIG_SYSTEM]:r;n.GIT_CONFIG_GLOBAL?o.push(n.GIT_CONFIG_GLOBAL):t&&o.push(C(n.XDG_CONFIG_HOME||C(t,".config"),"git","config"),C(t,".gitconfig")),o.push(C(s.common,"config"),C(s.gitDir,"config.worktree"));let i=[],c=24,u=(d,a)=>{let l=--c<0||a>5?void 0:I(d,1048576);if(l===void 0)return!1;for(let f of fn(l?.toString("utf8")??""))if(i.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)&&L(ie(d),f.value);if(!m||!u(m,a+1))return!1}return!0};return o.every(d=>u(d,0))?i:null}function dn(e){let t=n=>/^(ref: refs\/|[0-9a-f]{40})/.test(I(C(n,"HEAD"),4096)?.toString("utf8")??"");for(let n=L(e),s=0;s<64;s++,n=ie(n)){let r=C(n,".git"),o=["objects","refs"].every(i=>G(C(n,i)))&&t(n)?n:null;if(G(r)){let i=Ue(r);if(i.isDirectory())t(r)&&(o=r);else if(o=i.isFile()?/^gitdir:\s*(.+)$/m.exec(I(r,65536)?.toString("utf8")??"")?.[1]?.trim():null,!o)return null}if(o){let i=L(n,o),c=I(C(i,"commondir"),65536),u=c===null?i:L(i,c.toString("utf8").trim());for(let d of["remotes","branches"]){let a=C(u,d);if(G(a)&&(!Ue(a).isDirectory()||an(a).length>0))return null}return{gitDir:i,common:u}}if(ie(n)===n)return null}return null}function fn(e){let t=[],n="",s=null;for(let r of e.replace(/\\\r?\n/g,"").split(/\r?\n/)){r=r.trim();let o=/^\[\s*([\w.-]+)(?:\s+"((?:[^"\\]|\\.)*)")?\s*\]/.exec(r);if(o){let[c,...u]=o[1].toLowerCase().split(".");n=c,s=o[2]?.replace(/\\(.)/g,"$1")??(u.length>0?u.join("."):null),r=r.slice(o[0].length).trim()}let i=/^([a-z][\w-]*)\s*(?:=(.*))?$/i.exec(r);i&&t.push({section:n,sub:s,key:i[1].toLowerCase(),value:i[2]===void 0?"true":i[2].replace(/"((?:[^"\\]|\\.)*)"|\\(.)|[#;].*$/g,(c,u,d)=>u??d??"").trim()})}return t}var pn={slack:"channel",github:"repo",linear:"team",jira:"project"};var gn=/^[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 s=e==="jira"&&typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?String(t):t;if(typeof s!="string")return null;let r=s.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=a=>/^[\w.-]+$/.test(a)&&!/^\.+$/.test(a),d=a=>a.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 o=e==="linear"?"[A-Za-z][A-Za-z0-9]{0,6}":"[A-Z][A-Z0-9_]{1,9}",i=new RegExp(`^(${o})-\\d+$`).exec(r)??new RegExp(`(?:/issue/|/browse/)(${o})-\\d+`).exec(r);return i?`key:${i[1].toLowerCase()}`:n?null:(e==="linear"?gn.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 le={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},Ze={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},mn=/^(?:user|users|user_?ids?|recipient|recipients)$/i,hn=/^(?:arguments|args|params|parameters|input|data|payload|body|request|message|fields|issue|issues|items|options|update)$/i,ae=/^channels?$|^channel_ids?$/,yn=/^(?:text|body|title|description|content|comment|summary|markdown|blocks|attachments)$/i;function wn(e,t){let n=0,s=(r,o)=>++n>2e3||o>6?!1:typeof r=="string"?P(e.app,x(e.app,r)).some(i=>Xe(e,i)):Array.isArray(r)?r.slice(0,200).some(i=>s(i,o+1)):!!(r&&typeof r=="object")&&Object.entries(r).some(([i,c])=>!yn.test(i)&&!le[e.app].test(i)&&!Ze[e.app]?.test(i)&&s(c,o+1));return s(t,0)}function Ye(e,t,n=!1){if(!t)return null;let s=[],r=0,o=(i,c,u)=>{for(let[d,a]of Object.entries(i)){if(++r>2e3)return void s.push("?");let l=u?"":"~",f=Array.isArray(a)?a:[a];f.length>200&&s.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(le[e].test(d)||Ze[e]?.test(d)){let p=!le[e].test(d),h=e==="github"?/^(.*?)(_?)(?:repo|repository)(?:_?name)?$/i.exec(d):null,g=h?i[`${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)))s.push(b==="?"?"?":`${l}${b}`)}else if(e==="slack"&&mn.test(d))for(let p of m)s.push(x("slack",p)==="dm"?`${l}dm`:"?");else if(c<6&&a&&typeof a=="object")for(let p of f.slice(0,200))p&&typeof p=="object"&&!Array.isArray(p)&&o(p,c+1,n||u&&c<2&&hn.test(d))}};return o(t,0,!0),s.length>0?s.every(i=>i.startsWith("~"))?[...s,"?"]:s:null}function bn(e){let t=[],n="",s=null;for(let r=0;r<e.length;r++){let o=e[r];if(o==="\\"&&s!=="'"){n+=o+(e[++r]??"");continue}if(s)s=o===s?null:s;else if(o==="'"||o==='"')s=o;else if(o===";"||o==="&"||o==="|"||o===`
|
|
12
|
-
`){n.trim()&&t.push(n),n="";continue}n+=o}return n.trim()&&t.push(n),t}function Je(e){let t=[],n="",s=null,r=!1;for(let o=0;o<e.length;o++){let i=e[o];s==="'"?i==="'"?s=null:n+=i:s==='"'?i==='"'?s=null:n+=i==="\\"&&o+1<e.length?e[++o]:i:i==="'"||i==='"'?(s=i,r=!0):i==="\\"?(n+=e[++o]??"",r=!0):/\s/.test(i)?((n||r)&&t.push(n),n="",r=!1):(n+=i,r=!0)}return s?null:((n||r)&&t.push(n),t)}var Ke=e=>{try{return new URL(/^https?:\/\//i.test(e)?e:`/${e.replace(/^\/+/,"")}`,"https://x").pathname}catch{return"\0"}};function $n(e){let t=Je(e),n=t?t.findIndex(d=>/(?:^|\/)gh$/.test(d)):-1;if(!t||n<0)return["?"];let s=t.slice(0,n).flatMap(d=>d.startsWith("GH_REPO=")?[d.slice(8)]:[]).pop(),r=t.slice(n+1),o;for(let d=0;d<r.length;d++){let a=r[d];a==="-R"||a==="--repo"?o=r[++d]??"":a.startsWith("--repo=")?o=a.slice(7):/^-R[^-]/.test(a)?o=a.slice(2):/^-[A-Za-z]+R/.test(a)&&(o="?")}let i=r[0]==="repo"&&r[1]!=="rename"&&r[2]!==void 0&&!r[2].startsWith("-")?r[2]:void 0,c=o??s??i,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 kn=(e,t)=>Be(e.attributes,t.home)?.map(n=>x("github",n)??"?")??["?"];function vn(e,t){let n=Je(t),s=n?n.findIndex(a=>/(?:^|\/)(?:curl|wget)$/.test(a)):-1;if(!n||s<0)return["?"];let r=[],o=[],i=n.slice(s+1);for(let a=0;a<i.length;a++){let l=i[a],f=/^(--data(?:-ascii|-binary|-raw|-urlencode)?|--json|--form(?:-string)?|--post-data|--body-data)(?:=([\s\S]*))?$/.exec(l);f?r.push(f[2]??i[++a]??""):l==="-d"||l==="-F"?r.push(i[++a]??""):/^-[dF]./.test(l)?r.push(l.slice(2)):/^https?:\/\//i.test(l)&&o.push(l)}let c=[],u=a=>{for(let l of[a].flat().flatMap(f=>typeof f=="string"?f.split(","):[f]))c.push(...P(e,x(e,l)))},d=a=>{let l=a&&typeof a=="object"&&!Array.isArray(a)?a:null;if(!l)return void c.push("?");if(e==="slack"){let f=Object.keys(l).filter(m=>
|
|
11
|
+
`,w),_=e.slice(w,k<0?void 0:k);if(w=k<0?e.length:k+1,k<0||(y?_.replace(/^\t+/,""):_)===g)break;for(let A=0;!b&&A<_.length;A++)_[A]==="\\"?A++:s||=ee(_,A)}m=w-1}}else/\s/.test(p)?l():(i+=p,u=!0)}return f(),{list:t,sub:s,writes:n}}function Tt(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 te=["srAaSqTOuC","cb","tfHE"],Re=["sifmQd","cb","HeF"],zt=E({mail:te,mailx:te,"s-nail":te,sendmail:["fFOpRVNLBXh","","tC"],msmtp:["afCX","","t"],mutt:Re,neomutt:Re}),Ne=/^\s*(?:to|cc|bcc)\s*:/i,q="Anvil can't read who this goes to: it may read them from the message or its settings";function Dt(e,t,n,s,r){let o=zt[e];if(!o){let a=!1;for(let l=s;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];a=!0,m===void 0||n[l]?r.why??=j:S(m,r)}a||(r.why??=v);return}let[i,c,u]=o,d=!1;for(let a=s;a<t.length;a++){let l=t[a];if(d||!l.startsWith("-")||l==="-")n[a]?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[++a];p!==void 0&&Ne.test(p)&&(n[a]?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??=q)}else if(e==="sendmail"&&/^-b[^m]/.test(l))r.why??=q;else if(/mutt/.test(e)&&l.startsWith("-a"))for(;a+1<t.length&&t[a+1]!=="--";)a++;else for(let f=1;f<l.length;f++){let m=l[f];if(u.includes(m)&&(r.why??=q),!i.includes(m)&&!c.includes(m))continue;let p=f+1<l.length?l.slice(f+1):t[++a];/^\s*(?:sendmail|mta)\s*=/i.test(p??"")&&(r.why??=q),n[a]&&"aTC".includes(m)&&i.includes(m)&&(r.why??=j);let h=p!==void 0&&Ne.test(p);if(!c.includes(m)&&!h)break;p===void 0||n[a]?r.why??=j:S(h?p.slice(p.indexOf(":")+1):p,r);break}}}function Se(e){try{return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`http://${e}`)}catch{return null}}var Ft="AbcCdDeEFHKmoPQrtTuUwxXyYz",qt=/^(?:data(?:-ascii|-binary|-raw|-urlencode)?|json|form(?:-string)?|url|header)$/,je=/^(?:config|upload-file|url-query|variable|request-target|mail-rcpt|expand-[\w.-]+)$/,Ht=/^(?: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)$/,Ut=/^(?: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)$/,Gt=/^(?:[oDc]|output|output-dir|dump-header|cookie-jar|stderr|trace|trace-ascii|libcurl|etag-save|hsts|alt-svc)$/,H="Anvil can't read who this goes to: curl takes part of it from elsewhere";function M(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 Bt(e,t,n,s,r,o){let i=0,c=0,u=[],d=[],a=!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=Se(p);if(h?.hostname.toLowerCase().replace(/\.$/,"")!==s)o.why??=`${v}: a URL Anvil reads two ways`;else{c++;let g=h.pathname.toLowerCase();try{g=decodeURIComponent(g)}catch{o.why??=v}se.test(g)?o.why??=I:Ie.test(g)&&(o.why??=Le);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){i++;for(let w of d)Kt(w,a&&!l,u,o);Zt(u,o)}[c,u,d,a,l]=[0,[],[],!1,!1];continue}let g="",y;if(h.startsWith("--")){let w=/^--([\w.-]+)(=?)/.exec(h);if(g=w?.[1]??"",Ut.test(g.replace(/^no-/,"")))continue;if(g==="remote-header-name"||!qt.test(g)&&!je.test(g)&&!Ht.test(g)){o.why??=g==="remote-header-name"?H:`${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"&&(o.why??=H),Ft.includes(h[w])&&(g=h[w],y=h.slice(w+1)||e[++p]);if(!g)continue}else{if(f){let w=Se(h)?.pathname.split("/").pop()??"";M(w,!1,o);try{M(decodeURIComponent(w),!1,o)}catch{o.why??=v}}m(h);continue}if(y===void 0){o.why??=v;break}let b=t[p]??!1;if(/^[KT]$/.test(g)||je.test(g))o.why??=H;else if(g==="url")m(y);else if(g==="H"||g==="header"){let w=/^\s*content-type\s*:/i.exec(y);y.startsWith("@")?o.why??=H:w?/json/i.test(y.slice(w[0].length))&&!b?a=!0:l=!0:b&&!/^\s*[\w-]+\s*:/.test(y)&&(l=!0)}else if(Gt.test(g))M(y,b,o);else if(g==="F"||g.startsWith("form")||g==="data-urlencode"){let w=y.indexOf("="),k=y.indexOf("@"),_=g==="data-urlencode"?k>=0&&(w<0||k<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("@")?o.why??=`${v}: its body is ${b?"built when the line runs":"read from a file"}`:(a||=g==="json",d.push(y)))}return i}function Kt(e,t,n,s){let r=Te(e,s);if(r!==void 0?R(r,s):t&&(s.why??=xe),!t){r===void 0&&/^[\w-]+\s*:/.test(e)&&We(e,s);for(let o of e.split("&")){let i=o.indexOf("=");try{let c=decodeURIComponent(o.slice(0,Math.max(i,0)).replace(/\+/g," "));/^[\w.[\]-]*$/.test(c)&&(r===void 0||c.split(/[.[\]]+/).map(ne).some(u=>re.has(u)||oe.test(u)))&&n.push([c,decodeURIComponent(o.slice(i+1).replace(/\+/g," ")),!1,!1])}catch{s.why??=xe}}}}function Zt(e,t){for(let[n,s,r,o]of e){let i=n.split(/[.[\]]+/).map(ne).filter(Boolean),c=i[i.length-1]??"";if(i.some(u=>re.has(u)))o||r?t.why??=`${v}: it is ${o?"read from a file":"built when the line runs"}`:S(s,t);else if(i.some(u=>oe.test(u)))t.why??=`${v}: it names a list ("${n}")`;else if(i.some(u=>Ee.test(u)))t.why??=I;else{if(i.some(u=>Pe.test(u))||Oe.test(c)||i.some(u=>Me.test(u)))continue;r?t.why??=j:o||R(s,t)}}}var Yt=/^(?: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 Jt(e,t,n,s){let r=t.includes("."),o=new RegExp(`(?<![\\w.-])${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w-]|\\.\\w)`),i=l=>o.test(l.replace(/['"\\]/g,"").toLowerCase()),{list:c,sub:u,writes:d}=Wt(e);u&&(s.why??=`${v}: this line runs a command inside another ($(\u2026) or \`\u2026\`), which Anvil doesn't read`);for(let l of d)M(l.f,l.dyn,s);let a=0;for(let l of c){let f=Tt(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)))&&(s.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("-")||M(l.w[m],l.dyn[m],s);!f&&l.w.every(m=>/^[A-Za-z_]\w*\+?=/.test(m))||(f&&r&&f.name==="curl"?a+=Bt(l.w,l.dyn,f.at,t,i,s):f&&!r&&f.name===t?(a++,Dt(f.name,l.w,l.dyn,f.at,s)):(!f||!Yt.test(f.name))&&(s.why??=`${v}: this line also runs ${f?f.name:"a command built when it runs"}, which Anvil doesn't read`))}(a===0||a<n)&&(s.why??=`${v}: Anvil reads a plain curl request or mail program, not this`)}function ze(e,t){let n={list:[],why:null},s=(e.host??"").toLowerCase(),r=e.action==="claude.mcp.side_effect",o=`${s} ${r?t.tool??"":/^[a-z][a-z0-9+.-]*:\/\//i.test(e.target??"")?e.target:""}`.toLowerCase(),i=Ot.exec(o)?.[1];return i?n.why=`Anvil can't read who ${i} sends reach: they go to a list or a ticket`:se.test(o)?n.why=I:Ie.test(o)?n.why=Le:r&&t.input?R(t.input,n,!1,0,!1,/forward/.test((t.tool??"").split("__").pop().toLowerCase())):!r&&t.command&&s?Jt(t.command,s,t.parts.filter(c=>c.action===e.action&&(c.host??"").toLowerCase()===s).length,n):n.why=v,n.known||(n.why??=v),n}function Vt(e){let t=i=>Array.isArray(i)&&i.every(c=>typeof c=="string")?i:null,n=t(e.domains??[]),s=t(e.addresses??[]);if(!n||!s)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(ie),o=s.map(i=>{let[c,u]=U(i);return c&&!u?`${c.local}@${c.domain}`:""});return r.includes("")||o.includes("")?"a recipient condition names an address or a domain Anvil can't read":r.length+o.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:o}}var De=new WeakMap;function Fe(e,t,n){let s=De.get(e);if(s===void 0&&De.set(e,s=Vt(e)),typeof s=="string")return{hit:"unknown",why:`Anvil can't use this rule's recipients (${s})`};let r;try{r=ze(t,n)}catch{return{hit:"unknown",why:"Anvil can't read who this goes to"}}let o=r.why;for(let i of r.list){let c=s.addresses.includes(`${i.local}@${i.domain}`)||s.domains.some(u=>i.domain===u||i.domain.endsWith(`.${u}`));if(s.outside?!c:c)return{hit:"match",detail:s.outside?`${i.shown} is outside ${[...s.domains,...s.addresses.length>0?["the addresses your rule names"]:[]].join(" and ")}`:`it goes to ${i.shown}`};i.group?o??=`${i.shown} may reach ${s.outside?"people outside":"anyone"} (a list or a relay)`:i.alien&&!s.outside&&(o??=`${i.shown} is in letters from another alphabet`)}return o===null?null:{hit:"unknown",why:o}}var Xt="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");function Qt(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 s=(n[1]==="-"?1:-1)*(Number(n[2])*60+Number(n[3]??0)),r=-t.getTimezoneOffset();return r!==s&&!(n[4]!==void 0&&r===s+60)}function qe(e,t,n){let s=new Date(n.now??NaN),r=s.getDay(),o=s.getHours(),i=o*60+s.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(i%60).padStart(2,"0")}`;if(c!==void 0||s.getTimezoneOffset()===0){let d="";try{let a=Intl.DateTimeFormat().resolvedOptions().timeZone;a&&!Qt(c,s)&&(d=s.toLocaleTimeString("en-GB",{timeZone:a,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}))}catch{}if(d!==`${String(o).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)&&i>=d.from&&i<d.to)?{hit:"match",detail:`it's ${Xt[r]} ${o%12||12}${u}${o<12?"am":"pm"}`}:null}import{existsSync as or,readdirSync as sr,realpathSync as ir}from"fs";import{basename as lr,dirname as cr,join as ur}from"path";function L(e,t=8*1024*1024){let n;try{n=on(e,He.O_RDONLY|He.O_NONBLOCK)}catch(s){if(s.code==="ENOENT"||s.code==="ENOTDIR")return null;throw s}try{let s=rn(n);if(!s.isFile())throw new Error(`${e} is not a regular file`);if(s.size>t)throw new Error(`${e} is over ${t} bytes`);let r=Buffer.alloc(s.size),o=0;for(;o<s.size;){let i=sn(n,r,o,s.size-o,o);if(i===0)break;o+=i}return r.subarray(0,o)}finally{nn(n)}}var Qr=256*1024,eo=1024*1024;function Be(e,t){try{let n=typeof e.repo_dir=="string"?F(e.repo_dir):e.repo_dir,s=t===null?null:F(t),r=e.repo_via,o=typeof e.repo_remote=="string"&&e.repo_remote?e.repo_remote:r==="gh"&&process.env.GH_REPO||null;if(typeof n!="string"||!ln(n)||!G(n)||r!=="git"&&r!=="gh"||/[$`]/.test(o??""))return null;if(r==="gh"&&o!==null)return Ge([o],n);let i=un(n,s);if(i===null)return null;let c=new Map;for(let a of i)a.section==="remote"&&a.sub!==null&&(a.key==="url"||(r==="git"?a.key==="pushurl":a.key==="gh-resolved"&&a.value!=="base"))&&c.set(a.sub,[...c.get(a.sub)??[],a.value]);if(o!==null&&!c.has(o)&&!/^[./]|[/:]/.test(o))return null;let u=o!==null?c.get(o)??[o]:[...c.values()].flat();if(o===null)for(let a of i)(a.section==="branch"&&/^(push)?remote$/.test(a.key)||a.section==="remote"&&a.sub===null&&a.key==="pushdefault")&&a.value!=="."&&!c.has(a.value)&&u.push(a.value);let d=new Set(u);for(let a of u)for(let l of i)l.section==="url"&&l.sub!==null&&/^(push)?insteadof$/.test(l.key)&&l.value&&a.startsWith(l.value)&&d.add(l.sub+a.slice(l.value.length));return d.size>0?Ge([...d],n):null}catch{return null}}function Ge(e,t){let n=[];for(let s of e){let r=decodeURIComponent(s.trim()),o=process.platform==="win32"&&/^[A-Za-z]:[\\/]/.test(r)?null:/^[a-z][a-z0-9+.-]*:\/\/[^/]*(\/.*)?$|^(?:[^@/:\s]+@)?[^/:\s]+:(?!\/\/)(.*)$/i.exec(r),c=(o?cn.resolve("/",o[1]??o[2]??""):/^[\w.-]+(\/[\w.-]+){1,2}$/.test(r)&&!r.startsWith(".")?r:W(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,a]=c.slice(-2).map(f=>f.replace(/\.git$/i,"").toLowerCase()),l=a??d;if(!l||l==="..")return null;n.push(a!==void 0&&d!==".."?`${d}/${a}`:l)}return n}function un(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 s=dn(e);if(s===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`),o=n.GIT_CONFIG_NOSYSTEM?[]:n.GIT_CONFIG_SYSTEM?[n.GIT_CONFIG_SYSTEM]:r;n.GIT_CONFIG_GLOBAL?o.push(n.GIT_CONFIG_GLOBAL):t&&o.push(C(n.XDG_CONFIG_HOME||C(t,".config"),"git","config"),C(t,".gitconfig")),o.push(C(s.common,"config"),C(s.gitDir,"config.worktree"));let i=[],c=24,u=(d,a)=>{let l=--c<0||a>5?void 0:L(d,1048576);if(l===void 0)return!1;for(let f of fn(l?.toString("utf8")??""))if(i.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)&&W(ae(d),f.value);if(!m||!u(m,a+1))return!1}return!0};return o.every(d=>u(d,0))?i:null}function dn(e){let t=n=>/^(ref: refs\/|[0-9a-f]{40})/.test(L(C(n,"HEAD"),4096)?.toString("utf8")??"");for(let n=W(e),s=0;s<64;s++,n=ae(n)){let r=C(n,".git"),o=["objects","refs"].every(i=>G(C(n,i)))&&t(n)?n:null;if(G(r)){let i=Ue(r);if(i.isDirectory())t(r)&&(o=r);else if(o=i.isFile()?/^gitdir:\s*(.+)$/m.exec(L(r,65536)?.toString("utf8")??"")?.[1]?.trim():null,!o)return null}if(o){let i=W(n,o),c=L(C(i,"commondir"),65536),u=c===null?i:W(i,c.toString("utf8").trim());for(let d of["remotes","branches"]){let a=C(u,d);if(G(a)&&(!Ue(a).isDirectory()||an(a).length>0))return null}return{gitDir:i,common:u}}if(ae(n)===n)return null}return null}function fn(e){let t=[],n="",s=null;for(let r of e.replace(/\\\r?\n/g,"").split(/\r?\n/)){r=r.trim();let o=/^\[\s*([\w.-]+)(?:\s+"((?:[^"\\]|\\.)*)")?\s*\]/.exec(r);if(o){let[c,...u]=o[1].toLowerCase().split(".");n=c,s=o[2]?.replace(/\\(.)/g,"$1")??(u.length>0?u.join("."):null),r=r.slice(o[0].length).trim()}let i=/^([a-z][\w-]*)\s*(?:=(.*))?$/i.exec(r);i&&t.push({section:n,sub:s,key:i[1].toLowerCase(),value:i[2]===void 0?"true":i[2].replace(/"((?:[^"\\]|\\.)*)"|\\(.)|[#;].*$/g,(c,u,d)=>u??d??"").trim()})}return t}var pn={slack:"channel",github:"repo",linear:"team",jira:"project"};var gn=/^[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 s=e==="jira"&&typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?String(t):t;if(typeof s!="string")return null;let r=s.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=a=>/^[\w.-]+$/.test(a)&&!/^\.+$/.test(a),d=a=>a.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 o=e==="linear"?"[A-Za-z][A-Za-z0-9]{0,6}":"[A-Z][A-Z0-9_]{1,9}",i=new RegExp(`^(${o})-\\d+$`).exec(r)??new RegExp(`(?:/issue/|/browse/)(${o})-\\d+`).exec(r);return i?`key:${i[1].toLowerCase()}`:n?null:(e==="linear"?gn.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 ce={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},Ze={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},mn=/^(?:user|users|user_?ids?|recipient|recipients)$/i,hn=/^(?:arguments|args|params|parameters|input|data|payload|body|request|message|fields|issue|issues|items|options|update)$/i,le=/^channels?$|^channel_ids?$/,yn=/^(?:text|body|title|description|content|comment|summary|markdown|blocks|attachments)$/i;function wn(e,t){let n=0,s=(r,o)=>++n>2e3||o>6?!1:typeof r=="string"?P(e.app,x(e.app,r)).some(i=>Xe(e,i)):Array.isArray(r)?r.slice(0,200).some(i=>s(i,o+1)):!!(r&&typeof r=="object")&&Object.entries(r).some(([i,c])=>!yn.test(i)&&!ce[e.app].test(i)&&!Ze[e.app]?.test(i)&&s(c,o+1));return s(t,0)}function Ye(e,t,n=!1){if(!t)return null;let s=[],r=0,o=(i,c,u)=>{for(let[d,a]of Object.entries(i)){if(++r>2e3)return void s.push("?");let l=u?"":"~",f=Array.isArray(a)?a:[a];f.length>200&&s.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(ce[e].test(d)||Ze[e]?.test(d)){let p=!ce[e].test(d),h=e==="github"?/^(.*?)(_?)(?:repo|repository)(?:_?name)?$/i.exec(d):null,g=h?i[`${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)))s.push(b==="?"?"?":`${l}${b}`)}else if(e==="slack"&&mn.test(d))for(let p of m)s.push(x("slack",p)==="dm"?`${l}dm`:"?");else if(c<6&&a&&typeof a=="object")for(let p of f.slice(0,200))p&&typeof p=="object"&&!Array.isArray(p)&&o(p,c+1,n||u&&c<2&&hn.test(d))}};return o(t,0,!0),s.length>0?s.every(i=>i.startsWith("~"))?[...s,"?"]:s:null}function bn(e){let t=[],n="",s=null;for(let r=0;r<e.length;r++){let o=e[r];if(o==="\\"&&s!=="'"){n+=o+(e[++r]??"");continue}if(s)s=o===s?null:s;else if(o==="'"||o==='"')s=o;else if(o===";"||o==="&"||o==="|"||o===`
|
|
12
|
+
`){n.trim()&&t.push(n),n="";continue}n+=o}return n.trim()&&t.push(n),t}function Je(e){let t=[],n="",s=null,r=!1;for(let o=0;o<e.length;o++){let i=e[o];s==="'"?i==="'"?s=null:n+=i:s==='"'?i==='"'?s=null:n+=i==="\\"&&o+1<e.length?e[++o]:i:i==="'"||i==='"'?(s=i,r=!0):i==="\\"?(n+=e[++o]??"",r=!0):/\s/.test(i)?((n||r)&&t.push(n),n="",r=!1):(n+=i,r=!0)}return s?null:((n||r)&&t.push(n),t)}var Ke=e=>{try{return new URL(/^https?:\/\//i.test(e)?e:`/${e.replace(/^\/+/,"")}`,"https://x").pathname}catch{return"\0"}};function $n(e){let t=Je(e),n=t?t.findIndex(d=>/(?:^|\/)gh$/.test(d)):-1;if(!t||n<0)return["?"];let s=t.slice(0,n).flatMap(d=>d.startsWith("GH_REPO=")?[d.slice(8)]:[]).pop(),r=t.slice(n+1),o;for(let d=0;d<r.length;d++){let a=r[d];a==="-R"||a==="--repo"?o=r[++d]??"":a.startsWith("--repo=")?o=a.slice(7):/^-R[^-]/.test(a)?o=a.slice(2):/^-[A-Za-z]+R/.test(a)&&(o="?")}let i=r[0]==="repo"&&r[1]!=="rename"&&r[2]!==void 0&&!r[2].startsWith("-")?r[2]:void 0,c=o??s??i,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 kn=(e,t)=>Be(e.attributes,t.home)?.map(n=>x("github",n)??"?")??["?"];function vn(e,t){let n=Je(t),s=n?n.findIndex(a=>/(?:^|\/)(?:curl|wget)$/.test(a)):-1;if(!n||s<0)return["?"];let r=[],o=[],i=n.slice(s+1);for(let a=0;a<i.length;a++){let l=i[a],f=/^(--data(?:-ascii|-binary|-raw|-urlencode)?|--json|--form(?:-string)?|--post-data|--body-data)(?:=([\s\S]*))?$/.exec(l);f?r.push(f[2]??i[++a]??""):l==="-d"||l==="-F"?r.push(i[++a]??""):/^-[dF]./.test(l)?r.push(l.slice(2)):/^https?:\/\//i.test(l)&&o.push(l)}let c=[],u=a=>{for(let l of[a].flat().flatMap(f=>typeof f=="string"?f.split(","):[f]))c.push(...P(e,x(e,l)))},d=a=>{let l=a&&typeof a=="object"&&!Array.isArray(a)?a:null;if(!l)return void c.push("?");if(e==="slack"){let f=Object.keys(l).filter(m=>le.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=Ye("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 a of o)try{for(let[l,f]of new URL(a).searchParams)e==="slack"&&le.test(l)&&u(f)}catch{c.push("?")}for(let a of r){if(/^@|^[\w-]*@/.test(a)){c.push("?");continue}let l;try{l=JSON.parse(a)}catch{l=void 0}if(l!==void 0)d(l);else if(e==="slack"&&/^[\w-]+=/.test(a)){let f=a.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(!le.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 Ve=e=>/^[a-z][a-z-]*\s+[a-z][a-z-]*$/.test(e)||!/[/:]/.test(e)&&e!=="graphql"&&e.length>0;function _n(e,t,n){let s=t.target??"";if(e==="slack"&&/hooks\.slack\.com/i.test(`${t.host??""} ${s}`))return["?"];let r=e==="github"&&Ve(s);if(e==="github"&&!r){let a=Ke(s),l=/^\/repos\/([^/]+)\/([^/]+)/.exec(a)??(/^https?:\/\/(?:www\.)?github\.com\//i.test(s)?/^\/([^/]+)\/([^/]+)/.exec(a):null);return[l?x("github",`${l[1]}/${l[2]}`)??"?":"?"]}let o=e==="jira"?/\/rest\/api\/(?:2|3|latest)\/(issue|project)\/([^/]+)/.exec(Ke(s)):null;if(o)return P("jira",x("jira",o[2],o[1]==="issue"));let i=n.command??(typeof n.input?.command=="string"?n.input.command:"");if(i.length>65536)return["?"];let c=bn(i),u=c.filter(a=>r?/(?:^|[\s/])gh\s/.test(a)&&(/\s/.test(s)?a.includes(s.split(/\s+/)[1]):a.includes(s)):s.length>0&&a.includes(s)),d=a=>r?$n(a).flatMap(l=>l==="none"?kn(t,n):[l]):vn(e,a);return u.length>0?u.flatMap(d):[...c.flatMap(d).filter(a=>a!=="?"&&!a.startsWith("~")).map(a=>`~${a}`),"?"]}function Cn(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 Xe(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 B=e=>e.startsWith("key:")?e.slice(4).toUpperCase():e.replace(/^(?:name|id|repo):(?:\?\/)?/,"");function Qe(e,t,n){let s=pn[e.app],r=e.said.replace(/^in /,""),o=t.action==="claude.mcp.side_effect"?Ye(e.app,n.input):_n(e.app,t,n),i=`Anvil can't tell which ${s} this acts in${e.app==="github"&&t.action!=="claude.mcp.side_effect"&&Ve(t.target??"")?" (gh says it with --repo)":""}`;if(!o||o.length===0)return{hit:"unknown",why:i};let c=o.map(a=>a.replace(/^~/,"")).find(a=>Xe(e,a));if(c)return{hit:"match",detail:c.startsWith("id:")?`${B(c)} is ${r}`:e.app==="github"?B(c):r};let u=o.find(a=>a==="?"||a.startsWith("~")||!(e.not??[]).includes(a)&&!Cn(e,a));if(u===void 0)return t.action==="claude.mcp.side_effect"&&wn(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==="?"?i:`Anvil can't tell whether ${d.startsWith("id:")?`${s} ${B(d)}`:B(d)} is ${r}`}}function mo(e,t,n){switch(e.type){case"amount":return _e(e,t,n);case"recipient":return Fe(e,t,n);case"part":return Qe(e,t,n);case"when":return qe(e,t,n)}}async function ho(){}export{_t as capMoved,mo as matchCondition,ho as preloadConditions};
|