@useopentab/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1821 @@
1
+ import {
2
+ KeyFileAccountSigner,
3
+ acceptedVerifyUrls,
4
+ agentWalletProof,
5
+ defaultKeyDir,
6
+ destroyWallet,
7
+ evaluateBadge,
8
+ externalKeyIdEquals,
9
+ fetchAgentCard,
10
+ generateKeyFile,
11
+ keyFilePath,
12
+ loadWalletExport,
13
+ parseCaip10Account,
14
+ readKeyFile
15
+ } from "./chunk-IRXOU25X.js";
16
+ import {
17
+ accountCaip10,
18
+ agentBadge,
19
+ contractCaip,
20
+ isAccountAddress
21
+ } from "./chunk-HZHOKJIM.js";
22
+ import {
23
+ BADGE_EXTENSION_URI,
24
+ CIS8,
25
+ CIS8004,
26
+ HOSTED_MCP_URL,
27
+ HOSTED_REST_BASE,
28
+ TESTNET_CAIP2 as TESTNET_CAIP22
29
+ } from "./chunk-S5IAH7CT.js";
30
+ import {
31
+ BUREAU_CONTRACT_NAME,
32
+ BUREAU_ENTRYPOINTS,
33
+ CIS8_CANONICAL_TAG,
34
+ PROOF_SCHEME_SOLANA_ED25519,
35
+ SESSION_KEY_NAMESPACE,
36
+ TESTNET_CAIP2,
37
+ TESTNET_CIS8,
38
+ TESTNET_CIS8004,
39
+ TESTNET_GENESIS_HEX,
40
+ accountAddressFromBase58,
41
+ agentMetadataEntry,
42
+ bureauErrorName,
43
+ bytesEqual,
44
+ cis8CanonicalMessage,
45
+ contractAddress,
46
+ contractAddressEqual,
47
+ decodeBureauEvent,
48
+ decodeCis8004Event,
49
+ decodeCis8Event,
50
+ decodeSellerOfResult,
51
+ ed25519KeyId,
52
+ encodeExternalKeyId,
53
+ encodeRegisterExternalKeyParams,
54
+ encodeRegisterSellerParams,
55
+ encodeSellerOfParams,
56
+ encodeSetAgentWalletParams,
57
+ encodeWith,
58
+ externalKeyIdEqual,
59
+ externalReference,
60
+ formatContractAddress,
61
+ fromHex,
62
+ fromUtf8,
63
+ parseContractAddress,
64
+ policyHash,
65
+ setAgentWalletMessage,
66
+ sha256,
67
+ singleKeyAccountSignatures,
68
+ toHex,
69
+ utf8,
70
+ verifyCis8Canonical,
71
+ wire
72
+ } from "./chunk-D3C7KAMJ.js";
73
+
74
+ // packages/onboard/src/errors.ts
75
+ var OnboardError = class extends Error {
76
+ name = "OnboardError";
77
+ code;
78
+ constructor(code, message, options) {
79
+ super(message, options);
80
+ this.code = code;
81
+ }
82
+ };
83
+ function errorCode(err) {
84
+ return err instanceof OnboardError ? err.code : "error";
85
+ }
86
+ function errorMessage(err) {
87
+ return err instanceof Error ? err.message : String(err);
88
+ }
89
+
90
+ // packages/onboard/src/jcs.ts
91
+ import canonicalize from "canonicalize";
92
+ function jcsBytes(value) {
93
+ const text3 = canonicalize(value);
94
+ if (typeof text3 !== "string") throw new OnboardError("invalid_input", "value has no canonical JSON form");
95
+ return utf8(text3);
96
+ }
97
+ function sha256Hex(bytes) {
98
+ return toHex(sha256(bytes));
99
+ }
100
+
101
+ // packages/onboard/src/badge.ts
102
+ import { z } from "zod";
103
+ var MAX_TEXT = 2048;
104
+ var text = z.string().min(1).max(MAX_TEXT);
105
+ var badgeParamsSchema = z.object({
106
+ tokenAddress: text,
107
+ owner: z.object({ account: text }).loose(),
108
+ agentWallet: text,
109
+ contracts: z.object({ cis8004: text, cis8: text }).loose(),
110
+ verify: text,
111
+ verification: z.object({ service: text.optional(), verifyUrl: text, mcp: text.optional(), docs: text.optional() }).loose()
112
+ }).loose();
113
+ var badgeExtensionSchema = z.object({
114
+ uri: z.literal(BADGE_EXTENSION_URI),
115
+ description: z.string().max(MAX_TEXT),
116
+ required: z.boolean(),
117
+ params: badgeParamsSchema
118
+ }).strict();
119
+ var registrationSchema = z.object({ agentId: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER), agentRegistry: text }).strict();
120
+ var BADGE_DESCRIPTION = "Verified by Concordium badge \u2014 on-chain agent identity in a CIS-8004 registry";
121
+ var BADGE_VERIFY = "Resolve tokenAddress via CIS-8004 agent_of; confirm owner + status=Active + card SHA-256 == metadata_hash.";
122
+ var BADGE_DOCS = "https://docs.concordium.com/en/mainnet/technical-reference/agent-registry/concordium-badge.html";
123
+ function assertSubject(s) {
124
+ if (!isAccountAddress(s.owner)) throw new OnboardError("invalid_input", "owner is not an account address");
125
+ if (!isAccountAddress(s.agentWallet)) throw new OnboardError("invalid_input", "agentWallet is not an account address");
126
+ if (s.tokenId < 0n || s.tokenId > BigInt(Number.MAX_SAFE_INTEGER)) throw new OnboardError("invalid_input", "token id out of range");
127
+ }
128
+ function badgeRegistration(tokenId) {
129
+ return { agentId: Number(tokenId), agentRegistry: contractCaip(CIS8004.address, TESTNET_CAIP22) };
130
+ }
131
+ function localBadge(s) {
132
+ assertSubject(s);
133
+ const badge = agentBadge(s.tokenId);
134
+ const extension = {
135
+ uri: BADGE_EXTENSION_URI,
136
+ description: BADGE_DESCRIPTION,
137
+ required: false,
138
+ params: {
139
+ tokenAddress: `${TESTNET_CAIP22}/cis-2:${badge}`,
140
+ owner: { account: accountCaip10(s.owner, TESTNET_CAIP22) },
141
+ agentWallet: accountCaip10(s.agentWallet, TESTNET_CAIP22),
142
+ contracts: { cis8004: contractCaip(CIS8004.address, TESTNET_CAIP22), cis8: contractCaip(CIS8.address, TESTNET_CAIP22) },
143
+ verify: BADGE_VERIFY,
144
+ verification: {
145
+ service: "Concordium Agent Registry",
146
+ verifyUrl: `${HOSTED_REST_BASE}/v1/badge-check/${badge}`,
147
+ mcp: HOSTED_MCP_URL,
148
+ docs: BADGE_DOCS
149
+ }
150
+ }
151
+ };
152
+ return { extension, registrations: [badgeRegistration(s.tokenId)] };
153
+ }
154
+ function isRecord(v) {
155
+ return typeof v === "object" && v !== null && !Array.isArray(v);
156
+ }
157
+ function badgeFromMcpCard(cardJson) {
158
+ if (cardJson.length > 65536) throw new OnboardError("badge_invalid", "MCP card exceeds 64 KiB");
159
+ let card;
160
+ try {
161
+ card = JSON.parse(cardJson);
162
+ } catch {
163
+ throw new OnboardError("badge_invalid", "MCP card is not JSON");
164
+ }
165
+ if (!isRecord(card)) throw new OnboardError("badge_invalid", "MCP card is not an object");
166
+ const caps = card.capabilities;
167
+ const exts = isRecord(caps) && Array.isArray(caps.extensions) ? caps.extensions : [];
168
+ const found = exts.filter((e) => isRecord(e) && e.uri === BADGE_EXTENSION_URI);
169
+ if (found.length !== 1) throw new OnboardError("badge_invalid", `MCP card has ${found.length} badge extensions, expected 1`);
170
+ const extension = badgeExtensionSchema.safeParse(found[0]);
171
+ if (!extension.success) throw new OnboardError("badge_invalid", `MCP badge extension is malformed: ${extension.error.issues[0]?.message ?? ""}`);
172
+ const regs = z.array(registrationSchema).max(16).safeParse(card.registrations ?? []);
173
+ if (!regs.success) throw new OnboardError("badge_invalid", "MCP card registrations are malformed");
174
+ return { extension: extension.data, registrations: regs.data };
175
+ }
176
+ function badgeIssues(badge, s) {
177
+ assertSubject(s);
178
+ const p = badge.extension.params;
179
+ const issues = [];
180
+ const id = agentBadge(s.tokenId);
181
+ if (p.tokenAddress !== `${TESTNET_CAIP22}/cis-2:${id}`) issues.push("tokenAddress does not name this agent");
182
+ if (p.owner.account !== accountCaip10(s.owner, TESTNET_CAIP22)) issues.push("owner does not match");
183
+ if (parseCaip10Account(p.agentWallet, TESTNET_CAIP22) !== s.agentWallet) issues.push("agentWallet does not equal the agent wallet");
184
+ if (p.contracts.cis8004 !== contractCaip(CIS8004.address, TESTNET_CAIP22) || p.contracts.cis8 !== contractCaip(CIS8.address, TESTNET_CAIP22)) {
185
+ issues.push("registry contracts do not match testnet");
186
+ }
187
+ if (!acceptedVerifyUrls(id).has(p.verification.verifyUrl)) issues.push("verifyUrl is not the hosted check-badge URL");
188
+ const reg = badge.registrations.find((r) => r.agentRegistry === contractCaip(CIS8004.address, TESTNET_CAIP22));
189
+ if (reg === void 0 || BigInt(reg.agentId) !== s.tokenId) issues.push("registrations entry does not name this agent");
190
+ return issues;
191
+ }
192
+ function badgeDifferences(a, b) {
193
+ const pa = a.extension.params;
194
+ const pb = b.extension.params;
195
+ const diffs = [];
196
+ const pairs = [
197
+ ["tokenAddress", pa.tokenAddress, pb.tokenAddress],
198
+ ["owner.account", pa.owner.account, pb.owner.account],
199
+ ["agentWallet", pa.agentWallet, pb.agentWallet],
200
+ ["contracts.cis8004", pa.contracts.cis8004, pb.contracts.cis8004],
201
+ ["contracts.cis8", pa.contracts.cis8, pb.contracts.cis8],
202
+ ["verification.verifyUrl", pa.verification.verifyUrl, pb.verification.verifyUrl]
203
+ ];
204
+ for (const [name, x, y] of pairs) if (x !== y) diffs.push(name);
205
+ const ra = JSON.stringify(a.registrations);
206
+ const rb = JSON.stringify(b.registrations);
207
+ if (ra !== rb) diffs.push("registrations");
208
+ return diffs;
209
+ }
210
+
211
+ // packages/agent-kit/src/a2a/card.ts
212
+ import { z as z2 } from "zod";
213
+ var A2A_JSONRPC_PATH = "/a2a/v1";
214
+ var BADGE_EXTENSION_URI2 = "https://docs.concordium.com/a2a-extensions/concordium-badge/v1";
215
+ var CCD_TAB_EXTENSION_URI = "urn:ccd-tab:v1";
216
+ var MAX_LIST = 256;
217
+ var text2 = (max = 8192) => z2.string().max(max);
218
+ var nonEmpty = (max = 8192) => z2.string().min(1).max(max);
219
+ var list = (item, max = MAX_LIST) => z2.array(item).max(max);
220
+ function isHttpUrl(s) {
221
+ try {
222
+ const u = new URL(s);
223
+ return (u.protocol === "https:" || u.protocol === "http:") && u.username === "" && u.password === "";
224
+ } catch {
225
+ return false;
226
+ }
227
+ }
228
+ var HttpUrlSchema = z2.string().max(2048).refine(isHttpUrl, "expected an absolute http(s) URL without credentials");
229
+ var u64String = z2.string().regex(/^(0|[1-9][0-9]{0,19})$/, "expected a u64 decimal string").refine((s) => BigInt(s) < 1n << 64n, "out of u64 range");
230
+ var AgentProviderSchema = z2.looseObject({ url: nonEmpty(2048), organization: nonEmpty(512) });
231
+ var AgentExtensionSchema = z2.looseObject({
232
+ uri: text2(2048).optional(),
233
+ description: text2().optional(),
234
+ required: z2.boolean().optional(),
235
+ params: z2.record(z2.string(), z2.unknown()).optional()
236
+ });
237
+ var AgentCapabilitiesSchema = z2.looseObject({
238
+ streaming: z2.boolean().optional(),
239
+ pushNotifications: z2.boolean().optional(),
240
+ extensions: list(AgentExtensionSchema, 64).optional(),
241
+ extendedAgentCard: z2.boolean().optional()
242
+ });
243
+ var SecurityRequirementSchema = z2.record(z2.string(), z2.unknown());
244
+ var AgentSkillSchema = z2.looseObject({
245
+ id: nonEmpty(128),
246
+ name: nonEmpty(256),
247
+ description: nonEmpty(),
248
+ tags: list(text2(128), 64),
249
+ examples: list(text2(), 64).optional(),
250
+ inputModes: list(nonEmpty(128), 32).optional(),
251
+ outputModes: list(nonEmpty(128), 32).optional(),
252
+ securityRequirements: list(SecurityRequirementSchema, 32).optional()
253
+ });
254
+ var AgentInterfaceSchema = z2.looseObject({
255
+ url: nonEmpty(2048),
256
+ protocolBinding: nonEmpty(64),
257
+ protocolVersion: z2.string().regex(/^\d{1,3}\.\d{1,3}(\.\d{1,3})?$/, "expected Major.Minor"),
258
+ tenant: text2(256).optional()
259
+ }).superRefine((v, ctx) => {
260
+ if ((v.protocolBinding === "JSONRPC" || v.protocolBinding === "HTTP+JSON") && !isHttpUrl(v.url)) {
261
+ ctx.addIssue({ code: "custom", path: ["url"], message: `${v.protocolBinding} interfaces need an http(s) URL` });
262
+ }
263
+ });
264
+ var AgentCardSignatureSchema = z2.looseObject({
265
+ protected: nonEmpty(8192),
266
+ signature: nonEmpty(8192),
267
+ header: z2.record(z2.string(), z2.unknown()).optional()
268
+ });
269
+ var BadgeParamsSchema = z2.looseObject({
270
+ tokenAddress: nonEmpty(512),
271
+ owner: z2.looseObject({ account: nonEmpty(512) }),
272
+ agentWallet: nonEmpty(512).optional(),
273
+ contracts: z2.looseObject({ cis8004: nonEmpty(512), cis8: nonEmpty(512) }),
274
+ verify: nonEmpty(),
275
+ verification: z2.looseObject({ verifyUrl: HttpUrlSchema })
276
+ });
277
+ var CcdTabParamsSchema = z2.looseObject({
278
+ binding: z2.literal("ccd-tab/v1"),
279
+ network: z2.string().regex(/^ccd:[0-9a-f]{32}$/, "expected a Concordium CAIP-2 id"),
280
+ bureau: z2.looseObject({ index: u64String, subindex: u64String }),
281
+ sessionKeyNamespace: nonEmpty(128),
282
+ assets: list(nonEmpty(32), 8).min(1),
283
+ termsUrl: HttpUrlSchema.optional(),
284
+ handshakeUrl: HttpUrlSchema.optional()
285
+ });
286
+ function checkExtensions(extensions, ctx) {
287
+ const seen = /* @__PURE__ */ new Set();
288
+ (extensions ?? []).forEach((ext, i) => {
289
+ const path3 = ["capabilities", "extensions", i];
290
+ if (ext.uri === void 0) return;
291
+ if (seen.has(ext.uri)) ctx.addIssue({ code: "custom", path: [...path3, "uri"], message: "duplicate extension uri" });
292
+ seen.add(ext.uri);
293
+ const schema = ext.uri === BADGE_EXTENSION_URI2 ? BadgeParamsSchema : ext.uri === CCD_TAB_EXTENSION_URI ? CcdTabParamsSchema : null;
294
+ if (schema === null) return;
295
+ const parsed = schema.safeParse(ext.params);
296
+ if (!parsed.success) {
297
+ for (const issue of parsed.error.issues) {
298
+ ctx.addIssue({ code: "custom", path: [...path3, "params", ...issue.path.map((p) => typeof p === "symbol" ? String(p) : p)], message: issue.message });
299
+ }
300
+ }
301
+ });
302
+ }
303
+ var AgentCardSchema = z2.looseObject({
304
+ name: nonEmpty(256),
305
+ description: nonEmpty(),
306
+ supportedInterfaces: list(AgentInterfaceSchema, 16).min(1),
307
+ provider: AgentProviderSchema.optional(),
308
+ version: nonEmpty(64),
309
+ documentationUrl: text2(2048).optional(),
310
+ capabilities: AgentCapabilitiesSchema,
311
+ securitySchemes: z2.record(z2.string(), z2.unknown()).optional(),
312
+ securityRequirements: list(SecurityRequirementSchema, 32).optional(),
313
+ defaultInputModes: list(nonEmpty(128), 32),
314
+ defaultOutputModes: list(nonEmpty(128), 32),
315
+ skills: list(AgentSkillSchema, 128),
316
+ signatures: list(AgentCardSignatureSchema, 16).optional(),
317
+ iconUrl: text2(2048).optional()
318
+ }).superRefine((card, ctx) => {
319
+ checkExtensions(card.capabilities.extensions, ctx);
320
+ const ids = /* @__PURE__ */ new Set();
321
+ card.skills.forEach((s, i) => {
322
+ if (ids.has(s.id)) ctx.addIssue({ code: "custom", path: ["skills", i, "id"], message: "duplicate skill id" });
323
+ ids.add(s.id);
324
+ });
325
+ });
326
+ var UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: false });
327
+ function ccdTabExtension(input) {
328
+ const params = CcdTabParamsSchema.parse({
329
+ binding: "ccd-tab/v1",
330
+ network: input.network ?? TESTNET_CAIP2,
331
+ bureau: { index: input.bureau.index.toString(), subindex: input.bureau.subindex.toString() },
332
+ sessionKeyNamespace: SESSION_KEY_NAMESPACE,
333
+ assets: ["CCD"],
334
+ ...input.termsUrl === void 0 ? {} : { termsUrl: input.termsUrl },
335
+ ...input.handshakeUrl === void 0 ? {} : { handshakeUrl: input.handshakeUrl }
336
+ });
337
+ return {
338
+ uri: CCD_TAB_EXTENSION_URI,
339
+ description: "Pays and accepts metered calls on ccd-tab/v1 tabs (Concordium testnet)",
340
+ required: false,
341
+ params
342
+ };
343
+ }
344
+
345
+ // packages/onboard/src/card.ts
346
+ import { z as z3 } from "zod";
347
+ var A2A_PROTOCOL_VERSION = "1.0";
348
+ var HANDSHAKE_WELL_KNOWN = "/.well-known/ccd-tab/handshake";
349
+ var TERMS_WELL_KNOWN = "/.well-known/ccd-tab/terms";
350
+ var MAX_CARD_BYTES = 65536;
351
+ var shortText = z3.string().min(1).max(256);
352
+ var longText = z3.string().min(1).max(4096);
353
+ var mediaType = z3.string().min(1).max(128);
354
+ var httpsUrl = z3.string().max(2048).refine((s) => {
355
+ try {
356
+ const u = new URL(s);
357
+ return u.protocol === "https:" && u.username === "" && u.password === "";
358
+ } catch {
359
+ return false;
360
+ }
361
+ }, "expected an https URL");
362
+ var agentSkillSchema = z3.object({
363
+ id: shortText,
364
+ name: shortText,
365
+ description: longText,
366
+ tags: z3.array(shortText).max(32),
367
+ examples: z3.array(longText).max(16).optional(),
368
+ inputModes: z3.array(mediaType).max(16).optional(),
369
+ outputModes: z3.array(mediaType).max(16).optional()
370
+ }).strict();
371
+ var agentInterfaceSchema = z3.object({ url: httpsUrl, protocolBinding: shortText, protocolVersion: shortText, tenant: shortText.optional() }).strict();
372
+ var agentServiceSchema = z3.object({ name: shortText, endpoint: httpsUrl, version: shortText.optional() }).strict();
373
+ var extensionSchema = z3.object({ uri: z3.string().min(1).max(2048), description: z3.string().max(4096).optional(), required: z3.boolean().optional(), params: z3.record(z3.string(), z3.unknown()).optional() }).loose();
374
+ var agentCardSchema = z3.object({
375
+ name: shortText,
376
+ description: longText,
377
+ supportedInterfaces: z3.array(agentInterfaceSchema).min(1).max(16),
378
+ provider: z3.object({ url: httpsUrl, organization: shortText }).strict().optional(),
379
+ version: shortText,
380
+ documentationUrl: httpsUrl.optional(),
381
+ capabilities: z3.object({
382
+ streaming: z3.boolean().optional(),
383
+ pushNotifications: z3.boolean().optional(),
384
+ extendedAgentCard: z3.boolean().optional(),
385
+ extensions: z3.array(extensionSchema).max(32).optional()
386
+ }).strict(),
387
+ defaultInputModes: z3.array(mediaType).min(1).max(16),
388
+ defaultOutputModes: z3.array(mediaType).min(1).max(16),
389
+ skills: z3.array(agentSkillSchema).max(64),
390
+ iconUrl: httpsUrl.optional(),
391
+ services: z3.array(agentServiceSchema).max(32).optional(),
392
+ registrations: z3.array(registrationSchema).max(16).optional()
393
+ }).loose();
394
+ function normalizeBaseUrl(raw) {
395
+ let u;
396
+ try {
397
+ u = new URL(raw);
398
+ } catch {
399
+ throw new OnboardError("invalid_input", `publicBaseUrl ${JSON.stringify(raw)} is not a URL`);
400
+ }
401
+ if (u.protocol !== "https:") throw new OnboardError("invalid_input", "publicBaseUrl must be https");
402
+ if (u.username !== "" || u.password !== "" || u.search !== "" || u.hash !== "") {
403
+ throw new OnboardError("invalid_input", "publicBaseUrl must not carry credentials, a query or a fragment");
404
+ }
405
+ return `${u.origin}${u.pathname.replace(/\/+$/, "")}`;
406
+ }
407
+ function ccdTabExtension2(input, base, agentWallet) {
408
+ const ext = ccdTabExtension({
409
+ bureau: input.bureau,
410
+ ...input.role === "seller" ? { handshakeUrl: input.handshakeUrl ?? `${base}${HANDSHAKE_WELL_KNOWN}`, termsUrl: input.termsUrl ?? `${base}${TERMS_WELL_KNOWN}` } : {}
411
+ });
412
+ const params = { ...ext.params, role: input.role, agentWallet: accountCaip10(agentWallet, TESTNET_CAIP22) };
413
+ if (input.staged === true) params.staged = true;
414
+ return { uri: ext.uri, description: ext.description, required: false, params };
415
+ }
416
+ function buildAgentCard(input) {
417
+ const base = normalizeBaseUrl(input.publicBaseUrl);
418
+ if (!isAccountAddress(input.agentWallet)) throw new OnboardError("invalid_input", "agentWallet is not an account address");
419
+ if (input.ccdTab?.staged === true && !/\bSTAGED\b/.test(input.description)) {
420
+ throw new OnboardError("card_invalid", "a staged agent must say STAGED in its description");
421
+ }
422
+ const extensions = [];
423
+ const card = {
424
+ name: input.name,
425
+ description: input.description,
426
+ supportedInterfaces: input.interfaces ?? [{ url: `${base}${A2A_JSONRPC_PATH}`, protocolBinding: "JSONRPC", protocolVersion: A2A_PROTOCOL_VERSION }],
427
+ version: input.version ?? "1.0.0",
428
+ capabilities: { streaming: false, pushNotifications: false, extensions },
429
+ defaultInputModes: input.defaultInputModes ?? ["application/json"],
430
+ defaultOutputModes: input.defaultOutputModes ?? ["application/json"],
431
+ skills: input.skills
432
+ };
433
+ if (input.provider !== void 0) card.provider = { organization: input.provider.organization, url: input.provider.url };
434
+ if (input.documentationUrl !== void 0) card.documentationUrl = input.documentationUrl;
435
+ if (input.iconUrl !== void 0) card.iconUrl = input.iconUrl;
436
+ if (input.services !== void 0 && input.services.length > 0) card.services = input.services;
437
+ if (input.badge !== void 0) {
438
+ const ext = badgeExtensionSchema.safeParse(input.badge.extension);
439
+ if (!ext.success) throw new OnboardError("badge_invalid", "the badge extension is malformed");
440
+ if (ext.data.params.agentWallet !== accountCaip10(input.agentWallet, TESTNET_CAIP22)) {
441
+ throw new OnboardError("badge_invalid", "the badge names another wallet than the agent wallet");
442
+ }
443
+ extensions.push(ext.data);
444
+ card.registrations = input.badge.registrations;
445
+ }
446
+ if (input.ccdTab !== void 0) extensions.push(ccdTabExtension2(input.ccdTab, base, input.agentWallet));
447
+ const parsed = agentCardSchema.safeParse(card);
448
+ if (!parsed.success) {
449
+ const issue = parsed.error.issues[0];
450
+ throw new OnboardError("card_invalid", `card does not match A2A v1.0: ${issue?.path.join(".") ?? ""} ${issue?.message ?? ""}`.trim());
451
+ }
452
+ const bytes = jcsBytes(parsed.data);
453
+ if (bytes.length > MAX_CARD_BYTES) throw new OnboardError("card_invalid", `card is ${bytes.length} bytes, over ${MAX_CARD_BYTES}`);
454
+ const sha2562 = sha256Hex(bytes);
455
+ return { card: parsed.data, bytes, sha256: sha2562, url: `${base}/cards/${sha2562}.json` };
456
+ }
457
+
458
+ // packages/onboard/src/explorer.ts
459
+ var EXPLORER_BASE = "https://ccdexplorer.io/testnet";
460
+ var explorerTx = (hash) => `${EXPLORER_BASE}/transaction/${hash}`;
461
+ var explorerAccount = (address2) => `${EXPLORER_BASE}/account/${address2}`;
462
+
463
+ // packages/onboard/src/plan.ts
464
+ import { randomBytes } from "node:crypto";
465
+ import { promises as fsp } from "node:fs";
466
+ import path from "node:path";
467
+ import { z as z4 } from "zod";
468
+ var PLAN_FORMAT = "opentab-onboard-plan/v1";
469
+ var MAX_PLAN_BYTES = 256 * 1024;
470
+ var STEP_NAMES = ["register", "setAgentWallet", "sessionKey", "badge", "role"];
471
+ var STEP_STATUSES = [
472
+ "pending",
473
+ "awaiting_signature",
474
+ "submitted",
475
+ "pending_hosting",
476
+ "awaiting_owner",
477
+ "done",
478
+ "skipped",
479
+ "failed"
480
+ ];
481
+ var address = z4.string().max(64).refine(isAccountAddress, "an account address");
482
+ var hex32 = z4.string().regex(/^[0-9a-f]{64}$/, "32 bytes of lowercase hex");
483
+ var hex = z4.string().regex(/^([0-9a-f]{2}){0,65536}$/, "lowercase hex");
484
+ var u64 = z4.string().regex(/^(0|[1-9][0-9]{0,19})$/, "a u64 decimal string").refine((s) => BigInt(s) < 1n << 64n, "u64 out of range");
485
+ var contract = z4.string().regex(/^<\d{1,20},\d{1,20}>$/, "`<index,subindex>`");
486
+ var keyName = z4.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/);
487
+ var sellerPolicySchema = z4.object({
488
+ maxTabLimit: u64,
489
+ minBuyerTier: z4.number().int().min(0).max(2),
490
+ minBuyerK: z4.number().int().min(0).max(255),
491
+ minCycleMs: u64,
492
+ maxCycleMs: u64,
493
+ maxNewTabsPerDay: z4.number().int().min(0).max(4294967295),
494
+ priceScheduleHash: hex32,
495
+ admitBadgeInvalid: z4.boolean()
496
+ }).strict().refine((p) => BigInt(p.minCycleMs) <= BigInt(p.maxCycleMs), "minCycleMs must not exceed maxCycleMs");
497
+ var agentSpecSchema = z4.object({
498
+ name: z4.string().min(1).max(128),
499
+ description: z4.string().min(1).max(2048),
500
+ skills: z4.array(agentSkillSchema).max(64),
501
+ role: z4.enum(["buyer", "seller", "operator"]),
502
+ owner: address,
503
+ agentWallet: address,
504
+ /** Where the agent's cards are served (`<publicBaseUrl>/cards/<sha256>.json`). */
505
+ publicBaseUrl: z4.string().max(2048),
506
+ /** The web app origin that serves the openLine consent page (buyers). */
507
+ webBaseUrl: z4.string().max(2048),
508
+ staged: z4.boolean(),
509
+ sessionKey: z4.object({
510
+ name: keyName,
511
+ role: z4.enum(["buyer", "seller", "attestor", "ci-attestor"]),
512
+ /** Refuse to generate: the key must already be in keyd's directory (attestor keys). */
513
+ mustExist: z4.boolean(),
514
+ expectedPublicKey: hex32.nullable()
515
+ }).strict(),
516
+ seller: z4.object({ policy: sellerPolicySchema }).strict().nullable(),
517
+ /** Registers with this URI and hash instead of the pre-badge card (CI probes). */
518
+ register: z4.object({ uri: z4.string().min(1).max(2048), metadataHash: hex32.nullable() }).strict().nullable(),
519
+ services: z4.array(agentServiceSchema).max(32),
520
+ /** Which steps run; the others are skipped. */
521
+ steps: z4.array(z4.enum(STEP_NAMES)).min(1).max(STEP_NAMES.length)
522
+ }).strict().superRefine((s, ctx) => {
523
+ if (s.owner === s.agentWallet) ctx.addIssue({ code: "custom", message: "agentWallet must differ from the owner", path: ["agentWallet"] });
524
+ if (s.role === "seller" && s.seller === null) ctx.addIssue({ code: "custom", message: "a seller needs a policy", path: ["seller"] });
525
+ if (s.role !== "seller" && s.seller !== null) ctx.addIssue({ code: "custom", message: "only sellers take a policy", path: ["seller"] });
526
+ if (new Set(s.steps).size !== s.steps.length) ctx.addIssue({ code: "custom", message: "steps repeat", path: ["steps"] });
527
+ });
528
+ var unsignedPayloadSchema = z4.object({
529
+ kind: z4.literal("UpdateContract"),
530
+ sender: address,
531
+ contract: z4.object({ index: u64, subindex: u64 }).strict(),
532
+ receiveName: z4.string().max(128),
533
+ amountMicroCcd: u64,
534
+ parameterHex: hex,
535
+ maxContractExecutionEnergy: u64
536
+ }).strict();
537
+ var stepRecordSchema = z4.object({
538
+ status: z4.enum(STEP_STATUSES),
539
+ attempts: z4.number().int().min(0).max(1e3),
540
+ txHash: hex32.nullable(),
541
+ explorer: z4.string().max(256).nullable(),
542
+ blockHash: hex32.nullable(),
543
+ /** The signed transaction while it is in flight: resent as is if it never reached the node. */
544
+ pending: z4.object({ transactionHex: hex, expiry: u64 }).strict().nullable(),
545
+ unsigned: unsignedPayloadSchema.nullable(),
546
+ error: z4.object({ code: z4.string().max(64), message: z4.string().max(2048) }).strict().nullable(),
547
+ /** Step facts for the report (consent URL, wallet message, card URL...). Public values only. */
548
+ data: z4.record(z4.string().max(64), z4.string().max(4096)),
549
+ notes: z4.array(z4.string().max(1024)).max(64),
550
+ updatedAt: z4.string().max(64)
551
+ }).strict();
552
+ var cardRef = z4.object({ sha256: hex32, url: z4.string().max(2048), stored: z4.string().max(4096) }).strict();
553
+ var planSchema = z4.object({
554
+ format: z4.literal(PLAN_FORMAT),
555
+ createdAt: z4.string().max(64),
556
+ updatedAt: z4.string().max(64),
557
+ network: z4.literal("testnet"),
558
+ genesis: hex32,
559
+ cis8004: contract,
560
+ cis8: contract,
561
+ bureau: contract,
562
+ spec: agentSpecSchema,
563
+ tokenId: u64.nullable(),
564
+ sessionKey: z4.object({ publicKey: hex32, keyIdHex: hex }).strict().nullable(),
565
+ cards: z4.object({ initial: cardRef.nullable(), badged: cardRef.nullable() }).strict(),
566
+ steps: z4.object({
567
+ register: stepRecordSchema,
568
+ setAgentWallet: stepRecordSchema,
569
+ sessionKey: stepRecordSchema,
570
+ badge: stepRecordSchema,
571
+ role: stepRecordSchema
572
+ })
573
+ }).strict();
574
+ function freshStep(now, skipped) {
575
+ return {
576
+ status: skipped ? "skipped" : "pending",
577
+ attempts: 0,
578
+ txHash: null,
579
+ explorer: null,
580
+ blockHash: null,
581
+ pending: null,
582
+ unsigned: null,
583
+ error: null,
584
+ data: {},
585
+ notes: [],
586
+ updatedAt: now
587
+ };
588
+ }
589
+ function createPlan(input, opts) {
590
+ if (input.owner === input.agentWallet) throw new OnboardError("wallet_is_owner", "the agent wallet must be a different account from the owner");
591
+ const now = (opts.now ?? /* @__PURE__ */ new Date()).toISOString();
592
+ const defaultSteps = input.role === "operator" ? ["register", "setAgentWallet", "sessionKey", "badge"] : [...STEP_NAMES];
593
+ const steps = input.steps ?? defaultSteps;
594
+ const spec = {
595
+ ...input,
596
+ publicBaseUrl: normalizeBaseUrl(input.publicBaseUrl),
597
+ webBaseUrl: normalizeBaseUrl(input.webBaseUrl ?? new URL(input.publicBaseUrl).origin),
598
+ staged: input.staged ?? false,
599
+ seller: input.seller ?? null,
600
+ register: input.register ?? null,
601
+ services: input.services ?? [],
602
+ steps: STEP_NAMES.filter((s) => steps.includes(s)),
603
+ sessionKey: {
604
+ name: input.sessionKey.name,
605
+ role: input.sessionKey.role,
606
+ mustExist: input.sessionKey.mustExist ?? false,
607
+ expectedPublicKey: input.sessionKey.expectedPublicKey ?? null
608
+ }
609
+ };
610
+ const parsed = agentSpecSchema.safeParse(spec);
611
+ if (!parsed.success) {
612
+ const issue = parsed.error.issues[0];
613
+ throw new OnboardError("plan_invalid", `agent spec: ${issue?.path.join(".") ?? ""} ${issue?.message ?? ""}`.trim());
614
+ }
615
+ const record = (name) => freshStep(now, !parsed.data.steps.includes(name));
616
+ return {
617
+ format: PLAN_FORMAT,
618
+ createdAt: now,
619
+ updatedAt: now,
620
+ network: "testnet",
621
+ genesis: TESTNET_GENESIS_HEX,
622
+ cis8004: formatContractAddress(TESTNET_CIS8004),
623
+ cis8: formatContractAddress(TESTNET_CIS8),
624
+ bureau: formatContractAddress(opts.bureau),
625
+ spec: parsed.data,
626
+ tokenId: null,
627
+ sessionKey: null,
628
+ cards: { initial: null, badged: null },
629
+ steps: {
630
+ register: record("register"),
631
+ setAgentWallet: record("setAgentWallet"),
632
+ sessionKey: record("sessionKey"),
633
+ badge: record("badge"),
634
+ role: record("role")
635
+ }
636
+ };
637
+ }
638
+ function parsePlan(json) {
639
+ const parsed = planSchema.safeParse(json);
640
+ if (!parsed.success) {
641
+ const issue = parsed.error.issues[0];
642
+ throw new OnboardError("plan_invalid", `plan: ${issue?.path.join(".") ?? ""} ${issue?.message ?? ""}`.trim());
643
+ }
644
+ if (parsed.data.genesis !== TESTNET_GENESIS_HEX) throw new OnboardError("wrong_network", "the plan is not for testnet");
645
+ return parsed.data;
646
+ }
647
+ function planBureau(plan) {
648
+ return parseContractAddress(plan.bureau);
649
+ }
650
+ var FilePlanStore = class {
651
+ file;
652
+ constructor(file) {
653
+ this.file = path.resolve(file);
654
+ }
655
+ async load() {
656
+ let text3;
657
+ try {
658
+ const stat = await fsp.lstat(this.file);
659
+ if (!stat.isFile()) throw new OnboardError("plan_invalid", `${this.file} is not a regular file`);
660
+ if (stat.size > MAX_PLAN_BYTES) throw new OnboardError("plan_invalid", `${this.file} is larger than ${MAX_PLAN_BYTES} bytes`);
661
+ text3 = await fsp.readFile(this.file, "utf8");
662
+ } catch (e) {
663
+ if (e.code === "ENOENT") return null;
664
+ throw e;
665
+ }
666
+ let json;
667
+ try {
668
+ json = JSON.parse(text3);
669
+ } catch {
670
+ throw new OnboardError("plan_invalid", `${this.file} is not JSON`);
671
+ }
672
+ return parsePlan(json);
673
+ }
674
+ async save(plan) {
675
+ const body = `${JSON.stringify(parsePlan(plan), null, 2)}
676
+ `;
677
+ const dir = path.dirname(this.file);
678
+ await fsp.mkdir(dir, { recursive: true });
679
+ const tmp = path.join(dir, `.${path.basename(this.file)}.${randomBytes(6).toString("hex")}.tmp`);
680
+ const handle = await fsp.open(tmp, "wx", 420);
681
+ try {
682
+ await handle.writeFile(body, "utf8");
683
+ await handle.sync();
684
+ } finally {
685
+ await handle.close();
686
+ }
687
+ await fsp.rename(tmp, this.file);
688
+ }
689
+ };
690
+
691
+ // packages/onboard/src/consent.ts
692
+ var CONSENT_PATH = "/line";
693
+ var DEFAULT_LINE_TERMS = Object.freeze({
694
+ lineLimit: 100000000n,
695
+ perSellerMax: 25000000n,
696
+ maxCycleMs: 86400000n,
697
+ validForMs: 30n * 86400000n
698
+ });
699
+ var U64_MAX = (1n << 64n) - 1n;
700
+ function consentUrl(webBaseUrl, c, nowMs = Date.now()) {
701
+ if (!isAccountAddress(c.owner)) throw new OnboardError("invalid_input", "owner is not an account address");
702
+ if (!/^[0-9a-f]{64}$/.test(c.sessionKeyHex)) throw new OnboardError("invalid_input", "the session key must be 32 bytes of lowercase hex");
703
+ const t = { ...DEFAULT_LINE_TERMS, ...c.terms };
704
+ for (const [name, v] of Object.entries(t)) {
705
+ if (v <= 0n || v > U64_MAX) throw new OnboardError("invalid_input", `${name} must be a positive u64`);
706
+ }
707
+ if (t.perSellerMax > t.lineLimit) throw new OnboardError("invalid_input", "perSellerMax cannot exceed lineLimit");
708
+ const proposal = {
709
+ v: 1,
710
+ sessionKey: c.sessionKeyHex,
711
+ lineLimit: t.lineLimit.toString(),
712
+ perSellerMax: t.perSellerMax.toString(),
713
+ maxCycleMs: t.maxCycleMs.toString(),
714
+ validUntil: (BigInt(nowMs) + t.validForMs).toString()
715
+ };
716
+ const fragment = Buffer.from(JSON.stringify(proposal), "utf8").toString("base64url");
717
+ return `${normalizeBaseUrl(webBaseUrl)}${CONSENT_PATH}/${c.tokenId}#p=${fragment}`;
718
+ }
719
+
720
+ // packages/onboard/src/tx.ts
721
+ var ENERGY_MARGIN_PCT = 20n;
722
+ function energyWithMargin(used) {
723
+ return (used * (100n + ENERGY_MARGIN_PCT) + 99n) / 100n;
724
+ }
725
+ function unsignedPayload(update, energy) {
726
+ return {
727
+ kind: "UpdateContract",
728
+ sender: update.sender,
729
+ contract: { index: update.contract.index.toString(), subindex: update.contract.subindex.toString() },
730
+ receiveName: update.receiveName,
731
+ amountMicroCcd: update.amount.toString(),
732
+ parameterHex: toHex(update.parameter),
733
+ maxContractExecutionEnergy: energy.toString()
734
+ };
735
+ }
736
+ async function submitUpdate(update, o) {
737
+ if (o.signer !== null && o.signer.address !== update.sender) throw new OnboardError("invalid_input", `the key file is ${o.signer.address}, not ${update.sender}`);
738
+ const dry = await o.chain.dryRun(update);
739
+ if (!dry.ok) {
740
+ const named = dry.rejectCode === null ? null : bureauErrorName(dry.rejectCode);
741
+ throw new OnboardError("dry_run_failed", `${update.receiveName} dry run rejected: ${dry.reason}${dry.rejectCode === null ? "" : ` code ${dry.rejectCode}`}${named === null ? "" : ` ${named}`}`);
742
+ }
743
+ const energy = energyWithMargin(dry.usedEnergy);
744
+ if (o.signer === null) return { kind: "unsigned", payload: unsignedPayload(update, energy) };
745
+ const now = o.now ?? Date.now;
746
+ const nonce = await o.chain.nextNonce(update.sender);
747
+ const signed = await o.signer.signUpdate(update, { energy, nonce, expiry: BigInt(Math.floor(now() / 1e3) + (o.expirySeconds ?? 600)) });
748
+ const hash = await o.chain.send(signed.blockItemHex);
749
+ if (hash !== signed.txHash) throw new OnboardError("tx_unexpected", `the node returned hash ${hash}, expected ${signed.txHash}`);
750
+ const outcome = await o.chain.waitForFinalization(hash, o.finalizationTimeoutMs ?? 12e4);
751
+ if (!outcome.ok) throw new OnboardError("tx_failed", `transaction ${hash} was rejected: ${outcome.rejectReason ?? "unknown"}${outcome.rejectCode === null ? "" : ` code ${outcome.rejectCode}`}`);
752
+ return { kind: "sent", outcome };
753
+ }
754
+
755
+ // packages/onboard/src/cis8004.ts
756
+ var registerAgentParams = wire.struct("RegisterParams", [
757
+ ["agentUri", wire.option(wire.string)],
758
+ ["metadataHash", wire.option(wire.hash)],
759
+ ["externalReference", wire.option(externalReference)],
760
+ ["initialMetadata", wire.vec(agentMetadataEntry, 4)]
761
+ ]);
762
+ var encodeRegisterAgentParams = (p) => encodeWith(registerAgentParams, p, "RegisterParams");
763
+ var setAgentUriParams = wire.struct("SetAgentURIParams", [
764
+ ["tokenId", wire.agentTokenId],
765
+ ["agentUri", wire.option(wire.string)],
766
+ ["metadataHash", wire.option(wire.hash)]
767
+ ]);
768
+ var encodeSetAgentUriParams = (p) => encodeWith(setAgentUriParams, p, "SetAgentURIParams");
769
+ var RECEIVE = Object.freeze({
770
+ register: "CIS-8004.register",
771
+ setAgentWallet: "CIS-8004.setAgentWallet",
772
+ setAgentURI: "CIS-8004.setAgentURI",
773
+ registerExternalKey: "CIS-8.registerExternalKey",
774
+ registerSeller: "tab_bureau.registerSeller"
775
+ });
776
+
777
+ // packages/onboard/src/mcp.ts
778
+ import { z as z5 } from "zod";
779
+ var hex2 = z5.string().regex(/^([0-9a-fA-F]{2}){1,65536}$/).transform((s) => s.toLowerCase());
780
+ var u64ish = z5.union([z5.number().int().min(0).max(Number.MAX_SAFE_INTEGER), z5.string().regex(/^[0-9]{1,20}$/)]).transform((v) => BigInt(v));
781
+ var parameterResult = z5.object({ parameter_hex: hex2 }).loose();
782
+ var bytesResult = z5.object({ bytes_hex: hex2 }).loose();
783
+ var walletBytesResult = z5.object({ bytes_hex: hex2, owner_account: z5.string().max(64), wallet_set_nonce: u64ish }).loose();
784
+ var badgeResult = z5.object({ agent_card_json: z5.string().max(65536), metadata_hash_hex: hex2.optional() }).loose();
785
+ function parse(tool, schema, value) {
786
+ const r = schema.safeParse(value);
787
+ if (!r.success) throw new OnboardError("mcp_mismatch", `${tool}: unexpected answer shape`);
788
+ return r.data;
789
+ }
790
+ var McpBuilders = class {
791
+ #mcp;
792
+ constructor(mcp) {
793
+ this.#mcp = mcp;
794
+ }
795
+ async buildRegister(a) {
796
+ const v = await this.#mcp.call("build_register", { sender: a.sender, agent_uri: a.agentUri, metadata_hash_hex: a.metadataHashHex });
797
+ return parse("build_register", parameterResult, v).parameter_hex;
798
+ }
799
+ async setAgentWalletBytes(a) {
800
+ const v = await this.#mcp.call("set_agent_wallet_canonical_bytes", {
801
+ token_id: a.tokenId.toString(),
802
+ new_wallet: a.newWallet,
803
+ deadline_unix_ms: Number(a.deadline)
804
+ });
805
+ const r = parse("set_agent_wallet_canonical_bytes", walletBytesResult, v);
806
+ return { bytesHex: r.bytes_hex, owner: r.owner_account, nonce: r.wallet_set_nonce };
807
+ }
808
+ async buildSetAgentWallet(a) {
809
+ const v = await this.#mcp.call("build_set_agent_wallet", {
810
+ token_id: a.tokenId.toString(),
811
+ new_wallet: a.newWallet,
812
+ deadline_unix_ms: Number(a.deadline),
813
+ signature_hex: a.signatureHex,
814
+ sender: a.sender
815
+ });
816
+ return parse("build_set_agent_wallet", parameterResult, v).parameter_hex;
817
+ }
818
+ async cis8CanonicalBytes(a) {
819
+ const v = await this.#mcp.call("build_cis8_canonical_bytes", {
820
+ concordium_account: a.account,
821
+ external_namespace: a.namespace,
822
+ external_key_namespace: a.namespace,
823
+ external_key_type: a.keyType,
824
+ external_public_key_hex: a.publicKeyHex,
825
+ proof_scheme: a.proofScheme
826
+ });
827
+ return parse("build_cis8_canonical_bytes", bytesResult, v).bytes_hex;
828
+ }
829
+ async buildCis8Register(a) {
830
+ const v = await this.#mcp.call("build_cis8_register", {
831
+ sender: a.sender,
832
+ external_key: { namespace: a.namespace, key_type: a.keyType, public_key_hex: a.publicKeyHex },
833
+ proof: { scheme: a.scheme, signature_hex: a.signatureHex },
834
+ metadata: []
835
+ });
836
+ return parse("build_cis8_register", parameterResult, v).parameter_hex;
837
+ }
838
+ async buildSetAgentUri(a) {
839
+ const v = await this.#mcp.call("build_set_agent_uri", {
840
+ token_id: a.tokenId.toString(),
841
+ agent_uri: a.agentUri,
842
+ metadata_hash_hex: a.metadataHashHex,
843
+ sender: a.sender
844
+ });
845
+ return parse("build_set_agent_uri", parameterResult, v).parameter_hex;
846
+ }
847
+ /** `build_agent_badge` with `agent_wallet` = W; returns the merged card JSON the MCP built. */
848
+ async buildAgentBadge(a) {
849
+ const v = await this.#mcp.call("build_agent_badge", {
850
+ card_json: a.cardJson,
851
+ owner_account: a.owner,
852
+ token_id: a.tokenId.toString(),
853
+ agent_wallet: a.agentWallet
854
+ });
855
+ return parse("build_agent_badge", badgeResult, v).agent_card_json;
856
+ }
857
+ };
858
+
859
+ // packages/onboard/src/onboarder.ts
860
+ var AWAITING = { halt: "awaiting_signature" };
861
+ function clonePlan(plan) {
862
+ return JSON.parse(JSON.stringify(plan));
863
+ }
864
+ function sameContract(a, b) {
865
+ return contractAddressEqual(a, b);
866
+ }
867
+ var Onboarder = class {
868
+ #d;
869
+ #mcp;
870
+ #now;
871
+ #plan;
872
+ #external;
873
+ /** True while a sent transaction's outcome is unknown. */
874
+ #inFlight = false;
875
+ constructor(deps) {
876
+ this.#d = deps;
877
+ this.#mcp = deps.mcp === null ? null : new McpBuilders(deps.mcp);
878
+ this.#now = deps.now ?? Date.now;
879
+ }
880
+ /**
881
+ * Runs the plan's steps in order until one halts (awaiting a signature, hosting or the owner) or
882
+ * fails. The plan is saved after every change; run it again to resume.
883
+ */
884
+ async run(plan, opts = {}) {
885
+ this.#plan = clonePlan(plan);
886
+ this.#external = opts.external;
887
+ await this.#d.chain.assertTestnet();
888
+ for (const name of STEP_NAMES) {
889
+ const rec = this.#plan.steps[name];
890
+ if (rec.status === "done" || rec.status === "skipped") continue;
891
+ this.#inFlight = false;
892
+ try {
893
+ const halt = await this.#runStep(name);
894
+ if (halt !== null) return this.#halted(name, halt.halt);
895
+ } catch (err) {
896
+ const code = errorCode(err);
897
+ const message = errorMessage(err);
898
+ if (!(rec.status === "submitted" && this.#inFlight)) rec.status = "failed";
899
+ rec.error = { code, message: message.slice(0, 2048) };
900
+ await this.#save(rec);
901
+ this.#log(name, `failed: ${code}: ${message}`);
902
+ return { state: "failed", plan: clonePlan(this.#plan), step: name, error: { code, message } };
903
+ }
904
+ }
905
+ return { state: "complete", plan: clonePlan(this.#plan) };
906
+ }
907
+ /** Sets a failed or halted step back to `pending` (keeping its notes) so the next run retries it. */
908
+ static resetStep(plan, name) {
909
+ const next = clonePlan(plan);
910
+ const rec = next.steps[name];
911
+ if (rec.status === "skipped") throw new OnboardError("step_blocked", `${name} is not part of this plan`);
912
+ if (rec.status === "submitted") throw new OnboardError("step_blocked", `${name} has a transaction in flight (${rec.txHash ?? ""}); resume it instead`);
913
+ Object.assign(rec, { status: "pending", attempts: 0, error: null, unsigned: null, pending: null });
914
+ return next;
915
+ }
916
+ #halted(step, state) {
917
+ const rec = this.#plan.steps[step];
918
+ return {
919
+ state,
920
+ plan: clonePlan(this.#plan),
921
+ step,
922
+ ...rec.unsigned === null ? {} : { payload: rec.unsigned },
923
+ ...rec.data.walletMessage === void 0 || rec.unsigned !== null ? {} : { walletMessageHex: rec.data.walletMessage },
924
+ ...rec.data.consentUrl === void 0 ? {} : { consentUrl: rec.data.consentUrl }
925
+ };
926
+ }
927
+ async #runStep(name) {
928
+ switch (name) {
929
+ case "register":
930
+ return this.#register();
931
+ case "setAgentWallet":
932
+ return this.#setAgentWallet();
933
+ case "sessionKey":
934
+ return this.#sessionKey();
935
+ case "badge":
936
+ return this.#badge();
937
+ case "role":
938
+ return this.#role();
939
+ }
940
+ }
941
+ // -------------------------------------------------------------------------------------------
942
+ // Steps
943
+ async #register() {
944
+ const plan = this.#plan;
945
+ const rec = plan.steps.register;
946
+ const { spec } = plan;
947
+ if (plan.tokenId !== null) return this.#finish(rec, "done");
948
+ let uri;
949
+ let hashHex;
950
+ if (spec.register !== null) {
951
+ uri = spec.register.uri;
952
+ hashHex = spec.register.metadataHash;
953
+ } else {
954
+ const card = plan.cards.initial ?? await this.#storeCard(this.#initialCard(), "initial");
955
+ uri = card.url;
956
+ hashHex = card.sha256;
957
+ }
958
+ const parameter = encodeRegisterAgentParams({
959
+ agentUri: uri,
960
+ metadataHash: hashHex === null ? null : fromHex(hashHex, 32),
961
+ externalReference: null,
962
+ initialMetadata: []
963
+ });
964
+ const outcome = await this.#transact("register", async () => {
965
+ await this.#crossCheck(rec, "build_register", parameter, (m) => m.buildRegister({ sender: spec.owner, agentUri: uri, metadataHashHex: hashHex }));
966
+ return { sender: spec.owner, contract: this.#cis8004(), receiveName: RECEIVE.register, parameter, amount: 0n };
967
+ });
968
+ if ("halt" in outcome) return outcome;
969
+ const owner = accountAddressFromBase58(spec.owner);
970
+ const registered = this.#cis8004Events(outcome).find((e) => e.type === "Registered");
971
+ if (registered === void 0 || registered.type !== "Registered") throw new OnboardError("tx_unexpected", "register logged no Registered event");
972
+ if (!bytesEqual(registered.ownerAccount, owner)) throw new OnboardError("tx_unexpected", "the agent was registered to another account");
973
+ plan.tokenId = registered.tokenId.toString();
974
+ rec.data.tokenId = plan.tokenId;
975
+ rec.data.badge = agentBadge(registered.tokenId);
976
+ this.#log("register", `token ${plan.tokenId} (badge ${rec.data.badge})`, outcome.txHash);
977
+ return this.#finish(rec, "done");
978
+ }
979
+ async #setAgentWallet() {
980
+ const plan = this.#plan;
981
+ const rec = plan.steps.setAgentWallet;
982
+ const { spec } = plan;
983
+ if (spec.agentWallet === spec.owner) throw new OnboardError("wallet_is_owner", "the agent wallet must be a different account from the owner");
984
+ const tokenId = this.#tokenId();
985
+ if (rec.status !== "submitted") {
986
+ const agent = await this.#agent(tokenId);
987
+ if (agent.agentWallet === spec.agentWallet) {
988
+ rec.notes = [...rec.notes, "agentWallet already set on chain"].slice(-64);
989
+ return this.#finish(rec, "done");
990
+ }
991
+ }
992
+ const outcome = await this.#transact("setAgentWallet", async () => {
993
+ const parameter = await this.#walletParameter(rec, tokenId);
994
+ return parameter === null ? null : { sender: spec.owner, contract: this.#cis8004(), receiveName: RECEIVE.setAgentWallet, parameter, amount: 0n };
995
+ });
996
+ if ("halt" in outcome) return outcome;
997
+ const wallet = accountAddressFromBase58(spec.agentWallet);
998
+ const set = this.#cis8004Events(outcome).find((e) => e.type === "AgentWalletSet" && e.tokenId === tokenId);
999
+ if (set === void 0 || set.type !== "AgentWalletSet" || set.newWallet === null || !bytesEqual(set.newWallet, wallet)) {
1000
+ throw new OnboardError("tx_unexpected", "setAgentWallet logged no AgentWalletSet event for the agent wallet");
1001
+ }
1002
+ const after = await this.#agent(tokenId);
1003
+ if (after.agentWallet !== spec.agentWallet) throw new OnboardError("tx_unexpected", "agentOf does not show the agent wallet after setAgentWallet");
1004
+ if (after.agentWallet === after.ownerAccount) throw new OnboardError("wallet_is_owner", "agentOf shows the owner as the agent wallet");
1005
+ this.#log("setAgentWallet", `agentWallet ${spec.agentWallet}`, outcome.txHash);
1006
+ return this.#finish(rec, "done");
1007
+ }
1008
+ /** The setAgentWallet parameter, or null while the wallet's signature is awaited. */
1009
+ async #walletParameter(rec, tokenId) {
1010
+ const { spec } = this.#plan;
1011
+ const ext = this.#externalFor("setAgentWallet");
1012
+ const awaited = rec.data.walletMessage !== void 0 && rec.data.walletDeadline !== void 0 && this.#d.walletProver === null;
1013
+ if (awaited && BigInt(rec.data.walletDeadline ?? "0") > BigInt(this.#now() + 6e4)) {
1014
+ if (ext?.walletSignatureHex === void 0) return null;
1015
+ if (!/^[0-9a-fA-F]{128}$/.test(ext.walletSignatureHex)) throw new OnboardError("invalid_input", "the wallet signature must be 64 bytes of hex");
1016
+ return encodeSetAgentWalletParams({
1017
+ tokenId,
1018
+ newWallet: accountAddressFromBase58(spec.agentWallet),
1019
+ deadline: BigInt(rec.data.walletDeadline ?? "0"),
1020
+ signature: singleKeyAccountSignatures(fromHex(ext.walletSignatureHex.toLowerCase(), 64))
1021
+ });
1022
+ }
1023
+ const nonce = await this.#d.chain.agentWalletNonce(tokenId);
1024
+ if (nonce === null) throw new OnboardError("tx_unexpected", `agent ${tokenId} has no wallet nonce`);
1025
+ const deadline = BigInt(this.#now() + (this.#d.walletDeadlineMs ?? 6e5));
1026
+ const owner = accountAddressFromBase58(spec.owner);
1027
+ const message = setAgentWalletMessage({ tokenId, owner, newWallet: accountAddressFromBase58(spec.agentWallet), walletSetNonce: nonce, deadline });
1028
+ await this.#crossCheck(rec, "set_agent_wallet_canonical_bytes", message, async (m) => {
1029
+ const r = await m.setAgentWalletBytes({ tokenId, newWallet: spec.agentWallet, deadline });
1030
+ if (r.owner !== spec.owner || r.nonce !== nonce) throw new OnboardError("mcp_mismatch", "MCP reads another owner or wallet nonce");
1031
+ return r.bytesHex;
1032
+ });
1033
+ if (this.#d.walletProver === null) {
1034
+ rec.data.walletMessage = toHex(message);
1035
+ rec.data.walletDeadline = deadline.toString();
1036
+ rec.data.walletNonce = nonce.toString();
1037
+ rec.data.signer = "wallet";
1038
+ return null;
1039
+ }
1040
+ if (this.#d.walletProver.address !== spec.agentWallet) throw new OnboardError("invalid_input", "the wallet key file is not the agent wallet");
1041
+ const proof = await this.#d.walletProver.prove({ tokenId, owner, walletSetNonce: nonce, deadline });
1042
+ if (!bytesEqual(proof.message, message) || proof.newWallet !== spec.agentWallet) {
1043
+ throw new OnboardError("tx_unexpected", "the wallet proof is not over the expected 162-byte message");
1044
+ }
1045
+ await this.#crossCheck(
1046
+ rec,
1047
+ "build_set_agent_wallet",
1048
+ proof.parameter,
1049
+ (m) => m.buildSetAgentWallet({ tokenId, newWallet: spec.agentWallet, deadline, signatureHex: toHex(proof.signature), sender: spec.owner })
1050
+ );
1051
+ return proof.parameter;
1052
+ }
1053
+ async #sessionKey() {
1054
+ const plan = this.#plan;
1055
+ const rec = plan.steps.sessionKey;
1056
+ const { spec } = plan;
1057
+ const key = await this.#d.keys.ensure(spec.sessionKey.name, spec.sessionKey.role, { mustExist: spec.sessionKey.mustExist });
1058
+ if (spec.sessionKey.expectedPublicKey !== null && toHex(key.publicKey) !== spec.sessionKey.expectedPublicKey) {
1059
+ throw new OnboardError("key_mismatch", `key ${spec.sessionKey.name} is not the expected public key`);
1060
+ }
1061
+ const keyId = ed25519KeyId(key.publicKey, key.keyId.namespace);
1062
+ if (!externalKeyIdEqual(keyId, key.keyId)) throw new OnboardError("key_mismatch", "the key id is not a 32-byte ed25519 key");
1063
+ plan.sessionKey = { publicKey: toHex(key.publicKey), keyIdHex: toHex(encodeExternalKeyId(keyId)) };
1064
+ rec.data.publicKey = toHex(key.publicKey);
1065
+ rec.data.namespace = keyId.namespace;
1066
+ if (rec.status !== "submitted") {
1067
+ const bound2 = await this.#d.chain.ownerOfKey(keyId);
1068
+ if (bound2?.status === "Active") {
1069
+ if (bound2.owner !== spec.owner) throw new OnboardError("key_taken", `the key is bound to ${bound2.owner}, not the owner`);
1070
+ rec.notes = [...rec.notes, "key already bound to the owner"].slice(-64);
1071
+ return this.#finish(rec, "done");
1072
+ }
1073
+ }
1074
+ const outcome = await this.#transact("sessionKey", async () => {
1075
+ const owner2 = accountAddressFromBase58(spec.owner);
1076
+ const input = { account: owner2, externalKey: keyId, proofScheme: PROOF_SCHEME_SOLANA_ED25519 };
1077
+ const canonical = cis8CanonicalMessage(input);
1078
+ await this.#crossCheck(
1079
+ rec,
1080
+ "build_cis8_canonical_bytes",
1081
+ canonical,
1082
+ (m) => m.cis8CanonicalBytes({ account: spec.owner, namespace: keyId.namespace, keyType: keyId.keyType, publicKeyHex: toHex(keyId.publicKey), proofScheme: PROOF_SCHEME_SOLANA_ED25519 })
1083
+ );
1084
+ const signature = await this.#d.keys.signCis8(spec.sessionKey.name, canonical);
1085
+ if (!verifyCis8Canonical(input, signature)) throw new OnboardError("key_mismatch", "the key did not sign the CIS-8 canonical bytes");
1086
+ const parameter = encodeRegisterExternalKeyParams({ externalKey: keyId, proof: { scheme: PROOF_SCHEME_SOLANA_ED25519, signature }, metadata: [] });
1087
+ await this.#crossCheck(
1088
+ rec,
1089
+ "build_cis8_register",
1090
+ parameter,
1091
+ (m) => m.buildCis8Register({
1092
+ sender: spec.owner,
1093
+ namespace: keyId.namespace,
1094
+ keyType: keyId.keyType,
1095
+ publicKeyHex: toHex(keyId.publicKey),
1096
+ scheme: PROOF_SCHEME_SOLANA_ED25519,
1097
+ signatureHex: toHex(signature)
1098
+ })
1099
+ );
1100
+ return { sender: spec.owner, contract: this.#cis8(), receiveName: RECEIVE.registerExternalKey, parameter, amount: 0n };
1101
+ });
1102
+ if ("halt" in outcome) return outcome;
1103
+ const owner = accountAddressFromBase58(spec.owner);
1104
+ const logged = this.#cis8Events(outcome).find((e) => e.type === "ExternalKeyRegistered" && externalKeyIdEqual(e.externalKey, keyId));
1105
+ if (logged === void 0 || logged.type !== "ExternalKeyRegistered" || !bytesEqual(logged.owner, owner)) {
1106
+ throw new OnboardError("tx_unexpected", "registerExternalKey logged no ExternalKeyRegistered event for this key and owner");
1107
+ }
1108
+ const bound = await this.#d.chain.ownerOfKey(keyId);
1109
+ if (bound?.status !== "Active" || bound.owner !== spec.owner) throw new OnboardError("tx_unexpected", "ownerOfKey does not show the key Active for the owner");
1110
+ this.#log("sessionKey", `${keyId.namespace} key ${rec.data.publicKey} bound`, outcome.txHash);
1111
+ return this.#finish(rec, "done");
1112
+ }
1113
+ async #badge() {
1114
+ const plan = this.#plan;
1115
+ const rec = plan.steps.badge;
1116
+ const { spec } = plan;
1117
+ const tokenId = this.#tokenId();
1118
+ let card = plan.cards.badged;
1119
+ if (card === null) {
1120
+ const agent = await this.#agent(tokenId);
1121
+ if (agent.agentWallet !== spec.agentWallet) throw new OnboardError("step_blocked", "set the agent wallet before the badge (agentOf shows another wallet)");
1122
+ const badge = await this.#buildBadge(rec, tokenId);
1123
+ card = await this.#storeCard(this.#cardWith(badge), "badged");
1124
+ }
1125
+ if (rec.status !== "pending_hosting") {
1126
+ const agent = rec.status === "submitted" ? null : await this.#agent(tokenId);
1127
+ if (agent === null || agent.agentUri !== card.url || agent.metadataHash !== card.sha256) {
1128
+ const target = card;
1129
+ const parameter = encodeSetAgentUriParams({ tokenId, agentUri: target.url, metadataHash: fromHex(target.sha256, 32) });
1130
+ const outcome = await this.#transact("badge", async () => {
1131
+ await this.#crossCheck(
1132
+ rec,
1133
+ "build_set_agent_uri",
1134
+ parameter,
1135
+ (m) => m.buildSetAgentUri({ tokenId, agentUri: target.url, metadataHashHex: target.sha256, sender: spec.owner })
1136
+ );
1137
+ return { sender: spec.owner, contract: this.#cis8004(), receiveName: RECEIVE.setAgentURI, parameter, amount: 0n };
1138
+ });
1139
+ if ("halt" in outcome) return outcome;
1140
+ const updated = this.#cis8004Events(outcome).find((e) => e.type === "URIUpdated" && e.tokenId === tokenId);
1141
+ if (updated === void 0 || updated.type !== "URIUpdated" || updated.agentUri !== target.url || updated.metadataHash === null || toHex(updated.metadataHash) !== target.sha256) {
1142
+ throw new OnboardError("tx_unexpected", "setAgentURI logged no URIUpdated event with the card URL and hash");
1143
+ }
1144
+ this.#log("badge", `agent_uri ${target.url}`, outcome.txHash);
1145
+ }
1146
+ }
1147
+ return this.#checkHosted(rec, tokenId, card);
1148
+ }
1149
+ async #buildBadge(rec, tokenId) {
1150
+ const { spec } = this.#plan;
1151
+ const subject = { tokenId, owner: spec.owner, agentWallet: spec.agentWallet };
1152
+ const local = localBadge(subject);
1153
+ let badge = local;
1154
+ if (this.#mcp === null) {
1155
+ this.#note(rec, "build_agent_badge skipped: no MCP; using the local badge block");
1156
+ } else {
1157
+ let mcpCardJson = null;
1158
+ try {
1159
+ mcpCardJson = await this.#mcp.buildAgentBadge({
1160
+ cardJson: new TextDecoder().decode(this.#initialCard().bytes),
1161
+ owner: spec.owner,
1162
+ tokenId,
1163
+ agentWallet: spec.agentWallet
1164
+ });
1165
+ } catch (err) {
1166
+ if (err instanceof OnboardError) throw err;
1167
+ this.#note(rec, `build_agent_badge skipped: ${errorMessage(err)}; using the local badge block`);
1168
+ }
1169
+ if (mcpCardJson !== null) {
1170
+ const fromMcp = badgeFromMcpCard(mcpCardJson);
1171
+ const diffs = badgeDifferences(fromMcp, local);
1172
+ if (diffs.length > 0) throw new OnboardError("mcp_mismatch", `MCP badge differs from the local block in ${diffs.join(", ")}`);
1173
+ badge = fromMcp;
1174
+ this.#note(rec, "build_agent_badge matches the local badge block");
1175
+ }
1176
+ }
1177
+ const issues = badgeIssues(badge, subject);
1178
+ if (issues.length > 0) throw new OnboardError("badge_invalid", issues.join("; "));
1179
+ return badge;
1180
+ }
1181
+ async #checkHosted(rec, tokenId, card) {
1182
+ const { spec } = this.#plan;
1183
+ rec.data.cardUrl = card.url;
1184
+ rec.data.cardSha256 = card.sha256;
1185
+ const fetched = await this.#d.fetchCard.fetch(card.url);
1186
+ const served = fetched.ok ? toHex(sha256(fetched.body)) : null;
1187
+ if (!fetched.ok || served !== card.sha256) {
1188
+ rec.data.hosting = fetched.ok ? `served bytes hash ${served ?? ""}, expected ${card.sha256}` : fetched.error;
1189
+ return this.#finish(rec, "pending_hosting", { halt: "pending_hosting" });
1190
+ }
1191
+ const agent = await this.#d.chain.agentOf(tokenId);
1192
+ const verdict = evaluateBadge(tokenId, agent, { ok: true, uri: card.url, body: fetched.body });
1193
+ if (!verdict.badgeValid || !verdict.walletMatches || agent?.agentWallet !== spec.agentWallet) {
1194
+ throw new OnboardError("badge_invalid", `local badge recomputation fails: ${verdict.issues.join("; ")}`);
1195
+ }
1196
+ if (this.#d.mcp !== null) {
1197
+ let hosted = null;
1198
+ try {
1199
+ hosted = await this.#d.mcp.checkBadge(agentBadge(tokenId));
1200
+ } catch (err) {
1201
+ this.#note(rec, `hosted check-badge skipped: ${errorMessage(err)}`);
1202
+ }
1203
+ if (hosted !== null && !hosted.badgeValid) {
1204
+ rec.data.hosting = `hosted check-badge: badge_valid false (${hosted.issues.join("; ").slice(0, 512)})`;
1205
+ return this.#finish(rec, "pending_hosting", { halt: "pending_hosting" });
1206
+ }
1207
+ if (hosted !== null) rec.data.hostedBadgeValid = "true";
1208
+ }
1209
+ delete rec.data.hosting;
1210
+ rec.data.badgeValid = "true";
1211
+ this.#log("badge", `badge_valid for ${agentBadge(tokenId)}`);
1212
+ return this.#finish(rec, "done");
1213
+ }
1214
+ async #role() {
1215
+ const plan = this.#plan;
1216
+ const rec = plan.steps.role;
1217
+ const { spec } = plan;
1218
+ const tokenId = this.#tokenId();
1219
+ if (spec.role === "buyer") {
1220
+ const key2 = plan.sessionKey;
1221
+ if (key2 === null) throw new OnboardError("step_blocked", "bind the session key before opening a line");
1222
+ rec.data.consentUrl = consentUrl(spec.webBaseUrl, { tokenId, owner: spec.owner, sessionKeyHex: key2.publicKey, bureau: planBureau(plan) }, this.#now());
1223
+ this.#log("role", `the owner opens the line at ${rec.data.consentUrl}`);
1224
+ return this.#finish(rec, "awaiting_owner", { halt: "awaiting_owner" });
1225
+ }
1226
+ if (spec.role !== "seller" || spec.seller === null) return this.#finish(rec, "skipped");
1227
+ const key = plan.sessionKey;
1228
+ if (key === null) throw new OnboardError("step_blocked", "bind the seller session key before registerSeller");
1229
+ const keyId = ed25519KeyId(fromHex(key.publicKey, 32));
1230
+ const p = spec.seller.policy;
1231
+ const policy = {
1232
+ maxTabLimit: BigInt(p.maxTabLimit),
1233
+ minBuyerTier: p.minBuyerTier,
1234
+ minBuyerK: p.minBuyerK,
1235
+ minCycleMs: BigInt(p.minCycleMs),
1236
+ maxCycleMs: BigInt(p.maxCycleMs),
1237
+ maxNewTabsPerDay: p.maxNewTabsPerDay,
1238
+ priceScheduleHash: fromHex(p.priceScheduleHash, 32),
1239
+ admitBadgeInvalid: p.admitBadgeInvalid
1240
+ };
1241
+ const bureau = planBureau(plan);
1242
+ const wantHash = policyHash(policy);
1243
+ rec.data.policyHash = toHex(wantHash);
1244
+ if (rec.status !== "submitted") {
1245
+ const existing = await this.#d.chain.sellerOf(bureau, tokenId);
1246
+ if (existing !== null && bytesEqual(existing.owner, accountAddressFromBase58(spec.owner)) && bytesEqual(existing.wallet, accountAddressFromBase58(spec.agentWallet)) && externalKeyIdEqual(existing.sessionKey, keyId) && bytesEqual(policyHash(existing.policy), wantHash)) {
1247
+ this.#note(rec, "seller already registered with this key, wallet and policy");
1248
+ return this.#finish(rec, "done");
1249
+ }
1250
+ }
1251
+ const parameter = encodeRegisterSellerParams({ sellerToken: tokenId, sessionKey: keyId, policy });
1252
+ const outcome = await this.#transact("role", async () => ({
1253
+ sender: spec.owner,
1254
+ contract: bureau,
1255
+ receiveName: RECEIVE.registerSeller,
1256
+ parameter,
1257
+ amount: 0n
1258
+ }));
1259
+ if ("halt" in outcome) return outcome;
1260
+ const logged = outcome.contractEvents.filter((l) => sameContract(l.contract, bureau)).flatMap((l) => l.events.map(tryDecode(decodeBureauEvent))).find((e) => e?.type === "SellerRegistered" && e.tokenId === tokenId);
1261
+ if (logged?.type !== "SellerRegistered" || !bytesEqual(logged.policyHash, wantHash)) {
1262
+ throw new OnboardError("tx_unexpected", "registerSeller logged no SellerRegistered event with this policy");
1263
+ }
1264
+ const seller = await this.#d.chain.sellerOf(bureau, tokenId);
1265
+ if (seller === null || !bytesEqual(seller.wallet, accountAddressFromBase58(spec.agentWallet))) {
1266
+ throw new OnboardError("tx_unexpected", "sellerOf does not show the agent wallet as the seller snapshot");
1267
+ }
1268
+ this.#log("role", `seller ${tokenId} registered`, outcome.txHash);
1269
+ return this.#finish(rec, "done");
1270
+ }
1271
+ // -------------------------------------------------------------------------------------------
1272
+ // Transactions
1273
+ /**
1274
+ * Builds (`build` returns null while a wallet proof is awaited), dry-runs, signs or emits, sends
1275
+ * and follows one transaction for `name`. Resumes a recorded transaction instead of building a
1276
+ * new one.
1277
+ */
1278
+ async #transact(name, build) {
1279
+ const rec = this.#plan.steps[name];
1280
+ if (rec.status === "awaiting_signature" && rec.unsigned !== null) {
1281
+ const ext = this.#externalFor(name)?.txHash;
1282
+ if (ext === void 0) return AWAITING;
1283
+ if (!/^[0-9a-f]{64}$/.test(ext)) throw new OnboardError("invalid_input", "the transaction hash must be 64 lowercase hex digits");
1284
+ Object.assign(rec, { txHash: ext, explorer: explorerTx(ext), status: "submitted", unsigned: null, pending: null });
1285
+ await this.#save(rec);
1286
+ }
1287
+ if (rec.status === "submitted" && rec.txHash !== null) {
1288
+ const followed = await this.#follow(name);
1289
+ if (followed !== null) return followed;
1290
+ }
1291
+ if (rec.attempts >= (this.#d.maxAttempts ?? 3)) {
1292
+ throw new OnboardError("too_many_attempts", `${name} has built ${rec.attempts} transactions; reset the step after checking the chain`);
1293
+ }
1294
+ const update = await build();
1295
+ if (update === null) {
1296
+ rec.status = "awaiting_signature";
1297
+ await this.#save(rec);
1298
+ return AWAITING;
1299
+ }
1300
+ const dry = await this.#d.chain.dryRun(update);
1301
+ if (!dry.ok) {
1302
+ const named = dry.rejectCode === null ? null : bureauErrorName(dry.rejectCode);
1303
+ const code = dry.rejectCode === null ? "" : ` code ${dry.rejectCode}${named === null ? "" : ` ${named}`}`;
1304
+ throw new OnboardError("dry_run_failed", `${update.receiveName} dry run rejected: ${dry.reason}${code}`);
1305
+ }
1306
+ const energy = energyWithMargin(dry.usedEnergy);
1307
+ rec.data.energy = energy.toString();
1308
+ if (this.#d.signer === null) {
1309
+ rec.unsigned = unsignedPayload(update, energy);
1310
+ rec.data.signer = "owner";
1311
+ rec.status = "awaiting_signature";
1312
+ await this.#save(rec);
1313
+ this.#log(name, `awaiting the owner's signature for ${update.receiveName}`);
1314
+ return AWAITING;
1315
+ }
1316
+ if (this.#d.signer.address !== update.sender) throw new OnboardError("invalid_input", `the owner key file is ${this.#d.signer.address}, not ${update.sender}`);
1317
+ const nonce = await this.#d.chain.nextNonce(update.sender);
1318
+ const expiry = BigInt(Math.floor(this.#now() / 1e3) + (this.#d.expirySeconds ?? 600));
1319
+ const signed = await this.#d.signer.signUpdate(update, { energy, nonce, expiry });
1320
+ Object.assign(rec, {
1321
+ status: "submitted",
1322
+ attempts: rec.attempts + 1,
1323
+ txHash: signed.txHash,
1324
+ explorer: explorerTx(signed.txHash),
1325
+ blockHash: null,
1326
+ pending: { transactionHex: signed.blockItemHex, expiry: expiry.toString() },
1327
+ error: null
1328
+ });
1329
+ await this.#save(rec);
1330
+ this.#log(name, `sending ${update.receiveName}`, signed.txHash);
1331
+ this.#inFlight = true;
1332
+ const sent = await this.#d.chain.send(signed.blockItemHex);
1333
+ if (sent !== signed.txHash) throw new OnboardError("tx_unexpected", `the node returned hash ${sent}, expected ${signed.txHash}`);
1334
+ const outcome = await this.#follow(name);
1335
+ if (outcome === null) throw new OnboardError("tx_expired", `${name}: the transaction did not reach the node`);
1336
+ return outcome;
1337
+ }
1338
+ /**
1339
+ * Follows the recorded transaction to finalization. Returns null when it never reached the node
1340
+ * and has expired (the step then builds a new one); resends it when it is unknown but unexpired.
1341
+ */
1342
+ async #follow(name) {
1343
+ const rec = this.#plan.steps[name];
1344
+ const hash = rec.txHash;
1345
+ if (hash === null) return null;
1346
+ this.#inFlight = true;
1347
+ const status = await this.#d.chain.status(hash);
1348
+ if (status === "absent") {
1349
+ const pending = rec.pending;
1350
+ if (pending === null) {
1351
+ this.#inFlight = false;
1352
+ throw new OnboardError("tx_failed", `transaction ${hash} is not known to the node`);
1353
+ }
1354
+ if (BigInt(Math.floor(this.#now() / 1e3)) >= BigInt(pending.expiry)) {
1355
+ this.#inFlight = false;
1356
+ this.#note(rec, `transaction ${hash} expired before it reached the node; building a new one`);
1357
+ Object.assign(rec, { status: "pending", txHash: null, explorer: null, pending: null });
1358
+ await this.#save(rec);
1359
+ return null;
1360
+ }
1361
+ await this.#d.chain.send(pending.transactionHex);
1362
+ }
1363
+ const outcome = await this.#d.chain.waitForFinalization(hash, this.#d.finalizationTimeoutMs ?? 12e4);
1364
+ this.#inFlight = false;
1365
+ rec.blockHash = outcome.blockHash;
1366
+ rec.pending = null;
1367
+ if (!outcome.ok) {
1368
+ const named = outcome.rejectCode === null ? null : bureauErrorName(outcome.rejectCode);
1369
+ throw new OnboardError(
1370
+ "tx_failed",
1371
+ `transaction ${hash} was rejected: ${outcome.rejectReason ?? "unknown"}${outcome.rejectCode === null ? "" : ` code ${outcome.rejectCode}`}${named === null ? "" : ` ${named}`}`
1372
+ );
1373
+ }
1374
+ if (outcome.sender !== this.#plan.spec.owner) throw new OnboardError("tx_unexpected", `transaction ${hash} was sent by ${outcome.sender}, not the owner`);
1375
+ await this.#save(rec);
1376
+ return outcome;
1377
+ }
1378
+ // -------------------------------------------------------------------------------------------
1379
+ // Helpers
1380
+ /**
1381
+ * Compares `local` with what an MCP builder returns. A transport failure is noted and skipped;
1382
+ * an answer that differs (or does not parse) fails the step (`mcp_mismatch`).
1383
+ */
1384
+ async #crossCheck(rec, tool, local, call) {
1385
+ if (this.#mcp === null) {
1386
+ this.#note(rec, `${tool} cross-check skipped: no MCP`);
1387
+ return;
1388
+ }
1389
+ let remote;
1390
+ try {
1391
+ remote = await call(this.#mcp);
1392
+ } catch (err) {
1393
+ if (err instanceof OnboardError) throw err;
1394
+ this.#note(rec, `${tool} cross-check skipped: ${errorMessage(err)}`);
1395
+ return;
1396
+ }
1397
+ if (remote !== toHex(local)) throw new OnboardError("mcp_mismatch", `${tool} returned other bytes than the codec`);
1398
+ this.#note(rec, `${tool} matches the codec byte for byte`);
1399
+ }
1400
+ #initialCard() {
1401
+ return buildAgentCard(this.#cardInput());
1402
+ }
1403
+ #cardWith(badge) {
1404
+ return buildAgentCard({ ...this.#cardInput(), badge });
1405
+ }
1406
+ #cardInput() {
1407
+ const { spec } = this.#plan;
1408
+ return {
1409
+ name: spec.name,
1410
+ description: spec.description,
1411
+ skills: spec.skills,
1412
+ publicBaseUrl: spec.publicBaseUrl,
1413
+ agentWallet: spec.agentWallet,
1414
+ ccdTab: { role: spec.role, bureau: planBureau(this.#plan), staged: spec.staged },
1415
+ services: spec.services
1416
+ };
1417
+ }
1418
+ async #storeCard(card, which) {
1419
+ const stored = await this.#d.cards.put(card.sha256, card.bytes);
1420
+ const ref = { sha256: card.sha256, url: card.url, stored };
1421
+ this.#plan.cards[which] = ref;
1422
+ await this.#saveAll();
1423
+ return ref;
1424
+ }
1425
+ async #agent(tokenId) {
1426
+ const agent = await this.#d.chain.agentOf(tokenId);
1427
+ if (agent === null) throw new OnboardError("tx_unexpected", `agent ${tokenId} does not exist`);
1428
+ if (agent.ownerAccount !== this.#plan.spec.owner) throw new OnboardError("not_owner", `agent ${tokenId} is owned by ${agent.ownerAccount}`);
1429
+ if (agent.status !== "Active") throw new OnboardError("step_blocked", `agent ${tokenId} is revoked`);
1430
+ return agent;
1431
+ }
1432
+ #tokenId() {
1433
+ if (this.#plan.tokenId === null) throw new OnboardError("step_blocked", "register the agent first");
1434
+ return BigInt(this.#plan.tokenId);
1435
+ }
1436
+ #cis8004() {
1437
+ return parseContractAddress(this.#plan.cis8004);
1438
+ }
1439
+ #cis8() {
1440
+ return parseContractAddress(this.#plan.cis8);
1441
+ }
1442
+ #cis8004Events(o) {
1443
+ const c = this.#cis8004();
1444
+ return o.contractEvents.filter((l) => sameContract(l.contract, c)).flatMap((l) => l.events.map(tryDecode(decodeCis8004Event))).filter((e) => e !== null);
1445
+ }
1446
+ #cis8Events(o) {
1447
+ const c = this.#cis8();
1448
+ return o.contractEvents.filter((l) => sameContract(l.contract, c)).flatMap((l) => l.events.map(tryDecode(decodeCis8Event))).filter((e) => e !== null);
1449
+ }
1450
+ #externalFor(step) {
1451
+ return this.#external?.step === step ? this.#external : void 0;
1452
+ }
1453
+ #note(rec, note) {
1454
+ rec.notes = [...rec.notes, note.slice(0, 1024)].slice(-64);
1455
+ }
1456
+ async #finish(rec, status, halt = null) {
1457
+ rec.status = status;
1458
+ if (status === "done" || status === "skipped") rec.error = null;
1459
+ await this.#save(rec);
1460
+ return halt;
1461
+ }
1462
+ async #save(rec) {
1463
+ rec.updatedAt = new Date(this.#now()).toISOString();
1464
+ await this.#saveAll();
1465
+ }
1466
+ async #saveAll() {
1467
+ this.#plan.updatedAt = new Date(this.#now()).toISOString();
1468
+ await this.#d.store.save(this.#plan);
1469
+ }
1470
+ #log(step, message, txHash) {
1471
+ this.#d.log?.({ step, message, ...txHash === void 0 ? {} : { txHash } });
1472
+ }
1473
+ };
1474
+ function tryDecode(decode) {
1475
+ return (b) => {
1476
+ try {
1477
+ return decode(b);
1478
+ } catch {
1479
+ return null;
1480
+ }
1481
+ };
1482
+ }
1483
+
1484
+ // packages/onboard/src/report.ts
1485
+ var FAUCET_HINT = 'Request testnet CCD for this account from the Concordium testnet faucet (Browser Wallet or Concordium Wallet: "Request CCD").';
1486
+ var MIN_OWNER_BALANCE = 10000000n;
1487
+ async function checkFunding(chain, plan, required = MIN_OWNER_BALANCE) {
1488
+ const address2 = plan.spec.owner;
1489
+ const balance = await chain.balance(address2);
1490
+ return { address: address2, balance, required, ok: balance >= required, explorer: explorerAccount(address2) };
1491
+ }
1492
+
1493
+ // packages/onboard/src/adapters/keyfile.ts
1494
+ import {
1495
+ AccountAddress,
1496
+ AccountTransactionV0,
1497
+ CcdAmount,
1498
+ ContractAddress as SdkContractAddress,
1499
+ Energy,
1500
+ Parameter,
1501
+ ReceiveName,
1502
+ SequenceNumber,
1503
+ Transaction,
1504
+ TransactionExpiry
1505
+ } from "@concordium/web-sdk";
1506
+ function buffer(bytes) {
1507
+ const copy = new Uint8Array(bytes.length);
1508
+ copy.set(bytes);
1509
+ return copy.buffer;
1510
+ }
1511
+ function v0TransactionHash(tx) {
1512
+ return toHex(sha256(Transaction.serializeBlockItem(tx)));
1513
+ }
1514
+ var KeyFileOwnerSigner = class _KeyFileOwnerSigner {
1515
+ address;
1516
+ #signer;
1517
+ constructor(signer) {
1518
+ this.#signer = signer;
1519
+ this.address = signer.address;
1520
+ }
1521
+ /** Loads the export at `file` (owner-only permissions, outside the repository). */
1522
+ static async fromFile(file) {
1523
+ return new _KeyFileOwnerSigner(await KeyFileAccountSigner.fromFile(file));
1524
+ }
1525
+ async signUpdate(u, opts) {
1526
+ if (u.sender !== this.address) throw new OnboardError("invalid_input", `this key file signs for ${this.address}, not ${u.sender}`);
1527
+ const signable = Transaction.updateContract(
1528
+ {
1529
+ amount: CcdAmount.fromMicroCcd(u.amount),
1530
+ address: SdkContractAddress.create(u.contract.index, u.contract.subindex),
1531
+ receiveName: ReceiveName.fromString(u.receiveName),
1532
+ message: Parameter.fromBuffer(buffer(u.parameter))
1533
+ },
1534
+ Energy.create(opts.energy)
1535
+ ).addMetadata({
1536
+ sender: AccountAddress.fromBase58(u.sender),
1537
+ nonce: SequenceNumber.create(opts.nonce),
1538
+ expiry: TransactionExpiry.fromEpochSeconds(opts.expiry)
1539
+ }).build();
1540
+ const signature = await this.#signer.signAsSender(signable);
1541
+ const finalized = Transaction.finalize(Transaction.addSignature(signable, signature));
1542
+ if (finalized.version !== 0) throw new OnboardError("tx_unexpected", "expected a version 0 transaction");
1543
+ return { txHash: v0TransactionHash(finalized), blockItemHex: toHex(AccountTransactionV0.serialize(finalized)) };
1544
+ }
1545
+ /** Wipes the key from memory. */
1546
+ destroy() {
1547
+ this.#signer.destroy();
1548
+ }
1549
+ };
1550
+ var KeyFileWalletProver = class _KeyFileWalletProver {
1551
+ address;
1552
+ #wallet;
1553
+ constructor(wallet) {
1554
+ this.#wallet = wallet;
1555
+ this.address = wallet.address;
1556
+ }
1557
+ static async fromFile(file) {
1558
+ return new _KeyFileWalletProver(await loadWalletExport(file));
1559
+ }
1560
+ async prove(input) {
1561
+ return agentWalletProof(this.#wallet, input);
1562
+ }
1563
+ destroy() {
1564
+ destroyWallet(this.#wallet);
1565
+ }
1566
+ };
1567
+
1568
+ // packages/onboard/src/adapters/grpc.ts
1569
+ import {
1570
+ AccountAddress as AccountAddress2,
1571
+ AccountTransactionV0 as AccountTransactionV02,
1572
+ BlockHash,
1573
+ CcdAmount as CcdAmount2,
1574
+ ContractAddress as SdkContractAddress2,
1575
+ ContractEvent,
1576
+ Energy as Energy2,
1577
+ isKnown,
1578
+ Parameter as Parameter2,
1579
+ ReceiveName as ReceiveName2,
1580
+ RejectReasonTag,
1581
+ ReturnValue,
1582
+ TransactionEventTag,
1583
+ TransactionHash,
1584
+ TransactionKindString,
1585
+ TransactionStatusEnum,
1586
+ TransactionSummaryType
1587
+ } from "@concordium/web-sdk";
1588
+ function buffer2(bytes) {
1589
+ const copy = new Uint8Array(bytes.length);
1590
+ copy.set(bytes);
1591
+ return copy.buffer;
1592
+ }
1593
+ var GrpcOnboardChain = class {
1594
+ #client;
1595
+ #registry;
1596
+ #energy;
1597
+ constructor(client, registry, opts = {}) {
1598
+ this.#client = client;
1599
+ this.#registry = registry;
1600
+ this.#energy = opts.energy ?? 500000n;
1601
+ }
1602
+ async assertTestnet() {
1603
+ try {
1604
+ await this.#registry.assertTestnet();
1605
+ } catch (err) {
1606
+ throw new OnboardError("wrong_network", err.message, { cause: err });
1607
+ }
1608
+ }
1609
+ agentOf(tokenId) {
1610
+ return this.#registry.agentOf(tokenId);
1611
+ }
1612
+ agentWalletNonce(tokenId) {
1613
+ return this.#registry.getAgentWalletNonce(tokenId);
1614
+ }
1615
+ async ownerOfKey(key) {
1616
+ const wanted = { namespace: key.namespace, keyType: key.keyType, publicKey: toHex(key.publicKey) };
1617
+ const reg = await this.#registry.ownerOfKey(wanted);
1618
+ if (reg === null || !externalKeyIdEquals(reg.externalKey, wanted)) return null;
1619
+ return { owner: reg.owner, status: reg.status };
1620
+ }
1621
+ async sellerOf(bureau, tokenId) {
1622
+ const res = await this.#client.invokeContract({
1623
+ contract: SdkContractAddress2.create(bureau.index, bureau.subindex),
1624
+ method: ReceiveName2.fromString(`${BUREAU_CONTRACT_NAME}.${BUREAU_ENTRYPOINTS.sellerOf}`),
1625
+ parameter: Parameter2.fromBuffer(buffer2(encodeSellerOfParams(tokenId))),
1626
+ energy: Energy2.create(this.#energy)
1627
+ });
1628
+ if (res.tag === "failure" || res.returnValue === void 0) throw new OnboardError("chain_unavailable", "tab_bureau.sellerOf failed");
1629
+ return decodeSellerOfResult(Uint8Array.from(ReturnValue.toBuffer(res.returnValue)));
1630
+ }
1631
+ async balance(address2) {
1632
+ const info = await this.#client.getAccountInfo(AccountAddress2.fromBase58(address2));
1633
+ return info.accountAvailableBalance.microCcdAmount;
1634
+ }
1635
+ async nextNonce(address2) {
1636
+ return (await this.#client.getNextAccountNonce(AccountAddress2.fromBase58(address2))).nonce.value;
1637
+ }
1638
+ async dryRun(u) {
1639
+ const res = await this.#client.invokeContract({
1640
+ invoker: AccountAddress2.fromBase58(u.sender),
1641
+ contract: SdkContractAddress2.create(u.contract.index, u.contract.subindex),
1642
+ method: ReceiveName2.fromString(u.receiveName),
1643
+ parameter: Parameter2.fromBuffer(buffer2(u.parameter)),
1644
+ amount: CcdAmount2.fromMicroCcd(u.amount),
1645
+ energy: Energy2.create(this.#energy)
1646
+ });
1647
+ if (res.tag === "success") return { ok: true, usedEnergy: res.usedEnergy.value };
1648
+ const reason = res.reason;
1649
+ if (!isKnown(reason)) return { ok: false, rejectCode: null, reason: "Unknown" };
1650
+ return { ok: false, rejectCode: reason.tag === RejectReasonTag.RejectedReceive ? reason.rejectReason : null, reason: reason.tag };
1651
+ }
1652
+ async send(transactionHex) {
1653
+ const tx = AccountTransactionV02.deserialize(buffer2(fromHex(transactionHex)));
1654
+ try {
1655
+ return TransactionHash.toHexString(await this.#client.sendTransaction(tx));
1656
+ } catch (err) {
1657
+ if (err?.code === "ALREADY_EXISTS") return v0TransactionHash(tx);
1658
+ throw err;
1659
+ }
1660
+ }
1661
+ async status(txHash) {
1662
+ try {
1663
+ const s = await this.#client.getBlockItemStatus(TransactionHash.fromHexString(txHash));
1664
+ if (s.status === TransactionStatusEnum.Finalized) return "finalized";
1665
+ return s.status === TransactionStatusEnum.Committed ? "committed" : "received";
1666
+ } catch (err) {
1667
+ if (err?.code === "NOT_FOUND") return "absent";
1668
+ throw err;
1669
+ }
1670
+ }
1671
+ async waitForFinalization(txHash, timeoutMs) {
1672
+ const item = await this.#client.waitForTransactionFinalization(TransactionHash.fromHexString(txHash), timeoutMs);
1673
+ if (!isKnown(item.summary)) throw new OnboardError("tx_unexpected", `transaction ${txHash}: unknown summary`);
1674
+ return outcomeOf(txHash, BlockHash.toHexString(item.blockHash), item.summary);
1675
+ }
1676
+ };
1677
+ function outcomeOf(txHash, blockHash, summary) {
1678
+ if (summary.type !== TransactionSummaryType.AccountTransaction) throw new OnboardError("tx_unexpected", `${txHash} is not an account transaction`);
1679
+ const base = { txHash, blockHash, sender: summary.sender.address };
1680
+ if (summary.transactionType === TransactionKindString.Failed) {
1681
+ const reason = summary.rejectReason;
1682
+ const rejectCode = isKnown(reason) && reason.tag === RejectReasonTag.RejectedReceive ? reason.rejectReason : null;
1683
+ return { ...base, ok: false, rejectReason: isKnown(reason) ? reason.tag : "Unknown", rejectCode, contractEvents: [] };
1684
+ }
1685
+ const contractEvents = [];
1686
+ if (summary.transactionType === TransactionKindString.Update) {
1687
+ for (const ev of summary.events) {
1688
+ if (!isKnown(ev)) continue;
1689
+ if (ev.tag === TransactionEventTag.Updated || ev.tag === TransactionEventTag.Interrupted) {
1690
+ contractEvents.push({
1691
+ contract: contractAddress(ev.address.index, ev.address.subindex),
1692
+ events: ev.events.map((e) => Uint8Array.from(ContractEvent.toBuffer(e)))
1693
+ });
1694
+ }
1695
+ }
1696
+ }
1697
+ return { ...base, ok: true, rejectReason: null, rejectCode: null, contractEvents };
1698
+ }
1699
+
1700
+ // packages/onboard/src/adapters/hosted.ts
1701
+ var HostedRegistryMcp = class {
1702
+ #hosted;
1703
+ constructor(hosted) {
1704
+ this.#hosted = hosted;
1705
+ }
1706
+ call(tool, args) {
1707
+ return this.#hosted.callTool(tool, args, { cache: false });
1708
+ }
1709
+ async checkBadge(badge) {
1710
+ const v = await this.#hosted.checkBadge(badge, { cache: false });
1711
+ return { badgeValid: v.badgeValid, issues: v.issues.map((i) => typeof i === "string" ? i : JSON.stringify(i)) };
1712
+ }
1713
+ };
1714
+
1715
+ // packages/onboard/src/adapters/keyd.ts
1716
+ var KeydSessionKeys = class {
1717
+ dir;
1718
+ constructor(dir = defaultKeyDir()) {
1719
+ this.dir = dir;
1720
+ }
1721
+ async ensure(name, role, opts) {
1722
+ const file = keyFilePath(this.dir, name);
1723
+ let key;
1724
+ try {
1725
+ key = await readKeyFile(file);
1726
+ } catch (err) {
1727
+ if (err.code !== "ENOENT") throw err;
1728
+ if (opts.mustExist) throw new OnboardError("key_mismatch", `key ${name} must already exist in ${this.dir}`);
1729
+ key = await generateKeyFile(this.dir, name, role);
1730
+ }
1731
+ try {
1732
+ if (key.role !== role) throw new OnboardError("key_mismatch", `key ${name} has role ${key.role}, not ${role}`);
1733
+ const publicKey = Uint8Array.from(key.secret.publicKey);
1734
+ return { name, publicKey, keyId: ed25519KeyId(publicKey, key.keyId.namespace) };
1735
+ } finally {
1736
+ key.secret.destroy();
1737
+ }
1738
+ }
1739
+ async signCis8(name, canonical) {
1740
+ if (fromUtf8(canonical.subarray(0, CIS8_CANONICAL_TAG.length)) !== CIS8_CANONICAL_TAG) {
1741
+ throw new OnboardError("invalid_input", "not a CIS-8 canonical message");
1742
+ }
1743
+ const key = await readKeyFile(keyFilePath(this.dir, name));
1744
+ try {
1745
+ return key.secret.sign(canonical);
1746
+ } finally {
1747
+ key.secret.destroy();
1748
+ }
1749
+ }
1750
+ };
1751
+
1752
+ // packages/onboard/src/adapters/cards.ts
1753
+ import { promises as fsp2 } from "node:fs";
1754
+ import path2 from "node:path";
1755
+ var DirCardStore = class {
1756
+ dir;
1757
+ constructor(dir) {
1758
+ this.dir = path2.resolve(dir);
1759
+ }
1760
+ async put(sha2562, bytes) {
1761
+ if (!/^[0-9a-f]{64}$/.test(sha2562) || sha256Hex(bytes) !== sha2562) throw new OnboardError("card_invalid", "card bytes do not match their hash");
1762
+ await fsp2.mkdir(this.dir, { recursive: true });
1763
+ const file = path2.join(this.dir, `${sha2562}.json`);
1764
+ try {
1765
+ await fsp2.writeFile(file, bytes, { flag: "wx", mode: 420 });
1766
+ } catch (err) {
1767
+ if (err.code !== "EEXIST") throw err;
1768
+ const existing = new Uint8Array(await fsp2.readFile(file));
1769
+ if (sha256Hex(existing) !== sha2562) throw new OnboardError("card_invalid", `${file} exists with other bytes`);
1770
+ }
1771
+ return file;
1772
+ }
1773
+ };
1774
+ var SafeCardFetcher = class {
1775
+ #opts;
1776
+ constructor(opts = {}) {
1777
+ this.#opts = opts;
1778
+ }
1779
+ async fetch(url) {
1780
+ if (!url.startsWith("https://")) return { ok: false, error: "card URLs must be https" };
1781
+ const res = await fetchAgentCard(url, this.#opts);
1782
+ if (res.ok && res.body !== void 0) return { ok: true, body: res.body };
1783
+ return { ok: false, error: res.error ?? `HTTP ${res.status ?? "?"}` };
1784
+ }
1785
+ };
1786
+
1787
+ // packages/onboard/src/prices.ts
1788
+ import { z as z6 } from "zod";
1789
+ var prices = z6.record(z6.string().min(1).max(256), z6.string().regex(/^(0|[1-9][0-9]{0,19})$/));
1790
+ function priceScheduleHash(schedule) {
1791
+ const parsed = prices.safeParse(schedule);
1792
+ if (!parsed.success || Object.keys(parsed.data).length === 0) throw new OnboardError("invalid_input", "a price schedule maps routes to microCCD decimal strings");
1793
+ return sha256Hex(jcsBytes(parsed.data));
1794
+ }
1795
+
1796
+ export {
1797
+ errorCode,
1798
+ sha256Hex,
1799
+ badgeExtensionSchema,
1800
+ registrationSchema,
1801
+ badgeIssues,
1802
+ agentCardSchema,
1803
+ explorerTx,
1804
+ explorerAccount,
1805
+ STEP_NAMES,
1806
+ createPlan,
1807
+ FilePlanStore,
1808
+ consentUrl,
1809
+ submitUpdate,
1810
+ Onboarder,
1811
+ FAUCET_HINT,
1812
+ checkFunding,
1813
+ KeyFileOwnerSigner,
1814
+ KeyFileWalletProver,
1815
+ GrpcOnboardChain,
1816
+ HostedRegistryMcp,
1817
+ KeydSessionKeys,
1818
+ DirCardStore,
1819
+ SafeCardFetcher,
1820
+ priceScheduleHash
1821
+ };