@finchip.ai/foga 0.0.0-stage → 0.6.0-alpha.4

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 (131) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +21 -0
  3. package/README.md +216 -2
  4. package/artifacts/bundle.json +74250 -0
  5. package/artifacts/bundle.sha256 +1 -0
  6. package/bin/foga.js +14 -0
  7. package/build/known-interface-ids.json +18 -0
  8. package/build/profiles.json +120 -0
  9. package/dist/build/bundle.js +417 -0
  10. package/dist/build/vendor.js +74 -0
  11. package/dist/bundle/load.js +24 -0
  12. package/dist/bundle/types.js +1 -0
  13. package/dist/cli-cell.js +395 -0
  14. package/dist/cli.js +505 -0
  15. package/dist/core/acdf.js +162 -0
  16. package/dist/core/adrf.js +273 -0
  17. package/dist/core/aid.js +83 -0
  18. package/dist/core/ard.js +146 -0
  19. package/dist/core/asf.js +157 -0
  20. package/dist/core/canonical.js +79 -0
  21. package/dist/core/erc8004.js +52 -0
  22. package/dist/core/kya.js +225 -0
  23. package/dist/core/measure.js +96 -0
  24. package/dist/core/pack/cbor.js +130 -0
  25. package/dist/core/pack/skillpack.js +142 -0
  26. package/dist/core/skills.js +40 -0
  27. package/dist/core/swarm.js +206 -0
  28. package/dist/core/tenders.js +121 -0
  29. package/dist/core/units.js +122 -0
  30. package/dist/core/world.js +104 -0
  31. package/dist/demo/demander.js +76 -0
  32. package/dist/demo/evidence.js +1 -0
  33. package/dist/demo/loop-d.js +449 -0
  34. package/dist/doctor/checks.js +51 -0
  35. package/dist/doctor/doctor.js +385 -0
  36. package/dist/doctor/loop-d.js +103 -0
  37. package/dist/doctor/probe.js +97 -0
  38. package/dist/doctor/semantic.js +83 -0
  39. package/dist/genesis/extract.js +64 -0
  40. package/dist/genesis/funding.js +126 -0
  41. package/dist/genesis/operator-scope.js +90 -0
  42. package/dist/genesis/preflight.js +54 -0
  43. package/dist/genesis/probe.js +164 -0
  44. package/dist/genesis/roles.js +96 -0
  45. package/dist/genesis/run.js +71 -0
  46. package/dist/genesis/scenario.js +765 -0
  47. package/dist/genesis/skill-runner.js +103 -0
  48. package/dist/genesis/skill-worker.js +41 -0
  49. package/dist/genesis/t1-zk.js +62 -0
  50. package/dist/genesis/t3-zk.js +105 -0
  51. package/dist/genesis/t4.js +259 -0
  52. package/dist/genesis/t5.js +168 -0
  53. package/dist/genesis/t6.js +222 -0
  54. package/dist/genesis/t7.js +198 -0
  55. package/dist/genesis/t8.js +189 -0
  56. package/dist/genesis/t9.js +188 -0
  57. package/dist/genesis/zk.js +128 -0
  58. package/dist/http/server.js +276 -0
  59. package/dist/kernel/cell.js +104 -0
  60. package/dist/kernel/errors.js +78 -0
  61. package/dist/kernel/kernel.js +251 -0
  62. package/dist/kernel/provider.js +125 -0
  63. package/dist/kernel/store.js +470 -0
  64. package/dist/kernel/tx.js +385 -0
  65. package/dist/mcp/server.js +170 -0
  66. package/dist/node/config.js +195 -0
  67. package/dist/node/init.js +200 -0
  68. package/dist/node/keys.js +95 -0
  69. package/dist/node/migrate.js +173 -0
  70. package/dist/node/model/anthropic.js +97 -0
  71. package/dist/node/model/stub.js +129 -0
  72. package/dist/node/model/types.js +9 -0
  73. package/dist/node/node.js +198 -0
  74. package/dist/node/policy.js +95 -0
  75. package/dist/node/runner.js +256 -0
  76. package/dist/node/watchers.js +88 -0
  77. package/dist/tools/admin.js +184 -0
  78. package/dist/tools/catalog.js +261 -0
  79. package/dist/tools/common.js +143 -0
  80. package/dist/tools/identity.js +107 -0
  81. package/dist/tools/index.js +14 -0
  82. package/dist/tools/read.js +471 -0
  83. package/dist/tools/tenders.js +400 -0
  84. package/dist/tools/types.js +4 -0
  85. package/dist/util/bytecode.js +123 -0
  86. package/dist/util/fs.js +58 -0
  87. package/dist/util/hash.js +4 -0
  88. package/dist/util/log.js +11 -0
  89. package/dist/util/version.js +12 -0
  90. package/dist/world/deploy.js +277 -0
  91. package/dist/world/plan.js +93 -0
  92. package/dist/world/types.js +1 -0
  93. package/docs/build.md +45 -0
  94. package/docs/cell-account.md +58 -0
  95. package/docs/compatibility-matrix.md +38 -0
  96. package/docs/design-memo.md +113 -0
  97. package/docs/doctor.md +53 -0
  98. package/docs/examples/README.md +11 -0
  99. package/docs/examples/claude-code-mcp.json +13 -0
  100. package/docs/examples/claude_desktop_config.json +12 -0
  101. package/docs/examples/cursor-mcp.json +11 -0
  102. package/docs/genesis.md +312 -0
  103. package/docs/kernel.md +101 -0
  104. package/docs/loop-d.md +90 -0
  105. package/docs/mcp.md +105 -0
  106. package/docs/node.md +66 -0
  107. package/docs/version-lock.md +67 -0
  108. package/docs/world.md +50 -0
  109. package/docs/zk.md +48 -0
  110. package/package.json +82 -4
  111. package/prover/README.md +26 -0
  112. package/prover/build-predicate.mjs +77 -0
  113. package/prover/package-lock.json +1837 -0
  114. package/prover/package.json +15 -0
  115. package/prover/run.cjs +199 -0
  116. package/scenarios/fixtures/sample-filing.txt +16 -0
  117. package/scenarios/skills/finch-extract-verify/LICENSE +2 -0
  118. package/scenarios/skills/finch-extract-verify/SKILL.md +34 -0
  119. package/scenarios/skills/finch-extract-verify/fields.json +56 -0
  120. package/scenarios/skills/finch-extract-verify/manifest.json +16 -0
  121. package/scenarios/skills/foga-probe/LICENSE +2 -0
  122. package/scenarios/skills/foga-probe/SKILL.md +35 -0
  123. package/scenarios/skills/foga-probe/manifest.json +16 -0
  124. package/scenarios/skills/foga-probe/probe.schema.json +40 -0
  125. package/server.json +79 -0
  126. package/vendor/LOCK.json +107 -0
  127. package/vendor/README.md +13 -0
  128. package/worlds/local.json +34 -0
  129. package/worlds/sepolia.json +314 -0
  130. package/zk/build/verification_key.json +174 -0
  131. package/zk/circuits/kya_predicate_count_v1.circom +231 -0
