@fiderail/cli 0.0.0-stage → 2.4.3

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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation,
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Work; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Work, in at least one of the
111
+ following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional notices cannot be construed as modifying
121
+ the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, but not limited to, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate act or
156
+ grossly negligent act) or agreed to in writing, shall Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 FideRail Contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,19 @@
1
+ FideRail
2
+ Copyright 2026 FideRail Contributors (https://fiderail.com)
3
+
4
+ This product includes open-source client execution guardrails, protocol
5
+ specifications, cryptographic verification primitives, SDKs, and MCP client
6
+ adapters developed by FideRail Contributors and licensed under the Apache
7
+ License, Version 2.0.
8
+
9
+ OPEN-CORE & TRADEMARK NOTICE:
10
+ 1. The Apache License, Version 2.0 applies solely to the open-source edge
11
+ software distributed in this repository and its published public SDK
12
+ packages. It does NOT grant any rights to proprietary FideRail Cloud
13
+ services, anti-sybil risk engines, or hosted datasets operated at
14
+ https://api.fiderail.com.
15
+ 2. Pursuant to Section 6 of the Apache License, Version 2.0, this distribution
16
+ does NOT grant permission to use the "FideRail" trade name, trademarks,
17
+ service marks, or logos to brand, market, or impersonate third-party or
18
+ modified products or services. See TRADEMARK.md for acceptable use and
19
+ attribution requirements.
package/README.md CHANGED
@@ -1,3 +1,43 @@
1
- # Temporary Holding Version
1
+ # @fiderail/cli
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
+ One-line, 100% non-custodial CLI for configuring FideRail MCP & anti-drain firewall skills across AI IDEs and agents (**Claude Code**, **Cursor**, **Windsurf**, **Codex**, **OpenClaw**), scaffolding seller `x402#2299` `onBeforeSettle` middleware, and querying FideRail Cloud (`https://api.fiderail.com`) from the terminal.
4
+
5
+ - **Zero third-party runtime dependencies** (Node.js `>= 22.13.0`, built on `@fiderail/spec` + `@fiderail/core`)
6
+ - **Zero custody**: never reads, generates, stores, or asks for wallet private keys or seed phrases
7
+ - **Safe & idempotent**: automatically backs up modified files (`.fiderail.bak.<timestamp>`) and preserves existing `mcpServers` entries and unrelated TOML tables
8
+
9
+ ## Quick Usage
10
+
11
+ ```bash
12
+ # Auto-detect installed AI IDEs & configure remote Streamable HTTP MCP + SKILL.md
13
+ npx -y @fiderail/cli install
14
+
15
+ # Target all supported IDEs (Claude Code, Cursor, Windsurf, Codex, OpenClaw) with local stdio MCP + SQLite WAL host caps
16
+ npx -y @fiderail/cli install --target all --mode stdio
17
+
18
+ # Preview exact file edits without writing anything
19
+ npx -y @fiderail/cli install --target all --dry-run --json
20
+
21
+ # Scaffold non-custodial x402 seller buyer-screening middleware (TS or Python)
22
+ npx -y @fiderail/cli seller-init --lang ts --chain base
23
+
24
+ # Live terminal checks & pre-flight queries
25
+ npx -y @fiderail/cli check
26
+ npx -y @fiderail/cli trust base 0x7284d41b5b852f2bd4c99bdf95043d84452d299c
27
+ npx -y @fiderail/cli preflight base 0x7284d41b5b852f2bd4c99bdf95043d84452d299c 0.05
28
+ npx -y @fiderail/cli services --chain base --limit 5
29
+ npx -y @fiderail/cli diagnose https://x402.clashofcoins.com/x402/cheap-health
30
+ ```
31
+
32
+ The identical CLI experience is also shipped in the zero-dependency Python package via `pipx run fiderail install` / `fiderail install`.
33
+
34
+ ## Links
35
+
36
+ - Portal & Live Grader: [https://fiderail.com](https://fiderail.com)
37
+ - Documentation: [https://fiderail.com/docs](https://fiderail.com/docs)
38
+ - Source (GitHub): [https://github.com/fiderail/fiderail](https://github.com/fiderail/fiderail)
39
+ - Mirror (GitLab): [https://gitlab.com/fiderail/fiderail](https://gitlab.com/fiderail/fiderail)
40
+
41
+ ## License
42
+
43
+ [`Apache-2.0`](./LICENSE) · [`NOTICE`](./NOTICE)
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=cli.d.ts.map
package/dist/cli.js ADDED
@@ -0,0 +1,324 @@
1
+ #!/usr/bin/env node
2
+ import { FIDERAIL_MANIFEST } from "@fiderail/spec";
3
+ import { createCliTrustClient, runInstall, runLiveCheck, runSellerInit, } from "./index.js";
4
+ const VALUE_FLAGS = new Set([
5
+ "target",
6
+ "mode",
7
+ "scope",
8
+ "dir",
9
+ "home",
10
+ "api-url",
11
+ "lang",
12
+ "out",
13
+ "chain",
14
+ "payee",
15
+ "min-score",
16
+ "max-single",
17
+ "max-daily",
18
+ "allow-unknown-max",
19
+ "spent-today",
20
+ "q",
21
+ "max-price",
22
+ "limit",
23
+ "method",
24
+ ]);
25
+ function parseArgs(argv) {
26
+ const flags = {};
27
+ const positionals = [];
28
+ for (let i = 0; i < argv.length; i += 1) {
29
+ const arg = argv[i];
30
+ if (arg === "-h") {
31
+ flags.help = true;
32
+ continue;
33
+ }
34
+ if (arg === "-v") {
35
+ flags.version = true;
36
+ continue;
37
+ }
38
+ if (arg.startsWith("--")) {
39
+ const eqIdx = arg.indexOf("=");
40
+ if (eqIdx !== -1) {
41
+ const key = arg.slice(2, eqIdx);
42
+ flags[key] = arg.slice(eqIdx + 1);
43
+ }
44
+ else {
45
+ const key = arg.slice(2);
46
+ if (VALUE_FLAGS.has(key)) {
47
+ const val = argv[i + 1];
48
+ if (val === undefined || val.startsWith("--")) {
49
+ throw new Error(`Missing value for flag --${key}`);
50
+ }
51
+ flags[key] = val;
52
+ i += 1;
53
+ }
54
+ else {
55
+ flags[key] = true;
56
+ }
57
+ }
58
+ continue;
59
+ }
60
+ positionals.push(arg);
61
+ }
62
+ return { flags, positionals };
63
+ }
64
+ function getStringFlag(flags, key) {
65
+ const v = flags[key];
66
+ return typeof v === "string" ? v : undefined;
67
+ }
68
+ function getNumberFlag(flags, key) {
69
+ const v = getStringFlag(flags, key);
70
+ if (v === undefined)
71
+ return undefined;
72
+ const n = Number(v);
73
+ if (!Number.isFinite(n)) {
74
+ throw new Error(`Flag --${key} must be a finite number (received "${v}").`);
75
+ }
76
+ return n;
77
+ }
78
+ function printHelp() {
79
+ const version = FIDERAIL_MANIFEST.project.currentRelease;
80
+ const lines = [
81
+ `fiderail v${version} — Non-custodial FideRail setup, seller starter & live trust CLI`,
82
+ "",
83
+ "Usage:",
84
+ " fiderail install [options] Configure AI IDE MCP + anti-drain SKILL.md (alias: init)",
85
+ " fiderail seller-init [options] Generate non-custodial x402 before-settle starter",
86
+ " fiderail check [--api-url URL] Verify /healthz + remote MCP tools/list (alias: health)",
87
+ " fiderail trust <chain> <address> Fetch anti-sybil trust-v2 profile",
88
+ " fiderail preflight <chain> <addr> <amount> Run pre-flight payment firewall evaluation",
89
+ " fiderail services [options] Search audited x402 services directory",
90
+ " fiderail diagnose <url> [--method GET|POST] Grade x402 endpoint A-F (free)",
91
+ " fiderail --version | --help Show version or this help",
92
+ "",
93
+ "install options:",
94
+ " --target <claude|cursor|windsurf|codex|openclaw|all|auto> (default: auto)",
95
+ " --mode <remote|stdio> remote uses api.fiderail.com/mcp; stdio uses @fiderail/mcp (default: remote)",
96
+ " --scope <project|user> Write into current project or user home config (default: project)",
97
+ " --dir <path> Project root directory (default: cwd)",
98
+ " --home <path> User home override (for testing/CI)",
99
+ " --api-url <url> Override API base URL (default: https://api.fiderail.com)",
100
+ " --dry-run Preview planned changes without writing files",
101
+ " --no-skill Skip writing SKILL.md firewall instructions",
102
+ " --json Print structured JSON output",
103
+ "",
104
+ "seller-init options:",
105
+ " --lang <ts|py> Starter language (default: ts)",
106
+ " --chain <base|solana|arbitrum|polygon> Target settlement chain (default: base)",
107
+ " --payee <address> Optional payee wallet address comment hint",
108
+ " --out <path> Output file path",
109
+ " --dir <path> Working directory (default: cwd)",
110
+ " --force Overwrite an existing modified file (creates backup)",
111
+ " --dry-run --json Preview / JSON output",
112
+ "",
113
+ "Non-custodial guarantee: fiderail never asks for, reads, or stores private keys or seed phrases.",
114
+ "",
115
+ ];
116
+ process.stdout.write(lines.join("\n"));
117
+ }
118
+ function formatInstallText(res) {
119
+ const lines = [
120
+ `FideRail v${res.cliVersion} (${res.dryRun ? "dry-run" : "applied"})`,
121
+ `Mode: ${res.mode} · Scope: ${res.scope} · API: ${res.apiUrl} · Non-custodial: yes (zero private keys touched)`,
122
+ `Targets (${res.autoDetected ? "auto-detected" : "selected"}): ${res.targets.join(", ")}`,
123
+ "",
124
+ ];
125
+ for (const act of res.actions) {
126
+ const tag = act.status.toUpperCase().padEnd(9, " ");
127
+ const backup = act.backupPath ? ` (backup: ${act.backupPath})` : "";
128
+ lines.push(` [${tag}] ${act.kind}: ${act.path}${backup}`);
129
+ }
130
+ lines.push("");
131
+ return lines.join("\n");
132
+ }
133
+ function formatSellerText(res) {
134
+ const lines = [
135
+ `FideRail v${res.cliVersion} seller-init (${res.dryRun ? "dry-run" : "applied"})`,
136
+ `Language: ${res.lang} · Chain: ${res.chain} · API: ${res.apiUrl} · Non-custodial: yes`,
137
+ ` [${res.action.status.toUpperCase()}] ${res.action.path}${res.action.backupPath ? ` (backup: ${res.action.backupPath})` : ""}`,
138
+ "",
139
+ ];
140
+ return lines.join("\n");
141
+ }
142
+ async function main() {
143
+ const { flags, positionals } = parseArgs(process.argv.slice(2));
144
+ const version = FIDERAIL_MANIFEST.project.currentRelease;
145
+ if (flags.version && positionals.length === 0) {
146
+ process.stdout.write(`fiderail v${version}\n`);
147
+ return;
148
+ }
149
+ if (flags.help || positionals.length === 0) {
150
+ printHelp();
151
+ return;
152
+ }
153
+ const cmd = positionals[0].toLowerCase();
154
+ const asJson = Boolean(flags.json);
155
+ const apiUrl = getStringFlag(flags, "api-url");
156
+ if (cmd === "install" || cmd === "init") {
157
+ const modeRaw = (getStringFlag(flags, "mode") || "remote").toLowerCase();
158
+ if (modeRaw !== "remote" && modeRaw !== "stdio") {
159
+ throw new Error(`Invalid --mode "${modeRaw}". Expected "remote" or "stdio".`);
160
+ }
161
+ const scopeRaw = (getStringFlag(flags, "scope") || "project").toLowerCase();
162
+ if (scopeRaw !== "project" && scopeRaw !== "user") {
163
+ throw new Error(`Invalid --scope "${scopeRaw}". Expected "project" or "user".`);
164
+ }
165
+ const res = runInstall({
166
+ target: getStringFlag(flags, "target"),
167
+ mode: modeRaw,
168
+ scope: scopeRaw,
169
+ dir: getStringFlag(flags, "dir"),
170
+ home: getStringFlag(flags, "home"),
171
+ apiUrl,
172
+ dryRun: Boolean(flags["dry-run"]),
173
+ installSkill: !Boolean(flags["no-skill"]),
174
+ });
175
+ process.stdout.write(asJson ? JSON.stringify(res, null, 2) + "\n" : formatInstallText(res));
176
+ return;
177
+ }
178
+ if (cmd === "seller-init") {
179
+ const langRaw = (getStringFlag(flags, "lang") || "ts").toLowerCase();
180
+ if (langRaw !== "ts" && langRaw !== "py") {
181
+ throw new Error(`Invalid --lang "${langRaw}". Expected "ts" or "py".`);
182
+ }
183
+ const res = runSellerInit({
184
+ lang: langRaw,
185
+ out: getStringFlag(flags, "out"),
186
+ dir: getStringFlag(flags, "dir"),
187
+ chain: getStringFlag(flags, "chain"),
188
+ payee: getStringFlag(flags, "payee"),
189
+ apiUrl,
190
+ dryRun: Boolean(flags["dry-run"]),
191
+ force: Boolean(flags.force),
192
+ });
193
+ process.stdout.write(asJson ? JSON.stringify(res, null, 2) + "\n" : formatSellerText(res));
194
+ return;
195
+ }
196
+ if (cmd === "check" || cmd === "health") {
197
+ const res = await runLiveCheck(apiUrl);
198
+ if (asJson) {
199
+ process.stdout.write(JSON.stringify(res, null, 2) + "\n");
200
+ }
201
+ else {
202
+ process.stdout.write([
203
+ `FideRail Cloud OK · ${res.apiUrl}`,
204
+ ` Server: v${res.serverVersion ?? "unknown"} · Storage: ${res.storageMode ?? "unknown"} · HTTP 402 overage: $${res.priceUsdc ?? "?"} USDC`,
205
+ ` Ed25519 stateRoot signing: ${res.stateRootSigningEnabled} · Remote MCP tools: ${res.mcpToolCount} · Chains: ${res.indexerChains.join(", ")}`,
206
+ "",
207
+ ].join("\n"));
208
+ }
209
+ return;
210
+ }
211
+ const client = createCliTrustClient(apiUrl);
212
+ try {
213
+ if (cmd === "trust") {
214
+ const [, chain, address] = positionals;
215
+ if (!chain || !address) {
216
+ throw new Error("Usage: fiderail trust <chain> <address> [--api-url URL] [--json]");
217
+ }
218
+ const profile = await client.getAgentTrust(chain, address);
219
+ if (asJson) {
220
+ process.stdout.write(JSON.stringify(profile, null, 2) + "\n");
221
+ }
222
+ else {
223
+ process.stdout.write([
224
+ `${profile.chain}:${profile.address}`,
225
+ ` Found: ${profile.found} · Score: ${profile.creditScore ?? "N/A"} · Tier: ${profile.tier} · Risk: ${profile.riskLevel} · Confidence: ${profile.confidenceLevel} (${profile.confidence})`,
226
+ ` Flags: ${(profile.riskFlags || []).length > 0 ? profile.riskFlags.join(", ") : "none"}`,
227
+ "",
228
+ ].join("\n"));
229
+ }
230
+ return;
231
+ }
232
+ if (cmd === "preflight") {
233
+ const [, chain, counterparty, amountStr] = positionals;
234
+ if (!chain || !counterparty || !amountStr) {
235
+ throw new Error("Usage: fiderail preflight <chain> <counterparty> <amountUsdc> [--min-score N] [--max-single N] [--max-daily N] [--allow-unknown-max N] [--json]");
236
+ }
237
+ const amountUsdc = Number(amountStr);
238
+ const policy = {};
239
+ const minScore = getNumberFlag(flags, "min-score");
240
+ const maxSingle = getNumberFlag(flags, "max-single");
241
+ const maxDaily = getNumberFlag(flags, "max-daily");
242
+ const allowUnknownMax = getNumberFlag(flags, "allow-unknown-max");
243
+ const spentToday = getNumberFlag(flags, "spent-today") ?? 0;
244
+ if (minScore !== undefined)
245
+ policy.minTrustScore = minScore;
246
+ if (maxSingle !== undefined)
247
+ policy.maxSingleTxUsdc = maxSingle;
248
+ if (maxDaily !== undefined)
249
+ policy.maxDailyUsdc = maxDaily;
250
+ if (allowUnknownMax !== undefined)
251
+ policy.allowUnknownMaxUsdc = allowUnknownMax;
252
+ const verdict = await client.preflightPaymentGuard({
253
+ chain,
254
+ counterparty,
255
+ amountUsdc,
256
+ spentTodayUsdc: spentToday,
257
+ policy,
258
+ });
259
+ if (asJson) {
260
+ process.stdout.write(JSON.stringify(verdict, null, 2) + "\n");
261
+ }
262
+ else {
263
+ process.stdout.write([
264
+ `Decision: ${verdict.decision} · ${verdict.chain}:${verdict.counterparty} ($${verdict.amountUsdc} ${verdict.assetSymbol})`,
265
+ ` Reasons: ${verdict.reasons.join(" | ")}`,
266
+ ` Counterparty Score: ${verdict.trustProfile?.creditScore ?? "N/A"} (${verdict.trustProfile?.tier ?? "UNVERIFIED"}) · Remaining Daily Budget: $${verdict.remainingDailyBudgetUsdc}`,
267
+ "",
268
+ ].join("\n"));
269
+ }
270
+ return;
271
+ }
272
+ if (cmd === "services") {
273
+ const svcs = await client.discoverTrustedServices({
274
+ chain: getStringFlag(flags, "chain") || "all",
275
+ query: getStringFlag(flags, "q") || "",
276
+ maxPriceUsdc: getNumberFlag(flags, "max-price"),
277
+ minTrustScore: getNumberFlag(flags, "min-score") ?? 0,
278
+ excludeFlagged: !Boolean(flags["include-flagged"]),
279
+ limit: getNumberFlag(flags, "limit") ?? 10,
280
+ });
281
+ if (asJson) {
282
+ process.stdout.write(JSON.stringify(svcs, null, 2) + "\n");
283
+ }
284
+ else {
285
+ const items = Array.isArray(svcs.services) ? svcs.services : [];
286
+ process.stdout.write(`Found ${svcs.totalMatched ?? items.length} matched x402 services (showing ${items.length}):\n`);
287
+ for (const s of items) {
288
+ process.stdout.write(` - [${s.chain}] score=${s.trustScore ?? "N/A"} $${s.priceUsdc ?? "?"} ${s.name || s.resourceUrl} -> ${s.resourceUrl}\n`);
289
+ }
290
+ }
291
+ return;
292
+ }
293
+ if (cmd === "diagnose") {
294
+ const [, url] = positionals;
295
+ if (!url) {
296
+ throw new Error("Usage: fiderail diagnose <url> [--method GET|POST] [--api-url URL] [--json]");
297
+ }
298
+ const methodRaw = (getStringFlag(flags, "method") || "GET").toUpperCase();
299
+ if (methodRaw !== "GET" && methodRaw !== "POST") {
300
+ throw new Error(`Invalid --method "${methodRaw}". Expected "GET" or "POST".`);
301
+ }
302
+ if (!client.diagnoseEndpoint) {
303
+ throw new Error("Remote diagnoseEndpoint is unavailable on this trust client.");
304
+ }
305
+ const diag = await client.diagnoseEndpoint({ url, method: methodRaw });
306
+ if (asJson) {
307
+ process.stdout.write(JSON.stringify(diag, null, 2) + "\n");
308
+ }
309
+ else {
310
+ process.stdout.write(`Grade: ${diag.grade ?? "N/A"} · ${diag.url ?? url} · Compliant 402: ${diag.compliant402 ?? "unknown"} · Header bytes: ${diag.headerBytes ?? "N/A"}\n`);
311
+ }
312
+ return;
313
+ }
314
+ throw new Error(`Unknown command "${cmd}". Run "fiderail --help" for usage.`);
315
+ }
316
+ finally {
317
+ await client.close();
318
+ }
319
+ }
320
+ main().catch((err) => {
321
+ process.stderr.write(`fiderail error: ${err?.message || String(err)}\n`);
322
+ process.exit(1);
323
+ });
324
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1,82 @@
1
+ import { type ChainKey } from "@fiderail/spec";
2
+ export type CliIdeTarget = "claude" | "cursor" | "windsurf" | "codex" | "openclaw";
3
+ export type CliInstallTargetInput = CliIdeTarget | "all" | "auto";
4
+ export type CliInstallMode = "remote" | "stdio";
5
+ export type CliInstallScope = "project" | "user";
6
+ export type CliSellerLang = "ts" | "py";
7
+ export declare const SUPPORTED_IDE_TARGETS: readonly CliIdeTarget[];
8
+ export declare const CANONICAL_PAYMENT_FIREWALL_SKILL = "---\nname: fiderail-payment-firewall\ndescription: Non-custodial pre-flight payment risk check, anti-sybil counterparty audit, and free x402 endpoint grader via FideRail MCP (Base, Solana, Arbitrum, Polygon).\n---\n\n# FideRail Pre-Flight Payment Safety Skill\n\nUse FideRail's MCP tools **before** authorizing any autonomous AI Agent stablecoin payment (x402, MCP-Pay, A2A, or delegated session key) across Base, Solana, Arbitrum, or Polygon:\n\n1. **Pre-Flight Check First**: Always call `preflight_payment_guard` (or `check_agent_trust`) with the counterparty `chain`, `address`, and `amountUsdc` before signing any payment.\n - If the verdict is **`BLOCK`** (e.g. `RECIPROCAL_LOOP_DETECTED`, `ISOLATED_PAYER_FARM_ABOVE_CAP`, `SINGLE_PAYER_CONCENTRATED_ABOVE_CAP`, or budget cap exceeded), abort payment immediately.\n - If the verdict is **`WARN`** (e.g. `BEHAVIOR_DRIFT_DETECTED`, `NON_X402_WHALE_FLOW`, or `UNKNOWN_COUNTERPARTY_MICRO_ALLOWED`), verify the endpoint and respect micro caps.\n2. **Grade New x402 Endpoints Free**: Call `diagnose_x402_endpoint` before integrating a new paid HTTP API to check HTTP 402 compliance, 8 KB aiohttp / 16 KB Node header safety (`x402#3803`), and price drift.\n3. **Discover Verified Services**: Use `discover_trusted_services` with `excludeFlagged: true` to find live, audited x402 services ranked by `trust-v2` score and L1/L2 liveness.\n4. **Never Bypass Host Policy**: Respect immutable host-clamped limits (`maxSingleTxUsdc`, `maxDailyUsdc`, `allowedAssets`) and never transmit API keys, private keys, or PII in outbound requests.\n";
9
+ export interface PlannedFileAction {
10
+ kind: "mcp_config" | "skill" | "seller_starter";
11
+ target?: CliIdeTarget;
12
+ path: string;
13
+ status: "created" | "updated" | "unchanged";
14
+ backupPath: string | null;
15
+ }
16
+ export interface InstallOptions {
17
+ target?: string;
18
+ mode?: CliInstallMode;
19
+ scope?: CliInstallScope;
20
+ dir?: string;
21
+ home?: string;
22
+ apiUrl?: string;
23
+ dryRun?: boolean;
24
+ installSkill?: boolean;
25
+ }
26
+ export interface InstallResult {
27
+ ok: true;
28
+ cliVersion: string;
29
+ nonCustodial: true;
30
+ privateKeysTouched: false;
31
+ mode: CliInstallMode;
32
+ scope: CliInstallScope;
33
+ apiUrl: string;
34
+ dryRun: boolean;
35
+ autoDetected: boolean;
36
+ targets: CliIdeTarget[];
37
+ actions: PlannedFileAction[];
38
+ }
39
+ export interface SellerInitOptions {
40
+ lang?: CliSellerLang;
41
+ out?: string;
42
+ dir?: string;
43
+ chain?: string;
44
+ payee?: string;
45
+ apiUrl?: string;
46
+ dryRun?: boolean;
47
+ force?: boolean;
48
+ }
49
+ export interface SellerInitResult {
50
+ ok: true;
51
+ cliVersion: string;
52
+ nonCustodial: true;
53
+ privateKeysTouched: false;
54
+ lang: CliSellerLang;
55
+ chain: ChainKey;
56
+ payee: string | null;
57
+ apiUrl: string;
58
+ dryRun: boolean;
59
+ action: PlannedFileAction;
60
+ }
61
+ export interface LiveCheckResult {
62
+ ok: boolean;
63
+ cliVersion: string;
64
+ apiUrl: string;
65
+ serverStatus: string;
66
+ serverVersion: string | null;
67
+ priceUsdc: number | null;
68
+ storageMode: string | null;
69
+ stateRootSigningEnabled: boolean;
70
+ mcpToolCount: number;
71
+ indexerChains: string[];
72
+ }
73
+ export declare function detectInstalledTargets(dir: string, home: string): CliIdeTarget[];
74
+ export declare function resolveInstallTargets(targetInput: string | undefined, dir: string, home: string): {
75
+ targets: CliIdeTarget[];
76
+ autoDetected: boolean;
77
+ };
78
+ export declare function runInstall(options?: InstallOptions): InstallResult;
79
+ export declare function runSellerInit(options?: SellerInitOptions): SellerInitResult;
80
+ export declare function runLiveCheck(apiUrlInput?: string): Promise<LiveCheckResult>;
81
+ export declare function createCliTrustClient(apiUrlInput?: string): import("@fiderail/core").TrustEngine;
82
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,594 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { FIDERAIL_MANIFEST, isValidAddress, normalizeChainAddress, normalizeChainName, } from "@fiderail/spec";
5
+ import { createRemoteTrustClient } from "@fiderail/core";
6
+ export const SUPPORTED_IDE_TARGETS = [
7
+ "claude",
8
+ "cursor",
9
+ "windsurf",
10
+ "codex",
11
+ "openclaw",
12
+ ];
13
+ export const CANONICAL_PAYMENT_FIREWALL_SKILL = `---
14
+ name: fiderail-payment-firewall
15
+ description: Non-custodial pre-flight payment risk check, anti-sybil counterparty audit, and free x402 endpoint grader via FideRail MCP (Base, Solana, Arbitrum, Polygon).
16
+ ---
17
+
18
+ # FideRail Pre-Flight Payment Safety Skill
19
+
20
+ Use FideRail's MCP tools **before** authorizing any autonomous AI Agent stablecoin payment (x402, MCP-Pay, A2A, or delegated session key) across Base, Solana, Arbitrum, or Polygon:
21
+
22
+ 1. **Pre-Flight Check First**: Always call \`preflight_payment_guard\` (or \`check_agent_trust\`) with the counterparty \`chain\`, \`address\`, and \`amountUsdc\` before signing any payment.
23
+ - If the verdict is **\`BLOCK\`** (e.g. \`RECIPROCAL_LOOP_DETECTED\`, \`ISOLATED_PAYER_FARM_ABOVE_CAP\`, \`SINGLE_PAYER_CONCENTRATED_ABOVE_CAP\`, or budget cap exceeded), abort payment immediately.
24
+ - If the verdict is **\`WARN\`** (e.g. \`BEHAVIOR_DRIFT_DETECTED\`, \`NON_X402_WHALE_FLOW\`, or \`UNKNOWN_COUNTERPARTY_MICRO_ALLOWED\`), verify the endpoint and respect micro caps.
25
+ 2. **Grade New x402 Endpoints Free**: Call \`diagnose_x402_endpoint\` before integrating a new paid HTTP API to check HTTP 402 compliance, 8 KB aiohttp / 16 KB Node header safety (\`x402#3803\`), and price drift.
26
+ 3. **Discover Verified Services**: Use \`discover_trusted_services\` with \`excludeFlagged: true\` to find live, audited x402 services ranked by \`trust-v2\` score and L1/L2 liveness.
27
+ 4. **Never Bypass Host Policy**: Respect immutable host-clamped limits (\`maxSingleTxUsdc\`, \`maxDailyUsdc\`, \`allowedAssets\`) and never transmit API keys, private keys, or PII in outbound requests.
28
+ `;
29
+ function normalizeApiUrl(input) {
30
+ const raw = (input || process.env.FIDERAIL_API_URL || FIDERAIL_MANIFEST.project.apiBaseUrl).trim();
31
+ const clean = raw.replace(/\/+$/, "");
32
+ let parsed;
33
+ try {
34
+ parsed = new URL(clean);
35
+ }
36
+ catch {
37
+ throw new Error(`Invalid --api-url: "${raw}". Expected http(s) URL.`);
38
+ }
39
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
40
+ throw new Error(`Unsupported protocol in --api-url: "${parsed.protocol}". Expected http: or https:.`);
41
+ }
42
+ return clean;
43
+ }
44
+ function makeBackupStamp(now = new Date()) {
45
+ return now.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
46
+ }
47
+ function uniqueBackupPath(filePath) {
48
+ const stamp = makeBackupStamp();
49
+ const base = `${filePath}.fiderail.bak.${stamp}`;
50
+ if (!fs.existsSync(base))
51
+ return base;
52
+ let seq = 1;
53
+ while (fs.existsSync(`${base}.${seq}`)) {
54
+ seq += 1;
55
+ }
56
+ return `${base}.${seq}`;
57
+ }
58
+ export function detectInstalledTargets(dir, home) {
59
+ const detected = [];
60
+ if (fs.existsSync(path.join(dir, ".claude")) ||
61
+ fs.existsSync(path.join(dir, ".mcp.json")) ||
62
+ fs.existsSync(path.join(home, ".claude.json")) ||
63
+ fs.existsSync(path.join(home, ".claude"))) {
64
+ detected.push("claude");
65
+ }
66
+ if (fs.existsSync(path.join(dir, ".cursor")) || fs.existsSync(path.join(home, ".cursor"))) {
67
+ detected.push("cursor");
68
+ }
69
+ if (fs.existsSync(path.join(dir, ".windsurf")) ||
70
+ fs.existsSync(path.join(home, ".codeium", "windsurf"))) {
71
+ detected.push("windsurf");
72
+ }
73
+ if (fs.existsSync(path.join(dir, ".codex")) || fs.existsSync(path.join(home, ".codex"))) {
74
+ detected.push("codex");
75
+ }
76
+ if (fs.existsSync(path.join(dir, ".openclaw")) || fs.existsSync(path.join(home, ".openclaw"))) {
77
+ detected.push("openclaw");
78
+ }
79
+ return detected;
80
+ }
81
+ export function resolveInstallTargets(targetInput, dir, home) {
82
+ const raw = String(targetInput || "auto").trim().toLowerCase();
83
+ if (!raw || raw === "auto") {
84
+ const found = detectInstalledTargets(dir, home);
85
+ return {
86
+ targets: found.length > 0 ? found : ["claude", "cursor"],
87
+ autoDetected: true,
88
+ };
89
+ }
90
+ if (raw === "all") {
91
+ return { targets: [...SUPPORTED_IDE_TARGETS], autoDetected: false };
92
+ }
93
+ const parts = raw
94
+ .split(",")
95
+ .map((p) => p.trim())
96
+ .filter(Boolean);
97
+ if (parts.length === 0) {
98
+ throw new Error(`Invalid --target value: "${targetInput}".`);
99
+ }
100
+ const out = [];
101
+ for (const part of parts) {
102
+ if (!SUPPORTED_IDE_TARGETS.includes(part)) {
103
+ throw new Error(`Unsupported --target "${part}". Expected claude, cursor, windsurf, codex, openclaw, all, or auto.`);
104
+ }
105
+ if (!out.includes(part)) {
106
+ out.push(part);
107
+ }
108
+ }
109
+ return { targets: out, autoDetected: false };
110
+ }
111
+ function getTargetPaths(target, scope, dir, home) {
112
+ if (target === "claude") {
113
+ return scope === "project"
114
+ ? {
115
+ configPath: path.join(dir, ".mcp.json"),
116
+ format: "json",
117
+ skillPath: path.join(dir, ".claude", "skills", "fiderail-payment-firewall", "SKILL.md"),
118
+ }
119
+ : {
120
+ configPath: path.join(home, ".claude.json"),
121
+ format: "json",
122
+ skillPath: path.join(home, ".claude", "skills", "fiderail-payment-firewall", "SKILL.md"),
123
+ };
124
+ }
125
+ if (target === "cursor") {
126
+ return scope === "project"
127
+ ? {
128
+ configPath: path.join(dir, ".cursor", "mcp.json"),
129
+ format: "json",
130
+ skillPath: path.join(dir, ".agents", "skills", "fiderail-payment-firewall", "SKILL.md"),
131
+ }
132
+ : {
133
+ configPath: path.join(home, ".cursor", "mcp.json"),
134
+ format: "json",
135
+ skillPath: path.join(home, ".cursor", "skills", "fiderail-payment-firewall", "SKILL.md"),
136
+ };
137
+ }
138
+ if (target === "windsurf") {
139
+ return scope === "project"
140
+ ? {
141
+ configPath: path.join(dir, ".windsurf", "mcp.json"),
142
+ format: "json",
143
+ skillPath: path.join(dir, ".agents", "skills", "fiderail-payment-firewall", "SKILL.md"),
144
+ }
145
+ : {
146
+ configPath: path.join(home, ".codeium", "windsurf", "mcp_config.json"),
147
+ format: "json",
148
+ skillPath: path.join(home, ".codeium", "windsurf", "skills", "fiderail-payment-firewall", "SKILL.md"),
149
+ };
150
+ }
151
+ if (target === "codex") {
152
+ return scope === "project"
153
+ ? {
154
+ configPath: path.join(dir, ".codex", "config.toml"),
155
+ format: "toml",
156
+ skillPath: path.join(dir, ".agents", "skills", "fiderail-payment-firewall", "SKILL.md"),
157
+ }
158
+ : {
159
+ configPath: path.join(home, ".codex", "config.toml"),
160
+ format: "toml",
161
+ skillPath: path.join(home, ".agents", "skills", "fiderail-payment-firewall", "SKILL.md"),
162
+ };
163
+ }
164
+ return scope === "project"
165
+ ? {
166
+ configPath: path.join(dir, ".openclaw", "mcp.json"),
167
+ format: "json",
168
+ skillPath: path.join(dir, ".agents", "skills", "fiderail-payment-firewall", "SKILL.md"),
169
+ }
170
+ : {
171
+ configPath: path.join(home, ".openclaw", "mcp.json"),
172
+ format: "json",
173
+ skillPath: path.join(home, ".openclaw", "skills", "fiderail-payment-firewall", "SKILL.md"),
174
+ };
175
+ }
176
+ function buildJsonServerEntry(target, mode, apiUrl) {
177
+ if (mode === "stdio") {
178
+ return {
179
+ command: "npx",
180
+ args: ["-y", "@fiderail/mcp"],
181
+ env: {
182
+ FIDERAIL_API_URL: apiUrl,
183
+ FIDERAIL_OUTAGE_POLICY: "fail-closed",
184
+ FIDERAIL_SPEND_LEDGER_PATH: "./edge-ledger.db",
185
+ FIDERAIL_HOST_MAX_SINGLE_USDC: "1.0",
186
+ FIDERAIL_HOST_MAX_DAILY_USDC: "10.0",
187
+ FIDERAIL_HOST_MIN_TRUST_SCORE: "40",
188
+ FIDERAIL_HOST_ALLOWED_ASSETS: "USDC",
189
+ },
190
+ };
191
+ }
192
+ if (target === "claude") {
193
+ return {
194
+ type: "http",
195
+ url: `${apiUrl}/mcp`,
196
+ };
197
+ }
198
+ return {
199
+ url: `${apiUrl}/mcp`,
200
+ transport: "streamable-http",
201
+ };
202
+ }
203
+ function escapeTomlString(value) {
204
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
205
+ }
206
+ function buildCodexTomlBlock(mode, apiUrl) {
207
+ const escapedUrl = escapeTomlString(apiUrl);
208
+ if (mode === "stdio") {
209
+ return [
210
+ "[mcp_servers.fiderail]",
211
+ 'command = "npx"',
212
+ 'args = ["-y", "@fiderail/mcp"]',
213
+ "",
214
+ "[mcp_servers.fiderail.env]",
215
+ `FIDERAIL_API_URL = "${escapedUrl}"`,
216
+ 'FIDERAIL_OUTAGE_POLICY = "fail-closed"',
217
+ 'FIDERAIL_SPEND_LEDGER_PATH = "./edge-ledger.db"',
218
+ 'FIDERAIL_HOST_MAX_SINGLE_USDC = "1.0"',
219
+ 'FIDERAIL_HOST_MAX_DAILY_USDC = "10.0"',
220
+ 'FIDERAIL_HOST_MIN_TRUST_SCORE = "40"',
221
+ 'FIDERAIL_HOST_ALLOWED_ASSETS = "USDC"',
222
+ "",
223
+ ].join("\n");
224
+ }
225
+ return `[mcp_servers.fiderail]\nurl = "${escapedUrl}/mcp"\n`;
226
+ }
227
+ function mergeJsonConfig(existingContent, filePath, target, mode, apiUrl) {
228
+ let parsed = {};
229
+ if (existingContent !== null && existingContent.trim() !== "") {
230
+ let rawParsed;
231
+ try {
232
+ rawParsed = JSON.parse(existingContent);
233
+ }
234
+ catch (err) {
235
+ throw new Error(`Refusing to overwrite malformed JSON in ${filePath}: ${err?.message || "parse failed"}`);
236
+ }
237
+ if (!rawParsed || typeof rawParsed !== "object" || Array.isArray(rawParsed)) {
238
+ throw new Error(`Expected top-level JSON object in ${filePath}`);
239
+ }
240
+ parsed = rawParsed;
241
+ }
242
+ if (parsed.mcpServers !== undefined &&
243
+ (parsed.mcpServers === null || typeof parsed.mcpServers !== "object" || Array.isArray(parsed.mcpServers))) {
244
+ throw new Error(`Expected "mcpServers" to be a JSON object in ${filePath}`);
245
+ }
246
+ const nextDoc = {
247
+ ...parsed,
248
+ mcpServers: {
249
+ ...(parsed.mcpServers || {}),
250
+ fiderail: buildJsonServerEntry(target, mode, apiUrl),
251
+ },
252
+ };
253
+ return JSON.stringify(nextDoc, null, 2) + "\n";
254
+ }
255
+ function mergeTomlConfig(existingContent, mode, apiUrl) {
256
+ const block = buildCodexTomlBlock(mode, apiUrl);
257
+ if (existingContent === null || existingContent.trim() === "") {
258
+ return block;
259
+ }
260
+ const normalized = existingContent.replace(/\r\n/g, "\n");
261
+ const lines = normalized.split("\n");
262
+ const kept = [];
263
+ let skipping = false;
264
+ for (const line of lines) {
265
+ const tableMatch = /^\s*\[([^\[\]]+)\]\s*(?:#.*)?$/.exec(line);
266
+ if (tableMatch) {
267
+ const tableName = tableMatch[1].trim();
268
+ if (tableName === "mcp_servers.fiderail" || tableName.startsWith("mcp_servers.fiderail.")) {
269
+ skipping = true;
270
+ continue;
271
+ }
272
+ skipping = false;
273
+ }
274
+ if (!skipping) {
275
+ kept.push(line);
276
+ }
277
+ }
278
+ while (kept.length > 0 && kept[kept.length - 1].trim() === "") {
279
+ kept.pop();
280
+ }
281
+ if (kept.length === 0) {
282
+ return block;
283
+ }
284
+ return `${kept.join("\n")}\n\n${block}`;
285
+ }
286
+ export function runInstall(options = {}) {
287
+ const mode = options.mode === "stdio" ? "stdio" : "remote";
288
+ const scope = options.scope === "user" ? "user" : "project";
289
+ const dir = path.resolve(options.dir || process.cwd());
290
+ const home = path.resolve(options.home || os.homedir());
291
+ const apiUrl = normalizeApiUrl(options.apiUrl);
292
+ const dryRun = Boolean(options.dryRun);
293
+ const installSkill = options.installSkill !== false;
294
+ const { targets, autoDetected } = resolveInstallTargets(options.target, dir, home);
295
+ const pendingWrites = [];
296
+ const seenSkillPaths = new Set();
297
+ for (const target of targets) {
298
+ const paths = getTargetPaths(target, scope, dir, home);
299
+ const configAbs = path.resolve(paths.configPath);
300
+ const existingCfg = fs.existsSync(configAbs) ? fs.readFileSync(configAbs, "utf8") : null;
301
+ const nextCfg = paths.format === "toml"
302
+ ? mergeTomlConfig(existingCfg, mode, apiUrl)
303
+ : mergeJsonConfig(existingCfg, configAbs, target, mode, apiUrl);
304
+ pendingWrites.push({
305
+ kind: "mcp_config",
306
+ target,
307
+ absPath: configAbs,
308
+ existingContent: existingCfg,
309
+ nextContent: nextCfg,
310
+ });
311
+ if (installSkill) {
312
+ const skillAbs = path.resolve(paths.skillPath);
313
+ if (!seenSkillPaths.has(skillAbs)) {
314
+ seenSkillPaths.add(skillAbs);
315
+ const existingSkill = fs.existsSync(skillAbs) ? fs.readFileSync(skillAbs, "utf8") : null;
316
+ pendingWrites.push({
317
+ kind: "skill",
318
+ target,
319
+ absPath: skillAbs,
320
+ existingContent: existingSkill,
321
+ nextContent: CANONICAL_PAYMENT_FIREWALL_SKILL,
322
+ });
323
+ }
324
+ }
325
+ }
326
+ const actions = [];
327
+ for (const w of pendingWrites) {
328
+ if (w.existingContent === w.nextContent) {
329
+ actions.push({
330
+ kind: w.kind,
331
+ target: w.target,
332
+ path: w.absPath,
333
+ status: "unchanged",
334
+ backupPath: null,
335
+ });
336
+ continue;
337
+ }
338
+ const status = w.existingContent === null ? "created" : "updated";
339
+ let backupPath = null;
340
+ if (!dryRun) {
341
+ fs.mkdirSync(path.dirname(w.absPath), { recursive: true });
342
+ if (w.existingContent !== null) {
343
+ backupPath = uniqueBackupPath(w.absPath);
344
+ fs.writeFileSync(backupPath, w.existingContent, "utf8");
345
+ }
346
+ fs.writeFileSync(w.absPath, w.nextContent, "utf8");
347
+ }
348
+ actions.push({
349
+ kind: w.kind,
350
+ target: w.target,
351
+ path: w.absPath,
352
+ status,
353
+ backupPath,
354
+ });
355
+ }
356
+ return {
357
+ ok: true,
358
+ cliVersion: FIDERAIL_MANIFEST.project.currentRelease,
359
+ nonCustodial: true,
360
+ privateKeysTouched: false,
361
+ mode,
362
+ scope,
363
+ apiUrl,
364
+ dryRun,
365
+ autoDetected,
366
+ targets,
367
+ actions,
368
+ };
369
+ }
370
+ function buildSellerStarterTs(chain, payee, apiUrl) {
371
+ const payeeHint = payee || "0xYOUR_SELLER_WALLET_OR_X402_PAYTO";
372
+ return `// Non-custodial FideRail x402#2299 seller buyer-screening starter (zero third-party deps)
373
+ // Target chain: ${chain} | Example payTo: ${payeeHint}
374
+ import http from "node:http";
375
+
376
+ const API_BASE = (process.env.FIDERAIL_API_URL || "${apiUrl}").replace(/\\/+$/, "");
377
+
378
+ /**
379
+ * Screens an incoming buyer wallet before settlement via FideRail Cloud
380
+ * (\`POST /v1/trust-provider/before-settle\`), evaluating both payee profiles
381
+ * and pure-payer outgoing activity across Base, Solana, Arbitrum, and Polygon.
382
+ */
383
+ export async function screenBuyerBeforeSettle({ payer, amountUsdc = 0.05, chain = "${chain}" }) {
384
+ const res = await fetch(\`\${API_BASE}/v1/trust-provider/before-settle\`, {
385
+ method: "POST",
386
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
387
+ body: JSON.stringify({ chain, payer, amountUsdc }),
388
+ signal: AbortSignal.timeout(6000),
389
+ });
390
+ if (!res.ok) {
391
+ throw new Error(\`FideRail before-settle check failed (HTTP \${res.status})\`);
392
+ }
393
+ return res.json();
394
+ }
395
+
396
+ // Optional full HTTP 402 resource server middleware via \`@fiderail/seller\`:
397
+ // import { createRemoteTrustClient } from "@fiderail/core";
398
+ // import { createFideRailSellerGuard } from "@fiderail/seller";
399
+ // const sellerGuard = createFideRailSellerGuard({
400
+ // payToBase: "${payeeHint}",
401
+ // priceUsdc: 0.05,
402
+ // engine: createRemoteTrustClient({ apiBaseUrl: API_BASE }),
403
+ // facilitatorVerifyUrl: "https://your-facilitator.example/verify",
404
+ // });
405
+
406
+ // Standalone local HTTP webhook adapter preview (optional):
407
+ if (process.argv[1] && import.meta.url.endsWith(process.argv[1].split("/").pop())) {
408
+ const server = http.createServer(async (req, res) => {
409
+ if (req.method !== "POST") {
410
+ res.writeHead(405, { "Content-Type": "application/json" });
411
+ res.end(JSON.stringify({ error: "Method not allowed" }));
412
+ return;
413
+ }
414
+ let body = "";
415
+ for await (const chunk of req) body += chunk;
416
+ const payload = body ? JSON.parse(body) : {};
417
+ const verdict = await screenBuyerBeforeSettle({
418
+ payer: String(payload.payer || payload.payerAddress || ""),
419
+ amountUsdc: Number(payload.amountUsdc || 0.05),
420
+ });
421
+ res.writeHead(verdict.allow ? 200 : 403, { "Content-Type": "application/json" });
422
+ res.end(JSON.stringify(verdict, null, 2));
423
+ });
424
+ const port = Number(process.env.PORT || 4021);
425
+ server.listen(port, "127.0.0.1", () => {
426
+ console.log(\`FideRail seller guard listening on http://127.0.0.1:\${port} (${chain})\`);
427
+ });
428
+ }
429
+ `;
430
+ }
431
+ function buildSellerStarterPy(chain, payee, apiUrl) {
432
+ const payeeHint = payee || "0xYOUR_SELLER_WALLET_OR_X402_PAYTO";
433
+ return `\"\"\"Non-custodial FideRail x402#2299 seller buyer-screening starter (zero deps).
434
+ Target chain: ${chain} | Example payTo: ${payeeHint}
435
+ \"\"\"
436
+
437
+ from __future__ import annotations
438
+
439
+ import json
440
+ import os
441
+ import urllib.request
442
+ from typing import Any, Dict
443
+
444
+
445
+ def screen_buyer_before_settle(
446
+ payer_address: str,
447
+ amount_usdc: float = 0.05,
448
+ chain: str = "${chain}",
449
+ api_base_url: str = "${apiUrl}",
450
+ ) -> Dict[str, Any]:
451
+ base = (os.environ.get("FIDERAIL_API_URL") or api_base_url).rstrip("/")
452
+ payload = json.dumps(
453
+ {"chain": chain, "payer": payer_address, "amountUsdc": float(amount_usdc)}
454
+ ).encode("utf-8")
455
+ req = urllib.request.Request(
456
+ f"{base}/v1/trust-provider/before-settle",
457
+ data=payload,
458
+ headers={"Content-Type": "application/json", "Accept": "application/json"},
459
+ method="POST",
460
+ )
461
+ with urllib.request.urlopen(req, timeout=6.0) as resp:
462
+ return json.loads(resp.read().decode("utf-8"))
463
+ `;
464
+ }
465
+ export function runSellerInit(options = {}) {
466
+ const lang = options.lang === "py" ? "py" : "ts";
467
+ const dir = path.resolve(options.dir || process.cwd());
468
+ const chainInput = options.chain || "base";
469
+ const chain = normalizeChainName(chainInput);
470
+ if (!chain) {
471
+ throw new Error(`Unsupported --chain "${chainInput}". Expected "base", "solana", "arbitrum", or "polygon".`);
472
+ }
473
+ let payee = null;
474
+ if (options.payee) {
475
+ if (!isValidAddress(chain, options.payee)) {
476
+ throw new Error(`Invalid ${chain} wallet address: "${options.payee}".`);
477
+ }
478
+ payee = normalizeChainAddress(chain, options.payee);
479
+ }
480
+ const apiUrl = normalizeApiUrl(options.apiUrl);
481
+ const defaultName = lang === "py" ? "fiderail_seller_guard.py" : "fiderail-seller-guard.mjs";
482
+ const outAbs = path.resolve(dir, options.out || defaultName);
483
+ const dryRun = Boolean(options.dryRun);
484
+ const force = Boolean(options.force);
485
+ const nextContent = lang === "py"
486
+ ? buildSellerStarterPy(chain, payee, apiUrl)
487
+ : buildSellerStarterTs(chain, payee, apiUrl);
488
+ const existing = fs.existsSync(outAbs) ? fs.readFileSync(outAbs, "utf8") : null;
489
+ if (existing === nextContent) {
490
+ return {
491
+ ok: true,
492
+ cliVersion: FIDERAIL_MANIFEST.project.currentRelease,
493
+ nonCustodial: true,
494
+ privateKeysTouched: false,
495
+ lang,
496
+ chain,
497
+ payee,
498
+ apiUrl,
499
+ dryRun,
500
+ action: {
501
+ kind: "seller_starter",
502
+ path: outAbs,
503
+ status: "unchanged",
504
+ backupPath: null,
505
+ },
506
+ };
507
+ }
508
+ if (existing !== null && !force) {
509
+ throw new Error(`Refusing to overwrite existing file ${outAbs}. Re-run with --force to replace.`);
510
+ }
511
+ let backupPath = null;
512
+ const status = existing === null ? "created" : "updated";
513
+ if (!dryRun) {
514
+ fs.mkdirSync(path.dirname(outAbs), { recursive: true });
515
+ if (existing !== null) {
516
+ backupPath = uniqueBackupPath(outAbs);
517
+ fs.writeFileSync(backupPath, existing, "utf8");
518
+ }
519
+ fs.writeFileSync(outAbs, nextContent, "utf8");
520
+ }
521
+ return {
522
+ ok: true,
523
+ cliVersion: FIDERAIL_MANIFEST.project.currentRelease,
524
+ nonCustodial: true,
525
+ privateKeysTouched: false,
526
+ lang,
527
+ chain,
528
+ payee,
529
+ apiUrl,
530
+ dryRun,
531
+ action: {
532
+ kind: "seller_starter",
533
+ path: outAbs,
534
+ status,
535
+ backupPath,
536
+ },
537
+ };
538
+ }
539
+ export async function runLiveCheck(apiUrlInput) {
540
+ const apiUrl = normalizeApiUrl(apiUrlInput);
541
+ const headers = {
542
+ Accept: "application/json",
543
+ "User-Agent": `@fiderail/cli/${FIDERAIL_MANIFEST.project.currentRelease}`,
544
+ };
545
+ const healthRes = await fetch(`${apiUrl}/healthz`, {
546
+ headers,
547
+ signal: AbortSignal.timeout(8000),
548
+ });
549
+ if (!healthRes.ok) {
550
+ throw new Error(`HTTP ${healthRes.status} from ${apiUrl}/healthz`);
551
+ }
552
+ const health = (await healthRes.json());
553
+ if (health?.status !== "ok") {
554
+ throw new Error(`Unexpected /healthz status: ${String(health?.status)}`);
555
+ }
556
+ const mcpRes = await fetch(`${apiUrl}/mcp`, {
557
+ method: "POST",
558
+ headers: { ...headers, "Content-Type": "application/json" },
559
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }),
560
+ signal: AbortSignal.timeout(8000),
561
+ });
562
+ if (!mcpRes.ok) {
563
+ throw new Error(`HTTP ${mcpRes.status} from ${apiUrl}/mcp`);
564
+ }
565
+ const mcpJson = (await mcpRes.json());
566
+ const tools = Array.isArray(mcpJson?.result?.tools) ? mcpJson.result.tools : [];
567
+ if (tools.length === 0) {
568
+ throw new Error(`Remote MCP /mcp tools/list returned zero tools`);
569
+ }
570
+ const indexerChains = health.indexer && typeof health.indexer === "object" ? Object.keys(health.indexer) : [];
571
+ return {
572
+ ok: true,
573
+ cliVersion: FIDERAIL_MANIFEST.project.currentRelease,
574
+ apiUrl,
575
+ serverStatus: String(health.status),
576
+ serverVersion: health.version ?? null,
577
+ priceUsdc: typeof health.priceUsdc === "number" ? health.priceUsdc : null,
578
+ storageMode: health.storageMode ? String(health.storageMode) : null,
579
+ stateRootSigningEnabled: Boolean(health.stateRootSigning?.enabled),
580
+ mcpToolCount: tools.length,
581
+ indexerChains,
582
+ };
583
+ }
584
+ export function createCliTrustClient(apiUrlInput) {
585
+ const apiBaseUrl = normalizeApiUrl(apiUrlInput);
586
+ return createRemoteTrustClient({
587
+ apiBaseUrl,
588
+ timeoutMs: 10000,
589
+ headers: {
590
+ "User-Agent": `@fiderail/cli/${FIDERAIL_MANIFEST.project.currentRelease}`,
591
+ },
592
+ });
593
+ }
594
+ //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@fiderail/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.4.3",
4
+ "description": "One-line non-custodial AI IDE / Agent MCP & skill installer, seller middleware scaffolder, and live diagnostics CLI for FideRail.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "bin": {
9
+ "fiderail": "dist/cli.js"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js"
15
+ }
16
+ },
17
+ "files": [
18
+ "README.md",
19
+ "LICENSE",
20
+ "NOTICE",
21
+ "dist",
22
+ "!dist/**/*.map",
23
+ "!dist/**/*.tsbuildinfo"
24
+ ],
25
+ "scripts": {
26
+ "prepublishOnly": "tsc -b && node -e \"require('node:fs').chmodSync('dist/cli.js', 0o755)\""
27
+ },
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "engines": {
32
+ "node": ">=22.13.0"
33
+ },
34
+ "homepage": "https://fiderail.com",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/fiderail/fiderail.git",
38
+ "directory": "apps/cli"
39
+ },
40
+ "bugs": {
41
+ "url": "https://github.com/fiderail/fiderail/issues"
42
+ },
43
+ "keywords": [
44
+ "fiderail",
45
+ "cli",
46
+ "mcp",
47
+ "claude-code",
48
+ "cursor",
49
+ "windsurf",
50
+ "codex",
51
+ "openclaw",
52
+ "ai-agent",
53
+ "payment-control-plane",
54
+ "x402",
55
+ "anti-sybil"
56
+ ],
57
+ "dependencies": {
58
+ "@fiderail/core": "2.4.3",
59
+ "@fiderail/spec": "2.4.3"
60
+ },
61
+ "license": "Apache-2.0"
62
+ }