@fangorn-network/sdk 0.1.0-dev → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/lib/cli/cli.js +328 -128
  2. package/lib/cli/index.d.ts +4 -1
  3. package/lib/cli/index.js +20 -2
  4. package/lib/config.d.ts +111 -48
  5. package/lib/config.js +39 -11
  6. package/lib/contracts/app-registry/abi.d.ts +1265 -0
  7. package/lib/contracts/app-registry/abi.js +1454 -0
  8. package/lib/contracts/app-registry/index.d.ts +161 -0
  9. package/lib/contracts/app-registry/index.js +274 -0
  10. package/lib/contracts/data-registry/abi.d.ts +19 -195
  11. package/lib/contracts/data-registry/abi.js +206 -409
  12. package/lib/contracts/data-registry/index.d.ts +2 -126
  13. package/lib/contracts/data-registry/index.js +1 -174
  14. package/lib/contracts/index.d.ts +7 -4
  15. package/lib/contracts/index.js +7 -4
  16. package/lib/contracts/logs.d.ts +1 -1
  17. package/lib/contracts/logs.js +1 -1
  18. package/lib/contracts/{settlement-registry → membership-registry}/abi.d.ts +636 -301
  19. package/lib/contracts/membership-registry/abi.js +1333 -0
  20. package/lib/contracts/membership-registry/index.d.ts +79 -0
  21. package/lib/contracts/membership-registry/index.js +104 -0
  22. package/lib/contracts/types.d.ts +10 -0
  23. package/lib/contracts/types.js +12 -0
  24. package/lib/crypto/aes.d.ts +2 -2
  25. package/lib/crypto/aes.js +4 -4
  26. package/lib/crypto/encryption.d.ts +109 -8
  27. package/lib/crypto/encryption.js +114 -16
  28. package/lib/engine/car.d.ts +1 -5
  29. package/lib/engine/car.js +2 -2
  30. package/lib/engine/index.d.ts +14 -33
  31. package/lib/engine/index.js +41 -98
  32. package/lib/engine/records.d.ts +8 -19
  33. package/lib/engine/records.js +7 -81
  34. package/lib/engine/test-helpers.d.ts +3 -2
  35. package/lib/engine/test-helpers.js +5 -7
  36. package/lib/erc8004.js +10 -7
  37. package/lib/fangorn.d.ts +86 -65
  38. package/lib/fangorn.js +153 -115
  39. package/lib/feed.d.ts +8 -7
  40. package/lib/feed.js +8 -7
  41. package/lib/harness/examples/hackmd/build-markdown-graph.d.ts +1 -0
  42. package/lib/harness/examples/hackmd/build-markdown-graph.js +17 -0
  43. package/lib/harness/index.d.ts +58 -0
  44. package/lib/harness/index.js +73 -0
  45. package/lib/index.d.ts +13 -10
  46. package/lib/index.js +13 -10
  47. package/lib/node_modules/{@jridgewell → .pnpm/@jridgewell_sourcemap-codec@1.5.5/node_modules/@jridgewell}/sourcemap-codec/dist/sourcemap-codec.js +1 -1
  48. package/lib/node_modules/{@vitest → .pnpm/@vitest_expect@4.0.18/node_modules/@vitest}/expect/dist/index.js +8 -8
  49. package/lib/node_modules/{@vitest → .pnpm/@vitest_pretty-format@4.0.18/node_modules/@vitest}/pretty-format/dist/index.js +2 -2
  50. package/lib/node_modules/{@vitest → .pnpm/@vitest_runner@4.0.18/node_modules/@vitest}/runner/dist/chunk-tasks.js +2 -2
  51. package/lib/node_modules/{@vitest → .pnpm/@vitest_runner@4.0.18/node_modules/@vitest}/runner/dist/index.js +4 -4
  52. package/lib/node_modules/{@vitest → .pnpm/@vitest_snapshot@4.0.18/node_modules/@vitest}/snapshot/dist/index.js +4 -4
  53. package/lib/node_modules/{@vitest → .pnpm/@vitest_spy@4.0.18/node_modules/@vitest}/spy/dist/index.js +1 -1
  54. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/chunk-_commonjsHelpers.js +1 -1
  55. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/chunk-pathe.M-eThtNZ.js +1 -1
  56. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/diff.js +3 -3
  57. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/display.js +2 -2
  58. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/error.js +2 -2
  59. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/helpers.js +1 -1
  60. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/serialize.js +1 -1
  61. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/source-map.js +1 -1
  62. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/timers.js +1 -1
  63. package/lib/node_modules/{chai → .pnpm/chai@6.2.2/node_modules/chai}/index.js +1 -1
  64. package/lib/node_modules/{magic-string → .pnpm/magic-string@0.30.21/node_modules/magic-string}/dist/magic-string.es.js +2 -2
  65. package/lib/node_modules/{pathe → .pnpm/pathe@2.0.3/node_modules/pathe}/dist/shared/pathe.M-eThtNZ.js +1 -1
  66. package/lib/node_modules/{tinyrainbow → .pnpm/tinyrainbow@3.0.3/node_modules/tinyrainbow}/dist/index.js +1 -1
  67. package/lib/node_modules/{vitest → .pnpm/vitest@4.0.18_@types_node@24.10.1_jiti@2.6.1_terser@5.51.2_tsx@4.21.0_yaml@2.8.2/node_modules/vitest}/dist/chunks/_commonjsHelpers.D26ty3Ew.js +1 -1
  68. package/lib/node_modules/{vitest → .pnpm/vitest@4.0.18_@types_node@24.10.1_jiti@2.6.1_terser@5.51.2_tsx@4.21.0_yaml@2.8.2/node_modules/vitest}/dist/chunks/date.Bq6ZW5rf.js +1 -1
  69. package/lib/node_modules/{vitest → .pnpm/vitest@4.0.18_@types_node@24.10.1_jiti@2.6.1_terser@5.51.2_tsx@4.21.0_yaml@2.8.2/node_modules/vitest}/dist/chunks/utils.DvEY5TfP.js +2 -2
  70. package/lib/node_modules/{vitest → .pnpm/vitest@4.0.18_@types_node@24.10.1_jiti@2.6.1_terser@5.51.2_tsx@4.21.0_yaml@2.8.2/node_modules/vitest}/dist/chunks/vi.2VT5v0um.js +11 -11
  71. package/lib/providers/storage/signed-url.d.ts +10 -2
  72. package/lib/providers/storage/signed-url.js +15 -5
  73. package/lib/providers/storage/types.d.ts +1 -1
  74. package/lib/providers/storage/utils.js +3 -5
  75. package/lib/registry.d.ts +118 -0
  76. package/lib/registry.js +184 -0
  77. package/lib/test/mem-registry.d.ts +19 -14
  78. package/lib/test/mem-registry.js +37 -44
  79. package/lib/test/sdk-suite.d.ts +4 -1
  80. package/lib/test/sdk-suite.js +89 -18
  81. package/lib/test/testbed.d.ts +5227 -5218
  82. package/lib/test/testbed.js +56 -29
  83. package/lib/types/index.d.ts +11 -6
  84. package/package.json +1 -1
  85. package/lib/cli/sell.d.ts +0 -28
  86. package/lib/cli/sell.js +0 -95
  87. package/lib/cli/stage.d.ts +0 -19
  88. package/lib/cli/stage.js +0 -94
  89. package/lib/contracts/settlement-registry/abi.js +0 -962
  90. package/lib/contracts/settlement-registry/index.d.ts +0 -143
  91. package/lib/contracts/settlement-registry/index.js +0 -213
  92. package/lib/crypto/paid.d.ts +0 -104
  93. package/lib/crypto/paid.js +0 -147
  94. package/lib/test/key-server.d.ts +0 -12
  95. package/lib/test/key-server.js +0 -30
  96. /package/lib/node_modules/{@vitest → .pnpm/@vitest_runner@4.0.18/node_modules/@vitest}/runner/dist/utils.js +0 -0
