@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,491 @@
1
+ import {
2
+ CliError
3
+ } from "./chunk-MOZ4BFSB.js";
4
+
5
+ // packages/indexer-client/src/schemas.ts
6
+ import { z } from "zod";
7
+ var decimalSchema = z.string().max(80).regex(/^(0|[1-9][0-9]*)$/, "decimal string");
8
+ var ratioSchema = z.string().max(40).regex(/^(0|[1-9][0-9]*)\.[0-9]{2}$/, "ratio with two decimals");
9
+ var hexSchema = z.string().max(4096).regex(/^(?:[0-9a-f]{2})*$/, "lowercase hex");
10
+ var hash32Schema = z.string().regex(/^[0-9a-f]{64}$/, "32-byte lowercase hex");
11
+ var accountSchema = z.string().regex(/^[1-9A-HJ-NP-Za-km-z]{50}$/, "base58 account address");
12
+ var contractSchema = z.string().max(45).regex(/^<(0|[1-9][0-9]*),(0|[1-9][0-9]*)>$/, "contract address");
13
+ var isoTimeSchema = z.iso.datetime();
14
+ var standingKeySchema = z.union([accountSchema, hash32Schema]);
15
+ var eventDataSchema = z.record(z.string().max(64), z.string().max(4096).nullable());
16
+ var agentStatusSchema = z.enum(["Active", "Revoked"]);
17
+ var apiErrorSchema = z.object({
18
+ error: z.string().max(64).regex(/^[a-z][a-z0-9_]*$/),
19
+ message: z.string().max(2e3)
20
+ });
21
+ var badgeResultSchema = z.object({
22
+ valid: z.boolean(),
23
+ source: z.enum(["local", "hosted"]),
24
+ checkedAt: isoTimeSchema,
25
+ reasons: z.array(z.string().max(500)).max(64)
26
+ });
27
+ var agentSummarySchema = z.object({
28
+ token: decimalSchema,
29
+ owner: accountSchema,
30
+ agentWallet: accountSchema.nullable(),
31
+ uri: z.string().max(8192).nullable(),
32
+ status: agentStatusSchema,
33
+ registeredAt: isoTimeSchema,
34
+ updatedAt: isoTimeSchema,
35
+ badge: badgeResultSchema.nullable(),
36
+ ours: z.boolean()
37
+ });
38
+ var AGENT_EVENT_KINDS = ["registered", "uriChanged", "walletChanged", "metadataChanged", "transferred", "revoked"];
39
+ var agentEventKindSchema = z.enum(AGENT_EVENT_KINDS);
40
+ var agentEventSchema = z.object({
41
+ kind: agentEventKindSchema,
42
+ txHash: hash32Schema,
43
+ blockHeight: decimalSchema,
44
+ at: isoTimeSchema,
45
+ data: eventDataSchema
46
+ });
47
+ var cis8KeySchema = z.object({
48
+ namespace: z.string().max(256),
49
+ /** The key type of the ExternalKeyId (for example `ed25519`). */
50
+ keyType: z.string().max(256),
51
+ /** Hex of the public key bytes. */
52
+ keyId: hexSchema,
53
+ owner: accountSchema,
54
+ status: agentStatusSchema,
55
+ registeredAt: isoTimeSchema,
56
+ txHash: hash32Schema,
57
+ revokedAt: isoTimeSchema.nullable()
58
+ });
59
+ var agentDetailSchema = agentSummarySchema.extend({
60
+ history: z.array(agentEventSchema),
61
+ keys: z.array(cis8KeySchema)
62
+ });
63
+ function pageSchema(item) {
64
+ return z.object({ items: z.array(item), next: z.string().max(512).nullable() });
65
+ }
66
+ var agentPageSchema = pageSchema(agentSummarySchema);
67
+ var walletHistorySchema = z.object({
68
+ items: z.array(z.object({ wallet: accountSchema.nullable(), txHash: hash32Schema, at: isoTimeSchema }))
69
+ });
70
+ var ownerRowSchema = z.object({
71
+ owner: accountSchema,
72
+ agents: decimalSchema,
73
+ active: decimalSchema,
74
+ badgeValid: decimalSchema,
75
+ ours: z.boolean()
76
+ });
77
+ var ownerPageSchema = pageSchema(ownerRowSchema);
78
+ var cis8KeyPageSchema = pageSchema(cis8KeySchema);
79
+ var BUREAU_EVENT_KINDS = [
80
+ "SellerRegistered",
81
+ "LineOpened",
82
+ "TabOpened",
83
+ "TabSettled",
84
+ "CapStepped",
85
+ "DefaultReported",
86
+ "DefaultCured",
87
+ "TabClosed",
88
+ "LineClosed",
89
+ "FlagCleared",
90
+ "ParamsChanged"
91
+ ];
92
+ var bureauEventKindSchema = z.enum(BUREAU_EVENT_KINDS);
93
+ var bureauEventSchema = z.object({
94
+ kind: bureauEventKindSchema,
95
+ txHash: hash32Schema,
96
+ blockHeight: decimalSchema,
97
+ at: isoTimeSchema,
98
+ data: eventDataSchema
99
+ });
100
+ var bureauEventPageSchema = pageSchema(bureauEventSchema);
101
+ var externalKeyIdSchema = z.object({
102
+ namespace: z.string().max(256),
103
+ keyType: z.string().max(256),
104
+ publicKey: hexSchema
105
+ });
106
+ var sellerPolicyJsonSchema = z.object({
107
+ maxTabLimit: decimalSchema,
108
+ minBuyerTier: z.number().int().min(0).max(255),
109
+ minBuyerK: z.number().int().min(0).max(255),
110
+ minCycleMs: decimalSchema,
111
+ maxCycleMs: decimalSchema,
112
+ maxNewTabsPerDay: decimalSchema,
113
+ priceScheduleHash: hash32Schema,
114
+ admitBadgeInvalid: z.boolean()
115
+ });
116
+ var sellerViewJsonSchema = z.object({
117
+ token: decimalSchema,
118
+ owner: accountSchema,
119
+ wallet: accountSchema,
120
+ idp: z.number().int().min(0),
121
+ createdAt: isoTimeSchema,
122
+ sessionKey: externalKeyIdSchema,
123
+ policy: sellerPolicyJsonSchema,
124
+ registeredAt: isoTimeSchema,
125
+ day: decimalSchema,
126
+ tabsToday: decimalSchema
127
+ });
128
+ var lineViewJsonSchema = z.object({
129
+ lineId: decimalSchema,
130
+ buyerToken: decimalSchema,
131
+ owner: accountSchema,
132
+ buyerWallet: accountSchema.nullable(),
133
+ sessionKey: externalKeyIdSchema,
134
+ tier: z.number().int().min(0).max(255),
135
+ standingKey: standingKeySchema,
136
+ lineLimit: decimalSchema,
137
+ perSellerMax: decimalSchema,
138
+ maxCycleMs: decimalSchema,
139
+ validUntil: isoTimeSchema,
140
+ openTotal: decimalSchema,
141
+ ci: z.boolean(),
142
+ status: z.enum(["Active", "Closed"]),
143
+ steppedBy: z.array(accountSchema),
144
+ openTabs: z.array(decimalSchema),
145
+ termsHash: hash32Schema,
146
+ openedAt: isoTimeSchema
147
+ });
148
+ var tabViewJsonSchema = z.object({
149
+ tabId: decimalSchema,
150
+ lineId: decimalSchema,
151
+ sellerToken: decimalSchema,
152
+ sellerOwner: accountSchema,
153
+ sellerWallet: accountSchema,
154
+ sellerKey: hash32Schema,
155
+ limit: decimalSchema,
156
+ cycleMs: decimalSchema,
157
+ graceMs: decimalSchema,
158
+ settleWindowMs: decimalSchema,
159
+ maxLanes: z.number().int().min(0),
160
+ openedAt: isoTimeSchema,
161
+ lanes: z.array(z.object({ seq: decimalSchema, chargedCumulative: decimalSchema })),
162
+ settledTotal: decimalSchema,
163
+ lastSettledCycle: decimalSchema.nullable(),
164
+ lastSettledAt: isoTimeSchema.nullable(),
165
+ lastAcked: z.boolean(),
166
+ lastOnTime: z.boolean(),
167
+ reportedTotal: decimalSchema,
168
+ status: z.enum(["Active", "Defaulted", "Closed"]),
169
+ closeRequestedAt: isoTimeSchema.nullable(),
170
+ curedAt: isoTimeSchema.nullable(),
171
+ agreementHash: hash32Schema
172
+ });
173
+ var sellerRecordSchema = z.object({ view: sellerViewJsonSchema, events: z.array(bureauEventSchema) });
174
+ var lineRecordSchema = z.object({ view: lineViewJsonSchema, events: z.array(bureauEventSchema) });
175
+ var tabRecordSchema = z.object({ view: tabViewJsonSchema, events: z.array(bureauEventSchema) });
176
+ var standingSchema = z.object({
177
+ key: standingKeySchema,
178
+ /** 0 for an owner-account key; 1 or 2 for a subject key; null when no line names the key yet. */
179
+ tier: z.number().int().min(0).max(255).nullable(),
180
+ k: z.number().int().min(0).max(255),
181
+ openLimits: decimalSchema,
182
+ flagUntil: isoTimeSchema.nullable(),
183
+ counters: z.record(z.string().max(64), decimalSchema),
184
+ history: z.array(bureauEventSchema)
185
+ });
186
+ var explainSchema = z.object({
187
+ key: standingKeySchema,
188
+ facts: z.array(z.string().max(1e3)).max(64),
189
+ explanation: z.string().max(2e4),
190
+ generatedBy: z.enum(["template", "llm-draft"])
191
+ });
192
+ var reviewRequestSchema = z.strictObject({
193
+ key: standingKeySchema,
194
+ reason: z.string().trim().min(1).max(2e3),
195
+ contact: z.string().trim().min(1).max(200).optional()
196
+ });
197
+ var reviewAcceptedSchema = z.object({ reviewId: z.uuid() });
198
+ var txDetailSchema = z.object({
199
+ hash: hash32Schema,
200
+ blockHeight: decimalSchema,
201
+ at: isoTimeSchema,
202
+ sender: accountSchema,
203
+ sponsor: accountSchema.nullable(),
204
+ costMicroCcd: decimalSchema,
205
+ costEurMicro: decimalSchema.nullable(),
206
+ events: z.array(z.object({ contract: contractSchema, kind: z.string().max(64), data: eventDataSchema })),
207
+ transfers: z.array(
208
+ z.object({ from: z.union([accountSchema, contractSchema]), to: accountSchema, amountMicroCcd: decimalSchema })
209
+ )
210
+ });
211
+ var metricsSchema = z.object({
212
+ sellers: decimalSchema,
213
+ buyers: decimalSchema,
214
+ lines: decimalSchema,
215
+ tabs: decimalSchema,
216
+ settledCycles: decimalSchema,
217
+ settledMicroCcd: decimalSchema,
218
+ defaults: decimalSchema,
219
+ cures: decimalSchema,
220
+ vouchersReported: decimalSchema,
221
+ notaryRepairs: decimalSchema,
222
+ sponsoredTx: decimalSchema,
223
+ sponsorSpendMicroCcd: decimalSchema,
224
+ paidCallsPerSponsoredTx: ratioSchema.nullable()
225
+ });
226
+ var metricsSummarySchema = z.object({ ours: metricsSchema, external: metricsSchema, generatedAt: isoTimeSchema });
227
+ var ledgerLineSchema = z.object({
228
+ perCallEurMicro: decimalSchema.nullable(),
229
+ basis: z.string().max(1e3),
230
+ txHashes: z.array(hash32Schema).max(100)
231
+ });
232
+ var ledgerSchema = z.object({
233
+ exact: ledgerLineSchema,
234
+ steadyStateTab: ledgerLineSchema,
235
+ firstCycleAllIn: ledgerLineSchema
236
+ });
237
+ var anchorsSchema = z.object({
238
+ items: z.array(
239
+ z.object({
240
+ date: z.iso.date(),
241
+ root: hash32Schema,
242
+ txHash: hash32Schema.nullable()
243
+ })
244
+ )
245
+ });
246
+ var healthSchema = z.object({
247
+ status: z.enum(["ok", "degraded", "down"]),
248
+ database: z.enum(["ok", "down"]),
249
+ follower: z.object({
250
+ height: decimalSchema.nullable(),
251
+ tip: decimalSchema.nullable(),
252
+ lag: decimalSchema.nullable(),
253
+ halted: z.string().max(500).nullable()
254
+ }),
255
+ bootstrap: z.object({ cis8004: z.string().max(64), cis8: z.string().max(64) }),
256
+ /**
257
+ * Logged events the indexer could not decode that came from history before the module it pins for
258
+ * their contract: stored raw and skipped (services/indexer README, "Undecodable events"). An
259
+ * undecodable event that may come from a pinned module halts the job instead. Absent from indexers
260
+ * that predate it.
261
+ */
262
+ undecodable: z.object({ recorded: z.number().int().min(0) }).optional(),
263
+ /** The module tab_bureau runs at the last finalized block it was read at, against the expected one. */
264
+ bureauModule: z.object({
265
+ expected: hash32Schema.nullable(),
266
+ live: hash32Schema.nullable(),
267
+ matches: z.boolean().nullable(),
268
+ checkedAt: isoTimeSchema.nullable()
269
+ })
270
+ });
271
+ var bureauModuleEntrySchema = z.object({
272
+ kind: z.enum(["init", "upgrade"]),
273
+ moduleRef: hash32Schema,
274
+ /** The module before an upgrade; null for the init. */
275
+ previous: hash32Schema.nullable(),
276
+ blockHeight: decimalSchema,
277
+ txHash: hash32Schema,
278
+ at: isoTimeSchema
279
+ });
280
+ var bureauModuleSchema = z.object({
281
+ contract: contractSchema,
282
+ /** The indexer's `EXPECTED_BUREAU_MODULE`; null when it is not set. */
283
+ expected: hash32Schema.nullable(),
284
+ /** The module read at the last finalized block; null before the first successful read. */
285
+ live: z.object({ moduleRef: hash32Schema, height: decimalSchema, checkedAt: isoTimeSchema }).nullable(),
286
+ /** live = expected; null when either is unknown. */
287
+ matches: z.boolean().nullable(),
288
+ /** Why the last read of the live module failed; null after a successful one. */
289
+ error: z.string().max(500).nullable(),
290
+ /** Oldest first: the init module and every upgrade the indexer has seen. */
291
+ history: z.array(bureauModuleEntrySchema).max(1e3),
292
+ /** The height through which `history` is complete (the follower's height); null while it is not. */
293
+ historyThrough: decimalSchema.nullable()
294
+ });
295
+ var cis8StreamEventSchema = z.object({
296
+ kind: z.enum(["registered", "revoked", "metadataUpdated"]),
297
+ namespace: z.string().max(256),
298
+ keyType: z.string().max(256),
299
+ keyId: hexSchema,
300
+ owner: accountSchema.nullable(),
301
+ txHash: hash32Schema,
302
+ blockHeight: decimalSchema,
303
+ at: isoTimeSchema
304
+ });
305
+ var registryStreamEventSchema = agentEventSchema.extend({ token: decimalSchema });
306
+ var resyncStreamEventSchema = z.object({ reason: z.string().max(500) });
307
+
308
+ // packages/indexer-client/src/client.ts
309
+ var IndexerApiError = class extends Error {
310
+ name = "IndexerApiError";
311
+ /** HTTP status, or 0 when no response arrived. */
312
+ status;
313
+ /** The server's snake_case code, or `network_error` / `timeout` / `invalid_response`. */
314
+ code;
315
+ constructor(status, code, message) {
316
+ super(message);
317
+ this.status = status;
318
+ this.code = code;
319
+ }
320
+ };
321
+ var IndexerClient = class {
322
+ #base;
323
+ #fetch;
324
+ #timeoutMs;
325
+ #maxBytes;
326
+ constructor(opts) {
327
+ const url = new URL(opts.baseUrl);
328
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new TypeError("indexer baseUrl must be http(s)");
329
+ this.#base = url.toString().replace(/\/+$/, "");
330
+ this.#fetch = opts.fetch ?? ((input, init) => fetch(input, init));
331
+ this.#timeoutMs = opts.timeoutMs ?? 1e4;
332
+ this.#maxBytes = opts.maxResponseBytes ?? 4 * 1024 * 1024;
333
+ }
334
+ /** The normalized base URL (no trailing slash). */
335
+ get baseUrl() {
336
+ return this.#base;
337
+ }
338
+ agents(q = {}) {
339
+ return this.#get("/v1/agents", agentPageSchema, { status: q.status, owner: q.owner, limit: q.limit, cursor: q.cursor });
340
+ }
341
+ agent(token) {
342
+ return this.#get(`/v1/agents/${seg(token)}`, agentDetailSchema);
343
+ }
344
+ walletHistory(token) {
345
+ return this.#get(`/v1/agents/${seg(token)}/wallet-history`, walletHistorySchema);
346
+ }
347
+ owners(q = {}) {
348
+ return this.#get("/v1/owners", ownerPageSchema, { limit: q.limit, cursor: q.cursor });
349
+ }
350
+ cis8Keys(q = {}) {
351
+ return this.#get("/v1/cis8/keys", cis8KeyPageSchema, {
352
+ owner: q.owner,
353
+ namespace: q.namespace,
354
+ status: q.status,
355
+ limit: q.limit,
356
+ cursor: q.cursor
357
+ });
358
+ }
359
+ cis8Key(namespace, keyId) {
360
+ return this.#get(`/v1/cis8/keys/${seg(namespace)}/${seg(keyId)}`, cis8KeySchema);
361
+ }
362
+ seller(token) {
363
+ return this.#get(`/v1/bureau/sellers/${seg(token)}`, sellerRecordSchema);
364
+ }
365
+ line(lineId) {
366
+ return this.#get(`/v1/bureau/lines/${seg(lineId)}`, lineRecordSchema);
367
+ }
368
+ tab(tabId) {
369
+ return this.#get(`/v1/bureau/tabs/${seg(tabId)}`, tabRecordSchema);
370
+ }
371
+ /** The module tab_bureau runs, the expected one and the module history (`GET /v1/bureau/module`). */
372
+ bureauModule() {
373
+ return this.#get("/v1/bureau/module", bureauModuleSchema);
374
+ }
375
+ bureauEvents(q = {}) {
376
+ return this.#get("/v1/bureau/events", bureauEventPageSchema, { since: q.since, kind: q.kind, limit: q.limit });
377
+ }
378
+ standing(key) {
379
+ return this.#get(`/v1/standing/${seg(key)}`, standingSchema);
380
+ }
381
+ explain(key) {
382
+ return this.#get(`/v1/standing/${seg(key)}/explain`, explainSchema);
383
+ }
384
+ requestReview(body) {
385
+ return this.#request("/v1/review", reviewAcceptedSchema, {
386
+ method: "POST",
387
+ headers: { "content-type": "application/json", accept: "application/json" },
388
+ body: JSON.stringify(body)
389
+ });
390
+ }
391
+ tx(hash) {
392
+ return this.#get(`/v1/tx/${seg(hash)}`, txDetailSchema);
393
+ }
394
+ metricsSummary() {
395
+ return this.#get("/v1/metrics/summary", metricsSummarySchema);
396
+ }
397
+ ledger() {
398
+ return this.#get("/v1/metrics/ledger", ledgerSchema);
399
+ }
400
+ anchors() {
401
+ return this.#get("/v1/anchors", anchorsSchema);
402
+ }
403
+ health() {
404
+ return this.#request("/healthz", healthSchema, { method: "GET", headers: { accept: "application/json" } }, true);
405
+ }
406
+ #get(path, schema, query = {}) {
407
+ const params = new URLSearchParams();
408
+ for (const [k, v] of Object.entries(query)) if (v !== void 0) params.set(k, String(v));
409
+ const qs = params.toString();
410
+ return this.#request(qs === "" ? path : `${path}?${qs}`, schema, { method: "GET", headers: { accept: "application/json" } });
411
+ }
412
+ async #request(path, schema, init, acceptAnyStatus = false) {
413
+ let res;
414
+ try {
415
+ res = await this.#fetch(`${this.#base}${path}`, { ...init, signal: AbortSignal.timeout(this.#timeoutMs) });
416
+ } catch (e) {
417
+ const timedOut = e instanceof Error && (e.name === "TimeoutError" || e.name === "AbortError");
418
+ throw new IndexerApiError(0, timedOut ? "timeout" : "network_error", timedOut ? "indexer request timed out" : `indexer unreachable: ${messageOf(e)}`);
419
+ }
420
+ const body = await readJson(res, this.#maxBytes);
421
+ if (!res.ok && !acceptAnyStatus) {
422
+ const err = apiErrorSchema.safeParse(body);
423
+ if (err.success) throw new IndexerApiError(res.status, err.data.error, err.data.message);
424
+ throw new IndexerApiError(res.status, "http_error", `indexer answered HTTP ${res.status}`);
425
+ }
426
+ const parsed = schema.safeParse(body);
427
+ if (!parsed.success) {
428
+ throw new IndexerApiError(res.status, "invalid_response", `indexer response does not match the contract: ${parsed.error.issues[0]?.message ?? "invalid"}`);
429
+ }
430
+ return parsed.data;
431
+ }
432
+ };
433
+ function seg(v) {
434
+ const s = typeof v === "bigint" ? v.toString() : v;
435
+ if (s.length === 0 || s === "." || s === ".." || s.length > 512) throw new TypeError(`invalid path segment ${JSON.stringify(s)}`);
436
+ return encodeURIComponent(s);
437
+ }
438
+ async function readJson(res, maxBytes) {
439
+ const declared = Number(res.headers.get("content-length") ?? "0");
440
+ if (declared > maxBytes) throw new IndexerApiError(res.status, "invalid_response", "indexer response too large");
441
+ const text = await readText(res, maxBytes);
442
+ if (text === "") return null;
443
+ try {
444
+ return JSON.parse(text);
445
+ } catch {
446
+ throw new IndexerApiError(res.status, "invalid_response", "indexer response is not JSON");
447
+ }
448
+ }
449
+ async function readText(res, maxBytes) {
450
+ if (res.body === null) return "";
451
+ const reader = res.body.getReader();
452
+ const decoder = new TextDecoder();
453
+ let total = 0;
454
+ let out = "";
455
+ for (; ; ) {
456
+ const { done, value } = await reader.read();
457
+ if (done) break;
458
+ total += value.byteLength;
459
+ if (total > maxBytes) {
460
+ await reader.cancel().catch(() => void 0);
461
+ throw new IndexerApiError(res.status, "invalid_response", "indexer response too large");
462
+ }
463
+ out += decoder.decode(value, { stream: true });
464
+ }
465
+ return out + decoder.decode();
466
+ }
467
+ function messageOf(e) {
468
+ return e instanceof Error ? e.message : String(e);
469
+ }
470
+
471
+ // packages/cli/src/indexer.ts
472
+ var HttpIndexer = class {
473
+ #client;
474
+ constructor(baseUrl, fetchImpl) {
475
+ this.#client = new IndexerClient({ baseUrl, fetch: (input, init) => fetchImpl(input, { ...init, redirect: "error" }), timeoutMs: 15e3 });
476
+ }
477
+ async events(kind, id) {
478
+ const what = kind === "lines" ? "line" : "tab";
479
+ try {
480
+ const record = kind === "lines" ? await this.#client.line(id) : await this.#client.tab(id);
481
+ return record.events;
482
+ } catch (e) {
483
+ if (e instanceof IndexerApiError && e.status === 404) throw new CliError("not_found", `the indexer has no ${what} ${id}`);
484
+ if (e instanceof IndexerApiError) throw new CliError("indexer_error", `${this.#client.baseUrl}/v1/bureau/${kind}/${id}: ${e.code} (${e.message})`);
485
+ throw e;
486
+ }
487
+ }
488
+ };
489
+ export {
490
+ HttpIndexer
491
+ };
@@ -0,0 +1,176 @@
1
+ import {
2
+ DirCardStore,
3
+ FAUCET_HINT,
4
+ FilePlanStore,
5
+ KeyFileOwnerSigner,
6
+ KeyFileWalletProver,
7
+ KeydSessionKeys,
8
+ Onboarder,
9
+ STEP_NAMES,
10
+ checkFunding,
11
+ createPlan,
12
+ explorerAccount,
13
+ explorerTx,
14
+ priceScheduleHash
15
+ } from "./chunk-Q776JIO3.js";
16
+ import "./chunk-IRXOU25X.js";
17
+ import {
18
+ agentBadge
19
+ } from "./chunk-HZHOKJIM.js";
20
+ import "./chunk-S5IAH7CT.js";
21
+ import {
22
+ ReportBuilder
23
+ } from "./chunk-GOEFQ62Z.js";
24
+ import {
25
+ CliError
26
+ } from "./chunk-MOZ4BFSB.js";
27
+ import "./chunk-D3C7KAMJ.js";
28
+
29
+ // packages/cli/src/commands/init.ts
30
+ import { homedir } from "node:os";
31
+ import { join } from "node:path";
32
+ var EXIT_RUN_AGAIN = 3;
33
+ function slug(name) {
34
+ const s = name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48);
35
+ if (s === "") throw new CliError("usage", "the agent name needs letters or digits");
36
+ return s;
37
+ }
38
+ function u(v, what, max) {
39
+ if (!/^[0-9]{1,10}$/.test(v) || Number(v) > max) throw new CliError("usage", `${what} must be an integer up to ${max}`);
40
+ return Number(v);
41
+ }
42
+ function specOf(env, a, key) {
43
+ if (a.role !== "buyer" && a.role !== "seller") throw new CliError("usage", "init needs --role buyer or --role seller");
44
+ if (a.name === void 0 || a.owner === void 0 || a.wallet === void 0) throw new CliError("usage", "init needs --name, --owner <account> and --wallet <agent wallet account>");
45
+ const base = a.baseUrl ?? (env.config.publicBaseUrl === null ? void 0 : `${env.config.publicBaseUrl}/agents/${key}`);
46
+ if (base === void 0) throw new CliError("usage", "init needs --base-url <https origin that will serve the cards> (or PUBLIC_BASE_URL)");
47
+ const spec = {
48
+ name: a.name,
49
+ description: a.description ?? `${a.name}: an agent that ${a.role === "buyer" ? "pays" : "accepts"} metered calls on OpenTab tabs.`,
50
+ skills: [],
51
+ role: a.role,
52
+ owner: a.owner,
53
+ agentWallet: a.wallet,
54
+ publicBaseUrl: base,
55
+ ...env.config.publicBaseUrl === null ? {} : { webBaseUrl: env.config.publicBaseUrl },
56
+ sessionKey: { name: key, role: a.role }
57
+ };
58
+ if (a.role === "buyer") return spec;
59
+ let prices;
60
+ try {
61
+ prices = JSON.parse(a.prices ?? '{"GET /*":"1000000"}');
62
+ } catch {
63
+ throw new CliError("usage", '--prices must be JSON, e.g. {"GET /v1/*":"1000000"}');
64
+ }
65
+ return {
66
+ ...spec,
67
+ seller: {
68
+ policy: {
69
+ maxTabLimit: (BigInt(u(a.maxTabCcd, "--max-tab-ccd", 1e6)) * 1000000n).toString(),
70
+ minBuyerTier: u(a.minTier, "--min-tier", 2),
71
+ minBuyerK: u(a.minK, "--min-k", 255),
72
+ minCycleMs: "60000",
73
+ maxCycleMs: "86400000",
74
+ maxNewTabsPerDay: u(a.tabsPerDay, "--tabs-per-day", 4294967295),
75
+ priceScheduleHash: priceScheduleHash(prices),
76
+ admitBadgeInvalid: a.admitBadgeInvalid
77
+ }
78
+ },
79
+ services: [{ name: "api", endpoint: `${base}/v1` }]
80
+ };
81
+ }
82
+ function external(a) {
83
+ if (a.tx === void 0 && a.walletSignature === void 0) return void 0;
84
+ if (a.step === void 0 || !STEP_NAMES.includes(a.step)) throw new CliError("usage", `--tx and --wallet-signature need --step ${STEP_NAMES.join("|")}`);
85
+ return {
86
+ step: a.step,
87
+ ...a.tx === void 0 ? {} : { txHash: a.tx.toLowerCase() },
88
+ ...a.walletSignature === void 0 ? {} : { walletSignatureHex: a.walletSignature }
89
+ };
90
+ }
91
+ async function ensureFunded(env, plan, a) {
92
+ const chain = await env.onboardChain();
93
+ for (let attempt = 0; ; attempt++) {
94
+ const f = await checkFunding(chain, plan);
95
+ env.io.stdout(`owner ${f.address}: ${f.balance} microCCD available (${f.ok ? "enough" : `needs ${f.required}`})
96
+ `);
97
+ if (f.ok) break;
98
+ env.io.stdout(`${FAUCET_HINT}
99
+ ${explorerAccount(f.address)}
100
+ `);
101
+ if (a.yes || attempt >= 2) throw new CliError("unfunded", "the owner account is not funded");
102
+ const answer = await env.io.prompt("Press Enter once the faucet drop has arrived (q to stop): ");
103
+ if (answer.trim().toLowerCase() === "q") throw new CliError("unfunded", "stopped before funding");
104
+ }
105
+ if (!a.yes) {
106
+ const ok = await env.io.prompt(`Send onboarding transactions from ${plan.spec.owner}? [y/N] `);
107
+ if (ok.trim().toLowerCase() !== "y") throw new CliError("aborted", "nothing was sent");
108
+ }
109
+ }
110
+ function describe(r, plan, rb) {
111
+ if (plan.tokenId !== null) rb.fact("token", `${plan.tokenId} (badge ${agentBadge(BigInt(plan.tokenId))})`);
112
+ for (const name of STEP_NAMES) {
113
+ const rec = plan.steps[name];
114
+ rb.fact(`step ${name}`, `${rec.status}${rec.txHash === null ? "" : ` ${explorerTx(rec.txHash)}`}`);
115
+ }
116
+ switch (r.state) {
117
+ case "complete":
118
+ rb.check("onboarding complete", true);
119
+ return 0;
120
+ case "awaiting_owner":
121
+ rb.check("onboarding complete; the owner opens the line", true, r.consentUrl ?? "");
122
+ return 0;
123
+ case "awaiting_signature":
124
+ rb.check(`${r.step ?? ""} awaits a signature`, false, "sign and send it, then run again with --step and --tx (or --wallet-signature)");
125
+ if (r.payload !== void 0) rb.fact("payload", JSON.stringify(r.payload));
126
+ if (r.walletMessageHex !== void 0) rb.fact("agent wallet signs (raw ed25519, 162 bytes)", r.walletMessageHex);
127
+ return EXIT_RUN_AGAIN;
128
+ case "pending_hosting":
129
+ rb.check("badge waits for the card to be hosted", false, `serve the card bytes at ${plan.cards.badged?.url ?? ""} and run again`);
130
+ if (plan.cards.badged !== null) rb.fact("card file", plan.cards.badged.stored);
131
+ return EXIT_RUN_AGAIN;
132
+ case "failed":
133
+ rb.check(`${r.step ?? ""} failed`, false, `${r.error?.code ?? ""}: ${r.error?.message ?? ""}`);
134
+ return 1;
135
+ }
136
+ }
137
+ async function init(env, a) {
138
+ const home = env.io.env.HOME ?? homedir();
139
+ const key = a.keyName ?? slug(a.name ?? "");
140
+ const store = new FilePlanStore(a.plan ?? join(home, ".opentab", "onboard", "plans", `${key}.plan.json`));
141
+ const plan = await store.load() ?? createPlan(specOf(env, a, key), { bureau: env.config.bureau, now: new Date(env.io.now()) });
142
+ await store.save(plan);
143
+ if (a.ownerKey === void 0 && a.walletKey === void 0 && a.tx === void 0 && a.walletSignature === void 0) {
144
+ env.io.stdout("no --owner-key: transactions are printed as unsigned payloads for Browser Wallet\n");
145
+ }
146
+ await ensureFunded(env, plan, a);
147
+ const signer = a.ownerKey === void 0 ? null : await KeyFileOwnerSigner.fromFile(a.ownerKey);
148
+ const walletProver = a.walletKey === void 0 ? null : await KeyFileWalletProver.fromFile(a.walletKey);
149
+ try {
150
+ const onboarder = new Onboarder({
151
+ chain: await env.onboardChain(),
152
+ mcp: a.noMcp ? null : await env.mcp(),
153
+ signer,
154
+ walletProver,
155
+ keys: new KeydSessionKeys(env.io.env.KEYD_KEY_DIR ?? join(home, ".opentab", "keyd")),
156
+ cards: new DirCardStore(a.cardsDir ?? join(home, ".opentab", "onboard", "cards", key)),
157
+ fetchCard: env.cardFetcher(),
158
+ store,
159
+ now: () => env.io.now(),
160
+ log: (e) => env.io.stderr(`[${e.step}] ${e.message}${e.txHash === void 0 ? "" : ` (tx ${e.txHash})`}
161
+ `)
162
+ });
163
+ const ext = external(a);
164
+ const r = await onboarder.run(await store.load() ?? plan, ext === void 0 ? {} : { external: ext });
165
+ const rb = new ReportBuilder(`onboard ${r.plan.spec.name} (${r.plan.spec.role})`);
166
+ const exitCode = describe(r, r.plan, rb);
167
+ return { report: rb.build(), exitCode };
168
+ } finally {
169
+ signer?.destroy();
170
+ walletProver?.destroy();
171
+ }
172
+ }
173
+ export {
174
+ EXIT_RUN_AGAIN,
175
+ init
176
+ };