@rubicon-caliga/cli 0.1.1 → 0.1.2

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,330 @@
1
+ import { parseUsdcToAtomic, settlementNetworkInfo, type ArticleSummary, type StreamMode } from "@rubicon-caliga/core";
2
+ import type { ReadReceipt, RubiconClient } from "@rubicon-caliga/agent-sdk";
3
+ import { stringFlag, type ParsedArgs } from "./args.js";
4
+ import {
5
+ circleAgentWallet,
6
+ circleAuthStatus,
7
+ classifyCircleError,
8
+ circleGatewayBalance,
9
+ circleGatewayFaucet,
10
+ circleGuidance,
11
+ circleVersion,
12
+ type CircleRunner,
13
+ } from "./circle.js";
14
+ import { HOSTED_GATEWAY_URL, writeConfig, type RubiconCliConfig } from "./config.js";
15
+ import { CliError } from "./errors.js";
16
+ import { articleJson, formatAtomic } from "./format.js";
17
+ import { saveReceipt } from "./receipts.js";
18
+
19
+ export interface CommandRuntime {
20
+ parsed: ParsedArgs;
21
+ config: RubiconCliConfig;
22
+ gatewayUrl: string;
23
+ paymentMode: string;
24
+ circleChain?: string;
25
+ client: RubiconClient;
26
+ }
27
+
28
+ export interface CommandDeps {
29
+ fetch?: typeof fetch;
30
+ circleRunner?: CircleRunner;
31
+ circleCommand?: string;
32
+ cliVersion?: string;
33
+ }
34
+
35
+ interface CheckResult {
36
+ name: string;
37
+ ok: boolean;
38
+ status: "ok" | "warning" | "error";
39
+ value?: unknown;
40
+ guidance?: string;
41
+ }
42
+
43
+ export async function runDoctor(runtime: CommandRuntime, deps: CommandDeps = {}): Promise<Record<string, unknown>> {
44
+ const checks: CheckResult[] = [];
45
+ checks.push({
46
+ name: "cliVersion",
47
+ ok: true,
48
+ status: "ok",
49
+ value: deps.cliVersion ?? "unknown",
50
+ });
51
+ checks.push({
52
+ name: "gatewayConfig",
53
+ ok: Boolean(runtime.config.gatewayUrl || process.env.RUBICON_GATEWAY_URL || runtime.gatewayUrl),
54
+ status: runtime.config.gatewayUrl || process.env.RUBICON_GATEWAY_URL ? "ok" : "warning",
55
+ value: runtime.gatewayUrl,
56
+ guidance:
57
+ runtime.config.gatewayUrl || process.env.RUBICON_GATEWAY_URL
58
+ ? undefined
59
+ : `No gateway config found; using hosted default ${HOSTED_GATEWAY_URL}. Run rubicon config set gateway-url <url> to pin it.`,
60
+ });
61
+
62
+ try {
63
+ const fetcher = deps.fetch ?? fetch;
64
+ const response = await fetcher(`${runtime.gatewayUrl}/health`);
65
+ checks.push({
66
+ name: "gatewayReachability",
67
+ ok: response.ok,
68
+ status: response.ok ? "ok" : "error",
69
+ value: { status: response.status },
70
+ guidance: response.ok ? undefined : "Gateway health check failed. Confirm the URL and network access.",
71
+ });
72
+ } catch (error) {
73
+ checks.push({
74
+ name: "gatewayReachability",
75
+ ok: false,
76
+ status: "error",
77
+ value: errorMessage(error),
78
+ guidance: "Gateway is not reachable from this context. Retry in a network-capable shell or configure a reachable gateway.",
79
+ });
80
+ }
81
+
82
+ await addCircleCheck(checks, "circleCli", () => circleVersion(circleInput(runtime, deps)));
83
+ await addCircleCheck(checks, "circleAuth", () => circleAuthStatus(circleInput(runtime, deps)));
84
+
85
+ const chain = runtime.circleChain ?? runtime.config.circleChain ?? "ARC-TESTNET";
86
+ let walletAddress: `0x${string}` | undefined;
87
+ await addCircleCheck(checks, "arcTestnetWallet", async () => {
88
+ const wallet = await circleAgentWallet({
89
+ ...circleInput(runtime, deps),
90
+ chain,
91
+ configuredAddress: runtime.config.agentWalletAddress ?? envAddress("CIRCLE_AGENT_WALLET_ADDRESS"),
92
+ });
93
+ walletAddress = wallet.address;
94
+ return wallet.address;
95
+ });
96
+
97
+ if (walletAddress) {
98
+ await addCircleCheck(checks, "arcTestnetBalance", async () => circleGatewayBalance({ ...circleInput(runtime, deps), chain, address: walletAddress! }));
99
+ } else {
100
+ checks.push({
101
+ name: "arcTestnetBalance",
102
+ ok: false,
103
+ status: "warning",
104
+ guidance: "Balance check skipped because no Arc Testnet Agent Wallet was found.",
105
+ });
106
+ }
107
+
108
+ const balance = checks.find((check) => check.name === "arcTestnetBalance")?.value as { balanceAtomic?: `${bigint}` } | undefined;
109
+ checks.push({
110
+ name: "testnetTokenStatus",
111
+ ok: Boolean(balance?.balanceAtomic && BigInt(balance.balanceAtomic) > 0n),
112
+ status: balance?.balanceAtomic && BigInt(balance.balanceAtomic) > 0n ? "ok" : "warning",
113
+ value: balance?.balanceAtomic ? { balanceAtomic: balance.balanceAtomic, balanceUsdc: formatAtomic(balance.balanceAtomic) } : undefined,
114
+ guidance:
115
+ balance?.balanceAtomic && BigInt(balance.balanceAtomic) > 0n
116
+ ? undefined
117
+ : "Arc Testnet reads can be funded with the Circle testnet faucet / Gateway testnet funding flow. Do not send mainnet funds for testnet articles.",
118
+ });
119
+
120
+ return {
121
+ success: checks.every((check) => check.status !== "error"),
122
+ gatewayUrl: runtime.gatewayUrl,
123
+ paymentMode: runtime.paymentMode,
124
+ checks,
125
+ };
126
+ }
127
+
128
+ export async function runQuickstartRead(runtime: CommandRuntime, deps: CommandDeps = {}): Promise<Record<string, unknown>> {
129
+ if (runtime.parsed.positionals[1] !== "--first" && !runtime.parsed.flags.first) {
130
+ throw new CliError("MISSING_FIRST", "rubicon quickstart-read currently requires --first.");
131
+ }
132
+ const goal = stringFlag(runtime.parsed.flags, "goal");
133
+ if (!goal) throw new CliError("MISSING_GOAL", "rubicon quickstart-read requires --goal.");
134
+ const maxSpendAtomic = parseQuickstartBudget(runtime.parsed);
135
+ const approvedBudgetUsdc = formatAtomic(maxSpendAtomic);
136
+ const wroteGatewayConfig = await ensureGatewayConfig(runtime);
137
+ const repository = await runtime.client.getRepository();
138
+ const article = repository.articles[0];
139
+ if (!article) throw new CliError("NO_ARTICLES", "No public articles are available from the configured gateway.");
140
+
141
+ const navigation = await runtime.client.getNavigation(article.articleId, goal);
142
+ const sectionId = navigation.navigation.sellerAgent.recommendedSectionId;
143
+ const estimate = estimateRead(article, sectionId, maxSpendAtomic);
144
+ if (!estimate.withinBudget) {
145
+ throw new CliError(
146
+ "DRY_RUN_OVER_BUDGET",
147
+ `Dry-run estimate is ${formatAtomic(estimate.estimatedMaxCostAtomic)} USDC, which exceeds the approved ${approvedBudgetUsdc} USDC budget.`,
148
+ );
149
+ }
150
+
151
+ const networkInfo = settlementNetworkInfo(article.paymentTerms?.network);
152
+ const chain = article.paymentTerms?.circleChain ?? networkInfo.circleChain ?? runtime.circleChain ?? "ARC-TESTNET";
153
+ const environment = article.paymentTerms?.environment ?? networkInfo.environment;
154
+ let circleWalletAddress: `0x${string}` | undefined;
155
+ let balanceAtomic: `${bigint}` | undefined;
156
+
157
+ if (runtime.paymentMode === "circle-cli") {
158
+ try {
159
+ await circleAuthStatus(circleInput(runtime, deps));
160
+ const wallet = await circleAgentWallet({
161
+ ...circleInput(runtime, deps),
162
+ chain,
163
+ configuredAddress: runtime.config.agentWalletAddress ?? envAddress("CIRCLE_AGENT_WALLET_ADDRESS"),
164
+ });
165
+ circleWalletAddress = wallet.address;
166
+ let balance = await circleGatewayBalance({ ...circleInput(runtime, deps), chain, address: wallet.address });
167
+ balanceAtomic = balance.balanceAtomic;
168
+ if (BigInt(balance.balanceAtomic) < BigInt(estimate.estimatedMaxCostAtomic)) {
169
+ if (environment !== "testnet") {
170
+ throw new CliError("INSUFFICIENT_FUNDS", "Wallet balance is below the dry-run estimate. Refusing to suggest mainnet funding for this article.");
171
+ }
172
+ await circleGatewayFaucet({ ...circleInput(runtime, deps), chain, address: wallet.address });
173
+ balance = await circleGatewayBalance({ ...circleInput(runtime, deps), chain, address: wallet.address });
174
+ balanceAtomic = balance.balanceAtomic;
175
+ }
176
+ } catch (error) {
177
+ if (error instanceof CliError) throw error;
178
+ const guidance = circleGuidance(error) ?? circleGuidance(classifyCircleError(error));
179
+ if (guidance) throw new CliError(guidance.code.toUpperCase(), `${guidance.message} ${guidance.guidance}`);
180
+ throw error;
181
+ }
182
+ }
183
+
184
+ const receipt = await runtime.client.run({
185
+ articleId: article.articleId,
186
+ goal,
187
+ sectionId,
188
+ maxSpendAtomic,
189
+ chunkWords: 32,
190
+ streamMode: "bundled" as StreamMode,
191
+ metadata: { quickstart: true, stopAfterSection: true },
192
+ });
193
+ const stored = await saveReceipt(receipt);
194
+ return {
195
+ success: true,
196
+ gatewayUrl: runtime.gatewayUrl,
197
+ gatewayConfigured: wroteGatewayConfig || Boolean(runtime.config.gatewayUrl || process.env.RUBICON_GATEWAY_URL),
198
+ selectedArticle: articleJson(article),
199
+ navigation: navigation.navigation,
200
+ dryRun: {
201
+ ...estimate,
202
+ estimatedMaxCostUsdc: formatAtomic(estimate.estimatedMaxCostAtomic),
203
+ },
204
+ wallet: {
205
+ chain,
206
+ environment,
207
+ circleWalletAddress,
208
+ balanceAtomic,
209
+ balanceUsdc: balanceAtomic ? formatAtomic(balanceAtomic) : undefined,
210
+ },
211
+ receiptId: stored.receiptId,
212
+ savedAt: stored.savedAt,
213
+ receipt: finalReceiptJson({
214
+ receipt,
215
+ article,
216
+ receiptId: stored.receiptId,
217
+ goal,
218
+ approvedBudgetUsdc,
219
+ circleWalletAddress,
220
+ }),
221
+ };
222
+ }
223
+
224
+ async function ensureGatewayConfig(runtime: CommandRuntime): Promise<boolean> {
225
+ if (runtime.config.gatewayUrl || process.env.RUBICON_GATEWAY_URL) return false;
226
+ runtime.config.gatewayUrl = runtime.gatewayUrl;
227
+ await writeConfig(runtime.config);
228
+ return true;
229
+ }
230
+
231
+ export function finalReceiptJson(input: {
232
+ receipt: ReadReceipt;
233
+ article: ArticleSummary;
234
+ receiptId: string;
235
+ goal: string;
236
+ approvedBudgetUsdc: string;
237
+ circleWalletAddress?: `0x${string}`;
238
+ }): Record<string, unknown> {
239
+ const paymentIds = input.receipt.payments.map((payment) => payment.paymentId).filter(Boolean);
240
+ const buyerWalletAddress = input.receipt.buyerWalletAddress;
241
+ const mismatch =
242
+ buyerWalletAddress && input.circleWalletAddress && buyerWalletAddress.toLowerCase() !== input.circleWalletAddress.toLowerCase();
243
+ return {
244
+ articleId: input.article.articleId,
245
+ title: input.article.title,
246
+ author: input.article.author,
247
+ sessionId: input.receipt.sessionId,
248
+ receiptId: input.receiptId,
249
+ goal: input.goal,
250
+ approvedBudgetUsdc: input.approvedBudgetUsdc,
251
+ amountPaidAtomic: input.receipt.amountPaidAtomic,
252
+ amountPaidUsdc: formatAtomic(input.receipt.amountPaidAtomic),
253
+ wordsRead: input.receipt.wordsRead,
254
+ completed: input.receipt.completed,
255
+ stopReason: input.receipt.stopReason,
256
+ paymentIds,
257
+ settlementIds: input.receipt.settlementIds,
258
+ transactionHashes: input.receipt.transactionHashes,
259
+ buyerWalletAddress,
260
+ circleWalletAddress: input.circleWalletAddress,
261
+ walletAddressMismatchExplanation: mismatch
262
+ ? "Circle CLI signs with the Agent Wallet, while x402/Gateway receipts can show the Gateway backing EOA that actually authorizes settlement."
263
+ : undefined,
264
+ };
265
+ }
266
+
267
+ function estimateRead(article: ArticleSummary, sectionId: string | undefined, maxSpendAtomic: `${bigint}`): {
268
+ sectionId?: string;
269
+ estimatedWords: number;
270
+ estimatedMaxCostAtomic: `${bigint}`;
271
+ withinBudget: boolean;
272
+ } {
273
+ const section = sectionId ? article.sections.find((candidate) => candidate.sectionId === sectionId) : undefined;
274
+ const estimatedWords = section?.wordCount ?? article.totalWords;
275
+ const estimatedMaxCostAtomic = `${BigInt(article.pricePerWordAtomic) * BigInt(estimatedWords)}` as `${bigint}`;
276
+ return {
277
+ sectionId,
278
+ estimatedWords,
279
+ estimatedMaxCostAtomic,
280
+ withinBudget: BigInt(maxSpendAtomic) >= BigInt(estimatedMaxCostAtomic),
281
+ };
282
+ }
283
+
284
+ function parseQuickstartBudget(parsed: ParsedArgs): `${bigint}` {
285
+ const maxUsdc = stringFlag(parsed.flags, "max-usdc");
286
+ const maxAtomic = stringFlag(parsed.flags, "max-atomic");
287
+ if (!maxUsdc && !maxAtomic) {
288
+ throw new CliError("MISSING_BUDGET", "rubicon quickstart-read refuses paid reads without explicit --max-usdc or --max-atomic.");
289
+ }
290
+ if (maxUsdc && maxAtomic) {
291
+ throw new CliError("MULTIPLE_BUDGETS", "Use either --max-usdc or --max-atomic, not both.");
292
+ }
293
+ if (maxAtomic) {
294
+ if (!/^\d+$/.test(maxAtomic)) throw new CliError("INVALID_BUDGET", "--max-atomic must be an integer.");
295
+ return maxAtomic as `${bigint}`;
296
+ }
297
+ try {
298
+ return `${parseUsdcToAtomic(maxUsdc!)}` as `${bigint}`;
299
+ } catch {
300
+ throw new CliError("INVALID_BUDGET", "--max-usdc must be a decimal USDC amount.");
301
+ }
302
+ }
303
+
304
+ async function addCircleCheck(checks: CheckResult[], name: string, task: () => Promise<unknown>): Promise<void> {
305
+ try {
306
+ checks.push({ name, ok: true, status: "ok", value: await task() });
307
+ } catch (error) {
308
+ const guidance = circleGuidance(error) ?? circleGuidance(classifyCircleError(error));
309
+ checks.push({
310
+ name,
311
+ ok: false,
312
+ status: name === "circleCli" ? "error" : "warning",
313
+ value: errorMessage(error),
314
+ guidance: guidance?.guidance ?? "Check Circle CLI setup and retry.",
315
+ });
316
+ }
317
+ }
318
+
319
+ function circleInput(_runtime: CommandRuntime, deps: CommandDeps): { command?: string; runner?: CircleRunner } {
320
+ return { command: deps.circleCommand, runner: deps.circleRunner };
321
+ }
322
+
323
+ function envAddress(name: string): `0x${string}` | undefined {
324
+ const value = process.env[name];
325
+ return value?.startsWith("0x") ? (value as `0x${string}`) : undefined;
326
+ }
327
+
328
+ function errorMessage(error: unknown): string {
329
+ return error instanceof Error ? error.message : String(error);
330
+ }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Rubicon
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.