@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/fangorn.js CHANGED
@@ -1,12 +1,13 @@
1
- import { FangornConfig, nonBlank } from "./config.js";
1
+ import { FangornConfig, nonBlank, toAppId } from "./config.js";
2
2
  import { mcpTools, mintAgent, registrationFile, retryNonce, setAgentFile } from "./erc8004.js";
3
3
  import { SignedUrlBackend } from "./providers/storage/signed-url.js";
4
4
  import { PinataBackend } from "./providers/storage/pinata.js";
5
- import { ChainRegistry, ZERO_HEAD } from "./contracts/data-registry/index.js";
6
- import { SettlementRegistryClient } from "./contracts/settlement-registry/index.js";
5
+ import { AppRegistryClient } from "./contracts/app-registry/index.js";
6
+ import { MembershipRegistryClient } from "./contracts/membership-registry/index.js";
7
7
  import "./contracts/index.js";
8
- import { FangornEngine, assertValidRepoName, commitUpdate, rootHexFromCid } from "./engine/index.js";
9
- import { CommitFeed } from "./feed.js";
8
+ import { ChainRegistry, ZERO_HEAD, repoExcluded } from "./registry.js";
9
+ import { FangornEngine, assertValidRepoName, rootHexFromCid } from "./engine/index.js";
10
+ import { AppFeed } from "./feed.js";
10
11
  import { createPublicClient, createWalletClient, http } from "viem";
11
12
  import { privateKeyToAccount } from "viem/accounts";
12
13
  import { CID } from "multiformats/cid";
@@ -25,34 +26,22 @@ function walletSigner(walletClient) {
25
26
  })
26
27
  };
27
28
  }
28
- function resolveStorage(storage, walletClient, config) {
29
+ function resolveStorage(storage, walletClient, config, getAppId) {
29
30
  if (!storage) return void 0;
30
31
  if ("backend" in storage) return storage.backend;
31
- if ("pinata" in storage) return new PinataBackend(storage.pinata.jwt, nonBlank(storage.pinata.gateway) ?? config.ipfsGateway);
32
- if ("signedUrl" in storage) {
33
- const workerUrl = nonBlank(storage.signedUrl.workerUrl) ?? nonBlank(config.signedUrlWorker);
34
- if (!workerUrl) throw new Error(`no hosted upload worker on chain ${config.caip2.toString()}: pass storage.signedUrl.workerUrl, or bring your own storage ({ pinata } or { backend })`);
35
- return new SignedUrlBackend(workerUrl, walletSigner(walletClient), nonBlank(storage.signedUrl.gateway) ?? config.ipfsGateway);
36
- }
32
+ if ("pinata" in storage) return new PinataBackend(storage.pinata.jwt, storage.pinata.gateway);
33
+ if ("signedUrl" in storage) return new SignedUrlBackend(nonBlank(storage.signedUrl.workerUrl) ?? config.signedUrlWorker, walletSigner(walletClient), storage.signedUrl.gateway ?? config.ipfsGateway, getAppId);
37
34
  throw new Error(`Invalid storage config: must be { pinata: … }, { signedUrl: … } or { backend: … }, got ${JSON.stringify(storage)}`);
38
35
  }
39
- /**
40
- * The A2A extension a repo's agent card carries. Its params name the repo the
41
- * card speaks for: `{ chainId, dataRegistry, publisher, repo }`.
42
- */
43
- const FANGORN_REPO_EXTENSION = "https://fangorn.network/a2a/repo/v1";
44
- /**
45
- * The record that binds a repo to its agent card: `{ url }`, at this id in the
46
- * repo. Only the publisher can commit it, so it plays the part an on-chain
47
- * pointer would.
48
- */
49
- const CARD_RECORD = "@card";
36
+ /** The A2A extension a Fangorn app's agent card carries: it names the app the card speaks for. */
37
+ const FANGORN_APP_EXTENSION = "https://fangorn.network/a2a/app/v1";
50
38
  var Fangorn = class Fangorn {
51
39
  ctx;
52
40
  _engine = null;
53
41
  _feed = null;
54
- _settlement = null;
55
- /**
42
+ _apps = null;
43
+ _membership = null;
44
+ /**
56
45
  * The repo cache
57
46
  * Insertion order = LRU order
58
47
  */
@@ -67,8 +56,8 @@ var Fangorn = class Fangorn {
67
56
  }
68
57
  /**
69
58
  * Static creation of a new Fangorn client
70
- *
71
- * @param options
59
+ *
60
+ * @param options
72
61
  * @returns the client
73
62
  */
74
63
  static create(options) {
@@ -83,14 +72,16 @@ var Fangorn = class Fangorn {
83
72
  chain: config.chain,
84
73
  transport: http(config.rpcUrl)
85
74
  });
75
+ const chosenApp = nonBlank(options.appId);
86
76
  const ctx = {
87
77
  config,
88
78
  walletClient,
89
79
  publicClient,
80
+ appId: chosenApp ? toAppId(chosenApp) : void 0,
90
81
  metadataStorage: void 0,
91
82
  registry: options.registry ?? new ChainRegistry(config, publicClient, walletClient)
92
83
  };
93
- ctx.metadataStorage = resolveStorage(options.storage, walletClient, config);
84
+ ctx.metadataStorage = resolveStorage(options.storage, walletClient, config, () => ctx.appId);
94
85
  return new Fangorn(ctx);
95
86
  }
96
87
  /**
@@ -105,6 +96,7 @@ var Fangorn = class Fangorn {
105
96
  repo,
106
97
  base: head,
107
98
  records: [],
99
+ message: `Reset ${repo}`,
108
100
  replace: true
109
101
  });
110
102
  return this.engine.pushCommit(publisher, repo, commitCid);
@@ -121,7 +113,7 @@ var Fangorn = class Fangorn {
121
113
  });
122
114
  }
123
115
  /**
124
- * Allocates a repo in the publisher's root map.
116
+ * Allocates a repo in the publisher's root map.
125
117
  * A no-op (no on-chain tx) if the repo is already initialized.
126
118
  */
127
119
  async initRepo(repoName) {
@@ -137,7 +129,8 @@ var Fangorn = class Fangorn {
137
129
  const { commitCid } = await this.createCommit({
138
130
  repo: repoName,
139
131
  base: head,
140
- records: []
132
+ records: [],
133
+ message: `Initialize repository workspace: ${repoName}`
141
134
  });
142
135
  const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
143
136
  return {
@@ -162,7 +155,8 @@ var Fangorn = class Fangorn {
162
155
  id,
163
156
  type,
164
157
  payload
165
- }]
158
+ }],
159
+ message: `Upload to repo ${repoName} as type ${type}`
166
160
  });
