@useanvil/claude-code 0.0.0-stage → 0.8.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/LICENSE ADDED
@@ -0,0 +1,111 @@
1
+ Business Source License 1.1
2
+
3
+ License text copyright (c) 2020 MariaDB Corporation Ab, All Rights Reserved.
4
+ "Business Source License" is a trademark of MariaDB Corporation Ab.
5
+
6
+ -----------------------------------------------------------------------------
7
+
8
+ Parameters
9
+
10
+ Licensor: Anvil (henry@anvilcontrol.ai)
11
+
12
+ Licensed Work: Anvil — @useanvil/sdk, the `anvil` CLI, and the
13
+ accompanying control-plane and ghost-intake sources
14
+ distributed in this repository and in the published
15
+ npm package.
16
+ The Licensed Work is (c) 2026 Anvil.
17
+
18
+ Additional Use Grant: You may make production use of the Licensed Work for
19
+ your own internal business operations, including
20
+ running the Licensed Work (and any modified version of
21
+ it) on your own infrastructure to guard, observe, and
22
+ audit your own systems' actions, with no limit on the
23
+ number of users, workloads, hosts, or transactions.
24
+
25
+ This grant does not extend to offering the Licensed
26
+ Work to third parties as a hosted, managed, or embedded
27
+ service that provides those third parties with the
28
+ Licensed Work's execution-control, policy-enforcement,
29
+ idempotency, or decision-audit functionality, where that
30
+ service competes with a product or service offered by
31
+ the Licensor.
32
+
33
+ Change Date: 2030-07-29
34
+
35
+ Change License: Mozilla Public License, Version 2.0
36
+
37
+ For information about alternative licensing arrangements for the Licensed Work,
38
+ please contact henry@anvilcontrol.ai.
39
+
40
+ -----------------------------------------------------------------------------
41
+
42
+ Notice
43
+
44
+ Business Source License 1.1
45
+
46
+ Terms
47
+
48
+ The Licensor hereby grants you the right to copy, modify, create derivative
49
+ works, redistribute, and make non-production use of the Licensed Work. The
50
+ Licensor may make an Additional Use Grant, above, permitting limited
51
+ production use.
52
+
53
+ Effective on the Change Date, or the fourth anniversary of the first publicly
54
+ available distribution of a specific version of the Licensed Work under this
55
+ License, whichever comes first, the Licensor hereby grants you rights under
56
+ the terms of the Change License, and the rights granted in the paragraph
57
+ above terminate.
58
+
59
+ If your use of the Licensed Work does not comply with the requirements
60
+ currently in effect as described in this License, you must purchase a
61
+ commercial license from the Licensor, its affiliated entities, or authorized
62
+ resellers, or you must refrain from using the Licensed Work.
63
+
64
+ All copies of the original and modified Licensed Work, and derivative works
65
+ of the Licensed Work, are subject to this License. This License applies
66
+ separately for each version of the Licensed Work and the Change Date may vary
67
+ for each version of the Licensed Work released by Licensor.
68
+
69
+ You must conspicuously display this License on each original or modified copy
70
+ of the Licensed Work. If you receive the Licensed Work in original or
71
+ modified form from a third party, the terms and conditions set forth in this
72
+ License apply to your use of that work.
73
+
74
+ Any use of the Licensed Work in violation of this License will automatically
75
+ terminate your rights under this License for the current and all other
76
+ versions of the Licensed Work.
77
+
78
+ This License does not grant you any right in any trademark or logo of
79
+ Licensor or its affiliates (provided that you may use a trademark or logo of
80
+ Licensor as expressly required by this License).
81
+
82
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
83
+ AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
84
+ EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
85
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
86
+ TITLE.
87
+
88
+ MariaDB hereby grants you permission to use this License's text to license
89
+ your works, and to refer to it using the trademark "Business Source License",
90
+ as long as you comply with the Covenants of Licensor below.
91
+
92
+ Covenants of Licensor
93
+
94
+ In consideration of the right to use this License's text and the "Business
95
+ Source License" name and trademark, Licensor covenants to MariaDB, and to all
96
+ other recipients of the licensed work to be provided by Licensor:
97
+
98
+ 1. To specify as the Change License the GPL Version 2.0 or any later version,
99
+ or a license that is compatible with GPL Version 2.0 or a later version,
100
+ where "compatible" means that software provided under the Change License can
101
+ be included in a program with software provided under GPL Version 2.0 or a
102
+ later version. Licensor may specify additional Change Licenses without
103
+ limitation.
104
+
105
+ 2. To either: (a) specify an additional grant of rights to use that does not
106
+ impose any additional restriction on the right granted in this License, as
107
+ the Additional Use Grant; or (b) insert the text "None".
108
+
109
+ 3. To specify a Change Date.
110
+
111
+ 4. Not to modify this License in any other way.
package/README.md CHANGED
@@ -1,3 +1,215 @@
1
- # Temporary Holding Version
1
+ # Anvil for Claude Code
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Stop Claude Code before it does something you can't undo.**
4
+
5
+ Anvil checks every action Claude Code takes before it happens: each command it runs, each file it changes, each app it
6
+ touches. What can't be undone is blocked. What's dangerous waits for your OK. Everything else runs, and you see what
7
+ Anvil would have stopped.
8
+
9
+ No setup and no account. It runs on your machine, and it never stores or sends your prompts or Claude's replies.
10
+
11
+ <br>
12
+
13
+ ## Get started
14
+
15
+ ```bash
16
+ npm i -g @useanvil/claude-code && anvil-claude
17
+ ```
18
+
19
+ That installs it and opens Home. Choose **Turn it on**, press Enter, then start a new Claude Code session, in the
20
+ terminal or the desktop app: Home starts either one for you. Come back to Home any time with `anvil-claude`.
21
+
22
+ Want to see it first? `anvil-claude try` shows what Anvil does if Claude tries to wipe your home folder, drop your
23
+ database, email your customers or push to main. Nothing runs.
24
+
25
+ <br>
26
+
27
+ ## What it does
28
+
29
+ | | |
30
+ |---|---|
31
+ | ✕&nbsp;**Blocks** | What can't be undone: wiping your home folder or the project, force-pushing main. Always on. |
32
+ | ■&nbsp;**Holds** | The dangerous, until you say OK: cloud and database destroys, plus anything you choose. |
33
+ | ○&nbsp;**Watches** | Everything else risky. It runs, and you see what Anvil would have stopped. |
34
+
35
+ <br>
36
+
37
+ ## What you'll see
38
+
39
+ Anvil's lines in Claude Code lead with what happened, between two 🔹.
40
+
41
+ ```
42
+ 🔹 Anvil is on 🔹 blocking unsafe actions automatically · holding cluster, cloud and database destroys for your OK
43
+ › To add your own rules, run in a terminal: anvil-claude rules edit
44
+ 🔹 Blocked by Anvil 🔹 force-pushes main · can't be overridden
45
+ 🔹 Held by Anvil for your OK 🔹 deletes a real folder
46
+ › To allow it once, run this in a terminal (not in this chat):
47
+ anvil-claude allow k3mpq7rx
48
+ › Then tell Claude to go on.
49
+ 🔹 Anvil would've held this for review 🔹 pushes to main (a deploy) · it ran
50
+ › To hold these for your OK, run in a terminal:
51
+ anvil-claude enforce push-main
52
+ 🔹 Today's budget is spent 🔹 $50.12 of $50 · resets at midnight
53
+ › To keep going, run this in a terminal (not in this chat):
54
+ anvil-claude allow 7k2m9xqa
55
+ › Then send your message again.
56
+ ```
57
+
58
+ Every step Anvil asks of you says where it runs: an `anvil-claude` command goes in a terminal (in the desktop app, the
59
+ Terminal panel or any terminal), never in the chat, where Claude can't run it.
60
+
61
+ - **Terminal and desktop app:** both read the same Claude Code settings, so both are checked from the next session on.
62
+ - **Status bar:** in a terminal, Claude Code's bottom line keeps it in view, with what Claude spent today:
63
+ `🔹 Anvil on 🔹 14 checked · 2 stopped · $3.10 today`. On a Claude plan it shows your week instead: `… · 41% of week`.
64
+ If you have a status line of your own, `on` keeps it and adds nothing there.
65
+ - **Your own status line, and a plan budget:** Claude Code sends your plan's limits only to the status line it runs,
66
+ so a budget like `80% of my weekly limit` can't be measured until yours passes the same input to Anvil. `on`,
67
+ `anvil-claude rules add` and `anvil-claude report` print the exact command for your settings, with yours in it:
68
+ `input=$(cat); printf '%s' "$input" | node "$HOME/.anvil/claude/bin/claude-sync.js" --statusline >/dev/null 2>&1;
69
+ printf '%s' "$input" | { your-command; }`. Dollar and token budgets don't need it.
70
+ - **Notifications:** on a Mac, a held action Claude Code can't ask you about (the desktop app, a background run) sends one.
71
+
72
+ <br>
73
+
74
+ ## Make it yours
75
+
76
+ **How it starts:** the blocks and a few holds (cloud and database destroys, printed cloud keys) are on from the first
77
+ action. Every other risky action is only watched: it runs, and you see what Anvil would have stopped.
78
+
79
+ **Hold what you care about.** When a watched line keeps showing up, hold that kind: the line gives the command, and
80
+ Home offers the one it saw most as a single Enter. Or hold every rule at once with `anvil-claude enforce all`.
81
+
82
+ **Set a budget.** `anvil-claude rules add "budget: $50 a day"`. Past it, Claude Code stops before its next message or
83
+ action, and `anvil-claude allow <code>`, run in a terminal, lets that task go on (for that task, one more budget's
84
+ worth and an hour at most).
85
+ Also a week or a task, new tokens (`5M new tokens a day`), or a share of your plan (`80% of my weekly limit`). Anvil
86
+ checks it when you send a message, without reading the message. It can run over by about two replies per thread
87
+ (the reply that crosses it, the one in flight, and the one that reads the stop): usually cents, at worst a cold 1M
88
+ context reply, about $15–30.
89
+
90
+ **Every screen says what a limit does now.** `rules add`, `anvil-claude rules`, the rules screen, Home, `on` and
91
+ `report` show each budget, cap and model rule as it stands: one Anvil can't measure or hear here says why, with the
92
+ fix, never that it stops anything.
93
+
94
+ | Command | What it does |
95
+ |---|---|
96
+ | `anvil-claude` | Home: where it stands, what to do next |
97
+ | `anvil-claude try` | see it work; nothing runs |
98
+ | `anvil-claude report` | what it stopped this week, and what Claude spent |
99
+ | `anvil-claude rules` | every rule, and what it does now |
100
+ | `anvil-claude enforce push-main` | hold one kind of action for your OK |
101
+ | `anvil-claude enforce all` | hold every rule |
102
+ | `anvil-claude rules add "Ask before it deploys."` | add a rule in plain words |
103
+ | `anvil-claude rules add "budget: $50 a day"` | stop Claude Code past what it may spend |
104
+ | `anvil-claude rules add "model: opus for deploys"` | hold deploys made on another model |
105
+ | `anvil-claude rules edit` | every rule on one screen: type one in plain English to add it |
106
+ | `anvil-claude off` | take it out; your settings go back as they were |
107
+
108
+ Run these in your own terminal. Claude can't run them from inside Claude Code, so it can't switch Anvil off.
109
+
110
+ Your rules live in `~/.anvil/rules.md` (every project) or `.anvil/rules.md` (one project), one per line, like
111
+ `hold: deploys`. `anvil-claude help rules` prints the rest (`docs/coding-agents/YOUR-RULES.md`, in this package).
112
+
113
+ **Helper agents.** `model: haiku for exploring` (or `sonnet for helper agents`) runs the agents Claude launches on
114
+ the model you name, whatever Claude asks for. `cap: at most 5 helper agents at once` holds the next launch until one
115
+ finishes, and `cap: 20 helper agents an hour` works too. A fork keeps the session's model.
116
+
117
+ **The main chat's model.** No tool can switch it, so Anvil holds instead: `model: opus for deploys` holds a deploy made
118
+ on another model (`/model opus`, then ask Claude again, runs it), and `model: never haiku` refuses a switch to Haiku
119
+ and every message in a session on it (one the desktop app's picker or `claude --model haiku` started there), in the
120
+ terminal and the desktop app.
121
+
122
+ <br>
123
+
124
+ ## What a rule can cover
125
+
126
+ A rule is about a **kind of action** Claude takes, and it can name one app, one file or folder, or one target of the
127
+ kind. Type it in plain words, or paste the command: Anvil reads a command the way it does when Claude runs it, so
128
+ `docker push` holds what Anvil calls a publish.
129
+
130
+ | You can | For example |
131
+ |---|---|
132
+ | Hold a kind of action for your OK, or block it | `hold pushes to main` · `never force-push` · `ask before it deploys` · `docker push` |
133
+ | Narrow it to one app | `hold Stripe changes` · `never send email through Gmail` · `hold Slack posts` |
134
+ | Narrow it to a file or folder | `don't touch migrations/` · `ask before editing package-lock.json` · `hold changes to infra/` |
135
+ | Narrow it to one target | `hold deploys to production` · `hold pushes to main in billing-api` · `hold deletes outside the project` |
136
+ | Hold only some of them | `hold Stripe refunds over $500` · `never email anyone outside the company` · `hold Slack posts in #general` · `hold deploys on Fridays` |
137
+ | Cap how often, or how much | `at most 3 deploys a day` · `at most 5 Stripe refunds a day` · `at most $2,000 of Stripe refunds a day` · `5 helper agents at once` |
138
+ | Set a budget | `$50 a day` · `80% of my weekly limit` |
139
+ | Tie an action to a model | `model: opus for deploys` · `model: haiku for exploring` |
140
+
141
+ The kinds: pushes to main, force-pushes, deletes, throwing away uncommitted work, database destroys, deploys,
142
+ publishing, printing secrets, running as root, killing processes, writes to other services, paid compute, tunnels,
143
+ copying a database here, crypto transactions, background jobs, helper agents, `.env` files, and app changes.
144
+
145
+ **A narrowed rule only adds a stop, and holds what it can't read.** The box shows what still runs before you add one.
146
+
147
+ **Every rule you type gets one of three answers, said first:** ✓ ready; ▲ a catch, where it works with one difference
148
+ said plainly (an app not connected here, a category that covers every app of it Anvil knows, a deploy that doesn't say where it
149
+ goes held too); or ? can't yet, with the closest rule Anvil can do, one key away (`rules add` prints it as a command).
150
+ A catch stays on the rule's row: `hold Shopify refunds` says "not connected yet" until you connect Shopify.
151
+
152
+ - **One app** covers its MCP tools, its API reached from a command (`curl -X POST https://api.stripe.com/…`) and its
153
+ CLI. Reads run. Anvil knows an app by your own MCP servers and connectors too, by name only.
154
+ - **A file or folder** covers Claude's file tools and every shell write Anvil can read (`>`, `tee`, `sed -i`, `cp`,
155
+ `mv`, `rm`). Reads run. A script that builds its paths as it runs isn't seen. Claude Code's own `Edit(…)` rule is the
156
+ other way to do it, without the one-time OK.
157
+ - **A target** is read from the command itself: `vercel --prod`, `fly -a`, `railway -e`, `kubectl --context`, `modal -e`,
158
+ terraform's workspace; a push's repository from the checkout it runs in. A deploy whose command doesn't say where it
159
+ goes is held, and so is a tool whose default may be production.
160
+ - **A condition** is read from the call itself: a money app's amount, who an email or an invite reaches (with
161
+ `define: my company = acme.com` for "outside the company"), one part of an app (a Slack channel, a GitHub
162
+ repository, a Linear team, a Jira project), or the time on this Mac's clock. What it can't read, it holds, saying why
163
+ (a full refund names no amount; a channel id Anvil hasn't seen yet). `anvil-claude help rules` lists each.
164
+
165
+ **What a rule can't cover yet.** The box says which one, and what to type instead:
166
+
167
+ - **Conditions Anvil can't read** (`deploys unless tests pass`, `during the launch`, `on December 3rd`, refunds
168
+ `over 10%`, who a Slack message or a text reaches). The box offers the rule without them, which holds every one.
169
+ - **Other environments and regions** (`deploys to staging`, `to eu-west`). Hold production instead: staging and
170
+ previews run.
171
+ - **Advice for Claude** (`write tests first`). That belongs in CLAUDE.md.
172
+ - **Everyday commands** (`npm install`, `git commit`). They run as always.
173
+
174
+ Always on can't be turned down. Anvil checks what Claude does, not the commands you run yourself.
175
+
176
+ <br>
177
+
178
+ ## Privacy
179
+
180
+ - **Only actions.** Anvil judges what Claude does, never what you or Claude say, and it never stores or sends your
181
+ prompts or Claude's replies. From Claude Code's session files it picks out four things only: Claude Code's version,
182
+ whether you said Yes to a held action, each reply's model, token counts and cost, and when a helper agent last
183
+ worked, never its text. From a helper launch, only its type and model.
184
+ - **On your machine.** What it records stays in `~/.anvil`. What Claude spent is kept for 40 days.
185
+ - **Usage counts.** Anvil sends anonymous usage counts, listed in `TELEMETRY.md`. `DO_NOT_TRACK=1` turns them off.
186
+
187
+ <br>
188
+
189
+ ## Good to know
190
+
191
+ **Runs on** macOS and Linux · Node 20+ · Claude Code 2.1.295 or later. Not on Windows yet: it is built and in testing.
192
+
193
+ **What each limit needs:**
194
+
195
+ | Limit | Needs |
196
+ |---|---|
197
+ | rules, caps, a helper's model | Claude Code 2.1.295 or later |
198
+ | `model: opus for deploys` | Claude Code 2.1.304 or later (it records each request's model) |
199
+ | refusing the next message, a task budget, helpers at once, `model: never …` | Claude Code 2.1.318 or later, on every Claude Code `on` finds |
200
+ | a plan budget (`80% of my weekly limit`) | a status line reading in the terminal (above) |
201
+
202
+ An older Claude Code anywhere on the machine keeps `on` from adding the events those listen to (one that can't read them
203
+ could cost the hooks that guard); the screens name it, by version and path. The desktop app reads the same settings,
204
+ so everything works there, but it has no status line: a plan budget uses the latest terminal reading. The Claude Code
205
+ plugin, instead of `anvil-claude on`, checks actions only: no message refusal, task budgets, helper count or `/model`
206
+ refusal.
207
+
208
+ - **Update it:** `npm i -g @useanvil/claude-code`, then run `anvil-claude` once: it puts the new hook in place.
209
+ - **Remove it:** `anvil-claude off --purge`, then `npm uninstall -g @useanvil/claude-code`. Your rules files stay.
210
+ - **Beside the SDK:** this package's command is `anvil-claude`, and `@useanvil/sdk` keeps its own `anvil`, so the
211
+ two install side by side and neither touches the other's. The SDK's `anvil-claude …` is the same Anvil for Claude
212
+ Code, with the same files in `~/.anvil/claude`: use either.
213
+
214
+ Questions, or something broken? henry@anvilcontrol.ai · Security: [anvilcontrol.ai/security](https://anvilcontrol.ai/security) ·
215
+ What's new: `CHANGELOG.md`
package/TELEMETRY.md ADDED
@@ -0,0 +1,60 @@
1
+ # Telemetry
2
+
3
+ What the Anvil CLI (`@useanvil/sdk`) tells Anvil about how it is used, field by field. A test
4
+ (`tests/coding-agents/telemetry.test.ts`) holds this page to the code: an event or field that is not
5
+ listed here cannot be sent.
6
+
7
+ ## Turn it off
8
+
9
+ - `DO_NOT_TRACK=1` or `ANVIL_FUNNEL_DISABLED=1` turns all of it off.
10
+ - The Claude Code events below are never sent in CI (`CI`, `GITHUB_ACTIONS`, `GITLAB_CI`, `BUILDKITE`,
11
+ `CIRCLECI`, `TF_BUILD`, `JENKINS_URL`, `TEAMCITY_VERSION`).
12
+
13
+ ## Where it goes
14
+
15
+ One `POST` per event to `https://app.anvilcontrol.ai/api/funnel` (`ANVIL_HOSTED_DASHBOARD_URL` moves it),
16
+ with the body `{ "fid", "event", "props" }`:
17
+
18
+ - `fid` is a random id made on this machine, not derived from anything about you or your machine.
19
+ The Claude Code events below use their own (`c_` and 32 hex characters, in `~/.anvil/claude/telemetry-id`),
20
+ shared with nothing else. The other CLI events use `~/.anvil/anon-id.json` (`a_` and 32 hex characters):
21
+ `anvil protect` also puts that one in the address of the onboarding page it opens, and once you sign up
22
+ there the page can link it to your workspace. With tracking off, no id is made and none is passed.
23
+ - The server keeps the event name, the time, the `fid` and the fields below. It drops any event it does
24
+ not know and keeps at most 8 fields.
25
+
26
+ ## Never sent
27
+
28
+ Commands, file paths, folder or project names, rule text, your machine's name, emails, workspace ids,
29
+ API keys, and anything from your Claude Code transcripts.
30
+
31
+ ## Anvil for Claude Code
32
+
33
+ The first command that would send one of these prints a notice once per machine, before anything is
34
+ sent: `anvil claude on` on stdout, `anvil replay` on stderr. It counts only when that output is a terminal a
35
+ person can read: piped to a file, or run by an agent, nothing is shown and nothing is sent. Until it has been
36
+ shown, the hook's background sync never sends either.
37
+
38
+ | Event | When | Fields |
39
+ | --- | --- | --- |
40
+ | `claude_on` | `anvil claude on` | `mode` (`ghost` or `some-enforced`), `scope` (`user` or `project`), `linked` (signed in, `true`/`false`), `plugin` (the Claude Code plugin is enabled, `true`/`false`) |
41
+ | `replay_run` | `anvil replay` | `window` (`30d` or `all`), `sessions`, `actions`, `would_stop`, `active_days`: each a bucket, `0`, `1-9`, `10-99`, `100-999`, `1k-9k` or `10k+` |
42
+ | `decisions_daily` | once for each past day the hook ran, at most the last 7, never a day before the notice: sent by `anvil claude on` or `anvil claude sync`, or by the background sync when signed in | `day` (the UTC date), `calls` (tool calls checked, a bucket), and counts: `held`, `blocked`, `would` (would have stopped, in ghost), `approved` (allowed once), `errors` (calls Anvil could not check) |
43
+
44
+ ## Other CLI events
45
+
46
+ | Event | When | Fields |
47
+ | --- | --- | --- |
48
+ | `install` | the first `anvil protect` on a machine | none |
49
+ | `command_run` | each `anvil protect` | none |
50
+ | `protect_no_match` | `anvil protect` found nothing to wrap | `cause`, `scope`, `language` |
51
+ | `signed_in` | `anvil login` | none |
52
+
53
+ ## Not telemetry: your dashboard
54
+
55
+ Signed in (`anvil login`), the Claude Code hook's stops go to **your own workspace**, so your dashboard
56
+ can show them. That is your data, not usage counts, and the hook never sends it itself: a background
57
+ process does, within seconds. Each stop carries the kind of action (`claude.bash.git.push_main`), the
58
+ verdict and mode, the name of the Anvil rule (your own rules are sent as `your-rule`), a reason made only
59
+ of Anvil's fixed labels, the time, how long the check took, and a key made of your machine label, the
60
+ first 8 characters of the Claude Code session id, and a hash. Never the command, a path or a project name.
@@ -0,0 +1,12 @@
1
+ function E(e){return Object.assign(Object.create(null),e)}var ce=[{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 ue=/^[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]|$)/,de=e=>e.normalize("NFKC").replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase(),fe=(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=de(n);return e.toolWords.length===0||e.toolWords.some(o=>fe(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=de(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=>fe(g,m))?{hit:"match",part:t,why:e.said}:null;if(!ue.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 ${ue.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",ye="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)",pe="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)",we="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 z(e){let t=(e.host??"").toLowerCase(),n=`_${t}_`.replace(/_mcp(?=[a-z])|(?<=[a-z])mcp_/g,"_"),s=ce.filter(r=>e.action===we?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
+ `){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
+ `)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&&gt.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(`
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)&&oe.test(e.toLowerCase()))t.why??=M;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=te(c);u==null||u===""||Array.isArray(u)&&u.length===0||(n?Pt.test(d)&&(i=!0,R(u,t,!0,s+1)):ne.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??=M):re.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 Q=(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
+ `&&(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||=Q(e,g),c||=e[g]==="$"||e[g]==="`",i+=e[g])}c||=g>=e.length,u=!0,m=g}else if(p==="$"||p==="`")s||=Q(e,m),i+=p,c=u=!0;else if(p==="#"&&!u){let g=e.indexOf(`
9
+ `,m);m=(g<0?e.length:g)-1}else if(p==="<"&&h==="<"&&e[m+2]!=="<"){l();let g=/^<<(-?)[ \t]*((?:[^\s;&|<>()'"\\]|'[^']*'|"[^"]*"|\\.)+)/.exec(e.slice(m));g&&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
+ `)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=>ae.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"&&ae.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(!ae.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};
@@ -0,0 +1,12 @@
1
+ import{createHash as Me}from"crypto";import{readdirSync as L,readFileSync as Le,rmdirSync as Ie,rmSync as Te,statSync as De,unlinkSync as le}from"fs";import{basename as G,dirname as I,join as h,resolve as We}from"path";import{existsSync as Wt,readdirSync as Ft,statSync as zt}from"fs";import{dirname as Ht,isAbsolute as Ut,join as Bt,posix as Gt,resolve as Kt}from"path";import{posix as Q}from"path";var be=null;function P(){return be??process.platform==="win32"}var X=/^([A-Za-z]):(.*)$/s,$e=/^\/(?:cygdrive\/)?([A-Za-z])(\/.*)?$/s;function W(e,t){let n=Q.normalize(`/${t}`);return n==="/"?e:`${e}${n.replace(/\/$/,"")}`}function C(e,t){return e.split("/").map(n=>{if(n===""||n==="."||n===".."||/[\u0000\u0001]/.test(n))return n;let r=n.indexOf(":"),o=r>=0?n.slice(0,r):n,i=t?o:o.replace(/[. ]+$/,"");return i===""?".":i}).join("/")}function F(e){if(!P())return e;let t=e.replace(/^(?:Microsoft\.PowerShell\.Core\\)?FileSystem::/i,""),n=!1,r=/^[\\/]{2}([?.])[\\/](.*)$/s.exec(t);if(r){let s=r[2];if(r[1]===".")return`/dev/${s.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;if(/^unc[\\/]/i.test(s))t=`\\\\${s.slice(4)}`;else if(X.test(s))t=s;else return`/dev/${s.replace(/[\\/]+/g,"/").replace(/\/$/,"").toLowerCase()}`;n=!0}t=t.replace(/\\/g,"/");let o=/^\/\/([^/]+)(?:\/([^/]+))?(\/.*)?$/s.exec(t);if(o){let s=`/unc/${C(o[1],n).toLowerCase()}${o[2]?`/${C(o[2],n).toLowerCase()}`:""}`;return W(s,C(o[3]??"",n).toLowerCase())}let i=X.exec(t);if(i){let s=i[2];return s===""?`/${i[1].toLowerCase()}`:s.startsWith("/")?W(`/${i[1].toLowerCase()}`,C(s,n).toLowerCase()):null}let l=$e.exec(t);if(l)return W(`/${l[1].toLowerCase()}`,C(l[2]??"",n).toLowerCase());let c=C(t,n).toLowerCase();if(c.startsWith("/")){let s=Q.normalize(c);return s.length>1&&s.endsWith("/")?s.slice(0,-1):s}return c}function ke(e){return F(e)??e}function z(e){return!P()||typeof e!="string"||e===""?e:ke(e)}import{createHash as kt}from"crypto";import{appendFileSync as ve,closeSync as te,constants as ee,fstatSync as ne,mkdirSync as xe,openSync as re,readdirSync as xt,readFileSync as _t,readSync as oe,renameSync as At,statSync as _e,unlinkSync as Ct,writeFileSync as Rt}from"fs";import{homedir as Nt}from"os";import{dirname as Et,join as jt}from"path";var Ae=3500;function R(e,t=8*1024*1024){try{let n=_e(e);return n.isFile()&&n.size<=t}catch(n){return n.code==="ENOENT"?null:!1}}function S(e,t=8*1024*1024){let n;try{n=re(e,ee.O_RDONLY|ee.O_NONBLOCK)}catch(r){if(r.code==="ENOENT"||r.code==="ENOTDIR")return null;throw r}try{let r=ne(n);if(!r.isFile())throw new Error(`${e} is not a regular file`);if(r.size>t)throw new Error(`${e} is over ${t} bytes`);let o=Buffer.alloc(r.size),i=0;for(;i<r.size;){let l=oe(n,o,i,r.size-i,i);if(l===0)break;i+=l}return o.subarray(0,i)}finally{te(n)}}function y(e,t){let n=t.endsWith(`
2
+ `)?t:`${t}
3
+ `;if(Buffer.byteLength(n)>Ae)throw new Error(`refusing to append a ${Buffer.byteLength(n)}-byte line`);if(R(e,Number.MAX_SAFE_INTEGER)===!1)throw new Error(`refusing to append to ${e}: not a regular file`);ve(e,n,{mode:384})}function N(e){xe(e,{recursive:!0,mode:448})}function M(e,t){if(R(e,Number.MAX_SAFE_INTEGER)!==!0)return"";let n;try{n=re(e,"r")}catch{return""}try{let r=ne(n).size,o=Math.max(0,r-t),i=r-o;if(i<=0)return"";let l=Buffer.alloc(i);oe(n,l,0,i,o);let c=l.toString("utf8");if(o>0){let s=c.indexOf(`
4
+ `);c=s<0?"":c.slice(s+1)}return c}finally{te(n)}}var Mt=256*1024,Lt=1024*1024;import{domainToASCII as nn}from"url";var dn="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" ");import{existsSync as Nn,readdirSync as On,realpathSync as En}from"fs";import{basename as Pn,dirname as Mn,join as Ln}from"path";function se(e,t){return e.origin!=="project"||!!(t&&e.project_dir&&Se(t,e.project_dir))}function Se(e,t){let n=z(e),r=z(t),o=r.endsWith("/")?r.slice(0,-1):r;return n===o||n.startsWith(o+"/")}var k={on:"\u25CF",watching:"\u25CB",held:"\u25A0",ok:"\u2713",blocked:"\u2715",problem:"\u25B2",next:"\u203A"};function Ne(e){if(!e){let s=a=>a;return{on:!1,bold:s,dim:s,blue:s,grey:s,amber:s,mark:s,field:s}}let t=e==="truecolor",n=s=>a=>`\x1B[${s}m${a}\x1B[0m`,r=n(t?"38;2;76;139;255":"38;5;69"),o=n(t?"38;2;130;134;150":"90"),i=n(t?"38;2;245;165;36":"38;5;214"),l=n(t?"38;2;34;197;94":"32"),c={[k.on]:r,[k.blocked]:r,[k.held]:r,[k.next]:r,[k.watching]:o,[k.problem]:i,[k.ok]:l};return{on:!0,bold:n("1"),dim:n("2"),blue:r,grey:o,amber:i,mark:s=>(c[s]??(a=>a))(s),field:s=>`\x1B[${t?"48;2;24;2;166;38;2;255;255;255":"48;5;19;97"}m${Ee(s)}\x1B[0m`}}var sr=Ne(!1),Oe=/\u001b\[[0-9;]*m|\u001b\][^\u0007]*\u0007/g;function Ee(e){return e.replace(Oe,"")}var ie=[{id:"protect",name:"Protect what can't come back",verdict:"block",short:"wiping your home folder or the project, and force-pushing main",context:"blocks deleting the user's home folder, the disk, a system folder, the project or its .git, force-pushing main or deleting it on the remote, and killing every process",slugs:{protected:"deleting your home folder, the disk, a system folder, the project or its .git; force-pushing main or deleting it on the remote; killing every process"}},{id:"keep-anvil-on",name:"Keep Anvil on",verdict:"hold",short:"changes to Anvil",context:"holds any change to Anvil or to Claude Code's permissions, hooks and settings",slugs:{"agent-controls":"any change to Anvil, or to Claude Code's permissions, hooks and settings"}},{id:"stop-loops",name:"Stop runaway loops",verdict:"hold",short:"delete bursts and repeats",context:"holds more than 20 recursive deletes in a minute and the same app change twice in 10 minutes",slugs:{"delete-burst":"more than 20 recursive deletes in a minute",repeat:"the same app (MCP) change twice in 10 minutes"}},{id:"stop-helper-bursts",name:"Stop runaway helpers",verdict:"hold",short:"helper bursts",context:"holds more than 20 helper agent launches in 10 minutes in one session",slugs:{"helper-burst":"more than 20 helper launches in 10 minutes"}},{id:"keep-keys-in",name:"Keep keys in",verdict:"hold",short:"use of your account keys",context:"holds reading or writing the user's account key files (such as ~/.ssh/id_* and ~/.aws/credentials) and committing or sending a secrets file",slugs:{credentials:"reading or writing your account key files (~/.ssh/id_*, ~/.aws/credentials, ~/.npmrc \u2026)","secrets-expose":"committing or sending a secrets file"}},{id:"hold-unchecked",name:"Hold what it can't check",verdict:"hold",short:"actions it can't check",context:"holds a call it could not read in full or check in time",slugs:{"could-not-check":"a command too long or nested too deep to read, or one its classifier failed on","too-long-to-check":"a call it could not check in time (1 second a pass, 3 in all)"}}],je="home and project wipes and force-pushes to main",pr=`always blocking ${je}`,gr=new Map(ie.map(e=>[e.id,e]));var Pe=new Set(ie.flatMap(e=>Object.keys(e.slugs)));var q="anvil-claude";function O(e){let t=e.trim();return t===q||t.endsWith(` ${q}`)||t.endsWith(`/${q}`)||/(^|[\s/])@useanvil\/claude-code(@\S+)?$/.test(t)||/(^|\s)claude$/.test(t)?t:`${t} claude`}var ae="\u{1F539}",x=e=>`${ae} ${e} ${ae}`;var H=(e,t)=>`they run \`${O(e)} allow\` in a terminal (not in this chat: Claude can't run it), which lists what's waiting for their OK, then ${t}`;var ce="claude.agent.helper",Fe=6e4,ze=30*6e4,qe=30*6e4,ue=6e4,He="workflow-subagent",Ue=4*1024*1024,de=[2,1,318],Be="/.anvil/claude/bin/claude-hook.js",Ge=process.platform==="darwin"?"/Library/Application Support/ClaudeCode/managed-settings.json":process.platform==="win32"?`${process.env.ProgramFiles||"C:\\Program Files"}\\ClaudeCode\\managed-settings.json`:"/etc/claude-code/managed-settings.json",fe=40,m=e=>typeof e=="string"&&e.length>0?e:null,K=e=>e?/^[A-Za-z0-9_-]{1,80}$/.test(e)?e:Me("sha256").update(e).digest("hex").slice(0,24):"none",Ke=/^[A-Za-z0-9_-]{1,64}$/,Je=e=>e[0].toUpperCase()+e.slice(1),J=e=>{let t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`},_=e=>h(e.dir,"helpers"),Y=(e,t)=>h(_(e),"live",`${K(t)}.log`);function Ye(e,t){let n=null,r=null;for(let o of e)for(let i of o.helpers?.models??[])i.types===null?n=i:i.types.includes(t)&&(r=i);return r??(t==="fork"?null:n)}function Ze(e){let t=null;for(let n of e)for(let r of n.helpers?.at_once??[])(!t||r.limit<t.limit)&&(t=r);return t}function Ve(e,t){let n=m(e.env.CLAUDE_CONFIG_DIR),r=h(n?We(n):h(e.home,".claude"),"settings.json"),o=m(e.env.CLAUDE_PROJECT_DIR)??m(t.cwd);return o?[r,h(o,".claude","settings.local.json"),h(o,".claude","settings.json")]:[r]}function Fr(e){let t=Ve(e.deps,e.payload),n=e.modes?.kill_switch===!0,r=e.payload.tool_input&&typeof e.payload.tool_input=="object"&&!Array.isArray(e.payload.tool_input)?e.payload.tool_input:{},o=typeof r.subagent_type=="string"&&r.subagent_type.trim()?r.subagent_type.trim():"general-purpose",i=m(e.payload.session_id),l=e.table.policies.filter(p=>p.helpers&&se(p,e.projectDir)),c=[],s=(p,d)=>{nt(e.paths,i,p)&&c.push(d)},a=n?null:Ye(l,o);a&&r.model===a.model&&(a=null);let g=n?null:Ze(l),f=a||g?et(t,o,e.managed??Ge):null;if(f==="deny"&&(a=null),o==="fork"&&!n){let p=l.flatMap(d=>d.helpers?.models??[]).find(d=>d.types===null);p&&s(`fork-${p.id}`,`${x("Anvil")} a fork helper keeps this session's model \xB7 ${p.text} can't switch it`)}let u=m(e.payload.tool_use_id)??`${e.now}-${process.pid}`,w=Y(e.paths,i),b=!1,v=null,$=0;if(g&&f!=="deny"){let p=Xe(e,t);if(p)s(`count-${g.id}`,`${x("Anvil")} can't count helper agents here (${p}) \xB7 ${g.text} isn't enforced`);else{try{let d=it(w,u,g.limit,e.now);b=d===null,d!==null&&($=d)}catch(d){$=-1,v={action:ce,decision:{verdict:"hold",policy:"caps",origin:null,ruleId:g.id,blockedBy:"cap_unreadable",source:g.source},mode:"enforce",floor:null,why:`couldn't count helper agents for ${g.text} (${d?.code??(d instanceof Error?d.message.slice(0,60):"unreadable")})`,target:o}}$>0&&(v={action:ce,decision:{verdict:"hold",policy:"caps",origin:null,ruleId:g.id,blockedBy:"cap_reached",source:g.source},mode:"enforce",floor:null,why:`${$} helper ${$===1?"agent":"agents"} running or starting (cap: ${g.text})`,target:o})}}let T=()=>{if(b){b=!1;try{y(w,JSON.stringify({t:e.now,op:"x",k:u}))}catch{}}},ye=()=>{if(!b)return;let p=m(e.payload.transcript_path),d=m(e.payload.tool_use_id);try{y(w,JSON.stringify({t:e.now,op:"q",k:u,...p&&d&&p.length<1024&&d.length<256?{tr:p,c:d}:{}}))}catch{}};return{stop:v,agent:p=>$<0?`${x("Held by Anvil")} ${v.why}. Nothing ran. Tell the user${p?`: to let it start once, ${H(e.cli,"tell you to launch it again")}`:"; once it is fixed, launch it again"}. Do not try another way.`:`${x("Held by Anvil")} ${$} helper ${$===1?"agent is":"agents are"} running or starting in this session, and the user's cap is ${g?.text??"reached"}. Nothing ran. Wait for one of them to finish, then launch this one again; don't retry it before then.${p?` To let it start now, ${H(e.cli,"tell you to launch it")}.`:""}`,release:T,ran:()=>{if(a)try{at(e.paths,{t:e.now,session:i?K(i):null,type:o,from:typeof r.model=="string"?r.model.slice(0,40):null,to:a.model,rule:a.id,project:e.projectDir?G(e.projectDir):null})}catch{}},finish:p=>{let d={};try{d=p.stdout?JSON.parse(p.stdout):{}}catch{return T(),p}let Z=d.hookSpecificOutput&&typeof d.hookSpecificOutput=="object"?d.hookSpecificOutput:null,E=Z?.permissionDecision;E==="deny"?T():(E==="ask"||f==="ask")&&ye();let j=c.join(`
5
+ `);if(!a&&!j)return p;if(a&&E!=="deny"){let D={...r,model:a.model},V=`switched this helper to ${Je(a.model)} \xB7 ${a.text}`;E==="ask"?d.hookSpecificOutput={...Z,updatedInput:D}:f==="ask"?d.hookSpecificOutput={hookEventName:"PreToolUse",permissionDecision:"ask",permissionDecisionReason:`${x("Anvil")} ${V}; your own rule asks before helper agents`,updatedInput:D}:d.hookSpecificOutput={hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:`${x("Anvil")} ${V}`,updatedInput:D}}return j&&(d.systemMessage=typeof d.systemMessage=="string"?`${d.systemMessage}
6
+ ${j}`:j),{stdout:`${JSON.stringify(d)}
7
+ `,exitCode:0}}}}function Xe(e,t){if(!Qe(t))return e.deps.plugin===!0?`the plugin isn't told when helpers start and stop; ${O(e.cli)} on is`:`its helper start and stop entries aren't set up: run ${O(e.cli)} on, which names any Claude Code that keeps them out`;let n=tt(m(e.payload.transcript_path));if(!n)return"this session's Claude Code version can't be read";for(let r=0;r<3;r++)if(n[r]!==de[r])return n[r]>de[r]?null:`Claude Code ${n.join(".")} doesn't report helpers starting and stopping; 2.1.318 does`;return null}function pe(e){try{if(R(e,4*1024*1024)!==!0)return null;let t=JSON.parse(Le(e,"utf8").replace(/^/,""));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Qe(e){return e.some(t=>{let n=pe(t)?.hooks;return["SubagentStart","SubagentStop"].every(r=>JSON.stringify(n?.[r]??null).includes(Be))})}function et(e,t,n){let r=null;for(let o of[n,...e]){let i=pe(o)?.permissions;for(let l of["deny","ask"]){let s=(Array.isArray(i?.[l])?i[l]:[]).some(a=>{let g=typeof a=="string"?/^\s*(?:Agent|Task)\s*(?:\(\s*([^)]*?)\s*\))?\s*$/.exec(a):null;return g!==null&&(g[1]===void 0||g[1]===""||g[1]==="*"||g[1]===t)});if(s&&l==="deny")return"deny";s&&(r="ask")}}return r}function tt(e){if(!e)return null;try{let t=null;for(let n of M(e,256*1024).matchAll(/"version":"(\d+)\.(\d+)\.(\d+)"/g)){let r=[Number(n[1]),Number(n[2]),Number(n[3])];(!t||r[0]>t[0]||r[0]===t[0]&&(r[1]>t[1]||r[1]===t[1]&&r[2]>t[2]))&&(t=r)}return t}catch{return null}}function nt(e,t,n){try{let r=h(e.state,`helpers-said-${K(t)}`);return M(r,64*1024).split(`
8
+ `).includes(n)?!1:(N(e.state),y(r,n),!0)}catch{return!0}}function U(e){let t=S(e,Ue);if(!t)return[];let n=[];for(let r of t.toString("utf8").split(`
9
+ `))if(r)try{let o=JSON.parse(r);typeof o.t=="number"&&typeof o.op=="string"&&n.push(o)}catch{}return n}var B=e=>{try{return De(e).mtimeMs}catch{return 0}};function rt(e){let t=B(e);if(t>0)return t;let n=0;try{let r=h(I(e),"workflows");for(let o of L(r).slice(0,512))n=Math.max(n,B(h(r,o,G(e))))}catch{}return n}function ge(e,t,n=e.length,r=rt){return he(e,t,n,r).count}function he(e,t,n,r){let o=new Map,i=new Map,l=new Set,c=f=>f.q?ze:Fe;for(let f=0;f<Math.min(n,e.length);f++){let u=e[f];if(u.op==="z")o.clear(),i.clear();else if(u.op==="r"&&u.k)o.set(u.k,{t:u.t,q:null});else if(u.op==="q"&&u.k){let w=o.get(u.k);w&&(w.q=u)}else if(u.op==="x"&&u.k)o.delete(u.k);else if((u.op==="s"||u.op==="e")&&u.a){if(u.op==="s"&&!i.has(u.a)&&!l.has(u.a)){if(!u.w){for(let[b,v]of o)u.t-v.t>=c(v)&&o.delete(b);let w=[...o].find(([,b])=>!b.q)?.[0]??o.keys().next().value;w!==void 0&&o.delete(w)}i.set(u.a,u)}u.op==="e"&&(i.delete(u.a),l.add(u.a))}}let s=f=>f>t+ue?0:f,a=0,g=[];for(let f of o.values())f.t>t+ue||t-f.t>=c(f)||(a++,f.q&&g.push(f.q));for(let f of i.values())t-Math.max(s(f.t),f.f?s(r(f.f)):0)<qe&&a++;return{count:a,asked:g}}function ot(e,t,n){let r=0;for(let o of he(t,n,t.length,()=>0).asked)r>=4||!o.tr||!o.c||n-o.t<1e3||(r++,st(o.tr,o.c)&&y(e,JSON.stringify({t:n,op:"x",k:o.k})))}function st(e,t){try{let n=M(e,1048576),r=`"tool_use_id":"${t}"`;for(let o=n.indexOf(r);o>=0;o=n.indexOf(r,o+r.length)){let i=n.indexOf(`
10
+ `,o);try{let l=JSON.parse(n.slice(n.lastIndexOf(`
11
+ `,o)+1,i<0?void 0:i)),s=(Array.isArray(l.message?.content)?l.message.content:[]).find(a=>a.type==="tool_result"&&a.tool_use_id===t);if(s)return s.is_error===!0}catch{}}return!1}catch{return!1}}function it(e,t,n,r,o){try{ot(e,U(e),r)}catch{}let i=()=>{N(I(e)),y(e,JSON.stringify({t:r,op:"r",k:t}))};try{i()}catch(a){if(a.code!=="ENOENT")throw a;i()}o?.();let l=U(e),c=l.findIndex(a=>a.op==="r"&&a.k===t&&a.t===r);if(c<0)throw new Error("its place wasn't read back");let s=ge(l,r,c+1);return s<=n?null:(y(e,JSON.stringify({t:r,op:"x",k:t})),s-1)}function zr(e,t,n){return ge(U(Y(e,t)),n)}function qr(e,t,n){try{let r=m(e.hook_event_name),o=m(e.session_id);if(!o)return;if(!S(t.compiled,16*1024*1024)?.includes('"at_once"'))return void Te(h(_(t),"live"),{recursive:!0,force:!0});let i=Y(t,o),l=R(i,Number.MAX_SAFE_INTEGER)===!0;if(r==="SessionStart"){l&&m(e.source)==="resume"&&y(i,JSON.stringify({t:n,op:"z"}));return}let c=m(e.agent_id);if(!c||!Ke.test(c)||r!=="SubagentStart"&&r!=="SubagentStop")return;if(l||me(t,n),N(I(i)),r==="SubagentStop")return y(i,JSON.stringify({t:n,op:"e",a:c}));let s=m(e.transcript_path),a=s&&s.startsWith("/")&&s.endsWith(".jsonl")?h(I(s),G(s,".jsonl"),"subagents",`agent-${c}.jsonl`):null;y(i,JSON.stringify({t:n,op:"s",a:c,...a&&a.length<1024?{f:a}:{},...m(e.agent_type)===He?{w:1}:{}}))}catch{}}function at(e,t){let n=_(e),r=h(n,`${J(t.t)}.log`);N(n),R(r)===null&&me(e,t.t),y(r,JSON.stringify(t))}function Hr(e,t,n){let r={},o=0,i=new Date(Math.max(t,n-(fe+1)*864e5));for(i.setHours(0,0,0,0);i.getTime()<=n;i.setDate(i.getDate()+1)){let l="";try{l=S(h(_(e),`${J(i.getTime())}.log`),16*1024*1024)?.toString("utf8")??""}catch{l=""}for(let c of l.split(`
12
+ `))if(c)try{let s=JSON.parse(c);if(typeof s.t!="number"||s.t<t||s.t>n||typeof s.to!="string")continue;r[s.to]=(r[s.to]??0)+1,o++}catch{}}return{total:o,byModel:r}}function me(e,t){try{let n=J(t-fe*864e5);for(let r of L(_(e)))/^\d{4}-\d{2}-\d{2}\.log$/.test(r)&&r.slice(0,10)<n&&le(h(_(e),r))}catch{}try{let n=h(_(e),"live");for(let r of L(n))r.endsWith(".log")&&t-B(h(n,r))>2*864e5&&le(h(n,r));L(n).length===0&&Ie(n)}catch{}}export{ze as ASK_MS,ce as HELPER_ACTION,Fe as RESERVE_MS,qe as STALE_MS,it as admit,Ze as atOnceFor,_ as helpersDir,Fr as launchStep,Y as ledgerFile,ge as liveAt,Ye as modelRuleFor,qr as onEvent,et as ownAgentRule,U as readLedger,st as refusedIn,zr as runningNow,Ve as settingsFiles,Qe as subagentEntries,Hr as switchesIn,rt as transcriptChanged};