@fangorn-network/sdk 0.1.0-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.
- package/LICENSE.md +20 -0
- package/README.md +80 -0
- package/lib/cli/cli.d.ts +2 -0
- package/lib/cli/cli.js +571 -0
- package/lib/cli/index.d.ts +10 -0
- package/lib/cli/index.js +18 -0
- package/lib/cli/sell.d.ts +28 -0
- package/lib/cli/sell.js +95 -0
- package/lib/cli/stage.d.ts +19 -0
- package/lib/cli/stage.js +94 -0
- package/lib/config.d.ts +697 -0
- package/lib/config.js +45 -0
- package/lib/contracts/data-registry/abi.d.ts +442 -0
- package/lib/contracts/data-registry/abi.js +508 -0
- package/lib/contracts/data-registry/index.d.ts +131 -0
- package/lib/contracts/data-registry/index.js +183 -0
- package/lib/contracts/index.d.ts +6 -0
- package/lib/contracts/index.js +6 -0
- package/lib/contracts/logs.d.ts +17 -0
- package/lib/contracts/logs.js +28 -0
- package/lib/contracts/settlement-registry/abi.d.ts +810 -0
- package/lib/contracts/settlement-registry/abi.js +962 -0
- package/lib/contracts/settlement-registry/index.d.ts +143 -0
- package/lib/contracts/settlement-registry/index.js +213 -0
- package/lib/contracts/write.d.ts +59 -0
- package/lib/contracts/write.js +102 -0
- package/lib/crypto/aes.d.ts +19 -0
- package/lib/crypto/aes.js +26 -0
- package/lib/crypto/encryption.d.ts +38 -0
- package/lib/crypto/encryption.js +68 -0
- package/lib/crypto/paid.d.ts +104 -0
- package/lib/crypto/paid.js +147 -0
- package/lib/crypto/rand.d.ts +5 -0
- package/lib/crypto/rand.js +16 -0
- package/lib/crypto/types.d.ts +23 -0
- package/lib/crypto/types.js +1 -0
- package/lib/engine/car.d.ts +14 -0
- package/lib/engine/car.js +42 -0
- package/lib/engine/index.d.ts +206 -0
- package/lib/engine/index.js +377 -0
- package/lib/engine/records.d.ts +121 -0
- package/lib/engine/records.js +239 -0
- package/lib/engine/test-helpers.d.ts +38 -0
- package/lib/engine/test-helpers.js +63 -0
- package/lib/erc8004.d.ts +56 -0
- package/lib/erc8004.js +140 -0
- package/lib/fangorn.d.ts +342 -0
- package/lib/fangorn.js +642 -0
- package/lib/feed.d.ts +34 -0
- package/lib/feed.js +67 -0
- package/lib/index.d.ts +17 -0
- package/lib/index.js +16 -0
- package/lib/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.js +77 -0
- package/lib/node_modules/@vitest/expect/dist/index.js +1414 -0
- package/lib/node_modules/@vitest/pretty-format/dist/index.js +858 -0
- package/lib/node_modules/@vitest/runner/dist/chunk-tasks.js +51 -0
- package/lib/node_modules/@vitest/runner/dist/index.js +1199 -0
- package/lib/node_modules/@vitest/runner/dist/utils.js +3 -0
- package/lib/node_modules/@vitest/snapshot/dist/index.js +1075 -0
- package/lib/node_modules/@vitest/spy/dist/index.js +353 -0
- package/lib/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js +7 -0
- package/lib/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js +81 -0
- package/lib/node_modules/@vitest/utils/dist/diff.js +1345 -0
- package/lib/node_modules/@vitest/utils/dist/display.js +534 -0
- package/lib/node_modules/@vitest/utils/dist/error.js +30 -0
- package/lib/node_modules/@vitest/utils/dist/helpers.js +118 -0
- package/lib/node_modules/@vitest/utils/dist/serialize.js +76 -0
- package/lib/node_modules/@vitest/utils/dist/source-map.js +93 -0
- package/lib/node_modules/@vitest/utils/dist/timers.js +36 -0
- package/lib/node_modules/chai/index.js +2874 -0
- package/lib/node_modules/magic-string/dist/magic-string.es.js +939 -0
- package/lib/node_modules/pathe/dist/shared/pathe.M-eThtNZ.js +81 -0
- package/lib/node_modules/tinyrainbow/dist/index.js +85 -0
- package/lib/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.js +5 -0
- package/lib/node_modules/vitest/dist/chunks/date.Bq6ZW5rf.js +50 -0
- package/lib/node_modules/vitest/dist/chunks/utils.DvEY5TfP.js +44 -0
- package/lib/node_modules/vitest/dist/chunks/vi.2VT5v0um.js +2578 -0
- package/lib/providers/storage/car.d.ts +36 -0
- package/lib/providers/storage/car.js +81 -0
- package/lib/providers/storage/index.d.ts +5 -0
- package/lib/providers/storage/index.js +5 -0
- package/lib/providers/storage/pinata.d.ts +53 -0
- package/lib/providers/storage/pinata.js +178 -0
- package/lib/providers/storage/signed-url.d.ts +54 -0
- package/lib/providers/storage/signed-url.js +122 -0
- package/lib/providers/storage/types.d.ts +62 -0
- package/lib/providers/storage/types.js +1 -0
- package/lib/providers/storage/utils.d.ts +30 -0
- package/lib/providers/storage/utils.js +107 -0
- package/lib/repo/index.d.ts +56 -0
- package/lib/repo/index.js +73 -0
- package/lib/test/key-server.d.ts +12 -0
- package/lib/test/key-server.js +30 -0
- package/lib/test/mem-registry.d.ts +46 -0
- package/lib/test/mem-registry.js +114 -0
- package/lib/test/sdk-suite.d.ts +10 -0
- package/lib/test/sdk-suite.js +155 -0
- package/lib/test/testbed.d.ts +16786 -0
- package/lib/test/testbed.js +175 -0
- package/lib/types/index.d.ts +37 -0
- package/lib/types/index.js +1 -0
- package/package.json +87 -0
package/lib/fangorn.js
ADDED
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
import { FangornConfig, nonBlank } from "./config.js";
|
|
2
|
+
import { mcpTools, mintAgent, registrationFile, retryNonce, setAgentFile } from "./erc8004.js";
|
|
3
|
+
import { SignedUrlBackend } from "./providers/storage/signed-url.js";
|
|
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";
|
|
7
|
+
import "./contracts/index.js";
|
|
8
|
+
import { FangornEngine, assertValidRepoName, commitUpdate, rootHexFromCid } from "./engine/index.js";
|
|
9
|
+
import { CommitFeed } from "./feed.js";
|
|
10
|
+
import { createPublicClient, createWalletClient, http } from "viem";
|
|
11
|
+
import { privateKeyToAccount } from "viem/accounts";
|
|
12
|
+
import { CID } from "multiformats/cid";
|
|
13
|
+
|
|
14
|
+
//#region src/fangorn.ts
|
|
15
|
+
const ZERO_BYTES32 = ZERO_HEAD;
|
|
16
|
+
const NS_CACHE_MAX = 256;
|
|
17
|
+
function walletSigner(walletClient) {
|
|
18
|
+
const account = walletClient.account;
|
|
19
|
+
if (!account) throw new Error("Signed-url storage requires a wallet account to sign the access worker's challenge.");
|
|
20
|
+
return {
|
|
21
|
+
address: account.address,
|
|
22
|
+
signMessage: (message) => walletClient.signMessage({
|
|
23
|
+
account,
|
|
24
|
+
message
|
|
25
|
+
})
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
function resolveStorage(storage, walletClient, config) {
|
|
29
|
+
if (!storage) return void 0;
|
|
30
|
+
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
|
+
}
|
|
37
|
+
throw new Error(`Invalid storage config: must be { pinata: … }, { signedUrl: … } or { backend: … }, got ${JSON.stringify(storage)}`);
|
|
38
|
+
}
|
|
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";
|
|
50
|
+
var Fangorn = class Fangorn {
|
|
51
|
+
ctx;
|
|
52
|
+
_engine = null;
|
|
53
|
+
_feed = null;
|
|
54
|
+
_settlement = null;
|
|
55
|
+
/**
|
|
56
|
+
* The repo cache
|
|
57
|
+
* Insertion order = LRU order
|
|
58
|
+
*/
|
|
59
|
+
nsCache = /* @__PURE__ */ new Map();
|
|
60
|
+
constructor(ctx) {
|
|
61
|
+
this.ctx = ctx;
|
|
62
|
+
}
|
|
63
|
+
get engine() {
|
|
64
|
+
if (!this.ctx.metadataStorage) throw new Error("fangorn.engine requires storage configurations. Pass { pinata: { ... } } to Fangorn.create()");
|
|
65
|
+
this._engine ??= new FangornEngine(this.ctx.metadataStorage, this.ctx.registry);
|
|
66
|
+
return this._engine;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Static creation of a new Fangorn client
|
|
70
|
+
*
|
|
71
|
+
* @param options
|
|
72
|
+
* @returns the client
|
|
73
|
+
*/
|
|
74
|
+
static create(options) {
|
|
75
|
+
if (!options.privateKey && !options.walletClient) throw new Error("Either privateKey or walletClient must be provided");
|
|
76
|
+
const config = options.config ?? FangornConfig;
|
|
77
|
+
const walletClient = options.walletClient ?? createWalletClient({
|
|
78
|
+
account: privateKeyToAccount(options.privateKey ?? "0x0"),
|
|
79
|
+
chain: config.chain,
|
|
80
|
+
transport: http(config.rpcUrl)
|
|
81
|
+
});
|
|
82
|
+
const publicClient = createPublicClient({
|
|
83
|
+
chain: config.chain,
|
|
84
|
+
transport: http(config.rpcUrl)
|
|
85
|
+
});
|
|
86
|
+
const ctx = {
|
|
87
|
+
config,
|
|
88
|
+
walletClient,
|
|
89
|
+
publicClient,
|
|
90
|
+
metadataStorage: void 0,
|
|
91
|
+
registry: options.registry ?? new ChainRegistry(config, publicClient, walletClient)
|
|
92
|
+
};
|
|
93
|
+
ctx.metadataStorage = resolveStorage(options.storage, walletClient, config);
|
|
94
|
+
return new Fangorn(ctx);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Empties a repo: one commit of the empty state on top of the head. History
|
|
98
|
+
* stays (a head never goes back to zero), and so do the old records: the new
|
|
99
|
+
* head still names them as history.
|
|
100
|
+
*/
|
|
101
|
+
async reset(repo) {
|
|
102
|
+
const publisher = this.getAddress();
|
|
103
|
+
const head = await this.engine.resolveHeadCommit(publisher, repo);
|
|
104
|
+
const { commitCid } = await this.createCommit({
|
|
105
|
+
repo,
|
|
106
|
+
base: head,
|
|
107
|
+
records: [],
|
|
108
|
+
replace: true
|
|
109
|
+
});
|
|
110
|
+
return this.engine.pushCommit(publisher, repo, commitCid);
|
|
111
|
+
}
|
|
112
|
+
/** Stage records into one commit on top of `base`. */
|
|
113
|
+
createCommit(opts) {
|
|
114
|
+
return this.engine.createCommit({
|
|
115
|
+
...opts,
|
|
116
|
+
records: opts.records.map((r) => ({
|
|
117
|
+
id: r.id,
|
|
118
|
+
type: r.type,
|
|
119
|
+
payload: r.payload && typeof r.payload === "object" && !Array.isArray(r.payload) ? r.payload : { value: r.payload }
|
|
120
|
+
}))
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Allocates a repo in the publisher's root map.
|
|
125
|
+
* A no-op (no on-chain tx) if the repo is already initialized.
|
|
126
|
+
*/
|
|
127
|
+
async initRepo(repoName) {
|
|
128
|
+
assertValidRepoName(repoName);
|
|
129
|
+
const publisher = this.getAddress();
|
|
130
|
+
if (await this.engine.repoExists(publisher, repoName)) return {
|
|
131
|
+
cid: void 0,
|
|
132
|
+
commitCid: void 0,
|
|
133
|
+
txHash: void 0,
|
|
134
|
+
alreadyInitialized: true
|
|
135
|
+
};
|
|
136
|
+
const head = await this.engine.resolveHeadCommit(publisher, repoName);
|
|
137
|
+
const { commitCid } = await this.createCommit({
|
|
138
|
+
repo: repoName,
|
|
139
|
+
base: head,
|
|
140
|
+
records: []
|
|
141
|
+
});
|
|
142
|
+
const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
|
|
143
|
+
return {
|
|
144
|
+
cid: commitCid.toString(),
|
|
145
|
+
commitCid: commitCid.toString(),
|
|
146
|
+
txHash,
|
|
147
|
+
alreadyInitialized: false
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Put one record and settle it on-chain in a single shot. `id` defaults to
|
|
152
|
+
* a random one, so repeated calls add records; pass an id to update one.
|
|
153
|
+
*/
|
|
154
|
+
async upload(repoName, payload, type, id) {
|
|
155
|
+
const publisher = this.getAddress();
|
|
156
|
+
const head = await this.engine.resolveHeadCommit(publisher, repoName);
|
|
157
|
+
if (!head) throw new Error(`Repository '${repoName}' does not exist. Call initRepo() prior to uploading.`);
|
|
158
|
+
const { commitCid, recordCids } = await this.createCommit({
|
|
159
|
+
repo: repoName,
|
|
160
|
+
base: head,
|
|
161
|
+
records: [{
|
|
162
|
+
id,
|
|
163
|
+
type,
|
|
164
|
+
payload
|
|
165
|
+
}]
|
|
166
|
+
});
|
|
167
|
+
const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
|
|
168
|
+
const [[recordId, payloadCid]] = Object.entries(recordCids);
|
|
169
|
+
return {
|
|
170
|
+
id: recordId,
|
|
171
|
+
payloadCid,
|
|
172
|
+
commitCid: commitCid.toString(),
|
|
173
|
+
txHash
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Puts many records (and deletes some, by id) under one repo in a
|
|
178
|
+
* single commit, instead of one tx per record. Built in memory and persisted
|
|
179
|
+
* as ONE CAR upload plus one commit block, then settled in a single
|
|
180
|
+
* fast-forward tx. Relations are records too: give them `src`/`dst` `Ref`s.
|
|
181
|
+
*/
|
|
182
|
+
async uploadBatch(repoName, records, deletes = []) {
|
|
183
|
+
assertValidRepoName(repoName);
|
|
184
|
+
if (records.length === 0 && deletes.length === 0) throw new Error("uploadBatch requires at least one record or delete");
|
|
185
|
+
const publisher = this.getAddress();
|
|
186
|
+
const head = await this.engine.resolveHeadCommit(publisher, repoName);
|
|
187
|
+
if (!head) throw new Error(`Repository '${repoName}' does not exist. Call initRepo() prior to uploading.`);
|
|
188
|
+
const { commitCid, recordCids } = await this.createCommit({
|
|
189
|
+
repo: repoName,
|
|
190
|
+
base: head,
|
|
191
|
+
records,
|
|
192
|
+
deletes
|
|
193
|
+
});
|
|
194
|
+
const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
|
|
195
|
+
return {
|
|
196
|
+
commitCid: commitCid.toString(),
|
|
197
|
+
txHash,
|
|
198
|
+
recordCids
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Build a new commit (no on-chain tx) that puts/deletes records in
|
|
203
|
+
* `repo` on top of `parent` (a commit CID string, or undefined for a
|
|
204
|
+
* root commit). The commit and its CAR are uploaded to storage, so a later
|
|
205
|
+
* `push` — even in a separate process — can settle it.
|
|
206
|
+
*/
|
|
207
|
+
async commit(opts) {
|
|
208
|
+
assertValidRepoName(opts.repo);
|
|
209
|
+
const parentCid = opts.parent ? CID.parse(opts.parent) : null;
|
|
210
|
+
const { commitCid, root, recordCids } = await this.createCommit({
|
|
211
|
+
repo: opts.repo,
|
|
212
|
+
base: parentCid,
|
|
213
|
+
records: opts.records ?? [],
|
|
214
|
+
deletes: opts.deletes,
|
|
215
|
+
replace: opts.replace
|
|
216
|
+
});
|
|
217
|
+
return {
|
|
218
|
+
commitCid: commitCid.toString(),
|
|
219
|
+
parent: parentCid?.toString() ?? null,
|
|
220
|
+
root: root.toString(),
|
|
221
|
+
recordCids
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Build a commit on top of `owner`'s current on-chain head and return it
|
|
226
|
+
* together with the UNSIGNED settlement tx — the self-custodial publish path.
|
|
227
|
+
*
|
|
228
|
+
* `commit` + `push` assume the caller holds the publishing key. A relay server
|
|
229
|
+
* doesn't: it builds and pins the commit with a keyless service wallet, then
|
|
230
|
+
* hands the tx to the user's browser wallet to sign. The head only moves when
|
|
231
|
+
* the publisher themselves signs, so the server is never a trusted party.
|
|
232
|
+
*
|
|
233
|
+
* Nothing is on-chain when this returns. The commit and its CAR are durable in
|
|
234
|
+
* storage, so if the user never signs, the result is an orphaned commit — junk
|
|
235
|
+
* in IPFS, not a corrupted timeline.
|
|
236
|
+
*/
|
|
237
|
+
async prepareCommit(opts) {
|
|
238
|
+
assertValidRepoName(opts.repo);
|
|
239
|
+
const registry = this.ctx.registry;
|
|
240
|
+
const oldRoot = await registry.head({
|
|
241
|
+
publisher: opts.owner,
|
|
242
|
+
repo: opts.repo
|
|
243
|
+
});
|
|
244
|
+
const { commitCid, recordCids } = await this.createCommit({
|
|
245
|
+
repo: opts.repo,
|
|
246
|
+
base: oldRoot === ZERO_BYTES32 ? null : CID.parse(this.engine.commitCidFromRootHex(oldRoot)),
|
|
247
|
+
records: opts.records ?? [],
|
|
248
|
+
deletes: opts.deletes,
|
|
249
|
+
replace: opts.replace
|
|
250
|
+
});
|
|
251
|
+
const newRoot = rootHexFromCid(commitCid);
|
|
252
|
+
return {
|
|
253
|
+
commitCid: commitCid.toString(),
|
|
254
|
+
oldRoot,
|
|
255
|
+
newRoot,
|
|
256
|
+
staged: {
|
|
257
|
+
records: opts.records?.length ?? 0,
|
|
258
|
+
deletes: opts.deletes?.length ?? 0
|
|
259
|
+
},
|
|
260
|
+
tx: await registry.prepareUpdate(opts.owner, commitUpdate(await this.engine.getCommit(commitCid))),
|
|
261
|
+
recordCids
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Settle a local commit as the on-chain head of `repo`. Its parent must be
|
|
266
|
+
* the current head (see `FangornEngine.pushCommit`). Each repo has its own
|
|
267
|
+
* timeline, so pushes to different repos never contend.
|
|
268
|
+
*/
|
|
269
|
+
async push(repo, commitCid) {
|
|
270
|
+
const { txHash, onChainTip } = await this.engine.pushCommit(this.getAddress(), repo, CID.parse(commitCid));
|
|
271
|
+
return {
|
|
272
|
+
txHash,
|
|
273
|
+
onChainTip: onChainTip.toString()
|
|
274
|
+
};
|
|
275
|
+
}
|
|
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
|
+
/** The owner's current on-chain tip for a repo, or null if they have none. */
|
|
287
|
+
async onChainTip(owner, repo) {
|
|
288
|
+
const cid = await this.engine.resolveHeadCommit(owner, repo);
|
|
289
|
+
return cid ? cid.toString() : null;
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* A publisher's repo at its latest head, cached against that head.
|
|
293
|
+
*
|
|
294
|
+
* Reading a repo walks its whole record tree from the root. The tip is one
|
|
295
|
+
* cheap contract read and only moves on publish, so it doubles as the cache
|
|
296
|
+
* key: no TTL to tune, no invalidation to remember after a settle, and never
|
|
297
|
+
* stale.
|
|
298
|
+
*
|
|
299
|
+
* LRU-bounded so an always-on process can't accumulate every repo it
|
|
300
|
+
* ever touched. The durable copy is on-chain — an evicted entry re-walks.
|
|
301
|
+
* ponytail: fixed entry count, not byte-aware; switch to a size budget if a
|
|
302
|
+
* few huge repos blow memory before the count cap bites.
|
|
303
|
+
*/
|
|
304
|
+
async readRepo(owner, repo) {
|
|
305
|
+
const key = `${owner.toLowerCase()}/${repo}`;
|
|
306
|
+
const tip = await this.headCommit({
|
|
307
|
+
publisher: owner,
|
|
308
|
+
repo
|
|
309
|
+
});
|
|
310
|
+
const hit = this.nsCache.get(key);
|
|
311
|
+
if (hit?.tip === tip) {
|
|
312
|
+
this.nsCache.delete(key);
|
|
313
|
+
this.nsCache.set(key, hit);
|
|
314
|
+
return hit;
|
|
315
|
+
}
|
|
316
|
+
const entry = {
|
|
317
|
+
tip,
|
|
318
|
+
contents: await this.engine.listAt(tip ? CID.parse(tip) : null)
|
|
319
|
+
};
|
|
320
|
+
this.nsCache.delete(key);
|
|
321
|
+
this.nsCache.set(key, entry);
|
|
322
|
+
if (this.nsCache.size > NS_CACHE_MAX) {
|
|
323
|
+
const oldest = this.nsCache.keys().next().value;
|
|
324
|
+
if (oldest !== void 0) this.nsCache.delete(oldest);
|
|
325
|
+
}
|
|
326
|
+
return entry;
|
|
327
|
+
}
|
|
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);
|
|
331
|
+
return head === ZERO_BYTES32 ? null : this.engine.commitCidFromRootHex(head);
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
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.
|
|
336
|
+
*
|
|
337
|
+
* ponytail: scans the whole log from `fromBlock`; an indexer's sub-log once
|
|
338
|
+
* that is too slow.
|
|
339
|
+
*/
|
|
340
|
+
async repos(opts = {}) {
|
|
341
|
+
const entries = await this.ctx.registry.log({
|
|
342
|
+
publisher: opts.owner,
|
|
343
|
+
repo: opts.repo
|
|
344
|
+
}, opts.fromBlock ?? this.ctx.config.fromBlock);
|
|
345
|
+
const latest = /* @__PURE__ */ new Map();
|
|
346
|
+
for (const e of entries) latest.set(`${e.publisher.toLowerCase()}/${e.repo}`, {
|
|
347
|
+
owner: e.publisher,
|
|
348
|
+
repo: e.repo,
|
|
349
|
+
root: e.head,
|
|
350
|
+
blockNumber: e.t
|
|
351
|
+
});
|
|
352
|
+
return [...latest.values()];
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Resolve a repo from its agent card URL alone, and prove the card speaks for it.
|
|
356
|
+
*
|
|
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
|
|
360
|
+
* back at this exact URL. The comparison is exact string equality, so a
|
|
361
|
+
* trailing slash or a different host counts as a different card.
|
|
362
|
+
*/
|
|
363
|
+
async discoverCard(cardUrl) {
|
|
364
|
+
const res = await fetch(cardUrl, { signal: AbortSignal.timeout(1e4) });
|
|
365
|
+
if (!res.ok) throw new Error(`agent card ${cardUrl}: HTTP ${String(res.status)}`);
|
|
366
|
+
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`);
|
|
369
|
+
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"}`);
|
|
377
|
+
return {
|
|
378
|
+
card,
|
|
379
|
+
publisher,
|
|
380
|
+
repo: p.repo
|
|
381
|
+
};
|
|
382
|
+
}
|
|
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
|
+
/**
|
|
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.
|
|
395
|
+
*/
|
|
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({
|
|
411
|
+
...opts,
|
|
412
|
+
signal
|
|
413
|
+
}));
|
|
414
|
+
return this._feed;
|
|
415
|
+
}
|
|
416
|
+
/** Walk commit history from `head` (newest first). */
|
|
417
|
+
async *log(head, max) {
|
|
418
|
+
for await (const { cid, commit } of this.engine.walkParents(CID.parse(head), max)) yield {
|
|
419
|
+
cid: cid.toString(),
|
|
420
|
+
parent: commit.parent?.toString() ?? null,
|
|
421
|
+
epoch: commit.epoch,
|
|
422
|
+
root: commit.root.toString()
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
/** Show a commit and what it changed vs. its parent. */
|
|
426
|
+
async show(commitCid) {
|
|
427
|
+
return this.engine.diffCommit(CID.parse(commitCid));
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Lists every record currently committed under a repo, resolved
|
|
431
|
+
* from the publisher's on-chain root — useful for verifying what actually
|
|
432
|
+
* made it into the repository, as opposed to what a given call staged.
|
|
433
|
+
*/
|
|
434
|
+
async inspectRepo(repoName) {
|
|
435
|
+
return this.engine.listRepo(this.getAddress(), repoName);
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* Stream changes to one publisher's repo. Optionally replays from
|
|
439
|
+
* `fromBlock` first (resume cursor), then watches live until the `signal`
|
|
440
|
+
* aborts. Each yielded change carries `blockNumber` — persist it to resume
|
|
441
|
+
* exactly where you left off.
|
|
442
|
+
*/
|
|
443
|
+
subscribe(opts) {
|
|
444
|
+
return this.streamCommits({
|
|
445
|
+
publisher: opts.owner ?? this.getAddress(),
|
|
446
|
+
repo: opts.repo
|
|
447
|
+
}, opts);
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Stream changes to every repo of every publisher. Narrow it with `repo`
|
|
451
|
+
* (every publisher's `docs`) or `owner` (one publisher's repos).
|
|
452
|
+
*/
|
|
453
|
+
subscribeAll(opts = {}) {
|
|
454
|
+
return this.streamCommits({
|
|
455
|
+
publisher: opts.owner,
|
|
456
|
+
repo: opts.repo
|
|
457
|
+
}, opts);
|
|
458
|
+
}
|
|
459
|
+
/** Shared catch-up-then-live loop behind `subscribe` and `subscribeAll`. */
|
|
460
|
+
async *streamCommits(filter, opts) {
|
|
461
|
+
const registry = this.ctx.registry;
|
|
462
|
+
const seen = /* @__PURE__ */ new Set();
|
|
463
|
+
const lastHead = /* @__PURE__ */ new Map();
|
|
464
|
+
const buffer = [];
|
|
465
|
+
let wake = null;
|
|
466
|
+
const subState = {
|
|
467
|
+
failure: null,
|
|
468
|
+
stopped: false
|
|
469
|
+
};
|
|
470
|
+
const signal = () => {
|
|
471
|
+
const w = wake;
|
|
472
|
+
wake = null;
|
|
473
|
+
w?.();
|
|
474
|
+
};
|
|
475
|
+
const unwatch = registry.watch(filter, (log) => {
|
|
476
|
+
buffer.push(log);
|
|
477
|
+
signal();
|
|
478
|
+
}, (err) => {
|
|
479
|
+
subState.failure = err;
|
|
480
|
+
signal();
|
|
481
|
+
}, opts.pollingInterval);
|
|
482
|
+
const onAbort = () => {
|
|
483
|
+
subState.stopped = true;
|
|
484
|
+
signal();
|
|
485
|
+
};
|
|
486
|
+
opts.signal?.addEventListener("abort", onAbort);
|
|
487
|
+
try {
|
|
488
|
+
if (opts.fromBlock !== void 0) for (const log of await registry.log(filter, opts.fromBlock)) {
|
|
489
|
+
if (seen.has(log.id)) continue;
|
|
490
|
+
seen.add(log.id);
|
|
491
|
+
const change = await this.toRepoChange(log, lastHead);
|
|
492
|
+
if (change) yield change;
|
|
493
|
+
}
|
|
494
|
+
while (!subState.stopped) {
|
|
495
|
+
if (subState.failure) throw subState.failure;
|
|
496
|
+
if (buffer.length === 0) {
|
|
497
|
+
await new Promise((res) => {
|
|
498
|
+
wake = res;
|
|
499
|
+
});
|
|
500
|
+
continue;
|
|
501
|
+
}
|
|
502
|
+
const log = buffer.shift();
|
|
503
|
+
if (!log) continue;
|
|
504
|
+
if (seen.has(log.id)) continue;
|
|
505
|
+
seen.add(log.id);
|
|
506
|
+
const change = await this.toRepoChange(log, lastHead);
|
|
507
|
+
if (change) yield change;
|
|
508
|
+
}
|
|
509
|
+
} finally {
|
|
510
|
+
unwatch();
|
|
511
|
+
opts.signal?.removeEventListener("abort", onAbort);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Resolve a log entry into a repo change, or null if the repo's records did
|
|
516
|
+
* not change.
|
|
517
|
+
*
|
|
518
|
+
* The commit itself names its repo, which must be the one the entry was
|
|
519
|
+
* logged under, or the publisher settled a commit for one repo against
|
|
520
|
+
* another's timeline.
|
|
521
|
+
*
|
|
522
|
+
* The diff runs from the last head this stream saw for the repo, not from
|
|
523
|
+
* the entry's parent. If an entry was dropped (an RPC that left out a log),
|
|
524
|
+
* the two differ, and diffing from the entry's parent would skip what the
|
|
525
|
+
* dropped entry changed.
|
|
526
|
+
*/
|
|
527
|
+
async toRepoChange(log, lastHead) {
|
|
528
|
+
const declared = await this.engine.repoOf(log.head);
|
|
529
|
+
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}")`);
|
|
530
|
+
const key = `${log.publisher.toLowerCase()}/${log.repo}`;
|
|
531
|
+
const oldRoot = lastHead.get(key) ?? log.parent;
|
|
532
|
+
lastHead.set(key, log.head);
|
|
533
|
+
const diff = await this.engine.repoDiff(oldRoot === ZERO_BYTES32 ? null : oldRoot, log.head);
|
|
534
|
+
if (!diff.puts.length && !diff.deletes.length) return null;
|
|
535
|
+
return {
|
|
536
|
+
repo: log.repo,
|
|
537
|
+
owner: log.publisher,
|
|
538
|
+
commitCid: this.engine.commitCidFromRootHex(log.head),
|
|
539
|
+
oldRoot,
|
|
540
|
+
newRoot: log.head,
|
|
541
|
+
blockNumber: log.t,
|
|
542
|
+
...diff
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
getConfig() {
|
|
546
|
+
return this.ctx.config;
|
|
547
|
+
}
|
|
548
|
+
/** Heads and the update log: the registry of WHITEPAPER_1 §3.2. */
|
|
549
|
+
getRegistry() {
|
|
550
|
+
return this.ctx.registry;
|
|
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;
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
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
|
|
561
|
+
* browser wallet on signed-URL storage needs no Pinata JWT.
|
|
562
|
+
*
|
|
563
|
+
* `update` re-files an agent already minted (its token id) from the card as it is
|
|
564
|
+
* now, minting nothing. `skipRegister` only binds the card. A binding that already
|
|
565
|
+
* points at `cardUrl` is left alone.
|
|
566
|
+
*/
|
|
567
|
+
async registerAgent(cardUrl, opts) {
|
|
568
|
+
const res = await fetch(cardUrl);
|
|
569
|
+
if (!res.ok) throw new Error(`card at ${cardUrl} returned ${String(res.status)}`);
|
|
570
|
+
const card = await res.json();
|
|
571
|
+
if (!card.name || !card.description) throw new Error("card is missing `name` or `description`");
|
|
572
|
+
const named = {
|
|
573
|
+
...card,
|
|
574
|
+
name: card.name,
|
|
575
|
+
description: card.description
|
|
576
|
+
};
|
|
577
|
+
let agentId;
|
|
578
|
+
if (!opts.skipRegister) {
|
|
579
|
+
const c = {
|
|
580
|
+
chain: this.ctx.config.chain,
|
|
581
|
+
publicClient: this.ctx.publicClient,
|
|
582
|
+
walletClient: this.ctx.walletClient,
|
|
583
|
+
storage: this.getStorage()
|
|
584
|
+
};
|
|
585
|
+
const chainId = this.ctx.config.caip2;
|
|
586
|
+
const mcp = opts.mcp ? {
|
|
587
|
+
endpoint: opts.mcp,
|
|
588
|
+
tools: await mcpTools(opts.mcp)
|
|
589
|
+
} : void 0;
|
|
590
|
+
const file = (id) => registrationFile({
|
|
591
|
+
cardUrl,
|
|
592
|
+
card: named,
|
|
593
|
+
chainId,
|
|
594
|
+
agentId: id,
|
|
595
|
+
mcp
|
|
596
|
+
});
|
|
597
|
+
const { update } = opts;
|
|
598
|
+
if (update !== void 0) {
|
|
599
|
+
agentId = update;
|
|
600
|
+
await retryNonce(() => setAgentFile(c, update, file(update)));
|
|
601
|
+
} else {
|
|
602
|
+
const id = await mintAgent(c);
|
|
603
|
+
agentId = id;
|
|
604
|
+
try {
|
|
605
|
+
await retryNonce(() => setAgentFile(c, id, file(id)));
|
|
606
|
+
} catch (e) {
|
|
607
|
+
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 });
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
const txHash = await retryNonce(() => this.setCard(opts.repo, cardUrl));
|
|
612
|
+
return {
|
|
613
|
+
card: named,
|
|
614
|
+
agentId,
|
|
615
|
+
txHash
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
getStorage() {
|
|
619
|
+
if (!this.ctx.metadataStorage) throw new Error("storage is not configured. Pass { pinata: { ... } } or { signedUrl: { ... } } to Fangorn.create()");
|
|
620
|
+
return this.ctx.metadataStorage;
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* Swap the storage backend at runtime — e.g. move from access-worker signed
|
|
624
|
+
* URLs to your own Pinata JWT (or back). Rebuilds the engine on next use so it
|
|
625
|
+
* picks up the new backend.
|
|
626
|
+
*/
|
|
627
|
+
setStorage(storage) {
|
|
628
|
+
this.ctx.metadataStorage = resolveStorage(storage, this.ctx.walletClient, this.ctx.config);
|
|
629
|
+
this._engine = null;
|
|
630
|
+
}
|
|
631
|
+
getWalletClient() {
|
|
632
|
+
return this.ctx.walletClient;
|
|
633
|
+
}
|
|
634
|
+
getAddress() {
|
|
635
|
+
const address = this.ctx.walletClient.account?.address;
|
|
636
|
+
if (!address) throw new Error("No account connected to wallet client");
|
|
637
|
+
return address;
|
|
638
|
+
}
|
|
639
|
+
};
|
|
640
|
+
|
|
641
|
+
//#endregion
|
|
642
|
+
export { CARD_RECORD, FANGORN_REPO_EXTENSION, Fangorn };
|
package/lib/feed.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { RepoChange } from "./fangorn.js";
|
|
2
|
+
|
|
3
|
+
//#region src/feed.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* One shared commit stream, fanned out to many consumers.
|
|
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.
|
|
12
|
+
*
|
|
13
|
+
* Not a lens (WHITEPAPER_1 §3.4): a lens computes a view over the stream, this
|
|
14
|
+
* only shares the stream. fangorn-md's server fans it out to its connections.
|
|
15
|
+
*/
|
|
16
|
+
declare class CommitFeed {
|
|
17
|
+
private readonly open;
|
|
18
|
+
/** Delay before reopening the watch after it fails or ends. */
|
|
19
|
+
private readonly restartDelayMs;
|
|
20
|
+
private readonly listeners;
|
|
21
|
+
private abort;
|
|
22
|
+
constructor(open: (signal: AbortSignal) => AsyncGenerator<RepoChange>, /** Delay before reopening the watch after it fails or ends. */
|
|
23
|
+
restartDelayMs?: number);
|
|
24
|
+
/** Number of live listeners — 0 means the underlying watch is closed. */
|
|
25
|
+
get size(): number;
|
|
26
|
+
/**
|
|
27
|
+
* Register a listener, starting the feed if it was idle. Returns the
|
|
28
|
+
* unsubscribe function; the feed stops once the last listener leaves.
|
|
29
|
+
*/
|
|
30
|
+
on(onChange: (change: RepoChange) => void, onError?: (err: Error) => void): () => void;
|
|
31
|
+
private run;
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
export { CommitFeed };
|