package/lib/cli/cli.js CHANGED
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
- import getNetwork, { nonBlank } from "../config.js";
2
+ import getNetwork, { nonBlank, toAppId } from "../config.js";
3
3
  import { agentCardUrl, parseAgentId } from "../erc8004.js";
4
+ import { PublisherStatus } from "../contracts/types.js";
5
+ import "../contracts/index.js";
4
6
  import { Fangorn } from "../fangorn.js";
5
- import { sealRecords } from "./sell.js";
6
- import { fileToRecords, walk } from "./stage.js";
7
- import { handleCancel } from "./index.js";
8
- import { createPublicClient, formatEther, http, isAddress, parseUnits } from "viem";
7
+ import { handleCancel, selectChain } from "./index.js";
8
+ import { createPublicClient, formatEther, formatUnits, http } from "viem";
9
9
  import { privateKeyToAccount } from "viem/accounts";
10
- import { Command } from "commander";
11
- import { confirm, intro, outro, spinner, text } from "@clack/prompts";
12
10
  import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
13
11
  import { dirname, join } from "path";
12
+ import { Command } from "commander";
13
+ import { confirm, intro, outro, spinner, text } from "@clack/prompts";
14
14
  import { homedir } from "os";
15
15
  import "dotenv/config";
16
16
 
@@ -34,12 +34,15 @@ function loadConfig() {
34
34
  const pinataJwt = process.env.PINATA_JWT;
35
35
  const pinataGateway = process.env.PINATA_GATEWAY;
36
36
  const signedUrlWorkerUrl = process.env.SIGNED_URL_WORKER_URL;
37
+ const envAppId = nonBlank(process.env.FANGORN_APP_ID);
37
38
  const envChain = nonBlank(process.env.CHAIN_NAME);
38
39
  if (existsSync(CONFIG_PATH)) {
39
40
  const stored = readStoredConfig();
41
+ const storedChain = stored.chainName === "Arbitrum Sepolia" ? "arbitrumSepolia" : stored.chainName;
40
42
  _config = {
41
43
  privateKey: stored.privateKey,
42
- cfg: network(envChain ?? stored.chainName),
44
+ cfg: getNetwork(envChain ?? storedChain),
45
+ appId: envAppId ?? nonBlank(stored.appId),
43
46
  pinataJwt: stored.pinataJwt,
44
47
  pinataGateway: stored.pinataGateway,
45
48
  signedUrlWorkerUrl: stored.signedUrlWorkerUrl ?? ""
@@ -50,7 +53,8 @@ function loadConfig() {
50
53
  if (!privateKey) throw new Error("Incomplete environment configuration. Missing: ETH_PRIVATE_KEY\nSet it or run `fangorn init` to use a config file.");
51
54
  _config = {
52
55
  privateKey,
53
- cfg: network(envChain ?? "baseSepolia"),
56
+ cfg: getNetwork(envChain ?? "baseSepolia"),
57
+ appId: envAppId,
54
58
  pinataJwt: pinataJwt ?? "",
55
59
  pinataGateway: pinataGateway ?? "",
56
60
  signedUrlWorkerUrl: signedUrlWorkerUrl ?? ""
@@ -59,25 +63,6 @@ function loadConfig() {
59
63
  }
60
64
  throw new Error("No configuration found. Run `fangorn init` or set ETH_PRIVATE_KEY\n(with no config, uploads go to Fangorn's shared Pinata account; files may be unpinned without notice. Set PINATA_JWT + PINATA_GATEWAY to use your own storage).");
61
65
  }
62
- /**
63
- * The named network, with its RPC and contracts overridable from the environment:
64
- * FANGORN_RPC_URL, FANGORN_DATA_REGISTRY and FANGORN_SETTLEMENT_REGISTRY, for a local
65
- * chain (an anvil with the contracts deployed) or a private RPC. Blank counts as unset.
66
- */
67
- function network(name) {
68
- const cfg = getNetwork(name);
69
- const address = (variable) => {
70
- const value = nonBlank(process.env[variable]);
71
- if (value !== void 0 && !isAddress(value)) throw new Error(`${variable} is not an address: "${value}"`);
72
- return value;
73
- };
74
- return {
75
- ...cfg,
76
- rpcUrl: nonBlank(process.env.FANGORN_RPC_URL) ?? cfg.rpcUrl,
77
- dataRegistryContractAddress: address("FANGORN_DATA_REGISTRY") ?? cfg.dataRegistryContractAddress,
78
- settlementRegistryContractAddress: address("FANGORN_SETTLEMENT_REGISTRY") ?? cfg.settlementRegistryContractAddress
79
- };
80
- }
81
66
  function getAccount() {
82
67
  if (_account) return _account;
83
68
  _account = privateKeyToAccount(loadConfig().privateKey);
@@ -96,10 +81,27 @@ function getFangorn() {
96
81
  _fangorn = Fangorn.create({
97
82
  privateKey: cfg.privateKey,
98
83
  storage,
99
- config: cfg.cfg
84
+ config: cfg.cfg,
85
+ appId: appFlag() ?? cfg.appId
100
86
  });
101
87
  return _fangorn;
102
88
  }
89
+ /** The `--app` override for this invocation; blank counts as unset. */
90
+ function appFlag() {
91
+ return nonBlank(program.opts().app);
92
+ }
93
+ /**
94
+ * The currently configured app name. App commands need one: there is no default
95
+ * app, since publishing and reading need none.
96
+ */
97
+ function currentAppName() {
98
+ const name = appFlag() ?? loadConfig().appId;
99
+ if (!name) throw new Error("no app chosen: run `fangorn set-app <name>` or pass --app");
100
+ return name;
101
+ }
102
+ function currentAppId() {
103
+ return toAppId(currentAppName());
104
+ }
103
105
  var LocalRepo = class LocalRepo {
104
106
  constructor(dir, state) {
105
107
  this.dir = dir;
@@ -144,26 +146,14 @@ var LocalRepo = class LocalRepo {
144
146
  this.state.head = cid;
145
147
  this.save();
146
148
  }
147
- root() {
148
- return this.dir;
149
- }
150
- /** The staging area: what the next `fangorn commit` (no file) will commit. */
151
- staged() {
152
- const p = join(this.dir, ".fangorn", "index.json");
153
- return existsSync(p) ? JSON.parse(readFileSync(p, "utf-8")) : {
154
- records: [],
155
- deletes: []
156
- };
157
- }
158
- setStaged(s) {
159
- writeFileSync(join(this.dir, ".fangorn", "index.json"), JSON.stringify(s, null, 2), "utf-8");
160
- }
161
149
  };
162
150
  const program = new Command();
151
+ const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
163
152
  program.name("fangorn").description("Fangorn Network CLI").version("0.4.0");
153
+ program.option("--app <name-or-id>", "App (global namespace) for this command — overrides the stored app (see `set-app`)");
164
154
  program.command("init").description("Configure your Fangorn credentials").action(async () => {
165
155
  intro("Fangorn Setup");
166
- const chainName = "baseSepolia";
156
+ const chainName = await selectChain();
167
157
  const privateKey = await text({
168
158
  message: "Wallet private key (stored locally, never transmitted):",
169
159
  placeholder: "0x...",
@@ -176,7 +166,7 @@ program.command("init").description("Configure your Fangorn credentials").action
176
166
  const pinataJwt = await text({ message: "Pinata JWT — leave blank to use Fangorn's shared Pinata account (testnet convenience; files may be unpinned without notice):" });
177
167
  handleCancel(pinataJwt);
178
168
  const pinataGateway = await text({
179
- message: "Pinata Gateway URL (optional; blank uses the network's gateway):",
169
+ message: "Pinata Gateway URL (optional; blank uses a public IPFS gateway):",
180
170
  placeholder: "https://your-gateway.mypinata.cloud"
181
171
  });
182
172
  handleCancel(pinataGateway);
@@ -190,25 +180,124 @@ program.command("init").description("Configure your Fangorn credentials").action
190
180
  chainName,
191
181
  pinataJwt,
192
182
  pinataGateway,
193
- signedUrlWorkerUrl
183
+ signedUrlWorkerUrl,
184
+ appId: existsSync(CONFIG_PATH) ? readStoredConfig().appId : void 0
194
185
  });
195
186
  outro(`Config saved to ${CONFIG_PATH}`);
196
187
  });
197
- program.command("card").description("Point a repo at its agent card, and register the card as an ERC-8004 agent").argument("[cardUrl]", "The agent card URL; or pass --access-worker to use its /.well-known/agent-card.json").option("--repo <name>", "The repo the card speaks for (default: the repo tracked here)").option("--access-worker <url>", "The access worker serving the agent card").option("--mcp <url>", "An MCP endpoint to index alongside the card").option("--skip-register", "Only commit the @card record, for a card already registered with ERC-8004").option("--update <agentId>", "Update an agent already registered (e.g. 84532:10323) from the card as it is now: a new registration file, pointed to by setAgentURI; mints nothing").action(async (cardUrl, opts) => {
188
+ program.command("set-app").description("Set the app (global namespace) this CLI publishes and reads under").argument("[app]", "App name or 32-byte app id (omit to show the current one)").action((app) => {
189
+ try {
190
+ if (!app) {
191
+ const current = currentAppName();
192
+ console.log(`App: ${current}`);
193
+ console.log(`App id: ${toAppId(current)}`);
194
+ process.exit(0);
195
+ }
196
+ if (!existsSync(CONFIG_PATH)) throw new Error(`no config file at ${CONFIG_PATH} — run \`fangorn init\` first, or set FANGORN_APP_ID in the environment.`);
197
+ writeStoredConfig({
198
+ ...readStoredConfig(),
199
+ appId: app
200
+ });
201
+ console.log(`App: ${app}`);
202
+ console.log(`App id: ${toAppId(app)}`);
203
+ if (process.env.FANGORN_APP_ID) console.log(`\nNote: FANGORN_APP_ID=${process.env.FANGORN_APP_ID} is set and overrides this.`);
204
+ console.log(`\nSaved to ${CONFIG_PATH}. Run \`fangorn app info\` to see whether it is claimed and whether it has accepted you.`);
205
+ process.exit(0);
206
+ } catch (err) {
207
+ console.error("Failed:", err.message);
208
+ process.exit(1);
209
+ }
210
+ });
211
+ /** Fees are USDC, which has 6 decimals; the contracts count in its base units. */
212
+ const USDC_DECIMALS = 6;
213
+ function formatUsdc(amount) {
214
+ return `${formatUnits(amount, USDC_DECIMALS)} USDC`;
215
+ }
216
+ /** The status word for a publisher in one app, and whether they can publish. */
217
+ function membershipLine(status, canPublish, appSuspended, expired) {
218
+ if (appSuspended) return "the whole app is suspended by the protocol admin — nobody can publish under it";
219
+ if (expired) return "the app's subscription has expired — nobody can publish until its owner runs `fangorn app renew`";
220
+ if (canPublish) return "accepted";
221
+ if (status === PublisherStatus.SUSPENDED) return "suspended from this app by its owner";
222
+ if (status === PublisherStatus.ACTIVE) return "accepted, but suspended network-wide by the protocol admin";
223
+ return "not accepted here — ask the app's owner to run `fangorn app accept <your address>`";
224
+ }
225
+ const appCmd = program.command("app").description("Claim and manage apps, and the publishers they accept");
226
+ appCmd.command("info").description("Show this app's owner, subscription, and where you stand in it").action(async () => {
227
+ try {
228
+ const self = getAccount().address;
229
+ const apps = getFangorn().getAppRegistry();
230
+ const s = spinner();
231
+ s.start("Reading registry...");
232
+ const [{ canPublish, owner, expiresAt }, status, appSuspended, suspendedGlobally] = await Promise.all([
233
+ apps.access(self),
234
+ apps.status(self),
235
+ apps.isAppSuspended(),
236
+ apps.isGloballySuspended(self)
237
+ ]);
238
+ s.stop();
239
+ const expired = expiresAt <= BigInt(Math.floor(Date.now() / 1e3));
240
+ console.log(`App: ${currentAppName()}`);
241
+ console.log(`App id: ${apps.getAppId() ?? ""}`);
242
+ if (owner === ZERO_ADDRESS) console.log(`Owner: (unclaimed — \`fangorn app claim\` takes it)`);
243
+ else {
244
+ console.log(`Owner: ${owner}${owner.toLowerCase() === self.toLowerCase() ? " (you)" : ""}`);
245
+ console.log(expiresAt === 0n ? `Expires: cancelled — \`fangorn app renew\` starts a new period` : `Expires: ${(/* @__PURE__ */ new Date(Number(expiresAt) * 1e3)).toISOString()}${expired ? " (EXPIRED)" : ""}`);
246
+ }
247
+ if (appSuspended) console.log(`Status: SUSPENDED by the protocol admin`);
248
+ console.log(`\nWallet: ${self}`);
249
+ if (suspendedGlobally) console.log(`Network: SUSPENDED by the protocol admin — cannot claim, be accepted or publish`);
250
+ console.log(`This app: ${owner === ZERO_ADDRESS ? "n/a (unclaimed)" : membershipLine(status, canPublish, appSuspended, expired)}`);
251
+ process.exit(0);
252
+ } catch (err) {
253
+ console.error("Failed:", err.message);
254
+ process.exit(1);
255
+ }
256
+ });
257
+ appCmd.command("claim").description("Claim the configured app on-chain (first come, first served)").action(async () => {
258
+ try {
259
+ const self = getAccount().address;
260
+ const registry = getFangorn().getAppRegistry();
261
+ const s = spinner();
262
+ s.start("Checking app ownership...");
263
+ const [owner, suspendedGlobally] = await Promise.all([registry.getAppOwner(), registry.isGloballySuspended(self)]);
264
+ s.stop();
265
+ if (owner !== ZERO_ADDRESS) {
266
+ const mine = owner.toLowerCase() === self.toLowerCase();
267
+ console.log(mine ? `Already claimed by you: ${registry.getAppId() ?? ""}` : `App ${registry.getAppId() ?? ""} is already owned by ${owner}. Pick another name with \`fangorn set-app\`, or ask its owner to accept you.`);
268
+ process.exit(mine ? 0 : 1);
269
+ }
270
+ if (suspendedGlobally) {
271
+ console.error(`${self} is suspended by the protocol admin — claiming will revert.`);
272
+ process.exit(1);
273
+ }
274
+ const subscriptionFee = await registry.subscriptionFee();
275
+ console.log(`Subscription fee: ${formatUsdc(subscriptionFee)}`);
276
+ s.start("Claiming app...");
277
+ const txHash = await registry.registerApp();
278
+ s.stop();
279
+ console.log(`App: ${currentAppName()}`);
280
+ console.log(`App id: ${currentAppId()}`);
281
+ console.log(`Owner: ${self}`);
282
+ console.log(`Tx: ${txHash}`);
283
+ console.log(`\nClaiming makes you your own first publisher. Accept others with \`fangorn app accept <address>\`.`);
284
+ process.exit(0);
285
+ } catch (err) {
286
+ console.error("Failed:", err.message);
287
+ process.exit(1);
288
+ }
289
+ });
290
+ appCmd.command("agent").description("Register this app's gateway as an ERC-8004 agent and point the app at its card (owner only)").argument("[cardUrl]", "The agent card URL; or pass --access-worker to use its /.well-known/agent-card.json").option("--access-worker <url>", "The access worker serving the agent card").option("--mcp <url>", "An MCP endpoint to index alongside the card").option("--skip-register", "Only set agent_uri on-chain — for a gateway already registered with ERC-8004").option("--update <agentId>", "Update an agent already registered (e.g. 84532:10323) from the card as it is now: a new registration file, pointed to by setAgentURI; mints nothing").action(async (cardUrl, opts) => {
198
291
  try {
199
292
  const cfg = loadConfig();
200
293
  const url = agentCardUrl(cardUrl, opts.accessWorker);
201
- const local = opts.repo ? void 0 : LocalRepo.open();
202
- const repo = opts.repo ?? local?.namespace() ?? "";
203
294
  const s = spinner();
204
295
  const chainId = cfg.cfg.caip2;
205
296
  const update = opts.update ? parseAgentId(opts.update, chainId) : void 0;
206
- s.start(opts.skipRegister ? `Pointing ${repo} at its card` : update !== void 0 ? `Updating ERC-8004 agent ${opts.update ?? ""}` : "Registering with the ERC-8004 identity registry");
207
- const fangorn = getFangorn();
297
+ s.start(opts.skipRegister ? "Pointing the app at its card" : update !== void 0 ? `Updating ERC-8004 agent ${opts.update ?? ""}` : "Registering with the ERC-8004 identity registry");
208
298
  let result;
209
299
  try {
210
- result = await fangorn.registerAgent(url, {
211
- repo,
300
+ result = await getFangorn().registerAgent(url, {
212
301
  mcp: opts.mcp,
213
302
  update,
214
303
  skipRegister: opts.skipRegister
@@ -216,15 +305,180 @@ program.command("card").description("Point a repo at its agent card, and registe
216
305
  } catch (e) {
217
306
  s.stop();
218
307
  const minted = e.agentId;
219
- throw minted !== void 0 ? /* @__PURE__ */ new Error(`${e.message.replace(/; finish it with .*/, "")}. Finish it with: fangorn card ${url} --repo ${repo} --update ${String(chainId)}:${String(minted)}`) : e;
308
+ throw minted !== void 0 ? /* @__PURE__ */ new Error(`${e.message.replace(/; finish it with .*/, "")}. Finish it with: fangorn app agent ${url} --update ${String(chainId)}:${String(minted)}`) : e;
220
309
  }
221
310
  s.stop();
222
- if (local && result.txHash) local.setHead(await fangorn.onChainTip(fangorn.getAddress(), repo));
223
311
  const agentId = result.agentId !== void 0 ? `${String(chainId)}:${String(result.agentId)}` : void 0;
312
+ const txHash = result.txHash ?? "(already bound)";
224
313
  if (agentId) console.log(`Agent ID: ${agentId}`);
225
- console.log(`Repo: ${repo}`);
226
314
  console.log(`Card: ${url}`);
227
- console.log(`Tx: ${result.txHash ?? "(already bound)"}`);
315
+ console.log(`Tx: ${txHash}`);
316
+ process.exit(0);
317
+ } catch (err) {
318
+ console.error("Failed:", err.message);
319
+ process.exit(1);
320
+ }
321
+ });
322
+ appCmd.command("accept").description("Accept a publisher into your app (owner only): the app stores and includes its data").argument("<publisher>", "Publisher address").action(async (publisher) => {
323
+ try {
324
+ const registry = getFangorn().getAppRegistry();
325
+ const s = spinner();
326
+ s.start("Checking publisher standing...");
327
+ const suspended = await registry.isGloballySuspended(publisher);
328
+ s.stop();
329
+ if (suspended) {
330
+ console.error(`${publisher} is suspended by the protocol admin — accepting them will revert.`);
331
+ process.exit(1);
332
+ }
333
+ s.start("Accepting publisher...");
334
+ const txHash = await registry.acceptPublisher(publisher);
335
+ s.stop();
336
+ console.log(`Accepted: ${publisher}`);
337
+ console.log(`Tx: ${txHash}`);
338
+ console.log(`\nThey can now upload with this app's storage, and the app includes their data.`);
339
+ process.exit(0);
340
+ } catch (err) {
341
+ console.error("Failed:", err.message);
342
+ process.exit(1);
343
+ }
344
+ });
345
+ appCmd.command("renew").description("Pay for one more period of your app's subscription (owner only)").action(async () => {
346
+ try {
347
+ const registry = getFangorn().getAppRegistry();
348
+ const s = spinner();
349
+ s.start("Renewing subscription...");
350
+ const txHash = await registry.renewSubscription();
351
+ const expiresAt = await registry.expiresAt();
352
+ s.stop();
353
+ console.log(`Renewed: ${registry.getAppId() ?? ""}`);
354
+ console.log(`Expires: ${(/* @__PURE__ */ new Date(Number(expiresAt) * 1e3)).toISOString()}`);
355
+ console.log(`Tx: ${txHash}`);
356
+ process.exit(0);
357
+ } catch (err) {
358
+ console.error("Failed:", err.message);
359
+ process.exit(1);
360
+ }
361
+ });
362
+ appCmd.command("cancel").description("End your app's subscription now, without refund (owner only)").action(async () => {
363
+ try {
364
+ const registry = getFangorn().getAppRegistry();
365
+ const ok = await confirm({ message: `Cancel ${registry.getAppId() ?? ""}'s subscription? Nothing is refunded, and the app takes no commits or joins until renewed.` });
366
+ handleCancel(ok);
367
+ if (!ok) process.exit(0);
368
+ const s = spinner();
369
+ s.start("Cancelling subscription...");
370
+ const txHash = await registry.cancelSubscription();
371
+ s.stop();
372
+ console.log(`Cancelled: ${registry.getAppId() ?? ""}`);
373
+ console.log(`Tx: ${txHash}`);
374
+ process.exit(0);
375
+ } catch (err) {
376
+ console.error("Failed:", err.message);
377
+ process.exit(1);
378
+ }
379
+ });
380
+ appCmd.command("withdraw-fees").description("Withdraw the join fees your apps collected before joining was removed (owner only)").argument("[to]", "Where to send them; defaults to this wallet").action(async (to) => {
381
+ try {
382
+ const registry = getFangorn().getAppRegistry();
383
+ const owed = await registry.joinFeesOwed();
384
+ if (owed === 0n) {
385
+ console.log("No join fees to withdraw.");
386
+ process.exit(0);
387
+ }
388
+ const s = spinner();
389
+ s.start(`Withdrawing ${formatUsdc(owed)}...`);
390
+ const txHash = await registry.withdrawJoinFees(to);
391
+ s.stop();
392
+ console.log(`Withdrawn: ${formatUsdc(owed)}`);
393
+ console.log(`Tx: ${txHash}`);
394
+ process.exit(0);
395
+ } catch (err) {
396
+ console.error("Failed:", err.message);
397
+ process.exit(1);
398
+ }
399
+ });
400
+ appCmd.command("suspend").description("Suspend a member from your app (owner only)").argument("<publisher>", "Publisher address").action(async (publisher) => {
401
+ try {
402
+ const s = spinner();
403
+ s.start("Suspending publisher...");
404
+ const txHash = await getFangorn().getAppRegistry().setPublisherSuspended(publisher, true);
405
+ s.stop();
406
+ console.log(`Suspended: ${publisher}`);
407
+ console.log(`Tx: ${txHash}`);
408
+ process.exit(0);
409
+ } catch (err) {
410
+ console.error("Failed:", err.message);
411
+ process.exit(1);
412
+ }
413
+ });
414
+ appCmd.command("reinstate").description("Reinstate a suspended publisher in your app (owner only)").argument("<publisher>", "Publisher address").action(async (publisher) => {
415
+ try {
416
+ const s = spinner();
417
+ s.start("Reinstating publisher...");
418
+ const txHash = await getFangorn().getAppRegistry().setPublisherSuspended(publisher, false);
419
+ s.stop();
420
+ console.log(`Reinstated: ${publisher}`);
421
+ console.log(`Tx: ${txHash}`);
422
+ process.exit(0);
423
+ } catch (err) {
424
+ console.error("Failed:", err.message);
425
+ process.exit(1);
426
+ }
427
+ });
428
+ const appAdminCmd = appCmd.command("admin").description("Protocol-admin takedowns for the whole app (admin only)");
429
+ /** The AppRegistry client, refusing early if this wallet is not the protocol admin. */
430
+ async function requireAdmin() {
431
+ const registry = getFangorn().getAppRegistry();
432
+ const self = getAccount().address;
433
+ const admin = await registry.admin();
434
+ if (admin.toLowerCase() !== self.toLowerCase()) throw new Error(`Not the protocol admin: this registry's admin is ${admin}, you are ${self}.`);
435
+ return registry;
436
+ }
437
+ appAdminCmd.command("suspend").description("Suspend this entire app — nobody can publish under it (admin only)").action(async () => {
438
+ try {
439
+ const registry = await requireAdmin();
440
+ const ok = await confirm({ message: `Suspend the whole app ${registry.getAppId() ?? ""}? Every publisher, including its owner, stops being able to publish.` });
441
+ handleCancel(ok);
442
+ if (!ok) process.exit(0);
443
+ const s = spinner();
444
+ s.start("Suspending app...");
445
+ const txHash = await registry.setAppSuspended(true);
446
+ s.stop();
447
+ console.log(`Suspended: ${currentAppId()}`);
448
+ console.log(`Tx: ${txHash}`);
449
+ console.log(`\nMemberships are kept — \`fangorn app admin reinstate\` restores them as they were.`);
450
+ process.exit(0);
451
+ } catch (err) {
452
+ console.error("Failed:", err.message);
453
+ process.exit(1);
454
+ }
455
+ });
456
+ appAdminCmd.command("reinstate").description("Lift the suspension on this entire app (admin only)").action(async () => {
457
+ try {
458
+ const registry = await requireAdmin();
459
+ const s = spinner();
460
+ s.start("Reinstating app...");
461
+ const txHash = await registry.setAppSuspended(false);
462
+ s.stop();
463
+ console.log(`Reinstated: ${currentAppId()}`);
464
+ console.log(`Tx: ${txHash}`);
465
+ process.exit(0);
466
+ } catch (err) {
467
+ console.error("Failed:", err.message);
468
+ process.exit(1);
469
+ }
470
+ });
471
+ appAdminCmd.command("status").description("Who the protocol admin is, and whether this app is suspended").action(async () => {
472
+ try {
473
+ const registry = getFangorn().getAppRegistry();
474
+ const self = getAccount().address;
475
+ const s = spinner();
476
+ s.start("Reading registry...");
477
+ const [admin, suspended] = await Promise.all([registry.admin(), registry.isAppSuspended()]);
478
+ s.stop();
479
+ console.log(`App id: ${currentAppId()}`);
480
+ console.log(`Admin: ${admin}${admin.toLowerCase() === self.toLowerCase() ? " (you)" : ""}`);
481
+ console.log(`Suspended: ${suspended ? "yes — nobody can publish under this app" : "no"}`);
228
482
  process.exit(0);
229
483
  } catch (err) {
230
484
  console.error("Failed:", err.message);
@@ -243,6 +497,7 @@ program.command("wallet").description("Show the wallet this CLI signs with").arg
243
497
  console.log(`Public key: ${account.publicKey}`);
244
498
  console.log(`Balance: ${formatEther(balance)} ETH`);
245
499
  console.log(`Network: ${cfg.cfg.chain.name} (${cfg.cfg.caip2.toString()})`);
500
+ console.log(`App: ${currentAppName()}`);
246
501
  console.log(`Config: ${existsSync(CONFIG_PATH) ? CONFIG_PATH : "(from environment)"}`);
247
502
  if (opts.reveal) {
248
503
  console.log(`\nPrivate key: ${cfg.privateKey}`);
@@ -281,69 +536,16 @@ program.command("repo").description("Repository operations").command("init").des
281
536
  process.exit(1);
282
537
  }
283
538
  });
284
- program.command("add").description("Stage files as records: csv/jsonl/json arrays → a record per row, other text → one record per file").argument("<paths...>", "Files or directories (dot entries skipped)").option("--type <type>", "Record type (default: file name, or \"file\" for text)").option("--id-column <col>", "Column/field holding the record id", "id").action((paths, options) => {
285
- try {
286
- const repo = LocalRepo.open();
287
- const staged = repo.staged();
288
- let n = 0;
289
- for (const p of paths) for (const rel of walk(repo.root(), join(process.cwd(), p))) {
290
- const got = fileToRecords(repo.root(), rel, options);
291
- if (!got) {
292
- console.warn(`skipped (binary): ${rel}`);
293
- continue;
294
- }
295
- const ids = new Set(got.records.map((r) => r.id));
296
- staged.records = staged.records.filter((r) => !r.id || !ids.has(r.id)).concat(got.records);
297
- staged.deletes = staged.deletes.filter((d) => !ids.has(d)).concat(got.deletes);
298
- n += got.records.length + got.deletes.length;
299
- console.log(`added ${rel} (${got.records.length.toString()} record(s))`);
300
- }
301
- repo.setStaged(staged);
302
- console.log(`${n.toString()} change(s) staged. Run \`fangorn commit\`.`);
303
- process.exit(0);
304
- } catch (err) {
305
- console.error("Failed:", err.message);
306
- process.exit(1);
307
- }
308
- });
309
- program.command("rm").description("Stage record deletes (and drop them from the staging area)").argument("<ids...>", "Record ids").action((ids) => {
310
- try {
311
- const repo = LocalRepo.open();
312
- const staged = repo.staged();
313
- staged.records = staged.records.filter((r) => !r.id || !ids.includes(r.id));
314
- staged.deletes = [...new Set([...staged.deletes, ...ids])];
315
- repo.setStaged(staged);
316
- console.log(`${ids.length.toString()} delete(s) staged.`);
317
- process.exit(0);
318
- } catch (err) {
319
- console.error("Failed:", err.message);
320
- process.exit(1);
321
- }
322
- });
323
- program.command("commit").description("Put/delete a namespace's records in a new local commit (does not push)").argument("[file]", "JSON file: {\"records\":[{\"id\",\"type\",\"payload\"}],\"deletes\":[\"id\"]} (default: the staging area, see `fangorn add`)").option("--replace", "Snapshot semantics: the file replaces the namespace's previous contents (omitted entries are removed)").option("--paid <fields>", "Comma-separated payload fields to sell: sealed (field-v1) and priced with signed terms").option("--price <usdc>", "Price of each paid record, in USDC (e.g. 0.01)").option("--share <percent>", "Share of each sale paid to the referrer (Fangorn takes none by default)", "0").option("--deadline-days <days>", "Days the signed terms stay buyable", "365").option("--key-server <url>", "Key server a new deposit is sealed to (an existing deposit keeps its own)", "https://keys-test.fangorn.network").action(async (file, options) => {
539
+ program.command("commit").description("Put/delete a namespace's records in a new local commit (does not push)").argument("<file>", "JSON file: {\"records\":[{\"id\",\"type\",\"payload\"}],\"deletes\":[\"id\"]}").requiredOption("-m, --message <msg>", "Commit message").option("--replace", "Snapshot semantics: the file replaces the namespace's previous contents (omitted entries are removed)").action(async (file, options) => {
324
540
  try {
325
- const repo = LocalRepo.open();
326
- if (file && !existsSync(file)) throw new Error(`file not found: ${file}`);
327
- const data = file ? JSON.parse(readFileSync(file, "utf-8")) : repo.staged();
328
- let records = data.records ?? [];
541
+ if (!existsSync(file)) throw new Error(`file not found: ${file}`);
542
+ const data = JSON.parse(readFileSync(file, "utf-8"));
543
+ const records = data.records ?? [];
329
544
  const deletes = data.deletes ?? [];
330
- if (!Array.isArray(records) || !Array.isArray(deletes) || records.length + deletes.length === 0) throw new Error(file ? `${file} must contain a non-empty "records" or "deletes" array` : "nothing staged — run `fangorn add <paths>` first");
545
+ if (!Array.isArray(records) || !Array.isArray(deletes) || records.length + deletes.length === 0) throw new Error(`${file} must contain a non-empty "records" or "deletes" array`);
546
+ const repo = LocalRepo.open();
331
547
  const fangorn = getFangorn();
332
548
  const parent = repo.head() ?? void 0;
333
- if (options.paid) {
334
- if (!options.price) throw new Error("--paid needs --price");
335
- if (parent && parent !== await fangorn.onChainTip(fangorn.getAddress(), repo.namespace())) throw new Error("push your local commits before committing paid records");
336
- const shareBps = Math.round(Number(options.share) * 100);
337
- const days = Number(options.deadlineDays);
338
- if (!Number.isFinite(days) || days <= 0) throw new Error(`--deadline-days must be a positive number, got ${options.deadlineDays}`);
339
- records = await sealRecords(fangorn, repo.namespace(), records, {
340
- fields: options.paid.split(",").map((f) => f.trim()).filter(Boolean),
341
- price: parseUnits(options.price, 6),
342
- shareBps,
343
- deadline: BigInt(Math.floor(Date.now() / 1e3 + days * 86400)),
344
- keyServer: options.keyServer
345
- });
346
- }
347
549
  const s = spinner();
348
550
  s.start(parent ? "Committing (building on local HEAD)..." : "Committing (initial)...");
349
551
  const result = await fangorn.commit({
@@ -351,18 +553,16 @@ program.command("commit").description("Put/delete a namespace's records in a new
351
553
  records,
352
554
  deletes,
353
555
  parent,
556
+ message: options.message,
354
557
  replace: options.replace
355
558
  });
356
559
  s.stop();
357
560
  repo.setHead(result.commitCid);
358
- if (!file) repo.setStaged({
359
- records: [],
360
- deletes: []
361
- });
362
561
  console.log(`Commit: ${result.commitCid}`);
363
562
  console.log(`Parent: ${result.parent ?? "(root)"}`);
364
563
  console.log(`Tree: ${result.root}`);
365
564
  console.log(`Staged: ${records.length.toString()} put(s) / ${deletes.length.toString()} delete(s)`);
565
+ console.log(`Message: ${options.message}`);
366
566
  console.log(`\nCommitted locally. Run \`fangorn push\` to settle it on-chain.`);
367
567
  process.exit(0);
368
568
  } catch (err) {
@@ -400,8 +600,6 @@ program.command("status").description("Compare the local tip with the on-chain t
400
600
  console.log(`Local HEAD: ${localHead ?? "(none)"}`);
401
601
  console.log(`On-chain tip: ${onChainTip ?? "(none)"}`);
402
602
  console.log(`Status: ${state}`);
403
- const staged = repo.staged();
404
- console.log(`Staged: ${staged.records.length.toString()} put(s) / ${staged.deletes.length.toString()} delete(s)`);
405
603
  process.exit(0);
406
604
  } catch (err) {
407
605
  console.error("Failed:", err.message);
@@ -419,7 +617,8 @@ program.command("log").description("Walk commit history from the local tip").opt
419
617
  for await (const c of fangorn.log(head, options.max)) {
420
618
  console.log(`commit ${c.cid}`);
421
619
  console.log(`Epoch: ${c.epoch.toString()}`);
422
- console.log(`Tree: ${c.root}\n`);
620
+ console.log(`Tree: ${c.root}`);
621
+ console.log(`\n ${c.message}\n`);
423
622
  }
424
623
  process.exit(0);
425
624
  } catch (err) {
@@ -436,7 +635,8 @@ program.command("show").description("Show a commit and what it changed vs. its p
436
635
  console.log(`commit ${target}`);
437
636
  console.log(`Epoch: ${diff.epoch.toString()}`);
438
637
  console.log(`Parent: ${diff.parent ?? "(root)"}`);
439
- console.log(`Tree: ${diff.root}\n`);
638
+ console.log(`Tree: ${diff.root}`);
639
+ console.log(`\n ${diff.message}\n`);
440
640
  console.log(`Changes vs. parent: +${diff.added.length.toString()} / -${diff.removed.length.toString()} key(s)`);
441
641
  for (const k of diff.added) console.log(` + ${k}`);
442
642
  for (const k of diff.removed) console.log(` - ${k}`);
@@ -467,7 +667,7 @@ program.command("clone").description("Track an existing on-chain namespace by re
467
667
  process.exit(1);
468
668
  }
469
669
  });
470
- program.command("subscribe").description("Watch on-chain pushes to a namespace and stream JSON diffs (light client — no indexer)").argument("[namespace]", "Namespace name (default: current repo)").option("--owner <address>", "Owner (publisher) address (default: current repo owner, else self)").option("--from-block <n>", "Replay from this block (overrides the saved cursor)", (v) => BigInt(v)).option("--from-start", "Replay this namespace's full history (ignore the saved cursor)").option("--pretty", "Pretty-print each change").option("--all", "Watch every publisher and namespace; --owner/namespace narrow it").action(async (namespaceArg, options) => {
670
+ program.command("subscribe").description("Watch on-chain pushes to a namespace and stream JSON diffs (light client — no indexer)").argument("[namespace]", "Namespace name (default: current repo)").option("--owner <address>", "Owner (publisher) address (default: current repo owner, else self)").option("--from-block <n>", "Replay from this block (overrides the saved cursor)", (v) => BigInt(v)).option("--from-start", "Replay this namespace's full history (ignore the saved cursor)").option("--pretty", "Pretty-print each change").option("--all", "Watch the whole app (every publisher, every namespace); --owner/namespace narrow it").action(async (namespaceArg, options) => {
471
671
  try {
472
672
  const fangorn = getFangorn();
473
673
  let namespace = namespaceArg;
@@ -482,7 +682,7 @@ program.command("subscribe").description("Watch on-chain pushes to a namespace a
482
682
  owner = owner ?? fangorn.getAddress();
483
683
  }
484
684
  const repoDir = join(process.cwd(), ".fangorn");
485
- const cursorPath = join(repoDir, `subscribe-${owner ?? "all"}-${namespace ?? "all"}.json`);
685
+ const cursorPath = join(repoDir, `subscribe-${owner ?? "app"}-${namespace ?? "all"}.json`);
486
686
  const readCursor = () => {
487
687
  if (options.fromStart) return 0n;
488
688
  if (options.fromBlock !== void 0) return options.fromBlock;
@@ -501,7 +701,7 @@ program.command("subscribe").description("Watch on-chain pushes to a namespace a
501
701
  };
502
702
  const bigintReplacer = (_k, v) => typeof v === "bigint" ? v.toString() : v;
503
703
  const fromBlock = readCursor();
504
- console.error(`Subscribing to "${namespace ?? "*"}" @ ${owner ?? "*"} ` + (fromBlock !== void 0 ? `from block ${fromBlock.toString()}` : "(live from current tip)") + ` — Ctrl-C to stop.`);
704
+ console.error(`Subscribing to "${namespace ?? "*"}" @ ${owner ?? "* (whole app)"} ` + (fromBlock !== void 0 ? `from block ${fromBlock.toString()}` : "(live from current tip)") + ` — Ctrl-C to stop.`);
505
705
  const controller = new AbortController();
506
706
  process.on("SIGINT", () => {
507
707
  controller.abort();
@@ -509,7 +709,7 @@ program.command("subscribe").description("Watch on-chain pushes to a namespace a
509
709
  process.on("SIGTERM", () => {
510
710
  controller.abort();
511
711
  });
512
- const stream = options.all ? fangorn.subscribeAll({
712
+ const stream = options.all ? fangorn.subscribeApp({
513
713
  repo: namespace,
514
714
  owner,
515
715
  fromBlock,
@@ -1,10 +1,13 @@
1
1
  import "./cli.js";
2
+ import * as viem161 from "viem";
2
3
 
3
4
  //#region src/cli/index.d.ts
5
+ declare const getChain: (chainStr: string) => viem161.Chain;
4
6
  declare const handleCancel: (value: unknown) => void;
7
+ declare const selectChain: () => Promise<string>;
5
8
  declare function parseGadgetArg(raw: string): {
6
9
  type: string;
7
10
  args: string[];
8
11
  };
9
12
  //#endregion
10
- export { handleCancel, parseGadgetArg };
13
+ export { getChain, handleCancel, parseGadgetArg, selectChain };