@@ -0,0 +1,471 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { getAddress } from "ethers";
4
+ import { z } from "zod";
5
+ import { accountRef } from "../core/canonical.js";
6
+ import { accountSubject } from "../core/kya.js";
7
+ import { modelCallsKey } from "../node/runner.js";
8
+ import { TenderOutputSchema, readTender, tenderOutput, zAddress, zBool, zBytes32, zUint } from "./common.js";
9
+ /**
10
+ * The read capabilities: chain and store, no key, no decision record. Public ones answer anyone; `caller` ones
11
+ * return the caller's own jobs and operations (the operator sees every one); `evidence_export` is the operator's.
12
+ */
13
+ const str = (v) => (typeof v === "bigint" ? v.toString() : v);
14
+ export const world_describe = {
15
+ name: "world_describe",
16
+ title: "Describe the world",
17
+ description: "The world this cell lives in: id, chain, network, the contracts by id, the bundle hash, and the latest doctor summary when a report sits next to the world file.",
18
+ action: "read",
19
+ visibility: "public",
20
+ principal: "none",
21
+ ercs: [8338, 8414, 8419, 8434, 8436, 8444, 8447, 8454, 8468, 8471, 8004],
22
+ input: z.object({}),
23
+ output: z.object({
24
+ worldId: z.string(),
25
+ chainId: z.number(),
26
+ network: z.string(),
27
+ bundleHash: z.string(),
28
+ contracts: z.record(z.string(), zAddress),
29
+ doctor: z.object({ summary: z.record(z.string(), z.number()), at: z.string().optional() }).nullable(),
30
+ }),
31
+ async handler({ node }) {
32
+ const w = node.world.file;
33
+ let doctor = null;
34
+ const candidate = node.worldPath.replace(/\.json$/, ".doctor.json");
35
+ if (existsSync(candidate)) {
36
+ try {
37
+ const r = JSON.parse(readFileSync(candidate, "utf8"));
38
+ if (r?.summary)
39
+ doctor = { summary: r.summary, at: r.ranAt ?? r.at };
40
+ }
41
+ catch {
42
+ doctor = null;
43
+ }
44
+ }
45
+ return { worldId: w.worldId, chainId: w.chainId, network: w.network, bundleHash: w.bundleHash, contracts: Object.fromEntries(Object.entries(w.contracts).map(([id, c]) => [id, c.address])), doctor };
46
+ },
47
+ };
48
+ export const identity_resolve = {
49
+ name: "identity_resolve",
50
+ title: "Resolve an identity",
51
+ description: "The ten-ERC view of an address: ERC-8004 agent, ERC-8434 state in the reference and backing registries, ERC-8444 agent record, KYA level under the cell's standing scheme, ERC-8468 status when the address is a cell account.",
52
+ action: "read",
53
+ visibility: "public",
54
+ principal: "none",
55
+ ercs: [8004, 8434, 8444, 8419, 8468],
56
+ input: z.object({ address: zAddress }),
57
+ output: z.object({
58
+ address: zAddress,
59
+ aid: z.string(),
60
+ isContract: z.boolean(),
61
+ agent: z.object({ registry: zAddress, agentId: zUint, owner: zAddress.nullable() }).nullable(),
62
+ liveness: z.object({ registry: zAddress, state: z.string(), lastSeen: z.number() }).array(),
63
+ record: z.object({ recordId: zBytes32, status: z.number(), backed: z.boolean(), descriptorURI: z.string() }).nullable(),
64
+ standing: z.object({ schemeId: zBytes32, level: z.number(), expiresAt: z.number() }).nullable(),
65
+ safety: z.object({ verdict: z.string(), reasons: z.array(z.string()), restrictions: z.array(z.number()), bindings: z.array(zBytes32) }).nullable(),
66
+ }),
67
+ async handler({ node }, { address }) {
68
+ const k = node.kernel;
69
+ const addr = getAddress(address);
70
+ const code = await node.world.provider.getCode(addr);
71
+ const liveness = [];
72
+ let agent = null;
73
+ for (const registry of [k.aid.address, ...(k.aid.backing ? [k.aid.backing.address] : [])]) {
74
+ try {
75
+ const [state, bound] = await Promise.all([k.aid.stateName(addr, registry), k.aid.at(registry).bindingOf(addr)]);
76
+ const lastSeen = Number(await k.aid.at(registry).lastSeen(addr).catch(() => 0n));
77
+ liveness.push({ registry, state, lastSeen });
78
+ if (!agent && bound && String(bound.registry) !== "0x0000000000000000000000000000000000000000") {
79
+ const agentId = BigInt(bound.agentId);
80
+ const owner = await k.identity.ownerOf(agentId).catch(() => null);
81
+ agent = { registry: String(bound.registry), agentId: agentId.toString(), owner: owner ? getAddress(owner) : null };
82
+ }
83
+ }
84
+ catch {
85
+ /* not an anchor in this registry */
86
+ }
87
+ }
88
+ let record = null;
89
+ try {
90
+ const recordId = k.ard.recordIdOf(addr, 0n);
91
+ const r = await k.ard.recordOf(recordId);
92
+ if (r.kind !== "0x" + "00".repeat(32))
93
+ record = { recordId, status: r.status, backed: await k.ard.backed(recordId), descriptorURI: r.descriptorURI.length > 200 ? r.descriptorURI.slice(0, 200) + "…" : r.descriptorURI };
94
+ }
95
+ catch {
96
+ record = null;
97
+ }
98
+ let standing = null;
99
+ const st = node.config.identity.standing;
100
+ if (st) {
101
+ try {
102
+ const r = await k.kya.resolve(accountSubject(node.chainId, addr), st.schemeId, st.issuers);
103
+ standing = { schemeId: st.schemeId, level: r.level, expiresAt: Number(r.expiresAt) };
104
+ }
105
+ catch {
106
+ standing = null;
107
+ }
108
+ }
109
+ let safety = null;
110
+ if (code !== "0x") {
111
+ try {
112
+ const { Cell } = await import("../kernel/cell.js");
113
+ const probe = new Cell(k, "probe", addr, { owner: "owner", operator: "operator", guardian: addr });
114
+ const [status, bindings] = await Promise.all([probe.status(), probe.presentedBindings()]);
115
+ safety = { verdict: status.verdictName, reasons: status.reasonNames, restrictions: status.restrictions, bindings };
116
+ }
117
+ catch {
118
+ safety = null;
119
+ }
120
+ }
121
+ return { address: addr, aid: accountRef(node.chainId, addr), isContract: code !== "0x", agent, liveness, record, standing, safety };
122
+ },
123
+ };
124
+ export const tender_list = {
125
+ name: "tender_list",
126
+ title: "List tenders",
127
+ description: "Tenders minted within the lookback window (ERC-8414 TaskUpdated events), newest first; by default only those still open (funded, not cancelled, completions left, deadlines ahead).",
128
+ action: "read",
129
+ visibility: "public",
130
+ principal: "none",
131
+ ercs: [8414],
132
+ input: z.object({ lookbackBlocks: z.coerce.number().int().min(1).max(100_000).optional(), includeClosed: zBool.default(false), limit: z.coerce.number().int().min(1).max(200).default(50) }),
133
+ output: z.object({ fromBlock: z.number(), toBlock: z.number(), tenders: z.array(TenderOutputSchema) }),
134
+ async handler({ node }, input) {
135
+ const k = node.kernel;
136
+ const head = await k.blockNumber();
137
+ const fromBlock = Math.max(0, head - (input.lookbackBlocks ?? node.config.policy.tenders.lookbackBlocks));
138
+ const token = k.tenders.contract();
139
+ const events = await token.queryFilter(token.filters.TaskUpdated(), fromBlock, head);
140
+ const ids = [...new Set(events.map((e) => BigInt(e.args.tokenId).toString()))].map((s) => BigInt(s)).sort((a, b) => (a < b ? 1 : a > b ? -1 : 0));
141
+ const now = await node.now();
142
+ const out = [];
143
+ for (const id of ids) {
144
+ if (out.length >= input.limit)
145
+ break;
146
+ const v = await readTender(node, id);
147
+ const f = v.facts;
148
+ const open = !f.cancelled && f.escrowWei >= f.rewardWei && (f.maxCompletions === 0n || f.completions < f.maxCompletions) && (f.submitBy === 0n || Number(f.submitBy) > now) && (f.settleBy === 0n || Number(f.settleBy) > now);
149
+ if (open || input.includeClosed)
150
+ out.push(tenderOutput(v));
151
+ }
152
+ return { fromBlock, toBlock: head, tenders: out };
153
+ },
154
+ };
155
+ export const tender_inspect = {
156
+ name: "tender_inspect",
157
+ title: "Inspect a tender",
158
+ description: "One tender's terms, acceptance authority, escrow, deadlines, task document (when the task URI is a data: URI) and submissions.",
159
+ action: "read",
160
+ visibility: "public",
161
+ principal: "none",
162
+ ercs: [8414, 8444],
163
+ input: z.object({ tokenId: zUint }),
164
+ output: TenderOutputSchema,
165
+ async handler({ node }, { tokenId }) {
166
+ return tenderOutput(await readTender(node, BigInt(tokenId)));
167
+ },
168
+ };
169
+ const SkillOutput = z.object({ name: z.string().nullable(), tokenId: zUint, owner: zAddress, mdHash: zBytes32, packageHash: zBytes32, version: z.number(), skillURI: z.string(), record: z.object({ recordId: zBytes32, backed: z.boolean() }).nullable() });
170
+ async function skillView(node, tokenId, name) {
171
+ const k = node.kernel;
172
+ const [onchain, owner, skillURI] = await Promise.all([k.skills.skillOf(tokenId), k.skills.ownerOf(tokenId), k.skills.skillURI(tokenId).catch(() => "")]);
173
+ let record = null;
174
+ try {
175
+ const recordId = k.ard.recordIdOf(k.skills.address, tokenId);
176
+ const r = await k.ard.recordOf(recordId);
177
+ if (r.kind !== "0x" + "00".repeat(32))
178
+ record = { recordId, backed: await k.ard.backed(recordId) };
179
+ }
180
+ catch {
181
+ record = null;
182
+ }
183
+ return { name, tokenId: tokenId.toString(), owner: getAddress(owner), mdHash: onchain.mdHash, packageHash: onchain.packageHash, version: Number(onchain.version), skillURI: skillURI.length > 200 ? skillURI.slice(0, 200) + "…" : skillURI, record };
184
+ }
185
+ export const skill_list = {
186
+ name: "skill_list",
187
+ title: "List skills",
188
+ description: "The skill tokens a holder has: the cell's own from its configuration (verified against the chain), another holder's from the token's Transfer events in the lookback window.",
189
+ action: "read",
190
+ visibility: "public",
191
+ principal: "none",
192
+ ercs: [8338, 8444],
193
+ input: z.object({ holder: zAddress.optional(), lookbackBlocks: z.coerce.number().int().min(1).max(100_000).optional() }),
194
+ output: z.object({ holder: zAddress, offered: z.array(z.string()), skills: z.array(SkillOutput) }),
195
+ async handler({ node }, input) {
196
+ const k = node.kernel;
197
+ const holder = getAddress(input.holder ?? node.body.address);
198
+ if (holder === getAddress(node.body.address)) {
199
+ const held = await node.heldSkills();
200
+ const skills = [];
201
+ for (const h of held)
202
+ skills.push(await skillView(node, h.tokenId, h.name));
203
+ return { holder, offered: node.config.skills.offered, skills };
204
+ }
205
+ const head = await k.blockNumber();
206
+ const from = Math.max(0, head - (input.lookbackBlocks ?? node.config.policy.tenders.lookbackBlocks));
207
+ const token = k.skills.contract();
208
+ const events = await token.queryFilter(token.filters.Transfer(null, holder), from, head);
209
+ const ids = [...new Set(events.map((e) => BigInt(e.args.tokenId).toString()))].map((s) => BigInt(s));
210
+ const skills = [];
211
+ for (const id of ids) {
212
+ const owner = await k.skills.ownerOf(id);
213
+ if (getAddress(owner) === holder)
214
+ skills.push(await skillView(node, id, null));
215
+ }
216
+ return { holder, offered: [], skills };
217
+ },
218
+ };
219
+ export const skill_inspect = {
220
+ name: "skill_inspect",
221
+ title: "Inspect a skill",
222
+ description: "One skill token's commitment (mdHash, packageHash, version), owner, URI and ARD record.",
223
+ action: "read",
224
+ visibility: "public",
225
+ principal: "none",
226
+ ercs: [8338, 8444],
227
+ input: z.object({ tokenId: zUint }),
228
+ output: SkillOutput,
229
+ async handler({ node }, { tokenId }) {
230
+ const id = BigInt(tokenId);
231
+ const name = Object.entries(node.config.skills.held).find(([, h]) => h.tokenId === tokenId)?.[0] ?? null;
232
+ return skillView(node, id, name);
233
+ },
234
+ };
235
+ export const cell_status = {
236
+ name: "cell_status",
237
+ title: "The cell's status",
238
+ description: "The node's own cell: account and roles, anchor state in each registry, binding verdict, held and offered skills, policy summary; for the operator also the budget books, open operations and running jobs.",
239
+ action: "read",
240
+ visibility: "public",
241
+ principal: "none",
242
+ ercs: [8434, 8468, 8004],
243
+ input: z.object({}),
244
+ output: z.object({
245
+ name: z.string(),
246
+ account: zAddress,
247
+ owner: zAddress,
248
+ operator: zAddress,
249
+ guardian: zAddress,
250
+ agentId: zUint.nullable(),
251
+ accountVersion: z.number(),
252
+ liveness: z.array(z.object({ registry: zAddress, state: z.string() })),
253
+ safety: z.object({ verdict: z.string(), reasons: z.array(z.string()), restrictions: z.array(z.number()) }),
254
+ skills: z.object({ held: z.array(z.string()), offered: z.array(z.string()) }),
255
+ policy: z.object({ dailyValueWei: zUint, perOperationValueWei: zUint, dailyGasWei: zUint, maxConcurrentCommitments: z.number(), minRewardWei: zUint, acceptance: z.array(z.string()) }),
256
+ budget: z.object({ valueWei: zUint, gasWei: zUint, reservedValueWei: zUint, reservedFeeWei: zUint, runningCommitments: z.number(), operatorBalanceWei: zUint, accountBalanceWei: zUint, modelCallsToday: z.number(), modelDailyCalls: z.number() }).nullable(),
257
+ open: z.object({ operations: z.array(z.string()), jobs: z.array(z.string()) }).nullable(),
258
+ }),
259
+ async handler({ node, caller }) {
260
+ const k = node.kernel;
261
+ const cell = node.body;
262
+ const cfg = node.config;
263
+ const liveness = [];
264
+ for (const registry of [k.aid.address, ...(k.aid.backing ? [k.aid.backing.address] : [])])
265
+ liveness.push({ registry, state: await k.aid.stateName(cell.address, registry) });
266
+ const status = await cell.status();
267
+ let version = 1;
268
+ try {
269
+ version = Number(await cell.contract().ACCOUNT_VERSION());
270
+ }
271
+ catch {
272
+ version = 1;
273
+ }
274
+ const operator = caller.visibility === "operator";
275
+ const use = operator ? node.budgetUse() : null;
276
+ const [opBal, accBal] = operator ? await Promise.all([k.balance(cfg.identity.operator), cell.balance()]) : [0n, 0n];
277
+ return {
278
+ name: cfg.name,
279
+ account: cell.address,
280
+ owner: cfg.identity.owner,
281
+ operator: cfg.identity.operator,
282
+ guardian: cfg.identity.guardian,
283
+ agentId: cfg.identity.agentId ?? null,
284
+ accountVersion: version,
285
+ liveness,
286
+ safety: { verdict: status.verdictName, reasons: status.reasonNames, restrictions: status.restrictions },
287
+ skills: { held: Object.keys(cfg.skills.held), offered: cfg.skills.offered },
288
+ policy: { ...cfg.policy.budget, minRewardWei: cfg.policy.tenders.minRewardWei, acceptance: cfg.policy.tenders.acceptance },
289
+ budget: use ? { valueWei: use.valueWei.toString(), gasWei: use.gasWei.toString(), reservedValueWei: use.reservedValueWei.toString(), reservedFeeWei: use.reservedFeeWei.toString(), runningCommitments: use.runningCommitments, operatorBalanceWei: opBal.toString(), accountBalanceWei: accBal.toString(), modelCallsToday: node.store.getFact(modelCallsKey()) ?? 0, modelDailyCalls: cfg.runtime.model.dailyCalls } : null,
290
+ open: operator ? { operations: node.store.openOps("operator").map((o) => o.key), jobs: node.store.jobs(null, 200).filter((j) => j.status === "accepted" || j.status === "running").map((j) => j.id) } : null,
291
+ };
292
+ },
293
+ };
294
+ const OperationOutput = z.object({ key: z.string(), kind: z.string(), signer: z.string(), status: z.string(), txHash: z.string().nullable(), block: z.number().nullable(), nonce: z.number().nullable(), attempts: z.number(), replacements: z.number(), error: z.string().nullable(), capability: z.string().nullable(), caller: z.string().nullable(), valueWei: zUint, gasCostWei: zUint.nullable(), result: z.unknown().nullable(), updatedAt: z.string() });
295
+ const JobOutput = z.object({ id: z.string(), kind: z.string(), status: z.string(), caller: z.string().nullable(), inputHash: z.string(), operations: z.array(z.string()), result: z.unknown().nullable(), error: z.string().nullable(), createdAt: z.string(), updatedAt: z.string() });
296
+ function mayseeJob(caller, jobCaller) {
297
+ return caller.visibility === "operator" || (jobCaller !== null && jobCaller === caller.id);
298
+ }
299
+ export const operation_status = {
300
+ name: "operation_status",
301
+ title: "An operation's status",
302
+ description: "One keyed operation of the store (prepared, sent, confirmed, failed; hash, block, cost). A caller sees the operations of its own jobs; an operation id is a locator, not a pass.",
303
+ action: "read",
304
+ visibility: "caller",
305
+ principal: "none",
306
+ ercs: [],
307
+ input: z.object({ operationId: z.string().min(1) }),
308
+ output: OperationOutput.nullable(),
309
+ async handler({ node, caller }, { operationId }) {
310
+ const op = node.store.get(operationId);
311
+ if (!op)
312
+ return null;
313
+ if (!mayseeJob(caller, op.caller))
314
+ return null;
315
+ return { key: op.key, kind: op.kind, signer: op.signer, status: op.status, txHash: op.txHash, block: op.block, nonce: op.nonce, attempts: op.attempts, replacements: op.replacements, error: op.error, capability: op.capability, caller: op.caller, valueWei: op.valueWei.toString(), gasCostWei: op.gasCostWei === null ? null : op.gasCostWei.toString(), result: op.result, updatedAt: op.updatedAt };
316
+ },
317
+ };
318
+ export const job_status = {
319
+ name: "job_status",
320
+ title: "A job's status",
321
+ description: "One job (a tender taken, a skill run): its state, result and the operations it made. A caller sees its own jobs.",
322
+ action: "read",
323
+ visibility: "caller",
324
+ principal: "none",
325
+ ercs: [],
326
+ input: z.object({ jobId: z.string().min(1) }),
327
+ output: JobOutput.nullable(),
328
+ async handler({ node, caller }, { jobId }) {
329
+ const job = node.store.getJob(jobId);
330
+ if (!job || !mayseeJob(caller, job.caller))
331
+ return null;
332
+ return { id: job.id, kind: job.kind, status: job.status, caller: job.caller, inputHash: job.inputHash, operations: job.operations, result: job.result, error: job.error, createdAt: job.createdAt, updatedAt: job.updatedAt };
333
+ },
334
+ };
335
+ export const operation_list = {
336
+ name: "operation_list",
337
+ title: "List jobs and operations",
338
+ description: "The caller's jobs (newest first) with their operations; the operator sees every job and operation of the store.",
339
+ action: "read",
340
+ visibility: "caller",
341
+ principal: "none",
342
+ ercs: [],
343
+ input: z.object({ limit: z.coerce.number().int().min(1).max(500).default(50) }),
344
+ output: z.object({ jobs: z.array(JobOutput), operations: z.array(OperationOutput) }),
345
+ async handler({ node, caller }, { limit }) {
346
+ const jobs = node.store.jobs(caller.visibility === "operator" ? null : caller.id, limit);
347
+ const keys = new Set(jobs.flatMap((j) => j.operations));
348
+ const operations = caller.visibility === "operator" ? node.store.all().slice(-limit) : node.store.all().filter((o) => keys.has(o.key));
349
+ return {
350
+ jobs: jobs.map((job) => ({ id: job.id, kind: job.kind, status: job.status, caller: job.caller, inputHash: job.inputHash, operations: job.operations, result: job.result, error: job.error, createdAt: job.createdAt, updatedAt: job.updatedAt })),
351
+ operations: operations.map((op) => ({ key: op.key, kind: op.kind, signer: op.signer, status: op.status, txHash: op.txHash, block: op.block, nonce: op.nonce, attempts: op.attempts, replacements: op.replacements, error: op.error, capability: op.capability, caller: op.caller, valueWei: op.valueWei.toString(), gasCostWei: op.gasCostWei === null ? null : op.gasCostWei.toString(), result: op.result, updatedAt: op.updatedAt })),
352
+ };
353
+ },
354
+ };
355
+ const DecisionOutput = z.object({ id: z.number(), at: z.string(), entrance: z.string(), caller: z.string(), capability: z.string(), mode: z.string(), inputHash: z.string(), verdict: z.string(), gate: z.string(), reason: z.string(), jobId: z.string().nullable(), operationId: z.string().nullable(), model: z.object({ provider: z.string(), model: z.string(), promptHash: z.string(), responseHash: z.string() }).nullable() });
356
+ export const decision_list = {
357
+ name: "decision_list",
358
+ title: "List decision records",
359
+ description: "Decision records, oldest first: every act attempt, allowed or refused, with the gate and reason. A caller sees its own; the operator every one.",
360
+ action: "read",
361
+ visibility: "caller",
362
+ principal: "none",
363
+ ercs: [],
364
+ input: z.object({ capability: z.string().optional(), verdict: z.enum(["allowed", "refused"]).optional(), limit: z.coerce.number().int().min(1).max(1000).default(200) }),
365
+ output: z.object({ decisions: z.array(DecisionOutput) }),
366
+ async handler({ node, caller }, input) {
367
+ const decisions = node.store.decisions({ caller: caller.visibility === "operator" ? null : caller.id, capability: input.capability, verdict: input.verdict, limit: input.limit });
368
+ return { decisions };
369
+ },
370
+ };
371
+ export const evidence_export = {
372
+ name: "evidence_export",
373
+ title: "Export the node's evidence",
374
+ description: "The operator's view of the store: every decision record, job, operation and fact, with the store's summary — what a reviewer of the node's conduct reads.",
375
+ action: "read",
376
+ visibility: "operator",
377
+ principal: "none",
378
+ ercs: [],
379
+ input: z.object({}),
380
+ output: z.object({ schema: z.literal("foga.node-evidence/1"), cell: z.string(), account: zAddress, worldId: z.string(), exportedAt: z.string(), summary: z.unknown(), decisions: z.array(DecisionOutput), jobs: z.array(JobOutput), operations: z.array(OperationOutput), facts: z.record(z.string(), z.unknown()) }),
381
+ async handler({ node }) {
382
+ const ops = node.store.all();
383
+ return {
384
+ schema: "foga.node-evidence/1",
385
+ cell: node.config.name,
386
+ account: node.body.address,
387
+ worldId: node.world.file.worldId,
388
+ exportedAt: new Date().toISOString(),
389
+ summary: node.store.summary(),
390
+ decisions: node.store.decisions({ limit: 100_000 }),
391
+ jobs: node.store.jobs(null, 100_000).map((job) => ({ id: job.id, kind: job.kind, status: job.status, caller: job.caller, inputHash: job.inputHash, operations: job.operations, result: job.result, error: job.error, createdAt: job.createdAt, updatedAt: job.updatedAt })),
392
+ operations: ops.map((op) => ({ key: op.key, kind: op.kind, signer: op.signer, status: op.status, txHash: op.txHash, block: op.block, nonce: op.nonce, attempts: op.attempts, replacements: op.replacements, error: op.error, capability: op.capability, caller: op.caller, valueWei: op.valueWei.toString(), gasCostWei: op.gasCostWei === null ? null : op.gasCostWei.toString(), result: op.result, updatedAt: op.updatedAt })),
393
+ facts: JSON.parse(JSON.stringify(node.store.facts(), (_k, v) => str(v))),
394
+ };
395
+ },
396
+ };
397
+ export const kya_check = {
398
+ name: "kya_check",
399
+ title: "Check a KYA level",
400
+ description: "An account's level under a KYA scheme as resolved by the registry for the given issuers (the cell's standing scheme and issuers by default).",
401
+ action: "read",
402
+ visibility: "public",
403
+ principal: "none",
404
+ ercs: [8419],
405
+ input: z.object({ address: zAddress, schemeId: zBytes32.optional(), issuers: z.array(zAddress).optional(), minLevel: z.coerce.number().int().min(0).optional() }),
406
+ output: z.object({ address: zAddress, schemeId: zBytes32, issuers: z.array(zAddress), level: z.number(), expiresAt: z.number(), assertionId: zBytes32, meets: z.boolean().nullable() }),
407
+ async handler({ node }, input) {
408
+ const st = node.config.identity.standing;
409
+ const schemeId = input.schemeId ?? st?.schemeId;
410
+ const issuers = input.issuers ?? st?.issuers;
411
+ if (!schemeId || !issuers?.length)
412
+ throw new Error("no scheme: pass schemeId and issuers, or configure identity.standing");
413
+ const subject = accountSubject(node.chainId, input.address);
414
+ const r = await node.kernel.kya.resolve(subject, schemeId, issuers);
415
+ const meets = input.minLevel === undefined ? null : await node.kernel.kya.check(subject, schemeId, input.minLevel, issuers);
416
+ return { address: getAddress(input.address), schemeId, issuers, level: r.level, expiresAt: Number(r.expiresAt), assertionId: r.assertionId, meets };
417
+ },
418
+ };
419
+ export const safety_status = {
420
+ name: "safety_status",
421
+ title: "Safety status",
422
+ description: "The ERC-8468 verdict on a cell account (the node's own by default): verdict, reasons, restrictions, the presented bindings and their states.",
423
+ action: "read",
424
+ visibility: "public",
425
+ principal: "none",
426
+ ercs: [8468],
427
+ input: z.object({ address: zAddress.optional() }),
428
+ output: z.object({ address: zAddress, verdict: z.string(), reasons: z.array(z.string()), restrictions: z.array(z.number()), bindings: z.array(z.object({ bindingId: zBytes32, state: z.string(), restrictions: z.number(), validUntil: z.number() })) }),
429
+ async handler({ node }, input) {
430
+ const { Cell } = await import("../kernel/cell.js");
431
+ const { BindingStateName } = await import("../core/asf.js");
432
+ const address = getAddress(input.address ?? node.body.address);
433
+ const cell = input.address && getAddress(input.address) !== getAddress(node.body.address) ? new Cell(node.kernel, "probe", address, { owner: "owner", operator: "operator", guardian: address }) : node.body;
434
+ const [status, ids] = await Promise.all([cell.status(), cell.presentedBindings()]);
435
+ const bindings = [];
436
+ for (const bindingId of ids) {
437
+ const b = await node.kernel.asf.bindingOf(bindingId);
438
+ bindings.push({ bindingId, state: BindingStateName[b.state] ?? String(b.state), restrictions: b.restrictions, validUntil: Number(b.validUntil) });
439
+ }
440
+ return { address, verdict: status.verdictName, reasons: status.reasonNames, restrictions: status.restrictions, bindings };
441
+ },
442
+ };
443
+ /** The texts a caller (or a model) may read rules from; each ships in the package, so no vendor checkout is needed. */
444
+ export const SPEC_TEXTS = ["foga-cell-v1", "policy", "compatibility-matrix", "cell-config-schema"];
445
+ export const spec_read = {
446
+ name: "spec_read",
447
+ title: "Read a rule text",
448
+ description: "The texts the cell acts under: the FOGA-Cell-v1 safety specification it adopted, its own policy block, the compatibility matrix of the ten standards, and the schema of the cell configuration.",
449
+ action: "read",
450
+ visibility: "public",
451
+ principal: "none",
452
+ ercs: [8468],
453
+ input: z.object({ name: z.enum(SPEC_TEXTS) }),
454
+ output: z.object({ name: z.string(), mediaType: z.string(), text: z.string() }),
455
+ async handler({ node }, { name }) {
456
+ const { fogaCellSpecification } = await import("../core/asf.js");
457
+ const { CellConfigSchema } = await import("../node/config.js");
458
+ const { repoRoot } = await import("../util/fs.js");
459
+ if (name === "foga-cell-v1")
460
+ return { name, mediaType: "application/json", text: JSON.stringify(fogaCellSpecification(), null, 2) };
461
+ if (name === "policy")
462
+ return { name, mediaType: "application/json", text: JSON.stringify(node.config.policy, null, 2) };
463
+ if (name === "cell-config-schema")
464
+ return { name, mediaType: "application/schema+json", text: JSON.stringify(z.toJSONSchema(CellConfigSchema, { target: "draft-2020-12", io: "input" }), null, 2) };
465
+ const path = join(repoRoot(), "docs", "compatibility-matrix.md");
466
+ if (!existsSync(path))
467
+ throw new Error("the compatibility matrix is not in this installation");
468
+ return { name, mediaType: "text/markdown", text: readFileSync(path, "utf8") };
469
+ },
470
+ };
471
+ export const READ_CAPABILITIES = [world_describe, identity_resolve, tender_list, tender_inspect, skill_list, skill_inspect, cell_status, operation_status, job_status, operation_list, decision_list, evidence_export, kya_check, safety_status, spec_read];