167
161
  const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
168
162
  const [[recordId, payloadCid]] = Object.entries(recordCids);
@@ -189,7 +183,8 @@ var Fangorn = class Fangorn {
189
183
  repo: repoName,
190
184
  base: head,
191
185
  records,
192
- deletes
186
+ deletes,
187
+ message: `Batch upload to repo ${repoName}`
193
188
  });
194
189
  const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
195
190
  return {
@@ -212,6 +207,7 @@ var Fangorn = class Fangorn {
212
207
  base: parentCid,
213
208
  records: opts.records ?? [],
214
209
  deletes: opts.deletes,
210
+ message: opts.message,
215
211
  replace: opts.replace
216
212
  });
217
213
  return {
@@ -246,6 +242,7 @@ var Fangorn = class Fangorn {
246
242
  base: oldRoot === ZERO_BYTES32 ? null : CID.parse(this.engine.commitCidFromRootHex(oldRoot)),
247
243
  records: opts.records ?? [],
248
244
  deletes: opts.deletes,
245
+ message: opts.message,
249
246
  replace: opts.replace
250
247
  });
251
248
  const newRoot = rootHexFromCid(commitCid);
@@ -257,7 +254,7 @@ var Fangorn = class Fangorn {
257
254
  records: opts.records?.length ?? 0,
258
255
  deletes: opts.deletes?.length ?? 0
259
256
  },
260
- tx: await registry.prepareUpdate(opts.owner, commitUpdate(await this.engine.getCommit(commitCid))),
257
+ tx: await registry.prepareUpdate(opts.owner, opts.repo, oldRoot, newRoot),
261
258
  recordCids
262
259
  };
263
260
  }
@@ -273,23 +270,16 @@ var Fangorn = class Fangorn {
273
270
  onChainTip: onChainTip.toString()
274
271
  };
275
272
  }
