@fangorn-network/sdk 2026.10.20-dev → 2026.10.22-dev

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 (48) hide show
  1. package/README.md +23 -20
  2. package/lib/cli/cli.d.ts +0 -0
  3. package/lib/cli/cli.js +19 -55
  4. package/lib/cli/index.d.ts +2 -2
  5. package/lib/cli/index.js +3 -3
  6. package/lib/config.d.ts +420 -83
  7. package/lib/config.js +13 -5
  8. package/lib/contracts/membership-registry/index.d.ts +1 -1
  9. package/lib/contracts/membership-registry/index.js +1 -1
  10. package/lib/engine/index.d.ts +2 -16
  11. package/lib/engine/index.js +2 -18
  12. package/lib/erc8004.d.ts +56 -0
  13. package/lib/erc8004.js +143 -0
  14. package/lib/fangorn.d.ts +22 -7
  15. package/lib/fangorn.js +69 -8
  16. package/lib/index.d.ts +2 -2
  17. package/lib/index.js +2 -2
  18. package/lib/node_modules/{@jridgewell → .pnpm/@jridgewell_sourcemap-codec@1.5.5/node_modules/@jridgewell}/sourcemap-codec/dist/sourcemap-codec.js +1 -1
  19. package/lib/node_modules/{@vitest → .pnpm/@vitest_expect@4.0.18/node_modules/@vitest}/expect/dist/index.js +8 -8
  20. package/lib/node_modules/{@vitest → .pnpm/@vitest_pretty-format@4.0.18/node_modules/@vitest}/pretty-format/dist/index.js +2 -2
  21. package/lib/node_modules/{@vitest → .pnpm/@vitest_runner@4.0.18/node_modules/@vitest}/runner/dist/chunk-tasks.js +2 -2
  22. package/lib/node_modules/{@vitest → .pnpm/@vitest_runner@4.0.18/node_modules/@vitest}/runner/dist/index.js +4 -4
  23. package/lib/node_modules/{@vitest → .pnpm/@vitest_snapshot@4.0.18/node_modules/@vitest}/snapshot/dist/index.js +4 -4
  24. package/lib/node_modules/{@vitest → .pnpm/@vitest_spy@4.0.18/node_modules/@vitest}/spy/dist/index.js +1 -1
  25. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/chunk-_commonjsHelpers.js +1 -1
  26. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/chunk-pathe.M-eThtNZ.js +1 -1
  27. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/diff.js +3 -3
  28. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/display.js +2 -2
  29. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/error.js +2 -2
  30. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/helpers.js +1 -1
  31. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/serialize.js +1 -1
  32. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/source-map.js +1 -1
  33. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/timers.js +1 -1
  34. package/lib/node_modules/{chai → .pnpm/chai@6.2.2/node_modules/chai}/index.js +1 -1
  35. package/lib/node_modules/{magic-string → .pnpm/magic-string@0.30.21/node_modules/magic-string}/dist/magic-string.es.js +2 -2
  36. package/lib/node_modules/{pathe → .pnpm/pathe@2.0.3/node_modules/pathe}/dist/shared/pathe.M-eThtNZ.js +1 -1
  37. package/lib/node_modules/{tinyrainbow → .pnpm/tinyrainbow@3.0.3/node_modules/tinyrainbow}/dist/index.js +1 -1
  38. 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
  39. 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
  40. 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
  41. 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
  42. package/lib/providers/storage/signed-url.d.ts +4 -4
  43. package/lib/providers/storage/signed-url.js +5 -4
  44. package/lib/test/sdk-suite.js +2 -2
  45. package/lib/test/testbed.d.ts +6107 -5730
  46. package/lib/test/testbed.js +5 -1
  47. package/package.json +75 -89
  48. /package/lib/node_modules/{@vitest → .pnpm/@vitest_runner@4.0.18/node_modules/@vitest}/runner/dist/utils.js +0 -0
package/lib/config.js CHANGED
@@ -22,7 +22,7 @@ function toAppId(nameOrId) {
22
22
  if (!name) throw new Error("App name or id must not be blank.");
23
23
  return /^0x[0-9a-fA-F]{64}$/.test(name) ? name : appId(name);
24
24
  }
25
- const FangornConfig = {
25
+ const ArbitrumSepoliaConfig = {
26
26
  dataRegistryContractAddress: "0x72B5f83526F3893aF9f1eE0f32A27218EA09f8aE",
27
27
  appRegistryContractAddress: "0x55e6209ea1833ceD900989a3b3b22466934E04A5",
28
28
  membershipRegistryContractAddress: "0xDF17030Cd65435C86eb043F31DDACa99E819E347",
@@ -31,7 +31,8 @@ const FangornConfig = {
31
31
  rpcUrl: "https://sepolia-rollup.arbitrum.io/rpc",
32
32
  caip2: 421614,
33
33
  ipfsGateway: "https://ipfs.io",
34
- logWindow: 100000n
34
+ logWindow: 100000n,
35
+ signedUrlWorker: "https://pinata-url-provider.fangorn-0be.workers.dev"
35
36
  };
36
37
  const BaseSepoliaConfig = {
37
38
  dataRegistryContractAddress: "0xE9183f768865dd2Cde5f1B71F8446F0Cd798ebe0",
@@ -42,13 +43,20 @@ const BaseSepoliaConfig = {
42
43
  rpcUrl: "https://base-sepolia-rpc.publicnode.com",
43
44
  caip2: 84532,
44
45
  ipfsGateway: "https://ipfs.io",
45
- logWindow: 10000n
46
+ logWindow: 10000n,
47
+ signedUrlWorker: "https://pinata-url-provider-base.fangorn-0be.workers.dev"
46
48
  };
47
49
  /**
50
+ * The default network: what `Fangorn.create` uses without a `config`, and the CLI
51
+ * without `CHAIN_NAME`. Base Sepolia, which runs the contracts this SDK's ABIs are
52
+ * built from.
53
+ */
54
+ const FangornConfig = BaseSepoliaConfig;
55
+ /**
48
56
  * The networks supported by Fangorn, by the name `CHAIN_NAME` takes.
49
57
  */
50
58
  const SupportedNetworks = {
51
- arbitrumSepolia: FangornConfig,
59
+ arbitrumSepolia: ArbitrumSepoliaConfig,
52
60
  baseSepolia: BaseSepoliaConfig
53
61
  };
54
62
  /**
@@ -62,4 +70,4 @@ function getNetwork(name) {
62
70
  }
63
71
 
64
72
  //#endregion
65
- export { BaseSepoliaConfig, FangornConfig, SupportedNetworks, appId, getNetwork as default, nonBlank, toAppId };
73
+ export { ArbitrumSepoliaConfig, BaseSepoliaConfig, FangornConfig, SupportedNetworks, appId, getNetwork as default, nonBlank, toAppId };
@@ -40,7 +40,7 @@ declare const membershipTokenId: (appId: Hex, holder: Address) => bigint;
40
40
  *
41
41
  * The app owner's half is here (`setPlan`), with the reads every gate needs
42
42
  * (`canRead`, `planOf`, `currentEpoch`) and the two relayed writes (`join`, `claim`),
43
- * which take what a buyer signed and proved, so anyone may submit them; Barliman does.
43
+ * which take what a buyer signed and proved, so anyone may submit them.
44
44
  *
45
45
  * The buyer's half (Semaphore identity, stealth holder, the payment signature, the
46
46
  * group from `Joined` logs, the proof) lives in `@fangorn-network/fetch`: this SDK
@@ -24,7 +24,7 @@ const membershipTokenId = (appId, holder) => BigInt(keccak256(encodeAbiParameter
24
24
  *
25
25
  * The app owner's half is here (`setPlan`), with the reads every gate needs
26
26
  * (`canRead`, `planOf`, `currentEpoch`) and the two relayed writes (`join`, `claim`),
27
- * which take what a buyer signed and proved, so anyone may submit them; Barliman does.
27
+ * which take what a buyer signed and proved, so anyone may submit them.
28
28
  *
29
29
  * The buyer's half (Semaphore identity, stealth holder, the payment signature, the
30
30
  * group from `Joined` logs, the proof) lives in `@fangorn-network/fetch`: this SDK
@@ -20,10 +20,6 @@ interface StoredRecord {
20
20
  type: RecordType;
21
21
  payload: Record<string, unknown>;
22
22
  }
23
- interface RecordSchema {
24
- type: RecordType;
25
- requiredFields: string[];
26
- }
27
23
  /** A decoded commit, γ = (e, parent, root) plus its repo name, message and CAR (see CommitBlock). */
28
24
  type CommitObject = CommitBlock;
29
25
  interface RepoContents {
@@ -36,15 +32,6 @@ interface RepoDiff {
36
32
  /** Ids of records that are gone. */
37
33
  deletes: string[];
38
34
  }
39
- /**
40
- * Per-repo record schemas. Types without a registered schema are
41
- * accepted as-is (permissive by default); register one to require fields.
42
- */
43
- declare class SchemaRegistry {
44
- private schemas;
45
- register(repo: RepoName, schema: RecordSchema): void;
46
- validate(repo: RepoName, type: RecordType, payload: Record<string, unknown>): boolean;
47
- }
48
35
  /**
49
36
  * Upper bound on a repo name's length. The name is stored in every commit
50
37
  * block, so this is just a sanity bound keeping that block small and
@@ -90,7 +77,6 @@ interface CreateCommitOptions {
90
77
  }
91
78
  declare class FangornEngine {
92
79
  private storage;
93
- private schemas;
94
80
  private registry;
95
81
  /**
96
82
  * Local block cache. Written blocks land here immediately; remote blocks
@@ -100,7 +86,7 @@ declare class FangornEngine {
100
86
  private cache;
101
87
  /** Commits whose CAR has already been loaded into the cache. */
102
88
  private loadedCars;
103
- constructor(storage: MetadataStorage, schemas: SchemaRegistry, registry: Registry);
89
+ constructor(storage: MetadataStorage, registry: Registry);
104
90
  /**
105
91
  * Reconstructs the CID a commit's raw digest hex refers to. The contract only
106
92
  * stores the bare 32-byte sha256 digest (see commitStateRoot), so rebuilding
@@ -198,4 +184,4 @@ declare class FangornEngine {
198
184
  readRecord(publisher: Address, repo: RepoName, id: string): Promise<StoredRecord | null>;
199
185
  }
200
186
  //#endregion
201
- export { CommitDiff, CommitObject, CreateCommitOptions, FangornEngine, MAX_REPO_NAME_LENGTH, RecordInput, RecordSchema, RecordType, type Ref, RepoContents, RepoDiff, RepoName, SchemaRegistry, StoredRecord, assertValidRepoName, rootHexFromCid };
187
+ export { CommitDiff, CommitObject, CreateCommitOptions, FangornEngine, MAX_REPO_NAME_LENGTH, RecordInput, RecordType, type Ref, RepoContents, RepoDiff, RepoName, StoredRecord, assertValidRepoName, rootHexFromCid };
@@ -7,20 +7,6 @@ import { sha256 } from "multiformats/hashes/sha2";
7
7
  import * as Digest from "multiformats/hashes/digest";
8
8
 
9
9
  //#region src/engine/index.ts
10
- /**
11
- * Per-repo record schemas. Types without a registered schema are
12
- * accepted as-is (permissive by default); register one to require fields.
13
- */
14
- var SchemaRegistry = class {
15
- schemas = /* @__PURE__ */ new Map();
16
- register(repo, schema) {
17
- this.schemas.set(`${repo}|${schema.type}`, schema);
18
- }
19
- validate(repo, type, payload) {
20
- const schema = this.schemas.get(`${repo}|${type}`);
21
- return !schema || schema.requiredFields.every((field) => field in payload);
22
- }
23
- };
24
10
  const ZERO_BYTES32 = ZERO_HEAD;
25
11
  /**
26
12
  * Upper bound on a repo name's length. The name is stored in every commit
@@ -52,9 +38,8 @@ var FangornEngine = class {
52
38
  cache = /* @__PURE__ */ new Map();
53
39
  /** Commits whose CAR has already been loaded into the cache. */
54
40
  loadedCars = /* @__PURE__ */ new Set();
55
- constructor(storage, schemas, registry) {
41
+ constructor(storage, registry) {
56
42
  this.storage = storage;
57
- this.schemas = schemas;
58
43
  this.registry = registry;
59
44
  }
60
45
  /**
@@ -165,7 +150,6 @@ var FangornEngine = class {
165
150
  const id = r.id ?? randomUUID();
166
151
  assertValidRecordId(id);
167
152
  if (id in recordCids) throw new Error(`record id ${id} staged twice`);
168
- if (!this.schemas.validate(repo, r.type, r.payload)) throw new Error(`Schema violation for record type [${r.type}] in repo [${repo}]`);
169
153
  const block = await encodeBlock({
170
154
  id,
171
155
  type: r.type,
@@ -333,4 +317,4 @@ var FangornEngine = class {
333
317
  };
334
318
 
335
319
  //#endregion
336
- export { FangornEngine, MAX_REPO_NAME_LENGTH, SchemaRegistry, assertValidRepoName, rootHexFromCid };
320
+ export { FangornEngine, MAX_REPO_NAME_LENGTH, assertValidRepoName, rootHexFromCid };
@@ -0,0 +1,56 @@
1
+ import { MetadataStorage } from "./providers/storage/types.js";
2
+ import { Address, Chain, Hex, PublicClient, WalletClient } from "viem";
3
+
4
+ //#region src/erc8004.d.ts
5
+ /** The ERC-8004 identity registry by chain id */
6
+ declare const IDENTITY_REGISTRY: Record<number, Address>;
7
+ interface AgentCard {
8
+ name: string;
9
+ description: string;
10
+ skills?: {
11
+ tags?: unknown;
12
+ }[];
13
+ }
14
+ /**
15
+ * Get the agent card URL based on the access worker if defined, else return the carUrl
16
+ * Both params are optional, but at least one must be defined.
17
+ *
18
+ * Agent cards must live at accessWorker/.well-known/agent-card.json
19
+ *
20
+ * @param cardUrl The cardUrl (passthrough when defined)
21
+ * @param accessWorker The (optional) access worker url
22
+ * @returns
23
+ */
24
+ declare function agentCardUrl(cardUrl?: string, accessWorker?: string): string;
25
+ declare function mcpTools(endpoint: string): Promise<string[] | undefined>;
26
+ /**
27
+ * Build a registration file
28
+ * Since it desfines its own agent id,
29
+ * first registration mints without an agent URI and must be set retroactively.
30
+ */
31
+ declare function registrationFile(opts: {
32
+ cardUrl: string;
33
+ card: AgentCard;
34
+ chainId: number;
35
+ agentId: bigint;
36
+ mcp?: {
37
+ endpoint: string;
38
+ tools?: string[];
39
+ };
40
+ now?: number;
41
+ }): Record<string, unknown>;
42
+ /** `84532:10323` or `10323` → the token id, refusing an agent on another chain. */
43
+ declare function parseAgentId(id: string, chainId: number): bigint;
44
+ interface Erc8004Clients {
45
+ chain: Chain;
46
+ publicClient: PublicClient;
47
+ walletClient: WalletClient;
48
+ storage: Pick<MetadataStorage, "put">;
49
+ }
50
+ declare function retryNonce<T>(f: () => Promise<T>, tries?: number): Promise<T>;
51
+ /** Pin `file` and point agent `agentId` at it. */
52
+ declare function setAgentFile(c: Erc8004Clients, agentId: bigint, file: unknown): Promise<Hex>;
53
+ /** Mint an agent with no URI yet, and return its id. */
54
+ declare function mintAgent(c: Erc8004Clients): Promise<bigint>;
55
+ //#endregion
56
+ export { AgentCard, Erc8004Clients, IDENTITY_REGISTRY, agentCardUrl, mcpTools, mintAgent, parseAgentId, registrationFile, retryNonce, setAgentFile };
package/lib/erc8004.js ADDED
@@ -0,0 +1,143 @@
1
+ import { parseAbi, parseEventLogs } from "viem";
2
+
3
+ //#region src/erc8004.ts
4
+ /** The ERC-8004 identity registry by chain id */
5
+ const IDENTITY_REGISTRY = {
6
+ 84532: "0x8004A818BFB912233c491871b3d84c89A494BD9e",
7
+ 421614: "0x8004A818BFB912233c491871b3d84c89A494BD9e"
8
+ };
9
+ const ABI = parseAbi([
10
+ "function register(string agentURI, (string metadataKey, bytes metadataValue)[] metadata) returns (uint256 agentId)",
11
+ "function setAgentURI(uint256 agentId, string newURI)",
12
+ "event Registered(uint256 indexed agentId, string agentURI, address indexed owner)"
13
+ ]);
14
+ /**
15
+ * Get the agent card URL based on the access worker if defined, else return the carUrl
16
+ * Both params are optional, but at least one must be defined.
17
+ *
18
+ * Agent cards must live at accessWorker/.well-known/agent-card.json
19
+ *
20
+ * @param cardUrl The cardUrl (passthrough when defined)
21
+ * @param accessWorker The (optional) access worker url
22
+ * @returns
23
+ */
24
+ function agentCardUrl(cardUrl, accessWorker) {
25
+ if (cardUrl) return cardUrl;
26
+ if (!accessWorker) throw new Error("No card URL. Pass one, or pass --access-worker <url>.");
27
+ return `${accessWorker.replace(/\/$/, "")}/.well-known/agent-card.json`;
28
+ }
29
+ async function mcpTools(endpoint) {
30
+ try {
31
+ const res = await fetch(endpoint, {
32
+ method: "POST",
33
+ headers: {
34
+ "Content-Type": "application/json",
35
+ Accept: "application/json, text/event-stream"
36
+ },
37
+ body: JSON.stringify({
38
+ jsonrpc: "2.0",
39
+ id: 1,
40
+ method: "tools/list"
41
+ }),
42
+ signal: AbortSignal.timeout(1e4)
43
+ });
44
+ if (!res.ok) return void 0;
45
+ const text = await res.text();
46
+ const body = text.split("\n").find((l) => l.startsWith("data: "))?.slice(6) ?? text;
47
+ const names = (JSON.parse(body).result?.tools ?? []).map((t) => t.name).filter((n) => typeof n === "string");
48
+ return names.length ? names : void 0;
49
+ } catch {
50
+ return;
51
+ }
52
+ }
53
+ /**
54
+ * Build a registration file
55
+ * Since it desfines its own agent id,
56
+ * first registration mints without an agent URI and must be set retroactively.
57
+ */
58
+ function registrationFile(opts) {
59
+ const { cardUrl, card, chainId, agentId, mcp } = opts;
60
+ const tags = [...new Set((card.skills ?? []).flatMap((s) => Array.isArray(s.tags) ? s.tags : []).filter((t) => typeof t === "string"))];
61
+ const services = [{
62
+ name: "A2A",
63
+ endpoint: cardUrl,
64
+ version: "0.30",
65
+ ...tags.length && { a2aSkills: tags }
66
+ }];
67
+ if (mcp) services.push({
68
+ name: "MCP",
69
+ endpoint: mcp.endpoint,
70
+ version: "2025-06-18",
71
+ ...mcp.tools && { mcpTools: mcp.tools }
72
+ });
73
+ return {
74
+ type: "https://eips.ethereum.org/EIPS/eip-8004#registration-v1",
75
+ name: card.name,
76
+ description: card.description,
77
+ services,
78
+ registrations: [{
79
+ agentId: Number(agentId),
80
+ agentRegistry: `eip155:${String(chainId)}:${IDENTITY_REGISTRY[chainId]}`
81
+ }],
82
+ supportedTrust: ["reputation"],
83
+ active: true,
84
+ x402Support: card.skills?.some((s) => Array.isArray(s.tags) && s.tags.includes("x402")) ?? false,
85
+ updatedAt: opts.now ?? Math.floor(Date.now() / 1e3)
86
+ };
87
+ }
88
+ /** `84532:10323` or `10323` → the token id, refusing an agent on another chain. */
89
+ function parseAgentId(id, chainId) {
90
+ const m = /^(?:(\d+):)?(\d+)$/.exec(id.trim());
91
+ if (!m) throw new Error(`not an agent id: ${JSON.stringify(id)} (expected <chainId>:<tokenId>, e.g. 84532:10323)`);
92
+ if (m[1] && Number(m[1]) !== chainId) throw new Error(`agent ${id} is on chain ${m[1]}, but the CLI is configured for ${String(chainId)}`);
93
+ return BigInt(m[2]);
94
+ }
95
+ async function retryNonce(f, tries = 4) {
96
+ for (let i = 0;; i++) try {
97
+ return await f();
98
+ } catch (e) {
99
+ if (i >= tries - 1 || !/underpriced|nonce too low|nonce has already been used|already known/i.test(e.message)) throw e;
100
+ await new Promise((ok) => setTimeout(ok, 3e3 * (i + 1)));
101
+ }
102
+ }
103
+ function registry(chain) {
104
+ const address = IDENTITY_REGISTRY[chain.id];
105
+ if (!address) throw new Error(`no ERC-8004 identity registry known for chain ${String(chain.id)}`);
106
+ return address;
107
+ }
108
+ /** Pin `file` and point agent `agentId` at it. */
109
+ async function setAgentFile(c, agentId, file) {
110
+ const cid = await c.storage.put(file, { name: "agent-registration.json" });
111
+ const hash = await c.walletClient.writeContract({
112
+ address: registry(c.chain),
113
+ abi: ABI,
114
+ functionName: "setAgentURI",
115
+ args: [agentId, `ipfs://${cid}`],
116
+ chain: c.chain,
117
+ account: c.walletClient.account ?? null
118
+ });
119
+ await c.publicClient.waitForTransactionReceipt({ hash });
120
+ return hash;
121
+ }
122
+ /** Mint an agent with no URI yet, and return its id. */
123
+ async function mintAgent(c) {
124
+ const address = registry(c.chain);
125
+ const hash = await c.walletClient.writeContract({
126
+ address,
127
+ abi: ABI,
128
+ functionName: "register",
129
+ args: ["", []],
130
+ chain: c.chain,
131
+ account: c.walletClient.account ?? null
132
+ });
133
+ const minted = parseEventLogs({
134
+ abi: ABI,
135
+ eventName: "Registered",
136
+ logs: (await c.publicClient.waitForTransactionReceipt({ hash })).logs
137
+ }).find((l) => l.address.toLowerCase() === address.toLowerCase());
138
+ if (!minted) throw new Error(`register ${hash} confirmed with no Registered event`);
139
+ return minted.args.agentId;
140
+ }
141
+
142
+ //#endregion
143
+ export { IDENTITY_REGISTRY, agentCardUrl, mcpTools, mintAgent, parseAgentId, registrationFile, retryNonce, setAgentFile };
package/lib/fangorn.d.ts CHANGED
@@ -5,11 +5,11 @@ import { MembershipRegistryClient } from "./contracts/membership-registry/index.
5
5
  import "./contracts/index.js";
6
6
  import { Registry } from "./registry.js";
7
7
  import { MetadataStorage } from "./providers/storage/types.js";
8
- import { CommitDiff, FangornEngine, RecordInput, RepoContents, RepoDiff, SchemaRegistry } from "./engine/index.js";
8
+ import { CommitDiff, FangornEngine, RecordInput, RepoContents, RepoDiff } from "./engine/index.js";
9
+ import { AgentCard as AgentCard$1 } from "./erc8004.js";
9
10
  import { FangornCreateOptions, StorageConfig } from "./types/index.js";
10
11
  import { AppFeed } from "./feed.js";
11
- import * as viem0 from "viem";
12
- import { Hex, WalletClient } from "viem";
12
+ import { Hash, Hex, WalletClient } from "viem";
13
13
  import { CID } from "multiformats/cid";
14
14
 
15
15
  //#region src/fangorn.d.ts
@@ -61,7 +61,6 @@ interface AgentCard {
61
61
  declare class Fangorn {
62
62
  private readonly ctx;
63
63
  private _engine;
64
- private readonly _schemas;
65
64
  private _feed;
66
65
  private _apps;
67
66
  private _membership;
@@ -72,8 +71,6 @@ declare class Fangorn {
72
71
  private readonly nsCache;
73
72
  private constructor();
74
73
  get engine(): FangornEngine;
75
- /** Per-repo record schemas. Unregistered types are accepted as-is. */
76
- get schemas(): SchemaRegistry;
77
74
  /**
78
75
  * Static creation of a new Fangorn client
79
76
  *
@@ -87,7 +84,7 @@ declare class Fangorn {
87
84
  * head still names them as history.
88
85
  */
89
86
  reset(repo: string): Promise<{
90
- txHash: viem0.Hash;
87
+ txHash: Hash;
91
88
  onChainTip: CID;
92
89
  }>;
93
90
  /** Stage records into one commit on top of `base`. */
@@ -320,6 +317,24 @@ declare class Fangorn {
320
317
  */
321
318
  getAppRegistry(): AppRegistryClient;
322
319
  getMembershipRegistry(): MembershipRegistryClient;
320
+ /**
321
+ * Register the app as an ERC-8004 agent from its card, and point the app at the card
322
+ * (owner only). The registration file is pinned with this client's storage, so a
323
+ * browser wallet on signed-URL storage needs no Pinata JWT.
324
+ *
325
+ * `update` re-files an agent already minted (its token id) from the card as it is
326
+ * now, minting nothing. `skipRegister` only binds the card. A binding that already
327
+ * points at `cardUrl` is left alone.
328
+ */
329
+ registerAgent(cardUrl: string, opts?: {
330
+ mcp?: string;
331
+ update?: bigint;
332
+ skipRegister?: boolean;
333
+ }): Promise<{
334
+ card: AgentCard$1;
335
+ agentId?: bigint;
336
+ txHash?: Hash;
337
+ }>;
323
338
  /** The app this client reads and publishes under, or undefined for none. */
324
339
  getAppId(): Hex | undefined;
325
340
  private requireApp;
package/lib/fangorn.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { FangornConfig, nonBlank, toAppId } from "./config.js";
2
+ import { mcpTools, mintAgent, registrationFile, retryNonce, setAgentFile } from "./erc8004.js";
2
3
  import { SignedUrlBackend } from "./providers/storage/signed-url.js";
3
4
  import { PinataBackend } from "./providers/storage/pinata.js";
4
5
  import { AppRegistryClient } from "./contracts/app-registry/index.js";
5
6
  import { MembershipRegistryClient } from "./contracts/membership-registry/index.js";
6
7
  import "./contracts/index.js";
7
8
  import { ChainRegistry, ZERO_HEAD, repoExcluded } from "./registry.js";
8
- import { FangornEngine, SchemaRegistry, assertValidRepoName, rootHexFromCid } from "./engine/index.js";
9
+ import { FangornEngine, assertValidRepoName, rootHexFromCid } from "./engine/index.js";
9
10
  import { AppFeed } from "./feed.js";
10
11
  import { createPublicClient, createWalletClient, http } from "viem";
11
12
  import { privateKeyToAccount } from "viem/accounts";
@@ -29,7 +30,7 @@ function resolveStorage(storage, walletClient, config, getAppId) {
29
30
  if (!storage) return void 0;
30
31
  if ("backend" in storage) return storage.backend;
31
32
  if ("pinata" in storage) return new PinataBackend(storage.pinata.jwt, storage.pinata.gateway);
32
- if ("signedUrl" in storage) return new SignedUrlBackend(storage.signedUrl.workerUrl, walletSigner(walletClient), storage.signedUrl.gateway ?? config.ipfsGateway, getAppId);
33
+ if ("signedUrl" in storage) return new SignedUrlBackend(nonBlank(storage.signedUrl.workerUrl) ?? config.signedUrlWorker, walletSigner(walletClient), storage.signedUrl.gateway ?? config.ipfsGateway, getAppId);
33
34
  throw new Error(`Invalid storage config: must be { pinata: … }, { signedUrl: … } or { backend: … }, got ${JSON.stringify(storage)}`);
34
35
  }
35
36
  /** The A2A extension a Fangorn app's agent card carries: it names the app the card speaks for. */
@@ -37,7 +38,6 @@ const FANGORN_APP_EXTENSION = "https://fangorn.network/a2a/app/v1";
37
38
  var Fangorn = class Fangorn {
38
39
  ctx;
39
40
  _engine = null;
40
- _schemas = new SchemaRegistry();
41
41
  _feed = null;
42
42
  _apps = null;
43
43
  _membership = null;
@@ -51,13 +51,9 @@ var Fangorn = class Fangorn {
51
51
  }
52
52
  get engine() {
53
53
  if (!this.ctx.metadataStorage) throw new Error("fangorn.engine requires storage configurations. Pass { pinata: { ... } } to Fangorn.create()");
54
- this._engine ??= new FangornEngine(this.ctx.metadataStorage, this._schemas, this.ctx.registry);
54
+ this._engine ??= new FangornEngine(this.ctx.metadataStorage, this.ctx.registry);
55
55
  return this._engine;
56
56
  }
57
- /** Per-repo record schemas. Unregistered types are accepted as-is. */
58
- get schemas() {
59
- return this._schemas;
60
- }
61
57
  /**
62
58
  * Static creation of a new Fangorn client
63
59
  *
@@ -567,6 +563,71 @@ var Fangorn = class Fangorn {
567
563
  this._membership ??= new MembershipRegistryClient(this.ctx.config.membershipRegistryContractAddress, this.ctx.publicClient, this.ctx.walletClient);
568
564
  return this._membership;
569
565
  }
566
+ /**
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
569
+ * browser wallet on signed-URL storage needs no Pinata JWT.
570
+ *
571
+ * `update` re-files an agent already minted (its token id) from the card as it is
572
+ * now, minting nothing. `skipRegister` only binds the card. A binding that already
573
+ * points at `cardUrl` is left alone.
574
+ */
575
+ async registerAgent(cardUrl, opts = {}) {
576
+ const res = await fetch(cardUrl);
577
+ if (!res.ok) throw new Error(`card at ${cardUrl} returned ${String(res.status)}`);
578
+ const card = await res.json();
579
+ if (!card.name || !card.description) throw new Error("card is missing `name` or `description`");
580
+ const named = {
581
+ ...card,
582
+ name: card.name,
583
+ description: card.description
584
+ };
585
+ let agentId;
586
+ if (!opts.skipRegister) {
587
+ const c = {
588
+ chain: this.ctx.config.chain,
589
+ publicClient: this.ctx.publicClient,
590
+ walletClient: this.ctx.walletClient,
591
+ storage: this.getStorage()
592
+ };
593
+ const chainId = this.ctx.config.caip2;
594
+ const mcp = opts.mcp ? {
595
+ endpoint: opts.mcp,
596
+ tools: await mcpTools(opts.mcp)
597
+ } : void 0;
598
+ const file = (id) => registrationFile({
599
+ cardUrl,
600
+ card: named,
601
+ chainId,
602
+ agentId: id,
603
+ mcp
604
+ });
605
+ const { update } = opts;
606
+ if (update !== void 0) {
607
+ agentId = update;
608
+ await retryNonce(() => setAgentFile(c, update, file(update)));
609
+ } else {
610
+ const id = await mintAgent(c);
611
+ agentId = id;
612
+ try {
613
+ await retryNonce(() => setAgentFile(c, id, file(id)));
614
+ } catch (e) {
615
+ throw Object.assign(/* @__PURE__ */ new Error(`agent ${String(chainId)}:${String(agentId)} was minted but its registration file was not set (${e.message}); finish it with registerAgent(cardUrl, { update: ${String(agentId)}n })`), { agentId });
616
+ }
617
+ }
618
+ }
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));
625
+ return {
626
+ card: named,
627
+ agentId,
628
+ txHash
629
+ };
630
+ }
570
631
  /** The app this client reads and publishes under, or undefined for none. */
571
632
  getAppId() {
572
633
  return this.ctx.appId;
package/lib/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { AppConfig, BaseSepoliaConfig, FangornConfig, SupportedNetworks, appId, nonBlank, toAppId } from "./config.js";
1
+ import { AppConfig, ArbitrumSepoliaConfig, BaseSepoliaConfig, FangornConfig, SupportedNetworks, appId, nonBlank, toAppId } from "./config.js";
2
2
  import { APP_REGISTRY_ABI } from "./contracts/app-registry/abi.js";
3
3
  import { PublisherStatus } from "./contracts/types.js";
4
4
  import { PreparedTx } from "./contracts/write.js";
@@ -17,4 +17,4 @@ import { AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, Edge, FileFaca
17
17
  import { PinataBackend } from "./providers/storage/pinata.js";
18
18
  import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend, SignedUrlSigner } from "./providers/storage/signed-url.js";
19
19
  import { MAX_UPLOAD_ATTEMPTS, deserialize, fetchRawByCid, isTransientUpload, retrieveByCid, serialize, withUploadRetry } from "./providers/storage/utils.js";
20
- export { APP_REGISTRY_ABI, AccessRequest, AccessSigner, AgentCard, AppAccess, AppAgentLog, AppConfig, AppFeed, AppRegistryClient, AssetProcessor, BaseSepoliaConfig, BuildAssetGraphOptions, ChainRegistry, ChainRegistryConfig, ClaimArgs, CommitFileGraph, DATA_REGISTRY_ABI, DEFAULT_SIGNED_URL_WORKER, DecryptHandleParams, EPOCH_SECONDS, Edge, EncryptAndUploadParams, Exclusion, FANGORN_APP_EXTENSION, Fangorn, FangornConfig, FangornContext, FangornCreateOptions, FileFacade, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, Gadget, HandleFieldInput, JoinArgs, LogFilter, MAX_UPLOAD_ATTEMPTS, MEMBERSHIP_REGISTRY_ABI, MembershipPayment, MembershipRegistryClient, PinataBackend, PreparedTx, ProcessorResult, PublisherStatus, Registry, RepoChange, RepoRef, SignedUrlBackend, SignedUrlSigner, StorageConfig, SubscribeOptions, SupportedNetworks, UpdateEntry, Vertex, X25519_PUBKEY_LENGTH, ZERO_HEAD, accessMessageHash, appId, buildAccessRequest, buildAssetGraph, buildMarkdownGraph, covers, decryptHandle, deserialize, encryptAndUpload, epochOf, exclusionId, extractMarkdownLinks, fetchRawByCid, isTransientUpload, joinNonce, membershipScope, membershipTokenId, nonBlank, repoExcluded, repoId, retrieveByCid, seal, sealSelf, serialize, sha256Hex, toAppId, unseal, unsealSelf, withUploadRetry };
20
+ export { APP_REGISTRY_ABI, AccessRequest, AccessSigner, AgentCard, AppAccess, AppAgentLog, AppConfig, AppFeed, AppRegistryClient, ArbitrumSepoliaConfig, AssetProcessor, BaseSepoliaConfig, BuildAssetGraphOptions, ChainRegistry, ChainRegistryConfig, ClaimArgs, CommitFileGraph, DATA_REGISTRY_ABI, DEFAULT_SIGNED_URL_WORKER, DecryptHandleParams, EPOCH_SECONDS, Edge, EncryptAndUploadParams, Exclusion, FANGORN_APP_EXTENSION, Fangorn, FangornConfig, FangornContext, FangornCreateOptions, FileFacade, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, Gadget, HandleFieldInput, JoinArgs, LogFilter, MAX_UPLOAD_ATTEMPTS, MEMBERSHIP_REGISTRY_ABI, MembershipPayment, MembershipRegistryClient, PinataBackend, PreparedTx, ProcessorResult, PublisherStatus, Registry, RepoChange, RepoRef, SignedUrlBackend, SignedUrlSigner, StorageConfig, SubscribeOptions, SupportedNetworks, UpdateEntry, Vertex, X25519_PUBKEY_LENGTH, ZERO_HEAD, accessMessageHash, appId, buildAccessRequest, buildAssetGraph, buildMarkdownGraph, covers, decryptHandle, deserialize, encryptAndUpload, epochOf, exclusionId, extractMarkdownLinks, fetchRawByCid, isTransientUpload, joinNonce, membershipScope, membershipTokenId, nonBlank, repoExcluded, repoId, retrieveByCid, seal, sealSelf, serialize, sha256Hex, toAppId, unseal, unsealSelf, withUploadRetry };
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { BaseSepoliaConfig, FangornConfig, SupportedNetworks, appId, nonBlank, toAppId } from "./config.js";
1
+ import { ArbitrumSepoliaConfig, BaseSepoliaConfig, FangornConfig, SupportedNetworks, appId, nonBlank, toAppId } from "./config.js";
2
2
  import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend } from "./providers/storage/signed-url.js";
3
3
  import { MAX_UPLOAD_ATTEMPTS, deserialize, fetchRawByCid, isTransientUpload, retrieveByCid, serialize, withUploadRetry } from "./providers/storage/utils.js";
4
4
  import { PinataBackend } from "./providers/storage/pinata.js";
@@ -16,4 +16,4 @@ import { FANGORN_APP_EXTENSION, Fangorn } from "./fangorn.js";
16
16
  import { buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks } from "./harness/index.js";
17
17
  import { GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, X25519_PUBKEY_LENGTH, accessMessageHash, buildAccessRequest, decryptHandle, encryptAndUpload, seal, sealSelf, sha256Hex, unseal, unsealSelf } from "./crypto/encryption.js";
18
18
 
19
- export { APP_REGISTRY_ABI, AppFeed, AppRegistryClient, BaseSepoliaConfig, ChainRegistry, DATA_REGISTRY_ABI, DEFAULT_SIGNED_URL_WORKER, EPOCH_SECONDS, FANGORN_APP_EXTENSION, Fangorn, FangornConfig, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, MAX_UPLOAD_ATTEMPTS, MEMBERSHIP_REGISTRY_ABI, MembershipRegistryClient, PinataBackend, PublisherStatus, SignedUrlBackend, SupportedNetworks, X25519_PUBKEY_LENGTH, ZERO_HEAD, accessMessageHash, appId, buildAccessRequest, buildAssetGraph, buildMarkdownGraph, covers, decryptHandle, deserialize, encryptAndUpload, epochOf, exclusionId, extractMarkdownLinks, fetchRawByCid, isTransientUpload, joinNonce, membershipScope, membershipTokenId, nonBlank, repoExcluded, repoId, retrieveByCid, seal, sealSelf, serialize, sha256Hex, toAppId, unseal, unsealSelf, withUploadRetry };
19
+ export { APP_REGISTRY_ABI, AppFeed, AppRegistryClient, ArbitrumSepoliaConfig, BaseSepoliaConfig, ChainRegistry, DATA_REGISTRY_ABI, DEFAULT_SIGNED_URL_WORKER, EPOCH_SECONDS, FANGORN_APP_EXTENSION, Fangorn, FangornConfig, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, MAX_UPLOAD_ATTEMPTS, MEMBERSHIP_REGISTRY_ABI, MembershipRegistryClient, PinataBackend, PublisherStatus, SignedUrlBackend, SupportedNetworks, X25519_PUBKEY_LENGTH, ZERO_HEAD, accessMessageHash, appId, buildAccessRequest, buildAssetGraph, buildMarkdownGraph, covers, decryptHandle, deserialize, encryptAndUpload, epochOf, exclusionId, extractMarkdownLinks, fetchRawByCid, isTransientUpload, joinNonce, membershipScope, membershipTokenId, nonBlank, repoExcluded, repoId, retrieveByCid, seal, sealSelf, serialize, sha256Hex, toAppId, unseal, unsealSelf, withUploadRetry };
@@ -1,4 +1,4 @@
1
- //#region node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
1
+ //#region node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
2
2
  var comma = ",".charCodeAt(0);
3
3
  var semicolon = ";".charCodeAt(0);
4
4
  var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
@@ -1,12 +1,12 @@
1
- import { C } from "../../../tinyrainbow/dist/index.js";
2
- import { stringify } from "../../utils/dist/display.js";
3
- import { assertTypes, getType, isObject, noop } from "../../utils/dist/helpers.js";
4
- import { diff, printDiffOrStringify } from "../../utils/dist/diff.js";
5
- import { isMockFunction } from "../../spy/dist/index.js";
6
- import { processError } from "../../utils/dist/error.js";
7
- import { use, utils_exports } from "../../../chai/index.js";
1
+ import { C } from "../../../../../tinyrainbow@3.0.3/node_modules/tinyrainbow/dist/index.js";
2
+ import { stringify } from "../../../../../@vitest_utils@4.0.18/node_modules/@vitest/utils/dist/display.js";
3
+ import { assertTypes, getType, isObject, noop } from "../../../../../@vitest_utils@4.0.18/node_modules/@vitest/utils/dist/helpers.js";
4
+ import { diff, printDiffOrStringify } from "../../../../../@vitest_utils@4.0.18/node_modules/@vitest/utils/dist/diff.js";
5
+ import { isMockFunction } from "../../../../../@vitest_spy@4.0.18/node_modules/@vitest/spy/dist/index.js";
6
+ import { processError } from "../../../../../@vitest_utils@4.0.18/node_modules/@vitest/utils/dist/error.js";
7
+ import { use, utils_exports } from "../../../../../chai@6.2.2/node_modules/chai/index.js";
8
8
 
9
- //#region node_modules/@vitest/expect/dist/index.js
9
+ //#region node_modules/.pnpm/@vitest+expect@4.0.18/node_modules/@vitest/expect/dist/index.js
10
10
  const MATCHERS_OBJECT = Symbol.for("matchers-object");
11
11
  const JEST_MATCHERS_OBJECT = Symbol.for("$$jest-matchers-object");
12
12
  const GLOBAL_EXPECT = Symbol.for("expect-global");
@@ -1,6 +1,6 @@
1
- import { C } from "../../../tinyrainbow/dist/index.js";
1
+ import { C } from "../../../../../tinyrainbow@3.0.3/node_modules/tinyrainbow/dist/index.js";
2
2
 
3
- //#region node_modules/@vitest/pretty-format/dist/index.js
3
+ //#region node_modules/.pnpm/@vitest+pretty-format@4.0.18/node_modules/@vitest/pretty-format/dist/index.js
4
4
  function _mergeNamespaces(n, m) {
5
5
  m.forEach(function(e) {
6
6
  e && typeof e !== "string" && !Array.isArray(e) && Object.keys(e).forEach(function(k) {
@@ -1,6 +1,6 @@
1
- import { parseSingleStack } from "../../utils/dist/source-map.js";
1
+ import { parseSingleStack } from "../../../../../@vitest_utils@4.0.18/node_modules/@vitest/utils/dist/source-map.js";
2
2
 
3
- //#region node_modules/@vitest/runner/dist/chunk-tasks.js
3
+ //#region node_modules/.pnpm/@vitest+runner@4.0.18/node_modules/@vitest/runner/dist/chunk-tasks.js
4
4
  function createChainable(keys, fn) {
5
5
  function create(context) {
6
6
  const chain$1 = function(...args) {
@@ -1,9 +1,9 @@
1
- import { format, formatRegExp, objDisplay } from "../../utils/dist/display.js";
2
- import { assertTypes, createDefer, isNegativeNaN, isObject, objectAttr, toArray } from "../../utils/dist/helpers.js";
3
- import { getSafeTimers } from "../../utils/dist/timers.js";
1
+ import { format, formatRegExp, objDisplay } from "../../../../../@vitest_utils@4.0.18/node_modules/@vitest/utils/dist/display.js";
2
+ import { assertTypes, createDefer, isNegativeNaN, isObject, objectAttr, toArray } from "../../../../../@vitest_utils@4.0.18/node_modules/@vitest/utils/dist/helpers.js";
3
+ import { getSafeTimers } from "../../../../../@vitest_utils@4.0.18/node_modules/@vitest/utils/dist/timers.js";
4
4
  import { createChainable, createTaskName, findTestFileStackTrace } from "./chunk-tasks.js";
5
5
 
6
- //#region node_modules/@vitest/runner/dist/index.js
6
+ //#region node_modules/.pnpm/@vitest+runner@4.0.18/node_modules/@vitest/runner/dist/index.js
7
7
  var PendingError = class extends Error {
8
8
  code = "VITEST_PENDING";
9
9
  taskId;