276
- /**
277
- * `push`, signed instead of sent: anyone holding the result can settle it with
278
- * `relayPush`, paying the gas.
279
- */
280
- async signPush(repo, commitCid) {
281
- return this.engine.signCommit(this.getAddress(), repo, CID.parse(commitCid));
282
- }
283
- relayPush(signed) {
284
- return this.engine.relayCommit(signed);
285
- }
286
273
  /** The owner's current on-chain tip for a repo, or null if they have none. */
287
274
  async onChainTip(owner, repo) {
288
275
  const cid = await this.engine.resolveHeadCommit(owner, repo);
289
276
  return cid ? cid.toString() : null;
290
277
  }
291
278
  /**
292
- * A publisher's repo at its latest head, cached against that head.
279
+ * A publisher's repo as this client presents it, cached against its tip:
280
+ * the publisher's latest head, or, under an app, nothing unless the app
281
+ * presents the publisher (provides its storage) and excludes neither it nor
282
+ * the repo.
293
283
  *
294
284
  * Reading a repo walks its whole record tree from the root. The tip is one
295
285
  * cheap contract read and only moves on publish, so it doubles as the cache
@@ -303,7 +293,7 @@ var Fangorn = class Fangorn {
303
293
  */
304
294
  async readRepo(owner, repo) {
305
295
  const key = `${owner.toLowerCase()}/${repo}`;
306
- const tip = await this.headCommit({
296
+ const tip = await this.presentedTip({
307
297
  publisher: owner,
308
298
  repo
309
299
  });
@@ -325,23 +315,36 @@ var Fangorn = class Fangorn {
325
315
  }
326
316
  return entry;
327
317
  }
328
- /** The commit at a repo's head, or null for a repo never written. */
329
- async headCommit(ref) {
330
- const head = await this.ctx.registry.head(ref);
318
+ /** The commit this client presents of a repo, or null for none (see `readRepo`). */
319
+ async presentedTip(ref) {
320
+ const app = this.ctx.appId;
321
+ const registry = this.ctx.registry;
322
+ if (app && !await this.presentsRepo(app, ref)) return null;
323
+ const head = await registry.head(ref);
331
324
  return head === ZERO_BYTES32 ? null : this.engine.commitCidFromRootHex(head);
332
325
  }
326
+ /** Does `app` present `ref`: it presents the publisher, and excludes neither it nor the repo? */
327
+ async presentsRepo(app, ref) {
328
+ const registry = this.ctx.registry;
329
+ const [presents, excluded] = await Promise.all([registry.presents(app, ref.publisher), repoExcluded(registry, app, ref)]);
330
+ return presents && !excluded;
331
+ }
333
332
  /**
334
- * Every (publisher, repo) at its latest head, from one scan of the update log.
335
- * Narrow it with `repo` (every publisher's `docs`) or `owner`, filtered on-chain.
333
+ * Every (publisher, repo) this client's app presents, at its latest head, less
334
+ * what it excludes — the app's directory, from ONE `getLogs` over the update
335
+ * log, kept to the publishers the app presents.
336
336
  *
337
- * ponytail: scans the whole log from `fromBlock`; an indexer's sub-log once
338
- * that is too slow.
337
+ * ponytail: reads every publisher's updates and drops non-members, so it costs
338
+ * what the network writes, not what the app holds. Filter on-chain by the
339
+ * app's members (a `publisher` topic list) once that is too slow.
340
+ * Narrow it with `repo` (every publisher's `docs`) or `owner`, filtered on-chain.
339
341
  */
340
- async repos(opts = {}) {
342
+ async appRepos(opts = {}) {
343
+ const app = this.requireApp("appRepos");
341
344
  const entries = await this.ctx.registry.log({
342
345
  publisher: opts.owner,
343
346
  repo: opts.repo
344
- }, opts.fromBlock ?? this.ctx.config.fromBlock);
347
+ }, opts.fromBlock ?? this.ctx.config.appRegistryFromBlock);
345
348
  const latest = /* @__PURE__ */ new Map();
346
349
  for (const e of entries) latest.set(`${e.publisher.toLowerCase()}/${e.repo}`, {
347
350
  owner: e.publisher,
@@ -349,65 +352,54 @@ var Fangorn = class Fangorn {
349
352
  root: e.head,
350
353
  blockNumber: e.t
351
354
  });
352
- return [...latest.values()];
355
+ const all = [...latest.values()];
356
+ const kept = await Promise.all(all.map((d) => this.presentsRepo(app, {
357
+ publisher: d.owner,
358
+ repo: d.repo
359
+ })));
360
+ return all.filter((_, i) => kept[i]);
353
361
  }
354
362
  /**
355
- * Resolve a repo from its agent card URL alone, and prove the card speaks for it.
363
+ * Resolve an app from its agent card URL alone, and prove the card speaks for it.
356
364
  *
357
- * The card names its repo in the `FANGORN_REPO_EXTENSION` A2A extension, but
358
- * anyone can serve a card that names any repo. So the card is trusted only if
359
- * the repo's `@card` record, which only its publisher can commit, points
365
+ * The card names its app in the `FANGORN_APP_EXTENSION` A2A extension, but
366
+ * anyone can serve a card that names any app. So the card is trusted only if
367
+ * the app's on-chain `agent_uri`, which only the app owner can set, points
360
368
  * back at this exact URL. The comparison is exact string equality, so a
361
369
  * trailing slash or a different host counts as a different card.
370
+ *
371
+ * Doesn't touch this client's app. Pass `appId` to `setAppId` to read under it.
362
372
  */
363
- async discoverCard(cardUrl) {
373
+ async discoverApp(cardUrl) {
364
374
  const res = await fetch(cardUrl, { signal: AbortSignal.timeout(1e4) });
365
375
  if (!res.ok) throw new Error(`agent card ${cardUrl}: HTTP ${String(res.status)}`);
366
376
  const card = await res.json();
367
- const ext = card.capabilities?.extensions?.find((e) => e.uri === FANGORN_REPO_EXTENSION);
368
- if (!ext) throw new Error(`agent card ${cardUrl} has no ${FANGORN_REPO_EXTENSION} extension`);
377
+ const ext = card.capabilities?.extensions?.find((e) => e.uri === FANGORN_APP_EXTENSION);
378
+ if (!ext) throw new Error(`agent card ${cardUrl} has no ${FANGORN_APP_EXTENSION} extension`);
369
379
  const p = ext.params ?? {};
370
- if (typeof p.publisher !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(p.publisher)) throw new Error(`agent card ${cardUrl}: publisher is not an address`);
371
- if (typeof p.repo !== "string" || !p.repo) throw new Error(`agent card ${cardUrl}: repo is not a repo name`);
372
- const registry = this.ctx.config.dataRegistryContractAddress;
373
- if (p.chainId !== this.ctx.config.caip2 || typeof p.dataRegistry !== "string" || p.dataRegistry.toLowerCase() !== registry.toLowerCase()) throw new Error(`agent card ${cardUrl} is for chain ${String(p.chainId)} / DataRegistry ${String(p.dataRegistry)}, not this client's`);
374
- const publisher = p.publisher;
375
- const bound = await this.cardOf(publisher, p.repo);
376
- if (bound !== cardUrl) throw new Error(`agent card ${cardUrl} is not bound to ${publisher}/${p.repo}: its ${CARD_RECORD} record is ${bound ? `"${bound}"` : "unset"}`);
380
+ if (typeof p.appId !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(p.appId)) throw new Error(`agent card ${cardUrl}: appId is not a 32-byte hex string`);
381
+ if (typeof p.fromBlock !== "string" || !/^\d+$/.test(p.fromBlock)) throw new Error(`agent card ${cardUrl}: fromBlock is not a decimal block number`);
382
+ const repos = p.repos ?? p.namespaces ?? [];
383
+ if (!Array.isArray(repos) || !repos.every((n) => typeof n === "string")) throw new Error(`agent card ${cardUrl}: repos is not a list of strings`);
384
+ const apps = this.getAppRegistry();
385
+ if (p.chainId !== this.ctx.config.caip2 || typeof p.appRegistry !== "string" || p.appRegistry.toLowerCase() !== apps.getAddress().toLowerCase()) throw new Error(`agent card ${cardUrl} is for chain ${String(p.chainId)} / AppRegistry ${String(p.appRegistry)}, not this client's`);
386
+ const appId = p.appId;
387
+ const bound = await apps.appAgentUri(appId);
388
+ if (bound !== cardUrl) throw new Error(`agent card ${cardUrl} is not bound to app ${appId}: its on-chain agent_uri is ${bound ? `"${bound}"` : "unset"}`);
377
389
  return {
378
390
  card,
379
- publisher,
380
- repo: p.repo
391
+ appId,
392
+ fromBlock: BigInt(p.fromBlock),
393
+ repos
381
394
  };
382
395
  }
383
- /** The card URL a repo's `@card` record points at, or undefined for none. */
384
- async cardOf(publisher, repo) {
385
- if (!await this.headCommit({
386
- publisher,
387
- repo
388
- })) return void 0;
389
- const url = (await this.engine.readRecord(publisher, repo, CARD_RECORD))?.payload.url;
390
- return typeof url === "string" ? url : void 0;
391
- }
392
396
  /**
393
- * Point one of your repos at its agent card, by committing its `@card` record.
394
- * Returns the transaction, or undefined if it already points there.
397
+ * The app's commit stream as ONE shared, ref-counted subscription (see
398
+ * `AppFeed`). Prefer this over `subscribeApp` anywhere more than one consumer
399
+ * wants the same feed — a server fanning out to connections, say.
395
400
  */
396
- async setCard(repo, cardUrl) {
397
- if (await this.cardOf(this.getAddress(), repo) === cardUrl) return void 0;
398
- const { txHash } = await this.uploadBatch(repo, [{
399
- id: CARD_RECORD,
400
- type: "card",
401
- payload: { url: cardUrl }
402
- }]);
403
- return txHash;
404
- }
405
- /**
406
- * `subscribeAll` as ONE shared, ref-counted subscription (see `CommitFeed`), for
407
- * anywhere more than one consumer wants the same stream.
408
- */
409
- feed(opts = {}) {
410
- this._feed ??= new CommitFeed((signal) => this.subscribeAll({
401
+ appFeed(opts = {}) {
402
+ this._feed ??= new AppFeed((signal) => this.subscribeApp({
411
403
  ...opts,
412
404
  signal
413
405
  }));
@@ -419,6 +411,7 @@ var Fangorn = class Fangorn {
419
411
  cid: cid.toString(),
420
412
  parent: commit.parent?.toString() ?? null,
421
413
  epoch: commit.epoch,
414
+ message: commit.message,
422
415
  root: commit.root.toString()
423
416
  };
424
417
  }
@@ -447,16 +440,18 @@ var Fangorn = class Fangorn {
447
440
  }, opts);
448
441
  }
449
442
  /**
450
- * Stream changes to every repo of every publisher. Narrow it with `repo`
451
- * (every publisher's `docs`) or `owner` (one publisher's repos).
443
+ * Stream changes across the *whole app* — every repo of every publisher it
444
+ * presents, less its exclusions. Narrow it with `repo` (every publisher's `docs`) or
445
+ * `owner` (one publisher's whole app footprint). With no app, every update by
446
+ * anyone: a firehose.
452
447
  */
453
- subscribeAll(opts = {}) {
448
+ subscribeApp(opts = {}) {
454
449
  return this.streamCommits({
455
450
  publisher: opts.owner,
456
451
  repo: opts.repo
457
452
  }, opts);
458
453
  }
459
- /** Shared catch-up-then-live loop behind `subscribe` and `subscribeAll`. */
454
+ /** Shared catch-up-then-live loop behind `subscribe` and `subscribeApp`. */
460
455
  async *streamCommits(filter, opts) {
461
456
  const registry = this.ctx.registry;
462
457
  const seen = /* @__PURE__ */ new Set();
@@ -512,8 +507,8 @@ var Fangorn = class Fangorn {
512
507
  }
513
508
  }
514
509
  /**
515
- * Resolve a log entry into a repo change, or null if the repo's records did
516
- * not change.
510
+ * Resolve a log entry into a repo change, or null if nothing presented
511
+ * changed: the repo slice was untouched, or the app excludes it.
517
512
  *
518
513
  * The commit itself names its repo, which must be the one the entry was
519
514
  * logged under, or the publisher settled a commit for one repo against
@@ -527,6 +522,11 @@ var Fangorn = class Fangorn {
527
522
  async toRepoChange(log, lastHead) {
528
523
  const declared = await this.engine.repoOf(log.head);
529
524
  if (declared !== log.repo) throw new Error(`commit ${log.head} declares repo "${declared}", which does not match the repo it was committed to ("${log.repo}")`);
525
+ const ref = {
526
+ publisher: log.publisher,
527
+ repo: log.repo
528
+ };
529
+ if (this.ctx.appId && !await this.presentsRepo(this.ctx.appId, ref)) return null;
530
530
  const key = `${log.publisher.toLowerCase()}/${log.repo}`;
531
531
  const oldRoot = lastHead.get(key) ?? log.parent;
532
532
  lastHead.set(key, log.head);
@@ -545,26 +545,34 @@ var Fangorn = class Fangorn {
545
545
  getConfig() {
546
546
  return this.ctx.config;
547
547
  }
548
- /** Heads and the update log: the registry of WHITEPAPER_1 §3.2. */
548
+ /** Heads, membership, exclusions and logs: the registry of WHITEPAPER_1 §3.2. */
549
549
  getRegistry() {
550
550
  return this.ctx.registry;
551
551
  }
552
- getSettlementRegistry() {
553
- const address = this.ctx.config.settlementRegistryContractAddress;
554
- if (!address) throw new Error("No SettlementRegistry is deployed on this network.");
555
- this._settlement ??= new SettlementRegistryClient(address, this.ctx.publicClient, this.ctx.walletClient);
556
- return this._settlement;
552
+ /**
553
+ * App management: claiming an app (its storage subscription), terms,
554
+ * invitations and membership, the agent card, and the protocol admin's powers.
555
+ * The owner accepts a publisher (`acceptPublisher()`); from then its uploads
556
+ * bill the app's subscription, and the app presents its repos.
557
+ */
558
+ getAppRegistry() {
559
+ this._apps ??= new AppRegistryClient(this.ctx.config.appRegistryContractAddress, this.ctx.appId, this.ctx.publicClient, this.ctx.walletClient, this.ctx.config.logWindow);
560
+ return this._apps;
561
+ }
562
+ getMembershipRegistry() {
563
+ this._membership ??= new MembershipRegistryClient(this.ctx.config.membershipRegistryContractAddress, this.ctx.publicClient, this.ctx.walletClient);
564
+ return this._membership;
557
565
  }
558
566
  /**
559
- * Register a repo as an ERC-8004 agent from its card, and point the repo at
560
- * the card (`setCard`). The registration file is pinned with this client's storage, so a
567
+ * Register the app as an ERC-8004 agent from its card, and point the app at the card
568
+ * (owner only). The registration file is pinned with this client's storage, so a
561
569
  * browser wallet on signed-URL storage needs no Pinata JWT.
562
570
  *
563
571
  * `update` re-files an agent already minted (its token id) from the card as it is
564
572
  * now, minting nothing. `skipRegister` only binds the card. A binding that already
565
573
  * points at `cardUrl` is left alone.
566
574
  */
567
- async registerAgent(cardUrl, opts) {
575
+ async registerAgent(cardUrl, opts = {}) {
568
576
  const res = await fetch(cardUrl);
569
577
  if (!res.ok) throw new Error(`card at ${cardUrl} returned ${String(res.status)}`);
570
578
  const card = await res.json();
@@ -608,13 +616,43 @@ var Fangorn = class Fangorn {
608
616
  }
609
617
  }
610
618
  }
611
- const txHash = await retryNonce(() => this.setCard(opts.repo, cardUrl));
619
+ const apps = this.getAppRegistry();
620
+ if (await apps.appAgentUri().catch(() => "") === cardUrl) return {
621
+ card: named,
622
+ agentId
623
+ };
624
+ const txHash = await retryNonce(() => apps.setAppAgentUri(cardUrl));
612
625
  return {
613
626
  card: named,
614
627
  agentId,
615
628
  txHash
616
629
  };
617
630
  }
631
+ /** The app this client reads and publishes under, or undefined for none. */
632
+ getAppId() {
633
+ return this.ctx.appId;
634
+ }
635
+ requireApp(what) {
636
+ if (!this.ctx.appId) throw new Error(`${what} needs an app: pass \`appId\` to Fangorn.create() or call setAppId()`);
637
+ return this.ctx.appId;
638
+ }
639
+ /**
640
+ * Point this client at a different app — by name (`"my-app"`) or by app id —
641
+ * or at none, without rebuilding it. Every read, publish and subscription
642
+ * after this call is in the new context.
643
+ *
644
+ * Repo reads are dropped from the cache (its keys are app-agnostic) and
645
+ * the shared `appFeed` is released: a feed watches one app's commit stream, so
646
+ * the next `appFeed()` opens a fresh subscription. Generators already running
647
+ * from `subscribe`/`subscribeApp` keep their original filter until aborted.
648
+ */
649
+ setAppId(nameOrId) {
650
+ const chosen = nonBlank(nameOrId);
651
+ this.ctx.appId = chosen ? toAppId(chosen) : void 0;
652
+ this._apps?.setAppId(this.ctx.appId);
653
+ this.nsCache.clear();
654
+ this._feed = null;
655
+ }
618
656
  getStorage() {
619
657
  if (!this.ctx.metadataStorage) throw new Error("storage is not configured. Pass { pinata: { ... } } or { signedUrl: { ... } } to Fangorn.create()");
620
658
  return this.ctx.metadataStorage;
@@ -625,7 +663,7 @@ var Fangorn = class Fangorn {
625
663
  * picks up the new backend.
626
664
  */
627
665
  setStorage(storage) {
628
- this.ctx.metadataStorage = resolveStorage(storage, this.ctx.walletClient, this.ctx.config);
666
+ this.ctx.metadataStorage = resolveStorage(storage, this.ctx.walletClient, this.ctx.config, () => this.ctx.appId);
629
667
  this._engine = null;
630
668
  }
631
669
  getWalletClient() {
@@ -639,4 +677,4 @@ var Fangorn = class Fangorn {
639
677
  };
640
678
 
641
679
  //#endregion
642
- export { CARD_RECORD, FANGORN_REPO_EXTENSION, Fangorn };
680
+ export { FANGORN_APP_EXTENSION, Fangorn };
package/lib/feed.d.ts CHANGED
@@ -3,17 +3,18 @@ import { RepoChange } from "./fangorn.js";
3
3
  //#region src/feed.d.ts
4
4
 
5
5
  /**
6
- * One shared commit stream, fanned out to many consumers.
6
+ * One shared app-wide commit stream, fanned out to many consumers.
7
7
  *
8
- * `subscribeAll` opens a fresh RPC watch per call. A server that subscribes per
9
- * connection × per tracked repo opens N×M pollers for the *same* topic filter.
10
- * This opens exactly one, ref-counted: it starts with the first listener and
11
- * stops with the last. Consumers filter in memory.
8
+ * `subscribeApp` opens a fresh RPC watch per call. A server that subscribes per
9
+ * connection × per tracked repo opens N×M pollers for what is the *same*
10
+ * app-level topic filter. This opens exactly one, ref-counted: it starts with
11
+ * the first listener and stops with the last. Consumers filter in memory — the
12
+ * events are already narrowed to the app on-chain.
12
13
  *
13
14
  * Not a lens (WHITEPAPER_1 §3.4): a lens computes a view over the stream, this
14
15
  * only shares the stream. fangorn-md's server fans it out to its connections.
15
16
  */
16
- declare class CommitFeed {
17
+ declare class AppFeed {
17
18
  private readonly open;
18
19
  /** Delay before reopening the watch after it fails or ends. */
19
20
  private readonly restartDelayMs;
@@ -31,4 +32,4 @@ declare class CommitFeed {
31
32
  private run;
32
33
  }
33
34
  //#endregion
34
- export { CommitFeed };
35
+ export { AppFeed };
package/lib/feed.js CHANGED
@@ -1,16 +1,17 @@
1
1
  //#region src/feed.ts
2
2
  /**
3
- * One shared commit stream, fanned out to many consumers.
3
+ * One shared app-wide commit stream, fanned out to many consumers.
4
4
  *
5
- * `subscribeAll` opens a fresh RPC watch per call. A server that subscribes per
6
- * connection × per tracked repo opens N×M pollers for the *same* topic filter.
7
- * This opens exactly one, ref-counted: it starts with the first listener and
8
- * stops with the last. Consumers filter in memory.
5
+ * `subscribeApp` opens a fresh RPC watch per call. A server that subscribes per
6
+ * connection × per tracked repo opens N×M pollers for what is the *same*
7
+ * app-level topic filter. This opens exactly one, ref-counted: it starts with
8
+ * the first listener and stops with the last. Consumers filter in memory — the
9
+ * events are already narrowed to the app on-chain.
9
10
  *
10
11
  * Not a lens (WHITEPAPER_1 §3.4): a lens computes a view over the stream, this
11
12
  * only shares the stream. fangorn-md's server fans it out to its connections.
12
13
  */
13
- var CommitFeed = class {
14
+ var AppFeed = class {
14
15
  listeners = /* @__PURE__ */ new Set();
15
16
  abort = null;
16
17
  constructor(open, restartDelayMs = 2e3) {
@@ -64,4 +65,4 @@ var CommitFeed = class {
64
65
  const asError = (err) => err instanceof Error ? err : new Error(String(err));
65
66
 
66
67
  //#endregion
67
- export { CommitFeed };
68
+ export { AppFeed };
@@ -0,0 +1,17 @@
1
+ import { buildAssetGraph, extractMarkdownLinks } from "../../index.js";
2
+
3
+ //#region src/harness/examples/hackmd/build-markdown-graph.ts
4
+ const buildMarkdownGraph = (dir) => {
5
+ return buildAssetGraph(dir, { processors: { ".md": (file) => ({
6
+ tag: "doc",
7
+ payload: { content: file.readText() },
8
+ links: extractMarkdownLinks(file.readText())
9
+ }) } });
10
+ };
11
+ if (import.meta.url === `file://${process.argv[1]}`) {
12
+ const dir = process.argv[2] ?? ".";
13
+ process.stdout.write(JSON.stringify(buildMarkdownGraph(dir), null, 2) + "\n");
14
+ }
15
+
16
+ //#endregion
17
+ export { };
@@ -0,0 +1,58 @@
1
+ import { Stats } from "fs";
2
+
3
+ //#region src/harness/index.d.ts
4
+ interface FileFacade {
5
+ /** The full filename including extension (e.g., "notes.md") */
6
+ name: string;
7
+ /** The filename without extension, used as the default ID (e.g., "notes") */
8
+ nameNoExt: string;
9
+ /** The file extension in lowercase, including the dot (e.g., ".md") */
10
+ ext: string;
11
+ /** The absolute or relative path to the file */
12
+ path: string;
13
+ /** Reads the file and returns its content as a UTF-8 string */
14
+ readText: () => string;
15
+ /** Reads the file and returns its raw Buffer data */
16
+ readBuffer: () => Buffer;
17
+ /** Retrieves file system metadata stats for the file */
18
+ stat: () => Stats;
19
+ }
20
+ interface ProcessorResult {
21
+ /** The entity type/tag for the graph vertex (defaults to "asset") */
22
+ tag?: string;
23
+ /** Custom metadata object attached to the vertex */
24
+ payload?: Record<string, unknown>;
25
+ /** An array of target vertex IDs that this file links to */
26
+ links?: string[];
27
+ }
28
+ type AssetProcessor = (file: FileFacade) => ProcessorResult;
29
+ interface BuildAssetGraphOptions {
30
+ /** A dictionary mapping lowercase file extensions (e.g., ".md") to processor functions */
31
+ processors?: Record<string, AssetProcessor>;
32
+ }
33
+ interface Vertex {
34
+ id: string;
35
+ tag: string;
36
+ payload: Record<string, unknown>;
37
+ }
38
+ interface Edge {
39
+ rel: string;
40
+ from: string;
41
+ to: string;
42
+ }
43
+ interface CommitFileGraph {
44
+ vertices: Vertex[];
45
+ edges: Edge[];
46
+ }
47
+ /**
48
+ * Traverses a directory, parses files based on their extensions,
49
+ * and generates a strictly validated Fangorn-compliant commit graph.
50
+ */
51
+ declare function buildAssetGraph(dir: string, options?: BuildAssetGraphOptions): CommitFileGraph;
52
+ /**
53
+ * Utility helper to scan markdown strings for standard markdown links or wikilinks.
54
+ */
55
+ declare function extractMarkdownLinks(content: string): string[];
56
+ declare const buildMarkdownGraph: (dir: string) => CommitFileGraph;
57
+ //#endregion
58
+ export { AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, Edge, FileFacade, ProcessorResult, Vertex, buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks };